Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4722 was 4722, checked in by swagner, 13 years ago

Merged cloning refactoring branch back into trunk (#922)

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