Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3997 was 3789, checked in by abeham, 14 years ago

#893

  • Updated wiring of problem specific analyzers
File size: 18.1 KB
RevLine 
[2796]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
[2865]22using System;
[2975]23using System.Collections.Generic;
[2865]24using System.Drawing;
[3153]25using System.IO;
[2865]26using System.Linq;
[2975]27using HeuristicLab.Common;
[2796]28using HeuristicLab.Core;
29using HeuristicLab.Data;
[3053]30using HeuristicLab.Encodings.PermutationEncoding;
[2834]31using HeuristicLab.Optimization;
[2805]32using HeuristicLab.Parameters;
[2796]33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[2865]34using HeuristicLab.PluginInfrastructure;
[2796]35
[3158]36namespace HeuristicLab.Problems.TravelingSalesman {
[3159]37  [Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
[2796]38  [Creatable("Problems")]
[3017]39  [StorableClass]
[3159]40  public sealed class TravelingSalesmanProblem : ParameterizedNamedItem, ISingleObjectiveProblem {
[2865]41    public override Image ItemImage {
42      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Type; }
[2805]43    }
44
[2975]45    #region Parameter Properties
[3048]46    public ValueParameter<BoolValue> MaximizationParameter {
47      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
[2805]48    }
[2975]49    IParameter ISingleObjectiveProblem.MaximizationParameter {
50      get { return MaximizationParameter; }
[2865]51    }
[3048]52    public ValueParameter<DoubleMatrix> CoordinatesParameter {
53      get { return (ValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
[2865]54    }
[3066]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    }
[2975]61    public ValueParameter<IPermutationCreator> SolutionCreatorParameter {
62      get { return (ValueParameter<IPermutationCreator>)Parameters["SolutionCreator"]; }
[2865]63    }
[2975]64    IParameter IProblem.SolutionCreatorParameter {
65      get { return SolutionCreatorParameter; }
[2865]66    }
[2975]67    public ValueParameter<ITSPEvaluator> EvaluatorParameter {
68      get { return (ValueParameter<ITSPEvaluator>)Parameters["Evaluator"]; }
69    }
70    IParameter IProblem.EvaluatorParameter {
71      get { return EvaluatorParameter; }
72    }
[3048]73    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
74      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
[2975]75    }
[3080]76    IParameter ISingleObjectiveProblem.BestKnownQualityParameter {
77      get { return BestKnownQualityParameter; }
78    }
[3151]79    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
80      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
81    }
[2975]82    #endregion
[2805]83
[2975]84    #region Properties
[3048]85    public DoubleMatrix Coordinates {
[2975]86      get { return CoordinatesParameter.Value; }
87      set { CoordinatesParameter.Value = value; }
[2865]88    }
[3066]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    }
[2975]97    public IPermutationCreator SolutionCreator {
[2865]98      get { return SolutionCreatorParameter.Value; }
[2975]99      set { SolutionCreatorParameter.Value = value; }
[2865]100    }
[2975]101    ISolutionCreator IProblem.SolutionCreator {
102      get { return SolutionCreatorParameter.Value; }
103    }
104    public ITSPEvaluator Evaluator {
[2865]105      get { return EvaluatorParameter.Value; }
[2975]106      set { EvaluatorParameter.Value = value; }
[2865]107    }
[2975]108    ISingleObjectiveEvaluator ISingleObjectiveProblem.Evaluator {
109      get { return EvaluatorParameter.Value; }
110    }
[2865]111    IEvaluator IProblem.Evaluator {
112      get { return EvaluatorParameter.Value; }
113    }
[3048]114    public DoubleValue BestKnownQuality {
[2975]115      get { return BestKnownQualityParameter.Value; }
116      set { BestKnownQualityParameter.Value = value; }
117    }
[3151]118    public Permutation BestKnownSolution {
119      get { return BestKnownSolutionParameter.Value; }
120      set { BestKnownSolutionParameter.Value = value; }
121    }
[3616]122    private List<IOperator> operators;
[2975]123    public IEnumerable<IOperator> Operators {
[3616]124      get { return operators; }
[2865]125    }
[3663]126    private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
127      get { return operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
[3616]128    }
[2975]129    #endregion
[2865]130
[3159]131    public TravelingSalesmanProblem()
[2796]132      : base() {
[2891]133      RandomPermutationCreator creator = new RandomPermutationCreator();
134      TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
135
[3048]136      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Traveling Salesman Problem is a minimization problem.", new BoolValue(false)));
[3504]137      Parameters.Add(new ValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
[3066]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)));
[2891]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));
[3048]142      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this TSP instance."));
[3151]143      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
[2865]144
[3504]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
[2865]152      creator.PermutationParameter.ActualName = "TSPTour";
153      evaluator.QualityParameter.ActualName = "TSPTourLength";
[2975]154      ParameterizeSolutionCreator();
155      ParameterizeEvaluator();
[2865]156
[2986]157      Initialize();
[2975]158    }
[2986]159    [StorableConstructor]
[3159]160    private TravelingSalesmanProblem(bool deserializing) : base() { }
[2891]161
[2975]162    public override IDeepCloneable Clone(Cloner cloner) {
[3159]163      TravelingSalesmanProblem clone = (TravelingSalesmanProblem)base.Clone(cloner);
[3430]164      clone.DistanceMatrixParameter.Value = DistanceMatrixParameter.Value;
[2986]165      clone.Initialize();
[2975]166      return clone;
[2805]167    }
[2796]168
[3151]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);
[3155]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      }
[3151]184      BestKnownQuality = null;
[3153]185      BestKnownSolution = null;
[3155]186
[3151]187      if (!string.IsNullOrEmpty(optimalTourFileName)) {
188        TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
189        tourParser.Parse();
[3153]190        if (tourParser.Tour.Length != Coordinates.Rows) throw new InvalidDataException("Length of optimal tour is not equal to number of cities.");
[3231]191        BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, tourParser.Tour);
[3151]192      }
[3739]193      OnReset();
[2796]194    }
[3151]195    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
196      ImportFromTSPLIB(tspFileName, optimalTourFileName);
197      BestKnownQuality = new DoubleValue(bestKnownQuality);
198    }
[2865]199
[2975]200    #region Events
201    public event EventHandler SolutionCreatorChanged;
202    private void OnSolutionCreatorChanged() {
[3739]203      EventHandler handler = SolutionCreatorChanged;
204      if (handler != null) handler(this, EventArgs.Empty);
[2865]205    }
[2975]206    public event EventHandler EvaluatorChanged;
207    private void OnEvaluatorChanged() {
[3739]208      EventHandler handler = EvaluatorChanged;
209      if (handler != null) handler(this, EventArgs.Empty);
[2975]210    }
211    public event EventHandler OperatorsChanged;
212    private void OnOperatorsChanged() {
[3739]213      EventHandler handler = OperatorsChanged;
214      if (handler != null) handler(this, EventArgs.Empty);
[2975]215    }
[3739]216    public event EventHandler Reset;
217    private void OnReset() {
218      EventHandler handler = Reset;
219      if (handler != null) handler(this, EventArgs.Empty);
220    }
[2975]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();
[3066]226      ClearDistanceMatrix();
[2975]227    }
228    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
[3066]229      ClearDistanceMatrix();
[2975]230    }
231    private void Coordinates_Reset(object sender, EventArgs e) {
232      ParameterizeSolutionCreator();
[3066]233      ClearDistanceMatrix();
[2975]234    }
[2865]235    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
[2975]236      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
237      ParameterizeSolutionCreator();
238      ParameterizeEvaluator();
[3662]239      ParameterizeAnalyzer();
[2975]240      ParameterizeOperators();
[2865]241      OnSolutionCreatorChanged();
242    }
[2975]243    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
244      ParameterizeEvaluator();
[3662]245      ParameterizeAnalyzer();
[2975]246      ParameterizeOperators();
247    }
[2865]248    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
[3139]249      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[2975]250      ParameterizeEvaluator();
[3209]251      UpdateMoveEvaluators();
[3662]252      ParameterizeAnalyzer();
[3066]253      ClearDistanceMatrix();
[2865]254      OnEvaluatorChanged();
255    }
[3139]256    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[3662]257      ParameterizeAnalyzer();
[3139]258    }
[3232]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;
[3074]263      }
264    }
[3232]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;
[3074]269      }
270    }
[2975]271    #endregion
[2865]272
[2975]273    #region Helpers
[2986]274    [StorableHook(HookType.AfterDeserialization)]
275    private void Initialize() {
276      InitializeOperators();
[2975]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);
[3139]283      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[2865]284    }
[3139]285
[3099]286    private void InitializeOperators() {
[3616]287      operators = new List<IOperator>();
[3663]288      operators.Add(new BestTSPSolutionAnalyzer());
[3662]289      ParameterizeAnalyzer();
[3616]290      operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
[3199]291      ParameterizeOperators();
[3209]292      UpdateMoveEvaluators();
[3099]293      InitializeMoveGenerators();
294    }
295    private void InitializeMoveGenerators() {
[3232]296      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
[3099]297        if (op is IMoveGenerator) {
[3232]298          op.InversionMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_InversionMoveParameter_ActualNameChanged);
[3099]299        }
300      }
[3232]301      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
[3099]302        if (op is IMoveGenerator) {
[3232]303          op.TranslocationMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TranslocationMoveParameter_ActualNameChanged);
[3099]304        }
305      }
306    }
[3209]307    private void UpdateMoveEvaluators() {
[3303]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();
[3209]316    }
[2975]317    private void ParameterizeSolutionCreator() {
[3048]318      SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
[3231]319      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
[2865]320    }
[2975]321    private void ParameterizeEvaluator() {
322      if (Evaluator is ITSPPathEvaluator)
323        ((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[3066]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      }
[2865]330    }
[3662]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";
[3789]336      BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
337      BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
338      BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
[3107]339    }
[2975]340    private void ParameterizeOperators() {
341      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
342        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
343        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
344      }
345      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
346        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
347      }
[3074]348      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
349        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
350      }
351      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
352        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
353        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
354        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
[3209]355        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
356        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[3074]357      }
[3340]358      string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
359      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
360        op.InversionMoveParameter.ActualName = inversionMove;
361      string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
362      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
363        op.TranslocationMoveParameter.ActualName = translocationMove;
[2975]364    }
[3074]365
[3066]366    private void ClearDistanceMatrix() {
367      DistanceMatrixParameter.Value = null;
368    }
[2975]369    #endregion
[2796]370  }
371}
Note: See TracBrowser for help on using the repository browser.