Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1465

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