Changeset 13412 for branches/PTSP/HeuristicLab.Problems.PTSP
- Timestamp:
- 11/28/15 23:38:51 (9 years ago)
- Location:
- branches/PTSP/HeuristicLab.Problems.PTSP/3.3
- Files:
-
- 12 added
- 4 deleted
- 10 edited
- 10 copied
- 2 moved
Legend:
- Unmodified
- Added
- Removed
-
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/AnalyticalPTSP.cs
r12306 r13412 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using HeuristicLab.Optimization; 7 using HeuristicLab.PluginInfrastructure; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using HeuristicLab.Common; 8 23 using HeuristicLab.Core; 24 using HeuristicLab.Data; 25 using HeuristicLab.Encodings.PermutationEncoding; 9 26 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 10 using HeuristicLab.Problems.Instances;11 using HeuristicLab.Encodings.PermutationEncoding;12 using HeuristicLab.Common;13 using HeuristicLab.Parameters;14 using HeuristicLab.Data;15 27 16 28 namespace HeuristicLab.Problems.PTSP { 17 [Item("Analytical Probabilistic Traveling Salesman Problem ", "Represents an analytical Probabilistic Traveling Salesman Problem.")]18 [Creatable( "Problems")]29 [Item("Analytical Probabilistic Traveling Salesman Problem (PTSP)", "Represents a probabilistic traveling salesman problem where the expected tour length is calculated exactly.")] 30 [Creatable(CreatableAttribute.Categories.CombinatorialProblems)] 19 31 [StorableClass] 20 public sealed class AnalyticalProbabilisticTravelingSalesmanProblem : ProbabilisticTravelingSalesmanProblem, IStorableContent, 21 IProblemInstanceConsumer<PTSPData> { 32 public sealed class AnalyticalProbabilisticTravelingSalesmanProblem : ProbabilisticTravelingSalesmanProblem { 22 33 23 34 [StorableConstructor] 24 35 private AnalyticalProbabilisticTravelingSalesmanProblem(bool deserializing) : base(deserializing) { } 25 private AnalyticalProbabilisticTravelingSalesmanProblem(AnalyticalProbabilisticTravelingSalesmanProblem original, Cloner cloner) 26 : base(original, cloner) { 36 private AnalyticalProbabilisticTravelingSalesmanProblem(AnalyticalProbabilisticTravelingSalesmanProblem original, Cloner cloner) : base(original, cloner) { } 37 public AnalyticalProbabilisticTravelingSalesmanProblem() { 38 Operators.Add(new BestPTSPSolutionAnalyzer()); 27 39 } 28 40 … … 31 43 } 32 44 33 public override double Evaluate(Individual individual, IRandom random) { 34 Permutation p = individual.Permutation(); 35 // Compute A and B matrices 36 DoubleMatrix A = new DoubleMatrix(p.Length, p.Length - 1); 37 DoubleMatrix B = new DoubleMatrix(p.Length, p.Length - 1); 38 //for (int i = 0; i < p.Length; i++) { 39 // for (int k = 0; k < p.Length - 1; k++) { 40 // double firstPartial = 0; 41 // for (int r = k; k < p.Length - 1; r++) { 42 // double sum0 = DistanceMatrix[p[i],p[i+r]]* ProbabilityMatrix[0, p[i]] * ProbabilityMatrix[0, p[i+r]]; 43 // for(int s = i+1; s < i+r; s++) { 44 // sum0 = sum0 * (1 - ProbabilityMatrix[0, p[s]]); 45 // } 46 // firstPartial+=sum0; 47 // } 48 // double secondPartial = 0; 49 // for (int r = k; k < p.Length - 1; r++) { 50 // double sum1 = DistanceMatrix[p[i-r],p[i]]* ProbabilityMatrix[0, p[i-r]] * ProbabilityMatrix[0, p[i]]; 51 // for (int s = i + 1; s < p.Length-1; s++) { 52 // sum1 = sum1 * (1 - ProbabilityMatrix[0, p[s]]); 53 // } 54 // for (int t = 1; t < i-1; t++) { 55 // sum1 = sum1 * (1 - ProbabilityMatrix[0, p[t]]); 56 // } 57 // secondPartial+=sum1; 58 // } 59 // A[i, k] = firstPartial; 60 // B[i, k] = secondPartial; 61 // } 62 //} 63 45 public override double Evaluate(Permutation tour, IRandom random) { 64 46 // Analytical evaluation 65 47 double firstSum = 0; 66 for (int i = 0; i < p.Length - 1; i++) {67 for (int j = i + 1; j < p.Length - 1; j++) {68 double sum1 = DistanceMatrix[ p[i], p[j]] * ProbabilityMatrix[p[i]] * ProbabilityMatrix[p[j]];48 for (int i = 0; i < tour.Length - 1; i++) { 49 for (int j = i + 1; j < tour.Length - 1; j++) { 50 double sum1 = DistanceMatrix[tour[i], tour[j]] * Probabilities[tour[i]] * Probabilities[tour[j]]; 69 51 for (int k = i + 1; k < j; k++) { 70 sum1 = sum1 * (1 - Probabilit yMatrix[p[k]]);52 sum1 = sum1 * (1 - Probabilities[tour[k]]); 71 53 } 72 A[i, j - 1] = sum1;73 54 firstSum += sum1; 74 55 } 75 56 } 76 57 double secondSum = 0; 77 for (int j = 0; j < p.Length - 1; j++) {58 for (int j = 0; j < tour.Length - 1; j++) { 78 59 for (int i = 0; i < j; i++) { 79 double sum2 = DistanceMatrix[ p[j], p[i]] * ProbabilityMatrix[p[i]] * ProbabilityMatrix[p[j]];80 for (int k = j + 1; k < p.Length - 1; k++) {81 sum2 = sum2 * (1 - Probabilit yMatrix[p[k]]);60 double sum2 = DistanceMatrix[tour[j], tour[i]] * Probabilities[tour[i]] * Probabilities[tour[j]]; 61 for (int k = j + 1; k < tour.Length - 1; k++) { 62 sum2 = sum2 * (1 - Probabilities[tour[k]]); 82 63 } 83 64 for (int k = 1; k < i; k++) { 84 sum2 = sum2 * (1 - Probabilit yMatrix[p[k]]);65 sum2 = sum2 * (1 - Probabilities[tour[k]]); 85 66 } 86 B[i, j] = sum2;87 67 secondSum += sum2; 88 68 } 89 }90 foreach (var op in Operators.OfType<PTSPAnalyticalInversionMovePathEvaluator>()) {91 op.AParameter.Value = A;92 op.BParameter.Value = B;93 69 } 94 70 return firstSum + secondSum; 95 71 } 96 72 97 public double EvaluateWithParams(DistanceMatrix distances, DoubleArray probabilities, Permutation individual) { 98 Permutation p = individual; 99 // Compute A and B matrices 100 DoubleMatrix A = new DoubleMatrix(p.Length, p.Length - 1); 101 DoubleMatrix B = new DoubleMatrix(p.Length, p.Length - 1); 73 public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, DoubleArray probabilities) { 102 74 // Analytical evaluation 103 double firstSum =0;104 for ( int i = 0; i < p.Length; i++) {105 for ( int j = i + 1; j < p.Length; j++) {106 double sum1 = distances[p[i], p[j]] * probabilities[p[i]] * probabilities[p[j]];107 for ( intk = i + 1; k < j; k++) {108 sum1 = sum1 * (1 - probabilities[ p[k]]);75 var firstSum = 0.0; 76 for (var i = 0; i < tour.Length; i++) { 77 for (var j = i + 1; j < tour.Length; j++) { 78 var sum1 = distanceMatrix[tour[i], tour[j]] * probabilities[tour[i]] * probabilities[tour[j]]; 79 for (var k = i + 1; k < j; k++) { 80 sum1 = sum1 * (1 - probabilities[tour[k]]); 109 81 } 110 A[i, j - 1] = sum1;111 82 firstSum += sum1; 112 83 } 113 84 } 114 double secondSum =0;115 for ( int j = 0; j < p.Length; j++) {116 for ( inti = 0; i < j; i++) {117 double sum2 = distances[p[j], p[i]] * probabilities[p[i]] * probabilities[p[j]];118 for ( int k = j + 1; k < p.Length; k++) {119 sum2 = sum2 * (1 - probabilities[ p[k]]);85 var secondSum = 0.0; 86 for (var j = 0; j < tour.Length; j++) { 87 for (var i = 0; i < j; i++) { 88 var sum2 = distanceMatrix[tour[j], tour[i]] * probabilities[tour[i]] * probabilities[tour[j]]; 89 for (var k = j + 1; k < tour.Length; k++) { 90 sum2 = sum2 * (1 - probabilities[tour[k]]); 120 91 } 121 for ( intk = 0; k < i; k++) {122 sum2 = sum2 * (1 - probabilities[ p[k]]);92 for (var k = 0; k < i; k++) { 93 sum2 = sum2 * (1 - probabilities[tour[k]]); 123 94 } 124 B[j,i] = sum2;125 95 secondSum += sum2; 126 96 } 127 97 } 128 foreach (var op in Operators.OfType<PTSPAnalyticalInversionMovePathEvaluator>()) {129 op.AParameter.Value = A;130 op.BParameter.Value = B;131 }132 98 return firstSum + secondSum; 133 99 } 134 135 public AnalyticalProbabilisticTravelingSalesmanProblem() {136 Operators.Add(new PTSPAnalyticalInversionMovePathEvaluator());137 }138 139 public override void Load(PTSPData data) {140 base.Load(data);141 foreach (var op in Operators.OfType<PTSPAnalyticalInversionMovePathEvaluator>()) {142 op.ProbabilitiesParameter.Value = ProbabilityMatrix;143 }144 }145 146 100 } 147 101 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Analyzers/BestPTSPSolutionAnalyzer.cs
r12799 r13412 32 32 namespace HeuristicLab.Problems.PTSP { 33 33 /// <summary> 34 /// An operator for analyzing the best solution of Traveling Salesman Problems given in path representation using city coordinates.34 /// An operator for analyzing the best solution of probabilistic traveling salesman problems given in path representation. 35 35 /// </summary> 36 36 [Item("BestPTSPSolutionAnalyzer", "An operator for analyzing the best solution of Probabilistic Traveling Salesman Problems given in path representation using city coordinates.")] … … 41 41 } 42 42 43 public LookupParameter<BoolValue> MaximizationParameter {44 get { return ( LookupParameter<BoolValue>)Parameters["Maximization"]; }43 public ILookupParameter<BoolValue> MaximizationParameter { 44 get { return (ILookupParameter<BoolValue>)Parameters["Maximization"]; } 45 45 } 46 public LookupParameter<DoubleMatrix> CoordinatesParameter {47 get { return ( LookupParameter<DoubleMatrix>)Parameters["Coordinates"]; }46 public ILookupParameter<DoubleMatrix> CoordinatesParameter { 47 get { return (ILookupParameter<DoubleMatrix>)Parameters["Coordinates"]; } 48 48 } 49 public ScopeTreeLookupParameter<Permutation> PermutationParameter {50 get { return ( ScopeTreeLookupParameter<Permutation>)Parameters["Permutation"]; }49 public IScopeTreeLookupParameter<Permutation> PermutationParameter { 50 get { return (IScopeTreeLookupParameter<Permutation>)Parameters["Permutation"]; } 51 51 } 52 public ScopeTreeLookupParameter<DoubleValue> QualityParameter {53 get { return ( ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }52 public IScopeTreeLookupParameter<DoubleValue> QualityParameter { 53 get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; } 54 54 } 55 public LookupParameter<DoubleArray> ProbabilityMatrixParameter {56 get { return ( LookupParameter<DoubleArray>)Parameters["ProbabilityMatrix"]; }55 public ILookupParameter<DoubleArray> ProbabilitiesParameter { 56 get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; } 57 57 } 58 public LookupParameter<PathPTSPTour> BestSolutionParameter {59 get { return ( LookupParameter<PathPTSPTour>)Parameters["BestSolution"]; }58 public ILookupParameter<PathPTSPTour> BestSolutionParameter { 59 get { return (ILookupParameter<PathPTSPTour>)Parameters["BestSolution"]; } 60 60 } 61 public ValueLookupParameter<ResultCollection> ResultsParameter {62 get { return ( ValueLookupParameter<ResultCollection>)Parameters["Results"]; }61 public IValueLookupParameter<ResultCollection> ResultsParameter { 62 get { return (IValueLookupParameter<ResultCollection>)Parameters["Results"]; } 63 63 } 64 public LookupParameter<DoubleValue> BestKnownQualityParameter {65 get { return ( LookupParameter<DoubleValue>)Parameters["BestKnownQuality"]; }64 public ILookupParameter<DoubleValue> BestKnownQualityParameter { 65 get { return (ILookupParameter<DoubleValue>)Parameters["BestKnownQuality"]; } 66 66 } 67 public LookupParameter<Permutation> BestKnownSolutionParameter {68 get { return ( LookupParameter<Permutation>)Parameters["BestKnownSolution"]; }67 public ILookupParameter<Permutation> BestKnownSolutionParameter { 68 get { return (ILookupParameter<Permutation>)Parameters["BestKnownSolution"]; } 69 69 } 70 70 … … 81 81 Parameters.Add(new ScopeTreeLookupParameter<Permutation>("Permutation", "The PTSP solutions given in path representation from which the best solution should be analyzed.")); 82 82 Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The qualities of the PTSP solutions which should be analyzed.")); 83 Parameters.Add(new LookupParameter<DoubleArray>("Probabilit yMatrix", "The matrix which contains the probabilities of each of the cities."));83 Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "This list describes for each city the probability of appearing in a realized instance.")); 84 84 Parameters.Add(new LookupParameter<PathPTSPTour>("BestSolution", "The best PTSP solution.")); 85 85 Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the best PTSP solution should be stored.")); 86 86 Parameters.Add(new LookupParameter<DoubleValue>("BestKnownQuality", "The quality of the best known solution of this PTSP instance.")); 87 87 Parameters.Add(new LookupParameter<Permutation>("BestKnownSolution", "The best known solution of this PTSP instance.")); 88 89 MaximizationParameter.Hidden = true;90 CoordinatesParameter.Hidden = true;91 PermutationParameter.Hidden = true;92 QualityParameter.Hidden = true;93 ProbabilityMatrixParameter.Hidden = true;94 BestSolutionParameter.Hidden = true;95 ResultsParameter.Hidden = true;96 BestKnownQualityParameter.Hidden = true;97 BestKnownSolutionParameter.Hidden = true;98 88 } 99 89 100 90 public override IOperation Apply() { 101 DoubleMatrixcoordinates = CoordinatesParameter.ActualValue;102 ItemArray<Permutation>permutations = PermutationParameter.ActualValue;103 ItemArray<DoubleValue>qualities = QualityParameter.ActualValue;104 DoubleArray probabilities = ProbabilityMatrixParameter.ActualValue;105 ResultCollectionresults = ResultsParameter.ActualValue;106 boolmax = MaximizationParameter.ActualValue.Value;107 DoubleValuebestKnownQuality = BestKnownQualityParameter.ActualValue;91 var coordinates = CoordinatesParameter.ActualValue; 92 var permutations = PermutationParameter.ActualValue; 93 var qualities = QualityParameter.ActualValue; 94 var probabilities = ProbabilitiesParameter.ActualValue; 95 var results = ResultsParameter.ActualValue; 96 var max = MaximizationParameter.ActualValue.Value; 97 var bestKnownQuality = BestKnownQualityParameter.ActualValue; 108 98 109 int i = -1; 110 if (!max) 111 i = qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index; 112 else i = qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index; 99 var i = !max ? qualities.Select((x, index) => new { index, x.Value }).OrderBy(x => x.Value).First().index 100 : qualities.Select((x, index) => new { index, x.Value }).OrderByDescending(x => x.Value).First().index; 113 101 114 102 if (bestKnownQuality == null || … … 119 107 } 120 108 121 PathPTSPTour tour = BestSolutionParameter.ActualValue;109 var tour = BestSolutionParameter.ActualValue; 122 110 if (tour == null) { 123 tour = new PathPTSPTour(coordinates, probabilities, (Permutation)permutations[i].Clone(), new DoubleValue(qualities[i].Value));111 tour = new PathPTSPTour(coordinates, probabilities, (Permutation)permutations[i].Clone(), new DoubleValue(qualities[i].Value)); 124 112 BestSolutionParameter.ActualValue = tour; 125 113 results.Add(new Result("Best PTSP Solution", tour)); -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/DistanceMatrix.cs
r12191 r13412 1 using System; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using System; 2 23 using System.Collections.Generic; 3 24 using HeuristicLab.Common; -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/EstimatedPTSP.cs
r12799 r13412 1 using System.Text; 2 using System.Threading.Tasks; 3 using HeuristicLab.Optimization; 4 using HeuristicLab.PluginInfrastructure; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using System; 23 using System.Linq; 24 using HeuristicLab.Common; 5 25 using HeuristicLab.Core; 26 using HeuristicLab.Data; 27 using HeuristicLab.Encodings.PermutationEncoding; 28 using HeuristicLab.Parameters; 6 29 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 7 30 using HeuristicLab.Problems.Instances; 8 using HeuristicLab.Encodings.PermutationEncoding;9 using HeuristicLab.Common;10 using HeuristicLab.Parameters;11 using HeuristicLab.Data;12 31 using HeuristicLab.Random; 13 using System;14 using System.Linq;15 32 16 33 namespace HeuristicLab.Problems.PTSP { 17 [Item("Estimated Probabilistic Traveling Salesman Problem ", "Represents an estimated Probabilistic Traveling Salesman Problem.")]18 [Creatable( "Problems")]34 [Item("Estimated Probabilistic Traveling Salesman Problem (PTSP)", "Represents a probabilistic traveling salesman problem where the expected tour length is estimated by averaging over the length of tours on a number of, so called, realizations.")] 35 [Creatable(CreatableAttribute.Categories.CombinatorialProblems)] 19 36 [StorableClass] 20 public sealed class EstimatedProbabilisticTravelingSalesmanProblem : ProbabilisticTravelingSalesmanProblem, IStorableContent, 21 IProblemInstanceConsumer<PTSPData> { 22 37 public sealed class EstimatedProbabilisticTravelingSalesmanProblem : ProbabilisticTravelingSalesmanProblem { 23 38 24 39 #region Parameter Properties 25 public ValueParameter<ItemList<ItemList<IntValue>>> RealizationsParameter { 26 get { return (ValueParameter<ItemList<ItemList<IntValue>>>)Parameters["Realizations"]; } 27 } 28 public ValueParameter<IntValue> RealizationsSizeParameter { 29 get { return (ValueParameter<IntValue>)Parameters["RealizationsSize"]; } 30 } 31 40 public IValueParameter<ItemList<BoolArray>> RealizationsParameter { 41 get { return (IValueParameter<ItemList<BoolArray>>)Parameters["Realizations"]; } 42 } 43 public IFixedValueParameter<IntValue> RealizationsSizeParameter { 44 get { return (IFixedValueParameter<IntValue>)Parameters["RealizationsSize"]; } 45 } 32 46 #endregion 33 47 34 48 #region Properties 35 public ItemList< ItemList<IntValue>> Realizations {49 public ItemList<BoolArray> Realizations { 36 50 get { return RealizationsParameter.Value; } 37 51 set { RealizationsParameter.Value = value; } 38 52 } 39 53 40 public IntValueRealizationsSize {41 get { return RealizationsSizeParameter.Value ; }42 set { RealizationsSizeParameter.Value = value; }54 public int RealizationsSize { 55 get { return RealizationsSizeParameter.Value.Value; } 56 set { RealizationsSizeParameter.Value.Value = value; } 43 57 } 44 58 #endregion … … 51 65 } 52 66 public EstimatedProbabilisticTravelingSalesmanProblem() { 53 Parameters.Add(new ValueParameter<IntValue>("RealizationsSize", "Size of the sample for the estimation-based evaluation")); 54 Parameters.Add(new ValueParameter<ItemList<ItemList<IntValue>>>("Realizations", "The concrete...")); 55 56 Operators.RemoveAll(x => x is ISingleObjectiveMoveEvaluator); 57 Operators.RemoveAll(x => x is IMoveGenerator); 58 Operators.RemoveAll(x => x is IMoveMaker); 67 Parameters.Add(new FixedValueParameter<IntValue>("RealizationsSize", "Size of the sample for the estimation-based evaluation", new IntValue(100))); 68 Parameters.Add(new ValueParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances.", new ItemList<BoolArray>())); 59 69 60 70 Operators.Add(new BestPTSPSolutionAnalyzer()); 61 71 62 Operators.Add(new PTSPEstimatedInversion Evaluator());63 Operators.Add(new PTSPEstimatedInsertion Evaluator());72 Operators.Add(new PTSPEstimatedInversionMoveEvaluator()); 73 Operators.Add(new PTSPEstimatedInsertionMoveEvaluator()); 64 74 Operators.Add(new PTSPExhaustiveInversionLocalImprovement()); 65 75 Operators.Add(new PTSPExhaustiveInsertionLocalImprovement()); 66 76 67 Operators.Add(new Exhaustive 25MoveGenerator());68 Operators.Add(new Stochastic 25MultiMoveGenerator());69 Operators.Add(new Stochastic 25SingleMoveGenerator());77 Operators.Add(new ExhaustiveTwoPointFiveMoveGenerator()); 78 Operators.Add(new StochasticTwoPointFiveMultiMoveGenerator()); 79 Operators.Add(new StochasticTwoPointFiveSingleMoveGenerator()); 70 80 Operators.Add(new TwoPointFiveMoveMaker()); 71 Operators.Add(new PTSP 25MoveEvaluator());81 Operators.Add(new PTSPTwoPointFiveMoveEvaluator()); 72 82 73 83 Encoding.ConfigureOperators(Operators.OfType<IOperator>()); 74 foreach (var twopointfiveMoveOperator in Operators.OfType<I 25MoveOperator>()) {84 foreach (var twopointfiveMoveOperator in Operators.OfType<ITwoPointFiveMoveOperator>()) { 75 85 twopointfiveMoveOperator.TwoPointFiveMoveParameter.ActualName = "Permutation.TwoPointFiveMove"; 76 86 } 77 RealizationsSize = new IntValue(100); 87 78 88 RegisterEventHandlers(); 79 89 } … … 83 93 } 84 94 85 public override double Evaluate(Individual individual, IRandom random) { 86 Permutation p = individual.Permutation(); 95 [StorableHook(HookType.AfterDeserialization)] 96 private void AfterDeserialization() { 97 RegisterEventHandlers(); 98 } 99 100 private void RegisterEventHandlers() { 101 RealizationsSizeParameter.Value.ValueChanged += RealizationsSizeParameter_ValueChanged; 102 } 103 104 private void RealizationsSizeParameter_ValueChanged(object sender, EventArgs e) { 105 UpdateRealizations(); 106 } 107 108 public override double Evaluate(Permutation tour, IRandom random) { 87 109 // Estimation-based evaluation 88 MersenneTwister r = new MersenneTwister(); 89 double estimatedSum = 0; 90 for (int i = 0; i < Realizations.Count; i++) { 110 var estimatedSum = 0.0; 111 for (var i = 0; i < Realizations.Count; i++) { 91 112 int singleRealization = -1, firstNode = -1; 92 for ( int j = 0; j < Realizations[i].Count; j++) {93 if (Realizations[i][ p[j]].Value == 1) {113 for (var j = 0; j < Realizations[i].Length; j++) { 114 if (Realizations[i][tour[j]]) { 94 115 if (singleRealization != -1) { 95 estimatedSum += DistanceMatrix[singleRealization, p[j]];116 estimatedSum += GetDistance(singleRealization, tour[j]); 96 117 } else { 97 firstNode = p[j];118 firstNode = tour[j]; 98 119 } 99 singleRealization = p[j];120 singleRealization = tour[j]; 100 121 } 101 122 } 102 123 if (singleRealization != -1) { 103 estimatedSum += DistanceMatrix[singleRealization, firstNode]; 104 } 105 } 106 return estimatedSum / RealizationsSize.Value; 107 } 108 109 public double[] EvaluateWithParams(DistanceMatrix distances, DoubleArray probabilities, ItemList<ItemList<IntValue>> realizations, Permutation individual ) { 124 estimatedSum += GetDistance(singleRealization, firstNode); 125 } 126 } 127 return estimatedSum / RealizationsSize; 128 } 129 130 /// <summary> 131 /// An evaluate method that can be used if mean as well as variance should be calculated 132 /// </summary> 133 /// <param name="tour">The tour between all cities.</param> 134 /// <param name="distanceMatrix">The distances between the cities.</param> 135 /// <param name="realizations">A sample of realizations of the stochastic instance</param> 136 /// <returns>A vector with length two containing mean and variance.</returns> 137 public static double[] Evaluate(Permutation tour, DistanceMatrix distanceMatrix, ItemList<BoolArray> realizations) { 110 138 // Estimation-based evaluation 111 MersenneTwister r = new MersenneTwister(); 112 double estimatedSum = 0; 113 double[] partialSums = new double[realizations.Count]; 114 for (int i = 0; i < realizations.Count; i++) { 139 var estimatedSum = 0.0; 140 var partialSums = new double[realizations.Count]; 141 for (var i = 0; i < realizations.Count; i++) { 115 142 partialSums[i] = 0; 116 143 int singleRealization = -1, firstNode = -1; 117 for ( int j = 0; j < realizations[i].Count; j++) {118 if (realizations[i][ individual[j]].Value == 1) {144 for (var j = 0; j < realizations[i].Length; j++) { 145 if (realizations[i][tour[j]]) { 119 146 if (singleRealization != -1) { 120 partialSums[i] += distance s[singleRealization, individual[j]];147 partialSums[i] += distanceMatrix[singleRealization, tour[j]]; 121 148 } else { 122 firstNode = individual[j];149 firstNode = tour[j]; 123 150 } 124 singleRealization = individual[j];151 singleRealization = tour[j]; 125 152 } 126 153 } 127 154 if (singleRealization != -1) { 128 partialSums[i] += distance s[singleRealization, firstNode];155 partialSums[i] += distanceMatrix[singleRealization, firstNode]; 129 156 } 130 157 estimatedSum += partialSums[i]; 131 158 } 132 doublemean = estimatedSum / realizations.Count;133 double variance =0;134 for ( inti = 0; i < realizations.Count; i++) {159 var mean = estimatedSum / realizations.Count; 160 var variance = 0.0; 161 for (var i = 0; i < realizations.Count; i++) { 135 162 variance += Math.Pow((partialSums[i] - mean), 2); 136 163 } 137 164 variance = variance / realizations.Count; 138 return new double[] {mean,variance}; 139 } 140 141 142 143 private void RegisterEventHandlers() { 144 //RealizationsSizeParameter.ValueChanged += new EventHandler(RealizationsSizeParameter_ValueChanged); 145 RealizationsSize.ValueChanged += new EventHandler(RealizationsSizeParameter_ValueChanged); 146 //RealizationsSizeParameter.Value.ValueChanged += new EventHandler(RealizationsSizeParameter_ValueChanged); 147 } 148 149 private void RealizationsSizeParameter_ValueChanged(object sender, EventArgs e) { 150 UpdateRealizations(); 165 return new[] { mean, variance }; 166 } 167 168 public double GetDistance(int from, int to) { 169 if (UseDistanceMatrix) return DistanceMatrix[from, to]; 170 return DistanceCalculator.Calculate(from, to, Coordinates); 151 171 } 152 172 153 173 private void UpdateRealizations() { 154 MersenneTwister r = new MersenneTwister();155 int countOnes = 0;156 Realizations = new ItemList<ItemList<IntValue>>(RealizationsSize.Value);157 for (int i = 0; i < RealizationsSize.Value; i++) {158 ItemList<IntValue> newRealization = new ItemList<IntValue>();159 while (countOnes < 4) { // only generate realizations with at least 4 cities visited174 var realizations = new ItemList<BoolArray>(RealizationsSize); 175 var rand = new MersenneTwister(); 176 for (var i = 0; i < RealizationsSize; i++) { 177 var newRealization = new BoolArray(Probabilities.Length); 178 var countOnes = 0; 179 while (countOnes < 4) { // only generate realizations with at least 4 cities visited 160 180 countOnes = 0; 161 newRealization.Clear(); 162 for (int j = 0; j < DistanceMatrix.Rows; j++) { 163 if (ProbabilityMatrix[j] > r.NextDouble()) { 164 newRealization.Add(new IntValue(1)); 165 countOnes++; 166 } else { 167 newRealization.Add(new IntValue(0)); 168 } 181 for (var j = 0; j < Probabilities.Length; j++) { 182 newRealization[j] = Probabilities[j] < rand.NextDouble(); 183 if (newRealization[j]) countOnes++; 169 184 } 170 185 } 171 countOnes = 0;172 186 Realizations.Add(newRealization); 173 187 } 188 Realizations = realizations; 174 189 } 175 190 … … 178 193 UpdateRealizations(); 179 194 180 foreach (var op in Operators.OfType<PTSPMoveEvaluator>()) { 181 op.RealizationsParameter.Value = Realizations; 182 } 183 foreach (var op in Operators.OfType<PTSPExhaustiveInversionLocalImprovement>()) { 184 op.RealizationsParameter.Value = Realizations; 185 } 186 foreach (var op in Operators.OfType<PTSP25MoveEvaluator>()) { 187 op.RealizationsParameter.Value = Realizations; 188 } 189 195 foreach (var op in Operators.OfType<IEstimatedPTSPOperator>()) { 196 op.RealizationsParameter.ActualName = RealizationsParameter.Name; 197 } 190 198 } 191 199 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/HeuristicLab.Problems.PTSP-3.3.csproj
r13202 r13412 93 93 <Private>False</Private> 94 94 </Reference> 95 <Reference Include="HeuristicLab.Problems.Instances-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">96 <SpecificVersion>False</SpecificVersion>97 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.Instances-3.3.dll</HintPath>98 <Private>False</Private>99 </Reference>100 <Reference Include="HeuristicLab.Problems.Instances.TSPLIB-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">101 <SpecificVersion>False</SpecificVersion>102 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Problems.Instances.TSPLIB-3.3.dll</HintPath>103 <Private>False</Private>104 </Reference>105 95 <Reference Include="HeuristicLab.Random-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL"> 106 96 <SpecificVersion>False</SpecificVersion> 107 97 <HintPath>..\..\..\..\trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath> 98 <Private>False</Private> 108 99 </Reference> 109 100 <Reference Include="System" /> … … 118 109 </ItemGroup> 119 110 <ItemGroup> 120 <Compile Include="PTSPData.cs" />121 <Compile Include="PTSPLIBInstanceProvider.cs" />122 111 <None Include="Properties\AssemblyInfo.cs.frame" /> 123 112 <None Include="Plugin.cs.frame" /> 124 113 <Compile Include="AnalyticalPTSP.cs" /> 125 114 <Compile Include="Analyzers\BestPTSPSolutionAnalyzer.cs" /> 115 <Compile Include="DistanceCalculators\MaximumDistance.cs" /> 116 <Compile Include="DistanceCalculators\ManhattanDistance.cs" /> 117 <Compile Include="DistanceCalculators\GeoDistance.cs" /> 118 <Compile Include="DistanceCalculators\DistanceCalculator.cs" /> 119 <Compile Include="DistanceCalculators\AttDistance.cs" /> 120 <Compile Include="DistanceCalculators\UpperEuclideanDistance.cs" /> 121 <Compile Include="DistanceCalculators\RoundedEuclideanDistance.cs" /> 122 <Compile Include="DistanceCalculators\EuclideanDistance.cs" /> 126 123 <Compile Include="DistanceMatrix.cs" /> 127 124 <Compile Include="EstimatedPTSP.cs" /> 128 125 <Compile Include="Improvers\PTSPExhaustiveInsertionLocalImprovement.cs" /> 129 126 <Compile Include="Improvers\PTSPExhaustiveInversionLocalImprovement.cs" /> 130 <Compile Include="Interfaces\I 25MoveOperator.cs" />131 <Compile Include="Interfaces\I PTSPMoveEvaluator.cs" />132 <Compile Include=" MoveEvaluators\OneShift\PTSPEstimatedInsertionEvaluator.cs" />133 <Compile Include="Move Evaluators\PTSPMoveEvaluator.cs" />134 <Compile Include="Move Evaluators\TwoOpt\PTSPAnalyticalInversionMovePathEvaluator.cs" />135 <Compile Include="Move Evaluators\TwoOpt\PTSPEstimatedInversionEvaluator.cs" />136 <Compile Include="Move Evaluators\TwoPointFiveOpt\PTSP25MoveEvaluator.cs" />137 <Compile Include="Move Generators\Exhaustive25MoveGenerator.cs" />138 <Compile Include="Move Generators\Stochastic25MultiMoveGenerator.cs" />139 <Compile Include="Move Generators\Stochastic25SingleMoveGenerator.cs" />140 <Compile Include="Move Generators\TwoPointFiveMoveGenerator.cs" />141 <Compile Include="Move Makers\TwoPointFiveMoveMaker.cs" />127 <Compile Include="Interfaces\IEstimatedPTSPOperator.cs" /> 128 <Compile Include="Interfaces\ITwoPointFiveMoveOperator.cs" /> 129 <Compile Include="Interfaces\IEstimatedPTSPMoveEvaluator.cs" /> 130 <Compile Include="Moves\OneShift\PTSPEstimatedInsertionMoveEvaluator.cs" /> 131 <Compile Include="Moves\EstimatedPTSPMoveEvaluator.cs" /> 132 <Compile Include="Moves\TwoOpt\PTSPEstimatedInversionMoveEvaluator.cs" /> 133 <Compile Include="Moves\TwoPointFiveOpt\PTSPTwoPointFiveMoveEvaluator.cs" /> 134 <Compile Include="Moves\TwoPointFiveOpt\ExhaustiveTwoPointFiveMoveGenerator.cs" /> 135 <Compile Include="Moves\TwoPointFiveOpt\StochasticTwoPointFiveMultiMoveGenerator.cs" /> 136 <Compile Include="Moves\TwoPointFiveOpt\StochasticTwoPointFiveSingleMoveGenerator.cs" /> 137 <Compile Include="Moves\TwoPointFiveOpt\TwoPointFiveMoveGenerator.cs" /> 138 <Compile Include="Moves\TwoPointFiveOpt\TwoPointFiveMoveMaker.cs" /> 142 139 <Compile Include="Moves\TwoPointFiveOpt\TwoPointFiveMove.cs" /> 143 140 <Compile Include="PathPTSPTour.cs" /> … … 149 146 <None Include="HeuristicLab.snk" /> 150 147 </ItemGroup> 151 <ItemGroup /> 148 <ItemGroup> 149 <ProjectReference Include="..\..\HeuristicLab.Problems.Instances\3.3\HeuristicLab.Problems.Instances-3.3.csproj"> 150 <Project>{3540e29e-4793-49e7-8ee2-fea7f61c3994}</Project> 151 <Name>HeuristicLab.Problems.Instances-3.3</Name> 152 <Private>False</Private> 153 </ProjectReference> 154 </ItemGroup> 152 155 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> 153 156 <PropertyGroup> -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPExhaustiveInsertionLocalImprovement.cs
r12261 r13412 21 21 22 22 using System; 23 using System.Threading; 23 24 using HeuristicLab.Common; 24 25 using HeuristicLab.Core; … … 29 30 using HeuristicLab.Parameters; 30 31 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 31 using System.Threading;32 32 33 33 namespace HeuristicLab.Problems.PTSP { … … 36 36 /// </summary> 37 37 /// <remarks> 38 /// The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.38 /// The operator tries to improve the probabilistic traveling salesman solution by inserting a city in the tour between two other cities for a certain number of times. 39 39 /// </remarks> 40 40 [Item("PTSPExhaustiveInsertionLocalImprovement", "An operator that improves probabilistic traveling salesman solutions. The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.")] 41 41 [StorableClass] 42 public sealed class PTSPExhaustiveInsertionLocalImprovement : SingleSuccessorOperator, I LocalImprovementOperator {43 42 public sealed class PTSPExhaustiveInsertionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator { 43 44 44 public ILookupParameter<IntValue> LocalIterationsParameter { 45 45 get { return (ILookupParameter<IntValue>)Parameters["LocalIterations"]; } … … 74 74 } 75 75 76 public I ValueParameter<ItemList<ItemList<IntValue>>> RealizationsParameter {77 get { return (I ValueParameter<ItemList<ItemList<IntValue>>>)Parameters["Realizations"]; }76 public ILookupParameter<ItemList<BoolArray>> RealizationsParameter { 77 get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; } 78 78 } 79 79 80 80 [StorableConstructor] 81 protected PTSPExhaustiveInsertionLocalImprovement(bool deserializing) : base(deserializing) { } 82 protected PTSPExhaustiveInsertionLocalImprovement(PTSPExhaustiveInsertionLocalImprovement original, Cloner cloner) 83 : base(original, cloner) { 84 } 81 private PTSPExhaustiveInsertionLocalImprovement(bool deserializing) : base(deserializing) { } 82 private PTSPExhaustiveInsertionLocalImprovement(PTSPExhaustiveInsertionLocalImprovement original, Cloner cloner) : base(original, cloner) { } 85 83 public PTSPExhaustiveInsertionLocalImprovement() 86 84 : base() { … … 93 91 Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized.")); 94 92 Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities.")); 95 Parameters.Add(new ValueParameter<ItemList<ItemList<IntValue>>>("Realizations", "The concrete..."));93 Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances.")); 96 94 } 97 95 … … 100 98 } 101 99 102 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList< ItemList<IntValue>> realizations) {103 DistanceMatrixdistanceM = (DistanceMatrix)distances;104 for ( inti = localIterations.Value; i < maxIterations; i++) {100 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) { 101 var distanceM = (DistanceMatrix)distances; 102 for (var i = localIterations.Value; i < maxIterations; i++) { 105 103 TranslocationMove bestMove = null; 106 104 double bestQuality = 0; // we have to make an improvement, so 0 is the baseline 107 105 double evaluations = 0.0; 108 106 foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) { 109 double moveQuality = PTSPEstimatedInsertion Evaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);107 double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations); 110 108 int min = Math.Min(move.Index1, move.Index3); 111 109 int max = Math.Max(move.Index2, move.Index3 + (move.Index2 - move.Index1)); … … 135 133 var localIterations = LocalIterationsParameter.ActualValue; 136 134 var evaluations = EvaluatedSolutionsParameter.ActualValue; 137 var realizations = RealizationsParameter. Value;135 var realizations = RealizationsParameter.ActualValue; 138 136 if (localIterations == null) { 139 137 localIterations = new IntValue(0); -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPExhaustiveInversionLocalImprovement.cs
r12380 r13412 21 21 22 22 using System; 23 using System.Threading; 23 24 using HeuristicLab.Common; 24 25 using HeuristicLab.Core; … … 29 30 using HeuristicLab.Parameters; 30 31 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 31 using System.Threading;32 32 33 33 namespace HeuristicLab.Problems.PTSP { … … 40 40 [Item("PTSPExhaustiveInversionLocalImprovement", "An operator that improves probabilistic traveling salesman solutions. The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.")] 41 41 [StorableClass] 42 public sealed class PTSPExhaustiveInversionLocalImprovement : SingleSuccessorOperator, I LocalImprovementOperator {43 42 public sealed class PTSPExhaustiveInversionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator { 43 44 44 public ILookupParameter<IntValue> LocalIterationsParameter { 45 45 get { return (ILookupParameter<IntValue>)Parameters["LocalIterations"]; } … … 74 74 } 75 75 76 public I ValueParameter<ItemList<ItemList<IntValue>>> RealizationsParameter {77 get { return (I ValueParameter<ItemList<ItemList<IntValue>>>)Parameters["Realizations"]; }76 public ILookupParameter<ItemList<BoolArray>> RealizationsParameter { 77 get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; } 78 78 } 79 79 80 80 [StorableConstructor] 81 protected PTSPExhaustiveInversionLocalImprovement(bool deserializing) : base(deserializing) { } 82 protected PTSPExhaustiveInversionLocalImprovement(PTSPExhaustiveInversionLocalImprovement original, Cloner cloner) 83 : base(original, cloner) { 84 } 81 private PTSPExhaustiveInversionLocalImprovement(bool deserializing) : base(deserializing) { } 82 private PTSPExhaustiveInversionLocalImprovement(PTSPExhaustiveInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { } 85 83 public PTSPExhaustiveInversionLocalImprovement() 86 84 : base() { … … 93 91 Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized.")); 94 92 Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities.")); 95 Parameters.Add(new ValueParameter<ItemList<ItemList<IntValue>>>("Realizations", "The concrete..."));93 Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances.")); 96 94 } 97 95 … … 100 98 } 101 99 102 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList< ItemList<IntValue>> realizations) {103 DistanceMatrixdistanceM = (DistanceMatrix)distances;104 for ( inti = localIterations.Value; i < maxIterations; i++) {100 public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) { 101 var distanceM = (DistanceMatrix)distances; 102 for (var i = localIterations.Value; i < maxIterations; i++) { 105 103 InversionMove bestMove = null; 106 104 double bestQuality = 0; // we have to make an improvement, so 0 is the baseline 107 105 double evaluations = 0.0; 108 106 foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) { 109 double moveQuality = PTSPEstimatedInversion Evaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);107 double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations); 110 108 evaluations += 2 * (move.Index2 - move.Index1 + 1) / (double)assignment.Length; 111 109 if (maximization && moveQuality > bestQuality … … 132 130 var localIterations = LocalIterationsParameter.ActualValue; 133 131 var evaluations = EvaluatedSolutionsParameter.ActualValue; 134 var realizations = RealizationsParameter. Value;132 var realizations = RealizationsParameter.ActualValue; 135 133 if (localIterations == null) { 136 134 localIterations = new IntValue(0); -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Interfaces/IEstimatedPTSPMoveEvaluator.cs
r13408 r13412 24 24 using HeuristicLab.Encodings.PermutationEncoding; 25 25 using HeuristicLab.Optimization; 26 using System;27 26 28 27 namespace HeuristicLab.Problems.PTSP { 29 public interface IPTSPMoveEvaluator : ISingleObjectiveMoveEvaluator, IMoveOperator, IPermutationMoveOperator { 30 Type EvaluatorType { get; } 28 public interface IEstimatedPTSPMoveEvaluator : IEstimatedPTSPOperator, ISingleObjectiveMoveEvaluator, IPermutationMoveOperator { 31 29 ILookupParameter<DoubleMatrix> CoordinatesParameter { get; } 32 30 ILookupParameter<DistanceMatrix> DistanceMatrixParameter { get; } 33 31 ILookupParameter<BoolValue> UseDistanceMatrixParameter { get; } 34 35 32 } 36 33 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Interfaces/IEstimatedPTSPOperator.cs
r13408 r13412 22 22 using HeuristicLab.Core; 23 23 using HeuristicLab.Data; 24 using HeuristicLab.Encodings.PermutationEncoding;25 using HeuristicLab.Optimization;26 using System;27 24 28 25 namespace HeuristicLab.Problems.PTSP { 29 public interface IPTSPMoveEvaluator : ISingleObjectiveMoveEvaluator, IMoveOperator, IPermutationMoveOperator { 30 Type EvaluatorType { get; } 31 ILookupParameter<DoubleMatrix> CoordinatesParameter { get; } 32 ILookupParameter<DistanceMatrix> DistanceMatrixParameter { get; } 33 ILookupParameter<BoolValue> UseDistanceMatrixParameter { get; } 34 26 public interface IEstimatedPTSPOperator : IItem { 27 ILookupParameter<ItemList<BoolArray>> RealizationsParameter { get; } 35 28 } 36 29 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Interfaces/ITwoPointFiveMoveOperator.cs
r13408 r13412 1 using HeuristicLab.Core; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using HeuristicLab.Core; 2 23 using HeuristicLab.Optimization; 3 using System;4 using System.Collections.Generic;5 using System.Linq;6 using System.Text;7 using System.Threading.Tasks;8 24 9 25 namespace HeuristicLab.Problems.PTSP { 10 public interface I 25MoveOperator : IMoveOperator {26 public interface ITwoPointFiveMoveOperator : IMoveOperator { 11 27 ILookupParameter<TwoPointFiveMove> TwoPointFiveMoveParameter { get; } 12 28 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/EstimatedPTSPMoveEvaluator.cs
r13408 r13412 25 25 using HeuristicLab.Data; 26 26 using HeuristicLab.Encodings.PermutationEncoding; 27 using HeuristicLab.Operators; 27 28 using HeuristicLab.Parameters; 28 29 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 29 using HeuristicLab.Operators;30 using HeuristicLab.Optimization;31 30 32 31 namespace HeuristicLab.Problems.PTSP { 33 /// <summary> 34 /// A base class for operators which evaluate TSP solutions. 35 /// </summary> 36 [Item("PTSPMoveEvaluator", "A base class for operators which evaluate TSP moves.")] 32 [Item("EstimatedPTSPMoveEvaluator", "A base class for operators which evaluate TSP moves.")] 37 33 [StorableClass] 38 public abstract class PTSPMoveEvaluator : SingleSuccessorOperator, IPTSPMoveEvaluator, IMoveOperator {34 public abstract class EstimatedPTSPMoveEvaluator : SingleSuccessorOperator, IEstimatedPTSPMoveEvaluator { 39 35 40 public abstract Type EvaluatorType { get; }41 36 public override bool CanChangeName { 42 37 get { return false; } … … 55 50 get { return (ILookupParameter<BoolValue>)Parameters["UseDistanceMatrix"]; } 56 51 } 57 public I ValueParameter<ItemList<ItemList<IntValue>>> RealizationsParameter {58 get { return (I ValueParameter<ItemList<ItemList<IntValue>>>)Parameters["Realizations"]; }52 public ILookupParameter<ItemList<BoolArray>> RealizationsParameter { 53 get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; } 59 54 } 60 61 55 public ILookupParameter<DoubleValue> QualityParameter { 62 56 get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; } … … 65 59 get { return (ILookupParameter<DoubleValue>)Parameters["MoveQuality"]; } 66 60 } 61 public ILookupParameter<DistanceCalculator> DistanceCalculatorParameter { 62 get { return (ILookupParameter<DistanceCalculator>)Parameters["DistanceCalculator"]; } 63 } 67 64 68 65 [StorableConstructor] 69 protected PTSPMoveEvaluator(bool deserializing) : base(deserializing) { }70 protected PTSPMoveEvaluator(PTSPMoveEvaluator original, Cloner cloner) : base(original, cloner) { }71 protected PTSPMoveEvaluator()66 protected EstimatedPTSPMoveEvaluator(bool deserializing) : base(deserializing) { } 67 protected EstimatedPTSPMoveEvaluator(EstimatedPTSPMoveEvaluator original, Cloner cloner) : base(original, cloner) { } 68 protected EstimatedPTSPMoveEvaluator() 72 69 : base() { 73 70 Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation.")); … … 75 72 Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities.")); 76 73 Parameters.Add(new LookupParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated (if it does not exist already) and used for evaluation, otherwise false.")); 77 Parameters.Add(new ValueParameter<ItemList<ItemList<IntValue>>>("Realizations", "The concrete..."));74 Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances.")); 78 75 Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of a TSP solution.")); 79 76 Parameters.Add(new LookupParameter<DoubleValue>("MoveQuality", "The evaluated quality of a move on a TSP solution.")); 80 } 81 82 [StorableHook(HookType.AfterDeserialization)] 83 private void AfterDeserialization() { 84 // BackwardsCompatibility3.3 85 #region Backwards compatible code (remove with 3.4) 86 LookupParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as LookupParameter<DoubleMatrix>; 87 if (oldDistanceMatrixParameter != null) { 88 Parameters.Remove(oldDistanceMatrixParameter); 89 Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities.")); 90 DistanceMatrixParameter.ActualName = oldDistanceMatrixParameter.ActualName; 91 } 92 #endregion 77 Parameters.Add(new LookupParameter<DistanceCalculator>("DistanceCalculator", "The class that can compute distances between coordinates.")); 93 78 } 94 79 95 80 public override IOperation Apply() { 96 Permutationpermutation = PermutationParameter.ActualValue;97 DoubleMatrixcoordinates = CoordinatesParameter.ActualValue;81 var permutation = PermutationParameter.ActualValue; 82 var coordinates = CoordinatesParameter.ActualValue; 98 83 double relativeQualityDifference = 0; 99 84 if (UseDistanceMatrixParameter.ActualValue.Value) { 100 DistanceMatrix distanceMatrix = DistanceMatrixParameter.ActualValue; 101 if (distanceMatrix == null) { 102 if (coordinates == null) throw new InvalidOperationException("Neither a distance matrix nor coordinates were given."); 103 distanceMatrix = CalculateDistanceMatrix(coordinates); 104 DistanceMatrixParameter.ActualValue = distanceMatrix; 105 } 85 var distanceMatrix = DistanceMatrixParameter.ActualValue; 86 if (distanceMatrix == null) throw new InvalidOperationException("The distance matrix has not been calculated."); 106 87 relativeQualityDifference = EvaluateByDistanceMatrix(permutation, distanceMatrix); 107 88 } else { 108 89 if (coordinates == null) throw new InvalidOperationException("No coordinates were given."); 109 relativeQualityDifference = EvaluateByCoordinates(permutation, coordinates); 90 var distanceCalculator = DistanceCalculatorParameter.ActualValue; 91 if (distanceCalculator == null) throw new InvalidOperationException("Distance calculator is null!"); 92 relativeQualityDifference = EvaluateByCoordinates(permutation, coordinates, distanceCalculator); 110 93 } 111 DoubleValuemoveQuality = MoveQualityParameter.ActualValue;94 var moveQuality = MoveQualityParameter.ActualValue; 112 95 if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(QualityParameter.ActualValue.Value + relativeQualityDifference); 113 96 else moveQuality.Value = QualityParameter.ActualValue.Value + relativeQualityDifference; … … 115 98 } 116 99 117 protected abstract double CalculateDistance(double x1, double y1, double x2, double y2);118 100 protected abstract double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix); 119 protected abstract double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates); 120 121 private DistanceMatrix CalculateDistanceMatrix(DoubleMatrix c) { 122 DistanceMatrix distanceMatrix = new DistanceMatrix(c.Rows, c.Rows); 123 for (int i = 0; i < distanceMatrix.Rows; i++) { 124 for (int j = 0; j < distanceMatrix.Columns; j++) 125 distanceMatrix[i, j] = CalculateDistance(c[i, 0], c[i, 1], c[j, 0], c[j, 1]); 126 } 127 return (DistanceMatrix)distanceMatrix.AsReadOnly(); 128 } 101 protected abstract double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator); 129 102 } 130 103 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/OneShift/PTSPEstimatedInsertionMoveEvaluator.cs
r13408 r13412 20 20 #endregion 21 21 22 using System; 22 23 using HeuristicLab.Common; 23 24 using HeuristicLab.Core; … … 26 27 using HeuristicLab.Parameters; 27 28 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using System;29 29 30 30 namespace HeuristicLab.Problems.PTSP { 31 [Item("PTSPEstimatedInsertion Evaluator", "Evaluates an insertion move (1-shift)")]31 [Item("PTSPEstimatedInsertionMoveEvaluator", "Evaluates an insertion move (1-shift)")] 32 32 [StorableClass] 33 public class PTSPEstimatedInsertionEvaluator : PTSPMoveEvaluator, IPermutationTranslocationMoveOperator { 34 35 public override Type EvaluatorType { 36 get { return typeof(PTSPEstimatedInsertionEvaluator); } 37 } 33 public class PTSPEstimatedInsertionMoveEvaluator : EstimatedPTSPMoveEvaluator, IPermutationTranslocationMoveOperator { 34 38 35 public ILookupParameter<TranslocationMove> TranslocationMoveParameter { 39 36 get { return (ILookupParameter<TranslocationMove>)Parameters["TranslocationMove"]; } 40 37 } 41 38 42 public IValueParameter<ItemList<ItemList<IntValue>>> RealizationsParameter {43 get { return (IValueParameter<ItemList<ItemList<IntValue>>>)Parameters["Realizations"]; }44 }45 46 39 [StorableConstructor] 47 protected PTSPEstimatedInsertion Evaluator(bool deserializing) : base(deserializing) { }48 protected PTSPEstimatedInsertion Evaluator(PTSPEstimatedInsertionEvaluator original, Cloner cloner) : base(original, cloner) { }49 public PTSPEstimatedInsertion Evaluator()40 protected PTSPEstimatedInsertionMoveEvaluator(bool deserializing) : base(deserializing) { } 41 protected PTSPEstimatedInsertionMoveEvaluator(PTSPEstimatedInsertionMoveEvaluator original, Cloner cloner) : base(original, cloner) { } 42 public PTSPEstimatedInsertionMoveEvaluator() 50 43 : base() { 51 44 Parameters.Add(new LookupParameter<TranslocationMove>("TranslocationMove", "The move to evaluate.")); … … 53 46 54 47 public override IDeepCloneable Clone(Cloner cloner) { 55 return new PTSPEstimatedInsertionEvaluator(this, cloner); 56 } 57 58 public static double EvaluateByCoordinates(Permutation permutation, TranslocationMove move, DoubleMatrix coordinates, PTSPEstimatedInsertionEvaluator evaluator) { 59 int edge1source = permutation.GetCircular(move.Index1 - 1); 60 int edge1target = permutation[move.Index1]; 61 int edge2source = permutation[move.Index2]; 62 int edge2target = permutation.GetCircular(move.Index2 + 1); 63 if (move.Index2 - move.Index1 >= permutation.Length - 2) return 0; 64 double moveQuality = 0; 65 // remove two edges 66 moveQuality -= evaluator.CalculateDistance(coordinates[edge1source, 0], coordinates[edge1source, 1], 67 coordinates[edge1target, 0], coordinates[edge1target, 1]); 68 moveQuality -= evaluator.CalculateDistance(coordinates[edge2source, 0], coordinates[edge2source, 1], 69 coordinates[edge2target, 0], coordinates[edge2target, 1]); 70 // add two edges 71 moveQuality += evaluator.CalculateDistance(coordinates[edge1source, 0], coordinates[edge1source, 1], 72 coordinates[edge2source, 0], coordinates[edge2source, 1]); 73 moveQuality += evaluator.CalculateDistance(coordinates[edge1target, 0], coordinates[edge1target, 1], 74 coordinates[edge2target, 0], coordinates[edge2target, 1]); 75 return moveQuality; 76 } 77 78 public static double EvaluateByDistanceMatrix(Permutation permutation, TranslocationMove move, DistanceMatrix distanceMatrix, ItemList<ItemList<IntValue>> realizations) { 79 Permutation afterMove = new Permutation(PermutationTypes.RelativeUndirected,permutation); 48 return new PTSPEstimatedInsertionMoveEvaluator(this, cloner); 49 } 50 51 public static double EvaluateByCoordinates(Permutation permutation, TranslocationMove move, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, ItemList<BoolArray> realizations) { 52 var afterMove = new Permutation(PermutationTypes.RelativeUndirected, permutation); 80 53 TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3); 81 54 double moveQuality = 0; 82 int[]edges = new int[12];83 int[]indices = new int[12];55 var edges = new int[12]; 56 var indices = new int[12]; 84 57 edges[0] = permutation.GetCircular(move.Index1 - 1); 85 indices[0] = decreaseCircularIndex(permutation.Length, move.Index1);58 indices[0] = DecreaseCircularIndex(permutation.Length, move.Index1); 86 59 edges[1] = permutation[move.Index1]; 87 60 indices[1] = move.Index1; … … 89 62 indices[2] = move.Index1; 90 63 edges[3] = permutation.GetCircular(move.Index1 + 1); 91 indices[3] = increaseCircularIndex(permutation.Length, move.Index1);64 indices[3] = IncreaseCircularIndex(permutation.Length, move.Index1); 92 65 93 66 edges[6] = afterMove.GetCircular(move.Index3 - 1); 94 indices[6] = decreaseCircularIndex(afterMove.Length, move.Index3);67 indices[6] = DecreaseCircularIndex(afterMove.Length, move.Index3); 95 68 edges[7] = afterMove[move.Index3]; 96 69 indices[7] = move.Index3; … … 98 71 indices[8] = move.Index3; 99 72 edges[9] = afterMove.GetCircular(move.Index3 + 1); 100 indices[9] = increaseCircularIndex(afterMove.Length, move.Index3);73 indices[9] = IncreaseCircularIndex(afterMove.Length, move.Index3); 101 74 102 75 if (move.Index3 > move.Index1) { … … 120 93 } 121 94 int[] aPosteriori = new int[12]; 122 Permutation tempPermutation; 123 foreach (ItemList<IntValue> realization in realizations) { 95 foreach (var realization in realizations) { 124 96 for (int i = 0; i < edges.Length; i++) { 97 Permutation tempPermutation; 125 98 if (i < 6) { 126 99 tempPermutation = permutation; … … 128 101 tempPermutation = afterMove; 129 102 } 130 if (realization[edges[i]] .Value == 1) {103 if (realization[edges[i]]) { 131 104 aPosteriori[i] = edges[i]; 132 105 } else { 133 int j =1;134 if (i %2==0) {106 int j = 1; 107 if (i % 2 == 0) { 135 108 // find nearest predecessor in realization if source edge 136 while ( realization[tempPermutation.GetCircular(indices[i] - j)].Value == 0) {109 while (!realization[tempPermutation.GetCircular(indices[i] - j)]) { 137 110 j++; 138 111 } … … 140 113 } else { 141 114 // find nearest successor in realization if target edge 142 while (realization[tempPermutation.GetCircular(indices[i] + j)].Value == 0) { 115 while (!realization[tempPermutation.GetCircular(indices[i] + j)]) { 116 j++; 117 } 118 aPosteriori[i] = tempPermutation.GetCircular(indices[i] + j); 119 } 120 } 121 } 122 if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3]) && 123 !(aPosteriori[0] == aPosteriori[4] && aPosteriori[1] == aPosteriori[5]) && 124 !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5])) { 125 // compute cost difference between the two a posteriori solutions 126 127 moveQuality += distanceCalculator.Calculate(aPosteriori[6], aPosteriori[7], coordinates) 128 + distanceCalculator.Calculate(aPosteriori[8], aPosteriori[9], coordinates) 129 + distanceCalculator.Calculate(aPosteriori[10], aPosteriori[11], coordinates) 130 - distanceCalculator.Calculate(aPosteriori[0], aPosteriori[1], coordinates) 131 - distanceCalculator.Calculate(aPosteriori[2], aPosteriori[3], coordinates) 132 - distanceCalculator.Calculate(aPosteriori[4], aPosteriori[5], coordinates); 133 } 134 Array.Clear(aPosteriori, 0, aPosteriori.Length); 135 } 136 // return average of cost differences 137 return moveQuality / realizations.Count; 138 } 139 140 public static double EvaluateByDistanceMatrix(Permutation permutation, TranslocationMove move, DistanceMatrix distanceMatrix, ItemList<BoolArray> realizations) { 141 var afterMove = new Permutation(PermutationTypes.RelativeUndirected, permutation); 142 TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3); 143 double moveQuality = 0; 144 var edges = new int[12]; 145 var indices = new int[12]; 146 edges[0] = permutation.GetCircular(move.Index1 - 1); 147 indices[0] = DecreaseCircularIndex(permutation.Length, move.Index1); 148 edges[1] = permutation[move.Index1]; 149 indices[1] = move.Index1; 150 edges[2] = permutation[move.Index1]; 151 indices[2] = move.Index1; 152 edges[3] = permutation.GetCircular(move.Index1 + 1); 153 indices[3] = IncreaseCircularIndex(permutation.Length, move.Index1); 154 155 edges[6] = afterMove.GetCircular(move.Index3 - 1); 156 indices[6] = DecreaseCircularIndex(afterMove.Length, move.Index3); 157 edges[7] = afterMove[move.Index3]; 158 indices[7] = move.Index3; 159 edges[8] = afterMove[move.Index3]; 160 indices[8] = move.Index3; 161 edges[9] = afterMove.GetCircular(move.Index3 + 1); 162 indices[9] = IncreaseCircularIndex(afterMove.Length, move.Index3); 163 164 if (move.Index3 > move.Index1) { 165 edges[4] = permutation[move.Index3]; 166 indices[4] = move.Index3; 167 edges[5] = permutation.GetCircular(move.Index3 + 1); 168 indices[5] = indices[9]; 169 edges[10] = afterMove.GetCircular(move.Index1 - 1); 170 indices[10] = indices[0]; 171 edges[11] = afterMove[move.Index1]; 172 indices[11] = move.Index1; 173 } else { 174 edges[4] = permutation.GetCircular(move.Index3 - 1); 175 indices[4] = indices[6]; 176 edges[5] = permutation[move.Index3]; 177 indices[5] = move.Index3; 178 edges[10] = afterMove[move.Index1]; 179 indices[10] = move.Index1; 180 edges[11] = afterMove.GetCircular(move.Index1 + 1); 181 indices[11] = indices[3]; 182 } 183 int[] aPosteriori = new int[12]; 184 foreach (var realization in realizations) { 185 for (int i = 0; i < edges.Length; i++) { 186 Permutation tempPermutation; 187 if (i < 6) { 188 tempPermutation = permutation; 189 } else { 190 tempPermutation = afterMove; 191 } 192 if (realization[edges[i]]) { 193 aPosteriori[i] = edges[i]; 194 } else { 195 int j = 1; 196 if (i % 2 == 0) { 197 // find nearest predecessor in realization if source edge 198 while (!realization[tempPermutation.GetCircular(indices[i] - j)]) { 199 j++; 200 } 201 aPosteriori[i] = tempPermutation.GetCircular(indices[i] - j); 202 } else { 203 // find nearest successor in realization if target edge 204 while (!realization[tempPermutation.GetCircular(indices[i] + j)]) { 143 205 j++; 144 206 } … … 160 222 } 161 223 162 private static int decreaseCircularIndex(int length, int index) {163 intresult = index - 1;224 private static int DecreaseCircularIndex(int length, int index) { 225 var result = index - 1; 164 226 if (result == -1) { 165 227 result = length - 1; … … 168 230 } 169 231 170 private static int increaseCircularIndex(int length, int index) {171 intresult = index + 1;232 private static int IncreaseCircularIndex(int length, int index) { 233 var result = index + 1; 172 234 if (result == length + 1) { 173 235 result = 0; … … 176 238 } 177 239 178 protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates ) {179 return EvaluateByCoordinates(permutation, TranslocationMoveParameter.ActualValue, coordinates, this);240 protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) { 241 return EvaluateByCoordinates(permutation, TranslocationMoveParameter.ActualValue, coordinates, distanceCalculator, RealizationsParameter.ActualValue); 180 242 } 181 243 182 244 protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) { 183 return EvaluateByDistanceMatrix(permutation, TranslocationMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.Value); 184 } 185 186 protected override double CalculateDistance(double x1, double y1, double x2, double y2) { 187 return Math.Round(Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))); 245 return EvaluateByDistanceMatrix(permutation, TranslocationMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.ActualValue); 188 246 } 189 247 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoOpt/PTSPEstimatedInversionMoveEvaluator.cs
r13408 r13412 20 20 #endregion 21 21 22 using System; 22 23 using HeuristicLab.Common; 23 24 using HeuristicLab.Core; … … 26 27 using HeuristicLab.Parameters; 27 28 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using System;29 29 30 30 namespace HeuristicLab.Problems.PTSP { 31 /// <summary> 32 /// An operator to evaluate inversion moves (2-opt). 33 /// </summary> 34 [Item("PTSPInversionMovePathEvaluator", "Evaluates an inversion move (2-opt) by summing up the length of all added edges and subtracting the length of all deleted edges.")] 31 [Item("PTSPEstimatedInversionMoveEvaluator", "Evaluates an inversion move (2-opt) over several realizations of tours by summing up the length of all added edges and subtracting the length of all deleted edges.")] 35 32 [StorableClass] 36 public class PTSPEstimatedInversionEvaluator : PTSPMoveEvaluator, IPermutationInversionMoveOperator { 37 public override Type EvaluatorType { 38 get { return typeof(PTSPEstimatedInversionEvaluator); } 39 } 33 public class PTSPEstimatedInversionMoveEvaluator : EstimatedPTSPMoveEvaluator, IPermutationInversionMoveOperator { 34 40 35 public ILookupParameter<InversionMove> InversionMoveParameter { 41 36 get { return (ILookupParameter<InversionMove>)Parameters["InversionMove"]; } 42 37 } 43 38 44 45 46 39 [StorableConstructor] 47 protected PTSPEstimatedInversion Evaluator(bool deserializing) : base(deserializing) { }48 protected PTSPEstimatedInversion Evaluator(PTSPEstimatedInversionEvaluator original, Cloner cloner) : base(original, cloner) { }49 public PTSPEstimatedInversion Evaluator()40 protected PTSPEstimatedInversionMoveEvaluator(bool deserializing) : base(deserializing) { } 41 protected PTSPEstimatedInversionMoveEvaluator(PTSPEstimatedInversionMoveEvaluator original, Cloner cloner) : base(original, cloner) { } 42 public PTSPEstimatedInversionMoveEvaluator() 50 43 : base() { 51 44 Parameters.Add(new LookupParameter<InversionMove>("InversionMove", "The move to evaluate.")); … … 53 46 54 47 public override IDeepCloneable Clone(Cloner cloner) { 55 return new PTSPEstimatedInversion Evaluator(this, cloner);48 return new PTSPEstimatedInversionMoveEvaluator(this, cloner); 56 49 } 57 50 58 public static double EvaluateByCoordinates(Permutation permutation, InversionMove move, DoubleMatrix coordinates, PTSPEstimatedInversionEvaluator evaluator) { 59 int edge1source = permutation.GetCircular(move.Index1 - 1); 60 int edge1target = permutation[move.Index1]; 61 int edge2source = permutation[move.Index2]; 62 int edge2target = permutation.GetCircular(move.Index2 + 1); 63 if (move.Index2 - move.Index1 >= permutation.Length - 2) return 0; 51 public static double EvaluateByCoordinates(Permutation permutation, InversionMove move, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, ItemList<BoolArray> realizations) { 64 52 double moveQuality = 0; 65 // remove two edges 66 moveQuality -= evaluator.CalculateDistance(coordinates[edge1source, 0], coordinates[edge1source, 1], 67 coordinates[edge1target, 0], coordinates[edge1target, 1]); 68 moveQuality -= evaluator.CalculateDistance(coordinates[edge2source, 0], coordinates[edge2source, 1], 69 coordinates[edge2target, 0], coordinates[edge2target, 1]); 70 // add two edges 71 moveQuality += evaluator.CalculateDistance(coordinates[edge1source, 0], coordinates[edge1source, 1], 72 coordinates[edge2source, 0], coordinates[edge2source, 1]); 73 moveQuality += evaluator.CalculateDistance(coordinates[edge1target, 0], coordinates[edge1target, 1], 74 coordinates[edge2target, 0], coordinates[edge2target, 1]); 75 return moveQuality; 76 } 77 78 public static double EvaluateByDistanceMatrix(Permutation permutation, InversionMove move, DistanceMatrix distanceMatrix, ItemList<ItemList<IntValue>> realizations) { 79 double moveQuality = 0; 80 int[] edges = new int[4]; 81 int[] indices = new int[4]; 53 var edges = new int[4]; 54 var indices = new int[4]; 82 55 edges[0] = permutation.GetCircular(move.Index1 - 1); 83 indices[0] = move.Index1 -1;56 indices[0] = move.Index1 - 1; 84 57 if (indices[0] == -1) indices[0] = permutation.Length - 1; 85 58 edges[1] = permutation[move.Index1]; … … 88 61 indices[2] = move.Index2; 89 62 edges[3] = permutation.GetCircular(move.Index2 + 1); 90 indices[3] = move.Index2 +1;63 indices[3] = move.Index2 + 1; 91 64 if (indices[3] == permutation.Length + 1) indices[3] = 0; 92 int[]aPosteriori = new int[4];93 foreach ( ItemList<IntValue>realization in realizations) {94 for ( inti = 0; i < edges.Length; i++) {95 if (realization[edges[i]] .Value == 1) {65 var aPosteriori = new int[4]; 66 foreach (var realization in realizations) { 67 for (var i = 0; i < edges.Length; i++) { 68 if (realization[edges[i]]) { 96 69 aPosteriori[i] = edges[i]; 97 70 } else { 98 int j=1;99 if (i %2==0) {71 var j = 1; 72 if (i % 2 == 0) { 100 73 // find nearest predecessor in realization if source edge 101 while (realization[permutation.GetCircular(indices[i]-j)].Value==0) {74 while (!realization[permutation.GetCircular(indices[i] - j)]) { 102 75 j++; 103 76 } … … 105 78 } else { 106 79 // find nearest successor in realization if target edge 107 while(realization[permutation.GetCircular(indices[i]+j)].Value==0) { 80 while (!realization[permutation.GetCircular(indices[i] + j)]) { 81 j++; 82 } 83 aPosteriori[i] = permutation.GetCircular(indices[i] + j); 84 } 85 } 86 } 87 // compute cost difference between the two a posteriori solutions 88 if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3])) { 89 moveQuality = moveQuality 90 + distanceCalculator.Calculate(0, 2, coordinates) 91 + distanceCalculator.Calculate(1, 3, coordinates) 92 - distanceCalculator.Calculate(0, 1, coordinates) 93 - distanceCalculator.Calculate(2, 3, coordinates); 94 } 95 Array.Clear(aPosteriori, 0, aPosteriori.Length); 96 } 97 // return average of cost differences 98 return moveQuality / realizations.Count; 99 } 100 101 public static double EvaluateByDistanceMatrix(Permutation permutation, InversionMove move, DistanceMatrix distanceMatrix, ItemList<BoolArray> realizations) { 102 double moveQuality = 0; 103 var edges = new int[4]; 104 var indices = new int[4]; 105 edges[0] = permutation.GetCircular(move.Index1 - 1); 106 indices[0] = move.Index1 - 1; 107 if (indices[0] == -1) indices[0] = permutation.Length - 1; 108 edges[1] = permutation[move.Index1]; 109 indices[1] = move.Index1; 110 edges[2] = permutation[move.Index2]; 111 indices[2] = move.Index2; 112 edges[3] = permutation.GetCircular(move.Index2 + 1); 113 indices[3] = move.Index2 + 1; 114 if (indices[3] == permutation.Length + 1) indices[3] = 0; 115 var aPosteriori = new int[4]; 116 foreach (var realization in realizations) { 117 for (var i = 0; i < edges.Length; i++) { 118 if (realization[edges[i]]) { 119 aPosteriori[i] = edges[i]; 120 } else { 121 var j = 1; 122 if (i % 2 == 0) { 123 // find nearest predecessor in realization if source edge 124 while (!realization[permutation.GetCircular(indices[i] - j)]) { 125 j++; 126 } 127 aPosteriori[i] = permutation.GetCircular(indices[i] - j); 128 } else { 129 // find nearest successor in realization if target edge 130 while (!realization[permutation.GetCircular(indices[i] + j)]) { 108 131 j++; 109 132 } … … 122 145 } 123 146 124 protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates ) {125 return EvaluateByCoordinates(permutation, InversionMoveParameter.ActualValue, coordinates, this);147 protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) { 148 return EvaluateByCoordinates(permutation, InversionMoveParameter.ActualValue, coordinates, distanceCalculator, RealizationsParameter.ActualValue); 126 149 } 127 150 128 151 protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) { 129 return EvaluateByDistanceMatrix(permutation, InversionMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.Value); 130 } 131 132 protected override double CalculateDistance(double x1, double y1, double x2, double y2) { 133 return Math.Round(Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))); 152 return EvaluateByDistanceMatrix(permutation, InversionMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.ActualValue); 134 153 } 135 154 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/ExhaustiveTwoPointFiveMoveGenerator.cs
r13408 r13412 1 using System; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using System; 2 23 using System.Collections.Generic; 3 24 using System.Linq; 4 25 using HeuristicLab.Common; 5 26 using HeuristicLab.Core; 27 using HeuristicLab.Encodings.PermutationEncoding; 6 28 using HeuristicLab.Optimization; 7 29 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 8 using HeuristicLab.Encodings.PermutationEncoding;9 using HeuristicLab.Parameters;10 using HeuristicLab.Operators;11 30 12 31 namespace HeuristicLab.Problems.PTSP { 13 [Item("Exhaustive 25MoveGenerator", "Generates all possible inversion and shift moves (2.5-opt) from a given permutation.")]32 [Item("Exhaustive 2.5-MoveGenerator", "Generates all possible inversion and shift moves (2.5-opt) from a given permutation.")] 14 33 [StorableClass] 15 class Exhaustive25MoveGenerator : TwoPointFiveMoveGenerator, IExhaustiveMoveGenerator { 16 public override bool CanChangeName { 17 get { return false; } 34 public sealed class ExhaustiveTwoPointFiveMoveGenerator : TwoPointFiveMoveGenerator, IExhaustiveMoveGenerator { 35 36 [StorableConstructor] 37 private ExhaustiveTwoPointFiveMoveGenerator(bool deserializing) : base(deserializing) { } 38 private ExhaustiveTwoPointFiveMoveGenerator(ExhaustiveTwoPointFiveMoveGenerator original, Cloner cloner) : base(original, cloner) { } 39 public ExhaustiveTwoPointFiveMoveGenerator() : base() { } 40 41 public override IDeepCloneable Clone(Cloner cloner) { 42 return new ExhaustiveTwoPointFiveMoveGenerator(this, cloner); 18 43 } 19 44 20 [StorableConstructor]21 protected Exhaustive25MoveGenerator(bool deserializing) : base(deserializing) { }22 protected Exhaustive25MoveGenerator(Exhaustive25MoveGenerator original, Cloner cloner) : base(original, cloner) { }23 public Exhaustive25MoveGenerator()24 : base() {25 }26 27 public override IDeepCloneable Clone(Cloner cloner) {28 return new Exhaustive25MoveGenerator(this, cloner);29 }30 31 45 public static TwoPointFiveMove[] Apply(Permutation permutation) { 32 46 return Generate(permutation).ToArray(); … … 35 49 public static IEnumerable<TwoPointFiveMove> Generate(Permutation permutation) { 36 50 int length = permutation.Length; 37 if (length == 1) throw new ArgumentException("Exhaustive 25MoveGenerator: There cannot be a 2.5 move given a permutation of length 1.", "permutation");51 if (length == 1) throw new ArgumentException("Exhaustive 2.5-MoveGenerator: There cannot be a 2.5 move given a permutation of length 1.", "permutation"); 38 52 int totalMoves = (length) * (length - 1) / 2; 39 53 … … 44 58 // doesn't make sense to inverse the whole permutation or the whole but one in case of relative undirected permutations 45 59 if (j - i >= length - 2) continue; 46 yield return new TwoPointFiveMove(i, j, true);60 yield return new TwoPointFiveMove(i, j, true); 47 61 yield return new TwoPointFiveMove(i, j, false); 48 62 } 49 63 } 50 64 } else { // when length is 3 or less, there's actually no difference, but for the sake of not crashing the algorithm create a dummy move 51 yield return new TwoPointFiveMove(0, 1, true);65 yield return new TwoPointFiveMove(0, 1, true); 52 66 } 53 67 } else { 54 68 for (int i = 0; i < length - 1; i++) 55 69 for (int j = i + 1; j < length; j++) { 56 yield return new TwoPointFiveMove(i, j, true);70 yield return new TwoPointFiveMove(i, j, true); 57 71 yield return new TwoPointFiveMove(i, j, false); 58 72 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/PTSPTwoPointFiveMoveEvaluator.cs
r13408 r13412 20 20 #endregion 21 21 22 using System;23 22 using HeuristicLab.Common; 24 23 using HeuristicLab.Core; … … 27 26 using HeuristicLab.Parameters; 28 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 29 using HeuristicLab.Optimization;30 using HeuristicLab.Operators;31 28 32 29 namespace HeuristicLab.Problems.PTSP { 33 /// <summary> 34 /// A base class for operators which evaluate TSP solutions. 35 /// </summary> 36 [Item("PTSP25MoveEvaluator", "Operator that evaluates 2.5-p-opt moves of PTSP")] 30 [Item("PTSP 2.5-MoveEvaluator", "Operator that evaluates 2.5-p-opt moves of PTSP")] 37 31 [StorableClass] 38 public class PTSP25MoveEvaluator : SingleSuccessorOperator, I25MoveOperator, ISingleObjectiveMoveEvaluator { 39 public ILookupParameter<Permutation> PermutationParameter { 40 get { return (ILookupParameter<Permutation>)Parameters["Permutation"]; } 41 } 42 public ILookupParameter<DoubleMatrix> CoordinatesParameter { 43 get { return (ILookupParameter<DoubleMatrix>)Parameters["Coordinates"]; } 44 } 45 public ILookupParameter<DistanceMatrix> DistanceMatrixParameter { 46 get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; } 47 } 48 public ILookupParameter<BoolValue> UseDistanceMatrixParameter { 49 get { return (ILookupParameter<BoolValue>)Parameters["UseDistanceMatrix"]; } 50 } 51 public IValueParameter<ItemList<ItemList<IntValue>>> RealizationsParameter { 52 get { return (IValueParameter<ItemList<ItemList<IntValue>>>)Parameters["Realizations"]; } 53 } 32 public class PTSPTwoPointFiveMoveEvaluator : EstimatedPTSPMoveEvaluator, ITwoPointFiveMoveOperator { 33 54 34 public ILookupParameter<TwoPointFiveMove> TwoPointFiveMoveParameter { 55 35 get { return (ILookupParameter<TwoPointFiveMove>)Parameters["TwoPointFiveMove"]; } 56 36 } 57 public ILookupParameter<DoubleValue> QualityParameter {58 get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; }59 }60 public ILookupParameter<DoubleValue> MoveQualityParameter {61 get { return (ILookupParameter<DoubleValue>)Parameters["MoveQuality"]; }62 }63 37 64 38 [StorableConstructor] 65 protected PTSP 25MoveEvaluator(bool deserializing) : base(deserializing) { }66 protected PTSP 25MoveEvaluator(PTSP25MoveEvaluator original, Cloner cloner) : base(original, cloner) { }67 public PTSP 25MoveEvaluator()39 protected PTSPTwoPointFiveMoveEvaluator(bool deserializing) : base(deserializing) { } 40 protected PTSPTwoPointFiveMoveEvaluator(PTSPTwoPointFiveMoveEvaluator original, Cloner cloner) : base(original, cloner) { } 41 public PTSPTwoPointFiveMoveEvaluator() 68 42 : base() { 69 Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));70 Parameters.Add(new LookupParameter<DoubleMatrix>("Coordinates", "The city's coordinates."));71 Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));72 Parameters.Add(new LookupParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated (if it does not exist already) and used for evaluation, otherwise false."));73 Parameters.Add(new ValueParameter<ItemList<ItemList<IntValue>>>("Realizations", "The concrete..."));74 43 Parameters.Add(new LookupParameter<TwoPointFiveMove>("TwoPointFiveMove", "The move to evaluate.")); 75 Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of a TSP solution."));76 Parameters.Add(new LookupParameter<DoubleValue>("MoveQuality", "The evaluated quality of a move on a TSP solution."));77 44 } 78 45 79 46 public override IDeepCloneable Clone(Cloner cloner) { 80 return new PTSP 25MoveEvaluator(this, cloner);47 return new PTSPTwoPointFiveMoveEvaluator(this, cloner); 81 48 } 82 49 83 [StorableHook(HookType.AfterDeserialization)] 84 private void AfterDeserialization() { 85 // BackwardsCompatibility3.3 86 #region Backwards compatible code (remove with 3.4) 87 LookupParameter<DoubleMatrix> oldDistanceMatrixParameter = Parameters["DistanceMatrix"] as LookupParameter<DoubleMatrix>; 88 if (oldDistanceMatrixParameter != null) { 89 Parameters.Remove(oldDistanceMatrixParameter); 90 Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities.")); 91 DistanceMatrixParameter.ActualName = oldDistanceMatrixParameter.ActualName; 92 } 93 #endregion 50 protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) { 51 var move = TwoPointFiveMoveParameter.ActualValue; 52 var realizations = RealizationsParameter.ActualValue; 53 return EvaluateByCoordinates(permutation, coordinates, distanceCalculator, move, realizations); 94 54 } 95 55 96 public override IOperation Apply() { 97 Permutation permutation = PermutationParameter.ActualValue; 98 DoubleMatrix coordinates = CoordinatesParameter.ActualValue; 99 double relativeQualityDifference = 0; 100 if (UseDistanceMatrixParameter.ActualValue.Value) { 101 DistanceMatrix distanceMatrix = DistanceMatrixParameter.ActualValue; 102 if (distanceMatrix == null) { 103 if (coordinates == null) throw new InvalidOperationException("Neither a distance matrix nor coordinates were given."); 104 distanceMatrix = CalculateDistanceMatrix(coordinates); 105 DistanceMatrixParameter.ActualValue = distanceMatrix; 106 } 107 relativeQualityDifference = EvaluateByDistanceMatrix(permutation, distanceMatrix); 108 } 109 DoubleValue moveQuality = MoveQualityParameter.ActualValue; 110 if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(QualityParameter.ActualValue.Value + relativeQualityDifference); 111 else moveQuality.Value = QualityParameter.ActualValue.Value + relativeQualityDifference; 112 return base.Apply(); 56 public static double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, TwoPointFiveMove move, ItemList<BoolArray> realizations) { 57 if (move.IsInvert) { 58 return PTSPEstimatedInversionMoveEvaluator.EvaluateByCoordinates(permutation, 59 new InversionMove(move.Index1, move.Index2, move.Permutation), 60 coordinates, distanceCalculator, realizations); 61 } else { 62 return PTSPEstimatedInsertionMoveEvaluator.EvaluateByCoordinates(permutation, 63 new TranslocationMove(move.Index1, move.Index1, move.Index2), 64 coordinates, distanceCalculator, realizations); 65 } 113 66 } 114 67 115 protected double CalculateDistance(double x1, double y1, double x2, double y2) { 116 return Math.Round(Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))); 68 protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) { 69 var move = TwoPointFiveMoveParameter.ActualValue; 70 var realizations = RealizationsParameter.ActualValue; 71 return EvaluateByDistanceMatrix(permutation, distanceMatrix, move, realizations); 117 72 } 118 73 119 private static int decreaseCircularIndex(int length, int index) { 120 int result = index - 1; 121 if (result == -1) { 122 result = length - 1; 74 public static double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix, TwoPointFiveMove move, ItemList<BoolArray> realizations) { 75 if (move.IsInvert) { 76 return PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(permutation, 77 new InversionMove(move.Index1, move.Index2, move.Permutation), 78 distanceMatrix, realizations); 79 } else { 80 return PTSPEstimatedInsertionMoveEvaluator.EvaluateByDistanceMatrix(permutation, 81 new TranslocationMove(move.Index1, move.Index1, move.Index2), 82 distanceMatrix, realizations); 123 83 } 124 return result;125 }126 127 private static int increaseCircularIndex(int length, int index) {128 int result = index + 1;129 if (result == length + 1) {130 result = 0;131 }132 return result;133 }134 135 136 public static double EvaluateInversionByDistanceMatrix(Permutation permutation, TwoPointFiveMove move, DistanceMatrix distanceMatrix, ItemList<ItemList<IntValue>> realizations) {137 double moveQuality = 0;138 int[] edges = new int[4];139 int[] indices = new int[4];140 edges[0] = permutation.GetCircular(move.Index1 - 1);141 indices[0] = decreaseCircularIndex(permutation.Length, move.Index1);142 edges[1] = permutation[move.Index1];143 indices[1] = move.Index1;144 edges[2] = permutation[move.Index2];145 indices[2] = move.Index2;146 edges[3] = permutation.GetCircular(move.Index2 + 1);147 indices[3] = increaseCircularIndex(permutation.Length, move.Index2);148 int[] aPosteriori = new int[4];149 foreach (ItemList<IntValue> realization in realizations) {150 for (int i = 0; i < edges.Length; i++) {151 if (realization[edges[i]].Value == 1) {152 aPosteriori[i] = edges[i];153 } else {154 int j = 1;155 if (i % 2 == 0) {156 // find nearest predecessor in realization if source edge157 while (realization[permutation.GetCircular(indices[i] - j)].Value == 0) {158 j++;159 }160 aPosteriori[i] = permutation.GetCircular(indices[i] - j);161 } else {162 // find nearest successor in realization if target edge163 while (realization[permutation.GetCircular(indices[i] + j)].Value == 0) {164 j++;165 }166 aPosteriori[i] = permutation.GetCircular(indices[i] + j);167 }168 }169 }170 // compute cost difference between the two a posteriori solutions171 if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3])) {172 moveQuality = moveQuality + distanceMatrix[aPosteriori[0], aPosteriori[2]] + distanceMatrix[aPosteriori[1], aPosteriori[3]] - distanceMatrix[aPosteriori[0], aPosteriori[1]] - distanceMatrix[aPosteriori[2], aPosteriori[3]];173 }174 Array.Clear(aPosteriori, 0, aPosteriori.Length);175 }176 // return average of cost differences177 return moveQuality / realizations.Count;178 }179 public static double EvaluateInsertionByDistanceMatrix(Permutation permutation, TwoPointFiveMove move, DistanceMatrix distanceMatrix, ItemList<ItemList<IntValue>> realizations) {180 Permutation afterMove = new Permutation(PermutationTypes.RelativeUndirected, permutation);181 TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index2);182 double moveQuality = 0;183 int[] edges = new int[12];184 int[] indices = new int[12];185 edges[0] = permutation.GetCircular(move.Index1 - 1);186 indices[0] = decreaseCircularIndex(permutation.Length, move.Index1);187 edges[1] = permutation[move.Index1];188 indices[1] = move.Index1;189 edges[2] = permutation[move.Index1];190 indices[2] = move.Index1;191 edges[3] = permutation.GetCircular(move.Index1 + 1);192 indices[3] = increaseCircularIndex(permutation.Length, move.Index1);193 194 edges[6] = afterMove.GetCircular(move.Index2 - 1);195 indices[6] = decreaseCircularIndex(afterMove.Length, move.Index2);196 edges[7] = afterMove[move.Index2];197 indices[7] = move.Index2;198 edges[8] = afterMove[move.Index2];199 indices[8] = move.Index2;200 edges[9] = afterMove.GetCircular(move.Index2 + 1);201 indices[9] = increaseCircularIndex(afterMove.Length, move.Index2);202 203 if (move.Index2 > move.Index1) {204 edges[4] = permutation[move.Index2];205 indices[4] = move.Index2;206 edges[5] = permutation.GetCircular(move.Index2 + 1);207 indices[5] = indices[9];208 edges[10] = afterMove.GetCircular(move.Index1 - 1);209 indices[10] = indices[0];210 edges[11] = afterMove[move.Index1];211 indices[11] = move.Index1;212 } else {213 edges[4] = permutation.GetCircular(move.Index2 - 1);214 indices[4] = indices[6];215 edges[5] = permutation[move.Index2];216 indices[5] = move.Index2;217 edges[10] = afterMove[move.Index1];218 indices[10] = move.Index1;219 edges[11] = afterMove.GetCircular(move.Index1 + 1);220 indices[11] = indices[3];221 }222 int[] aPosteriori = new int[12];223 Permutation tempPermutation;224 foreach (ItemList<IntValue> realization in realizations) {225 for (int i = 0; i < edges.Length; i++) {226 if (i < 6) {227 tempPermutation = permutation;228 } else {229 tempPermutation = afterMove;230 }231 if (realization[edges[i]].Value == 1) {232 aPosteriori[i] = edges[i];233 } else {234 int j = 1;235 if (i % 2 == 0) {236 // find nearest predecessor in realization if source edge237 while (realization[tempPermutation.GetCircular(indices[i] - j)].Value == 0) {238 j++;239 }240 aPosteriori[i] = tempPermutation.GetCircular(indices[i] - j);241 } else {242 // find nearest successor in realization if target edge243 while (realization[tempPermutation.GetCircular(indices[i] + j)].Value == 0) {244 j++;245 }246 aPosteriori[i] = tempPermutation.GetCircular(indices[i] + j);247 }248 }249 }250 if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3]) &&251 !(aPosteriori[0] == aPosteriori[4] && aPosteriori[1] == aPosteriori[5]) &&252 !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5])) {253 // compute cost difference between the two a posteriori solutions254 moveQuality = moveQuality + distanceMatrix[aPosteriori[6], aPosteriori[7]] + distanceMatrix[aPosteriori[8], aPosteriori[9]] + distanceMatrix[aPosteriori[10], aPosteriori[11]];255 moveQuality = moveQuality - distanceMatrix[aPosteriori[0], aPosteriori[1]] - distanceMatrix[aPosteriori[2], aPosteriori[3]] - distanceMatrix[aPosteriori[4], aPosteriori[5]];256 }257 Array.Clear(aPosteriori, 0, aPosteriori.Length);258 }259 // return average of cost differences260 return moveQuality / realizations.Count;261 }262 protected double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) {263 TwoPointFiveMove currentMove = TwoPointFiveMoveParameter.ActualValue;264 if (currentMove.IsInvert) {265 return EvaluateInversionByDistanceMatrix(permutation, currentMove, distanceMatrix, RealizationsParameter.Value);266 } else {267 return EvaluateInsertionByDistanceMatrix(permutation, currentMove, distanceMatrix, RealizationsParameter.Value);268 }269 }270 271 private DistanceMatrix CalculateDistanceMatrix(DoubleMatrix c) {272 DistanceMatrix distanceMatrix = new DistanceMatrix(c.Rows, c.Rows);273 for (int i = 0; i < distanceMatrix.Rows; i++) {274 for (int j = 0; j < distanceMatrix.Columns; j++)275 distanceMatrix[i, j] = CalculateDistance(c[i, 0], c[i, 1], c[j, 0], c[j, 1]);276 }277 return (DistanceMatrix)distanceMatrix.AsReadOnly();278 84 } 279 85 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/StochasticTwoPointFiveMultiMoveGenerator.cs
r13408 r13412 24 24 using HeuristicLab.Data; 25 25 using HeuristicLab.Encodings.PermutationEncoding; 26 using HeuristicLab.Operators;27 26 using HeuristicLab.Optimization; 28 27 using HeuristicLab.Parameters; … … 30 29 31 30 namespace HeuristicLab.Problems.PTSP { 32 [Item("Stochastic 25MultiMoveGenerator", "Randomly samples n from all possible inversion and shift moves (2.5-opt) from a given permutation.")]31 [Item("Stochastic 2.5-MultiMoveGenerator", "Randomly samples n from all possible inversion and shift moves (2.5-opt) from a given permutation.")] 33 32 [StorableClass] 34 class Stochastic25MultiMoveGenerator : TwoPointFiveMoveGenerator, IMultiMoveGenerator, IStochasticOperator {33 public sealed class StochasticTwoPointFiveMultiMoveGenerator : TwoPointFiveMoveGenerator, IMultiMoveGenerator, IStochasticOperator { 35 34 public ILookupParameter<IRandom> RandomParameter { 36 35 get { return (ILookupParameter<IRandom>)Parameters["Random"]; } … … 46 45 47 46 [StorableConstructor] 48 pr otected Stochastic25MultiMoveGenerator(bool deserializing) : base(deserializing) { }49 pr otected Stochastic25MultiMoveGenerator(Stochastic25MultiMoveGenerator original, Cloner cloner) : base(original, cloner) { }50 public Stochastic 25MultiMoveGenerator()47 private StochasticTwoPointFiveMultiMoveGenerator(bool deserializing) : base(deserializing) { } 48 private StochasticTwoPointFiveMultiMoveGenerator(StochasticTwoPointFiveMultiMoveGenerator original, Cloner cloner) : base(original, cloner) { } 49 public StochasticTwoPointFiveMultiMoveGenerator() 51 50 : base() { 52 51 Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator.")); … … 55 54 56 55 public override IDeepCloneable Clone(Cloner cloner) { 57 return new Stochastic 25MultiMoveGenerator(this, cloner);56 return new StochasticTwoPointFiveMultiMoveGenerator(this, cloner); 58 57 } 59 58 60 59 public static TwoPointFiveMove[] Apply(Permutation permutation, IRandom random, int sampleSize) { 61 int length = permutation.Length; 62 TwoPointFiveMove[] moves = new TwoPointFiveMove[sampleSize]; 63 for (int i = 0; i < sampleSize; i++) { 64 moves[i] = Stochastic25SingleMoveGenerator.Apply(permutation, random); 60 var moves = new TwoPointFiveMove[sampleSize]; 61 for (var i = 0; i < sampleSize; i++) { 62 moves[i] = StochasticTwoPointFiveSingleMoveGenerator.Apply(permutation, random); 65 63 } 66 64 return moves; … … 68 66 69 67 protected override TwoPointFiveMove[] GenerateMoves(Permutation permutation) { 70 IRandom random = RandomParameter.ActualValue; 71 return Apply(permutation, random, SampleSizeParameter.ActualValue.Value); 68 return Apply(permutation, RandomParameter.ActualValue, SampleSizeParameter.ActualValue.Value); 72 69 } 73 70 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/StochasticTwoPointFiveSingleMoveGenerator.cs
r13408 r13412 23 23 using HeuristicLab.Common; 24 24 using HeuristicLab.Core; 25 using HeuristicLab.Encodings.PermutationEncoding; 25 26 using HeuristicLab.Optimization; 26 27 using HeuristicLab.Parameters; 27 28 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Operators;29 using HeuristicLab.Encodings.PermutationEncoding;30 31 29 32 30 namespace HeuristicLab.Problems.PTSP { 33 [Item("Stochastic 25SingleMoveGenerator", "Randomly samples a single from all possible inversion and shift moves (2.5-opt) from a given permutation.")]31 [Item("Stochastic 2.5-SingleMoveGenerator", "Randomly samples a single from all possible inversion and shift moves (2.5-opt) from a given permutation.")] 34 32 [StorableClass] 35 class Stochastic25SingleMoveGenerator : TwoPointFiveMoveGenerator, IStochasticOperator, ISingleMoveGenerator {33 public sealed class StochasticTwoPointFiveSingleMoveGenerator : TwoPointFiveMoveGenerator, IStochasticOperator, ISingleMoveGenerator { 36 34 public ILookupParameter<IRandom> RandomParameter { 37 35 get { return (ILookupParameter<IRandom>)Parameters["Random"]; } … … 39 37 40 38 [StorableConstructor] 41 pr otected Stochastic25SingleMoveGenerator(bool deserializing) : base(deserializing) { }42 pr otected Stochastic25SingleMoveGenerator(Stochastic25SingleMoveGenerator original, Cloner cloner) : base(original, cloner) { }43 public Stochastic 25SingleMoveGenerator()39 private StochasticTwoPointFiveSingleMoveGenerator(bool deserializing) : base(deserializing) { } 40 private StochasticTwoPointFiveSingleMoveGenerator(StochasticTwoPointFiveSingleMoveGenerator original, Cloner cloner) : base(original, cloner) { } 41 public StochasticTwoPointFiveSingleMoveGenerator() 44 42 : base() { 45 43 Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator.")); … … 47 45 48 46 public override IDeepCloneable Clone(Cloner cloner) { 49 return new Stochastic 25SingleMoveGenerator(this, cloner);47 return new StochasticTwoPointFiveSingleMoveGenerator(this, cloner); 50 48 } 51 49 52 50 public static TwoPointFiveMove Apply(Permutation permutation, IRandom random) { 53 51 int length = permutation.Length; 54 if (length == 1) throw new ArgumentException("Stochastic 25SingleMoveGenerator: There cannot be an inversion move given a permutation of length 1.", "permutation");52 if (length == 1) throw new ArgumentException("Stochastic 2.5-SingleMoveGenerator: There cannot be an inversion move given a permutation of length 1.", "permutation"); 55 53 int index1 = random.Next(length - 1); 56 54 int index2 = random.Next(index1 + 1, length); … … 63 61 bool isInvert = random.NextDouble() > 0.5; 64 62 return new TwoPointFiveMove(index1, index2, isInvert); 65 63 66 64 } 67 65 68 66 protected override TwoPointFiveMove[] GenerateMoves(Permutation permutation) { 69 IRandom random = RandomParameter.ActualValue; 70 return new TwoPointFiveMove[] { Apply(permutation, random) }; 67 return new[] { Apply(permutation, RandomParameter.ActualValue) }; 71 68 } 72 69 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/TwoPointFiveMove.cs
r12272 r13412 1 using HeuristicLab.Common; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using HeuristicLab.Common; 2 23 using HeuristicLab.Core; 3 24 using HeuristicLab.Encodings.PermutationEncoding; … … 5 26 6 27 namespace HeuristicLab.Problems.PTSP { 7 public class TwoPointFiveMove : Item { 8 28 [Item("2.5-Move", "Represents a 2.5-move.")] 29 [StorableClass] 30 public sealed class TwoPointFiveMove : Item { 31 [Storable] 32 public int Index1 { get; protected set; } 33 [Storable] 34 public int Index2 { get; protected set; } 35 [Storable] 36 public Permutation Permutation { get; protected set; } 37 [Storable] 38 public bool IsInvert { get; protected set; } 39 9 40 [StorableConstructor] 10 public TwoPointFiveMove() : this(-1, -1, null, true) { }11 pr otectedTwoPointFiveMove(bool deserializing) : base(deserializing) { }12 pr otectedTwoPointFiveMove(TwoPointFiveMove original, Cloner cloner)41 public TwoPointFiveMove() : this(-1, -1, null, true) { } 42 private TwoPointFiveMove(bool deserializing) : base(deserializing) { } 43 private TwoPointFiveMove(TwoPointFiveMove original, Cloner cloner) 13 44 : base(original, cloner) { 14 45 this.Index1 = original.Index1; 15 46 this.Index2 = original.Index2; 16 47 this.IsInvert = original.IsInvert; 17 if (original.Permutation != null) 18 this.Permutation = cloner.Clone(original.Permutation); 48 this.Permutation = cloner.Clone(original.Permutation); 19 49 } 20 50 public TwoPointFiveMove(int index1, int index2, Permutation permutation, bool isinvert) … … 34 64 } 35 65 36 [Storable]37 public int Index1 { get; protected set; }38 [Storable]39 public int Index2 { get; protected set; }40 [Storable]41 public Permutation Permutation { get; protected set; }42 [Storable]43 public bool IsInvert { get; protected set; }44 45 66 public override IDeepCloneable Clone(Cloner cloner) { 46 67 return new TwoPointFiveMove(this, cloner); -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/TwoPointFiveMoveGenerator.cs
r13408 r13412 32 32 [Item("TwoPointFiveMoveGenerator", "Base class for all inversion and shift (2.5-opt) move generators.")] 33 33 [StorableClass] 34 public abstract class TwoPointFiveMoveGenerator : SingleSuccessorOperator, I 25MoveOperator, IMoveGenerator {34 public abstract class TwoPointFiveMoveGenerator : SingleSuccessorOperator, ITwoPointFiveMoveOperator, IMoveGenerator { 35 35 public override bool CanChangeName { 36 36 get { return false; } 37 37 } 38 38 39 public ILookupParameter<Permutation> PermutationParameter { 39 40 get { return (ILookupParameter<Permutation>)Parameters["Permutation"]; } … … 42 43 get { return (LookupParameter<TwoPointFiveMove>)Parameters["TwoPointFiveMove"]; } 43 44 } 44 protected ScopeParameter CurrentScopeParameter {45 get { return (ScopeParameter)Parameters["CurrentScope"]; }46 }47 45 48 46 [StorableConstructor] 49 47 protected TwoPointFiveMoveGenerator(bool deserializing) : base(deserializing) { } 50 48 protected TwoPointFiveMoveGenerator(TwoPointFiveMoveGenerator original, Cloner cloner) : base(original, cloner) { } 51 p ublicTwoPointFiveMoveGenerator()49 protected TwoPointFiveMoveGenerator() 52 50 : base() { 53 51 Parameters.Add(new LookupParameter<Permutation>("Permutation", "The permutation for which moves should be generated.")); … … 57 55 58 56 public override IOperation Apply() { 59 Permutationp = PermutationParameter.ActualValue;60 TwoPointFiveMove[]moves = GenerateMoves(p);61 Scope[]moveScopes = new Scope[moves.Length];57 var p = PermutationParameter.ActualValue; 58 var moves = GenerateMoves(p); 59 var moveScopes = new Scope[moves.Length]; 62 60 for (int i = 0; i < moveScopes.Length; i++) { 63 61 moveScopes[i] = new Scope(i.ToString()); 64 62 moveScopes[i].Variables.Add(new Variable(TwoPointFiveMoveParameter.ActualName, moves[i])); 65 63 } 66 CurrentScopeParameter.ActualValue.SubScopes.AddRange(moveScopes);64 ExecutionContext.Scope.SubScopes.AddRange(moveScopes); 67 65 return base.Apply(); 68 66 } -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/TwoPointFiveMoveMaker.cs
r13408 r13412 1 using HeuristicLab.Common; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using HeuristicLab.Common; 2 23 using HeuristicLab.Core; 3 24 using HeuristicLab.Data; … … 11 32 [Item("TwoPointFiveMoveMaker", "Peforms an inversion and shift (2.5-opt) on a given permutation and updates the quality.")] 12 33 [StorableClass] 13 public class TwoPointFiveMoveMaker : SingleSuccessorOperator, I 25MoveOperator, IMoveMaker {34 public class TwoPointFiveMoveMaker : SingleSuccessorOperator, ITwoPointFiveMoveOperator, IMoveMaker { 14 35 public override bool CanChangeName { 15 36 get { return false; } 16 37 } 38 17 39 public ILookupParameter<DoubleValue> QualityParameter { 18 40 get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; } … … 27 49 get { return (ILookupParameter<Permutation>)Parameters["Permutation"]; } 28 50 } 51 29 52 [StorableConstructor] 30 53 protected TwoPointFiveMoveMaker(bool deserializing) : base(deserializing) { } … … 43 66 44 67 public override IOperation Apply() { 45 TwoPointFiveMovemove = TwoPointFiveMoveParameter.ActualValue;46 Permutationpermutation = PermutationParameter.ActualValue;47 DoubleValuemoveQuality = MoveQualityParameter.ActualValue;48 DoubleValuequality = QualityParameter.ActualValue;68 var move = TwoPointFiveMoveParameter.ActualValue; 69 var permutation = PermutationParameter.ActualValue; 70 var moveQuality = MoveQualityParameter.ActualValue; 71 var quality = QualityParameter.ActualValue; 49 72 50 73 if (move.IsInvert) { … … 53 76 TranslocationManipulator.Apply(permutation, move.Index1, move.Index1, move.Index2); 54 77 } 55 78 56 79 quality.Value = moveQuality.Value; 57 80 -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/PTSP.cs
r13202 r13412 20 20 #endregion 21 21 22 using System; 22 23 using HeuristicLab.Common; 23 24 using HeuristicLab.Core; … … 30 31 31 32 namespace HeuristicLab.Problems.PTSP { 32 [Item("Probabilistic Traveling Salesman Problem ", "Represents a Probabilistic Traveling Salesman Problem.")]33 [Item("Probabilistic Traveling Salesman Problem (PTSP)", "Represents a Probabilistic Traveling Salesman Problem.")] 33 34 [StorableClass] 34 public abstract class ProbabilisticTravelingSalesmanProblem : SingleObjectiveBasicProblem<PermutationEncoding>, IStorableContent,35 public abstract class ProbabilisticTravelingSalesmanProblem : SingleObjectiveBasicProblem<PermutationEncoding>, 35 36 IProblemInstanceConsumer<PTSPData> { 36 37 private static readonly int DistanceMatrixSizeLimit = 1000; … … 40 41 get { return (OptionalValueParameter<DoubleMatrix>)Parameters["Coordinates"]; } 41 42 } 43 public OptionalValueParameter<DistanceCalculator> DistanceCalculatorParameter { 44 get { return (OptionalValueParameter<DistanceCalculator>)Parameters["DistanceCalculator"]; } 45 } 42 46 public OptionalValueParameter<DistanceMatrix> DistanceMatrixParameter { 43 47 get { return (OptionalValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; } 44 48 } 45 public ValueParameter<BoolValue> UseDistanceMatrixParameter {46 get { return ( ValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }49 public IFixedValueParameter<BoolValue> UseDistanceMatrixParameter { 50 get { return (IFixedValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; } 47 51 } 48 52 public OptionalValueParameter<Permutation> BestKnownSolutionParameter { 49 53 get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; } 50 54 } 51 public ValueParameter<DoubleArray> ProbabilityMatrixParameter {52 get { return ( ValueParameter<DoubleArray>)Parameters["ProbabilityMatrix"]; }55 public IValueParameter<DoubleArray> ProbabilitiesParameter { 56 get { return (IValueParameter<DoubleArray>)Parameters["Probabilities"]; } 53 57 } 54 55 56 58 #endregion 57 59 … … 61 63 set { CoordinatesParameter.Value = value; } 62 64 } 65 public DistanceCalculator DistanceCalculator { 66 get { return DistanceCalculatorParameter.Value; } 67 set { DistanceCalculatorParameter.Value = value; } 68 } 63 69 public DistanceMatrix DistanceMatrix { 64 70 get { return DistanceMatrixParameter.Value; } 65 71 set { DistanceMatrixParameter.Value = value; } 66 72 } 67 public BoolValueUseDistanceMatrix {68 get { return UseDistanceMatrixParameter.Value ; }69 set { UseDistanceMatrixParameter.Value = value; }73 public bool UseDistanceMatrix { 74 get { return UseDistanceMatrixParameter.Value.Value; } 75 set { UseDistanceMatrixParameter.Value.Value = value; } 70 76 } 71 77 public Permutation BestKnownSolution { … … 73 79 set { BestKnownSolutionParameter.Value = value; } 74 80 } 75 public DoubleArray Probabilit yMatrix{76 get { return Probabilit yMatrixParameter.Value; }77 set { Probabilit yMatrixParameter.Value = value; }81 public DoubleArray Probabilities { 82 get { return ProbabilitiesParameter.Value; } 83 set { ProbabilitiesParameter.Value = value; } 78 84 } 79 85 80 86 #endregion 81 82 87 83 88 public override bool Maximization { … … 87 92 [StorableConstructor] 88 93 protected ProbabilisticTravelingSalesmanProblem(bool deserializing) : base(deserializing) { } 89 protected ProbabilisticTravelingSalesmanProblem(ProbabilisticTravelingSalesmanProblem original, Cloner cloner) 90 : base(original, cloner) { 91 } 92 93 public ProbabilisticTravelingSalesmanProblem() { 94 protected ProbabilisticTravelingSalesmanProblem(ProbabilisticTravelingSalesmanProblem original, Cloner cloner) : base(original, cloner) { } 95 protected ProbabilisticTravelingSalesmanProblem() { 94 96 Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities.")); 97 Parameters.Add(new OptionalValueParameter<DistanceCalculator>("DistanceCalculator", "Calculates the distance between two rows in the coordinates matrix.")); 95 98 Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities.")); 96 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)));99 Parameters.Add(new FixedValueParameter<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))); 97 100 Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance.")); 98 Parameters.Add(new ValueParameter<DoubleArray>("Probabilit yMatrix", "The matrix which contains the probabilities of each of the cities."));101 Parameters.Add(new ValueParameter<DoubleArray>("Probabilities", "This list describes for each city the probability of appearing in a realized instance.")); 99 102 100 103 Coordinates = new DoubleMatrix(new double[,] { … … 105 108 }); 106 109 107 ProbabilityMatrix = new DoubleArray(new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }); 110 Probabilities = new DoubleArray(new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }); 111 } 108 112 113 public override double Evaluate(Individual individual, IRandom random) { 114 return Evaluate(individual.Permutation(), random); 109 115 } 116 117 public abstract double Evaluate(Permutation tour, IRandom random); 110 118 111 119 public virtual void Load(PTSPData data) { 112 120 if (data.Coordinates == null && data.Distances == null) 113 121 throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!"); 114 if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == DistanceMeasure.Att 115 || data.DistanceMeasure == DistanceMeasure.Manhattan 116 || data.DistanceMeasure == DistanceMeasure.Maximum)) 117 throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix."); 118 if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2) 119 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."); 122 if (data.Dimension > DistanceMatrixSizeLimit && (data.Coordinates == null || data.Coordinates.GetLength(0) != data.Dimension || data.Coordinates.GetLength(1) != 2)) 123 throw new System.IO.InvalidDataException("The given instance is too large for using a distance matrix and there is a problem with the coordinates."); 124 if (data.Coordinates != null && (data.Coordinates.GetLength(0) != data.Dimension || data.Coordinates.GetLength(1) != 2)) 125 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 respectively."); 126 127 switch (data.DistanceMeasure) { 128 case DistanceMeasure.Direct: 129 DistanceCalculator = null; 130 if (data.Dimension > DistanceMatrixSizeLimit && Coordinates != null) { 131 DistanceCalculator = new EuclideanDistance(); 132 UseDistanceMatrix = false; 133 } else UseDistanceMatrix = true; 134 break; 135 case DistanceMeasure.Att: DistanceCalculator = new AttDistance(); break; 136 case DistanceMeasure.Euclidean: DistanceCalculator = new EuclideanDistance(); break; 137 case DistanceMeasure.Geo: DistanceCalculator = new GeoDistance(); break; 138 case DistanceMeasure.Manhattan: DistanceCalculator = new ManhattanDistance(); break; 139 case DistanceMeasure.Maximum: DistanceCalculator = new MaximumDistance(); break; 140 case DistanceMeasure.RoundedEuclidean: DistanceCalculator = new RoundedEuclideanDistance(); break; 141 case DistanceMeasure.UpperEuclidean: DistanceCalculator = new UpperEuclideanDistance(); break; 142 default: throw new ArgumentException("Distance measure is unknown"); 143 } 120 144 121 145 Name = data.Name; 122 146 Description = data.Description; 123 147 124 ProbabilityMatrix = new DoubleArray(data.Probabilities); 125 126 if (data.BestKnownTour != null) { 127 BestKnownSolution = new Permutation(PermutationTypes.RelativeUndirected, data.BestKnownTour); 128 } 129 148 Probabilities = new DoubleArray(data.Probabilities); 149 BestKnownSolution = data.BestKnownTour != null ? new Permutation(PermutationTypes.RelativeUndirected, data.BestKnownTour) : null; 130 150 Coordinates = data.Coordinates != null && data.Coordinates.GetLength(0) > 0 ? new DoubleMatrix(data.Coordinates) : null; 131 151 DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix()); -
branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Plugin.cs.frame
r12317 r13412 1 using HeuristicLab.PluginInfrastructure; 1 #region License Information 2 /* HeuristicLab 3 * Copyright (C) 2002-2015 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 22 using HeuristicLab.PluginInfrastructure; 23 2 24 namespace HeuristicLab.Problems.PTSP { 3 [Plugin("HeuristicLab.Problems.PTSP", "Provides an implementation of the PTSP", "3.3.11.$WCREV$")]4 5 6 7 8 9 10 11 12 13 14 15 16 17 public classPlugin : PluginBase {18 25 [Plugin("HeuristicLab.Problems.PTSP", "Provides an implementation of the probabilistic traveling salesman problem (PTSP)", "3.3.13.$WCREV$")] 26 [PluginFile("HeuristicLab.Problems.PTSP-3.3.dll", PluginFileType.Assembly)] 27 [PluginDependency("HeuristicLab.Collections", "3.3")] 28 [PluginDependency("HeuristicLab.Common", "3.3")] 29 [PluginDependency("HeuristicLab.Common.Resources", "3.3")] 30 [PluginDependency("HeuristicLab.Core", "3.3")] 31 [PluginDependency("HeuristicLab.Data", "3.3")] 32 [PluginDependency("HeuristicLab.Encodings.PermutationEncoding", "3.3")] 33 [PluginDependency("HeuristicLab.Operators", "3.3")] 34 [PluginDependency("HeuristicLab.Optimization", "3.3")] 35 [PluginDependency("HeuristicLab.Parameters", "3.3")] 36 [PluginDependency("HeuristicLab.Persistence", "3.3")] 37 [PluginDependency("HeuristicLab.Problems.Instances", "3.3")] 38 [PluginDependency("HeuristicLab.Random", "3.3")] 39 public class HeuristicLabProblemsPTSPPlugin : PluginBase { 40 } 19 41 }
Note: See TracChangeset
for help on using the changeset viewer.