Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs @ 6094

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

#1330

  • Fixed an issue were a TSP move evaluator could be selected in the QAP
File size: 16.9 KB
RevLine 
[5558]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;
[5563]23using System.Collections.Generic;
[5558]24using System.Drawing;
[5562]25using System.IO;
[5558]26using System.Linq;
[5562]27using System.Reflection;
[5558]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;
[5562]35using HeuristicLab.PluginInfrastructure;
[5558]36
37namespace HeuristicLab.Problems.QuadraticAssignment {
[5838]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.")]
[5558]39  [Creatable("Problems")]
40  [StorableClass]
[5953]41  public sealed class QuadraticAssignmentProblem : SingleObjectiveHeuristicOptimizationProblem<IQAPEvaluator, IPermutationCreator>, IStorableContent {
[5563]42    private static string InstancePrefix = "HeuristicLab.Problems.QuadraticAssignment.Data.";
43
[5953]44    public string Filename { get; set; }
45
[5558]46    public override Image ItemImage {
47      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
48    }
49
50    #region Parameter Properties
[5641]51    public IValueParameter<Permutation> BestKnownSolutionParameter {
52      get { return (IValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
[5558]53    }
[5641]54    public IValueParameter<DoubleMatrix> WeightsParameter {
55      get { return (IValueParameter<DoubleMatrix>)Parameters["Weights"]; }
[5558]56    }
[5838]57    public IValueParameter<DoubleMatrix> DistancesParameter {
58      get { return (IValueParameter<DoubleMatrix>)Parameters["Distances"]; }
[5558]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    }
[5838]71    public DoubleMatrix Distances {
72      get { return DistancesParameter.Value; }
73      set { DistancesParameter.Value = value; }
[5558]74    }
[5563]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    }
[5583]86
87    private BestQAPSolutionAnalyzer BestQAPSolutionAnalyzer {
88      get { return Operators.OfType<BestQAPSolutionAnalyzer>().FirstOrDefault(); }
89    }
[5558]90    #endregion
91
92    [StorableConstructor]
93    private QuadraticAssignmentProblem(bool deserializing) : base(deserializing) { }
[5562]94    private QuadraticAssignmentProblem(QuadraticAssignmentProblem original, Cloner cloner)
[5558]95      : base(original, cloner) {
96      AttachEventHandlers();
97    }
98    public QuadraticAssignmentProblem()
[5931]99      : base(new QAPEvaluator(), new RandomPermutationCreator()) {
[5648]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));
[5558]101      Parameters.Add(new ValueParameter<DoubleMatrix>("Weights", "The strength of the connection between the facilities.", new DoubleMatrix(5, 5)));
[5838]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)));
[5558]103
[5563]104      Maximization = new BoolValue(false);
105
[5558]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
[5838]114      Distances = new DoubleMatrix(new double[,] {
[5558]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
[5931]122      SolutionCreator.PermutationParameter.ActualName = "Assignment";
123      ParameterizeSolutionCreator();
124      ParameterizeEvaluator();
[5558]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
[5562]135    protected override void OnSolutionCreatorChanged() {
136      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
137      ParameterizeSolutionCreator();
138      ParameterizeEvaluator();
[5583]139      ParameterizeAnalyzers();
[5562]140      ParameterizeOperators();
141      base.OnSolutionCreatorChanged();
[5558]142    }
[5562]143    protected override void OnEvaluatorChanged() {
[5583]144      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[5562]145      ParameterizeEvaluator();
[5583]146      ParameterizeAnalyzers();
[5562]147      ParameterizeOperators();
148      base.OnEvaluatorChanged();
[5558]149    }
[5562]150
151    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
152      ParameterizeEvaluator();
[5583]153      ParameterizeAnalyzers();
[5562]154      ParameterizeOperators();
[5558]155    }
[5583]156    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
157      ParameterizeAnalyzers();
158      ParameterizeOperators();
159    }
[5562]160    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
161      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
[5855]162      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
[5562]163      ParameterizeSolutionCreator();
164      ParameterizeEvaluator();
165      ParameterizeOperators();
[5855]166      AdjustDistanceMatrix();
[5558]167    }
[5562]168    private void Weights_RowsChanged(object sender, EventArgs e) {
[5855]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);
[5562]191      ParameterizeSolutionCreator();
192      ParameterizeEvaluator();
193      ParameterizeOperators();
[5855]194      AdjustWeightsMatrix();
[5562]195    }
[5855]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    }
[5558]216    #endregion
217
218    #region Helpers
219    [StorableHook(HookType.AfterDeserialization)]
220    private void AfterDeserializationHook() {
221      AttachEventHandlers();
222    }
223
224    private void AttachEventHandlers() {
[5598]225      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
226      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[5562]227      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
228      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
[5855]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);
[5558]233    }
234
235    private void InitializeOperators() {
[5562]236      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
[6088]237      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
238      Operators.AddRange(ApplicationManager.Manager.GetInstances<IQAPMoveEvaluator>());
[5583]239      Operators.Add(new BestQAPSolutionAnalyzer());
240      ParameterizeAnalyzers();
[5563]241      ParameterizeOperators();
[5558]242    }
243    private void ParameterizeSolutionCreator() {
[5563]244      if (SolutionCreator != null) {
245        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
246        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
247      }
[5558]248    }
249    private void ParameterizeEvaluator() {
[5563]250      if (Evaluator != null) {
251        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[5838]252        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
[5563]253        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
254      }
[5558]255    }
[5583]256    private void ParameterizeAnalyzers() {
257      if (BestQAPSolutionAnalyzer != null) {
258        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
[5838]259        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
[5583]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    }
[5562]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      }
[5563]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;
[5838]286        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
287        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
288          op.Swap2MoveParameter.ActualName = swapMove;
[5785]289        }
[5563]290      }
[6042]291      foreach (var op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>())
292        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[5562]293    }
[5598]294
[5855]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    }
[5558]306    #endregion
[5562]307
[5563]308    public void ImportFileInstance(string filename) {
[5562]309      QAPLIBParser parser = new QAPLIBParser();
310      parser.Parse(filename);
[5641]311      if (parser.Error != null) throw parser.Error;
[5838]312      Distances = new DoubleMatrix(parser.Distances);
[5562]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 + ".";
[5598]316      BestKnownQuality = null;
317      BestKnownSolution = null;
[5562]318      OnReset();
319    }
[5563]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);
[5641]326        if (parser.Error != null) throw parser.Error;
[5838]327        Distances = new DoubleMatrix(parser.Distances);
[5563]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      }
[5598]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();
[5948]341          solParser.Parse(solStream, true); // most sln's seem to be of the type index = "facility" => value = "location"
[5641]342          if (solParser.Error != null) throw solParser.Error;
[5838]343          if (!solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
[5814]344            solStream.Seek(0, SeekOrigin.Begin);
[5949]345            solParser.Reset();
[5948]346            solParser.Parse(solStream, false); // some sln's seem to be of the type index = "location" => value = "facility"
[5814]347            if (solParser.Error != null) throw solParser.Error;
[5838]348            if (solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
[5814]349              BestKnownQuality = new DoubleValue(solParser.Quality);
350              BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
351            } else {
[5949]352              BestKnownQuality = new DoubleValue(solParser.Quality);
[5814]353              BestKnownSolution = null;
354            }
355          } else {
356            BestKnownQuality = new DoubleValue(solParser.Quality);
357            BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
358          }
[5598]359        }
360      } else {
361        BestKnownQuality = null;
362        BestKnownSolution = null;
363      }
[5563]364    }
[5558]365  }
366}
Note: See TracBrowser for help on using the repository browser.