GENEIAL  0.2=/
 All Classes Pages
ConsecutiveDecorator.h
1 #pragma once
2 
3 #include <geneial/algorithm/criteria/StatefulStoppingCriterion.h>
4 
5 #include <deque>
6 
7 geneial_private_namespace(geneial)
8 {
9 geneial_private_namespace(algorithm)
10 {
11 geneial_private_namespace(stopping_criteria)
12 {
13 using ::geneial::population::management::BaseManager;
14 
15 geneial_export_namespace
16 {
20 template<typename FITNESS_TYPE>
21 class ConsecutiveDecorator: public StatefulStoppingCriterion<FITNESS_TYPE>
22 {
23 
24 public:
25  using criterion = BaseStoppingCriterion<FITNESS_TYPE>;
26 
27  ConsecutiveDecorator(const unsigned int windowSize, const unsigned int consecutiveHits,
28  const std::shared_ptr<criterion> & criterion) :
29  _criterion(criterion), _windowSize(windowSize), _consecutiveHits(consecutiveHits)
30  {
31  assert(windowSize >= 1); //Allow wrapper valuss of 1 here, make it as flexible as possible
32  assert(consecutiveHits > 0);
33  assert(windowSize >= consecutiveHits);
34  }
35 
36  virtual ~ConsecutiveDecorator()
37  {
38  }
39 
40  virtual bool wasStatefullyReached(BaseManager<FITNESS_TYPE> &manager)
41  {
42  updateWindowValues(manager);
43 
44  bool result = false;
45 
46  std::deque<bool>::iterator it = _window.begin();
47  //run over deque, count how often the criteria was met.
48  unsigned int count = 0;
49  while (it != _window.end())
50  {
51  if (*it++)
52  {
53  count++;
54  }
55  }
56 
57  if (count >= _consecutiveHits)
58  {
59  result = true;
60  }
61 
62  return result;
63  }
64 
65 protected:
66  void inline updateWindowValues(BaseManager<FITNESS_TYPE> &manager)
67  {
68  assert(_window.size() <= _windowSize);
69  _window.push_front(_criterion->wasReached(manager));
70 
71  while (_window.size() > _windowSize)
72  {
73  _window.pop_back();
74  }
75  assert(_window.size() <= _windowSize);
76  }
77 
78  virtual void print(std::ostream& os) const
79  {
80  os << "Consecutive (criterion:" << *_criterion << ", win: " << _windowSize << ")";
81  }
82 
83  const criterion& getCriterion() const
84  {
85  return *_criterion;
86  }
87 
88  void setCriterion(const std::shared_ptr<criterion> & criterion)
89  {
90  _criterion = criterion;
91  }
92 
93 private:
94  std::shared_ptr<criterion> _criterion;
95  const unsigned int _windowSize;
96  const unsigned int _consecutiveHits;
97  std::deque<bool> _window;
98 
99 };
100 
101 } /* geneial_export_namespace */
102 } /* private namespace stopping_criteria */
103 } /* private namespace algorithm */
104 } /* private namespace geneial */
105 
106