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" 
   37    #undef GetClassName // Conflict from wxMSW headers ? (cygwin) 
   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;
 
   70 mName(name),mSaveFileName(
"GlobalOptim.save"),
 
   71 mNbTrialPerRun(10000000),mNbTrial(0),mBestCost(-1),
 
   72 mBestParSavedSetIndex(-1),
 
   74 mIsOptimizing(false),mStopAfterCycle(false),
 
   75 mRefinedObjList(
"OptimizationObj: "+mName+
" RefinableObj registry"),
 
   76 mRecursiveRefinedObjList(
"OptimizationObj: "+mName+
" recursive RefinableObj registry"),
 
   79    VFN_DEBUG_ENTRY(
"OptimizationObj::OptimizationObj()",5)
 
   84    static bool need_initRandomSeed=
true;
 
   85    if(need_initRandomSeed==
true)
 
   88       need_initRandomSeed=
false;
 
   92    VFN_DEBUG_EXIT(
"OptimizationObj::OptimizationObj()",5)
 
   97    VFN_DEBUG_ENTRY(
"OptimizationObj::~OptimizationObj()",5)
 
   99    VFN_DEBUG_EXIT(
"OptimizationObj::~OptimizationObj()",5)
 
  104    VFN_DEBUG_ENTRY(
"OptimizationObj::RandomizeStartingConfig()",5)
 
  119    VFN_DEBUG_EXIT(
"OptimizationObj::RandomizeStartingConfig()",5)
 
  124    VFN_DEBUG_ENTRY(
"OptimizationObj::FixAllPar()",5)
 
  128    VFN_DEBUG_EXIT(
"OptimizationObj::FixAllPar():End",5)
 
  163                                        const REAL min, 
const REAL max)
 
  170                                        const REAL min, 
const REAL max)
 
  177                                        const REAL min, 
const REAL max)
 
  184                                        const REAL min, 
const REAL max)
 
  193    TAU_PROFILE(
"OptimizationObj::GetLogLikelihood()",
"void ()",TAU_DEFAULT);
 
  213    VFN_DEBUG_MESSAGE(
"OptimizationObj::StopAfterCycle()",5)
 
  217       wxMutexLocker lock(mMutexStopAfterCycle);
 
  230    VFN_DEBUG_MESSAGE(
"OptimizationObj::AddRefinableObj():"<<obj.
GetName(),5)
 
  237    if(0!=this->WXGet()) this->WXGet()->AddRefinedObject(obj);
 
  280 const RefObjOpt& OptimizationObj::GetXMLAutoSaveOption()
const {
return mXMLAutoSave;}
 
  289       mRefinedObjList.GetObj(i).BeginOptimization(allowApproximations,enableRestraints);
 
  304    VFN_DEBUG_ENTRY(
"OptimizationObj::PrepareRefParList()",6)
 
  314       VFN_DEBUG_MESSAGE(
"OptimizationObj::PrepareRefParList():Rebuild list",6)
 
  328          (this->
GetName()+
"::Overall LogLikelihood",*
this,fl));
 
  343                (pCryst->
GetName()+
"::BumpMergeCost",*pCryst,fc));
 
  346                (pCryst->
GetName()+
"::BondValenceCost",*pCryst,fc));
 
  355    VFN_DEBUG_EXIT(
"OptimizationObj::PrepareRefParList()",6)
 
  360    VFN_DEBUG_MESSAGE(
"OptimizationObj::InitOptions()",5)
 
  361    static string xmlAutoSaveName;
 
  362    static string xmlAutoSaveChoices[6];
 
  364    static bool needInitNames=
true;
 
  365    if(
true==needInitNames)
 
  367       xmlAutoSaveName=
"Save Best Config Regularly";
 
  368       xmlAutoSaveChoices[0]=
"No";
 
  369       xmlAutoSaveChoices[1]=
"Every day";
 
  370       xmlAutoSaveChoices[2]=
"Every hour";
 
  371       xmlAutoSaveChoices[3]=
"Every 10mn";
 
  372       xmlAutoSaveChoices[4]=
"Every new best config (a lot ! Not Recommended !)";
 
  373       xmlAutoSaveChoices[5]=
"Every Run (Recommended)";
 
  377    mXMLAutoSave.Init(6,&xmlAutoSaveName,xmlAutoSaveChoices);
 
  378    VFN_DEBUG_MESSAGE(
"OptimizationObj::InitOptions():End",5)
 
  385    if(0!=this->WXGet()) this->WXGet()->CrystUpdate(
true,
true);
 
  399       VFN_DEBUG_ENTRY(
"OptimizationObj::BuildRecursiveRefObjList()",5)
 
  403       VFN_DEBUG_EXIT(
"OptimizationObj::BuildRecursiveRefObjList()",5)
 
  415 mTemperatureMax(1e6),mTemperatureMin(.001),mTemperatureGamma(1.0),
 
  416 mMutationAmplitudeMax(8.),mMutationAmplitudeMin(.125),mMutationAmplitudeGamma(1.0),
 
  417 mNbTrialRetry(0),mMinCostRetry(0)
 
  422    VFN_DEBUG_ENTRY(
"MonteCarloObj::MonteCarloObj()",5)
 
  430    VFN_DEBUG_EXIT(
"MonteCarloObj::MonteCarloObj()",5)
 
  436 mTemperatureMax(.03),mTemperatureMin(.003),mTemperatureGamma(1.0),
 
  437 mMutationAmplitudeMax(16.),mMutationAmplitudeMin(.125),mMutationAmplitudeGamma(1.0),
 
  438 mNbTrialRetry(0),mMinCostRetry(0)
 
  443    VFN_DEBUG_ENTRY(
"MonteCarloObj::MonteCarloObj(bool)",5)
 
  451    VFN_DEBUG_EXIT(
"MonteCarloObj::MonteCarloObj(bool)",5)
 
  456    VFN_DEBUG_ENTRY(
"MonteCarloObj::~MonteCarloObj()",5)
 
  458    VFN_DEBUG_EXIT (
"MonteCarloObj::~MonteCarloObj()",5)
 
  461                            const REAL tMax, 
const REAL tMin,
 
  463                            const REAL mutMax, 
const REAL mutMin,
 
  464                            const long nbTrialRetry,
const REAL minCostRetry)
 
  466    VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmSimulAnnealing()",5)
 
  478    VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmSimulAnnealing():End",3)
 
  482                                  const REAL tMax, 
const REAL tMin,
 
  484                                  const REAL mutMax, 
const REAL mutMin)
 
  486    VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmParallTempering()",5)
 
  497    VFN_DEBUG_MESSAGE(
"MonteCarloObj::SetAlgorithmParallTempering():End",3)
 
  503    TAU_PROFILE(
"MonteCarloObj::Optimize()",
"void (long)",TAU_DEFAULT);
 
  504    VFN_DEBUG_ENTRY(
"MonteCarloObj::Optimize()",5)
 
  523       case GLOBAL_OPTIM_SIMULATED_ANNEALING:
 
  528       case GLOBAL_OPTIM_PARALLEL_TEMPERING:
 
  533       case GLOBAL_OPTIM_RANDOM_LSQ: 
 
  536           this->RunRandomLSQMethod(cycles);
 
  542    mMutexStopAfterCycle.Lock();
 
  546    mMutexStopAfterCycle.Unlock();
 
  555       const string outTrackerName=this->
