Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs @ 13482

Last change on this file since 13482 was 13482, checked in by bburlacu, 9 years ago

#1772: Merged trunk changes

File size: 20.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [StorableClass]
34  [Item("SymbolicDataAnalysisExpressionTreeLinearInterpreter", "Fast linear (non-recursive) interpreter for symbolic expression trees. Does not support ADFs.")]
35  public sealed class SymbolicDataAnalysisExpressionTreeLinearInterpreter : ParameterizedNamedItem, ISymbolicDataAnalysisExpressionTreeInterpreter {
36    private const string CheckExpressionsWithIntervalArithmeticParameterName = "CheckExpressionsWithIntervalArithmetic";
37    private const string CheckExpressionsWithIntervalArithmeticParameterDescription = "Switch that determines if the interpreter checks the validity of expressions with interval arithmetic before evaluating the expression.";
38    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
39
40    private SymbolicDataAnalysisExpressionTreeInterpreter interpreter;
41
42    public override bool CanChangeName {
43      get { return false; }
44    }
45
46    public override bool CanChangeDescription {
47      get { return false; }
48    }
49
50    #region parameter properties
51    public IFixedValueParameter<BoolValue> CheckExpressionsWithIntervalArithmeticParameter {
52      get { return (IFixedValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName]; }
53    }
54
55    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
56      get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
57    }
58    #endregion
59
60    #region properties
61    public bool CheckExpressionsWithIntervalArithmetic {
62      get { return CheckExpressionsWithIntervalArithmeticParameter.Value.Value; }
63      set { CheckExpressionsWithIntervalArithmeticParameter.Value.Value = value; }
64    }
65    public int EvaluatedSolutions {
66      get { return EvaluatedSolutionsParameter.Value.Value; }
67      set { EvaluatedSolutionsParameter.Value.Value = value; }
68    }
69    #endregion
70
71    [StorableConstructor]
72    private SymbolicDataAnalysisExpressionTreeLinearInterpreter(bool deserializing)
73      : base(deserializing) {
74    }
75
76    private SymbolicDataAnalysisExpressionTreeLinearInterpreter(SymbolicDataAnalysisExpressionTreeLinearInterpreter original, Cloner cloner)
77      : base(original, cloner) {
78      interpreter = cloner.Clone(original.interpreter);
79    }
80
81    public override IDeepCloneable Clone(Cloner cloner) {
82      return new SymbolicDataAnalysisExpressionTreeLinearInterpreter(this, cloner);
83    }
84
85    public SymbolicDataAnalysisExpressionTreeLinearInterpreter()
86      : base("SymbolicDataAnalysisExpressionTreeLinearInterpreter", "Linear (non-recursive) interpreter for symbolic expression trees (does not support ADFs).") {
87      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, CheckExpressionsWithIntervalArithmeticParameterDescription, new BoolValue(false)));
88      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
89      interpreter = new SymbolicDataAnalysisExpressionTreeInterpreter();
90    }
91
92    public SymbolicDataAnalysisExpressionTreeLinearInterpreter(string name, string description)
93      : base(name, description) {
94      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, CheckExpressionsWithIntervalArithmeticParameterDescription, new BoolValue(false)));
95      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
96      interpreter = new SymbolicDataAnalysisExpressionTreeInterpreter();
97    }
98
99    [StorableHook(HookType.AfterDeserialization)]
100    private void AfterDeserialization() {
101      var evaluatedSolutions = new IntValue(0);
102      var checkExpressionsWithIntervalArithmetic = new BoolValue(false);
103      if (Parameters.ContainsKey(EvaluatedSolutionsParameterName)) {
104        var evaluatedSolutionsParameter = (IValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName];
105        evaluatedSolutions = evaluatedSolutionsParameter.Value;
106        Parameters.Remove(EvaluatedSolutionsParameterName);
107      }
108      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", evaluatedSolutions));
109      if (Parameters.ContainsKey(CheckExpressionsWithIntervalArithmeticParameterName)) {
110        var checkExpressionsWithIntervalArithmeticParameter = (IValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName];
111        Parameters.Remove(CheckExpressionsWithIntervalArithmeticParameterName);
112        checkExpressionsWithIntervalArithmetic = checkExpressionsWithIntervalArithmeticParameter.Value;
113      }
114      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, CheckExpressionsWithIntervalArithmeticParameterDescription, checkExpressionsWithIntervalArithmetic));
115    }
116
117    #region IStatefulItem
118    public void InitializeState() {
119      EvaluatedSolutions = 0;
120    }
121
122    public void ClearState() { }
123    #endregion
124
125    private readonly object syncRoot = new object();
126    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) {
127      if (CheckExpressionsWithIntervalArithmetic)
128        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
129
130      lock (syncRoot) {
131        EvaluatedSolutions++; // increment the evaluated solutions counter
132      }
133
134      var code = SymbolicExpressionTreeLinearCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
135      PrepareInstructions(code, dataset);
136      return rows.Select(row => Evaluate(dataset, row, code));
137    }
138
139    // NOTE: do not use this method when evaluating trees. this method is provided as a shortcut for evaluating subtrees ad-hoc
140    public IEnumerable<double> GetValues(ISymbolicExpressionTreeNode node, IDataset dataset, IEnumerable<int> rows) {
141      var code = SymbolicExpressionTreeLinearCompiler.Compile(node, OpCodes.MapSymbolToOpCode);
142      PrepareInstructions(code, dataset);
143      return rows.Select(row => Evaluate(dataset, row, code));
144    }
145
146    private double Evaluate(IDataset dataset, int row, LinearInstruction[] code) {
147      for (int i = code.Length - 1; i >= 0; --i) {
148        if (code[i].skip) continue;
149        #region opcode if
150        var instr = code[i];
151        if (instr.opCode == OpCodes.Variable) {
152          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
153          else {
154            var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
155            instr.value = ((IList<double>)instr.data)[row] * variableTreeNode.Weight;
156          }
157        } else if (instr.opCode == OpCodes.LagVariable) {
158          var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
159          int actualRow = row + laggedVariableTreeNode.Lag;
160          if (actualRow < 0 || actualRow >= dataset.Rows)
161            instr.value = double.NaN;
162          else
163            instr.value = ((IList<double>)instr.data)[actualRow] * laggedVariableTreeNode.Weight;
164        } else if (instr.opCode == OpCodes.VariableCondition) {
165          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
166          var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
167          double variableValue = ((IList<double>)instr.data)[row];
168          double x = variableValue - variableConditionTreeNode.Threshold;
169          double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x));
170
171          double trueBranch = code[instr.childIndex].value;
172          double falseBranch = code[instr.childIndex + 1].value;
173
174          instr.value = trueBranch * p + falseBranch * (1 - p);
175        } else if (instr.opCode == OpCodes.Add) {
176          double s = code[instr.childIndex].value;
177          for (int j = 1; j != instr.nArguments; ++j) {
178            s += code[instr.childIndex + j].value;
179          }
180          instr.value = s;
181        } else if (instr.opCode == OpCodes.Sub) {
182          double s = code[instr.childIndex].value;
183          for (int j = 1; j != instr.nArguments; ++j) {
184            s -= code[instr.childIndex + j].value;
185          }
186          if (instr.nArguments == 1) s = -s;
187          instr.value = s;
188        } else if (instr.opCode == OpCodes.Mul) {
189          double p = code[instr.childIndex].value;
190          for (int j = 1; j != instr.nArguments; ++j) {
191            p *= code[instr.childIndex + j].value;
192          }
193          instr.value = p;
194        } else if (instr.opCode == OpCodes.Div) {
195          double p = code[instr.childIndex].value;
196          for (int j = 1; j != instr.nArguments; ++j) {
197            p /= code[instr.childIndex + j].value;
198          }
199          if (instr.nArguments == 1) p = 1.0 / p;
200          instr.value = p;
201        } else if (instr.opCode == OpCodes.Average) {
202          double s = code[instr.childIndex].value;
203          for (int j = 1; j != instr.nArguments; ++j) {
204            s += code[instr.childIndex + j].value;
205          }
206          instr.value = s / instr.nArguments;
207        } else if (instr.opCode == OpCodes.Cos) {
208          instr.value = Math.Cos(code[instr.childIndex].value);
209        } else if (instr.opCode == OpCodes.Sin) {
210          instr.value = Math.Sin(code[instr.childIndex].value);
211        } else if (instr.opCode == OpCodes.Tan) {
212          instr.value = Math.Tan(code[instr.childIndex].value);
213        } else if (instr.opCode == OpCodes.Square) {
214          instr.value = Math.Pow(code[instr.childIndex].value, 2);
215        } else if (instr.opCode == OpCodes.Power) {
216          double x = code[instr.childIndex].value;
217          double y = Math.Round(code[instr.childIndex + 1].value);
218          instr.value = Math.Pow(x, y);
219        } else if (instr.opCode == OpCodes.SquareRoot) {
220          instr.value = Math.Sqrt(code[instr.childIndex].value);
221        } else if (instr.opCode == OpCodes.Root) {
222          double x = code[instr.childIndex].value;
223          double y = Math.Round(code[instr.childIndex + 1].value);
224          instr.value = Math.Pow(x, 1 / y);
225        } else if (instr.opCode == OpCodes.Exp) {
226          instr.value = Math.Exp(code[instr.childIndex].value);
227        } else if (instr.opCode == OpCodes.Log) {
228          instr.value = Math.Log(code[instr.childIndex].value);
229        } else if (instr.opCode == OpCodes.Gamma) {
230          var x = code[instr.childIndex].value;
231          instr.value = double.IsNaN(x) ? double.NaN : alglib.gammafunction(x);
232        } else if (instr.opCode == OpCodes.Psi) {
233          var x = code[instr.childIndex].value;
234          if (double.IsNaN(x)) instr.value = double.NaN;
235          else if (x <= 0 && (Math.Floor(x) - x).IsAlmost(0)) instr.value = double.NaN;
236          else instr.value = alglib.psi(x);
237        } else if (instr.opCode == OpCodes.Dawson) {
238          var x = code[instr.childIndex].value;
239          instr.value = double.IsNaN(x) ? double.NaN : alglib.dawsonintegral(x);
240        } else if (instr.opCode == OpCodes.ExponentialIntegralEi) {
241          var x = code[instr.childIndex].value;
242          instr.value = double.IsNaN(x) ? double.NaN : alglib.exponentialintegralei(x);
243        } else if (instr.opCode == OpCodes.SineIntegral) {
244          double si, ci;
245          var x = code[instr.childIndex].value;
246          if (double.IsNaN(x)) instr.value = double.NaN;
247          else {
248            alglib.sinecosineintegrals(x, out si, out ci);
249            instr.value = si;
250          }
251        } else if (instr.opCode == OpCodes.CosineIntegral) {
252          double si, ci;
253          var x = code[instr.childIndex].value;
254          if (double.IsNaN(x)) instr.value = double.NaN;
255          else {
256            alglib.sinecosineintegrals(x, out si, out ci);
257            instr.value = ci;
258          }
259        } else if (instr.opCode == OpCodes.HyperbolicSineIntegral) {
260          double shi, chi;
261          var x = code[instr.childIndex].value;
262          if (double.IsNaN(x)) instr.value = double.NaN;
263          else {
264            alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
265            instr.value = shi;
266          }
267        } else if (instr.opCode == OpCodes.HyperbolicCosineIntegral) {
268          double shi, chi;
269          var x = code[instr.childIndex].value;
270          if (double.IsNaN(x)) instr.value = double.NaN;
271          else {
272            alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
273            instr.value = chi;
274          }
275        } else if (instr.opCode == OpCodes.FresnelCosineIntegral) {
276          double c = 0, s = 0;
277          var x = code[instr.childIndex].value;
278          if (double.IsNaN(x)) instr.value = double.NaN;
279          else {
280            alglib.fresnelintegral(x, ref c, ref s);
281            instr.value = c;
282          }
283        } else if (instr.opCode == OpCodes.FresnelSineIntegral) {
284          double c = 0, s = 0;
285          var x = code[instr.childIndex].value;
286          if (double.IsNaN(x)) instr.value = double.NaN;
287          else {
288            alglib.fresnelintegral(x, ref c, ref s);
289            instr.value = s;
290          }
291        } else if (instr.opCode == OpCodes.AiryA) {
292          double ai, aip, bi, bip;
293          var x = code[instr.childIndex].value;
294          if (double.IsNaN(x)) instr.value = double.NaN;
295          else {
296            alglib.airy(x, out ai, out aip, out bi, out bip);
297            instr.value = ai;
298          }
299        } else if (instr.opCode == OpCodes.AiryB) {
300          double ai, aip, bi, bip;
301          var x = code[instr.childIndex].value;
302          if (double.IsNaN(x)) instr.value = double.NaN;
303          else {
304            alglib.airy(x, out ai, out aip, out bi, out bip);
305            instr.value = bi;
306          }
307        } else if (instr.opCode == OpCodes.Norm) {
308          var x = code[instr.childIndex].value;
309          if (double.IsNaN(x)) instr.value = double.NaN;
310          else instr.value = alglib.normaldistribution(x);
311        } else if (instr.opCode == OpCodes.Erf) {
312          var x = code[instr.childIndex].value;
313          if (double.IsNaN(x)) instr.value = double.NaN;
314          else instr.value = alglib.errorfunction(x);
315        } else if (instr.opCode == OpCodes.Bessel) {
316          var x = code[instr.childIndex].value;
317          if (double.IsNaN(x)) instr.value = double.NaN;
318          else instr.value = alglib.besseli0(x);
319        } else if (instr.opCode == OpCodes.IfThenElse) {
320          double condition = code[instr.childIndex].value;
321          double result;
322          if (condition > 0.0) {
323            result = code[instr.childIndex + 1].value;
324          } else {
325            result = code[instr.childIndex + 2].value;
326          }
327          instr.value = result;
328        } else if (instr.opCode == OpCodes.AND) {
329          double result = code[instr.childIndex].value;
330          for (int j = 1; j < instr.nArguments; j++) {
331            if (result > 0.0) result = code[instr.childIndex + j].value;
332            else break;
333          }
334          instr.value = result > 0.0 ? 1.0 : -1.0;
335        } else if (instr.opCode == OpCodes.OR) {
336          double result = code[instr.childIndex].value;
337          for (int j = 1; j < instr.nArguments; j++) {
338            if (result <= 0.0) result = code[instr.childIndex + j].value;
339            else break;
340          }
341          instr.value = result > 0.0 ? 1.0 : -1.0;
342        } else if (instr.opCode == OpCodes.NOT) {
343          instr.value = code[instr.childIndex].value > 0.0 ? -1.0 : 1.0;
344        } else if (instr.opCode == OpCodes.XOR) {
345          int positiveSignals = 0;
346          for (int j = 0; j < instr.nArguments; j++) {
347            if (code[instr.childIndex + j].value > 0.0) positiveSignals++;
348          }
349          instr.value = positiveSignals % 2 != 0 ? 1.0 : -1.0;
350        } else if (instr.opCode == OpCodes.GT) {
351          double x = code[instr.childIndex].value;
352          double y = code[instr.childIndex + 1].value;
353          instr.value = x > y ? 1.0 : -1.0;
354        } else if (instr.opCode == OpCodes.LT) {
355          double x = code[instr.childIndex].value;
356          double y = code[instr.childIndex + 1].value;
357          instr.value = x < y ? 1.0 : -1.0;
358        } else if (instr.opCode == OpCodes.TimeLag || instr.opCode == OpCodes.Derivative || instr.opCode == OpCodes.Integral) {
359          var state = (InterpreterState)instr.data;
360          state.Reset();
361          instr.value = interpreter.Evaluate(dataset, ref row, state);
362        } else if (instr.opCode == OpCodes.Passthrough) {
363          instr.value = code[instr.childIndex].value;
364        } else {
365          var errorText = string.Format("The {0} symbol is not supported by the linear interpreter. To support this symbol, please use the SymbolicDataAnalysisExpressionTreeInterpreter.", instr.dynamicNode.Symbol.Name);
366          throw new NotSupportedException(errorText);
367        }
368        #endregion
369      }
370      return code[0].value;
371    }
372
373    private static LinearInstruction[] GetPrefixSequence(LinearInstruction[] code, int startIndex) {
374      var s = new Stack<int>();
375      var list = new List<LinearInstruction>();
376      s.Push(startIndex);
377      while (s.Any()) {
378        int i = s.Pop();
379        var instr = code[i];
380        // push instructions in reverse execution order
381        for (int j = instr.nArguments - 1; j >= 0; j--) s.Push(instr.childIndex + j);
382        list.Add(instr);
383      }
384      return list.ToArray();
385    }
386
387    public static void PrepareInstructions(LinearInstruction[] code, IDataset dataset) {
388      for (int i = 0; i != code.Length; ++i) {
389        var instr = code[i];
390        #region opcode switch
391        switch (instr.opCode) {
392          case OpCodes.Constant: {
393              var constTreeNode = (ConstantTreeNode)instr.dynamicNode;
394              instr.value = constTreeNode.Value;
395              instr.skip = true; // the value is already set so this instruction should be skipped in the evaluation phase
396            }
397            break;
398          case OpCodes.Variable: {
399              var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
400              instr.data = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
401            }
402            break;
403          case OpCodes.LagVariable: {
404              var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
405              instr.data = dataset.GetReadOnlyDoubleValues(laggedVariableTreeNode.VariableName);
406            }
407            break;
408          case OpCodes.VariableCondition: {
409              var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
410              instr.data = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
411            }
412            break;
413          case OpCodes.TimeLag:
414          case OpCodes.Integral:
415          case OpCodes.Derivative: {
416              var seq = GetPrefixSequence(code, i);
417              var interpreterState = new InterpreterState(seq, 0);
418              instr.data = interpreterState;
419              for (int j = 1; j != seq.Length; ++j)
420                seq[j].skip = true;
421            }
422            break;
423        }
424        #endregion
425      }
426    }
427  }
428}
Note: See TracBrowser for help on using the repository browser.