Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs @ 12875

Last change on this file since 12875 was 4790, checked in by abeham, 14 years ago

#1258

  • Added detection if a certain link in the chain implements INotifyPropertyChanged (still missing -> fire only on a change to the "right" property)
  • Added optional parameter LambdaExpression in the binding
  • Changed cloning behavior of binding -> bindings have to be cloned only after the clone is fully constructed
File size: 20.3 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;
35using System.Linq.Expressions;
36
37namespace HeuristicLab.Problems.TravelingSalesman {
38  [Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
39  [Creatable("Problems")]
40  [StorableClass]
41  public sealed class TravelingSalesmanProblem : ParameterizedNamedItem, ISingleObjectiveProblem, IStorableContent {
42    public string Filename { get; set; }
43
44    public override Image ItemImage {
45      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Type; }
46    }
47
48    #region Parameter Properties
49    public ValueParameter<BoolValue> MaximizationParameter {
50      get { return (ValueParameter<BoolValue>)Parameters["Maximization"]; }
51    }
52    IParameter ISingleObjectiveProblem.MaximizationParameter {
53      get { return MaximizationParameter; }
54    }
55    public ValueParameter<DoubleMatrix> CoordinatesParameter {
56      get { return (ValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
57    }
58    public OptionalValueParameter<DoubleMatrix> DistanceMatrixParameter {
59      get { return (OptionalValueParameter<DoubleMatrix>)Parameters["DistanceMatrix"]; }
60    }
61    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
62      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
63    }
64    public ValueParameter<IPermutationCreator> SolutionCreatorParameter {
65      get { return (ValueParameter<IPermutationCreator>)Parameters["SolutionCreator"]; }
66    }
67    IParameter IProblem.SolutionCreatorParameter {
68      get { return SolutionCreatorParameter; }
69    }
70    public ValueParameter<ITSPEvaluator> EvaluatorParameter {
71      get { return (ValueParameter<ITSPEvaluator>)Parameters["Evaluator"]; }
72    }
73    IParameter IProblem.EvaluatorParameter {
74      get { return EvaluatorParameter; }
75    }
76    public OptionalValueParameter<DoubleValue> BestKnownQualityParameter {
77      get { return (OptionalValueParameter<DoubleValue>)Parameters["BestKnownQuality"]; }
78    }
79    IParameter ISingleObjectiveProblem.BestKnownQualityParameter {
80      get { return BestKnownQualityParameter; }
81    }
82    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
83      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
84    }
85    #endregion
86
87    #region Properties
88    public DoubleMatrix Coordinates {
89      get { return CoordinatesParameter.Value; }
90      set { CoordinatesParameter.Value = value; }
91    }
92    public DoubleMatrix DistanceMatrix {
93      get { return DistanceMatrixParameter.Value; }
94      set { DistanceMatrixParameter.Value = value; }
95    }
96    public BoolValue UseDistanceMatrix {
97      get { return UseDistanceMatrixParameter.Value; }
98      set { UseDistanceMatrixParameter.Value = value; }
99    }
100    public IPermutationCreator SolutionCreator {
101      get { return SolutionCreatorParameter.Value; }
102      set { SolutionCreatorParameter.Value = value; }
103    }
104    ISolutionCreator IProblem.SolutionCreator {
105      get { return SolutionCreatorParameter.Value; }
106    }
107    public ITSPEvaluator Evaluator {
108      get { return EvaluatorParameter.Value; }
109      set { EvaluatorParameter.Value = value; }
110    }
111    ISingleObjectiveEvaluator ISingleObjectiveProblem.Evaluator {
112      get { return EvaluatorParameter.Value; }
113    }
114    IEvaluator IProblem.Evaluator {
115      get { return EvaluatorParameter.Value; }
116    }
117    public DoubleValue BestKnownQuality {
118      get { return BestKnownQualityParameter.Value; }
119      set { BestKnownQualityParameter.Value = value; }
120    }
121    public Permutation BestKnownSolution {
122      get { return BestKnownSolutionParameter.Value; }
123      set { BestKnownSolutionParameter.Value = value; }
124    }
125    public IEnumerable<IOperator> Operators {
126      get { return operators; }
127    }
128    private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
129      get { return operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
130    }
131    private TSPAlleleFrequencyAnalyzer TSPAlleleFrequencyAnalyzer {
132      get { return operators.OfType<TSPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
133    }
134    private TSPPopulationDiversityAnalyzer TSPPopulationDiversityAnalyzer {
135      get { return operators.OfType<TSPPopulationDiversityAnalyzer>().FirstOrDefault(); }
136    }
137    #endregion
138
139    [Storable]
140    private List<IOperator> operators;
141
142    [StorableConstructor]
143    private TravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
144    private TravelingSalesmanProblem(TravelingSalesmanProblem original, Cloner cloner)
145      : base(original, cloner) {
146      this.operators = original.operators.Select(x => (IOperator)cloner.Clone(x)).ToList();
147      this.DistanceMatrixParameter.Value = original.DistanceMatrixParameter.Value;
148      AttachEventHandlers();
149    }
150    public override IDeepCloneable Clone(Cloner cloner) {
151      TravelingSalesmanProblem clone = new TravelingSalesmanProblem(this, cloner);
152      clone.parameterBindingList = this.parameterBindingList.Select(x => cloner.Clone(x)).ToList();
153      return clone;
154    }
155    public TravelingSalesmanProblem()
156      : base() {
157      RandomPermutationCreator creator = new RandomPermutationCreator();
158      TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
159
160      Parameters.Add(new ValueParameter<BoolValue>("Maximization", "Set to false as the Traveling Salesman Problem is a minimization problem.", new BoolValue(false)));
161      Parameters.Add(new ValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
162      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
163      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false.", new BoolValue(true)));
164      Parameters.Add(new ValueParameter<IPermutationCreator>("SolutionCreator", "The operator which should be used to create new TSP solutions.", creator));
165      Parameters.Add(new ValueParameter<ITSPEvaluator>("Evaluator", "The operator which should be used to evaluate TSP solutions.", evaluator));
166      Parameters.Add(new OptionalValueParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this TSP instance."));
167      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
168
169      Coordinates = new DoubleMatrix(new double[,] {
170        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
171        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
172        { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
173        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
174      });
175
176      creator.PermutationParameter.ActualName = "TSPTour";
177      evaluator.QualityParameter.ActualName = "TSPTourLength";
178      ParameterizeSolutionCreator();
179      ParameterizeEvaluator();
180
181      InitializeOperators();
182      AttachEventHandlers();
183      CreateBindings();
184    }
185
186    private void CreateBindings() {
187      #region Analyzers
188      AddBinding("BestTSPSolutionAnalyzer.QualityParameter.ActualName", "Evaluator.QualityParameter.ActualName");
189      AddBinding("BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName", "CoordinatesParameter.Name");
190      AddBinding("BestTSPSolutionAnalyzer.PermutationParameter.ActualName", "SolutionCreator.PermutationParameter.ActualName");
191      AddBinding("BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName", "BestKnownQualityParameter.Name");
192      AddBinding("BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName", "BestKnownSolutionParameter.Name");
193      AddBinding("BestTSPSolutionAnalyzer.MaximizationParameter.ActualName", "MaximizationParameter.Name");
194      AddBinding("TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName", "MaximizationParameter.Name");
195      AddBinding("TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName", "CoordinatesParameter.Name");
196      AddBinding("TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName", "SolutionCreator.PermutationParameter.ActualName");
197      AddBinding("TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName", "Evaluator.QualityParameter.ActualName");
198      AddBinding("TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName", "BestKnownSolutionParameter.Name");
199      AddBinding("TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName", "MaximizationParameter.Name");
200      AddBinding("TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName", "SolutionCreator.PermutationParameter.ActualName");
201      AddBinding("TSPPopulationDiversityAnalyzer.QualityParameter.ActualName", "Evaluator.QualityParameter.ActualName");
202      #endregion
203      Expression<Func<IEnumerable<string>,IntValue>> tmp = (x) => new IntValue(x.Count());
204      AddBinding("SolutionCreator.LengthParameter.Value", "Coordinates.RowNames", tmp);
205      Expression<Func<IPermutationCreator, PermutationType>> tmp2 = (x) => new PermutationType(PermutationTypes.RelativeUndirected);
206      AddBinding("SolutionCreator.PermutationTypeParameter.Value", "SolutionCreator", tmp2);
207    }
208
209    #region Events
210    public event EventHandler SolutionCreatorChanged;
211    private void OnSolutionCreatorChanged() {
212      EventHandler handler = SolutionCreatorChanged;
213      if (handler != null) handler(this, EventArgs.Empty);
214    }
215    public event EventHandler EvaluatorChanged;
216    private void OnEvaluatorChanged() {
217      EventHandler handler = EvaluatorChanged;
218      if (handler != null) handler(this, EventArgs.Empty);
219    }
220    public event EventHandler OperatorsChanged;
221    private void OnOperatorsChanged() {
222      EventHandler handler = OperatorsChanged;
223      if (handler != null) handler(this, EventArgs.Empty);
224    }
225    public event EventHandler Reset;
226    private void OnReset() {
227      EventHandler handler = Reset;
228      if (handler != null) handler(this, EventArgs.Empty);
229    }
230
231    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
232      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
233      Coordinates.Reset += new EventHandler(Coordinates_Reset);
234      ParameterizeSolutionCreator();
235      ClearDistanceMatrix();
236    }
237    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
238      ClearDistanceMatrix();
239    }
240    private void Coordinates_Reset(object sender, EventArgs e) {
241      ParameterizeSolutionCreator();
242      ClearDistanceMatrix();
243    }
244    private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
245      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
246      ParameterizeSolutionCreator();
247      ParameterizeEvaluator();
248      ParameterizeOperators();
249      OnSolutionCreatorChanged();
250    }
251    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
252      ParameterizeEvaluator();
253      ParameterizeOperators();
254    }
255    private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
256      ParameterizeEvaluator();
257      UpdateMoveEvaluators();
258      ClearDistanceMatrix();
259      OnEvaluatorChanged();
260    }
261    private void MoveGenerator_InversionMoveParameter_ActualNameChanged(object sender, EventArgs e) {
262      string name = ((ILookupParameter<InversionMove>)sender).ActualName;
263      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
264        op.InversionMoveParameter.ActualName = name;
265      }
266    }
267    private void MoveGenerator_TranslocationMoveParameter_ActualNameChanged(object sender, EventArgs e) {
268      string name = ((ILookupParameter<TranslocationMove>)sender).ActualName;
269      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
270        op.TranslocationMoveParameter.ActualName = name;
271      }
272    }
273    #endregion
274
275    #region Helpers
276    [StorableHook(HookType.AfterDeserialization)]
277    private void AfterDeserialization() {
278      // BackwardsCompatibility3.3
279      #region Backwards compatible code (remove with 3.4)
280      if (operators == null) InitializeOperators();
281      #endregion
282      AttachEventHandlers();
283    }
284
285    private void AttachEventHandlers() {
286      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
287      Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
288      Coordinates.Reset += new EventHandler(Coordinates_Reset);
289      SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
290      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
291      EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
292    }
293
294    private void InitializeOperators() {
295      operators = new List<IOperator>();
296      operators.Add(new BestTSPSolutionAnalyzer());
297      operators.Add(new TSPAlleleFrequencyAnalyzer());
298      operators.Add(new TSPPopulationDiversityAnalyzer());
299      BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
300      TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
301      TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
302      operators.AddRange(ApplicationManager.Manager.GetInstances<IPermutationOperator>().Cast<IOperator>());
303      ParameterizeOperators();
304      UpdateMoveEvaluators();
305      InitializeMoveGenerators();
306    }
307    private void InitializeMoveGenerators() {
308      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>()) {
309        if (op is IMoveGenerator) {
310          op.InversionMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_InversionMoveParameter_ActualNameChanged);
311        }
312      }
313      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>()) {
314        if (op is IMoveGenerator) {
315          op.TranslocationMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TranslocationMoveParameter_ActualNameChanged);
316        }
317      }
318    }
319    private void UpdateMoveEvaluators() {
320      operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
321      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
322        if (op.EvaluatorType == Evaluator.GetType()) {
323          operators.Add(op);
324        }
325      ParameterizeOperators();
326      OnOperatorsChanged();
327    }
328    private void ParameterizeSolutionCreator() {
329      //SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
330      //SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
331    }
332    private void ParameterizeEvaluator() {
333      if (Evaluator is ITSPPathEvaluator)
334        ((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
335      if (Evaluator is ITSPCoordinatesPathEvaluator) {
336        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
337        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
338        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
339        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
340      }
341    }
342    private void ParameterizeOperators() {
343      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
344        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
345        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
346      }
347      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
348        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
349      }
350      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
351        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
352      }
353      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
354        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
355        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
356        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
357        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
358        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
359      }
360      string inversionMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationInversionMoveOperator>().First().InversionMoveParameter.ActualName;
361      foreach (IPermutationInversionMoveOperator op in Operators.OfType<IPermutationInversionMoveOperator>())
362        op.InversionMoveParameter.ActualName = inversionMove;
363      string translocationMove = Operators.OfType<IMoveGenerator>().OfType<IPermutationTranslocationMoveOperator>().First().TranslocationMoveParameter.ActualName;
364      foreach (IPermutationTranslocationMoveOperator op in Operators.OfType<IPermutationTranslocationMoveOperator>())
365        op.TranslocationMoveParameter.ActualName = translocationMove;
366    }
367
368    private void ClearDistanceMatrix() {
369      DistanceMatrixParameter.Value = null;
370    }
371    #endregion
372
373    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName) {
374      TSPLIBParser tspParser = new TSPLIBParser(tspFileName);
375      tspParser.Parse();
376      Name = tspParser.Name + " TSP (imported from TSPLIB)";
377      if (!string.IsNullOrEmpty(tspParser.Comment)) Description = tspParser.Comment;
378      Coordinates = new DoubleMatrix(tspParser.Vertices);
379      if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D) {
380        TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
381        evaluator.QualityParameter.ActualName = "TSPTourLength";
382        Evaluator = evaluator;
383      } else if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.GEO) {
384        TSPGeoPathEvaluator evaluator = new TSPGeoPathEvaluator();
385        evaluator.QualityParameter.ActualName = "TSPTourLength";
386        Evaluator = evaluator;
387      }
388      BestKnownQuality = null;
389      BestKnownSolution = null;
390
391      if (!string.IsNullOrEmpty(optimalTourFileName)) {
392        TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
393        tourParser.Parse();
394        if (tourParser.Tour.Length != Coordinates.Rows) throw new InvalidDataException("Length of optimal tour is not equal to number of cities.");
395        BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, tourParser.Tour);
396      }
397      OnReset();
398    }
399    public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
400      ImportFromTSPLIB(tspFileName, optimalTourFileName);
401      BestKnownQuality = new DoubleValue(bestKnownQuality);
402    }
403  }
404}
Note: See TracBrowser for help on using the repository browser.