GetName()+
"-Tracker.dat";
 
  556       outTracker.open(outTrackerName.c_str());
 
  574    VFN_DEBUG_EXIT(
"MonteCarloObj::Optimize()",5)
 
  577                                      const REAL finalcost,
const REAL maxTime)
 
  580    TAU_PROFILE(
"MonteCarloObj::MultiRunOptimize()",
"void (long)",TAU_DEFAULT);
 
  581    VFN_DEBUG_ENTRY(
"MonteCarloObj::MultiRunOptimize()",5)
 
  583    const long nbStep0=nbStep;
 
  600    const long nbCycle0=nbCycle;
 
  604       if(!silent) cout <<
"MonteCarloObj::MultiRunOptimize: Starting Run#"<<abs(nbCycle)<<endl;
 
  611          case GLOBAL_OPTIM_SIMULATED_ANNEALING:
 
  614             catch(...){cout<<
"Unhandled exception in MonteCarloObj::MultiRunOptimize() ?"<<endl;}
 
  617          case GLOBAL_OPTIM_PARALLEL_TEMPERING:
 
  620             catch(...){cout<<
"Unhandled exception in MonteCarloObj::MultiRunOptimize() ?"<<endl;}
 
  623          case GLOBAL_OPTIM_RANDOM_LSQ:
 
  625             try{this->RunRandomLSQMethod(nbCycle);}
 
  626             catch(...){cout<<
"Unhandled exception in MonteCarloObj::RunRandomLSQMethod() ?"<<endl;}
 
  631       nbTrialCumul+=(nbStep0-nbStep);
 
  633          cout<<
"Finished Run #"<<nbCycle0-nbCycle<<
", final cost=" 
  634              <<this->
GetLogLikelihood()<<
", nbTrial="<< nbStep0-nbStep<<
" ("<<chrono.seconds()
 
  635              <<
" seconds), so far <nbTrial>="<< nbTrialCumul/(nbCycle0-nbCycle+1)<<endl;
 
  637          cout<<
"Finished Run #"<<nbCycle0-nbCycle<<
", final cost=" 
  638              <<this->
GetLogLikelihood()<<
", nbTrial="<< nbStep0-nbStep<<
" ("<<chrono.seconds()
 
  644       s<<
"Run #"<<abs(nbCycle);
 
  646       if(!silent) cout <<
"MonteCarloObj::MultiRunOptimize: Finished Run#" 
  648                        <<
", Overall Best Cost:"<<
mBestCost<<endl;
 
  651          string saveFileName=this->
GetName();
 
  654          strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
 
  656          sprintf(costAsChar,
"-Run#%ld-Cost-%f",abs(nbCycle),this->
GetLogLikelihood());
 
  657          saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
 
  664          sprintf(runNum,
"-Tracker-Run#%ld.dat",abs(nbCycle));
 
  665          const string outTrackerName=this->
GetName()+runNum;
 
  666          outTracker.open(outTrackerName.c_str());
 
  672       mMutexStopAfterCycle.Lock();
 
  677          mMutexStopAfterCycle.Unlock();
 
  682       mMutexStopAfterCycle.Unlock();
 
  688    mMutexStopAfterCycle.Lock();
 
  692    mMutexStopAfterCycle.Unlock();
 
  713       cout<<endl<<
"Finished all runs, number of trials to reach cost=" 
  714           <<finalcost<<
" : <nbTrial>="<<nbTrialCumul/(nbCycle0-nbCycle)<<endl;
 
  715    VFN_DEBUG_EXIT(
"MonteCarloObj::MultiRunOptimize()",5)
 
  719                                           const REAL finalcost,
const REAL maxTime)
 
  722    const long nbSteps=nbStep;
 
  726       unsigned long secondsWhenAutoSave=0;
 
  728    if(!silent) cout << 
"Starting Simulated Annealing Optimization for"<<nbSteps<<
" trials"<<endl;
 
  736       const int nbTryReport=3000;
 
  738       long nbAcceptedMoves=0;
 
  739       long nbAcceptedMovesTemp=0;
 
  741       long nbTriesSinceBest=0;
 
  743       const int nbTryPerTemp=300;
 
  749    bool needUpdateDisplay=
false;
 
  756          VFN_DEBUG_MESSAGE(
"-> Updating temperature and mutation amplitude.",3)
 
  760             case ANNEALING_BOLTZMANN:
 
  763             case ANNEALING_CAUCHY:
 
  766             case ANNEALING_EXPONENTIAL:
 
  770             case ANNEALING_GAMMA:
 
  773             case ANNEALING_SMART:
 
  775                if((nbAcceptedMovesTemp/(REAL)nbTryPerTemp)>0.30)
 
  777                if((nbAcceptedMovesTemp/(REAL)nbTryPerTemp)<0.10)
 
  781                nbAcceptedMovesTemp=0;
 
  788             case ANNEALING_BOLTZMANN:
 
  792             case ANNEALING_CAUCHY:
 
  795             case ANNEALING_EXPONENTIAL:
 
  799             case ANNEALING_GAMMA:
 
  802             case ANNEALING_SMART:
 
  809                nbAcceptedMovesTemp=0;
 
  828             needUpdateDisplay=
true;
 
  834                if(!silent) cout << 
"Trial :" << 
mNbTrial 
  837                              << 
" NEW OVERALL Best Cost="<<runBestCost<< endl;
 
  839             else if(!silent) cout << 
"Trial :" << 
mNbTrial 
  842                              << 
" NEW Run Best Cost="<<runBestCost<< endl;
 
  846          nbAcceptedMovesTemp++;
 
  856             nbAcceptedMovesTemp++;
 
  864          if(!silent) cout <<
" Mutation Ampl.: " <<
mMutationAmplitude<< 
" Best Cost=" << runBestCost
 
  866                           <<
" Accepting "<<(int)((REAL)nbAcceptedMoves/nbTryReport*100)
 
  870          if(0!=mpWXCrystObj) mpWXCrystObj->UpdateDisplayNbTrial();
 
  876       mMutexStopAfterCycle.Lock();
 
  878       if((runBestCost<finalcost) || 
mStopAfterCycle ||( (maxTime>0)&&(chrono.seconds()>maxTime)))
 
  881          mMutexStopAfterCycle.Unlock();
 
  883          if(!silent) cout << endl <<endl << 
