Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2994-AutoDiffForIntervals/HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Extensions/ConstrainedConstantOptimizationEvaluator.cs @ 17176

Last change on this file since 17176 was 17176, checked in by gkronber, 5 years ago

#2994 linear scaling for const opt with constraints

File size: 31.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HEAL.Attic;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  [Item("Constant Optimization Evaluator (with constraints)", "")]
35  [StorableType("A8958E06-C54A-4193-862E-8315C86EB5C1")]
36  public class ConstrainedConstantOptimizationEvaluator : 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    private const string FunctionEvaluationsResultParameterName = "Constants Optimization Function Evaluations";
45    private const string GradientEvaluationsResultParameterName = "Constants Optimization Gradient Evaluations";
46    private const string CountEvaluationsParameterName = "Count Function and Gradient Evaluations";
47
48    public IFixedValueParameter<IntValue> ConstantOptimizationIterationsParameter {
49      get { return (IFixedValueParameter<IntValue>)Parameters[ConstantOptimizationIterationsParameterName]; }
50    }
51    public IFixedValueParameter<DoubleValue> ConstantOptimizationImprovementParameter {
52      get { return (IFixedValueParameter<DoubleValue>)Parameters[ConstantOptimizationImprovementParameterName]; }
53    }
54    public IFixedValueParameter<PercentValue> ConstantOptimizationProbabilityParameter {
55      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationProbabilityParameterName]; }
56    }
57    public IFixedValueParameter<PercentValue> ConstantOptimizationRowsPercentageParameter {
58      get { return (IFixedValueParameter<PercentValue>)Parameters[ConstantOptimizationRowsPercentageParameterName]; }
59    }
60    public IFixedValueParameter<BoolValue> UpdateConstantsInTreeParameter {
61      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateConstantsInTreeParameterName]; }
62    }
63    public IFixedValueParameter<BoolValue> UpdateVariableWeightsParameter {
64      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateVariableWeightsParameterName]; }
65    }
66
67    public IResultParameter<IntValue> FunctionEvaluationsResultParameter {
68      get { return (IResultParameter<IntValue>)Parameters[FunctionEvaluationsResultParameterName]; }
69    }
70    public IResultParameter<IntValue> GradientEvaluationsResultParameter {
71      get { return (IResultParameter<IntValue>)Parameters[GradientEvaluationsResultParameterName]; }
72    }
73    public IFixedValueParameter<BoolValue> CountEvaluationsParameter {
74      get { return (IFixedValueParameter<BoolValue>)Parameters[CountEvaluationsParameterName]; }
75    }
76    public IConstrainedValueParameter<StringValue> SolverParameter {
77      get { return (IConstrainedValueParameter<StringValue>)Parameters["Solver"]; }
78    }
79
80
81    public IntValue ConstantOptimizationIterations {
82      get { return ConstantOptimizationIterationsParameter.Value; }
83    }
84    public DoubleValue ConstantOptimizationImprovement {
85      get { return ConstantOptimizationImprovementParameter.Value; }
86    }
87    public PercentValue ConstantOptimizationProbability {
88      get { return ConstantOptimizationProbabilityParameter.Value; }
89    }
90    public PercentValue ConstantOptimizationRowsPercentage {
91      get { return ConstantOptimizationRowsPercentageParameter.Value; }
92    }
93    public bool UpdateConstantsInTree {
94      get { return UpdateConstantsInTreeParameter.Value.Value; }
95      set { UpdateConstantsInTreeParameter.Value.Value = value; }
96    }
97
98    public bool UpdateVariableWeights {
99      get { return UpdateVariableWeightsParameter.Value.Value; }
100      set { UpdateVariableWeightsParameter.Value.Value = value; }
101    }
102
103    public bool CountEvaluations {
104      get { return CountEvaluationsParameter.Value.Value; }
105      set { CountEvaluationsParameter.Value.Value = value; }
106    }
107
108    public string Solver {
109      get { return SolverParameter.Value.Value; }
110    }
111    public override bool Maximization {
112      get { return false; }
113    }
114
115    [StorableConstructor]
116    protected ConstrainedConstantOptimizationEvaluator(StorableConstructorFlag _) : base(_) { }
117    protected ConstrainedConstantOptimizationEvaluator(ConstrainedConstantOptimizationEvaluator original, Cloner cloner)
118      : base(original, cloner) {
119    }
120    public ConstrainedConstantOptimizationEvaluator()
121      : base() {
122      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)));
123      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)) { Hidden = true });
124      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationProbabilityParameterName, "Determines the probability that the constants are optimized", new PercentValue(1)));
125      Parameters.Add(new FixedValueParameter<PercentValue>(ConstantOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for constant optimization", new PercentValue(1)));
126      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 });
127      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
128
129      Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
130      var validSolvers = new ItemSet<StringValue>(new[] { "non-smooth (minns)", "sequential linear programming (minnlc)" }.Select(s => new StringValue(s).AsReadOnly()));
131      Parameters.Add(new ConstrainedValueParameter<StringValue>("Solver", "The solver algorithm", validSolvers, validSolvers.First()));
132      Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
133      Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the constants optimization evaluator", "Results", new IntValue()));
134    }
135
136    public override IDeepCloneable Clone(Cloner cloner) {
137      return new ConstrainedConstantOptimizationEvaluator(this, cloner);
138    }
139
140    [StorableHook(HookType.AfterDeserialization)]
141    private void AfterDeserialization() { }
142
143    private static readonly object locker = new object();
144
145    public override IOperation InstrumentedApply() {
146      var solution = SymbolicExpressionTreeParameter.ActualValue;
147      double quality;
148      if (RandomParameter.ActualValue.NextDouble() < ConstantOptimizationProbability.Value) {
149        IEnumerable<int> constantOptimizationRows = GenerateRowsToEvaluate(ConstantOptimizationRowsPercentage.Value);
150        var counter = new EvaluationsCounter();
151        quality = OptimizeConstants(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, ProblemDataParameter.ActualValue,
152           constantOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, Solver, ConstantOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateConstantsInTree: UpdateConstantsInTree, counter: counter);
153
154        if (ConstantOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
155          throw new NotSupportedException();
156        }
157
158        if (CountEvaluations) {
159          lock (locker) {
160            FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
161            GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
162          }
163        }
164
165      } else {
166        throw new NotSupportedException();
167      }
168      QualityParameter.ActualValue = new DoubleValue(quality);
169
170      return base.InstrumentedApply();
171    }
172
173    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
174      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
175      EstimationLimitsParameter.ExecutionContext = context;
176      ApplyLinearScalingParameter.ExecutionContext = context;
177      FunctionEvaluationsResultParameter.ExecutionContext = context;
178      GradientEvaluationsResultParameter.ExecutionContext = context;
179
180      // MSE evaluator is used on purpose instead of the const-opt evaluator,
181      // because Evaluate() is used to get the quality of evolved models on
182      // different partitions of the dataset (e.g., best validation model)
183      double mse = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, double.MinValue, double.MaxValue, problemData, rows, applyLinearScaling: false);
184
185      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
186      EstimationLimitsParameter.ExecutionContext = null;
187      ApplyLinearScalingParameter.ExecutionContext = null;
188      FunctionEvaluationsResultParameter.ExecutionContext = null;
189      GradientEvaluationsResultParameter.ExecutionContext = null;
190
191      return mse;
192    }
193
194    public class EvaluationsCounter {
195      public int FunctionEvaluations = 0;
196      public int GradientEvaluations = 0;
197    }
198
199    private static void GetParameterNodes(ISymbolicExpressionTree tree, out List<ISymbolicExpressionTreeNode> thetaNodes, out List<double> thetaValues) {
200      thetaNodes = new List<ISymbolicExpressionTreeNode>();
201      thetaValues = new List<double>();
202
203      var nodes = tree.IterateNodesPrefix().ToArray();
204      for (int i = 0; i < nodes.Length; ++i) {
205        var node = nodes[i];
206        if (node is VariableTreeNode variableTreeNode) {
207          thetaValues.Add(variableTreeNode.Weight);
208          thetaNodes.Add(node);
209        } else if (node is ConstantTreeNode constantTreeNode) {
210          thetaNodes.Add(node);
211          thetaValues.Add(constantTreeNode.Value);
212        }
213      }
214    }
215
216    public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
217      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
218      string solver,
219      int maxIterations, bool updateVariableWeights = true,
220      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
221      bool updateConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
222
223      if (!updateVariableWeights) throw new NotSupportedException("not updating variable weights is not supported");
224      if (!updateConstantsInTree) throw new NotSupportedException("not updating tree parameters is not supported");
225      if (!applyLinearScaling) throw new NotSupportedException("application without linear scaling is not supported");
226
227      // we always update constants, so we don't need to calculate initial quality
228      // double originalQuality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
229
230      if (counter == null) counter = new EvaluationsCounter();
231      var rowEvaluationsCounter = new EvaluationsCounter();
232
233      var intervalConstraints = problemData.IntervalConstraints;
234      var dataIntervals = problemData.VariableRanges.GetIntervals();
235
236      // buffers
237      var target = problemData.TargetVariableTrainingValues.ToArray();
238      var targetStDev = target.StandardDeviationPop();
239      var targetVariance = targetStDev * targetStDev;
240      var targetMean = target.Average();
241      var pred = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices).ToArray();
242      var predStDev = pred.StandardDeviationPop();
243      var predMean = pred.Average();
244
245      var scalingFactor = targetStDev / predStDev;
246      var offset = targetMean - predMean * scalingFactor;
247
248      ISymbolicExpressionTree scaledTree = null;
249      if (applyLinearScaling) scaledTree = CopyAndScaleTree(tree, scalingFactor, offset);
250
251      // convert constants to variables named theta...
252      var treeForDerivation = ReplaceConstWithVar(scaledTree, out List<string> thetaNames, out List<double> thetaValues); // copies the tree
253
254      // create trees for relevant derivatives
255      Dictionary<string, ISymbolicExpressionTree> derivatives = new Dictionary<string, ISymbolicExpressionTree>();
256      var allThetaNodes = thetaNames.Select(_ => new List<ConstantTreeNode>()).ToArray();
257      var constraintTrees = new List<ISymbolicExpressionTree>();
258      foreach (var constraint in intervalConstraints.Constraints) {
259        if (constraint.IsDerivation) {
260          if (!problemData.AllowedInputVariables.Contains(constraint.Variable))
261            throw new ArgumentException($"Invalid constraint: the variable {constraint.Variable} does not exist in the dataset.");
262          var df = DerivativeCalculator.Derive(treeForDerivation, constraint.Variable);
263
264          // alglib requires constraint expressions of the form c(x) <= 0
265          // -> we make two expressions, one for the lower bound and one for the upper bound
266
267          if (constraint.Interval.UpperBound < double.PositiveInfinity) {
268            var df_smaller_upper = Subtract((ISymbolicExpressionTree)df.Clone(), CreateConstant(constraint.Interval.UpperBound));
269            // convert variables named theta back to constants
270            var df_prepared = ReplaceVarWithConst(df_smaller_upper, thetaNames, thetaValues, allThetaNodes);
271            constraintTrees.Add(df_prepared);
272          }
273          if (constraint.Interval.LowerBound > double.NegativeInfinity) {
274            var df_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)df.Clone());
275            // convert variables named theta back to constants
276            var df_prepared = ReplaceVarWithConst(df_larger_lower, thetaNames, thetaValues, allThetaNodes);
277            constraintTrees.Add(df_prepared);
278          }
279        } else {
280          if (constraint.Interval.UpperBound < double.PositiveInfinity) {
281            var f_smaller_upper = Subtract((ISymbolicExpressionTree)treeForDerivation.Clone(), CreateConstant(constraint.Interval.UpperBound));
282            // convert variables named theta back to constants
283            var df_prepared = ReplaceVarWithConst(f_smaller_upper, thetaNames, thetaValues, allThetaNodes);
284            constraintTrees.Add(df_prepared);
285          }
286          if (constraint.Interval.LowerBound > double.NegativeInfinity) {
287            var f_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)treeForDerivation.Clone());
288            // convert variables named theta back to constants
289            var df_prepared = ReplaceVarWithConst(f_larger_lower, thetaNames, thetaValues, allThetaNodes);
290            constraintTrees.Add(df_prepared);
291          }
292        }
293      }
294
295      var preparedTree = ReplaceVarWithConst(treeForDerivation, thetaNames, thetaValues, allThetaNodes);
296
297
298      // local function
299      void UpdateThetaValues(double[] theta) {
300        for (int i = 0; i < theta.Length; ++i) {
301          foreach (var constNode in allThetaNodes[i]) constNode.Value = theta[i];
302        }
303      }
304
305      var fi_eval = new double[target.Length];
306      var jac_eval = new double[target.Length, thetaValues.Count];
307
308      // define the callback used by the alglib optimizer
309      // the x argument for this callback represents our theta
310      // local function
311      void calculate_jacobian(double[] x, double[] fi, double[,] jac, object obj) {
312        UpdateThetaValues(x);
313
314        var autoDiffEval = new VectorAutoDiffEvaluator();
315        autoDiffEval.Evaluate(preparedTree, problemData.Dataset, problemData.TrainingIndices.ToArray(),
316          GetParameterNodes(preparedTree, allThetaNodes), fi_eval, jac_eval);
317
318        // calc sum of squared errors and gradient
319        var sse = 0.0;
320        var g = new double[x.Length];
321        for (int i = 0; i < target.Length; i++) {
322          var res = target[i] - fi_eval[i];
323          sse += 0.5 * res * res;
324          for (int j = 0; j < g.Length; j++) {
325            g[j] -= res * jac_eval[i, j];
326          }
327        }
328
329        fi[0] = sse / target.Length;
330        for (int j = 0; j < x.Length; j++) { jac[0, j] = g[j] / target.Length; }
331
332        var intervalEvaluator = new IntervalEvaluator();
333        for (int i = 0; i < constraintTrees.Count; i++) {
334          var interval = intervalEvaluator.Evaluate(constraintTrees[i], dataIntervals, GetParameterNodes(constraintTrees[i], allThetaNodes),
335            out double[] lowerGradient, out double[] upperGradient);
336
337          // we transformed this to a constraint c(x) <= 0, so only the upper bound is relevant for us
338          fi[i + 1] = interval.UpperBound;
339          for (int j = 0; j < x.Length; j++) {
340            jac[i + 1, j] = upperGradient[j];
341          }
342        }
343      }
344
345      if (solver.Contains("minns")) {
346        alglib.minnsstate state;
347        alglib.minnsreport rep;
348        try {
349          alglib.minnscreate(thetaValues.Count, thetaValues.ToArray(), out state);
350          alglib.minnssetbc(state, thetaValues.Select(_ => -10000.0).ToArray(), thetaValues.Select(_ => +10000.0).ToArray());
351          alglib.minnssetcond(state, 0, maxIterations);
352          var s = Enumerable.Repeat(1d, thetaValues.Count).ToArray();  // scale is set to unit scale
353          alglib.minnssetscale(state, s);
354
355          // set non-linear constraints: 0 equality constraints, constraintTrees inequality constraints
356          alglib.minnssetnlc(state, 0, constraintTrees.Count);
357
358          alglib.minnsoptimize(state, calculate_jacobian, null, null);
359          alglib.minnsresults(state, out double[] xOpt, out rep);
360
361
362          // counter.FunctionEvaluations += rep.nfev; TODO
363          counter.GradientEvaluations += rep.nfev;
364
365          if (rep.terminationtype > 0) {
366            // update parameters in tree
367            var pIdx = 0;
368            // here we lose the two last parameters (for linear scaling)
369            foreach (var node in tree.IterateNodesPostfix()) {
370              if (node is ConstantTreeNode constTreeNode) {
371                constTreeNode.Value = xOpt[pIdx++];
372              } else if (node is VariableTreeNode varTreeNode) {
373                varTreeNode.Weight = xOpt[pIdx++];
374              }
375            }
376            // note: we keep the optimized constants even when the tree is worse.
377            // assert that we lose the last two parameters
378            if (pIdx != xOpt.Length - 2) throw new InvalidProgramException();
379          }
380          if (Math.Abs(rep.nlcerr) > 0.01) return targetVariance; // constraints are violated
381        } catch (ArithmeticException) {
382          return targetVariance;
383        } catch (alglib.alglibexception) {
384          // eval MSE of original tree
385          return targetVariance;
386        }
387      } else if (solver.Contains("minnlc")) {
388        alglib.minnlcstate state;
389        alglib.minnlcreport rep;
390        alglib.optguardreport optGuardRep;
391        try {
392          alglib.minnlccreate(thetaValues.Count, thetaValues.ToArray(), out state);
393          alglib.minnlcsetalgoslp(state);        // SLP is more robust but slower
394          alglib.minnlcsetbc(state, thetaValues.Select(_ => -10000.0).ToArray(), thetaValues.Select(_ => +10000.0).ToArray());
395          alglib.minnlcsetcond(state, 0, maxIterations);
396          var s = Enumerable.Repeat(1d, thetaValues.Count).ToArray();  // scale is set to unit scale
397          alglib.minnlcsetscale(state, s);
398
399          // set non-linear constraints: 0 equality constraints, constraintTrees inequality constraints
400          alglib.minnlcsetnlc(state, 0, constraintTrees.Count);
401          alglib.minnlcoptguardsmoothness(state, 1);
402
403          alglib.minnlcoptimize(state, calculate_jacobian, null, null);
404          alglib.minnlcresults(state, out double[] xOpt, out rep);
405          alglib.minnlcoptguardresults(state, out optGuardRep);
406          if (optGuardRep.nonc0suspected) throw new InvalidProgramException("optGuardRep.nonc0suspected");
407          if (optGuardRep.nonc1suspected) {
408            alglib.minnlcoptguardnonc1test1results(state, out alglib.optguardnonc1test1report strrep, out alglib.optguardnonc1test1report lngrep);
409            throw new InvalidProgramException("optGuardRep.nonc1suspected");
410          }
411
412          // counter.FunctionEvaluations += rep.nfev; TODO
413          counter.GradientEvaluations += rep.nfev;
414
415          if (rep.terminationtype != -8) {
416            // update parameters in tree
417            var pIdx = 0;
418            foreach (var node in tree.IterateNodesPostfix()) {
419              if (node is ConstantTreeNode constTreeNode) {
420                constTreeNode.Value = xOpt[pIdx++];
421              } else if (node is VariableTreeNode varTreeNode) {
422                varTreeNode.Weight = xOpt[pIdx++];
423              }
424            }
425            // note: we keep the optimized constants even when the tree is worse.
426            // assert that we lose the last two parameters
427            if (pIdx != xOpt.Length - 2) throw new InvalidProgramException();
428
429          }
430          if (Math.Abs(rep.nlcerr) > 0.01) return targetVariance; // constraints are violated
431
432        } catch (ArithmeticException) {
433          return targetVariance;
434        } catch (alglib.alglibexception) {
435          return targetVariance;
436        }
437      } else {
438        throw new ArgumentException($"Unknown solver {solver}");
439      }
440   
441
442      // evaluate tree with updated constants
443      var residualVariance = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, scaledTree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
444      return Math.Min(residualVariance, targetVariance);
445    }
446
447    private static ISymbolicExpressionTree CopyAndScaleTree(ISymbolicExpressionTree tree, double scalingFactor, double offset) {
448      var m = (ISymbolicExpressionTree)tree.Clone();
449
450      var add = MakeNode<Addition>(MakeNode<Multiplication>(m.Root.GetSubtree(0).GetSubtree(0), CreateConstant(scalingFactor)), CreateConstant(offset));
451      m.Root.GetSubtree(0).RemoveSubtree(0);
452      m.Root.GetSubtree(0).AddSubtree(add);
453      return m;
454    }
455
456    #region helper
457    private static ISymbolicExpressionTreeNode[] GetParameterNodes(ISymbolicExpressionTree tree, List<ConstantTreeNode>[] allNodes) {
458      // TODO better solution necessary
459      var treeConstNodes = tree.IterateNodesPostfix().OfType<ConstantTreeNode>().ToArray();
460      var paramNodes = new ISymbolicExpressionTreeNode[allNodes.Length];
461      for (int i = 0; i < paramNodes.Length; i++) {
462        paramNodes[i] = allNodes[i].SingleOrDefault(n => treeConstNodes.Contains(n));
463      }
464      return paramNodes;
465    }
466
467    private static ISymbolicExpressionTree ReplaceVarWithConst(ISymbolicExpressionTree tree, List<string> thetaNames, List<double> thetaValues, List<ConstantTreeNode>[] thetaNodes) {
468      var copy = (ISymbolicExpressionTree)tree.Clone();
469      var nodes = copy.IterateNodesPostfix().ToList();
470      for (int i = 0; i < nodes.Count; i++) {
471        var n = nodes[i] as VariableTreeNode;
472        if (n != null) {
473          var thetaIdx = thetaNames.IndexOf(n.VariableName);
474          if (thetaIdx >= 0) {
475            var parent = n.Parent;
476            if (thetaNodes[thetaIdx].Any()) {
477              // HACK: REUSE CONSTANT TREE NODE IN SEVERAL TREES
478              // we use this trick to allow autodiff over thetas when thetas occurr multiple times in the tree (e.g. in derived trees)
479              var constNode = thetaNodes[thetaIdx].First();
480              var childIdx = parent.IndexOfSubtree(n);
481              parent.RemoveSubtree(childIdx);
482              parent.InsertSubtree(childIdx, constNode);
483            } else {
484              var constNode = (ConstantTreeNode)CreateConstant(thetaValues[thetaIdx]);
485              var childIdx = parent.IndexOfSubtree(n);
486              parent.RemoveSubtree(childIdx);
487              parent.InsertSubtree(childIdx, constNode);
488              thetaNodes[thetaIdx].Add(constNode);
489            }
490          }
491        }
492      }
493      return copy;
494    }
495
496    private static ISymbolicExpressionTree ReplaceConstWithVar(ISymbolicExpressionTree tree, out List<string> thetaNames, out List<double> thetaValues) {
497      thetaNames = new List<string>();
498      thetaValues = new List<double>();
499      var copy = (ISymbolicExpressionTree)tree.Clone();
500      var nodes = copy.IterateNodesPostfix().ToList();
501
502      int n = 1;
503      for (int i = 0; i < nodes.Count; ++i) {
504        var node = nodes[i];
505        if (node is ConstantTreeNode constantTreeNode) {
506          var thetaVar = (VariableTreeNode)new Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
507          thetaVar.Weight = 1;
508          thetaVar.VariableName = $"θ{n++}";
509
510          thetaNames.Add(thetaVar.VariableName);
511          thetaValues.Add(constantTreeNode.Value);
512
513          var parent = constantTreeNode.Parent;
514          if (parent != null) {
515            var index = constantTreeNode.Parent.IndexOfSubtree(constantTreeNode);
516            parent.RemoveSubtree(index);
517            parent.InsertSubtree(index, thetaVar);
518          }
519        }
520        if (node is VariableTreeNode varTreeNode) {
521          var thetaVar = (VariableTreeNode)new Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
522          thetaVar.Weight = 1;
523          thetaVar.VariableName = $"θ{n++}";
524
525          thetaNames.Add(thetaVar.VariableName);
526          thetaValues.Add(varTreeNode.Weight);
527
528          var parent = varTreeNode.Parent;
529          if (parent != null) {
530            var index = varTreeNode.Parent.IndexOfSubtree(varTreeNode);
531            parent.RemoveSubtree(index);
532            var prodNode = MakeNode<Multiplication>();
533            varTreeNode.Weight = 1.0;
534            prodNode.AddSubtree(varTreeNode);
535            prodNode.AddSubtree(thetaVar);
536            parent.InsertSubtree(index, prodNode);
537          }
538        }
539      }
540      return copy;
541    }
542
543    private static ISymbolicExpressionTreeNode CreateConstant(double value) {
544      var constantNode = (ConstantTreeNode)new Constant().CreateTreeNode();
545      constantNode.Value = value;
546      return constantNode;
547    }
548
549    private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTree t, ISymbolicExpressionTreeNode b) {
550      var sub = MakeNode<Subtraction>(t.Root.GetSubtree(0).GetSubtree(0), b);
551      t.Root.GetSubtree(0).RemoveSubtree(0);
552      t.Root.GetSubtree(0).InsertSubtree(0, sub);
553      return t;
554    }
555    private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTreeNode b, ISymbolicExpressionTree t) {
556      var sub = MakeNode<Subtraction>(b, t.Root.GetSubtree(0).GetSubtree(0));
557      t.Root.GetSubtree(0).RemoveSubtree(0);
558      t.Root.GetSubtree(0).InsertSubtree(0, sub);
559      return t;
560    }
561
562    private static ISymbolicExpressionTreeNode MakeNode<T>(params ISymbolicExpressionTreeNode[] fs) where T : ISymbol, new() {
563      var node = new T().CreateTreeNode();
564      foreach (var f in fs) node.AddSubtree(f);
565      return node;
566    }
567    #endregion
568
569    private static void UpdateConstants(ISymbolicExpressionTreeNode[] nodes, double[] constants) {
570      if (nodes.Length != constants.Length) throw new InvalidOperationException();
571      for (int i = 0; i < nodes.Length; i++) {
572        if (nodes[i] is VariableTreeNode varNode) varNode.Weight = constants[i];
573        else if (nodes[i] is ConstantTreeNode constNode) constNode.Value = constants[i];
574      }
575    }
576
577    private static alglib.ndimensional_fvec CreateFunc(ISymbolicExpressionTree tree, VectorEvaluator eval, ISymbolicExpressionTreeNode[] parameterNodes, IDataset ds, string targetVar, int[] rows) {
578      var y = ds.GetDoubleValues(targetVar, rows).ToArray();
579      return (double[] c, double[] fi, object o) => {
580        UpdateConstants(parameterNodes, c);
581        var pred = eval.Evaluate(tree, ds, rows);
582        for (int i = 0; i < fi.Length; i++)
583          fi[i] = pred[i] - y[i];
584
585        var counter = (EvaluationsCounter)o;
586        counter.FunctionEvaluations++;
587      };
588    }
589
590    private static alglib.ndimensional_jac CreateJac(ISymbolicExpressionTree tree, VectorAutoDiffEvaluator eval, ISymbolicExpressionTreeNode[] parameterNodes, IDataset ds, string targetVar, int[] rows) {
591      var y = ds.GetDoubleValues(targetVar, rows).ToArray();
592      return (double[] c, double[] fi, double[,] jac, object o) => {
593        UpdateConstants(parameterNodes, c);
594        eval.Evaluate(tree, ds, rows, parameterNodes, fi, jac);
595
596        for (int i = 0; i < fi.Length; i++)
597          fi[i] -= y[i];
598
599        var counter = (EvaluationsCounter)o;
600        counter.GradientEvaluations++;
601      };
602    }
603    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
604      return TreeToAutoDiffTermConverter.IsCompatible(tree);
605    }
606  }
607}
Note: See TracBrowser for help on using the repository browser.