Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2994: return a bad quality if constraints are violated

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