25 #include "ObjCryst/RefinableObj/GlobalOptimObj.h"
26 #include "ObjCryst/ObjCryst/Crystal.h"
27 #include "ObjCryst/Quirks/VFNStreamFormat.h"
28 #include "ObjCryst/Quirks/VFNDebug.h"
29 #include "ObjCryst/Quirks/Chronometer.h"
30 #include "ObjCryst/ObjCryst/IO.h"
31 #include "ObjCryst/RefinableObj/LSQNumObj.h"
33 #include "ObjCryst/ObjCryst/Molecule.h"
36 #include "ObjCryst/wxCryst/wxRefinableObj.h"
44 #include <boost/format.hpp>
48 void CompareWorlds(
const CrystVector_long &idx,
const CrystVector_long &swap,
const RefinableObj &obj)
50 const long nb=swap.numElements();
51 const CrystVector_REAL *pv0=&(obj.GetParamSet(idx(swap(nb-1))));
52 for(
long i=0;i<idx.numElements();++i)
55 const CrystVector_REAL *pv1=&(obj.GetParamSet(idx(swap(i))));
56 for(
long j=0;j<pv0->numElements();++j) d += ((*pv0)(j)-(*pv1)(j))*((*pv0)(j)-(*pv1)(j));
57 cout<<
"d("<<i<<
")="<<sqrt(d)<<endl;
69 mName(
""),mSaveFileName(
"GlobalOptim.save"),
70 mNbTrialPerRun(10000000),mNbTrial(0),mRun(0),mBestCost(-1),
71 mBestParSavedSetIndex(-1),
73 mIsOptimizing(false),mStopAfterCycle(false),
74 mRefinedObjList(
"OptimizationObj: "+mName+
" RefinableObj registry"),
75 mRecursiveRefinedObjList(
"OptimizationObj: "+mName+
" recursive RefinableObj registry"),
78 VFN_DEBUG_ENTRY(
"OptimizationObj::OptimizationObj()",5)
83 static bool need_initRandomSeed=
true;
84 if(need_initRandomSeed==
true)
87 need_initRandomSeed=
false;
91 VFN_DEBUG_EXIT(
"OptimizationObj::OptimizationObj()",5)
95 mName(name),mSaveFileName(
"GlobalOptim.save"),
96 mNbTrialPerRun(10000000),mNbTrial(0),mRun(0),mBestCost(-1),
97 mBestParSavedSetIndex(-1),
99 mIsOptimizing(false),mStopAfterCycle(false),
100 mRefinedObjList(
"OptimizationObj: "+mName+
" RefinableObj registry"),
101 mRecursiveRefinedObjList(
"OptimizationObj: "+mName+
" recursive RefinableObj registry"),
104 VFN_DEBUG_ENTRY(
"OptimizationObj::OptimizationObj()",5)
109 static bool need_initRandomSeed=
true;
110 if(need_initRandomSeed==
true)
113 need_initRandomSeed=
false;
117 VFN_DEBUG_EXIT(
"OptimizationObj::OptimizationObj()",5)
121 mName(old.mName),mSaveFileName(old.mSaveFileName),
122 mNbTrialPerRun(old.mNbTrialPerRun),mNbTrial(old.mNbTrial),mRun(old.mRun),mBestCost(old.mBestCost),
123 mBestParSavedSetIndex(-1),
125 mIsOptimizing(false),mStopAfterCycle(false),
126 mRefinedObjList(
"OptimizationObj: "+mName+
" RefinableObj registry"),
127 mRecursiveRefinedObjList(
"OptimizationObj: "+mName+
" recursive RefinableObj registry"),
130 VFN_DEBUG_ENTRY(
"OptimizationObj::OptimizationObj(&old)",5)
135 static bool need_initRandomSeed=
true;
136 if(need_initRandomSeed==
true)
139 need_initRandomSeed=
false;
147 VFN_DEBUG_EXIT(
"OptimizationObj::OptimizationObj(&old)",5)
152 VFN_DEBUG_ENTRY(
"OptimizationObj::~OptimizationObj()",5)
154 VFN_DEBUG_EXIT(
"OptimizationObj::~OptimizationObj()",5)
159 VFN_DEBUG_ENTRY(
"OptimizationObj::RandomizeStartingConfig()",5)
174 VFN_DEBUG_EXIT(
"OptimizationObj::RandomizeStartingConfig()",5)
179 VFN_DEBUG_ENTRY(
"OptimizationObj::FixAllPar()",5)
183 VFN_DEBUG_EXIT(
"OptimizationObj::FixAllPar():End",5)
218 const REAL min,
const REAL max)
225 const REAL min,
const REAL max)
232 const REAL min,
const REAL max)
239 const REAL min,
const REAL max)
248 TAU_PROFILE(
"OptimizationObj::GetLogLikelihood()",
"void ()",TAU_DEFAULT);
268 VFN_DEBUG_MESSAGE(
"OptimizationObj::StopAfterCycle()",5)
272 wxMutexLocker lock(mMutexStopAfterCycle);
285 VFN_DEBUG_MESSAGE(
"OptimizationObj::AddRefinableObj():"<<obj.
GetName(),5)
292 if(0!=this->WXGet()) this->WXGet()->AddRefinedObject(obj);
335 const RefObjOpt& OptimizationObj::GetXMLAutoSaveOption()
const {
return mXMLAutoSave;}
345 mRefinedObjList.GetObj(i).BeginOptimization(allowApproximations,enableRestraints);
374 VFN_DEBUG_MESSAGE(
"RefinableObj::GetOption()"<<i,3)
381 VFN_DEBUG_MESSAGE(
"OptimizationObj::GetOption()"<<name,3)
393 VFN_DEBUG_MESSAGE(
"RefinableObj::GetOption()"<<i,3)
400 VFN_DEBUG_MESSAGE(
"OptimizationObj::GetOption()"<<name,3)
423 throw ObjCrystException(
"OptimizationObj::GetSavedParamSetIndex(i): i > nb saved param set");
431 throw ObjCrystException(
"OptimizationObj::GetSavedParamSetCost(i): i > nb saved param set");
443 VFN_DEBUG_ENTRY(
"OptimizationObj::PrepareRefParList()",6)
453 VFN_DEBUG_MESSAGE(
"OptimizationObj::PrepareRefParList():Rebuild list",6)
467 (this->
GetName()+
"::Overall LogLikelihood",*
this,fl));
482 (pCryst->
GetName()+
"::BumpMergeCost",*pCryst,fc));
485 (pCryst->
GetName()+
"::BondValenceCost",*pCryst,fc));
487 fc=&Crystal::GetInterMolDistCost;
489 (pCryst->
GetName()+
"::InterMolDistCost",*pCryst,fc));
498 VFN_DEBUG_EXIT(
"OptimizationObj::PrepareRefParList()",6)
503 VFN_DEBUG_MESSAGE(
"OptimizationObj::InitOptions()",5)
504 static string xmlAutoSaveName;
505 static string xmlAutoSaveChoices[6];
507 static bool needInitNames=
true;
508 if(
true==needInitNames)
510 xmlAutoSaveName=
"Save Best Config Regularly";
511 xmlAutoSaveChoices[0]=
"No";
512 xmlAutoSaveChoices[1]=
"Every day";
513 xmlAutoSaveChoices[2]=
"Every hour";
514 xmlAutoSaveChoices[3]=
"Every 10mn";
515 xmlAutoSaveChoices[4]=
"Every new best config (a lot ! Not Recommended !)";
516 xmlAutoSaveChoices[5]=
"Every Run (Recommended)";
520 mXMLAutoSave.Init(6,&xmlAutoSaveName,xmlAutoSaveChoices);
522 VFN_DEBUG_MESSAGE(
"OptimizationObj::InitOptions():End",5)
541 VFN_DEBUG_ENTRY(
"OptimizationObj::BuildRecursiveRefObjList()",5)
545 VFN_DEBUG_EXIT(
"OptimizationObj::BuildRecursiveRefObjList()",5)
551 VFN_DEBUG_ENTRY(
"OptimizationObj::AddOption()",5)
553 VFN_DEBUG_EXIT(
"OptimizationObj::AddOption()",5)
564 mTemperatureMax(1e6),mTemperatureMin(.001),mTemperatureGamma(1.0),
565 mMutationAmplitudeMax(8.),mMutationAmplitudeMin(.125),mMutationAmplitudeGamma(1.0),
566 mNbTrialRetry(0),mMinCostRetry(0)
571 VFN_DEBUG_ENTRY(
"MonteCarloObj::MonteCarloObj()",5)
579 VFN_DEBUG_EXIT(
"MonteCarloObj::MonteCarloObj()",5)
585 mTemperatureMax(1e6),mTemperatureMin(.001),mTemperatureGamma(1.0),
586 mMutationAmplitudeMax(8.),mMutationAmplitudeMin(.125),mMutationAmplitudeGamma(1.0),
587 mNbTrialRetry(0),mMinCostRetry(0)
592 VFN_DEBUG_ENTRY(
"MonteCarloObj::MonteCarloObj()",5)
600 VFN_DEBUG_EXIT(
"MonteCarloObj::MonteCarloObj()",5)
605 mCurrentCost(old.mCurrentCost),
606 mTemperatureMax(old.mTemperatureMax),mTemperatureMin(old.mTemperatureMin),
607 mTemperatureGamma(old.mTemperatureGamma),
608 mMutationAmplitudeMax(old.mMutationAmplitudeMax),mMutationAmplitudeMin(old.mMutationAmplitudeMin),
609 mMutationAmplitudeGamma(old.mMutationAmplitudeGamma),
610 mNbTrialRetry(old.mNbTrialRetry),mMinCostRetry(old.mMinCostRetry)
615 VFN_DEBUG_ENTRY(
"MonteCarloObj::MonteCarloObj(&old)",5)
621 VFN_DEBUG_EXIT(
"MonteCarloObj::MonteCarloObj(&old)",5)
627 mTemperatureMax(.03),mTemperatureMin(.003),mTemperatureGamma(1.0),
628 mMutationAmplitudeMax(16.),mMutationAmplitudeMin(.125),mMutationAmplitudeGamma(1.0),
629 mNbTrialRetry(0),mMinCostRetry(0)
634 VFN_DEBUG_ENTRY(
"MonteCarloObj::MonteCarloObj(bool)",5)
642 VFN_DEBUG_EXIT(
"MonteCarloObj::MonteCarloObj(bool)",5)
647 VFN_DEBUG_ENTRY(
"MonteCarloObj::~MonteCarloObj()",5)
649 VFN_DEBUG_EXIT (
"MonteCarloObj::~MonteCarloObj()",5)
652 const REAL tMax,
const REAL tMin,
654 const REAL mutMax,
const REAL mutMin,
655 const long nbTrialRetry,
const REAL minCostRetry)
657 VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmSimulAnnealing()",5)
669 VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmSimulAnnealing():End",3)
673 const REAL tMax,
const REAL tMin,
675 const REAL mutMax,
const REAL mutMin)
677 VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmParallTempering()",5)
688 VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmParallTempering():End",3)
694 TAU_PROFILE(
"MonteCarloObj::Optimize()",
"void (long)",TAU_DEFAULT);
695 VFN_DEBUG_ENTRY(
"MonteCarloObj::Optimize()",5)
716 case GLOBAL_OPTIM_SIMULATED_ANNEALING:
721 case GLOBAL_OPTIM_PARALLEL_TEMPERING:
726 case GLOBAL_OPTIM_RANDOM_LSQ:
729 this->RunRandomLSQMethod(cycles);
735 mMutexStopAfterCycle.Lock();
739 mMutexStopAfterCycle.Unlock();
744 (*fpObjCrystInformUser)((boost::format(
"Finished Optimization, final cost=%12.2f (dt=%.1fs)") % this->
GetLogLikelihood() % chrono.seconds()).str());
749 outTracker.imbue(std::locale::classic());
750 const string outTrackerName=this->
GetName()+
"-Tracker.dat";
751 outTracker.open(outTrackerName.c_str());
769 VFN_DEBUG_EXIT(
"MonteCarloObj::Optimize()",5)
772 const REAL finalcost,
const REAL maxTime)
775 TAU_PROFILE(
"MonteCarloObj::MultiRunOptimize()",
"void (long)",TAU_DEFAULT);
776 VFN_DEBUG_ENTRY(
"MonteCarloObj::MultiRunOptimize()",5)
778 const long nbStep0=nbStep;
795 const long nbCycle0=nbCycle;
800 if(!silent) cout <<
"MonteCarloObj::MultiRunOptimize: Starting Run#"<<abs(nbCycle)<<endl;
807 case GLOBAL_OPTIM_SIMULATED_ANNEALING:
810 catch(...){cout<<
"Unhandled exception in MonteCarloObj::MultiRunOptimize() ?"<<endl;}
813 case GLOBAL_OPTIM_PARALLEL_TEMPERING:
816 catch(...){cout<<
"Unhandled exception in MonteCarloObj::MultiRunOptimize() ?"<<endl;}
819 case GLOBAL_OPTIM_RANDOM_LSQ:
821 try{this->RunRandomLSQMethod(nbCycle);}
822 catch(...){cout<<
"Unhandled exception in MonteCarloObj::RunRandomLSQMethod() ?"<<endl;}
827 nbTrialCumul+=(nbStep0-nbStep);
829 (*fpObjCrystInformUser)((boost::format(
"Finished Run #%d, final cost=%12.2f, nbTrial=%d (dt=%.1fs), so far <nbTrial>=%d")
830 % (nbCycle0-nbCycle) % this->
GetLogLikelihood() % (nbStep0-nbStep) % chrono.seconds() % (nbTrialCumul/(nbCycle0-nbCycle+1))).str());
832 (*
fpObjCrystInformUser)((boost::format(
"Finished Run #%d, final cost=%12.2f, nbTrial=%d (dt=%.1fs)")
833 % (nbCycle0-nbCycle) % this->
GetLogLikelihood() % (nbStep0-nbStep) % chrono.seconds()).str());
839 s<<
"Run #"<<abs(nbCycle);
841 if(!silent) cout <<
"MonteCarloObj::MultiRunOptimize: Finished Run#"
843 <<
", Overall Best Cost:"<<
mBestCost<<endl;
846 string saveFileName=this->
GetName();
849 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
857 snprintf(costAsChar,
sizeof(costAsChar),
"-Run#%ld-Cost-%g",abs(nbCycle),this->
GetLogLikelihood());
858 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
864 outTracker.imbue(std::locale::classic());
866 snprintf(runNum,
sizeof(runNum),
"-Tracker-Run#%ld.dat",abs(nbCycle));
867 const string outTrackerName=this->
GetName()+runNum;
868 outTracker.open(outTrackerName.c_str());
874 mMutexStopAfterCycle.Lock();
879 mMutexStopAfterCycle.Unlock();
884 mMutexStopAfterCycle.Unlock();
908 mMutexStopAfterCycle.Lock();
912 mMutexStopAfterCycle.Unlock();
916 cout<<endl<<
"Finished all runs, number of trials to reach cost="
917 <<finalcost<<
" : <nbTrial>="<<nbTrialCumul/(nbCycle0-nbCycle)<<endl;
918 VFN_DEBUG_EXIT(
"MonteCarloObj::MultiRunOptimize()",5)
922 const REAL finalcost,
const REAL maxTime)
925 const long nbSteps=nbStep;
929 unsigned long secondsWhenAutoSave=0;
931 if(!silent) cout <<
"Starting Simulated Annealing Optimization for"<<nbSteps<<
" trials"<<endl;
939 const int nbTryReport=3000;
941 long nbAcceptedMoves=0;
942 long nbAcceptedMovesTemp=0;
944 long nbTriesSinceBest=0;
946 const int nbTryPerTemp=300;
952 bool needUpdateDisplay=
false;
959 VFN_DEBUG_MESSAGE(
"-> Updating temperature and mutation amplitude.",3)
963 case ANNEALING_BOLTZMANN:
966 case ANNEALING_CAUCHY:
969 case ANNEALING_EXPONENTIAL:
973 case ANNEALING_GAMMA:
976 case ANNEALING_SMART:
978 if((nbAcceptedMovesTemp/(REAL)nbTryPerTemp)>0.30)
980 if((nbAcceptedMovesTemp/(REAL)nbTryPerTemp)<0.10)
984 nbAcceptedMovesTemp=0;
991 case ANNEALING_BOLTZMANN:
995 case ANNEALING_CAUCHY:
998 case ANNEALING_EXPONENTIAL:
1002 case ANNEALING_GAMMA:
1005 case ANNEALING_SMART:
1012 nbAcceptedMovesTemp=0;
1031 needUpdateDisplay=
true;
1037 if(!silent) cout <<
"Trial :" <<
mNbTrial
1040 <<
" NEW OVERALL Best Cost="<<runBestCost<< endl;
1042 else if(!silent) cout <<
"Trial :" <<
mNbTrial
1045 <<
" NEW Run Best Cost="<<runBestCost<< endl;
1049 nbAcceptedMovesTemp++;
1059 nbAcceptedMovesTemp++;
1067 if(!silent) cout <<
" Mutation Ampl.: " <<
mMutationAmplitude<<
" Best Cost=" << runBestCost
1069 <<
" Accepting "<<(int)((REAL)nbAcceptedMoves/nbTryReport*100)
1070 <<
"% moves" << endl;
1072 #ifdef __WX__CRYST__
1073 if(0!=mpWXCrystObj) mpWXCrystObj->UpdateDisplayNbTrial();
1078 #ifdef __WX__CRYST__
1079 mMutexStopAfterCycle.Lock();
1081 if((runBestCost<finalcost) ||
mStopAfterCycle ||( (maxTime>0)&&(chrono.seconds()>maxTime)))
1083 #ifdef __WX__CRYST__
1084 mMutexStopAfterCycle.Unlock();
1086 if(!silent) cout << endl <<endl <<
"Refinement Stopped."<<endl;
1089 #ifdef __WX__CRYST__
1090 mMutexStopAfterCycle.Unlock();
1093 if( ((
mXMLAutoSave.GetChoice()==1)&&((chrono.seconds()-secondsWhenAutoSave)>86400))
1094 ||((
mXMLAutoSave.GetChoice()==2)&&((chrono.seconds()-secondsWhenAutoSave)>3600))
1095 ||((
mXMLAutoSave.GetChoice()==3)&&((chrono.seconds()-secondsWhenAutoSave)> 600))
1098 secondsWhenAutoSave=(
unsigned long)chrono.seconds();
1099 string saveFileName=this->
GetName();
1100 time_t date=time(0);
1102 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
1103 char costAsChar[64];
1108 snprintf(costAsChar,
sizeof(costAsChar),
"-Cost-%g",this->
GetLogLikelihood());
1109 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
1113 if((
mNbTrial%300==0)&&needUpdateDisplay)
1116 needUpdateDisplay=
false;
1124 if(!silent) cout<<
"Beginning final LSQ refinement"<<endl;
1128 try {
mLSQ.
Refine(-50,
true,
true,
false,0.001);}
1148 if(!silent) cout <<
"LSQ : NEW OVERALL Best Cost="<<runBestCost<< endl;
1150 else if(!silent) cout <<
" LSQ : NEW Run Best Cost="<<runBestCost<< endl;
1153 if(!silent) cout<<
"Finished LSQ refinement"<<endl;
1164 if(!silent) chrono.print();
1235 void MonteCarloObj::RunRandomLSQMethod(
long &nbCycle)
1239 float bsigma=-1, bdelta=-1;
1240 float asigma=-1, adelta=-1;
1250 if(pMol==NULL)
continue;
1251 for(vector<MolBond*>::iterator pos = pMol->GetBondList().begin(); pos != pMol->GetBondList().end();++pos) {
1252 bsigma = (*pos)->GetLengthSigma();
1253 bdelta = (*pos)->GetLengthDelta();
1254 (*pos)->SetLengthDelta(0.02);
1255 (*pos)->SetLengthSigma(0.001);
1257 for(vector<MolBondAngle*>::iterator pos=pMol->GetBondAngleList().begin();pos != pMol->GetBondAngleList().end();++pos)
1259 asigma = (*pos)->GetAngleSigma();
1260 adelta = (*pos)->GetAngleDelta();
1261 (*pos)->SetAngleDelta(0.2*DEG2RAD);
1262 (*pos)->SetAngleSigma(0.01*DEG2RAD);
1265 }
catch (
const std::bad_cast& e){
1287 catch(
const ObjCrystException &except) {
1303 string saveFileName=this->
GetName();
1304 time_t date=time(0);
1306 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
1307 char costAsChar[64];
1311 snprintf(costAsChar,
sizeof(costAsChar),
"#Run%ld-Cost-%g",nbCycle,
mCurrentCost);
1312 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
1315 #ifdef __WX__CRYST__
1316 mMutexStopAfterCycle.Lock();
1320 #ifdef __WX__CRYST__
1321 mMutexStopAfterCycle.Unlock();
1325 #ifdef __WX__CRYST__
1326 mMutexStopAfterCycle.Unlock();
1331 if(bsigma<0 || bdelta<0 || asigma<0 || adelta<0)
return;
1336 Crystal * pCryst =
dynamic_cast<Crystal *
>(&(
mRefinedObjList.GetObj(i)));
1337 for(
int s=0;s<pCryst->GetScattererRegistry().GetNb();s++)
1339 Molecule *pMol=
dynamic_cast<Molecule*
>(&(pCryst->GetScatt(s)));
1340 if(pMol==NULL)
continue;
1341 for(vector<MolBond*>::iterator pos = pMol->GetBondList().begin(); pos != pMol->GetBondList().end();++pos) {
1342 (*pos)->SetLengthDelta(bdelta);
1343 (*pos)->SetLengthSigma(bsigma);
1345 for(vector<MolBondAngle*>::iterator pos=pMol->GetBondAngleList().begin();pos != pMol->GetBondAngleList().end();++pos)
1347 (*pos)->SetAngleDelta(adelta);
1348 (*pos)->SetAngleSigma(asigma);
1351 }
catch (
const std::bad_cast& e){
1359 const REAL finalcost,
const REAL maxTime)
1361 TAU_PROFILE(
"MonteCarloObj::RunParallelTempering()",
"void ()",TAU_DEFAULT);
1362 TAU_PROFILE_TIMER(timer0a,
"MonteCarloObj::RunParallelTempering() Begin 1",
"", TAU_FIELD);
1363 TAU_PROFILE_TIMER(timer0b,
"MonteCarloObj::RunParallelTempering() Begin 2",
"", TAU_FIELD);
1364 TAU_PROFILE_TIMER(timer1,
"MonteCarloObj::RunParallelTempering() New Config + LLK",
"", TAU_FIELD);
1365 TAU_PROFILE_TIMER(timerN,
"MonteCarloObj::RunParallelTempering() Finish",
"", TAU_FIELD);
1366 TAU_PROFILE_START(timer0a);
1368 const long nbSteps=nbStep;
1369 unsigned int accept;
1372 unsigned long secondsWhenAutoSave=0;
1375 const unsigned int autoLSQPeriod=150000;
1377 if(!silent) cout <<
"Starting Parallel Tempering Optimization"<<endl;
1381 const long nbWorld=30;
1382 CrystVector_long worldSwapIndex(nbWorld);
1383 for(
int i=0;i<nbWorld;++i) worldSwapIndex(i)=i;
1387 const int nbTryPerWorld=10;
1391 CrystVector_REAL currentCost(nbWorld);
1394 CrystVector_REAL simAnnealTemp(nbWorld);
1395 for(
int i=0;i<nbWorld;i++)
1399 case ANNEALING_BOLTZMANN:
1402 case ANNEALING_CAUCHY:
1405 case ANNEALING_EXPONENTIAL:
1408 i/(REAL)(nbWorld-1));
break;
1409 case ANNEALING_GAMMA:
1412 case ANNEALING_SMART:
1413 simAnnealTemp(i)=
mCurrentCost/(100.+(REAL)i/(REAL)nbWorld*900.);
break;
1415 simAnnealTemp(i)=
mCurrentCost/(100.+(REAL)i/(REAL)nbWorld*900.);
break;
1419 CrystVector_REAL mutationAmplitude(nbWorld);
1420 for(
int i=0;i<nbWorld;i++)
1424 case ANNEALING_BOLTZMANN:
1425 mutationAmplitude(i)=
1428 case ANNEALING_CAUCHY:
1431 case ANNEALING_EXPONENTIAL:
1434 i/(REAL)(nbWorld-1));
break;
1435 case ANNEALING_GAMMA:
1438 case ANNEALING_SMART:
1446 CrystVector_long worldCurrentSetIndex(nbWorld);
1447 for(
int i=nbWorld-1;i>=0;i--)
1449 if((i!=(nbWorld-1))&&(i%2==0))
1455 TAU_PROFILE_STOP(timer0a);
1456 TAU_PROFILE_START(timer0b);
1460 CrystVector_REAL swapPar;
1462 CrystVector_long worldNbAcceptedMoves(nbWorld);
1463 worldNbAcceptedMoves=0;
1465 const int nbTrialsReport=3000;
1469 unsigned int first=1;
1476 cout <<
"Gene Group:"<<refParGeneGroupIndex(i)<<
" :";
1491 bool needUpdateDisplay=
false;
1493 bool makeReport=
false;
1496 float lastUpdateDisplayTime=chrono.seconds();
1497 TAU_PROFILE_STOP(timer0b);
1500 for(
int i=0;i<nbWorld;i++)
1506 for(
int j=0;j<nbTryPerWorld;j++)
1509 TAU_PROFILE_START(timer1);
1514 TAU_PROFILE_STOP(timer1);
1516 if(cost<currentCost(i))
1519 currentCost(i)=cost;
1521 if(cost<runBestCost)
1524 runBestCost=currentCost(i);
1526 needUpdateDisplay=
true;
1533 if(!silent) cout <<
"->Trial :" <<
mNbTrial
1534 <<
" World="<< worldSwapIndex(i)
1537 <<
" NEW OVERALL Best Cost="<<
mBestCost<< endl;
1539 else if(!silent) cout <<
"->Trial :" <<
mNbTrial
1540 <<
" World="<< worldSwapIndex(i)
1543 <<
" NEW RUN Best Cost="<<runBestCost<< endl;
1546 worldNbAcceptedMoves(i)++;
1550 if(log((rand()+1)/(REAL)RAND_MAX)<(-(cost-currentCost(i))/
mTemperature) )
1553 currentCost(i)=cost;
1555 worldNbAcceptedMoves(i)++;
1559 if( ((
mXMLAutoSave.GetChoice()==1)&&((chrono.seconds()-secondsWhenAutoSave)>86400))
1560 ||((
mXMLAutoSave.GetChoice()==2)&&((chrono.seconds()-secondsWhenAutoSave)>3600))
1561 ||((
mXMLAutoSave.GetChoice()==3)&&((chrono.seconds()-secondsWhenAutoSave)> 600))
1564 secondsWhenAutoSave=(
unsigned long)chrono.seconds();
1565 string saveFileName=this->
GetName();
1566 time_t date=time(0);
1568 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
1569 char costAsChar[64];
1574 snprintf(costAsChar,
sizeof(costAsChar),
"-Cost-%g",this->
GetLogLikelihood());
1575 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
1581 if((
mNbTrial%nbTrialsReport)==0) makeReport=
true;
1586 if((
mNbTrial%autoLSQPeriod)<(nbTryPerWorld*nbWorld))
1589 for(
int i=nbWorld-5;i<nbWorld;i++)
1591 #ifdef __WX__CRYST__
1592 mMutexStopAfterCycle.Lock();
1595 mMutexStopAfterCycle.Unlock();
1598 mMutexStopAfterCycle.Unlock();
1606 if(pos->first->GetNbLSQFunction()>0)
1608 CrystVector_REAL tmp;
1609 tmp =pos->first->GetLSQCalc(pos->second);
1610 tmp-=pos->first->GetLSQObs (pos->second);
1612 tmp*=pos->first->GetLSQWeight(pos->second);
1613 cout<<pos->first->GetClassName()<<
":"<<pos->first->GetName()<<
": GoF="<<tmp.sum()/tmp.numElements();
1619 if(!silent) cout<<
"LSQ: World="<<worldSwapIndex(i)<<
": cost="<<cost0;
1620 try {
mLSQ.
Refine(-30,
true,
true,
false,0.001);}
1625 if(pos->first->GetNbLSQFunction()>0)
1627 CrystVector_REAL tmp;
1628 tmp =pos->first->GetLSQCalc(pos->second);
1629 tmp-=pos->first->GetLSQObs (pos->second);
1631 tmp*=pos->first->GetLSQWeight(pos->second);
1632 cout<<pos->first->GetClassName()<<
":"<<pos->first->GetName()<<
": GoF="<<tmp.sum()/tmp.numElements();
1637 if(!silent) cout<<
" -> "<<cost<<endl;
1643 for(
int i=nbWorld-5;i<nbWorld;i++)
1647 if(!silent) cout<<
"LSQ2:"<<currentCost(i)<<
"->"<<cost<<endl;
1648 if(cost<currentCost(i))
1650 const REAL oldcost=currentCost(i);
1652 currentCost(i)=cost;
1653 if(cost<runBestCost)
1655 runBestCost=currentCost(i);
1657 needUpdateDisplay=
true;
1664 if(!silent) cout <<
"->Trial :" <<
mNbTrial
1665 <<
" World="<< worldSwapIndex(i)
1666 <<
" LSQ2: NEW OVERALL Best Cost="<<
mBestCost<< endl;
1668 else if(!silent) cout <<
"->Trial :" <<
mNbTrial
1669 <<
" World="<< worldSwapIndex(i)
1670 <<
" LSQ2: NEW RUN Best Cost="<<runBestCost<< endl;
1684 if(!silent) cout<<
"LSQ3: #"<<worldSwapIndex(i)<<
":"<<cost<<
"->"<<currentCost(i)<<endl;
1686 currentCost(i)=oldcost;
1693 for(
int i=1;i<nbWorld;i++)
1701 if( log((rand()+1)/(REAL)RAND_MAX)
1702 < (-(currentCost(i-1)-currentCost(i))/simAnnealTemp(i)))
1708 if( log((rand()+1)/(REAL)RAND_MAX)
1723 const REAL tmp=currentCost(i);
1724 currentCost(i)=currentCost(i-1);
1725 currentCost(i-1)=tmp;
1726 const long tmpIndex=worldSwapIndex(i);
1727 worldSwapIndex(i)=worldSwapIndex(i-1);
1728 worldSwapIndex(i-1)=tmpIndex;
1743 TAU_PROFILE_TIMER(timer1,\
1744 "MonteCarloObj::Optimize (Try mating Worlds)"\
1746 TAU_PROFILE_START(timer1);
1747 if( (rand()/(REAL)RAND_MAX)<.1)
1748 for(
int k=nbWorld-1;k>nbWorld/2;k--)
1749 for(
int i=k-nbWorld/3;i<k;i++)
1753 for(
unsigned int j=0;j<nbGeneGroup;j++)
1754 crossoverGroupIndex(j)= (int) floor(rand()/((REAL)RAND_MAX-1)*2);
1757 if(0==crossoverGroupIndex(refParGeneGroupIndex(j)-1))
1775 unsigned int crossoverPoint1=
1776 (int)(1+floor(rand()/((REAL)RAND_MAX-1)*(nbGeneGroup)));
1777 unsigned int crossoverPoint2=
1778 (int)(1+floor(rand()/((REAL)RAND_MAX-1)*(nbGeneGroup)));
1779 if(crossoverPoint2<crossoverPoint1)
1781 int tmp=crossoverPoint1;
1782 crossoverPoint1=crossoverPoint2;
1783 crossoverPoint2=tmp;
1785 if(crossoverPoint1==crossoverPoint2) crossoverPoint2+=1;
1788 if((refParGeneGroupIndex(j)>crossoverPoint1)&&refParGeneGroupIndex(j)<crossoverPoint2)
1805 for(
int junk=0;junk<2;junk++)
1812 if(cost<currentCost(k))
1821 currentCost(k)=cost;
1824 if(!silent) cout <<
"Accepted mating :"<<k<<
"(with"<<i<<
")"
1825 <<
" (crossoverGene1="<< crossoverPoint1<<
","
1826 <<
" crossoverGene2="<< crossoverPoint2<<
")"
1828 if(cost<runBestCost)
1832 needUpdateDisplay=
true;
1838 if(!silent) cout <<
"->Trial :" <<
mNbTrial
1839 <<
" World="<< worldSwapIndex(k)
1840 <<
" Temp="<< simAnnealTemp(k)
1842 <<
" NEW OVERALL Best Cost="<<
mBestCost<<
"(MATING !)"<<endl;
1844 else if(!silent) cout <<
"->Trial :" <<
mNbTrial
1845 <<
" World="<< worldSwapIndex(k)
1846 <<
" Temp="<< simAnnealTemp(k)
1848 <<
" NEW RUN Best Cost="<<runBestCost<<
"(MATING !)"<<endl;
1861 TAU_PROFILE_STOP(timer1);
1863 if(
true==makeReport)
1866 worldNbAcceptedMoves*=nbWorld;
1872 map<const RefinableObj*,REAL> ll,llvar;
1873 map<const RefinableObj*,LogLikelihoodStats>::iterator pos;
1877 llvar[pos->first]=0.;
1879 for(
int i=0;i<nbWorld;i++)
1883 ll [pos->first] += pos->second.mTotalLogLikelihood;
1884 llvar[pos->first] += pos->second.mTotalLogLikelihoodDeltaSq;
1889 cout << pos->first->GetName()
1890 <<
" " << llvar[pos->first]
1892 <<
" " << max<<endl;
1893 llvar[pos->first] *=
mvObjWeight[pos->first].mWeight;
1894 if(llvar[pos->first]>max) max=llvar[pos->first];
1896 map<const RefinableObj*,REAL>::iterator pos2;
1897 for(pos2=llvar.begin();pos2!=llvar.end();++pos2)
1899 const REAL d=pos2->second;
1908 for(pos2=ll.begin();pos2!=ll.end();++pos2)
1910 llt += pos2->second;
1911 ll1 += pos2->second *
mvObjWeight[pos2->first].mWeight;
1913 map<const RefinableObj*,DynamicObjWeight>::iterator posw;
1916 posw->second.mWeight *= llt/ll1;
1921 for(
int i=0;i<nbWorld;i++)
1923 cout<<
" World :"<<worldSwapIndex(i)<<
":";
1924 map<const RefinableObj*,LogLikelihoodStats>::iterator pos;
1927 cout << pos->first->GetName()
1929 << pos->second.mLastLogLikelihood
1936 pos->second.mTotalLogLikelihood=0;
1937 pos->second.mTotalLogLikelihoodDeltaSq=0;
1942 for(
int i=0;i<nbWorld;i++)
1945 cout <<
" World :" << worldSwapIndex(i)
1946 <<
" Temp.: " << simAnnealTemp(i)
1947 <<
" Mutation Ampl.: " << mutationAmplitude(i)
1948 <<
" Current Cost=" << currentCost(i)
1950 << (int)((REAL)worldNbAcceptedMoves(i)/nbTrialsReport*100)
1951 <<
"% moves " <<endl;
1955 if(!silent) cout <<
"Trial :" <<
mNbTrial <<
" Best Cost=" << runBestCost<<
" ";
1956 if(!silent) chrono.print();
1960 for(
int i=0;i<nbWorld;i++)
1962 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.30)
1963 mutationAmplitude(i)*=2.;
1964 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.10)
1965 mutationAmplitude(i)/=2.;
1974 for(
int i=0;i<nbWorld;i++)
1976 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.30)
1977 simAnnealTemp(i)/=1.5;
1978 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.80)
1979 simAnnealTemp(i)/=1.5;
1980 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.95)
1981 simAnnealTemp(i)/=1.5;
1983 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.10)
1984 simAnnealTemp(i)*=1.5;
1985 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.04)
1986 simAnnealTemp(i)*=1.5;
1994 worldNbAcceptedMoves=0;
1997 #ifdef __WX__CRYST__
1998 if(0!=mpWXCrystObj) mpWXCrystObj->UpdateDisplayNbTrial();
2001 if( (needUpdateDisplay&&(lastUpdateDisplayTime<(chrono.seconds()-1)))||(lastUpdateDisplayTime<(chrono.seconds()-10)))
2005 needUpdateDisplay=
false;
2006 lastUpdateDisplayTime=chrono.seconds();
2008 #ifdef __WX__CRYST__
2009 mMutexStopAfterCycle.Lock();
2011 if((runBestCost<finalcost) ||
mStopAfterCycle ||( (maxTime>0)&&(chrono.seconds()>maxTime)))
2013 #ifdef __WX__CRYST__
2014 mMutexStopAfterCycle.Unlock();
2016 if(!silent) cout << endl <<endl <<
"Refinement Stopped:"<<
mBestCost<<endl;
2019 #ifdef __WX__CRYST__
2020 mMutexStopAfterCycle.Unlock();
2024 TAU_PROFILE_START(timerN);
2027 if(!silent) cout<<
"Beginning final LSQ refinement"<<endl;
2031 try {
mLSQ.
Refine(-50,
true,
true,
false,0.001);}
2051 if(!silent) cout <<
"LSQ : NEW OVERALL Best Cost="<<runBestCost<< endl;
2053 else if(!silent) cout <<
" LSQ : NEW Run Best Cost="<<runBestCost<< endl;
2056 if(!silent) cout<<
"Finished LSQ refinement"<<endl;
2066 if(!silent) cout<<
"Run Best Cost:"<<
mCurrentCost<<endl;
2067 if(!silent) chrono.print();
2073 for(
int i=0;i<nbWorld;i++)
2080 TAU_PROFILE_STOP(timerN);
2085 VFN_DEBUG_ENTRY(
"MonteCarloObj::XMLOutput():"<<this->
GetName(),5)
2086 for(
int i=0;i<indent;i++) os <<
" " ;
2088 tag.AddAttribute(
"Name",this->
GetName());
2089 tag.AddAttribute(
"NbTrialPerRun",(boost::format(
"%d")%(this->
NbTrialPerRun())).str());
2108 for(
int i=0;i<indent;i++) os <<
" " ;
2110 tag2.SetIsEndTag(
true);
2122 for(
int i=0;i<indent;i++) os <<
" " ;
2124 tag2.SetIsEndTag(
true);
2131 tag2.AddAttribute(
"ObjectType",
mRefinedObjList.GetObj(j).GetClassName());
2133 for(
int i=0;i<indent;i++) os <<
" " ;
2138 tag.SetIsEndTag(
true);
2139 for(
int i=0;i<indent;i++) os <<
" " ;
2141 VFN_DEBUG_EXIT(
"MonteCarloObj::XMLOutput():"<<this->
GetName(),5)
2146 VFN_DEBUG_ENTRY(
"MonteCarloObj::XMLInput():"<<this->
GetName(),5)
2147 for(
unsigned int i=0;i<tagg.GetNbAttribute();i++)
2149 if(
"Name"==tagg.GetAttributeName(i)) this->
SetName(tagg.GetAttributeValue(i));
2150 if(
"NbTrialPerRun"==tagg.GetAttributeName(i))
2152 stringstream ss(tagg.GetAttributeValue(i));
2161 if((
"GlobalOptimObj"==tag.GetName())&&tag.IsEndTag())
2163 VFN_DEBUG_EXIT(
"MonteCarloObj::Exit():"<<this->
GetName(),5)
2167 if(
"Option"==tag.GetName())
2169 for(
unsigned int i=0;i<tag.GetNbAttribute();i++)
2170 if(
"Name"==tag.GetAttributeName(i))
2172 if(
"Algorithm"==tag.GetAttributeValue(i))
2177 if(
"Temperature Schedule"==tag.GetAttributeValue(i))
2182 if(
"Displacement Amplitude Schedule"==tag.GetAttributeValue(i))
2187 if(
"Save Best Config Regularly"==tag.GetAttributeValue(i))
2192 if(
"Save Tracked Data"==tag.GetAttributeValue(i))
2197 if(
"Automatic Least Squares Refinement"==tag.GetAttributeValue(i))
2205 if(
"TempMaxMin"==tag.GetName())
2211 if(
"MutationMaxMin"==tag.GetName())
2217 if(
"RefinedObject"==tag.GetName())
2220 for(
unsigned int i=0;i<tag.GetNbAttribute();i++)
2222 if(
"ObjectName"==tag.GetAttributeName(i)) name=tag.GetAttributeValue(i);
2223 if(
"ObjectType"==tag.GetAttributeName(i)) type=tag.GetAttributeValue(i);
2240 TAU_PROFILE(
"MonteCarloObj::NewConfiguration()",
"void ()",TAU_DEFAULT);
2241 VFN_DEBUG_ENTRY(
"MonteCarloObj::NewConfiguration()",4)
2246 VFN_DEBUG_EXIT(
"MonteCarloObj::NewConfiguration()",4)
2251 VFN_DEBUG_MESSAGE(
"MonteCarloObj::InitOptions()",5)
2253 static string GlobalOptimTypeName;
2254 static string GlobalOptimTypeChoices[2];
2256 static string AnnealingScheduleChoices[6];
2258 static string AnnealingScheduleTempName;
2259 static string AnnealingScheduleMutationName;
2261 static string runAutoLSQName;
2262 static string runAutoLSQChoices[3];
2264 static string saveTrackedDataName;
2265 static string saveTrackedDataChoices[2];
2267 static bool needInitNames=
true;
2268 if(
true==needInitNames)
2270 GlobalOptimTypeName=
"Algorithm";
2271 GlobalOptimTypeChoices[0]=
"Simulated Annealing";
2272 GlobalOptimTypeChoices[1]=
"Parallel Tempering";
2275 AnnealingScheduleTempName=
"Temperature Schedule";
2276 AnnealingScheduleMutationName=
"Displacement Amplitude Schedule";
2277 AnnealingScheduleChoices[0]=
"Constant";
2278 AnnealingScheduleChoices[1]=
"Boltzmann";
2279 AnnealingScheduleChoices[2]=
"Cauchy";
2280 AnnealingScheduleChoices[3]=
"Exponential";
2281 AnnealingScheduleChoices[4]=
"Smart";
2282 AnnealingScheduleChoices[5]=
"Gamma";
2284 runAutoLSQName=
"Automatic Least Squares Refinement";
2285 runAutoLSQChoices[0]=
"Never";
2286 runAutoLSQChoices[1]=
"At the end of each run";
2287 runAutoLSQChoices[2]=
"Every 150000 trials, and at the end of each run";
2289 saveTrackedDataName=
"Save Tracked Data";
2290 saveTrackedDataChoices[0]=
"No (recommended!)";
2291 saveTrackedDataChoices[1]=
"Yes (for tests ONLY)";
2293 needInitNames=
false;
2299 mAutoLSQ.Init(3,&runAutoLSQName,runAutoLSQChoices);
2305 VFN_DEBUG_MESSAGE(
"MonteCarloObj::InitOptions():End",5)
2314 if(!useFullPowderPatternProfile)
2317 if(pos->first->GetClassName()==
"PowderPattern") pos->second=1;
2323 std::list<RefinablePar*> vIntCorrPar;
2331 for(std::list<RefinablePar*>::iterator pos=vIntCorrPar.begin();pos!=vIntCorrPar.end();pos++)
2332 (*pos)->SetIsFixed(
false);
2341 #ifdef __WX__CRYST__
2342 if(0!=mpWXCrystObj) mpWXCrystObj->CrystUpdate(
true,
true);
2347 #ifdef __WX__CRYST__
2351 return mpWXCrystObj;
2353 WXOptimizationObj* MonteCarloObj::WXGet()
2355 return mpWXCrystObj;
2357 void MonteCarloObj::WXDelete()
2359 if(0!=mpWXCrystObj)
delete mpWXCrystObj;
2362 void MonteCarloObj::WXNotifyDelete()
The namespace which includes all objects (crystallographic and algorithmic) in ObjCryst++.
void RefObjRegisterRecursive(T &obj, ObjRegistry< T > ®)
Register a new object in a registry, and recursively include all included (sub)objects.
const RefParType * gpRefParTypeScattDataScale
Type for scattering data scale factors.
ObjRegistry< OptimizationObj > gOptimizationObjRegistry("List of all Optimization objects")
Global Registry for all OptimizationObj.
void(* fpObjCrystInformUser)(const string &)
Pointer to a function for passing info to the user during or after long/important processes (use scar...
AnnealingSchedule
Annealing schedule type.
const RefParType * gpRefParTypeObjCryst
Top RefParType for the ObjCryst++ library.
void GetSubRefObjListClockRecursive(ObjRegistry< RefinableObj > ®, RefinableObjClock &clock)
Get the last time any object was added in the recursive list of objects.
ObjRegistry< RefinableObj > gRefinableObjRegistry("Global RefinableObj registry")
Global Registry for all RefinableObj.
const RefParType * gpRefParTypeScattDataCorrInt
Generic type for correction to calculated intensities.
void GetRefParListClockRecursive(ObjRegistry< RefinableObj > ®, RefinableObjClock &clock)
Get the last time any RefinablePar was added in a recursive list of objects.
const RefParType * gpRefParTypeScattData
Generic type for scattering data.
void XMLCrystFileSaveGlobal(const string &filename)
Save all Objcryst++ objects.
Crystal class: Unit cell, spacegroup, scatterers.
REAL GetBondValenceCost() const
Get the Bond-Valence cost function, which compares the expected valence to the one computed from Bond...
ObjRegistry< Scatterer > & GetScattererRegistry()
Get the registry of scatterers.
REAL GetBumpMergeCost() const
Get the Anti-bumping/pro-Merging cost function.
Scatterer & GetScatt(const string &scattName)
Provides an access to the scatterers.
Exception class for ObjCryst++ library.
Molecule : class for complex scatterer descriptions using cartesian coordinates with bond length/angl...
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.
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.
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.
long mNbTrialPerRun
Number of trial per run, to be saved/restored in XML output.
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
void SetParIsFixed(const std::string &parName, const bool fix)
Fix one parameter.
const std::map< RefinableObj *, unsigned int > & GetRefinedObjMap() const
Get the map of refined objects - this is a recursive list of all the objects that are taken into acco...
void Refine(int nbCycle=1, bool useLevenbergMarquardt=false, const bool silent=false, const bool callBeginEndOptimization=true, const float minChi2var=0.01)
Do the refinement.
void SetRefinedObj(RefinableObj &obj, const unsigned int LSQFuncIndex=0, const bool init=true, const bool recursive=false)
Choose the object to refine.
RefinableObj & GetCompiledRefinedObj()
Access to the RefinableObj which is the compilation of all parameters from the object supplied for op...
void PrepareRefParList(const bool copy_param=false)
Prepare the full parameter list for the refinement.
class of refinable parameter types.
bool IsDescendantFromOrSameAs(const RefParType *type) const
Returns true if the parameter is a descendant of 'type'.
We need to record exactly when refinable objects have been modified for the last time (to avoid re-co...
REAL GetMin() const
Minimum value allowed (if limited or periodic)
void MutateTo(const REAL newValue)
Change the current value to the given one.
REAL GetMax() const
Get the maximum value allowed (if limited)
REAL GetPeriod() const
Get the period (if periodic)
void XMLInput(istream &is, const XMLCrystTag &tag)
XMLInput From stream.
void XMLOutput(ostream &os, int indent=0) const
XMLOutput to stream in well-formed XML.
Generic Refinable Object.
void RestoreParamSet(const unsigned long id)
Restore a saved set of values.
void AddPar(const RefinablePar &newRefPar)
Add a refinable parameter.
RefinablePar & GetPar(const long i)
Access all parameters in the order they were inputted.
virtual const string & GetName() const
Name of the object.
void SetDeleteRefParInDestructor(const bool b)
Set this object not to delete its list of parameters when destroyed.
long GetNbPar() const
Total number of refinable parameter in the object.
void ResetParList()
Re-init the list of refinable parameters, removing all parameters.
void SaveParamSet(const unsigned long id) const
Save the current set of refined values over a previously-created set of saved values.
void PrepareForRefinement() const
Find which parameters are used and not fixed, for a refinement /optimization.
RefinablePar & GetParNotFixed(const long i)
Access all parameters in the order they were inputted, skipping fixed parameters.
const RefinableObjClock & GetRefParListClock() const
What was the last time a RefinablePar was added/removed ?
const CrystVector_REAL & GetParamSet(const unsigned long setId) const
Access one save refpar set.
void ClearParamSet(const unsigned long id) const
Erase the param set with the given id, releasing memory.
unsigned long CreateParamSet(const string name="") const
Save the current set of refined values in a new set.
const void EraseAllParamSet()
Erase all saved refpar sets.
virtual REAL GetLogLikelihood() const
Get -log(likelihood) of the current configuration for the object.
long GetNbParNotFixed() const
Total number of non-fixed parameters. Is initialized by PrepareForRefinement()
A class to hold all trackers.
void SaveAll(std::ostream &out) const
Will save to a single file if all recorded trial numbers are the same Otherwise ?
void ClearTrackers()
Removes all Trackers.
void ClearValues()
Removes all stored values.
void UpdateDisplay() const
Update display, if any.
Tracker for objects (RefinableObj, Crystal, PowderPattern, RefPar,...)
Simple chronometer class, with microsecond precision.
Abstract base class for all objects in wxCryst.
Class for Graphical interface to Monte-Carlo objects (Simulated Annealing, Parallel Tempering)