Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.TravelingSalesman/3.3/TravelingSalesmanProblem.cs @ 12966

Last change on this file since 12966 was 12891, checked in by bburlacu, 9 years ago

#1772: Merge trunk changes. Remove dead code from the genealogy analyzer.

File size: 24.8 KB
RevLine 
[2796]1#region License Information
2/* HeuristicLab
[12155]3 * Copyright (C) 2002-2015 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;
[8478]26using HeuristicLab.Analysis;
[2975]27using HeuristicLab.Common;
[2796]28using HeuristicLab.Core;
29using HeuristicLab.Data;
[3053]30using HeuristicLab.Encodings.PermutationEncoding;
[10347]31using HeuristicLab.EvolutionTracking;
[2834]32using HeuristicLab.Optimization;
[12155]33using HeuristicLab.Optimization.Operators;
[2805]34using HeuristicLab.Parameters;
[2796]35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[2865]36using HeuristicLab.PluginInfrastructure;
[7558]37using HeuristicLab.Problems.Instances;
[10300]38using HeuristicLab.Problems.TravelingSalesman.Analyzers;
[2796]39
[3158]40namespace HeuristicLab.Problems.TravelingSalesman {
[3159]41  [Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
[12891]42  [Creatable(CreatableAttribute.Categories.CombinatorialProblems, Priority = 100)]
[3017]43  [StorableClass]
[7558]44  public sealed class TravelingSalesmanProblem : SingleObjectiveHeuristicOptimizationProblem<ITSPEvaluator, IPermutationCreator>, IStorableContent,
45    IProblemInstanceConsumer<TSPData> {
46    private static readonly int DistanceMatrixSizeLimit = 1000;
[4419]47    public string Filename { get; set; }
48
[2975]49    #region Parameter Properties
[7621]50    public OptionalValueParameter<DoubleMatrix> CoordinatesParameter {
51      get { return (OptionalValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
[2865]52    }
[4825]53    public OptionalValueParameter<DistanceMatrix> DistanceMatrixParameter {
54      get { return (OptionalValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
[3066]55    }
56    public ValueParameter<BoolValue> UseDistanceMatrixParameter {
57      get { return (ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
58    }
[3151]59    public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
60      get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
61    }
[2975]62    #endregion
[2805]63
[2975]64    #region Properties
[3048]65    public DoubleMatrix Coordinates {
[2975]66      get { return CoordinatesParameter.Value; }
67      set { CoordinatesParameter.Value = value; }
[2865]68    }
[4825]69    public DistanceMatrix DistanceMatrix {
[3066]70      get { return DistanceMatrixParameter.Value; }
71      set { DistanceMatrixParameter.Value = value; }
72    }
73    public BoolValue UseDistanceMatrix {
74      get { return UseDistanceMatrixParameter.Value; }
75      set { UseDistanceMatrixParameter.Value = value; }
76    }
[3151]77    public Permutation BestKnownSolution {
78      get { return BestKnownSolutionParameter.Value; }
79      set { BestKnownSolutionParameter.Value = value; }
80    }
[3663]81    private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
[6938]82      get { return Operators.OfType<BestTSPSolutionAnalyzer>().FirstOrDefault(); }
[3616]83    }
[4623]84    private TSPAlleleFrequencyAnalyzer TSPAlleleFrequencyAnalyzer {
[6938]85      get { return Operators.OfType<TSPAlleleFrequencyAnalyzer>().FirstOrDefault(); }
[4623]86    }
[10300]87
88    private TSPGenealogyAnalyzer TSPGenealogyAnalyzer {
89      get { return Operators.OfType<TSPGenealogyAnalyzer>().FirstOrDefault(); }
90    }
91    private IPermutationCrossover TSPCrossover {
92      get { return Operators.OfType<IPermutationCrossover>().FirstOrDefault(); }
93    }
94
95    private IPermutationManipulator TSPManipulator {
96      get { return Operators.OfType<IPermutationManipulator>().FirstOrDefault(); }
97    }
[2975]98    #endregion
[2865]99
[6938]100    // BackwardsCompatibility3.3
101    #region Backwards compatible code, remove with 3.4
102    [Obsolete]
103    [Storable(Name = "operators")]
104    private IEnumerable<IOperator> oldOperators {
105      get { return null; }
106      set {
107        if (value != null && value.Any())
108          Operators.AddRange(value);
109      }
110    }
111    #endregion
[4098]112
113    [StorableConstructor]
[4118]114    private TravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
[4722]115    private TravelingSalesmanProblem(TravelingSalesmanProblem original, Cloner cloner)
116      : base(original, cloner) {
[7351]117      RegisterEventHandlers();
[4722]118    }
119    public override IDeepCloneable Clone(Cloner cloner) {
120      return new TravelingSalesmanProblem(this, cloner);
121    }
[3159]122    public TravelingSalesmanProblem()
[6938]123      : base(new TSPRoundedEuclideanPathEvaluator(), new RandomPermutationCreator()) {
[7621]124      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
[4825]125      Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
[8221]126      Parameters.Add(new ValueParameter<BoolValue>("UseDistanceMatrix", "True if the coordinates based evaluators should calculate the distance matrix from the coordinates and use it for evaluation similar to the distance matrix evaluator, otherwise false.", new BoolValue(true)));
[3151]127      Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
[2865]128
[6939]129      Maximization.Value = false;
[6051]130      MaximizationParameter.Hidden = true;
[8221]131      UseDistanceMatrixParameter.Hidden = true;
[4825]132      DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
133
[3504]134      Coordinates = new DoubleMatrix(new double[,] {
135        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
136        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
137        { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
138        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
139      });
140
[6938]141      SolutionCreator.PermutationParameter.ActualName = "TSPTour";
142      Evaluator.QualityParameter.ActualName = "TSPTourLength";
[2975]143      ParameterizeSolutionCreator();
144      ParameterizeEvaluator();
[2865]145
[4098]146      InitializeOperators();
[7351]147      RegisterEventHandlers();
[2975]148    }
[2891]149
[2975]150    #region Events
[6938]151    protected override void OnSolutionCreatorChanged() {
152      base.OnSolutionCreatorChanged();
153      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
154      ParameterizeSolutionCreator();
155      ParameterizeEvaluator();
156      ParameterizeAnalyzers();
157      ParameterizeOperators();
[2865]158    }
[6938]159    protected override void OnEvaluatorChanged() {
160      base.OnEvaluatorChanged();
161      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
162      ParameterizeEvaluator();
[7621]163      ParameterizeSolutionCreator();
[6938]164      UpdateMoveEvaluators();
165      ParameterizeAnalyzers();
[8221]166      if (Evaluator is ITSPCoordinatesPathEvaluator && Coordinates != null)
167        ClearDistanceMatrix();
[2975]168    }
169    private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
[7621]170      if (Coordinates != null) {
171        Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
172        Coordinates.Reset += new EventHandler(Coordinates_Reset);
173      }
[8221]174      if (Evaluator is ITSPCoordinatesPathEvaluator) {
175        ParameterizeSolutionCreator();
176        ClearDistanceMatrix();
177      }
[2975]178    }
179    private void Coordinates_ItemChanged(object sender, EventArgs<int, int> e) {
[8221]180      if (Evaluator is ITSPCoordinatesPathEvaluator) {
181        ClearDistanceMatrix();
182      }
[2975]183    }
184    private void Coordinates_Reset(object sender, EventArgs e) {
[8221]185      if (Evaluator is ITSPCoordinatesPathEvaluator) {
186        ParameterizeSolutionCreator();
187        ClearDistanceMatrix();
188      }
[2975]189    }
190    private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
191      ParameterizeEvaluator();
[4623]192      ParameterizeAnalyzers();
[2975]193      ParameterizeOperators();
194    }
[3139]195    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
[4623]196      ParameterizeAnalyzers();
[3139]197    }
[2975]198    #endregion
[2865]199
[2975]200    #region Helpers
[2986]201    [StorableHook(HookType.AfterDeserialization)]
[4722]202    private void AfterDeserialization() {
[4118]203      // BackwardsCompatibility3.3
204      #region Backwards compatible code (remove with 3.4)
[4825]205      OptionalValueParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as OptionalValueParameter<DoubleMatrix>;
206      if (oldDistanceMatrixParameter != null) {
207        Parameters.Remove(oldDistanceMatrixParameter);
208        Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
209        DistanceMatrixParameter.GetsCollected = oldDistanceMatrixParameter.GetsCollected;
210        DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
211        if (oldDistanceMatrixParameter.Value != null) {
212          DoubleMatrix oldDM = oldDistanceMatrixParameter.Value;
213          DistanceMatrix newDM = new DistanceMatrix(oldDM.Rows, oldDM.Columns, oldDM.ColumnNames, oldDM.RowNames);
214          newDM.SortableView = oldDM.SortableView;
215          for (int i = 0; i < newDM.Rows; i++)
216            for (int j = 0; j < newDM.Columns; j++)
217              newDM[i, j] = oldDM[i, j];
218          DistanceMatrixParameter.Value = (DistanceMatrix)newDM.AsReadOnly();
219        }
220      }
221
[7621]222      ValueParameter<DoubleMatrix> oldCoordinates = (Parameters["Coordinates"] as ValueParameter<DoubleMatrix>);
223      if (oldCoordinates != null) {
224        Parameters.Remove(oldCoordinates);
225        Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities.", oldCoordinates.Value, oldCoordinates.GetsCollected));
226      }
227
[6938]228      if (Operators.Count == 0) InitializeOperators();
[4118]229      #endregion
[7351]230      RegisterEventHandlers();
[4118]231    }
232
[7351]233    private void RegisterEventHandlers() {
[2975]234      CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
[7621]235      if (Coordinates != null) {
236        Coordinates.ItemChanged += new EventHandler<EventArgs<int, int>>(Coordinates_ItemChanged);
237        Coordinates.Reset += new EventHandler(Coordinates_Reset);
238      }
[2975]239      SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
[3139]240      Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
[2865]241    }
[3139]242
[3099]243    private void InitializeOperators() {
[8334]244      Operators.Add(new TSPImprovementOperator());
245      Operators.Add(new TSPMultipleGuidesPathRelinker());
246      Operators.Add(new TSPPathRelinker());
247      Operators.Add(new TSPSimultaneousPathRelinker());
248      Operators.Add(new TSPSimilarityCalculator());
[12155]249      Operators.Add(new QualitySimilarityCalculator());
250      Operators.Add(new NoSimilarityCalculator());
[8334]251
[6938]252      Operators.Add(new BestTSPSolutionAnalyzer());
253      Operators.Add(new TSPAlleleFrequencyAnalyzer());
[12155]254      Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
[10300]255      Operators.Add(new TSPGenealogyAnalyzer());
[4623]256      ParameterizeAnalyzers();
[7658]257      var operators = new HashSet<IPermutationOperator>(new IPermutationOperator[] {
[7626]258        new OrderCrossover2(),
259        new InversionManipulator(),
260        new StochasticInversionMultiMoveGenerator()
[7658]261      }, new TypeEqualityComparer<IPermutationOperator>());
262      foreach (var op in ApplicationManager.Manager.GetInstances<IPermutationOperator>())
263        operators.Add(op);
264      Operators.AddRange(operators);
[3199]265      ParameterizeOperators();
[3209]266      UpdateMoveEvaluators();
[3099]267    }
[3209]268    private void UpdateMoveEvaluators() {
[6938]269      Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
[3303]270      foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances<ITSPPathMoveEvaluator>())
271        if (op.EvaluatorType == Evaluator.GetType()) {
[6938]272          Operators.Add(op);
[3303]273        }
274      ParameterizeOperators();
275      OnOperatorsChanged();
[3209]276    }
[2975]277    private void ParameterizeSolutionCreator() {
[7621]278      if (Evaluator is ITSPDistanceMatrixEvaluator && DistanceMatrix != null)
279        SolutionCreator.LengthParameter.Value = new IntValue(DistanceMatrix.Rows);
280      else if (Evaluator is ITSPCoordinatesPathEvaluator && Coordinates != null)
281        SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
[8208]282      else {
283        SolutionCreator.LengthParameter.Value = null;
284        string error = "The given problem does not support the selected evaluator.";
285        if (Evaluator is ITSPDistanceMatrixEvaluator)
286          error += Environment.NewLine + "Please review that the " + DistanceMatrixParameter.Name + " parameter is defined or choose another evaluator.";
287        else error += Environment.NewLine + "Please review that the " + CoordinatesParameter.Name + " parameter is defined or choose another evaluator.";
288        PluginInfrastructure.ErrorHandling.ShowErrorDialog(error, null);
289      }
[7621]290      SolutionCreator.LengthParameter.Hidden = SolutionCreator.LengthParameter.Value != null;
[3231]291      SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
[6051]292      SolutionCreator.PermutationTypeParameter.Hidden = true;
[2865]293    }
[2975]294    private void ParameterizeEvaluator() {
[6051]295      if (Evaluator is ITSPPathEvaluator) {
296        ITSPPathEvaluator evaluator = (ITSPPathEvaluator)Evaluator;
297        evaluator.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
298        evaluator.PermutationParameter.Hidden = true;
299      }
[3066]300      if (Evaluator is ITSPCoordinatesPathEvaluator) {
301        ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
302        evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
[6051]303        evaluator.CoordinatesParameter.Hidden = true;
[3066]304        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
[6051]305        evaluator.DistanceMatrixParameter.Hidden = true;
[3066]306        evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
[6051]307        evaluator.UseDistanceMatrixParameter.Hidden = true;
[3066]308      }
[7558]309      if (Evaluator is ITSPDistanceMatrixEvaluator) {
310        var evaluator = (ITSPDistanceMatrixEvaluator)Evaluator;
311        evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
312        evaluator.DistanceMatrixParameter.Hidden = true;
313      }
[2865]314    }
[4623]315    private void ParameterizeAnalyzers() {
[4641]316      if (BestTSPSolutionAnalyzer != null) {
317        BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
318        BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
319        BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
320        BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
321        BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
322        BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
323        BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
324      }
[4623]325
[4641]326      if (TSPAlleleFrequencyAnalyzer != null) {
327        TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
328        TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
[4866]329        TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
[4641]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      }
[4703]335
[3107]336    }
[2975]337    private void ParameterizeOperators() {
338      foreach (IPermutationCrossover op in Operators.OfType<IPermutationCrossover>()) {
339        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]340        op.ParentsParameter.Hidden = true;
[2975]341        op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]342        op.ChildParameter.Hidden = true;
[2975]343      }
344      foreach (IPermutationManipulator op in Operators.OfType<IPermutationManipulator>()) {
345        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]346        op.PermutationParameter.Hidden = true;
[2975]347      }
[3074]348      foreach (IPermutationMoveOperator op in Operators.OfType<IPermutationMoveOperator>()) {
349        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]350        op.PermutationParameter.Hidden = true;
[3074]351      }
352      foreach (ITSPPathMoveEvaluator op in Operators.OfType<ITSPPathMoveEvaluator>()) {
353        op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
[6051]354        op.CoordinatesParameter.Hidden = true;
[3074]355        op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
[6051]356        op.DistanceMatrixParameter.Hidden = true;
[3074]357        op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
[6051]358        op.UseDistanceMatrixParameter.Hidden = true;
[3209]359        op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
[6051]360        op.QualityParameter.Hidden = true;
[3209]361        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]362        op.PermutationParameter.Hidden = true;
[3074]363      }
[6051]364      foreach (IPermutationMultiNeighborhoodShakingOperator op in Operators.OfType<IPermutationMultiNeighborhoodShakingOperator>()) {
[6042]365        op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
[6051]366        op.PermutationParameter.Hidden = true;
367      }
[8334]368      foreach (ISingleObjectiveImprovementOperator op in Operators.OfType<ISingleObjectiveImprovementOperator>()) {
369        op.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
370        op.SolutionParameter.Hidden = true;
371      }
372      foreach (ISingleObjectivePathRelinker op in Operators.OfType<ISingleObjectivePathRelinker>()) {
373        op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
374        op.ParentsParameter.Hidden = true;
375      }
[12155]376      foreach (ISolutionSimilarityCalculator op in Operators.OfType<ISolutionSimilarityCalculator>()) {
[8334]377        op.SolutionVariableName = SolutionCreator.PermutationParameter.ActualName;
378        op.QualityVariableName = Evaluator.QualityParameter.ActualName;
379      }
[10300]380      if (TSPGenealogyAnalyzer != null) {
381        if (TSPCrossover != null) {
[10830]382          TSPGenealogyAnalyzer.BeforeCrossoverOperatorParameter.ActualValue = new BeforeCrossoverOperator<Permutation>();
[11864]383          TSPGenealogyAnalyzer.BeforeCrossoverOperator.ParentsParameter.ActualName = TSPCrossover.ParentsParameter.ActualName;
384          TSPGenealogyAnalyzer.BeforeCrossoverOperator.ChildParameter.ActualName = TSPCrossover.ChildParameter.ActualName;
[10830]385          TSPGenealogyAnalyzer.AfterCrossoverOperatorParameter.ActualValue = new AfterCrossoverOperator<Permutation>();
[11864]386          TSPGenealogyAnalyzer.AfterCrossoverOperator.ParentsParameter.ActualName = TSPCrossover.ParentsParameter.ActualName;
387          TSPGenealogyAnalyzer.AfterCrossoverOperator.ChildParameter.ActualName = TSPCrossover.ChildParameter.ActualName;
[10300]388        }
389        if (TSPManipulator != null) {
[10830]390          TSPGenealogyAnalyzer.BeforeManipulatorOperatorParameter.ActualValue = new BeforeManipulatorOperator<Permutation>();
[11864]391          TSPGenealogyAnalyzer.BeforeManipulatorOperator.ChildParameter.ActualName = TSPManipulator.PermutationParameter.ActualName;
[10830]392          TSPGenealogyAnalyzer.AfterManipulatorOperatorParameter.ActualValue = new AfterManipulatorOperator<Permutation>();
[11864]393          TSPGenealogyAnalyzer.AfterManipulatorOperator.ChildParameter.ActualName = TSPManipulator.PermutationParameter.ActualName;
[10300]394        }
395        TSPGenealogyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
396        if (Evaluator is ITSPPathEvaluator) {
397          TSPGenealogyAnalyzer.PopulationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
398        } else {
399          throw new Exception("Unknown Evaluator. Could not parameterize genealogy analyzer.");
400        }
401      }
[2975]402    }
[3074]403
[3066]404    private void ClearDistanceMatrix() {
[8221]405      DistanceMatrixParameter.Value = null;
[3066]406    }
[2975]407    #endregion
[4098]408
[7558]409    public void Load(TSPData data) {
410      if (data.Coordinates == null && data.Distances == null)
[7621]411        throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
[7872]412      if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == DistanceMeasure.Att
413        || data.DistanceMeasure == DistanceMeasure.Manhattan
[9848]414        || data.DistanceMeasure == DistanceMeasure.Maximum))
[7558]415        throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix.");
416      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
417        throw new System.IO.InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
418
419      Name = data.Name;
420      Description = data.Description;
421
[8221]422      bool clearCoordinates = false, clearDistanceMatrix = false;
[7558]423      if (data.Coordinates != null && data.Coordinates.GetLength(0) > 0)
424        Coordinates = new DoubleMatrix(data.Coordinates);
[8221]425      else clearCoordinates = true;
[7558]426
427      TSPEvaluator evaluator;
[7872]428      if (data.DistanceMeasure == DistanceMeasure.Att
429        || data.DistanceMeasure == DistanceMeasure.Manhattan
[9848]430        || data.DistanceMeasure == DistanceMeasure.Maximum) {
[7558]431        evaluator = new TSPDistanceMatrixEvaluator();
432        UseDistanceMatrix = new BoolValue(true);
433        DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
[7872]434      } else if (data.DistanceMeasure == DistanceMeasure.Direct && data.Distances != null) {
[7558]435        evaluator = new TSPDistanceMatrixEvaluator();
436        UseDistanceMatrix = new BoolValue(true);
437        DistanceMatrix = new DistanceMatrix(data.Distances);
438      } else {
[8221]439        clearDistanceMatrix = true;
[7558]440        UseDistanceMatrix = new BoolValue(data.Dimension <= DistanceMatrixSizeLimit);
441        switch (data.DistanceMeasure) {
[7872]442          case DistanceMeasure.Euclidean:
[7558]443            evaluator = new TSPEuclideanPathEvaluator();
444            break;
[7872]445          case DistanceMeasure.RoundedEuclidean:
[7558]446            evaluator = new TSPRoundedEuclideanPathEvaluator();
447            break;
[9848]448          case DistanceMeasure.UpperEuclidean:
449            evaluator = new TSPUpperEuclideanPathEvaluator();
450            break;
[7872]451          case DistanceMeasure.Geo:
[7558]452            evaluator = new TSPGeoPathEvaluator();
453            break;
454          default:
455            throw new InvalidDataException("An unknown distance measure is given in the instance!");
456        }
[4098]457      }
[7558]458      evaluator.QualityParameter.ActualName = "TSPTourLength";
459      Evaluator = evaluator;
460
[8221]461      // reset them after assigning the evaluator
462      if (clearCoordinates) Coordinates = null;
463      if (clearDistanceMatrix) DistanceMatrix = null;
464
[7558]465      BestKnownSolution = null;
[4098]466      BestKnownQuality = null;
467
[7558]468      if (data.BestKnownTour != null) {
469        try {
470          EvaluateAndLoadTour(data.BestKnownTour);
[8720]471        }
472        catch (InvalidOperationException) {
[7558]473          if (data.BestKnownQuality.HasValue)
474            BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
475        }
476      } else if (data.BestKnownQuality.HasValue) {
477        BestKnownQuality = new DoubleValue(data.BestKnownQuality.Value);
[4098]478      }
479      OnReset();
480    }
[7558]481
482    public void EvaluateAndLoadTour(int[] tour) {
483      var route = new Permutation(PermutationTypes.RelativeUndirected, tour);
484      BestKnownSolution = route;
485
486      double quality;
[7621]487      if (Evaluator is ITSPDistanceMatrixEvaluator) {
[7558]488        quality = TSPDistanceMatrixEvaluator.Apply(DistanceMatrix, route);
[7621]489      } else if (Evaluator is ITSPCoordinatesPathEvaluator) {
[7558]490        quality = TSPCoordinatesPathEvaluator.Apply((TSPCoordinatesPathEvaluator)Evaluator, Coordinates, route);
491      } else {
492        throw new InvalidOperationException("Cannot calculate solution quality, evaluator type is unknown.");
493      }
494      BestKnownQuality = new DoubleValue(quality);
[4098]495    }
[2796]496  }
497}
Note: See TracBrowser for help on using the repository browser.