Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2520_PersistenceReintegration/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs @ 16605

Last change on this file since 16605 was 16559, checked in by jkarder, 6 years ago

#2520: renamed Fossil to Attic and set version to 1.0.0-pre01

File size: 22.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [StorableType("EF325166-E03A-44C4-83CE-7F07B836285E")]
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(StorableConstructorFlag _) : base(_) {
73      interpreter = new SymbolicDataAnalysisExpressionTreeInterpreter();
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 (!rows.Any()) return Enumerable.Empty<double>();
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.BinaryFactorVariable) {
152          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
153          else {
154            var factorTreeNode = instr.dynamicNode as BinaryFactorVariableTreeNode;
155            instr.value = ((IList<string>)instr.data)[row] == factorTreeNode.VariableValue ? factorTreeNode.Weight : 0;
156          }
157        } else if (instr.opCode == OpCodes.FactorVariable) {
158          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
159          else {
160            var factorTreeNode = instr.dynamicNode as FactorVariableTreeNode;
161            instr.value = factorTreeNode.GetValue(((IList<string>)instr.data)[row]);
162          }
163        } else if (instr.opCode == OpCodes.LagVariable) {
164          var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
165          int actualRow = row + laggedVariableTreeNode.Lag;
166          if (actualRow < 0 || actualRow >= dataset.Rows)
167            instr.value = double.NaN;
168          else
169            instr.value = ((IList<double>)instr.data)[actualRow] * laggedVariableTreeNode.Weight;
170        } else if (instr.opCode == OpCodes.VariableCondition) {
171          if (row < 0 || row >= dataset.Rows) instr.value = double.NaN;
172          var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
173          if (!variableConditionTreeNode.Symbol.IgnoreSlope) {
174            double variableValue = ((IList<double>)instr.data)[row];
175            double x = variableValue - variableConditionTreeNode.Threshold;
176            double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x));
177
178            double trueBranch = code[instr.childIndex].value;
179            double falseBranch = code[instr.childIndex + 1].value;
180
181            instr.value = trueBranch * p + falseBranch * (1 - p);
182          } else {
183            double variableValue = ((IList<double>)instr.data)[row];
184            if (variableValue <= variableConditionTreeNode.Threshold) {
185              instr.value = code[instr.childIndex].value;
186            } else {
187              instr.value = code[instr.childIndex + 1].value;
188            }
189          }
190        } else if (instr.opCode == OpCodes.Add) {
191          double s = code[instr.childIndex].value;
192          for (int j = 1; j != instr.nArguments; ++j) {
193            s += code[instr.childIndex + j].value;
194          }
195          instr.value = s;
196        } else if (instr.opCode == OpCodes.Sub) {
197          double s = code[instr.childIndex].value;
198          for (int j = 1; j != instr.nArguments; ++j) {
199            s -= code[instr.childIndex + j].value;
200          }
201          if (instr.nArguments == 1) s = -s;
202          instr.value = s;
203        } else if (instr.opCode == OpCodes.Mul) {
204          double p = code[instr.childIndex].value;
205          for (int j = 1; j != instr.nArguments; ++j) {
206            p *= code[instr.childIndex + j].value;
207          }
208          instr.value = p;
209        } else if (instr.opCode == OpCodes.Div) {
210          double p = code[instr.childIndex].value;
211          for (int j = 1; j != instr.nArguments; ++j) {
212            p /= code[instr.childIndex + j].value;
213          }
214          if (instr.nArguments == 1) p = 1.0 / p;
215          instr.value = p;
216        } else if (instr.opCode == OpCodes.AnalyticQuotient) {
217          var x1 = code[instr.childIndex].value;
218          var x2 = code[instr.childIndex + 1].value;
219          instr.value = x1 / Math.Sqrt(1 + x2 * x2);
220        } else if (instr.opCode == OpCodes.Average) {
221          double s = code[instr.childIndex].value;
222          for (int j = 1; j != instr.nArguments; ++j) {
223            s += code[instr.childIndex + j].value;
224          }
225          instr.value = s / instr.nArguments;
226        } else if (instr.opCode == OpCodes.Absolute) {
227          instr.value = Math.Abs(code[instr.childIndex].value);
228        } else if (instr.opCode == OpCodes.Cos) {
229          instr.value = Math.Cos(code[instr.childIndex].value);
230        } else if (instr.opCode == OpCodes.Sin) {
231          instr.value = Math.Sin(code[instr.childIndex].value);
232        } else if (instr.opCode == OpCodes.Tan) {
233          instr.value = Math.Tan(code[instr.childIndex].value);
234        } else if (instr.opCode == OpCodes.Square) {
235          instr.value = Math.Pow(code[instr.childIndex].value, 2);
236        } else if (instr.opCode == OpCodes.Cube) {
237          instr.value = Math.Pow(code[instr.childIndex].value, 3);
238        } else if (instr.opCode == OpCodes.Power) {
239          double x = code[instr.childIndex].value;
240          double y = Math.Round(code[instr.childIndex + 1].value);
241          instr.value = Math.Pow(x, y);
242        } else if (instr.opCode == OpCodes.SquareRoot) {
243          instr.value = Math.Sqrt(code[instr.childIndex].value);
244        } else if (instr.opCode == OpCodes.CubeRoot) {
245          instr.value = Math.Pow(code[instr.childIndex].value, 1.0 / 3.0);
246        } else if (instr.opCode == OpCodes.Root) {
247          double x = code[instr.childIndex].value;
248          double y = Math.Round(code[instr.childIndex + 1].value);
249          instr.value = Math.Pow(x, 1 / y);
250        } else if (instr.opCode == OpCodes.Exp) {
251          instr.value = Math.Exp(code[instr.childIndex].value);
252        } else if (instr.opCode == OpCodes.Log) {
253          instr.value = Math.Log(code[instr.childIndex].value);
254        } else if (instr.opCode == OpCodes.Gamma) {
255          var x = code[instr.childIndex].value;
256          instr.value = double.IsNaN(x) ? double.NaN : alglib.gammafunction(x);
257        } else if (instr.opCode == OpCodes.Psi) {
258          var x = code[instr.childIndex].value;
259          if (double.IsNaN(x)) instr.value = double.NaN;
260          else if (x <= 0 && (Math.Floor(x) - x).IsAlmost(0)) instr.value = double.NaN;
261          else instr.value = alglib.psi(x);
262        } else if (instr.opCode == OpCodes.Dawson) {
263          var x = code[instr.childIndex].value;
264          instr.value = double.IsNaN(x) ? double.NaN : alglib.dawsonintegral(x);
265        } else if (instr.opCode == OpCodes.ExponentialIntegralEi) {
266          var x = code[instr.childIndex].value;
267          instr.value = double.IsNaN(x) ? double.NaN : alglib.exponentialintegralei(x);
268        } else if (instr.opCode == OpCodes.SineIntegral) {
269          double si, ci;
270          var x = code[instr.childIndex].value;
271          if (double.IsNaN(x)) instr.value = double.NaN;
272          else {
273            alglib.sinecosineintegrals(x, out si, out ci);
274            instr.value = si;
275          }
276        } else if (instr.opCode == OpCodes.CosineIntegral) {
277          double si, ci;
278          var x = code[instr.childIndex].value;
279          if (double.IsNaN(x)) instr.value = double.NaN;
280          else {
281            alglib.sinecosineintegrals(x, out si, out ci);
282            instr.value = ci;
283          }
284        } else if (instr.opCode == OpCodes.HyperbolicSineIntegral) {
285          double shi, chi;
286          var x = code[instr.childIndex].value;
287          if (double.IsNaN(x)) instr.value = double.NaN;
288          else {
289            alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
290            instr.value = shi;
291          }
292        } else if (instr.opCode == OpCodes.HyperbolicCosineIntegral) {
293          double shi, chi;
294          var x = code[instr.childIndex].value;
295          if (double.IsNaN(x)) instr.value = double.NaN;
296          else {
297            alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
298            instr.value = chi;
299          }
300        } else if (instr.opCode == OpCodes.FresnelCosineIntegral) {
301          double c = 0, s = 0;
302          var x = code[instr.childIndex].value;
303          if (double.IsNaN(x)) instr.value = double.NaN;
304          else {
305            alglib.fresnelintegral(x, ref c, ref s);
306            instr.value = c;
307          }
308        } else if (instr.opCode == OpCodes.FresnelSineIntegral) {
309          double c = 0, s = 0;
310          var x = code[instr.childIndex].value;
311          if (double.IsNaN(x)) instr.value = double.NaN;
312          else {
313            alglib.fresnelintegral(x, ref c, ref s);
314            instr.value = s;
315          }
316        } else if (instr.opCode == OpCodes.AiryA) {
317          double ai, aip, bi, bip;
318          var x = code[instr.childIndex].value;
319          if (double.IsNaN(x)) instr.value = double.NaN;
320          else {
321            alglib.airy(x, out ai, out aip, out bi, out bip);
322            instr.value = ai;
323          }
324        } else if (instr.opCode == OpCodes.AiryB) {
325          double ai, aip, bi, bip;
326          var x = code[instr.childIndex].value;
327          if (double.IsNaN(x)) instr.value = double.NaN;
328          else {
329            alglib.airy(x, out ai, out aip, out bi, out bip);
330            instr.value = bi;
331          }
332        } else if (instr.opCode == OpCodes.Norm) {
333          var x = code[instr.childIndex].value;
334          if (double.IsNaN(x)) instr.value = double.NaN;
335          else instr.value = alglib.normaldistribution(x);
336        } else if (instr.opCode == OpCodes.Erf) {
337          var x = code[instr.childIndex].value;
338          if (double.IsNaN(x)) instr.value = double.NaN;
339          else instr.value = alglib.errorfunction(x);
340        } else if (instr.opCode == OpCodes.Bessel) {
341          var x = code[instr.childIndex].value;
342          if (double.IsNaN(x)) instr.value = double.NaN;
343          else instr.value = alglib.besseli0(x);
344        } else if (instr.opCode == OpCodes.IfThenElse) {
345          double condition = code[instr.childIndex].value;
346          double result;
347          if (condition > 0.0) {
348            result = code[instr.childIndex + 1].value;
349          } else {
350            result = code[instr.childIndex + 2].value;
351          }
352          instr.value = result;
353        } else if (instr.opCode == OpCodes.AND) {
354          double result = code[instr.childIndex].value;
355          for (int j = 1; j < instr.nArguments; j++) {
356            if (result > 0.0) result = code[instr.childIndex + j].value;
357            else break;
358          }
359          instr.value = result > 0.0 ? 1.0 : -1.0;
360        } else if (instr.opCode == OpCodes.OR) {
361          double result = code[instr.childIndex].value;
362          for (int j = 1; j < instr.nArguments; j++) {
363            if (result <= 0.0) result = code[instr.childIndex + j].value;
364            else break;
365          }
366          instr.value = result > 0.0 ? 1.0 : -1.0;
367        } else if (instr.opCode == OpCodes.NOT) {
368          instr.value = code[instr.childIndex].value > 0.0 ? -1.0 : 1.0;
369        } else if (instr.opCode == OpCodes.XOR) {
370          int positiveSignals = 0;
371          for (int j = 0; j < instr.nArguments; j++) {
372            if (code[instr.childIndex + j].value > 0.0) positiveSignals++;
373          }
374          instr.value = positiveSignals % 2 != 0 ? 1.0 : -1.0;
375        } else if (instr.opCode == OpCodes.GT) {
376          double x = code[instr.childIndex].value;
377          double y = code[instr.childIndex + 1].value;
378          instr.value = x > y ? 1.0 : -1.0;
379        } else if (instr.opCode == OpCodes.LT) {
380          double x = code[instr.childIndex].value;
381          double y = code[instr.childIndex + 1].value;
382          instr.value = x < y ? 1.0 : -1.0;
383        } else if (instr.opCode == OpCodes.TimeLag || instr.opCode == OpCodes.Derivative || instr.opCode == OpCodes.Integral) {
384          var state = (InterpreterState)instr.data;
385          state.Reset();
386          instr.value = interpreter.Evaluate(dataset, ref row, state);
387        } else {
388          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);
389          throw new NotSupportedException(errorText);
390        }
391        #endregion
392      }
393      return code[0].value;
394    }
395
396    private static LinearInstruction[] GetPrefixSequence(LinearInstruction[] code, int startIndex) {
397      var s = new Stack<int>();
398      var list = new List<LinearInstruction>();
399      s.Push(startIndex);
400      while (s.Any()) {
401        int i = s.Pop();
402        var instr = code[i];
403        // push instructions in reverse execution order
404        for (int j = instr.nArguments - 1; j >= 0; j--) s.Push(instr.childIndex + j);
405        list.Add(instr);
406      }
407      return list.ToArray();
408    }
409
410    public static void PrepareInstructions(LinearInstruction[] code, IDataset dataset) {
411      for (int i = 0; i != code.Length; ++i) {
412        var instr = code[i];
413        #region opcode switch
414        switch (instr.opCode) {
415          case OpCodes.Constant: {
416              var constTreeNode = (ConstantTreeNode)instr.dynamicNode;
417              instr.value = constTreeNode.Value;
418              instr.skip = true; // the value is already set so this instruction should be skipped in the evaluation phase
419            }
420            break;
421          case OpCodes.Variable: {
422              var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
423              instr.data = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
424            }
425            break;
426          case OpCodes.BinaryFactorVariable: {
427              var factorVariableTreeNode = instr.dynamicNode as BinaryFactorVariableTreeNode;
428              instr.data = dataset.GetReadOnlyStringValues(factorVariableTreeNode.VariableName);
429            }
430            break;
431          case OpCodes.FactorVariable: {
432              var factorVariableTreeNode = instr.dynamicNode as FactorVariableTreeNode;
433              instr.data = dataset.GetReadOnlyStringValues(factorVariableTreeNode.VariableName);
434            }
435            break;
436          case OpCodes.LagVariable: {
437              var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
438              instr.data = dataset.GetReadOnlyDoubleValues(laggedVariableTreeNode.VariableName);
439            }
440            break;
441          case OpCodes.VariableCondition: {
442              var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
443              instr.data = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
444            }
445            break;
446          case OpCodes.TimeLag:
447          case OpCodes.Integral:
448          case OpCodes.Derivative: {
449              var seq = GetPrefixSequence(code, i);
450              var interpreterState = new InterpreterState(seq, 0);
451              instr.data = interpreterState;
452              for (int j = 1; j != seq.Length; ++j)
453                seq[j].skip = true;
454              break;
455            }
456        }
457        #endregion
458      }
459    }
460  }
461}
Note: See TracBrowser for help on using the repository browser.