Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionConstantOptimizationEvaluator.cs @ 15131

Last change on this file since 15131 was 15131, checked in by gkronber, 7 years ago

#2650: merged r14826 from trunk to stable. The only remaining conflict is DataTableControl and ScatterPlotControl which have been renamed within r14982 (-> tree conflict).

File size: 28.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 AutoDiff;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  [Item("Constant Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the constant used.")]
35  [StorableClass]
36  public class SymbolicRegressionConstantOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
37    private const string ConstantOptimizationIterationsParameterName = "ConstantOptimizationIterations";
38    private const string ConstantOptimizationImprovementParameterName = "ConstantOptimizationImprovement";
39    private const string ConstantOptimizationProbabilityParameterName = "ConstantOptimizationProbability";
40    private const string ConstantOptimizationRowsPercentageParameterName = "ConstantOptimizationRowsPercentage";
41    private const string UpdateConstantsInTreeParameterName = "UpdateConstantsInSymbolicExpressionTree";
42    private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
43
44    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
45      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
46    }
47    public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
48      get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
49    }
50    public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
51      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
52    }
53    public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
54      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
55    }
56    public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
57      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
58    }
59    public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
60      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
61    }
62
63
64    public IntValue ConstantOptimizationIterations {
65      get { return ConstantOptimizationIterationsParameter.Value; }
66    }
67    public DoubleValue ConstantOptimizationImprovement {
68      get { return ConstantOptimizationImprovementParameter.Value; }
69    }
70    public PercentValue ConstantOptimizationProbability {
71      get { return ConstantOptimizationProbabilityParameter.Value; }
72    }
73    public PercentValue ConstantOptimizationRowsPercentage {
74      get { return ConstantOptimizationRowsPercentageParameter.Value; }
75    }
76    public bool UpdateConstantsInTree {
77      get { return UpdateConstantsInTreeParameter.Value.Value; }
78      set { UpdateConstantsInTreeParameter.Value.Value = value; }
79    }
80
81    public bool UpdateVariableWeights {
82      get { return UpdateVariableWeightsParameter.Value.Value; }
83      set { UpdateVariableWeightsParameter.Value.Value = value; }
84    }
85
86    public override bool Maximization {
87      get { return true; }
88    }
89
90    [StorableConstructor]
91    protected SymbolicRegressionConstantOptimizationEvaluator(bool deserializing) : base(deserializing) { }
92    protected SymbolicRegressionConstantOptimizationEvaluator(SymbolicRegressionConstantOptimizationEvaluator original, Cloner cloner)
93      : base(original, cloner) {
94    }
95    public SymbolicRegressionConstantOptimizationEvaluator()
96      : base() {
97      Parameters.Add(new FixedValueParameter<IntValue>(ConstantOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the constant of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10), true));
98      Parameters.Add(new FixedValueParameter<DoubleValue>(ConstantOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the constant optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0), true) { Hidden = true });
99      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1), true));
100      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1), true));
101      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)) { Hidden = true });
102      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
103    }
104
105    public override IDeepCloneable Clone(Cloner cloner) {
106      return new SymbolicRegressionConstantOptimizationEvaluator(this, cloner);
107    }
108
109    [StorableHook(HookType.AfterDeserialization)]
110    private void AfterDeserialization() {
111      if (!Parameters.ContainsKey(UpdateConstantsInTreeParameterName))
112        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateConstantsInTreeParameterName, "Determines if the constants in the tree should be overwritten by the optimized constants.", new BoolValue(true)));
113      if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
114        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)));
115    }
116
117    public override IOperation InstrumentedApply() {
118      var solution = SymbolicExpressionTreeParameter.ActualValue;
119      double quality;
120      if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
121        IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
122        quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
123           constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree);
124
125        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
126          var evaluationRows = GenerateRowsToEvaluate();
127          quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
128        }
129      } else {
130        var evaluationRows = GenerateRowsToEvaluate();
131        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, ProblemDataParameter.ActualValue, evaluationRows, ApplyLinearScalingParameter.ActualValue.Value);
132      }
133      QualityParameter.ActualValue = new DoubleValue(quality);
134
135      return base.InstrumentedApply();
136    }
137
138    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
139      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
140      EstimationLimitsParameter.ExecutionContext = context;
141      ApplyLinearScalingParameter.ExecutionContext = context;
142
143      // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
144      // because Evaluate() is used to get the quality of evolved models on
145      // different partitions of the dataset (e.g., best validation model)
146      double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, EstimationLimitsParameter.ActualValue.Lower, EstimationLimitsParameter.ActualValue.Upper, problemData, rows, ApplyLinearScalingParameter.ActualValue.Value);
147
148      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
149      EstimationLimitsParameter.ExecutionContext = null;
150      ApplyLinearScalingParameter.ExecutionContext = null;
151
152      return r2;
153    }
154
155    #region derivations of functions
156    // create function factory for arctangent
157    private readonly Func<Term, UnaryFunc> arctan = UnaryFunc.Factory(
158      eval: Math.Atan,
159      diff: x => 1 / (1 + x * x));
160    private static readonly Func<Term, UnaryFunc> sin = UnaryFunc.Factory(
161      eval: Math.Sin,
162      diff: Math.Cos);
163    private static readonly Func<Term, UnaryFunc> cos = UnaryFunc.Factory(
164       eval: Math.Cos,
165       diff: x => -Math.Sin(x));
166    private static readonly Func<Term, UnaryFunc> tan = UnaryFunc.Factory(
167      eval: Math.Tan,
168      diff: x => 1 + Math.Tan(x) * Math.Tan(x));
169    private static readonly Func<Term, UnaryFunc> erf = UnaryFunc.Factory(
170      eval: alglib.errorfunction,
171      diff: x => 2.0 * Math.Exp(-(x * x)) / Math.Sqrt(Math.PI));
172    private static readonly Func<Term, UnaryFunc> norm = UnaryFunc.Factory(
173      eval: alglib.normaldistribution,
174      diff: x => -(Math.Exp(-(x * x)) * Math.Sqrt(Math.Exp(x * x)) * x) / Math.Sqrt(2 * Math.PI));
175    #endregion
176
177
178
179    public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
180      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
181      int maxIterations, bool updateVariableWeights = true,
182      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
183      bool updateConstantsInTree = true) {
184
185      // numeric constants in the tree become variables for constant opt
186      // variables in the tree become parameters (fixed values) for constant opt
187      // for each parameter (variable in the original tree) we store the
188      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
189      // A dictionary is used to find parameters
190      var variables = new List<AutoDiff.Variable>();
191      var parameters = new Dictionary<DataForVariable, AutoDiff.Variable>();
192
193      AutoDiff.Term func;
194      if (!TryTransformToAutoDiff(tree.Root.GetSubtree(0), variables, parameters, updateVariableWeights, out func))
195        throw new NotSupportedException("Could not optimize constants of symbolic expression tree due to not supported symbols used in the tree.");
196      if (parameters.Count == 0) return 0.0; // gkronber: constant expressions always have a R² of 0.0
197
198      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
199      AutoDiff.IParametricCompiledTerm compiledFunc = func.Compile(variables.ToArray(), parameterEntries.Select(kvp => kvp.Value).ToArray());
200
201      List<SymbolicExpressionTreeTerminalNode> terminalNodes = null; // gkronber only used for extraction of initial constants
202      if (updateVariableWeights)
203        terminalNodes = tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>().ToList();
204      else
205        terminalNodes = new List<SymbolicExpressionTreeTerminalNode>
206          (tree.Root.IterateNodesPrefix()
207          .OfType<SymbolicExpressionTreeTerminalNode>()
208          .Where(node => node is ConstantTreeNode || node is FactorVariableTreeNode));
209
210      //extract inital constants
211      double[] c = new double[variables.Count];
212      {
213        c[0] = 0.0;
214        c[1] = 1.0;
215        int i = 2;
216        foreach (var node in terminalNodes) {
217          ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
218          VariableTreeNode variableTreeNode = node as VariableTreeNode;
219          BinaryFactorVariableTreeNode binFactorVarTreeNode = node as BinaryFactorVariableTreeNode;
220          FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
221          if (constantTreeNode != null)
222            c[i++] = constantTreeNode.Value;
223          else if (updateVariableWeights && variableTreeNode != null)
224            c[i++] = variableTreeNode.Weight;
225          else if (updateVariableWeights && binFactorVarTreeNode != null)
226            c[i++] = binFactorVarTreeNode.Weight;
227          else if (factorVarTreeNode != null) {
228            // gkronber: a factorVariableTreeNode holds a category-specific constant therefore we can consider factors to be the same as constants
229            foreach (var w in factorVarTreeNode.Weights) c[i++] = w;
230          }
231        }
232      }
233      double[] originalConstants = (double[])c.Clone();
234      double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
235
236      alglib.lsfitstate state;
237      alglib.lsfitreport rep;
238      int retVal;
239
240      IDataset ds = problemData.Dataset;
241      double[,] x = new double[rows.Count(), parameters.Count];
242      int row = 0;
243      foreach (var r in rows) {
244        int col = 0;
245        foreach (var kvp in parameterEntries) {
246          var info = kvp.Key;
247          int lag = info.lag;
248          if (ds.VariableHasType<double>(info.variableName)) {
249            x[row, col] = ds.GetDoubleValue(info.variableName, r + lag);
250          } else if (ds.VariableHasType<string>(info.variableName)) {
251            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
252          } else throw new InvalidProgramException("found a variable of unknown type");
253          col++;
254        }
255        row++;
256      }
257      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
258      int n = x.GetLength(0);
259      int m = x.GetLength(1);
260      int k = c.Length;
261
262      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(compiledFunc);
263      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(compiledFunc);
264
265      try {
266        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
267        alglib.lsfitsetcond(state, 0.0, 0.0, maxIterations);
268        //alglib.lsfitsetgradientcheck(state, 0.001);
269        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, null, null);
270        alglib.lsfitresults(state, out retVal, out c, out rep);
271      } catch (ArithmeticException) {
272        return originalQuality;
273      } catch (alglib.alglibexception) {
274        return originalQuality;
275      }
276
277      //retVal == -7  => constant optimization failed due to wrong gradient
278      if (retVal != -7) UpdateConstants(tree, c.Skip(2).ToArray(), updateVariableWeights);
279      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling);
280
281      if (!updateConstantsInTree) UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
282      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
283        UpdateConstants(tree, originalConstants.Skip(2).ToArray(), updateVariableWeights);
284        return originalQuality;
285      }
286      return quality;
287    }
288
289    private static void UpdateConstants(ISymbolicExpressionTree tree, double[] constants, bool updateVariableWeights) {
290      int i = 0;
291      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
292        ConstantTreeNode constantTreeNode = node as ConstantTreeNode;
293        VariableTreeNode variableTreeNode = node as VariableTreeNode;
294        BinaryFactorVariableTreeNode binFactorVarTreeNode = node as BinaryFactorVariableTreeNode;
295        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
296        if (constantTreeNode != null)
297          constantTreeNode.Value = constants[i++];
298        else if (updateVariableWeights && variableTreeNode != null)
299          variableTreeNode.Weight = constants[i++];
300        else if (updateVariableWeights && binFactorVarTreeNode != null)
301          binFactorVarTreeNode.Weight = constants[i++];
302        else if (factorVarTreeNode != null) {
303          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
304            factorVarTreeNode.Weights[j] = constants[i++];
305        }
306      }
307    }
308
309    private static alglib.ndimensional_pfunc CreatePFunc(AutoDiff.IParametricCompiledTerm compiledFunc) {
310      return (double[] c, double[] x, ref double func, object o) => {
311        func = compiledFunc.Evaluate(c, x);
312      };
313    }
314
315    private static alglib.ndimensional_pgrad CreatePGrad(AutoDiff.IParametricCompiledTerm compiledFunc) {
316      return (double[] c, double[] x, ref double func, double[] grad, object o) => {
317        var tupel = compiledFunc.Differentiate(c, x);
318        func = tupel.Item2;
319        Array.Copy(tupel.Item1, grad, grad.Length);
320      };
321    }
322
323    private static bool TryTransformToAutoDiff(ISymbolicExpressionTreeNode node,
324      List<AutoDiff.Variable> variables, Dictionary<DataForVariable, AutoDiff.Variable> parameters,
325      bool updateVariableWeights, out AutoDiff.Term term) {
326      if (node.Symbol is Constant) {
327        var var = new AutoDiff.Variable();
328        variables.Add(var);
329        term = var;
330        return true;
331      }
332      if (node.Symbol is Variable || node.Symbol is BinaryFactorVariable) {
333        var varNode = node as VariableTreeNodeBase;
334        var factorVarNode = node as BinaryFactorVariableTreeNode;
335        // factor variable values are only 0 or 1 and set in x accordingly
336        var varValue = factorVarNode != null ? factorVarNode.VariableValue : string.Empty;
337        var par = FindOrCreateParameter(parameters, varNode.VariableName, varValue);
338
339        if (updateVariableWeights) {
340          var w = new AutoDiff.Variable();
341          variables.Add(w);
342          term = AutoDiff.TermBuilder.Product(w, par);
343        } else {
344          term = varNode.Weight * par;
345        }
346        return true;
347      }
348      if (node.Symbol is FactorVariable) {
349        var factorVarNode = node as FactorVariableTreeNode;
350        var products = new List<Term>();
351        foreach (var variableValue in factorVarNode.Symbol.GetVariableValues(factorVarNode.VariableName)) {
352          var par = FindOrCreateParameter(parameters, factorVarNode.VariableName, variableValue);
353
354          var wVar = new AutoDiff.Variable();
355          variables.Add(wVar);
356
357          products.Add(AutoDiff.TermBuilder.Product(wVar, par));
358        }
359        term = AutoDiff.TermBuilder.Sum(products);
360        return true;
361      }
362      if (node.Symbol is LaggedVariable) {
363        var varNode = node as LaggedVariableTreeNode;
364        var par = FindOrCreateParameter(parameters, varNode.VariableName, string.Empty, varNode.Lag);
365
366        if (updateVariableWeights) {
367          var w = new AutoDiff.Variable();
368          variables.Add(w);
369          term = AutoDiff.TermBuilder.Product(w, par);
370        } else {
371          term = varNode.Weight * par;
372        }
373        return true;
374      }
375      if (node.Symbol is Addition) {
376        List<AutoDiff.Term> terms = new List<Term>();
377        foreach (var subTree in node.Subtrees) {
378          AutoDiff.Term t;
379          if (!TryTransformToAutoDiff(subTree, variables, parameters, updateVariableWeights, out t)) {
380            term = null;
381            return false;
382          }
383          terms.Add(t);
384        }
385        term = AutoDiff.TermBuilder.Sum(terms);
386        return true;
387      }
388      if (node.Symbol is Subtraction) {
389        List<AutoDiff.Term> terms = new List<Term>();
390        for (int i = 0; i < node.SubtreeCount; i++) {
391          AutoDiff.Term t;
392          if (!TryTransformToAutoDiff(node.GetSubtree(i), variables, parameters, updateVariableWeights, out t)) {
393            term = null;
394            return false;
395          }
396          if (i > 0) t = -t;
397          terms.Add(t);
398        }
399        if (terms.Count == 1) term = -terms[0];
400        else term = AutoDiff.TermBuilder.Sum(terms);
401        return true;
402      }
403      if (node.Symbol is Multiplication) {
404        List<AutoDiff.Term> terms = new List<Term>();
405        foreach (var subTree in node.Subtrees) {
406          AutoDiff.Term t;
407          if (!TryTransformToAutoDiff(subTree, variables, parameters, updateVariableWeights, out t)) {
408            term = null;
409            return false;
410          }
411          terms.Add(t);
412        }
413        if (terms.Count == 1) term = terms[0];
414        else term = terms.Aggregate((a, b) => new AutoDiff.Product(a, b));
415        return true;
416
417      }
418      if (node.Symbol is Division) {
419        List<AutoDiff.Term> terms = new List<Term>();
420        foreach (var subTree in node.Subtrees) {
421          AutoDiff.Term t;
422          if (!TryTransformToAutoDiff(subTree, variables, parameters, updateVariableWeights, out t)) {
423            term = null;
424            return false;
425          }
426          terms.Add(t);
427        }
428        if (terms.Count == 1) term = 1.0 / terms[0];
429        else term = terms.Aggregate((a, b) => new AutoDiff.Product(a, 1.0 / b));
430        return true;
431      }
432      if (node.Symbol is Logarithm) {
433        AutoDiff.Term t;
434        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
435          term = null;
436          return false;
437        } else {
438          term = AutoDiff.TermBuilder.Log(t);
439          return true;
440        }
441      }
442      if (node.Symbol is Exponential) {
443        AutoDiff.Term t;
444        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
445          term = null;
446          return false;
447        } else {
448          term = AutoDiff.TermBuilder.Exp(t);
449          return true;
450        }
451      }
452      if (node.Symbol is Square) {
453        AutoDiff.Term t;
454        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
455          term = null;
456          return false;
457        } else {
458          term = AutoDiff.TermBuilder.Power(t, 2.0);
459          return true;
460        }
461      }
462      if (node.Symbol is SquareRoot) {
463        AutoDiff.Term t;
464        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
465          term = null;
466          return false;
467        } else {
468          term = AutoDiff.TermBuilder.Power(t, 0.5);
469          return true;
470        }
471      }
472      if (node.Symbol is Sine) {
473        AutoDiff.Term t;
474        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
475          term = null;
476          return false;
477        } else {
478          term = sin(t);
479          return true;
480        }
481      }
482      if (node.Symbol is Cosine) {
483        AutoDiff.Term t;
484        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
485          term = null;
486          return false;
487        } else {
488          term = cos(t);
489          return true;
490        }
491      }
492      if (node.Symbol is Tangent) {
493        AutoDiff.Term t;
494        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
495          term = null;
496          return false;
497        } else {
498          term = tan(t);
499          return true;
500        }
501      }
502      if (node.Symbol is Erf) {
503        AutoDiff.Term t;
504        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
505          term = null;
506          return false;
507        } else {
508          term = erf(t);
509          return true;
510        }
511      }
512      if (node.Symbol is Norm) {
513        AutoDiff.Term t;
514        if (!TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out t)) {
515          term = null;
516          return false;
517        } else {
518          term = norm(t);
519          return true;
520        }
521      }
522      if (node.Symbol is StartSymbol) {
523        var alpha = new AutoDiff.Variable();
524        var beta = new AutoDiff.Variable();
525        variables.Add(beta);
526        variables.Add(alpha);
527        AutoDiff.Term branchTerm;
528        if (TryTransformToAutoDiff(node.GetSubtree(0), variables, parameters, updateVariableWeights, out branchTerm)) {
529          term = branchTerm * alpha + beta;
530          return true;
531        } else {
532          term = null;
533          return false;
534        }
535      }
536      term = null;
537      return false;
538    }
539
540    // for each factor variable value we need a parameter which represents a binary indicator for that variable & value combination
541    // each binary indicator is only necessary once. So we only create a parameter if this combination is not yet available
542    private static Term FindOrCreateParameter(Dictionary<DataForVariable, AutoDiff.Variable> parameters,
543      string varName, string varValue = "", int lag = 0) {
544      var data = new DataForVariable(varName, varValue, lag);
545
546      AutoDiff.Variable par = null;
547      if (!parameters.TryGetValue(data, out par)) {
548        // not found -> create new parameter and entries in names and values lists
549        par = new AutoDiff.Variable();
550        parameters.Add(data, par);
551      }
552      return par;
553    }
554
555    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
556      var containsUnknownSymbol = (
557        from n in tree.Root.GetSubtree(0).IterateNodesPrefix()
558        where
559         !(n.Symbol is Variable) &&
560         !(n.Symbol is BinaryFactorVariable) &&
561         !(n.Symbol is FactorVariable) &&
562         !(n.Symbol is LaggedVariable) &&
563         !(n.Symbol is Constant) &&
564         !(n.Symbol is Addition) &&
565         !(n.Symbol is Subtraction) &&
566         !(n.Symbol is Multiplication) &&
567         !(n.Symbol is Division) &&
568         !(n.Symbol is Logarithm) &&
569         !(n.Symbol is Exponential) &&
570         !(n.Symbol is SquareRoot) &&
571         !(n.Symbol is Square) &&
572         !(n.Symbol is Sine) &&
573         !(n.Symbol is Cosine) &&
574         !(n.Symbol is Tangent) &&
575         !(n.Symbol is Erf) &&
576         !(n.Symbol is Norm) &&
577         !(n.Symbol is StartSymbol)
578        select n).
579      Any();
580      return !containsUnknownSymbol;
581    }
582
583
584    #region helper class
585    private class DataForVariable {
586      public readonly string variableName;
587      public readonly string variableValue; // for factor vars
588      public readonly int lag;
589
590      public DataForVariable(string varName, string varValue, int lag) {
591        this.variableName = varName;
592        this.variableValue = varValue;
593        this.lag = lag;
594      }
595
596      public override bool Equals(object obj) {
597        var other = obj as DataForVariable;
598        if (other == null) return false;
599        return other.variableName.Equals(this.variableName) &&
600               other.variableValue.Equals(this.variableValue) &&
601               other.lag == this.lag;
602      }
603
604      public override int GetHashCode() {
605        return variableName.GetHashCode() ^ variableValue.GetHashCode() ^ lag;
606      }
607    }
608    #endregion
609  }
610}
Note: See TracBrowser for help on using the repository browser.