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>
6
7namespace 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] rng Random number generator.
18 /// \param [in,out] individual1 Individual to be mated.
19 /// \param [in,out] individual2 Individual to be mated.
20 template<class Rng, typename IndividualType>
21 void operator()(Rng& rng, IndividualType & individual1, IndividualType & individual2 )const{
22 SIZE_CHECK(individual1.searchPoint().size() == individual2.searchPoint().size());
23
24 typedef typename IndividualType::SearchPointType PointType;
25 PointType& t1 = individual1.searchPoint();
26 PointType& t2 = individual2.searchPoint();
27
28 std::size_t n = t1.size();
29 unsigned int unset = static_cast<unsigned int>(n + 1);
30
31
32 //compute cuttingpoints 0 <= cuttingPoint1 < cuttingPoint2 <= n
33 std::size_t cuttingPoint1 = random::discrete(rng, std::size_t(0), n - 2);
34 std::size_t cuttingPoint2 = random::discrete(rng,cuttingPoint1+1,n-1);
35
36 PointType r1(n, unset), r2(n, unset);
37 PointType p1(n, unset), p2(n, unset);
38
39 //swap ranges [cuttingPoint1,cuttingPoint2] and store in p1,p2
40 //also keep track which elements are already taken and which one are free
41 for( std::size_t i = cuttingPoint1; i <= cuttingPoint2; i++ ) {
42 p1[i] = t2[i];
43 p2[i] = t1[i];
44
45 r1[ t2[i] ] = t1[i];
46 r2[ t1[i] ] = t2[i];
47 }
48
49 for( std::size_t i = 0; i < t1.size(); i++) {
50 if ((i >= cuttingPoint1) && (i <= cuttingPoint2)) continue;
51
52 std::size_t n1 = t1[i] ;
53 std::size_t m1 = r1[n1] ;
54
55 std::size_t n2 = t2[i] ;
56 std::size_t m2 = r2[n2] ;
57
58 while (m1 != unset) {
59 n1 = m1 ;
60 m1 = r1[m1] ;
61 }
62 while (m2 != unset) {
63 n2 = m2 ;
64 m2 = r2[m2] ;
65 }
66 p1[i] = n1 ;
67 p2[i] = n2 ;
68 }
69
70 t1 = p1;
71 t2 = p2;
72
73 }
74
75 /// \brief Serializes this instance to the supplied archive.
76 template<typename Archive>
77 void serialize( Archive &, const unsigned int ) {}
78};
79}
80
81#endif