dignea  1.0.0
Diverse Instance Generator with Novelty Search and Evolutionary Algorithms
FirstImprove.h
Go to the documentation of this file.
1 
11 #ifndef DIGNEA_FIRSTIMPROVE_H
12 #define DIGNEA_FIRSTIMPROVE_H
13 
14 #include <dignea/core/Replacement.h>
17 #include <dignea/utilities/exceptions/NotImplemented.h>
18 
19 #include <string>
20 
21 using namespace std;
22 
30 template <class S>
31 class FirstImprove : public Replacement<S> {
32  public:
33  FirstImprove() = default;
34 
35  virtual ~FirstImprove() = default;
36 
37  vector<S> replace(vector<S> &vector1, vector<S> &vector2) override;
38 
39  vector<S> replace(vector<S> &vector1, const S &solution,
40  const int &position) override;
41 
42  string getName() const override { return "First Improve"; }
43 };
44 
54 template <class S>
55 vector<S> FirstImprove<S>::replace(vector<S> &population,
56  vector<S> &offspring) {
57  if (population.empty() || offspring.empty()) {
58  std::string what = "Empty vector of individuals";
59  throw(runtime_error("Replacement in First Improve" + what));
60  }
61  if (population.size() != offspring.size()) {
62  std::string what =
63  "popSize = " + to_string(population.size()) +
64  " != offspring.size = " + to_string(offspring.size());
65  throw(runtime_error("Replacement in First Improve" + what));
66  }
67  for (unsigned int i = 0; i < population.size(); i++) {
68  // Improves the constraints?
69  if (offspring[i].getNumberOfCons() != 0) {
70  for (int j = 0; j < offspring[i].getNumberOfCons(); j++) {
71  if (offspring[i].getConstAt(j) < population[i].getConstAt(j)) {
72  population[i] = offspring[i];
73  break; // Improves --> continue with the next individual
74  }
75  }
76  } else {
77  if (cmpByFitness(offspring[i], population[i]) == FIRST_BEST) {
78  population[i] = offspring[i];
79  }
80  }
81  }
82  return population;
83 }
84 
94 template <class S>
95 vector<S> FirstImprove<S>::replace(vector<S> &vector1, const S &solution,
96  const int &position) {
97  string where =
98  "Replace with position not allowed in First Improve replacement";
99  throw NotImplemented(where);
100 }
101 
102 #endif // DIGNEA_FIRSTIMPROVE_H
int cmpByFitness(const S &ind1, const S &ind2)
Compares two individuals by their fitness.
Definition: Comparator.h:39
Replacement procedure which compares the individuals of the current population with the offspring ind...
Definition: FirstImprove.h:31
vector< S > replace(vector< S > &vector1, vector< S > &vector2) override
First Improve replacement logic. Loops both vector of individuals doing pairwise comparisons for each...
Definition: FirstImprove.h:55
Replacement skeleton operator.
Definition: Replacement.h:16