20#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
21#define protected public
69std::shared_ptr<RooLinkedList> xRooFit::sDefaultNLLOptions =
nullptr;
70std::shared_ptr<ROOT::Fit::FitConfig> xRooFit::sDefaultFitConfig =
nullptr;
72const char *xRooFit::GetVersion()
76const char *xRooFit::GetVersionDate()
83 return RooCmdArg(
"ReuseNLL", flag, 0, 0, 0,
nullptr,
nullptr,
nullptr,
nullptr);
93 return RooCmdArg(
"StrategySequence", 0, 0, 0, 0, val);
101xRooNLLVar xRooFit::createNLL(
const std::shared_ptr<RooAbsPdf> pdf,
const std::shared_ptr<RooAbsData>
data,
109 return createNLL(std::shared_ptr<RooAbsPdf>(&pdf, [](
RooAbsPdf *) {}),
127 return createNLL(pdf,
data,
l);
130std::shared_ptr<const RooFitResult>
132 const std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> &
data,
140std::shared_ptr<const RooFitResult> xRooFit::fitTo(
RooAbsPdf &pdf,
141 const std::pair<RooAbsData *, const RooAbsCollection *> &
data,
149std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>>
153 std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> out;
159 auto _allVars = std::unique_ptr<RooAbsCollection>(pdf.
getVariables());
160 auto _snap = std::unique_ptr<RooAbsCollection>(_allVars->snapshot());
161 *_allVars = fr->constPars();
162 *_allVars = fr->floatParsFinal();
165 auto _globs = std::unique_ptr<RooAbsCollection>(fr->constPars().selectByAttrib(
"global",
true));
176 std::function<std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooArgSet>>(
RooAbsPdf *)> genSubPdf;
179 std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooArgSet>> _out;
182 std::unique_ptr<RooArgSet> _obs(_pdf->getVariables());
183 _obs->remove(fr->constPars(),
true,
true);
184 _obs->remove(fr->floatParsFinal(),
true,
true);
186 if (!_globs->empty()) {
191 std::unique_ptr<RooArgSet> globs(_pdf->getObservables(t));
192 globs->snapshot(*toy_gobs);
193 if (!toy_gobs->
empty() &&
197 *toy_gobs = *std::unique_ptr<RooDataSet>(_pdf->generate(*globs, 1))->
get();
202 for (
auto thePdf : pp->pdfList()) {
203 auto gob = std::unique_ptr<RooArgSet>(thePdf->getObservables(*globs));
206 if (gob->size() > 1) {
207 Warning(
"generate",
"%s contains multiple global obs: %s", thePdf->GetName(),
208 gob->contentsString().c_str());
212 std::unique_ptr<RooArgSet> cpars(thePdf->getParameters(*globs));
214 bool foundServer =
false;
222 !(cClass && strcmp(cClass->
GetName(),
"SimpleGaussianConstraint") == 0)) {
225 <<
"AsymptoticCalculator::MakeAsimovData:constraint term " << thePdf->GetName()
226 <<
" of type " << className <<
" is a non-supported type - result might be not correct "
245 <<
"AsymptoticCalculator::MakeAsimovData:constraint term " << thePdf->
GetName()
246 <<
" has no direct dependence on global observable- cannot generate it " << std::endl;
258 for (
RooAbsArg *a2 : thePdf->servers()) {
264 if (thetaGamma ==
nullptr) {
266 <<
"AsymptoticCalculator::MakeAsimovData:constraint term " << thePdf->
GetName()
267 <<
" is a Gamma distribution and no server named theta is found. Assume that the Gamma "
272 for (
RooAbsArg *a2 : thePdf->servers()) {
280 <<
"AsymptoticCalculator::MakeAsimovData:constraint term " << thePdf->
GetName()
281 <<
" constraint term has more server depending on nuisance- cannot generate it "
286 if (thetaGamma && thetaGamma->
getVal() > 0) {
297 <<
"AsymptoticCalculator::MakeAsimovData - can't find nuisance for constraint term - global "
298 "observables will not be set to Asimov value "
299 << thePdf->GetName() << std::endl;
300 std::cerr <<
"Parameters: " << std::endl;
302 std::cerr <<
"Observables: " << std::endl;
307 Error(
"generate",
"Cannot generate global observables, pdf is: %s::%s", _pdf->ClassName(),
313 _out.second.reset(toy_gobs);
320 _out.first = std::make_unique<RooDataSet>(
321 uuid,
TString::Format(
"%s %s", _pdf->GetTitle(), (expected) ?
"Expected" :
"Toy"), *_obs,
324 for (
auto &
c : s->indexCat()) {
325#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 22, 00)
326 std::string cLabel =
c.first;
328 std::string cLabel =
c->GetName();
330 auto p = s->getPdf(cLabel.c_str());
333 auto toy = genSubPdf(
p);
334 if (toy.second && _out.second)
335 *
const_cast<RooArgSet *
>(_out.second.get()) = *toy.second;
336 _obs->setCatLabel(s->indexCat().GetName(), cLabel.c_str());
337 for (
int i = 0; i < toy.first->numEntries(); i++) {
338 *_obs = *toy.first->get(i);
339 _out.first->add(*_obs, toy.first->weight());
345 std::map<RooRealVar *, std::shared_ptr<RooAbsBinning>> binnings;
347 for (
auto &o : *_obs) {
351 if (
auto res = _pdf->binBoundaries(*
r, -std::numeric_limits<double>::infinity(),
352 std::numeric_limits<double>::infinity())) {
353 binnings[
r] = std::shared_ptr<RooAbsBinning>(
r->getBinning().clone(
r->getBinning().GetName()));
355 std::vector<double> boundaries;
356 boundaries.reserve(res->size());
357 for (
auto &rr : *res) {
358 if (boundaries.empty() || std::abs(boundaries.back() - rr) > 1
e-3 ||
359 std::abs(boundaries.back() - rr) > 1
e-5 * boundaries.back())
360 boundaries.push_back(rr);
362 r->setBinning(
RooBinning(boundaries.size() - 1, &boundaries[0]));
364 }
else if (
r->numBins(
r->getBinning().GetName()) == 0 && expected) {
366 binnings[
r] = std::shared_ptr<RooAbsBinning>(
r->getBinning().clone(
r->getBinning().GetName()));
377 _out.first = std::make_unique<RooDataSet>(
"",
"Toy", _tmp,
RooFit::WeightVar(
"weightVar"));
378 _out.first->add(_tmp);
380 if (_pdf->canBeExtended()) {
390 _out.first = std::unique_ptr<RooDataSet>{_pdf->generate(*_obs,
RooFit::ExpectedData(expected))};
394 _out.first->SetName(
TUUID().AsString());
396 for (
auto &
b : binnings) {
398 auto binning =
b.second;
399 v->setBinning(*binning);
402 auto x =
dynamic_cast<RooRealVar *
>(_out.first->get()->find(
v->GetName()));
403 auto r =
x->getRange();
404 if (
r.first > binning->lowBound())
405 x->setMin(binning->lowBound());
406 if (
r.second < binning->highBound())
407 x->setMax(binning->highBound());
412 out = genSubPdf(&pdf);
413 out.first->SetName(expected ? (
TString(fr->GetName()) +
"_asimov") : uuid);
417 out.first->setGlobalObservables(*out.second);
421#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
424 w->setStringAttribute(
"fitResult", fr->GetName());
425 w->setAttribute(
"expected", expected);
435#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
436 auto _ws = pdf.
_myws;
443 for (
auto obj : _ws->components()) {
444 for (
int i = 0; i < obj->numCaches(); i++) {
450 p->setNormRange(
p->normRange());
452 obj->setValueDirty();
460std::shared_ptr<RooLinkedList> xRooFit::createNLLOptions()
466 for (
auto opt : *defaultNLLOptions()) {
467 out->Add(opt->Clone(
nullptr));
473std::shared_ptr<RooLinkedList> xRooFit::defaultNLLOptions()
475 if (sDefaultNLLOptions)
476 return sDefaultNLLOptions;
484 return sDefaultNLLOptions;
487std::shared_ptr<ROOT::Fit::FitConfig> xRooFit::createFitConfig()
489 return std::make_shared<ROOT::Fit::FitConfig>(*defaultFitConfig());
492std::shared_ptr<ROOT::Fit::FitConfig> xRooFit::defaultFitConfig()
494 if (sDefaultFitConfig)
495 return sDefaultFitConfig;
496 sDefaultFitConfig = std::make_shared<ROOT::Fit::FitConfig>();
497 auto &fitConfig = *sDefaultFitConfig;
498 fitConfig.SetParabErrors(
true);
499 fitConfig.MinimizerOptions().SetMinimizerType(
"Minuit2");
500 fitConfig.MinimizerOptions().SetErrorDef(0.5);
501 fitConfig.SetParabErrors(
true);
502 fitConfig.SetMinosErrors(
true);
503 fitConfig.MinimizerOptions().SetMaxFunctionCalls(
505 fitConfig.MinimizerOptions().SetMaxIterations(-1);
506 fitConfig.MinimizerOptions().SetStrategy(-1);
510 fitConfig.MinimizerOptions().SetPrintLevel(-2);
513 auto extraOpts =
const_cast<ROOT::Math::IOptions *
>(fitConfig.MinimizerOptions().ExtraOptions());
514 extraOpts->
SetValue(
"OptimizeConst", 2);
516#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 29, 00)
517 extraOpts->SetValue(
"StrategySequence",
"0s01s12s2s3m");
518 extraOpts->SetValue(
"HesseStrategySequence",
"23");
520 extraOpts->SetValue(
"StrategySequence",
"0s01s12s2m");
521 extraOpts->SetValue(
"HesseStrategySequence",
"2");
526 extraOpts->SetValue(
"LogSize", 0);
527 extraOpts->SetValue(
"BoundaryCheck",
529 extraOpts->SetValue(
"TrackProgress", 30);
536 return sDefaultFitConfig;
541 return const_cast<ROOT::Math::IOptions *
>(defaultFitConfig()->MinimizerOptions().ExtraOptions());
551 if (signum == SIGINT) {
552 std::cout <<
"Minimization interrupted ... will exit as soon as possible" << std::endl;
563 fFunc(
"func",
"func", this,
f),
569 vars.reset(std::unique_ptr<RooAbsCollection>(
f.getVariables())->selectByAttrib(
"Constant",
false));
606 throw std::runtime_error(
"Keyboard interrupt");
607 return std::numeric_limits<double>::quiet_NaN();
610 if (
prevMin == std::numeric_limits<double>::infinity()) {
614 if (!std::isnan(out)) {
626 std::stringstream sout;
635 nRequired *= nRequired;
646 std::vector<std::pair<double, std::string>> parDeltas;
649 parDeltas.emplace_back(std::pair<double, std::string>(
652 std::sort(parDeltas.begin(), parDeltas.end(),
653 [](
auto &left,
auto &right) { return std::abs(left.first) > std::abs(right.first); });
655 for (i = 0; i < std::min(3,
int(parDeltas.size())); i++) {
656 if (parDeltas.at(i).first == 0)
660 sout << parDeltas.at(i).second << (parDeltas.at(i).first >= 0 ?
"+" :
"-") <<
"="
661 << std::abs(parDeltas.at(i).first) <<
"(" <<
minPars.
getRealValue(parDeltas.at(i).second.c_str())
664 if (i <
int(parDeltas.size()) && parDeltas.at(i).first != 0)
669 if (
gROOT->FromPopUp() &&
gROOT->GetListOfBrowsers()->At(0)) {
670 auto browser =
dynamic_cast<TBrowser *
>(
gROOT->GetListOfBrowsers()->At(0));
671 std::string status = sout.str();
674 std::string status_part;
675 if (status.find(
" : ") != std::string::npos) {
676 status_part = status.substr(0, status.find(
" : "));
677 status = status.substr(status.find(
" : ") + 3);
679 status_part = status;
687 std::cerr << sout.str() << std::endl;
703 mutable double minVal = std::numeric_limits<double>::infinity();
704 mutable double prevMin = std::numeric_limits<double>::infinity();
710 std::shared_ptr<RooAbsCollection>
vars;
723 const std::shared_ptr<ROOT::Fit::FitConfig> &_fitConfig,
724 const std::shared_ptr<RooLinkedList> &nllOpts)
728 auto &fitConfig = *myFitConfig;
732 TString resultTitle = nll.getStringAttribute(
"fitresultTitle");
734 if (resultTitle ==
"")
739 if (nll.getStringAttribute(
"userPars")) {
740 TStringToken st(nll.getStringAttribute(
"userPars"),
",");
743 TString parVal = nll.getStringAttribute(parName);
752 auto _nllVars = std::unique_ptr<RooAbsCollection>(_nll->getVariables());
754 std::unique_ptr<RooAbsCollection> constPars(_nllVars->selectByAttrib(
"Constant",
true));
755 constPars->add(fUserPars,
true);
756 std::unique_ptr<RooAbsCollection> floatPars(_nllVars->selectByAttrib(
"Constant",
false));
759 double boundaryCheck = 0;
763#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 29, 00)
764 int hesseStrategy = 3;
766 int hesseStrategy = 2;
768 if (fitConfig.MinimizerOptions().ExtraOptions()) {
769 fitConfig.MinimizerOptions().ExtraOptions()->GetNamedValue(
"StrategySequence", s);
770 fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue(
"TrackProgress", _progress);
771 fitConfig.MinimizerOptions().ExtraOptions()->GetRealValue(
"BoundaryCheck", boundaryCheck);
772 fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue(
"LogSize", logSize);
773 fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue(
"HesseStrategy", hesseStrategy);
774 fitConfig.MinimizerOptions().ExtraOptions()->GetNamedValue(
"HesseStrategySequence", hs);
784 if (
auto nllDir = cacheDir->
GetDirectory(nll.GetName()); nllDir) {
785 if (
auto keys = nllDir->GetListOfKeys(); keys) {
786 for (
auto &&k : *keys) {
788 if (cl->InheritsFrom(
"RooFitResult")) {
790 nllDir->GetList() ?
dynamic_cast<StoredFitResult *
>(nllDir->GetList()->FindObject(k->GetName()))
793 (storedFr) ? storedFr->
fr.get() :
dynamic_cast<TKey *
>(k)->ReadObject<RooFitResult>();
797 nllDir->Add(storedFr);
802 if (!cachedFit->floatParsFinal().equals(*floatPars)) {
805 for (
auto &
p : *constPars) {
812 _p->getCurrentIndex() !=
c->getCurrentIndex()) {
821 if (
auto _p =
dynamic_cast<RooAbsReal *
>(cachedFit->constPars().find(
p->
GetName())); _p) {
824 if (!_p->getAttribute(
"global") && std::abs(_p->getVal() -
v->getVal()) > 1
e-12) {
847 if (nll.getAttribute(
"readOnly"))
850 int printLevel = fitConfig.MinimizerOptions().PrintLevel();
856 if (floatPars->empty() || fitConfig.MinimizerOptions().MaxFunctionCalls() == 1) {
857 std::shared_ptr<RooFitResult>
result;
859 parsList.
add(*floatPars);
861 result = std::make_shared<RooFitResult>();
863 result->SetTitle(resultTitle);
864 result->setFinalParList(parsList);
865 result->setInitParList(parsList);
869 result->setCovarianceMatrix(
d);
870 result->setCovQual(floatPars->empty() ? 3 : -1);
871 result->setMinNLL(_nll->getVal());
873 result->setStatus(floatPars->empty() ? 0 : 1);
875 std::vector<std::pair<std::string, int>> statusHistory;
876 statusHistory.emplace_back(std::make_pair(
"EVAL",
result->status()));
877 result->setStatusHistory(statusHistory);
882 cacheDir->
mkdir(nll.GetName());
883 if (
auto dir = cacheDir->
GetDirectory(nll.GetName()); dir) {
886 if (strlen(nllOpts->GetName()) == 0) {
889 if (!dir->FindKey(nllOpts->GetName())) {
890 dir->WriteObject(nllOpts.get(), nllOpts->GetName());
902 std::shared_ptr<RooFitResult> out;
906 for (
auto p : *floatPars) {
907 if (
p->isCategory()) {
911 if (!floatCats.
empty()) {
912 RooSuperCategory allCats(
"floatCats",
"Floating categorical parameters", floatCats);
913 std::unique_ptr<RooAbsCollection> _snap(floatCats.
snapshot());
916 std::shared_ptr<const RooFitResult> bestFr;
917 for (
auto c : allCats) {
919 Info(
"minimize",
"Minimizing with discrete %s",
c.first.c_str());
920 auto fr =
minimize(nll, _fitConfig, nllOpts);
922 Warning(
"minimize",
"Minimization with discrete %s failed",
c.first.c_str());
925 if (!bestFr || fr->minNll() < bestFr->minNll()) {
936 out = std::make_shared<RooFitResult>(*bestFr);
937 const_cast<RooArgList &
>(out->floatParsFinal())
938 .addClone(*std::unique_ptr<RooAbsCollection>(out->constPars().selectCommon(floatCats)));
939 const_cast<RooArgList &
>(out->floatParsInit()).addClone(*_snap);
940 const_cast<RooArgList &
>(out->constPars()).remove(floatCats);
944 bool restore = !fitConfig.UpdateAfterFit();
947 int strategy = fitConfig.MinimizerOptions().Strategy();
953 auto logger = (logSize > 0) ? std::make_unique<cout_redirect>(logs, logSize) :
nullptr;
955 _minimizer.
fitter()->Config() = fitConfig;
967 bool autoMaxCalls = (_minimizer.
fitter()->Config().MinimizerOptions().MaxFunctionCalls() == 0);
969 _minimizer.
fitter()->Config().MinimizerOptions().SetMaxFunctionCalls(
970 500 * floatPars->size() * floatPars->size());
972 if (_minimizer.
fitter()->Config().MinimizerOptions().MaxIterations() == 0) {
973 _minimizer.
fitter()->Config().MinimizerOptions().SetMaxIterations(500 * floatPars->size());
976 bool hesse = _minimizer.
fitter()->Config().ParabErrors();
977 _minimizer.
fitter()->Config().SetParabErrors(
979 bool minos = _minimizer.
fitter()->Config().MinosErrors();
980 _minimizer.
fitter()->Config().SetMinosErrors(
false);
981 _minimizer.
fitter()->Config().SetUpdateAfterFit(
true);
983 std::vector<std::pair<std::string, int>> statusHistory;
988 TString actualFirstMinimizer = _minimizer.
fitter()->Config().MinimizerType();
992 int constOptimize = 2;
993 _minimizer.
fitter()->Config().MinimizerOptions().ExtraOptions()->GetValue(
"OptimizeConst", constOptimize);
1013 TString minim = _minimizer.
fitter()->Config().MinimizerType();
1014 TString algo = _minimizer.
fitter()->Config().MinimizerAlgoType();
1015 if (minim ==
"Minuit2") {
1016 if (strategy == -1) {
1019 sIdx = m_strategy.
Index(
'0' + strategy);
1022 Warning(
"minimize",
"Strategy %d not specified in StrategySequence %s ... defaulting to start of sequence",
1023 strategy, m_strategy.
Data());
1026 }
else if (minim ==
"Minuit")
1027 sIdx = m_strategy.
Index(
'm');
1032 while (tries < maxtries && sIdx != -1) {
1033 if (m_strategy(sIdx) ==
'm') {
1035 algo =
"migradImproved";
1036 }
else if (m_strategy(sIdx) ==
's') {
1038 }
else if (m_strategy(sIdx) ==
'h') {
1041 strategy =
int(m_strategy(sIdx) -
'0');
1047 fff->fState = minim + algo + std::to_string(_minimizer.
fitter()->Config().MinimizerOptions().Strategy());
1050 status = _minimizer.
minimize(minim, algo);
1051 }
catch (
const std::exception &
e) {
1052 std::cerr <<
"Exception while minimizing: " <<
e.what() << std::endl;
1054 if (first && actualFirstMinimizer != _minimizer.
fitter()->Config().MinimizerType())
1055 actualFirstMinimizer = _minimizer.
fitter()->Config().MinimizerType();
1061 throw std::runtime_error(
"Keyboard interrupt while minimizing");
1065 status = _minimizer.
fitter()
1068 minim = _minimizer.
fitter()->Config().MinimizerType();
1069 statusHistory.emplace_back(_minimizer.
fitter()->Config().MinimizerType() +
1070 _minimizer.
fitter()->Config().MinimizerAlgoType() +
1071 std::to_string(_minimizer.
fitter()->Config().MinimizerOptions().Strategy()),
1073 if (status % 1000 == 0)
1076 if (status == 4 && minim !=
"Minuit") {
1077 if (printLevel >= -1) {
1078 Warning(
"fitTo",
"%s Hit max function calls of %d", fitName.
Data(),
1079 _minimizer.
fitter()->Config().MinimizerOptions().MaxFunctionCalls());
1082 if (printLevel >= -1)
1083 Warning(
"fitTo",
"will try doubling this");
1084 _minimizer.
fitter()->Config().MinimizerOptions().SetMaxFunctionCalls(
1085 _minimizer.
fitter()->Config().MinimizerOptions().MaxFunctionCalls() * 2);
1086 _minimizer.
fitter()->Config().MinimizerOptions().SetMaxIterations(
1087 _minimizer.
fitter()->Config().MinimizerOptions().MaxIterations() * 2);
1095 if (printLevel >= -1) {
1096 Warning(
"fitTo",
"%s %s%s Status=%d (edm=%f, tol=%f, strat=%d), tries=#%d...", fitName.
Data(),
1097 _minimizer.
fitter()->Config().MinimizerType().c_str(),
1098 _minimizer.
fitter()->Config().MinimizerAlgoType().c_str(), status,
1099 _minimizer.
fitter()->Result().Edm(), _minimizer.
fitter()->Config().MinimizerOptions().Tolerance(),
1100 _minimizer.
fitter()->Config().MinimizerOptions().Strategy(), tries);
1104 if (sIdx == m_strategy.
Length() - 1) {
1123 if (printLevel >= -1 && status != 0) {
1124 Warning(
"fitTo",
"%s final status is %d", fitName.
Data(), status);
1133 double dCovar = std::numeric_limits<double>::quiet_NaN();
1140 if (hesse && m_hessestrategy.
Length() != 0 &&
1141 (m_strategy(sIdx) ==
'h' || (_minimizer.
fitter()->Result().IsValid()))) {
1164 if (hesseStrategy == -1) {
1167 sIdx = m_hessestrategy.
Index(
'0' + hesseStrategy);
1171 "HesseStrategy %d not specified in HesseStrategySequence %s ... defaulting to start of sequence",
1172 hesseStrategy, m_hessestrategy.
Data());
1175 while (sIdx != -1) {
1176 hesseStrategy =
int(m_hessestrategy(sIdx) -
'0');
1178 if (strategy == 2 && hesseStrategy == 2) {
1180 if (_minimizer.
fitter()->GetMinimizer()->CovMatrixStatus() == 3) {
1183 if (sIdx >= m_hessestrategy.
Length() - 1) {
1190 _minimizer.
fitter()->Config().MinimizerOptions().SetStrategy(hesseStrategy);
1195 fff->fState =
TString::Format(
"Hesse%d", _minimizer.
fitter()->Config().MinimizerOptions().Strategy());
1196 fff->counter2 = fff->counter;
1204 auto _status = _minimizer.
hesse();
1227 statusHistory.push_back(std::pair<std::string, int>(
1232 throw std::runtime_error(
"Keyboard interrupt while hesse calculating");
1234 if ((_status != 0 || _minimizer.
fitter()->GetMinimizer()->CovMatrixStatus() != 3) && status == 0 &&
1236 Warning(
"fitTo",
"%s hesse status is %d, covQual=%d", fitName.
Data(), _status,
1237 _minimizer.
fitter()->GetMinimizer()->CovMatrixStatus());
1240 if (sIdx >= m_hessestrategy.
Length() - 1) {
1244 if (_status == 0 && _minimizer.
fitter()->GetMinimizer()->CovMatrixStatus() == 3) {
1247 }
else if (_status == 0) {
1249 statusHistory.back().second = _minimizer.
fitter()->GetMinimizer()->CovMatrixStatus();
1256 if (status == 0 &&
minos) {
1257 if (std::unique_ptr<RooAbsCollection> mpars(floatPars->selectByAttrib(
"minos",
true)); !mpars->empty()) {
1259 fff->fState =
"Minos";
1262 auto _status = _minimizer.
minos(*mpars);
1263 statusHistory.push_back(std::pair(
"Minos", _status));
1272 out = std::unique_ptr<RooFitResult>{_minimizer.
save(fitName, resultTitle)};
1276 if (out->status() == 0 && out->covQual() != 3 && hesse) {
1277 if (out->covQual() == 2) {
1285 out->setStatusHistory(statusHistory);
1288 const_cast<RooArgList &
>(out->constPars()).addClone(fUserPars,
true);
1290 if (!std::isnan(dCovar)) {
1292 .addClone(
RooRealVar(
".dCovar",
"dCovar from minimization", dCovar),
true);
1295 if (boundaryCheck) {
1298 int limit_status = 0;
1299 std::string listpars;
1300 for (
auto *
v : dynamic_range_cast<RooRealVar *>(*floatPars)) {
1303 double vRange =
v->getMax() -
v->getMin();
1304 if (
v->getMin() >
v->getVal() - vRange * boundaryCheck ||
1305 v->getMax() <
v->getVal() + vRange * boundaryCheck) {
1309 auto tmp =
v->getVal();
1310 v->setVal(
v->getMin());
1311 double boundary_nll = _nll->getVal();
1312 if (boundary_nll <= out->minNll()) {
1313 static_cast<RooRealVar *
>(out->floatParsFinal().find(
v->GetName()))->
setVal(
v->getMin());
1314 out->setMinNLL(boundary_nll);
1322 if (
v->hasRange(
"physical"))
1324 listpars +=
v->GetName();
1327 (
v->getMin() >
v->getVal() -
v->getError() ||
v->getMax() <
v->getVal() +
v->getError())) {
1328 if (printLevel >= 0) {
1329 Info(
"minimize",
"PARLIM: %s (%f +/- %f) range (%f - %f)",
v->GetName(),
v->getVal(),
v->getError(),
1330 v->getMin(),
v->getMax());
1332 limit_status = 9000;
1335 if (limit_status == 900) {
1336 if (printLevel >= 0) {
1337 Warning(
"minimize",
"BOUNDCHK: Parameters within %g%% limit in fit result: %s", boundaryCheck * 100,
1340 }
else if (limit_status > 0) {
1341 if (printLevel >= 0)
1342 Warning(
"minimize",
"BOUNDCHK: Parameters near limit in fit result");
1346 statusHistory.emplace_back(
"BOUNDCHK", limit_status);
1347 out->setStatusHistory(statusHistory);
1348 out->setStatus(out->status() + limit_status);
1374 out->setMinNLL(_nll->getVal());
1377 for (
auto o : out->floatParsFinal()) {
1379 v && !
v->
getAttribute(
"minos") && !
v->getAttribute(
"xminos") && !
v->getAttribute(
"xMinos"))
1380 v->removeAsymError();
1384 if (fitConfig.MinimizerOptions().MinimizerType() != actualFirstMinimizer) {
1385 fitConfig.MinimizerOptions().SetMinimizerType(actualFirstMinimizer);
1393 if (status == 0 &&
minos) {
1394 for (
auto label : {
"xminos",
"xMinos"}) {
1395 std::unique_ptr<RooAbsCollection> pars(floatPars->selectByAttrib(label,
true));
1396 for (
auto p : *pars) {
1397 Info(
"minimize",
"Computing xminos error for %s",
p->
GetName());
1401 *floatPars = out->floatParsFinal();
1407 *floatPars = out->floatParsInit();
1410 if (out && !logs.empty()) {
1412#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00)
1413 const_cast<RooArgList &
>(out->constPars()).addOwned(std::make_unique<RooStringVar>(
".log",
"log", logs.c_str()));
1419 if (out && cacheDir && cacheDir->
IsWritable()) {
1423 cacheDir->
mkdir(nll.GetName());
1424 if (
auto dir = cacheDir->
GetDirectory(nll.GetName()); dir) {
1427 if (strlen(nllOpts->GetName()) == 0) {
1430 if (!dir->FindKey(nllOpts->GetName())) {
1431 dir->WriteObject(nllOpts.get(), nllOpts->GetName());
1436 std::string configName;
1437 if (!fitConfig.MinimizerOptions().ExtraOptions()->GetValue(
"Name", configName)) {
1438 auto extraOpts =
const_cast<ROOT::Math::IOptions *
>(fitConfig.MinimizerOptions().ExtraOptions());
1440 extraOpts->SetValue(
"Name", configName.data());
1442 if (!dir->GetKey(configName.data())) {
1443 dir->WriteObject(&fitConfig, configName.data());
1446#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00)
1448 .addOwned(std::make_unique<RooStringVar>(
".fitConfigName",
"fitConfigName", configName.c_str()));
1451 .addOwned(*
new RooStringVar(
".fitConfigName",
"fitConfigName", configName.c_str()));
1453 dir->WriteObject(out.get(), out->GetName());
1467 const std::shared_ptr<ROOT::Fit::FitConfig> &_fitConfig)
1470 auto par =
dynamic_cast<RooRealVar *
>(std::unique_ptr<RooArgSet>(nll.getVariables())->find(parName));
1479 auto &fitConfig = *myFitConfig;
1481 bool pErrs = fitConfig.ParabErrors();
1482 fitConfig.SetParabErrors(
false);
1483 double mErrs = fitConfig.MinosErrors();
1484 fitConfig.SetMinosErrors(
false);
1486 double val_best = par_hat->getVal();
1487 double val_err = (par_hat->hasError() ? par_hat->getError() : -1);
1488 double orig_err = val_err;
1489 double nll_min = ufit.
minNll();
1493 bool isConst = par->isConstant();
1494 par->setConstant(
true);
1496 auto findValue = [&](
double val_guess,
double N_sigma = 1,
double precision = 0.002,
int printLevel = 0) {
1499 double sigma_guess = std::abs((val_guess - val_best) / N_sigma);
1502 10 * precision * sigma_guess;
1503 bool lastOverflow =
false;
1504 bool lastUnderflow =
false;
1505 while (std::abs(val_pre - val_guess) > precision * sigma_guess) {
1506 val_pre = val_guess;
1507 if (val_guess > 0 && par->getMax() < val_guess)
1508 par->setMax(2 * val_guess);
1509 if (val_guess < 0 && par->getMin() > val_guess)
1510 par->setMin(2 * val_guess);
1511 par->setVal(val_guess);
1516 return std::numeric_limits<double>::quiet_NaN();
1518 double nll_val =
result->minNll();
1519 status +=
result->status() * 10;
1520 tmu = 2 * (nll_val - nll_min);
1521 sigma_guess = std::abs(val_guess - val_best) / sqrt(tmu);
1525 std::cout <<
"Warning: Alternative best-fit of " << par->GetName() <<
" @ " << val_guess <<
" vs "
1526 << val_best <<
" (delta=" << tmu / 2. <<
")" << std::endl;
1527 double new_guess = val_guess + (val_guess - val_best);
1528 val_best = val_guess;
1529 val_guess = new_guess;
1530 sigma_guess = std::abs((val_guess - val_best) / N_sigma);
1531 val_pre = val_guess - 10 * precision * sigma_guess;
1532 status = (status / 10) * 10 + 1;
1536 double corr = (val_pre - val_best - N_sigma * sigma_guess);
1541 if (printLevel > 1) {
1545 std::cout <<
"NLL min: " << nll_min << std::endl;
1546 std::cout <<
"N_sigma*sigma(pre): " << std::abs(val_pre - val_best) << std::endl;
1547 std::cout <<
"sigma(guess): " << sigma_guess << std::endl;
1548 std::cout <<
"par(guess): " << val_guess + corr << std::endl;
1549 std::cout <<
"true val: " << val_best << std::endl;
1550 std::cout <<
"tmu: " << tmu << std::endl;
1551 std::cout <<
"Precision: " << sigma_guess * precision << std::endl;
1552 std::cout <<
"Correction: " << (-corr < 0 ?
" " :
"") << -corr << std::endl;
1553 std::cout <<
"N_sigma*sigma(guess): " << std::abs(val_guess - val_best) << std::endl;
1554 std::cout << std::endl;
1556 if (val_guess > par->getMax()) {
1558 val_guess = par->getMin();
1561 lastOverflow =
true;
1562 lastUnderflow =
false;
1563 val_guess = par->getMax() - 1
e-12;
1564 }
else if (val_guess < par->getMin()) {
1565 if (lastUnderflow) {
1566 val_guess = par->getMin();
1569 lastOverflow =
false;
1570 lastUnderflow =
true;
1571 val_guess = par->getMin() + 1
e-12;
1573 lastUnderflow =
false;
1574 lastOverflow =
false;
1579 status = (status / 10) * 10 + 3;
1587 status = (status / 10) * 10 + 2;
1588 }
else if (lastUnderflow) {
1591 status = (status / 10) * 10 + 2;
1595 std::cout <<
"Found sigma for nll " << nll.GetName() <<
": " << (val_guess - val_best) / N_sigma << std::endl;
1597 std::cout <<
"Finished in " << nrItr <<
" iterations." << std::endl;
1599 std::cout << std::endl;
1600 return (val_guess - val_best) / N_sigma;
1605 par_hat->setError(std::numeric_limits<double>::quiet_NaN());
1606 double lo = par_hat->getErrorLo();
1607 double hi = par_hat->getErrorHi();
1608 if (std::isnan(
hi)) {
1609 hi = findValue(val_best + val_err, 1) + val_best -
1614 if (std::isnan(lo)) {
1615 lo = -findValue(val_best - val_err, -1) + val_best -
1621 fitConfig.SetParabErrors(pErrs);
1622 fitConfig.SetMinosErrors(mErrs);
1623 par->setConstant(isConst);
1625 std::vector<std::pair<std::string, int>> statusHistory;
1629 statusHistory.emplace_back(
TString::Format(
"xMinos:%s", parName), status);
1630 const_cast<RooFitResult &
>(ufit).setStatusHistory(statusHistory);
1643 std::deque<RooAbsArg *> topPdfs;
1645 for (
auto p :
w.allPdfs()) {
1646 if (
p->hasClients())
1648 flagCount +=
p->getAttribute(
"hypoTest");
1649 if (
p->getAttribute(
"hypoTest")) {
1650 topPdfs.push_front(
p);
1652 topPdfs.push_back(
p);
1655 if (topPdfs.empty()) {
1656 Error(
"hypoTest",
"Cannot find top-level pdf in workspace");
1658 }
else if (topPdfs.size() > 1) {
1660 if (flagCount == 0) {
1661 Error(
"hypoTest",
"Multiple top-level pdfs. Flag which one to test with "
1662 "w->pdf(\"pdfName\")->setAttribute(\"hypoTest\",true)");
1664 }
else if (flagCount != 1) {
1665 Error(
"hypoTest",
"Multiple top-level pdfs flagged for hypoTest -- pick one.");
1669 model =
dynamic_cast<RooAbsPdf *
>(topPdfs.front());
1671 Info(
"hypoTest",
"Using PDF: %s", model->
GetName());
1677 std::shared_ptr<RooArgSet> obsGlobs =
nullptr;
1679 for (
auto p :
w.allData()) {
1681 Error(
"hypoTest",
"Multiple datasets in workspace. Flag which one to test with "
1682 "w->data(\"dataName\")->setAttribute(\"hypoTest\",true)");
1689 Error(
"hypoTest",
"No data -- cannot determine observables");
1693 Info(
"hypoTest",
"Using Dataset: %s", obsData->
GetName());
1696 auto _globs = xRooNode(
w).datasets()[obsData->
GetName()]->globs();
1697 obsGlobs = std::make_shared<RooArgSet>();
1698 obsGlobs->addClone(_globs.argList());
1699 Info(
"hypoTest",
"Using Globs: %s", (obsGlobs->empty()) ?
" <NONE>" : obsGlobs->contentsString().c_str());
1704 auto _vars = std::unique_ptr<RooArgSet>(model->
getVariables());
1707 for (
auto _v : *_vars) {
1712 if (poi.
size() > 1) {
1713 auto _const = std::unique_ptr<RooAbsCollection>(poi.
selectByAttrib(
"Constant",
true));
1717 if (!args.
empty()) {
1721 Error(
"hypoTest",
"No POI detected: add the hypoPoints binning to at least one non-const model parameter e.g.:\n "
1722 "w->var(\"mu\")->setBinning(RooUniformBinning(0.5,10.5,10),\"hypoPoints\"))");
1734 xRooNLLVar
nll(*model, std::make_pair(obsData, obsGlobs.get()), *nllOpts);
1735 nll.SetFitConfig(fitConfig);
1737 if (poi.
size() == 1) {
1740 double altVal = (mu->getStringAttribute(
"altVal")) ?
TString(mu->getStringAttribute(
"altVal")).Atof()
1741 : std::numeric_limits<double>::quiet_NaN();
1743 if (std::isnan(altVal) && mu->hasRange(
"physical")) {
1745 altVal = mu->getMin(
"physical");
1746 Info(
"hypoTest",
"No altVal specified - using min of given physical range = %g", altVal);
1748 if (!std::isnan(altVal)) {
1749 Info(
"hypoTest",
"alt hypo: %g - CLs activated", altVal);
1751 Info(
"hypoTest",
"No altVal found - to specify setStringAttribute(\"altVal\",\"<value>\") on POI or set "
1752 "the physical range");
1755 bool doCLs = !std::isnan(altVal) && std::abs(mu->getMin(
"hypoPoints")) > altVal &&
1756 std::abs(mu->getMax(
"hypoPoints")) > altVal;
1758 const char *sCL = (doCLs) ?
"CLs" :
"null";
1759 Info(
"hypoTest",
"%s testing active", sCL);
1769 std::vector<int> expSig = {-2, -1, 0, 1, 2};
1770 if (std::isnan(altVal))
1772 std::map<int, TGraphErrors> exp_pcls;
1773 std::map<int, TGraphErrors> exp_cls;
1774 for (
auto &s : expSig) {
1776 TString::Format(
"Expected (%d#sigma) p_{%s};%s", s, sCL, mu->GetTitle()));
1778 TString::Format(
"Expected (%d#sigma) %s;%s", s, sCL, mu->GetTitle()));
1782 double _out = std::numeric_limits<double>::quiet_NaN();
1783 bool lastAbove =
false;
1784 for (
int i = 0; i < pValues.GetN(); i++) {
1785 bool thisAbove = pValues.GetPointY(i) >= (1. - CL);
1786 if (i != 0 && thisAbove != lastAbove) {
1789 _out = pValues.GetPointX(i - 1) + (pValues.GetPointX(i) - pValues.GetPointX(i - 1)) *
1790 ((1. - CL) - pValues.GetPointY(i - 1)) /
1791 (pValues.GetPointY(i) - pValues.GetPointY(i - 1));
1793 lastAbove = thisAbove;
1798 auto testPoint = [&](
double testVal) {
1799 auto hp =
nll.hypoPoint(mu->GetName(), testVal, altVal, pllType);
1800 obs_ts->SetPoint(obs_ts->GetN(), testVal, hp.pll().first);
1801 obs_ts->SetPointError(obs_ts->GetN() - 1, 0, hp.pll().second);
1803 if (nToysNull > 0) {
1806 obs_pcls->SetPoint(obs_pcls->GetN(), testVal, (doCLs) ? hp.pCLs_asymp().first : hp.pNull_asymp().first);
1807 obs_pcls->SetPointError(obs_pcls->GetN() - 1, 0, (doCLs) ? hp.pCLs_asymp().second : hp.pNull_asymp().second);
1808 for (
auto &s : expSig) {
1809 exp_pcls[s].SetPoint(exp_pcls[s].GetN(), testVal,
1810 (doCLs) ? hp.pCLs_asymp(s).first : hp.pNull_asymp(s).first);
1813 Info(
"hypoTest",
"%s=%g: %s=%g sigma_mu=%g %s=%g", mu->GetName(), testVal, obs_ts->GetName(),
1814 obs_ts->GetPointY(obs_ts->GetN() - 1), hp.sigma_mu().first, obs_pcls->GetName(),
1815 obs_pcls->GetPointY(obs_pcls->GetN() - 1));
1817 Info(
"hypoTest",
"%s=%g: %s=%g %s=%g", mu->GetName(), testVal, obs_ts->GetName(),
1818 obs_ts->GetPointY(obs_ts->GetN() - 1), obs_pcls->GetName(), obs_pcls->GetPointY(obs_pcls->GetN() - 1));
1822 if (mu->getBins(
"hypoPoints") <= 0) {
1825 testPoint(mu->getMin(
"hypoPoints"));
1826 testPoint(mu->getMax(
"hypoPoints"));
1827 testPoint((mu->getMax(
"hypoPoints") + mu->getMin(
"hypoPoints")) / 2.);
1829 while (std::abs(obs_pcls->GetPointY(obs_pcls->GetN() - 1) - (1. - CL)) > 0.01) {
1831 double nextTest = getLimit(*obs_pcls);
1832 if (std::isnan(nextTest))
1834 testPoint(nextTest);
1836 for (
auto s : expSig) {
1837 while (std::abs(exp_pcls[s].GetPointY(exp_pcls[s].GetN() - 1) - (1. - CL)) > 0.01) {
1839 double nextTest = getLimit(exp_pcls[s]);
1840 if (std::isnan(nextTest))
1842 testPoint(nextTest);
1847 for (
auto &s : expSig)
1851 for (
int i = 0; i <= mu->getBins(
"hypoPoints"); i++) {
1852 testPoint((i == mu->getBins(
"hypoPoints")) ? mu->getBinning(
"hypoPoints").binHigh(i - 1)
1853 : mu->getBinning(
"hypoPoints").binLow(i));
1857 obs_cls->SetPoint(obs_cls->GetN(), getLimit(*obs_pcls), 0.05);
1858 for (
auto &s : expSig) {
1859 exp_cls[s].SetPoint(exp_cls[s].GetN(), getLimit(exp_pcls[s]), 0.05);
1863 if (exp_pcls[2].GetN() > 1) {
1869 band2down->
SetNameTitle(
".pCLs_2sigma_downUncert",
"");
1875 for (
int i = 0; i < exp_pcls[2].GetN(); i++) {
1876 band2->
SetPoint(band2->
GetN(), exp_pcls[2].GetPointX(i),
1877 exp_pcls[2].GetPointY(i) - exp_pcls[2].GetErrorYlow(i));
1878 band2up->
SetPoint(band2up->
GetN(), exp_pcls[2].GetPointX(i),
1879 exp_pcls[2].GetPointY(i) + exp_pcls[2].GetErrorYhigh(i));
1881 for (
int i = exp_pcls[2].GetN() - 1; i >= 0; i--) {
1882 band2up->
SetPoint(band2up->
GetN(), exp_pcls[2].GetPointX(i),
1883 exp_pcls[2].GetPointY(i) - exp_pcls[2].GetErrorYlow(i));
1885 for (
int i = 0; i < exp_pcls[-2].GetN(); i++) {
1886 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-2].GetPointX(i),
1887 exp_pcls[-2].GetPointY(i) + exp_pcls[-2].GetErrorYhigh(i));
1889 for (
int i = exp_pcls[-2].GetN() - 1; i >= 0; i--) {
1890 band2->
SetPoint(band2->
GetN(), exp_pcls[-2].GetPointX(i),
1891 exp_pcls[-2].GetPointY(i) + exp_pcls[-2].GetErrorYhigh(i));
1892 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-2].GetPointX(i),
1893 exp_pcls[-2].GetPointY(i) - exp_pcls[-2].GetErrorYlow(i));
1898 auto ax =
static_cast<TNamed *
>(band2->
Clone(
".axis"));
1903 band2down->
Draw(
"F");
1906 if (exp_pcls[1].GetN() > 1) {
1912 band2down->
SetNameTitle(
".pCLs_1sigma_downUncert",
"");
1918 for (
int i = 0; i < exp_pcls[1].GetN(); i++) {
1919 band2->
SetPoint(band2->
GetN(), exp_pcls[1].GetPointX(i),
1920 exp_pcls[1].GetPointY(i) - exp_pcls[1].GetErrorYlow(i));
1921 band2up->
SetPoint(band2up->
GetN(), exp_pcls[1].GetPointX(i),
1922 exp_pcls[1].GetPointY(i) + exp_pcls[1].GetErrorYhigh(i));
1924 for (
int i = exp_pcls[1].GetN() - 1; i >= 0; i--) {
1925 band2up->
SetPoint(band2up->
GetN(), exp_pcls[1].GetPointX(i),
1926 exp_pcls[1].GetPointY(i) - exp_pcls[1].GetErrorYlow(i));
1928 for (
int i = 0; i < exp_pcls[-1].GetN(); i++) {
1929 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-1].GetPointX(i),
1930 exp_pcls[-1].GetPointY(i) + exp_pcls[-1].GetErrorYhigh(i));
1932 for (
int i = exp_pcls[-1].GetN() - 1; i >= 0; i--) {
1933 band2->
SetPoint(band2->
GetN(), exp_pcls[-1].GetPointX(i),
1934 exp_pcls[-1].GetPointY(i) + exp_pcls[-1].GetErrorYhigh(i));
1935 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-1].GetPointX(i),
1936 exp_pcls[-1].GetPointY(i) - exp_pcls[-1].GetErrorYlow(i));
1943 band2down->
Draw(
"F");
1947 if (exp_cls[0].GetN() > 0) {
1948 exp_pcls[0].SetLineStyle(2);
1949 exp_pcls[0].SetFillColor(
kGreen);
1950 exp_pcls[0].SetMarkerStyle(0);
1954 obs_pcls->Draw(
gPad->GetListOfPrimitives()->IsEmpty() ?
"ALP" :
"LP");
1956 obs_ts->SetLineColor(
kRed);
1957 obs_ts->SetMarkerColor(
kRed);
1961 auto l =
new TLegend(0.5, 0.6, 1. -
gPad->GetRightMargin(), 1. -
gPad->GetTopMargin());
1962 l->SetName(
"legend");
1963 l->AddEntry(obs_ts, obs_ts->GetTitle(),
"LPE");
1964 l->AddEntry(obs_pcls, obs_pcls->GetTitle(),
"LPE");
1966 l->AddEntry(expPlot,
"Expected",
"LFE");
1970 obs_cls->SetMarkerStyle(29);
1971 obs_cls->SetEditable(
false);
1972 obs_cls->Draw(
"LP");
1973 for (
auto s : expSig) {
1974 exp_cls[s].SetMarkerStyle(29);
1975 exp_cls[s].SetEditable(
false);
1976 exp_cls[s].DrawClone(
"LP");
1990 double factor = pow(10.0, digits - ceil(log10(std::abs(
value))));
1991 return std::round(
value * factor) / factor;
1995 const double multiplier = std::pow(10.0, decimal_places);
1996 return std::round(
value * multiplier) / multiplier;
2003 if (!std::isinf(out.second)) {
2004 auto tmp = out.second;
2006 int expo = (out.second == 0) ? 0 : (
int)std::floor(std::log10(std::abs(out.second)));
2009 out.first = (expo >= 0) ? round(out.first) :
round_to_decimal(out.first, -expo);
2010 }
else if (out.second != 0) {
2011 out.first = (expo >= 0) ? round(out.first) :
round_to_decimal(out.first, -expo + 1);
static void indent(ostringstream &buf, int indent_level)
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
R__EXTERN TSystem * gSystem
double getValV(const RooArgSet *) const override
Return value of object.
double evaluate() const override
Evaluate this PDF / function / constant. Needs to be overridden by all derived classes.
bool setData(RooAbsData &data, bool cloneData) override
ProgressMonitor(const ProgressMonitor &other, const char *name=nullptr)
~ProgressMonitor() override
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Interface for detailed printing of object.
TObject * clone(const char *newname) const override
std::shared_ptr< RooAbsCollection > vars
bool getParameters(const RooArgSet *observables, RooArgSet &outputSet, bool stripDisconnected) const override
Fills a list with leaf nodes in the arg tree starting with ourself as top node that don't match any o...
void applyWeightSquared(bool flag) override
Disables or enables the usage of squared weights.
void constOptimizeTestStatistic(ConstOpCode opcode, bool doAlsoTrackingOpt) override
Interface function signaling a request to perform constant term optimization.
ProgressMonitor(RooAbsReal &f, int interval=30)
static ProgressMonitor * me
double defaultErrorLevel() const override
static void interruptHandler(int signum)
StoredFitResult(RooFitResult *_fr)
std::shared_ptr< RooFitResult > fr
static int minos(RooAbsReal &nll, const RooFitResult &ufit, const char *parName="", const std::shared_ptr< ROOT::Fit::FitConfig > &_fitConfig=nullptr)
static std::shared_ptr< const RooFitResult > minimize(RooAbsReal &nll, const std::shared_ptr< ROOT::Fit::FitConfig > &fitConfig=nullptr, const std::shared_ptr< RooLinkedList > &nllOpts=nullptr)
static std::shared_ptr< RooLinkedList > createNLLOptions()
static TCanvas * hypoTest(RooWorkspace &w, const xRooFit::Asymptotics::PLLType &pllType=xRooFit::Asymptotics::Unknown)
static std::shared_ptr< ROOT::Fit::FitConfig > createFitConfig()
static std::pair< double, double > matchPrecision(const std::pair< double, double > &in)
This xRooNLLVar object has several special methods, e.g.
xRooFitResult minimize(const std::shared_ptr< ROOT::Fit::FitConfig > &=nullptr)
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
class implementing generic options for a numerical algorithm Just store the options in a map of strin...
Generic interface for defining configuration options of a numerical algorithm.
void SetValue(const char *name, double val)
generic methods for retrieving options
Common abstract base class for objects that represent a value and a "shape" in RooFit.
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
RooWorkspace * _myws
Prevent 'AlwaysDirty' mode for this node.
bool isConstant() const
Check if the "Constant" attribute is set.
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
RooWorkspace * workspace() const
virtual void constOptimizeTestStatistic(ConstOpCode opcode, bool doAlsoTrackingOpt=true)
Interface function signaling a request to perform constant term optimization.
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
RooFit::OwningPtr< RooArgSet > getVariables(bool stripDisconnected=true) const
Return RooArgSet with all variables (tree leaf nodes of expression tree)
virtual void applyWeightSquared(bool flag)
Disables or enables the usage of squared weights.
RooAbsArg * findServer(const char *name) const
Return server of this with name name. Returns nullptr if not found.
A space to attach TBranches.
RooAbsCollection * selectByAttrib(const char *name, bool value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
double getRealValue(const char *name, double defVal=0.0, bool verbose=false) const
Get value of a RooAbsReal stored in set with given name.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
Storage_t const & get() const
Const access to the underlying stl container.
void assignFast(const RooAbsCollection &other, bool setValDirty=true) const
Functional equivalent of assign() but assumes this and other collection have same layout.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void setAttribAll(const Text_t *name, bool value=true)
Set given attribute in each element of the collection by calling each elements setAttribute() functio...
Storage_t::size_type size() const
RooAbsArg * first() const
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
std::string contentsString() const
Return comma separated list of contained object names as STL string.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Abstract interface for all probability density functions.
Abstract base class for objects that represent a real value and implements functionality common to al...
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
virtual double defaultErrorLevel() const
virtual bool setData(RooAbsData &, bool=true)
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Structure printing.
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Implements a RooAbsBinning in terms of an array of boundary values, posing no constraints on the choi...
Named container for two doubles, two integers two object points and three string pointers that can be...
Container class to hold unbinned data.
RooRealVar * weightVar() const
Returns a pointer to the weight variable (if set).
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Int_t statusCodeHistory(UInt_t icycle) const
const char * statusLabelHistory(UInt_t icycle) const
const RooArgList & floatParsFinal() const
Return list of floating parameters after fit.
Int_t status() const
Return MINUIT status code.
UInt_t numStatusHistory() const
double minNll() const
Return minimized -log(L) value.
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
Wrapper class around ROOT::Math::Minimizer that provides a seamless interface between the minimizer f...
void optimizeConst(int flag)
If flag is true, perform constant term optimization on function being minimized.
auto fitter()
Return underlying ROOT fitter object.
RooFit::OwningPtr< RooFitResult > save(const char *name=nullptr, const char *title=nullptr)
Save and return a RooFitResult snapshot of current minimizer status.
int minos()
Execute MINOS.
int hesse()
Execute HESSE.
int minimize(const char *type, const char *alg=nullptr)
Minimise the function passed in the constructor.
void setStrategy(int istrat)
Change MINUIT strategy to istrat.
static RooMsgService & instance()
Return reference to singleton instance.
void setGlobalKillBelow(RooFit::MsgLevel level)
RooFit::MsgLevel globalKillBelow() const
Implementation of a RooCacheManager<RooAbsCacheElement> that specializes in the storage of cache elem...
void setNoRounding(bool flag=true)
Switch off/on rounding of x to the nearest integer.
Efficient implementation of a product of PDFs of the form.
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
Variable that can be changed from the outside.
void setVal(double value) override
Set value of variable to 'value'.
void setError(double value)
bool hasBinning(const char *name) const override
Returns true if variable has a binning named 'name'.
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
static RooAbsData * GenerateAsimovData(const RooAbsPdf &pdf, const RooArgSet &observables)
generate the asimov data for the observables (not the global ones) need to deal with the case of a si...
A RooAbsArg implementing string values.
Joins several RooAbsCategoryLValue objects into a single category.
bool setIndex(value_type index, bool printError=true) override
Set the value of the super category to the specified index.
Persistable container for RooFit projects.
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Using a TBrowser one can browse all ROOT objects.
void SetStatusText(const char *txt, Int_t col)
static TCanvas * MakeDefCanvas()
Static function to build a default canvas.
TClass instances represent classes, structs and namespaces in the ROOT type system.
TClass * IsA() const override
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
This class stores the date and time with a precision of one second in an unsigned 32 bit word (950130...
const char * AsString() const
Return the date & time as a string (ctime() format).
Describe directory structure in memory.
virtual TDirectory * GetDirectory(const char *namecycle, Bool_t printError=false, const char *funcname="GetDirectory")
Find a directory using apath.
virtual Bool_t IsWritable() const
virtual TDirectory * mkdir(const char *name, const char *title="", Bool_t returnExistingDirectory=kFALSE)
Create a sub-directory "a" or a hierarchy of sub-directories "a/b/c/...".
void SetName(const char *newname) override
Set the name for directory If the directory name is changed after the directory was written once,...
A TGraphErrors is a TGraph with error bars.
A TGraph is an object made of two arrays X and Y with npoints each.
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
void Draw(Option_t *chopt="") override
Draw this graph with its current attributes.
void SetNameTitle(const char *name="", const char *title="") override
Set graph name and title.
Book space in a file, create I/O buffers, to fill them, (un)compress them.
This class displays a legend box (TPaveText) containing several legend entries.
TMatrixTBase< Element > & ResizeTo(Int_t nrows, Int_t ncols, Int_t=-1) override
Set size of the matrix to nrows x ncols New dynamic elements are created, the overlapping part of the...
The TNamed class is the base class for all named ROOT classes.
TObject * Clone(const char *newname="") const override
Make a clone of an object using the Streamer facility.
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
const char * GetName() const override
Returns name of object.
Mother of all ROOT objects.
virtual const char * GetName() const
Returns name of object.
virtual TObject * DrawClone(Option_t *option="") const
Draw a clone of this object in the current selected pad with: gROOT->SetSelectedPad(c1).
virtual void Delete(Option_t *option="")
Delete this object.
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
virtual void Draw(Option_t *option="")
Default Draw method for all objects.
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
virtual UInt_t Integer(UInt_t imax)
Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
Double_t RealTime()
Stop the stopwatch (if it is running) and return the realtime (in seconds) passed between the start a...
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void Continue()
Resume a stopped stopwatch.
Provides iteration through tokens of a given string.
Bool_t NextToken()
Get the next token, it is stored in this TString.
Double_t Atof() const
Return floating-point value contained in string.
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
const char * Data() const
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
TDatime GetTime() const
Get time from UUID.
const char * AsString() const
Return UUID as string. Copy string immediately since it will be reused.
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Offset(std::string const &mode)
RooCmdArg Optimize(Int_t flag=2)
RooCmdArg Extended(bool flag=true)
RooCmdArg ExpectedData(bool flag=true)
double nll(double pdf, double weight, int binnedL, int doBinOffset)
MsgLevel
Verbosity level for RooMsgService::StreamConfig in RooMsgService.
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Sort the n elements of the array a of generic templated type Element.
#define BEGIN_XROOFIT_NAMESPACE
#define END_XROOFIT_NAMESPACE
double round_to_decimal(double value, int decimal_places)
double round_to_digits(double value, int digits)