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));
851 sprintf(costAsChar,
"-Run#%ld-Cost-%f",abs(nbCycle),this->
GetLogLikelihood());
852 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
858 outTracker.imbue(std::locale::classic());
860 sprintf(runNum,
"-Tracker-Run#%ld.dat",abs(nbCycle));
861 const string outTrackerName=this->
GetName()+runNum;
862 outTracker.open(outTrackerName.c_str());
868 mMutexStopAfterCycle.Lock();
873 mMutexStopAfterCycle.Unlock();
878 mMutexStopAfterCycle.Unlock();
902 mMutexStopAfterCycle.Lock();
906 mMutexStopAfterCycle.Unlock();
910 cout<<endl<<
"Finished all runs, number of trials to reach cost="
911 <<finalcost<<
" : <nbTrial>="<<nbTrialCumul/(nbCycle0-nbCycle)<<endl;
912 VFN_DEBUG_EXIT(
"MonteCarloObj::MultiRunOptimize()",5)
916 const REAL finalcost,
const REAL maxTime)
919 const long nbSteps=nbStep;
923 unsigned long secondsWhenAutoSave=0;
925 if(!silent) cout <<
"Starting Simulated Annealing Optimization for"<<nbSteps<<
" trials"<<endl;
933 const int nbTryReport=3000;
935 long nbAcceptedMoves=0;
936 long nbAcceptedMovesTemp=0;
938 long nbTriesSinceBest=0;
940 const int nbTryPerTemp=300;
946 bool needUpdateDisplay=
false;
953 VFN_DEBUG_MESSAGE(
"-> Updating temperature and mutation amplitude.",3)
957 case ANNEALING_BOLTZMANN:
960 case ANNEALING_CAUCHY:
963 case ANNEALING_EXPONENTIAL:
967 case ANNEALING_GAMMA:
970 case ANNEALING_SMART:
972 if((nbAcceptedMovesTemp/(REAL)nbTryPerTemp)>0.30)
974 if((nbAcceptedMovesTemp/(REAL)nbTryPerTemp)<0.10)
978 nbAcceptedMovesTemp=0;
985 case ANNEALING_BOLTZMANN:
989 case ANNEALING_CAUCHY:
992 case ANNEALING_EXPONENTIAL:
996 case ANNEALING_GAMMA:
999 case ANNEALING_SMART:
1006 nbAcceptedMovesTemp=0;
1025 needUpdateDisplay=
true;
1031 if(!silent) cout <<
"Trial :" <<
mNbTrial
1034 <<
" NEW OVERALL Best Cost="<<runBestCost<< endl;
1036 else if(!silent) cout <<
"Trial :" <<
mNbTrial
1039 <<
" NEW Run Best Cost="<<runBestCost<< endl;
1043 nbAcceptedMovesTemp++;
1053 nbAcceptedMovesTemp++;
1061 if(!silent) cout <<
" Mutation Ampl.: " <<
mMutationAmplitude<<
" Best Cost=" << runBestCost
1063 <<
" Accepting "<<(int)((REAL)nbAcceptedMoves/nbTryReport*100)
1064 <<
"% moves" << endl;
1066 #ifdef __WX__CRYST__
1067 if(0!=mpWXCrystObj) mpWXCrystObj->UpdateDisplayNbTrial();
1072 #ifdef __WX__CRYST__
1073 mMutexStopAfterCycle.Lock();
1075 if((runBestCost<finalcost) ||
mStopAfterCycle ||( (maxTime>0)&&(chrono.seconds()>maxTime)))
1077 #ifdef __WX__CRYST__
1078 mMutexStopAfterCycle.Unlock();
1080 if(!silent) cout << endl <<endl <<
"Refinement Stopped."<<endl;
1083 #ifdef __WX__CRYST__
1084 mMutexStopAfterCycle.Unlock();
1087 if( ((
mXMLAutoSave.GetChoice()==1)&&((chrono.seconds()-secondsWhenAutoSave)>86400))
1088 ||((
mXMLAutoSave.GetChoice()==2)&&((chrono.seconds()-secondsWhenAutoSave)>3600))
1089 ||((
mXMLAutoSave.GetChoice()==3)&&((chrono.seconds()-secondsWhenAutoSave)> 600))
1092 secondsWhenAutoSave=(
unsigned long)chrono.seconds();
1093 string saveFileName=this->
GetName();
1094 time_t date=time(0);
1096 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
1097 char costAsChar[30];
1100 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
1104 if((
mNbTrial%300==0)&&needUpdateDisplay)
1107 needUpdateDisplay=
false;
1115 if(!silent) cout<<
"Beginning final LSQ refinement"<<endl;
1119 try {
mLSQ.
Refine(-50,
true,
true,
false,0.001);}
1139 if(!silent) cout <<
"LSQ : NEW OVERALL Best Cost="<<runBestCost<< endl;
1141 else if(!silent) cout <<
" LSQ : NEW Run Best Cost="<<runBestCost<< endl;
1144 if(!silent) cout<<
"Finished LSQ refinement"<<endl;
1155 if(!silent) chrono.print();
1226 void MonteCarloObj::RunRandomLSQMethod(
long &nbCycle)
1230 float bsigma=-1, bdelta=-1;
1231 float asigma=-1, adelta=-1;
1241 if(pMol==NULL)
continue;
1242 for(vector<MolBond*>::iterator pos = pMol->GetBondList().begin(); pos != pMol->GetBondList().end();++pos) {
1243 bsigma = (*pos)->GetLengthSigma();
1244 bdelta = (*pos)->GetLengthDelta();
1245 (*pos)->SetLengthDelta(0.02);
1246 (*pos)->SetLengthSigma(0.001);
1248 for(vector<MolBondAngle*>::iterator pos=pMol->GetBondAngleList().begin();pos != pMol->GetBondAngleList().end();++pos)
1250 asigma = (*pos)->GetAngleSigma();
1251 adelta = (*pos)->GetAngleDelta();
1252 (*pos)->SetAngleDelta(0.2*DEG2RAD);
1253 (*pos)->SetAngleSigma(0.01*DEG2RAD);
1256 }
catch (
const std::bad_cast& e){
1278 catch(
const ObjCrystException &except) {
1294 string saveFileName=this->
GetName();
1295 time_t date=time(0);
1297 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
1298 char costAsChar[30];
1299 sprintf(costAsChar,
"#Run%ld-Cost-%f",nbCycle,
mCurrentCost);
1300 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
1303 #ifdef __WX__CRYST__
1304 mMutexStopAfterCycle.Lock();
1308 #ifdef __WX__CRYST__
1309 mMutexStopAfterCycle.Unlock();
1313 #ifdef __WX__CRYST__
1314 mMutexStopAfterCycle.Unlock();
1319 if(bsigma<0 || bdelta<0 || asigma<0 || adelta<0)
return;
1324 Crystal * pCryst =
dynamic_cast<Crystal *
>(&(
mRefinedObjList.GetObj(i)));
1325 for(
int s=0;s<pCryst->GetScattererRegistry().GetNb();s++)
1327 Molecule *pMol=
dynamic_cast<Molecule*
>(&(pCryst->GetScatt(s)));
1328 if(pMol==NULL)
continue;
1329 for(vector<MolBond*>::iterator pos = pMol->GetBondList().begin(); pos != pMol->GetBondList().end();++pos) {
1330 (*pos)->SetLengthDelta(bdelta);
1331 (*pos)->SetLengthSigma(bsigma);
1333 for(vector<MolBondAngle*>::iterator pos=pMol->GetBondAngleList().begin();pos != pMol->GetBondAngleList().end();++pos)
1335 (*pos)->SetAngleDelta(adelta);
1336 (*pos)->SetAngleSigma(asigma);
1339 }
catch (
const std::bad_cast& e){
1347 const REAL finalcost,
const REAL maxTime)
1349 TAU_PROFILE(
"MonteCarloObj::RunParallelTempering()",
"void ()",TAU_DEFAULT);
1350 TAU_PROFILE_TIMER(timer0a,
"MonteCarloObj::RunParallelTempering() Begin 1",
"", TAU_FIELD);
1351 TAU_PROFILE_TIMER(timer0b,
"MonteCarloObj::RunParallelTempering() Begin 2",
"", TAU_FIELD);
1352 TAU_PROFILE_TIMER(timer1,
"MonteCarloObj::RunParallelTempering() New Config + LLK",
"", TAU_FIELD);
1353 TAU_PROFILE_TIMER(timerN,
"MonteCarloObj::RunParallelTempering() Finish",
"", TAU_FIELD);
1354 TAU_PROFILE_START(timer0a);
1356 const long nbSteps=nbStep;
1357 unsigned int accept;
1360 unsigned long secondsWhenAutoSave=0;
1363 const unsigned int autoLSQPeriod=150000;
1365 if(!silent) cout <<
"Starting Parallel Tempering Optimization"<<endl;
1369 const long nbWorld=30;
1370 CrystVector_long worldSwapIndex(nbWorld);
1371 for(
int i=0;i<nbWorld;++i) worldSwapIndex(i)=i;
1375 const int nbTryPerWorld=10;
1379 CrystVector_REAL currentCost(nbWorld);
1382 CrystVector_REAL simAnnealTemp(nbWorld);
1383 for(
int i=0;i<nbWorld;i++)
1387 case ANNEALING_BOLTZMANN:
1390 case ANNEALING_CAUCHY:
1393 case ANNEALING_EXPONENTIAL:
1396 i/(REAL)(nbWorld-1));
break;
1397 case ANNEALING_GAMMA:
1400 case ANNEALING_SMART:
1401 simAnnealTemp(i)=
mCurrentCost/(100.+(REAL)i/(REAL)nbWorld*900.);
break;
1403 simAnnealTemp(i)=
mCurrentCost/(100.+(REAL)i/(REAL)nbWorld*900.);
break;
1407 CrystVector_REAL mutationAmplitude(nbWorld);
1408 for(
int i=0;i<nbWorld;i++)
1412 case ANNEALING_BOLTZMANN:
1413 mutationAmplitude(i)=
1416 case ANNEALING_CAUCHY:
1419 case ANNEALING_EXPONENTIAL:
1422 i/(REAL)(nbWorld-1));
break;
1423 case ANNEALING_GAMMA:
1426 case ANNEALING_SMART:
1434 CrystVector_long worldCurrentSetIndex(nbWorld);
1435 for(
int i=nbWorld-1;i>=0;i--)
1437 if((i!=(nbWorld-1))&&(i%2==0))
1443 TAU_PROFILE_STOP(timer0a);
1444 TAU_PROFILE_START(timer0b);
1448 CrystVector_REAL swapPar;
1450 CrystVector_long worldNbAcceptedMoves(nbWorld);
1451 worldNbAcceptedMoves=0;
1453 const int nbTrialsReport=3000;
1457 unsigned int first=1;
1464 cout <<
"Gene Group:"<<refParGeneGroupIndex(i)<<
" :";
1479 bool needUpdateDisplay=
false;
1481 bool makeReport=
false;
1484 float lastUpdateDisplayTime=chrono.seconds();
1485 TAU_PROFILE_STOP(timer0b);
1488 for(
int i=0;i<nbWorld;i++)
1494 for(
int j=0;j<nbTryPerWorld;j++)
1497 TAU_PROFILE_START(timer1);
1502 TAU_PROFILE_STOP(timer1);
1504 if(cost<currentCost(i))
1507 currentCost(i)=cost;
1509 if(cost<runBestCost)
1512 runBestCost=currentCost(i);
1514 needUpdateDisplay=
true;
1521 if(!silent) cout <<
"->Trial :" <<
mNbTrial
1522 <<
" World="<< worldSwapIndex(i)
1525 <<
" NEW OVERALL Best Cost="<<
mBestCost<< endl;
1527 else if(!silent) cout <<
"->Trial :" <<
mNbTrial
1528 <<
" World="<< worldSwapIndex(i)
1531 <<
" NEW RUN Best Cost="<<runBestCost<< endl;
1534 worldNbAcceptedMoves(i)++;
1538 if(log((rand()+1)/(REAL)RAND_MAX)<(-(cost-currentCost(i))/
mTemperature) )
1541 currentCost(i)=cost;
1543 worldNbAcceptedMoves(i)++;
1547 if( ((
mXMLAutoSave.GetChoice()==1)&&((chrono.seconds()-secondsWhenAutoSave)>86400))
1548 ||((
mXMLAutoSave.GetChoice()==2)&&((chrono.seconds()-secondsWhenAutoSave)>3600))
1549 ||((
mXMLAutoSave.GetChoice()==3)&&((chrono.seconds()-secondsWhenAutoSave)> 600))
1552 secondsWhenAutoSave=(
unsigned long)chrono.seconds();
1553 string saveFileName=this->
GetName();
1554 time_t date=time(0);
1556 strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
1557 char costAsChar[30];
1560 saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
1566 if((
mNbTrial%nbTrialsReport)==0) makeReport=
true;
1571 if((
mNbTrial%autoLSQPeriod)<(nbTryPerWorld*nbWorld))
1574 for(
int i=nbWorld-5;i<nbWorld;i++)
1576 #ifdef __WX__CRYST__
1577 mMutexStopAfterCycle.Lock();
1580 mMutexStopAfterCycle.Unlock();
1583 mMutexStopAfterCycle.Unlock();
1591 if(pos->first->GetNbLSQFunction()>0)
1593 CrystVector_REAL tmp;
1594 tmp =pos->first->GetLSQCalc(pos->second);
1595 tmp-=pos->first->GetLSQObs (pos->second);
1597 tmp*=pos->first->GetLSQWeight(pos->second);
1598 cout<<pos->first->GetClassName()<<
":"<<pos->first->GetName()<<
": GoF="<<tmp.sum()/tmp.numElements();
1604 if(!silent) cout<<
"LSQ: World="<<worldSwapIndex(i)<<
": cost="<<cost0;
1605 try {
mLSQ.
Refine(-30,
true,
true,
false,0.001);}
1610 if(pos->first->GetNbLSQFunction()>0)
1612 CrystVector_REAL tmp;
1613 tmp =pos->first->GetLSQCalc(pos->second);
1614 tmp-=pos->first->GetLSQObs (pos->second);
1616 tmp*=pos->first->GetLSQWeight(pos->second);
1617 cout<<pos->first->GetClassName()<<
":"<<pos->first->GetName()<<
": GoF="<<tmp.sum()/tmp.numElements();
1622 if(!silent) cout<<
" -> "<<cost<<endl;
1628 for(
int i=nbWorld-5;i<nbWorld;i++)
1632 if(!silent) cout<<
"LSQ2:"<<currentCost(i)<<
"->"<<cost<<endl;
1633 if(cost<currentCost(i))
1635 const REAL oldcost=currentCost(i);
1637 currentCost(i)=cost;
1638 if(cost<runBestCost)
1640 runBestCost=currentCost(i);
1642 needUpdateDisplay=
true;
1649 if(!silent) cout <<
"->Trial :" <<
mNbTrial
1650 <<
" World="<< worldSwapIndex(i)
1651 <<
" LSQ2: NEW OVERALL Best Cost="<<
mBestCost<< endl;
1653 else if(!silent) cout <<
"->Trial :" <<
mNbTrial
1654 <<
" World="<< worldSwapIndex(i)
1655 <<
" LSQ2: NEW RUN Best Cost="<<runBestCost<< endl;
1669 if(!silent) cout<<
"LSQ3: #"<<worldSwapIndex(i)<<
":"<<cost<<
"->"<<currentCost(i)<<endl;
1671 currentCost(i)=oldcost;
1678 for(
int i=1;i<nbWorld;i++)
1686 if( log((rand()+1)/(REAL)RAND_MAX)
1687 < (-(currentCost(i-1)-currentCost(i))/simAnnealTemp(i)))
1693 if( log((rand()+1)/(REAL)RAND_MAX)
1708 const REAL tmp=currentCost(i);
1709 currentCost(i)=currentCost(i-1);
1710 currentCost(i-1)=tmp;
1711 const long tmpIndex=worldSwapIndex(i);
1712 worldSwapIndex(i)=worldSwapIndex(i-1);
1713 worldSwapIndex(i-1)=tmpIndex;
1728 TAU_PROFILE_TIMER(timer1,\
1729 "MonteCarloObj::Optimize (Try mating Worlds)"\
1731 TAU_PROFILE_START(timer1);
1732 if( (rand()/(REAL)RAND_MAX)<.1)
1733 for(
int k=nbWorld-1;k>nbWorld/2;k--)
1734 for(
int i=k-nbWorld/3;i<k;i++)
1738 for(
unsigned int j=0;j<nbGeneGroup;j++)
1739 crossoverGroupIndex(j)= (int) floor(rand()/((REAL)RAND_MAX-1)*2);
1742 if(0==crossoverGroupIndex(refParGeneGroupIndex(j)-1))
1760 unsigned int crossoverPoint1=
1761 (int)(1+floor(rand()/((REAL)RAND_MAX-1)*(nbGeneGroup)));
1762 unsigned int crossoverPoint2=
1763 (int)(1+floor(rand()/((REAL)RAND_MAX-1)*(nbGeneGroup)));
1764 if(crossoverPoint2<crossoverPoint1)
1766 int tmp=crossoverPoint1;
1767 crossoverPoint1=crossoverPoint2;
1768 crossoverPoint2=tmp;
1770 if(crossoverPoint1==crossoverPoint2) crossoverPoint2+=1;
1773 if((refParGeneGroupIndex(j)>crossoverPoint1)&&refParGeneGroupIndex(j)<crossoverPoint2)
1790 for(
int junk=0;junk<2;junk++)
1797 if(cost<currentCost(k))
1806 currentCost(k)=cost;
1809 if(!silent) cout <<
"Accepted mating :"<<k<<
"(with"<<i<<
")"
1810 <<
" (crossoverGene1="<< crossoverPoint1<<
","
1811 <<
" crossoverGene2="<< crossoverPoint2<<
")"
1813 if(cost<runBestCost)
1817 needUpdateDisplay=
true;
1823 if(!silent) cout <<
"->Trial :" <<
mNbTrial
1824 <<
" World="<< worldSwapIndex(k)
1825 <<
" Temp="<< simAnnealTemp(k)
1827 <<
" NEW OVERALL Best Cost="<<
mBestCost<<
"(MATING !)"<<endl;
1829 else if(!silent) cout <<
"->Trial :" <<
mNbTrial
1830 <<
" World="<< worldSwapIndex(k)
1831 <<
" Temp="<< simAnnealTemp(k)
1833 <<
" NEW RUN Best Cost="<<runBestCost<<
"(MATING !)"<<endl;
1846 TAU_PROFILE_STOP(timer1);
1848 if(
true==makeReport)
1851 worldNbAcceptedMoves*=nbWorld;
1857 map<const RefinableObj*,REAL> ll,llvar;
1858 map<const RefinableObj*,LogLikelihoodStats>::iterator pos;
1862 llvar[pos->first]=0.;
1864 for(
int i=0;i<nbWorld;i++)
1868 ll [pos->first] += pos->second.mTotalLogLikelihood;
1869 llvar[pos->first] += pos->second.mTotalLogLikelihoodDeltaSq;
1874 cout << pos->first->GetName()
1875 <<
" " << llvar[pos->first]
1877 <<
" " << max<<endl;
1878 llvar[pos->first] *=
mvObjWeight[pos->first].mWeight;
1879 if(llvar[pos->first]>max) max=llvar[pos->first];
1881 map<const RefinableObj*,REAL>::iterator pos2;
1882 for(pos2=llvar.begin();pos2!=llvar.end();++pos2)
1884 const REAL d=pos2->second;
1893 for(pos2=ll.begin();pos2!=ll.end();++pos2)
1895 llt += pos2->second;
1896 ll1 += pos2->second *
mvObjWeight[pos2->first].mWeight;
1898 map<const RefinableObj*,DynamicObjWeight>::iterator posw;
1901 posw->second.mWeight *= llt/ll1;
1906 for(
int i=0;i<nbWorld;i++)
1908 cout<<
" World :"<<worldSwapIndex(i)<<
":";
1909 map<const RefinableObj*,LogLikelihoodStats>::iterator pos;
1912 cout << pos->first->GetName()
1914 << pos->second.mLastLogLikelihood
1921 pos->second.mTotalLogLikelihood=0;
1922 pos->second.mTotalLogLikelihoodDeltaSq=0;
1927 for(
int i=0;i<nbWorld;i++)
1930 cout <<
" World :" << worldSwapIndex(i)
1931 <<
" Temp.: " << simAnnealTemp(i)
1932 <<
" Mutation Ampl.: " << mutationAmplitude(i)
1933 <<
" Current Cost=" << currentCost(i)
1935 << (int)((REAL)worldNbAcceptedMoves(i)/nbTrialsReport*100)
1936 <<
"% moves " <<endl;
1940 if(!silent) cout <<
"Trial :" <<
mNbTrial <<
" Best Cost=" << runBestCost<<
" ";
1941 if(!silent) chrono.print();
1945 for(
int i=0;i<nbWorld;i++)
1947 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.30)
1948 mutationAmplitude(i)*=2.;
1949 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.10)
1950 mutationAmplitude(i)/=2.;
1959 for(
int i=0;i<nbWorld;i++)
1961 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.30)
1962 simAnnealTemp(i)/=1.5;
1963 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.80)
1964 simAnnealTemp(i)/=1.5;
1965 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.95)
1966 simAnnealTemp(i)/=1.5;
1968 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.10)
1969 simAnnealTemp(i)*=1.5;
1970 if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.04)
1971 simAnnealTemp(i)*=1.5;
1979 worldNbAcceptedMoves=0;
1982 #ifdef __WX__CRYST__
1983 if(0!=mpWXCrystObj) mpWXCrystObj->UpdateDisplayNbTrial();
1986 if( (needUpdateDisplay&&(lastUpdateDisplayTime<(chrono.seconds()-1)))||(lastUpdateDisplayTime<(chrono.seconds()-10)))
1990 needUpdateDisplay=
false;
1991 lastUpdateDisplayTime=chrono.seconds();
1993 #ifdef __WX__CRYST__
1994 mMutexStopAfterCycle.Lock();
1996 if((runBestCost<finalcost) ||
mStopAfterCycle ||( (maxTime>0)&&(chrono.seconds()>maxTime)))
1998 #ifdef __WX__CRYST__
1999 mMutexStopAfterCycle.Unlock();
2001 if(!silent) cout << endl <<endl <<
"Refinement Stopped:"<<
mBestCost<<endl;
2004 #ifdef __WX__CRYST__
2005 mMutexStopAfterCycle.Unlock();
2009 TAU_PROFILE_START(timerN);
2012 if(!silent) cout<<
"Beginning final LSQ refinement"<<endl;
2016 try {
mLSQ.
Refine(-50,
true,
true,
false,0.001);}
2036 if(!silent) cout <<
"LSQ : NEW OVERALL Best Cost="<<runBestCost<< endl;
2038 else if(!silent) cout <<
" LSQ : NEW Run Best Cost="<<runBestCost<< endl;
2041 if(!silent) cout<<
"Finished LSQ refinement"<<endl;
2051 if(!silent) cout<<
"Run Best Cost:"<<
mCurrentCost<<endl;
2052 if(!silent) chrono.print();
2058 for(
int i=0;i<nbWorld;i++)
2065 TAU_PROFILE_STOP(timerN);
2070 VFN_DEBUG_ENTRY(
"MonteCarloObj::XMLOutput():"<<this->
GetName(),5)
2071 for(
int i=0;i<indent;i++) os <<
" " ;
2073 tag.AddAttribute(
"Name",this->
GetName());
2074 tag.AddAttribute(
"NbTrialPerRun",(boost::format(
"%d")%(this->
NbTrialPerRun())).str());
2093 for(
int i=0;i<indent;i++) os <<
" " ;
2095 tag2.SetIsEndTag(
true);
2107 for(
int i=0;i<indent;i++) os <<
" " ;
2109 tag2.SetIsEndTag(
true);
2116 tag2.AddAttribute(
"ObjectType",
mRefinedObjList.GetObj(j).GetClassName());
2118 for(
int i=0;i<indent;i++) os <<
" " ;
2123 tag.SetIsEndTag(
true);
2124 for(
int i=0;i<indent;i++) os <<
" " ;
2126 VFN_DEBUG_EXIT(
"MonteCarloObj::XMLOutput():"<<this->
GetName(),5)
2131 VFN_DEBUG_ENTRY(
"MonteCarloObj::XMLInput():"<<this->
GetName(),5)
2132 for(
unsigned int i=0;i<tagg.GetNbAttribute();i++)
2134 if(
"Name"==tagg.GetAttributeName(i)) this->
SetName(tagg.GetAttributeValue(i));
2135 if(
"NbTrialPerRun"==tagg.GetAttributeName(i))
2137 stringstream ss(tagg.GetAttributeValue(i));
2146 if((
"GlobalOptimObj"==tag.GetName())&&tag.IsEndTag())
2148 VFN_DEBUG_EXIT(
"MonteCarloObj::Exit():"<<this->
GetName(),5)
2152 if(
"Option"==tag.GetName())
2154 for(
unsigned int i=0;i<tag.GetNbAttribute();i++)
2155 if(
"Name"==tag.GetAttributeName(i))
2157 if(
"Algorithm"==tag.GetAttributeValue(i))
2162 if(
"Temperature Schedule"==tag.GetAttributeValue(i))
2167 if(
"Displacement Amplitude Schedule"==tag.GetAttributeValue(i))
2172 if(
"Save Best Config Regularly"==tag.GetAttributeValue(i))
2177 if(
"Save Tracked Data"==tag.GetAttributeValue(i))
2182 if(
"Automatic Least Squares Refinement"==tag.GetAttributeValue(i))
2190 if(
"TempMaxMin"==tag.GetName())
2196 if(
"MutationMaxMin"==tag.GetName())
2202 if(
"RefinedObject"==tag.GetName())
2205 for(
unsigned int i=0;i<tag.GetNbAttribute();i++)
2207 if(
"ObjectName"==tag.GetAttributeName(i)) name=tag.GetAttributeValue(i);
2208 if(
"ObjectType"==tag.GetAttributeName(i)) type=tag.GetAttributeValue(i);
2225 TAU_PROFILE(
"MonteCarloObj::NewConfiguration()",
"void ()",TAU_DEFAULT);
2226 VFN_DEBUG_ENTRY(
"MonteCarloObj::NewConfiguration()",4)
2231 VFN_DEBUG_EXIT(
"MonteCarloObj::NewConfiguration()",4)
2236 VFN_DEBUG_MESSAGE(
"MonteCarloObj::InitOptions()",5)
2238 static string GlobalOptimTypeName;
2239 static string GlobalOptimTypeChoices[2];
2241 static string AnnealingScheduleChoices[6];
2243 static string AnnealingScheduleTempName;
2244 static string AnnealingScheduleMutationName;
2246 static string runAutoLSQName;
2247 static string runAutoLSQChoices[3];
2249 static string saveTrackedDataName;
2250 static string saveTrackedDataChoices[2];
2252 static bool needInitNames=
true;
2253 if(
true==needInitNames)
2255 GlobalOptimTypeName=
"Algorithm";
2256 GlobalOptimTypeChoices[0]=
"Simulated Annealing";
2257 GlobalOptimTypeChoices[1]=
"Parallel Tempering";
2260 AnnealingScheduleTempName=
"Temperature Schedule";
2261 AnnealingScheduleMutationName=
"Displacement Amplitude Schedule";
2262 AnnealingScheduleChoices[0]=
"Constant";
2263 AnnealingScheduleChoices[1]=
"Boltzmann";
2264 AnnealingScheduleChoices[2]=
"Cauchy";
2265 AnnealingScheduleChoices[3]=
"Exponential";
2266 AnnealingScheduleChoices[4]=
"Smart";
2267 AnnealingScheduleChoices[5]=
"Gamma";
2269 runAutoLSQName=
"Automatic Least Squares Refinement";
2270 runAutoLSQChoices[0]=
"Never";
2271 runAutoLSQChoices[1]=
"At the end of each run";
2272 runAutoLSQChoices[2]=
"Every 150000 trials, and at the end of each run";
2274 saveTrackedDataName=
"Save Tracked Data";
2275 saveTrackedDataChoices[0]=
"No (recommended!)";
2276 saveTrackedDataChoices[1]=
"Yes (for tests ONLY)";
2278 needInitNames=
false;
2284 mAutoLSQ.Init(3,&runAutoLSQName,runAutoLSQChoices);
2290 VFN_DEBUG_MESSAGE(
"MonteCarloObj::InitOptions():End",5)
2299 if(!useFullPowderPatternProfile)
2302 if(pos->first->GetClassName()==
"PowderPattern") pos->second=1;
2308 std::list<RefinablePar*> vIntCorrPar;
2316 for(std::list<RefinablePar*>::iterator pos=vIntCorrPar.begin();pos!=vIntCorrPar.end();pos++)
2317 (*pos)->SetIsFixed(
false);
2326 #ifdef __WX__CRYST__
2327 if(0!=mpWXCrystObj) mpWXCrystObj->CrystUpdate(
true,
true);
2332 #ifdef __WX__CRYST__
2336 return mpWXCrystObj;
2338 WXOptimizationObj* MonteCarloObj::WXGet()
2340 return mpWXCrystObj;
2342 void MonteCarloObj::WXDelete()
2344 if(0!=mpWXCrystObj)
delete mpWXCrystObj;
2347 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)