GENEIAL  0.2=/
 All Classes Pages
StatefulStoppingCriterion.h
1 #pragma once
2 
3 #include <geneial/algorithm/criteria/BaseStoppingCriterion.h>
4 
5 geneial_private_namespace(geneial)
6 {
7 geneial_private_namespace(algorithm)
8 {
9 geneial_private_namespace(stopping_criteria)
10 {
11 using ::geneial::population::management::BaseManager;
12 geneial_export_namespace
13 {
14 
15 //Encapsulates when a StoppingCriterion has a state and makes sure wasReached has no sideeffects
16 //and ensures wasStatefully reached is only called once per generation
17 template<typename FITNESS_TYPE>
18 class StatefulStoppingCriterion: public BaseStoppingCriterion<FITNESS_TYPE>
19 {
20 public:
21  StatefulStoppingCriterion() :
22  _lastGenerationChecked(0), _cachedResult(false), _wasInvoked(false)
23  {
24  }
25 
26  virtual ~StatefulStoppingCriterion()
27  {
28  }
29 
30  virtual bool wasStatefullyReached(BaseManager<FITNESS_TYPE> &manager) = 0;
31 
32  virtual bool wasReached(BaseManager<FITNESS_TYPE> &manager)
33  {
34  const unsigned int currentAge = manager.getPopulation().getAge();
35 
36  if ((!_wasInvoked) || (_lastGenerationChecked != currentAge))
37  {
38  assert((_wasInvoked) ? (_lastGenerationChecked < currentAge) : (_lastGenerationChecked <= currentAge));
39  _cachedResult = wasStatefullyReached(manager);
40  _lastGenerationChecked = manager.getPopulation().getAge();
41  }
42 
43  _wasInvoked = true;
44 
45  return _cachedResult;
46  }
47 
48 private:
49 
50  unsigned int _lastGenerationChecked;
51 
52  bool _cachedResult;
53 
54  bool _wasInvoked;
55 };
56 
57 } /* geneial_export_namespace */
58 } /* private namespace stopping_criteria */
59 } /* private namespace algorithm */
60 } /* private namespace geneial */
61 
62