Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3569 was 3504, checked in by swagner, 15 years ago

Implemented reviewers' comments (#893)

File size: 18.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Drawing;
25using System.IO;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.PermutationEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
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 : ParameterizedNamedItem, ISingleObjectiveProblem {
41    public override Image ItemImage {
42      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Type; }
43    }
44
45    #region Parameter Properties
46    public ValueParameter<BoolValue> MaximizationParameter {
47      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
48    }
49    IParameter ISingleObjectiveProblem.MaximizationParameter {
50      get { return MaximizationParameter; }
51    }
52    public ValueParameter<DoubleMatrix> CoordinatesParameter {
53      get { return (ValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
54    }
55    public OptionalValueParameter<DoubleMatrix> DistanceMatrixParameter {
56      get { return (OptionalValueParameter<DoubleMatrix>)Parameters["DistanceMatrix"]; }
57    }
58    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
59      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
60    }
61    public ValueParameter<IPermutationCreator> SolutionCreatorParameter {
62      get { return (ValueParameter<IPermutationCreator>)Parameters["SolutionCreator"]; }
63    }
64    IParameter IProblem.SolutionCreatorParameter {
65      get { return SolutionCreatorParameter; }
66    }
67    public ValueParameter<ITSPEvaluator> EvaluatorParameter {
68      get { return (ValueParameter<ITSPEvaluator>)Parameters["Evaluator"]; }
69    }
70    IParameter IProblem.EvaluatorParameter {
71      get { return EvaluatorParameter; }
72    }
73    public OptionalValueParameter<ITSPSolutionsVisualizer> VisualizerParameter {
74      get { return (OptionalValueParameter<ITSPSolutionsVisualizer>)Parameters["Visualizer"]; }
75    }
76    IParameter IProblem.VisualizerParameter {
77      get { return VisualizerParameter; }
78    }
79    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
80      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
81    }
82    IParameter ISingleObjectiveProblem.BestKnownQualityParameter {
83      get { return BestKnownQualityParameter; }
84    }
85    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
86      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
87    }
88    #endregion
89
90    #region Properties
91    public DoubleMatrix Coordinates {
92      get { return CoordinatesParameter.Value; }
93      set { CoordinatesParameter.Value = value; }
94    }
95    public DoubleMatrix DistanceMatrix {
96      get { return DistanceMatrixParameter.Value; }
97      set { DistanceMatrixParameter.Value = value; }
98    }
99    public BoolValue UseDistanceMatrix {
100      get { return UseDistanceMatrixParameter.Value; }
101      set { UseDistanceMatrixParameter.Value = value; }
102    }
103    public IPermutationCreator SolutionCreator {
104      get { return SolutionCreatorParameter.Value; }
105      set { SolutionCreatorParameter.Value = value; }
106    }
107    ISolutionCreator IProblem.SolutionCreator {
108      get { return SolutionCreatorParameter.Value; }
109    }
110    public ITSPEvaluator Evaluator {
111      get { return EvaluatorParameter.Value; }
112      set { EvaluatorParameter.Value = value; }
113    }
114    ISingleObjectiveEvaluator ISingleObjectiveProblem.Evaluator {
115      get { return EvaluatorParameter.Value; }
116    }
117    IEvaluator IProblem.Evaluator {
118      get { return EvaluatorParameter.Value; }
119    }
120    public ITSPSolutionsVisualizer Visualizer {
121      get { return VisualizerParameter.Value; }
122      set { VisualizerParameter.Value = value; }
123    }
124    ISolutionsVisualizer IProblem.Visualizer {
125      get { return VisualizerParameter.Value; }
126    }
127    public DoubleValue BestKnownQuality {
128      get { return BestKnownQualityParameter.Value; }
129      set { BestKnownQualityParameter.Value = value; }
130    }
131    public Permutation BestKnownSolution {
132      get { return BestKnownSolutionParameter.Value; }
133      set { BestKnownSolutionParameter.Value = value; }
134    }
135    private List<IPermutationOperator> operators;
136    public IEnumerable<IOperator> Operators {
137      get { return operators.Cast<IOperator>(); }
138    }
139    #endregion
140
141    public TravelingSalesmanProblem()
142      : base() {
143      RandomPermutationCreator creator = new RandomPermutationCreator();
144      TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
145      BestPathTSPTourVisualizer visualizer = new BestPathTSPTourVisualizer();
146
147      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Traveling Salesman Problem is a minimization problem.", new BoolValue(false)));
148      Parameters.Add(new ValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
149      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
150      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false.", new BoolValue(true)));
151      Parameters.Add(new ValueParameter<IPermutationCreator>("SolutionCreator", "The operator which should be used to create new TSP solutions.", creator));
152      Parameters.Add(new ValueParameter<ITSPEvaluator>("Evaluator", "The operator which should be used to evaluate TSP solutions.", evaluator));
153      Parameters.Add(new OptionalValueParameter<ITSPSolutionsVisualizer>("Visualizer", "The operator which should be used to visualize TSP solutions.", visualizer));
154      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this TSP instance."));
155      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
156
157      Coordinates = new DoubleMatrix(new double[,] {
158        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
159        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
160        { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
161        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
162      });
163
164      creator.PermutationParameter.ActualName = "TSPTour";
165      evaluator.QualityParameter.ActualName = "TSPTourLength";
166      ParameterizeSolutionCreator();
167      ParameterizeEvaluator();
168      ParameterizeVisualizer();
169
170      Initialize();
171    }
172    [StorableConstructor]
173    private TravelingSalesmanProblem(bool deserializing) : base() { }
174
175    public override IDeepCloneable Clone(Cloner cloner) {
176      TravelingSalesmanProblem clone = (TravelingSalesmanProblem)base.Clone(cloner);
177      clone.DistanceMatrixParameter.Value = DistanceMatrixParameter.Value;
178      clone.Initialize();
179      return clone;
180    }
181
182    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName) {
183      TSPLIBParser tspParser = new TSPLIBParser(tspFileName);
184      tspParser.Parse();
185      Name = tspParser.Name + " TSP (imported from TSPLIB)";
186      if (!string.IsNullOrEmpty(tspParser.Comment)) Description = tspParser.Comment;
187      Coordinates = new DoubleMatrix(tspParser.Vertices);
188      if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D) {
189        TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
190        evaluator.QualityParameter.ActualName = "TSPTourLength";
191        Evaluator = evaluator;
192      } else if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.GEO) {
193        TSPGeoPathEvaluator evaluator = new TSPGeoPathEvaluator();
194        evaluator.QualityParameter.ActualName = "TSPTourLength";
195        Evaluator = evaluator;
196      }
197      BestKnownQuality = null;
198      BestKnownSolution = null;
199
200      if (!string.IsNullOrEmpty(optimalTourFileName)) {
201        TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
202        tourParser.Parse();
203        if (tourParser.Tour.Length != Coordinates.Rows) throw new InvalidDataException("Length of optimal tour is not equal to number of cities.");
204        BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, tourParser.Tour);
205      }
206    }
207    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
208      ImportFromTSPLIB(tspFileName, optimalTourFileName);
209      BestKnownQuality = new DoubleValue(bestKnownQuality);
210    }
211
212    #region Events
213    public event EventHandler SolutionCreatorChanged;
214    private void OnSolutionCreatorChanged() {
215      if (SolutionCreatorChanged != null)
216        SolutionCreatorChanged(this, EventArgs.Empty);
217    }
218    public event EventHandler EvaluatorChanged;
219    private void OnEvaluatorChanged() {
220      if (EvaluatorChanged != null)
221        EvaluatorChanged(this, EventArgs.Empty);
222    }
223    public event EventHandler VisualizerChanged;
224    private void OnVisualizerChanged() {
225      if (VisualizerChanged != null)
226        VisualizerChanged(this, EventArgs.Empty);
227    }
228    public event EventHandler OperatorsChanged;
229    private void OnOperatorsChanged() {
230      if (OperatorsChanged != null)
231        OperatorsChanged(this, EventArgs.Empty);
232    }
233
234    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
235      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
236      Coordinates.Reset += new EventHandler(Coordinates_Reset);
237      ParameterizeSolutionCreator();
238      ClearDistanceMatrix();
239    }
240    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
241      ClearDistanceMatrix();
242    }
243    private void Coordinates_Reset(object sender, EventArgs e) {
244      ParameterizeSolutionCreator();
245      ClearDistanceMatrix();
246    }
247    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
248      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
249      ParameterizeSolutionCreator();
250      ParameterizeEvaluator();
251      ParameterizeVisualizer();
252      ParameterizeOperators();
253      OnSolutionCreatorChanged();
254    }
255    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
256      ParameterizeEvaluator();
257      ParameterizeVisualizer();
258      ParameterizeOperators();
259    }
260    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
261      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
262      ParameterizeEvaluator();
263      UpdateMoveEvaluators();
264      ParameterizeVisualizer();
265      ClearDistanceMatrix();
266      OnEvaluatorChanged();
267    }
268    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
269      ParameterizeVisualizer();
270    }
271    private void VisualizerParameter_ValueChanged(object sender, EventArgs e) {
272      ParameterizeVisualizer();
273      OnVisualizerChanged();
274    }
275    private void MoveGenerator_InversionMoveParameter_ActualNameChanged(object sender, EventArgs e) {
276      string name = ((ILookupParameter<InversionMove>)sender).ActualName;
277      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
278        op.InversionMoveParameter.ActualName = name;
279      }
280    }
281    private void MoveGenerator_TranslocationMoveParameter_ActualNameChanged(object sender, EventArgs e) {
282      string name = ((ILookupParameter<TranslocationMove>)sender).ActualName;
283      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
284        op.TranslocationMoveParameter.ActualName = name;
285      }
286    }
287    #endregion
288
289    #region Helpers
290    [StorableHook(HookType.AfterDeserialization)]
291    private void Initialize() {
292      InitializeOperators();
293      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
294      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
295      Coordinates.Reset += new EventHandler(Coordinates_Reset);
296      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
297      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
298      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
299      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
300      VisualizerParameter.ValueChanged += new EventHandler(VisualizerParameter_ValueChanged);
301    }
302
303    private void InitializeOperators() {
304      operators = new List<IPermutationOperator>();
305      operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
306      ParameterizeOperators();
307      UpdateMoveEvaluators();
308      InitializeMoveGenerators();
309    }
310    private void InitializeMoveGenerators() {
311      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
312        if (op is IMoveGenerator) {
313          op.InversionMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_InversionMoveParameter_ActualNameChanged);
314        }
315      }
316      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
317        if (op is IMoveGenerator) {
318          op.TranslocationMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TranslocationMoveParameter_ActualNameChanged);
319        }
320      }
321    }
322    private void UpdateMoveEvaluators() {
323      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>().ToList())
324        operators.Remove(op);
325      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
326        if (op.EvaluatorType == Evaluator.GetType()) {
327          operators.Add(op);
328        }
329      ParameterizeOperators();
330      OnOperatorsChanged();
331    }
332    private void ParameterizeSolutionCreator() {
333      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
334      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
335    }
336    private void ParameterizeEvaluator() {
337      if (Evaluator is ITSPPathEvaluator)
338        ((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
339      if (Evaluator is ITSPCoordinatesPathEvaluator) {
340        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
341        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
342        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
343        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
344      }
345    }
346    private void ParameterizeVisualizer() {
347      if (Visualizer != null) {
348        Visualizer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
349        if (Visualizer is ICoordinatesTSPSolutionsVisualizer)
350          ((ICoordinatesTSPSolutionsVisualizer)Visualizer).CoordinatesParameter.ActualName = CoordinatesParameter.Name;
351        if (Visualizer is IPathCoordinatesTSPSolutionsVisualizer)
352          ((IPathCoordinatesTSPSolutionsVisualizer)Visualizer).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
353      }
354    }
355    private void ParameterizeOperators() {
356      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
357        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
358        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
359      }
360      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
361        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
362      }
363      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
364        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
365      }
366      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
367        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
368        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
369        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
370        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
371        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
372      }
373      string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
374      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
375        op.InversionMoveParameter.ActualName = inversionMove;
376      string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
377      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
378        op.TranslocationMoveParameter.ActualName = translocationMove;
379    }
380
381    private void ClearDistanceMatrix() {
382      DistanceMatrixParameter.Value = null;
383    }
384    #endregion
385  }
386}
Note: See TracBrowser for help on using the repository browser.