PartiallyMappedCrossover.h
Go to the documentation of this file.
1 #ifndef SHARK_ALGORITHMS_DIRECT_SEARCH_OPERATORS_RECOMBINATION_PARTIALLYMAPPEDCROSSOVER_H
2 #define SHARK_ALGORITHMS_DIRECT_SEARCH_OPERATORS_RECOMBINATION_PARTIALLYMAPPEDCROSSOVER_H
3 
4 #include <shark/Core/Random.h>
5 #include <shark/Core/Exception.h>
6 
7 namespace shark {
8 
9 /// @brief Implements partially mapped crossover
10 ///
11 /// PartiallyMappedCrossover recombines points representing
12 /// permutations, i.e. it ensures that the results are also permutations.
14 
15  /// \brief Mates the supplied individuals.
16  ///
17  /// \param [in,out] individual1 Individual to be mated.
18  /// \param [in,out] individual2 Individual to be mated.
19  template<class Rng, typename IndividualType>
20  void operator()(Rng& rng, IndividualType & individual1, IndividualType & individual2 )const{
21  SIZE_CHECK(individual1.searchPoint().size() == individual2.searchPoint().size());
22 
23  typedef typename IndividualType::SearchPointType PointType;
24  PointType& t1 = individual1.searchPoint();
25  PointType& t2 = individual2.searchPoint();
26 
27  std::size_t n = t1.size();
28  unsigned int unset = static_cast<unsigned int>(n + 1);
29 
30 
31  //compute cuttingpoints 0 <= cuttingPoint1 < cuttingPoint2 <= n
32  std::size_t cuttingPoint1 = random::discrete(rng, std::size_t(0), n - 2);
33  std::size_t cuttingPoint2 = random::discrete(rng,cuttingPoint1+1,n-1);
34 
35  PointType r1(n, unset), r2(n, unset);
36  PointType p1(n, unset), p2(n, unset);
37 
38  //swap ranges [cuttingPoint1,cuttingPoint2] and store in p1,p2
39  //also keep track which elements are already taken and which one are free
40  for( std::size_t i = cuttingPoint1; i <= cuttingPoint2; i++ ) {
41  p1[i] = t2[i];
42  p2[i] = t1[i];
43 
44  r1[ t2[i] ] = t1[i];
45  r2[ t1[i] ] = t2[i];
46  }
47 
48  for( std::size_t i = 0; i < t1.size(); i++) {
49  if ((i >= cuttingPoint1) && (i <= cuttingPoint2)) continue;
50 
51  std::size_t n1 = t1[i] ;
52  std::size_t m1 = r1[n1] ;
53 
54  std::size_t n2 = t2[i] ;
55  std::size_t m2 = r2[n2] ;
56 
57  while (m1 != unset) {
58  n1 = m1 ;
59  m1 = r1[m1] ;
60  }
61  while (m2 != unset) {
62  n2 = m2 ;
63  m2 = r2[m2] ;
64  }
65  p1[i] = n1 ;
66  p2[i] = n2 ;
67  }
68 
69  t1 = p1;
70  t2 = p2;
71 
72  }
73 
74  /// \brief Serializes this instance to the supplied archive.
75  template<typename Archive>
76  void serialize( Archive &, const unsigned int ) {}
77 };
78 }
79 
80 #endif