Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10903 was 10886, checked in by bburlacu, 11 years ago

#1772: Simplified GenealogyGraph (and related components) API in an effort to improve speed and memory consumption (eg., by sharing the same arc when walking the graph in both directions: parent-child and child-parent).

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