Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1330

  • Added IStorableContent interface
File size: 16.5 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>());
[5583]237      Operators.Add(new BestQAPSolutionAnalyzer());
238      ParameterizeAnalyzers();
[5563]239      ParameterizeOperators();
[5558]240    }
241    private void ParameterizeSolutionCreator() {
[5563]242      if (SolutionCreator != null) {
243        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
244        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
245      }
[5558]246    }
247    private void ParameterizeEvaluator() {
[5563]248      if (Evaluator != null) {
249        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[5838]250        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
[5563]251        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
252      }
[5558]253    }
[5583]254    private void ParameterizeAnalyzers() {
255      if (BestQAPSolutionAnalyzer != null) {
256        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
[5838]257        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
[5583]258        BestQAPSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
259        BestQAPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
260        BestQAPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
261        BestQAPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
262        BestQAPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
263        BestQAPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
264      }
265    }
[5562]266    private void ParameterizeOperators() {
267      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
268        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
269        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
270      }
271      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
272        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
273      }
274      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
275        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
276      }
[5563]277      if (Operators.OfType<IMoveGenerator>().Any()) {
278        string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
279        foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
280          op.InversionMoveParameter.ActualName = inversionMove;
281        string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
282        foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
283          op.TranslocationMoveParameter.ActualName = translocationMove;
[5838]284        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
285        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
286          op.Swap2MoveParameter.ActualName = swapMove;
[5785]287        }
[5563]288      }
[5562]289    }
[5598]290
[5855]291    private void AdjustDistanceMatrix() {
292      if (Distances.Rows != Weights.Rows || Distances.Columns != Weights.Columns) {
293        ((IStringConvertibleMatrix)Distances).Rows = Weights.Rows;
294      }
295    }
296
297    private void AdjustWeightsMatrix() {
298      if (Weights.Rows != Distances.Rows || Weights.Columns != Distances.Columns) {
299        ((IStringConvertibleMatrix)Weights).Rows = Distances.Rows;
300      }
301    }
[5558]302    #endregion
[5562]303
[5563]304    public void ImportFileInstance(string filename) {
[5562]305      QAPLIBParser parser = new QAPLIBParser();
306      parser.Parse(filename);
[5641]307      if (parser.Error != null) throw parser.Error;
[5838]308      Distances = new DoubleMatrix(parser.Distances);
[5562]309      Weights = new DoubleMatrix(parser.Weights);
310      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(filename) + ")";
311      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
[5598]312      BestKnownQuality = null;
313      BestKnownSolution = null;
[5562]314      OnReset();
315    }
[5563]316
317    public void LoadEmbeddedInstance(string instance) {
318      using (Stream stream = Assembly.GetExecutingAssembly()
319        .GetManifestResourceStream(InstancePrefix + instance + ".dat")) {
320        QAPLIBParser parser = new QAPLIBParser();
321        parser.Parse(stream);
[5641]322        if (parser.Error != null) throw parser.Error;
[5838]323        Distances = new DoubleMatrix(parser.Distances);
[5563]324        Weights = new DoubleMatrix(parser.Weights);
325        Name = "Quadratic Assignment Problem (loaded instance " + instance + ")";
326        Description = "Loaded embedded problem data of instance " + instance + ".";
327        OnReset();
328      }
[5598]329      bool solutionExists = Assembly.GetExecutingAssembly()
330          .GetManifestResourceNames()
331          .Where(x => x.EndsWith(instance + ".sln"))
332          .Any();
333      if (solutionExists) {
334        using (Stream solStream = Assembly.GetExecutingAssembly()
335          .GetManifestResourceStream(InstancePrefix + instance + ".sln")) {
336          QAPLIBSolutionParser solParser = new QAPLIBSolutionParser();
[5948]337          solParser.Parse(solStream, true); // most sln's seem to be of the type index = "facility" => value = "location"
[5641]338          if (solParser.Error != null) throw solParser.Error;
[5838]339          if (!solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
[5814]340            solStream.Seek(0, SeekOrigin.Begin);
[5949]341            solParser.Reset();
[5948]342            solParser.Parse(solStream, false); // some sln's seem to be of the type index = "location" => value = "facility"
[5814]343            if (solParser.Error != null) throw solParser.Error;
[5838]344            if (solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
[5814]345              BestKnownQuality = new DoubleValue(solParser.Quality);
346              BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
347            } else {
[5949]348              BestKnownQuality = new DoubleValue(solParser.Quality);
[5814]349              BestKnownSolution = null;
350            }
351          } else {
352            BestKnownQuality = new DoubleValue(solParser.Quality);
353            BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
354          }
[5598]355        }
356      } else {
357        BestKnownQuality = null;
358        BestKnownSolution = null;
359      }
[5563]360    }
[5558]361  }
362}
Note: See TracBrowser for help on using the repository browser.