Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveHiveEngine/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs @ 11303

Last change on this file since 11303 was 7383, checked in by ascheibe, 13 years ago

#1745 merged trunk changes into branch

File size: 24.1 KB
RevLine 
[5558]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5558]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;
[6952]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
[7201]46    public static new Image StaticItemImage {
[5558]47      get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
48    }
49
50    #region Parameter Properties
[6525]51    public IValueParameter<ItemSet<Permutation>> BestKnownSolutionsParameter {
52      get { return (IValueParameter<ItemSet<Permutation>>)Parameters["BestKnownSolutions"]; }
[6342]53    }
[5641]54    public IValueParameter<Permutation> BestKnownSolutionParameter {
55      get { return (IValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
[5558]56    }
[5641]57    public IValueParameter<DoubleMatrix> WeightsParameter {
58      get { return (IValueParameter<DoubleMatrix>)Parameters["Weights"]; }
[5558]59    }
[5838]60    public IValueParameter<DoubleMatrix> DistancesParameter {
61      get { return (IValueParameter<DoubleMatrix>)Parameters["Distances"]; }
[5558]62    }
63    #endregion
64
65    #region Properties
[6525]66    public ItemSet<Permutation> BestKnownSolutions {
[6342]67      get { return BestKnownSolutionsParameter.Value; }
68      set { BestKnownSolutionsParameter.Value = value; }
69    }
[5558]70    public Permutation BestKnownSolution {
71      get { return BestKnownSolutionParameter.Value; }
72      set { BestKnownSolutionParameter.Value = value; }
73    }
74    public DoubleMatrix Weights {
75      get { return WeightsParameter.Value; }
76      set { WeightsParameter.Value = value; }
77    }
[5838]78    public DoubleMatrix Distances {
79      get { return DistancesParameter.Value; }
80      set { DistancesParameter.Value = value; }
[5558]81    }
[5563]82
[5583]83    private BestQAPSolutionAnalyzer BestQAPSolutionAnalyzer {
84      get { return Operators.OfType<BestQAPSolutionAnalyzer>().FirstOrDefault(); }
85    }
[6342]86
87    private QAPAlleleFrequencyAnalyzer QAPAlleleFrequencyAnalyzer {
88      get { return Operators.OfType<QAPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
89    }
90
91    private QAPPopulationDiversityAnalyzer QAPPopulationDiversityAnalyzer {
92      get { return Operators.OfType<QAPPopulationDiversityAnalyzer>().FirstOrDefault(); }
93    }
[6891]94
[6952]95    public IEnumerable<string> Instances {
96      get {
97        return Assembly.GetExecutingAssembly()
98          .GetManifestResourceNames()
99          .Where(x => x.EndsWith(".dat"))
100          .OrderBy(x => x)
101          .Select(x => x.Replace(".dat", String.Empty))
102          .Select(x => x.Replace(InstancePrefix, String.Empty));
103      }
[6891]104    }
[5558]105    #endregion
106
107    [StorableConstructor]
108    private QuadraticAssignmentProblem(bool deserializing) : base(deserializing) { }
[5562]109    private QuadraticAssignmentProblem(QuadraticAssignmentProblem original, Cloner cloner)
[5558]110      : base(original, cloner) {
[7383]111      RegisterEventHandlers();
[5558]112    }
113    public QuadraticAssignmentProblem()
[5931]114      : base(new QAPEvaluator(), new RandomPermutationCreator()) {
[6525]115      Parameters.Add(new OptionalValueParameter<ItemSet<Permutation>>("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
[5648]116      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]117      Parameters.Add(new ValueParameter<DoubleMatrix>("Weights", "The strength of the connection between the facilities.", new DoubleMatrix(5, 5)));
[5838]118      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]119
[6939]120      Maximization.Value = false;
121      MaximizationParameter.Hidden = true;
[5563]122
[5558]123      Weights = new DoubleMatrix(new double[,] {
124        { 0, 1, 0, 0, 1 },
125        { 1, 0, 1, 0, 0 },
126        { 0, 1, 0, 1, 0 },
127        { 0, 0, 1, 0, 1 },
128        { 1, 0, 0, 1, 0 }
129      });
130
[5838]131      Distances = new DoubleMatrix(new double[,] {
[5558]132        {   0, 360, 582, 582, 360 },
133        { 360,   0, 360, 582, 582 },
134        { 582, 360,   0, 360, 582 },
135        { 582, 582, 360,   0, 360 },
136        { 360, 582, 582, 360,   0 }
137      });
138
[5931]139      SolutionCreator.PermutationParameter.ActualName = "Assignment";
140      ParameterizeSolutionCreator();
141      ParameterizeEvaluator();
[5558]142
143      InitializeOperators();
[7383]144      RegisterEventHandlers();
[5558]145    }
146
147    public override IDeepCloneable Clone(Cloner cloner) {
148      return new QuadraticAssignmentProblem(this, cloner);
149    }
150
[6342]151    [StorableHook(HookType.AfterDeserialization)]
152    private void AfterDeserialization() {
153      // BackwardsCompatibility3.3
154      #region Backwards compatible code, remove with 3.4
155      if (!Parameters.ContainsKey("BestKnownSolutions")) {
[6525]156        Parameters.Add(new OptionalValueParameter<ItemSet<Permutation>>("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", null));
157      } else if (Parameters["BestKnownSolutions"].GetType().Equals(typeof(OptionalValueParameter<ItemList<Permutation>>))) {
158        ItemList<Permutation> list = ((OptionalValueParameter<ItemList<Permutation>>)Parameters["BestKnownSolutions"]).Value;
[6540]159        Parameters.Remove("BestKnownSolutions");
[6571]160        Parameters.Add(new OptionalValueParameter<ItemSet<Permutation>>("BestKnownSolutions", "The list of best known solutions which is updated whenever a new better solution is found or may be the optimal solution if it is known beforehand.", (list != null ? new ItemSet<Permutation>(list) : null)));
[6342]161      }
162      if (Parameters.ContainsKey("DistanceMatrix")) {
[6525]163        DoubleMatrix d = ((ValueParameter<DoubleMatrix>)Parameters["DistanceMatrix"]).Value;
[6342]164        Parameters.Remove("DistanceMatrix");
[6525]165        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.", d));
[6342]166      }
[7383]167      RegisterEventHandlers();
[6342]168      #endregion
169    }
170
[5558]171    #region Events
[5562]172    protected override void OnSolutionCreatorChanged() {
173      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
174      ParameterizeSolutionCreator();
175      ParameterizeEvaluator();
[5583]176      ParameterizeAnalyzers();
[5562]177      ParameterizeOperators();
178      base.OnSolutionCreatorChanged();
[5558]179    }
[5562]180    protected override void OnEvaluatorChanged() {
[5583]181      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[5562]182      ParameterizeEvaluator();
[5583]183      ParameterizeAnalyzers();
[5562]184      ParameterizeOperators();
185      base.OnEvaluatorChanged();
[5558]186    }
[5562]187
188    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
189      ParameterizeEvaluator();
[5583]190      ParameterizeAnalyzers();
[5562]191      ParameterizeOperators();
[5558]192    }
[5583]193    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
194      ParameterizeAnalyzers();
195      ParameterizeOperators();
196    }
[5562]197    private void WeightsParameter_ValueChanged(object sender, EventArgs e) {
198      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
[5855]199      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
[5562]200      ParameterizeSolutionCreator();
201      ParameterizeEvaluator();
202      ParameterizeOperators();
[5855]203      AdjustDistanceMatrix();
[5558]204    }
[5562]205    private void Weights_RowsChanged(object sender, EventArgs e) {
[5855]206      if (Weights.Rows != Weights.Columns)
207        ((IStringConvertibleMatrix)Weights).Columns = Weights.Rows;
208      else {
209        ParameterizeSolutionCreator();
210        ParameterizeEvaluator();
211        ParameterizeOperators();
212        AdjustDistanceMatrix();
213      }
214    }
215    private void Weights_ColumnsChanged(object sender, EventArgs e) {
216      if (Weights.Rows != Weights.Columns)
217        ((IStringConvertibleMatrix)Weights).Rows = Weights.Columns;
218      else {
219        ParameterizeSolutionCreator();
220        ParameterizeEvaluator();
221        ParameterizeOperators();
222        AdjustDistanceMatrix();
223      }
224    }
225    private void DistancesParameter_ValueChanged(object sender, EventArgs e) {
226      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
227      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
[5562]228      ParameterizeSolutionCreator();
229      ParameterizeEvaluator();
230      ParameterizeOperators();
[5855]231      AdjustWeightsMatrix();
[5562]232    }
[5855]233    private void Distances_RowsChanged(object sender, EventArgs e) {
234      if (Distances.Rows != Distances.Columns)
235        ((IStringConvertibleMatrix)Distances).Columns = Distances.Rows;
236      else {
237        ParameterizeSolutionCreator();
238        ParameterizeEvaluator();
239        ParameterizeOperators();
240        AdjustWeightsMatrix();
241      }
242    }
243    private void Distances_ColumnsChanged(object sender, EventArgs e) {
244      if (Distances.Rows != Distances.Columns)
245        ((IStringConvertibleMatrix)Distances).Rows = Distances.Columns;
246      else {
247        ParameterizeSolutionCreator();
248        ParameterizeEvaluator();
249        ParameterizeOperators();
250        AdjustWeightsMatrix();
251      }
252    }
[5558]253    #endregion
254
255    #region Helpers
[7383]256    private void RegisterEventHandlers() {
[5598]257      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
258      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[5562]259      WeightsParameter.ValueChanged += new EventHandler(WeightsParameter_ValueChanged);
260      Weights.RowsChanged += new EventHandler(Weights_RowsChanged);
[5855]261      Weights.ColumnsChanged += new EventHandler(Weights_ColumnsChanged);
262      DistancesParameter.ValueChanged += new EventHandler(DistancesParameter_ValueChanged);
263      Distances.RowsChanged += new EventHandler(Distances_RowsChanged);
264      Distances.ColumnsChanged += new EventHandler(Distances_ColumnsChanged);
[5558]265    }
266
267    private void InitializeOperators() {
[5562]268      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
[6088]269      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
270      Operators.AddRange(ApplicationManager.Manager.GetInstances<IQAPMoveEvaluator>());
[5583]271      Operators.Add(new BestQAPSolutionAnalyzer());
[6342]272      Operators.Add(new QAPAlleleFrequencyAnalyzer());
273      Operators.Add(new QAPPopulationDiversityAnalyzer());
274      Operators.Add(new QAPExhaustiveSwap2LocalImprovement());
[5583]275      ParameterizeAnalyzers();
[5563]276      ParameterizeOperators();
[5558]277    }
278    private void ParameterizeSolutionCreator() {
[5563]279      if (SolutionCreator != null) {
280        SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.Absolute);
281        SolutionCreator.LengthParameter.Value = new IntValue(Weights.Rows);
282      }
[5558]283    }
284    private void ParameterizeEvaluator() {
[5563]285      if (Evaluator != null) {
286        Evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[5838]287        Evaluator.DistancesParameter.ActualName = DistancesParameter.Name;
[5563]288        Evaluator.WeightsParameter.ActualName = WeightsParameter.Name;
289      }
[5558]290    }
[5583]291    private void ParameterizeAnalyzers() {
292      if (BestQAPSolutionAnalyzer != null) {
293        BestQAPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
[5838]294        BestQAPSolutionAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
[5583]295        BestQAPSolutionAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
296        BestQAPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
297        BestQAPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
298        BestQAPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
[6342]299        BestQAPSolutionAnalyzer.BestKnownSolutionsParameter.ActualName = BestKnownSolutionsParameter.Name;
[5583]300        BestQAPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
301      }
[6342]302      if (QAPAlleleFrequencyAnalyzer != null) {
303        QAPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
304        QAPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
305        QAPAlleleFrequencyAnalyzer.DistancesParameter.ActualName = DistancesParameter.Name;
306        QAPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
307        QAPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
308        QAPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
309        QAPAlleleFrequencyAnalyzer.WeightsParameter.ActualName = WeightsParameter.Name;
310      }
311      if (QAPPopulationDiversityAnalyzer != null) {
312        QAPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
313        QAPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
314        QAPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
315        QAPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
316      }
[5583]317    }
[5562]318    private void ParameterizeOperators() {
319      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
320        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
321        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
322      }
323      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
324        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
325      }
326      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
327        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
328      }
[5563]329      if (Operators.OfType<IMoveGenerator>().Any()) {
330        string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
331        foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
332          op.InversionMoveParameter.ActualName = inversionMove;
333        string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
334        foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
335          op.TranslocationMoveParameter.ActualName = translocationMove;
[5838]336        string swapMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationSwap2MoveOperator>().First().Swap2MoveParameter.ActualName;
337        foreach (IPermutationSwap2MoveOperator op in Operators.OfType<IPermutationSwap2MoveOperator>()) {
338          op.Swap2MoveParameter.ActualName = swapMove;
[5785]339        }
[5563]340      }
[6042]341      foreach (var op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>())
342        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6342]343
344      QAPExhaustiveSwap2LocalImprovement localOpt = Operators.OfType<QAPExhaustiveSwap2LocalImprovement>().SingleOrDefault();
345      if (localOpt != null) {
346        localOpt.AssignmentParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
347        localOpt.DistancesParameter.ActualName = DistancesParameter.Name;
348        localOpt.MaximizationParameter.ActualName = MaximizationParameter.Name;
349        localOpt.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
350        localOpt.WeightsParameter.ActualName = WeightsParameter.Name;
351      }
[5562]352    }
[5598]353
[5855]354    private void AdjustDistanceMatrix() {
355      if (Distances.Rows != Weights.Rows || Distances.Columns != Weights.Columns) {
356        ((IStringConvertibleMatrix)Distances).Rows = Weights.Rows;
357      }
358    }
359
360    private void AdjustWeightsMatrix() {
361      if (Weights.Rows != Distances.Rows || Weights.Columns != Distances.Columns) {
362        ((IStringConvertibleMatrix)Weights).Rows = Distances.Rows;
363      }
364    }
[5558]365    #endregion
[5562]366
[6891]367    public void LoadInstanceFromFile(string filename) {
[5562]368      QAPLIBParser parser = new QAPLIBParser();
369      parser.Parse(filename);
[5641]370      if (parser.Error != null) throw parser.Error;
[5838]371      Distances = new DoubleMatrix(parser.Distances);
[5562]372      Weights = new DoubleMatrix(parser.Weights);
373      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(filename) + ")";
374      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
[5598]375      BestKnownQuality = null;
[6891]376      BestKnownSolution = null;
[6342]377      BestKnownSolutions = null;
[5562]378      OnReset();
379    }
[5563]380
[6891]381    public void LoadInstanceFromFile(string datFilename, string slnFilename) {
382      QAPLIBParser datParser = new QAPLIBParser();
383      datParser.Parse(datFilename);
384      if (datParser.Error != null) throw datParser.Error;
385      Distances = new DoubleMatrix(datParser.Distances);
386      Weights = new DoubleMatrix(datParser.Weights);
387      Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(datFilename) + ")";
388      Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
389
390      QAPLIBSolutionParser slnParser = new QAPLIBSolutionParser();
391      slnParser.Parse(slnFilename, true);
392      if (slnParser.Error != null) throw slnParser.Error;
393
394      BestKnownQuality = new DoubleValue(slnParser.Quality);
395      BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
396      BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
397      BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
398
399      if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
400        // the solution doesn't result in the given quality, maybe indices and values are inverted
401        // try parsing again, this time inverting them
402        slnParser.Reset();
403        slnParser.Parse(slnFilename, false);
404        if (slnParser.Error != null) throw slnParser.Error;
405
406        BestKnownQuality = new DoubleValue(slnParser.Quality);
407        BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
408        BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
409        BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
410
411        if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
412          // if the solution still doesn't result in the given quality, remove it and only take the quality
413          BestKnownSolution = null;
414          BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
[5598]415        }
416      }
[6891]417      OnReset();
[5563]418    }
[6952]419
420    public void LoadInstanceFromEmbeddedResource(string instance) {
421      using (Stream stream = Assembly.GetExecutingAssembly()
422        .GetManifestResourceStream(InstancePrefix + instance + ".dat")) {
423        QAPLIBParser datParser = new QAPLIBParser();
424        datParser.Parse(stream);
425        if (datParser.Error != null) throw datParser.Error;
426        Distances = new DoubleMatrix(datParser.Distances);
427        Weights = new DoubleMatrix(datParser.Weights);
428        Name = instance;
429        Description = "Loaded embedded instance " + instance + " of plugin version " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
430
431        bool solutionExists = Assembly.GetExecutingAssembly()
432          .GetManifestResourceNames()
433          .Where(x => x.EndsWith(instance + ".sln"))
434          .Any();
435
436        if (solutionExists) {
437          using (Stream solStream = Assembly.GetExecutingAssembly()
438            .GetManifestResourceStream(InstancePrefix + instance + ".sln")) {
439            QAPLIBSolutionParser slnParser = new QAPLIBSolutionParser();
440            slnParser.Parse(solStream, true);
441            if (slnParser.Error != null) throw slnParser.Error;
442
443            BestKnownQuality = new DoubleValue(slnParser.Quality);
444            BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
445            BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
446            BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
447
448            if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
449              // the solution doesn't result in the given quality, maybe indices and values are inverted
450              // try parsing again, this time inverting them
451              solStream.Seek(0, SeekOrigin.Begin);
452              slnParser.Reset();
453              slnParser.Parse(solStream, false);
454              if (slnParser.Error != null) throw slnParser.Error;
455
456              BestKnownQuality = new DoubleValue(slnParser.Quality);
457              BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
458              BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
459              BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
460
461              if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
462                // if the solution still doesn't result in the given quality, remove it and only take the quality
463                BestKnownSolution = null;
464                BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
465              }
466            }
467          }
[7041]468        } else {  // no solution exists
469          BestKnownSolution = null;
470          BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
471          BestKnownQuality = null;
[6952]472        }
473      }
474      OnReset();
475    }
[5558]476  }
477}
Note: See TracBrowser for help on using the repository browser.