Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Analysis/3.3/PopulationDiversityAnalysis/PopulationDiversityAnalyzer.cs @ 8228

Last change on this file since 8228 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

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