Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HLScript/HeuristicLab.Analysis/3.3/PopulationDiversityAnalysis/SingleObjectivePopulationDiversityAnalyzer.cs @ 10442

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

Updated copyright year and added some missing license headers (#1889)

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