dignea  1.0.0
Diverse Instance Generator with Novelty Search and Evolutionary Algorithms
SwapMutation.h
Go to the documentation of this file.
1 
11 #ifndef DIGNEA_SWAPMUTATION_H
12 #define DIGNEA_SWAPMUTATION_H
13 
14 #include <dignea/core/Mutation.h>
15 #include <dignea/utilities/random/PseudoRandom.h>
16 
17 #include <nlohmann/json.hpp>
18 
19 using json = nlohmann::json;
20 
27 template <class S>
28 class SwapMutation : public Mutation<S> {
29  public:
30  SwapMutation() = default;
31 
32  virtual ~SwapMutation() = default;
33 
34  void run(S &ind, const double &probability, Problem<S> *) override;
35 
36  std::string getName() const override { return "Swap Mutation"; };
37 };
38 
50 template <class S>
51 void SwapMutation<S>::run(S &ind, const double &probability,
52  Problem<S> *problem) {
53  int idx2Swap = 0;
54  int idx2Swap2 = 0;
55  while ((idx2Swap == idx2Swap2)) {
56  // Cannot change first and last element
57  // -2 to skip the last element too
58  idx2Swap = PseudoRandom::randInt(1, ind.getNumberOfVars() - 2);
59  idx2Swap2 = PseudoRandom::randInt(1, ind.getNumberOfVars() - 2);
60  }
61  try {
62  auto iGene = ind.getVarAt(idx2Swap);
63  auto iGene2 = ind.getVarAt(idx2Swap2);
64  ind.setVarAt(idx2Swap, iGene2);
65  ind.setVarAt(idx2Swap2, iGene);
66  } catch (OutOfRange const &err) {
67  auto j = ind.to_json();
68  std::string msg = std::string(err.what()) +
69  " from SwapMutation operator with idx1: " +
70  to_string(idx2Swap).c_str() +
71  " and idx2: " + to_string(idx2Swap2).c_str() +
72  " with ind.getNumberOfVars() = " +
73  to_string(ind.getNumberOfVars()) +
74  "\n Individual is: \n" + j.dump(4);
75  std::cout << msg << std::endl;
76  exit(1);
77  }
78 }
79 
80 #endif // DIGNEA_SWAPMUTATION_H
nlohmann::json json
Definition: MinKnap.h:85
Abstract Mutation interface.
Definition: Mutation.h:21
Class to represent a Problem in the tool. It includes the basic information for a problem a few metho...
Definition: Problem.h:29
static int randInt(int minBound, int maxBound)
Returns a random integer int the range [minBound, maxBound].
Definition: PseudoRandom.cpp:38
Swap Mutation Operator for Permutation Based Problems like TSP. Fixes the first and last genes to zer...
Definition: SwapMutation.h:28
void run(S &ind, const double &probability, Problem< S > *) override
Performs Swap Mutation Operation.
Definition: SwapMutation.h:51