Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Analysis/3.3/PopulationDiversityAnalyzer.cs @ 12751

Last change on this file since 12751 was 4739, checked in by swagner, 14 years ago

Worked on population diversity analysis (#1188)

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