Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2965_CancelablePersistence/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs @ 16321

Last change on this file since 16321 was 15583, checked in by swagner, 6 years ago

#2640: Updated year of copyrights in license headers

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