Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3635 was 3635, checked in by swagner, 14 years ago

Worked on best solution analysis for the TSP (#999)

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