source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/ConstantOptimizationAnalyzer.cs @ 16641

Last change on this file since 16641 was 16641, checked in by gkronber, 4 months ago

#2971: merged r16527:16625 from trunk/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression to branch/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression (resolving all conflicts)

File size: 8.3 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.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HEAL.Attic;
31using HEAL.Attic;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
34  /// <summary>
35  /// An operator that optimizes the constants for the best symbolic expression tress in the current generation.
36  /// </summary>
37  [Item("ConstantOptimizationAnalyzer", "An operator that performs a constant optimization on the best symbolic expression trees.")]
38  [StorableType("9FB87E7B-A9E2-49DD-A92A-78BD9FC17916")]
39  public sealed class ConstantOptimizationAnalyzer : SymbolicDataAnalysisSingleObjectiveAnalyzer, IStatefulItem {
40    private const string PercentageOfBestSolutionsParameterName = "PercentageOfBestSolutions";
41    private const string ConstantOptimizationEvaluatorParameterName = "ConstantOptimizationOperator";
42
43    private const string DataTableNameConstantOptimizationImprovement = "Constant Optimization Improvement";
44    private const string DataRowNameMinimumImprovement = "Minimum improvement";
45    private const string DataRowNameMedianImprovement = "Median improvement";
46    private const string DataRowNameAverageImprovement = "Average improvement";
47    private const string DataRowNameMaximumImprovement = "Maximum improvement";
48
49    #region parameter properties
50    public IFixedValueParameter<PercentValue> PercentageOfBestSolutionsParameter {
51      get { return (IFixedValueParameter<PercentValue>)Parameters[PercentageOfBestSolutionsParameterName]; }
52    }
53
54    public IFixedValueParameter<SymbolicRegressionConstantOptimizationEvaluator> ConstantOptimizationEvaluatorParameter {
55      get { return (IFixedValueParameter<SymbolicRegressionConstantOptimizationEvaluator>)Parameters[ConstantOptimizationEvaluatorParameterName]; }
56    }
57    #endregion
58
59    #region properties
60    public SymbolicRegressionConstantOptimizationEvaluator ConstantOptimizationEvaluator {
61      get { return ConstantOptimizationEvaluatorParameter.Value; }
62    }
63    public double PercentageOfBestSolutions {
64      get { return PercentageOfBestSolutionsParameter.Value.Value; }
65    }
66
67    private DataTable ConstantOptimizationImprovementDataTable {
68      get {
69        IResult result;
70        ResultCollection.TryGetValue(DataTableNameConstantOptimizationImprovement, out result);
71        if (result == null) return null;
72        return (DataTable)result.Value;
73      }
74    }
75    private DataRow MinimumImprovement {
76      get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameMinimumImprovement]; }
77    }
78    private DataRow MedianImprovement {
79      get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameMedianImprovement]; }
80    }
81    private DataRow AverageImprovement {
82      get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameAverageImprovement]; }
83    }
84    private DataRow MaximumImprovement {
85      get { return ConstantOptimizationImprovementDataTable.Rows[DataRowNameMaximumImprovement]; }
86    }
87    #endregion
88
89    [StorableConstructor]
90    private ConstantOptimizationAnalyzer(StorableConstructorFlag _) : base(_) { }
91    private ConstantOptimizationAnalyzer(ConstantOptimizationAnalyzer original, Cloner cloner) : base(original, cloner) { }
92    public override IDeepCloneable Clone(Cloner cloner) { return new ConstantOptimizationAnalyzer(this, cloner); }
93    public ConstantOptimizationAnalyzer()
94      : base() {
95      Parameters.Add(new FixedValueParameter<PercentValue>(PercentageOfBestSolutionsParameterName, "The percentage of the top solutions which should be analyzed.", new PercentValue(0.1)));
96      Parameters.Add(new FixedValueParameter<SymbolicRegressionConstantOptimizationEvaluator>(ConstantOptimizationEvaluatorParameterName, "The operator used to perform the constant optimization"));
97
98      //Changed the ActualName of the EvaluationPartitionParameter so that it matches the parameter name of symbolic regression problems.
99      ConstantOptimizationEvaluator.EvaluationPartitionParameter.ActualName = "FitnessCalculationPartition";
100    }
101
102
103    private double[] qualitiesBeforeCoOp = null;
104    private int[] scopeIndexes = null;
105    void IStatefulItem.InitializeState() {
106      qualitiesBeforeCoOp = null;
107      scopeIndexes = null;
108    }
109    void IStatefulItem.ClearState() {
110      qualitiesBeforeCoOp = null;
111      scopeIndexes = null;
112    }
113
114    public override IOperation Apply() {
115      //code executed in the first call of analyzer
116      if (qualitiesBeforeCoOp == null) {
117        double[] trainingQuality;
118        // sort is ascending and we take the first n% => order so that best solutions are smallest
119        // sort order is determined by maximization parameter
120        if (Maximization.Value) {
121          // largest values must be sorted first
122          trainingQuality = Quality.Select(x => -x.Value).ToArray();
123        } else {
124          // smallest values must be sorted first
125          trainingQuality = Quality.Select(x => x.Value).ToArray();
126        }
127        // sort trees by training qualities
128        int topN = (int)Math.Max(trainingQuality.Length * PercentageOfBestSolutions, 1);
129        scopeIndexes = Enumerable.Range(0, trainingQuality.Length).ToArray();
130        Array.Sort(trainingQuality, scopeIndexes);
131        scopeIndexes = scopeIndexes.Take(topN).ToArray();
132        qualitiesBeforeCoOp = scopeIndexes.Select(x => Quality[x].Value).ToArray();
133
134        OperationCollection operationCollection = new OperationCollection();
135        operationCollection.Parallel = true;
136        foreach (var scopeIndex in scopeIndexes) {
137          var childOperation = ExecutionContext.CreateChildOperation(ConstantOptimizationEvaluator, ExecutionContext.Scope.SubScopes[scopeIndex]);
138          operationCollection.Add(childOperation);
139        }
140
141        return new OperationCollection { operationCollection, ExecutionContext.CreateOperation(this) };
142      }
143
144      //code executed to analyze results of constant optimization
145      double[] qualitiesAfterCoOp = scopeIndexes.Select(x => Quality[x].Value).ToArray();
146      var qualityImprovement = qualitiesBeforeCoOp.Zip(qualitiesAfterCoOp, (b, a) => a - b).ToArray();
147
148      if (!ResultCollection.ContainsKey(DataTableNameConstantOptimizationImprovement)) {
149        var dataTable = new DataTable(DataTableNameConstantOptimizationImprovement);
150        ResultCollection.Add(new Result(DataTableNameConstantOptimizationImprovement, dataTable));
151        dataTable.VisualProperties.YAxisTitle = "R²";
152
153        dataTable.Rows.Add(new DataRow(DataRowNameMinimumImprovement));
154        MinimumImprovement.VisualProperties.StartIndexZero = true;
155
156        dataTable.Rows.Add(new DataRow(DataRowNameMedianImprovement));
157        MedianImprovement.VisualProperties.StartIndexZero = true;
158
159        dataTable.Rows.Add(new DataRow(DataRowNameAverageImprovement));
160        AverageImprovement.VisualProperties.StartIndexZero = true;
161
162        dataTable.Rows.Add(new DataRow(DataRowNameMaximumImprovement));
163        MaximumImprovement.VisualProperties.StartIndexZero = true;
164      }
165
166      MinimumImprovement.Values.Add(qualityImprovement.Min());
167      MedianImprovement.Values.Add(qualityImprovement.Median());
168      AverageImprovement.Values.Add(qualityImprovement.Average());
169      MaximumImprovement.Values.Add(qualityImprovement.Max());
170
171      qualitiesBeforeCoOp = null;
172      scopeIndexes = null;
173      return base.Apply();
174    }
175  }
176}
Note: See TracBrowser for help on using the repository browser.