Free cookie consent management tool by TermsFeed Policy Generator

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

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

Worked on refactoring of algorithm analysis and tracing (#999)

  • adapted GA and TSP
  • removed stuff related to visualizers
File size: 17.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 {
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 BestTSPSolutionAnalyzer Analyzer {
127      get { return operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
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      ParameterizeAnalyzer();
234      ParameterizeOperators();
235      OnSolutionCreatorChanged();
236    }
237    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
238      ParameterizeEvaluator();
239      ParameterizeAnalyzer();
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      ParameterizeAnalyzer();
247      ClearDistanceMatrix();
248      OnEvaluatorChanged();
249    }
250    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
251      ParameterizeAnalyzer();
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      ParameterizeAnalyzer();
284      operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
285      ParameterizeOperators();
286      UpdateMoveEvaluators();
287      InitializeMoveGenerators();
288    }
289    private void InitializeMoveGenerators() {
290      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
291        if (op is IMoveGenerator) {
292          op.InversionMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_InversionMoveParameter_ActualNameChanged);
293        }
294      }
295      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
296        if (op is IMoveGenerator) {
297          op.TranslocationMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TranslocationMoveParameter_ActualNameChanged);
298        }
299      }
300    }
301    private void UpdateMoveEvaluators() {
302      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>().ToList())
303        operators.Remove(op);
304      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
305        if (op.EvaluatorType == Evaluator.GetType()) {
306          operators.Add(op);
307        }
308      ParameterizeOperators();
309      OnOperatorsChanged();
310    }
311    private void ParameterizeSolutionCreator() {
312      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
313      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
314    }
315    private void ParameterizeEvaluator() {
316      if (Evaluator is ITSPPathEvaluator)
317        ((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
318      if (Evaluator is ITSPCoordinatesPathEvaluator) {
319        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
320        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
321        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
322        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
323      }
324    }
325    private void ParameterizeAnalyzer() {
326      if (Analyzer != null) {
327        Analyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
328        Analyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
329        Analyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
330        Analyzer.ResultsParameter.ActualName = "Results";
331      }
332    }
333    private void ParameterizeOperators() {
334      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
335        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
336        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
337      }
338      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
339        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
340      }
341      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
342        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
343      }
344      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
345        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
346        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
347        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
348        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
349        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
350      }
351      string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
352      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
353        op.InversionMoveParameter.ActualName = inversionMove;
354      string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
355      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
356        op.TranslocationMoveParameter.ActualName = translocationMove;
357    }
358
359    private void ClearDistanceMatrix() {
360      DistanceMatrixParameter.Value = null;
361    }
362    #endregion
363  }
364}
Note: See TracBrowser for help on using the repository browser.