Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4722 was 4722, checked in by swagner, 12 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 12.6 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
90        // sort solutions by quality
91        T[] sortedSolutions = null;
92        if (max)
93          sortedSolutions = solutions.Select((x, index) => new { Solution = x, Quality = qualities[index] }).OrderByDescending(x => x.Quality).Select(x => x.Solution).ToArray();
94        else
95          sortedSolutions = solutions.Select((x, index) => new { Solution = x, Quality = qualities[index] }).OrderBy(x => x.Quality).Select(x => x.Solution).ToArray();
96
97        // calculate solution similarities
98        double[,] similarities = CalculateSimilarities(sortedSolutions);
99
100        // calculate minimum, average and maximum similarities
101        double similarity;
102        int count = sortedSolutions.Length;
103        double[] minSimilarities = new double[sortedSolutions.Length];
104        double[] avgSimilarities = new double[sortedSolutions.Length];
105        double[] maxSimilarities = new double[sortedSolutions.Length];
106        double avgSimilarity = 0;
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              avgSimilarity += similarity;
115              if (minSimilarities[i] > similarity) minSimilarities[i] = similarity;
116              avgSimilarities[i] += similarity;
117              if (maxSimilarities[i] < similarity) maxSimilarities[i] = similarity;
118            }
119          }
120          avgSimilarities[i] = avgSimilarities[i] / (count - 1);
121        }
122        double avgMinSimilarity = minSimilarities.Average();
123        double avgAvgSimilarity = avgSimilarities.Average();
124        double avgMaxSimilarity = maxSimilarities.Average();
125        avgSimilarity = avgSimilarity / (count * count - count);
126
127        // fetch results collection
128        ResultCollection results;
129        if (!ResultsParameter.ActualValue.ContainsKey("Population Diversity Analysis Results")) {
130          results = new ResultCollection();
131          ResultsParameter.ActualValue.Add(new Result("Population Diversity Analysis Results", results));
132        } else {
133          results = (ResultCollection)ResultsParameter.ActualValue["Population Diversity Analysis Results"].Value;
134        }
135
136        // store similarities
137        HeatMap similaritiesHeatMap = new HeatMap(similarities);
138        if (!results.ContainsKey("Solution Similarities"))
139          results.Add(new Result("Solution Similarities", similaritiesHeatMap));
140        else
141          results["Solution Similarities"].Value = similaritiesHeatMap;
142
143        // store similarities history
144        if (storeHistory) {
145          if (!results.ContainsKey("Solution Similarities History")) {
146            HeatMapHistory history = new HeatMapHistory();
147            history.Add(similaritiesHeatMap);
148            results.Add(new Result("Solution Similarities History", history));
149          } else {
150            ((HeatMapHistory)results["Solution Similarities History"].Value).Add(similaritiesHeatMap);
151          }
152        }
153
154        // store average similarity
155        if (!results.ContainsKey("Average Population Similarity"))
156          results.Add(new Result("Average Population Similarity", new DoubleValue(avgSimilarity)));
157        else
158          ((DoubleValue)results["Average Population Similarity"].Value).Value = avgSimilarity;
159
160        // store average minimum, average and maximum similarity
161        if (!results.ContainsKey("Average Minimum Solution Similarity"))
162          results.Add(new Result("Average Minimum Solution Similarity", new DoubleValue(avgMinSimilarity)));
163        else
164          ((DoubleValue)results["Average Minimum Solution Similarity"].Value).Value = avgMinSimilarity;
165
166        if (!results.ContainsKey("Average Average Solution Similarity"))
167          results.Add(new Result("Average Average Solution Similarity", new DoubleValue(avgAvgSimilarity)));
168        else
169          ((DoubleValue)results["Average Average Solution Similarity"].Value).Value = avgAvgSimilarity;
170
171        if (!results.ContainsKey("Average Maximum Solution Similarity"))
172          results.Add(new Result("Average Maximum Solution Similarity", new DoubleValue(avgMaxSimilarity)));
173        else
174          ((DoubleValue)results["Average Maximum Solution Similarity"].Value).Value = avgMaxSimilarity;
175
176        // store population similarity data table
177        DataTable similarityDataTable;
178        if (!results.ContainsKey("Average Solution Similarity")) {
179          similarityDataTable = new DataTable("Average Solution Similarity");
180          results.Add(new Result("Average Solution Similarity", similarityDataTable));
181          DataRowVisualProperties visualProperties = new DataRowVisualProperties();
182          visualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Line;
183          visualProperties.StartIndexZero = true;
184          similarityDataTable.Rows.Add(new DataRow("Average Population Similarity", null, visualProperties));
185          similarityDataTable.Rows.Add(new DataRow("Average Minimum Solution Similarity", null, visualProperties));
186          similarityDataTable.Rows.Add(new DataRow("Average Average Solution Similarity", null, visualProperties));
187          similarityDataTable.Rows.Add(new DataRow("Average Maximum Solution Similarity", null, visualProperties));
188        } else {
189          similarityDataTable = (DataTable)results["Average Solution Similarity"].Value;
190        }
191        similarityDataTable.Rows["Average Population Similarity"].Values.Add(avgSimilarity);
192        similarityDataTable.Rows["Average Minimum Solution Similarity"].Values.Add(avgMinSimilarity);
193        similarityDataTable.Rows["Average Average Solution Similarity"].Values.Add(avgAvgSimilarity);
194        similarityDataTable.Rows["Average Maximum Solution Similarity"].Values.Add(avgMaxSimilarity);
195
196        // store maximum similarities
197        DataTable minAvgMaxSimilaritiesDataTable = new DataTable("Minimum/Average/Maximum Solution Similarities");
198        minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Minimum Solution Similarity"));
199        minAvgMaxSimilaritiesDataTable.Rows["Minimum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Columns;
200        minAvgMaxSimilaritiesDataTable.Rows["Minimum Solution Similarity"].Values.AddRange(minSimilarities);
201        minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Average Solution Similarity"));
202        minAvgMaxSimilaritiesDataTable.Rows["Average Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Columns;
203        minAvgMaxSimilaritiesDataTable.Rows["Average Solution Similarity"].Values.AddRange(avgSimilarities);
204        minAvgMaxSimilaritiesDataTable.Rows.Add(new DataRow("Maximum Solution Similarity"));
205        minAvgMaxSimilaritiesDataTable.Rows["Maximum Solution Similarity"].VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Columns;
206        minAvgMaxSimilaritiesDataTable.Rows["Maximum Solution Similarity"].Values.AddRange(maxSimilarities);
207        if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities")) {
208          results.Add(new Result("Minimum/Average/Maximum Solution Similarities", minAvgMaxSimilaritiesDataTable));
209        } else {
210          results["Minimum/Average/Maximum Solution Similarities"].Value = minAvgMaxSimilaritiesDataTable;
211        }
212
213        // store maximum similarities history
214        if (storeHistory) {
215          if (!results.ContainsKey("Minimum/Average/Maximum Solution Similarities History")) {
216            DataTableHistory history = new DataTableHistory();
217            history.Add(minAvgMaxSimilaritiesDataTable);
218            results.Add(new Result("Minimum/Average/Maximum Solution Similarities History", history));
219          } else {
220            ((DataTableHistory)results["Minimum/Average/Maximum Solution Similarities History"].Value).Add(minAvgMaxSimilaritiesDataTable);
221          }
222        }
223      }
224      return base.Apply();
225    }
226
227    protected abstract double[,] CalculateSimilarities(T[] solutions);
228  }
229}
Note: See TracBrowser for help on using the repository browser.