bpp-core3  3.0.0
AbstractOptimizer.cpp
Go to the documentation of this file.
1 //
2 // File: AbstractOptimizer.cpp
3 // Authors:
4 // Julien Dutheil
5 // Created: 2003-12-22 12:18:09
6 //
7 
8 /*
9  Copyright or © or Copr. Bio++ Development Team, (November 17, 2004)
10 
11  This software is a computer program whose purpose is to provide classes
12  for numerical calculus.
13 
14  This software is governed by the CeCILL license under French law and
15  abiding by the rules of distribution of free software. You can use,
16  modify and/ or redistribute the software under the terms of the CeCILL
17  license as circulated by CEA, CNRS and INRIA at the following URL
18  "http://www.cecill.info".
19 
20  As a counterpart to the access to the source code and rights to copy,
21  modify and redistribute granted by the license, users are provided only
22  with a limited warranty and the software's author, the holder of the
23  economic rights, and the successive licensors have only limited
24  liability.
25 
26  In this respect, the user's attention is drawn to the risks associated
27  with loading, using, modifying and/or developing or reproducing the
28  software by the user in light of its specific status of free software,
29  that may mean that it is complicated to manipulate, and that also
30  therefore means that it is reserved for developers and experienced
31  professionals having in-depth computer knowledge. Users are therefore
32  encouraged to load and test the software's suitability as regards their
33  requirements in conditions enabling the security of their systems and/or
34  data to be ensured and, more generally, to use and operate it in the
35  same conditions as regards security.
36 
37  The fact that you are presently reading this means that you have had
38  knowledge of the CeCILL license and that you accept its terms.
39 */
40 
41 
42 #include "../../App/ApplicationTools.h"
43 #include "../../Text/TextTools.h"
44 #include "../AutoParameter.h"
45 #include "AbstractOptimizer.h"
46 
47 // From the STL:
48 #include <iomanip>
49 #include <time.h>
50 
51 using namespace std;
52 using namespace bpp;
53 
54 /******************************************************************************/
55 
56 AbstractOptimizer::AbstractOptimizer(Function* function) :
57  function_(function),
58  parameters_(),
59  messageHandler_(ApplicationTools::message.get()),
60  profiler_(ApplicationTools::message.get()),
61  constraintPolicy_(AutoParameter::CONSTRAINTS_KEEP),
62  stopCondition_(0), defaultStopCondition_(0),
63  verbose_(true), isInitialized_(false), startTime_(), listeners_(),
64  updateParameters_(false), stepChar_("*"),
65  nbEvalMax_(1000000), nbEval_(0),
66  currentValue_(0), tolIsReached_(false)
67 {}
68 
69 /******************************************************************************/
70 
72  function_(opt.function_),
73  parameters_(opt.parameters_),
74  messageHandler_(opt.messageHandler_),
75  profiler_(opt.profiler_),
76  constraintPolicy_(opt.constraintPolicy_),
77  stopCondition_(0), defaultStopCondition_(0),
78  verbose_(opt.verbose_),
79  isInitialized_(opt.isInitialized_),
80  startTime_(opt.startTime_),
81  listeners_(), // We do not copy listeners!
82  updateParameters_(opt.updateParameters_),
83  stepChar_(opt.stepChar_),
84  nbEvalMax_(opt.nbEvalMax_),
85  nbEval_(opt.nbEval_),
86  currentValue_(opt.currentValue_),
87  tolIsReached_(opt.tolIsReached_)
88 {
89  if (opt.stopCondition_)
90  {
93  }
94  else
95  stopCondition_ = 0;
96  if (opt.defaultStopCondition_)
97  {
100  }
101  else
103  // In case of AutoParameter instances, we must actualize the pointers toward _messageHandler:
104  if (isInitialized_)
105  {
107  autoParameter();
110  }
111 }
112 
113 /******************************************************************************/
114 
116 {
117  function_ = opt.function_;
118  parameters_ = opt.parameters_;
120  profiler_ = opt.profiler_;
123  if (opt.stopCondition_)
124  {
127  }
128  else
129  stopCondition_ = 0;
130  if (opt.defaultStopCondition_)
131  {
134  }
135  else
137  nbEvalMax_ = opt.nbEvalMax_;
138  nbEval_ = opt.nbEval_;
139  verbose_ = opt.verbose_;
141  // In case of AutoParameter instances, we must actualize the pointers toward messageHandler_:
142  if (isInitialized_)
143  {
145  autoParameter();
148  }
149  startTime_ = opt.startTime_;
150  listeners_.resize(0); // Reset listener list, do not copy it!
152  stepChar_ = opt.stepChar_;
153  return *this;
154 }
155 
156 /******************************************************************************/
157 
159 {
160  if (!function_)
161  throw Exception("AbstractOptimizer::init. Optimizer currently has no function.");
162  // We do this in order to keep original constraints:
163  parameters_ = params;
164  // More secure, but too slow:
165  // parameters_ = function_->getParameters().createSubList(params.getParameterNames());
166  // parameters_.matchParametersValues(params);
168  autoParameter();
171  doInit(params);
172  nbEval_ = 0;
173  tolIsReached_ = false;
174  isInitialized_ = true;
175  time(&startTime_);
177 
178  profile("Step\t");
179  for (unsigned int i = 0; i < parameters_.size(); i++)
180  {
181  profile(parameters_[i].getName() + "\t");
182  }
183  profileln("Function\tTime");
184 
185  // Parameters must be assigned by doInit:
186 
188 
189  // Initialize the StopCondition:
190  stopCondition_->init();
192 }
193 
194 /******************************************************************************/
195 
197 {
198  currentValue_ = doStep();
202  {
203  if (!updateParameters_)
205  // else already done!
206  // _currentValue = function_->getValue();
207  // Often useless, but avoid some bizare behaviour in particular cases:
209  }
211  return currentValue_;
212 }
213 
214 /**************************************************************************/
215 
217 {
218  if (!isInitialized_)
219  throw Exception("AbstractOptimizer::optimize. Optimizer not initialized: call the 'init' method first!");
220  tolIsReached_ = false;
221  for (nbEval_ = 1; nbEval_ < nbEvalMax_ && !tolIsReached_; nbEval_++)
222  {
223  if (verbose_)
225  step();
226  }
227  return currentValue_;
228 }
229 
230 /******************************************************************************/
231 
233 {
234  if (profiler_)
235  *profiler_ << v;
236 }
237 
238 /******************************************************************************/
239 
241 {
242  if (profiler_)
243  (*profiler_ << v).endLine();
244 }
245 
246 /******************************************************************************/
247 
248 void AbstractOptimizer::profile(unsigned int v)
249 {
250  if (profiler_)
251  *profiler_ << v;
252 }
253 /******************************************************************************/
254 
255 void AbstractOptimizer::profileln(unsigned int v)
256 {
257  if (profiler_)
258  (*profiler_ << v).endLine();
259 }
260 
261 /******************************************************************************/
262 
263 void AbstractOptimizer::profile(const std::string& s)
264 {
265  if (profiler_)
266  *profiler_ << s;
267 }
268 
269 /******************************************************************************/
270 
271 void AbstractOptimizer::profileln(const std::string& s)
272 {
273  if (profiler_)
274  (*profiler_ << s).endLine();
275 }
276 
277 /******************************************************************************/
278 
279 void AbstractOptimizer::printPoint(const ParameterList& params, double value)
280 {
281  size_t ndim = params.size();
282  profile(nbEval_);
283  profile("\t");
284  for (size_t j = 0; j < ndim; j++)
285  {
286  profile(TextTools::toString(params[j].getValue()));
287  profile("\t");
288  }
289  profile(value);
290  profile("\t");
291  time_t seconds;
292  time(&seconds);
293  profileln(difftime(seconds, startTime_));
294 }
295 
296 /******************************************************************************/
297 
298 void AbstractOptimizer::printMessage(const std::string& message)
299 {
300  if (messageHandler_)
301  (*messageHandler_ << message).endLine();
302 }
303 
304 /******************************************************************************/
305 
307 {
308  for (unsigned int i = 0; i < parameters_.size(); i++)
309  {
310  AutoParameter ap(parameters_[i]);
312  parameters_.setParameter(i, ap);
313  }
314 }
315 
316 /******************************************************************************/
317 
319 {
320  for (unsigned int i = 0; i < parameters_.size(); i++)
321  {
322  parameters_[i].removeConstraint();
323  }
324 }
325 
326 /******************************************************************************/
327 
329 {
330  for (unsigned int i = 0; i < listeners_.size(); i++)
331  {
332  listeners_[i]->optimizationInitializationPerformed(event);
333  }
334 }
335 
336 /******************************************************************************/
337 
339 {
340  for (unsigned int i = 0; i < listeners_.size(); i++)
341  {
342  listeners_[i]->optimizationStepPerformed(event);
343  }
344 }
345 
346 /******************************************************************************/
347 
349 {
350  for (unsigned int i = 0; i < listeners_.size(); i++)
351  {
353  return true;
354  }
355  return false;
356 }
357 
358 /******************************************************************************/
Partial implementation of the Optimizer interface.
void ignoreConstraints()
Remove the constraints of all the arguments.
Function * function_
The function to optimize.
std::vector< OptimizationListener * > listeners_
OptimizationStopCondition * stopCondition_
The stoping condition to use while optimizing.
void fireOptimizationInitializationPerformed(const OptimizationEvent &event)
Notify all listeners that optimizer initialization was performed.
void printPoint(const ParameterList &params, double value)
Print parameters and corresponding function evaluation to profiler.
double step()
Basic implementation.
double optimize()
Basic implementation.
void printMessage(const std::string &message)
Give a message to print to the message handler.
bool listenerModifiesParameters() const
void profileln(double v)
Print to the profile if there is one and end line.
unsigned int nbEvalMax_
The maximum number of function evaluations allowed.
void fireOptimizationStepPerformed(const OptimizationEvent &event)
Notify all listeners that an optimization step was performed.
OutputStream * profiler_
The profiler.
unsigned int nbEval_
The current number of function evaluations achieved.
OptimizationStopCondition * defaultStopCondition_
The default stoping condition to use while optimizing.
AbstractOptimizer(Function *function=0)
void init(const ParameterList &params)
Basic implementation.
OutputStream * messageHandler_
The message handler.
unsigned int verbose_
State of the verbose mode: > 0 = enabled.
std::string constraintPolicy_
The constraint policy.
bool isInitialized_
Check if the optimizer have been feeded with initial parameters values.
double currentValue_
The current value of the function.
bool tolIsReached_
Tell if the tolerance level has been reached.
virtual void doInit(const ParameterList &params)=0
This function is called by the init() method and contains all calculations.
void profile(double v)
Print to the profile if there is one.
void autoParameter()
Build a list of AutoParameter instead of Parameter.
AbstractOptimizer & operator=(const AbstractOptimizer &opt)
ParameterList parameters_
The parameters that will be optimized.
virtual double doStep()=0
This function is called by the step() method and contains all calculations.
This class provides some common tools for developping applications.
static void displayUnlimitedGauge(size_t iter, const std::string &mes="")
Display a gauge for unefined amount of iterations.
The AutoParameter class.
Definition: AutoParameter.h:61
static std::string CONSTRAINTS_AUTO
static std::string CONSTRAINTS_IGNORE
virtual void setMessageHandler(OutputStream *mh)
Set the message handler for this AutoParameter.
Exception base class. Overload exception constructor (to control the exceptions mechanism)....
Definition: Exceptions.h:59
This is the function abstract class.
Definition: Functions.h:89
virtual double getValue() const =0
Get the value of the function at the current point.
virtual double f(const ParameterList &parameters)
Get the value of the function according to a given set of parameters.
Definition: Functions.h:117
An event object which indicates that an optimization event occured.
Definition: Optimizer.h:57
Interface for otimization stop condition objet.
OptimizationStopCondition * clone() const =0
Create a copy of this object and send a pointer to it.
virtual bool isToleranceReached() const =0
Tell if the we reached the desired tolerance with a given new set of estimates.
virtual void setOptimizer(const Optimizer *optimizer)=0
Set the optimizer attached to this instance.
virtual void init()=0
Initialize the condition.
The parameter list object.
Definition: ParameterList.h:65
size_t size() const
Definition: ParameterList.h:92
virtual bool matchParametersValues(const ParameterList &params, std::vector< size_t > *updatedParameters=0)
Update the parameters from params.
virtual void setParameter(size_t index, const Parameter &param)
Change given parameter.
virtual const ParameterList & getParameters() const =0
Get all parameters available.
std::string toString(T t)
General template method to convert to a string.
Definition: TextTools.h:153