"Refinement Stopped."<<endl;
 
  887       mMutexStopAfterCycle.Unlock();
 
  890       if(  ((
mXMLAutoSave.GetChoice()==1)&&((chrono.seconds()-secondsWhenAutoSave)>86400))
 
  891          ||((
mXMLAutoSave.GetChoice()==2)&&((chrono.seconds()-secondsWhenAutoSave)>3600))
 
  892          ||((
mXMLAutoSave.GetChoice()==3)&&((chrono.seconds()-secondsWhenAutoSave)> 600))
 
  895          secondsWhenAutoSave=(
unsigned long)chrono.seconds();
 
  896          string saveFileName=this->
GetName();
 
  899          strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
 
  903          saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
 
  907       if((
mNbTrial%300==0)&&needUpdateDisplay)
 
  910          needUpdateDisplay=
false;
 
  918       if(!silent) cout<<
"Beginning final LSQ refinement"<<endl;
 
  942                if(!silent) cout << 
"LSQ : NEW OVERALL Best Cost="<<runBestCost<< endl;
 
  944             else if(!silent) cout << 
" LSQ : NEW Run Best Cost="<<runBestCost<< endl;
 
  947       if(!silent) cout<<
"Finished LSQ refinement"<<endl;
 
  958    if(!silent) chrono.print();
 
 1029 void MonteCarloObj::RunRandomLSQMethod(
long &nbCycle)
 
 1033     float bsigma=-1, bdelta=-1;
 
 1034     float asigma=-1, adelta=-1;
 
 1044                     if(pMol==NULL) 
continue; 
 
 1045                     for(vector<MolBond*>::iterator pos = pMol->GetBondList().begin(); pos != pMol->GetBondList().end();++pos) {
 
 1046                         bsigma = (*pos)->GetLengthSigma();
 
 1047                         bdelta = (*pos)->GetLengthDelta();
 
 1048                         (*pos)->SetLengthDelta(0.02);
 
 1049                         (*pos)->SetLengthSigma(0.001);
 
 1051                     for(vector<MolBondAngle*>::iterator pos=pMol->GetBondAngleList().begin();pos != pMol->GetBondAngleList().end();++pos)
 
 1053                         asigma = (*pos)->GetAngleSigma();
 
 1054                         adelta = (*pos)->GetAngleDelta();
 
 1055                         (*pos)->SetAngleDelta(0.2*DEG2RAD);
 
 1056                         (*pos)->SetAngleSigma(0.01*DEG2RAD);
 
 1059             } 
catch (
const std::bad_cast& e){
 
 1080         catch(
const ObjCrystException &except) {
 
 1096         string saveFileName=this->
GetName();
 
 1097         time_t date=time(0);
 
 1099         strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
 
 1100         char costAsChar[30];
 
 1101         sprintf(costAsChar,
"#Run%ld-Cost-%f",nbCycle, 
mCurrentCost);
 
 1102         saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(
string)".xml";
 
 1105          #ifdef __WX__CRYST__ 
 1106           mMutexStopAfterCycle.Lock();
 
 1110              #ifdef __WX__CRYST__ 
 1111              mMutexStopAfterCycle.Unlock();
 
 1115           #ifdef __WX__CRYST__ 
 1116           mMutexStopAfterCycle.Unlock();
 
 1120     if(bsigma<0 || bdelta<0 || asigma<0 || adelta<0) 
return;
 
 1125                 Crystal * pCryst = 
dynamic_cast<Crystal *
>(&(
mRefinedObjList.GetObj(i)));
 
 1126                 for(
int s=0;s<pCryst->GetScattererRegistry().GetNb();s++)
 
 1128                     Molecule *pMol=
dynamic_cast<Molecule*
>(&(pCryst->GetScatt(s)));
 
 1129                     if(pMol==NULL) 
continue; 
 
 1130                     for(vector<MolBond*>::iterator pos = pMol->GetBondList().begin(); pos != pMol->GetBondList().end();++pos) {
 
 1131                         (*pos)->SetLengthDelta(bdelta);
 
 1132                         (*pos)->SetLengthSigma(bsigma);
 
 1134                     for(vector<MolBondAngle*>::iterator pos=pMol->GetBondAngleList().begin();pos != pMol->GetBondAngleList().end();++pos)
 
 1136                         (*pos)->SetAngleDelta(adelta);
 
 1137                         (*pos)->SetAngleSigma(asigma);
 
 1140             } 
catch (
const std::bad_cast& e){
 
 1148                                          const REAL finalcost,
const REAL maxTime)
 
 1150    TAU_PROFILE(
"MonteCarloObj::RunParallelTempering()",
"void ()",TAU_DEFAULT);
 
 1151    TAU_PROFILE_TIMER(timer0a,
"MonteCarloObj::RunParallelTempering() Begin 1",
"", TAU_FIELD);
 
 1152    TAU_PROFILE_TIMER(timer0b,
"MonteCarloObj::RunParallelTempering() Begin 2",
"", TAU_FIELD);
 
 1153    TAU_PROFILE_TIMER(timer1,
"MonteCarloObj::RunParallelTempering() New Config + LLK",
"", TAU_FIELD);
 
 1154    TAU_PROFILE_TIMER(timerN,
"MonteCarloObj::RunParallelTempering() Finish",
"", TAU_FIELD);
 
 1155    TAU_PROFILE_START(timer0a);
 
 1157    const long nbSteps=nbStep;
 
 1158    unsigned int accept;
 
 1161       unsigned long secondsWhenAutoSave=0;
 
 1164    const unsigned int autoLSQPeriod=150000;
 
 1166    if(!silent) cout << 
"Starting Parallel Tempering Optimization"<<endl;
 
 1170       const long nbWorld=30;
 
 1171       CrystVector_long worldSwapIndex(nbWorld);
 
 1172       for(
int i=0;i<nbWorld;++i) worldSwapIndex(i)=i;
 
 1176       const int nbTryPerWorld=10;
 
 1180       CrystVector_REAL currentCost(nbWorld);
 
 1183       CrystVector_REAL simAnnealTemp(nbWorld);
 
 1184       for(
int i=0;i<nbWorld;i++)
 
 1188             case ANNEALING_BOLTZMANN:
 
 1191             case ANNEALING_CAUCHY:
 
 1194             case ANNEALING_EXPONENTIAL:
 
 1197                                     i/(REAL)(nbWorld-1));
break;
 
 1198             case ANNEALING_GAMMA:
 
 1201             case ANNEALING_SMART:
 
 1202                simAnnealTemp(i)=
mCurrentCost/(100.+(REAL)i/(REAL)nbWorld*900.);
break;
 
 1204                simAnnealTemp(i)=
mCurrentCost/(100.+(REAL)i/(REAL)nbWorld*900.);
break;
 
 1208       CrystVector_REAL mutationAmplitude(nbWorld);
 
 1209       for(
int i=0;i<nbWorld;i++)
 
 1213             case ANNEALING_BOLTZMANN:
 
 1214                mutationAmplitude(i)=
 
 1217             case ANNEALING_CAUCHY:
 
 1220             case ANNEALING_EXPONENTIAL:
 
 1223                                     i/(REAL)(nbWorld-1));
break;
 
 1224             case ANNEALING_GAMMA:
 
 1227             case ANNEALING_SMART:
 
 1235       CrystVector_long worldCurrentSetIndex(nbWorld);
 
 1236       for(
int i=nbWorld-1;i>=0;i--)
 
 1238          if((i!=(nbWorld-1))&&(i%2==0))
 
 1244    TAU_PROFILE_STOP(timer0a);
 
 1245    TAU_PROFILE_START(timer0b);
 
 1249       CrystVector_REAL swapPar;
 
 1251       CrystVector_long worldNbAcceptedMoves(nbWorld);
 
 1252       worldNbAcceptedMoves=0;
 
 1254       const int nbTrialsReport=3000;
 
 1258          unsigned int first=1;
 
 1265                cout << 
"Gene Group:"<<refParGeneGroupIndex(i)<<
" :";
 
 1280    bool needUpdateDisplay=
false;
 
 1282    bool makeReport=
false;
 
 1285    float lastUpdateDisplayTime=chrono.seconds();
 
 1286    TAU_PROFILE_STOP(timer0b);
 
 1289       for(
int i=0;i<nbWorld;i++)
 
 1295          for(
int j=0;j<nbTryPerWorld;j++)
 
 1298             TAU_PROFILE_START(timer1);
 
 1303             TAU_PROFILE_STOP(timer1);
 
 1305             if(cost<currentCost(i))
 
 1308                currentCost(i)=cost;
 
 1310                if(cost<runBestCost)
 
 1313                   runBestCost=currentCost(i);
 
 1315                   needUpdateDisplay=
true;
 
 1322                      if(!silent) cout << 
"->Trial :" << 
mNbTrial 
 1323                                    << 
" World="<< worldSwapIndex(i)
 
 1326                                    << 
" NEW OVERALL Best Cost="<<
mBestCost<< endl;
 
 1328                   else if(!silent) cout << 
"->Trial :" << 
mNbTrial 
 1329                                    << 
" World="<< worldSwapIndex(i)
 
 1332                                    << 
" NEW RUN Best Cost="<<runBestCost<< endl;
 
 1335                worldNbAcceptedMoves(i)++;
 
 1339                if(log((rand()+1)/(REAL)RAND_MAX)<(-(cost-currentCost(i))/
mTemperature) )
 
 1342                   currentCost(i)=cost;
 
 1344                   worldNbAcceptedMoves(i)++;
 
 1348             if(  ((
mXMLAutoSave.GetChoice()==1)&&((chrono.seconds()-secondsWhenAutoSave)>86400))
 
 1349                ||((
mXMLAutoSave.GetChoice()==2)&&((chrono.seconds()-secondsWhenAutoSave)>3600))
 
 1350                ||((
mXMLAutoSave.GetChoice()==3)&&((chrono.seconds()-secondsWhenAutoSave)> 600))
 
 1353                secondsWhenAutoSave=(
unsigned long)chrono.seconds();
 
 1354                string saveFileName=this->
GetName();
 
 1355                time_t date=time(0);
 
 1357                strftime(strDate,
sizeof(strDate),
"%Y-%m-%d_%H-%M-%S",localtime(&date));
 
 1358                char costAsChar[30];
 
 1361                saveFileName=saveFileName+(string)strDate+(
string)costAsChar+(string)
".xml";
 
 1367             if((
mNbTrial%nbTrialsReport)==0) makeReport=
true;
 
 1372          if((
mNbTrial%autoLSQPeriod)<(nbTryPerWorld*nbWorld))
 
 1375             for(
int i=nbWorld-5;i<nbWorld;i++)
 
 1377                #ifdef __WX__CRYST__ 
 1378                mMutexStopAfterCycle.Lock();
 
 1381                   mMutexStopAfterCycle.Unlock();
 
 1384                mMutexStopAfterCycle.Unlock();
 
 1392                   if(pos->first->GetNbLSQFunction()>0)
 
 1394                      CrystVector_REAL tmp;
 
 1395                      tmp =pos->first->GetLSQCalc(pos->second);
 
 1396                      tmp-=pos->first->GetLSQObs (pos->second);
 
 1398                      tmp*=pos->first->GetLSQWeight(pos->second);
 
 1399                      cout<<pos->first->GetClassName()<<
":"<<pos->first->GetName()<<
": GoF="<<tmp.sum()/tmp.numElements();
 
 1405                if(!silent) cout<<
"LSQ: World="<<worldSwapIndex(i)<<
": cost="<<cost0;
 
 1406                try {
mLSQ.
Refine(-30,
true,
true,
false,0.001);}
 
 1411                   if(pos->first->GetNbLSQFunction()>0)
 
 1413                      CrystVector_REAL tmp;
 
 1414                      tmp =pos->first->GetLSQCalc(pos->second);
 
 1415                      tmp-=pos->first->GetLSQObs (pos->second);
 
 1417                      tmp*=pos->first->GetLSQWeight(pos->second);
 
 1418                      cout<<pos->first->GetClassName()<<
":"<<pos->first->GetName()<<
": GoF="<<tmp.sum()/tmp.numElements();
 
 1423                if(!silent) cout<<
" -> "<<cost<<endl;
 
 1429             for(
int i=nbWorld-5;i<nbWorld;i++)
 
 1433                if(!silent) cout<<
"LSQ2:"<<currentCost(i)<<
"->"<<cost<<endl;
 
 1434                if(cost<currentCost(i))
 
 1436                   const REAL oldcost=currentCost(i);
 
 1438                   currentCost(i)=cost;
 
 1439                   if(cost<runBestCost)
 
 1441                      runBestCost=currentCost(i);
 
 1443                      needUpdateDisplay=
true;
 
 1450                         if(!silent) cout << 
"->Trial :" << 
mNbTrial 
 1451                                        << 
" World="<< worldSwapIndex(i)
 
 1452                                        << 
" LSQ2: NEW OVERALL Best Cost="<<
mBestCost<< endl;
 
 1454                      else if(!silent) cout << 
"->Trial :" << 
mNbTrial 
 1455                                        << 
" World="<< worldSwapIndex(i)
 
 1456                                        << 
" LSQ2: NEW RUN Best Cost="<<runBestCost<< endl;
 
 1470                   if(!silent) cout<<
"LSQ3: #"<<worldSwapIndex(i)<<
":"<<cost<<
"->"<<currentCost(i)<<endl;
 
 1472                   currentCost(i)=oldcost;
 
 1479       for(
int i=1;i<nbWorld;i++)
 
 1487          if( log((rand()+1)/(REAL)RAND_MAX)
 
 1488                 < (-(currentCost(i-1)-currentCost(i))/simAnnealTemp(i)))
 
 1494          if( log((rand()+1)/(REAL)RAND_MAX)
 
 1509             const REAL tmp=currentCost(i);
 
 1510             currentCost(i)=currentCost(i-1);
 
 1511             currentCost(i-1)=tmp;
 
 1512             const long tmpIndex=worldSwapIndex(i);
 
 1513             worldSwapIndex(i)=worldSwapIndex(i-1);
 
 1514             worldSwapIndex(i-1)=tmpIndex;
 
 1529       TAU_PROFILE_TIMER(timer1,\
 
 1530                "MonteCarloObj::Optimize (Try mating Worlds)"\
 
 1532       TAU_PROFILE_START(timer1);
 
 1533       if( (rand()/(REAL)RAND_MAX)<.1)
 
 1534       for(
int k=nbWorld-1;k>nbWorld/2;k--)
 
 1535          for(
int i=k-nbWorld/3;i<k;i++)
 
 1539             for(
unsigned int j=0;j<nbGeneGroup;j++)
 
 1540                crossoverGroupIndex(j)= (int) floor(rand()/((REAL)RAND_MAX-1)*2);
 
 1543                if(0==crossoverGroupIndex(refParGeneGroupIndex(j)-1))
 
 1561             unsigned int crossoverPoint1=
 
 1562                (int)(1+floor(rand()/((REAL)RAND_MAX-1)*(nbGeneGroup)));
 
 1563             unsigned int crossoverPoint2=
 
 1564                (int)(1+floor(rand()/((REAL)RAND_MAX-1)*(nbGeneGroup)));
 
 1565             if(crossoverPoint2<crossoverPoint1)
 
 1567                int tmp=crossoverPoint1;
 
 1568                crossoverPoint1=crossoverPoint2;
 
 1569                crossoverPoint2=tmp;
 
 1571             if(crossoverPoint1==crossoverPoint2) crossoverPoint2+=1;
 
 1574                if((refParGeneGroupIndex(j)>crossoverPoint1)&&refParGeneGroupIndex(j)<crossoverPoint2)
 
 1591             for(
int junk=0;junk<2;junk++)
 
 1598                if(cost<currentCost(k))
 
 1607                   currentCost(k)=cost;
 
 1610                   if(!silent) cout << 
"Accepted mating :"<<k<<
"(with"<<i<<
")" 
 1611                        <<
" (crossoverGene1="<< crossoverPoint1<<
"," 
 1612                        <<
" crossoverGene2="<< crossoverPoint2<<
")" 
 1614                   if(cost<runBestCost)
 
 1618                      needUpdateDisplay=
true;
 
 1624                         if(!silent) cout << 
"->Trial :" << 
mNbTrial 
 1625                           << 
" World="<< worldSwapIndex(k)
 
 1626                           << 
" Temp="<< simAnnealTemp(k)
 
 1628                           << 
" NEW OVERALL Best Cost="<<
mBestCost<< 
"(MATING !)"<<endl;
 
 1630                      else if(!silent) cout << 
"->Trial :" << 
mNbTrial 
 1631                           << 
" World="<< worldSwapIndex(k)
 
 1632                           << 
" Temp="<< simAnnealTemp(k)
 
 1634                           << 
" NEW RUN Best Cost="<<runBestCost<< 
"(MATING !)"<<endl;
 
 1647       TAU_PROFILE_STOP(timer1);
 
 1649       if(
true==makeReport)
 
 1652          worldNbAcceptedMoves*=nbWorld;
 
 1658                map<const RefinableObj*,REAL> ll,llvar;
 
 1659                map<const RefinableObj*,LogLikelihoodStats>::iterator pos;
 
 1663                   llvar[pos->first]=0.;
 
 1665                for(
int i=0;i<nbWorld;i++)
 
 1669                      ll   [pos->first] += pos->second.mTotalLogLikelihood;
 
 1670                      llvar[pos->first] += pos->second.mTotalLogLikelihoodDeltaSq;
 
 1675                   cout << pos->first->GetName()
 
 1676                        << 
" " << llvar[pos->first]
 
 1678                        << 
" " << max<<endl;
 
 1679                   llvar[pos->first] *= 
mvObjWeight[pos->first].mWeight;
 
 1680                   if(llvar[pos->first]>max) max=llvar[pos->first];
 
 1682                map<const RefinableObj*,REAL>::iterator pos2;
 
 1683                for(pos2=llvar.begin();pos2!=llvar.end();++pos2)
 
 1685                   const REAL d=pos2->second;
 
 1694                for(pos2=ll.begin();pos2!=ll.end();++pos2)
 
 1696                   llt += pos2->second;
 
 1697                   ll1 += pos2->second * 
mvObjWeight[pos2->first].mWeight;
 
 1699                map<const RefinableObj*,DynamicObjWeight>::iterator posw;
 
 1702                   posw->second.mWeight *= llt/ll1;
 
 1705             #endif //Experimental dynamical weighting 
 1706             #if 1 //def __DEBUG__ 
 1707             for(
int i=0;i<nbWorld;i++)
 
 1709                cout<<
"   World :"<<worldSwapIndex(i)<<
":";
 
 1710                map<const RefinableObj*,LogLikelihoodStats>::iterator pos;
 
 1713                   cout << pos->first->GetName()
 
 1715                        << pos->second.mLastLogLikelihood
 
 1722                   pos->second.mTotalLogLikelihood=0;
 
 1723                   pos->second.mTotalLogLikelihoodDeltaSq=0;
 
 1728             for(
int i=0;i<nbWorld;i++)
 
 1731                cout <<
"   World :" << worldSwapIndex(i)
 
 1732                     <<
" Temp.: " << simAnnealTemp(i)
 
 1733                     <<
" Mutation Ampl.: " << mutationAmplitude(i)
 
 1734                     <<
" Current Cost=" << currentCost(i)
 
 1736                     << (int)((REAL)worldNbAcceptedMoves(i)/nbTrialsReport*100)
 
 1737                     <<
"% moves " <<endl;
 
 1741          if(!silent) cout <<
"Trial :" << 
mNbTrial << 
" Best Cost=" << runBestCost<< 
" ";
 
 1742          if(!silent) chrono.print();
 
 1746             for(
int i=0;i<nbWorld;i++)
 
 1748                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.30)
 
 1749                   mutationAmplitude(i)*=2.;
 
 1750                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.10)
 
 1751                   mutationAmplitude(i)/=2.;
 
 1760             for(
int i=0;i<nbWorld;i++)
 
 1762                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.30)
 
 1763                   simAnnealTemp(i)/=1.5;
 
 1764                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.80)
 
 1765                   simAnnealTemp(i)/=1.5;
 
 1766                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)>0.95)
 
 1767                   simAnnealTemp(i)/=1.5;
 
 1769                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.10)
 
 1770                   simAnnealTemp(i)*=1.5;
 
 1771                if((worldNbAcceptedMoves(i)/(REAL)nbTrialsReport)<0.04)
 
 1772                    simAnnealTemp(i)*=1.5;
 
 1780          worldNbAcceptedMoves=0;
 
 1783          #ifdef __WX__CRYST__ 
 1784          if(0!=mpWXCrystObj) mpWXCrystObj->UpdateDisplayNbTrial();
 
 1787       if( (needUpdateDisplay&&(lastUpdateDisplayTime<(chrono.seconds()-1)))||(lastUpdateDisplayTime<(chrono.seconds()-10)))
 
 1791          needUpdateDisplay=
