FOX/ObjCryst++  1.10.X (development)
GlobalOptimObj.h
1 /* ObjCryst++ Object-Oriented Crystallographic Library
2  (c) 2000-2002 Vincent Favre-Nicolin vincefn@users.sourceforge.net
3  2000-2001 University of Geneva (Switzerland)
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program; if not, write to the Free Software
17  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 /* OptimizationObj.h
20 * header file for the Global Optimization object
21 *
22 */
23 #ifndef _GLOBALOPTIMOBJ_H
24 #define _GLOBALOPTIMOBJ_H
25 
26 #include <map>
27 #include "ObjCryst/ObjCryst/General.h"
28 
29 namespace ObjCryst
30 {
31  class OptimizationObj;
32  class MonteCarloObj;
33 }
34 
35 #include "ObjCryst/RefinableObj/RefinableObj.h"
36 #include "ObjCryst/RefinableObj/LSQNumObj.h"
37 #include "ObjCryst/RefinableObj/IO.h"
38 #include "ObjCryst/RefinableObj/Tracker.h"
39 #include <string>
40 #include <iostream>
41 #ifdef __WX__CRYST__
42  //#undef GetClassName // Conflict from wxMSW headers ? (cygwin)
43 #include "ObjCryst/wxCryst/wxGlobalOptimObj.h"
44 #endif
45 
46 namespace ObjCryst
47 {
67 {
68  ANNEALING_CONSTANT,
69  ANNEALING_BOLTZMANN,
70  ANNEALING_CAUCHY,
71 // ANNEALING_QUENCHING,
72  ANNEALING_EXPONENTIAL,
73  ANNEALING_SMART,
74  ANNEALING_GAMMA
75 };
76 
83 {
84  GLOBAL_OPTIM_SIMULATED_ANNEALING,
85  GLOBAL_OPTIM_PARALLEL_TEMPERING,
86  GLOBAL_OPTIM_RANDOM_LSQ,
87  GLOBAL_OPTIM_SIMULATED_ANNEALING_MULTI,
88  GLOBAL_OPTIM_PARALLEL_TEMPERING_MULTI,
89 };
90 
103 {
104  public:
106  OptimizationObj(const string name="");
108  virtual ~OptimizationObj();
109 
112  virtual void RandomizeStartingConfig();
120  virtual void Optimize(long &nbSteps,const bool silent=false,const REAL finalcost=0,
121  const REAL maxTime=-1)=0;
133  virtual void MultiRunOptimize(long &nbCycle,long &nbSteps,const bool silent=false,const REAL finalcost=0,
134  const REAL maxTime=-1)=0;
135  //Set Refinable parameters status
137  void FixAllPar();
139  void SetParIsFixed(const string& parName,const bool fix);
141  void SetParIsFixed(const RefParType *type,const bool fix);
143  void UnFixAllPar();
145  void SetParIsUsed(const string& parName,const bool use);
147  void SetParIsUsed(const RefParType *type,const bool use);
149  void SetLimitsRelative(const string &parName, const REAL min, const REAL max);
151  void SetLimitsRelative(const RefParType *type, const REAL min, const REAL max);
153  void SetLimitsAbsolute(const string &parName, const REAL min, const REAL max);
155  void SetLimitsAbsolute(const RefParType *type, const REAL min, const REAL max);
156 
162  virtual REAL GetLogLikelihood()const;
163 
165  void StopAfterCycle();
167  virtual void DisplayReport();
168 
173  RefinableObj& GetFullRefinableObj(const bool rebuild=true);
180  virtual void XMLOutput(ostream &os,int indent=0)const=0;
186  virtual void XMLInput(istream &is,const XMLCrystTag &tag)=0;
187  //virtual void XMLInputOld(istream &is,const IOCrystTag &tag);
189  const string& GetName()const;
191  void SetName(const string&);
193  virtual const string GetClassName()const;
195  virtual void Print()const;
199  bool IsOptimizing()const;
203  void TagNewBestConfig();
205  REAL GetLastOptimElapsedTime()const;
209  const MainTracker& GetMainTracker()const;
210  RefObjOpt& GetXMLAutoSaveOption();
211  const RefObjOpt& GetXMLAutoSaveOption()const;
213  const REAL& GetBestCost()const;
215  REAL& GetBestCost();
217  virtual void BeginOptimization(const bool allowApproximations=false,
218  const bool enableRestraints=false);
220  virtual void EndOptimization();
222  virtual long& NbTrialPerRun();
224  virtual const long& NbTrialPerRun() const;
225  protected:
227  void PrepareRefParList();
228 
230  virtual void InitOptions();
233  virtual void UpdateDisplay();
244  string mName;
247 
248  //Status of optimization
252  long mNbTrial;
254  REAL mBestCost;
259  unsigned long mContext;
262  {
269  };
272  mutable map <unsigned long, map<const RefinableObj*,LogLikelihoodStats> > mvContextObjStats;
273  // Dynamic weights (EXPERIMENTAL!)
275  {
276  DynamicObjWeight():mWeight(1.){};
277  REAL mWeight;
278  };
281  mutable map<const RefinableObj*,DynamicObjWeight> mvObjWeight;
282 
289  std::vector<pair<long,REAL> > mvSavedParamSet;
290 
295 
296  // Refined objects
302 
305 
311  private:
312  #ifdef __WX__CRYST__
313  public:
315  virtual WXCrystObjBasic* WXCreate(wxWindow*)=0;
316  virtual WXOptimizationObj* WXGet()=0;
317  virtual void WXDelete()=0;
318  virtual void WXNotifyDelete()=0;
319  protected:
320  //:TODO: remove this !
321  friend class ObjCryst::WXOptimizationObj;
322  //friend class ObjCryst::WXMonteCarloObj;
323  //friend class ObjCryst::WXGeneticAlgorithm;
325  wxMutex mMutexStopAfterCycle;
326  #endif
327 };
328 
337 {
338  public:
340  MonteCarloObj(const string name="");
344  MonteCarloObj(const bool internalUseOnly);
346  virtual ~MonteCarloObj();
347 
375  void SetAlgorithmSimulAnnealing(const AnnealingSchedule scheduleTemp,
376  const REAL tMax, const REAL tMin,
377  const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT,
378  const REAL mutMax=16., const REAL mutMin=.125,
379  const long nbTrialRetry=0,const REAL minCostRetry=0.);
398  void SetAlgorithmParallTempering(const AnnealingSchedule scheduleTemp,
399  const REAL tMax, const REAL tMin,
400  const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT,
401  const REAL mutMax=16., const REAL mutMin=.125);
402 
403  virtual void Optimize(long &nbSteps,const bool silent=false,const REAL finalcost=0,
404  const REAL maxTime=-1);
405  virtual void MultiRunOptimize(long &nbCycle,long &nbSteps,const bool silent=false,const REAL finalcost=0,
406  const REAL maxTime=-1);
407 
411  void RunSimulatedAnnealing(long &nbSteps,const bool silent=false,const REAL finalcost=0,
412  const REAL maxTime=-1);
416  void RunParallelTempering(long &nbSteps,const bool silent=false,const REAL finalcost=0,
417  const REAL maxTime=-1);
418 
419  void RunRandomLSQMethod(long &nbCycle);
420 
421  //Parameter Access by name
422  //RefinablePar& GetPar(const string& parName);
423 
424  // Print information about the current state of optimization (parameters value,
425  // characteristic figures...)
426  //virtual ostream& operator<<(ostream& os)const;
427  virtual void XMLOutput(ostream &os,int indent=0)const;
428  virtual void XMLInput(istream &is,const XMLCrystTag &tag);
429  //virtual void XMLInputOld(istream &is,const IOCrystTag &tag);
430  virtual const string GetClassName()const;
432  LSQNumObj & GetLSQObj();
434  const LSQNumObj & GetLSQObj() const;
435 
442  virtual void InitLSQ(const bool useFullPowderPatternProfile=true);
443  protected:
444 
459  virtual void NewConfiguration(const RefParType *type=gpRefParTypeObjCryst);
460 
461  virtual void InitOptions();
462 
466 
467  //Status of optimization
470 
471  // History, for experimental purposes only !
475 
476  // Annealing parameters
487  //Parameters to create new configurations
501  //Automatic retry
511  private:
512  #ifdef __WX__CRYST__
513  public:
514  virtual WXCrystObjBasic* WXCreate(wxWindow*);
515  virtual WXOptimizationObj* WXGet();
516  virtual void WXDelete();
517  virtual void WXNotifyDelete();
518  protected:
519  WXMonteCarloObj* mpWXCrystObj;
520  friend class ObjCryst::WXMonteCarloObj;
521  #endif
522 };
523 
526 
527 }// namespace
528 
529 #endif //_GLOBALOPTIMOBJ_H
void SetName(const string &)
Set the name for this object.
void SetLimitsRelative(const string &parName, const REAL min, const REAL max)
Change the relative limits for a parameter from its name.
OptimizationObj(const string name="")
Constructor.
virtual void XMLOutput(ostream &os, int indent=0) const =0
Output a description of the object in XML format to a stream.
RefObjOpt mAutoLSQ
Option to run automatic least-squares refinements.
void RunSimulatedAnnealing(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
virtual void RandomizeStartingConfig()
Randomize starting configuration.
virtual void InitLSQ(const bool useFullPowderPatternProfile=true)
Prepare mLSQ for least-squares refinement during the global optimization.
string mName
Name of the GlobalOptimization object.
virtual void MultiRunOptimize(long &nbCycle, long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)=0
Launch optimization for multiple runs of N steps.
virtual void Optimize(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
Launch optimization (a single run) for N steps.
long mNbTrialRetry
Number of trials before testing if we are below the given minimum cost.
REAL mTemperature
Current temperature for annealing.
void BuildRecursiveRefObjList()
(Re)build OptimizationObj::mRecursiveRefinedObjList, if an object has been added or modified...
REAL mCurrentCost
Current value of the cost function.
void AddRefinableObj(RefinableObj &)
Add a refined object. All sub-objects are also added.
AnnealingSchedule
Annealing schedule type.
virtual void XMLInput(istream &is, const XMLCrystTag &tag)=0
Input in XML format from a stream, restoring the set of refined objects and the associated cost funct...
string mSaveFileName
File name where refinement info is saved (NOT USED so far...)
REAL mTemperatureMax
Beginning temperature for annealing.
RefObjOpt mGlobalOptimType
Method used for the global optimization.
LSQNumObj & GetLSQObj()
Access to the builtin LSQ optimization object.
ObjRegistry< OptimizationObj > gOptimizationObjRegistry("List of all Optimization objects")
Global Registry for all OptimizationObj.
void SetParIsFixed(const string &parName, const bool fix)
Fix one parameter.
void SetParIsUsed(const string &parName, const bool use)
Set a parameter to be used.
virtual void Optimize(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)=0
Launch optimization (a single run) for N steps.
virtual void DisplayReport()
Show report to the user during refinement. Used for GUI update.
REAL GetLastOptimElapsedTime() const
Get the elapsed time (in seconds) during the last optimization.
void FixAllPar()
Fix all parameters.
GlobalOptimType
Global optimization type.
Generic Refinable Object.
Definition: RefinableObj.h:752
REAL mTotalLogLikelihood
Total Log(Likelihood), to compute the average.
MonteCarloObj(const string name="")
Constructor.
bool mStopAfterCycle
If true, then stop at the end of the cycle. Used in multi-threaded environment.
MainTracker mMainTracker
MainTracker object to track the evolution of cost functions, likelihood, and individual parameters...
REAL mTemperatureMin
Lower temperature.
Abstract base class for all objects in wxCryst.
Definition: wxCryst.h:127
REAL mMutationAmplitudeGamma
Gamma for the 'gamma' Mutation amplitude schedule.
REAL mMutationAmplitude
Mutation amplitude.
Base object for Monte-Carlo Global Optimization methods.
const string & GetName() const
Get the name for this object.
REAL mBestCost
Best value of the cost function so far.
LSQNumObj mLSQ
Least squares object.
virtual ~OptimizationObj()
Destructor.
long mBestParSavedSetIndex
Index of the 'best' saved parameter set.
Base class for options.
Definition: RefinableObj.h:550
virtual void Print() const
Print some information about this object.
virtual void NewConfiguration(const RefParType *type=gpRefParTypeObjCryst)
Make a random change in the configuration.
void TagNewBestConfig()
During a global optimization, tell all objects that the current config is the latest "best" config...
REAL mMutationAmplitudeMin
Mutation amplitude at the end of the optimization.
void SetAlgorithmParallTempering(const AnnealingSchedule scheduleTemp, const REAL tMax, const REAL tMin, const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT, const REAL mutMax=16., const REAL mutMin=.125)
Set the refinement method to Parallel Tempering.
void SetLimitsAbsolute(const string &parName, const REAL min, const REAL max)
Change the absolute limits for a parameter from its name.
RefObjOpt mAnnealingScheduleTemp
Schedule for the annealing.
unsigned long mContext
The current 'context', in the case the optimization is run in different parallel contexts.
RefinableObj & GetFullRefinableObj(const bool rebuild=true)
Get the RefinableObj with all the parameters from all refined objects.
bool IsOptimizing() const
Are we busy optimizing ?
virtual void MultiRunOptimize(long &nbCycle, long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
Launch optimization for multiple runs of N steps.
Statistics about each object contributing to the overall Log(likelihood)
long mNbTrialPerRun
Number of trial per run, to be saved/restored in XML output.
RefinableObj mRefParList
The refinable par list used during refinement.
virtual const string GetClassName() const
Get the name for this class type.
RefObjOpt mXMLAutoSave
Periodic save of complete environment as an xml file.
void RunParallelTempering(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
A class to hold all trackers.
Definition: Tracker.h:68
void RestoreBestConfiguration()
Restore the Best configuration.
virtual ~MonteCarloObj()
Destructor.
ObjRegistry< RefinableObj > mRefinedObjList
The refined objects.
REAL mLastOptimTime
The time elapsed after the last optimization, in seconds.
void UnFixAllPar()
UnFix All parameters.
MainTracker & GetMainTracker()
Get the MainTracker.
map< const RefinableObj *, DynamicObjWeight > mvObjWeight
Weights for each objects in each context (mutable for dynamic update during optimization) ...
Class for Graphical interface to Monte-Carlo objects (Simulated Annealing, Parallel Tempering) ...
REAL mMutationAmplitudeMax
Mutation amplitude at the beginning of the optimization.
Base object for Optimization methods.
ObjRegistry< RefinableObj > mRecursiveRefinedObjList
The refined objects, recursively including all sub-objects.
REAL mMinCostRetry
Cost to reach unless an automatic randomization and retry is done.
void StopAfterCycle()
Stop after the current cycle. USed for interactive refinement.
The namespace which includes all objects (crystallographic and algorithmic) in ObjCryst++.
Definition: Atom.cpp:47
WX Class for a Global Optimization objects.
RefObjOpt mAnnealingScheduleMutation
Schedule for the annealing.
virtual void EndOptimization()
End optimization for all objects.
virtual const string GetClassName() const
Get the name for this class type.
virtual void XMLInput(istream &is, const XMLCrystTag &tag)
Input in XML format from a stream, restoring the set of refined objects and the associated cost funct...
map< unsigned long, map< const RefinableObj *, LogLikelihoodStats > > mvContextObjStats
Statistics for each context (mutable for dynamic update during optimization)
bool mIsOptimizing
True if a refinement is being done. For multi-threaded environment.
virtual void InitOptions()
Initialization of options.
virtual void XMLOutput(ostream &os, int indent=0) const
Output a description of the object in XML format to a stream.
(Quick & dirty) Least-Squares Refinement Object with Numerical derivatives
Definition: LSQNumObj.h:37
virtual void BeginOptimization(const bool allowApproximations=false, const bool enableRestraints=false)
Begin optimization for all objects.
REAL mLastLogLikelihood
Previous log(likelihood)
virtual void UpdateDisplay()
Update Display (if any display is available), when a new 'relevant' configuration is reached...
class to input or output a well-formatted xml beginning or ending tag.
REAL mTemperatureGamma
Gamma for the 'gamma' temperature schedule.
RefObjOpt mSaveTrackedData
Option to save the evolution of tracked data (cost functions, likelihhod, individual parameters...
class of refinable parameter types.
Definition: RefinableObj.h:78
void SetAlgorithmSimulAnnealing(const AnnealingSchedule scheduleTemp, const REAL tMax, const REAL tMin, const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT, const REAL mutMax=16., const REAL mutMin=.125, const long nbTrialRetry=0, const REAL minCostRetry=0.)
Set the refinement method to simulated Annealing.
long mNbTrial
Number of trials so far.
virtual long & NbTrialPerRun()
Number of trial per run.
std::vector< pair< long, REAL > > mvSavedParamSet
List of saved parameter sets.
const RefParType * gpRefParTypeObjCryst
Top RefParType for the ObjCryst++ library.
Object Registry.
Definition: RefinableObj.h:643
virtual REAL GetLogLikelihood() const
The optimized (minimized, actually) function.
const REAL & GetBestCost() const
Access to current best cost.
virtual void InitOptions()
Initialization of options.
REAL mTotalLogLikelihoodDeltaSq
total of (Delta(Log(Likelihood)))^2 between successive trials