bpp-core3  3.0.0
MetaOptimizer.cpp
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: The Bio++ Development Group
2 //
3 // SPDX-License-Identifier: CECILL-2.1
4 
5 /**************************************************************************/
6 
7 #include "MetaOptimizer.h"
8 #include "../../App/ApplicationTools.h"
9 
10 using namespace bpp;
11 using namespace std;
12 
13 /**************************************************************************/
14 
15 string MetaOptimizerInfos::IT_TYPE_STEP = "step";
16 string MetaOptimizerInfos::IT_TYPE_FULL = "full";
17 
18 /**************************************************************************/
19 
21  std::shared_ptr<FunctionInterface> function,
22  std::unique_ptr<MetaOptimizerInfos> desc,
23  unsigned int n) :
24  AbstractOptimizer(function),
25  optDesc_(std::move(desc)), optParameters_(optDesc_->getNumberOfOptimizers()),
26  nbParameters_(optDesc_->getNumberOfOptimizers()), n_(n),
27  precisionStep_(-1.), stepCount_(0), initialValue_(-1.)
28 {
29  setDefaultStopCondition_(make_shared<FunctionStopCondition>(this));
31  precisionStep_ = log10(getStopCondition()->getTolerance()) / n_;
33 }
34 
35 /**************************************************************************/
36 
38  const MetaOptimizer& opt) :
39  AbstractOptimizer(opt),
40  optDesc_(dynamic_cast<MetaOptimizerInfos*>(opt.optDesc_->clone())),
43  n_(opt.n_),
47 {}
48 
49 /**************************************************************************/
50 
52  const MetaOptimizer& opt)
53 {
55  optDesc_.reset(dynamic_cast<MetaOptimizerInfos*>(opt.optDesc_->clone()));
58  n_ = opt.n_;
60  stepCount_ = opt.stepCount_;
62  return *this;
63 }
64 
65 /**************************************************************************/
66 
68 
69 /**************************************************************************/
70 
71 void MetaOptimizer::doInit(const ParameterList& parameters)
72 {
73  optParameters_.resize(optDesc_->getNumberOfOptimizers());
74  for (unsigned int i = 0; i < optDesc_->getNumberOfOptimizers(); ++i)
75  {
76  optParameters_[i].reset();
77  for (size_t j = 0; j < optDesc_->getParameterNames(i).size(); ++j)
78  {
79  string pname = optDesc_->getParameterNames(i)[j];
80  if (parameters.hasParameter(pname))
81  {
82  optParameters_[i].addParameter(parameters.parameter(pname));
83  }
84  }
85  nbParameters_[i] = optParameters_[i].size();
86  }
87 
88  // Initialize optimizers:
89  for (unsigned int i = 0; i < optDesc_->getNumberOfOptimizers(); ++i)
90  {
91  if (nbParameters_[i] > 0)
92  {
93  OptimizerInterface& opt = optDesc_->optimizer(i);
95  opt.setProfiler(getProfiler());
98  opt.setVerbose(getVerbose() > 0 ? getVerbose() - 1 : 0);
99  }
100  }
101 
102  // Actualize parameters:
104 
105  getFunction()->setParameters(getParameters());
106  initialValue_ = getFunction()->getValue();
107  // Reset counter:
108  stepCount_ = 1;
109  // Recompute step if precision has changed:
110  precisionStep_ = (log10(getStopCondition()->getTolerance()) - log10(initialValue_)) / n_;
111 }
112 
113 /**************************************************************************/
114 
116 {
117  stepCount_++;
118 
119  int tolTest = 0;
120  double tol = getStopCondition()->getTolerance();
121  if (stepCount_ <= n_)
122  {
123  tol = initialValue_ * pow(10, stepCount_ * precisionStep_);
124  }
125 
126  for (unsigned int i = 0; i < optDesc_->getNumberOfOptimizers(); ++i)
127  {
128  if (nbParameters_[i] > 0)
129  {
131  {
132  (ApplicationTools::message->endLine() << optDesc_->getName(i)).endLine();
133  ApplicationTools::message->flush();
134  }
135  if (optDesc_->requiresFirstOrderDerivatives(i))
136  dynamic_cast<FirstOrderDerivable&>(function()).enableFirstOrderDerivatives(true);
137  if (optDesc_->requiresSecondOrderDerivatives(i))
138  dynamic_cast<SecondOrderDerivable&>(function()).enableSecondOrderDerivatives(true);
139 
140  optParameters_[i].matchParametersValues(getParameters());
141  OptimizerInterface& opt = optDesc_->optimizer(i);
142  opt.getStopCondition()->setTolerance(tol);
143  opt.init(optParameters_[i]);
144  if (optDesc_->getIterationType(i) == MetaOptimizerInfos::IT_TYPE_STEP)
145  opt.step();
146  else if (optDesc_->getIterationType(i) == MetaOptimizerInfos::IT_TYPE_FULL)
147  opt.optimize();
148  else
149  throw Exception("MetaOptimizer::step. Unknown iteration type specified.");
151  if (optDesc_->requiresFirstOrderDerivatives(i))
152  dynamic_cast<FirstOrderDerivable&>(function()).enableFirstOrderDerivatives(false);
153  if (optDesc_->requiresSecondOrderDerivatives(i))
154  dynamic_cast<SecondOrderDerivable&>(function()).enableSecondOrderDerivatives(false);
155  if (getVerbose() > 1)
156  cout << endl;
157 
159  }
160  tolTest += nbParameters_[i] > 0 ? 1 : 0;
161  }
162  tolIsReached_ = (tolTest == 1);
163 
164  return getFunction()->getValue();
165 }
166 
167 /**************************************************************************/
virtual void setConstraintPolicy(const std::string &constraintPolicy)=0
Set the constraint policy for this optimizer.
virtual void setVerbose(unsigned int v)=0
Set the verbose level.
AbstractOptimizer & operator=(const AbstractOptimizer &opt)
MetaOptimizer & operator=(const MetaOptimizer &opt)
virtual const Parameter & parameter(const std::string &name) const
Get the parameter with name name.
std::unique_ptr< MetaOptimizerInfos > optDesc_
virtual double optimize()=0
Perform as many optimization steps untill the stop condition is met.
virtual bool matchParametersValues(const ParameterList &params, std::vector< size_t > *updatedParameters=0)
Update the parameters from params.
std::shared_ptr< OptimizationStopCondition > getStopCondition() override
Get the stop condition of the optimization algorithm.
virtual void updateParameters(bool yn)=0
Tell if we shall update all parameters after one optimization step.
MetaOptimizer(std::shared_ptr< FunctionInterface > function, std::unique_ptr< MetaOptimizerInfos > desc, unsigned int n=1)
Build a new MetaOptimizer object.
static std::string IT_TYPE_STEP
Definition: MetaOptimizer.h:23
STL namespace.
void setDefaultStopCondition_(std::shared_ptr< OptimizationStopCondition > osc)
ParameterList & getParameters_()
const ParameterList & getParameters() const override
std::shared_ptr< OutputStream > getProfiler() const override
std::string getConstraintPolicy() const override
Get the constraint policy for this optimizer.
static std::string IT_TYPE_FULL
Definition: MetaOptimizer.h:24
The parameter list object.
Definition: ParameterList.h:27
virtual ~MetaOptimizer()
virtual unsigned int getNumberOfEvaluations() const =0
Get the number of function evaluations performed since the call of the init function.
virtual void setMessageHandler(std::shared_ptr< OutputStream > mh)=0
Set the message handler for this optimizer.
bool tolIsReached_
Tell if the tolerance level has been reached.
std::vector< ParameterList > optParameters_
void setOptimizationProgressCharacter(const std::string &c)
Set the character to be displayed during optimization.
virtual double step()=0
Perform an optimization step.
unsigned int getVerbose() const override
Get the verbose level.
void doInit(const ParameterList &parameters) override
This function is called by the init() method and contains all calculations.
virtual bool hasParameter(const std::string &name) const
virtual void init(const ParameterList &params)=0
Set the initial values of the parameters.
virtual void setProfiler(std::shared_ptr< OutputStream > profiler)=0
Set the profiler for this optimizer.
virtual const ParameterList & getParameters() const =0
static std::shared_ptr< OutputStream > message
The output stream where messages have to be displayed.
Meta-optimizer.
MetaOptimizer * clone() const override
Create a copy of this object and send a pointer to it.
bool updateParameters() const override
Tell if we shall update all parameters after one optimization step.
Exception base class. Overload exception constructor (to control the exceptions mechanism). Destructor is already virtual (from std::exception)
Definition: Exceptions.h:20
This is the basal interface for all optimization methods.
Definition: Optimizer.h:88
Provide a list of optimizer and corresponding options to be used with the MetaOptimizer class...
Definition: MetaOptimizer.h:19
unsigned int nbEval_
The current number of function evaluations achieved.
Partial implementation of the Optimizer interface.
double doStep() override
This function is called by the step() method and contains all calculations.
std::shared_ptr< OutputStream > getMessageHandler() const override
std::shared_ptr< const FunctionInterface > getFunction() const override
Get the current function being optimized.
unsigned int stepCount_
std::shared_ptr< OptimizationStopCondition > getDefaultStopCondition() override
Get the default stop condition of the optimization algorithm.
std::vector< size_t > nbParameters_
void setStopCondition(std::shared_ptr< OptimizationStopCondition > stopCondition) override
Set the stop condition of the optimization algorithm.
virtual std::shared_ptr< OptimizationStopCondition > getStopCondition()=0
Get the stop condition of the optimization algorithm.