Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer.cs @ 6593

Last change on this file since 6593 was 5907, checked in by mkommend, 14 years ago

#1418: Removed calls to IEnumerable.Count() in performance critical sections.

File size: 8.3 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;
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 HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
34  /// <summary>
35  /// An operator that analyzes the validation best symbolic data analysis solution for multi objective symbolic data analysis problems.
36  /// </summary>
37  [Item("SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer", "An operator that analyzes the validation best symbolic data analysis solution for multi objective symbolic data analysis problems.")]
38  [StorableClass]
39  public abstract class SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer<S, T, U> : SymbolicDataAnalysisMultiObjectiveValidationAnalyzer<T, U>,
40    ISymbolicDataAnalysisMultiObjectiveAnalyzer
41    where S : class, ISymbolicDataAnalysisSolution
42    where T : class, ISymbolicDataAnalysisMultiObjectiveEvaluator<U>
43    where U : class, IDataAnalysisProblemData {
44    private const string ValidationBestSolutionsParameterName = "Best validation solutions";
45    private const string ValidationBestSolutionQualitiesParameterName = "Best validation solution qualities";
46
47    #region parameter properties
48    public ILookupParameter<ItemList<S>> ValidationBestSolutionsParameter {
49      get { return (ILookupParameter<ItemList<S>>)Parameters[ValidationBestSolutionsParameterName]; }
50    }
51    public ILookupParameter<ItemList<DoubleArray>> ValidationBestSolutionQualitiesParameter {
52      get { return (ILookupParameter<ItemList<DoubleArray>>)Parameters[ValidationBestSolutionQualitiesParameterName]; }
53    }
54    #endregion
55    #region properties
56    public ItemList<S> ValidationBestSolutions {
57      get { return ValidationBestSolutionsParameter.ActualValue; }
58      set { ValidationBestSolutionsParameter.ActualValue = value; }
59    }
60    public ItemList<DoubleArray> ValidationBestSolutionQualities {
61      get { return ValidationBestSolutionQualitiesParameter.ActualValue; }
62      set { ValidationBestSolutionQualitiesParameter.ActualValue = value; }
63    }
64    #endregion
65
66    [StorableConstructor]
67    protected SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer(bool deserializing) : base(deserializing) { }
68    protected SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer(SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer<S, T, U> original, Cloner cloner) : base(original, cloner) { }
69    public SymbolicDataAnalysisMultiObjectiveValidationBestSolutionAnalyzer()
70      : base() {
71      Parameters.Add(new LookupParameter<ItemList<S>>(ValidationBestSolutionsParameterName, "The validation best (Pareto-optimal) symbolic data analysis solutions."));
72      Parameters.Add(new LookupParameter<ItemList<DoubleArray>>(ValidationBestSolutionQualitiesParameterName, "The qualities of the validation best (Pareto-optimal) solutions."));
73    }
74
75    public override IOperation Apply() {
76      IEnumerable<int> rows = GenerateRowsToEvaluate();
77      if (!rows.Any()) return base.Apply();
78
79      var results = ResultCollection;
80      // create empty parameter and result values
81      if (ValidationBestSolutions == null) {
82        ValidationBestSolutions = new ItemList<S>();
83        ValidationBestSolutionQualities = new ItemList<DoubleArray>();
84        results.Add(new Result(ValidationBestSolutionQualitiesParameter.Name, ValidationBestSolutionQualitiesParameter.Description, ValidationBestSolutionQualities));
85        results.Add(new Result(ValidationBestSolutionsParameter.Name, ValidationBestSolutionsParameter.Description, ValidationBestSolutions));
86      }
87
88      IList<double[]> trainingBestQualities = ValidationBestSolutionQualities
89        .Select(x => x.ToArray())
90        .ToList();
91
92      #region find best trees
93      IList<int> nonDominatedIndexes = new List<int>();
94      ISymbolicExpressionTree[] tree = SymbolicExpressionTree.ToArray();
95      List<double[]> qualities = new List<double[]>();
96      bool[] maximization = Maximization.ToArray();
97      List<double[]> newNonDominatedQualities = new List<double[]>();
98      var evaluator = EvaluatorParameter.ActualValue;
99      IExecutionContext childContext = (IExecutionContext)ExecutionContext.CreateChildOperation(evaluator);
100      for (int i = 0; i < tree.Length; i++) {
101        qualities.Add(evaluator.Evaluate(childContext, tree[i], ProblemDataParameter.ActualValue, rows)); // qualities[i] = ...
102        if (IsNonDominated(qualities[i], trainingBestQualities, maximization) &&
103          IsNonDominated(qualities[i], qualities, maximization)) {
104          if (!newNonDominatedQualities.Contains(qualities[i], new DoubleArrayComparer())) {
105            newNonDominatedQualities.Add(qualities[i]);
106            nonDominatedIndexes.Add(i);
107          }
108        }
109      }
110      #endregion
111      #region update Pareto-optimal solution archive
112      if (nonDominatedIndexes.Count > 0) {
113        ItemList<DoubleArray> nonDominatedQualities = new ItemList<DoubleArray>();
114        ItemList<S> nonDominatedSolutions = new ItemList<S>();
115        // add all new non-dominated solutions to the archive
116        foreach (var index in nonDominatedIndexes) {
117          S solution = CreateSolution(tree[index], qualities[index]);
118          nonDominatedSolutions.Add(solution);
119          nonDominatedQualities.Add(new DoubleArray(qualities[index]));
120        }
121        // add old non-dominated solutions only if they are not dominated by one of the new solutions
122        for (int i = 0; i < trainingBestQualities.Count; i++) {
123          if (IsNonDominated(trainingBestQualities[i], newNonDominatedQualities, maximization)) {
124            if (!newNonDominatedQualities.Contains(trainingBestQualities[i], new DoubleArrayComparer())) {
125              nonDominatedSolutions.Add(ValidationBestSolutions[i]);
126              nonDominatedQualities.Add(ValidationBestSolutionQualities[i]);
127            }
128          }
129        }
130
131        results[ValidationBestSolutionsParameter.Name].Value = nonDominatedSolutions;
132        results[ValidationBestSolutionQualitiesParameter.Name].Value = nonDominatedQualities;
133      }
134      #endregion
135      return base.Apply();
136    }
137
138    protected abstract S CreateSolution(ISymbolicExpressionTree bestTree, double[] bestQuality);
139
140    private bool IsNonDominated(double[] point, IList<double[]> points, bool[] maximization) {
141      foreach (var refPoint in points) {
142        bool refPointDominatesPoint = true;
143        for (int i = 0; i < point.Length; i++) {
144          refPointDominatesPoint &= IsBetter(refPoint[i], point[i], maximization[i]);
145        }
146        if (refPointDominatesPoint) return false;
147      }
148      return true;
149    }
150    private bool IsBetter(double lhs, double rhs, bool maximization) {
151      if (maximization) return lhs > rhs;
152      else return lhs < rhs;
153    }
154
155    private class DoubleArrayComparer : IEqualityComparer<double[]> {
156      public bool Equals(double[] x, double[] y) {
157        if (y.Length != x.Length) throw new ArgumentException();
158        for (int i = 0; i < x.Length; i++) {
159          if (!x[i].IsAlmost(y[i])) return false;
160        }
161        return true;
162      }
163
164      public int GetHashCode(double[] obj) {
165        int c = obj.Length;
166        for (int i = 0; i < obj.Length; i++)
167          c ^= obj[i].GetHashCode();
168        return c;
169      }
170    }
171
172  }
173}
Note: See TracBrowser for help on using the repository browser.