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

Last change on this file since 17006 was 17006, checked in by gkronber, 18 months ago

#2994: added option to use NLC (SLP) or Non-smooth solver

File size: 30.6 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          var evaluationRows = GenerateRowsToEvaluate();
156          quality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, double.MinValue, double.MaxValue, ProblemDataParameter.ActualValue, evaluationRows, applyLinearScaling: false);
157        }
158
159        if (CountEvaluations) {
160          lock (locker) {
161            FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
162            GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
163          }
164        }
165
166      } else {
167        var evaluationRows = GenerateRowsToEvaluate();
168        quality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, solution, double.MinValue, double.MaxValue, ProblemDataParameter.ActualValue, evaluationRows, applyLinearScaling: false);
169      }
170      QualityParameter.ActualValue = new DoubleValue(quality);
171
172      return base.InstrumentedApply();
173    }
174
175    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
176      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
177      EstimationLimitsParameter.ExecutionContext = context;
178      ApplyLinearScalingParameter.ExecutionContext = context;
179      FunctionEvaluationsResultParameter.ExecutionContext = context;
180      GradientEvaluationsResultParameter.ExecutionContext = context;
181
182      // MSE evaluator is used on purpose instead of the const-opt evaluator,
183      // because Evaluate() is used to get the quality of evolved models on
184      // different partitions of the dataset (e.g., best validation model)
185      double mse = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, double.MinValue, double.MaxValue, problemData, rows, applyLinearScaling: false);
186
187      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
188      EstimationLimitsParameter.ExecutionContext = null;
189      ApplyLinearScalingParameter.ExecutionContext = null;
190      FunctionEvaluationsResultParameter.ExecutionContext = null;
191      GradientEvaluationsResultParameter.ExecutionContext = null;
192
193      return mse;
194    }
195
196    public class EvaluationsCounter {
197      public int FunctionEvaluations = 0;
198      public int GradientEvaluations = 0;
199    }
200
201    private static void GetParameterNodes(ISymbolicExpressionTree tree, out List<ISymbolicExpressionTreeNode> thetaNodes, out List<double> thetaValues) {
202      thetaNodes = new List<ISymbolicExpressionTreeNode>();
203      thetaValues = new List<double>();
204
205      var nodes = tree.IterateNodesPrefix().ToArray();
206      for (int i = 0; i < nodes.Length; ++i) {
207        var node = nodes[i];
208        if (node is VariableTreeNode variableTreeNode) {
209          thetaValues.Add(variableTreeNode.Weight);
210          thetaNodes.Add(node);
211        } else if (node is ConstantTreeNode constantTreeNode) {
212          thetaNodes.Add(node);
213          thetaValues.Add(constantTreeNode.Value);
214        }
215      }
216    }
217
218    public static double OptimizeConstants(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
219      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
220      string solver,
221      int maxIterations, bool updateVariableWeights = true,
222      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
223      bool updateConstantsInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
224
225      if (!updateVariableWeights) throw new NotSupportedException("not updating variable weights is not supported");
226      if (!updateConstantsInTree) throw new NotSupportedException("not updating tree parameters is not supported");
227      if (applyLinearScaling) throw new NotSupportedException("linear scaling is not supported");
228
229      // we always update constants, so we don't need to calculate initial quality
230      // double originalQuality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
231
232      if (counter == null) counter = new EvaluationsCounter();
233      var rowEvaluationsCounter = new EvaluationsCounter();
234
235      var intervalConstraints = problemData.IntervalConstraints;
236      var dataIntervals = problemData.VariableRanges.GetIntervals();
237
238      // convert constants to variables named theta...
239      var treeForDerivation = ReplaceConstWithVar(tree, out List<string> thetaNames, out List<double> thetaValues); // copies the tree
240
241      // create trees for relevant derivatives
242      Dictionary<string, ISymbolicExpressionTree> derivatives = new Dictionary<string, ISymbolicExpressionTree>();
243      var allThetaNodes = thetaNames.Select(_ => new List<ConstantTreeNode>()).ToArray();
244      var constraintTrees = new List<ISymbolicExpressionTree>();
245      foreach (var constraint in intervalConstraints.Constraints) {
246        if (constraint.IsDerivation) {
247          if (!problemData.AllowedInputVariables.Contains(constraint.Variable))
248            throw new ArgumentException($"Invalid constraint: the variable {constraint.Variable} does not exist in the dataset.");
249          var df = DerivativeCalculator.Derive(treeForDerivation, constraint.Variable);
250
251          // alglib requires constraint expressions of the form c(x) <= 0
252          // -> we make two expressions, one for the lower bound and one for the upper bound
253
254          if (constraint.Interval.UpperBound < double.PositiveInfinity) {
255            var df_smaller_upper = Subtract((ISymbolicExpressionTree)df.Clone(), CreateConstant(constraint.Interval.UpperBound));
256            // convert variables named theta back to constants
257            var df_prepared = ReplaceVarWithConst(df_smaller_upper, thetaNames, thetaValues, allThetaNodes);
258            constraintTrees.Add(df_prepared);
259          }
260          if (constraint.Interval.LowerBound > double.NegativeInfinity) {
261            var df_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)df.Clone());
262            // convert variables named theta back to constants
263            var df_prepared = ReplaceVarWithConst(df_larger_lower, thetaNames, thetaValues, allThetaNodes);
264            constraintTrees.Add(df_prepared);
265          }
266        } else {
267          if (constraint.Interval.UpperBound < double.PositiveInfinity) {
268            var f_smaller_upper = Subtract((ISymbolicExpressionTree)treeForDerivation.Clone(), CreateConstant(constraint.Interval.UpperBound));
269            // convert variables named theta back to constants
270            var df_prepared = ReplaceVarWithConst(f_smaller_upper, thetaNames, thetaValues, allThetaNodes);
271            constraintTrees.Add(df_prepared);
272          }
273          if (constraint.Interval.LowerBound > double.NegativeInfinity) {
274            var f_larger_lower = Subtract(CreateConstant(constraint.Interval.LowerBound), (ISymbolicExpressionTree)treeForDerivation.Clone());
275            // convert variables named theta back to constants
276            var df_prepared = ReplaceVarWithConst(f_larger_lower, thetaNames, thetaValues, allThetaNodes);
277            constraintTrees.Add(df_prepared);
278          }
279        }
280      }
281
282      var preparedTree = ReplaceVarWithConst(treeForDerivation, thetaNames, thetaValues, allThetaNodes);
283
284
285      // local function
286      void UpdateThetaValues(double[] theta) {
287        for (int i = 0; i < theta.Length; ++i) {
288          foreach (var constNode in allThetaNodes[i]) constNode.Value = theta[i];
289        }
290      }
291
292      // buffers for calculate_jacobian
293      var target = problemData.TargetVariableTrainingValues.ToArray();
294      var fi_eval = new double[target.Length];
295      var jac_eval = new double[target.Length, thetaValues.Count];
296
297      // define the callback used by the alglib optimizer
298      // the x argument for this callback represents our theta
299      // local function
300      void calculate_jacobian(double[] x, double[] fi, double[,] jac, object obj) {
301        UpdateThetaValues(x);
302
303        var autoDiffEval = new VectorAutoDiffEvaluator();
304        autoDiffEval.Evaluate(preparedTree, problemData.Dataset, problemData.TrainingIndices.ToArray(),
305          GetParameterNodes(preparedTree, allThetaNodes), fi_eval, jac_eval);
306
307        // calc sum of squared errors and gradient
308        var sse = 0.0;
309        var g = new double[x.Length];
310        for (int i = 0; i < target.Length; i++) {
311          var res = target[i] - fi_eval[i];
312          sse += 0.5 * res * res;
313          for (int j = 0; j < g.Length; j++) {
314            g[j] -= res * jac_eval[i, j];
315          }
316        }
317
318        fi[0] = sse / target.Length;
319        for (int j = 0; j < x.Length; j++) { jac[0, j] = g[j] / target.Length; }
320
321        var intervalEvaluator = new IntervalEvaluator();
322        for (int i = 0; i < constraintTrees.Count; i++) {
323          var interval = intervalEvaluator.Evaluate(constraintTrees[i], dataIntervals, GetParameterNodes(constraintTrees[i], allThetaNodes),
324            out double[] lowerGradient, out double[] upperGradient);
325
326          // we transformed this to a constraint c(x) <= 0, so only the upper bound is relevant for us
327          fi[i + 1] = interval.UpperBound;
328          for (int j = 0; j < x.Length; j++) {
329            jac[i + 1, j] = upperGradient[j];
330          }
331        }
332      }
333
334      if (solver.Contains("minns")) {
335        alglib.minnsstate state;
336        alglib.minnsreport rep;
337        try {
338          alglib.minnscreate(thetaValues.Count, thetaValues.ToArray(), out state);
339          // alglib.minnssetalgoslp(state);        // SLP is more robust but slower
340          alglib.minnssetbc(state, thetaValues.Select(_ => -10000.0).ToArray(), thetaValues.Select(_ => +10000.0).ToArray());
341          alglib.minnssetcond(state, 1E-7, maxIterations);
342          var s = Enumerable.Repeat(1d, thetaValues.Count).ToArray();  // scale is set to unit scale
343          alglib.minnssetscale(state, s);
344
345          // set non-linear constraints: 0 equality constraints, constraintTrees inequality constraints
346          alglib.minnssetnlc(state, 0, constraintTrees.Count);
347
348          alglib.minnsoptimize(state, calculate_jacobian, null, null);
349          alglib.minnsresults(state, out double[] xOpt, out rep);
350
351
352          // counter.FunctionEvaluations += rep.nfev; TODO
353          counter.GradientEvaluations += rep.nfev;
354
355          if (rep.terminationtype != -8) {
356            // update parameters in tree
357            var pIdx = 0;
358            foreach (var node in tree.IterateNodesPostfix()) {
359              if (node is ConstantTreeNode constTreeNode) {
360                constTreeNode.Value = xOpt[pIdx++];
361              } else if (node is VariableTreeNode varTreeNode) {
362                varTreeNode.Weight = xOpt[pIdx++];
363              }
364            }
365
366            // note: we keep the optimized constants even when the tree is worse.
367          }
368
369        } catch (ArithmeticException) {
370          // eval MSE of original tree
371          return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
372
373        } catch (alglib.alglibexception) {
374          // eval MSE of original tree
375          return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
376        }
377      } else if (solver.Contains("minnlc")) {
378        alglib.minnlcstate state;
379        alglib.minnlcreport rep;
380        alglib.optguardreport optGuardRep;
381        try {
382          alglib.minnlccreate(thetaValues.Count, thetaValues.ToArray(), out state);
383          alglib.minnlcsetalgoslp(state);        // SLP is more robust but slower
384          alglib.minnlcsetbc(state, thetaValues.Select(_ => -10000.0).ToArray(), thetaValues.Select(_ => +10000.0).ToArray());
385          alglib.minnlcsetcond(state, 1E-7, maxIterations);
386          var s = Enumerable.Repeat(1d, thetaValues.Count).ToArray();  // scale is set to unit scale
387          alglib.minnlcsetscale(state, s);
388
389          // set non-linear constraints: 0 equality constraints, constraintTrees inequality constraints
390          alglib.minnlcsetnlc(state, 0, constraintTrees.Count);
391          alglib.minnlcoptguardsmoothness(state, 1);
392
393          alglib.minnlcoptimize(state, calculate_jacobian, null, null);
394          alglib.minnlcresults(state, out double[] xOpt, out rep);
395          alglib.minnlcoptguardresults(state, out optGuardRep);
396          if (optGuardRep.nonc0suspected) throw new InvalidProgramException("optGuardRep.nonc0suspected");
397          if (optGuardRep.nonc1suspected) throw new InvalidProgramException("optGuardRep.nonc1suspected");
398
399          // counter.FunctionEvaluations += rep.nfev; TODO
400          counter.GradientEvaluations += rep.nfev;
401
402          if (rep.terminationtype != -8) {
403            // update parameters in tree
404            var pIdx = 0;
405            foreach (var node in tree.IterateNodesPostfix()) {
406              if (node is ConstantTreeNode constTreeNode) {
407                constTreeNode.Value = xOpt[pIdx++];
408              } else if (node is VariableTreeNode varTreeNode) {
409                varTreeNode.Weight = xOpt[pIdx++];
410              }
411            }
412
413            // note: we keep the optimized constants even when the tree is worse.
414          }
415
416        } catch (ArithmeticException) {
417          // eval MSE of original tree
418          return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
419
420        } catch (alglib.alglibexception) {
421          // eval MSE of original tree
422          return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
423        }
424      } else {
425        throw new ArgumentException($"Unknown solver {solver}");
426      }
427   
428
429      // evaluate tree with updated constants
430      return SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(interpreter, tree, lowerEstimationLimit, upperEstimationLimit, problemData, rows, applyLinearScaling: false);
431    }
432
433    #region helper
434    private static ISymbolicExpressionTreeNode[] GetParameterNodes(ISymbolicExpressionTree tree, List<ConstantTreeNode>[] allNodes) {
435      // TODO better solution necessary
436      var treeConstNodes = tree.IterateNodesPostfix().OfType<ConstantTreeNode>().ToArray();
437      var paramNodes = new ISymbolicExpressionTreeNode[allNodes.Length];
438      for (int i = 0; i < paramNodes.Length; i++) {
439        paramNodes[i] = allNodes[i].SingleOrDefault(n => treeConstNodes.Contains(n));
440      }
441      return paramNodes;
442    }
443
444    private static ISymbolicExpressionTree ReplaceVarWithConst(ISymbolicExpressionTree tree, List<string> thetaNames, List<double> thetaValues, List<ConstantTreeNode>[] thetaNodes) {
445      var copy = (ISymbolicExpressionTree)tree.Clone();
446      var nodes = copy.IterateNodesPostfix().ToList();
447      for (int i = 0; i < nodes.Count; i++) {
448        var n = nodes[i] as VariableTreeNode;
449        if (n != null) {
450          var thetaIdx = thetaNames.IndexOf(n.VariableName);
451          if (thetaIdx >= 0) {
452            var parent = n.Parent;
453            if (thetaNodes[thetaIdx].Any()) {
454              // HACK: REUSE CONSTANT TREE NODE IN SEVERAL TREES
455              // we use this trick to allow autodiff over thetas when thetas occurr multiple times in the tree (e.g. in derived trees)
456              var constNode = thetaNodes[thetaIdx].First();
457              var childIdx = parent.IndexOfSubtree(n);
458              parent.RemoveSubtree(childIdx);
459              parent.InsertSubtree(childIdx, constNode);
460            } else {
461              var constNode = (ConstantTreeNode)CreateConstant(thetaValues[thetaIdx]);
462              var childIdx = parent.IndexOfSubtree(n);
463              parent.RemoveSubtree(childIdx);
464              parent.InsertSubtree(childIdx, constNode);
465              thetaNodes[thetaIdx].Add(constNode);
466            }
467          }
468        }
469      }
470      return copy;
471    }
472
473    private static ISymbolicExpressionTree ReplaceConstWithVar(ISymbolicExpressionTree tree, out List<string> thetaNames, out List<double> thetaValues) {
474      thetaNames = new List<string>();
475      thetaValues = new List<double>();
476      var copy = (ISymbolicExpressionTree)tree.Clone();
477      var nodes = copy.IterateNodesPostfix().ToList();
478
479      int n = 1;
480      for (int i = 0; i < nodes.Count; ++i) {
481        var node = nodes[i];
482        if (node is ConstantTreeNode constantTreeNode) {
483          var thetaVar = (VariableTreeNode)new Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
484          thetaVar.Weight = 1;
485          thetaVar.VariableName = $"θ{n++}";
486
487          thetaNames.Add(thetaVar.VariableName);
488          thetaValues.Add(constantTreeNode.Value);
489
490          var parent = constantTreeNode.Parent;
491          if (parent != null) {
492            var index = constantTreeNode.Parent.IndexOfSubtree(constantTreeNode);
493            parent.RemoveSubtree(index);
494            parent.InsertSubtree(index, thetaVar);
495          }
496        }
497        if (node is VariableTreeNode varTreeNode) {
498          var thetaVar = (VariableTreeNode)new Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
499          thetaVar.Weight = 1;
500          thetaVar.VariableName = $"θ{n++}";
501
502          thetaNames.Add(thetaVar.VariableName);
503          thetaValues.Add(varTreeNode.Weight);
504
505          var parent = varTreeNode.Parent;
506          if (parent != null) {
507            var index = varTreeNode.Parent.IndexOfSubtree(varTreeNode);
508            parent.RemoveSubtree(index);
509            var prodNode = MakeNode<Multiplication>();
510            varTreeNode.Weight = 1.0;
511            prodNode.AddSubtree(varTreeNode);
512            prodNode.AddSubtree(thetaVar);
513            parent.InsertSubtree(index, prodNode);
514          }
515        }
516      }
517      return copy;
518    }
519
520    private static ISymbolicExpressionTreeNode CreateConstant(double value) {
521      var constantNode = (ConstantTreeNode)new Constant().CreateTreeNode();
522      constantNode.Value = value;
523      return constantNode;
524    }
525
526    private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTree t, ISymbolicExpressionTreeNode b) {
527      var sub = MakeNode<Subtraction>(t.Root.GetSubtree(0).GetSubtree(0), b);
528      t.Root.GetSubtree(0).RemoveSubtree(0);
529      t.Root.GetSubtree(0).InsertSubtree(0, sub);
530      return t;
531    }
532    private static ISymbolicExpressionTree Subtract(ISymbolicExpressionTreeNode b, ISymbolicExpressionTree t) {
533      var sub = MakeNode<Subtraction>(b, t.Root.GetSubtree(0).GetSubtree(0));
534      t.Root.GetSubtree(0).RemoveSubtree(0);
535      t.Root.GetSubtree(0).InsertSubtree(0, sub);
536      return t;
537    }
538
539    private static ISymbolicExpressionTreeNode MakeNode<T>(params ISymbolicExpressionTreeNode[] fs) where T : ISymbol, new() {
540      var node = new T().CreateTreeNode();
541      foreach (var f in fs) node.AddSubtree(f);
542      return node;
543    }
544    #endregion
545
546    private static void UpdateConstants(ISymbolicExpressionTreeNode[] nodes, double[] constants) {
547      if (nodes.Length != constants.Length) throw new InvalidOperationException();
548      for (int i = 0; i < nodes.Length; i++) {
549        if (nodes[i] is VariableTreeNode varNode) varNode.Weight = constants[i];
550        else if (nodes[i] is ConstantTreeNode constNode) constNode.Value = constants[i];
551      }
552    }
553
554    private static alglib.ndimensional_fvec CreateFunc(ISymbolicExpressionTree tree, VectorEvaluator eval, ISymbolicExpressionTreeNode[] parameterNodes, IDataset ds, string targetVar, int[] rows) {
555      var y = ds.GetDoubleValues(targetVar, rows).ToArray();
556      return (double[] c, double[] fi, object o) => {
557        UpdateConstants(parameterNodes, c);
558        var pred = eval.Evaluate(tree, ds, rows);
559        for (int i = 0; i < fi.Length; i++)
560          fi[i] = pred[i] - y[i];
561
562        var counter = (EvaluationsCounter)o;
563        counter.FunctionEvaluations++;
564      };
565    }
566
567    private static alglib.ndimensional_jac CreateJac(ISymbolicExpressionTree tree, VectorAutoDiffEvaluator eval, ISymbolicExpressionTreeNode[] parameterNodes, IDataset ds, string targetVar, int[] rows) {
568      var y = ds.GetDoubleValues(targetVar, rows).ToArray();
569      return (double[] c, double[] fi, double[,] jac, object o) => {
570        UpdateConstants(parameterNodes, c);
571        eval.Evaluate(tree, ds, rows, parameterNodes, fi, jac);
572
573        for (int i = 0; i < fi.Length; i++)
574          fi[i] -= y[i];
575
576        var counter = (EvaluationsCounter)o;
577        counter.GradientEvaluations++;
578      };
579    }
580    public static bool CanOptimizeConstants(ISymbolicExpressionTree tree) {
581      return TreeToAutoDiffTermConverter.IsCompatible(tree);
582    }
583  }
584}
Note: See TracBrowser for help on using the repository browser.