BCEngineMCMC.cxx
90 BCEngineMCMC::BCEngineMCMC(const std::string& filename, const std::string& name, bool loadObservables)
152 fMultivariateProposalFunctionCholeskyDecomposition(other.fMultivariateProposalFunctionCholeskyDecomposition),
227 fMultivariateProposalFunctionCholeskyDecomposition = other.fMultivariateProposalFunctionCholeskyDecomposition;
277 fH2Marginalized = std::vector<std::vector<TH2*> > (other.fH2Marginalized.size(), std::vector<TH2*>(other.fH2Marginalized.front().size(), NULL));
336 void BCEngineMCMC::SetPriorGauss(unsigned index, double mean, double sigma_below, double sigma_above)
433 BCLog::OutError("BCEngineMCMC::WriteMarkovChainRun: First turn on output using WriteMarkovChain(filename, option, main_run, pre_run).");
441 BCLog::OutError("BCEngineMCMC::WriteMarkovChainPreRun: First turn on output using WriteMarkovChain(filename, option, main_run, pre_run).");
446 void BCEngineMCMC::WriteMarkovChain(const std::string& filename, const std::string& option, bool flag_run, bool flag_prerun)
453 BCLog::OutError("BCEngineMCMC::WriteMarkovChain: You must specify the filename when turning on Markov chain output.");
464 void BCEngineMCMC::WriteMarginalizedDistributions(const std::string& filename, const std::string& option, bool closeExistingFile)
480 BCLog::OutError("BCEngineMCMC::WriteMarginalizedDistributions: File already open. option \"RECREATE\" will now overwrite it!");
487 BCLog::OutError("BCEngineMCMC::WriteMarginalizedDistributions: File already open but not in readable mode.");
504 BCLog::OutError("BCEngineMCMC::WriteMarginalizedDistributions: File must be opened in writeable mode.");
540 BCLog::OutWarning(Form("BCEngineMCMC::GetMarginalizedHistogram: marginal distribution not stored for %s %s", GetVariable(index).GetPrefix().data(), GetVariable(index).GetName().data()));
549 BCLog::OutError(Form("BCEngineMCMC::GetMarginalizedHistogram. Called with identical indices %u.", i));
566 BCLog::OutWarning(Form("BCEngineMCMC::GetMarginalizedHistogram : marginal distribution not stored for %s %s vs %s %s",
626 BCLOG_WARNING(Form("global %d min %d max %d", fMCMCNIterationsConvergenceGlobal, int(fMCMCNIterationsPreRunMin), int(fMCMCNIterationsPreRunMax)));
659 BCLog::OutError("BCEngineMCMC::GetLocalModes : unfixed parameter is missing marginalized information. returning empty vector.");
663 BCLog::OutWarning("BCEngineMCMC::GetLocalModes : user-defined observable is missing marginalized information. returning only local modes of parameters.");
676 BCLOG_ERROR(Form("#initial positions does not match #parameters: %u vs %u", unsigned(x0.size()), GetNParameters()));
735 BCLog::OutError("BCEngineMCMC::InitializeMarkovChainTree: File must be opened in a writeable mode.");
750 fMCMCTree = new TTree(TString::Format("%s_mcmc", GetSafeName().data()), TString::Format("%s_mcmc", GetSafeName().data()));
757 fMCMCTree->Branch(GetParameter(j).GetSafeName().data(), &fMCMCTree_State.parameters[j], (GetParameter(j).GetSafeName() + "/D").data());
762 fMCMCTree->Branch(GetObservable(j).GetSafeName().data(), &fMCMCTree_State.observables[j], (GetObservable(j).GetSafeName() + "/D").data());
772 fParameterTree = new TTree(TString::Format("%s_parameters", GetSafeName().data()), TString::Format("%s_parameters", GetSafeName().data()));
839 b_scale = fParameterTree->Branch("scale", &(scale.front()), TString::Format("scale[%d]/D", GetNChains()));
848 TBranch* b_eff = fParameterTree->Branch(TString::Format("efficiency_%d", i), &(eff.front()), TString::Format("efficiency_%d[%d]/D", i, GetNChains()));
855 scale[j] = (n < GetNParameters()) ? (fMCMCProposeMultivariate ? fMCMCProposalFunctionScaleFactor[j][0] : fMCMCProposalFunctionScaleFactor[j][n]) : -1;
922 throw std::runtime_error("BCEngineMCMC::LoadParametersFromTree: tree missing parameter branch");
928 throw std::runtime_error("BCEngineMCMC::LoadParametersFromTree: tree missing lower_limit branch");
930 throw std::runtime_error("BCEngineMCMC::LoadParametersFromTree: tree missing upper_limit branch");
1010 throw std::runtime_error("BCEngineMCMC::LoadMCMCParameters: tree missing efficiency_0 branch");
1030 std::vector<std::vector<double> > scales(GetNChains(), std::vector<double>(GetNParameters(), -1));
1031 std::vector<std::vector<double> > efficiencies(GetNChains(), std::vector<double>(GetNParameters(), -1));
1090 BCLog::OutError("BCEngineMCMC::ParameterTreeMatchesModel : Parameter tree contains too few entries.");
1095 BCLog::OutError(Form("BCEngineMCMC::ParameterTreeMatchesModel : Parameter[%d]'s names do not match.", i));
1099 BCLog::OutDetail(Form("BCEngineMCMC::ParameterTreeMatchesModel : Lower limit of parameter \"%s\" does not match.", p_name));
1101 BCLog::OutDetail(Form("BCEngineMCMC::ParameterTreeMatchesModel : Upper limit of parameter \"%s\" does not match.", p_name));
1104 BCLog::OutDetail(Form("BCEngineMCMC::ParameterTreeMatchesModel : Fixed status of parameter \"%s\" does not match. Fixing it to %f.", p_name, p_fixedvalue));
1107 BCLog::OutDetail(Form("BCEngineMCMC::ParameterTreeMatchesModel : Fixed status of parameter \"%s\" does not match. Unfixing it.", p_name));
1111 if (has_fixed && GetParameter(i).Fixed() && has_fixed_value && GetParameter(i).GetFixedValue() != p_fixedvalue) {
1112 BCLog::OutDetail(Form("BCEngineMCMC::ParameterTreeMatchesModel : Fixed value of parameter \"%s\" does not match. Updating it.", p_name));
1121 BCLog::OutError("BCEngineMCMC::ParameterTreeMatchesModel : Parameters tree contains too few entries.");
1126 BCLog::OutError(Form("BCEngineMCMC::ParameterTreeMatchesModel : Observable[%d]'s names do not match.", i));
1130 BCLog::OutWarning(Form("BCEngineMCMC::ParameterTreeMatchesModel : Lower limit of observable \"%s\" does not match.", p_name));
1132 BCLog::OutWarning(Form("BCEngineMCMC::ParameterTreeMatchesModel : Upper limit of observable \"%s\" does not match.", p_name));
1138 void BCEngineMCMC::LoadMCMC(const std::string& filename, std::string mcmcTreeName, std::string parameterTreeName, bool loadObservables)
1146 throw std::runtime_error(Form("BCEngineMCMC::LoadMCMC: Could not open file %s.", filename.data()));
1174 throw std::runtime_error(Form("BCEngineMCMC::LoadMCMC : %s contains no matching MCMC and Parameter trees.", filename.data()));
1180 throw std::runtime_error(Form("BCEngineMCMC::LoadMCMC : %s contains more than one model, please select one by providing a model name: %s", filename.data(), model_names_string.data()));
1189 // check mcmcTreeName and parameterTreeName for default BAT name scheme [modelname]_mcmc/parameters:
1190 if (mcmcTreeName.find_last_of("_") != std::string::npos && mcmcTreeName.substr(mcmcTreeName.find_last_of("_")) == "_mcmc"
1191 && parameterTreeName.find_last_of("_") != std::string::npos && parameterTreeName.substr(parameterTreeName.find_last_of("_")) == "_parameters") {
1205 throw std::runtime_error(Form("BCEngineMCMC::LoadMCMC : %s does not contain a tree named %s", filename.data(), mcmcTreeName.data()));
1211 throw std::runtime_error(Form("BCEngineMCMC::LoadMCMC : %s does not contain a tree named %s", filename.data(), parameterTreeName.data()));
1288 fMCMCTree->SetBranchAddress(GetParameter(i).GetSafeName().data(), &fMCMCTree_State.parameters[i]);
1294 fMCMCTree->SetBranchAddress(GetObservable(i).GetSafeName().data(), &fMCMCTree_State.observables[i]);
1333 XMin[GetNParameters() + i] = std::min(XMin[GetNParameters() + i], fMCMCTree_State.observables[i]);
1334 XMax[GetNParameters() + i] = std::max(XMax[GetNParameters() + i], fMCMCTree_State.observables[i]);
1362 fMCMCStatistics.assign(fMCMCNChains, BCEngineMCMC::Statistics(GetNParameters(), GetNObservables()));
1407 fMultivariateProposalFunctionCovariance.assign(fMCMCNChains, TMatrixDSym(GetNFreeParameters()));
1419 void BCEngineMCMC::PrepareToContinueMarginalization(const std::string& filename, const std::string& mcmcTreeName, const std::string& parameterTreeName, bool loadObservables, bool autorange)
1448 fMultivariateProposalFunctionCovariance[c][J][I] = fMultivariateProposalFunctionCovariance[c][I][J];
1474 throw std::runtime_error("BCEngineMCMC::CalculateCholeskyDecompositions: size of fMultivariateProposalFunctionCovariance does not match number of chains.");
1477 fMultivariateProposalFunctionCholeskyDecomposition.assign(fMCMCNChains, TMatrixD(GetNFreeParameters(), GetNFreeParameters()));
1485 CholeskyDecomposer.SetMatrix(fMultivariateProposalFunctionCovariance[c]*fMCMCProposalFunctionScaleFactor[c][0]);
1491 BCLog::OutDetail(Form("BCEngineMCMC::CalculateCholeskyDecompositions : chain %u Cholesky decomposition failed! Adding epsilon*I and trying again.", c));
1492 TMatrixDSym U(fMultivariateProposalFunctionCovariance[c]*fMCMCProposalFunctionScaleFactor[c][0]);
1501 BCLog::OutDetail(Form("BCEngineMCMC::CalculateCholeskyDecompositions : chain %u Cholesky decomposition failed! Setting off-diagonal elements of covariance to zero", c));
1502 TMatrixDSym U(fMultivariateProposalFunctionCovariance[c]*fMCMCProposalFunctionScaleFactor[c][0]);
1511 throw std::runtime_error(Form("BCEngineMCMC::CalculateCholeskyDecompositions : chain %u Cholesky decomposition failed! No remedies!", c));
1521 // multiply by 1 (dof <=0, Gauss) or a random variate that scales the Gaussian to a Student's t with dof degrees of freedom
1524 return scale * fMCMCThreadLocalStorage[ichain].rng->Gaus(0, fMCMCProposalFunctionScaleFactor[ichain][iparameter]);
1541 // multiply by 1 (dof <=0, Gauss) or a random variate that scales the Gaussian to a Student's t with dof degrees of freedom
1557 bool BCEngineMCMC::GetProposalPointMetropolis(unsigned ichain, unsigned ipar, std::vector<double>& x)
1589 if (std::isfinite(p1) && (p1 >= p0 || log(fMCMCThreadLocalStorage[chain].rng->Rndm()) < (p1 - p0))) {
1593 fMCMCStatistics[chain].efficiency[parameter] += (1. - fMCMCStatistics[chain].efficiency[parameter]) / (fMCMCStatistics[chain].n_samples_efficiency + 1.);
1600 fMCMCStatistics[chain].efficiency[parameter] *= 1.*fMCMCStatistics[chain].n_samples_efficiency / (fMCMCStatistics[chain].n_samples_efficiency + 1.);
1605 BCLog::OutDebug(Form("log(probability) evaluated to nan or inf in chain %i while at ", chain));
1608 BCLog::OutDebug(Form("log(probability) evaluated to nan or inf in chain %i while varying parameter %s to %.3e", chain, GetParameter(parameter).GetName().data(), fMCMCThreadLocalStorage[chain].parameters[parameter]));
1774 BCLog::OutSummary(Form(" --> Perform MCMC pre-run with %i chains, each with maximum %i iterations", fMCMCNChains, fMCMCNIterationsPreRunMax));
1836 // OR the minimum number of tuning steps have been made to the multivariate proposal function, if using it.
1844 for (unsigned i = 0; i < nIterationsPreRunCheck && fMCMCCurrentIteration < (int)fMCMCNIterationsPreRunMax; ++i) {
1869 if (fMCMCStatistics[c].efficiency[0] >= fMCMCEfficiencyMin && fMCMCStatistics[c].efficiency[0] <= fMCMCEfficiencyMax)
1873 BCLog::OutDetail(Form(" * Efficiency status: Efficiencies not within predefined range after %i iterations. Efficiency of ", fMCMCCurrentIteration));
1878 if (fMCMCStatistics[c].efficiency[0] < fMCMCEfficiencyMin) { // efficiency too low... decrease scale factor
1881 if (fMCMCProposalFunctionScaleFactor[c][0] > fMCMCScaleFactorLowerLimit) { // still room to tune
1883 BCLog::OutDetail(Form(" chain %d is below %.0f %% (zero). Scale decreased to %.4g", c, 100 * fMCMCEfficiencyMin, fMCMCProposalFunctionScaleFactor[c][0]));
1885 BCLog::OutDetail(Form(" chain %d is below %.0f %% (%.0g %%). Scale decreased to %.4g", c, 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[0], fMCMCProposalFunctionScaleFactor[c][0]));
1887 BCLog::OutDetail(Form(" chain %d is below %.0f %% (%.0f %%). Scale decreased to %.4g", c, 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[0], fMCMCProposalFunctionScaleFactor[c][0]));
1893 BCLog::OutDetail(Form(" chain %d is below %.0f %% (zero). Scale now at lower limit (%.4g)", c, 100 * fMCMCEfficiencyMin, fMCMCScaleFactorLowerLimit));
1895 BCLog::OutDetail(Form(" chain %d is below %.0f %% (%.0g %%). Scale now at lower limit (%.4g)", c, 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[0], fMCMCScaleFactorLowerLimit));
1897 BCLog::OutDetail(Form(" chain %d is below %.0f %% f(%.0f %%). Scale now at lower limit (%.4g)", c, 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[0], fMCMCScaleFactorLowerLimit));
1904 if (fMCMCProposalFunctionScaleFactor[c][0] < fMCMCScaleFactorUpperLimit) { // still room to tune
1905 BCLog::OutDetail(Form(" chain %d is above %.0f %% (%.0f %%). Scale increased to %.4g", c, 100 * fMCMCEfficiencyMax, 100 * fMCMCStatistics[c].efficiency[0], fMCMCProposalFunctionScaleFactor[c][0]));
1909 BCLog::OutDetail(Form(" chain %d is above %.0f %% (%.0f %%). Scale now at upper limit (%.4g)", c, 100 * fMCMCEfficiencyMax, 100 * fMCMCStatistics[c].efficiency[0], fMCMCScaleFactorUpperLimit));
1923 if (fMCMCStatistics[c].efficiency[p] >= fMCMCEfficiencyMin && fMCMCStatistics[c].efficiency[p] <= fMCMCEfficiencyMax)
1927 BCLog::OutDetail(Form(" * Efficiency status: Efficiencies not within pre-defined range after %i iterations. Efficiency of ", fMCMCCurrentIteration));
1932 if (fMCMCStatistics[c].efficiency[p] < fMCMCEfficiencyMin) { // efficiency too low... decrease scale factor
1933 fMCMCProposalFunctionScaleFactor[c][p] /= (fMCMCStatistics[c].efficiency[p] < fMCMCEfficiencyMin / 2) ? 4 : 2;
1935 if (fMCMCProposalFunctionScaleFactor[c][p] > fMCMCScaleFactorLowerLimit) { // still room to tune
1937 BCLog::OutDetail(Form(" %-*s is below %.0f %% (zero) in chain %i. Scale decreased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMin, c, fMCMCProposalFunctionScaleFactor[c][p]));
1939 BCLog::OutDetail(Form(" %-*s is below %.0f %% (%.0g %%) in chain %i. Scale decreased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[p], c, fMCMCProposalFunctionScaleFactor[c][p]));
1941 BCLog::OutDetail(Form(" %-*s is below %.0f %% (%.0f %%) in chain %i. Scale decreased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[p], c, fMCMCProposalFunctionScaleFactor[c][p]));
1945 BCLog::OutDetail(Form(" %-*s is below %.0f %% (zero) in chain %i. Scale decreased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMin, c, fMCMCProposalFunctionScaleFactor[c][p]));
1947 BCLog::OutDetail(Form(" %-*s is below %.0f %% (%.0g %%) in chain %i. Scale decreased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[p], c, fMCMCProposalFunctionScaleFactor[c][p]));
1949 BCLog::OutDetail(Form(" %-*s is below %.0f %% (%.0f %%) in chain %i. Scale decreased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMin, 100 * fMCMCStatistics[c].efficiency[p], c, fMCMCProposalFunctionScaleFactor[c][p]));
1956 if (fMCMCProposalFunctionScaleFactor[c][p] < fMCMCScaleFactorUpperLimit) { // still room to tune
1957 BCLog::OutDetail(Form(" %-*s is above %.0f %% (%.0f %%) in chain %i. Scale increased to %.4g", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMax, 100 * fMCMCStatistics[c].efficiency[p], c, fMCMCProposalFunctionScaleFactor[c][p]));
1961 BCLog::OutDetail(Form(" %-*s is above %.0f %% (%.0f %%) in chain %i. Scale now at upper limit (%.4g)", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), 100 * fMCMCEfficiencyMax, 100 * fMCMCStatistics[c].efficiency[p], c, fMCMCScaleFactorUpperLimit));
1987 fMCMCRValueParameters[p] = RValue(means, variances, fMCMCStatistics[0].n_samples, fCorrectRValueForSamplingVariability);
1994 BCLog::OutDetail(Form(" * Convergence status: Set of %i Markov chains did not converge after %i iterations.", fMCMCNChains, fMCMCCurrentIteration));
2002 BCLog::OutDetail(Form(" %-*s : %.03f", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), fMCMCRValueParameters[p]));
2004 BCLog::OutDetail(Form(" %-*s : %.03f <-- Greater than threshold", fParameters.MaxNameLength(), GetParameter(p).GetName().data(), fMCMCRValueParameters[p]));
2006 BCLog::OutDetail(Form(" %-*s : error in calculation", fParameters.MaxNameLength(), GetParameter(p).GetName().data()));
2020 BCLog::OutDetail(Form(" * Running until at least %d iterations performed in prerun. Current iteration is %d", fMCMCNIterationsPreRunMin, fMCMCCurrentIteration));
2037 fMCMCStatistics[c].Reset(false, true); // clear means and (co)variances, preserve mode information, clear efficiency information
2049 BCLog::OutSummary(Form(" --> Set of %i Markov chains converged within %i iterations, and all scales are adjusted.", fMCMCNChains, fMCMCNIterationsConvergenceGlobal));
2051 BCLog::OutSummary(Form(" --> Set of %i Markov chains converged within %i iterations, but could not adjust all scales (scale limits reached).", fMCMCNChains, fMCMCNIterationsConvergenceGlobal));
2053 BCLog::OutSummary(Form(" --> Set of %i Markov chains converged within %i iterations, but could not adjust all scales (maximum number of iterations reached).", fMCMCNChains, fMCMCNIterationsConvergenceGlobal));
2055 BCLog::OutSummary(Form(" --> %i updates to multivariate proposal function's covariances were made.", fMultivariateCovarianceUpdates));
2057 BCLog::OutSummary(Form(" --> Set of %i Markov chains did not converge within %i iterations, but all scales are adjusted.", fMCMCNChains, fMCMCNIterationsPreRunMax));
2059 BCLog::OutSummary(Form(" --> Set of %i Markov chains did not converge within %i iterations, and could not adjust all scales (scale limits reached).", fMCMCNChains, fMCMCNIterationsPreRunMax));
2061 BCLog::OutSummary(Form(" --> Set of %i Markov chains did not converge within %i iterations, and could not adjust all scales.", fMCMCNChains, fMCMCNIterationsPreRunMax));
2070 BCLog::OutDetail(Form(" --> Scale factors and efficiencies (measured in last %u iterations):", fMCMCStatistics.front().n_samples_efficiency));
2073 BCLog::OutDetail(Form(" %3d : % 6.4g %4.1f %%", c, fMCMCProposalFunctionScaleFactor[c][0], 100.*fMCMCStatistics[c].efficiency[0]));
2075 BCLog::OutDetail(Form(" --> Average scale factors and efficiencies (measured in last %u iterations):", fMCMCStatistics.front().n_samples_efficiency));
2076 BCLog::OutDetail(Form(" - %-*s : Scale factor Efficiency", fParameters.MaxNameLength(), "Parameter"));
2084 BCLog::OutDetail(Form(" %-*s : % 6.4g %% %4.1f %%", fParameters.MaxNameLength(), GetParameter(i).GetName().data(), 100.*scalefactors, 100.*fMCMCStatistics_AllChains.efficiency[i]));
2106 double BCEngineMCMC::RValue(const std::vector<double>& means, const std::vector<double>& variances, unsigned n, bool correctForSamplingVariability)
2131 variance_of_variances += (variances[c] - mean_of_variances) * (variances[c] - mean_of_variances);
2137 double full_variance = m * (n - 1.) / (m * n - 1) * mean_of_variances + n * (m - 1.) / (m * n - 1) * variance_of_means;
2148 double rvalue = sqrt(full_variance / mean_of_variances); // variance(all samples) / mean(chain variances)
2163 covariance_of_variance_with_mean += (variances[c] - mean_of_variances) * (means[c] - mean_of_means);
2164 covariance_of_variance_with_meansquare += (variances[c] - mean_of_variances) * (means[c] * means[c] - meansquare_of_means);
2174 double varV = N * N / m * variance_of_variances + 2 * M / (m - 1) * variance_of_means * variance_of_means
2175 + 2 * M * N / m * (covariance_of_variance_with_meansquare - 2 * mean_of_means * covariance_of_variance_with_mean);
2187 BCLog::OutWarning("BCEngineMCMC::MCMCMetropolis. Number of free parameters <= 0. Do not run Metropolis.");
2211 throw std::runtime_error("BCEngineMCMC::Metropolis: size of fMCMCStatistics does not match number of chains.");
2213 throw std::runtime_error("BCEngineMCMC::Metropolis: size of fMCMCStates does not match number of chains.");
2215 throw std::runtime_error("BCEngineMCMC::Metropolis: size of fMCMCThreadLocalStorage does not match number of chains.");
2218 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: size of fMCMCThreadLocalStorage[%u].parameters does not match number of parameters.", c));
2220 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: fMCMCThreadLocalStorage[%u] lacks random number generator.", c));
2223 if (fMultivariateProposalFunctionCholeskyDecomposition.empty() && fMultivariateProposalFunctionCovariance.empty())
2224 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: pre-run was run with factorized proposal function."));
2231 if (fMultivariateProposalFunctionCholeskyDecomposition[c].GetNrows() != static_cast<int>(GetNFreeParameters()) or
2232 fMultivariateProposalFunctionCholeskyDecomposition[c].GetNcols() != static_cast<int>(GetNFreeParameters()))
2239 throw std::runtime_error("BCEngineMCMC::Metropolis: size of fMultivariateProposalFunctionCholeskyDecomposition does not match number of chains.");
2241 if (fMultivariateProposalFunctionCholeskyDecomposition[c].GetNrows() != static_cast<int>(GetNFreeParameters()) or
2242 fMultivariateProposalFunctionCholeskyDecomposition[c].GetNcols() != static_cast<int>(GetNFreeParameters()))
2243 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: size of fMultivariateProposalFunctionCholeskyDecomposition[%u] matrix does not match number of free parameters.", c));
2246 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: size of fThreadLocalStorage[%u].yLocal matrix does not match number of free parameters.", c));
2250 throw std::runtime_error("BCEngineMCMC::Metropolis: pre-run was run with multivariate proposal function.");
2252 throw std::runtime_error("BCEngineMCMC::Metropolis: size of fProposalFunctionScaleFactor does not match number of chains.");
2255 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: size of fMCMCProposalFunctionScaleFactor[%u] does not match number of parameters.", c));
2258 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: fMCMCProposalFunctionScaleFactor[%u][%u] <= 0.", c, p));
2260 throw std::runtime_error(Form("BCEngineMCMC::Metropolis: parameter %u has been unfixed without rerunning the pre-run.", p));
2271 BCLog::OutSummary(Form(" --> Perform MCMC run with %i chains, each with %i iterations.", fMCMCNChains, fMCMCNIterationsRun));
2283 BCLog::OutDetail(Form(" --> iteration number %6i (%3.0f %%)", fMCMCCurrentIteration, (double)(fMCMCCurrentIteration) / (double)fMCMCNIterationsRun * 100.));
2316 BCLog::OutDetail(Form(" --> Efficiencies (measured in %u iterations):", fMCMCStatistics.front().n_samples_efficiency));
2321 BCLog::OutDetail(Form(" --> Average efficiencies (measured in %u iterations):", fMCMCStatistics_AllChains.n_samples_efficiency / fMCMCNChains));
2326 BCLog::OutDetail(Form(" %-*s : %4.1f %%", fParameters.MaxNameLength(), GetParameter(i).GetName().data(), 100.*fMCMCStatistics_AllChains.efficiency[i]));
2334 BCLog::OutDebug(Form(" --> Posterior value: %g", fMCMCStatistics_AllChains.probability_at_mode));
2402 fMCMCStatistics.assign(fMCMCNChains, BCEngineMCMC::Statistics(GetNParameters(), GetNObservables()));
2433 fMCMCProposalFunctionScaleFactor.push_back(std::vector<double>(1, fMCMCInitialScaleFactors[i]));
2437 fMCMCProposalFunctionScaleFactor.assign(fMCMCNChains, std::vector<double>(1, 2.38 * 2.38 / GetNFreeParameters()));
2469 // before we set the initial position and evaluate the likelihood, it's time to let the user initialize the model with #chains etc. fixed
2484 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : Range center as initial point yields invalid probability.");
2494 for (unsigned n = 0; n < fInitialPositionAttemptLimit && !std::isfinite(fMCMCThreadLocalStorage[c].log_probability); ++n) {
2495 fMCMCThreadLocalStorage[c].parameters = GetParameters().GetUniformRandomValues(fMCMCThreadLocalStorage[c].rng);
2500 throw std::runtime_error(Form("BCEngineMCMC::MCMCInitialize : Could not generate uniformly distributed initial point with valid probability in %u tries.", fInitialPositionAttemptLimit));
2511 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : Too few initial positions provided.");
2522 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : User-defined initial point is out of bounds.");
2529 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : User-defined initial point yields invalid probability.");
2541 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : Not all unfixed parameters have priors set.");
2544 for (unsigned n = 0; n < fInitialPositionAttemptLimit && !std::isfinite(fMCMCThreadLocalStorage[c].log_probability); ++n) {
2545 fMCMCThreadLocalStorage[c].parameters = GetParameters().GetRandomValuesAccordingToPriors(fMCMCThreadLocalStorage[c].rng);
2548 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : Could not generate random point within limits.");
2554 throw std::runtime_error(Form("BCEngineMCMC::MCMCInitialize : Could not generate initial point from prior with valid probability in %u tries.", fInitialPositionAttemptLimit));
2562 throw std::runtime_error("BCEngineMCMC::MCMCInitialize : No MCMC position initialization scheme specified.");
2612 original_bounds.push_back(std::make_pair(GetVariable(i).GetLowerLimit(), GetVariable(i).GetUpperLimit()));
2616 if (i < fMCMCStatistics_AllChains.minimum.size() && std::isfinite(fMCMCStatistics_AllChains.minimum[i]))
2618 if (i < fMCMCStatistics_AllChains.maximum.size() && std::isfinite(fMCMCStatistics_AllChains.maximum[i]))
2624 GetVariable(i).SetLowerLimit(std::max<double>(GetVariable(i).GetLowerLimit() - range_width_rescale, original_bounds.back().first));
2625 GetVariable(i).SetUpperLimit(std::min<double>(GetVariable(i).GetUpperLimit() + range_width_rescale, original_bounds.back().second));
2637 fH1Marginalized[i] = GetVariable(i).CreateH1(Form("h1_%s_parameter_%s", GetSafeName().data() , GetParameter(i).GetSafeName().data()));
2641 fH1Marginalized[i] = GetVariable(i).CreateH1(Form("h1_%s_observable_%s", GetSafeName().data() , GetVariable(i).GetSafeName().data()));
2653 for (std::vector<std::pair<int, int> >::const_iterator h = fRequestedH2.begin(); h != fRequestedH2.end(); ++h) {
2669 fH2Marginalized[i][j] = GetParameter(i).CreateH2(Form("h2_%s_par_%s_vs_par_%s", GetSafeName().data(), GetParameter(j).GetSafeName().data(), GetParameter(i).GetSafeName().data()), GetParameter(j));
2673 fH2Marginalized[i][j + GetNParameters()] = GetParameter(i).CreateH2(Form("h2_%s_obs_%s_vs_par_%s", GetSafeName().data(), GetObservable(j).GetSafeName().data(), GetParameter(i).GetSafeName().data()), GetObservable(j));
2683 fH2Marginalized[i + GetNParameters()][j] = GetObservable(i).CreateH2(Form("h2_%s_par_%s_vs_obs_%s", GetSafeName().data(), GetParameter(j).GetSafeName().data(), GetObservable(i).GetSafeName().data()), GetParameter(j));
2687 fH2Marginalized[i + GetNParameters()][j + GetNParameters()] = GetObservable(i).CreateH2(Form("h2_%s_obs_%s_vs_obs_%s", GetSafeName().data(), GetObservable(j).GetSafeName().data(), GetObservable(i).GetSafeName().data()), GetObservable(j));
2703 fH2Marginalized[i][j] = GetParameter(i).CreateH2(Form("h2_%s_par_%s_vs_par_%s", GetSafeName().data(), GetParameter(j).GetSafeName().data(), GetParameter(i).GetSafeName().data()), GetParameter(j));
2709 fH2Marginalized[i][j + GetNParameters()] = GetParameter(i).CreateH2(Form("h2_%s_obs_%s_vs_par_%s", GetSafeName().data(), GetObservable(j).GetSafeName().data(), GetParameter(i).GetSafeName().data()), GetObservable(j));
2721 if (GetObservable(j).FillH2() && !fH2Marginalized[i + GetNParameters()][j + GetNParameters()]) {
2722 fH2Marginalized[i + GetNParameters()][j + GetNParameters()] = GetObservable(i).CreateH2(Form("h2_%s_obs_%s_vs_obs_%s", GetSafeName().data(), GetObservable(j).GetSafeName().data(), GetObservable(i).GetSafeName().data()), GetObservable(j));
2776 if (GetBestFitParameters().size() != GetNParameters() && GetBestFitParameters().size() != GetNVariables()) {
2798 std::string par_summary = Form(" %*d) %10s \"%s\"%*s : %.*g", n, i, GetVariable(i).GetPrefix().data(),
2799 GetVariable(i).GetName().data(), (int)(GetMaximumParameterNameLength() - GetVariable(i).GetName().length()), "",
2825 std::string par_summary = Form(" (%u) ", i) + GetVariable(i).GetPrefix() + " \"" + GetVariable(i).GetName() + "\" :";
2828 par_summary += Form(" fixed at %.*g", GetVariable(i).GetPrecision(), GetParameter(i).GetFixedValue());
2837 GetMarginalized(i).PrintSummary(" ", GetVariable(i).GetPrecision(), std::vector<double>(1, 0.68));
2850 BCLog::OutSummary(Form(" Number of iterations until convergence: %d", fMCMCNIterationsConvergenceGlobal));
2858 BCLog::OutDetail(Form(" Scale factors and efficiencies (measured in last %u iterations):", fMCMCStatistics.front().n_samples_efficiency));
2861 BCLog::OutDetail(Form(" %3d : %-6.4g %4.1f %%", c, fMCMCProposalFunctionScaleFactor[c][0], 100.*fMCMCStatistics[c].efficiency[0]));
2866 BCLog::OutDetail(Form(" %-*s : Scale factor Efficiency", fParameters.MaxNameLength(), "Parameter"));
2873 BCLog::OutDetail(Form(" %-*s : % 6.4g %% %4.1f %%", fParameters.MaxNameLength(), GetParameter(i).GetName().data(), 100.*scalefactor, 100.*fMCMCStatistics_AllChains.efficiency[i]));
2881 void BCEngineMCMC::PrintParameters(const std::vector<double>& P, void (*output)(const std::string&)) const
2887 output(Form(" %-*s : % .*g", GetMaximumParameterNameLength(P.size() > GetNParameters()), GetVariable(i).GetName().data(), GetVariable(i).GetPrecision(), P[i]));
2932 unsigned BCEngineMCMC::PrintAllMarginalized(const std::string& filename, unsigned hdiv, unsigned vdiv) const
2940 BCLog::OutError("BCEngineMCMC::PrintAllMarginalized : Marginalized distributions not stored.");
2953 if (GetMarginalizedHistogram(H1Indices[i])->Integral() == 0) { // histogram was never filled in range
2954 BCLog::OutWarning(Form("BCEngineMCMC::PrintAllMarginalized : 1D Marginalized histogram for \"%s\" is empty; printing is skipped.", GetVariable(H1Indices[i]).GetName().data()));
2972 BCLog::OutWarning(Form("BCEngineMCMC::PrintAllMarginalized : 2D Marginalized histogram for \"%s\":\"%s\" is empty; printing is skipped.", GetVariable(i).GetName().data(), GetVariable(i).GetName().data()));
2986 unsigned BCEngineMCMC::PrintParameterPlot(const std::string& filename, int npar, double interval_content, std::vector<double> quantiles, bool rescale_ranges) const
3007 if (DrawParameterPlot(i, std::min<int>(npar, GetNParameters() - i), interval_content, quantiles, rescale_ranges)) {
3015 if (DrawParameterPlot(i, std::min<int>(npar, GetNVariables() - i), interval_content, quantiles, rescale_ranges)) {
3026 bool BCEngineMCMC::DrawParameterPlot(unsigned i0, unsigned npar, double interval_content, std::vector<double> quantiles, bool rescale_ranges) const
3033 BCLog::OutError(Form("BCSummaryTool::PrintParameterPlot : invalid parameter range [%d, %d)", i0, i1));
3060 if (i < fMCMCStatistics_AllChains.minimum.size() && std::isfinite(fMCMCStatistics_AllChains.minimum[i]))
3062 if (i < fMCMCStatistics_AllChains.maximum.size() && std::isfinite(fMCMCStatistics_AllChains.maximum[i]))
3115 interval_lo.push_back(fabs(SI.intervals.front().mode - SI.intervals.front().xmin) / GetVariable(i).GetRangeWidth());
3116 interval_hi.push_back(fabs(SI.intervals.front().mode - SI.intervals.front().xmax) / GetVariable(i).GetRangeWidth());
3122 if (i < fMCMCStatistics_AllChains.mean.size() && std::isfinite(fMCMCStatistics_AllChains.mean[i]))
3124 if (i < fMCMCStatistics_AllChains.variance.size() && std::isfinite(fMCMCStatistics_AllChains.variance[i]))
3141 hist_axes = new TH2D(Form("h2_axes_parplot_%s_%d_%d", GetSafeName().data(), i0, i1), "", //";;Scaled range [a.u.]",
3148 hist_axes->GetXaxis()->SetLabelSize(std::max<double>(0.01, 0.05 * std::min<double>(1, 4. / hist_axes->GetNbinsX())));
3174 latex->DrawLatex((double)i, 0.47, Form("%.*g", GetVariable(i).GetPrecision(), GetParameter(i).GetFixedValue()));
3177 latex->DrawLatex((double)i, 1.015, Form("%+.*g", GetVariable(i).GetPrecision(), GetVariable(i).GetUpperLimit()));
3179 latex->DrawLatex((double)i, -0.015, Form("%+.*g", GetVariable(i).GetPrecision(), GetVariable(i).GetLowerLimit()));
3195 TGraphAsymmErrors* graph_intervals = new TGraphAsymmErrors(x_i.size(), x_i.data(), local_mode.data(), x_i_err.data(), x_i_err.data(), interval_lo.data(), interval_hi.data());
3210 TGraphErrors* graph_quantiles = new TGraphErrors(x_quantiles.size(), x_quantiles.data(), quantile_vals.data(), quantiles_err.data(), 0);
3224 TGraphErrors* graph_mean = new TGraphErrors(x_i.size(), x_i.data(), mean.data(), 0, rms.data());
3232 legend->AddEntry(graph_intervals, Form("Smallest %.0f%% interval and local mode", 100.*interval_content), "FL");
3286 TH2D hist_corr(Form("hist_correlation_matrix_%s", GetSafeName().data()), ";;", GetNVariables(), -0.5, GetNVariables() - 0.5, GetNVariables(), -0.5, GetNVariables() - 0.5);
3300 double var_i = (i < fMCMCStatistics_AllChains.variance.size()) ? fMCMCStatistics_AllChains.variance[i] : std::numeric_limits<double>::infinity();
3302 double var_j = (j < fMCMCStatistics_AllChains.variance.size()) ? fMCMCStatistics_AllChains.variance[j] : std::numeric_limits<double>::infinity();
3303 double covar_ij = (i < fMCMCStatistics_AllChains.covariance.size() && j < fMCMCStatistics_AllChains.covariance[i].size()) ? fMCMCStatistics_AllChains.covariance[i][j] : std::numeric_limits<double>::infinity();
3371 bcorr.DrawBox(hist_corr.GetXaxis()->GetBinLowEdge(unfilled[i].first + 1), hist_corr.GetYaxis()->GetBinLowEdge(GetNVariables() - unfilled[i].second),
3372 hist_corr.GetXaxis()->GetBinUpEdge (unfilled[i].first + 1), hist_corr.GetYaxis()->GetBinUpEdge (GetNVariables() - unfilled[i].second));
3373 bcorr.DrawBox(hist_corr.GetXaxis()->GetBinLowEdge(unfilled[i].second + 1), hist_corr.GetYaxis()->GetBinLowEdge(GetNVariables() - unfilled[i].first),
3374 hist_corr.GetXaxis()->GetBinUpEdge (unfilled[i].second + 1), hist_corr.GetYaxis()->GetBinUpEdge (GetNVariables() - unfilled[i].first));
3379 lA.DrawLine(hist_corr.GetXaxis()->GetXmin(), hist_corr.GetYaxis()->GetXmax(), hist_corr.GetXaxis()->GetXmax(), hist_corr.GetYaxis()->GetXmax());
3380 lA.DrawLine(hist_corr.GetXaxis()->GetXmax(), hist_corr.GetYaxis()->GetXmin(), hist_corr.GetXaxis()->GetXmax(), hist_corr.GetYaxis()->GetXmax());
3383 lA.DrawLine(hist_corr.GetXaxis()->GetXmin() - 0.40, hist_corr.GetYaxis()->GetBinLowEdge(hist_corr.GetNbinsY() - GetNParameters() + 1),
3384 hist_corr.GetXaxis()->GetBinUpEdge(GetNParameters()), hist_corr.GetYaxis()->GetBinLowEdge(hist_corr.GetNbinsY() - GetNParameters() + 1));
3385 lA.DrawLine(hist_corr.GetXaxis()->GetBinUpEdge(GetNParameters()), hist_corr.GetYaxis()->GetBinLowEdge(hist_corr.GetNbinsY() - GetNParameters() + 1),
3397 bool BCEngineMCMC::PrintCorrelationPlot(const std::string& filename, bool include_observables) const
3420 BCLog::OutError("BCEngineMCMC::PrintCorrelationPlot : Marginalized distributions not stored. Cannot print correlation plots.");
3508 } else if (!(MarginalizedHistogramExists(I[j], I[i])) && I[i] >= I[j]) { // if the histogram is not available, draw "N/A"
3516 ylabel.DrawLatex(margin * (1 - 8 * ylabel.GetTextSize()), yup - padsize / 2., GetVariable(I[j]).GetLatexNameWithUnits().data());
3518 xlabel.DrawLatex(xlow + padsize / 2., margin * (1 - 8 * xlabel.GetTextSize()), GetVariable(I[i]).GetLatexNameWithUnits().data());
3591 ofi << Form(" \\multicolumn{7}{c}{--- fixed to %*.*g ---}\\\\\n", texwidth, prec, GetParameter(i).GetFixedValue()) << std::endl;
3674 BCEngineMCMC::ThreadLocalStorage& BCEngineMCMC::ThreadLocalStorage::operator = (ThreadLocalStorage other)
3680 void BCEngineMCMC::ThreadLocalStorage::swap(BCEngineMCMC::ThreadLocalStorage& A, BCEngineMCMC::ThreadLocalStorage& B)
3743 // each chains gets a different seed. fRandom always returns same seed after the fixing done above
3873 probability_variance += (n_samples > 1) ? prob_delta * prob_delta / n_samples - probability_variance / (n_samples - 1) : 0;
3883 double x = (i < cs.parameters.size()) ? cs.parameters[i] : cs.observables[i - cs.parameters.size()];
3889 variance[i] += (n_samples > 1) ? delta[i] * delta[i] / n_samples - variance[i] / (n_samples - 1.) : 0;
3908 BCEngineMCMC::Statistics& BCEngineMCMC::Statistics::operator+=(const BCEngineMCMC::Statistics& rhs)
3931 probability_variance = (probability_variance * (n_samples - 1) + rhs.probability_variance * (rhs.n_samples - 1) + (rhs.probability_mean - probability_mean) * (rhs.probability_mean - probability_mean) * N) / (n - 1);
3943 variance[i] = (variance[i] * (n_samples - 1) + rhs.variance[i] * (rhs.n_samples - 1) + (rhs.mean[i] - mean[i]) * (rhs.mean[i] - mean[i]) * N) / (n - 1);
3946 covariance[i][j] = (covariance[i][j] * (n_samples - 1) + rhs.covariance[i][j] * (rhs.n_samples - 1) + (rhs.mean[i] - mean[i]) * (rhs.mean[j] - mean[j]) * N) / (n - 1);
3963 efficiency[i] = (n_samples_efficiency * efficiency[i] + rhs.n_samples_efficiency * rhs.efficiency[i]) / (n_eff);
void SetProposeMultivariate(bool flag)
Set flag to true to turn on the multivariate proposal for MCMC based on (Haario et al...
Definition: BCEngineMCMC.h:859
BCEngineMCMC & operator=(const BCEngineMCMC &)
Copy-assignment operator.
Definition: BCEngineMCMC.cxx:191
BCH2D fBCH2DdrawingOptions
A BCH2D (with no histogram) for storing BCH2D drawing options.
Definition: BCEngineMCMC.h:1821
virtual TH1 * CreateH1(const std::string &name) const
Creates a 1D Histogram for this variable.
Definition: BCVariable.cxx:132
std::vector< TMatrixDSym > fMultivariateProposalFunctionCovariance
Covariance matrices used in multivariate proposal functions.
Definition: BCEngineMCMC.h:1686
virtual std::vector< double > GetUniformRandomValues(TRandom *const R) const
Get vector of values uniformly distributed in parameter ranges (or at fixed values, if fixed)
Definition: BCParameterSet.cxx:135
bool MetropolisPreRun()
Runs a pre run for the Metropolis algorithm.
Definition: BCEngineMCMC.cxx:1762
bool MarginalizedHistogramExists(unsigned index) const
Definition: BCEngineMCMC.h:511
void Reset(bool reset_mode=true, bool reset_efficiency=true)
reset all members
Definition: BCEngineMCMC.cxx:3824
std::vector< std::vector< double > > fMCMCInitialPosition
The intial position of each Markov chain.
Definition: BCEngineMCMC.h:1714
BCObservable & GetObservable(unsigned index)
Definition: BCEngineMCMC.h:685
virtual void PrintSummary() const
Print summary of variable set to logs.
Definition: BCVariableSet.h:303
void Update(const ChainState &cs)
update statistics given a new chain state
Definition: BCEngineMCMC.cxx:3855
virtual void Remarginalize(bool autorange=true)
Marginalize from TTree.
Definition: BCEngineMCMC.cxx:1253
bool fCorrectRValueForSamplingVariability
flag for correcting R value for initial sampling variability.
Definition: BCEngineMCMC.h:1760
virtual bool Fix(double value)
Fix parameter to value (set prior to delta).
Definition: BCParameter.h:141
T * OwnClone(const T *o)
Create a clone of the input but avoid registering the object with ROOT so it cannot be deleted twice...
Definition: BCAux.h:189
virtual void CalculateObservables(const std::vector< double > &pars)
Evaluates user-defined observables.
Definition: BCEngineMCMC.h:1292
double GetQuantile(double probability)
Returns the quantile of the distribution.
Definition: BCH1D.cxx:68
A class to represent a split-Gaussian prior of a parameter.
Definition: BCSplitGaussianPrior.h:32
virtual bool AddParameter(const std::string &name, double min, double max, const std::string &latexname="", const std::string &unitstring="")
Definition: BCEngineMCMC.h:1246
void UpdateChainIndex(int chain)
Keep track of which chain is currently computed (within a thread).
Definition: BCEngineMCMC.cxx:3750
TTree * fParameterTree
The tree containing the parameter information.
Definition: BCEngineMCMC.h:1809
void LoadMCMC(const std::string &filename, std::string mcmcTreeName="", std::string parameterTreeName="", bool loadObservables=true)
Load previous MCMC run.
Definition: BCEngineMCMC.cxx:1138
unsigned n_samples_efficiency
number of samples used to calculate efficiencies
Definition: BCEngineMCMC.h:207
virtual void MCMCUserIterationInterface()
Interface allowing to execute arbitrary code for each iteration of the MCMC while running the chains ...
Definition: BCEngineMCMC.h:1428
bool GetNewPointMetropolis()
Generate a new point using the Metropolis algorithm for all chains.
Definition: BCEngineMCMC.cxx:1647
static double RValue(const std::vector< double > &means, const std::vector< double > &variances, unsigned n, bool correctForSamplingVariability=true)
Calculate R value of set of batches of samples—represented by their means and variances, all batches containing the same number of samples—according to Brooks & Gelman, "General Methods for Monitoring Convergence of Iterative Simulations," (1988)
Definition: BCEngineMCMC.cxx:2106
std::string fMCMCOutputFileOption
Output file open option for for writing MCMC Tree.
Definition: BCEngineMCMC.h:1664
virtual std::vector< std::pair< unsigned, unsigned > > GetH2DPrintOrder() const
Definition: BCEngineMCMC.cxx:2902
A guard object to prevent ROOT from taking over ownership of TNamed objects.
Definition: BCAux.h:171
std::vector< std::vector< double > > fMCMCProposalFunctionScaleFactor
Scale factors for proposal functions.
Definition: BCEngineMCMC.h:1678
std::string fMCMCOutputFilename
Output filename for for writing MCMC Tree.
Definition: BCEngineMCMC.h:1660
const std::vector< double > & GetLocalModes(bool force_recalculation=false)
Definition: BCEngineMCMC.cxx:648
void WriteMarginalizedDistributions(const std::string &filename, const std::string &option, bool closeExistingFile=false)
Write marginalization histograms to file.
Definition: BCEngineMCMC.cxx:464
Definition: libBAT_rdict.cxx:16
A class to represent the prior of a parameter by a formula through a TF1.
Definition: BCTF1Prior.h:32
unsigned fMultivariateCovarianceUpdates
Number of multivariate-proposal-function covariance updates performed.
Definition: BCEngineMCMC.h:1695
unsigned PrintPlots(std::vector< BCH1D > &h1, std::vector< BCH2D > &h2, const std::string &filename, unsigned hdiv=1, unsigned vdiv=1)
Print plots.
Definition: BCAux.cxx:339
A class to represent the log of a prior of a parameter by a formula through a TF1.
Definition: BCTF1LogPrior.h:32
unsigned PrintParameterPlot(const std::string &filename, int npar=10, double interval_content=68e-2, std::vector< double > quantile_values=std::vector< double >(0), bool rescale_ranges=true) const
Print a summary plot for the parameters and user-defined observables.
Definition: BCEngineMCMC.cxx:2986
void WriteMarkovChain(bool flag)
Turn on/off writing of Markov chain to root file.
Definition: BCEngineMCMC.h:1016
void CalculateCholeskyDecompositions()
Calculate Cholesky decompositions needed for multivariate proposal function.
Definition: BCEngineMCMC.cxx:1471
void PrintParameters(const std::vector< double > &P, void(*output)(const std::string &)=BCLog::OutSummary) const
Print parameters.
Definition: BCEngineMCMC.cxx:2881
BCH1D fBCH1DdrawingOptions
A BCH1D (with no histogram) for storing BCH1D drawing options.
Definition: BCEngineMCMC.h:1817
std::vector< std::pair< int, int > > fRequestedH2
Vector of pairs of indices for which 2D histograms should be stored.
Definition: BCEngineMCMC.h:1785
bool PrintCorrelationPlot(const std::string &filename="correlation.pdf", bool include_observables=true) const
Print a correlation plot for the parameters.
Definition: BCEngineMCMC.cxx:3397
virtual double GetPriorVariance() const
Definition: BCParameter.cxx:117
virtual void CreateHistograms(bool rescale_ranges=false)
Create histograms from parameter and observable sets.
Definition: BCEngineMCMC.cxx:2596
randomly distribute according to factorized priors
Definition: BCEngineMCMC.h:86
bool GetProposalPointMetropolis(unsigned chain, std::vector< double > &x)
Return a proposal point for the Metropolis algorithm.
Definition: BCEngineMCMC.cxx:1528
virtual bool IsWithinLimits(double value) const
Definition: BCVariable.h:250
std::vector< double > efficiency
efficiencies for each parameter (NB: not stored for observables)
Definition: BCEngineMCMC.h:208
virtual bool ParameterTreeMatchesModel(TTree *partree, bool checkObservables=true)
Check parameter tree against model.
Definition: BCEngineMCMC.cxx:1065
bool PrintParameterLatex(const std::string &filename) const
Print a LaTeX table of the parameters.
Definition: BCEngineMCMC.cxx:3533
unsigned fInitialPositionAttemptLimit
Maximum number of attempts to make to set the initial position.
Definition: BCEngineMCMC.h:1731
void SetPrior(unsigned index, TF1 &f, bool logL=true)
Definition: BCEngineMCMC.cxx:315
virtual bool IsWithinLimits(const std::vector< double > &x) const
Check if vector of values is within limits.
Definition: BCParameterSet.cxx:92
A class to represent a gaussian prior of a parameter.
Definition: BCGaussianPrior.h:33
TH2 * Transpose(const TH2 *const h, const std::string &name="")
Transpose a TH2.
Definition: BCAux.cxx:55
unsigned GetMaximumParameterNameLength(bool observables=true) const
Definition: BCEngineMCMC.h:592
virtual void MCMCCurrentPointInterface(const std::vector< double > &point, int ichain, bool accepted)
Interface allowing to execute arbitrary code for each new point of the MCMC whether it is accepted or...
Definition: BCEngineMCMC.h:1441
double fMCMCProposalFunctionDof
Degree of freedom of Student's t proposal.
Definition: BCEngineMCMC.h:1740
bool DrawParameterPlot(unsigned i0, unsigned npar=0, double interval_content=68e-2, std::vector< double > quantile_values=std::vector< double >(0), bool rescale_ranges=true) const
Draw a summary plot for the parameters in the range provided to current pad.
Definition: BCEngineMCMC.cxx:3026
virtual void MCMCUserInitialize()
User hook called from MCMCInitialize().
Definition: BCEngineMCMC.h:1404
unsigned fMCMCNIterationsPreRunMin
Minimum number of iterations for the pre-run.
Definition: BCEngineMCMC.h:1644
std::string SafeName(const std::string &name)
Convert a name into a safe name for use in ROOT object naming.
Definition: BCAux.cxx:111
void SetInitialPositionScheme(BCEngineMCMC::InitialPositionScheme scheme)
Sets flag which defines initial position.
Definition: BCEngineMCMC.h:835
void UpdateParameterTree()
Update Paramater TTree with scales and efficiencies.
Definition: BCEngineMCMC.cxx:817
virtual void FillHistograms(bool flag)
Set the filling of 1D and 2D histograms.
Definition: BCVariable.h:183
int fMCMCNIterationsConvergenceGlobal
Number of iterations needed for all chains to convergence simultaneously.
Definition: BCEngineMCMC.h:1632
void SetPrecision(BCEngineMCMC::Precision precision)
Set the precision for the MCMC run.
Definition: BCEngineMCMC.cxx:353
std::vector< double > fMCMCInitialScaleFactors
User-provided initial values of the scale factors of the factorized proposal function.
Definition: BCEngineMCMC.h:1682
virtual std::vector< unsigned > GetH1DPrintOrder() const
Definition: BCEngineMCMC.cxx:2891
BCAux::BCTrash< TObject > fObjectTrash
Storage for plot objects with proper clean-up.
Definition: BCEngineMCMC.h:1832
void Clear(bool clear_mode=true, bool clear_efficiency=true)
clear all members.
Definition: BCEngineMCMC.cxx:3780
bool fMCMCProposeMultivariate
Flag for using multivariate proposal function.
Definition: BCEngineMCMC.h:1735
virtual void InitializeMarkovChainTree(bool replacetree=false, bool replacefile=false)
Initialize the trees containing the Markov chains and parameter info.
Definition: BCEngineMCMC.cxx:703
double fHistogramRescalePadding
factor for enlarging range of histograms when rescaling.
Definition: BCEngineMCMC.h:1829
double fMultivariateEpsilon
multivariate-proposal-function cholesky-decomposition nudge.
Definition: BCEngineMCMC.h:1703
virtual const std::vector< double > & GetBestFitParameterErrors() const
Definition: BCEngineMCMC.cxx:639
A struct for holding statistical information about samples.
Definition: BCEngineMCMC.h:187
std::vector< TMatrixD > fMultivariateProposalFunctionCholeskyDecomposition
Cholesky decompositions for multivariate proposal function.
Definition: BCEngineMCMC.h:1691
int GetNIterationsConvergenceGlobal() const
Definition: BCEngineMCMC.h:301
virtual bool AddObservable(const std::string &name, double min, double max, const std::string &latexname="", const std::string &unitstring="")
Definition: BCEngineMCMC.h:1266
virtual void PrintModelSummary() const
Print model summary to log.
Definition: BCEngineMCMC.cxx:2746
BCEngineMCMC::Statistics fMCMCStatistics_AllChains
Statistics across all Markov chains.
Definition: BCEngineMCMC.h:1756
void SetNChains(unsigned n)
Sets the number of Markov chains which are run in parallel.
Definition: BCEngineMCMC.h:775
unsigned fMCMCPreRunCheckClear
Number of iterations between clearing of convergence stats in pre-run.
Definition: BCEngineMCMC.h:1627
unsigned fMCMCNIterationsRun
Number of iterations for a Markov chain run.
Definition: BCEngineMCMC.h:1640
unsigned PrintAllMarginalized(const std::string &filename, unsigned hdiv=1, unsigned vdiv=1) const
Print all marginalizations.
Definition: BCEngineMCMC.cxx:2932
std::vector< BCH1D::BCH1DSmallestInterval > GetSmallestIntervals(std::vector< double > masses)
Definition: BCH1D.cxx:452
virtual void PrintMarginalizationSummary() const
Print marginalization to log.
Definition: BCEngineMCMC.cxx:2809
std::vector< std::vector< TH2 * > > fH2Marginalized
Vector of 2D marginalized distributions.
Definition: BCEngineMCMC.h:1779
std::string fSafeName
Safe name of the engine for use in naming ROOT objects.
Definition: BCEngineMCMC.h:1597
std::vector< BCEngineMCMC::Statistics > fMCMCStatistics
Statistics for each Markov chain.
Definition: BCEngineMCMC.h:1752
virtual double LogEval(const std::vector< double > ¶meters)=0
Needs to be overloaded in the derived class.
std::vector< TH1 * > fH1Marginalized
Vector of 1D marginalized distributions.
Definition: BCEngineMCMC.h:1775
bool fMCMCTreeReuseObservables
flag for whether to reuse MCMC Tree's observables.
Definition: BCEngineMCMC.h:1797
virtual bool UpdateMultivariateProposalFunctionCovariances()
Update multivariate proposal function covariances.
Definition: BCEngineMCMC.cxx:1459
bool ValidParameterTree(TTree *tree) const
Check tree structure for parameter tree.
Definition: BCEngineMCMC.cxx:894
bool GetProposeMultivariate() const
Definition: BCEngineMCMC.h:403
void PrintSummary(const std::string &prefix="", unsigned prec=6, std::vector< double > intervals=std::vector< double >(0))
Print information to log.
Definition: BCH1D.cxx:408
virtual void SetLimits(double lowerlimit=0, double upperlimit=1)
Set the limits of the variable values.
Definition: BCVariable.cxx:59
void LoadMCMCParameters(TTree &partree)
Load MCMC parameters from parameter tree: nchains, proposal function type, scales.
Definition: BCEngineMCMC.cxx:999
void WriteMarkovChainRun(bool flag)
Turn on/off writing of Markov chain to root file during run.
Definition: BCEngineMCMC.cxx:430
virtual bool Valid() const
Whether histogram has been set and filled.
Definition: BCHistogramBase.cxx:226
virtual std::string GetLatexNameWithUnits() const
Definition: BCVariable.h:92
virtual double PositionInRange(double x) const
return position in range of given value from 0 (at lower limit) to 1 (at upper limit) ...
Definition: BCVariable.h:228
std::vector< ChainState > fMCMCStates
The current states of each Markov chain.
Definition: BCEngineMCMC.h:1748
void SetPriorGauss(unsigned index, double mean, double sigma)
Definition: BCEngineMCMC.cxx:330
void LoadParametersFromTree(TTree *partree, bool loadObservables=true)
Load parameters and observables from tree.
Definition: BCEngineMCMC.cxx:918
bool PrintCorrelationMatrix(const std::string &filename="matrix.pdf") const
Print a correlation matrix for the parameters.
Definition: BCEngineMCMC.cxx:3278
virtual void SetLowerLimit(double limit)
Set the lower limit of the variable values.
Definition: BCVariable.h:159
BCEngineMCMC::InitialPositionScheme fInitialPositionScheme
Variable which defines the initial position.
Definition: BCEngineMCMC.h:1727
void MCMCInitialize()
Resets all containers used in MCMC and initializes starting points.
Definition: BCEngineMCMC.cxx:2393
unsigned GetNIterationsPreRun() const
Definition: BCEngineMCMC.cxx:622
void DefaultToPDF(std::string &filename)
Force file extension to be .pdf if not already .pdf or .ps.
Definition: BCAux.cxx:36
virtual const std::vector< double > & GetBestFitParameters() const
Definition: BCEngineMCMC.cxx:633
void SetFillHistogram(int x, int y, bool flag)
Set whether to fill 2D histogram y vs x: positive indices for parameters; negative for observables...
Definition: BCEngineMCMC.cxx:2574
virtual std::string GetBestFitSummary(unsigned i) const
Get string summarizing best fit for single variable.
Definition: BCEngineMCMC.cxx:2792
virtual std::vector< double > GetRangeCenters() const
Get range centers, leaving fixed parameters at fixed values.
Definition: BCParameterSet.cxx:126
double fMultivariateScaleMultiplier
factor to multiply or divide scale factors by in adjusting multivariate-proposal-function scales...
Definition: BCEngineMCMC.h:1707
TH1 * GetMarginalizedHistogram(const std::string &name) const
Obtain the individual marginalized distributions with respect to one parameter as a ROOT TH1...
Definition: BCEngineMCMC.h:527
unsigned fMCMCNIterationsPreRunCheck
Number of iterations between scale adjustments and convergence checks in pre-run. ...
Definition: BCEngineMCMC.h:1623
virtual void EvaluateObservables()
Evaluates user-defined observables at current state of all chains and stores results in fMCMCState...
Definition: BCEngineMCMC.cxx:2344
virtual void SetPrecision(unsigned precision)
Set the precision of the output of variable.
Definition: BCVariable.h:177
bool fRescaleHistogramRangesAfterPreRun
flag for rescaling of histograms after pre-run.
Definition: BCEngineMCMC.h:1825
Vector of intervals with information about total mass.
Definition: BCH1D.h:247
void WriteMarkovChainPreRun(bool flag)
Turn on/off writing of Markov chain to root file during prerun.
Definition: BCEngineMCMC.cxx:438
double fMCMCRValueParametersCriterion
The R-value criterion for convergence of parameters.
Definition: BCEngineMCMC.h:1764
double fMultivariateCovarianceUpdateLambda
weighting parameter for multivariate-proposal-function covariance update.
Definition: BCEngineMCMC.h:1699
Statistics & operator+=(const Statistics &rhs)
addition assignment operator.
Definition: BCEngineMCMC.cxx:3908
virtual double ProposalFunction(unsigned ichain, unsigned ipar)
The default proposal function is a Breit-Wigner random walk.
Definition: BCEngineMCMC.cxx:1519
virtual bool ApplyFixedValues(std::vector< double > &x) const
Change values to fixed values for fixed parameters.
Definition: BCParameterSet.cxx:153
virtual std::vector< double > GetRandomValuesAccordingToPriors(TRandom *const R) const
Get vector values distributed randomly by the parameter priors.
Definition: BCParameterSet.cxx:144
virtual void SetUpperLimit(double limit)
Set the upper limit of the variable values.
Definition: BCVariable.h:165
unsigned fMCMCNIterationsPreRunMax
Maximum number of iterations for a Markov chain prerun.
Definition: BCEngineMCMC.h:1636
void InChainFillHistograms()
Fill marginalized distributions from all chain states.
Definition: BCEngineMCMC.cxx:1718
std::vector< double > fMCMCRValueParameters
The R-values for each parameter.
Definition: BCEngineMCMC.h:1767
void PrepareToContinueMarginalization(const std::string &filename, const std::string &mcmcTreeName="", const std::string ¶meterTreeName="", bool loadObservables=true, bool autorange=true)
Continue the marginalization already stored in another file.
Definition: BCEngineMCMC.cxx:1419
bool AcceptOrRejectPoint(unsigned chain, unsigned parameter)
Accept or rejects a point for a chain and updates efficiency.
Definition: BCEngineMCMC.cxx:1580
virtual double GetRangeWidth() const
Returns the range width of the variable values.
Definition: BCVariable.h:109
BCH1D GetMarginalized(const std::string &name) const
Obtain the individual marginalized distributions with respect to one parameter.
Definition: BCEngineMCMC.h:561
virtual T & At(unsigned index)
Safe access, but slightly less efficient access to parameter.
Definition: BCVariableSet.h:120
bool ValidMCMCTree(TTree *tree, bool checkObservables=true) const
Check tree structure for MCMC tree.
Definition: BCEngineMCMC.cxx:874
A struct for holding a state in a Markov chain.
Definition: BCEngineMCMC.h:159
std::vector< std::vector< double > > covariance
covariances of all pairs of variables
Definition: BCEngineMCMC.h:199
randomly distribute uniformly over parameter ranges
Definition: BCEngineMCMC.h:84
unsigned UpdateFrequency(unsigned N) const
return appropriate update interval
Definition: BCEngineMCMC.cxx:3639
void SetInitialPositions(const std::vector< double > &x0s)
Sets the initial positions for all chains.
Definition: BCEngineMCMC.cxx:673