Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Permutation/3.3/MaximalPreservativeCrossover.cs @ 2823

Last change on this file since 2823 was 2823, checked in by abeham, 14 years ago

updated MPX (documentation) and PMX (documentation + implementation) (#889)
previously commited implementation of PMX was faulty

File size: 7.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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 HeuristicLab.Core;
24using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
25
26namespace HeuristicLab.Permutation {
27  /// <summary>An operator which performs the maximal preservative crossover on two permutations.</summary>
28  /// <remarks>
29  /// Performs a crossover between two permuation arrays by preserving a large number of edges in both parents.
30  /// The operator also maintains the position in the arrays to some extent.
31  /// It is implemented as described in Mühlenbein, H. Evolution in time and space - the parallel genetic algorithm. FOUNDATIONS OF GENETIC ALGORITHMS, Morgan Kaufmann, 1991, 316-337.
32  /// The length of the segment copied from the first parent to the offspring is uniformly distributed in the interval [3, N/3) with N = length of the permutation.
33  /// </remarks>
34  [Item("MaximalPreservativeCrossover", "An operator which performs the maximal preservative crossover on two permutations.")]
35  [EmptyStorableClass]
36  [Creatable("Test")]
37  public class MaximalPreservativeCrossover : PermutationCrossover {
38    /// <summary>
39    /// Performs the maximal preservative crossover on <paramref name="parent1"/> and <paramref name="parent2"/>
40    /// by preserving a large number of edges in both parents.
41    /// </summary>
42    /// <exception cref="InvalidOperationException">Thrown if the numbers in the permutation array are not in the range [0,N) with N = length of the permutation.</exception>
43    /// <exception cref="ArgumentException">Thrown when <paramref name="parent1"/> and <paramref name="parent2"/> are not of equal length or when the permutations are shorter than 4 elements.</exception>
44    /// <remarks>
45    /// First one segment is copied from the first parent to the offspring in the same position.
46    /// Then the tour is completed by adding the next number from the second parent if such an edge exists,
47    /// or from the first parent, or from the next number of the second parent.
48    /// The last case results in an unwanted mutation.
49    /// </remarks>
50    /// <param name="random">A random number generator.</param>
51    /// <param name="parent1">The first parent permutation to cross.</param>
52    /// <param name="parent2">The second parent permutation to cross.</param>
53    /// <returns>The new permutation resulting from the crossover.</returns>
54    public static Permutation Apply(IRandom random, Permutation parent1, Permutation parent2) {
55      if (parent1.Length != parent2.Length) throw new ArgumentException("MaximalPreservativeCrossover: The parent permutations are of unequal length");
56      if (parent1.Length < 4) throw new ArgumentException("MaximalPreservativeCrossover: The parent permutation must be at least of size 4");
57      int length = parent1.Length;
58      Permutation result = new Permutation(length);
59      bool[] numberCopied = new bool[length];
60      int breakPoint1, breakPoint2, subsegmentLength, index;
61
62      subsegmentLength = random.Next(3, Math.Max(length / 3, 4)); // as mentioned in "Pohlheim, H. Evolutionäre Algorithmen: Verfahren, Operatoren und Hinweise für die Praxis, 1999, p.44, Springer.
63      breakPoint1 = random.Next(length);
64      breakPoint2 = breakPoint1 + subsegmentLength;
65      if (breakPoint2 >= length) breakPoint2 -= length;
66
67      // copy string between position [breakPoint1, breakPoint2) from parent1 to the offspring
68      index = breakPoint1;
69      do {
70        result[index] = parent1[index];
71        numberCopied[result[index]] = true;
72        index++;
73        if (index >= length) index -= length;
74      } while (index != breakPoint2);
75
76      // calculate inverse permutation (number -> index) to help finding the follower of a given number
77      int[] invParent1 = new int[length];
78      int[] invParent2 = new int[length];
79      try {
80        for (int i = 0; i < length; i++) {
81          invParent1[parent1[i]] = i;
82          invParent2[parent2[i]] = i;
83        }
84      } catch (IndexOutOfRangeException) {
85        throw new InvalidOperationException("MaximalPreservativeCrossover: The permutation must consist of consecutive numbers from 0 to N-1 with N = length of the permutation");
86      }
87
88      int prevIndex = ((index > 0) ? (index - 1) : (length - 1));
89      do {
90        // look for the follower of the last number in parent2
91        int p2Follower = GetFollower(parent2, invParent2[result[prevIndex]]);
92        if (!numberCopied[p2Follower]) {
93          result[index] = p2Follower;
94        } else {
95          // if that follower has already been added, look for the follower of the last number in parent1
96          int p1Follower = GetFollower(parent1, invParent1[result[prevIndex]]);
97          if (!numberCopied[p1Follower]) {
98            result[index] = p1Follower;
99          } else {
100            // if that has also been added, look for the next not already added number in parent2
101            int tempIndex = index;
102            for (int i = 0; i < parent2.Length; i++) {
103              if (!numberCopied[parent2[tempIndex]]) {
104                result[index] = parent2[tempIndex];
105                break;
106              }
107              tempIndex++;
108              if (tempIndex >= parent2.Length) tempIndex = 0;
109            }
110          }
111        }
112        numberCopied[result[index]] = true;
113        prevIndex = index;
114        index++;
115        if (index >= length) index -= length;
116      } while (index != breakPoint1);
117
118      return result;
119    }
120
121    private static int GetFollower(Permutation parent, int index) {
122      if (index + 1 == parent.Length)
123        return parent[0];
124      return parent[index + 1];
125    }
126
127    /// <summary>
128    /// Checks number of parents and calls <see cref="Apply"/>.
129    /// </summary>
130    /// <exception cref="InvalidOperationException">Thrown if there are not exactly two permutations in <paramref name="parents"/>.</exception>
131    /// <param name="scope">The current scope.</param>
132    /// <param name="random">A random number generator.</param>
133    /// <param name="parents">An array containing the two permutations that should be crossed.</param>
134    /// <returns>The newly created permutation, resulting from the crossover operation.</returns>
135    protected override Permutation Cross(IRandom random, ItemArray<Permutation> parents) {
136      if (parents.Length != 2) throw new InvalidOperationException("MaximalPreservativeCrossover: Number of parents is not equal to 2.");
137      return Apply(random, parents[0], parents[1]);
138    }
139  }
140}
Note: See TracBrowser for help on using the repository browser.