Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1396:

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