Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14576 was 14576, checked in by bburlacu, 7 years ago

#1772: Merge trunk changes.

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