source: branches/HeuristicLab.DiversityAnalysis/HeuristicLab.Problems.TravelingSalesman/3.3/Analyzers/TSPPopulationDiversityAnalyzer.cs @ 4432

Last change on this file since 4432 was 4432, checked in by swinkler, 10 years ago

Worked on population diversity analyzer for TSP. (#1188)

File size: 9.0 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;
23using System.Linq;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Encodings.PermutationEncoding;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.TravelingSalesman {
33  /// <summary>
34  /// An operator for analyzing the diversity of a population of solutions for a Traveling Salesman Problems given in path representation using city coordinates.
35  /// </summary>
36  [Item("TSPPopulationDiversityAnalyzer", "An operator for analyzing the diversity of a population of solutions for a Traveling Salesman Problems given in path representation using city coordinates.")]
37  [StorableClass]
38  public sealed class TSPPopulationDiversityAnalyzer : SingleSuccessorOperator, IAnalyzer {
39
40    // TODO:
41    // - iterations sampling
42    // - view
43
44    public ScopeTreeLookupParameter<Permutation> PermutationParameter {
45      get { return (ScopeTreeLookupParameter<Permutation>)Parameters["Permutation"]; }
46    }
47    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
48      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
49    }
50    public ValueParameter<BoolValue> StoreCompleteHistoryParameter {
51      get { return (ValueParameter<BoolValue>)Parameters["StoreCompleteHistory"]; }
52    }
53    public ValueParameter<ItemList<DoubleMatrix>> SimilaritiesParameter {
54      get { return (ValueParameter<ItemList<DoubleMatrix>>)Parameters["Similarities"]; }
55    }
56    public ValueParameter<ItemList<DoubleArray>> MaximumSimilaritiesParameter {
57      get { return (ValueParameter<ItemList<DoubleArray>>)Parameters["MaximumSimilarities"]; }
58    }
59    public ValueParameter<ItemList<DoubleValue>> AverageMaximumSimilaritiesParameter {
60      get { return (ValueParameter<ItemList<DoubleValue>>)Parameters["AverageMaximumSimilarities"]; }
61    }
62    public ValueParameter<ItemList<DoubleValue>> AverageSimilaritiesParameter {
63      get { return (ValueParameter<ItemList<DoubleValue>>)Parameters["AverageSimilarities"]; }
64    }
65
66    public TSPPopulationDiversityAnalyzer()
67      : base() {
68      Parameters.Add(new ScopeTreeLookupParameter<Permutation>("Permutation", "The TSP solutions given in path representation from which the best solution should be analyzed."));
69      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the TSP solutions which should be analyzed."));
70      Parameters.Add(new ValueParameter<BoolValue>("StoreCompleteHistory", "Flag that denotes whether the complete history of similarity values shall be stored.", new BoolValue(true)));
71      Parameters.Add(new ValueParameter<ItemList<DoubleMatrix>>("Similarities", "The similarities of the TSP solutions which should be analyzed."));
72      Parameters.Add(new ValueParameter<ItemList<DoubleArray>>("MaximumSimilarities", "The maximum similarities of the TSP solutions which should be analyzed."));
73      Parameters.Add(new ValueParameter<ItemList<DoubleValue>>("AverageMaximumSimilarities", "The average maximum similarities of the TSP solutions which should be analyzed."));
74      Parameters.Add(new ValueParameter<ItemList<DoubleValue>>("AverageSimilarities", "The average similarities of the TSP solutions which should be analyzed."));
75    }
76
77    public override IOperation Apply() {
78
79      #region testing
80      /*
81      Permutation permutationA = new Permutation(PermutationTypes.Absolute, new int[] { 0, 5, 4, 3, 2, 1 });
82      Permutation permutationB = new Permutation(PermutationTypes.Absolute, new int[] { 0, 3, 2, 4, 5, 1 });
83      Permutation permutationC = new Permutation(PermutationTypes.Absolute, new int[] { 3, 2, 4, 5, 1, 0 });
84      Permutation permutationD = new Permutation(PermutationTypes.Absolute, new int[] { 3, 2, 4, 5, 0, 1 });
85      int[] edgesA = CalculateEdgesVector(permutationA);
86      int[] edgesB = CalculateEdgesVector(permutationB);
87      int[] edgesC = CalculateEdgesVector(permutationC);
88      int[] edgesD = CalculateEdgesVector(permutationD);
89      double s = CalculateSimilarity(edgesA, edgesB);
90      s = CalculateSimilarity(edgesA, edgesA);
91      s = CalculateSimilarity(edgesB, edgesB);
92      s = CalculateSimilarity(edgesC, edgesC);
93      s = CalculateSimilarity(edgesD, edgesD);
94      s = CalculateSimilarity(edgesB, edgesC);
95      s = CalculateSimilarity(edgesC, edgesD);
96      */
97      #endregion
98
99      ItemArray<Permutation> permutations = PermutationParameter.ActualValue;
100      ItemArray<DoubleValue> qualities = QualityParameter.ActualValue;
101      Permutation[] permutationsArray = permutations.ToArray();
102      DoubleValue[] qualitiesArray = qualities.ToArray();
103      int cities = permutationsArray.Length;
104      #region sort permutations array
105      for (int i = 0; i < cities; i++) {
106        int minIndex = i;
107        for (int j = i + 1; j < cities; j++) {
108          if (qualitiesArray[j].Value < qualitiesArray[minIndex].Value)
109            minIndex = j;
110        }
111        if (minIndex != i) {
112          Permutation p = permutationsArray[i];
113          permutationsArray[i] = permutationsArray[minIndex];
114          permutationsArray[minIndex] = p;
115          DoubleValue d = qualitiesArray[i];
116          qualitiesArray[i] = qualitiesArray[minIndex];
117          qualitiesArray[minIndex] = d;
118        }
119      }
120      #endregion
121
122      int[][] edges = new int[cities][];
123      for (int i = 0; i < cities; i++)
124        edges[i] = CalculateEdgesVector(permutationsArray[i]);
125
126      DoubleMatrix similarities = new DoubleMatrix(cities, cities);
127      DoubleArray maxSimilarities = new DoubleArray(cities);
128      double avgSimilarity = 0;
129      int n = 0;
130      for (int i = 0; i < cities; i++) {
131        similarities[i, i] = 1;
132        for (int j = (i + 1); j < cities; j++) {
133          double similarity = CalculateSimilarity(edges[i], edges[j]);
134          avgSimilarity += similarity;
135          n++;
136          similarities[i, j] = similarity;
137          similarities[j, i] = similarity;
138          if (maxSimilarities[i] < similarity)
139            maxSimilarities[i] = similarity;
140          if (maxSimilarities[j] < similarity)
141            maxSimilarities[j] = similarity;
142        }
143      }
144      DoubleValue averageMaximumSimilarity = new DoubleValue(maxSimilarities.Average());
145      DoubleValue averageSimilarity = new DoubleValue(avgSimilarity / n);
146
147      if (SimilaritiesParameter.Value == null) {
148        SimilaritiesParameter.Value = new ItemList<DoubleMatrix>();
149        MaximumSimilaritiesParameter.Value = new ItemList<DoubleArray>();
150        AverageMaximumSimilaritiesParameter.Value = new ItemList<DoubleValue>();
151        AverageSimilaritiesParameter.Value = new ItemList<DoubleValue>();
152      }
153      if (!StoreCompleteHistoryParameter.Value.Value && SimilaritiesParameter.Value.Count > 0) {
154        SimilaritiesParameter.Value[SimilaritiesParameter.Value.Count - 1] = null;
155        MaximumSimilaritiesParameter.Value[MaximumSimilaritiesParameter.Value.Count - 1] = null;
156      }
157      SimilaritiesParameter.Value.Add(similarities);
158      MaximumSimilaritiesParameter.Value.Add(maxSimilarities);
159      AverageMaximumSimilaritiesParameter.Value.Add(averageMaximumSimilarity);
160      AverageSimilaritiesParameter.Value.Add(averageSimilarity);
161
162      return base.Apply();
163    }
164
165    private static int[] CalculateEdgesVector(Permutation permutation) {
166      int cities = permutation.Length;
167      int[] edgesVector = new int[cities];
168      for (int i = 0; i < (cities - 1); i++)
169        edgesVector[permutation[i]] = permutation[i + 1];
170      edgesVector[permutation[cities - 1]] = permutation[0];
171      return edgesVector;
172    }
173
174    private double CalculateSimilarity(int[] edgesA, int[] edgesB) {
175      if (edgesA.Length != edgesB.Length)
176        throw new InvalidOperationException("ERROR in " + Name + ": Similarity can only be calculated between instances of an equal number of cities");
177      int cities = edgesA.Length;
178      int similarEdges = 0;
179      for (int i = 0; i < edgesA.Length; i++) {
180        if (edgesA[i] == edgesB[i] || edgesA[edgesB[i]] == i)
181          similarEdges++;
182      }
183      return (double)(similarEdges) / cities;
184    }
185
186  }
187}
Note: See TracBrowser for help on using the repository browser.