false;
 
 1792          lastUpdateDisplayTime=chrono.seconds();
 
 1794       #ifdef __WX__CRYST__ 
 1795       mMutexStopAfterCycle.Lock();
 
 1797       if((runBestCost<finalcost) || 
mStopAfterCycle ||( (maxTime>0)&&(chrono.seconds()>maxTime)))
 
 1799          #ifdef __WX__CRYST__ 
 1800          mMutexStopAfterCycle.Unlock();
 
 1802          if(!silent) cout << endl <<endl << 
"Refinement Stopped:"<<
mBestCost<<endl;
 
 1805       #ifdef __WX__CRYST__ 
 1806       mMutexStopAfterCycle.Unlock();
 
 1810    TAU_PROFILE_START(timerN);
 
 1813       if(!silent) cout<<
"Beginning final LSQ refinement"<<endl;
 
 1817       try {
mLSQ.
Refine(-50,
true,
true,
false,0.001);}
 
 1837                if(!silent) cout << 
"LSQ : NEW OVERALL Best Cost="<<runBestCost<< endl;
 
 1839             else if(!silent) cout << 
" LSQ : NEW Run Best Cost="<<runBestCost<< endl;
 
 1842       if(!silent) cout<<
"Finished LSQ refinement"<<endl;
 
 1852       if(!silent) cout<<
