Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis/3.3/PopulationDiversityAnalysis/PopulationDiversityAnalyzer.cs @ 6193

Last change on this file since 6193 was 6051, checked in by swagner, 14 years ago

Changed some more parameters to be hidden per default and corrected wrong layout in some parameter views (#1377)

File size: 13.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.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Analysis {
33  /// <summary>
34  /// An operator for analyzing the solution diversity in a population.
35  /// </summary>
36  [Item("PopulationDiversityAnalyzer", "An operator for analyzing the solution diversity in a population.")]
37  [StorableClass]
38  public abstract class PopulationDiversityAnalyzer<T> : SingleSuccessorOperator, IAnalyzer where T : class, IItem {
39    public LookupParameter<BoolValue> MaximizationParameter {
40      get { return (LookupParameter<BoolValue>)Parameters["Maximization"]; }
41    }
42    public ScopeTreeLookupParameter<T> SolutionParameter {
43      get { return (ScopeTreeLookupParameter<T>)Parameters["Solution"]; }
44    }
45    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
46      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
47    }
48    public ValueLookupParameter<ResultCollection> ResultsParameter {
49      get { return (ValueLookupParameter<ResultCollection>)Parameters["Results"]; }
50    }
51    public ValueParameter<BoolValue> StoreHistoryParameter {
52      get { return (ValueParameter<BoolValue>)Parameters["StoreHistory"]; }
53    }
54    public ValueParameter<IntValue> UpdateIntervalParameter {
55      get { return (ValueParameter<IntValue>)Parameters["UpdateInterval"]; }
56    }
57    public LookupParameter<IntValue> UpdateCounterParameter {
58      get { return (LookupParameter<IntValue>)Parameters["UpdateCounter"]; }
59    }
60
61    [StorableConstructor]
62    protected PopulationDiversityAnalyzer(bool deserializing) : base(deserializing) { }
63    protected PopulationDiversityAnalyzer(PopulationDiversityAnalyzer<T> original, Cloner cloner) : base(original, cloner) { }
64    public PopulationDiversityAnalyzer()
65      : base() {
66      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem."));
67      Parameters.Add(new ScopeTreeLookupParameter<T>("Solution", "The solutions whose diversity should be analyzed."));
68      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the solutions which should be analyzed."));
69      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the population diversity analysis results should be stored."));
70      Parameters.Add(new ValueParameter<BoolValue>("StoreHistory", "True if the history of the population diversity analysis should be stored.", new BoolValue(false)));
71      Parameters.Add(new ValueParameter<IntValue>("UpdateInterval", "The interval in which the population diversity analysis should be applied.", new IntValue(1)));
72      Parameters.Add(new LookupParameter<IntValue>("UpdateCounter", "The value which counts how many times the operator was called since the last update.", "PopulationDiversityAnalyzerUpdateCounter"));
73
74      MaximizationParameter.Hidden = true;
75      SolutionParameter.Hidden = true;
76      QualityParameter.Hidden = true;
77      ResultsParameter.Hidden = true;
78      UpdateCounterParameter.Hidden = true;
79    }
80
81    public override IOperation Apply() {
82      int updateInterval = UpdateIntervalParameter.Value.Value;
83      IntValue updateCounter = UpdateCounterParameter.ActualValue;
84      // if counter does not yet exist then initialize it with update interval
85      // to make sure the solutions are analyzed on the first application of this operator
86      if (updateCounter == null) {
87        updateCounter = new IntValue(updateInterval);
88        UpdateCounterParameter.ActualValue = updateCounter;
89      } else updateCounter.Value++;
90
91      //analyze solutions only every 'updateInterval' times
92      if (updateCounter.Value == updateInterval) {
93        updateCounter.Value = 0;
94
95        bool max = MaximizationParameter.ActualValue.Value;
96        ItemArray<T> solutions = SolutionParameter.ActualValue;
97        ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
98        bool storeHistory = StoreHistoryParameter.Value.Value;
99        int count = solutions.Length;
100
101        if (count > 1) {
102          // sort solutions by quality
103          T[] sortedSolutions = null;
104          if (max)
105            sortedSolutions = solutions
106              .Select((x, index) => new { Solution = x, Quality = qualities[index] })
107              .OrderByDescending(x => x.Quality)
108              .Select(x => x.Solution)
109              .ToArray();
110          else
111            sortedSolutions = solutions
112              .Select((x, index) => new { Solution = x, Quality = qualities[index] })
113              .OrderBy(x => x.Quality)
114              .Select(x => x.Solution)
115              .ToArray();
116
117          // calculate solution similarities
118          double[,] similarities = CalculateSimilarities(sortedSolutions);
119
120          // calculate minimum, average and maximum similarities
121          double similarity;
122          double[] minSimilarities = new double[count];
123          double[] avgSimilarities = new double[count];
124          double[] maxSimilarities = new double[count];
125          for (int i = 0; i < count; i++) {
126            minSimilarities[i] = 1;
127            avgSimilarities[i] = 0;
128            maxSimilarities[i] = 0;
129            for (int j = 0; j < count; j++) {
130              if (i != j) {
131                similarity = similarities[i, j];
132
133                if ((similarity < 0) || (similarity > 1))
134                  throw new InvalidOperationException("Solution similarities have to be in the interval [0;1].");
135
136                if (minSimilarities[i] > similarity) minSimilarities[i] = similarity;
137                avgSimilarities[i] += similarity;
138                if (maxSimilarities[i] < similarity) maxSimilarities[i] = similarity;
139              }
140            }
141            avgSimilarities[i] = avgSimilarities[i] / (count - 1);
142          }
143          double avgMinSimilarity = minSimilarities.Average();
144          double avgAvgSimilarity = avgSimilarities.Average();
145          double avgMaxSimilarity = maxSimilarities.Average();
146
147          // fetch results collection
148          ResultCollection results;
149          if (!ResultsParameter.ActualValue.ContainsKey(Name + " Results")) {
150            results = new ResultCollection();
151            ResultsParameter.ActualValue.Add(new Result(Name + " Results", results));
152          } else {
153            results = (ResultCollection)ResultsParameter.ActualValue[Name + " Results"].Value;
154          }
155
156          // store similarities
157          HeatMap similaritiesHeatMap = new HeatMap(similarities, "Solution Similarities", 0.0, 1.0);
158          if (!results.ContainsKey("Solution Similarities"))
159            results.Add(new Result("Solution Similarities", similaritiesHeatMap));
160          else
161            results["Solution Similarities"].Value = similaritiesHeatMap;
162
163          // store similarities history
164          if (storeHistory) {
165            if (!results.ContainsKey("Solution Similarities History")) {
166              HeatMapHistory history = new HeatMapHistory();
167              history.Add(similaritiesHeatMap);
168              results.Add(new Result("Solution Similarities History", history));
169            } else {
170              ((HeatMapHistory)results["Solution Similarities History"].Value).Add(similaritiesHeatMap);
171            }
172          }
173
174          // store average minimum, average and maximum similarity
175          if (!results.ContainsKey("Average Minimum Solution Similarity"))
176            results.Add(new Result("Average Minimum Solution Similarity", new DoubleValue(avgMinSimilarity)));
177          else
178            ((DoubleValue)results["Average Minimum Solution Similarity"].Value).Value = avgMinSimilarity;
179
180          if (!results.ContainsKey("Average Average Solution Similarity"))
181            results.Add(new Result("Average Average Solution Similarity", new DoubleValue(avgAvgSimilarity)));
182          else
183            ((DoubleValue)results["Average Average Solution Similarity"].Value).Value = avgAvgSimilarity;
184
185          if (!results.ContainsKey("Average Maximum Solution Similarity"))
186            results.Add(new Result("Average Maximum Solution Similarity", new DoubleValue(avgMaxSimilarity)));
187          else
188            ((DoubleValue)results["Average Maximum Solution Similarity"].Value).Value = avgMaxSimilarity;
189
190          // store average minimum, average and maximum solution similarity data table
191          DataTable minAvgMaxSimilarityDataTable;
192          if (!results.ContainsKey("Average Minimum/Average/Maximum Solution Similarity")) {
193            minAvgMaxSimilarityDataTable = new DataTable("Average Minimum/Average/Maximum Solution Similarity");
194            minAvgMaxSimilarityDataTable.VisualProperties.XAxisTitle = "Iteration";
195            minAvgMaxSimilarityDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
196            minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Minimum Solution Similarity", null));
197            minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].VisualProperties.StartIndexZero = true;
198            minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Average Solution Similarity", null));
199            minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].VisualProperties.StartIndexZero = true;
200            minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Maximum Solution Similarity", null));
201            minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].VisualProperties.StartIndexZero = true;
202            results.Add(new Result("Average Minimum/Average/Maximum Solution Similarity", minAvgMaxSimilarityDataTable));
203          } else {
204            minAvgMaxSimilarityDataTable = (DataTable)results["Average Minimum/Average/Maximum Solution Similarity"].Value;
205          }
206          minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].Values.Add(avgMinSimilarity);
207          minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].Values.Add(avgAvgSimilarity);
208          minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].Values.Add(avgMaxSimilarity);
209
210          // store minimum, average, maximum similarities data table
211          DataTable minAvgMaxSimilaritiesDataTable = new DataTable("Minimum/Average/Maximum Solution Similarities");
212          minAvgMaxSimilaritiesDataTable.VisualProperties.XAxisTitle = "Solution Index";
213          minAvgMaxSimilaritiesDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
214          minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Minimum Solution Similarity", null, minSimilarities));
215          minAvgMaxSimilaritiesDataTable.Rows["Minimum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
216          minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Average Solution Similarity", null, avgSimilarities));
217          minAvgMaxSimilaritiesDataTable.Rows["Average Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
218          minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Maximum Solution Similarity", null, maxSimilarities));
219          minAvgMaxSimilaritiesDataTable.Rows["Maximum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
220          if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities")) {
221            results.Add(new Result("Minimum/Average/Maximum Solution Similarities", minAvgMaxSimilaritiesDataTable));
222          } else {
223            results["Minimum/Average/Maximum Solution Similarities"].Value = minAvgMaxSimilaritiesDataTable;
224          }
225
226          // store minimum, average, maximum similarities history
227          if (storeHistory) {
228            if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities History")) {
229              DataTableHistory history = new DataTableHistory();
230              history.Add(minAvgMaxSimilaritiesDataTable);
231              results.Add(new Result("Minimum/Average/Maximum Solution Similarities History", history));
232            } else {
233              ((DataTableHistory)results["Minimum/Average/Maximum Solution Similarities History"].Value).Add(minAvgMaxSimilaritiesDataTable);
234            }
235          }
236        }
237      }
238      return base.Apply();
239    }
240
241    protected abstract double[,] CalculateSimilarities(T[] solutions);
242  }
243}
Note: See TracBrowser for help on using the repository browser.