Free cookie consent management tool by TermsFeed Policy Generator

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

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

Worked on allele frequency analysis (#1234)

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