FOX/ObjCryst++  2022
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();
108  OptimizationObj(const string name);
110  OptimizationObj(const OptimizationObj &old);
112  virtual ~OptimizationObj();
113 
116  virtual void RandomizeStartingConfig();
124  virtual void Optimize(long &nbSteps,const bool silent=false,const REAL finalcost=0,
125  const REAL maxTime=-1)=0;
137  virtual void MultiRunOptimize(long &nbCycle,long &nbSteps,const bool silent=false,const REAL finalcost=0,
138  const REAL maxTime=-1)=0;
139  //Set Refinable parameters status
141  void FixAllPar();
143  void SetParIsFixed(const string& parName,const bool fix);
145  void SetParIsFixed(const RefParType *type,const bool fix);
147  void UnFixAllPar();
149  void SetParIsUsed(const string& parName,const bool use);
151  void SetParIsUsed(const RefParType *type,const bool use);
153  void SetLimitsRelative(const string &parName, const REAL min, const REAL max);
155  void SetLimitsRelative(const RefParType *type, const REAL min, const REAL max);
157  void SetLimitsAbsolute(const string &parName, const REAL min, const REAL max);
159  void SetLimitsAbsolute(const RefParType *type, const REAL min, const REAL max);
160 
166  virtual REAL GetLogLikelihood()const;
167 
169  void StopAfterCycle();
171  virtual void DisplayReport();
172 
177  RefinableObj& GetFullRefinableObj(const bool rebuild=true);
184  virtual void XMLOutput(ostream &os,int indent=0)const=0;
190  virtual void XMLInput(istream &is,const XMLCrystTag &tag)=0;
191  //virtual void XMLInputOld(istream &is,const IOCrystTag &tag);
193  const string& GetName()const;
195  void SetName(const string&);
197  virtual const string GetClassName()const;
199  virtual void Print()const;
203  bool IsOptimizing()const;
207  void TagNewBestConfig();
209  REAL GetLastOptimElapsedTime()const;
213  const MainTracker& GetMainTracker()const;
214  RefObjOpt& GetXMLAutoSaveOption();
215  const RefObjOpt& GetXMLAutoSaveOption()const;
217  const REAL& GetBestCost()const;
219  REAL& GetBestCost();
221  virtual void BeginOptimization(const bool allowApproximations=false,
222  const bool enableRestraints=false);
224  virtual void EndOptimization();
226  virtual long& NbTrialPerRun();
228  virtual const long& NbTrialPerRun() const;
230  long GetTrial() const;
232  long GetRun() const;
233  //Options
237  unsigned int GetNbOption()const;
239  RefObjOpt& GetOption(const unsigned int i);
241  RefObjOpt& GetOption(const string & name);
243  const RefObjOpt& GetOption(const unsigned int i)const;
245  const RefObjOpt& GetOption(const string & name)const;
250  virtual void UpdateDisplay() const;
252  unsigned int GetNbParamSet() const;
255  long GetParamSetIndex(const unsigned int i) const;
257  long GetParamSetCost(const unsigned int i) const;
261  void RestoreParamSet(const unsigned int i, const bool update_display=true);
262  protected:
264  void PrepareRefParList();
265 
267  virtual void InitOptions();
273  void AddOption(RefObjOpt *opt);
280  string mName;
283 
284  //Status of optimization
288  long mNbTrial;
290  long mRun;
292  REAL mBestCost;
297  unsigned long mContext;
300  {
307  };
310  mutable map <unsigned long, map<const RefinableObj*,LogLikelihoodStats> > mvContextObjStats;
311  // Dynamic weights (EXPERIMENTAL!)
313  {
314  DynamicObjWeight():mWeight(1.){};
315  REAL mWeight;
316  };
319  mutable map<const RefinableObj*,DynamicObjWeight> mvObjWeight;
320 
327  std::vector<pair<long,REAL> > mvSavedParamSet;
328 
333 
334  // Refined objects
342 
345 
355  private:
356  #ifdef __WX__CRYST__
357  public:
359  virtual WXCrystObjBasic* WXCreate(wxWindow*)=0;
360  virtual WXOptimizationObj* WXGet()=0;
361  virtual void WXDelete()=0;
362  virtual void WXNotifyDelete()=0;
363  protected:
364  //:TODO: remove this !
365  friend class ObjCryst::WXOptimizationObj;
366  //friend class ObjCryst::WXMonteCarloObj;
367  //friend class ObjCryst::WXGeneticAlgorithm;
369  wxMutex mMutexStopAfterCycle;
370  #endif
371 };
372 
381 {
382  public:
384  MonteCarloObj();
386  MonteCarloObj(const string name);
388  MonteCarloObj(const MonteCarloObj &old);
392  MonteCarloObj(const bool internalUseOnly);
394  virtual ~MonteCarloObj();
395 
423  void SetAlgorithmSimulAnnealing(const AnnealingSchedule scheduleTemp,
424  const REAL tMax, const REAL tMin,
425  const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT,
426  const REAL mutMax=16., const REAL mutMin=.125,
427  const long nbTrialRetry=0,const REAL minCostRetry=0.);
446  void SetAlgorithmParallTempering(const AnnealingSchedule scheduleTemp,
447  const REAL tMax, const REAL tMin,
448  const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT,
449  const REAL mutMax=16., const REAL mutMin=.125);
450 
451  virtual void Optimize(long &nbSteps,const bool silent=false,const REAL finalcost=0,
452  const REAL maxTime=-1);
453  virtual void MultiRunOptimize(long &nbCycle,long &nbSteps,const bool silent=false,const REAL finalcost=0,
454  const REAL maxTime=-1);
455 
459  void RunSimulatedAnnealing(long &nbSteps,const bool silent=false,const REAL finalcost=0,
460  const REAL maxTime=-1);
464  void RunParallelTempering(long &nbSteps,const bool silent=false,const REAL finalcost=0,
465  const REAL maxTime=-1);
466 
467  void RunRandomLSQMethod(long &nbCycle);
468 
469  //Parameter Access by name
470  //RefinablePar& GetPar(const string& parName);
471 
472  // Print information about the current state of optimization (parameters value,
473  // characteristic figures...)
474  //virtual ostream& operator<<(ostream& os)const;
475  virtual void XMLOutput(ostream &os,int indent=0)const;
476  virtual void XMLInput(istream &is,const XMLCrystTag &tag);
477  //virtual void XMLInputOld(istream &is,const IOCrystTag &tag);
478  virtual const string GetClassName()const;
480  LSQNumObj & GetLSQObj();
482  const LSQNumObj & GetLSQObj() const;
483 
490  virtual void InitLSQ(const bool useFullPowderPatternProfile=true);
493  virtual void UpdateDisplay() const;
494  protected:
495 
510  virtual void NewConfiguration(const RefParType *type=gpRefParTypeObjCryst);
511 
512  virtual void InitOptions();
513 
517 
518  //Status of optimization
521 
522  // History, for experimental purposes only !
526 
527  // Annealing parameters
538  //Parameters to create new configurations
552  //Automatic retry
562  private:
563  #ifdef __WX__CRYST__
564  public:
565  virtual WXCrystObjBasic* WXCreate(wxWindow*);
566  virtual WXOptimizationObj* WXGet();
567  virtual void WXDelete();
568  virtual void WXNotifyDelete();
569  protected:
570  WXMonteCarloObj* mpWXCrystObj;
571  friend class ObjCryst::WXMonteCarloObj;
572  #endif
573 };
574 
577 
578 }// namespace
579 
580 #endif //_GLOBALOPTIMOBJ_H
The namespace which includes all objects (crystallographic and algorithmic) in ObjCryst++.
Definition: doc-main.h:25
ObjRegistry< OptimizationObj > gOptimizationObjRegistry("List of all Optimization objects")
Global Registry for all OptimizationObj.
AnnealingSchedule
Annealing schedule type.
const RefParType * gpRefParTypeObjCryst
Top RefParType for the ObjCryst++ library.
GlobalOptimType
Global optimization type.
Base object for Optimization methods.
virtual const string GetClassName() const
Get the name for this class type.
void AddRefinableObj(RefinableObj &)
Add a refined object. All sub-objects are also added.
void SetName(const string &)
Set the name for this object.
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.
ObjRegistry< RefinableObj > mRecursiveRefinedObjList
The refined objects, recursively including all sub-objects.
REAL GetLastOptimElapsedTime() const
Get the elapsed time (in seconds) during the last optimization.
virtual void UpdateDisplay() const
Update Display (if any display is available), when a new 'relevant' configuration is reached.
unsigned int GetNbParamSet() const
Get the number of saved parameters set.
map< unsigned long, map< const RefinableObj *, LogLikelihoodStats > > mvContextObjStats
Statistics for each context (mutable for dynamic update during optimization)
void RestoreParamSet(const unsigned int i, const bool update_display=true)
Restore a given saved parameter set.
ObjRegistry< RefObjOpt > mOptionRegistry
List of options for this object.
bool IsOptimizing() const
Are we busy optimizing ?
void RestoreBestConfiguration()
Restore the Best configuration.
string mSaveFileName
File name where refinement info is saved (NOT USED so far...)
void StopAfterCycle()
Stop after the current cycle. USed for interactive refinement.
virtual void Print() const
Print some information about this object.
RefinableObj & GetFullRefinableObj(const bool rebuild=true)
Get the RefinableObj with all the parameters from all refined objects.
virtual REAL GetLogLikelihood() const
The optimized (minimized, actually) function.
virtual void EndOptimization()
End optimization for all objects.
REAL mBestCost
Best value of the cost function so far.
void AddOption(RefObjOpt *opt)
map< const RefinableObj *, DynamicObjWeight > mvObjWeight
Weights for each objects in each context (mutable for dynamic update during optimization)
OptimizationObj()
Default constructor.
virtual void RandomizeStartingConfig()
Randomize starting configuration.
virtual void DisplayReport()
Show report to the user during refinement. Used for GUI update.
long GetParamSetCost(const unsigned int i) const
Get the cost (log-likelihood) of a saved parameters set.
ObjRegistry< RefObjOpt > & GetOptionList()
Access to the options registry.
virtual void XMLOutput(ostream &os, int indent=0) const =0
Output a description of the object in XML format to a stream.
long GetParamSetIndex(const unsigned int i) const
Get the index of a saved parameters set in the compiled RefinableObj.
bool mIsOptimizing
True if a refinement is being done. For multi-threaded environment.
unsigned long mContext
The current 'context', in the case the optimization is run in different parallel contexts.
ObjRegistry< RefinableObj > mRefinedObjList
The refined objects.
RefObjOpt & GetOption(const unsigned int i)
Access to the options.
void SetLimitsRelative(const string &parName, const REAL min, const REAL max)
Change the relative limits for a parameter from its name.
void BuildRecursiveRefObjList()
(Re)build OptimizationObj::mRecursiveRefinedObjList, if an object has been added or modified.
long mRun
Current run number (during multiple runs)
virtual void InitOptions()
Initialization of options.
std::vector< pair< long, REAL > > mvSavedParamSet
List of saved parameter sets.
long GetRun() const
Current run number (updated during a run)
long GetTrial() const
Current trial number (updated during a run)
RefObjOpt mXMLAutoSave
Periodic save of complete environment as an xml file.
void TagNewBestConfig()
During a global optimization, tell all objects that the current config is the latest "best" config.
RefinableObj mRefParList
The refinable par list used during refinement.
string mName
Name of the GlobalOptimization object.
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...
long mNbTrialPerRun
Number of trial per run, to be saved/restored in XML output.
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.
long mBestParSavedSetIndex
Index of the 'best' saved parameter set.
void SetParIsUsed(const string &parName, const bool use)
Set a parameter to be used.
virtual long & NbTrialPerRun()
Number of trial per run.
MainTracker mMainTracker
MainTracker object to track the evolution of cost functions, likelihood, and individual parameters.
bool mStopAfterCycle
If true, then stop at the end of the cycle. Used in multi-threaded environment.
REAL mLastOptimTime
The time elapsed after the last optimization, in seconds.
const REAL & GetBestCost() const
Access to current best cost.
void SetParIsFixed(const string &parName, const bool fix)
Fix one parameter.
unsigned int GetNbOption() const
Number of Options for this object.
void SetLimitsAbsolute(const string &parName, const REAL min, const REAL max)
Change the absolute limits for a parameter from its name.
virtual void BeginOptimization(const bool allowApproximations=false, const bool enableRestraints=false)
Begin optimization for all objects.
const string & GetName() const
Get the name for this object.
void UnFixAllPar()
UnFix All parameters.
virtual ~OptimizationObj()
Destructor.
const ObjRegistry< RefinableObj > & GetRefinedObjList() const
Access the list of refined object.
long mNbTrial
Current trial number.
void FixAllPar()
Fix all parameters.
MainTracker & GetMainTracker()
Get the MainTracker.
Statistics about each object contributing to the overall Log(likelihood)
REAL mTotalLogLikelihoodDeltaSq
total of (Delta(Log(Likelihood)))^2 between successive trials
REAL mTotalLogLikelihood
Total Log(Likelihood), to compute the average.
REAL mLastLogLikelihood
Previous log(likelihood)
Base object for Monte-Carlo Global Optimization methods.
REAL mTemperatureMax
Beginning temperature for annealing.
REAL mTemperature
Current temperature for annealing.
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...
REAL mMutationAmplitudeGamma
Gamma for the 'gamma' Mutation amplitude schedule.
long mNbTrialRetry
Number of trials before testing if we are below the given minimum cost.
LSQNumObj mLSQ
Least squares object.
RefObjOpt mAutoLSQ
Option to run automatic least-squares refinements.
virtual ~MonteCarloObj()
Destructor.
virtual void InitOptions()
Initialization of options.
virtual const string GetClassName() const
Get the name for this class type.
virtual void XMLOutput(ostream &os, int indent=0) const
Output a description of the object in XML format to a stream.
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.
RefObjOpt mAnnealingScheduleMutation
Schedule for the annealing.
virtual void NewConfiguration(const RefParType *type=gpRefParTypeObjCryst)
Make a random change in the configuration.
MonteCarloObj()
Default Constructor.
virtual void UpdateDisplay() const
Update Display (if any display is available), when a new 'relevant' configuration is reached.
REAL mMutationAmplitudeMin
Mutation amplitude at the end of the optimization.
void RunParallelTempering(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
void RunSimulatedAnnealing(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
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.
REAL mTemperatureMin
Lower temperature.
REAL mCurrentCost
Current value of the cost function.
REAL mMinCostRetry
Cost to reach unless an automatic randomization and retry is done.
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.
RefObjOpt mSaveTrackedData
Option to save the evolution of tracked data (cost functions, likelihhod, individual parameters,...
virtual void InitLSQ(const bool useFullPowderPatternProfile=true)
Prepare mLSQ for least-squares refinement during the global optimization.
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.
LSQNumObj & GetLSQObj()
Access to the builtin LSQ optimization object.
REAL mMutationAmplitudeMax
Mutation amplitude at the beginning of the optimization.
RefObjOpt mAnnealingScheduleTemp
Schedule for the annealing.
REAL mTemperatureGamma
Gamma for the 'gamma' temperature schedule.
RefObjOpt mGlobalOptimType
Method used for the global optimization.
REAL mMutationAmplitude
Mutation amplitude.
class to input or output a well-formatted xml beginning or ending tag.
(Quick & dirty) Least-Squares Refinement Object with Numerical derivatives
Definition: LSQNumObj.h:39
class of refinable parameter types.
Definition: RefinableObj.h:80
Base class for options.
Definition: RefinableObj.h:552
Object Registry.
Definition: RefinableObj.h:645
Generic Refinable Object.
Definition: RefinableObj.h:784
A class to hold all trackers.
Definition: Tracker.h:69
Abstract base class for all objects in wxCryst.
Definition: wxCryst.h:128
WX Class for a Global Optimization objects.
Class for Graphical interface to Monte-Carlo objects (Simulated Annealing, Parallel Tempering)