Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ScatterSearch/HeuristicLab.Algorithms.ScatterSearch/3.3/TravelingSalesman/TravelingSalesmanMultipleGuidesPathRelinker.cs @ 7786

Last change on this file since 7786 was 7786, checked in by jkarder, 12 years ago

#1331:

  • fixed bug in path relinking selection
  • fixed bug in ScatterSearch.Prepare()
  • added custom interface (IImprovementOperator) for Scatter Search specific improvement operators
  • switched from diversity calculation to similarity calculation
  • separated IPathRelinker from ICrossover
  • changed TestFunctionsImprovementOperator to use reflection for evaluating functions
  • changed SolutionPoolUpdateMethod to use similarity calculation for solution comparison
  • improved TravelingSalesmanImprovementOperator
  • improved operator graph
  • removed specific operators used to evaluate TestFunctions problems
  • removed custom crossover operator (NChildCrossover)
  • added parameters and adjusted types
  • adjusted event handling
  • changed access levels
  • minor code improvements
File size: 5.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.PermutationEncoding;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.TravelingSalesman;
32
33namespace HeuristicLab.Algorithms.ScatterSearch.TravelingSalesman {
34  /// <summary>
35  /// An operator that relinks paths between traveling salesman solutions using a multiple guiding strategy.
36  /// </summary>
37  [Item("TravelingSalesmanMultipleGuidingPathRelinker", "An operator that relinks paths between traveling salesman solutions using a multiple guiding strategy.")]
38  [StorableClass]
39  public sealed class TravelingSalesmanMultipleGuidesPathRelinker : PathRelinker {
40    #region Parameter properties
41    public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
42      get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
43    }
44    #endregion
45
46    #region Properties
47    public DistanceMatrix DistanceMatrix {
48      get { return DistanceMatrixParameter.ActualValue; }
49      set { DistanceMatrixParameter.ActualValue = value; }
50    }
51    #endregion
52
53    [StorableConstructor]
54    private TravelingSalesmanMultipleGuidesPathRelinker(bool deserializing) : base(deserializing) { }
55    private TravelingSalesmanMultipleGuidesPathRelinker(TravelingSalesmanMultipleGuidesPathRelinker original, Cloner cloner) : base(original, cloner) { }
56    public TravelingSalesmanMultipleGuidesPathRelinker()
57      : base() {
58      #region Create parameters
59      Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix"));
60      #endregion
61      ParentsParameter.ActualName = "TSPTour";
62    }
63
64    public override IDeepCloneable Clone(Cloner cloner) {
65      return new TravelingSalesmanMultipleGuidesPathRelinker(this, cloner);
66    }
67
68    public static ItemArray<IItem> Apply(IItem initiator, IItem[] guides, DistanceMatrix distances, PercentValue n) {
69      if (!(initiator is Permutation) || guides.Any(x => !(x is Permutation)))
70        throw new ArgumentException("Cannot relink path because some of the provided solutions have the wrong type.");
71      if (n.Value <= 0.0)
72        throw new ArgumentException("RelinkingAccuracy must be greater than 0.");
73
74      Permutation v1 = initiator.Clone() as Permutation;
75      Permutation[] targets = new Permutation[guides.Length];
76      Array.Copy(guides, targets, guides.Length);
77
78      if (targets.Any(x => x.Length != v1.Length))
79        throw new ArgumentException("At least one solution is of different length.");
80
81      IList<Permutation> solutions = new List<Permutation>();
82      for (int i = 0; i < v1.Length; i++) {
83        int currCityIndex = i;
84        int bestCityIndex = (i + 1) % v1.Length;
85        double currDistance = distances[v1[currCityIndex], v1[bestCityIndex]];
86        targets.ToList().ForEach(solution => {
87          var node = solution.Select((x, index) => new { Id = x, Index = index }).First(x => x.Id == v1[currCityIndex]);
88          int pred = solution[(node.Index - 1 + solution.Length) % solution.Length];
89          int succ = solution[(node.Index + 1) % solution.Length];
90          var results = new[] { pred, succ }.Select(x => new { Id = x, Distance = distances[x, node.Id] });
91          if (results.Any(x => x.Distance < currDistance)) {
92            var bestCity = results.OrderBy(x => x.Distance).First();
93            bestCityIndex = v1.Select((x, index) => new { Id = x, Index = index }).First(x => x.Id == bestCity.Id).Index;
94            currDistance = bestCity.Distance;
95          }
96        });
97        Invert(v1, i, bestCityIndex);
98        solutions.Add(v1.Clone() as Permutation);
99      }
100
101      IList<IItem> selection = new List<IItem>();
102      if (solutions.Count > 0) {
103        int noSol = (int)(solutions.Count * n.Value);
104        if (noSol <= 0) noSol++;
105        double stepSize = (double)solutions.Count / (double)noSol;
106        for (int i = 0; i < noSol; i++)
107          selection.Add(solutions.ElementAt((int)((i + 1) * stepSize - stepSize * 0.5)));
108      }
109
110      return new ItemArray<IItem>(selection);
111    }
112
113    private static void Invert(Permutation sol, int i, int j) {
114      if (i != j)
115        for (int a = 0; a < Math.Abs(i - j) / 2; a++)
116          if (sol[(i + a) % sol.Length] != sol[(j - a + sol.Length) % sol.Length]) {
117            // XOR swap
118            sol[(i + a) % sol.Length] ^= sol[(j - a + sol.Length) % sol.Length];
119            sol[(j - a + sol.Length) % sol.Length] ^= sol[(i + a) % sol.Length];
120            sol[(i + a) % sol.Length] ^= sol[(j - a + sol.Length) % sol.Length];
121          }
122    }
123
124    protected override ItemArray<IItem> Relink(ItemArray<IItem> parents, PercentValue n) {
125      if (parents.Length < 2)
126        throw new ArgumentException("The number of parents is smaller than 2.");
127      return Apply(parents[0], parents.Skip(1).ToArray(), DistanceMatrix, n);
128    }
129  }
130}
Note: See TracBrowser for help on using the repository browser.