source: branches/DataAnalysis Refactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer.cs @ 5742

Last change on this file since 5742 was 5742, checked in by gkronber, 11 years ago

#1418 fixed grammar cloning bug, improved analyzers for multi objective symbolic data analysis problems.

File size: 9.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using System;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  /// <summary>
36  /// An operator that analyzes the validation best symbolic data analysis solution for multi objective symbolic data analysis problems.
37  /// </summary>
38  [Item("SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer", "An operator that analyzes the validation best symbolic data analysis solution for multi objective symbolic data analysis problems.")]
39  [StorableClass]
40  public abstract class SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer<S, T, U> : SymbolicDataAnalysisValidationAnalyzer<T, U>,
41    ISymbolicDataAnalysisMultiObjectiveAnalyzer
42    where S : class, ISymbolicDataAnalysisSolution
43    where T : class, ISymbolicDataAnalysisMultiObjectiveEvaluator<U>
44    where U : class, IDataAnalysisProblemData {
45    private const string QualitiesParameterName = "Qualities";
46    private const string MaximizationParameterName = "Maximization";
47    private const string ValidationBestSolutionsParameterName = "Best validation solutions";
48    private const string ValidationBestSolutionQualitiesParameterName = "Best validation solution qualities";
49    private const string ValidationBestSolutionsResultName = ValidationBestSolutionsParameterName;
50    private const string ValidationBestSolutionQualitiesResultName = ValidationBestSolutionQualitiesParameterName;
51
52    #region parameter properties
53    public IScopeTreeLookupParameter<DoubleArray> QualitiesParameter {
54      get { return (IScopeTreeLookupParameter<DoubleArray>)Parameters[QualitiesParameterName]; }
55    }
56    public ILookupParameter<BoolArray> MaximizationParameter {
57      get { return (ILookupParameter<BoolArray>)Parameters[MaximizationParameterName]; }
58    }
59    public ILookupParameter<ItemList<S>> ValidationBestSolutionsParameter {
60      get { return (ILookupParameter<ItemList<S>>)Parameters[ValidationBestSolutionsParameterName]; }
61    }
62    public ILookupParameter<ItemList<DoubleArray>> ValidationBestSolutionQualitiesParameter {
63      get { return (ILookupParameter<ItemList<DoubleArray>>)Parameters[ValidationBestSolutionQualitiesParameterName]; }
64    }
65    #endregion
66    #region properties
67    public ItemArray<DoubleArray> Qualities {
68      get { return QualitiesParameter.ActualValue; }
69    }
70    public BoolArray Maximization {
71      get { return MaximizationParameter.ActualValue; }
72    }
73    public ItemList<S> ValidationBestSolutions {
74      get { return ValidationBestSolutionsParameter.ActualValue; }
75      set { ValidationBestSolutionsParameter.ActualValue = value; }
76    }
77    public ItemList<DoubleArray> ValidationBestSolutionQualities {
78      get { return ValidationBestSolutionQualitiesParameter.ActualValue; }
79      set { ValidationBestSolutionQualitiesParameter.ActualValue = value; }
80    }
81    #endregion
82
83    [StorableConstructor]
84    protected SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer(bool deserializing) : base(deserializing) { }
85    protected SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer(SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer<S, T, U> original, Cloner cloner) : base(original, cloner) { }
86    public SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer()
87      : base() {
88      Parameters.Add(new ScopeTreeLookupParameter<DoubleArray>(QualitiesParameterName, "The qualities of the trees that should be analyzed."));
89      Parameters.Add(new LookupParameter<BoolArray>(MaximizationParameterName, "The directions of optimization for each dimension."));
90      Parameters.Add(new LookupParameter<ItemList<S>>(ValidationBestSolutionsParameterName, "The validation best (Pareto-optimal) symbolic data analysis solutions."));
91      Parameters.Add(new LookupParameter<ItemList<DoubleArray>>(ValidationBestSolutionQualitiesParameterName, "The qualities of the validation best (Pareto-optimal) solutions."));
92    }
93
94    public override IOperation Apply() {
95      var results = ResultCollection;
96      // create empty parameter and result values
97      if (ValidationBestSolutions == null) {
98        ValidationBestSolutions = new ItemList<S>();
99        ValidationBestSolutionQualities = new ItemList<DoubleArray>();
100        results.Add(new Result(ValidationBestSolutionQualitiesResultName, ValidationBestSolutionQualities));
101        results.Add(new Result(ValidationBestSolutionsResultName, ValidationBestSolutions));
102      }
103
104      IList<double[]> trainingBestQualities = ValidationBestSolutionQualities
105        .Select(x => x.ToArray())
106        .ToList();
107
108      #region find best trees
109      IList<int> nonDominatedIndexes = new List<int>();
110      ISymbolicExpressionTree[] tree = SymbolicExpressionTrees.ToArray();
111      List<double[]> qualities = new List<double[]>();
112      bool[] maximization = Maximization.ToArray();
113      List<double[]> newNonDominatedQualities = new List<double[]>();
114      var evaluator = Evaluator;
115      int start = ValidationSamplesStart.Value;
116      int end = ValidationSamplesEnd.Value;
117      IEnumerable<int> rows = Enumerable.Range(start, end - start);
118      IExecutionContext childContext = (IExecutionContext)ExecutionContext.CreateChildOperation(evaluator);
119      for (int i = 0; i < tree.Length; i++) {
120        qualities.Add(evaluator.Evaluate(childContext, tree[i], ProblemData, rows)); // qualities[i] = ...
121        if (IsNonDominated(qualities[i], trainingBestQualities, maximization) &&
122          IsNonDominated(qualities[i], qualities, maximization)) {
123          if (!newNonDominatedQualities.Contains(qualities[i], new DoubleArrayComparer())) {
124            newNonDominatedQualities.Add(qualities[i]);
125            nonDominatedIndexes.Add(i);
126          }
127        }
128      }
129      #endregion
130      #region update Pareto-optimal solution archive
131      if (nonDominatedIndexes.Count > 0) {
132        ItemList<DoubleArray> nonDominatedQualities = new ItemList<DoubleArray>();
133        ItemList<S> nonDominatedSolutions = new ItemList<S>();
134        // add all new non-dominated solutions to the archive
135        foreach (var index in nonDominatedIndexes) {
136          S solution = CreateSolution(tree[index], qualities[index]);
137          nonDominatedSolutions.Add(solution);
138          nonDominatedQualities.Add(new DoubleArray(qualities[index]));
139        }
140        // add old non-dominated solutions only if they are not dominated by one of the new solutions
141        for (int i = 0; i < trainingBestQualities.Count; i++) {
142          if (IsNonDominated(trainingBestQualities[i], newNonDominatedQualities, maximization)) {
143            if (!newNonDominatedQualities.Contains(trainingBestQualities[i], new DoubleArrayComparer())) {
144              nonDominatedSolutions.Add(ValidationBestSolutions[i]);
145              nonDominatedQualities.Add(ValidationBestSolutionQualities[i]);
146            }
147          }
148        }
149
150        results[ValidationBestSolutionsResultName].Value = nonDominatedSolutions;
151        results[ValidationBestSolutionQualitiesResultName].Value = nonDominatedQualities;
152      }
153      #endregion
154      return base.Apply();
155    }
156
157    protected abstract S CreateSolution(ISymbolicExpressionTree bestTree, double[] bestQuality);
158
159    private bool IsNonDominated(double[] point, IList<double[]> points, bool[] maximization) {
160      foreach (var refPoint in points) {
161        bool refPointDominatesPoint = true;
162        for (int i = 0; i < point.Length; i++) {
163          refPointDominatesPoint &= IsBetter(refPoint[i], point[i], maximization[i]);
164        }
165        if (refPointDominatesPoint) return false;
166      }
167      return true;
168    }
169    private bool IsBetter(double lhs, double rhs, bool maximization) {
170      if (maximization) return lhs > rhs;
171      else return lhs < rhs;
172    }
173
174    private class DoubleArrayComparer : IEqualityComparer<double[]> {
175      public bool Equals(double[] x, double[] y) {
176        if (y.Length != x.Length) throw new ArgumentException();
177        for (int i = 0; i < x.Length; i++) {
178          if (!x[i].IsAlmost(y[i])) return false;
179        }
180        return true;
181      }
182
183      public int GetHashCode(double[] obj) {
184        int c = obj.Length;
185        for (int i = 0; i < obj.Length; i++)
186          c ^= obj[i].GetHashCode();
187        return c;
188      }
189    }
190
191  }
192}
Note: See TracBrowser for help on using the repository browser.