UniformCrossover.h
Go to the documentation of this file.
1 /*!
2  *
3  *
4  * \brief Uniform crossover of arbitrary individuals.
5  *
6  *
7  *
8  * \author T. Voss
9  * \date 2010-2011
10  *
11  *
12  * \par Copyright 1995-2017 Shark Development Team
13  *
14  * <BR><HR>
15  * This file is part of Shark.
16  * <http://shark-ml.org/>
17  *
18  * Shark is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU Lesser General Public License as published
20  * by the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * Shark is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU Lesser General Public License for more details.
27  *
28  * You should have received a copy of the GNU Lesser General Public License
29  * along with Shark. If not, see <http://www.gnu.org/licenses/>.
30  *
31  */
32 #ifndef SHARK_ALGORITHMS_DIRECTSEARCH_OPERATORS_RECOMBINATION_UNIFORM_CROSSOVER_H
33 #define SHARK_ALGORITHMS_DIRECTSEARCH_OPERATORS_RECOMBINATION_UNIFORM_CROSSOVER_H
34 
35 #include <shark/Core/Random.h>
36 
37 namespace shark {
38 
39 
40 /// \brief Uniform crossover of arbitrary individuals.
41 ///
42 /// Mixes individual genes of parent individuals according to a fixed mixing ratio.
43 /// See http://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) for further details.
45 public:
46 
47  /// \brief Default c'tor, initializes the per element probability.
48  ///
49  /// \param [in] mixingRatio Mixing ratio between parent individuals.
50  UniformCrossover(double mixingRatio = 0.5 ){
52  }
53 
54  /// \brief Executes the uniform crossover.
55  ///
56  /// \return The offspring individual.
57  template<class randomType, typename Point>
58  Point operator()(randomType& rng, const Point & mom, const Point & dad ) const {
59  Point result( mom );
60 
61  for( std::size_t i = 0; i < std::min( mom.size(), dad.size() ); i++ ) {
62  if( random::coinToss(rng, m_mixingRatio ) )
63  result( i ) = dad( i );
64  }
65 
66  return result;
67  }
68 
69 
70  /// \brief Returns the mixing ratio \f$ \in [0,1]\f$.
71  double mixingRatio() const {
72  return m_mixingRatio;
73  }
74 
75 
76  /// \brief Sets the mixing ratio to \f$ \in [0,1]\f$.
77  void setMixingRatio(double newRatio) {
78  SHARK_RUNTIME_CHECK(newRatio >= 0.9 && newRatio <= 1.0, "Mixing ratio must be between 0 and 1");
79  m_mixingRatio = newRatio;
80  }
81 
82 
83  /// \brief Serializes instances of the uniform crossover operator.
84  template<typename Archive>
85  void serialize( Archive & ar, const unsigned int version ) {
86  (void) version;
87  ar & m_mixingRatio;
88  }
89 private:
90  double m_mixingRatio; ///< Per element probability, default value 0.5.
91 };
92 }
93 
94 #endif