Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8072 was 7872, checked in by svonolfe, 12 years ago

Moved distance measure to helper class (#1782)

File size: 20.7 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      var operators = new HashSet<IPermutationOperator>(new IPermutationOperator[] {
229        new OrderCrossover2(),
230        new InversionManipulator(),
231        new StochasticInversionMultiMoveGenerator()
232      }, new TypeEqualityComparer<IPermutationOperator>());
233      foreach (var op in ApplicationManager.Manager.GetInstances<IPermutationOperator>())
234        operators.Add(op);
235      Operators.AddRange(operators);
236      ParameterizeOperators();
237      UpdateMoveEvaluators();
238    }
239    private void UpdateMoveEvaluators() {
240      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
241      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
242        if (op.EvaluatorType == Evaluator.GetType()) {
243          Operators.Add(op);
244        }
245      ParameterizeOperators();
246      OnOperatorsChanged();
247    }
248    private void ParameterizeSolutionCreator() {
249      if (Evaluator is ITSPDistanceMatrixEvaluator && DistanceMatrix != null)
250        SolutionCreator.LengthParameter.Value = new IntValue(DistanceMatrix.Rows);
251      else if (Evaluator is ITSPCoordinatesPathEvaluator && Coordinates != null)
252        SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
253      else SolutionCreator.LengthParameter.Value = null;
254      SolutionCreator.LengthParameter.Hidden = SolutionCreator.LengthParameter.Value != null;
255      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
256      SolutionCreator.PermutationTypeParameter.Hidden = true;
257    }
258    private void ParameterizeEvaluator() {
259      if (Evaluator is ITSPPathEvaluator) {
260        ITSPPathEvaluator evaluator = (ITSPPathEvaluator)Evaluator;
261        evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
262        evaluator.PermutationParameter.Hidden = true;
263      }
264      if (Evaluator is ITSPCoordinatesPathEvaluator) {
265        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
266        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
267        evaluator.CoordinatesParameter.Hidden = true;
268        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
269        evaluator.DistanceMatrixParameter.Hidden = true;
270        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
271        evaluator.UseDistanceMatrixParameter.Hidden = true;
272      }
273      if (Evaluator is ITSPDistanceMatrixEvaluator) {
274        var evaluator = (ITSPDistanceMatrixEvaluator)Evaluator;
275        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
276        evaluator.DistanceMatrixParameter.Hidden = true;
277      }
278    }
279    private void ParameterizeAnalyzers() {
280      if (BestTSPSolutionAnalyzer != null) {
281        BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
282        BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
283        BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
284        BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
285        BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
286        BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
287        BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
288      }
289
290      if (TSPAlleleFrequencyAnalyzer != null) {
291        TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
292        TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
293        TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
294        TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
295        TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
296        TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
297        TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
298      }
299
300      if (TSPPopulationDiversityAnalyzer != null) {
301        TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
302        TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
303        TSPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
304        TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
305      }
306    }
307    private void ParameterizeOperators() {
308      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
309        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
310        op.ParentsParameter.Hidden = true;
311        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
312        op.ChildParameter.Hidden = true;
313      }
314      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
315        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
316        op.PermutationParameter.Hidden = true;
317      }
318      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
319        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
320        op.PermutationParameter.Hidden = true;
321      }
322      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
323        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
324        op.CoordinatesParameter.Hidden = true;
325        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
326        op.DistanceMatrixParameter.Hidden = true;
327        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
328        op.UseDistanceMatrixParameter.Hidden = true;
329        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
330        op.QualityParameter.Hidden = true;
331        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
332        op.PermutationParameter.Hidden = true;
333      }
334      foreach (IPermutationMultiNeighborhoodShakingOperator op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>()) {
335        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
336        op.PermutationParameter.Hidden = true;
337      }
338    }
339
340    private void ClearDistanceMatrix() {
341      if (!(Evaluator is ITSPDistanceMatrixEvaluator))
342        DistanceMatrixParameter.Value = null;
343    }
344    #endregion
345
346    public void Load(TSPData data) {
347      if (data.Coordinates == null && data.Distances == null)
348        throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
349      if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == DistanceMeasure.Att
350        || data.DistanceMeasure == DistanceMeasure.Manhattan
351        || data.DistanceMeasure == DistanceMeasure.Maximum
352        || data.DistanceMeasure == DistanceMeasure.UpperEuclidean))
353        throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix.");
354      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
355        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.");
356
357      Name = data.Name;
358      Description = data.Description;
359
360      if (data.Coordinates != null && data.Coordinates.GetLength(0) > 0)
361        Coordinates = new DoubleMatrix(data.Coordinates);
362      else Coordinates = null;
363
364      TSPEvaluator evaluator;
365      if (data.DistanceMeasure == DistanceMeasure.Att
366        || data.DistanceMeasure == DistanceMeasure.Manhattan
367        || data.DistanceMeasure == DistanceMeasure.Maximum
368        || data.DistanceMeasure == DistanceMeasure.UpperEuclidean) {
369        evaluator = new TSPDistanceMatrixEvaluator();
370        UseDistanceMatrix = new BoolValue(true);
371        DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
372      } else if (data.DistanceMeasure == DistanceMeasure.Direct && data.Distances != null) {
373        evaluator = new TSPDistanceMatrixEvaluator();
374        UseDistanceMatrix = new BoolValue(true);
375        DistanceMatrix = new DistanceMatrix(data.Distances);
376      } else {
377        DistanceMatrix = null;
378        UseDistanceMatrix = new BoolValue(data.Dimension <= DistanceMatrixSizeLimit);
379        switch (data.DistanceMeasure) {
380          case DistanceMeasure.Euclidean:
381            evaluator = new TSPEuclideanPathEvaluator();
382            break;
383          case DistanceMeasure.RoundedEuclidean:
384            evaluator = new TSPRoundedEuclideanPathEvaluator();
385            break;
386          case DistanceMeasure.Geo:
387            evaluator = new TSPGeoPathEvaluator();
388            break;
389          default:
390            throw new InvalidDataException("An unknown distance measure is given in the instance!");
391        }
392      }
393      evaluator.QualityParameter.ActualName = "TSPTourLength";
394      Evaluator = evaluator;
395
396      BestKnownSolution = null;
397      BestKnownQuality = null;
398
399      if (data.BestKnownTour != null) {
400        try {
401          EvaluateAndLoadTour(data.BestKnownTour);
402        }
403        catch (InvalidOperationException) {
404          if (data.BestKnownQuality.HasValue)
405            BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
406        }
407      } else if (data.BestKnownQuality.HasValue) {
408        BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
409      }
410      OnReset();
411    }
412
413    public void EvaluateAndLoadTour(int[] tour) {
414      var route = new Permutation(PermutationTypes.RelativeUndirected, tour);
415      BestKnownSolution = route;
416
417      double quality;
418      if (Evaluator is ITSPDistanceMatrixEvaluator) {
419        quality = TSPDistanceMatrixEvaluator.Apply(DistanceMatrix, route);
420      } else if (Evaluator is ITSPCoordinatesPathEvaluator) {
421        quality = TSPCoordinatesPathEvaluator.Apply((TSPCoordinatesPathEvaluator)Evaluator, Coordinates, route);
422      } else {
423        throw new InvalidOperationException("Cannot calculate solution quality, evaluator type is unknown.");
424      }
425      BestKnownQuality = new DoubleValue(quality);
426    }
427  }
428}
Note: See TracBrowser for help on using the repository browser.