Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Scheduling/HeuristicLab.Analysis/3.3/PopulationDiversityAnalysis/PopulationDiversityAnalyzer.cs @ 6514

Last change on this file since 6514 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 13.1 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
75    public override IOperation Apply() {
76      int updateInterval = UpdateIntervalParameter.Value.Value;
77      IntValue updateCounter = UpdateCounterParameter.ActualValue;
78      // if counter does not yet exist then initialize it with update interval
79      // to make sure the solutions are analyzed on the first application of this operator
80      if (updateCounter == null) {
81        updateCounter = new IntValue(updateInterval);
82        UpdateCounterParameter.ActualValue = updateCounter;
83      } else updateCounter.Value++;
84
85      //analyze solutions only every 'updateInterval' times
86      if (updateCounter.Value == updateInterval) {
87        updateCounter.Value = 0;
88
89        bool max = MaximizationParameter.ActualValue.Value;
90        ItemArray<T> solutions = SolutionParameter.ActualValue;
91        ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
92        bool storeHistory = StoreHistoryParameter.Value.Value;
93        int count = solutions.Length;
94
95        if (count > 1) {
96          // sort solutions by quality
97          T[] sortedSolutions = null;
98          if (max)
99            sortedSolutions = solutions
100              .Select((x, index) => new { Solution = x, Quality = qualities[index] })
101              .OrderByDescending(x => x.Quality)
102              .Select(x => x.Solution)
103              .ToArray();
104          else
105            sortedSolutions = solutions
106              .Select((x, index) => new { Solution = x, Quality = qualities[index] })
107              .OrderBy(x => x.Quality)
108              .Select(x => x.Solution)
109              .ToArray();
110
111          // calculate solution similarities
112          double[,] similarities = CalculateSimilarities(sortedSolutions);
113
114          // calculate minimum, average and maximum similarities
115          double similarity;
116          double[] minSimilarities = new double[count];
117          double[] avgSimilarities = new double[count];
118          double[] maxSimilarities = new double[count];
119          for (int i = 0; i < count; i++) {
120            minSimilarities[i] = 1;
121            avgSimilarities[i] = 0;
122            maxSimilarities[i] = 0;
123            for (int j = 0; j < count; j++) {
124              if (i != j) {
125                similarity = similarities[i, j];
126
127                if ((similarity < 0) || (similarity > 1))
128                  throw new InvalidOperationException("Solution similarities have to be in the interval [0;1].");
129
130                if (minSimilarities[i] > similarity) minSimilarities[i] = similarity;
131                avgSimilarities[i] += similarity;
132                if (maxSimilarities[i] < similarity) maxSimilarities[i] = similarity;
133              }
134            }
135            avgSimilarities[i] = avgSimilarities[i] / (count - 1);
136          }
137          double avgMinSimilarity = minSimilarities.Average();
138          double avgAvgSimilarity = avgSimilarities.Average();
139          double avgMaxSimilarity = maxSimilarities.Average();
140
141          // fetch results collection
142          ResultCollection results;
143          if (!ResultsParameter.ActualValue.ContainsKey(Name + " Results")) {
144            results = new ResultCollection();
145            ResultsParameter.ActualValue.Add(new Result(Name + " Results", results));
146          } else {
147            results = (ResultCollection)ResultsParameter.ActualValue[Name + " Results"].Value;
148          }
149
150          // store similarities
151          HeatMap similaritiesHeatMap = new HeatMap(similarities, "Solution Similarities", 0.0, 1.0);
152          if (!results.ContainsKey("Solution Similarities"))
153            results.Add(new Result("Solution Similarities", similaritiesHeatMap));
154          else
155            results["Solution Similarities"].Value = similaritiesHeatMap;
156
157          // store similarities history
158          if (storeHistory) {
159            if (!results.ContainsKey("Solution Similarities History")) {
160              HeatMapHistory history = new HeatMapHistory();
161              history.Add(similaritiesHeatMap);
162              results.Add(new Result("Solution Similarities History", history));
163            } else {
164              ((HeatMapHistory)results["Solution Similarities History"].Value).Add(similaritiesHeatMap);
165            }
166          }
167
168          // store average minimum, average and maximum similarity
169          if (!results.ContainsKey("Average Minimum Solution Similarity"))
170            results.Add(new Result("Average Minimum Solution Similarity", new DoubleValue(avgMinSimilarity)));
171          else
172            ((DoubleValue)results["Average Minimum Solution Similarity"].Value).Value = avgMinSimilarity;
173
174          if (!results.ContainsKey("Average Average Solution Similarity"))
175            results.Add(new Result("Average Average Solution Similarity", new DoubleValue(avgAvgSimilarity)));
176          else
177            ((DoubleValue)results["Average Average Solution Similarity"].Value).Value = avgAvgSimilarity;
178
179          if (!results.ContainsKey("Average Maximum Solution Similarity"))
180            results.Add(new Result("Average Maximum Solution Similarity", new DoubleValue(avgMaxSimilarity)));
181          else
182            ((DoubleValue)results["Average Maximum Solution Similarity"].Value).Value = avgMaxSimilarity;
183
184          // store average minimum, average and maximum solution similarity data table
185          DataTable minAvgMaxSimilarityDataTable;
186          if (!results.ContainsKey("Average Minimum/Average/Maximum Solution Similarity")) {
187            minAvgMaxSimilarityDataTable = new DataTable("Average Minimum/Average/Maximum Solution Similarity");
188            minAvgMaxSimilarityDataTable.VisualProperties.XAxisTitle = "Iteration";
189            minAvgMaxSimilarityDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
190            minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Minimum Solution Similarity", null));
191            minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].VisualProperties.StartIndexZero = true;
192            minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Average Solution Similarity", null));
193            minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].VisualProperties.StartIndexZero = true;
194            minAvgMaxSimilarityDataTable.Rows.Add(new DataRow("Average Maximum Solution Similarity", null));
195            minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].VisualProperties.StartIndexZero = true;
196            results.Add(new Result("Average Minimum/Average/Maximum Solution Similarity", minAvgMaxSimilarityDataTable));
197          } else {
198            minAvgMaxSimilarityDataTable = (DataTable)results["Average Minimum/Average/Maximum Solution Similarity"].Value;
199          }
200          minAvgMaxSimilarityDataTable.Rows["Average Minimum Solution Similarity"].Values.Add(avgMinSimilarity);
201          minAvgMaxSimilarityDataTable.Rows["Average Average Solution Similarity"].Values.Add(avgAvgSimilarity);
202          minAvgMaxSimilarityDataTable.Rows["Average Maximum Solution Similarity"].Values.Add(avgMaxSimilarity);
203
204          // store minimum, average, maximum similarities data table
205          DataTable minAvgMaxSimilaritiesDataTable = new DataTable("Minimum/Average/Maximum Solution Similarities");
206          minAvgMaxSimilaritiesDataTable.VisualProperties.XAxisTitle = "Solution Index";
207          minAvgMaxSimilaritiesDataTable.VisualProperties.YAxisTitle = "Solution Similarity";
208          minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Minimum Solution Similarity", null, minSimilarities));
209          minAvgMaxSimilaritiesDataTable.Rows["Minimum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
210          minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Average Solution Similarity", null, avgSimilarities));
211          minAvgMaxSimilaritiesDataTable.Rows["Average Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
212          minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Maximum Solution Similarity", null, maxSimilarities));
213          minAvgMaxSimilaritiesDataTable.Rows["Maximum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
214          if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities")) {
215            results.Add(new Result("Minimum/Average/Maximum Solution Similarities", minAvgMaxSimilaritiesDataTable));
216          } else {
217            results["Minimum/Average/Maximum Solution Similarities"].Value = minAvgMaxSimilaritiesDataTable;
218          }
219
220          // store minimum, average, maximum similarities history
221          if (storeHistory) {
222            if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities History")) {
223              DataTableHistory history = new DataTableHistory();
224              history.Add(minAvgMaxSimilaritiesDataTable);
225              results.Add(new Result("Minimum/Average/Maximum Solution Similarities History", history));
226            } else {
227              ((DataTableHistory)results["Minimum/Average/Maximum Solution Similarities History"].Value).Add(minAvgMaxSimilaritiesDataTable);
228            }
229          }
230        }
231      }
232      return base.Apply();
233    }
234
235    protected abstract double[,] CalculateSimilarities(T[] solutions);
236  }
237}
Note: See TracBrowser for help on using the repository browser.