source: trunk/sources/HeuristicLab.Problems.TSP/3.3/TSP.cs @ 3151

Last change on this file since 3151 was 3151, checked in by swagner, 12 years ago

Implemented import of optimal TSP solutions (#924).

File size: 16.0 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.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.PermutationEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34
35namespace HeuristicLab.Problems.TSP {
36  [Item("TSP", "Represents a symmetric Traveling Salesman Problem.")]
37  [Creatable("Problems")]
38  [StorableClass]
39  public sealed class TSP : ParameterizedNamedItem, ISingleObjectiveProblem {
40    public override Image ItemImage {
41      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Type; }
42    }
43
44    #region Parameter Properties
45    public ValueParameter<BoolValue> MaximizationParameter {
46      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
47    }
48    IParameter ISingleObjectiveProblem.MaximizationParameter {
49      get { return MaximizationParameter; }
50    }
51    public ValueParameter<DoubleMatrix> CoordinatesParameter {
52      get { return (ValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
53    }
54    public OptionalValueParameter<DoubleMatrix> DistanceMatrixParameter {
55      get { return (OptionalValueParameter<DoubleMatrix>)Parameters["DistanceMatrix"]; }
56    }
57    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
58      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
59    }
60    public ValueParameter<IPermutationCreator> SolutionCreatorParameter {
61      get { return (ValueParameter<IPermutationCreator>)Parameters["SolutionCreator"]; }
62    }
63    IParameter IProblem.SolutionCreatorParameter {
64      get { return SolutionCreatorParameter; }
65    }
66    public ValueParameter<ITSPEvaluator> EvaluatorParameter {
67      get { return (ValueParameter<ITSPEvaluator>)Parameters["Evaluator"]; }
68    }
69    IParameter IProblem.EvaluatorParameter {
70      get { return EvaluatorParameter; }
71    }
72    public OptionalValueParameter<ITSPSolutionsVisualizer> VisualizerParameter {
73      get { return (OptionalValueParameter<ITSPSolutionsVisualizer>)Parameters["Visualizer"]; }
74    }
75    IParameter IProblem.VisualizerParameter {
76      get { return VisualizerParameter; }
77    }
78    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
79      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
80    }
81    IParameter ISingleObjectiveProblem.BestKnownQualityParameter {
82      get { return BestKnownQualityParameter; }
83    }
84    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
85      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
86    }
87    #endregion
88
89    #region Properties
90    public DoubleMatrix Coordinates {
91      get { return CoordinatesParameter.Value; }
92      set { CoordinatesParameter.Value = value; }
93    }
94    public DoubleMatrix DistanceMatrix {
95      get { return DistanceMatrixParameter.Value; }
96      set { DistanceMatrixParameter.Value = value; }
97    }
98    public BoolValue UseDistanceMatrix {
99      get { return UseDistanceMatrixParameter.Value; }
100      set { UseDistanceMatrixParameter.Value = value; }
101    }
102    public IPermutationCreator SolutionCreator {
103      get { return SolutionCreatorParameter.Value; }
104      set { SolutionCreatorParameter.Value = value; }
105    }
106    ISolutionCreator IProblem.SolutionCreator {
107      get { return SolutionCreatorParameter.Value; }
108    }
109    public ITSPEvaluator Evaluator {
110      get { return EvaluatorParameter.Value; }
111      set { EvaluatorParameter.Value = value; }
112    }
113    ISingleObjectiveEvaluator ISingleObjectiveProblem.Evaluator {
114      get { return EvaluatorParameter.Value; }
115    }
116    IEvaluator IProblem.Evaluator {
117      get { return EvaluatorParameter.Value; }
118    }
119    public ITSPSolutionsVisualizer Visualizer {
120      get { return VisualizerParameter.Value; }
121      set { VisualizerParameter.Value = value; }
122    }
123    ISolutionsVisualizer IProblem.Visualizer {
124      get { return VisualizerParameter.Value; }
125    }
126    public DoubleValue BestKnownQuality {
127      get { return BestKnownQualityParameter.Value; }
128      set { BestKnownQualityParameter.Value = value; }
129    }
130    public Permutation BestKnownSolution {
131      get { return BestKnownSolutionParameter.Value; }
132      set { BestKnownSolutionParameter.Value = value; }
133    }
134    private List<IPermutationOperator> operators;
135    public IEnumerable<IOperator> Operators {
136      get { return operators.Cast<IOperator>(); }
137    }
138    #endregion
139
140    public TSP()
141      : base() {
142      RandomPermutationCreator creator = new RandomPermutationCreator();
143      TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
144      BestPathTSPTourVisualizer visualizer = new BestPathTSPTourVisualizer();
145
146      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Traveling Salesman Problem is a minimization problem.", new BoolValue(false)));
147      Parameters.Add(new ValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities.", new DoubleMatrix(0, 0)));
148      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
149      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false.", new BoolValue(true)));
150      Parameters.Add(new ValueParameter<IPermutationCreator>("SolutionCreator", "The operator which should be used to create new TSP solutions.", creator));
151      Parameters.Add(new ValueParameter<ITSPEvaluator>("Evaluator", "The operator which should be used to evaluate TSP solutions.", evaluator));
152      Parameters.Add(new OptionalValueParameter<ITSPSolutionsVisualizer>("Visualizer", "The operator which should be used to visualize TSP solutions.", visualizer));
153      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this TSP instance."));
154      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
155
156      creator.PermutationParameter.ActualName = "TSPTour";
157      evaluator.QualityParameter.ActualName = "TSPTourLength";
158      ParameterizeSolutionCreator();
159      ParameterizeEvaluator();
160      ParameterizeVisualizer();
161
162      Initialize();
163    }
164    [StorableConstructor]
165    private TSP(bool deserializing) : base() { }
166
167    public override IDeepCloneable Clone(Cloner cloner) {
168      TSP clone = (TSP)base.Clone(cloner);
169      clone.Initialize();
170      return clone;
171    }
172
173    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName) {
174      TSPLIBParser tspParser = new TSPLIBParser(tspFileName);
175      tspParser.Parse();
176      Name = tspParser.Name + " TSP (imported from TSPLIB)";
177      if (!string.IsNullOrEmpty(tspParser.Comment)) Description = tspParser.Comment;
178      Coordinates = new DoubleMatrix(tspParser.Vertices);
179      BestKnownQuality = null;
180
181      if (!string.IsNullOrEmpty(optimalTourFileName)) {
182        TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
183        tourParser.Parse();
184        BestKnownSolution = new Permutation(tourParser.Tour);
185      }
186    }
187    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
188      ImportFromTSPLIB(tspFileName, optimalTourFileName);
189      BestKnownQuality = new DoubleValue(bestKnownQuality);
190    }
191
192    #region Events
193    public event EventHandler SolutionCreatorChanged;
194    private void OnSolutionCreatorChanged() {
195      if (SolutionCreatorChanged != null)
196        SolutionCreatorChanged(this, EventArgs.Empty);
197    }
198    public event EventHandler EvaluatorChanged;
199    private void OnEvaluatorChanged() {
200      if (EvaluatorChanged != null)
201        EvaluatorChanged(this, EventArgs.Empty);
202    }
203    public event EventHandler VisualizerChanged;
204    private void OnVisualizerChanged() {
205      if (VisualizerChanged != null)
206        VisualizerChanged(this, EventArgs.Empty);
207    }
208    public event EventHandler OperatorsChanged;
209    private void OnOperatorsChanged() {
210      if (OperatorsChanged != null)
211        OperatorsChanged(this, EventArgs.Empty);
212    }
213
214    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
215      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
216      Coordinates.Reset += new EventHandler(Coordinates_Reset);
217      ParameterizeSolutionCreator();
218      ClearDistanceMatrix();
219    }
220    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
221      ClearDistanceMatrix();
222    }
223    private void Coordinates_Reset(object sender, EventArgs e) {
224      ParameterizeSolutionCreator();
225      ClearDistanceMatrix();
226    }
227    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
228      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
229      ParameterizeSolutionCreator();
230      ParameterizeEvaluator();
231      ParameterizeVisualizer();
232      ParameterizeOperators();
233      OnSolutionCreatorChanged();
234    }
235    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
236      ParameterizeEvaluator();
237      ParameterizeVisualizer();
238      ParameterizeOperators();
239    }
240    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
241      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
242      ParameterizeEvaluator();
243      ParameterizeVisualizer();
244      ClearDistanceMatrix();
245      OnEvaluatorChanged();
246    }
247    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
248      ParameterizeVisualizer();
249    }
250    private void VisualizerParameter_ValueChanged(object sender, EventArgs e) {
251      ParameterizeVisualizer();
252      OnVisualizerChanged();
253    }
254    private void MoveGenerator_TwoOptMoveParameter_ActualNameChanged(object sender, EventArgs e) {
255      string name = ((ILookupParameter<TwoOptMove>)sender).ActualName;
256      foreach (ITwoOptPermutationMoveOperator op in Operators.OfType<ITwoOptPermutationMoveOperator>()) {
257        op.TwoOptMoveParameter.ActualName = name;
258      }
259    }
260    private void MoveGenerator_ThreeOptMoveParameter_ActualNameChanged(object sender, EventArgs e) {
261      string name = ((ILookupParameter<ThreeOptMove>)sender).ActualName;
262      foreach (IThreeOptPermutationMoveOperator op in Operators.OfType<IThreeOptPermutationMoveOperator>()) {
263        op.ThreeOptMoveParameter.ActualName = name;
264      }
265    }
266    #endregion
267
268    #region Helpers
269    [StorableHook(HookType.AfterDeserialization)]
270    private void Initialize() {
271      InitializeOperators();
272      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
273      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
274      Coordinates.Reset += new EventHandler(Coordinates_Reset);
275      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
276      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
277      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
278      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
279      VisualizerParameter.ValueChanged += new EventHandler(VisualizerParameter_ValueChanged);
280    }
281
282    private void InitializeOperators() {
283      operators = new List<IPermutationOperator>();
284      if (ApplicationManager.Manager != null) {
285        operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>());
286        ParameterizeOperators();
287      }
288      InitializeMoveGenerators();
289    }
290    private void InitializeMoveGenerators() {
291      foreach (ITwoOptPermutationMoveOperator op in Operators.OfType<ITwoOptPermutationMoveOperator>()) {
292        if (op is IMoveGenerator) {
293          op.TwoOptMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TwoOptMoveParameter_ActualNameChanged);
294        }
295      }
296      foreach (IThreeOptPermutationMoveOperator op in Operators.OfType<IThreeOptPermutationMoveOperator>()) {
297        if (op is IMoveGenerator) {
298          op.ThreeOptMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_ThreeOptMoveParameter_ActualNameChanged);
299        }
300      }
301    }
302    private void ParameterizeSolutionCreator() {
303      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
304    }
305    private void ParameterizeEvaluator() {
306      if (Evaluator is ITSPPathEvaluator)
307        ((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
308      if (Evaluator is ITSPCoordinatesPathEvaluator) {
309        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
310        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
311        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
312        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
313      }
314    }
315    private void ParameterizeVisualizer() {
316      if (Visualizer != null) {
317        Visualizer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
318        if (Visualizer is ICoordinatesTSPSolutionsVisualizer)
319          ((ICoordinatesTSPSolutionsVisualizer)Visualizer).CoordinatesParameter.ActualName = CoordinatesParameter.Name;
320        if (Visualizer is IPathCoordinatesTSPSolutionsVisualizer)
321          ((IPathCoordinatesTSPSolutionsVisualizer)Visualizer).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
322      }
323    }
324    private void ParameterizeOperators() {
325      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
326        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
327        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
328      }
329      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
330        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
331      }
332      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
333        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
334      }
335      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
336        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
337        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
338        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
339      }
340    }
341
342    private void ClearDistanceMatrix() {
343      DistanceMatrixParameter.Value = null;
344    }
345    #endregion
346  }
347}
Note: See TracBrowser for help on using the repository browser.