Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveHiveEngine/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs @ 7572

Last change on this file since 7572 was 7383, checked in by ascheibe, 13 years ago

#1745 merged trunk changes into branch

File size: 16.9 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;
34
35namespace HeuristicLab.Problems.TravelingSalesman {
36  [Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
37  [Creatable("Problems")]
38  [StorableClass]
39  public sealed class TravelingSalesmanProblem : SingleObjectiveHeuristicOptimizationProblem<ITSPEvaluator, IPermutationCreator>, IStorableContent {
40    public string Filename { get; set; }
41
42    #region Parameter Properties
43    public ValueParameter<DoubleMatrix> CoordinatesParameter {
44      get { return (ValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
45    }
46    public OptionalValueParameter<DistanceMatrix> DistanceMatrixParameter {
47      get { return (OptionalValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
48    }
49    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
50      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
51    }
52    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
53      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
54    }
55    #endregion
56
57    #region Properties
58    public DoubleMatrix Coordinates {
59      get { return CoordinatesParameter.Value; }
60      set { CoordinatesParameter.Value = value; }
61    }
62    public DistanceMatrix DistanceMatrix {
63      get { return DistanceMatrixParameter.Value; }
64      set { DistanceMatrixParameter.Value = value; }
65    }
66    public BoolValue UseDistanceMatrix {
67      get { return UseDistanceMatrixParameter.Value; }
68      set { UseDistanceMatrixParameter.Value = value; }
69    }
70    public Permutation BestKnownSolution {
71      get { return BestKnownSolutionParameter.Value; }
72      set { BestKnownSolutionParameter.Value = value; }
73    }
74    private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
75      get { return Operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
76    }
77    private TSPAlleleFrequencyAnalyzer TSPAlleleFrequencyAnalyzer {
78      get { return Operators.OfType<TSPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
79    }
80    private TSPPopulationDiversityAnalyzer TSPPopulationDiversityAnalyzer {
81      get { return Operators.OfType<TSPPopulationDiversityAnalyzer>().FirstOrDefault(); }
82    }
83    #endregion
84
85    // BackwardsCompatibility3.3
86    #region Backwards compatible code, remove with 3.4
87    [Obsolete]
88    [Storable(Name = "operators")]
89    private IEnumerable<IOperator> oldOperators {
90      get { return null; }
91      set {
92        if (value != null && value.Any())
93          Operators.AddRange(value);
94      }
95    }
96    #endregion
97
98    [StorableConstructor]
99    private TravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
100    private TravelingSalesmanProblem(TravelingSalesmanProblem original, Cloner cloner)
101      : base(original, cloner) {
102      RegisterEventHandlers();
103    }
104    public override IDeepCloneable Clone(Cloner cloner) {
105      return new TravelingSalesmanProblem(this, cloner);
106    }
107    public TravelingSalesmanProblem()
108      : base(new TSPRoundedEuclideanPathEvaluator(), new RandomPermutationCreator()) {
109
110      Parameters.Add(new ValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
111      Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
112      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false.", new BoolValue(true)));
113      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
114
115      Maximization.Value = false;
116      MaximizationParameter.Hidden = true;
117      DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
118
119      Coordinates = new DoubleMatrix(new double[,] {
120        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
121        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
122        { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
123        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
124      });
125
126      SolutionCreator.PermutationParameter.ActualName = "TSPTour";
127      Evaluator.QualityParameter.ActualName = "TSPTourLength";
128      ParameterizeSolutionCreator();
129      ParameterizeEvaluator();
130
131      InitializeOperators();
132      RegisterEventHandlers();
133    }
134
135    #region Events
136    protected override void OnSolutionCreatorChanged() {
137      base.OnSolutionCreatorChanged();
138      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
139      ParameterizeSolutionCreator();
140      ParameterizeEvaluator();
141      ParameterizeAnalyzers();
142      ParameterizeOperators();
143    }
144    protected override void OnEvaluatorChanged() {
145      base.OnEvaluatorChanged();
146      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
147      ParameterizeEvaluator();
148      UpdateMoveEvaluators();
149      ParameterizeAnalyzers();
150      ClearDistanceMatrix();
151    }
152    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
153      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
154      Coordinates.Reset += new EventHandler(Coordinates_Reset);
155      ParameterizeSolutionCreator();
156      ClearDistanceMatrix();
157    }
158    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
159      ClearDistanceMatrix();
160    }
161    private void Coordinates_Reset(object sender, EventArgs e) {
162      ParameterizeSolutionCreator();
163      ClearDistanceMatrix();
164    }
165    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
166      ParameterizeEvaluator();
167      ParameterizeAnalyzers();
168      ParameterizeOperators();
169    }
170    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
171      ParameterizeAnalyzers();
172    }
173    #endregion
174
175    #region Helpers
176    [StorableHook(HookType.AfterDeserialization)]
177    private void AfterDeserialization() {
178      // BackwardsCompatibility3.3
179      #region Backwards compatible code (remove with 3.4)
180      OptionalValueParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as OptionalValueParameter<DoubleMatrix>;
181      if (oldDistanceMatrixParameter != null) {
182        Parameters.Remove(oldDistanceMatrixParameter);
183        Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
184        DistanceMatrixParameter.GetsCollected = oldDistanceMatrixParameter.GetsCollected;
185        DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
186        if (oldDistanceMatrixParameter.Value != null) {
187          DoubleMatrix oldDM = oldDistanceMatrixParameter.Value;
188          DistanceMatrix newDM = new DistanceMatrix(oldDM.Rows, oldDM.Columns, oldDM.ColumnNames, oldDM.RowNames);
189          newDM.SortableView = oldDM.SortableView;
190          for (int i = 0; i < newDM.Rows; i++)
191            for (int j = 0; j < newDM.Columns; j++)
192              newDM[i, j] = oldDM[i, j];
193          DistanceMatrixParameter.Value = (DistanceMatrix)newDM.AsReadOnly();
194        }
195      }
196
197      if (Operators.Count == 0) InitializeOperators();
198      #endregion
199      RegisterEventHandlers();
200    }
201
202    private void RegisterEventHandlers() {
203      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
204      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
205      Coordinates.Reset += new EventHandler(Coordinates_Reset);
206      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
207      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
208    }
209
210    private void InitializeOperators() {
211      Operators.Add(new BestTSPSolutionAnalyzer());
212      Operators.Add(new TSPAlleleFrequencyAnalyzer());
213      Operators.Add(new TSPPopulationDiversityAnalyzer());
214      ParameterizeAnalyzers();
215      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
216      ParameterizeOperators();
217      UpdateMoveEvaluators();
218    }
219    private void UpdateMoveEvaluators() {
220      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
221      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
222        if (op.EvaluatorType == Evaluator.GetType()) {
223          Operators.Add(op);
224        }
225      ParameterizeOperators();
226      OnOperatorsChanged();
227    }
228    private void ParameterizeSolutionCreator() {
229      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
230      SolutionCreator.LengthParameter.Hidden = true;
231      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
232      SolutionCreator.PermutationTypeParameter.Hidden = true;
233    }
234    private void ParameterizeEvaluator() {
235      if (Evaluator is ITSPPathEvaluator) {
236        ITSPPathEvaluator evaluator = (ITSPPathEvaluator)Evaluator;
237        evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
238        evaluator.PermutationParameter.Hidden = true;
239      }
240      if (Evaluator is ITSPCoordinatesPathEvaluator) {
241        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
242        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
243        evaluator.CoordinatesParameter.Hidden = true;
244        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
245        evaluator.DistanceMatrixParameter.Hidden = true;
246        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
247        evaluator.UseDistanceMatrixParameter.Hidden = true;
248      }
249    }
250    private void ParameterizeAnalyzers() {
251      if (BestTSPSolutionAnalyzer != null) {
252        BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
253        BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
254        BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
255        BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
256        BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
257        BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
258        BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
259      }
260
261      if (TSPAlleleFrequencyAnalyzer != null) {
262        TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
263        TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
264        TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
265        TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
266        TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
267        TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
268        TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
269      }
270
271      if (TSPPopulationDiversityAnalyzer != null) {
272        TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
273        TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
274        TSPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
275        TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
276      }
277    }
278    private void ParameterizeOperators() {
279      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
280        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
281        op.ParentsParameter.Hidden = true;
282        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
283        op.ChildParameter.Hidden = true;
284      }
285      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
286        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
287        op.PermutationParameter.Hidden = true;
288      }
289      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
290        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
291        op.PermutationParameter.Hidden = true;
292      }
293      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
294        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
295        op.CoordinatesParameter.Hidden = true;
296        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
297        op.DistanceMatrixParameter.Hidden = true;
298        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
299        op.UseDistanceMatrixParameter.Hidden = true;
300        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
301        op.QualityParameter.Hidden = true;
302        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
303        op.PermutationParameter.Hidden = true;
304      }
305      foreach (IPermutationMultiNeighborhoodShakingOperator op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>()) {
306        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
307        op.PermutationParameter.Hidden = true;
308      }
309    }
310
311    private void ClearDistanceMatrix() {
312      DistanceMatrixParameter.Value = null;
313    }
314    #endregion
315
316    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName) {
317      TSPLIBParser tspParser = new TSPLIBParser(tspFileName);
318      tspParser.Parse();
319      Name = tspParser.Name + " TSP (imported from TSPLIB)";
320      if (!string.IsNullOrEmpty(tspParser.Comment)) Description = tspParser.Comment;
321      Coordinates = new DoubleMatrix(tspParser.Vertices);
322      if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D) {
323        TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
324        evaluator.QualityParameter.ActualName = "TSPTourLength";
325        Evaluator = evaluator;
326      } else if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.GEO) {
327        TSPGeoPathEvaluator evaluator = new TSPGeoPathEvaluator();
328        evaluator.QualityParameter.ActualName = "TSPTourLength";
329        Evaluator = evaluator;
330      }
331      BestKnownQuality = null;
332      BestKnownSolution = null;
333
334      if (!string.IsNullOrEmpty(optimalTourFileName)) {
335        TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
336        tourParser.Parse();
337        if (tourParser.Tour.Length != Coordinates.Rows) throw new InvalidDataException("Length of optimal tour is not equal to number of cities.");
338        BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, tourParser.Tour);
339      }
340      OnReset();
341    }
342    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
343      ImportFromTSPLIB(tspFileName, optimalTourFileName);
344      BestKnownQuality = new DoubleValue(bestKnownQuality);
345    }
346  }
347}
Note: See TracBrowser for help on using the repository browser.