Free cookie consent management tool by TermsFeed Policy Generator

source: branches/histogram/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
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.Add(new BestQAPSolutionAnalyzer());
238      ParameterizeAnalyzers();
239      ParameterizeOperators();
240    }
241    private void ParameterizeSolutionCreator() {
242      if (SolutionCreator != null) {
243        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
244        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
245      }
246    }
247    private void ParameterizeEvaluator() {
248      if (Evaluator != null) {
249        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
250        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
251        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
252      }
253    }
254    private void ParameterizeAnalyzers() {
255      if (BestQAPSolutionAnalyzer != null) {
256        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
257        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
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    }
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      }
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;
284        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
285        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
286          op.Swap2MoveParameter.ActualName = swapMove;
287        }
288      }
289    }
290
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    }
302    #endregion
303
304    public void ImportFileInstance(string filename) {
305      QAPLIBParser parser = new QAPLIBParser();
306      parser.Parse(filename);
307      if (parser.Error != null) throw parser.Error;
308      Distances = new DoubleMatrix(parser.Distances);
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 + ".";
312      BestKnownQuality = null;
313      BestKnownSolution = null;
314      OnReset();
315    }
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);
322        if (parser.Error != null) throw parser.Error;
323        Distances = new DoubleMatrix(parser.Distances);
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      }
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();
337          solParser.Parse(solStream, true); // most sln's seem to be of the type index = "facility" => value = "location"
338          if (solParser.Error != null) throw solParser.Error;
339          if (!solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
340            solStream.Seek(0, SeekOrigin.Begin);
341            solParser.Reset();
342            solParser.Parse(solStream, false); // some sln's seem to be of the type index = "location" => value = "facility"
343            if (solParser.Error != null) throw solParser.Error;
344            if (solParser.Quality.IsAlmost(QAPEvaluator.Apply(new Permutation(PermutationTypes.Absolute, solParser.Assignment), Weights, Distances))) {
345              BestKnownQuality = new DoubleValue(solParser.Quality);
346              BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
347            } else {
348              BestKnownQuality = new DoubleValue(solParser.Quality);
349              BestKnownSolution = null;
350            }
351          } else {
352            BestKnownQuality = new DoubleValue(solParser.Quality);
353            BestKnownSolution = new Permutation(PermutationTypes.Absolute, solParser.Assignment);
354          }
355        }
356      } else {
357        BestKnownQuality = null;
358        BestKnownSolution = null;
359      }
360    }
361  }
362}
Note: See TracBrowser for help on using the repository browser.