Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Analysis.AlgorithmBehavior/HeuristicLab.Analysis.AlgorithmBehavior/3.3/Analyzers/SchemaAnalyzer.cs @ 8216

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

#1886:

  • added SchemaAnalyzer
  • added BrokenInteritanceSchemaAnalyzer
File size: 7.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.Linq;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Operators;
26using HeuristicLab.Optimization;
27using HeuristicLab.Parameters;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Analysis.AlgorithmBehavior {
31  using System.Collections.Generic;
32  using HeuristicLab.Data;
33  using HeuristicLab.Encodings.PermutationEncoding;
34  using TraceMapType = HeuristicLab.Core.ItemDictionary<HeuristicLab.Core.IItem, HeuristicLab.Core.IItemList<HeuristicLab.Core.IItem>>;
35
36  /// <summary>
37  /// An operator that analyzes schemata.
38  /// </summary>
39  [Item("SchemaAnalyzer", "An operator that analyzes schemata.")]
40  [StorableClass]
41  public sealed class SchemaAnalyzer : SingleSuccessorOperator, IAnalyzer {
42    private const string GlobalTraceMapParameterName = "GlobalTraceMap";
43    private const string ResultsParameterName = "Results";
44    private const string PopulationGraphResultParameterName = "PopulationGraph";
45    private const string SchemaMatrixParameterName = "SchemaMatrix";
46    private const string SchemataParameterName = "Schemata";
47
48    #region IAnalyzer Members
49    public bool EnabledByDefault {
50      get { return true; }
51    }
52    #endregion
53
54    #region Parameter properties
55    public ILookupParameter<TraceMapType> GlobalTraceMapParameter {
56      get { return (ILookupParameter<TraceMapType>)Parameters[GlobalTraceMapParameterName]; }
57    }
58    public ILookupParameter<ResultCollection> ResultsParameter {
59      get { return (ILookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
60    }
61    #endregion
62
63    #region Properties
64    public TraceMapType GlobalTraceMap {
65      get { return GlobalTraceMapParameter.ActualValue; }
66    }
67    public ResultCollection Results {
68      get { return ResultsParameter.ActualValue; }
69    }
70    #endregion
71
72    [StorableConstructor]
73    private SchemaAnalyzer(bool deserializing) : base(deserializing) { }
74    private SchemaAnalyzer(SchemaAnalyzer original, Cloner cloner) : base(original, cloner) { }
75    public SchemaAnalyzer()
76      : base() {
77      Parameters.Add(new LookupParameter<TraceMapType>(GlobalTraceMapParameterName, "A global cache containing the whole genealogy."));
78      Parameters.Add(new LookupParameter<ResultCollection>(ResultsParameterName, "The results collection where the analysis values should are stored."));
79    }
80
81    public override IDeepCloneable Clone(Cloner cloner) {
82      return new SchemaAnalyzer(this, cloner);
83    }
84
85    public override IOperation Apply() {
86      var graph = (GenealogyGraph<Permutation>)Results[PopulationGraphResultParameterName].Value;
87      var generationZero = graph.Values.Where(x => x.Rank == 0);
88
89      // extract all subtours for each individual in generation zero
90      var subtours = new Dictionary<Permutation, ItemArray<IntArray>>();
91      foreach (var individual in generationZero) {
92        subtours[(Permutation)individual.Data] = ExtractSubtours((Permutation)individual.Data);
93      }
94
95      // process all schemata
96      var schemataMatrix = new Dictionary<IntArray, int>(new SchemaEqualityComparer());
97      foreach (var entry in subtours) {
98        foreach (var schema in entry.Value) {
99          if (!schemataMatrix.ContainsKey(schema)) {
100            schemataMatrix.Add(schema, ExploreGlobalSchemaOccurrence(graph, schema));
101          }
102        }
103      }
104
105      // order schemas according to their global occurrence count
106      var sortedSchemataMatrix = schemataMatrix.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
107      IList<string> rowNames = new List<string>();
108      var schemataStringMatrix = new StringMatrix(sortedSchemataMatrix.Keys.Count, 1);
109      for (int i = 0; i < sortedSchemataMatrix.Keys.Count; i++) {
110        var element = sortedSchemataMatrix.ElementAt(i);
111        rowNames.Add(new Permutation(PermutationTypes.RelativeUndirected, element.Key).ToString());
112        schemataStringMatrix[i, 0] = element.Value.ToString();
113      }
114      schemataStringMatrix.RowNames = rowNames;
115      schemataStringMatrix.ColumnNames = new[] { "GlobalSchemaOccurrence" };
116
117      Results.Add(new Result(SchemataParameterName, new ItemArray<IntArray>(schemataMatrix.Keys)));
118      Results.Add(new Result(SchemaMatrixParameterName, schemataStringMatrix));
119
120      return base.Apply();
121    }
122
123    private int ExploreGlobalSchemaOccurrence(GenealogyGraph<Permutation> graph, IntArray schema) {
124      int occurrences = 0;
125      foreach (var individual in graph.Values)
126        if (IsSubtour(schema, (Permutation)individual.Data)) occurrences++;
127      return occurrences;
128    }
129
130    private ItemArray<IntArray> ExtractSubtours(Permutation permutation) {
131      var subtours = new List<IntArray>();
132      for (int i = 2; i <= permutation.Count() / 2; i++) { // increase schema length from 2 to n/2
133        for (int j = 0; j < permutation.Count(); j++) { // visit all positions in the permutation
134          var schema = new IntArray(i);
135          for (int k = 0; k < i; k++) schema[k] = permutation[(j + k) % permutation.Length]; // copy edge to schema
136          subtours.Add(schema);
137        }
138      }
139      return new ItemArray<IntArray>(subtours);
140    }
141
142    private bool IsSubtour(IntArray tour, Permutation permutation) {
143      // determine starting position for subtour match
144      int idx = permutation.Select((x, index) => new { Value = x, Index = index }).Single(x => x.Value == tour[0]).Index;
145      bool isSubtour = true;
146      for (int i = 1; i < tour.Length; i++) {
147        if (tour[i] == permutation[(idx + 1) % permutation.Length]) { // check right side
148          idx = (idx + 1) % permutation.Length;
149        } else if (tour[i] == permutation[(idx - 1 + permutation.Length) % permutation.Length]) { // check left side
150          idx = (idx - 1 + permutation.Length) % permutation.Length;
151        } else {
152          isSubtour = false;
153          break;
154        }
155      }
156      return isSubtour;
157    }
158
159    private class SchemaEqualityComparer : EqualityComparer<IntArray> {
160      public override bool Equals(IntArray x, IntArray y) {
161        if (object.ReferenceEquals(x, y)) return true;
162        if (x == null || y == null || x.Length != y.Length) return false;
163        bool match = true;
164        for (int i = 0; i < x.Length && match; i++) // check normal tour
165          if (x[i] != y[i]) match = false;
166        if (!match) {
167          match = true;
168          for (int i = x.Length - 1; i >= 0 && match; i--) // check inverse tour
169            if (x[i] != y[i]) match = false;
170        }
171        return match;
172      }
173
174      public override int GetHashCode(IntArray obj) {
175        return 0; // return the same hash code for each object, otherwise Equals will not be called
176      }
177    }
178  }
179}
Note: See TracBrowser for help on using the repository browser.