Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3766 was 3739, checked in by swagner, 15 years ago

Added Reset event to IProblem (#1006)

File size: 17.8 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 BestTSPSolutionAnalyzer {
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      OnReset();
194    }
195    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
196      ImportFromTSPLIB(tspFileName, optimalTourFileName);
197      BestKnownQuality = new DoubleValue(bestKnownQuality);
198    }
199
200    #region Events
201    public event EventHandler SolutionCreatorChanged;
202    private void OnSolutionCreatorChanged() {
203      EventHandler handler = SolutionCreatorChanged;
204      if (handler != null) handler(this, EventArgs.Empty);
205    }
206    public event EventHandler EvaluatorChanged;
207    private void OnEvaluatorChanged() {
208      EventHandler handler = EvaluatorChanged;
209      if (handler != null) handler(this, EventArgs.Empty);
210    }
211    public event EventHandler OperatorsChanged;
212    private void OnOperatorsChanged() {
213      EventHandler handler = OperatorsChanged;
214      if (handler != null) handler(this, EventArgs.Empty);
215    }
216    public event EventHandler Reset;
217    private void OnReset() {
218      EventHandler handler = Reset;
219      if (handler != null) handler(this, EventArgs.Empty);
220    }
221
222    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
223      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
224      Coordinates.Reset += new EventHandler(Coordinates_Reset);
225      ParameterizeSolutionCreator();
226      ClearDistanceMatrix();
227    }
228    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
229      ClearDistanceMatrix();
230    }
231    private void Coordinates_Reset(object sender, EventArgs e) {
232      ParameterizeSolutionCreator();
233      ClearDistanceMatrix();
234    }
235    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
236      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
237      ParameterizeSolutionCreator();
238      ParameterizeEvaluator();
239      ParameterizeAnalyzer();
240      ParameterizeOperators();
241      OnSolutionCreatorChanged();
242    }
243    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
244      ParameterizeEvaluator();
245      ParameterizeAnalyzer();
246      ParameterizeOperators();
247    }
248    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
249      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
250      ParameterizeEvaluator();
251      UpdateMoveEvaluators();
252      ParameterizeAnalyzer();
253      ClearDistanceMatrix();
254      OnEvaluatorChanged();
255    }
256    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
257      ParameterizeAnalyzer();
258    }
259    private void MoveGenerator_InversionMoveParameter_ActualNameChanged(object sender, EventArgs e) {
260      string name = ((ILookupParameter<InversionMove>)sender).ActualName;
261      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
262        op.InversionMoveParameter.ActualName = name;
263      }
264    }
265    private void MoveGenerator_TranslocationMoveParameter_ActualNameChanged(object sender, EventArgs e) {
266      string name = ((ILookupParameter<TranslocationMove>)sender).ActualName;
267      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
268        op.TranslocationMoveParameter.ActualName = name;
269      }
270    }
271    #endregion
272
273    #region Helpers
274    [StorableHook(HookType.AfterDeserialization)]
275    private void Initialize() {
276      InitializeOperators();
277      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
278      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
279      Coordinates.Reset += new EventHandler(Coordinates_Reset);
280      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
281      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
282      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
283      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
284    }
285
286    private void InitializeOperators() {
287      operators = new List<IOperator>();
288      operators.Add(new BestTSPSolutionAnalyzer());
289      ParameterizeAnalyzer();
290      operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
291      ParameterizeOperators();
292      UpdateMoveEvaluators();
293      InitializeMoveGenerators();
294    }
295    private void InitializeMoveGenerators() {
296      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
297        if (op is IMoveGenerator) {
298          op.InversionMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_InversionMoveParameter_ActualNameChanged);
299        }
300      }
301      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
302        if (op is IMoveGenerator) {
303          op.TranslocationMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TranslocationMoveParameter_ActualNameChanged);
304        }
305      }
306    }
307    private void UpdateMoveEvaluators() {
308      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>().ToList())
309        operators.Remove(op);
310      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
311        if (op.EvaluatorType == Evaluator.GetType()) {
312          operators.Add(op);
313        }
314      ParameterizeOperators();
315      OnOperatorsChanged();
316    }
317    private void ParameterizeSolutionCreator() {
318      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
319      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
320    }
321    private void ParameterizeEvaluator() {
322      if (Evaluator is ITSPPathEvaluator)
323        ((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
324      if (Evaluator is ITSPCoordinatesPathEvaluator) {
325        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
326        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
327        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
328        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
329      }
330    }
331    private void ParameterizeAnalyzer() {
332      BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
333      BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
334      BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
335      BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
336    }
337    private void ParameterizeOperators() {
338      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
339        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
340        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
341      }
342      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
343        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
344      }
345      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
346        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
347      }
348      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
349        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
350        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
351        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
352        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
353        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
354      }
355      string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
356      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
357        op.InversionMoveParameter.ActualName = inversionMove;
358      string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
359      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
360        op.TranslocationMoveParameter.ActualName = translocationMove;
361    }
362
363    private void ClearDistanceMatrix() {
364      DistanceMatrixParameter.Value = null;
365    }
366    #endregion
367  }
368}
Note: See TracBrowser for help on using the repository browser.