Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs @ 11813

Last change on this file since 11813 was 11171, checked in by ascheibe, 10 years ago

#2115 merged r11170 (copyright update) into trunk

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