"Run Best Cost:"<<
mCurrentCost<<endl;
 
 1853       if(!silent) chrono.print();
 
 1859       for(
int i=0;i<nbWorld;i++)
 
 1866    TAU_PROFILE_STOP(timerN);
 
 1871    VFN_DEBUG_ENTRY(
"MonteCarloObj::XMLOutput():"<<this->
GetName(),5)
 
 1872    for(
int i=0;i<indent;i++) os << 
"  " ;
 
 1874    tag.AddAttribute(
"Name",this->
GetName());
 
 1875    tag.AddAttribute(
"NbTrialPerRun",(boost::format(
"%d")%(this->
NbTrialPerRun())).str());
 
 1894       for(
int i=0;i<indent;i++) os << 
"  " ;
 
 1896       tag2.SetIsEndTag(
true);
 
 1908       for(
int i=0;i<indent;i++) os << 
"  " ;
 
 1910       tag2.SetIsEndTag(
true);
 
 1917       tag2.AddAttribute(
"ObjectType",
mRefinedObjList.GetObj(j).GetClassName());
 
 1919       for(
int i=0;i<indent;i++) os << 
"  " ;
 
 1924    tag.SetIsEndTag(
true);
 
 1925    for(
int i=0;i<indent;i++) os << 
"  " ;
 
 1927    VFN_DEBUG_EXIT(
"MonteCarloObj::XMLOutput():"<<this->
GetName(),5)
 
 1932    VFN_DEBUG_ENTRY(
"MonteCarloObj::XMLInput():"<<this->
GetName(),5)
 
 1933    for(
unsigned int i=0;i<tagg.GetNbAttribute();i++)
 
 1935       if(
"Name"==tagg.GetAttributeName(i)) this->
SetName(tagg.GetAttributeValue(i));
 
 1936       if(
"NbTrialPerRun"==tagg.GetAttributeName(i))
 
 1938          stringstream ss(tagg.GetAttributeValue(i));
 
 1947       if((
"GlobalOptimObj"==tag.GetName())&&tag.IsEndTag())
 
 1949          VFN_DEBUG_EXIT(
"MonteCarloObj::Exit():"<<this->
GetName(),5)
 
 1953       if(
"Option"==tag.GetName())
 
 1955          for(
unsigned int i=0;i<tag.GetNbAttribute();i++)
 
 1956             if(
"Name"==tag.GetAttributeName(i))
 
 1958                if(
"Algorithm"==tag.GetAttributeValue(i))
 
 1963                if(
"Temperature Schedule"==tag.GetAttributeValue(i))
 
 1968                if(
"Displacement Amplitude Schedule"==tag.GetAttributeValue(i))
 
 1973                if(
"Save Best Config Regularly"==tag.GetAttributeValue(i))
 
 1978                if(
"Save Tracked Data"==tag.GetAttributeValue(i))
 
 1983                if(
"Automatic Least Squares Refinement"==tag.GetAttributeValue(i))
 
 1991       if(
"TempMaxMin"==tag.GetName())
 
 1997       if(
"MutationMaxMin"==tag.GetName())
 
 2003       if(
"RefinedObject"==tag.GetName())
 
 2006          for(
unsigned int i=0;i<tag.GetNbAttribute();i++)
 
 2008             if(
"ObjectName"==tag.GetAttributeName(i)) name=tag.GetAttributeValue(i);
 
 2009             if(
"ObjectType"==tag.GetAttributeName(i)) type=tag.GetAttributeValue(i);
 
 2026    TAU_PROFILE(
"MonteCarloObj::NewConfiguration()",
"void ()",TAU_DEFAULT);
 
 2027    VFN_DEBUG_ENTRY(
"MonteCarloObj::NewConfiguration()",4)
 
 2032    VFN_DEBUG_EXIT(
"MonteCarloObj::NewConfiguration()",4)
 
 2037    VFN_DEBUG_MESSAGE(
"MonteCarloObj::InitOptions()",5)
 
 2039    static string GlobalOptimTypeName;
 
 2040    static string GlobalOptimTypeChoices[2];
 
 2042    static string AnnealingScheduleChoices[6];
 
 2044    static string AnnealingScheduleTempName;
 
 2045    static string AnnealingScheduleMutationName;
 
 2047    static string runAutoLSQName;
 
 2048    static string runAutoLSQChoices[3];
 
 2050    static string saveTrackedDataName;
 
 2051    static string saveTrackedDataChoices[2];
 
 2053    static bool needInitNames=
