Free cookie consent management tool by TermsFeed Policy Generator

Changeset 13470


Ignore:
Timestamp:
12/15/15 16:38:08 (9 years ago)
Author:
abeham
Message:

#2221:

  • implemented review comments
    • hid rng as private class, implemented djb2 hash function (hash function implementation may also change)
    • added missing probabilities
    • base class for instance providers
    • prebuild event events
    • build platforms
    • unit test will be removed on trunk integration
    • corrected assembly file version
    • distance calculator parameter was not hidden, can be changed by user, updates distance matrix
    • fixed performance problems (ouch!) also for estimated ptsp (inlined GetDistance method)
  • added moves (full evaluation) for analytical tsp
  • added local improvement operators for analytical ptsp
  • added recalculation of distance matrix when parameters change
  • still lots of other changes
Location:
branches/PTSP
Files:
1 deleted
20 edited
11 copied
3 moved

Legend:

Unmodified
Added
Removed
  • branches/PTSP/HeuristicLab.Problems.Instances.TSPLIB/3.3/HeuristicLab.Problems.Instances.TSPLIB-3.3.csproj

    r13412 r13470  
    123123  </ItemGroup>
    124124  <ItemGroup>
    125     <Compile Include="MarsagliaRandom.cs" />
    126125    <Compile Include="TSPLIBHeterogeneousPTSPDataDescriptor.cs" />
    127126    <Compile Include="TSPLIBHomogeneousPTSPDataDescriptor.cs" />
    128127    <Compile Include="TSPLIBHeterogeneousPTSPInstanceProvider.cs" />
     128    <Compile Include="TSPLIBPTSPInstanceProvider.cs" />
    129129    <Compile Include="TSPLIBInstanceProvider.cs" />
    130130    <Compile Include="TSPLIBATSPInstanceProvider.cs" />
  • branches/PTSP/HeuristicLab.Problems.Instances.TSPLIB/3.3/TSPLIBHeterogeneousPTSPInstanceProvider.cs

    r13412 r13470  
    2222using System;
    2323using System.Collections.Generic;
    24 using System.IO;
    2524using System.Linq;
    2625
    2726namespace HeuristicLab.Problems.Instances.TSPLIB {
    28   public class TSPLIBHeterogeneousPTSPInstanceProvider : TSPLIBInstanceProvider<PTSPData> {
     27  public class TSPLIBHeterogeneousPTSPInstanceProvider : TSPLIBPTSPInstanceProvider {
    2928
    3029    public override string Name {
     
    3231    }
    3332
    34     public override string Description {
    35       get { return "Traveling Salesman Problem Library"; }
    36     }
    37 
    38     protected override string FileExtension { get { return "tsp"; } }
    39 
    4033    public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
    4134      foreach (var desc in base.GetDataDescriptors().OfType<TSPLIBDataDescriptor>()) {
    42         desc.Name += " [0.1;0.9]";
    4335        desc.SolutionIdentifier = null;
    4436        yield return desc;
     
    4638    }
    4739
    48     protected override PTSPData LoadInstance(TSPLIBParser parser, IDataDescriptor descriptor = null) {
    49       parser.Parse();
    50       if (parser.FixedEdges != null) throw new InvalidDataException("TSP instance " + parser.Name + " contains fixed edges which are not supported by HeuristicLab.");
    51       var instance = new PTSPData();
    52       instance.Dimension = parser.Dimension;
    53       instance.Coordinates = parser.Vertices != null ? parser.Vertices : parser.DisplayVertices;
    54       instance.Distances = parser.Distances;
    55       switch (parser.EdgeWeightType) {
    56         case TSPLIBEdgeWeightTypes.ATT:
    57           instance.DistanceMeasure = DistanceMeasure.Att; break;
    58         case TSPLIBEdgeWeightTypes.CEIL_2D:
    59           instance.DistanceMeasure = DistanceMeasure.UpperEuclidean; break;
    60         case TSPLIBEdgeWeightTypes.EUC_2D:
    61           instance.DistanceMeasure = DistanceMeasure.RoundedEuclidean; break;
    62         case TSPLIBEdgeWeightTypes.EUC_3D:
    63           throw new InvalidDataException("3D coordinates are not supported.");
    64         case TSPLIBEdgeWeightTypes.EXPLICIT:
    65           instance.DistanceMeasure = DistanceMeasure.Direct; break;
    66         case TSPLIBEdgeWeightTypes.GEO:
    67           instance.DistanceMeasure = DistanceMeasure.Geo; break;
    68         case TSPLIBEdgeWeightTypes.MAN_2D:
    69           instance.DistanceMeasure = DistanceMeasure.Manhattan; break;
    70         case TSPLIBEdgeWeightTypes.MAN_3D:
    71           throw new InvalidDataException("3D coordinates are not supported.");
    72         case TSPLIBEdgeWeightTypes.MAX_2D:
    73           instance.DistanceMeasure = DistanceMeasure.Maximum; break;
    74         case TSPLIBEdgeWeightTypes.MAX_3D:
    75           throw new InvalidDataException("3D coordinates are not supported.");
    76         default:
    77           throw new InvalidDataException("The given edge weight is not supported by HeuristicLab.");
     40    protected override double[] GetProbabilities(IDataDescriptor descriptor, PTSPData instance) {
     41      var random = new MarsagliaRandom(GetInstanceHash(instance.Name));
     42      return Enumerable.Range(0, instance.Dimension).Select(_ => (int)Math.Round((0.1 + 0.9 * random.NextDouble()) * 100) / 100.0).ToArray();
     43    }
     44
     45    // Bernstein's hash function
     46    private uint GetInstanceHash(string name) {
     47      uint hash = 5381;
     48      var len = name.Length;
     49      for (var i = 0; i < len; i++)
     50        unchecked { hash = ((hash * 33) + name[i]); }
     51      return hash;
     52    }
     53
     54    /// <summary>
     55    /// This class is used to randomly generate PTSP instances given the TSPLIB instances.
     56    /// An own implementation of a RNG was used in order to avoid possible implementation changes
     57    /// in future .NET versions which would result in entirely different instances.
     58    /// </summary>
     59    /// <remarks>
     60    /// RNG is implemented according to George Marsaglia https://en.wikipedia.org/wiki/Multiply-with-carry
     61    /// </remarks>
     62    private class MarsagliaRandom {
     63      /*
     64       * S = 2111111111*X[n-4] + 1492*X[n-3] + 1776*X[n-2] + 5115*X[n-1] + C
     65       * X[n] = S modulo 2^32
     66       * C = floor(S / 2^32)
     67       *
     68       */
     69      private readonly uint[] mem = new uint[4];
     70      private uint c;
     71
     72      public MarsagliaRandom(uint s) {
     73        int i;
     74        for (i = 0; i < mem.Length; i++) {
     75          unchecked { s = s * 31294061 + 1; }
     76          mem[i] = s;
     77        }
     78        unchecked { c = s * 31294061 + 1; }
    7879      }
    7980
    80       instance.Name = parser.Name;
    81       instance.Description = parser.Comment
    82         + Environment.NewLine + Environment.NewLine
    83         + GetInstanceDescription();
     81      private uint Next() {
     82        unchecked {
     83          ulong wsum = 2111111111 * mem[0]
     84                      + 1492 * mem[1]
     85                      + 1776 * mem[2]
     86                      + 5115 * mem[3]
     87                      + c;
    8488
    85       var random = new MarsagliaRandom((uint)(descriptor != null ? descriptor.Name : instance.Name).GetHashCode());
    86       instance.Probabilities = Enumerable.Range(0, instance.Dimension).Select(_ => 0.1 + 0.9 * random.NextDouble()).ToArray();
     89          mem[0] = mem[1];
     90          mem[1] = mem[2];
     91          mem[2] = mem[3];
     92          mem[3] = (uint)wsum;
     93          c = (uint)(wsum >> 32);
     94          return mem[3];
     95        }
     96      }
    8797
    88       return instance;
     98      public double NextDouble() {
     99        return (double)Next() / uint.MaxValue;
     100      }
    89101    }
    90 
    91     protected override void LoadSolution(TSPLIBParser parser, PTSPData instance) {
    92       parser.Parse();
    93       instance.BestKnownTour = parser.Tour.FirstOrDefault();
    94     }
    95 
    96     public PTSPData LoadData(string tspFile, string tourFile, double? bestQuality) {
    97       var data = LoadInstance(new TSPLIBParser(tspFile));
    98       if (!String.IsNullOrEmpty(tourFile)) {
    99         var tourParser = new TSPLIBParser(tourFile);
    100         LoadSolution(tourParser, data);
    101       }
    102       if (bestQuality.HasValue)
    103         data.BestKnownQuality = bestQuality.Value;
    104       return data;
    105     }
    106 
    107102  }
    108103}
  • branches/PTSP/HeuristicLab.Problems.Instances.TSPLIB/3.3/TSPLIBHomogeneousPTSPInstanceProvider.cs

    r13412 r13470  
    2020#endregion
    2121
    22 using System;
    2322using System.Collections.Generic;
    2423using System.Globalization;
    25 using System.IO;
    2624using System.Linq;
    2725
    2826namespace HeuristicLab.Problems.Instances.TSPLIB {
    29   public class TSPLIBHomogeneousPTSPInstanceProvider : TSPLIBInstanceProvider<PTSPData> {
    30     private static readonly double[] probabilities = new[] { 0.1, 0.2, 0.4, 0.5, 0.6, 0.8, 0.9, 1.0 };
     27  public class TSPLIBHomogeneousPTSPInstanceProvider : TSPLIBPTSPInstanceProvider {
     28    private static readonly double[] Probabilities = new[] { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
    3129
    3230    public override string Name {
     
    3432    }
    3533
    36     public override string Description {
    37       get { return "Traveling Salesman Problem Library"; }
    38     }
    39 
    40     protected override string FileExtension { get { return "tsp"; } }
    41 
    4234    public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
    4335      var tspDescriptors = base.GetDataDescriptors().OfType<TSPLIBDataDescriptor>();
    4436      foreach (var desc in tspDescriptors) {
    45         foreach (var p in probabilities) {
     37        foreach (var p in Probabilities) {
    4638          yield return new TSPLIBHomogeneousPTSPDataDescriptor(
    4739            desc.Name + "-" + p.ToString(CultureInfo.InvariantCulture.NumberFormat),
     
    5446    }
    5547
    56     protected override PTSPData LoadInstance(TSPLIBParser parser, IDataDescriptor descriptor = null) {
    57       parser.Parse();
    58       if (parser.FixedEdges != null) throw new InvalidDataException("TSP instance " + parser.Name + " contains fixed edges which are not supported by HeuristicLab.");
    59       var instance = new PTSPData();
    60       instance.Dimension = parser.Dimension;
    61       instance.Coordinates = parser.Vertices != null ? parser.Vertices : parser.DisplayVertices;
    62       instance.Distances = parser.Distances;
    63       switch (parser.EdgeWeightType) {
    64         case TSPLIBEdgeWeightTypes.ATT:
    65           instance.DistanceMeasure = DistanceMeasure.Att; break;
    66         case TSPLIBEdgeWeightTypes.CEIL_2D:
    67           instance.DistanceMeasure = DistanceMeasure.UpperEuclidean; break;
    68         case TSPLIBEdgeWeightTypes.EUC_2D:
    69           instance.DistanceMeasure = DistanceMeasure.RoundedEuclidean; break;
    70         case TSPLIBEdgeWeightTypes.EUC_3D:
    71           throw new InvalidDataException("3D coordinates are not supported.");
    72         case TSPLIBEdgeWeightTypes.EXPLICIT:
    73           instance.DistanceMeasure = DistanceMeasure.Direct; break;
    74         case TSPLIBEdgeWeightTypes.GEO:
    75           instance.DistanceMeasure = DistanceMeasure.Geo; break;
    76         case TSPLIBEdgeWeightTypes.MAN_2D:
    77           instance.DistanceMeasure = DistanceMeasure.Manhattan; break;
    78         case TSPLIBEdgeWeightTypes.MAN_3D:
    79           throw new InvalidDataException("3D coordinates are not supported.");
    80         case TSPLIBEdgeWeightTypes.MAX_2D:
    81           instance.DistanceMeasure = DistanceMeasure.Maximum; break;
    82         case TSPLIBEdgeWeightTypes.MAX_3D:
    83           throw new InvalidDataException("3D coordinates are not supported.");
    84         default:
    85           throw new InvalidDataException("The given edge weight is not supported by HeuristicLab.");
    86       }
    87 
    88       instance.Name = parser.Name;
    89       instance.Description = parser.Comment
    90         + Environment.NewLine + Environment.NewLine
    91         + GetInstanceDescription();
     48    protected override double[] GetProbabilities(IDataDescriptor descriptor, PTSPData instance) {
    9249      var ptspDesc = descriptor as TSPLIBHomogeneousPTSPDataDescriptor;
    93       instance.Probabilities = ptspDesc != null ? Enumerable.Range(0, instance.Dimension).Select(_ => ptspDesc.Probability).ToArray()
    94                                                 : Enumerable.Range(0, instance.Dimension).Select(_ => 0.5).ToArray();
    95 
    96       return instance;
     50      return ptspDesc != null ? Enumerable.Range(0, instance.Dimension).Select(_ => ptspDesc.Probability).ToArray()
     51                              : Enumerable.Range(0, instance.Dimension).Select(_ => 0.5).ToArray();
    9752    }
    98 
    99     protected override void LoadSolution(TSPLIBParser parser, PTSPData instance) {
    100       parser.Parse();
    101       instance.BestKnownTour = parser.Tour.FirstOrDefault();
    102     }
    103 
    104     public PTSPData LoadData(string tspFile, string tourFile, double? bestQuality) {
    105       var data = LoadInstance(new TSPLIBParser(tspFile));
    106       if (!String.IsNullOrEmpty(tourFile)) {
    107         var tourParser = new TSPLIBParser(tourFile);
    108         LoadSolution(tourParser, data);
    109       }
    110       if (bestQuality.HasValue)
    111         data.BestKnownQuality = bestQuality.Value;
    112       return data;
    113     }
    114 
    11553  }
    11654}
  • branches/PTSP/HeuristicLab.Problems.Instances.TSPLIB/3.3/TSPLIBPTSPInstanceProvider.cs

    r13451 r13470  
    2121
    2222using System;
    23 using System.Collections.Generic;
    24 using System.Globalization;
    2523using System.IO;
    2624using System.Linq;
    2725
    2826namespace HeuristicLab.Problems.Instances.TSPLIB {
    29   public class TSPLIBHomogeneousPTSPInstanceProvider : TSPLIBInstanceProvider<PTSPData> {
    30     private static readonly double[] probabilities = new[] { 0.1, 0.2, 0.4, 0.5, 0.6, 0.8, 0.9, 1.0 };
    31 
    32     public override string Name {
    33       get { return "TSPLIB (homogeneous symmetric PTSP)"; }
    34     }
     27  public abstract class TSPLIBPTSPInstanceProvider : TSPLIBInstanceProvider<PTSPData> {
    3528
    3629    public override string Description {
    37       get { return "Traveling Salesman Problem Library"; }
     30      get { return "Traveling Salesman Problem Library (adapted for generating PTSP instances)"; }
    3831    }
    3932
    4033    protected override string FileExtension { get { return "tsp"; } }
    41 
    42     public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
    43       var tspDescriptors = base.GetDataDescriptors().OfType<TSPLIBDataDescriptor>();
    44       foreach (var desc in tspDescriptors) {
    45         foreach (var p in probabilities) {
    46           yield return new TSPLIBHomogeneousPTSPDataDescriptor(
    47             desc.Name + "-" + p.ToString(CultureInfo.InvariantCulture.NumberFormat),
    48             desc.Description,
    49             desc.InstanceIdentifier,
    50             p == 1.0 ? desc.SolutionIdentifier : null,
    51             p);
    52         }
    53       }
    54     }
    5534
    5635    protected override PTSPData LoadInstance(TSPLIBParser parser, IDataDescriptor descriptor = null) {
     
    9069        + Environment.NewLine + Environment.NewLine
    9170        + GetInstanceDescription();
    92       var ptspDesc = descriptor as TSPLIBHomogeneousPTSPDataDescriptor;
    93       instance.Probabilities = ptspDesc != null ? Enumerable.Range(0, instance.Dimension).Select(_ => ptspDesc.Probability).ToArray()
    94                                                 : Enumerable.Range(0, instance.Dimension).Select(_ => 0.5).ToArray();
    9571
     72      instance.Probabilities = GetProbabilities(descriptor, instance);
    9673      return instance;
    9774    }
     75
     76    protected abstract double[] GetProbabilities(IDataDescriptor descriptor, PTSPData instance);
    9877
    9978    protected override void LoadSolution(TSPLIBParser parser, PTSPData instance) {
  • branches/PTSP/HeuristicLab.Problems.PTSP.Tests-3.3/HeuristicLab.Problems.PTSP.Tests-3.3.csproj

    r12322 r13470  
    3434    <ErrorReport>prompt</ErrorReport>
    3535    <WarningLevel>4</WarningLevel>
     36  </PropertyGroup>
     37  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
     38    <DebugSymbols>true</DebugSymbols>
     39    <OutputPath>bin\x64\Debug\</OutputPath>
     40    <DefineConstants>DEBUG;TRACE</DefineConstants>
     41    <DebugType>full</DebugType>
     42    <PlatformTarget>x64</PlatformTarget>
     43    <ErrorReport>prompt</ErrorReport>
     44    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     45  </PropertyGroup>
     46  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
     47    <OutputPath>bin\x64\Release\</OutputPath>
     48    <DefineConstants>TRACE</DefineConstants>
     49    <Optimize>true</Optimize>
     50    <DebugType>pdbonly</DebugType>
     51    <PlatformTarget>x64</PlatformTarget>
     52    <ErrorReport>prompt</ErrorReport>
     53    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     54  </PropertyGroup>
     55  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
     56    <DebugSymbols>true</DebugSymbols>
     57    <OutputPath>bin\x86\Debug\</OutputPath>
     58    <DefineConstants>DEBUG;TRACE</DefineConstants>
     59    <DebugType>full</DebugType>
     60    <PlatformTarget>x86</PlatformTarget>
     61    <ErrorReport>prompt</ErrorReport>
     62    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     63  </PropertyGroup>
     64  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
     65    <OutputPath>bin\x86\Release\</OutputPath>
     66    <DefineConstants>TRACE</DefineConstants>
     67    <Optimize>true</Optimize>
     68    <DebugType>pdbonly</DebugType>
     69    <PlatformTarget>x86</PlatformTarget>
     70    <ErrorReport>prompt</ErrorReport>
     71    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
    3672  </PropertyGroup>
    3773  <ItemGroup>
  • branches/PTSP/HeuristicLab.Problems.PTSP.Tests-3.3/PTSPMoveEvaluatorTest.cs

    r13412 r13470  
    8585    [TestProperty("Time", "short")]
    8686    public void InversionMoveEvaluatorTest() {
    87       var beforeMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distances, realizations)[0];
     87      Func<int, int, double> distance = (a, b) => distances[a, b];
     88      double variance;
     89      var beforeMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distance, realizations, out variance);
    8890
    8991      for (var i = 0; i < 500; i++) {
    9092        var move = StochasticInversionSingleMoveGenerator.Apply(tour, random);
    91         var moveMatrix = PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(tour, move, distances, realizations);
     93        var moveMatrix = PTSPEstimatedInversionMoveEvaluator.EvaluateMove(tour, move, distance, realizations);
    9294        InversionManipulator.Apply(tour, move.Index1, move.Index2);
    93         var afterMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distances, realizations)[0];
     95        var afterMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distance, realizations, out variance);
    9496
    9597        Assert.IsTrue(Math.Abs(moveMatrix).IsAlmost(Math.Abs(afterMatrix - beforeMatrix)),
     
    106108    [TestProperty("Time", "short")]
    107109    public void InsertionMoveEvaluatorTest() {
    108       var beforeMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distances, realizations)[0];
    109 
     110      Func<int, int, double> distance = (a, b) => distances[a, b];
     111      double variance;
     112      var beforeMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distance, realizations, out variance);
    110113      for (var i = 0; i < 500; i++) {
    111114        var move = StochasticTranslocationSingleMoveGenerator.Apply(tour, random);
    112         var moveMatrix = PTSPEstimatedInsertionMoveEvaluator.EvaluateByDistanceMatrix(tour, move, distances, realizations);
     115        var moveMatrix = PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(tour, move, distance, realizations);
    113116        TranslocationManipulator.Apply(tour, move.Index1, move.Index1, move.Index3);
    114         var afterMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distances, realizations)[0];
     117        var afterMatrix = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(tour, distance, realizations, out variance);
    115118
    116119        Assert.IsTrue(Math.Abs(moveMatrix).IsAlmost(Math.Abs(afterMatrix - beforeMatrix)),
     
    122125      }
    123126    }
    124 
    125     [TestMethod]
    126     [TestCategory("Problems.ProbabilisticTravelingSalesman")]
    127     [TestProperty("Time", "short")]
    128     public void AnalyticalTest() {
    129       for (var i = 0; i < 10; i++) {
    130         var perm = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random);
    131         var estimated = EstimatedProbabilisticTravelingSalesmanProblem.Evaluate(perm, distances, realizations)[0];
    132 
    133         var analytical = AnalyticalProbabilisticTravelingSalesmanProblem.Evaluate(perm, distances, probabilities);
    134         Console.WriteLine(Math.Abs(analytical - estimated));
    135       }
    136     }
    137127  }
    138128}
  • branches/PTSP/HeuristicLab.Problems.PTSP.Views/3.3/HeuristicLab.Problems.PTSP.Views-3.3.csproj

    r13412 r13470  
    3030    <ErrorReport>prompt</ErrorReport>
    3131    <WarningLevel>4</WarningLevel>
     32  </PropertyGroup>
     33  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
     34    <DebugSymbols>true</DebugSymbols>
     35    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     36    <DefineConstants>DEBUG;TRACE</DefineConstants>
     37    <DebugType>full</DebugType>
     38    <PlatformTarget>x64</PlatformTarget>
     39    <ErrorReport>prompt</ErrorReport>
     40    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     41  </PropertyGroup>
     42  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
     43    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     44    <DefineConstants>TRACE</DefineConstants>
     45    <Optimize>true</Optimize>
     46    <DebugType>pdbonly</DebugType>
     47    <PlatformTarget>x64</PlatformTarget>
     48    <ErrorReport>prompt</ErrorReport>
     49    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     50  </PropertyGroup>
     51  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
     52    <DebugSymbols>true</DebugSymbols>
     53    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     54    <DefineConstants>DEBUG;TRACE</DefineConstants>
     55    <DebugType>full</DebugType>
     56    <PlatformTarget>x86</PlatformTarget>
     57    <ErrorReport>prompt</ErrorReport>
     58    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     59  </PropertyGroup>
     60  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
     61    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     62    <DefineConstants>TRACE</DefineConstants>
     63    <Optimize>true</Optimize>
     64    <DebugType>pdbonly</DebugType>
     65    <PlatformTarget>x86</PlatformTarget>
     66    <ErrorReport>prompt</ErrorReport>
     67    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
    3268  </PropertyGroup>
    3369  <ItemGroup>
  • branches/PTSP/HeuristicLab.Problems.PTSP.Views/3.3/ProbabilisticTravelingSalesmanProblemView.Designer.cs

    r12269 r13470  
    7777      //
    7878      this.tabControl.AllowDrop = true;
    79       this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    80                   | System.Windows.Forms.AnchorStyles.Left)
    81                   | System.Windows.Forms.AnchorStyles.Right)));
     79      this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
     80            | System.Windows.Forms.AnchorStyles.Left)
     81            | System.Windows.Forms.AnchorStyles.Right)));
    8282      this.tabControl.Controls.Add(this.parametersTabPage);
    8383      this.tabControl.Controls.Add(this.visualizationTabPage);
     
    112112      // pathPTSPTourView
    113113      //
    114       this.pathPTSPTourView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    115                   | System.Windows.Forms.AnchorStyles.Left)
    116                   | System.Windows.Forms.AnchorStyles.Right)));
     114      this.pathPTSPTourView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
     115            | System.Windows.Forms.AnchorStyles.Left)
     116            | System.Windows.Forms.AnchorStyles.Right)));
    117117      this.pathPTSPTourView.Caption = "PathPTSPTour View";
    118118      this.pathPTSPTourView.Content = null;
     
    123123      this.pathPTSPTourView.TabIndex = 0;
    124124      //
    125       // TravelingSalesmanProblemView
     125      // ProbabilisticTravelingSalesmanProblemView
    126126      //
    127       this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    128127      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
    129       this.Name = "TravelingSalesmanProblemView";
     128      this.Name = "ProbabilisticTravelingSalesmanProblemView";
    130129      this.problemInstanceSplitContainer.Panel1.ResumeLayout(false);
    131130      this.problemInstanceSplitContainer.Panel1.PerformLayout();
  • branches/PTSP/HeuristicLab.Problems.PTSP.Views/3.3/ProbabilisticTravelingSalesmanProblemView.cs

    r13412 r13470  
    7979    private void BestKnownSolutionParameter_ValueChanged(object sender, EventArgs e) {
    8080      pathPTSPTourView.Content.Permutation = Content.BestKnownSolution;
    81       pathPTSPTourView.Content.Quality = new DoubleValue(Content.Evaluate(Content.BestKnownSolution, new MersenneTwister()));
     81      if (Content.BestKnownSolution != null)
     82        pathPTSPTourView.Content.Quality = new DoubleValue(Content.Evaluate(Content.BestKnownSolution, new MersenneTwister(13)));
     83      else pathPTSPTourView.Content.Quality = null;
    8284    }
    8385  }
  • branches/PTSP/HeuristicLab.Problems.PTSP.Views/3.3/Properties/AssemblyInfo.cs.frame

    r12269 r13470  
    3434// [assembly: AssemblyVersion("1.0.*")]
    3535[assembly: AssemblyVersion("3.3.0.0")]
    36 [assembly: AssemblyFileVersion("3.3.11.$WCREV$")]
     36[assembly: AssemblyFileVersion("3.3.13.$WCREV$")]
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/AnalyticalPTSP.cs

    r13412 r13470  
    2020#endregion
    2121
     22using System;
     23using System.Linq;
    2224using HeuristicLab.Common;
    2325using HeuristicLab.Core;
    2426using HeuristicLab.Data;
    2527using HeuristicLab.Encodings.PermutationEncoding;
     28using HeuristicLab.Optimization;
    2629using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2730
     
    3740    public AnalyticalProbabilisticTravelingSalesmanProblem() {
    3841      Operators.Add(new BestPTSPSolutionAnalyzer());
     42
     43      Operators.Add(new PTSPAnalyticalInversionMoveEvaluator());
     44      Operators.Add(new PTSPAnalyticalInsertionMoveEvaluator());
     45      Operators.Add(new PTSPAnalyticalInversionLocalImprovement());
     46      Operators.Add(new PTSPAnalyticalInsertionLocalImprovement());
     47      Operators.Add(new PTSPAnalyticalTwoPointFiveLocalImprovement());
     48
     49      Operators.Add(new ExhaustiveTwoPointFiveMoveGenerator());
     50      Operators.Add(new StochasticTwoPointFiveMultiMoveGenerator());
     51      Operators.Add(new StochasticTwoPointFiveSingleMoveGenerator());
     52      Operators.Add(new TwoPointFiveMoveMaker());
     53      Operators.Add(new PTSPAnalyticalTwoPointFiveMoveEvaluator());
     54
     55      Operators.RemoveAll(x => x is SingleObjectiveMoveGenerator);
     56      Operators.RemoveAll(x => x is SingleObjectiveMoveMaker);
     57      Operators.RemoveAll(x => x is SingleObjectiveMoveEvaluator);
     58
     59      Encoding.ConfigureOperators(Operators.OfType<IOperator>());
     60      foreach (var twopointfiveMoveOperator in Operators.OfType<ITwoPointFiveMoveOperator>()) {
     61        twopointfiveMoveOperator.TwoPointFiveMoveParameter.ActualName = "Permutation.TwoPointFiveMove";
     62      }
    3963    }
    4064
     
    4468
    4569    public override double Evaluate(Permutation tour, IRandom random) {
     70      // abeham: Cache in local variable for performance reasons
     71      var distanceMatrix = DistanceMatrix;
     72      return Evaluate(tour, (a, b) => distanceMatrix[a, b], Probabilities);
     73    }
     74
     75    public static double Evaluate(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
    4676      // Analytical evaluation
    47       double firstSum = 0;
    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]];
    51           for (int k = i + 1; k < j; k++) {
    52             sum1 = sum1 * (1 - Probabilities[tour[k]]);
     77      var firstSum = 0.0;
     78      for (var i = 0; i < tour.Length - 1; i++) {
     79        for (var j = i + 1; j < tour.Length; j++) {
     80          var prod1 = distance(tour[i], tour[j]) * probabilities[tour[i]] * probabilities[tour[j]];
     81          for (var k = i + 1; k < j; k++) {
     82            prod1 = prod1 * (1 - probabilities[tour[k]]);
    5383          }
    54           firstSum += sum1;
     84          firstSum += prod1;
    5585        }
    5686      }
    57       double secondSum = 0;
    58       for (int j = 0; j < tour.Length - 1; j++) {
    59         for (int i = 0; i < j; i++) {
    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]]);
     87      var secondSum = 0.0;
     88      for (var j = 0; j < tour.Length; j++) {
     89        for (var i = 0; i < j; i++) {
     90          var prod2 = distance(tour[j], tour[i]) * probabilities[tour[i]] * probabilities[tour[j]];
     91          for (var k = j + 1; k < tour.Length; k++) {
     92            prod2 = prod2 * (1 - probabilities[tour[k]]);
    6393          }
    64           for (int k = 1; k < i; k++) {
    65             sum2 = sum2 * (1 - Probabilities[tour[k]]);
     94          for (var k = 0; k < i; k++) {
     95            prod2 = prod2 * (1 - probabilities[tour[k]]);
    6696          }
    67           secondSum += sum2;
     97          secondSum += prod2;
    6898        }
    6999      }
     
    72102
    73103    public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, DoubleArray probabilities) {
    74       // Analytical evaluation
    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]]);
    81           }
    82           firstSum += sum1;
    83         }
    84       }
    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]]);
    91           }
    92           for (var k = 0; k < i; k++) {
    93             sum2 = sum2 * (1 - probabilities[tour[k]]);
    94           }
    95           secondSum += sum2;
    96         }
    97       }
    98       return firstSum + secondSum;
     104      return Evaluate(tour, (a, b) => distanceMatrix[a, b], probabilities);
    99105    }
    100106  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/EstimatedPTSP.cs

    r13412 r13470  
    2626using HeuristicLab.Data;
    2727using HeuristicLab.Encodings.PermutationEncoding;
     28using HeuristicLab.Optimization;
    2829using HeuristicLab.Parameters;
    2930using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    7273      Operators.Add(new PTSPEstimatedInversionMoveEvaluator());
    7374      Operators.Add(new PTSPEstimatedInsertionMoveEvaluator());
    74       Operators.Add(new PTSPExhaustiveInversionLocalImprovement());
    75       Operators.Add(new PTSPExhaustiveInsertionLocalImprovement());
     75      Operators.Add(new PTSPEstimatedInversionLocalImprovement());
     76      Operators.Add(new PTSPEstimatedInsertionLocalImprovement());
     77      Operators.Add(new PTSPEstimatedTwoPointFiveLocalImprovement());
    7678
    7779      Operators.Add(new ExhaustiveTwoPointFiveMoveGenerator());
     
    7981      Operators.Add(new StochasticTwoPointFiveSingleMoveGenerator());
    8082      Operators.Add(new TwoPointFiveMoveMaker());
    81       Operators.Add(new PTSPTwoPointFiveMoveEvaluator());
     83      Operators.Add(new PTSPEstimatedTwoPointFiveMoveEvaluator());
     84
     85      Operators.RemoveAll(x => x is SingleObjectiveMoveGenerator);
     86      Operators.RemoveAll(x => x is SingleObjectiveMoveMaker);
     87      Operators.RemoveAll(x => x is SingleObjectiveMoveEvaluator);
    8288
    8389      Encoding.ConfigureOperators(Operators.OfType<IOperator>());
     
    8692      }
    8793
     94      UpdateRealizations();
    8895      RegisterEventHandlers();
    8996    }
     
    107114
    108115    public override double Evaluate(Permutation tour, IRandom random) {
    109       // Estimation-based evaluation
     116      // abeham: Cache parameters in local variables for performance reasons
     117      var realizations = Realizations;
     118      var realizationsSize = RealizationsSize;
     119      var useDistanceMatrix = UseDistanceMatrix;
     120      var distanceMatrix = DistanceMatrix;
     121      var distanceCalculator = DistanceCalculator;
     122      var coordinates = Coordinates;
     123
     124      // Estimation-based evaluation, here without calculating variance for faster evaluation
    110125      var estimatedSum = 0.0;
    111       for (var i = 0; i < Realizations.Count; i++) {
     126      for (var i = 0; i < realizations.Count; i++) {
    112127        int singleRealization = -1, firstNode = -1;
    113         for (var j = 0; j < Realizations[i].Length; j++) {
    114           if (Realizations[i][tour[j]]) {
     128        for (var j = 0; j < realizations[i].Length; j++) {
     129          if (realizations[i][tour[j]]) {
    115130            if (singleRealization != -1) {
    116               estimatedSum += GetDistance(singleRealization, tour[j]);
     131              estimatedSum += useDistanceMatrix ? distanceMatrix[singleRealization, tour[j]] : distanceCalculator.Calculate(singleRealization, tour[j], coordinates);
    117132            } else {
    118133              firstNode = tour[j];
     
    122137        }
    123138        if (singleRealization != -1) {
    124           estimatedSum += GetDistance(singleRealization, firstNode);
    125         }
    126       }
    127       return estimatedSum / RealizationsSize;
     139          estimatedSum += useDistanceMatrix ? distanceMatrix[singleRealization, firstNode] : distanceCalculator.Calculate(singleRealization, firstNode, coordinates);
     140        }
     141      }
     142      return estimatedSum / realizationsSize;
    128143    }
    129144
     
    134149    /// <param name="distanceMatrix">The distances between the cities.</param>
    135150    /// <param name="realizations">A sample of realizations of the stochastic instance</param>
     151    /// <param name="variance">The estimated variance will be returned in addition to the mean.</param>
    136152    /// <returns>A vector with length two containing mean and variance.</returns>
    137     public static double[] Evaluate(Permutation tour, DistanceMatrix distanceMatrix, ItemList<BoolArray> realizations) {
     153    public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, ItemList<BoolArray> realizations, out double variance) {
     154      return Evaluate(tour, (a, b) => distanceMatrix[a, b], realizations, out variance);
     155    }
     156
     157    /// <summary>
     158    /// An evaluate method that can be used if mean as well as variance should be calculated
     159    /// </summary>
     160    /// <param name="tour">The tour between all cities.</param>
     161    /// <param name="distance">A func that accepts the index of two cities and returns the distance as a double.</param>
     162    /// <param name="realizations">A sample of realizations of the stochastic instance</param>
     163    /// <param name="variance">The estimated variance will be returned in addition to the mean.</param>
     164    /// <returns>A vector with length two containing mean and variance.</returns>
     165    public static double Evaluate(Permutation tour, Func<int, int, double> distance, ItemList<BoolArray> realizations, out double variance) {
    138166      // Estimation-based evaluation
    139167      var estimatedSum = 0.0;
     
    145173          if (realizations[i][tour[j]]) {
    146174            if (singleRealization != -1) {
    147               partialSums[i] += distanceMatrix[singleRealization, tour[j]];
     175              partialSums[i] += distance(singleRealization, tour[j]);
    148176            } else {
    149177              firstNode = tour[j];
     
    153181        }
    154182        if (singleRealization != -1) {
    155           partialSums[i] += distanceMatrix[singleRealization, firstNode];
     183          partialSums[i] += distance(singleRealization, firstNode);
    156184        }
    157185        estimatedSum += partialSums[i];
    158186      }
    159187      var mean = estimatedSum / realizations.Count;
    160       var variance = 0.0;
     188      variance = 0.0;
    161189      for (var i = 0; i < realizations.Count; i++) {
    162190        variance += Math.Pow((partialSums[i] - mean), 2);
    163191      }
    164192      variance = variance / realizations.Count;
    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);
     193      return mean;
     194    }
     195
     196    public override void Load(PTSPData data) {
     197      base.Load(data);
     198      UpdateRealizations();
     199
     200      foreach (var op in Operators.OfType<IEstimatedPTSPOperator>()) {
     201        op.RealizationsParameter.ActualName = RealizationsParameter.Name;
     202      }
    171203    }
    172204
     
    177209        var newRealization = new BoolArray(Probabilities.Length);
    178210        var countOnes = 0;
    179         while (countOnes < 4) { // only generate realizations with at least 4 cities visited
     211        do {
    180212          countOnes = 0;
    181213          for (var j = 0; j < Probabilities.Length; j++) {
     
    183215            if (newRealization[j]) countOnes++;
    184216          }
    185         }
    186         Realizations.Add(newRealization);
     217          // only generate realizations with at least 4 cities visited
     218        } while (countOnes < 4 && Probabilities.Length > 3);
     219        realizations.Add(newRealization);
    187220      }
    188221      Realizations = realizations;
    189     }
    190 
    191     public override void Load(PTSPData data) {
    192       base.Load(data);
    193       UpdateRealizations();
    194 
    195       foreach (var op in Operators.OfType<IEstimatedPTSPOperator>()) {
    196         op.RealizationsParameter.ActualName = RealizationsParameter.Name;
    197       }
    198222    }
    199223  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/HeuristicLab.Problems.PTSP-3.3.csproj

    r13412 r13470  
    3636  <PropertyGroup>
    3737    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
     38  </PropertyGroup>
     39  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
     40    <DebugSymbols>true</DebugSymbols>
     41    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     42    <DefineConstants>DEBUG;TRACE</DefineConstants>
     43    <DebugType>full</DebugType>
     44    <PlatformTarget>x64</PlatformTarget>
     45    <ErrorReport>prompt</ErrorReport>
     46    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     47  </PropertyGroup>
     48  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
     49    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     50    <DefineConstants>TRACE</DefineConstants>
     51    <Optimize>true</Optimize>
     52    <DebugType>pdbonly</DebugType>
     53    <PlatformTarget>x64</PlatformTarget>
     54    <ErrorReport>prompt</ErrorReport>
     55    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     56  </PropertyGroup>
     57  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
     58    <DebugSymbols>true</DebugSymbols>
     59    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     60    <DefineConstants>DEBUG;TRACE</DefineConstants>
     61    <DebugType>full</DebugType>
     62    <PlatformTarget>x86</PlatformTarget>
     63    <ErrorReport>prompt</ErrorReport>
     64    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
     65  </PropertyGroup>
     66  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
     67    <OutputPath>..\..\..\..\trunk\sources\bin\</OutputPath>
     68    <DefineConstants>TRACE</DefineConstants>
     69    <Optimize>true</Optimize>
     70    <DebugType>pdbonly</DebugType>
     71    <PlatformTarget>x86</PlatformTarget>
     72    <ErrorReport>prompt</ErrorReport>
     73    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
    3874  </PropertyGroup>
    3975  <ItemGroup>
     
    123159    <Compile Include="DistanceMatrix.cs" />
    124160    <Compile Include="EstimatedPTSP.cs" />
    125     <Compile Include="Improvers\PTSPExhaustiveInsertionLocalImprovement.cs" />
    126     <Compile Include="Improvers\PTSPExhaustiveInversionLocalImprovement.cs" />
     161    <Compile Include="Improvers\PTSPAnalyticalInsertionLocalImprovement.cs" />
     162    <Compile Include="Improvers\PTSPAnalyticalTwoPointFiveLocalImprovement.cs" />
     163    <Compile Include="Improvers\PTSPEstimatedInsertionLocalImprovement.cs" />
     164    <Compile Include="Improvers\PTSPAnalyticalInversionLocalImprovement.cs" />
     165    <Compile Include="Improvers\PTSPEstimatedTwoPointFiveLocalImprovement.cs" />
     166    <Compile Include="Improvers\PTSPEstimatedInversionLocalImprovement.cs" />
     167    <Compile Include="Interfaces\IAnalyticalPTSPMoveEvaluator.cs" />
     168    <Compile Include="Interfaces\IAnalyticalPTSPOperator.cs" />
    127169    <Compile Include="Interfaces\IEstimatedPTSPOperator.cs" />
    128170    <Compile Include="Interfaces\ITwoPointFiveMoveOperator.cs" />
    129171    <Compile Include="Interfaces\IEstimatedPTSPMoveEvaluator.cs" />
     172    <Compile Include="Moves\AnalyticalPTSPMoveEvaluator.cs" />
     173    <Compile Include="Moves\OneShift\PTSPAnalyticalInsertionMoveEvaluator.cs" />
    130174    <Compile Include="Moves\OneShift\PTSPEstimatedInsertionMoveEvaluator.cs" />
    131175    <Compile Include="Moves\EstimatedPTSPMoveEvaluator.cs" />
     176    <Compile Include="Moves\TwoOpt\PTSPAnalyticalInversionMoveEvaluator.cs" />
    132177    <Compile Include="Moves\TwoOpt\PTSPEstimatedInversionMoveEvaluator.cs" />
    133     <Compile Include="Moves\TwoPointFiveOpt\PTSPTwoPointFiveMoveEvaluator.cs" />
     178    <Compile Include="Moves\TwoPointFiveOpt\PTSPAnalyticalTwoPointFiveMoveEvaluator.cs" />
     179    <Compile Include="Moves\TwoPointFiveOpt\PTSPEstimatedTwoPointFiveMoveEvaluator.cs" />
    134180    <Compile Include="Moves\TwoPointFiveOpt\ExhaustiveTwoPointFiveMoveGenerator.cs" />
    135181    <Compile Include="Moves\TwoPointFiveOpt\StochasticTwoPointFiveMultiMoveGenerator.cs" />
     
    158204set ProjectDir=$(ProjectDir)
    159205set SolutionDir=$(SolutionDir)
    160 set Outdir=$(Outdir)
    161206
    162207call PreBuildEvent.cmd</PreBuildEvent>
     208    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
     209      export ProjectDir=$(ProjectDir)
     210      export SolutionDir=$(SolutionDir)
     211
     212      $SolutionDir/PreBuildEvent.sh
     213    </PreBuildEvent>
    163214  </PropertyGroup>
    164215  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPAnalyticalInsertionLocalImprovement.cs

    r13451 r13470  
    3838  /// 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.
    3939  /// </remarks>
    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.")]
     40  [Item("PTSP Analytical Insertion Local Improvement", "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.")]
    4141  [StorableClass]
    42   public sealed class PTSPExhaustiveInsertionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
     42  public sealed class PTSPAnalyticalInsertionLocalImprovement : SingleSuccessorOperator, IAnalyticalPTSPOperator, ILocalImprovementOperator {
    4343
    4444    public ILookupParameter<IntValue> LocalIterationsParameter {
     
    7474    }
    7575
    76     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    77       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     76    public ILookupParameter<DoubleArray> ProbabilitiesParameter {
     77      get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
    7878    }
    7979
    8080    [StorableConstructor]
    81     private PTSPExhaustiveInsertionLocalImprovement(bool deserializing) : base(deserializing) { }
    82     private PTSPExhaustiveInsertionLocalImprovement(PTSPExhaustiveInsertionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
    83     public PTSPExhaustiveInsertionLocalImprovement()
     81    private PTSPAnalyticalInsertionLocalImprovement(bool deserializing) : base(deserializing) { }
     82    private PTSPAnalyticalInsertionLocalImprovement(PTSPAnalyticalInsertionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
     83    public PTSPAnalyticalInsertionLocalImprovement()
    8484      : base() {
    8585      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    9191      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    9292      Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
     93      Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities of the cities to appear."));
    9494    }
    9595
    9696    public override IDeepCloneable Clone(Cloner cloner) {
    97       return new PTSPExhaustiveInsertionLocalImprovement(this, cloner);
     97      return new PTSPAnalyticalInsertionLocalImprovement(this, cloner);
    9898    }
    9999
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) {
     100    public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
    101101      var distanceM = (DistanceMatrix)distances;
     102      Func<int, int, double> distance = (a, b) => distanceM[a, b];
    102103      for (var i = localIterations.Value; i < maxIterations; i++) {
    103104        TranslocationMove bestMove = null;
    104         double bestQuality = 0; // we have to make an improvement, so 0 is the baseline
    105         double evaluations = 0.0;
     105        var bestQuality = quality.Value; // we have to make an improvement, so current quality is the baseline
     106        var evaluations = 0.0;
    106107        foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
    107           double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);
    108           int min = Math.Min(move.Index1, move.Index3);
    109           int max = Math.Max(move.Index2, move.Index3 + (move.Index2 - move.Index1));
    110           evaluations += 2.0 * (max - min + 1) / assignment.Length
    111             + 4.0 * (assignment.Length - (max - min + 1)) / assignment.Length;
     108          var moveQuality = PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
     109          evaluations++;
    112110          if (maximization && moveQuality > bestQuality
    113111            || !maximization && moveQuality < bestQuality) {
     
    119117        if (bestMove == null) break;
    120118        TranslocationManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2, bestMove.Index3);
    121         quality.Value += bestQuality;
     119        quality.Value = bestQuality;
    122120        localIterations.Value++;
    123121        cancellation.ThrowIfCancellationRequested();
     
    133131      var localIterations = LocalIterationsParameter.ActualValue;
    134132      var evaluations = EvaluatedSolutionsParameter.ActualValue;
    135       var realizations = RealizationsParameter.ActualValue;
     133      var probabilities = ProbabilitiesParameter.ActualValue;
    136134      if (localIterations == null) {
    137135        localIterations = new IntValue(0);
     
    139137      }
    140138
    141       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken, realizations);
     139      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, probabilities, CancellationToken);
    142140
    143141      localIterations.Value = 0;
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPAnalyticalInversionLocalImprovement.cs

    r13451 r13470  
    3838  /// The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.
    3939  /// </remarks>
    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.")]
     40  [Item("PTSP Analytical Inversion Local Improvement", "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.")]
    4141  [StorableClass]
    42   public sealed class PTSPExhaustiveInversionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
     42  public sealed class PTSPAnalyticalInversionLocalImprovement : SingleSuccessorOperator, IAnalyticalPTSPOperator, ILocalImprovementOperator {
    4343
    4444    public ILookupParameter<IntValue> LocalIterationsParameter {
     
    7474    }
    7575
    76     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    77       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     76    public ILookupParameter<DoubleArray> ProbabilitiesParameter {
     77      get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
    7878    }
    7979
    8080    [StorableConstructor]
    81     private PTSPExhaustiveInversionLocalImprovement(bool deserializing) : base(deserializing) { }
    82     private PTSPExhaustiveInversionLocalImprovement(PTSPExhaustiveInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
    83     public PTSPExhaustiveInversionLocalImprovement()
     81    private PTSPAnalyticalInversionLocalImprovement(bool deserializing) : base(deserializing) { }
     82    private PTSPAnalyticalInversionLocalImprovement(PTSPAnalyticalInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
     83    public PTSPAnalyticalInversionLocalImprovement()
    8484      : base() {
    8585      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    9191      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    9292      Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
     93      Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities of the cities to appear."));
    9494    }
    9595
    9696    public override IDeepCloneable Clone(Cloner cloner) {
    97       return new PTSPExhaustiveInversionLocalImprovement(this, cloner);
     97      return new PTSPAnalyticalInversionLocalImprovement(this, cloner);
    9898    }
    9999
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) {
     100    public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
    101101      var distanceM = (DistanceMatrix)distances;
     102      Func<int, int, double> distance = (a, b) => distanceM[a, b];
    102103      for (var i = localIterations.Value; i < maxIterations; i++) {
    103104        InversionMove bestMove = null;
    104         double bestQuality = 0; // we have to make an improvement, so 0 is the baseline
    105         double evaluations = 0.0;
     105        var bestQuality = quality.Value; // we have to make an improvement, so current quality is the baseline
     106        var evaluations = 0.0;
    106107        foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
    107           double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);
    108           evaluations += 2 * (move.Index2 - move.Index1 + 1) / (double)assignment.Length;
     108          var moveQuality = PTSPAnalyticalInversionMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
     109          evaluations++;
    109110          if (maximization && moveQuality > bestQuality
    110111            || !maximization && moveQuality < bestQuality) {
     
    116117        if (bestMove == null) break;
    117118        InversionManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2);
    118         quality.Value += bestQuality;
     119        quality.Value = bestQuality;
    119120        localIterations.Value++;
    120121        cancellation.ThrowIfCancellationRequested();
     
    130131      var localIterations = LocalIterationsParameter.ActualValue;
    131132      var evaluations = EvaluatedSolutionsParameter.ActualValue;
    132       var realizations = RealizationsParameter.ActualValue;
     133      var probabilities = ProbabilitiesParameter.ActualValue;
    133134      if (localIterations == null) {
    134135        localIterations = new IntValue(0);
     
    136137      }
    137138
    138       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken, realizations);
     139      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, probabilities, CancellationToken);
    139140
    140141      localIterations.Value = 0;
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPAnalyticalTwoPointFiveLocalImprovement.cs

    r13451 r13470  
    3838  /// The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.
    3939  /// </remarks>
    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.")]
     40  [Item("PTSP Analytical 2.5 Local Improvement", "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.")]
    4141  [StorableClass]
    42   public sealed class PTSPExhaustiveInversionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
     42  public sealed class PTSPAnalyticalTwoPointFiveLocalImprovement : SingleSuccessorOperator, IAnalyticalPTSPOperator, ILocalImprovementOperator {
    4343
    4444    public ILookupParameter<IntValue> LocalIterationsParameter {
     
    7474    }
    7575
    76     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    77       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     76    public ILookupParameter<DoubleArray> ProbabilitiesParameter {
     77      get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
    7878    }
    7979
    8080    [StorableConstructor]
    81     private PTSPExhaustiveInversionLocalImprovement(bool deserializing) : base(deserializing) { }
    82     private PTSPExhaustiveInversionLocalImprovement(PTSPExhaustiveInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
    83     public PTSPExhaustiveInversionLocalImprovement()
     81    private PTSPAnalyticalTwoPointFiveLocalImprovement(bool deserializing) : base(deserializing) { }
     82    private PTSPAnalyticalTwoPointFiveLocalImprovement(PTSPAnalyticalTwoPointFiveLocalImprovement original, Cloner cloner) : base(original, cloner) { }
     83    public PTSPAnalyticalTwoPointFiveLocalImprovement()
    8484      : base() {
    8585      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    9191      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    9292      Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
     93      Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities of the cities to appear."));
    9494    }
    9595
    9696    public override IDeepCloneable Clone(Cloner cloner) {
    97       return new PTSPExhaustiveInversionLocalImprovement(this, cloner);
     97      return new PTSPAnalyticalTwoPointFiveLocalImprovement(this, cloner);
    9898    }
    9999
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) {
     100    public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
    101101      var distanceM = (DistanceMatrix)distances;
     102      Func<int, int, double> distance = (a, b) => distanceM[a, b];
    102103      for (var i = localIterations.Value; i < maxIterations; i++) {
    103         InversionMove bestMove = null;
    104         double bestQuality = 0; // we have to make an improvement, so 0 is the baseline
    105         double evaluations = 0.0;
    106         foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
    107           double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);
    108           evaluations += 2 * (move.Index2 - move.Index1 + 1) / (double)assignment.Length;
     104        TwoPointFiveMove bestMove = null;
     105        var bestQuality = quality.Value; // we have to make an improvement, so current quality is the baseline
     106        var evaluations = 0.0;
     107        foreach (var move in ExhaustiveTwoPointFiveMoveGenerator.Generate(assignment)) {
     108          var moveQuality = PTSPAnalyticalTwoPointFiveMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
     109          evaluations++;
    109110          if (maximization && moveQuality > bestQuality
    110111            || !maximization && moveQuality < bestQuality) {
     
    115116        evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
    116117        if (bestMove == null) break;
    117         InversionManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2);
    118         quality.Value += bestQuality;
     118        TwoPointFiveMoveMaker.Apply(assignment, bestMove);
     119        quality.Value = bestQuality;
    119120        localIterations.Value++;
    120121        cancellation.ThrowIfCancellationRequested();
     
    130131      var localIterations = LocalIterationsParameter.ActualValue;
    131132      var evaluations = EvaluatedSolutionsParameter.ActualValue;
    132       var realizations = RealizationsParameter.ActualValue;
     133      var probabilities = ProbabilitiesParameter.ActualValue;
    133134      if (localIterations == null) {
    134135        localIterations = new IntValue(0);
     
    136137      }
    137138
    138       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken, realizations);
     139      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, probabilities, CancellationToken);
    139140
    140141      localIterations.Value = 0;
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPEstimatedInsertionLocalImprovement.cs

    r13469 r13470  
    3838  /// 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.
    3939  /// </remarks>
    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.")]
     40  [Item("PTSP Estimated Insertion Local Improvement", "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.")]
    4141  [StorableClass]
    42   public sealed class PTSPExhaustiveInsertionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
     42  public sealed class PTSPEstimatedInsertionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
    4343
    4444    public ILookupParameter<IntValue> LocalIterationsParameter {
     
    7979
    8080    [StorableConstructor]
    81     private PTSPExhaustiveInsertionLocalImprovement(bool deserializing) : base(deserializing) { }
    82     private PTSPExhaustiveInsertionLocalImprovement(PTSPExhaustiveInsertionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
    83     public PTSPExhaustiveInsertionLocalImprovement()
     81    private PTSPEstimatedInsertionLocalImprovement(bool deserializing) : base(deserializing) { }
     82    private PTSPEstimatedInsertionLocalImprovement(PTSPEstimatedInsertionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
     83    public PTSPEstimatedInsertionLocalImprovement()
    8484      : base() {
    8585      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    9595
    9696    public override IDeepCloneable Clone(Cloner cloner) {
    97       return new PTSPExhaustiveInsertionLocalImprovement(this, cloner);
     97      return new PTSPEstimatedInsertionLocalImprovement(this, cloner);
    9898    }
    9999
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) {
     100    public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
    101101      var distanceM = (DistanceMatrix)distances;
     102      Func<int, int, double> distance = (a, b) => distanceM[a, b];
    102103      for (var i = localIterations.Value; i < maxIterations; i++) {
    103104        TranslocationMove bestMove = null;
     
    105106        double evaluations = 0.0;
    106107        foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
    107           double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);
    108           int min = Math.Min(move.Index1, move.Index3);
    109           int max = Math.Max(move.Index2, move.Index3 + (move.Index2 - move.Index1));
    110           evaluations += 2.0 * (max - min + 1) / assignment.Length
    111             + 4.0 * (assignment.Length - (max - min + 1)) / assignment.Length;
     108          double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
     109          evaluations += realizations.Count * 6.0 / (assignment.Length * assignment.Length);
    112110          if (maximization && moveQuality > bestQuality
    113111            || !maximization && moveQuality < bestQuality) {
     
    139137      }
    140138
    141       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken, realizations);
     139      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
    142140
    143141      localIterations.Value = 0;
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPEstimatedInversionLocalImprovement.cs

    r13469 r13470  
    3838  /// The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.
    3939  /// </remarks>
    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.")]
     40  [Item("PTSP Estimated Inversion Local Improvement", "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.")]
    4141  [StorableClass]
    42   public sealed class PTSPExhaustiveInversionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
     42  public sealed class PTSPEstimatedInversionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
    4343
    4444    public ILookupParameter<IntValue> LocalIterationsParameter {
     
    7979
    8080    [StorableConstructor]
    81     private PTSPExhaustiveInversionLocalImprovement(bool deserializing) : base(deserializing) { }
    82     private PTSPExhaustiveInversionLocalImprovement(PTSPExhaustiveInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
    83     public PTSPExhaustiveInversionLocalImprovement()
     81    private PTSPEstimatedInversionLocalImprovement(bool deserializing) : base(deserializing) { }
     82    private PTSPEstimatedInversionLocalImprovement(PTSPEstimatedInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
     83    public PTSPEstimatedInversionLocalImprovement()
    8484      : base() {
    8585      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    9595
    9696    public override IDeepCloneable Clone(Cloner cloner) {
    97       return new PTSPExhaustiveInversionLocalImprovement(this, cloner);
     97      return new PTSPEstimatedInversionLocalImprovement(this, cloner);
    9898    }
    9999
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) {
     100    public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
    101101      var distanceM = (DistanceMatrix)distances;
     102      Func<int, int, double> distance = (a, b) => distanceM[a, b];
    102103      for (var i = localIterations.Value; i < maxIterations; i++) {
    103104        InversionMove bestMove = null;
     
    105106        double evaluations = 0.0;
    106107        foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
    107           double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);
    108           evaluations += 2 * (move.Index2 - move.Index1 + 1) / (double)assignment.Length;
     108          double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
     109          evaluations += realizations.Count * 4.0 / (assignment.Length * assignment.Length);
    109110          if (maximization && moveQuality > bestQuality
    110111            || !maximization && moveQuality < bestQuality) {
     
    136137      }
    137138
    138       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken, realizations);
     139      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
    139140
    140141      localIterations.Value = 0;
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPEstimatedTwoPointFiveLocalImprovement.cs

    r13451 r13470  
    3838  /// The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.
    3939  /// </remarks>
    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.")]
     40  [Item("PTSP Estimated 2.5 Local Improvement", "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.")]
    4141  [StorableClass]
    42   public sealed class PTSPExhaustiveInversionLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
     42  public sealed class PTSPEstimatedTwoPointFiveLocalImprovement : SingleSuccessorOperator, IEstimatedPTSPOperator, ILocalImprovementOperator {
    4343
    4444    public ILookupParameter<IntValue> LocalIterationsParameter {
     
    7979
    8080    [StorableConstructor]
    81     private PTSPExhaustiveInversionLocalImprovement(bool deserializing) : base(deserializing) { }
    82     private PTSPExhaustiveInversionLocalImprovement(PTSPExhaustiveInversionLocalImprovement original, Cloner cloner) : base(original, cloner) { }
    83     public PTSPExhaustiveInversionLocalImprovement()
     81    private PTSPEstimatedTwoPointFiveLocalImprovement(bool deserializing) : base(deserializing) { }
     82    private PTSPEstimatedTwoPointFiveLocalImprovement(PTSPEstimatedTwoPointFiveLocalImprovement original, Cloner cloner) : base(original, cloner) { }
     83    public PTSPEstimatedTwoPointFiveLocalImprovement()
    8484      : base() {
    8585      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    9595
    9696    public override IDeepCloneable Clone(Cloner cloner) {
    97       return new PTSPExhaustiveInversionLocalImprovement(this, cloner);
     97      return new PTSPEstimatedTwoPointFiveLocalImprovement(this, cloner);
    9898    }
    9999
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation, ItemList<BoolArray> realizations) {
     100    public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
    101101      var distanceM = (DistanceMatrix)distances;
     102      Func<int, int, double> distance = (a, b) => distanceM[a, b];
    102103      for (var i = localIterations.Value; i < maxIterations; i++) {
    103         InversionMove bestMove = null;
    104         double bestQuality = 0; // we have to make an improvement, so 0 is the baseline
    105         double evaluations = 0.0;
    106         foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
    107           double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateByDistanceMatrix(assignment, move, distanceM, realizations);
    108           evaluations += 2 * (move.Index2 - move.Index1 + 1) / (double)assignment.Length;
     104        TwoPointFiveMove bestMove = null;
     105        var bestQuality = 0.0; // we have to make an improvement, so 0 is the baseline
     106        var evaluations = 0.0;
     107        foreach (var move in ExhaustiveTwoPointFiveMoveGenerator.Generate(assignment)) {
     108          var moveQuality = PTSPEstimatedTwoPointFiveMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
     109          if (move.IsInvert) evaluations += realizations.Count * 4.0 / (assignment.Length * assignment.Length);
     110          else evaluations += realizations.Count * 6.0 / (assignment.Length * assignment.Length);
    109111          if (maximization && moveQuality > bestQuality
    110112            || !maximization && moveQuality < bestQuality) {
     
    115117        evaluatedSolutions.Value += (int)Math.Ceiling(evaluations);
    116118        if (bestMove == null) break;
    117         InversionManipulator.Apply(assignment, bestMove.Index1, bestMove.Index2);
     119        TwoPointFiveMoveMaker.Apply(assignment, bestMove);
    118120        quality.Value += bestQuality;
    119121        localIterations.Value++;
     
    136138      }
    137139
    138       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken, realizations);
     140      Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
    139141
    140142      localIterations.Value = 0;
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Interfaces/IAnalyticalPTSPMoveEvaluator.cs

    r13451 r13470  
    2626
    2727namespace HeuristicLab.Problems.PTSP {
    28   public interface IEstimatedPTSPMoveEvaluator : IEstimatedPTSPOperator, ISingleObjectiveMoveEvaluator, IPermutationMoveOperator {
     28  public interface IAnalyticalPTSPMoveEvaluator : IAnalyticalPTSPOperator, ISingleObjectiveMoveEvaluator, IPermutationMoveOperator {
    2929    ILookupParameter<DoubleMatrix> CoordinatesParameter { get; }
     30    ILookupParameter<DistanceCalculator> DistanceCalculatorParameter { get; }
    3031    ILookupParameter<DistanceMatrix> DistanceMatrixParameter { get; }
    3132    ILookupParameter<BoolValue> UseDistanceMatrixParameter { get; }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Interfaces/IAnalyticalPTSPOperator.cs

    r13451 r13470  
    2424
    2525namespace HeuristicLab.Problems.PTSP {
    26   public interface IEstimatedPTSPOperator : IItem {
    27     ILookupParameter<ItemList<BoolArray>> RealizationsParameter { get; }
     26  public interface IAnalyticalPTSPOperator : IItem {
     27    ILookupParameter<DoubleArray> ProbabilitiesParameter { get; }
    2828  }
    2929}
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Interfaces/IEstimatedPTSPMoveEvaluator.cs

    r13412 r13470  
    2828  public interface IEstimatedPTSPMoveEvaluator : IEstimatedPTSPOperator, ISingleObjectiveMoveEvaluator, IPermutationMoveOperator {
    2929    ILookupParameter<DoubleMatrix> CoordinatesParameter { get; }
     30    ILookupParameter<DistanceCalculator> DistanceCalculatorParameter { get; }
    3031    ILookupParameter<DistanceMatrix> DistanceMatrixParameter { get; }
    3132    ILookupParameter<BoolValue> UseDistanceMatrixParameter { get; }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/AnalyticalPTSPMoveEvaluator.cs

    r13451 r13470  
    3030
    3131namespace HeuristicLab.Problems.PTSP {
    32   [Item("EstimatedPTSPMoveEvaluator", "A base class for operators which evaluate TSP moves.")]
     32  [Item("AnalyticalPTSPMoveEvaluator", "A base class for operators which evaluate PTSP moves.")]
    3333  [StorableClass]
    34   public abstract class EstimatedPTSPMoveEvaluator : SingleSuccessorOperator, IEstimatedPTSPMoveEvaluator {
     34  public abstract class AnalyticalPTSPMoveEvaluator : SingleSuccessorOperator, IAnalyticalPTSPMoveEvaluator {
    3535
    3636    public override bool CanChangeName {
     
    5050      get { return (ILookupParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
    5151    }
    52     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    53       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     52    public ILookupParameter<DoubleArray> ProbabilitiesParameter {
     53      get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
    5454    }
    5555    public ILookupParameter<DoubleValue> QualityParameter {
     
    6464
    6565    [StorableConstructor]
    66     protected EstimatedPTSPMoveEvaluator(bool deserializing) : base(deserializing) { }
    67     protected EstimatedPTSPMoveEvaluator(EstimatedPTSPMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
    68     protected EstimatedPTSPMoveEvaluator()
     66    protected AnalyticalPTSPMoveEvaluator(bool deserializing) : base(deserializing) { }
     67    protected AnalyticalPTSPMoveEvaluator(AnalyticalPTSPMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
     68    protected AnalyticalPTSPMoveEvaluator()
    6969      : base() {
    7070      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
     
    7272      Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    7373      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."));
    74       Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
     74      Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities for each city to appear."));
    7575      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of a TSP solution."));
    7676      Parameters.Add(new LookupParameter<DoubleValue>("MoveQuality", "The evaluated quality of a move on a TSP solution."));
     
    8181      var permutation = PermutationParameter.ActualValue;
    8282      var coordinates = CoordinatesParameter.ActualValue;
    83       double relativeQualityDifference = 0;
     83      var probabilities = ProbabilitiesParameter.ActualValue;
     84      Func<int, int, double> distance = null;
    8485      if (UseDistanceMatrixParameter.ActualValue.Value) {
    8586        var distanceMatrix = DistanceMatrixParameter.ActualValue;
    8687        if (distanceMatrix == null) throw new InvalidOperationException("The distance matrix has not been calculated.");
    87         relativeQualityDifference = EvaluateByDistanceMatrix(permutation, distanceMatrix);
     88        distance = (a, b) => distanceMatrix[a, b];
    8889      } else {
    8990        if (coordinates == null) throw new InvalidOperationException("No coordinates were given.");
    9091        var distanceCalculator = DistanceCalculatorParameter.ActualValue;
    9192        if (distanceCalculator == null) throw new InvalidOperationException("Distance calculator is null!");
    92         relativeQualityDifference = EvaluateByCoordinates(permutation, coordinates, distanceCalculator);
     93        distance = (a, b) => distanceCalculator.Calculate(a, b, coordinates);
    9394      }
     95      // here moves are not delta-evaluated
     96      var newQuality = EvaluateMove(permutation, distance, probabilities);
    9497      var moveQuality = MoveQualityParameter.ActualValue;
    95       if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(QualityParameter.ActualValue.Value + relativeQualityDifference);
    96       else moveQuality.Value = QualityParameter.ActualValue.Value + relativeQualityDifference;
     98      if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(newQuality);
     99      else moveQuality.Value = newQuality;
     100
    97101      return base.Apply();
    98102    }
    99103
    100     protected abstract double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix);
    101     protected abstract double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator);
     104    protected abstract double EvaluateMove(Permutation permutation, Func<int, int, double> distance, DoubleArray probabilities);
    102105  }
    103106}
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/EstimatedPTSPMoveEvaluator.cs

    r13412 r13470  
    3030
    3131namespace HeuristicLab.Problems.PTSP {
    32   [Item("EstimatedPTSPMoveEvaluator", "A base class for operators which evaluate TSP moves.")]
     32  [Item("EstimatedPTSPMoveEvaluator", "A base class for operators which evaluate PTSP moves.")]
    3333  [StorableClass]
    3434  public abstract class EstimatedPTSPMoveEvaluator : SingleSuccessorOperator, IEstimatedPTSPMoveEvaluator {
     
    8181      var permutation = PermutationParameter.ActualValue;
    8282      var coordinates = CoordinatesParameter.ActualValue;
    83       double relativeQualityDifference = 0;
     83      var realizations = RealizationsParameter.ActualValue;
     84      Func<int, int, double> distance = null;
    8485      if (UseDistanceMatrixParameter.ActualValue.Value) {
    8586        var distanceMatrix = DistanceMatrixParameter.ActualValue;
    8687        if (distanceMatrix == null) throw new InvalidOperationException("The distance matrix has not been calculated.");
    87         relativeQualityDifference = EvaluateByDistanceMatrix(permutation, distanceMatrix);
     88        distance = (a, b) => distanceMatrix[a, b];
    8889      } else {
    8990        if (coordinates == null) throw new InvalidOperationException("No coordinates were given.");
    9091        var distanceCalculator = DistanceCalculatorParameter.ActualValue;
    9192        if (distanceCalculator == null) throw new InvalidOperationException("Distance calculator is null!");
    92         relativeQualityDifference = EvaluateByCoordinates(permutation, coordinates, distanceCalculator);
     93        distance = (a, b) => distanceCalculator.Calculate(a, b, coordinates);
    9394      }
     95      var relativeQualityDifference = EvaluateMove(permutation, distance, realizations);
    9496      var moveQuality = MoveQualityParameter.ActualValue;
    9597      if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(QualityParameter.ActualValue.Value + relativeQualityDifference);
     
    98100    }
    99101
    100     protected abstract double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix);
    101     protected abstract double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator);
     102    protected abstract double EvaluateMove(Permutation permutation, Func<int, int, double> distance, ItemList<BoolArray> realizations);
    102103  }
    103104}
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/OneShift/PTSPAnalyticalInsertionMoveEvaluator.cs

    r13451 r13470  
    2929
    3030namespace HeuristicLab.Problems.PTSP {
    31   [Item("PTSPEstimatedInsertionMoveEvaluator", "Evaluates an insertion move (1-shift)")]
     31  [Item("PTSP Analytical Insertion Move Evaluator", "Evaluates an insertion move (1-shift) by a full solution evaluation")]
    3232  [StorableClass]
    33   public class PTSPEstimatedInsertionMoveEvaluator : EstimatedPTSPMoveEvaluator, IPermutationTranslocationMoveOperator {
     33  public class PTSPAnalyticalInsertionMoveEvaluator : AnalyticalPTSPMoveEvaluator, IPermutationTranslocationMoveOperator {
    3434
    3535    public ILookupParameter<TranslocationMove> TranslocationMoveParameter {
     
    3838
    3939    [StorableConstructor]
    40     protected PTSPEstimatedInsertionMoveEvaluator(bool deserializing) : base(deserializing) { }
    41     protected PTSPEstimatedInsertionMoveEvaluator(PTSPEstimatedInsertionMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
    42     public PTSPEstimatedInsertionMoveEvaluator()
     40    protected PTSPAnalyticalInsertionMoveEvaluator(bool deserializing) : base(deserializing) { }
     41    protected PTSPAnalyticalInsertionMoveEvaluator(PTSPAnalyticalInsertionMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
     42    public PTSPAnalyticalInsertionMoveEvaluator()
    4343      : base() {
    4444      Parameters.Add(new LookupParameter<TranslocationMove>("TranslocationMove", "The move to evaluate."));
     
    4646
    4747    public override IDeepCloneable Clone(Cloner cloner) {
    48       return new PTSPEstimatedInsertionMoveEvaluator(this, cloner);
     48      return new PTSPAnalyticalInsertionMoveEvaluator(this, cloner);
    4949    }
    5050
    51     public static double EvaluateByCoordinates(Permutation permutation, TranslocationMove move, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, ItemList<BoolArray> realizations) {
    52       var afterMove = new Permutation(PermutationTypes.RelativeUndirected, permutation);
     51    public static double EvaluateMove(Permutation tour, TranslocationMove move, Func<int, int, double> distance, DoubleArray probabilities) {
     52      var afterMove = (Permutation)tour.Clone();
    5353      TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3);
    54       double moveQuality = 0;
    55       var edges = new int[12];
    56       var indices = new int[12];
    57       edges[0] = permutation.GetCircular(move.Index1 - 1);
    58       indices[0] = DecreaseCircularIndex(permutation.Length, move.Index1);
    59       edges[1] = permutation[move.Index1];
    60       indices[1] = move.Index1;
    61       edges[2] = permutation[move.Index1];
    62       indices[2] = move.Index1;
    63       edges[3] = permutation.GetCircular(move.Index1 + 1);
    64       indices[3] = IncreaseCircularIndex(permutation.Length, move.Index1);
    65 
    66       edges[6] = afterMove.GetCircular(move.Index3 - 1);
    67       indices[6] = DecreaseCircularIndex(afterMove.Length, move.Index3);
    68       edges[7] = afterMove[move.Index3];
    69       indices[7] = move.Index3;
    70       edges[8] = afterMove[move.Index3];
    71       indices[8] = move.Index3;
    72       edges[9] = afterMove.GetCircular(move.Index3 + 1);
    73       indices[9] = IncreaseCircularIndex(afterMove.Length, move.Index3);
    74 
    75       if (move.Index3 > move.Index1) {
    76         edges[4] = permutation[move.Index3];
    77         indices[4] = move.Index3;
    78         edges[5] = permutation.GetCircular(move.Index3 + 1);
    79         indices[5] = indices[9];
    80         edges[10] = afterMove.GetCircular(move.Index1 - 1);
    81         indices[10] = indices[0];
    82         edges[11] = afterMove[move.Index1];
    83         indices[11] = move.Index1;
    84       } else {
    85         edges[4] = permutation.GetCircular(move.Index3 - 1);
    86         indices[4] = indices[6];
    87         edges[5] = permutation[move.Index3];
    88         indices[5] = move.Index3;
    89         edges[10] = afterMove[move.Index1];
    90         indices[10] = move.Index1;
    91         edges[11] = afterMove.GetCircular(move.Index1 + 1);
    92         indices[11] = indices[3];
    93       }
    94       int[] aPosteriori = new int[12];
    95       foreach (var realization in realizations) {
    96         for (int i = 0; i < edges.Length; i++) {
    97           Permutation tempPermutation;
    98           if (i < 6) {
    99             tempPermutation = permutation;
    100           } else {
    101             tempPermutation = afterMove;
    102           }
    103           if (realization[edges[i]]) {
    104             aPosteriori[i] = edges[i];
    105           } else {
    106             int j = 1;
    107             if (i % 2 == 0) {
    108               // find nearest predecessor in realization if source edge
    109               while (!realization[tempPermutation.GetCircular(indices[i] - j)]) {
    110                 j++;
    111               }
    112               aPosteriori[i] = tempPermutation.GetCircular(indices[i] - j);
    113             } else {
    114               // find nearest successor in realization if target edge
    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;
     54      return AnalyticalProbabilisticTravelingSalesmanProblem.Evaluate(afterMove, distance, probabilities);
    13855    }
    13956
    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)]) {
    205                 j++;
    206               }
    207               aPosteriori[i] = tempPermutation.GetCircular(indices[i] + j);
    208             }
    209           }
    210         }
    211         if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3]) &&
    212           !(aPosteriori[0] == aPosteriori[4] && aPosteriori[1] == aPosteriori[5]) &&
    213           !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5])) {
    214           // compute cost difference between the two a posteriori solutions
    215           moveQuality = moveQuality + distanceMatrix[aPosteriori[6], aPosteriori[7]] + distanceMatrix[aPosteriori[8], aPosteriori[9]] + distanceMatrix[aPosteriori[10], aPosteriori[11]];
    216           moveQuality = moveQuality - distanceMatrix[aPosteriori[0], aPosteriori[1]] - distanceMatrix[aPosteriori[2], aPosteriori[3]] - distanceMatrix[aPosteriori[4], aPosteriori[5]];
    217         }
    218         Array.Clear(aPosteriori, 0, aPosteriori.Length);
    219       }
    220       // return average of cost differences
    221       return moveQuality / realizations.Count;
    222     }
    223 
    224     private static int DecreaseCircularIndex(int length, int index) {
    225       var result = index - 1;
    226       if (result == -1) {
    227         result = length - 1;
    228       }
    229       return result;
    230     }
    231 
    232     private static int IncreaseCircularIndex(int length, int index) {
    233       var result = index + 1;
    234       if (result == length + 1) {
    235         result = 0;
    236       }
    237       return result;
    238     }
    239 
    240     protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) {
    241       return EvaluateByCoordinates(permutation, TranslocationMoveParameter.ActualValue, coordinates, distanceCalculator, RealizationsParameter.ActualValue);
    242     }
    243 
    244     protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) {
    245       return EvaluateByDistanceMatrix(permutation, TranslocationMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.ActualValue);
     57    protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
     58      return EvaluateMove(tour, TranslocationMoveParameter.ActualValue, distance, probabilities);
    24659    }
    24760  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/OneShift/PTSPEstimatedInsertionMoveEvaluator.cs

    r13412 r13470  
    2929
    3030namespace HeuristicLab.Problems.PTSP {
    31   [Item("PTSPEstimatedInsertionMoveEvaluator", "Evaluates an insertion move (1-shift)")]
     31  [Item("PTSP Estimated Insertion Move Evaluator", "Evaluates an insertion move (1-shift)")]
    3232  [StorableClass]
    3333  public class PTSPEstimatedInsertionMoveEvaluator : EstimatedPTSPMoveEvaluator, IPermutationTranslocationMoveOperator {
     
    4949    }
    5050
    51     public static double EvaluateByCoordinates(Permutation permutation, TranslocationMove move, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, ItemList<BoolArray> realizations) {
    52       var afterMove = new Permutation(PermutationTypes.RelativeUndirected, permutation);
     51    public static double EvaluateMove(Permutation tour, TranslocationMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     52      var afterMove = (Permutation)tour.Clone();
    5353      TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3);
    5454      double moveQuality = 0;
    5555      var edges = new int[12];
    5656      var indices = new int[12];
    57       edges[0] = permutation.GetCircular(move.Index1 - 1);
    58       indices[0] = DecreaseCircularIndex(permutation.Length, move.Index1);
    59       edges[1] = permutation[move.Index1];
     57      edges[0] = tour.GetCircular(move.Index1 - 1);
     58      indices[0] = DecreaseCircularIndex(tour.Length, move.Index1);
     59      edges[1] = tour[move.Index1];
    6060      indices[1] = move.Index1;
    61       edges[2] = permutation[move.Index1];
     61      edges[2] = tour[move.Index1];
    6262      indices[2] = move.Index1;
    63       edges[3] = permutation.GetCircular(move.Index1 + 1);
    64       indices[3] = IncreaseCircularIndex(permutation.Length, move.Index1);
     63      edges[3] = tour.GetCircular(move.Index1 + 1);
     64      indices[3] = IncreaseCircularIndex(tour.Length, move.Index1);
    6565
    6666      edges[6] = afterMove.GetCircular(move.Index3 - 1);
     
    7474
    7575      if (move.Index3 > move.Index1) {
    76         edges[4] = permutation[move.Index3];
     76        edges[4] = tour[move.Index3];
    7777        indices[4] = move.Index3;
    78         edges[5] = permutation.GetCircular(move.Index3 + 1);
     78        edges[5] = tour.GetCircular(move.Index3 + 1);
    7979        indices[5] = indices[9];
    8080        edges[10] = afterMove.GetCircular(move.Index1 - 1);
     
    8383        indices[11] = move.Index1;
    8484      } else {
    85         edges[4] = permutation.GetCircular(move.Index3 - 1);
     85        edges[4] = tour.GetCircular(move.Index3 - 1);
    8686        indices[4] = indices[6];
    87         edges[5] = permutation[move.Index3];
     87        edges[5] = tour[move.Index3];
    8888        indices[5] = move.Index3;
    8989        edges[10] = afterMove[move.Index1];
     
    9797          Permutation tempPermutation;
    9898          if (i < 6) {
    99             tempPermutation = permutation;
     99            tempPermutation = tour;
    100100          } else {
    101101            tempPermutation = afterMove;
     
    124124          !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5])) {
    125125          // 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)]) {
    205                 j++;
    206               }
    207               aPosteriori[i] = tempPermutation.GetCircular(indices[i] + j);
    208             }
    209           }
    210         }
    211         if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3]) &&
    212           !(aPosteriori[0] == aPosteriori[4] && aPosteriori[1] == aPosteriori[5]) &&
    213           !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5])) {
    214           // compute cost difference between the two a posteriori solutions
    215           moveQuality = moveQuality + distanceMatrix[aPosteriori[6], aPosteriori[7]] + distanceMatrix[aPosteriori[8], aPosteriori[9]] + distanceMatrix[aPosteriori[10], aPosteriori[11]];
    216           moveQuality = moveQuality - distanceMatrix[aPosteriori[0], aPosteriori[1]] - distanceMatrix[aPosteriori[2], aPosteriori[3]] - distanceMatrix[aPosteriori[4], aPosteriori[5]];
     126          moveQuality = moveQuality + distance(aPosteriori[6], aPosteriori[7]) + distance(aPosteriori[8], aPosteriori[9]) + distance(aPosteriori[10], aPosteriori[11]);
     127          moveQuality = moveQuality - distance(aPosteriori[0], aPosteriori[1]) - distance(aPosteriori[2], aPosteriori[3]) - distance(aPosteriori[4], aPosteriori[5]);
    217128        }
    218129        Array.Clear(aPosteriori, 0, aPosteriori.Length);
     
    238149    }
    239150
    240     protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) {
    241       return EvaluateByCoordinates(permutation, TranslocationMoveParameter.ActualValue, coordinates, distanceCalculator, RealizationsParameter.ActualValue);
    242     }
    243 
    244     protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) {
    245       return EvaluateByDistanceMatrix(permutation, TranslocationMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.ActualValue);
     151    protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     152      return EvaluateMove(tour, TranslocationMoveParameter.ActualValue, distance, realizations);
    246153    }
    247154  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoOpt/PTSPAnalyticalInversionMoveEvaluator.cs

    r13451 r13470  
    2929
    3030namespace HeuristicLab.Problems.PTSP {
    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.")]
     31  [Item("PTSP Analytical Inversion Move Evaluator", "Evaluates an inversion move (2-opt) by a full solution evaluation.")]
    3232  [StorableClass]
    33   public class PTSPEstimatedInversionMoveEvaluator : EstimatedPTSPMoveEvaluator, IPermutationInversionMoveOperator {
     33  public class PTSPAnalyticalInversionMoveEvaluator : AnalyticalPTSPMoveEvaluator, IPermutationInversionMoveOperator {
    3434
    3535    public ILookupParameter<InversionMove> InversionMoveParameter {
     
    3838
    3939    [StorableConstructor]
    40     protected PTSPEstimatedInversionMoveEvaluator(bool deserializing) : base(deserializing) { }
    41     protected PTSPEstimatedInversionMoveEvaluator(PTSPEstimatedInversionMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
    42     public PTSPEstimatedInversionMoveEvaluator()
     40    protected PTSPAnalyticalInversionMoveEvaluator(bool deserializing) : base(deserializing) { }
     41    protected PTSPAnalyticalInversionMoveEvaluator(PTSPAnalyticalInversionMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
     42    public PTSPAnalyticalInversionMoveEvaluator()
    4343      : base() {
    4444      Parameters.Add(new LookupParameter<InversionMove>("InversionMove", "The move to evaluate."));
     
    4646
    4747    public override IDeepCloneable Clone(Cloner cloner) {
    48       return new PTSPEstimatedInversionMoveEvaluator(this, cloner);
     48      return new PTSPAnalyticalInversionMoveEvaluator(this, cloner);
    4949    }
    5050
    51     public static double EvaluateByCoordinates(Permutation permutation, InversionMove move, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, ItemList<BoolArray> realizations) {
    52       double moveQuality = 0;
    53       var edges = new int[4];
    54       var indices = new int[4];
    55       edges[0] = permutation.GetCircular(move.Index1 - 1);
    56       indices[0] = move.Index1 - 1;
    57       if (indices[0] == -1) indices[0] = permutation.Length - 1;
    58       edges[1] = permutation[move.Index1];
    59       indices[1] = move.Index1;
    60       edges[2] = permutation[move.Index2];
    61       indices[2] = move.Index2;
    62       edges[3] = permutation.GetCircular(move.Index2 + 1);
    63       indices[3] = move.Index2 + 1;
    64       if (indices[3] == permutation.Length + 1) indices[3] = 0;
    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]]) {
    69             aPosteriori[i] = edges[i];
    70           } else {
    71             var j = 1;
    72             if (i % 2 == 0) {
    73               // find nearest predecessor in realization if source edge
    74               while (!realization[permutation.GetCircular(indices[i] - j)]) {
    75                 j++;
    76               }
    77               aPosteriori[i] = permutation.GetCircular(indices[i] - j);
    78             } else {
    79               // find nearest successor in realization if target edge
    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;
     51    public static double EvaluateMove(Permutation tour, InversionMove move, Func<int, int, double> distance, DoubleArray probabilities) {
     52      var afterMove = (Permutation)tour.Clone();
     53      InversionManipulator.Apply(afterMove, move.Index1, move.Index2);
     54      return AnalyticalProbabilisticTravelingSalesmanProblem.Evaluate(afterMove, distance, probabilities);
    9955    }
    10056
    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)]) {
    131                 j++;
    132               }
    133               aPosteriori[i] = permutation.GetCircular(indices[i] + j);
    134             }
    135           }
    136         }
    137         // compute cost difference between the two a posteriori solutions
    138         if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3])) {
    139           moveQuality = moveQuality + distanceMatrix[aPosteriori[0], aPosteriori[2]] + distanceMatrix[aPosteriori[1], aPosteriori[3]] - distanceMatrix[aPosteriori[0], aPosteriori[1]] - distanceMatrix[aPosteriori[2], aPosteriori[3]];
    140         }
    141         Array.Clear(aPosteriori, 0, aPosteriori.Length);
    142       }
    143       // return average of cost differences
    144       return moveQuality / realizations.Count;
    145     }
    146 
    147     protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) {
    148       return EvaluateByCoordinates(permutation, InversionMoveParameter.ActualValue, coordinates, distanceCalculator, RealizationsParameter.ActualValue);
    149     }
    150 
    151     protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) {
    152       return EvaluateByDistanceMatrix(permutation, InversionMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.ActualValue);
     57    protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
     58      return EvaluateMove(tour, InversionMoveParameter.ActualValue, distance, probabilities);
    15359    }
    15460  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoOpt/PTSPEstimatedInversionMoveEvaluator.cs

    r13412 r13470  
    2929
    3030namespace HeuristicLab.Problems.PTSP {
    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.")]
     31  [Item("PTSP Estimated Inversion Move Evaluator", "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.")]
    3232  [StorableClass]
    3333  public class PTSPEstimatedInversionMoveEvaluator : EstimatedPTSPMoveEvaluator, IPermutationInversionMoveOperator {
     
    4949    }
    5050
    51     public static double EvaluateByCoordinates(Permutation permutation, InversionMove move, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, ItemList<BoolArray> realizations) {
     51    public static double EvaluateMove(Permutation tour, InversionMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
    5252      double moveQuality = 0;
    5353      var edges = new int[4];
    5454      var indices = new int[4];
    55       edges[0] = permutation.GetCircular(move.Index1 - 1);
     55      edges[0] = tour.GetCircular(move.Index1 - 1);
    5656      indices[0] = move.Index1 - 1;
    57       if (indices[0] == -1) indices[0] = permutation.Length - 1;
    58       edges[1] = permutation[move.Index1];
     57      if (indices[0] == -1) indices[0] = tour.Length - 1;
     58      edges[1] = tour[move.Index1];
    5959      indices[1] = move.Index1;
    60       edges[2] = permutation[move.Index2];
     60      edges[2] = tour[move.Index2];
    6161      indices[2] = move.Index2;
    62       edges[3] = permutation.GetCircular(move.Index2 + 1);
     62      edges[3] = tour.GetCircular(move.Index2 + 1);
    6363      indices[3] = move.Index2 + 1;
    64       if (indices[3] == permutation.Length + 1) indices[3] = 0;
     64      if (indices[3] == tour.Length + 1) indices[3] = 0;
    6565      var aPosteriori = new int[4];
    6666      foreach (var realization in realizations) {
     
    7272            if (i % 2 == 0) {
    7373              // find nearest predecessor in realization if source edge
    74               while (!realization[permutation.GetCircular(indices[i] - j)]) {
     74              while (!realization[tour.GetCircular(indices[i] - j)]) {
    7575                j++;
    7676              }
    77               aPosteriori[i] = permutation.GetCircular(indices[i] - j);
     77              aPosteriori[i] = tour.GetCircular(indices[i] - j);
    7878            } else {
    7979              // find nearest successor in realization if target edge
    80               while (!realization[permutation.GetCircular(indices[i] + j)]) {
     80              while (!realization[tour.GetCircular(indices[i] + j)]) {
    8181                j++;
    8282              }
    83               aPosteriori[i] = permutation.GetCircular(indices[i] + j);
     83              aPosteriori[i] = tour.GetCircular(indices[i] + j);
    8484            }
    8585          }
     
    8787        // compute cost difference between the two a posteriori solutions
    8888        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);
     89          moveQuality = moveQuality + distance(aPosteriori[0], aPosteriori[2]) + distance(aPosteriori[1], aPosteriori[3])
     90            - distance(aPosteriori[0], aPosteriori[1]) - distance(aPosteriori[2], aPosteriori[3]);
    9491        }
    9592        Array.Clear(aPosteriori, 0, aPosteriori.Length);
     
    9996    }
    10097
    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)]) {
    131                 j++;
    132               }
    133               aPosteriori[i] = permutation.GetCircular(indices[i] + j);
    134             }
    135           }
    136         }
    137         // compute cost difference between the two a posteriori solutions
    138         if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3])) {
    139           moveQuality = moveQuality + distanceMatrix[aPosteriori[0], aPosteriori[2]] + distanceMatrix[aPosteriori[1], aPosteriori[3]] - distanceMatrix[aPosteriori[0], aPosteriori[1]] - distanceMatrix[aPosteriori[2], aPosteriori[3]];
    140         }
    141         Array.Clear(aPosteriori, 0, aPosteriori.Length);
    142       }
    143       // return average of cost differences
    144       return moveQuality / realizations.Count;
    145     }
    146 
    147     protected override double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator) {
    148       return EvaluateByCoordinates(permutation, InversionMoveParameter.ActualValue, coordinates, distanceCalculator, RealizationsParameter.ActualValue);
    149     }
    150 
    151     protected override double EvaluateByDistanceMatrix(Permutation permutation, DistanceMatrix distanceMatrix) {
    152       return EvaluateByDistanceMatrix(permutation, InversionMoveParameter.ActualValue, distanceMatrix, RealizationsParameter.ActualValue);
     98    protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     99      return EvaluateMove(tour, InversionMoveParameter.ActualValue, distance, realizations);
    153100    }
    154101  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/PTSPAnalyticalTwoPointFiveMoveEvaluator.cs

    r13451 r13470  
    2020#endregion
    2121
     22using System;
    2223using HeuristicLab.Common;
    2324using HeuristicLab.Core;
     
    2829
    2930namespace HeuristicLab.Problems.PTSP {
    30   [Item("PTSP 2.5-MoveEvaluator", "Operator that evaluates 2.5-p-opt moves of PTSP")]
     31  [Item("PTSP Analytical 2.5-MoveEvaluator", "Operator that evaluates 2.5-p-opt moves of PTSP by a full solution evaluation.")]
    3132  [StorableClass]
    32   public class PTSPTwoPointFiveMoveEvaluator : EstimatedPTSPMoveEvaluator, ITwoPointFiveMoveOperator {
     33  public class PTSPAnalyticalTwoPointFiveMoveEvaluator : AnalyticalPTSPMoveEvaluator, ITwoPointFiveMoveOperator {
    3334
    3435    public ILookupParameter<TwoPointFiveMove> TwoPointFiveMoveParameter {
     
    3738
    3839    [StorableConstructor]
    39     protected PTSPTwoPointFiveMoveEvaluator(bool deserializing) : base(deserializing) { }
    40     protected PTSPTwoPointFiveMoveEvaluator(PTSPTwoPointFiveMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
    41     public PTSPTwoPointFiveMoveEvaluator()
     40    protected PTSPAnalyticalTwoPointFiveMoveEvaluator(bool deserializing) : base(deserializing) { }
     41    protected PTSPAnalyticalTwoPointFiveMoveEvaluator(PTSPAnalyticalTwoPointFiveMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
     42    public PTSPAnalyticalTwoPointFiveMoveEvaluator()
    4243      : base() {
    4344      Parameters.Add(new LookupParameter<TwoPointFiveMove>("TwoPointFiveMove", "The move to evaluate."));
     
    4546
    4647    public override IDeepCloneable Clone(Cloner cloner) {
    47       return new PTSPTwoPointFiveMoveEvaluator(this, cloner);
     48      return new PTSPAnalyticalTwoPointFiveMoveEvaluator(this, cloner);
    4849    }
    4950
    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);
     51    protected override double EvaluateMove(Permutation permutation, Func<int, int, double> distance, DoubleArray probabilities) {
     52      return EvaluateMove(permutation, TwoPointFiveMoveParameter.ActualValue, distance, probabilities);
    5453    }
    5554
    56     public static double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, TwoPointFiveMove move, ItemList<BoolArray> realizations) {
     55    public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, Func<int, int, double> distance, DoubleArray probabilities) {
    5756      if (move.IsInvert) {
    58         return PTSPEstimatedInversionMoveEvaluator.EvaluateByCoordinates(permutation,
    59           new InversionMove(move.Index1, move.Index2, move.Permutation),
    60           coordinates, distanceCalculator, realizations);
     57        return PTSPAnalyticalInversionMoveEvaluator.EvaluateMove(permutation,
     58          new InversionMove(move.Index1, move.Index2, move.Permutation), distance, probabilities);
    6159      } else {
    62         return PTSPEstimatedInsertionMoveEvaluator.EvaluateByCoordinates(permutation,
    63           new TranslocationMove(move.Index1, move.Index1, move.Index2),
    64           coordinates, distanceCalculator, realizations);
    65       }
    66     }
    67 
    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);
    72     }
    73 
    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);
     60        return PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(permutation,
     61          new TranslocationMove(move.Index1, move.Index1, move.Index2), distance, probabilities);
    8362      }
    8463    }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/PTSPEstimatedTwoPointFiveMoveEvaluator.cs

    r13469 r13470  
    2020#endregion
    2121
     22using System;
    2223using HeuristicLab.Common;
    2324using HeuristicLab.Core;
     
    2829
    2930namespace HeuristicLab.Problems.PTSP {
    30   [Item("PTSP 2.5-MoveEvaluator", "Operator that evaluates 2.5-p-opt moves of PTSP")]
     31  [Item("PTSP Estimated 2.5-MoveEvaluator", "Operator that evaluates 2.5-p-opt moves of PTSP")]
    3132  [StorableClass]
    32   public class PTSPTwoPointFiveMoveEvaluator : EstimatedPTSPMoveEvaluator, ITwoPointFiveMoveOperator {
     33  public class PTSPEstimatedTwoPointFiveMoveEvaluator : EstimatedPTSPMoveEvaluator, ITwoPointFiveMoveOperator {
    3334
    3435    public ILookupParameter<TwoPointFiveMove> TwoPointFiveMoveParameter {
     
    3738
    3839    [StorableConstructor]
    39     protected PTSPTwoPointFiveMoveEvaluator(bool deserializing) : base(deserializing) { }
    40     protected PTSPTwoPointFiveMoveEvaluator(PTSPTwoPointFiveMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
    41     public PTSPTwoPointFiveMoveEvaluator()
     40    protected PTSPEstimatedTwoPointFiveMoveEvaluator(bool deserializing) : base(deserializing) { }
     41    protected PTSPEstimatedTwoPointFiveMoveEvaluator(PTSPEstimatedTwoPointFiveMoveEvaluator original, Cloner cloner) : base(original, cloner) { }
     42    public PTSPEstimatedTwoPointFiveMoveEvaluator()
    4243      : base() {
    4344      Parameters.Add(new LookupParameter<TwoPointFiveMove>("TwoPointFiveMove", "The move to evaluate."));
     
    4546
    4647    public override IDeepCloneable Clone(Cloner cloner) {
    47       return new PTSPTwoPointFiveMoveEvaluator(this, cloner);
     48      return new PTSPEstimatedTwoPointFiveMoveEvaluator(this, cloner);
    4849    }
    4950
    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);
     51    protected override double EvaluateMove(Permutation permutation, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     52      return EvaluateMove(permutation, TwoPointFiveMoveParameter.ActualValue, distance, realizations);
    5453    }
    5554
    56     public static double EvaluateByCoordinates(Permutation permutation, DoubleMatrix coordinates, DistanceCalculator distanceCalculator, TwoPointFiveMove move, ItemList<BoolArray> realizations) {
     55    public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
    5756      if (move.IsInvert) {
    58         return PTSPEstimatedInversionMoveEvaluator.EvaluateByCoordinates(permutation,
    59           new InversionMove(move.Index1, move.Index2, move.Permutation),
    60           coordinates, distanceCalculator, realizations);
     57        return PTSPEstimatedInversionMoveEvaluator.EvaluateMove(permutation,
     58          new InversionMove(move.Index1, move.Index2, move.Permutation), distance, realizations);
    6159      } else {
    62         return PTSPEstimatedInsertionMoveEvaluator.EvaluateByCoordinates(permutation,
    63           new TranslocationMove(move.Index1, move.Index1, move.Index2),
    64           coordinates, distanceCalculator, realizations);
    65       }
    66     }
    67 
    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);
    72     }
    73 
    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);
     60        return PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(permutation,
     61          new TranslocationMove(move.Index1, move.Index1, move.Index2), distance, realizations);
    8362      }
    8463    }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/TwoPointFiveMoveMaker.cs

    r13412 r13470  
    7171      var quality = QualityParameter.ActualValue;
    7272
     73      Apply(permutation, move);
     74
     75      quality.Value = moveQuality.Value;
     76
     77      return base.Apply();
     78    }
     79
     80    public static void Apply(Permutation permutation, TwoPointFiveMove move) {
    7381      if (move.IsInvert) {
    7482        InversionManipulator.Apply(permutation, move.Index1, move.Index2);
     
    7684        TranslocationManipulator.Apply(permutation, move.Index1, move.Index1, move.Index2);
    7785      }
    78 
    79       quality.Value = moveQuality.Value;
    80 
    81       return base.Apply();
    8286    }
    8387  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/PTSP.cs

    r13412 r13470  
    2121
    2222using System;
     23using System.Linq;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
     
    3536  public abstract class ProbabilisticTravelingSalesmanProblem : SingleObjectiveBasicProblem<PermutationEncoding>,
    3637  IProblemInstanceConsumer<PTSPData> {
     38    protected bool SuppressEvents { get; set; }
     39
    3740    private static readonly int DistanceMatrixSizeLimit = 1000;
    3841
     
    9295    [StorableConstructor]
    9396    protected ProbabilisticTravelingSalesmanProblem(bool deserializing) : base(deserializing) { }
    94     protected ProbabilisticTravelingSalesmanProblem(ProbabilisticTravelingSalesmanProblem original, Cloner cloner) : base(original, cloner) { }
     97    protected ProbabilisticTravelingSalesmanProblem(ProbabilisticTravelingSalesmanProblem original, Cloner cloner)
     98      : base(original, cloner) {
     99      RegisterEventHandlers();
     100    }
    95101    protected ProbabilisticTravelingSalesmanProblem() {
    96102      Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
     
    101107      Parameters.Add(new ValueParameter<DoubleArray>("Probabilities", "This list describes for each city the probability of appearing in a realized instance."));
    102108
    103       Coordinates = new DoubleMatrix(new double[,] {
     109      var coordinates = new DoubleMatrix(new double[,] {
    104110        { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
    105111        { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
     
    107113        { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
    108114      });
    109 
    110       Probabilities = new DoubleArray(new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });
     115      Coordinates = coordinates;
     116      Encoding.Length = coordinates.Rows;
     117      DistanceCalculator = new EuclideanDistance();
     118      DistanceMatrix = new DistanceMatrix(CalculateDistances());
     119      Probabilities = new DoubleArray(Enumerable.Range(0, coordinates.Rows).Select(x => 0.5).ToArray());
     120
     121      RegisterEventHandlers();
     122    }
     123
     124    [StorableHook(HookType.AfterDeserialization)]
     125    private void AfterDeserialization() {
     126      RegisterEventHandlers();
     127    }
     128
     129    private void RegisterEventHandlers() {
     130      CoordinatesParameter.ValueChanged += CoordinatesParameterOnValueChanged;
     131      if (Coordinates != null) {
     132        Coordinates.RowsChanged += CoordinatesOnChanged;
     133        Coordinates.ItemChanged += CoordinatesOnChanged;
     134      }
     135      UseDistanceMatrixParameter.Value.ValueChanged += UseDistanceMatrixValueChanged;
     136      DistanceCalculatorParameter.ValueChanged += DistanceCalculatorParameterOnValueChanged;
     137    }
     138
     139    private void CoordinatesParameterOnValueChanged(object sender, EventArgs eventArgs) {
     140      if (Coordinates != null) {
     141        Coordinates.RowsChanged += CoordinatesOnChanged;
     142        Coordinates.ItemChanged += CoordinatesOnChanged;
     143      }
     144      if (SuppressEvents) return;
     145      UpdateInstance();
     146    }
     147
     148    private void CoordinatesOnChanged(object sender, EventArgs eventArgs) {
     149      if (SuppressEvents) return;
     150      UpdateInstance();
     151    }
     152
     153    private void UseDistanceMatrixValueChanged(object sender, EventArgs eventArgs) {
     154      if (SuppressEvents) return;
     155      UpdateInstance();
     156    }
     157
     158    private void DistanceCalculatorParameterOnValueChanged(object sender, EventArgs eventArgs) {
     159      if (SuppressEvents) return;
     160      UpdateInstance();
    111161    }
    112162
     
    117167    public abstract double Evaluate(Permutation tour, IRandom random);
    118168
     169    public double[,] CalculateDistances() {
     170      var coords = Coordinates;
     171      var len = coords.Rows;
     172      var dist = DistanceCalculator;
     173
     174      var matrix = new double[len, len];
     175      for (var i = 0; i < len - 1; i++)
     176        for (var j = i + 1; j < len; j++)
     177          matrix[i, j] = matrix[j, i] = dist.Calculate(i, j, coords);
     178
     179      return matrix;
     180    }
     181
    119182    public virtual void Load(PTSPData data) {
    120       if (data.Coordinates == null && data.Distances == null)
    121         throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
    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       }
    144 
    145       Name = data.Name;
    146       Description = data.Description;
    147 
    148       Probabilities = new DoubleArray(data.Probabilities);
    149       BestKnownSolution = data.BestKnownTour != null ? new Permutation(PermutationTypes.RelativeUndirected, data.BestKnownTour) : null;
    150       Coordinates = data.Coordinates != null && data.Coordinates.GetLength(0) > 0 ? new DoubleMatrix(data.Coordinates) : null;
    151       DistanceMatrix = new DistanceMatrix(data.GetDistanceMatrix());
    152 
    153       Encoding.Length = data.Dimension;
    154 
     183      try {
     184        SuppressEvents = true;
     185        if (data.Coordinates == null && data.Distances == null)
     186          throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
     187        if (data.Dimension > DistanceMatrixSizeLimit && (data.Coordinates == null || data.Coordinates.GetLength(0) != data.Dimension || data.Coordinates.GetLength(1) != 2))
     188          throw new System.IO.InvalidDataException("The given instance is too large for using a distance matrix and there is a problem with the coordinates.");
     189        if (data.Coordinates != null && (data.Coordinates.GetLength(0) != data.Dimension || data.Coordinates.GetLength(1) != 2))
     190          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.");
     191
     192        switch (data.DistanceMeasure) {
     193          case DistanceMeasure.Direct:
     194            DistanceCalculator = null;
     195            if (data.Dimension > DistanceMatrixSizeLimit && Coordinates != null) {
     196              DistanceCalculator = new EuclideanDistance();
     197              UseDistanceMatrix = false;
     198            } else UseDistanceMatrix = true;
     199            break;
     200          case DistanceMeasure.Att: DistanceCalculator = new AttDistance(); break;
     201          case DistanceMeasure.Euclidean: DistanceCalculator = new EuclideanDistance(); break;
     202          case DistanceMeasure.Geo: DistanceCalculator = new GeoDistance(); break;
     203          case DistanceMeasure.Manhattan: DistanceCalculator = new ManhattanDistance(); break;
     204          case DistanceMeasure.Maximum: DistanceCalculator = new MaximumDistance(); break;
     205          case DistanceMeasure.RoundedEuclidean: DistanceCalculator = new RoundedEuclideanDistance(); break;
     206          case DistanceMeasure.UpperEuclidean: DistanceCalculator = new UpperEuclideanDistance(); break;
     207          default: throw new ArgumentException("Distance measure is unknown");
     208        }
     209
     210        Name = data.Name;
     211        Description = data.Description;
     212
     213        Probabilities = new DoubleArray(data.Probabilities);
     214        BestKnownSolution = data.BestKnownTour != null ? new Permutation(PermutationTypes.RelativeUndirected, data.BestKnownTour) : null;
     215        Coordinates = data.Coordinates != null && data.Coordinates.GetLength(0) > 0 ? new DoubleMatrix(data.Coordinates) : null;
     216        DistanceMatrix = data.Dimension <= DistanceMatrixSizeLimit && UseDistanceMatrix ? new DistanceMatrix(data.GetDistanceMatrix()) : null;
     217
     218        Encoding.Length = data.Dimension;
     219      } finally { SuppressEvents = false; }
    155220      OnReset();
     221    }
     222
     223    private void UpdateInstance() {
     224      var len = GetProblemDimension();
     225      if (Coordinates != null && Coordinates.Rows <= DistanceMatrixSizeLimit
     226        && DistanceCalculator != null && UseDistanceMatrix)
     227        DistanceMatrix = new DistanceMatrix(CalculateDistances());
     228      if (!UseDistanceMatrix) DistanceMatrix = null;
     229      Encoding.Length = len;
     230
     231      OnReset();
     232    }
     233
     234    private int GetProblemDimension() {
     235      if (Coordinates == null && DistanceMatrix == null) throw new InvalidOperationException("Both coordinates and distance matrix are null, please specify at least one of them.");
     236      return Coordinates != null ? Coordinates.Rows : DistanceMatrix.Rows;
    156237    }
    157238  }
  • branches/PTSP/HeuristicLab.Problems.PTSP/3.3/Properties/AssemblyInfo.cs.frame

    r12166 r13470  
    3434// [assembly: AssemblyVersion("1.0.*")]
    3535[assembly: AssemblyVersion("3.3.0.0")]
    36 [assembly: AssemblyFileVersion("3.3.11.$WCREV$")]
     36[assembly: AssemblyFileVersion("3.3.13.$WCREV$")]
  • branches/PTSP/PTSP.sln

    r13412 r13470  
    2626    {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    2727    {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
    28     {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|x64.ActiveCfg = Debug|Any CPU
    29     {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|x86.ActiveCfg = Debug|Any CPU
     28    {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|x64.ActiveCfg = Debug|x64
     29    {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|x64.Build.0 = Debug|x64
     30    {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|x86.ActiveCfg = Debug|x86
     31    {97198965-AFEA-496B-B3B1-316905C43FD6}.Debug|x86.Build.0 = Debug|x86
    3032    {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
    3133    {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|Any CPU.Build.0 = Release|Any CPU
    32     {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|x64.ActiveCfg = Release|Any CPU
    33     {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|x86.ActiveCfg = Release|Any CPU
     34    {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|x64.ActiveCfg = Release|x64
     35    {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|x64.Build.0 = Release|x64
     36    {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|x86.ActiveCfg = Release|x86
     37    {97198965-AFEA-496B-B3B1-316905C43FD6}.Release|x86.Build.0 = Release|x86
    3438    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    3539    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
    36     {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|x64.ActiveCfg = Debug|Any CPU
    37     {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|x86.ActiveCfg = Debug|Any CPU
     40    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|x64.ActiveCfg = Debug|x64
     41    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|x64.Build.0 = Debug|x64
     42    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|x86.ActiveCfg = Debug|x86
     43    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Debug|x86.Build.0 = Debug|x86
    3844    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
    3945    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|Any CPU.Build.0 = Release|Any CPU
    40     {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|x64.ActiveCfg = Release|Any CPU
    41     {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|x86.ActiveCfg = Release|Any CPU
     46    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|x64.ActiveCfg = Release|x64
     47    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|x64.Build.0 = Release|x64
     48    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|x86.ActiveCfg = Release|x86
     49    {90B6CA12-9791-4430-B2D7-CD3ED7F75E2B}.Release|x86.Build.0 = Release|x86
    4250    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    4351    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|Any CPU.Build.0 = Debug|Any CPU
    44     {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|x64.ActiveCfg = Debug|Any CPU
    45     {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|x86.ActiveCfg = Debug|Any CPU
     52    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|x64.ActiveCfg = Debug|x64
     53    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|x64.Build.0 = Debug|x64
     54    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|x86.ActiveCfg = Debug|x86
     55    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Debug|x86.Build.0 = Debug|x86
    4656    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|Any CPU.ActiveCfg = Release|Any CPU
    4757    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|Any CPU.Build.0 = Release|Any CPU
    48     {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|x64.ActiveCfg = Release|Any CPU
    49     {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|x86.ActiveCfg = Release|Any CPU
     58    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|x64.ActiveCfg = Release|x64
     59    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|x64.Build.0 = Release|x64
     60    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|x86.ActiveCfg = Release|x86
     61    {CBEC171A-F7EC-460D-94E2-D58625811D99}.Release|x86.Build.0 = Release|x86
    5062    {CE0F99D6-1C56-48A9-9B68-3E5B833703EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    5163    {CE0F99D6-1C56-48A9-9B68-3E5B833703EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
Note: See TracChangeset for help on using the changeset viewer.