Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeLinearInterpreter.cs @ 14232

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

created a feature branch for #2650 (support for categorical variables in symb reg) with a first set of changes

work in progress...

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