Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Crossovers/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeInterpreter.cs @ 7477

Last change on this file since 7477 was 7477, checked in by bburlacu, 12 years ago

#1682: Added missing files (that were previously incorrectly referencing the old branch), added unit tests, recommitted lost changes.

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