#region License Information /* HeuristicLab * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System.Linq; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Operators; using HeuristicLab.Optimization; using HeuristicLab.Parameters; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; namespace HeuristicLab.Analysis.AlgorithmBehavior { using System.Collections.Generic; using HeuristicLab.Data; using HeuristicLab.Encodings.PermutationEncoding; using TraceMapType = HeuristicLab.Core.ItemDictionary>; /// /// An operator that analyzes schemata. /// [Item("SchemaAnalyzer", "An operator that analyzes schemata.")] [StorableClass] public sealed class SchemaAnalyzer : SingleSuccessorOperator, IAnalyzer { private const string GlobalTraceMapParameterName = "GlobalTraceMap"; private const string ResultsParameterName = "Results"; private const string PopulationGraphResultParameterName = "PopulationGraph"; private const string SchemaMatrixParameterName = "SchemaMatrix"; private const string SchemataParameterName = "Schemata"; #region IAnalyzer Members public bool EnabledByDefault { get { return true; } } #endregion #region Parameter properties public ILookupParameter GlobalTraceMapParameter { get { return (ILookupParameter)Parameters[GlobalTraceMapParameterName]; } } public ILookupParameter ResultsParameter { get { return (ILookupParameter)Parameters[ResultsParameterName]; } } #endregion #region Properties public TraceMapType GlobalTraceMap { get { return GlobalTraceMapParameter.ActualValue; } } public ResultCollection Results { get { return ResultsParameter.ActualValue; } } #endregion [StorableConstructor] private SchemaAnalyzer(bool deserializing) : base(deserializing) { } private SchemaAnalyzer(SchemaAnalyzer original, Cloner cloner) : base(original, cloner) { } public SchemaAnalyzer() : base() { Parameters.Add(new LookupParameter(GlobalTraceMapParameterName, "A global cache containing the whole genealogy.")); Parameters.Add(new LookupParameter(ResultsParameterName, "The results collection where the analysis values should are stored.")); } public override IDeepCloneable Clone(Cloner cloner) { return new SchemaAnalyzer(this, cloner); } public override IOperation Apply() { var graph = (GenealogyGraph)Results[PopulationGraphResultParameterName].Value; var generationZero = graph.Values.Where(x => x.Rank == 0); // extract all subtours for each individual in generation zero var subtours = new Dictionary>(); foreach (var individual in generationZero) { subtours[(Permutation)individual.Data] = ExtractSubtours((Permutation)individual.Data); } // process all schemata var schemataMatrix = new Dictionary(new SchemaEqualityComparer()); foreach (var entry in subtours) { foreach (var schema in entry.Value) { if (!schemataMatrix.ContainsKey(schema)) { schemataMatrix.Add(schema, ExploreGlobalSchemaOccurrence(graph, schema)); } } } // order schemas according to their global occurrence count var sortedSchemataMatrix = schemataMatrix.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value); IList rowNames = new List(); var schemataStringMatrix = new StringMatrix(sortedSchemataMatrix.Keys.Count, 1); for (int i = 0; i < sortedSchemataMatrix.Keys.Count; i++) { var element = sortedSchemataMatrix.ElementAt(i); rowNames.Add(new Permutation(PermutationTypes.RelativeUndirected, element.Key).ToString()); schemataStringMatrix[i, 0] = element.Value.ToString(); } schemataStringMatrix.RowNames = rowNames; schemataStringMatrix.ColumnNames = new[] { "GlobalSchemaOccurrence" }; Results.Add(new Result(SchemataParameterName, new ItemArray(schemataMatrix.Keys))); Results.Add(new Result(SchemaMatrixParameterName, schemataStringMatrix)); return base.Apply(); } private int ExploreGlobalSchemaOccurrence(GenealogyGraph graph, IntArray schema) { int occurrences = 0; foreach (var individual in graph.Values) if (IsSubtour(schema, (Permutation)individual.Data)) occurrences++; return occurrences; } private ItemArray ExtractSubtours(Permutation permutation) { var subtours = new List(); for (int i = 2; i <= permutation.Count() / 2; i++) { // increase schema length from 2 to n/2 for (int j = 0; j < permutation.Count(); j++) { // visit all positions in the permutation var schema = new IntArray(i); for (int k = 0; k < i; k++) schema[k] = permutation[(j + k) % permutation.Length]; // copy edge to schema subtours.Add(schema); } } return new ItemArray(subtours); } private bool IsSubtour(IntArray tour, Permutation permutation) { // determine starting position for subtour match int idx = permutation.Select((x, index) => new { Value = x, Index = index }).Single(x => x.Value == tour[0]).Index; bool isSubtour = true; for (int i = 1; i < tour.Length; i++) { if (tour[i] == permutation[(idx + 1) % permutation.Length]) { // check right side idx = (idx + 1) % permutation.Length; } else if (tour[i] == permutation[(idx - 1 + permutation.Length) % permutation.Length]) { // check left side idx = (idx - 1 + permutation.Length) % permutation.Length; } else { isSubtour = false; break; } } return isSubtour; } private class SchemaEqualityComparer : EqualityComparer { public override bool Equals(IntArray x, IntArray y) { if (object.ReferenceEquals(x, y)) return true; if (x == null || y == null || x.Length != y.Length) return false; bool match = true; for (int i = 0; i < x.Length && match; i++) // check normal tour if (x[i] != y[i]) match = false; if (!match) { match = true; for (int i = x.Length - 1; i >= 0 && match; i--) // check inverse tour if (x[i] != y[i]) match = false; } return match; } public override int GetHashCode(IntArray obj) { return 0; // return the same hash code for each object, otherwise Equals will not be called } } } }