Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs @ 7615

Last change on this file since 7615 was 7615, checked in by gkronber, 13 years ago

#1081 merged r7462:7609 from trunk into time series branch

File size: 19.5 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 ValueParameter<DoubleMatrix> CoordinatesParameter {
47      get { return (ValueParameter<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 ValueParameter<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      UpdateMoveEvaluators();
151      ParameterizeAnalyzers();
152      ClearDistanceMatrix();
153    }
154    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
155      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
156      Coordinates.Reset += new EventHandler(Coordinates_Reset);
157      ParameterizeSolutionCreator();
158      ClearDistanceMatrix();
159    }
160    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
161      ClearDistanceMatrix();
162    }
163    private void Coordinates_Reset(object sender, EventArgs e) {
164      ParameterizeSolutionCreator();
165      ClearDistanceMatrix();
166    }
167    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
168      ParameterizeEvaluator();
169      ParameterizeAnalyzers();
170      ParameterizeOperators();
171    }
172    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
173      ParameterizeAnalyzers();
174    }
175    #endregion
176
177    #region Helpers
178    [StorableHook(HookType.AfterDeserialization)]
179    private void AfterDeserialization() {
180      // BackwardsCompatibility3.3
181      #region Backwards compatible code (remove with 3.4)
182      OptionalValueParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as OptionalValueParameter<DoubleMatrix>;
183      if (oldDistanceMatrixParameter != null) {
184        Parameters.Remove(oldDistanceMatrixParameter);
185        Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
186        DistanceMatrixParameter.GetsCollected = oldDistanceMatrixParameter.GetsCollected;
187        DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
188        if (oldDistanceMatrixParameter.Value != null) {
189          DoubleMatrix oldDM = oldDistanceMatrixParameter.Value;
190          DistanceMatrix newDM = new DistanceMatrix(oldDM.Rows, oldDM.Columns, oldDM.ColumnNames, oldDM.RowNames);
191          newDM.SortableView = oldDM.SortableView;
192          for (int i = 0; i < newDM.Rows; i++)
193            for (int j = 0; j < newDM.Columns; j++)
194              newDM[i, j] = oldDM[i, j];
195          DistanceMatrixParameter.Value = (DistanceMatrix)newDM.AsReadOnly();
196        }
197      }
198
199      if (Operators.Count == 0) InitializeOperators();
200      #endregion
201      RegisterEventHandlers();
202    }
203
204    private void RegisterEventHandlers() {
205      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
206      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
207      Coordinates.Reset += new EventHandler(Coordinates_Reset);
208      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
209      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
210    }
211
212    private void InitializeOperators() {
213      Operators.Add(new BestTSPSolutionAnalyzer());
214      Operators.Add(new TSPAlleleFrequencyAnalyzer());
215      Operators.Add(new TSPPopulationDiversityAnalyzer());
216      ParameterizeAnalyzers();
217      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
218      ParameterizeOperators();
219      UpdateMoveEvaluators();
220    }
221    private void UpdateMoveEvaluators() {
222      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
223      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
224        if (op.EvaluatorType == Evaluator.GetType()) {
225          Operators.Add(op);
226        }
227      ParameterizeOperators();
228      OnOperatorsChanged();
229    }
230    private void ParameterizeSolutionCreator() {
231      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
232      SolutionCreator.LengthParameter.Hidden = true;
233      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
234      SolutionCreator.PermutationTypeParameter.Hidden = true;
235    }
236    private void ParameterizeEvaluator() {
237      if (Evaluator is ITSPPathEvaluator) {
238        ITSPPathEvaluator evaluator = (ITSPPathEvaluator)Evaluator;
239        evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
240        evaluator.PermutationParameter.Hidden = true;
241      }
242      if (Evaluator is ITSPCoordinatesPathEvaluator) {
243        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
244        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
245        evaluator.CoordinatesParameter.Hidden = true;
246        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
247        evaluator.DistanceMatrixParameter.Hidden = true;
248        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
249        evaluator.UseDistanceMatrixParameter.Hidden = true;
250      }
251      if (Evaluator is ITSPDistanceMatrixEvaluator) {
252        var evaluator = (ITSPDistanceMatrixEvaluator)Evaluator;
253        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
254        evaluator.DistanceMatrixParameter.Hidden = true;
255      }
256    }
257    private void ParameterizeAnalyzers() {
258      if (BestTSPSolutionAnalyzer != null) {
259        BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
260        BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
261        BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
262        BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
263        BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
264        BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
265        BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
266      }
267
268      if (TSPAlleleFrequencyAnalyzer != null) {
269        TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
270        TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
271        TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
272        TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
273        TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
274        TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
275        TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
276      }
277
278      if (TSPPopulationDiversityAnalyzer != null) {
279        TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
280        TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
281        TSPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
282        TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
283      }
284    }
285    private void ParameterizeOperators() {
286      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
287        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
288        op.ParentsParameter.Hidden = true;
289        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
290        op.ChildParameter.Hidden = true;
291      }
292      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
293        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
294        op.PermutationParameter.Hidden = true;
295      }
296      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
297        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
298        op.PermutationParameter.Hidden = true;
299      }
300      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
301        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
302        op.CoordinatesParameter.Hidden = true;
303        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
304        op.DistanceMatrixParameter.Hidden = true;
305        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
306        op.UseDistanceMatrixParameter.Hidden = true;
307        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
308        op.QualityParameter.Hidden = true;
309        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
310        op.PermutationParameter.Hidden = true;
311      }
312      foreach (IPermutationMultiNeighborhoodShakingOperator op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>()) {
313        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
314        op.PermutationParameter.Hidden = true;
315      }
316    }
317
318    private void ClearDistanceMatrix() {
319      if (!(Evaluator is ITSPDistanceMatrixEvaluator))
320        DistanceMatrixParameter.Value = null;
321    }
322    #endregion
323
324    public void Load(TSPData data) {
325      if (data.Coordinates == null && data.Distances == null)
326        throw new System.IO.InvalidDataException("The given instance does not specify neither coordinates or distances!");
327      if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == TSPDistanceMeasure.Att
328        || data.DistanceMeasure == TSPDistanceMeasure.Manhattan
329        || data.DistanceMeasure == TSPDistanceMeasure.Maximum
330        || data.DistanceMeasure == TSPDistanceMeasure.UpperEuclidean))
331        throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix.");
332      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
333        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.");
334
335      Name = data.Name;
336      Description = data.Description;
337
338      if (data.Coordinates != null && data.Coordinates.GetLength(0) > 0)
339        Coordinates = new DoubleMatrix(data.Coordinates);
340
341      TSPEvaluator evaluator;
342      if (data.DistanceMeasure == TSPDistanceMeasure.Att
343        || data.DistanceMeasure == TSPDistanceMeasure.Manhattan
344        || data.DistanceMeasure == TSPDistanceMeasure.Maximum
345        || data.DistanceMeasure == TSPDistanceMeasure.UpperEuclidean) {
346        evaluator = new TSPDistanceMatrixEvaluator();
347        UseDistanceMatrix = new BoolValue(true);
348        DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
349      } else if (data.DistanceMeasure == TSPDistanceMeasure.Direct && data.Distances != null) {
350        evaluator = new TSPDistanceMatrixEvaluator();
351        UseDistanceMatrix = new BoolValue(true);
352        DistanceMatrix = new DistanceMatrix(data.Distances);
353      } else {
354        DistanceMatrix = null;
355        UseDistanceMatrix = new BoolValue(data.Dimension <= DistanceMatrixSizeLimit);
356        switch (data.DistanceMeasure) {
357          case TSPDistanceMeasure.Euclidean:
358            evaluator = new TSPEuclideanPathEvaluator();
359            break;
360          case TSPDistanceMeasure.RoundedEuclidean:
361            evaluator = new TSPRoundedEuclideanPathEvaluator();
362            break;
363          case TSPDistanceMeasure.Geo:
364            evaluator = new TSPGeoPathEvaluator();
365            break;
366          default:
367            throw new InvalidDataException("An unknown distance measure is given in the instance!");
368        }
369      }
370      evaluator.QualityParameter.ActualName = "TSPTourLength";
371      Evaluator = evaluator;
372
373      BestKnownSolution = null;
374      BestKnownQuality = null;
375
376      if (data.BestKnownTour != null) {
377        try {
378          EvaluateAndLoadTour(data.BestKnownTour);
379        } catch (InvalidOperationException) {
380          if (data.BestKnownQuality.HasValue)
381            BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
382        }
383      } else if (data.BestKnownQuality.HasValue) {
384        BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
385      }
386      OnReset();
387    }
388
389    public void EvaluateAndLoadTour(int[] tour) {
390      var route = new Permutation(PermutationTypes.RelativeUndirected, tour);
391      BestKnownSolution = route;
392
393      double quality;
394      if (Evaluator is TSPDistanceMatrixEvaluator) {
395        quality = TSPDistanceMatrixEvaluator.Apply(DistanceMatrix, route);
396      } else if (Evaluator is TSPCoordinatesPathEvaluator) {
397        quality = TSPCoordinatesPathEvaluator.Apply((TSPCoordinatesPathEvaluator)Evaluator, Coordinates, route);
398      } else {
399        throw new InvalidOperationException("Cannot calculate solution quality, evaluator type is unknown.");
400      }
401      BestKnownQuality = new DoubleValue(quality);
402    }
403  }
404}
Note: See TracBrowser for help on using the repository browser.