Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs @ 15016

Last change on this file since 15016 was 14974, checked in by gkronber, 8 years ago

#2640: merged r13268 from trunk to stable (was omitted in merging #2442)

File size: 19.9 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 (CheckExpressionsWithIntervalArithmetic)
129        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
130
131      lock (syncRoot) {
132        EvaluatedSolutions++; // increment the evaluated solutions counter
133      }
134
135      var code = SymbolicExpressionTreeLinearCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
136      PrepareInstructions(code, dataset);
137      return rows.Select(row => Evaluate(dataset, row, code));
138    }
139
140    private double Evaluate(IDataset dataset, int row, LinearInstruction[] code) {
141      for (int i = code.Length - 1; i >= 0; --i) {
142        if (code[i].skip) continue;
143        #region opcode if
144        var instr = code[i];
145        if (instr.opCode == OpCodes.Variable) {
146          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
147          else {
148            var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
149            instr.value = ((IList<double>)instr.data)[row] * variableTreeNode.Weight;
150          }
151        } else if (instr.opCode == OpCodes.LagVariable) {
152          var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
153          int actualRow = row + laggedVariableTreeNode.Lag;
154          if (actualRow < 0 || actualRow >= dataset.Rows)
155            instr.value = double.NaN;
156          else
157            instr.value = ((IList<double>)instr.data)[actualRow] * laggedVariableTreeNode.Weight;
158        } else if (instr.opCode == OpCodes.VariableCondition) {
159          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
160          var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
161          double variableValue = ((IList<double>)instr.data)[row];
162          double x = variableValue - variableConditionTreeNode.Threshold;
163          double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x));
164
165          double trueBranch = code[instr.childIndex].value;
166          double falseBranch = code[instr.childIndex + 1].value;
167
168          instr.value = trueBranch * p + falseBranch * (1 - p);
169        } else if (instr.opCode == OpCodes.Add) {
170          double s = code[instr.childIndex].value;
171          for (int j = 1; j != instr.nArguments; ++j) {
172            s += code[instr.childIndex + j].value;
173          }
174          instr.value = s;
175        } else if (instr.opCode == OpCodes.Sub) {
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          if (instr.nArguments == 1) s = -s;
181          instr.value = s;
182        } else if (instr.opCode == OpCodes.Mul) {
183          double p = code[instr.childIndex].value;
184          for (int j = 1; j != instr.nArguments; ++j) {
185            p *= code[instr.childIndex + j].value;
186          }
187          instr.value = p;
188        } else if (instr.opCode == OpCodes.Div) {
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          if (instr.nArguments == 1) p = 1.0 / p;
194          instr.value = p;
195        } else if (instr.opCode == OpCodes.Average) {
196          double s = code[instr.childIndex].value;
197          for (int j = 1; j != instr.nArguments; ++j) {
198            s += code[instr.childIndex + j].value;
199          }
200          instr.value = s / instr.nArguments;
201        } else if (instr.opCode == OpCodes.Cos) {
202          instr.value = Math.Cos(code[instr.childIndex].value);
203        } else if (instr.opCode == OpCodes.Sin) {
204          instr.value = Math.Sin(code[instr.childIndex].value);
205        } else if (instr.opCode == OpCodes.Tan) {
206          instr.value = Math.Tan(code[instr.childIndex].value);
207        } else if (instr.opCode == OpCodes.Square) {
208          instr.value = Math.Pow(code[instr.childIndex].value, 2);
209        } else if (instr.opCode == OpCodes.Power) {
210          double x = code[instr.childIndex].value;
211          double y = Math.Round(code[instr.childIndex + 1].value);
212          instr.value = Math.Pow(x, y);
213        } else if (instr.opCode == OpCodes.SquareRoot) {
214          instr.value = Math.Sqrt(code[instr.childIndex].value);
215        } else if (instr.opCode == OpCodes.Root) {
216          double x = code[instr.childIndex].value;
217          double y = Math.Round(code[instr.childIndex + 1].value);
218          instr.value = Math.Pow(x, 1 / y);
219        } else if (instr.opCode == OpCodes.Exp) {
220          instr.value = Math.Exp(code[instr.childIndex].value);
221        } else if (instr.opCode == OpCodes.Log) {
222          instr.value = Math.Log(code[instr.childIndex].value);
223        } else if (instr.opCode == OpCodes.Gamma) {
224          var x = code[instr.childIndex].value;
225          instr.value = double.IsNaN(x) ? double.NaN : alglib.gammafunction(x);
226        } else if (instr.opCode == OpCodes.Psi) {
227          var x = code[instr.childIndex].value;
228          if (double.IsNaN(x)) instr.value = double.NaN;
229          else if (x <= 0 && (Math.Floor(x) - x).IsAlmost(0)) instr.value = double.NaN;
230          else instr.value = alglib.psi(x);
231        } else if (instr.opCode == OpCodes.Dawson) {
232          var x = code[instr.childIndex].value;
233          instr.value = double.IsNaN(x) ? double.NaN : alglib.dawsonintegral(x);
234        } else if (instr.opCode == OpCodes.ExponentialIntegralEi) {
235          var x = code[instr.childIndex].value;
236          instr.value = double.IsNaN(x) ? double.NaN : alglib.exponentialintegralei(x);
237        } else if (instr.opCode == OpCodes.SineIntegral) {
238          double si, ci;
239          var x = code[instr.childIndex].value;
240          if (double.IsNaN(x)) instr.value = double.NaN;
241          else {
242            alglib.sinecosineintegrals(x, out si, out ci);
243            instr.value = si;
244          }
245        } else if (instr.opCode == OpCodes.CosineIntegral) {
246          double si, ci;
247          var x = code[instr.childIndex].value;
248          if (double.IsNaN(x)) instr.value = double.NaN;
249          else {
250            alglib.sinecosineintegrals(x, out si, out ci);
251            instr.value = ci;
252          }
253        } else if (instr.opCode == OpCodes.HyperbolicSineIntegral) {
254          double shi, chi;
255          var x = code[instr.childIndex].value;
256          if (double.IsNaN(x)) instr.value = double.NaN;
257          else {
258            alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
259            instr.value = shi;
260          }
261        } else if (instr.opCode == OpCodes.HyperbolicCosineIntegral) {
262          double shi, chi;
263          var x = code[instr.childIndex].value;
264          if (double.IsNaN(x)) instr.value = double.NaN;
265          else {
266            alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
267            instr.value = chi;
268          }
269        } else if (instr.opCode == OpCodes.FresnelCosineIntegral) {
270          double c = 0, s = 0;
271          var x = code[instr.childIndex].value;
272          if (double.IsNaN(x)) instr.value = double.NaN;
273          else {
274            alglib.fresnelintegral(x, ref c, ref s);
275            instr.value = c;
276          }
277        } else if (instr.opCode == OpCodes.FresnelSineIntegral) {
278          double c = 0, s = 0;
279          var x = code[instr.childIndex].value;
280          if (double.IsNaN(x)) instr.value = double.NaN;
281          else {
282            alglib.fresnelintegral(x, ref c, ref s);
283            instr.value = s;
284          }
285        } else if (instr.opCode == OpCodes.AiryA) {
286          double ai, aip, bi, bip;
287          var x = code[instr.childIndex].value;
288          if (double.IsNaN(x)) instr.value = double.NaN;
289          else {
290            alglib.airy(x, out ai, out aip, out bi, out bip);
291            instr.value = ai;
292          }
293        } else if (instr.opCode == OpCodes.AiryB) {
294          double ai, aip, bi, bip;
295          var x = code[instr.childIndex].value;
296          if (double.IsNaN(x)) instr.value = double.NaN;
297          else {
298            alglib.airy(x, out ai, out aip, out bi, out bip);
299            instr.value = bi;
300          }
301        } else if (instr.opCode == OpCodes.Norm) {
302          var x = code[instr.childIndex].value;
303          if (double.IsNaN(x)) instr.value = double.NaN;
304          else instr.value = alglib.normaldistribution(x);
305        } else if (instr.opCode == OpCodes.Erf) {
306          var x = code[instr.childIndex].value;
307          if (double.IsNaN(x)) instr.value = double.NaN;
308          else instr.value = alglib.errorfunction(x);
309        } else if (instr.opCode == OpCodes.Bessel) {
310          var x = code[instr.childIndex].value;
311          if (double.IsNaN(x)) instr.value = double.NaN;
312          else instr.value = alglib.besseli0(x);
313        } else if (instr.opCode == OpCodes.IfThenElse) {
314          double condition = code[instr.childIndex].value;
315          double result;
316          if (condition > 0.0) {
317            result = code[instr.childIndex + 1].value;
318          } else {
319            result = code[instr.childIndex + 2].value;
320          }
321          instr.value = result;
322        } else if (instr.opCode == OpCodes.AND) {
323          double result = code[instr.childIndex].value;
324          for (int j = 1; j < instr.nArguments; j++) {
325            if (result > 0.0) result = code[instr.childIndex + j].value;
326            else break;
327          }
328          instr.value = result > 0.0 ? 1.0 : -1.0;
329        } else if (instr.opCode == OpCodes.OR) {
330          double result = code[instr.childIndex].value;
331          for (int j = 1; j < instr.nArguments; j++) {
332            if (result <= 0.0) result = code[instr.childIndex + j].value;
333            else break;
334          }
335          instr.value = result > 0.0 ? 1.0 : -1.0;
336        } else if (instr.opCode == OpCodes.NOT) {
337          instr.value = code[instr.childIndex].value > 0.0 ? -1.0 : 1.0;
338        } else if (instr.opCode == OpCodes.XOR) {
339          int positiveSignals = 0;
340          for (int j = 0; j < instr.nArguments; j++) {
341            if (code[instr.childIndex + j].value > 0.0) positiveSignals++;
342          }
343          instr.value = positiveSignals % 2 != 0 ? 1.0 : -1.0;
344        } else if (instr.opCode == OpCodes.GT) {
345          double x = code[instr.childIndex].value;
346          double y = code[instr.childIndex + 1].value;
347          instr.value = x > y ? 1.0 : -1.0;
348        } else if (instr.opCode == OpCodes.LT) {
349          double x = code[instr.childIndex].value;
350          double y = code[instr.childIndex + 1].value;
351          instr.value = x < y ? 1.0 : -1.0;
352        } else if (instr.opCode == OpCodes.TimeLag || instr.opCode == OpCodes.Derivative || instr.opCode == OpCodes.Integral) {
353          var state = (InterpreterState)instr.data;
354          state.Reset();
355          instr.value = interpreter.Evaluate(dataset, ref row, state);
356        } else {
357          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);
358          throw new NotSupportedException(errorText);
359        }
360        #endregion
361      }
362      return code[0].value;
363    }
364
365    private static LinearInstruction[] GetPrefixSequence(LinearInstruction[] code, int startIndex) {
366      var s = new Stack<int>();
367      var list = new List<LinearInstruction>();
368      s.Push(startIndex);
369      while (s.Any()) {
370        int i = s.Pop();
371        var instr = code[i];
372        // push instructions in reverse execution order
373        for (int j = instr.nArguments - 1; j >= 0; j--) s.Push(instr.childIndex + j);
374        list.Add(instr);
375      }
376      return list.ToArray();
377    }
378
379    public static void PrepareInstructions(LinearInstruction[] code, IDataset dataset) {
380      for (int i = 0; i != code.Length; ++i) {
381        var instr = code[i];
382        #region opcode switch
383        switch (instr.opCode) {
384          case OpCodes.Constant: {
385              var constTreeNode = (ConstantTreeNode)instr.dynamicNode;
386              instr.value = constTreeNode.Value;
387              instr.skip = true; // the value is already set so this instruction should be skipped in the evaluation phase
388            }
389            break;
390          case OpCodes.Variable: {
391              var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
392              instr.data = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
393            }
394            break;
395          case OpCodes.LagVariable: {
396              var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
397              instr.data = dataset.GetReadOnlyDoubleValues(laggedVariableTreeNode.VariableName);
398            }
399            break;
400          case OpCodes.VariableCondition: {
401              var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
402              instr.data = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
403            }
404            break;
405          case OpCodes.TimeLag:
406          case OpCodes.Integral:
407          case OpCodes.Derivative: {
408              var seq = GetPrefixSequence(code, i);
409              var interpreterState = new InterpreterState(seq, 0);
410              instr.data = interpreterState;
411              for (int j = 1; j != seq.Length; ++j)
412                seq[j].skip = true;
413            }
414            break;
415        }
416        #endregion
417      }
418    }
419  }
420}
Note: See TracBrowser for help on using the repository browser.