Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs @ 6875

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

#1619

  • Moved QAPLIB files from the problem plugin to the test plugin
  • Updated unit test
  • Moved service reference to the problem plugin (from the views plugin)
  • Created a simple test list for our most common tests
File size: 21.7 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.Drawing;
24using System.IO;
25using System.Linq;
26using System.Reflection;
27using HeuristicLab.Collections;
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<ItemSet<Permutation>> BestKnownSolutionsParameter {
52      get { return (IValueParameter<ItemSet<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 ItemSet<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    private BestQAPSolutionAnalyzer BestQAPSolutionAnalyzer {
84      get { return Operators.OfType<BestQAPSolutionAnalyzer>().FirstOrDefault(); }
85    }
86
87    private QAPAlleleFrequencyAnalyzer QAPAlleleFrequencyAnalyzer {
88      get { return Operators.OfType<QAPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
89    }
90
91    private QAPPopulationDiversityAnalyzer QAPPopulationDiversityAnalyzer {
92      get { return Operators.OfType<QAPPopulationDiversityAnalyzer>().FirstOrDefault(); }
93    }
94
95    private ObservableList<string> instances = new ObservableList<string>();
96    public ObservableList<string> Instances {
97      get { return instances; }
98    }
99    #endregion
100
101    [StorableConstructor]
102    private QuadraticAssignmentProblem(bool deserializing) : base(deserializing) { }
103    private QuadraticAssignmentProblem(QuadraticAssignmentProblem original, Cloner cloner)
104      : base(original, cloner) {
105      instances = new ObservableList<string>(original.instances);
106      AttachEventHandlers();
107    }
108    public QuadraticAssignmentProblem()
109      : base(new QAPEvaluator(), new RandomPermutationCreator()) {
110      Parameters.Add(new OptionalValueParameter<ItemSet<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));
111      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));
112      Parameters.Add(new ValueParameter<DoubleMatrix>("Weights", "The strength of the connection between the facilities.", new DoubleMatrix(5, 5)));
113      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)));
114
115      Maximization = new BoolValue(false);
116
117      Weights = new DoubleMatrix(new double[,] {
118        { 0, 1, 0, 0, 1 },
119        { 1, 0, 1, 0, 0 },
120        { 0, 1, 0, 1, 0 },
121        { 0, 0, 1, 0, 1 },
122        { 1, 0, 0, 1, 0 }
123      });
124
125      Distances = new DoubleMatrix(new double[,] {
126        {   0, 360, 582, 582, 360 },
127        { 360,   0, 360, 582, 582 },
128        { 582, 360,   0, 360, 582 },
129        { 582, 582, 360,   0, 360 },
130        { 360, 582, 582, 360,   0 }
131      });
132
133      SolutionCreator.PermutationParameter.ActualName = "Assignment";
134      ParameterizeSolutionCreator();
135      ParameterizeEvaluator();
136
137      InitializeOperators();
138      AttachEventHandlers();
139    }
140
141    public override IDeepCloneable Clone(Cloner cloner) {
142      return new QuadraticAssignmentProblem(this, cloner);
143    }
144
145    [StorableHook(HookType.AfterDeserialization)]
146    private void AfterDeserialization() {
147      // BackwardsCompatibility3.3
148      #region Backwards compatible code, remove with 3.4
149      if (!Parameters.ContainsKey("BestKnownSolutions")) {
150        Parameters.Add(new OptionalValueParameter<ItemSet<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));
151      } else if (Parameters["BestKnownSolutions"].GetType().Equals(typeof(OptionalValueParameter<ItemList<Permutation>>))) {
152        ItemList<Permutation> list = ((OptionalValueParameter<ItemList<Permutation>>)Parameters["BestKnownSolutions"]).Value;
153        Parameters.Remove("BestKnownSolutions");
154        Parameters.Add(new OptionalValueParameter<ItemSet<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.", (list != null ? new ItemSet<Permutation>(list) : null)));
155      }
156      if (Parameters.ContainsKey("DistanceMatrix")) {
157        DoubleMatrix d = ((ValueParameter<DoubleMatrix>)Parameters["DistanceMatrix"]).Value;
158        Parameters.Remove("DistanceMatrix");
159        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.", d));
160      }
161      AttachEventHandlers();
162      #endregion
163    }
164
165    #region Events
166    protected override void OnSolutionCreatorChanged() {
167      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
168      ParameterizeSolutionCreator();
169      ParameterizeEvaluator();
170      ParameterizeAnalyzers();
171      ParameterizeOperators();
172      base.OnSolutionCreatorChanged();
173    }
174    protected override void OnEvaluatorChanged() {
175      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
176      ParameterizeEvaluator();
177      ParameterizeAnalyzers();
178      ParameterizeOperators();
179      base.OnEvaluatorChanged();
180    }
181
182    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
183      ParameterizeEvaluator();
184      ParameterizeAnalyzers();
185      ParameterizeOperators();
186    }
187    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
188      ParameterizeAnalyzers();
189      ParameterizeOperators();
190    }
191    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
192      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
193      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
194      ParameterizeSolutionCreator();
195      ParameterizeEvaluator();
196      ParameterizeOperators();
197      AdjustDistanceMatrix();
198    }
199    private void Weights_RowsChanged(object sender, EventArgs e) {
200      if (Weights.Rows != Weights.Columns)
201        ((IStringConvertibleMatrix)Weights).Columns = Weights.Rows;
202      else {
203        ParameterizeSolutionCreator();
204        ParameterizeEvaluator();
205        ParameterizeOperators();
206        AdjustDistanceMatrix();
207      }
208    }
209    private void Weights_ColumnsChanged(object sender, EventArgs e) {
210      if (Weights.Rows != Weights.Columns)
211        ((IStringConvertibleMatrix)Weights).Rows = Weights.Columns;
212      else {
213        ParameterizeSolutionCreator();
214        ParameterizeEvaluator();
215        ParameterizeOperators();
216        AdjustDistanceMatrix();
217      }
218    }
219    private void DistancesParameter_ValueChanged(object sender, EventArgs e) {
220      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
221      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
222      ParameterizeSolutionCreator();
223      ParameterizeEvaluator();
224      ParameterizeOperators();
225      AdjustWeightsMatrix();
226    }
227    private void Distances_RowsChanged(object sender, EventArgs e) {
228      if (Distances.Rows != Distances.Columns)
229        ((IStringConvertibleMatrix)Distances).Columns = Distances.Rows;
230      else {
231        ParameterizeSolutionCreator();
232        ParameterizeEvaluator();
233        ParameterizeOperators();
234        AdjustWeightsMatrix();
235      }
236    }
237    private void Distances_ColumnsChanged(object sender, EventArgs e) {
238      if (Distances.Rows != Distances.Columns)
239        ((IStringConvertibleMatrix)Distances).Rows = Distances.Columns;
240      else {
241        ParameterizeSolutionCreator();
242        ParameterizeEvaluator();
243        ParameterizeOperators();
244        AdjustWeightsMatrix();
245      }
246    }
247    #endregion
248
249    #region Helpers
250    private void AttachEventHandlers() {
251      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
252      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
253      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
254      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
255      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
256      DistancesParameter.ValueChanged += new EventHandler(DistancesParameter_ValueChanged);
257      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
258      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
259    }
260
261    private void InitializeOperators() {
262      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
263      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
264      Operators.AddRange(ApplicationManager.Manager.GetInstances<IQAPMoveEvaluator>());
265      Operators.AddRange(ApplicationManager.Manager.GetInstances<IAffinitySwapMoveOperator>().Where(x => !(x is IQAPMoveEvaluator)));
266      Operators.Add(new BestQAPSolutionAnalyzer());
267      Operators.Add(new QAPAlleleFrequencyAnalyzer());
268      Operators.Add(new QAPPopulationDiversityAnalyzer());
269      Operators.Add(new QAPExhaustiveSwap2LocalImprovement());
270      ParameterizeAnalyzers();
271      ParameterizeOperators();
272    }
273    private void ParameterizeSolutionCreator() {
274      if (SolutionCreator != null) {
275        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
276        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
277      }
278    }
279    private void ParameterizeEvaluator() {
280      if (Evaluator != null) {
281        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
282        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
283        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
284      }
285    }
286    private void ParameterizeAnalyzers() {
287      if (BestQAPSolutionAnalyzer != null) {
288        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
289        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
290        BestQAPSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
291        BestQAPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
292        BestQAPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
293        BestQAPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
294        BestQAPSolutionAnalyzer.BestKnownSolutionsParameter.ActualName = BestKnownSolutionsParameter.Name;
295        BestQAPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
296      }
297      if (QAPAlleleFrequencyAnalyzer != null) {
298        QAPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
299        QAPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
300        QAPAlleleFrequencyAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
301        QAPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
302        QAPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
303        QAPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
304        QAPAlleleFrequencyAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
305      }
306      if (QAPPopulationDiversityAnalyzer != null) {
307        QAPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
308        QAPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
309        QAPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
310        QAPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
311      }
312    }
313    private void ParameterizeOperators() {
314      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
315        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
316        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
317      }
318      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
319        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
320      }
321      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
322        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
323      }
324      foreach (IAffinitySwapMoveOperator op in Operators.OfType<IAffinitySwapMoveOperator>()) {
325        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
326        op.WeightsParameter.ActualName = WeightsParameter.Name;
327        op.DistancesParameter.ActualName = DistancesParameter.Name;
328      }
329      if (Operators.OfType<IMoveGenerator>().Any()) {
330        string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
331        foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
332          op.InversionMoveParameter.ActualName = inversionMove;
333        string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
334        foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
335          op.TranslocationMoveParameter.ActualName = translocationMove;
336        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
337        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
338          op.Swap2MoveParameter.ActualName = swapMove;
339        }
340        string affinitySwapMove = Operators.OfType<IMoveGenerator>().OfType<IAffinitySwapMoveOperator>().First().AffinitySwapMoveParameter.ActualName;
341        foreach (IAffinitySwapMoveOperator op in Operators.OfType<IAffinitySwapMoveOperator>()) {
342          op.AffinitySwapMoveParameter.ActualName = affinitySwapMove;
343        }
344      }
345      foreach (var op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>())
346        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
347
348      QAPExhaustiveSwap2LocalImprovement localOpt = Operators.OfType<QAPExhaustiveSwap2LocalImprovement>().SingleOrDefault();
349      if (localOpt != null) {
350        localOpt.AssignmentParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
351        localOpt.DistancesParameter.ActualName = DistancesParameter.Name;
352        localOpt.MaximizationParameter.ActualName = MaximizationParameter.Name;
353        localOpt.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
354        localOpt.WeightsParameter.ActualName = WeightsParameter.Name;
355      }
356    }
357
358    private void AdjustDistanceMatrix() {
359      if (Distances.Rows != Weights.Rows || Distances.Columns != Weights.Columns) {
360        ((IStringConvertibleMatrix)Distances).Rows = Weights.Rows;
361      }
362    }
363
364    private void AdjustWeightsMatrix() {
365      if (Weights.Rows != Distances.Rows || Weights.Columns != Distances.Columns) {
366        ((IStringConvertibleMatrix)Weights).Rows = Distances.Rows;
367      }
368    }
369    #endregion
370
371    public void LoadInstanceFromFile(string filename) {
372      QAPLIBParser parser = new QAPLIBParser();
373      parser.Parse(filename);
374      if (parser.Error != null) throw parser.Error;
375      Distances = new DoubleMatrix(parser.Distances);
376      Weights = new DoubleMatrix(parser.Weights);
377      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(filename) + ")";
378      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
379      BestKnownQuality = null;
380      BestKnownSolution = null;
381      BestKnownSolutions = null;
382      OnReset();
383    }
384
385    public void LoadInstanceFromFile(string datFilename, string slnFilename) {
386      QAPLIBParser datParser = new QAPLIBParser();
387      datParser.Parse(datFilename);
388      if (datParser.Error != null) throw datParser.Error;
389      Distances = new DoubleMatrix(datParser.Distances);
390      Weights = new DoubleMatrix(datParser.Weights);
391      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(datFilename) + ")";
392      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
393
394      QAPLIBSolutionParser slnParser = new QAPLIBSolutionParser();
395      slnParser.Parse(slnFilename, true);
396      if (slnParser.Error != null) throw slnParser.Error;
397
398      BestKnownQuality = new DoubleValue(slnParser.Quality);
399      BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
400      BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
401      BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
402
403      if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
404        // the solution doesn't result in the given quality, maybe indices and values are inverted
405        // try parsing again, this time inverting them
406        slnParser.Reset();
407        slnParser.Parse(slnFilename, false);
408        if (slnParser.Error != null) throw slnParser.Error;
409
410        BestKnownQuality = new DoubleValue(slnParser.Quality);
411        BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
412        BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
413        BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
414
415        if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
416          // if the solution still doesn't result in the given quality, remove it and only take the quality
417          BestKnownSolution = null;
418          BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
419        }
420      }
421      OnReset();
422    }
423  }
424}
Note: See TracBrowser for help on using the repository browser.