Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2965_CancelablePersistence/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeInterpreter.cs @ 16605

Last change on this file since 16605 was 16433, checked in by pfleck, 6 years ago

#2965 Merged recent trunk changes.
Enabled the prepared hooks that allows to cancel the save file using the recently introduced cancelable progressbars (in FileManager).

File size: 23.7 KB
RevLine 
[5571]1#region License Information
2/* HeuristicLab
[15583]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5571]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;
[14826]24using System.Linq;
[5571]25using HeuristicLab.Common;
26using HeuristicLab.Core;
[6740]27using HeuristicLab.Data;
[5571]28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[6740]29using HeuristicLab.Parameters;
[5571]30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [StorableClass]
34  [Item("SymbolicDataAnalysisExpressionTreeInterpreter", "Interpreter for symbolic expression trees including automatically defined functions.")]
[13248]35  public class SymbolicDataAnalysisExpressionTreeInterpreter : ParameterizedNamedItem,
36    ISymbolicDataAnalysisExpressionTreeInterpreter {
[5749]37    private const string CheckExpressionsWithIntervalArithmeticParameterName = "CheckExpressionsWithIntervalArithmetic";
[13248]38    private const string CheckExpressionsWithIntervalArithmeticParameterDescription = "Switch that determines if the interpreter checks the validity of expressions with interval arithmetic before evaluating the expression.";
[7615]39    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
[5571]40
[13248]41    public override bool CanChangeName {
42      get { return false; }
43    }
[5571]44
[13248]45    public override bool CanChangeDescription {
46      get { return false; }
47    }
48
[5749]49    #region parameter properties
[13248]50    public IFixedValueParameter<BoolValue> CheckExpressionsWithIntervalArithmeticParameter {
51      get { return (IFixedValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName]; }
[5749]52    }
[7615]53
[13248]54    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
55      get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
[7615]56    }
[5749]57    #endregion
58
59    #region properties
[13248]60    public bool CheckExpressionsWithIntervalArithmetic {
61      get { return CheckExpressionsWithIntervalArithmeticParameter.Value.Value; }
62      set { CheckExpressionsWithIntervalArithmeticParameter.Value.Value = value; }
[5749]63    }
[7615]64
[13248]65    public int EvaluatedSolutions {
66      get { return EvaluatedSolutionsParameter.Value.Value; }
67      set { EvaluatedSolutionsParameter.Value.Value = value; }
[7615]68    }
[5749]69    #endregion
70
[5571]71    [StorableConstructor]
[8436]72    protected SymbolicDataAnalysisExpressionTreeInterpreter(bool deserializing) : base(deserializing) { }
[13248]73
74    protected SymbolicDataAnalysisExpressionTreeInterpreter(SymbolicDataAnalysisExpressionTreeInterpreter original,
[13251]75      Cloner cloner)
76      : base(original, cloner) { }
[13248]77
[5571]78    public override IDeepCloneable Clone(Cloner cloner) {
79      return new SymbolicDataAnalysisExpressionTreeInterpreter(this, cloner);
80    }
81
82    public SymbolicDataAnalysisExpressionTreeInterpreter()
[5749]83      : base("SymbolicDataAnalysisExpressionTreeInterpreter", "Interpreter for symbolic expression trees including automatically defined functions.") {
[13248]84      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, "Switch that determines if the interpreter checks the validity of expressions with interval arithmetic before evaluating the expression.", new BoolValue(false)));
85      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
[5571]86    }
87
[8436]88    protected SymbolicDataAnalysisExpressionTreeInterpreter(string name, string description)
89      : base(name, description) {
[13248]90      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, "Switch that determines if the interpreter checks the validity of expressions with interval arithmetic before evaluating the expression.", new BoolValue(false)));
91      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
[8436]92    }
93
[7615]94    [StorableHook(HookType.AfterDeserialization)]
95    private void AfterDeserialization() {
[13248]96      var evaluatedSolutions = new IntValue(0);
97      var checkExpressionsWithIntervalArithmetic = new BoolValue(false);
98      if (Parameters.ContainsKey(EvaluatedSolutionsParameterName)) {
99        var evaluatedSolutionsParameter = (IValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName];
100        evaluatedSolutions = evaluatedSolutionsParameter.Value;
101        Parameters.Remove(EvaluatedSolutionsParameterName);
102      }
103      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", evaluatedSolutions));
104      if (Parameters.ContainsKey(CheckExpressionsWithIntervalArithmeticParameterName)) {
105        var checkExpressionsWithIntervalArithmeticParameter = (IValueParameter<BoolValue>)Parameters[CheckExpressionsWithIntervalArithmeticParameterName];
106        Parameters.Remove(CheckExpressionsWithIntervalArithmeticParameterName);
107        checkExpressionsWithIntervalArithmetic = checkExpressionsWithIntervalArithmeticParameter.Value;
108      }
109      Parameters.Add(new FixedValueParameter<BoolValue>(CheckExpressionsWithIntervalArithmeticParameterName, CheckExpressionsWithIntervalArithmeticParameterDescription, checkExpressionsWithIntervalArithmetic));
[7615]110    }
111
112    #region IStatefulItem
113    public void InitializeState() {
[13248]114      EvaluatedSolutions = 0;
[7615]115    }
116
[13248]117    public void ClearState() { }
[7615]118    #endregion
119
[13251]120    private readonly object syncRoot = new object();
[13248]121    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, IDataset dataset,
122      IEnumerable<int> rows) {
123      if (CheckExpressionsWithIntervalArithmetic) {
[8436]124        throw new NotSupportedException("Interval arithmetic is not yet supported in the symbolic data analysis interpreter.");
[13248]125      }
[7120]126
[13251]127      lock (syncRoot) {
[13248]128        EvaluatedSolutions++; // increment the evaluated solutions counter
[9004]129      }
[8436]130      var state = PrepareInterpreterState(tree, dataset);
131
132      foreach (var rowEnum in rows) {
133        int row = rowEnum;
134        yield return Evaluate(dataset, ref row, state);
135        state.Reset();
136      }
[7154]137    }
138
[12509]139    private static InterpreterState PrepareInterpreterState(ISymbolicExpressionTree tree, IDataset dataset) {
[8436]140      Instruction[] code = SymbolicExpressionTreeCompiler.Compile(tree, OpCodes.MapSymbolToOpCode);
[5987]141      int necessaryArgStackSize = 0;
[8436]142      foreach (Instruction instr in code) {
[6860]143        if (instr.opCode == OpCodes.Variable) {
[8436]144          var variableTreeNode = (VariableTreeNode)instr.dynamicNode;
[9828]145          instr.data = dataset.GetReadOnlyDoubleValues(variableTreeNode.VariableName);
[14826]146        } else if (instr.opCode == OpCodes.FactorVariable) {
147          var factorTreeNode = instr.dynamicNode as FactorVariableTreeNode;
148          instr.data = dataset.GetReadOnlyStringValues(factorTreeNode.VariableName);
149        } else if (instr.opCode == OpCodes.BinaryFactorVariable) {
150          var factorTreeNode = instr.dynamicNode as BinaryFactorVariableTreeNode;
151          instr.data = dataset.GetReadOnlyStringValues(factorTreeNode.VariableName);
[5571]152        } else if (instr.opCode == OpCodes.LagVariable) {
[8436]153          var laggedVariableTreeNode = (LaggedVariableTreeNode)instr.dynamicNode;
[9828]154          instr.data = dataset.GetReadOnlyDoubleValues(laggedVariableTreeNode.VariableName);
[6860]155        } else if (instr.opCode == OpCodes.VariableCondition) {
[8436]156          var variableConditionTreeNode = (VariableConditionTreeNode)instr.dynamicNode;
[9828]157          instr.data = dataset.GetReadOnlyDoubleValues(variableConditionTreeNode.VariableName);
[5987]158        } else if (instr.opCode == OpCodes.Call) {
159          necessaryArgStackSize += instr.nArguments + 1;
[5571]160        }
161      }
[8436]162      return new InterpreterState(code, necessaryArgStackSize);
163    }
[5571]164
[12509]165    public virtual double Evaluate(IDataset dataset, ref int row, InterpreterState state) {
[5571]166      Instruction currentInstr = state.NextInstruction();
167      switch (currentInstr.opCode) {
168        case OpCodes.Add: {
[8436]169            double s = Evaluate(dataset, ref row, state);
[5571]170            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]171              s += Evaluate(dataset, ref row, state);
[5571]172            }
173            return s;
174          }
175        case OpCodes.Sub: {
[8436]176            double s = Evaluate(dataset, ref row, state);
[5571]177            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]178              s -= Evaluate(dataset, ref row, state);
[5571]179            }
[13248]180            if (currentInstr.nArguments == 1) { s = -s; }
[5571]181            return s;
182          }
183        case OpCodes.Mul: {
[8436]184            double p = Evaluate(dataset, ref row, state);
[5571]185            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]186              p *= Evaluate(dataset, ref row, state);
[5571]187            }
188            return p;
189          }
190        case OpCodes.Div: {
[8436]191            double p = Evaluate(dataset, ref row, state);
[5571]192            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]193              p /= Evaluate(dataset, ref row, state);
[5571]194            }
[13248]195            if (currentInstr.nArguments == 1) { p = 1.0 / p; }
[5571]196            return p;
197          }
198        case OpCodes.Average: {
[8436]199            double sum = Evaluate(dataset, ref row, state);
[5571]200            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]201              sum += Evaluate(dataset, ref row, state);
[5571]202            }
203            return sum / currentInstr.nArguments;
204          }
[16433]205        case OpCodes.Absolute: {
206            return Math.Abs(Evaluate(dataset, ref row, state));
207          }
[5571]208        case OpCodes.Cos: {
[8436]209            return Math.Cos(Evaluate(dataset, ref row, state));
[5571]210          }
211        case OpCodes.Sin: {
[8436]212            return Math.Sin(Evaluate(dataset, ref row, state));
[5571]213          }
214        case OpCodes.Tan: {
[8436]215            return Math.Tan(Evaluate(dataset, ref row, state));
[5571]216          }
[7842]217        case OpCodes.Square: {
[8436]218            return Math.Pow(Evaluate(dataset, ref row, state), 2);
[7842]219          }
[16433]220        case OpCodes.Cube: {
221            return Math.Pow(Evaluate(dataset, ref row, state), 3);
222          }
[5571]223        case OpCodes.Power: {
[8436]224            double x = Evaluate(dataset, ref row, state);
225            double y = Math.Round(Evaluate(dataset, ref row, state));
[5571]226            return Math.Pow(x, y);
227          }
[7842]228        case OpCodes.SquareRoot: {
[8436]229            return Math.Sqrt(Evaluate(dataset, ref row, state));
[7842]230          }
[16433]231        case OpCodes.CubeRoot: {
232            return Math.Pow(Evaluate(dataset, ref row, state), 1.0 / 3.0);
233          }
[5571]234        case OpCodes.Root: {
[8436]235            double x = Evaluate(dataset, ref row, state);
236            double y = Math.Round(Evaluate(dataset, ref row, state));
[5571]237            return Math.Pow(x, 1 / y);
238          }
239        case OpCodes.Exp: {
[8436]240            return Math.Exp(Evaluate(dataset, ref row, state));
[5571]241          }
242        case OpCodes.Log: {
[8436]243            return Math.Log(Evaluate(dataset, ref row, state));
[5571]244          }
[7842]245        case OpCodes.Gamma: {
[8436]246            var x = Evaluate(dataset, ref row, state);
[13248]247            if (double.IsNaN(x)) { return double.NaN; } else { return alglib.gammafunction(x); }
[7842]248          }
249        case OpCodes.Psi: {
[8436]250            var x = Evaluate(dataset, ref row, state);
[7842]251            if (double.IsNaN(x)) return double.NaN;
[8430]252            else if (x <= 0 && (Math.Floor(x) - x).IsAlmost(0)) return double.NaN;
[7842]253            return alglib.psi(x);
254          }
255        case OpCodes.Dawson: {
[8436]256            var x = Evaluate(dataset, ref row, state);
[13248]257            if (double.IsNaN(x)) { return double.NaN; }
[7842]258            return alglib.dawsonintegral(x);
259          }
260        case OpCodes.ExponentialIntegralEi: {
[8436]261            var x = Evaluate(dataset, ref row, state);
[13248]262            if (double.IsNaN(x)) { return double.NaN; }
[7842]263            return alglib.exponentialintegralei(x);
264          }
265        case OpCodes.SineIntegral: {
266            double si, ci;
[8436]267            var x = Evaluate(dataset, ref row, state);
[7842]268            if (double.IsNaN(x)) return double.NaN;
269            else {
270              alglib.sinecosineintegrals(x, out si, out ci);
271              return si;
272            }
273          }
274        case OpCodes.CosineIntegral: {
275            double si, ci;
[8436]276            var x = Evaluate(dataset, ref row, state);
[7842]277            if (double.IsNaN(x)) return double.NaN;
278            else {
279              alglib.sinecosineintegrals(x, out si, out ci);
280              return ci;
281            }
282          }
283        case OpCodes.HyperbolicSineIntegral: {
284            double shi, chi;
[8436]285            var x = Evaluate(dataset, ref row, state);
[7842]286            if (double.IsNaN(x)) return double.NaN;
287            else {
288              alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
289              return shi;
290            }
291          }
292        case OpCodes.HyperbolicCosineIntegral: {
293            double shi, chi;
[8436]294            var x = Evaluate(dataset, ref row, state);
[7842]295            if (double.IsNaN(x)) return double.NaN;
296            else {
297              alglib.hyperbolicsinecosineintegrals(x, out shi, out chi);
298              return chi;
299            }
300          }
301        case OpCodes.FresnelCosineIntegral: {
302            double c = 0, s = 0;
[8436]303            var x = Evaluate(dataset, ref row, state);
[7842]304            if (double.IsNaN(x)) return double.NaN;
305            else {
306              alglib.fresnelintegral(x, ref c, ref s);
307              return c;
308            }
309          }
310        case OpCodes.FresnelSineIntegral: {
311            double c = 0, s = 0;
[8436]312            var x = Evaluate(dataset, ref row, state);
[7842]313            if (double.IsNaN(x)) return double.NaN;
314            else {
315              alglib.fresnelintegral(x, ref c, ref s);
316              return s;
317            }
318          }
319        case OpCodes.AiryA: {
320            double ai, aip, bi, bip;
[8436]321            var x = Evaluate(dataset, ref row, state);
[7842]322            if (double.IsNaN(x)) return double.NaN;
323            else {
324              alglib.airy(x, out ai, out aip, out bi, out bip);
325              return ai;
326            }
327          }
328        case OpCodes.AiryB: {
329            double ai, aip, bi, bip;
[8436]330            var x = Evaluate(dataset, ref row, state);
[7842]331            if (double.IsNaN(x)) return double.NaN;
332            else {
333              alglib.airy(x, out ai, out aip, out bi, out bip);
334              return bi;
335            }
336          }
337        case OpCodes.Norm: {
[8436]338            var x = Evaluate(dataset, ref row, state);
[7842]339            if (double.IsNaN(x)) return double.NaN;
340            else return alglib.normaldistribution(x);
341          }
342        case OpCodes.Erf: {
[8436]343            var x = Evaluate(dataset, ref row, state);
[7842]344            if (double.IsNaN(x)) return double.NaN;
345            else return alglib.errorfunction(x);
346          }
347        case OpCodes.Bessel: {
[8436]348            var x = Evaluate(dataset, ref row, state);
[7842]349            if (double.IsNaN(x)) return double.NaN;
350            else return alglib.besseli0(x);
351          }
[16433]352
353        case OpCodes.AnalyticQuotient: {
354            var x1 = Evaluate(dataset, ref row, state);
355            var x2 = Evaluate(dataset, ref row, state);
356            return x1 / Math.Pow(1 + x2 * x2, 0.5);
357          }
[5571]358        case OpCodes.IfThenElse: {
[8436]359            double condition = Evaluate(dataset, ref row, state);
[5571]360            double result;
361            if (condition > 0.0) {
[8436]362              result = Evaluate(dataset, ref row, state); state.SkipInstructions();
[5571]363            } else {
[8436]364              state.SkipInstructions(); result = Evaluate(dataset, ref row, state);
[5571]365            }
366            return result;
367          }
368        case OpCodes.AND: {
[8436]369            double result = Evaluate(dataset, ref row, state);
[5571]370            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]371              if (result > 0.0) result = Evaluate(dataset, ref row, state);
[5571]372              else {
[8436]373                state.SkipInstructions();
[5571]374              }
375            }
[6732]376            return result > 0.0 ? 1.0 : -1.0;
[5571]377          }
378        case OpCodes.OR: {
[8436]379            double result = Evaluate(dataset, ref row, state);
[5571]380            for (int i = 1; i < currentInstr.nArguments; i++) {
[8436]381              if (result <= 0.0) result = Evaluate(dataset, ref row, state);
[5571]382              else {
[8436]383                state.SkipInstructions();
[5571]384              }
385            }
386            return result > 0.0 ? 1.0 : -1.0;
387          }
388        case OpCodes.NOT: {
[8436]389            return Evaluate(dataset, ref row, state) > 0.0 ? -1.0 : 1.0;
[5571]390          }
[10774]391        case OpCodes.XOR: {
[10788]392            //mkommend: XOR on multiple inputs is defined as true if the number of positive signals is odd
393            // this is equal to a consecutive execution of binary XOR operations.
394            int positiveSignals = 0;
395            for (int i = 0; i < currentInstr.nArguments; i++) {
[13248]396              if (Evaluate(dataset, ref row, state) > 0.0) { positiveSignals++; }
[10774]397            }
[10788]398            return positiveSignals % 2 != 0 ? 1.0 : -1.0;
[10774]399          }
[5571]400        case OpCodes.GT: {
[8436]401            double x = Evaluate(dataset, ref row, state);
402            double y = Evaluate(dataset, ref row, state);
[13248]403            if (x > y) { return 1.0; } else { return -1.0; }
[5571]404          }
405        case OpCodes.LT: {
[8436]406            double x = Evaluate(dataset, ref row, state);
407            double y = Evaluate(dataset, ref row, state);
[13248]408            if (x < y) { return 1.0; } else { return -1.0; }
[5571]409          }
410        case OpCodes.TimeLag: {
411            var timeLagTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
412            row += timeLagTreeNode.Lag;
[8436]413            double result = Evaluate(dataset, ref row, state);
[5571]414            row -= timeLagTreeNode.Lag;
415            return result;
416          }
417        case OpCodes.Integral: {
418            int savedPc = state.ProgramCounter;
419            var timeLagTreeNode = (LaggedTreeNode)currentInstr.dynamicNode;
420            double sum = 0.0;
421            for (int i = 0; i < Math.Abs(timeLagTreeNode.Lag); i++) {
422              row += Math.Sign(timeLagTreeNode.Lag);
[8436]423              sum += Evaluate(dataset, ref row, state);
[5571]424              state.ProgramCounter = savedPc;
425            }
426            row -= timeLagTreeNode.Lag;
[8436]427            sum += Evaluate(dataset, ref row, state);
[5571]428            return sum;
429          }
430
431        //mkommend: derivate calculation taken from:
432        //http://www.holoborodko.com/pavel/numerical-methods/numerical-derivative/smooth-low-noise-differentiators/
433        //one sided smooth differentiatior, N = 4
434        // y' = 1/8h (f_i + 2f_i-1, -2 f_i-3 - f_i-4)
435        case OpCodes.Derivative: {
436            int savedPc = state.ProgramCounter;
[8436]437            double f_0 = Evaluate(dataset, ref row, state); row--;
[5571]438            state.ProgramCounter = savedPc;
[8436]439            double f_1 = Evaluate(dataset, ref row, state); row -= 2;
[5571]440            state.ProgramCounter = savedPc;
[8436]441            double f_3 = Evaluate(dataset, ref row, state); row--;
[5571]442            state.ProgramCounter = savedPc;
[8436]443            double f_4 = Evaluate(dataset, ref row, state);
[5571]444            row += 4;
445
446            return (f_0 + 2 * f_1 - 2 * f_3 - f_4) / 8; // h = 1
447          }
448        case OpCodes.Call: {
449            // evaluate sub-trees
450            double[] argValues = new double[currentInstr.nArguments];
451            for (int i = 0; i < currentInstr.nArguments; i++) {
[8436]452              argValues[i] = Evaluate(dataset, ref row, state);
[5571]453            }
454            // push on argument values on stack
455            state.CreateStackFrame(argValues);
456
457            // save the pc
458            int savedPc = state.ProgramCounter;
459            // set pc to start of function 
[9828]460            state.ProgramCounter = (ushort)currentInstr.data;
[5571]461            // evaluate the function
[8436]462            double v = Evaluate(dataset, ref row, state);
[5571]463
464            // delete the stack frame
465            state.RemoveStackFrame();
466
467            // restore the pc => evaluation will continue at point after my subtrees 
468            state.ProgramCounter = savedPc;
469            return v;
470          }
471        case OpCodes.Arg: {
[9828]472            return state.GetStackFrameValue((ushort)currentInstr.data);
[5571]473          }
474        case OpCodes.Variable: {
[8486]475            if (row < 0 || row >= dataset.Rows) return double.NaN;
[6740]476            var variableTreeNode = (VariableTreeNode)currentInstr.dynamicNode;
[9828]477            return ((IList<double>)currentInstr.data)[row] * variableTreeNode.Weight;
[5571]478          }
[14826]479        case OpCodes.BinaryFactorVariable: {
480            if (row < 0 || row >= dataset.Rows) return double.NaN;
481            var factorVarTreeNode = currentInstr.dynamicNode as BinaryFactorVariableTreeNode;
482            return ((IList<string>)currentInstr.data)[row] == factorVarTreeNode.VariableValue ? factorVarTreeNode.Weight : 0;
483          }
484        case OpCodes.FactorVariable: {
485            if (row < 0 || row >= dataset.Rows) return double.NaN;
486            var factorVarTreeNode = currentInstr.dynamicNode as FactorVariableTreeNode;
487            return factorVarTreeNode.GetValue(((IList<string>)currentInstr.data)[row]);
488          }
[5571]489        case OpCodes.LagVariable: {
[6740]490            var laggedVariableTreeNode = (LaggedVariableTreeNode)currentInstr.dynamicNode;
[5571]491            int actualRow = row + laggedVariableTreeNode.Lag;
[13248]492            if (actualRow < 0 || actualRow >= dataset.Rows) { return double.NaN; }
[9828]493            return ((IList<double>)currentInstr.data)[actualRow] * laggedVariableTreeNode.Weight;
[5571]494          }
495        case OpCodes.Constant: {
[8436]496            var constTreeNode = (ConstantTreeNode)currentInstr.dynamicNode;
[5897]497            return constTreeNode.Value;
[5571]498          }
499
500        //mkommend: this symbol uses the logistic function f(x) = 1 / (1 + e^(-alpha * x) )
501        //to determine the relative amounts of the true and false branch see http://en.wikipedia.org/wiki/Logistic_function
502        case OpCodes.VariableCondition: {
[8486]503            if (row < 0 || row >= dataset.Rows) return double.NaN;
[5571]504            var variableConditionTreeNode = (VariableConditionTreeNode)currentInstr.dynamicNode;
[14345]505            if (!variableConditionTreeNode.Symbol.IgnoreSlope) {
506              double variableValue = ((IList<double>)currentInstr.data)[row];
507              double x = variableValue - variableConditionTreeNode.Threshold;
508              double p = 1 / (1 + Math.Exp(-variableConditionTreeNode.Slope * x));
[5571]509
[14345]510              double trueBranch = Evaluate(dataset, ref row, state);
511              double falseBranch = Evaluate(dataset, ref row, state);
[5571]512
[14345]513              return trueBranch * p + falseBranch * (1 - p);
514            } else {
515              // strict threshold
516              double variableValue = ((IList<double>)currentInstr.data)[row];
517              if (variableValue <= variableConditionTreeNode.Threshold) {
518                var left = Evaluate(dataset, ref row, state);
519                state.SkipInstructions();
520                return left;
521              } else {
522                state.SkipInstructions();
523                return Evaluate(dataset, ref row, state);
524              }
525            }
[5571]526          }
[13248]527        default:
528          throw new NotSupportedException();
[5571]529      }
530    }
531  }
[13248]532}
Note: See TracBrowser for help on using the repository browser.