Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ImprovingStringConvertibleMatrix/HeuristicLab.Analysis/3.3/PopulationDiversityAnalysis/PopulationDiversityAnalyzer.cs @ 9280

Last change on this file since 9280 was 8720, checked in by jkarder, 12 years ago

#1899: applied the changes suggested by ascheibe in comment:6:ticket:1899

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