Free cookie consent management tool by TermsFeed Policy Generator

source: branches/histogram/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs @ 6087

Last change on this file since 6087 was 6086, checked in by abeham, 13 years ago

#1497

  • Added problem-specific local improvement operator (best improvement local search using swap2 moves)
    • Adapted ExhaustiveSwap2MoveGenerator to yield moves
  • Added a parameter BestKnownSolutions to collect possible optimal invariants
    • Adapted BestQAPSolutionAnalyzer to collect optimal invariants
  • Added a function to the QAP Evaluator that calculates the impact of a certain allele
File size: 21.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Collections.Generic;
24using System.Drawing;
25using System.IO;
26using System.Linq;
27using System.Reflection;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Encodings.PermutationEncoding;
32using HeuristicLab.Optimization;
33using HeuristicLab.Parameters;
34using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
35using HeuristicLab.PluginInfrastructure;
36
37namespace HeuristicLab.Problems.QuadraticAssignment {
38  [Item("Quadratic Assignment Problem", "The Quadratic Assignment Problem (QAP) can be described as the problem of assigning N facilities to N fixed locations such that there is exactly one facility in each location and that the sum of the distances multiplied by the connection strength between the facilities becomes minimal.")]
39  [Creatable("Problems")]
40  [StorableClass]
41  public sealed class QuadraticAssignmentProblem : SingleObjectiveHeuristicOptimizationProblem<IQAPEvaluator, IPermutationCreator>, IStorableContent {
42    private static string InstancePrefix = "HeuristicLab.Problems.QuadraticAssignment.Data.";
43
44    public string Filename { get; set; }
45
46    public override Image ItemImage {
47      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
48    }
49
50    #region Parameter Properties
51    public IValueParameter<ItemList<Permutation>> BestKnownSolutionsParameter {
52      get { return (IValueParameter<ItemList<Permutation>>)Parameters["BestKnownSolutions"]; }
53    }
54    public IValueParameter<Permutation> BestKnownSolutionParameter {
55      get { return (IValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
56    }
57    public IValueParameter<DoubleMatrix> WeightsParameter {
58      get { return (IValueParameter<DoubleMatrix>)Parameters["Weights"]; }
59    }
60    public IValueParameter<DoubleMatrix> DistancesParameter {
61      get { return (IValueParameter<DoubleMatrix>)Parameters["Distances"]; }
62    }
63    #endregion
64
65    #region Properties
66    public ItemList<Permutation> BestKnownSolutions {
67      get { return BestKnownSolutionsParameter.Value; }
68      set { BestKnownSolutionsParameter.Value = value; }
69    }
70    public Permutation BestKnownSolution {
71      get { return BestKnownSolutionParameter.Value; }
72      set { BestKnownSolutionParameter.Value = value; }
73    }
74    public DoubleMatrix Weights {
75      get { return WeightsParameter.Value; }
76      set { WeightsParameter.Value = value; }
77    }
78    public DoubleMatrix Distances {
79      get { return DistancesParameter.Value; }
80      set { DistancesParameter.Value = value; }
81    }
82
83    public IEnumerable<string> EmbeddedInstances {
84      get {
85        return Assembly.GetExecutingAssembly()
86          .GetManifestResourceNames()
87          .Where(x => x.EndsWith(".dat"))
88          .OrderBy(x => x)
89          .Select(x => x.Replace(".dat", String.Empty))
90          .Select(x => x.Replace(InstancePrefix, String.Empty));
91      }
92    }
93
94    private BestQAPSolutionAnalyzer BestQAPSolutionAnalyzer {
95      get { return Operators.OfType<BestQAPSolutionAnalyzer>().FirstOrDefault(); }
96    }
97
98    private QAPAlleleFrequencyAnalyzer QAPAlleleFrequencyAnalyzer {
99      get { return Operators.OfType<QAPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
100    }
101
102    private QAPPopulationDiversityAnalyzer QAPPopulationDiversityAnalyzer {
103      get { return Operators.OfType<QAPPopulationDiversityAnalyzer>().FirstOrDefault(); }
104    }
105    #endregion
106
107    [StorableConstructor]
108    private QuadraticAssignmentProblem(bool deserializing) : base(deserializing) { }
109    private QuadraticAssignmentProblem(QuadraticAssignmentProblem original, Cloner cloner)
110      : base(original, cloner) {
111      AttachEventHandlers();
112    }
113    public QuadraticAssignmentProblem()
114      : base(new QAPEvaluator(), new RandomPermutationCreator()) {
115      Parameters.Add(new OptionalValueParameter<ItemList<Permutation>>("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
116      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
117      Parameters.Add(new ValueParameter<DoubleMatrix>("Weights", "The strength of the connection between the facilities.", new DoubleMatrix(5, 5)));
118      Parameters.Add(new ValueParameter<DoubleMatrix>("Distances", "The distance matrix which can either be specified directly without the coordinates, or can be calculated automatically from the coordinates.", new DoubleMatrix(5, 5)));
119
120      Maximization = new BoolValue(false);
121
122      Weights = new DoubleMatrix(new double[,] {
123        { 0, 1, 0, 0, 1 },
124        { 1, 0, 1, 0, 0 },
125        { 0, 1, 0, 1, 0 },
126        { 0, 0, 1, 0, 1 },
127        { 1, 0, 0, 1, 0 }
128      });
129
130      Distances = new DoubleMatrix(new double[,] {
131        {   0, 360, 582, 582, 360 },
132        { 360,   0, 360, 582, 582 },
133        { 582, 360,   0, 360, 582 },
134        { 582, 582, 360,   0, 360 },
135        { 360, 582, 582, 360,   0 }
136      });
137
138      SolutionCreator.PermutationParameter.ActualName = "Assignment";
139      ParameterizeSolutionCreator();
140      ParameterizeEvaluator();
141
142      InitializeOperators();
143      AttachEventHandlers();
144    }
145
146    public override IDeepCloneable Clone(Cloner cloner) {
147      return new QuadraticAssignmentProblem(this, cloner);
148    }
149
150    [StorableHook(HookType.AfterDeserialization)]
151    private void AfterDeserialization() {
152      // BackwardsCompatibility3.3
153      #region Backwards compatible code, remove with 3.4
154      /*if (Parameters.ContainsKey("BestKnownSolution")) {
155        Permutation solution = ((IValueParameter<Permutation>)Parameters["BestKnownSolution"]).Value;
156        Parameters.Remove("BestKnownSolution");
157        Parameters.Add(new OptionalValueParameter<ItemList<Permutation>>("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
158        if (solution != null) {
159          BestKnownSolutions = new ItemList<Permutation>();
160          BestKnownSolutions.Add(solution);
161        }
162      }*/
163      if (!Parameters.ContainsKey("BestKnownSolutions")) {
164        Parameters.Add(new OptionalValueParameter<ItemList<Permutation>>("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
165      }
166      #endregion
167    }
168
169    #region Events
170    protected override void OnSolutionCreatorChanged() {
171      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
172      ParameterizeSolutionCreator();
173      ParameterizeEvaluator();
174      ParameterizeAnalyzers();
175      ParameterizeOperators();
176      base.OnSolutionCreatorChanged();
177    }
178    protected override void OnEvaluatorChanged() {
179      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
180      ParameterizeEvaluator();
181      ParameterizeAnalyzers();
182      ParameterizeOperators();
183      base.OnEvaluatorChanged();
184    }
185
186    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
187      ParameterizeEvaluator();
188      ParameterizeAnalyzers();
189      ParameterizeOperators();
190    }
191    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
192      ParameterizeAnalyzers();
193      ParameterizeOperators();
194    }
195    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
196      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
197      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
198      ParameterizeSolutionCreator();
199      ParameterizeEvaluator();
200      ParameterizeOperators();
201      AdjustDistanceMatrix();
202    }
203    private void Weights_RowsChanged(object sender, EventArgs e) {
204      if (Weights.Rows != Weights.Columns)
205        ((IStringConvertibleMatrix)Weights).Columns = Weights.Rows;
206      else {
207        ParameterizeSolutionCreator();
208        ParameterizeEvaluator();
209        ParameterizeOperators();
210        AdjustDistanceMatrix();
211      }
212    }
213    private void Weights_ColumnsChanged(object sender, EventArgs e) {
214      if (Weights.Rows != Weights.Columns)
215        ((IStringConvertibleMatrix)Weights).Rows = Weights.Columns;
216      else {
217        ParameterizeSolutionCreator();
218        ParameterizeEvaluator();
219        ParameterizeOperators();
220        AdjustDistanceMatrix();
221      }
222    }
223    private void DistancesParameter_ValueChanged(object sender, EventArgs e) {
224      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
225      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
226      ParameterizeSolutionCreator();
227      ParameterizeEvaluator();
228      ParameterizeOperators();
229      AdjustWeightsMatrix();
230    }
231    private void Distances_RowsChanged(object sender, EventArgs e) {
232      if (Distances.Rows != Distances.Columns)
233        ((IStringConvertibleMatrix)Distances).Columns = Distances.Rows;
234      else {
235        ParameterizeSolutionCreator();
236        ParameterizeEvaluator();
237        ParameterizeOperators();
238        AdjustWeightsMatrix();
239      }
240    }
241    private void Distances_ColumnsChanged(object sender, EventArgs e) {
242      if (Distances.Rows != Distances.Columns)
243        ((IStringConvertibleMatrix)Distances).Rows = Distances.Columns;
244      else {
245        ParameterizeSolutionCreator();
246        ParameterizeEvaluator();
247        ParameterizeOperators();
248        AdjustWeightsMatrix();
249      }
250    }
251    #endregion
252
253    #region Helpers
254    [StorableHook(HookType.AfterDeserialization)]
255    private void AfterDeserializationHook() {
256      AttachEventHandlers();
257    }
258
259    private void AttachEventHandlers() {
260      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
261      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
262      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
263      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
264      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
265      DistancesParameter.ValueChanged += new EventHandler(DistancesParameter_ValueChanged);
266      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
267      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
268    }
269
270    private void InitializeOperators() {
271      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
272      Operators.Add(new BestQAPSolutionAnalyzer());
273      Operators.Add(new QAPAlleleFrequencyAnalyzer());
274      Operators.Add(new QAPPopulationDiversityAnalyzer());
275      Operators.Add(new QAPExhaustiveSwap2LocalImprovement());
276      ParameterizeAnalyzers();
277      ParameterizeOperators();
278    }
279    private void ParameterizeSolutionCreator() {
280      if (SolutionCreator != null) {
281        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
282        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
283      }
284    }
285    private void ParameterizeEvaluator() {
286      if (Evaluator != null) {
287        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
288        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
289        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
290      }
291    }
292    private void ParameterizeAnalyzers() {
293      if (BestQAPSolutionAnalyzer != null) {
294        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
295        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
296        BestQAPSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
297        BestQAPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
298        BestQAPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
299        BestQAPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
300        BestQAPSolutionAnalyzer.BestKnownSolutionsParameter.ActualName = BestKnownSolutionsParameter.Name;
301        BestQAPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
302      }
303      if (QAPAlleleFrequencyAnalyzer != null) {
304        QAPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
305        QAPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
306        QAPAlleleFrequencyAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
307        QAPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
308        QAPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
309        QAPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
310        QAPAlleleFrequencyAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
311      }
312      if (QAPPopulationDiversityAnalyzer != null) {
313        QAPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
314        QAPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
315        QAPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
316        QAPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
317      }
318    }
319    private void ParameterizeOperators() {
320      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
321        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
322        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
323      }
324      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
325        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
326      }
327      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
328        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
329      }
330      if (Operators.OfType<IMoveGenerator>().Any()) {
331        string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
332        foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
333          op.InversionMoveParameter.ActualName = inversionMove;
334        string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
335        foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
336          op.TranslocationMoveParameter.ActualName = translocationMove;
337        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
338        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
339          op.Swap2MoveParameter.ActualName = swapMove;
340        }
341      }
342      foreach (var op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>())
343        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
344
345      QAPExhaustiveSwap2LocalImprovement localOpt = Operators.OfType<QAPExhaustiveSwap2LocalImprovement>().SingleOrDefault();
346      if (localOpt != null) {
347        localOpt.AssignmentParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
348        localOpt.DistancesParameter.ActualName = DistancesParameter.Name;
349        localOpt.MaximizationParameter.ActualName = MaximizationParameter.Name;
350        localOpt.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
351        localOpt.WeightsParameter.ActualName = WeightsParameter.Name;
352      }
353    }
354
355    private void AdjustDistanceMatrix() {
356      if (Distances.Rows != Weights.Rows || Distances.Columns != Weights.Columns) {
357        ((IStringConvertibleMatrix)Distances).Rows = Weights.Rows;
358      }
359    }
360
361    private void AdjustWeightsMatrix() {
362      if (Weights.Rows != Distances.Rows || Weights.Columns != Distances.Columns) {
363        ((IStringConvertibleMatrix)Weights).Rows = Distances.Rows;
364      }
365    }
366    #endregion
367
368    public void ImportFileInstance(string filename) {
369      QAPLIBParser parser = new QAPLIBParser();
370      parser.Parse(filename);
371      if (parser.Error != null) throw parser.Error;
372      Distances = new DoubleMatrix(parser.Distances);
373      Weights = new DoubleMatrix(parser.Weights);
374      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(filename) + ")";
375      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
376      BestKnownQuality = null;
377      BestKnownSolutions = null;
378      OnReset();
379    }
380
381    public void LoadEmbeddedInstance(string instance) {
382      using (Stream stream = Assembly.GetExecutingAssembly()
383        .GetManifestResourceStream(InstancePrefix + instance + ".dat")) {
384        QAPLIBParser parser = new QAPLIBParser();
385        parser.Parse(stream);
386        if (parser.Error != null) throw parser.Error;
387        Distances = new DoubleMatrix(parser.Distances);
388        Weights = new DoubleMatrix(parser.Weights);
389        Name = "Quadratic Assignment Problem (loaded instance " + instance + ")";
390        Description = "Loaded embedded problem data of instance " + instance + ".";
391        OnReset();
392      }
393      bool solutionExists = Assembly.GetExecutingAssembly()
394          .GetManifestResourceNames()
395          .Where(x => x.EndsWith(instance + ".sln"))
396          .Any();
397      if (solutionExists) {
398        using (Stream solStream = Assembly.GetExecutingAssembly()
399          .GetManifestResourceStream(InstancePrefix + instance + ".sln")) {
400          QAPLIBSolutionParser solParser = new QAPLIBSolutionParser();
401          solParser.Parse(solStream, true); // most sln's seem to be of the type index = "facility" => value = "location"
402          if (solParser.Error != null) throw solParser.Error;
403          if (!solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
404            solStream.Seek(0, SeekOrigin.Begin);
405            solParser.Reset();
406            solParser.Parse(solStream, false); // some sln's seem to be of the type index = "location" => value = "facility"
407            if (solParser.Error != null) throw solParser.Error;
408            if (solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
409              BestKnownQuality = new DoubleValue(solParser.Quality);
410              BestKnownSolutions = new ItemList<Permutation>(new Permutation[] { new Permutation(PermutationTypes.Absolute, solParser.Assignment) });
411              BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
412            } else {
413              BestKnownQuality = new DoubleValue(solParser.Quality);
414              BestKnownSolutions = null;
415              BestKnownSolution = null;
416            }
417          } else {
418            BestKnownQuality = new DoubleValue(solParser.Quality);
419            BestKnownSolutions = new ItemList<Permutation>(new Permutation[] { new Permutation(PermutationTypes.Absolute, solParser.Assignment) });
420            BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
421          }
422        }
423      } else {
424        BestKnownQuality = null;
425        BestKnownSolutions = null;
426        BestKnownSolution = null;
427      }
428    }
429  }
430}
Note: See TracBrowser for help on using the repository browser.