Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4118 was 4118, checked in by abeham, 14 years ago

#1090

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