Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14811 was 14811, checked in by mkommend, 7 years ago

#2442: Merged r12807, r13039, r13139, r13140, r13141, r13222, r13247, r13248, r13251, r13254, r13255, r13256, r1326, r13288, r13313, r13314, r13315, r13318, r14282, r14809, r14810 into stable.

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