Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/Evaluators/SymbolicRegressionParameterOptimizationEvaluator.cs

Last change on this file was 18220, checked in by gkronber, 11 months ago

#3136: reintegrated structure-template GP branch into trunk

File size: 25.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  [Item("Parameter Optimization Evaluator", "Calculates Pearson R² of a symbolic regression solution and optimizes the parameters used.")]
35  [StorableType("24B68851-036D-4446-BD6F-3823E9028FF4")]
36  public class SymbolicRegressionParameterOptimizationEvaluator : SymbolicRegressionSingleObjectiveEvaluator {
37    private const string ParameterOptimizationIterationsParameterName = "ParameterOptimizationIterations";
38    private const string ParameterOptimizationImprovementParameterName = "ParameterOptimizationImprovement";
39    private const string ParameterOptimizationProbabilityParameterName = "ParameterOptimizationProbability";
40    private const string ParameterOptimizationRowsPercentageParameterName = "ParameterOptimizationRowsPercentage";
41    private const string UpdateParametersInTreeParameterName = "UpdateParametersInSymbolicExpressionTree";
42    private const string UpdateVariableWeightsParameterName = "Update Variable Weights";
43
44    private const string FunctionEvaluationsResultParameterName = "Parameters Optimization Function Evaluations";
45    private const string GradientEvaluationsResultParameterName = "Parameters Optimization Gradient Evaluations";
46    private const string CountEvaluationsParameterName = "Count Function and Gradient Evaluations";
47
48    public IFixedValueParameter<IntValue> ParameterOptimizationIterationsParameter {
49      get { return (IFixedValueParameter<IntValue>)Parameters[ParameterOptimizationIterationsParameterName]; }
50    }
51    public IFixedValueParameter<DoubleValue> ParameterOptimizationImprovementParameter {
52      get { return (IFixedValueParameter<DoubleValue>)Parameters[ParameterOptimizationImprovementParameterName]; }
53    }
54    public IFixedValueParameter<PercentValue> ParameterOptimizationProbabilityParameter {
55      get { return (IFixedValueParameter<PercentValue>)Parameters[ParameterOptimizationProbabilityParameterName]; }
56    }
57    public IFixedValueParameter<PercentValue> ParameterOptimizationRowsPercentageParameter {
58      get { return (IFixedValueParameter<PercentValue>)Parameters[ParameterOptimizationRowsPercentageParameterName]; }
59    }
60    public IFixedValueParameter<BoolValue> UpdateParametersInTreeParameter {
61      get { return (IFixedValueParameter<BoolValue>)Parameters[UpdateParametersInTreeParameterName]; }
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
77
78    public IntValue ParameterOptimizationIterations {
79      get { return ParameterOptimizationIterationsParameter.Value; }
80    }
81    public DoubleValue ParameterOptimizationImprovement {
82      get { return ParameterOptimizationImprovementParameter.Value; }
83    }
84    public PercentValue ParameterOptimizationProbability {
85      get { return ParameterOptimizationProbabilityParameter.Value; }
86    }
87    public PercentValue ParameterOptimizationRowsPercentage {
88      get { return ParameterOptimizationRowsPercentageParameter.Value; }
89    }
90    public bool UpdateParametersInTree {
91      get { return UpdateParametersInTreeParameter.Value.Value; }
92      set { UpdateParametersInTreeParameter.Value.Value = value; }
93    }
94
95    public bool UpdateVariableWeights {
96      get { return UpdateVariableWeightsParameter.Value.Value; }
97      set { UpdateVariableWeightsParameter.Value.Value = value; }
98    }
99
100    public bool CountEvaluations {
101      get { return CountEvaluationsParameter.Value.Value; }
102      set { CountEvaluationsParameter.Value.Value = value; }
103    }
104
105    public override bool Maximization {
106      get { return true; }
107    }
108
109    [StorableConstructor]
110    protected SymbolicRegressionParameterOptimizationEvaluator(StorableConstructorFlag _) : base(_) { }
111    protected SymbolicRegressionParameterOptimizationEvaluator(SymbolicRegressionParameterOptimizationEvaluator original, Cloner cloner)
112      : base(original, cloner) {
113    }
114    public SymbolicRegressionParameterOptimizationEvaluator()
115      : base() {
116      Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the parameter of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10)));
117      Parameters.Add(new FixedValueParameter<DoubleValue>(ParameterOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the parameter optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0)) { Hidden = true });
118      Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationProbabilityParameterName, "Determines the probability that the parameters are optimized", new PercentValue(1)));
119      Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for parameter optimization", new PercentValue(1)));
120      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateParametersInTreeParameterName, "Determines if the parameters in the tree should be overwritten by the optimized parameters.", new BoolValue(true)) { Hidden = true });
121      Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)) { Hidden = true });
122
123      Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
124      Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the parameters optimization evaluator", "Results", new IntValue()));
125      Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the parameters optimization evaluator", "Results", new IntValue()));
126    }
127
128    public override IDeepCloneable Clone(Cloner cloner) {
129      return new SymbolicRegressionParameterOptimizationEvaluator(this, cloner);
130    }
131
132    [StorableHook(HookType.AfterDeserialization)]
133    private void AfterDeserialization() {
134      if (!Parameters.ContainsKey(UpdateParametersInTreeParameterName)) {
135        if (Parameters.ContainsKey("UpdateConstantsInSymbolicExpressionTree")) {
136          Parameters.Add(new FixedValueParameter<BoolValue>(UpdateParametersInTreeParameterName, "Determines if the parameters in the tree should be overwritten by the optimized parameters.", (BoolValue)Parameters["UpdateConstantsInSymbolicExpressionTree"].ActualValue));
137          Parameters.Remove("UpdateConstantsInSymbolicExpressionTree");
138        } else {
139          Parameters.Add(new FixedValueParameter<BoolValue>(UpdateParametersInTreeParameterName, "Determines if the parameters in the tree should be overwritten by the optimized parameters.", new BoolValue(true)));
140        }
141      }
142
143      if (!Parameters.ContainsKey(UpdateVariableWeightsParameterName))
144        Parameters.Add(new FixedValueParameter<BoolValue>(UpdateVariableWeightsParameterName, "Determines if the variable weights in the tree should be  optimized.", new BoolValue(true)));
145
146      if (!Parameters.ContainsKey(CountEvaluationsParameterName))
147        Parameters.Add(new FixedValueParameter<BoolValue>(CountEvaluationsParameterName, "Determines if function and gradient evaluation should be counted.", new BoolValue(false)));
148
149      if (!Parameters.ContainsKey(FunctionEvaluationsResultParameterName)) {
150        if (Parameters.ContainsKey("Constants Optimization Function Evaluations")) {
151          Parameters.Remove("Constants Optimization Function Evaluations");
152        }
153        Parameters.Add(new ResultParameter<IntValue>(FunctionEvaluationsResultParameterName, "The number of function evaluations performed by the parameters optimization evaluator", "Results", new IntValue()));
154      }
155
156      if (!Parameters.ContainsKey(GradientEvaluationsResultParameterName)) {
157        if (Parameters.ContainsKey("Constants Optimization Gradient Evaluations")) {
158          Parameters.Remove("Constants Optimization Gradient Evaluations");
159        }
160        Parameters.Add(new ResultParameter<IntValue>(GradientEvaluationsResultParameterName, "The number of gradient evaluations performed by the parameters optimization evaluator", "Results", new IntValue()));
161      }
162
163      if (!Parameters.ContainsKey(ParameterOptimizationIterationsParameterName)) {
164        if (Parameters.ContainsKey("ConstantOptimizationIterations")) {
165          Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the parameter of a symbolic expression tree (0 indicates other or default stopping criterion).", (IntValue)Parameters["ConstantOptimizationIterations"].ActualValue));
166          Parameters.Remove("ConstantOptimizationIterations");
167        } else {
168          Parameters.Add(new FixedValueParameter<IntValue>(ParameterOptimizationIterationsParameterName, "Determines how many iterations should be calculated while optimizing the parameter of a symbolic expression tree (0 indicates other or default stopping criterion).", new IntValue(10)));
169        }
170      }
171
172      if (!Parameters.ContainsKey(ParameterOptimizationImprovementParameterName)) {
173        if (Parameters.ContainsKey("CosntantOptimizationImprovement")) {
174          Parameters.Add(new FixedValueParameter<DoubleValue>(ParameterOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the parameter optimization to continue with it (0 indicates other or default stopping criterion).",
175            (DoubleValue)Parameters["CosntantOptimizationImprovement"].ActualValue) { Hidden = true });
176          Parameters.Remove("CosntantOptimizationImprovement");
177        } else {
178          Parameters.Add(new FixedValueParameter<DoubleValue>(ParameterOptimizationImprovementParameterName, "Determines the relative improvement which must be achieved in the parameter optimization to continue with it (0 indicates other or default stopping criterion).", new DoubleValue(0)) { Hidden = true });
179        }
180      }
181
182      if (!Parameters.ContainsKey(ParameterOptimizationProbabilityParameterName)) {
183        if (Parameters.ContainsKey("ConstantOptimizationProbability")) {
184          Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationProbabilityParameterName, "Determines the probability that the parameters are optimized",
185            (PercentValue)Parameters["ConstantOptimizationProbability"].ActualValue));
186          Parameters.Remove("ConstantOptimizationProbability");
187        } else {
188          Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationProbabilityParameterName, "Determines the probability that the parameters are optimized", new PercentValue(1)));
189        }
190      }
191
192      if (!Parameters.ContainsKey(ParameterOptimizationRowsPercentageParameterName)) {
193        if (Parameters.ContainsKey("ConstantOptimizationRowsPercentage")) {
194          Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for parameter optimization", (PercentValue)Parameters["ConstantOptimizationRowsPercentage"].ActualValue));
195          Parameters.Remove("ConstantOptimizationRowsPercentage");
196        } else {
197          Parameters.Add(new FixedValueParameter<PercentValue>(ParameterOptimizationRowsPercentageParameterName, "Determines the percentage of the rows which should be used for parameter optimization", new PercentValue(1)));
198        }
199
200      }
201    }
202
203    private static readonly object locker = new object();
204    public override IOperation InstrumentedApply() {
205      var tree = SymbolicExpressionTreeParameter.ActualValue;
206      double quality;
207      if (RandomParameter.ActualValue.NextDouble() < ParameterOptimizationProbability.Value) {
208        IEnumerable<int> parameterOptimizationRows = GenerateRowsToEvaluate(ParameterOptimizationRowsPercentage.Value);
209        var counter = new EvaluationsCounter();
210        quality = OptimizeParameters(SymbolicDataAnalysisTreeInterpreterParameter.ActualValue, tree, ProblemDataParameter.ActualValue,
211           parameterOptimizationRows, ApplyLinearScalingParameter.ActualValue.Value, ParameterOptimizationIterations.Value, updateVariableWeights: UpdateVariableWeights, lowerEstimationLimit: EstimationLimitsParameter.ActualValue.Lower, upperEstimationLimit: EstimationLimitsParameter.ActualValue.Upper, updateParametersInTree: UpdateParametersInTree, counter: counter);
212
213        if (ParameterOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
214          var evaluationRows = GenerateRowsToEvaluate();
215          quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
216            tree, ProblemDataParameter.ActualValue,
217            evaluationRows, SymbolicDataAnalysisTreeInterpreterParameter.ActualValue,
218            ApplyLinearScalingParameter.ActualValue.Value,
219            EstimationLimitsParameter.ActualValue.Lower,
220            EstimationLimitsParameter.ActualValue.Upper);
221        }
222
223        if (CountEvaluations) {
224          lock (locker) {
225            FunctionEvaluationsResultParameter.ActualValue.Value += counter.FunctionEvaluations;
226            GradientEvaluationsResultParameter.ActualValue.Value += counter.GradientEvaluations;
227          }
228        }
229
230      } else {
231        var evaluationRows = GenerateRowsToEvaluate();
232        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
233          tree, ProblemDataParameter.ActualValue,
234          evaluationRows, SymbolicDataAnalysisTreeInterpreterParameter.ActualValue,
235          ApplyLinearScalingParameter.ActualValue.Value,
236          EstimationLimitsParameter.ActualValue.Lower,
237          EstimationLimitsParameter.ActualValue.Upper);
238      }
239      QualityParameter.ActualValue = new DoubleValue(quality);
240
241      return base.InstrumentedApply();
242    }
243
244    public override double Evaluate(
245      ISymbolicExpressionTree tree,
246      IRegressionProblemData problemData,
247      IEnumerable<int> rows,
248      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
249      bool applyLinearScaling = true,
250      double lowerEstimationLimit = double.MinValue,
251      double upperEstimationLimit = double.MaxValue) {
252
253      var random = RandomParameter.ActualValue;
254      double quality = double.NaN;
255
256      var propability = random.NextDouble();
257      if (propability < ParameterOptimizationProbability.Value) {
258        quality = OptimizeParameters(
259          interpreter, tree,
260          problemData, rows,
261          applyLinearScaling,
262          ParameterOptimizationIterations.Value,
263          updateVariableWeights: UpdateVariableWeights,
264          lowerEstimationLimit: lowerEstimationLimit,
265          upperEstimationLimit: upperEstimationLimit,
266          updateParametersInTree: UpdateParametersInTree);
267      }
268      if (double.IsNaN(quality) || ParameterOptimizationRowsPercentage.Value != RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value) {
269        quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
270          tree, problemData,
271          rows, interpreter,
272          applyLinearScaling,
273          lowerEstimationLimit,
274          upperEstimationLimit);
275      }
276      return quality;
277    }
278
279    public override double Evaluate(IExecutionContext context, ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows) {
280      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = context;
281      EstimationLimitsParameter.ExecutionContext = context;
282      ApplyLinearScalingParameter.ExecutionContext = context;
283      FunctionEvaluationsResultParameter.ExecutionContext = context;
284      GradientEvaluationsResultParameter.ExecutionContext = context;
285
286      // Pearson R² evaluator is used on purpose instead of the const-opt evaluator,
287      // because Evaluate() is used to get the quality of evolved models on
288      // different partitions of the dataset (e.g., best validation model)
289      double r2 = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
290        tree, problemData, rows,
291        SymbolicDataAnalysisTreeInterpreterParameter.ActualValue,
292        ApplyLinearScalingParameter.ActualValue.Value,
293        EstimationLimitsParameter.ActualValue.Lower,
294        EstimationLimitsParameter.ActualValue.Upper);
295
296      SymbolicDataAnalysisTreeInterpreterParameter.ExecutionContext = null;
297      EstimationLimitsParameter.ExecutionContext = null;
298      ApplyLinearScalingParameter.ExecutionContext = null;
299      FunctionEvaluationsResultParameter.ExecutionContext = null;
300      GradientEvaluationsResultParameter.ExecutionContext = null;
301
302      return r2;
303    }
304
305    public class EvaluationsCounter {
306      public int FunctionEvaluations = 0;
307      public int GradientEvaluations = 0;
308    }
309
310    public static double OptimizeParameters(ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
311      ISymbolicExpressionTree tree, IRegressionProblemData problemData, IEnumerable<int> rows, bool applyLinearScaling,
312      int maxIterations, bool updateVariableWeights = true,
313      double lowerEstimationLimit = double.MinValue, double upperEstimationLimit = double.MaxValue,
314      bool updateParametersInTree = true, Action<double[], double, object> iterationCallback = null, EvaluationsCounter counter = null) {
315
316      // Numeric parameters in the tree become variables for parameter optimization.
317      // Variables in the tree become parameters (fixed values) for parameter optimization.
318      // For each parameter (variable in the original tree) we store the
319      // variable name, variable value (for factor vars) and lag as a DataForVariable object.
320      // A dictionary is used to find parameters
321      double[] initialParameters;
322      var parameters = new List<TreeToAutoDiffTermConverter.DataForVariable>();
323
324      TreeToAutoDiffTermConverter.ParametricFunction func;
325      TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad;
326      if (!TreeToAutoDiffTermConverter.TryConvertToAutoDiff(tree, updateVariableWeights, applyLinearScaling, out parameters, out initialParameters, out func, out func_grad))
327        throw new NotSupportedException("Could not optimize parameters of symbolic expression tree due to not supported symbols used in the tree.");
328      if (parameters.Count == 0) return 0.0; // constant expressions always have a R² of 0.0
329      var parameterEntries = parameters.ToArray(); // order of entries must be the same for x
330
331      // extract inital parameters
332      double[] c;
333      if (applyLinearScaling) {
334        c = new double[initialParameters.Length + 2];
335        c[0] = 0.0;
336        c[1] = 1.0;
337        Array.Copy(initialParameters, 0, c, 2, initialParameters.Length);
338      } else {
339        c = (double[])initialParameters.Clone();
340      }
341
342      double originalQuality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
343        tree, problemData, rows,
344        interpreter, applyLinearScaling,
345        lowerEstimationLimit,
346        upperEstimationLimit);
347
348      if (counter == null) counter = new EvaluationsCounter();
349      var rowEvaluationsCounter = new EvaluationsCounter();
350
351      alglib.lsfitstate state;
352      alglib.lsfitreport rep;
353      int retVal;
354
355      IDataset ds = problemData.Dataset;
356      double[,] x = new double[rows.Count(), parameters.Count];
357      int row = 0;
358      foreach (var r in rows) {
359        int col = 0;
360        foreach (var info in parameterEntries) {
361          if (ds.VariableHasType<double>(info.variableName)) {
362            x[row, col] = ds.GetDoubleValue(info.variableName, r + info.lag);
363          } else if (ds.VariableHasType<string>(info.variableName)) {
364            x[row, col] = ds.GetStringValue(info.variableName, r) == info.variableValue ? 1 : 0;
365          } else throw new InvalidProgramException("found a variable of unknown type");
366          col++;
367        }
368        row++;
369      }
370      double[] y = ds.GetDoubleValues(problemData.TargetVariable, rows).ToArray();
371      int n = x.GetLength(0);
372      int m = x.GetLength(1);
373      int k = c.Length;
374
375      alglib.ndimensional_pfunc function_cx_1_func = CreatePFunc(func);
376      alglib.ndimensional_pgrad function_cx_1_grad = CreatePGrad(func_grad);
377      alglib.ndimensional_rep xrep = (p, f, obj) => iterationCallback(p, f, obj);
378
379      try {
380        alglib.lsfitcreatefg(x, y, c, n, m, k, false, out state);
381        alglib.lsfitsetcond(state, 0.0, maxIterations);
382        alglib.lsfitsetxrep(state, iterationCallback != null);
383        alglib.lsfitfit(state, function_cx_1_func, function_cx_1_grad, xrep, rowEvaluationsCounter);
384        alglib.lsfitresults(state, out retVal, out c, out rep);
385      } catch (ArithmeticException) {
386        return originalQuality;
387      } catch (alglib.alglibexception) {
388        return originalQuality;
389      }
390
391      counter.FunctionEvaluations += rowEvaluationsCounter.FunctionEvaluations / n;
392      counter.GradientEvaluations += rowEvaluationsCounter.GradientEvaluations / n;
393
394      //retVal == -7  => parameter optimization failed due to wrong gradient
395      //          -8  => optimizer detected  NAN / INF  in  the target
396      //                 function and/ or gradient
397      if (retVal != -7 && retVal != -8) {
398        if (applyLinearScaling) {
399          var tmp = new double[c.Length - 2];
400          Array.Copy(c, 2, tmp, 0, tmp.Length);
401          UpdateParameters(tree, tmp, updateVariableWeights);
402        } else UpdateParameters(tree, c, updateVariableWeights);
403      }
404      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
405        tree, problemData, rows,
406        interpreter, applyLinearScaling,
407        lowerEstimationLimit, upperEstimationLimit);
408
409      if (!updateParametersInTree) UpdateParameters(tree, initialParameters, updateVariableWeights);
410
411      if (originalQuality - quality > 0.001 || double.IsNaN(quality)) {
412        UpdateParameters(tree, initialParameters, updateVariableWeights);
413        return originalQuality;
414      }
415      return quality;
416    }
417
418    private static void UpdateParameters(ISymbolicExpressionTree tree, double[] parameters, bool updateVariableWeights) {
419      int i = 0;
420      foreach (var node in tree.Root.IterateNodesPrefix().OfType<SymbolicExpressionTreeTerminalNode>()) {
421        NumberTreeNode numberTreeNode = node as NumberTreeNode;
422        VariableTreeNodeBase variableTreeNodeBase = node as VariableTreeNodeBase;
423        FactorVariableTreeNode factorVarTreeNode = node as FactorVariableTreeNode;
424        if (numberTreeNode != null) {
425          if (numberTreeNode.Parent.Symbol is Power
426              && numberTreeNode.Parent.GetSubtree(1) == numberTreeNode) continue; // exponents in powers are not optimizated (see TreeToAutoDiffTermConverter)
427          numberTreeNode.Value = parameters[i++];
428        } else if (updateVariableWeights && variableTreeNodeBase != null)
429          variableTreeNodeBase.Weight = parameters[i++];
430        else if (factorVarTreeNode != null) {
431          for (int j = 0; j < factorVarTreeNode.Weights.Length; j++)
432            factorVarTreeNode.Weights[j] = parameters[i++];
433        }
434      }
435    }
436
437    private static alglib.ndimensional_pfunc CreatePFunc(TreeToAutoDiffTermConverter.ParametricFunction func) {
438      return (double[] c, double[] x, ref double fx, object o) => {
439        fx = func(c, x);
440        var counter = (EvaluationsCounter)o;
441        counter.FunctionEvaluations++;
442      };
443    }
444
445    private static alglib.ndimensional_pgrad CreatePGrad(TreeToAutoDiffTermConverter.ParametricFunctionGradient func_grad) {
446      return (double[] c, double[] x, ref double fx, double[] grad, object o) => {
447        var tuple = func_grad(c, x);
448        fx = tuple.Item2;
449        Array.Copy(tuple.Item1, grad, grad.Length);
450        var counter = (EvaluationsCounter)o;
451        counter.GradientEvaluations++;
452      };
453    }
454    public static bool CanOptimizeParameters(ISymbolicExpressionTree tree) {
455      return TreeToAutoDiffTermConverter.IsCompatible(tree);
456    }
457  }
458}
Note: See TracBrowser for help on using the repository browser.