Free cookie consent management tool by TermsFeed Policy Generator

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

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

Updated year of copyrights to 2012 (#1716)

File size: 16.9 KB
RevLine 
[2796]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2796]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
[2865]22using System;
[2975]23using System.Collections.Generic;
[3153]24using System.IO;
[2865]25using System.Linq;
[2975]26using HeuristicLab.Common;
[2796]27using HeuristicLab.Core;
28using HeuristicLab.Data;
[3053]29using HeuristicLab.Encodings.PermutationEncoding;
[2834]30using HeuristicLab.Optimization;
[2805]31using HeuristicLab.Parameters;
[2796]32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[2865]33using HeuristicLab.PluginInfrastructure;
[2796]34
[3158]35namespace HeuristicLab.Problems.TravelingSalesman {
[3159]36  [Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
[2796]37  [Creatable("Problems")]
[3017]38  [StorableClass]
[6938]39  public sealed class TravelingSalesmanProblem : SingleObjectiveHeuristicOptimizationProblem<ITSPEvaluator, IPermutationCreator>, IStorableContent {
[4419]40    public string Filename { get; set; }
41
[2975]42    #region Parameter Properties
[3048]43    public ValueParameter<DoubleMatrix> CoordinatesParameter {
44      get { return (ValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
[2865]45    }
[4825]46    public OptionalValueParameter<DistanceMatrix> DistanceMatrixParameter {
47      get { return (OptionalValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
[3066]48    }
49    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
50      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
51    }
[3151]52    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
53      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
54    }
[2975]55    #endregion
[2805]56
[2975]57    #region Properties
[3048]58    public DoubleMatrix Coordinates {
[2975]59      get { return CoordinatesParameter.Value; }
60      set { CoordinatesParameter.Value = value; }
[2865]61    }
[4825]62    public DistanceMatrix DistanceMatrix {
[3066]63      get { return DistanceMatrixParameter.Value; }
64      set { DistanceMatrixParameter.Value = value; }
65    }
66    public BoolValue UseDistanceMatrix {
67      get { return UseDistanceMatrixParameter.Value; }
68      set { UseDistanceMatrixParameter.Value = value; }
69    }
[3151]70    public Permutation BestKnownSolution {
71      get { return BestKnownSolutionParameter.Value; }
72      set { BestKnownSolutionParameter.Value = value; }
73    }
[3663]74    private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
[6938]75      get { return Operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
[3616]76    }
[4623]77    private TSPAlleleFrequencyAnalyzer TSPAlleleFrequencyAnalyzer {
[6938]78      get { return Operators.OfType<TSPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
[4623]79    }
[4703]80    private TSPPopulationDiversityAnalyzer TSPPopulationDiversityAnalyzer {
[6938]81      get { return Operators.OfType<TSPPopulationDiversityAnalyzer>().FirstOrDefault(); }
[4703]82    }
[2975]83    #endregion
[2865]84
[6938]85    // BackwardsCompatibility3.3
86    #region Backwards compatible code, remove with 3.4
87    [Obsolete]
88    [Storable(Name = "operators")]
89    private IEnumerable<IOperator> oldOperators {
90      get { return null; }
91      set {
92        if (value != null && value.Any())
93          Operators.AddRange(value);
94      }
95    }
96    #endregion
[4098]97
98    [StorableConstructor]
[4118]99    private TravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
[4722]100    private TravelingSalesmanProblem(TravelingSalesmanProblem original, Cloner cloner)
101      : base(original, cloner) {
102      AttachEventHandlers();
103    }
104    public override IDeepCloneable Clone(Cloner cloner) {
105      return new TravelingSalesmanProblem(this, cloner);
106    }
[3159]107    public TravelingSalesmanProblem()
[6938]108      : base(new TSPRoundedEuclideanPathEvaluator(), new RandomPermutationCreator()) {
[2891]109
[3504]110      Parameters.Add(new ValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
[4825]111      Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
[3066]112      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false.", new BoolValue(true)));
[3151]113      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
[2865]114
[6939]115      Maximization.Value = false;
[6051]116      MaximizationParameter.Hidden = true;
[4825]117      DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
118
[3504]119      Coordinates = new DoubleMatrix(new double[,] {
120        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
121        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
122        { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
123        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
124      });
125
[6938]126      SolutionCreator.PermutationParameter.ActualName = "TSPTour";
127      Evaluator.QualityParameter.ActualName = "TSPTourLength";
[2975]128      ParameterizeSolutionCreator();
129      ParameterizeEvaluator();
[2865]130
[4098]131      InitializeOperators();
132      AttachEventHandlers();
[2975]133    }
[2891]134
[2975]135    #region Events
[6938]136    protected override void OnSolutionCreatorChanged() {
137      base.OnSolutionCreatorChanged();
138      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
139      ParameterizeSolutionCreator();
140      ParameterizeEvaluator();
141      ParameterizeAnalyzers();
142      ParameterizeOperators();
[2865]143    }
[6938]144    protected override void OnEvaluatorChanged() {
145      base.OnEvaluatorChanged();
146      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
147      ParameterizeEvaluator();
148      UpdateMoveEvaluators();
149      ParameterizeAnalyzers();
150      ClearDistanceMatrix();
[2975]151    }
152    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
153      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
154      Coordinates.Reset += new EventHandler(Coordinates_Reset);
155      ParameterizeSolutionCreator();
[3066]156      ClearDistanceMatrix();
[2975]157    }
158    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
[3066]159      ClearDistanceMatrix();
[2975]160    }
161    private void Coordinates_Reset(object sender, EventArgs e) {
162      ParameterizeSolutionCreator();
[3066]163      ClearDistanceMatrix();
[2975]164    }
165    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
166      ParameterizeEvaluator();
[4623]167      ParameterizeAnalyzers();
[2975]168      ParameterizeOperators();
169    }
[3139]170    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[4623]171      ParameterizeAnalyzers();
[3139]172    }
[2975]173    #endregion
[2865]174
[2975]175    #region Helpers
[2986]176    [StorableHook(HookType.AfterDeserialization)]
[4722]177    private void AfterDeserialization() {
[4118]178      // BackwardsCompatibility3.3
179      #region Backwards compatible code (remove with 3.4)
[4825]180      OptionalValueParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as OptionalValueParameter<DoubleMatrix>;
181      if (oldDistanceMatrixParameter != null) {
182        Parameters.Remove(oldDistanceMatrixParameter);
183        Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
184        DistanceMatrixParameter.GetsCollected = oldDistanceMatrixParameter.GetsCollected;
185        DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
186        if (oldDistanceMatrixParameter.Value != null) {
187          DoubleMatrix oldDM = oldDistanceMatrixParameter.Value;
188          DistanceMatrix newDM = new DistanceMatrix(oldDM.Rows, oldDM.Columns, oldDM.ColumnNames, oldDM.RowNames);
189          newDM.SortableView = oldDM.SortableView;
190          for (int i = 0; i < newDM.Rows; i++)
191            for (int j = 0; j < newDM.Columns; j++)
192              newDM[i, j] = oldDM[i, j];
193          DistanceMatrixParameter.Value = (DistanceMatrix)newDM.AsReadOnly();
194        }
195      }
196
[6938]197      if (Operators.Count == 0) InitializeOperators();
[4118]198      #endregion
199      AttachEventHandlers();
200    }
201
[4098]202    private void AttachEventHandlers() {
[2975]203      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
204      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
205      Coordinates.Reset += new EventHandler(Coordinates_Reset);
206      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
[3139]207      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[2865]208    }
[3139]209
[3099]210    private void InitializeOperators() {
[6938]211      Operators.Add(new BestTSPSolutionAnalyzer());
212      Operators.Add(new TSPAlleleFrequencyAnalyzer());
213      Operators.Add(new TSPPopulationDiversityAnalyzer());
[4623]214      ParameterizeAnalyzers();
[6938]215      Operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
[3199]216      ParameterizeOperators();
[3209]217      UpdateMoveEvaluators();
[3099]218    }
[3209]219    private void UpdateMoveEvaluators() {
[6938]220      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
[3303]221      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
222        if (op.EvaluatorType == Evaluator.GetType()) {
[6938]223          Operators.Add(op);
[3303]224        }
225      ParameterizeOperators();
226      OnOperatorsChanged();
[3209]227    }
[2975]228    private void ParameterizeSolutionCreator() {
[3048]229      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
[6051]230      SolutionCreator.LengthParameter.Hidden = true;
[3231]231      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
[6051]232      SolutionCreator.PermutationTypeParameter.Hidden = true;
[2865]233    }
[2975]234    private void ParameterizeEvaluator() {
[6051]235      if (Evaluator is ITSPPathEvaluator) {
236        ITSPPathEvaluator evaluator = (ITSPPathEvaluator)Evaluator;
237        evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
238        evaluator.PermutationParameter.Hidden = true;
239      }
[3066]240      if (Evaluator is ITSPCoordinatesPathEvaluator) {
241        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
242        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
[6051]243        evaluator.CoordinatesParameter.Hidden = true;
[3066]244        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
[6051]245        evaluator.DistanceMatrixParameter.Hidden = true;
[3066]246        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
[6051]247        evaluator.UseDistanceMatrixParameter.Hidden = true;
[3066]248      }
[2865]249    }
[4623]250    private void ParameterizeAnalyzers() {
[4641]251      if (BestTSPSolutionAnalyzer != null) {
252        BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
253        BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
254        BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
255        BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
256        BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
257        BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
258        BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
259      }
[4623]260
[4641]261      if (TSPAlleleFrequencyAnalyzer != null) {
262        TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
263        TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
[4866]264        TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
[4641]265        TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
266        TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
267        TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
268        TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
269      }
[4703]270
271      if (TSPPopulationDiversityAnalyzer != null) {
272        TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
273        TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
274        TSPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
275        TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
276      }
[3107]277    }
[2975]278    private void ParameterizeOperators() {
279      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
280        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]281        op.ParentsParameter.Hidden = true;
[2975]282        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]283        op.ChildParameter.Hidden = true;
[2975]284      }
285      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
286        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]287        op.PermutationParameter.Hidden = true;
[2975]288      }
[3074]289      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
290        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]291        op.PermutationParameter.Hidden = true;
[3074]292      }
293      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
294        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
[6051]295        op.CoordinatesParameter.Hidden = true;
[3074]296        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
[6051]297        op.DistanceMatrixParameter.Hidden = true;
[3074]298        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
[6051]299        op.UseDistanceMatrixParameter.Hidden = true;
[3209]300        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
[6051]301        op.QualityParameter.Hidden = true;
[3209]302        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]303        op.PermutationParameter.Hidden = true;
[3074]304      }
[6051]305      foreach (IPermutationMultiNeighborhoodShakingOperator op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>()) {
[6042]306        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]307        op.PermutationParameter.Hidden = true;
308      }
[2975]309    }
[3074]310
[3066]311    private void ClearDistanceMatrix() {
312      DistanceMatrixParameter.Value = null;
313    }
[2975]314    #endregion
[4098]315
316    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName) {
317      TSPLIBParser tspParser = new TSPLIBParser(tspFileName);
318      tspParser.Parse();
319      Name = tspParser.Name + " TSP (imported from TSPLIB)";
320      if (!string.IsNullOrEmpty(tspParser.Comment)) Description = tspParser.Comment;
321      Coordinates = new DoubleMatrix(tspParser.Vertices);
322      if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D) {
323        TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
324        evaluator.QualityParameter.ActualName = "TSPTourLength";
325        Evaluator = evaluator;
326      } else if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.GEO) {
327        TSPGeoPathEvaluator evaluator = new TSPGeoPathEvaluator();
328        evaluator.QualityParameter.ActualName = "TSPTourLength";
329        Evaluator = evaluator;
330      }
331      BestKnownQuality = null;
332      BestKnownSolution = null;
333
334      if (!string.IsNullOrEmpty(optimalTourFileName)) {
335        TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
336        tourParser.Parse();
337        if (tourParser.Tour.Length != Coordinates.Rows) throw new InvalidDataException("Length of optimal tour is not equal to number of cities.");
338        BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, tourParser.Tour);
339      }
340      OnReset();
341    }
342    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
343      ImportFromTSPLIB(tspFileName, optimalTourFileName);
344      BestKnownQuality = new DoubleValue(bestKnownQuality);
345    }
[2796]346  }
347}
Note: See TracBrowser for help on using the repository browser.