Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.1/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs

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

Enabled saving only for some specific items (#1193)

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