true;
 
 2054    if(
true==needInitNames)
 
 2056       GlobalOptimTypeName=
"Algorithm";
 
 2057       GlobalOptimTypeChoices[0]=
"Simulated Annealing";
 
 2058       GlobalOptimTypeChoices[1]=
"Parallel Tempering";
 
 2061       AnnealingScheduleTempName=
"Temperature Schedule";
 
 2062       AnnealingScheduleMutationName=
"Displacement Amplitude Schedule";
 
 2063       AnnealingScheduleChoices[0]=
"Constant";
 
 2064       AnnealingScheduleChoices[1]=
"Boltzmann";
 
 2065       AnnealingScheduleChoices[2]=
"Cauchy";
 
 2066       AnnealingScheduleChoices[3]=
"Exponential";
 
 2067       AnnealingScheduleChoices[4]=
"Smart";
 
 2068       AnnealingScheduleChoices[5]=
"Gamma";
 
 2070       runAutoLSQName=
"Automatic Least Squares Refinement";
 
 2071       runAutoLSQChoices[0]=
"Never";
 
 2072       runAutoLSQChoices[1]=
"At the end of each run";
 
 2073       runAutoLSQChoices[2]=
"Every 150000 trials, and at the end of each run";
 
 2075       saveTrackedDataName=
