Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs @ 6452

Last change on this file since 6452 was 6088, checked in by abeham, 14 years ago

#1330

  • Fixed an issue were a TSP move evaluator could be selected in the QAP
File size: 16.9 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<Permutation> BestKnownSolutionParameter {
52      get { return (IValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
53    }
54    public IValueParameter<DoubleMatrix> WeightsParameter {
55      get { return (IValueParameter<DoubleMatrix>)Parameters["Weights"]; }
56    }
57    public IValueParameter<DoubleMatrix> DistancesParameter {
58      get { return (IValueParameter<DoubleMatrix>)Parameters["Distances"]; }
59    }
60    #endregion
61
62    #region Properties
63    public Permutation BestKnownSolution {
64      get { return BestKnownSolutionParameter.Value; }
65      set { BestKnownSolutionParameter.Value = value; }
66    }
67    public DoubleMatrix Weights {
68      get { return WeightsParameter.Value; }
69      set { WeightsParameter.Value = value; }
70    }
71    public DoubleMatrix Distances {
72      get { return DistancesParameter.Value; }
73      set { DistancesParameter.Value = value; }
74    }
75
76    public IEnumerable<string> EmbeddedInstances {
77      get {
78        return Assembly.GetExecutingAssembly()
79          .GetManifestResourceNames()
80          .Where(x => x.EndsWith(".dat"))
81          .OrderBy(x => x)
82          .Select(x => x.Replace(".dat", String.Empty))
83          .Select(x => x.Replace(InstancePrefix, String.Empty));
84      }
85    }
86
87    private BestQAPSolutionAnalyzer BestQAPSolutionAnalyzer {
88      get { return Operators.OfType<BestQAPSolutionAnalyzer>().FirstOrDefault(); }
89    }
90    #endregion
91
92    [StorableConstructor]
93    private QuadraticAssignmentProblem(bool deserializing) : base(deserializing) { }
94    private QuadraticAssignmentProblem(QuadraticAssignmentProblem original, Cloner cloner)
95      : base(original, cloner) {
96      AttachEventHandlers();
97    }
98    public QuadraticAssignmentProblem()
99      : base(new QAPEvaluator(), new RandomPermutationCreator()) {
100      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));
101      Parameters.Add(new ValueParameter<DoubleMatrix>("Weights", "The strength of the connection between the facilities.", new DoubleMatrix(5, 5)));
102      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)));
103
104      Maximization = new BoolValue(false);
105
106      Weights = new DoubleMatrix(new double[,] {
107        { 0, 1, 0, 0, 1 },
108        { 1, 0, 1, 0, 0 },
109        { 0, 1, 0, 1, 0 },
110        { 0, 0, 1, 0, 1 },
111        { 1, 0, 0, 1, 0 }
112      });
113
114      Distances = new DoubleMatrix(new double[,] {
115        {   0, 360, 582, 582, 360 },
116        { 360,   0, 360, 582, 582 },
117        { 582, 360,   0, 360, 582 },
118        { 582, 582, 360,   0, 360 },
119        { 360, 582, 582, 360,   0 }
120      });
121
122      SolutionCreator.PermutationParameter.ActualName = "Assignment";
123      ParameterizeSolutionCreator();
124      ParameterizeEvaluator();
125
126      InitializeOperators();
127      AttachEventHandlers();
128    }
129
130    public override IDeepCloneable Clone(Cloner cloner) {
131      return new QuadraticAssignmentProblem(this, cloner);
132    }
133
134    #region Events
135    protected override void OnSolutionCreatorChanged() {
136      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
137      ParameterizeSolutionCreator();
138      ParameterizeEvaluator();
139      ParameterizeAnalyzers();
140      ParameterizeOperators();
141      base.OnSolutionCreatorChanged();
142    }
143    protected override void OnEvaluatorChanged() {
144      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
145      ParameterizeEvaluator();
146      ParameterizeAnalyzers();
147      ParameterizeOperators();
148      base.OnEvaluatorChanged();
149    }
150
151    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
152      ParameterizeEvaluator();
153      ParameterizeAnalyzers();
154      ParameterizeOperators();
155    }
156    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
157      ParameterizeAnalyzers();
158      ParameterizeOperators();
159    }
160    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
161      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
162      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
163      ParameterizeSolutionCreator();
164      ParameterizeEvaluator();
165      ParameterizeOperators();
166      AdjustDistanceMatrix();
167    }
168    private void Weights_RowsChanged(object sender, EventArgs e) {
169      if (Weights.Rows != Weights.Columns)
170        ((IStringConvertibleMatrix)Weights).Columns = Weights.Rows;
171      else {
172        ParameterizeSolutionCreator();
173        ParameterizeEvaluator();
174        ParameterizeOperators();
175        AdjustDistanceMatrix();
176      }
177    }
178    private void Weights_ColumnsChanged(object sender, EventArgs e) {
179      if (Weights.Rows != Weights.Columns)
180        ((IStringConvertibleMatrix)Weights).Rows = Weights.Columns;
181      else {
182        ParameterizeSolutionCreator();
183        ParameterizeEvaluator();
184        ParameterizeOperators();
185        AdjustDistanceMatrix();
186      }
187    }
188    private void DistancesParameter_ValueChanged(object sender, EventArgs e) {
189      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
190      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
191      ParameterizeSolutionCreator();
192      ParameterizeEvaluator();
193      ParameterizeOperators();
194      AdjustWeightsMatrix();
195    }
196    private void Distances_RowsChanged(object sender, EventArgs e) {
197      if (Distances.Rows != Distances.Columns)
198        ((IStringConvertibleMatrix)Distances).Columns = Distances.Rows;
199      else {
200        ParameterizeSolutionCreator();
201        ParameterizeEvaluator();
202        ParameterizeOperators();
203        AdjustWeightsMatrix();
204      }
205    }
206    private void Distances_ColumnsChanged(object sender, EventArgs e) {
207      if (Distances.Rows != Distances.Columns)
208        ((IStringConvertibleMatrix)Distances).Rows = Distances.Columns;
209      else {
210        ParameterizeSolutionCreator();
211        ParameterizeEvaluator();
212        ParameterizeOperators();
213        AdjustWeightsMatrix();
214      }
215    }
216    #endregion
217
218    #region Helpers
219    [StorableHook(HookType.AfterDeserialization)]
220    private void AfterDeserializationHook() {
221      AttachEventHandlers();
222    }
223
224    private void AttachEventHandlers() {
225      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
226      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
227      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
228      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
229      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
230      DistancesParameter.ValueChanged += new EventHandler(DistancesParameter_ValueChanged);
231      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
232      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
233    }
234
235    private void InitializeOperators() {
236      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
237      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
238      Operators.AddRange(ApplicationManager.Manager.GetInstances<IQAPMoveEvaluator>());
239      Operators.Add(new BestQAPSolutionAnalyzer());
240      ParameterizeAnalyzers();
241      ParameterizeOperators();
242    }
243    private void ParameterizeSolutionCreator() {
244      if (SolutionCreator != null) {
245        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
246        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
247      }
248    }
249    private void ParameterizeEvaluator() {
250      if (Evaluator != null) {
251        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
252        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
253        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
254      }
255    }
256    private void ParameterizeAnalyzers() {
257      if (BestQAPSolutionAnalyzer != null) {
258        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
259        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
260        BestQAPSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
261        BestQAPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
262        BestQAPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
263        BestQAPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
264        BestQAPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
265        BestQAPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
266      }
267    }
268    private void ParameterizeOperators() {
269      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
270        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
271        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
272      }
273      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
274        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
275      }
276      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
277        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
278      }
279      if (Operators.OfType<IMoveGenerator>().Any()) {
280        string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
281        foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
282          op.InversionMoveParameter.ActualName = inversionMove;
283        string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
284        foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
285          op.TranslocationMoveParameter.ActualName = translocationMove;
286        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
287        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
288          op.Swap2MoveParameter.ActualName = swapMove;
289        }
290      }
291      foreach (var op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>())
292        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
293    }
294
295    private void AdjustDistanceMatrix() {
296      if (Distances.Rows != Weights.Rows || Distances.Columns != Weights.Columns) {
297        ((IStringConvertibleMatrix)Distances).Rows = Weights.Rows;
298      }
299    }
300
301    private void AdjustWeightsMatrix() {
302      if (Weights.Rows != Distances.Rows || Weights.Columns != Distances.Columns) {
303        ((IStringConvertibleMatrix)Weights).Rows = Distances.Rows;
304      }
305    }
306    #endregion
307
308    public void ImportFileInstance(string filename) {
309      QAPLIBParser parser = new QAPLIBParser();
310      parser.Parse(filename);
311      if (parser.Error != null) throw parser.Error;
312      Distances = new DoubleMatrix(parser.Distances);
313      Weights = new DoubleMatrix(parser.Weights);
314      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(filename) + ")";
315      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
316      BestKnownQuality = null;
317      BestKnownSolution = null;
318      OnReset();
319    }
320
321    public void LoadEmbeddedInstance(string instance) {
322      using (Stream stream = Assembly.GetExecutingAssembly()
323        .GetManifestResourceStream(InstancePrefix + instance + ".dat")) {
324        QAPLIBParser parser = new QAPLIBParser();
325        parser.Parse(stream);
326        if (parser.Error != null) throw parser.Error;
327        Distances = new DoubleMatrix(parser.Distances);
328        Weights = new DoubleMatrix(parser.Weights);
329        Name = "Quadratic Assignment Problem (loaded instance " + instance + ")";
330        Description = "Loaded embedded problem data of instance " + instance + ".";
331        OnReset();
332      }
333      bool solutionExists = Assembly.GetExecutingAssembly()
334          .GetManifestResourceNames()
335          .Where(x => x.EndsWith(instance + ".sln"))
336          .Any();
337      if (solutionExists) {
338        using (Stream solStream = Assembly.GetExecutingAssembly()
339          .GetManifestResourceStream(InstancePrefix + instance + ".sln")) {
340          QAPLIBSolutionParser solParser = new QAPLIBSolutionParser();
341          solParser.Parse(solStream, true); // most sln's seem to be of the type index = "facility" => value = "location"
342          if (solParser.Error != null) throw solParser.Error;
343          if (!solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
344            solStream.Seek(0, SeekOrigin.Begin);
345            solParser.Reset();
346            solParser.Parse(solStream, false); // some sln's seem to be of the type index = "location" => value = "facility"
347            if (solParser.Error != null) throw solParser.Error;
348            if (solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
349              BestKnownQuality = new DoubleValue(solParser.Quality);
350              BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
351            } else {
352              BestKnownQuality = new DoubleValue(solParser.Quality);
353              BestKnownSolution = null;
354            }
355          } else {
356            BestKnownQuality = new DoubleValue(solParser.Quality);
357            BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
358          }
359        }
360      } else {
361        BestKnownQuality = null;
362        BestKnownSolution = null;
363      }
364    }
365  }
366}
Note: See TracBrowser for help on using the repository browser.