#region License Information
/* HeuristicLab
* Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Encodings.PermutationEncoding;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.PluginInfrastructure;
namespace HeuristicLab.Problems.TravelingSalesman {
[Item("Traveling Salesman Problem", "Represents a symmetric Traveling Salesman Problem.")]
[Creatable("Problems")]
[StorableClass]
public sealed class TravelingSalesmanProblem : ParameterizedNamedItem, ISingleObjectiveHeuristicOptimizationProblem, IStorableContent {
public string Filename { get; set; }
public override Image ItemImage {
get { return HeuristicLab.Common.Resources.VSImageLibrary.Type; }
}
#region Parameter Properties
public ValueParameter MaximizationParameter {
get { return (ValueParameter)Parameters["Maximization"]; }
}
IParameter ISingleObjectiveHeuristicOptimizationProblem.MaximizationParameter {
get { return MaximizationParameter; }
}
public ValueParameter CoordinatesParameter {
get { return (ValueParameter)Parameters["Coordinates"]; }
}
public OptionalValueParameter DistanceMatrixParameter {
get { return (OptionalValueParameter)Parameters["DistanceMatrix"]; }
}
public ValueParameter UseDistanceMatrixParameter {
get { return (ValueParameter)Parameters["UseDistanceMatrix"]; }
}
public ValueParameter SolutionCreatorParameter {
get { return (ValueParameter)Parameters["SolutionCreator"]; }
}
IParameter IHeuristicOptimizationProblem.SolutionCreatorParameter {
get { return SolutionCreatorParameter; }
}
public ValueParameter EvaluatorParameter {
get { return (ValueParameter)Parameters["Evaluator"]; }
}
IParameter IHeuristicOptimizationProblem.EvaluatorParameter {
get { return EvaluatorParameter; }
}
public OptionalValueParameter BestKnownQualityParameter {
get { return (OptionalValueParameter)Parameters["BestKnownQuality"]; }
}
IParameter ISingleObjectiveHeuristicOptimizationProblem.BestKnownQualityParameter {
get { return BestKnownQualityParameter; }
}
public OptionalValueParameter BestKnownSolutionParameter {
get { return (OptionalValueParameter)Parameters["BestKnownSolution"]; }
}
#endregion
#region Properties
public DoubleMatrix Coordinates {
get { return CoordinatesParameter.Value; }
set { CoordinatesParameter.Value = value; }
}
public DistanceMatrix DistanceMatrix {
get { return DistanceMatrixParameter.Value; }
set { DistanceMatrixParameter.Value = value; }
}
public BoolValue UseDistanceMatrix {
get { return UseDistanceMatrixParameter.Value; }
set { UseDistanceMatrixParameter.Value = value; }
}
public IPermutationCreator SolutionCreator {
get { return SolutionCreatorParameter.Value; }
set { SolutionCreatorParameter.Value = value; }
}
ISolutionCreator IHeuristicOptimizationProblem.SolutionCreator {
get { return SolutionCreatorParameter.Value; }
}
public ITSPEvaluator Evaluator {
get { return EvaluatorParameter.Value; }
set { EvaluatorParameter.Value = value; }
}
ISingleObjectiveEvaluator ISingleObjectiveHeuristicOptimizationProblem.Evaluator {
get { return EvaluatorParameter.Value; }
}
IEvaluator IHeuristicOptimizationProblem.Evaluator {
get { return EvaluatorParameter.Value; }
}
public DoubleValue BestKnownQuality {
get { return BestKnownQualityParameter.Value; }
set { BestKnownQualityParameter.Value = value; }
}
public Permutation BestKnownSolution {
get { return BestKnownSolutionParameter.Value; }
set { BestKnownSolutionParameter.Value = value; }
}
public IEnumerable Operators {
get { return operators; }
}
private BestTSPSolutionAnalyzer BestTSPSolutionAnalyzer {
get { return operators.OfType().FirstOrDefault(); }
}
private TSPAlleleFrequencyAnalyzer TSPAlleleFrequencyAnalyzer {
get { return operators.OfType().FirstOrDefault(); }
}
private TSPPopulationDiversityAnalyzer TSPPopulationDiversityAnalyzer {
get { return operators.OfType().FirstOrDefault(); }
}
#endregion
[Storable]
private List operators;
[StorableConstructor]
private TravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
private TravelingSalesmanProblem(TravelingSalesmanProblem original, Cloner cloner)
: base(original, cloner) {
this.operators = original.operators.Select(x => (IOperator)cloner.Clone(x)).ToList();
AttachEventHandlers();
}
public override IDeepCloneable Clone(Cloner cloner) {
return new TravelingSalesmanProblem(this, cloner);
}
public TravelingSalesmanProblem()
: base() {
RandomPermutationCreator creator = new RandomPermutationCreator();
TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
Parameters.Add(new ValueParameter("Maximization", "Set to false as the Traveling Salesman Problem is a minimization problem.", new BoolValue(false)));
Parameters.Add(new ValueParameter("Coordinates", "The x- and y-Coordinates of the cities."));
Parameters.Add(new OptionalValueParameter("DistanceMatrix", "The matrix which contains the distances between the cities."));
Parameters.Add(new ValueParameter("UseDistanceMatrix", "True if a distance matrix should be calculated and used for evaluation, otherwise false.", new BoolValue(true)));
Parameters.Add(new ValueParameter("SolutionCreator", "The operator which should be used to create new TSP solutions.", creator));
Parameters.Add(new ValueParameter("Evaluator", "The operator which should be used to evaluate TSP solutions.", evaluator));
Parameters.Add(new OptionalValueParameter("BestKnownQuality", "The quality of the best known solution of this TSP instance."));
Parameters.Add(new OptionalValueParameter("BestKnownSolution", "The best known solution of this TSP instance."));
DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
Coordinates = new DoubleMatrix(new double[,] {
{ 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
{ 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
{ 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
{ 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
});
creator.PermutationParameter.ActualName = "TSPTour";
evaluator.QualityParameter.ActualName = "TSPTourLength";
ParameterizeSolutionCreator();
ParameterizeEvaluator();
InitializeOperators();
AttachEventHandlers();
}
#region Events
public event EventHandler SolutionCreatorChanged;
private void OnSolutionCreatorChanged() {
EventHandler handler = SolutionCreatorChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public event EventHandler EvaluatorChanged;
private void OnEvaluatorChanged() {
EventHandler handler = EvaluatorChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public event EventHandler OperatorsChanged;
private void OnOperatorsChanged() {
EventHandler handler = OperatorsChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public event EventHandler Reset;
private void OnReset() {
EventHandler handler = Reset;
if (handler != null) handler(this, EventArgs.Empty);
}
private void CoordinatesParameter_ValueChanged(object sender, EventArgs e) {
Coordinates.ItemChanged += new EventHandler>(Coordinates_ItemChanged);
Coordinates.Reset += new EventHandler(Coordinates_Reset);
ParameterizeSolutionCreator();
ClearDistanceMatrix();
}
private void Coordinates_ItemChanged(object sender, EventArgs e) {
ClearDistanceMatrix();
}
private void Coordinates_Reset(object sender, EventArgs e) {
ParameterizeSolutionCreator();
ClearDistanceMatrix();
}
private void SolutionCreatorParameter_ValueChanged(object sender, EventArgs e) {
SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
ParameterizeSolutionCreator();
ParameterizeEvaluator();
ParameterizeAnalyzers();
ParameterizeOperators();
OnSolutionCreatorChanged();
}
private void SolutionCreator_PermutationParameter_ActualNameChanged(object sender, EventArgs e) {
ParameterizeEvaluator();
ParameterizeAnalyzers();
ParameterizeOperators();
}
private void EvaluatorParameter_ValueChanged(object sender, EventArgs e) {
Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
ParameterizeEvaluator();
UpdateMoveEvaluators();
ParameterizeAnalyzers();
ClearDistanceMatrix();
OnEvaluatorChanged();
}
private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
ParameterizeAnalyzers();
}
private void MoveGenerator_InversionMoveParameter_ActualNameChanged(object sender, EventArgs e) {
string name = ((ILookupParameter)sender).ActualName;
foreach (IPermutationInversionMoveOperator op in Operators.OfType()) {
op.InversionMoveParameter.ActualName = name;
}
}
private void MoveGenerator_TranslocationMoveParameter_ActualNameChanged(object sender, EventArgs e) {
string name = ((ILookupParameter)sender).ActualName;
foreach (IPermutationTranslocationMoveOperator op in Operators.OfType()) {
op.TranslocationMoveParameter.ActualName = name;
}
}
#endregion
#region Helpers
[StorableHook(HookType.AfterDeserialization)]
private void AfterDeserialization() {
// BackwardsCompatibility3.3
#region Backwards compatible code (remove with 3.4)
OptionalValueParameter oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as OptionalValueParameter;
if (oldDistanceMatrixParameter != null) {
Parameters.Remove(oldDistanceMatrixParameter);
Parameters.Add(new OptionalValueParameter("DistanceMatrix", "The matrix which contains the distances between the cities."));
DistanceMatrixParameter.GetsCollected = oldDistanceMatrixParameter.GetsCollected;
DistanceMatrixParameter.ReactOnValueToStringChangedAndValueItemImageChanged = false;
if (oldDistanceMatrixParameter.Value != null) {
DoubleMatrix oldDM = oldDistanceMatrixParameter.Value;
DistanceMatrix newDM = new DistanceMatrix(oldDM.Rows, oldDM.Columns, oldDM.ColumnNames, oldDM.RowNames);
newDM.SortableView = oldDM.SortableView;
for (int i = 0; i < newDM.Rows; i++)
for (int j = 0; j < newDM.Columns; j++)
newDM[i, j] = oldDM[i, j];
DistanceMatrixParameter.Value = (DistanceMatrix)newDM.AsReadOnly();
}
}
if (operators == null) InitializeOperators();
#endregion
AttachEventHandlers();
}
private void AttachEventHandlers() {
CoordinatesParameter.ValueChanged += new EventHandler(CoordinatesParameter_ValueChanged);
Coordinates.ItemChanged += new EventHandler>(Coordinates_ItemChanged);
Coordinates.Reset += new EventHandler(Coordinates_Reset);
SolutionCreatorParameter.ValueChanged += new EventHandler(SolutionCreatorParameter_ValueChanged);
SolutionCreator.PermutationParameter.ActualNameChanged += new EventHandler(SolutionCreator_PermutationParameter_ActualNameChanged);
EvaluatorParameter.ValueChanged += new EventHandler(EvaluatorParameter_ValueChanged);
Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
}
private void InitializeOperators() {
operators = new List();
operators.Add(new BestTSPSolutionAnalyzer());
operators.Add(new TSPAlleleFrequencyAnalyzer());
operators.Add(new TSPPopulationDiversityAnalyzer());
ParameterizeAnalyzers();
operators.AddRange(ApplicationManager.Manager.GetInstances().Cast());
ParameterizeOperators();
UpdateMoveEvaluators();
InitializeMoveGenerators();
}
private void InitializeMoveGenerators() {
foreach (IPermutationInversionMoveOperator op in Operators.OfType()) {
if (op is IMoveGenerator) {
op.InversionMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_InversionMoveParameter_ActualNameChanged);
}
}
foreach (IPermutationTranslocationMoveOperator op in Operators.OfType()) {
if (op is IMoveGenerator) {
op.TranslocationMoveParameter.ActualNameChanged += new EventHandler(MoveGenerator_TranslocationMoveParameter_ActualNameChanged);
}
}
}
private void UpdateMoveEvaluators() {
operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator);
foreach (ITSPPathMoveEvaluator op in ApplicationManager.Manager.GetInstances())
if (op.EvaluatorType == Evaluator.GetType()) {
operators.Add(op);
}
ParameterizeOperators();
OnOperatorsChanged();
}
private void ParameterizeSolutionCreator() {
SolutionCreator.LengthParameter.Value = new IntValue(Coordinates.Rows);
SolutionCreator.PermutationTypeParameter.Value = new PermutationType(PermutationTypes.RelativeUndirected);
}
private void ParameterizeEvaluator() {
if (Evaluator is ITSPPathEvaluator)
((ITSPPathEvaluator)Evaluator).PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
if (Evaluator is ITSPCoordinatesPathEvaluator) {
ITSPCoordinatesPathEvaluator evaluator = (ITSPCoordinatesPathEvaluator)Evaluator;
evaluator.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
evaluator.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
evaluator.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
}
}
private void ParameterizeAnalyzers() {
if (BestTSPSolutionAnalyzer != null) {
BestTSPSolutionAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
BestTSPSolutionAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
BestTSPSolutionAnalyzer.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
BestTSPSolutionAnalyzer.ResultsParameter.ActualName = "Results";
BestTSPSolutionAnalyzer.BestKnownQualityParameter.ActualName = BestKnownQualityParameter.Name;
BestTSPSolutionAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
BestTSPSolutionAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
}
if (TSPAlleleFrequencyAnalyzer != null) {
TSPAlleleFrequencyAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
TSPAlleleFrequencyAnalyzer.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
TSPAlleleFrequencyAnalyzer.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
TSPAlleleFrequencyAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
TSPAlleleFrequencyAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
TSPAlleleFrequencyAnalyzer.BestKnownSolutionParameter.ActualName = BestKnownSolutionParameter.Name;
TSPAlleleFrequencyAnalyzer.ResultsParameter.ActualName = "Results";
}
if (TSPPopulationDiversityAnalyzer != null) {
TSPPopulationDiversityAnalyzer.MaximizationParameter.ActualName = MaximizationParameter.Name;
TSPPopulationDiversityAnalyzer.SolutionParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
TSPPopulationDiversityAnalyzer.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
TSPPopulationDiversityAnalyzer.ResultsParameter.ActualName = "Results";
}
}
private void ParameterizeOperators() {
foreach (IPermutationCrossover op in Operators.OfType()) {
op.ParentsParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
op.ChildParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
}
foreach (IPermutationManipulator op in Operators.OfType()) {
op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
}
foreach (IPermutationMoveOperator op in Operators.OfType()) {
op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
}
foreach (ITSPPathMoveEvaluator op in Operators.OfType()) {
op.CoordinatesParameter.ActualName = CoordinatesParameter.Name;
op.DistanceMatrixParameter.ActualName = DistanceMatrixParameter.Name;
op.UseDistanceMatrixParameter.ActualName = UseDistanceMatrixParameter.Name;
op.QualityParameter.ActualName = Evaluator.QualityParameter.ActualName;
op.PermutationParameter.ActualName = SolutionCreator.PermutationParameter.ActualName;
}
string inversionMove = Operators.OfType().OfType().First().InversionMoveParameter.ActualName;
foreach (IPermutationInversionMoveOperator op in Operators.OfType())
op.InversionMoveParameter.ActualName = inversionMove;
string translocationMove = Operators.OfType().OfType().First().TranslocationMoveParameter.ActualName;
foreach (IPermutationTranslocationMoveOperator op in Operators.OfType())
op.TranslocationMoveParameter.ActualName = translocationMove;
}
private void ClearDistanceMatrix() {
DistanceMatrixParameter.Value = null;
}
#endregion
public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName) {
TSPLIBParser tspParser = new TSPLIBParser(tspFileName);
tspParser.Parse();
Name = tspParser.Name + " TSP (imported from TSPLIB)";
if (!string.IsNullOrEmpty(tspParser.Comment)) Description = tspParser.Comment;
Coordinates = new DoubleMatrix(tspParser.Vertices);
if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.EUC_2D) {
TSPRoundedEuclideanPathEvaluator evaluator = new TSPRoundedEuclideanPathEvaluator();
evaluator.QualityParameter.ActualName = "TSPTourLength";
Evaluator = evaluator;
} else if (tspParser.WeightType == TSPLIBParser.TSPLIBEdgeWeightType.GEO) {
TSPGeoPathEvaluator evaluator = new TSPGeoPathEvaluator();
evaluator.QualityParameter.ActualName = "TSPTourLength";
Evaluator = evaluator;
}
BestKnownQuality = null;
BestKnownSolution = null;
if (!string.IsNullOrEmpty(optimalTourFileName)) {
TSPLIBTourParser tourParser = new TSPLIBTourParser(optimalTourFileName);
tourParser.Parse();
if (tourParser.Tour.Length != Coordinates.Rows) throw new InvalidDataException("Length of optimal tour is not equal to number of cities.");
BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, tourParser.Tour);
}
OnReset();
}
public void ImportFromTSPLIB(string tspFileName, string optimalTourFileName, double bestKnownQuality) {
ImportFromTSPLIB(tspFileName, optimalTourFileName);
BestKnownQuality = new DoubleValue(bestKnownQuality);
}
}
}