"Save Tracked Data";
 
 2076       saveTrackedDataChoices[0]=
"No (recommended!)";
 
 2077       saveTrackedDataChoices[1]=
"Yes (for tests ONLY)";
 
 2079       needInitNames=
false;
 
 2085    mAutoLSQ.Init(3,&runAutoLSQName,runAutoLSQChoices);
 
 2086    VFN_DEBUG_MESSAGE(
"MonteCarloObj::InitOptions():End",5)
 
 2095    if(!useFullPowderPatternProfile)
 
 2098          if(pos->first->GetClassName()==
"PowderPattern") pos->second=1;
 
 2109 #ifdef __WX__CRYST__ 
 2113    return mpWXCrystObj;
 
 2115 WXOptimizationObj* MonteCarloObj::WXGet()
 
 2117    return mpWXCrystObj;
 
 2119 void MonteCarloObj::WXDelete()
 
 2121    if(0!=mpWXCrystObj) 
delete mpWXCrystObj;
 
 2124 void MonteCarloObj::WXNotifyDelete()
 
void SetName(const string &)
Set the name for this object. 
void SetLimitsRelative(const string &parName, const REAL min, const REAL max)
Change the relative limits for a parameter from its name. 
OptimizationObj(const string name="")
Constructor. 
virtual void XMLOutput(ostream &os, int indent=0) const =0
Output a description of the object in XML format to a stream. 
RefObjOpt mAutoLSQ
Option to run automatic least-squares refinements. 
void RunSimulatedAnnealing(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
void AddPar(const RefinablePar &newRefPar)
Add a refinable parameter. 
virtual void RandomizeStartingConfig()
Randomize starting configuration. 
REAL GetMin() const 
Minimum value allowed (if limited or periodic) 
virtual void InitLSQ(const bool useFullPowderPatternProfile=true)
Prepare mLSQ for least-squares refinement during the global optimization. 
Tracker for objects (RefinableObj, Crystal, PowderPattern, RefPar,...) 
string mName
Name of the GlobalOptimization object. 
virtual void Optimize(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
Launch optimization (a single run) for N steps. 
long mNbTrialRetry
Number of trials before testing if we are below the given minimum cost. 
void PrepareRefParList(const bool copy_param=false)
Prepare the full parameter list for the refinement. 
REAL mTemperature
Current temperature for annealing. 
We need to record exactly when refinable objects have been modified for the last time (to avoid re-co...
void BuildRecursiveRefObjList()
(Re)build OptimizationObj::mRecursiveRefinedObjList, if an object has been added or modified...
REAL mCurrentCost
Current value of the cost function. 
void AddRefinableObj(RefinableObj &)
Add a refined object. All sub-objects are also added. 
AnnealingSchedule
Annealing schedule type. 
void SetRefinedObj(RefinableObj &obj, const unsigned int LSQFuncIndex=0, const bool init=true, const bool recursive=false)
Choose the object to refine. 
void SaveParamSet(const unsigned long id) const 
Save the current set of refined values over a previously-created set of saved values. 
REAL mTemperatureMax
Beginning temperature for annealing. 
RefObjOpt mGlobalOptimType
Method used for the global optimization. 
Simple chronometer class, with microsecond precision. 
REAL GetBumpMergeCost() const 
Get the Anti-bumping/pro-Merging cost function. 
LSQNumObj & GetLSQObj()
Access to the builtin LSQ optimization object. 
void UpdateDisplay() const 
Update display, if any. 
void RefObjRegisterRecursive(T &obj, ObjRegistry< T > ®)
Register a new object in a registry, and recursively include all included (sub)objects. 
ObjRegistry< OptimizationObj > gOptimizationObjRegistry("List of all Optimization objects")
Global Registry for all OptimizationObj. 
long GetNbPar() const 
Total number of refinable parameter in the object. 
void SetParIsFixed(const string &parName, const bool fix)
Fix one parameter. 
const CrystVector_REAL & GetParamSet(const unsigned long setId) const 
Access one save refpar set. 
RefinablePar & GetParNotFixed(const long i)
Access all parameters in the order they were inputted, skipping fixed parameters. ...
long GetNbParNotFixed() const 
Total number of non-fixed parameters. Is initialized by PrepareForRefinement() 
RefinablePar & GetPar(const long i)
Access all parameters in the order they were inputted. 
void SetParIsUsed(const string &parName, const bool use)
Set a parameter to be used. 
virtual void DisplayReport()
Show report to the user during refinement. Used for GUI update. 
void XMLInput(istream &is, const XMLCrystTag &tag)
XMLInput From stream. 
void ClearValues()
Removes all stored values. 
REAL GetLastOptimElapsedTime() const 
Get the elapsed time (in seconds) during the last optimization. 
void FixAllPar()
Fix all parameters. 
Generic Refinable Object. 
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...
REAL mTotalLogLikelihood
Total Log(Likelihood), to compute the average. 
const RefParType * gpRefParTypeScattDataScale
Type for scattering data scale factors. 
MonteCarloObj(const string name="")
Constructor. 
void ResetParList()
Re-init the list of refinable parameters, removing all parameters. 
bool mStopAfterCycle
If true, then stop at the end of the cycle. Used in multi-threaded environment. 
MainTracker mMainTracker
MainTracker object to track the evolution of cost functions, likelihood, and individual parameters...
ObjRegistry< RefinableObj > gRefinableObjRegistry("Global RefinableObj registry")
Global Registry for all RefinableObj. 
void SetParIsFixed(const std::string &parName, const bool fix)
Fix one parameter. 
REAL mTemperatureMin
Lower temperature. 
Abstract base class for all objects in wxCryst. 
REAL mMutationAmplitudeGamma
Gamma for the 'gamma' Mutation amplitude schedule. 
REAL mMutationAmplitude
Mutation amplitude. 
void GetRefParListClockRecursive(ObjRegistry< RefinableObj > ®, RefinableObjClock &clock)
Get the last time any RefinablePar was added in a recursive list of objects. 
const string & GetName() const 
Get the name for this object. 
void PrepareForRefinement() const 
Find which parameters are used and not fixed, for a refinement /optimization. 
REAL mBestCost
Best value of the cost function so far. 
REAL GetBondValenceCost() const 
Get the Bond-Valence cost function, which compares the expected valence to the one computed from Bond...
LSQNumObj mLSQ
Least squares object. 
virtual ~OptimizationObj()
Destructor. 
const void EraseAllParamSet()
Erase all saved refpar sets. 
long mBestParSavedSetIndex
Index of the 'best' saved parameter set. 
virtual void Print() const 
Print some information about this object. 
void XMLCrystFileSaveGlobal(const string &filename)
Save all Objcryst++ objects. 
Molecule : class for complex scatterer descriptions using cartesian coordinates with bond length/angl...
virtual void NewConfiguration(const RefParType *type=gpRefParTypeObjCryst)
Make a random change in the configuration. 
void TagNewBestConfig()
During a global optimization, tell all objects that the current config is the latest "best" config...
REAL mMutationAmplitudeMin
Mutation amplitude at the end of the optimization. 
void RestoreParamSet(const unsigned long id)
Restore a saved set of values. 
void SetAlgorithmParallTempering(const AnnealingSchedule scheduleTemp, const REAL tMax, const REAL tMin, const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT, const REAL mutMax=16., const REAL mutMin=.125)
Set the refinement method to Parallel Tempering. 
void SetLimitsAbsolute(const string &parName, const REAL min, const REAL max)
Change the absolute limits for a parameter from its name. 
RefObjOpt mAnnealingScheduleTemp
Schedule for the annealing. 
REAL GetMax() const 
Get the maximum value allowed (if limited) 
void XMLOutput(ostream &os, int indent=0) const 
XMLOutput to stream in well-formed XML. 
REAL GetPeriod() const 
Get the period (if periodic) 
unsigned long mContext
The current 'context', in the case the optimization is run in different parallel contexts. 
RefinableObj & GetFullRefinableObj(const bool rebuild=true)
Get the RefinableObj with all the parameters from all refined objects. 
bool IsOptimizing() const 
Are we busy optimizing ? 
virtual void MultiRunOptimize(long &nbCycle, long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
Launch optimization for multiple runs of N steps. 
const RefinableObjClock & GetRefParListClock() const 
What was the last time a RefinablePar was added/removed ? 
Scatterer & GetScatt(const string &scattName)
Provides an access to the scatterers. 
Statistics about each object contributing to the overall Log(likelihood) 
long mNbTrialPerRun
Number of trial per run, to be saved/restored in XML output. 
RefinableObj mRefParList
The refinable par list used during refinement. 
virtual const string GetClassName() const 
Get the name for this class type. 
RefObjOpt mXMLAutoSave
Periodic save of complete environment as an xml file. 
void RunParallelTempering(long &nbSteps, const bool silent=false, const REAL finalcost=0, const REAL maxTime=-1)
ObjRegistry< Scatterer > & GetScattererRegistry()
Get the registry of scatterers. 
A class to hold all trackers. 
void RestoreBestConfiguration()
Restore the Best configuration. 
virtual ~MonteCarloObj()
Destructor. 
ObjRegistry< RefinableObj > mRefinedObjList
The refined objects. 
REAL mLastOptimTime
The time elapsed after the last optimization, in seconds. 
void UnFixAllPar()
UnFix All parameters. 
MainTracker & GetMainTracker()
Get the MainTracker. 
void MutateTo(const REAL newValue)
Change the current value to the given one. 
void ClearParamSet(const unsigned long id) const 
Erase the param set with the given id, releasing memory. 
map< const RefinableObj *, DynamicObjWeight > mvObjWeight
Weights for each objects in each context (mutable for dynamic update during optimization) ...
Class for Graphical interface to Monte-Carlo objects (Simulated Annealing, Parallel Tempering) ...
REAL mMutationAmplitudeMax
Mutation amplitude at the beginning of the optimization. 
Base object for Optimization methods. 
void ClearTrackers()
Removes all Trackers. 
ObjRegistry< RefinableObj > mRecursiveRefinedObjList
The refined objects, recursively including all sub-objects. 
Exception class for ObjCryst++ library. 
REAL mMinCostRetry
Cost to reach unless an automatic randomization and retry is done. 
void StopAfterCycle()
Stop after the current cycle. USed for interactive refinement. 
The namespace which includes all objects (crystallographic and algorithmic) in ObjCryst++. 
virtual REAL GetLogLikelihood() const 
Get -log(likelihood) of the current configuration for the object. 
RefObjOpt mAnnealingScheduleMutation
Schedule for the annealing. 
virtual void EndOptimization()
End optimization for all objects. 
virtual const string GetClassName() const 
Get the name for this class type. 
virtual void XMLInput(istream &is, const XMLCrystTag &tag)
Input in XML format from a stream, restoring the set of refined objects and the associated cost funct...
map< unsigned long, map< const RefinableObj *, LogLikelihoodStats > > mvContextObjStats
Statistics for each context (mutable for dynamic update during optimization) 
virtual const string & GetName() const 
Name of the object. 
bool mIsOptimizing
True if a refinement is being done. For multi-threaded environment. 
void SaveAll(std::ostream &out) const 
Will save to a single file if all recorded trial numbers are the same Otherwise ? ...
void GetSubRefObjListClockRecursive(ObjRegistry< RefinableObj > ®, RefinableObjClock &clock)
Get the last time any object was added in the recursive list of objects. 
virtual void InitOptions()
Initialization of options. 
Crystal class: Unit cell, spacegroup, scatterers. 
virtual void XMLOutput(ostream &os, int indent=0) const 
Output a description of the object in XML format to a stream. 
(Quick & dirty) Least-Squares Refinement Object with Numerical derivatives 
virtual void BeginOptimization(const bool allowApproximations=false, const bool enableRestraints=false)
Begin optimization for all objects. 
REAL mLastLogLikelihood
Previous log(likelihood) 
virtual void UpdateDisplay()
Update Display (if any display is available), when a new 'relevant' configuration is reached...
class to input or output a well-formatted xml beginning or ending tag. 
REAL mTemperatureGamma
Gamma for the 'gamma' temperature schedule. 
RefObjOpt mSaveTrackedData
Option to save the evolution of tracked data (cost functions, likelihhod, individual parameters...
void SetDeleteRefParInDestructor(const bool b)
Set this object not to delete its list of parameters when destroyed. 
class of refinable parameter types. 
void SetAlgorithmSimulAnnealing(const AnnealingSchedule scheduleTemp, const REAL tMax, const REAL tMin, const AnnealingSchedule scheduleMutation=ANNEALING_CONSTANT, const REAL mutMax=16., const REAL mutMin=.125, const long nbTrialRetry=0, const REAL minCostRetry=0.)
Set the refinement method to simulated Annealing. 
long mNbTrial
Number of trials so far. 
virtual long & NbTrialPerRun()
Number of trial per run. 
const RefParType * gpRefParTypeScattData
Generic type for scattering data. 
unsigned long CreateParamSet(const string name="") const 
Save the current set of refined values in a new set. 
std::vector< pair< long, REAL > > mvSavedParamSet
List of saved parameter sets. 
const RefParType * gpRefParTypeObjCryst
Top RefParType for the ObjCryst++ library. 
virtual REAL GetLogLikelihood() const 
The optimized (minimized, actually) function. 
const REAL & GetBestCost() const 
Access to current best cost. 
void Refine(int nbCycle=1, bool useLevenbergMarquardt=false, const bool silent=false, const bool callBeginEndOptimization=true, const float minChi2var=0.01)
Do the refinement. 
virtual void InitOptions()
Initialization of options. 
REAL mTotalLogLikelihoodDeltaSq
total of (Delta(Log(Likelihood)))^2 between successive trials