Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ExportSymbolicDataAnalysisSolutions/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeInterpreter.cs @ 10078

Last change on this file since 10078 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 19.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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 class SymbolicDataAnalysisExpressionTreeInterpreter : ParameterizedNamedItem, ISymbolicDataAnalysisExpressionTreeInterpreter {
35    private const string CheckExpressionsWithIntervalArithmeticParameterName = "CheckExpressionsWithIntervalArithmetic";
36    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
37
38    public override bool CanChangeName { get { return false; } }
39    public override bool CanChangeDescription { get { return false; } }
40
41    #region parameter properties
42    public IValueParameter<BoolValue> CheckExpressionsWithIntervalArithmeticParameter {
43      get { return (IValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName]; }
44    }
45
46    public IValueParameter<IntValue> EvaluatedSolutionsParameter {
47      get { return (IValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
48    }
49    #endregion
50
51    #region properties
52    public BoolValue CheckExpressionsWithIntervalArithmetic {
53      get { return CheckExpressionsWithIntervalArithmeticParameter.Value; }
54      set { CheckExpressionsWithIntervalArithmeticParameter.Value = value; }
55    }
56
57    public IntValue EvaluatedSolutions {
58      get { return EvaluatedSolutionsParameter.Value; }
59      set { EvaluatedSolutionsParameter.Value = value; }
60    }
61    #endregion
62
63    [StorableConstructor]
64    protected SymbolicDataAnalysisExpressionTreeInterpreter(bool deserializing) : base(deserializing) { }
65    protected SymbolicDataAnalysisExpressionTreeInterpreter(SymbolicDataAnalysisExpressionTreeInterpreter original, Cloner cloner) : base(original, cloner) { }
66    public override IDeepCloneable Clone(Cloner cloner) {
67      return new SymbolicDataAnalysisExpressionTreeInterpreter(this, cloner);
68    }
69
70    public SymbolicDataAnalysisExpressionTreeInterpreter()
71      : base("SymbolicDataAnalysisExpressionTreeInterpreter", "Interpreter for symbolic expression trees including automatically defined functions.") {
72      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)));
73      Parameters.Add(new ValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
74    }
75
76    protected SymbolicDataAnalysisExpressionTreeInterpreter(string name, string description)
77      : base(name, description) {
78      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)));
79      Parameters.Add(new ValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
80    }
81
82    [StorableHook(HookType.AfterDeserialization)]
83    private void AfterDeserialization() {
84      if (!Parameters.ContainsKey(EvaluatedSolutionsParameterName))
85        Parameters.Add(new ValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
86    }
87
88    #region IStatefulItem
89    public void InitializeState() {
90      EvaluatedSolutions.Value = 0;
91    }
92
93    public void ClearState() {
94    }
95    #endregion
96
97    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
98      if (CheckExpressionsWithIntervalArithmetic.Value)
99        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
100
101      lock (EvaluatedSolutions) {
102        EvaluatedSolutions.Value++; // increment the evaluated solutions counter
103      }
104      var state = PrepareInterpreterState(tree, dataset);
105
106      foreach (var rowEnum in rows) {
107        int row = rowEnum;
108        yield return Evaluate(dataset, ref row, state);
109        state.Reset();
110      }
111    }
112
113    private static InterpreterState PrepareInterpreterState(ISymbolicExpressionTree tree, Dataset dataset) {
114      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
115      int necessaryArgStackSize = 0;
116      foreach (Instruction instr in code) {
117        if (instr.opCode == OpCodes.Variable) {
118          var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
119          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
120        } else if (instr.opCode == OpCodes.LagVariable) {
121          var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
122          instr.iArg0 = dataset.GetReadOnlyDoubleValues(laggedVariableTreeNode.VariableName);
123        } else if (instr.opCode == OpCodes.VariableCondition) {
124          var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
125          instr.iArg0 = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
126        } else if (instr.opCode == OpCodes.Call) {
127          necessaryArgStackSize += instr.nArguments + 1;
128        }
129      }
130      return new InterpreterState(code, necessaryArgStackSize);
131    }
132
133
134    protected virtual double Evaluate(Dataset dataset, ref int row, InterpreterState state) {
135      Instruction currentInstr = state.NextInstruction();
136      switch (currentInstr.opCode) {
137        case OpCodes.Add: {
138            double s = Evaluate(dataset, ref row, state);
139            for (int i = 1; i < currentInstr.nArguments; i++) {
140              s += Evaluate(dataset, ref row, state);
141            }
142            return s;
143          }
144        case OpCodes.Sub: {
145            double s = Evaluate(dataset, ref row, state);
146            for (int i = 1; i < currentInstr.nArguments; i++) {
147              s -= Evaluate(dataset, ref row, state);
148            }
149            if (currentInstr.nArguments == 1) s = -s;
150            return s;
151          }
152        case OpCodes.Mul: {
153            double p = Evaluate(dataset, ref row, state);
154            for (int i = 1; i < currentInstr.nArguments; i++) {
155              p *= Evaluate(dataset, ref row, state);
156            }
157            return p;
158          }
159        case OpCodes.Div: {
160            double p = Evaluate(dataset, ref row, state);
161            for (int i = 1; i < currentInstr.nArguments; i++) {
162              p /= Evaluate(dataset, ref row, state);
163            }
164            if (currentInstr.nArguments == 1) p = 1.0 / p;
165            return p;
166          }
167        case OpCodes.Average: {
168            double sum = Evaluate(dataset, ref row, state);
169            for (int i = 1; i < currentInstr.nArguments; i++) {
170              sum += Evaluate(dataset, ref row, state);
171            }
172            return sum / currentInstr.nArguments;
173          }
174        case OpCodes.Cos: {
175            return Math.Cos(Evaluate(dataset, ref row, state));
176          }
177        case OpCodes.Sin: {
178            return Math.Sin(Evaluate(dataset, ref row, state));
179          }
180        case OpCodes.Tan: {
181            return Math.Tan(Evaluate(dataset, ref row, state));
182          }
183        case OpCodes.Square: {
184            return Math.Pow(Evaluate(dataset, ref row, state), 2);
185          }
186        case OpCodes.Power: {
187            double x = Evaluate(dataset, ref row, state);
188            double y = Math.Round(Evaluate(dataset, ref row, state));
189            return Math.Pow(x, y);
190          }
191        case OpCodes.SquareRoot: {
192            return Math.Sqrt(Evaluate(dataset, ref row, state));
193          }
194        case OpCodes.Root: {
195            double x = Evaluate(dataset, ref row, state);
196            double y = Math.Round(Evaluate(dataset, ref row, state));
197            return Math.Pow(x, 1 / y);
198          }
199        case OpCodes.Exp: {
200            return Math.Exp(Evaluate(dataset, ref row, state));
201          }
202        case OpCodes.Log: {
203            return Math.Log(Evaluate(dataset, ref row, state));
204          }
205        case OpCodes.Gamma: {
206            var x = Evaluate(dataset, ref row, state);
207            if (double.IsNaN(x)) return double.NaN;
208            else return alglib.gammafunction(x);
209          }
210        case OpCodes.Psi: {
211            var x = Evaluate(dataset, ref row, state);
212            if (double.IsNaN(x)) return double.NaN;
213            else if (x <= 0 && (Math.Floor(x) - x).IsAlmost(0)) return double.NaN;
214            return alglib.psi(x);
215          }
216        case OpCodes.Dawson: {
217            var x = Evaluate(dataset, ref row, state);
218            if (double.IsNaN(x)) return double.NaN;
219            return alglib.dawsonintegral(x);
220          }
221        case OpCodes.ExponentialIntegralEi: {
222            var x = Evaluate(dataset, ref row, state);
223            if (double.IsNaN(x)) return double.NaN;
224            return alglib.exponentialintegralei(x);
225          }
226        case OpCodes.SineIntegral: {
227            double si, ci;
228            var x = Evaluate(dataset, ref row, state);
229            if (double.IsNaN(x)) return double.NaN;
230            else {
231              alglib.sinecosineintegrals(x, out si, out ci);
232              return si;
233            }
234          }
235        case OpCodes.CosineIntegral: {
236            double si, ci;
237            var x = Evaluate(dataset, ref row, state);
238            if (double.IsNaN(x)) return double.NaN;
239            else {
240              alglib.sinecosineintegrals(x, out si, out ci);
241              return ci;
242            }
243          }
244        case OpCodes.HyperbolicSineIntegral: {
245            double shi, chi;
246            var x = Evaluate(dataset, ref row, state);
247            if (double.IsNaN(x)) return double.NaN;
248            else {
249              alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
250              return shi;
251            }
252          }
253        case OpCodes.HyperbolicCosineIntegral: {
254            double shi, chi;
255            var x = Evaluate(dataset, ref row, state);
256            if (double.IsNaN(x)) return double.NaN;
257            else {
258              alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
259              return chi;
260            }
261          }
262        case OpCodes.FresnelCosineIntegral: {
263            double c = 0, s = 0;
264            var x = Evaluate(dataset, ref row, state);
265            if (double.IsNaN(x)) return double.NaN;
266            else {
267              alglib.fresnelintegral(x, ref c, ref s);
268              return c;
269            }
270          }
271        case OpCodes.FresnelSineIntegral: {
272            double c = 0, s = 0;
273            var x = Evaluate(dataset, ref row, state);
274            if (double.IsNaN(x)) return double.NaN;
275            else {
276              alglib.fresnelintegral(x, ref c, ref s);
277              return s;
278            }
279          }
280        case OpCodes.AiryA: {
281            double ai, aip, bi, bip;
282            var x = Evaluate(dataset, ref row, state);
283            if (double.IsNaN(x)) return double.NaN;
284            else {
285              alglib.airy(x, out ai, out aip, out bi, out bip);
286              return ai;
287            }
288          }
289        case OpCodes.AiryB: {
290            double ai, aip, bi, bip;
291            var x = Evaluate(dataset, ref row, state);
292            if (double.IsNaN(x)) return double.NaN;
293            else {
294              alglib.airy(x, out ai, out aip, out bi, out bip);
295              return bi;
296            }
297          }
298        case OpCodes.Norm: {
299            var x = Evaluate(dataset, ref row, state);
300            if (double.IsNaN(x)) return double.NaN;
301            else return alglib.normaldistribution(x);
302          }
303        case OpCodes.Erf: {
304            var x = Evaluate(dataset, ref row, state);
305            if (double.IsNaN(x)) return double.NaN;
306            else return alglib.errorfunction(x);
307          }
308        case OpCodes.Bessel: {
309            var x = Evaluate(dataset, ref row, state);
310            if (double.IsNaN(x)) return double.NaN;
311            else return alglib.besseli0(x);
312          }
313        case OpCodes.IfThenElse: {
314            double condition = Evaluate(dataset, ref row, state);
315            double result;
316            if (condition > 0.0) {
317              result = Evaluate(dataset, ref row, state); state.SkipInstructions();
318            } else {
319              state.SkipInstructions(); result = Evaluate(dataset, ref row, state);
320            }
321            return result;
322          }
323        case OpCodes.AND: {
324            double result = Evaluate(dataset, ref row, state);
325            for (int i = 1; i < currentInstr.nArguments; i++) {
326              if (result > 0.0) result = Evaluate(dataset, ref row, state);
327              else {
328                state.SkipInstructions();
329              }
330            }
331            return result > 0.0 ? 1.0 : -1.0;
332          }
333        case OpCodes.OR: {
334            double result = Evaluate(dataset, ref row, state);
335            for (int i = 1; i < currentInstr.nArguments; i++) {
336              if (result <= 0.0) result = Evaluate(dataset, ref row, state);
337              else {
338                state.SkipInstructions();
339              }
340            }
341            return result > 0.0 ? 1.0 : -1.0;
342          }
343        case OpCodes.NOT: {
344            return Evaluate(dataset, ref row, state) > 0.0 ? -1.0 : 1.0;
345          }
346        case OpCodes.GT: {
347            double x = Evaluate(dataset, ref row, state);
348            double y = Evaluate(dataset, ref row, state);
349            if (x > y) return 1.0;
350            else return -1.0;
351          }
352        case OpCodes.LT: {
353            double x = Evaluate(dataset, ref row, state);
354            double y = Evaluate(dataset, ref row, state);
355            if (x < y) return 1.0;
356            else return -1.0;
357          }
358        case OpCodes.TimeLag: {
359            var timeLagTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
360            row += timeLagTreeNode.Lag;
361            double result = Evaluate(dataset, ref row, state);
362            row -= timeLagTreeNode.Lag;
363            return result;
364          }
365        case OpCodes.Integral: {
366            int savedPc = state.ProgramCounter;
367            var timeLagTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
368            double sum = 0.0;
369            for (int i = 0; i < Math.Abs(timeLagTreeNode.Lag); i++) {
370              row += Math.Sign(timeLagTreeNode.Lag);
371              sum += Evaluate(dataset, ref row, state);
372              state.ProgramCounter = savedPc;
373            }
374            row -= timeLagTreeNode.Lag;
375            sum += Evaluate(dataset, ref row, state);
376            return sum;
377          }
378
379        //mkommend: derivate calculation taken from:
380        //http://www.holoborodko.com/pavel/numerical-methods/numerical-derivative/smooth-low-noise-differentiators/
381        //one sided smooth differentiatior, N = 4
382        // y' = 1/8h (f_i + 2f_i-1, -2 f_i-3 - f_i-4)
383        case OpCodes.Derivative: {
384            int savedPc = state.ProgramCounter;
385            double f_0 = Evaluate(dataset, ref row, state); row--;
386            state.ProgramCounter = savedPc;
387            double f_1 = Evaluate(dataset, ref row, state); row -= 2;
388            state.ProgramCounter = savedPc;
389            double f_3 = Evaluate(dataset, ref row, state); row--;
390            state.ProgramCounter = savedPc;
391            double f_4 = Evaluate(dataset, ref row, state);
392            row += 4;
393
394            return (f_0 + 2 * f_1 - 2 * f_3 - f_4) / 8; // h = 1
395          }
396        case OpCodes.Call: {
397            // evaluate sub-trees
398            double[] argValues = new double[currentInstr.nArguments];
399            for (int i = 0; i < currentInstr.nArguments; i++) {
400              argValues[i] = Evaluate(dataset, ref row, state);
401            }
402            // push on argument values on stack
403            state.CreateStackFrame(argValues);
404
405            // save the pc
406            int savedPc = state.ProgramCounter;
407            // set pc to start of function 
408            state.ProgramCounter = (ushort)currentInstr.iArg0;
409            // evaluate the function
410            double v = Evaluate(dataset, ref row, state);
411
412            // delete the stack frame
413            state.RemoveStackFrame();
414
415            // restore the pc => evaluation will continue at point after my subtrees 
416            state.ProgramCounter = savedPc;
417            return v;
418          }
419        case OpCodes.Arg: {
420            return state.GetStackFrameValue((ushort)currentInstr.iArg0);
421          }
422        case OpCodes.Variable: {
423            if (row < 0 || row >= dataset.Rows) return double.NaN;
424            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
425            return ((IList<double>)currentInstr.iArg0)[row] * variableTreeNode.Weight;
426          }
427        case OpCodes.LagVariable: {
428            var laggedVariableTreeNode = (LaggedVariableTreeNode)currentInstr.dynamicNode;
429            int actualRow = row + laggedVariableTreeNode.Lag;
430            if (actualRow < 0 || actualRow >= dataset.Rows) return double.NaN;
431            return ((IList<double>)currentInstr.iArg0)[actualRow] * laggedVariableTreeNode.Weight;
432          }
433        case OpCodes.Constant: {
434            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
435            return constTreeNode.Value;
436          }
437
438        //mkommend: this symbol uses the logistic function f(x) = 1 / (1 + e^(-alpha * x) )
439        //to determine the relative amounts of the true and false branch see http://en.wikipedia.org/wiki/Logistic_function
440        case OpCodes.VariableCondition: {
441            if (row < 0 || row >= dataset.Rows) return double.NaN;
442            var variableConditionTreeNode = (VariableConditionTreeNode)currentInstr.dynamicNode;
443            double variableValue = ((IList<double>)currentInstr.iArg0)[row];
444            double x = variableValue - variableConditionTreeNode.Threshold;
445            double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x));
446
447            double trueBranch = Evaluate(dataset, ref row, state);
448            double falseBranch = Evaluate(dataset, ref row, state);
449
450            return trueBranch * p + falseBranch * (1 - p);
451          }
452        default: throw new NotSupportedException();
453      }
454    }
455  }
456}
Note: See TracBrowser for help on using the repository browser.