Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs @ 11291

Last change on this file since 11291 was 8660, checked in by gkronber, 12 years ago

#1847 merged r8205:8635 from trunk into branch

File size: 23.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.IO;
25using System.Linq;
26using HeuristicLab.Analysis;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.PermutationEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35using HeuristicLab.Problems.Instances;
36
37namespace HeuristicLab.Problems.TravelingSalesman {
38  [Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
39  [Creatable("Problems")]
40  [StorableClass]
41  public sealed class TravelingSalesmanProblem : SingleObjectiveHeuristicOptimizationProblem<ITSPEvaluator, IPermutationCreator>, IStorableContent,
42    IProblemInstanceConsumer<TSPData> {
43    private static readonly int DistanceMatrixSizeLimit = 1000;
44    public string Filename { get; set; }
45
46    #region Parameter Properties
47    public OptionalValueParameter<DoubleMatrix> CoordinatesParameter {
48      get { return (OptionalValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
49    }
50    public OptionalValueParameter<DistanceMatrix> DistanceMatrixParameter {
51      get { return (OptionalValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
52    }
53    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
54      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
55    }
56    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
57      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
58    }
59    #endregion
60
61    #region Properties
62    public DoubleMatrix Coordinates {
63      get { return CoordinatesParameter.Value; }
64      set { CoordinatesParameter.Value = value; }
65    }
66    public DistanceMatrix DistanceMatrix {
67      get { return DistanceMatrixParameter.Value; }
68      set { DistanceMatrixParameter.Value = value; }
69    }
70    public BoolValue UseDistanceMatrix {
71      get { return UseDistanceMatrixParameter.Value; }
72      set { UseDistanceMatrixParameter.Value = value; }
73    }
74    public Permutation BestKnownSolution {
75      get { return BestKnownSolutionParameter.Value; }
76      set { BestKnownSolutionParameter.Value = value; }
77    }
78    private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
79      get { return Operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
80    }
81    private TSPAlleleFrequencyAnalyzer TSPAlleleFrequencyAnalyzer {
82      get { return Operators.OfType<TSPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
83    }
84    private TSPPopulationDiversityAnalyzer TSPPopulationDiversityAnalyzer {
85      get { return Operators.OfType<TSPPopulationDiversityAnalyzer>().FirstOrDefault(); }
86    }
87    private SingleObjectivePopulationDiversityAnalyzer SingleObjectivePopulationDiversityAnalyzer {
88      get { return Operators.OfType<SingleObjectivePopulationDiversityAnalyzer>().FirstOrDefault(); }
89    }
90    #endregion
91
92    // BackwardsCompatibility3.3
93    #region Backwards compatible code, remove with 3.4
94    [Obsolete]
95    [Storable(Name = "operators")]
96    private IEnumerable<IOperator> oldOperators {
97      get { return null; }
98      set {
99        if (value != null && value.Any())
100          Operators.AddRange(value);
101      }
102    }
103    #endregion
104
105    [StorableConstructor]
106    private TravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
107    private TravelingSalesmanProblem(TravelingSalesmanProblem original, Cloner cloner)
108      : base(original, cloner) {
109      RegisterEventHandlers();
110    }
111    public override IDeepCloneable Clone(Cloner cloner) {
112      return new TravelingSalesmanProblem(this, cloner);
113    }
114    public TravelingSalesmanProblem()
115      : base(new TSPRoundedEuclideanPathEvaluator(), new RandomPermutationCreator()) {
116      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
117      Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
118      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if the coordinates based evaluators should calculate the distance matrix from the coordinates and use it for evaluation similar to the distance matrix evaluator, otherwise false.", new BoolValue(true)));
119      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
120
121      Maximization.Value = false;
122      MaximizationParameter.Hidden = true;
123      UseDistanceMatrixParameter.Hidden = true;
124      DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
125
126      Coordinates = new DoubleMatrix(new double[,] {
127        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
128        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
129        { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
130        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
131      });
132
133      SolutionCreator.PermutationParameter.ActualName = "TSPTour";
134      Evaluator.QualityParameter.ActualName = "TSPTourLength";
135      ParameterizeSolutionCreator();
136      ParameterizeEvaluator();
137
138      InitializeOperators();
139      RegisterEventHandlers();
140    }
141
142    #region Events
143    protected override void OnSolutionCreatorChanged() {
144      base.OnSolutionCreatorChanged();
145      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
146      ParameterizeSolutionCreator();
147      ParameterizeEvaluator();
148      ParameterizeAnalyzers();
149      ParameterizeOperators();
150    }
151    protected override void OnEvaluatorChanged() {
152      base.OnEvaluatorChanged();
153      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
154      ParameterizeEvaluator();
155      ParameterizeSolutionCreator();
156      UpdateMoveEvaluators();
157      ParameterizeAnalyzers();
158      if (Evaluator is ITSPCoordinatesPathEvaluator && Coordinates != null)
159        ClearDistanceMatrix();
160    }
161    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
162      if (Coordinates != null) {
163        Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
164        Coordinates.Reset += new EventHandler(Coordinates_Reset);
165      }
166      if (Evaluator is ITSPCoordinatesPathEvaluator) {
167        ParameterizeSolutionCreator();
168        ClearDistanceMatrix();
169      }
170    }
171    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
172      if (Evaluator is ITSPCoordinatesPathEvaluator) {
173        ClearDistanceMatrix();
174      }
175    }
176    private void Coordinates_Reset(object sender, EventArgs e) {
177      if (Evaluator is ITSPCoordinatesPathEvaluator) {
178        ParameterizeSolutionCreator();
179        ClearDistanceMatrix();
180      }
181    }
182    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
183      ParameterizeEvaluator();
184      ParameterizeAnalyzers();
185      ParameterizeOperators();
186    }
187    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
188      ParameterizeAnalyzers();
189    }
190    #endregion
191
192    #region Helpers
193    [StorableHook(HookType.AfterDeserialization)]
194    private void AfterDeserialization() {
195      // BackwardsCompatibility3.3
196      #region Backwards compatible code (remove with 3.4)
197      OptionalValueParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as OptionalValueParameter<DoubleMatrix>;
198      if (oldDistanceMatrixParameter != null) {
199        Parameters.Remove(oldDistanceMatrixParameter);
200        Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
201        DistanceMatrixParameter.GetsCollected = oldDistanceMatrixParameter.GetsCollected;
202        DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
203        if (oldDistanceMatrixParameter.Value != null) {
204          DoubleMatrix oldDM = oldDistanceMatrixParameter.Value;
205          DistanceMatrix newDM = new DistanceMatrix(oldDM.Rows, oldDM.Columns, oldDM.ColumnNames, oldDM.RowNames);
206          newDM.SortableView = oldDM.SortableView;
207          for (int i = 0; i < newDM.Rows; i++)
208            for (int j = 0; j < newDM.Columns; j++)
209              newDM[i, j] = oldDM[i, j];
210          DistanceMatrixParameter.Value = (DistanceMatrix)newDM.AsReadOnly();
211        }
212      }
213
214      ValueParameter<DoubleMatrix> oldCoordinates = (Parameters["Coordinates"] as ValueParameter<DoubleMatrix>);
215      if (oldCoordinates != null) {
216        Parameters.Remove(oldCoordinates);
217        Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities.", oldCoordinates.Value, oldCoordinates.GetsCollected));
218      }
219
220      if (Operators.Count == 0) InitializeOperators();
221      #endregion
222      RegisterEventHandlers();
223    }
224
225    private void RegisterEventHandlers() {
226      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
227      if (Coordinates != null) {
228        Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
229        Coordinates.Reset += new EventHandler(Coordinates_Reset);
230      }
231      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
232      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
233    }
234
235    private void InitializeOperators() {
236      Operators.Add(new TSPImprovementOperator());
237      Operators.Add(new TSPMultipleGuidesPathRelinker());
238      Operators.Add(new TSPPathRelinker());
239      Operators.Add(new TSPSimultaneousPathRelinker());
240      Operators.Add(new TSPSimilarityCalculator());
241
242      Operators.Add(new BestTSPSolutionAnalyzer());
243      Operators.Add(new TSPAlleleFrequencyAnalyzer());
244      Operators.Add(new SingleObjectivePopulationDiversityAnalyzer());
245      ParameterizeAnalyzers();
246      var operators = new HashSet<IPermutationOperator>(new IPermutationOperator[] {
247        new OrderCrossover2(),
248        new InversionManipulator(),
249        new StochasticInversionMultiMoveGenerator()
250      }, new TypeEqualityComparer<IPermutationOperator>());
251      foreach (var op in ApplicationManager.Manager.GetInstances<IPermutationOperator>())
252        operators.Add(op);
253      Operators.AddRange(operators);
254      ParameterizeOperators();
255      UpdateMoveEvaluators();
256    }
257    private void UpdateMoveEvaluators() {
258      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
259      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
260        if (op.EvaluatorType == Evaluator.GetType()) {
261          Operators.Add(op);
262        }
263      ParameterizeOperators();
264      OnOperatorsChanged();
265    }
266    private void ParameterizeSolutionCreator() {
267      if (Evaluator is ITSPDistanceMatrixEvaluator && DistanceMatrix != null)
268        SolutionCreator.LengthParameter.Value = new IntValue(DistanceMatrix.Rows);
269      else if (Evaluator is ITSPCoordinatesPathEvaluator && Coordinates != null)
270        SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
271      else {
272        SolutionCreator.LengthParameter.Value = null;
273        string error = "The given problem does not support the selected evaluator.";
274        if (Evaluator is ITSPDistanceMatrixEvaluator)
275          error += Environment.NewLine + "Please review that the " + DistanceMatrixParameter.Name + " parameter is defined or choose another evaluator.";
276        else error += Environment.NewLine + "Please review that the " + CoordinatesParameter.Name + " parameter is defined or choose another evaluator.";
277        PluginInfrastructure.ErrorHandling.ShowErrorDialog(error, null);
278      }
279      SolutionCreator.LengthParameter.Hidden = SolutionCreator.LengthParameter.Value != null;
280      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
281      SolutionCreator.PermutationTypeParameter.Hidden = true;
282    }
283    private void ParameterizeEvaluator() {
284      if (Evaluator is ITSPPathEvaluator) {
285        ITSPPathEvaluator evaluator = (ITSPPathEvaluator)Evaluator;
286        evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
287        evaluator.PermutationParameter.Hidden = true;
288      }
289      if (Evaluator is ITSPCoordinatesPathEvaluator) {
290        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
291        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
292        evaluator.CoordinatesParameter.Hidden = true;
293        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
294        evaluator.DistanceMatrixParameter.Hidden = true;
295        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
296        evaluator.UseDistanceMatrixParameter.Hidden = true;
297      }
298      if (Evaluator is ITSPDistanceMatrixEvaluator) {
299        var evaluator = (ITSPDistanceMatrixEvaluator)Evaluator;
300        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
301        evaluator.DistanceMatrixParameter.Hidden = true;
302      }
303    }
304    private void ParameterizeAnalyzers() {
305      if (BestTSPSolutionAnalyzer != null) {
306        BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
307        BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
308        BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
309        BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
310        BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
311        BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
312        BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
313      }
314
315      if (TSPAlleleFrequencyAnalyzer != null) {
316        TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
317        TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
318        TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
319        TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
320        TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
321        TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
322        TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
323      }
324
325      if (TSPPopulationDiversityAnalyzer != null) {
326        TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
327        TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
328        TSPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
329        TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
330      }
331
332      if (SingleObjectivePopulationDiversityAnalyzer != null) {
333        SingleObjectivePopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
334        SingleObjectivePopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
335        SingleObjectivePopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
336        SingleObjectivePopulationDiversityAnalyzer.SimilarityCalculator = Operators.OfType<TSPSimilarityCalculator>().SingleOrDefault();
337      }
338    }
339    private void ParameterizeOperators() {
340      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
341        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
342        op.ParentsParameter.Hidden = true;
343        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
344        op.ChildParameter.Hidden = true;
345      }
346      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
347        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
348        op.PermutationParameter.Hidden = true;
349      }
350      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
351        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
352        op.PermutationParameter.Hidden = true;
353      }
354      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
355        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
356        op.CoordinatesParameter.Hidden = true;
357        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
358        op.DistanceMatrixParameter.Hidden = true;
359        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
360        op.UseDistanceMatrixParameter.Hidden = true;
361        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
362        op.QualityParameter.Hidden = true;
363        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
364        op.PermutationParameter.Hidden = true;
365      }
366      foreach (IPermutationMultiNeighborhoodShakingOperator op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>()) {
367        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
368        op.PermutationParameter.Hidden = true;
369      }
370      foreach (ISingleObjectiveImprovementOperator op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
371        op.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
372        op.SolutionParameter.Hidden = true;
373      }
374      foreach (ISingleObjectivePathRelinker op in Operators.OfType<ISingleObjectivePathRelinker>()) {
375        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
376        op.ParentsParameter.Hidden = true;
377      }
378      foreach (TSPSimilarityCalculator op in Operators.OfType<TSPSimilarityCalculator>()) {
379        op.SolutionVariableName = SolutionCreator.PermutationParameter.ActualName;
380        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
381      }
382    }
383
384    private void ClearDistanceMatrix() {
385      DistanceMatrixParameter.Value = null;
386    }
387    #endregion
388
389    public void Load(TSPData data) {
390      if (data.Coordinates == null && data.Distances == null)
391        throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
392      if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == DistanceMeasure.Att
393        || data.DistanceMeasure == DistanceMeasure.Manhattan
394        || data.DistanceMeasure == DistanceMeasure.Maximum
395        || data.DistanceMeasure == DistanceMeasure.UpperEuclidean))
396        throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix.");
397      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
398        throw new System.IO.InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
399
400      Name = data.Name;
401      Description = data.Description;
402
403      bool clearCoordinates = false, clearDistanceMatrix = false;
404      if (data.Coordinates != null && data.Coordinates.GetLength(0) > 0)
405        Coordinates = new DoubleMatrix(data.Coordinates);
406      else clearCoordinates = true;
407
408      TSPEvaluator evaluator;
409      if (data.DistanceMeasure == DistanceMeasure.Att
410        || data.DistanceMeasure == DistanceMeasure.Manhattan
411        || data.DistanceMeasure == DistanceMeasure.Maximum
412        || data.DistanceMeasure == DistanceMeasure.UpperEuclidean) {
413        evaluator = new TSPDistanceMatrixEvaluator();
414        UseDistanceMatrix = new BoolValue(true);
415        DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
416      } else if (data.DistanceMeasure == DistanceMeasure.Direct && data.Distances != null) {
417        evaluator = new TSPDistanceMatrixEvaluator();
418        UseDistanceMatrix = new BoolValue(true);
419        DistanceMatrix = new DistanceMatrix(data.Distances);
420      } else {
421        clearDistanceMatrix = true;
422        UseDistanceMatrix = new BoolValue(data.Dimension <= DistanceMatrixSizeLimit);
423        switch (data.DistanceMeasure) {
424          case DistanceMeasure.Euclidean:
425            evaluator = new TSPEuclideanPathEvaluator();
426            break;
427          case DistanceMeasure.RoundedEuclidean:
428            evaluator = new TSPRoundedEuclideanPathEvaluator();
429            break;
430          case DistanceMeasure.Geo:
431            evaluator = new TSPGeoPathEvaluator();
432            break;
433          default:
434            throw new InvalidDataException("An unknown distance measure is given in the instance!");
435        }
436      }
437      evaluator.QualityParameter.ActualName = "TSPTourLength";
438      Evaluator = evaluator;
439
440      // reset them after assigning the evaluator
441      if (clearCoordinates) Coordinates = null;
442      if (clearDistanceMatrix) DistanceMatrix = null;
443
444      BestKnownSolution = null;
445      BestKnownQuality = null;
446
447      if (data.BestKnownTour != null) {
448        try {
449          EvaluateAndLoadTour(data.BestKnownTour);
450        } catch (InvalidOperationException) {
451          if (data.BestKnownQuality.HasValue)
452            BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
453        }
454      } else if (data.BestKnownQuality.HasValue) {
455        BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
456      }
457      OnReset();
458    }
459
460    public void EvaluateAndLoadTour(int[] tour) {
461      var route = new Permutation(PermutationTypes.RelativeUndirected, tour);
462      BestKnownSolution = route;
463
464      double quality;
465      if (Evaluator is ITSPDistanceMatrixEvaluator) {
466        quality = TSPDistanceMatrixEvaluator.Apply(DistanceMatrix, route);
467      } else if (Evaluator is ITSPCoordinatesPathEvaluator) {
468        quality = TSPCoordinatesPathEvaluator.Apply((TSPCoordinatesPathEvaluator)Evaluator, Coordinates, route);
469      } else {
470        throw new InvalidOperationException("Cannot calculate solution quality, evaluator type is unknown.");
471      }
472      BestKnownQuality = new DoubleValue(quality);
473    }
474  }
475}
Note: See TracBrowser for help on using the repository browser.