20#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
21#define protected public
73std::shared_ptr<RooLinkedList> xRooFit::sDefaultNLLOptions =
nullptr;
74std::shared_ptr<ROOT::Fit::FitConfig> xRooFit::sDefaultFitConfig =
nullptr;
76const char *xRooFit::GetVersion()
80const char *xRooFit::GetVersionDate()
87 return RooCmdArg(
"ReuseNLL", flag, 0, 0, 0,
nullptr,
nullptr,
nullptr,
nullptr);
97 return RooCmdArg(
"StrategySequence", 0, 0, 0, 0, val);
105xRooNLLVar xRooFit::createNLL(
const std::shared_ptr<RooAbsPdf> pdf,
const std::shared_ptr<RooAbsData>
data,
113 return createNLL(std::shared_ptr<RooAbsPdf>(&pdf, [](
RooAbsPdf *) {}),
131 return createNLL(pdf,
data,
l);
134std::shared_ptr<const RooFitResult>
136 const std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> &
data,
144std::shared_ptr<const RooFitResult> xRooFit::fitTo(
RooAbsPdf &pdf,
145 const std::pair<RooAbsData *, const RooAbsCollection *> &
data,
153std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>>
157 std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> out;
163 auto _allVars = std::unique_ptr<RooAbsCollection>(pdf.
getVariables());
164 auto _snap = std::unique_ptr<RooAbsCollection>(_allVars->snapshot());
165 *_allVars = fr->constPars();
166 *_allVars = fr->floatParsFinal();
169 auto _globs = std::unique_ptr<RooAbsCollection>(fr->constPars().selectByAttrib(
"global",
true));
180 std::function<std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooArgSet>>(
RooAbsPdf *)> genSubPdf;
183 std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooArgSet>> _out;
186 std::unique_ptr<RooArgSet> _obs(_pdf->getVariables());
187 _obs->remove(fr->constPars(),
true,
true);
188 _obs->remove(fr->floatParsFinal(),
true,
true);
190 if (!_globs->empty()) {
195 std::unique_ptr<RooArgSet> globs(_pdf->getObservables(t));
196 globs->snapshot(*toy_gobs);
197 if (!toy_gobs->
empty() &&
201 *toy_gobs = *std::unique_ptr<RooDataSet>(_pdf->generate(*globs, 1))->
get();
206 for (
auto thePdf : pp->pdfList()) {
207 auto gob = std::unique_ptr<RooArgSet>(thePdf->getObservables(*globs));
210 if (gob->size() > 1) {
211 Warning(
"generate",
"%s contains multiple global obs: %s", thePdf->GetName(),
212 gob->contentsString().c_str());
216 std::unique_ptr<RooArgSet> cpars(thePdf->getParameters(*globs));
218 bool foundServer =
false;
226 !(cClass && strcmp(cClass->
GetName(),
"SimpleGaussianConstraint") == 0)) {
229 <<
"xRooFit::generateFrom : constraint term " << thePdf->GetName() <<
" of type "
230 << className <<
" is a non-supported type - result might be not correct " << std::endl;
248 <<
"xRooFit::generateFrom : constraint term " << thePdf->
GetName()
249 <<
" has no direct dependence on global observable- cannot generate it " << std::endl;
261 for (
RooAbsArg *a2 : thePdf->servers()) {
267 if (thetaGamma ==
nullptr) {
269 <<
"xRooFit::generateFrom : constraint term " << thePdf->
GetName()
270 <<
" is a Gamma distribution and no server named theta is found. Assume that the Gamma "
275 for (
RooAbsArg *a2 : thePdf->servers()) {
283 <<
"xRooFit::generateFrom : constraint term " << thePdf->
GetName()
284 <<
" constraint term has more server depending on nuisance- cannot generate it "
289 if (thetaGamma && thetaGamma->
getVal() > 0) {
300 <<
"xRooFit::generateFrom : can't find nuisance for constraint term - global "
301 "observables will not be set to Asimov value "
302 << thePdf->GetName() <<
" glob = " << rrv.
GetName() << std::endl;
303 std::cerr <<
"Parameters: " << std::endl;
305 std::cerr <<
"Observables: " << std::endl;
310 Error(
"generate",
"Cannot generate global observables, pdf is: %s::%s", _pdf->ClassName(),
316 _out.second.reset(toy_gobs);
323 _out.first = std::make_unique<RooDataSet>(
324 uuid,
TString::Format(
"%s %s", _pdf->GetTitle(), (expected) ?
"Expected" :
"Toy"), *_obs,
327 for (
auto &
c : s->indexCat()) {
328#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 22, 00)
329 std::string cLabel =
c.first;
331 std::string cLabel =
c->GetName();
333 auto p = s->getPdf(cLabel.c_str());
336 auto toy = genSubPdf(
p);
337 if (toy.second && _out.second)
338 *
const_cast<RooArgSet *
>(_out.second.get()) = *toy.second;
339 _obs->setCatLabel(s->indexCat().GetName(), cLabel.c_str());
340 for (
int i = 0; i < toy.first->numEntries(); i++) {
341 *_obs = *toy.first->get(i);
342 _out.first->add(*_obs, toy.first->weight());
348 std::map<RooRealVar *, std::shared_ptr<RooAbsBinning>> binnings;
350 for (
auto &o : *_obs) {
354 if (
auto res = _pdf->binBoundaries(*
r, -std::numeric_limits<double>::infinity(),
355 std::numeric_limits<double>::infinity())) {
356 binnings[
r] = std::shared_ptr<RooAbsBinning>(
r->getBinning().clone(
r->getBinning().GetName()));
358 std::vector<double> boundaries;
359 boundaries.reserve(res->size());
360 for (
auto &rr : *res) {
361 if (boundaries.empty() || std::abs(boundaries.back() - rr) > 1
e-3 ||
362 std::abs(boundaries.back() - rr) > 1
e-5 * boundaries.back())
363 boundaries.push_back(rr);
368 if(boundaries.size() < res->size()) {
369 r->setBinning(
RooBinning(boundaries.size() - 1, &boundaries[0]));
372 }
else if (
r->numBins(
r->getBinning().GetName()) == 0 && expected) {
374 binnings[
r] = std::shared_ptr<RooAbsBinning>(
r->getBinning().clone(
r->getBinning().GetName()));
385 _out.first = std::make_unique<RooDataSet>(
"",
"Toy", _tmp,
RooFit::WeightVar(
"weightVar"));
386 _out.first->add(_tmp);
388 if (_pdf->canBeExtended()) {
398 _out.first = std::unique_ptr<RooDataSet>{_pdf->generate(*_obs,
RooFit::ExpectedData(expected))};
402 _out.first->SetName(
TUUID().AsString());
404 for (
auto &
b : binnings) {
406 auto binning =
b.second;
407 v->setBinning(*binning);
410 auto x =
dynamic_cast<RooRealVar *
>(_out.first->get()->find(
v->GetName()));
411 auto r =
x->getRange();
412 if (
r.first > binning->lowBound())
413 x->setMin(binning->lowBound());
414 if (
r.second < binning->highBound())
415 x->setMax(binning->highBound());
420 out = genSubPdf(&pdf);
421 out.first->SetName(expected ? (
TString(fr->GetName()) +
"_asimov") : uuid);
425 out.first->setGlobalObservables(*out.second);
429#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
432 w->setStringAttribute(
"fitResult", fr->GetName());
433 w->setAttribute(
"expected", expected);
443#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
444 auto _ws = pdf.
_myws;
451 for (
auto obj : _ws->components()) {
452 for (
int i = 0; i < obj->numCaches(); i++) {
458 p->setNormRange(
p->normRange());
460 obj->setValueDirty();
468std::shared_ptr<RooLinkedList> xRooFit::createNLLOptions()
474 for (
auto opt : *defaultNLLOptions()) {
475 out->Add(opt->Clone(
nullptr));
481std::shared_ptr<RooLinkedList> xRooFit::defaultNLLOptions()
483 if (sDefaultNLLOptions)
484 return sDefaultNLLOptions;
490#if ROOT_VERSION_CODE < ROOT_VERSION(6, 41, 00)
494 return sDefaultNLLOptions;
497std::shared_ptr<ROOT::Fit::FitConfig> xRooFit::createFitConfig()
499 return std::make_shared<ROOT::Fit::FitConfig>(*defaultFitConfig());
502std::shared_ptr<ROOT::Fit::FitConfig> xRooFit::defaultFitConfig()
504 if (sDefaultFitConfig)
505 return sDefaultFitConfig;
506 sDefaultFitConfig = std::make_shared<ROOT::Fit::FitConfig>();
507 auto &fitConfig = *sDefaultFitConfig;
508 fitConfig.SetParabErrors(
true);
509 fitConfig.MinimizerOptions().SetMinimizerType(
"Minuit2");
510 fitConfig.MinimizerOptions().SetErrorDef(0.5);
511 fitConfig.SetParabErrors(
true);
512 fitConfig.SetMinosErrors(
true);
513 fitConfig.MinimizerOptions().SetMaxFunctionCalls(
515 fitConfig.MinimizerOptions().SetMaxIterations(-1);
516 fitConfig.MinimizerOptions().SetStrategy(-1);
520 fitConfig.MinimizerOptions().SetPrintLevel(-2);
523 auto extraOpts =
const_cast<ROOT::Math::IOptions *
>(fitConfig.MinimizerOptions().ExtraOptions());
524#if ROOT_VERSION_CODE < ROOT_VERSION(6, 41, 00)
525 extraOpts->
SetValue(
"OptimizeConst", 2);
528#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 29, 00)
532 extraOpts->SetValue(
"HesseStrategySequence",
"23");
534 extraOpts->SetValue(
"StrategySequence",
"0s01s12s2m");
535 extraOpts->SetValue(
"HesseStrategySequence",
"2");
540 extraOpts->SetValue(
"LogSize", 0);
541 extraOpts->SetValue(
"BoundaryCheck",
543 extraOpts->SetValue(
"TrackProgress", 30);
550 return sDefaultFitConfig;
555 return const_cast<ROOT::Math::IOptions *
>(defaultFitConfig()->MinimizerOptions().ExtraOptions());
566 std::cerr << msg << std::endl;
577 std::cout << msg << std::endl;
588 if (signum == SIGINT) {
589 printCout(
"Minimization interrupted ... will exit as soon as possible");
600 fFunc(
"func",
"func", this,
f),
606 vars.reset(std::unique_ptr<RooAbsCollection>(
f.getVariables())->selectByAttrib(
"Constant",
false));
635#if ROOT_VERSION_CODE < ROOT_VERSION(6, 41, 00)
636 void constOptimizeTestStatistic(ConstOpCode opcode,
bool doAlsoTrackingOpt)
override
638 fFunc->constOptimizeTestStatistic(opcode, doAlsoTrackingOpt);
644 throw std::runtime_error(
"Keyboard interrupt");
645 return std::numeric_limits<double>::quiet_NaN();
648 if (
prevMin == std::numeric_limits<double>::infinity()) {
652 if (!std::isnan(out)) {
664 std::stringstream sout;
673 nRequired *= (nRequired - 1);
685 std::vector<std::pair<double, std::string>> parDeltas;
688 parDeltas.emplace_back(std::pair<double, std::string>(
691 std::sort(parDeltas.begin(), parDeltas.end(),
692 [](
auto &left,
auto &right) { return std::abs(left.first) > std::abs(right.first); });
694 for (i = 0; i < std::min(3,
int(parDeltas.size())); i++) {
695 if (parDeltas.at(i).first == 0)
699 sout << parDeltas.at(i).second << (parDeltas.at(i).first >= 0 ?
"+" :
"-") <<
"="
700 << std::abs(parDeltas.at(i).first) <<
"(" <<
minPars.
getRealValue(parDeltas.at(i).second.c_str())
703 if (i <
int(parDeltas.size()) && parDeltas.at(i).first != 0)
708 if (
gROOT->FromPopUp() &&
gROOT->GetListOfBrowsers()->At(0)) {
709 auto browser =
dynamic_cast<TBrowser *
>(
gROOT->GetListOfBrowsers()->At(0));
710 std::string status = sout.str();
713 std::string status_part;
714 if (status.find(
" : ") != std::string::npos) {
715 status_part = status.substr(0, status.find(
" : "));
716 status = status.substr(status.find(
" : ") + 3);
718 status_part = status;
721 browser->SetStatusText(status_part.c_str(), col);
740 mutable double minVal = std::numeric_limits<double>::infinity();
741 mutable double prevMin = std::numeric_limits<double>::infinity();
750 std::shared_ptr<RooAbsCollection>
vars;
763 const std::shared_ptr<ROOT::Fit::FitConfig> &_fitConfig,
764 const std::shared_ptr<RooLinkedList> &nllOpts)
768 auto &fitConfig = *myFitConfig;
772 TString resultTitle = nll.getStringAttribute(
"fitresultTitle");
774 if (resultTitle ==
"")
779 if (nll.getStringAttribute(
"userPars")) {
780 TStringToken st(nll.getStringAttribute(
"userPars"),
",");
783 TString parVal = nll.getStringAttribute(parName);
792 auto _nllVars = std::unique_ptr<RooAbsCollection>(_nll->getVariables());
794 std::unique_ptr<RooAbsCollection> constPars(_nllVars->selectByAttrib(
"Constant",
true));
795 constPars->add(fUserPars,
true);
796 std::unique_ptr<RooAbsCollection> floatPars(_nllVars->selectByAttrib(
"Constant",
false));
799 double boundaryCheck = 0;
803#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 29, 00)
804 int hesseStrategy = 3;
806 int hesseStrategy = 2;
808 if (fitConfig.MinimizerOptions().ExtraOptions()) {
809 fitConfig.MinimizerOptions().ExtraOptions()->GetNamedValue(
"StrategySequence", s);
810 fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue(
"TrackProgress", _progress);
811 fitConfig.MinimizerOptions().ExtraOptions()->GetRealValue(
"BoundaryCheck", boundaryCheck);
812 fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue(
"LogSize", logSize);
813 fitConfig.MinimizerOptions().ExtraOptions()->GetIntValue(
"HesseStrategy", hesseStrategy);
814 fitConfig.MinimizerOptions().ExtraOptions()->GetNamedValue(
"HesseStrategySequence", hs);
824 if (
auto nllDir = cacheDir->
GetDirectory(nll.GetName()); nllDir) {
825 if (
auto keys = nllDir->GetListOfKeys(); keys) {
826 for (
auto &&k : *keys) {
828 if (cl->InheritsFrom(
"RooFitResult")) {
830 nllDir->GetList() ?
dynamic_cast<StoredFitResult *
>(nllDir->GetList()->FindObject(k->GetName()))
833 (storedFr) ? storedFr->
fr.get() :
dynamic_cast<TKey *
>(k)->ReadObject<RooFitResult>();
837 nllDir->Add(storedFr);
842 if (!cachedFit->floatParsFinal().equals(*floatPars)) {
845 for (
auto &
p : *constPars) {
852 _p->getCurrentIndex() !=
c->getCurrentIndex()) {
861 if (
auto _p =
dynamic_cast<RooAbsReal *
>(cachedFit->constPars().find(
p->
GetName())); _p) {
864 if (!_p->getAttribute(
"global") && std::abs(_p->getVal() -
v->getVal()) > 1
e-12) {
887 if (nll.getAttribute(
"readOnly"))
890 int printLevel = fitConfig.MinimizerOptions().PrintLevel();
896 if (floatPars->empty() || fitConfig.MinimizerOptions().MaxFunctionCalls() == 1) {
897 std::shared_ptr<RooFitResult>
result;
899 parsList.
add(*floatPars);
901 result = std::make_shared<RooFitResult>();
903 result->SetTitle(resultTitle);
904 result->setFinalParList(parsList);
905 result->setInitParList(parsList);
909 result->setCovarianceMatrix(
d);
910 result->setCovQual(floatPars->empty() ? 3 : -1);
911 result->setMinNLL(_nll->getVal());
913 result->setStatus(floatPars->empty() ? 0 : 1);
915 std::vector<std::pair<std::string, int>> statusHistory;
916 statusHistory.emplace_back(std::make_pair(
"EVAL",
result->status()));
917 result->setStatusHistory(statusHistory);
922 cacheDir->
mkdir(nll.GetName());
923 if (
auto dir = cacheDir->
GetDirectory(nll.GetName()); dir) {
926 if (strlen(nllOpts->GetName()) == 0) {
929 if (!dir->FindKey(nllOpts->GetName())) {
930 dir->WriteObject(nllOpts.get(), nllOpts->GetName());
942 std::shared_ptr<RooFitResult> out;
946 for (
auto p : *floatPars) {
947 if (
p->isCategory()) {
951 if (!floatCats.
empty()) {
952 RooSuperCategory allCats(
"floatCats",
"Floating categorical parameters", floatCats);
953 std::unique_ptr<RooAbsCollection> _snap(floatCats.
snapshot());
956 std::shared_ptr<const RooFitResult> bestFr;
957 for (
auto c : allCats) {
959 Info(
"minimize",
"Minimizing with discrete %s",
c.first.c_str());
960 auto fr =
minimize(nll, _fitConfig, nllOpts);
962 Warning(
"minimize",
"Minimization with discrete %s failed",
c.first.c_str());
965 if (!bestFr || fr->minNll() < bestFr->minNll()) {
976 out = std::make_shared<RooFitResult>(*bestFr);
977 const_cast<RooArgList &
>(out->floatParsFinal())
978 .addClone(*std::unique_ptr<RooAbsCollection>(out->constPars().selectCommon(floatCats)));
979 const_cast<RooArgList &
>(out->floatParsInit()).addClone(*_snap);
980 const_cast<RooArgList &
>(out->constPars()).remove(floatCats);
984 bool restore = !fitConfig.UpdateAfterFit();
985 bool minos = fitConfig.MinosErrors();
988 int strategy = fitConfig.MinimizerOptions().Strategy();
990 if (_progress && printLevel >= -2) {
994 auto logger = (logSize > 0) ? std::make_unique<cout_redirect>(logs, logSize) :
nullptr;
995 std::unique_ptr<RooMinimizer> _minimizerPtr = std::make_unique<RooMinimizer>(*_nll);
997 _minimizer->
fitter()->Config() = fitConfig;
1009 bool autoMaxCalls = (_minimizer->
fitter()->Config().MinimizerOptions().MaxFunctionCalls() == 0);
1011 _minimizer->
fitter()->Config().MinimizerOptions().SetMaxFunctionCalls(
1012 500 * floatPars->size() * floatPars->size());
1014 if (_minimizer->
fitter()->Config().MinimizerOptions().MaxIterations() == 0) {
1015 _minimizer->
fitter()->Config().MinimizerOptions().SetMaxIterations(500 * floatPars->size());
1018 std::unique_ptr<RooAbsCollection> floatInitVals(floatPars->snapshot());
1019 bool hesse = _minimizer->
fitter()->Config().ParabErrors();
1020 _minimizer->
fitter()->Config().SetParabErrors(
1022 _minimizer->
fitter()->Config().SetMinosErrors(
false);
1023 _minimizer->
fitter()->Config().SetUpdateAfterFit(
true);
1025 std::vector<std::pair<std::string, int>> statusHistory;
1030 TString actualFirstMinimizer = _minimizer->
fitter()->Config().MinimizerType();
1033#if ROOT_VERSION_CODE < ROOT_VERSION(6, 41, 00)
1034 int constOptimize = 2;
1035 _minimizer->
fitter()->Config().MinimizerOptions().ExtraOptions()->GetValue(
"OptimizeConst", constOptimize);
1036 if (constOptimize) {
1051 nll.constOptimizeTestStatistic(RooAbsArg::DeActivate);
1055 TString minim = _minimizer->
fitter()->Config().MinimizerType();
1056 TString algo = _minimizer->
fitter()->Config().MinimizerAlgoType();
1057 if (minim ==
"Minuit2") {
1058 if (strategy == -1) {
1061 sIdx = m_strategy.
Index(
'0' + strategy);
1064 Warning(
"minimize",
"Strategy %d not specified in StrategySequence %s ... defaulting to start of sequence",
1065 strategy, m_strategy.
Data());
1068 }
else if (minim ==
"Minuit")
1069 sIdx = m_strategy.
Index(
'm');
1074 while (tries < maxtries && sIdx != -1) {
1075 if (m_strategy(sIdx) ==
'm') {
1077 algo =
"migradImproved";
1078 }
else if (m_strategy(sIdx) ==
's') {
1080 }
else if (m_strategy(sIdx) ==
'h') {
1082 }
else if (m_strategy(sIdx) ==
'r') {
1086 *floatPars = *floatInitVals;
1087 std::unique_ptr<RooMinimizer> _minimizerPtr2 = std::make_unique<RooMinimizer>(*_nll);
1088 auto initPars = _minimizerPtr2->fitter()->Config().ParamsSettings();
1089 auto initOpts = _minimizerPtr2->fitter()->Config().MinimizerOptions();
1090 _minimizerPtr2->fitter()->Config() = _minimizer->
fitter()->Config();
1091 _minimizerPtr2->fitter()->Config().SetParamsSettings({});
1092 _minimizerPtr = std::move(_minimizerPtr2);
1093 _minimizer = _minimizerPtr.get();
1095 statusHistory.emplace_back(
"Reset", 0);
1098 fff->prevMin = fff->minVal;
1102 strategy =
int(m_strategy(sIdx) -
'0');
1108 fff->fState = minim + algo + std::to_string(_minimizer->
fitter()->Config().MinimizerOptions().Strategy());
1111 status = _minimizer->
minimize(minim, algo);
1112 }
catch (
const std::exception &
e) {
1113 std::cerr <<
"Exception while minimizing: " <<
e.what() << std::endl;
1115 if (first && actualFirstMinimizer != _minimizer->
fitter()->Config().MinimizerType())
1116 actualFirstMinimizer = _minimizer->
fitter()->Config().MinimizerType();
1122 throw std::runtime_error(
"Keyboard interrupt while minimizing");
1126 status = _minimizer->
fitter()
1129 minim = _minimizer->
fitter()->Config().MinimizerType();
1130 statusHistory.emplace_back(_minimizer->
fitter()->Config().MinimizerType() +
1131 _minimizer->
fitter()->Config().MinimizerAlgoType() +
1132 std::to_string(_minimizer->
fitter()->Config().MinimizerOptions().Strategy()),
1134 if (status % 1000 == 0)
1137 if (status == 4 && minim !=
"Minuit") {
1138 if (printLevel >= -1) {
1139 Warning(
"fitTo",
"%s Hit max function calls of %d", fitName.
Data(),
1140 _minimizer->
fitter()->Config().MinimizerOptions().MaxFunctionCalls());
1143 if (printLevel >= -1)
1144 Warning(
"fitTo",
"will try doubling this");
1145 _minimizer->
fitter()->Config().MinimizerOptions().SetMaxFunctionCalls(
1146 _minimizer->
fitter()->Config().MinimizerOptions().MaxFunctionCalls() * 2);
1147 _minimizer->
fitter()->Config().MinimizerOptions().SetMaxIterations(
1148 _minimizer->
fitter()->Config().MinimizerOptions().MaxIterations() * 2);
1156 if (printLevel >= -1) {
1158 fitName.
Data(), _minimizer->
fitter()->Config().MinimizerType().c_str(),
1159 _minimizer->
fitter()->Config().MinimizerAlgoType().c_str(), status,
1160 _minimizer->
fitter()->Result().Edm(),
1161 _minimizer->
fitter()->Config().MinimizerOptions().Tolerance(),
1162 _minimizer->
fitter()->Config().MinimizerOptions().Strategy(), tries)
1167 if (sIdx == m_strategy.
Length() - 1) {
1174 auto mini_sIdx = sIdx;
1187 if (printLevel >= -1 && status != 0) {
1188 Warning(
"fitTo",
"%s final status is %d", fitName.
Data(), status);
1197 int miniStrat = _minimizer->
fitter()->Config().MinimizerOptions().Strategy();
1198 double dCovar = std::numeric_limits<double>::quiet_NaN();
1205 if (hesse && m_hessestrategy.
Length() != 0 &&
1206 (m_strategy(sIdx) ==
'h' || (_minimizer->
fitter()->Result().IsValid()))) {
1229 if (hesseStrategy == -1) {
1232 sIdx = m_hessestrategy.
Index(
'0' + hesseStrategy);
1236 "HesseStrategy %d not specified in HesseStrategySequence %s ... defaulting to start of sequence",
1237 hesseStrategy, m_hessestrategy.
Data());
1240 while (sIdx != -1) {
1241 hesseStrategy =
int(m_hessestrategy(sIdx) -
'0');
1243 if (strategy == 2 && hesseStrategy == 2) {
1245 if (_minimizer->
fitter()->GetMinimizer()->CovMatrixStatus() == 3) {
1248 if (sIdx >= m_hessestrategy.
Length() - 1) {
1255 _minimizer->
fitter()->Config().MinimizerOptions().SetStrategy(hesseStrategy);
1260 fff->fState =
TString::Format(
"Hesse%d", _minimizer->
fitter()->Config().MinimizerOptions().Strategy());
1261 fff->counter2 = fff->counter;
1271 auto _status = _minimizer->
hesse();
1294 statusHistory.push_back(std::pair<std::string, int>(
1295 TString::Format(
"Hesse%d", _minimizer->
fitter()->Config().MinimizerOptions().Strategy()), _status));
1299 throw std::runtime_error(
"Keyboard interrupt while hesse calculating");
1301 if ((_status != 0 || _minimizer->
fitter()->GetMinimizer()->CovMatrixStatus() != 3) && status == 0 &&
1304 _minimizer->
fitter()->GetMinimizer()->CovMatrixStatus())
1308 if (_status == 0 && _minimizer->
fitter()->GetMinimizer()->CovMatrixStatus() == 3) {
1311 }
else if (_status == 0) {
1313 statusHistory.back().second = _minimizer->
fitter()->GetMinimizer()->CovMatrixStatus();
1316 if (sIdx >= m_hessestrategy.
Length() - 1) {
1323 if (
gEnv->
GetValue(
"XRooFit.ResumeInvalidFits",
false) &&
1324 (statusHistory.back().second == 1 || statusHistory.back().second == 2) &&
1325 mini_sIdx < (m_strategy.
Length() - 1)) {
1327 goto resetMinimization;
1332 if (status == 0 &&
minos) {
1333 if (std::unique_ptr<RooAbsCollection> mpars(floatPars->selectByAttrib(
"minos",
true)); !mpars->empty()) {
1335 fff->fState =
"Minos";
1337 fff->prevMin = fff->minVal;
1339 auto _status = _minimizer->
minos(*mpars);
1340 statusHistory.push_back(std::pair(
"Minos", _status));
1346 out = std::unique_ptr<RooFitResult>{_minimizer->
save(fitName, resultTitle)};
1352 if (out->status() == -1 && !_minimizer->
fitter()->Result().IsValid() && _minimizer->
fitter()->Result().Status()) {
1353 out->setStatus(_minimizer->
fitter()->Result().Status());
1358 if (out->status() == 0 && out->covQual() != 3 && hesse) {
1359 if (out->covQual() == 2) {
1367 if (printLevel >= -2 && miniStrat < _minimizer->fitter()->Config().MinimizerOptions().Strategy() && hesse &&
1368 out->edm() > _minimizer->
fitter()->Config().MinimizerOptions().Tolerance() * 1
e-2 && out->status() != 3) {
1371 std::stringstream ss;
1372 ss <<
"Warning: post-Hesse edm " << out->edm()
1373 <<
" > 10xMaxEDM (MaxEDM=" << _minimizer->
fitter()->Config().MinimizerOptions().Tolerance() * 1
e-3
1374 <<
"). Consider increasing your minimization strategy";
1381 out->setStatusHistory(statusHistory);
1384 const_cast<RooArgList &
>(out->constPars()).addClone(fUserPars,
true);
1386 if (!std::isnan(dCovar)) {
1388 .addClone(
RooRealVar(
".dCovar",
"dCovar from minimization", dCovar),
true);
1391 if (boundaryCheck) {
1394 int limit_status = 0;
1395 std::string listpars;
1396 for (
auto *
v : dynamic_range_cast<RooRealVar *>(*floatPars)) {
1399 double vRange =
v->getMax() -
v->getMin();
1400 if (
v->getMin() >
v->getVal() - vRange * boundaryCheck ||
1401 v->getMax() <
v->getVal() + vRange * boundaryCheck) {
1405 auto tmp =
v->getVal();
1406 v->setVal(
v->getMin());
1407 double boundary_nll = _nll->getVal();
1408 if (boundary_nll <= out->minNll()) {
1409 static_cast<RooRealVar *
>(out->floatParsFinal().find(
v->GetName()))->
setVal(
v->getMin());
1410 out->setMinNLL(boundary_nll);
1418 if (
v->hasRange(
"physical"))
1420 listpars +=
v->GetName();
1423 (
v->getMin() >
v->getVal() -
v->getError() ||
v->getMax() <
v->getVal() +
v->getError())) {
1424 if (printLevel >= 0) {
1425 Info(
"minimize",
"PARLIM: %s (%f +/- %f) range (%f - %f)",
v->GetName(),
v->getVal(),
v->getError(),
1426 v->getMin(),
v->getMax());
1428 limit_status = 9000;
1431 if (limit_status == 900) {
1432 if (printLevel >= 0) {
1433 Warning(
"minimize",
"BOUNDCHK: Parameters within %g%% limit in fit result: %s", boundaryCheck * 100,
1436 }
else if (limit_status > 0) {
1437 if (printLevel >= 0)
1438 Warning(
"minimize",
"BOUNDCHK: Parameters near limit in fit result");
1442 statusHistory.emplace_back(
"BOUNDCHK", limit_status);
1443 out->setStatusHistory(statusHistory);
1444 out->setStatus(out->status() + limit_status);
1470 out->setMinNLL(_nll->getVal());
1473 for (
auto o : out->floatParsFinal()) {
1475 v && !
v->
getAttribute(
"minos") && !
v->getAttribute(
"xminos") && !
v->getAttribute(
"xMinos"))
1476 v->removeAsymError();
1480 if (fitConfig.MinimizerOptions().MinimizerType() != actualFirstMinimizer) {
1481 fitConfig.MinimizerOptions().SetMinimizerType(actualFirstMinimizer);
1484 if (_progress && printLevel >= -2) {
1489 if (out && out->status() == 0 &&
minos) {
1491 for (
auto label : {
"xminos",
"xMinos"}) {
1492 std::unique_ptr<RooAbsCollection> pars(floatPars->selectByAttrib(label,
true));
1493 for (
auto p : *pars) {
1494 Info(
"minimize",
"Computing xminos error for %s",
p->
GetName());
1498 *floatPars = out->floatParsFinal();
1503 *floatPars = out->floatParsInit();
1506 if (out && !logs.empty()) {
1508#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00)
1509 const_cast<RooArgList &
>(out->constPars()).addOwned(std::make_unique<RooStringVar>(
".log",
"log", logs.c_str()));
1515 if (out && cacheDir && cacheDir->
IsWritable()) {
1519 cacheDir->
mkdir(nll.GetName());
1520 if (
auto dir = cacheDir->
GetDirectory(nll.GetName()); dir) {
1523 if (strlen(nllOpts->GetName()) == 0) {
1526 if (!dir->FindKey(nllOpts->GetName())) {
1527 dir->WriteObject(nllOpts.get(), nllOpts->GetName());
1532 std::string configName;
1533 if (!fitConfig.MinimizerOptions().ExtraOptions()->GetValue(
"Name", configName)) {
1534 auto extraOpts =
const_cast<ROOT::Math::IOptions *
>(fitConfig.MinimizerOptions().ExtraOptions());
1536 extraOpts->SetValue(
"Name", configName.data());
1538 if (!dir->GetKey(configName.data())) {
1539 dir->WriteObject(&fitConfig, configName.data());
1542#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00)
1544 .addOwned(std::make_unique<RooStringVar>(
".fitConfigName",
"fitConfigName", configName.c_str()));
1547 .addOwned(*
new RooStringVar(
".fitConfigName",
"fitConfigName", configName.c_str()));
1549 dir->WriteObject(out.get(), out->GetName());
1563 const std::shared_ptr<ROOT::Fit::FitConfig> &_fitConfig)
1566 auto par =
dynamic_cast<RooRealVar *
>(std::unique_ptr<RooArgSet>(nll.getVariables())->find(parName));
1575 auto &fitConfig = *myFitConfig;
1577 bool pErrs = fitConfig.ParabErrors();
1578 fitConfig.SetParabErrors(
false);
1579 double mErrs = fitConfig.MinosErrors();
1580 fitConfig.SetMinosErrors(
false);
1582 double val_best = par_hat->getVal();
1583 double val_err = (par_hat->hasError() ? par_hat->getError() : -1);
1584 double orig_err = val_err;
1585 double nll_min = ufit.
minNll();
1589 bool isConst = par->isConstant();
1590 par->setConstant(
true);
1592 auto findValue = [&](
double val_guess,
double N_sigma = 1,
double precision = 0.002,
int printLevel = 0) {
1595 double sigma_guess = std::abs((val_guess - val_best) / N_sigma);
1598 10 * precision * sigma_guess;
1599 bool lastOverflow =
false;
1600 bool lastUnderflow =
false;
1601 while (std::abs(val_pre - val_guess) > precision * sigma_guess) {
1602 val_pre = val_guess;
1603 if (val_guess > 0 && par->getMax() < val_guess)
1604 par->setMax(2 * val_guess);
1605 if (val_guess < 0 && par->getMin() > val_guess)
1606 par->setMin(2 * val_guess);
1607 par->setVal(val_guess);
1612 return std::numeric_limits<double>::quiet_NaN();
1614 double nll_val =
result->minNll();
1615 status +=
result->status() * 10;
1616 tmu = 2 * (nll_val - nll_min);
1617 sigma_guess = std::abs(val_guess - val_best) / sqrt(tmu);
1621 std::cout <<
"Warning: Alternative best-fit of " << par->GetName() <<
" @ " << val_guess <<
" vs "
1622 << val_best <<
" (delta=" << tmu / 2. <<
")" << std::endl;
1623 double new_guess = val_guess + (val_guess - val_best);
1624 val_best = val_guess;
1625 val_guess = new_guess;
1626 sigma_guess = std::abs((val_guess - val_best) / N_sigma);
1627 val_pre = val_guess - 10 * precision * sigma_guess;
1628 status = (status / 10) * 10 + 1;
1632 double corr = (val_pre - val_best - N_sigma * sigma_guess);
1637 if (printLevel > 1) {
1641 std::cout <<
"NLL min: " << nll_min << std::endl;
1642 std::cout <<
"N_sigma*sigma(pre): " << std::abs(val_pre - val_best) << std::endl;
1643 std::cout <<
"sigma(guess): " << sigma_guess << std::endl;
1644 std::cout <<
"par(guess): " << val_guess + corr << std::endl;
1645 std::cout <<
"true val: " << val_best << std::endl;
1646 std::cout <<
"tmu: " << tmu << std::endl;
1647 std::cout <<
"Precision: " << sigma_guess * precision << std::endl;
1648 std::cout <<
"Correction: " << (-corr < 0 ?
" " :
"") << -corr << std::endl;
1649 std::cout <<
"N_sigma*sigma(guess): " << std::abs(val_guess - val_best) << std::endl;
1650 std::cout << std::endl;
1652 if (val_guess > par->getMax()) {
1654 val_guess = par->getMin();
1657 lastOverflow =
true;
1658 lastUnderflow =
false;
1659 val_guess = par->getMax() - 1
e-12;
1660 }
else if (val_guess < par->getMin()) {
1661 if (lastUnderflow) {
1662 val_guess = par->getMin();
1665 lastOverflow =
false;
1666 lastUnderflow =
true;
1667 val_guess = par->getMin() + 1
e-12;
1669 lastUnderflow =
false;
1670 lastOverflow =
false;
1675 status = (status / 10) * 10 + 3;
1683 status = (status / 10) * 10 + 2;
1684 }
else if (lastUnderflow) {
1687 status = (status / 10) * 10 + 2;
1691 std::cout <<
"Found sigma for nll " << nll.GetName() <<
": " << (val_guess - val_best) / N_sigma << std::endl;
1693 std::cout <<
"Finished in " << nrItr <<
" iterations." << std::endl;
1695 std::cout << std::endl;
1696 return (val_guess - val_best) / N_sigma;
1701 par_hat->setError(std::numeric_limits<double>::quiet_NaN());
1702 double lo = par_hat->getErrorLo();
1703 double hi = par_hat->getErrorHi();
1704 if (std::isnan(
hi)) {
1705 hi = findValue(val_best + val_err, 1) + val_best -
1710 if (std::isnan(lo)) {
1711 lo = -findValue(val_best - val_err, -1) + val_best -
1717 fitConfig.SetParabErrors(pErrs);
1718 fitConfig.SetMinosErrors(mErrs);
1719 par->setConstant(isConst);
1721 std::vector<std::pair<std::string, int>> statusHistory;
1725 statusHistory.emplace_back(
TString::Format(
"xMinos:%s", parName), status);
1726 const_cast<RooFitResult &
>(ufit).setStatusHistory(statusHistory);
1739 std::deque<RooAbsArg *> topPdfs;
1741 for (
auto p :
w.allPdfs()) {
1742 if (
p->hasClients())
1744 flagCount +=
p->getAttribute(
"hypoTest");
1745 if (
p->getAttribute(
"hypoTest")) {
1746 topPdfs.push_front(
p);
1748 topPdfs.push_back(
p);
1751 if (topPdfs.empty()) {
1752 Error(
"hypoTest",
"Cannot find top-level pdf in workspace");
1754 }
else if (topPdfs.size() > 1) {
1756 if (flagCount == 0) {
1757 Error(
"hypoTest",
"Multiple top-level pdfs. Flag which one to test with "
1758 "w->pdf(\"pdfName\")->setAttribute(\"hypoTest\",true)");
1760 }
else if (flagCount != 1) {
1761 Error(
"hypoTest",
"Multiple top-level pdfs flagged for hypoTest -- pick one.");
1767 Info(
"hypoTest",
"Using PDF: %s", model->GetName());
1773 std::shared_ptr<RooArgSet> obsGlobs =
nullptr;
1775 for (
auto p :
w.allData()) {
1777 Error(
"hypoTest",
"Multiple datasets in workspace. Flag which one to test with "
1778 "w->data(\"dataName\")->setAttribute(\"hypoTest\",true)");
1785 Error(
"hypoTest",
"No data -- cannot determine observables");
1789 Info(
"hypoTest",
"Using Dataset: %s", obsData->
GetName());
1792 auto _globs = xRooNode(
w).datasets()[obsData->
GetName()]->globs();
1793 obsGlobs = std::make_shared<RooArgSet>();
1794 obsGlobs->addClone(_globs.argList());
1795 Info(
"hypoTest",
"Using Globs: %s", (obsGlobs->empty()) ?
" <NONE>" : obsGlobs->contentsString().c_str());
1800 auto _vars = std::unique_ptr<RooArgSet>(model->getVariables());
1803 for (
auto _v : *_vars) {
1808 if (poi.
size() > 1) {
1809 auto _const = std::unique_ptr<RooAbsCollection>(poi.
selectByAttrib(
"Constant",
true));
1813 if (!args.
empty()) {
1817 Error(
"hypoTest",
"No POI detected: add the hypoPoints binning to at least one non-const model parameter e.g.:\n "
1818 "w->var(\"mu\")->setBinning(RooUniformBinning(0.5,10.5,10),\"hypoPoints\"))");
1830 xRooNLLVar
nll(*model, std::make_pair(obsData, obsGlobs.get()), *nllOpts);
1831 nll.SetFitConfig(fitConfig);
1833 if (poi.
size() == 1) {
1836 double altVal = (mu->getStringAttribute(
"altVal")) ?
TString(mu->getStringAttribute(
"altVal")).Atof()
1837 : std::numeric_limits<double>::quiet_NaN();
1839 if (std::isnan(altVal) && mu->hasRange(
"physical")) {
1841 altVal = mu->getMin(
"physical");
1842 Info(
"hypoTest",
"No altVal specified - using min of given physical range = %g", altVal);
1844 if (!std::isnan(altVal)) {
1845 Info(
"hypoTest",
"alt hypo: %g - CLs activated", altVal);
1847 Info(
"hypoTest",
"No altVal found - to specify setStringAttribute(\"altVal\",\"<value>\") on POI or set "
1848 "the physical range");
1851 bool doCLs = !std::isnan(altVal) && std::abs(mu->getMin(
"hypoPoints")) > altVal &&
1852 std::abs(mu->getMax(
"hypoPoints")) > altVal;
1854 const char *sCL = (doCLs) ?
"CLs" :
"null";
1855 Info(
"hypoTest",
"%s testing active", sCL);
1865 std::vector<int> expSig = {-2, -1, 0, 1, 2};
1866 if (std::isnan(altVal))
1868 std::map<int, TGraphErrors> exp_pcls;
1869 std::map<int, TGraphErrors> exp_cls;
1870 for (
auto &s : expSig) {
1872 TString::Format(
"Expected (%d#sigma) p_{%s};%s", s, sCL, mu->GetTitle()));
1874 TString::Format(
"Expected (%d#sigma) %s;%s", s, sCL, mu->GetTitle()));
1878 double _out = std::numeric_limits<double>::quiet_NaN();
1879 bool lastAbove =
false;
1880 for (
int i = 0; i < pValues.GetN(); i++) {
1881 bool thisAbove = pValues.GetPointY(i) >= (1. - CL);
1882 if (i != 0 && thisAbove != lastAbove) {
1885 _out = pValues.GetPointX(i - 1) + (pValues.GetPointX(i) - pValues.GetPointX(i - 1)) *
1886 ((1. - CL) - pValues.GetPointY(i - 1)) /
1887 (pValues.GetPointY(i) - pValues.GetPointY(i - 1));
1889 lastAbove = thisAbove;
1894 auto testPoint = [&](
double testVal) {
1895 auto hp =
nll.hypoPoint(mu->GetName(), testVal, altVal, pllType);
1896 obs_ts->SetPoint(obs_ts->GetN(), testVal, hp.pll().first);
1897 obs_ts->SetPointError(obs_ts->GetN() - 1, 0, hp.pll().second);
1899 if (nToysNull > 0) {
1902 obs_pcls->SetPoint(obs_pcls->GetN(), testVal, (doCLs) ? hp.pCLs_asymp().first : hp.pNull_asymp().first);
1903 obs_pcls->SetPointError(obs_pcls->GetN() - 1, 0, (doCLs) ? hp.pCLs_asymp().second : hp.pNull_asymp().second);
1904 for (
auto &s : expSig) {
1905 exp_pcls[s].SetPoint(exp_pcls[s].GetN(), testVal,
1906 (doCLs) ? hp.pCLs_asymp(s).first : hp.pNull_asymp(s).first);
1909 Info(
"hypoTest",
"%s=%g: %s=%g sigma_mu=%g %s=%g", mu->GetName(), testVal, obs_ts->GetName(),
1910 obs_ts->GetPointY(obs_ts->GetN() - 1), hp.sigma_mu().first, obs_pcls->GetName(),
1911 obs_pcls->GetPointY(obs_pcls->GetN() - 1));
1913 Info(
"hypoTest",
"%s=%g: %s=%g %s=%g", mu->GetName(), testVal, obs_ts->GetName(),
1914 obs_ts->GetPointY(obs_ts->GetN() - 1), obs_pcls->GetName(), obs_pcls->GetPointY(obs_pcls->GetN() - 1));
1918 if (mu->getBins(
"hypoPoints") <= 0) {
1921 testPoint(mu->getMin(
"hypoPoints"));
1922 testPoint(mu->getMax(
"hypoPoints"));
1923 testPoint((mu->getMax(
"hypoPoints") + mu->getMin(
"hypoPoints")) / 2.);
1925 while (std::abs(obs_pcls->GetPointY(obs_pcls->GetN() - 1) - (1. - CL)) > 0.01) {
1927 double nextTest = getLimit(*obs_pcls);
1928 if (std::isnan(nextTest))
1930 testPoint(nextTest);
1932 for (
auto s : expSig) {
1933 while (std::abs(exp_pcls[s].GetPointY(exp_pcls[s].GetN() - 1) - (1. - CL)) > 0.01) {
1935 double nextTest = getLimit(exp_pcls[s]);
1936 if (std::isnan(nextTest))
1938 testPoint(nextTest);
1943 for (
auto &s : expSig)
1947 for (
int i = 0; i <= mu->getBins(
"hypoPoints"); i++) {
1948 testPoint((i == mu->getBins(
"hypoPoints")) ? mu->getBinning(
"hypoPoints").binHigh(i - 1)
1949 : mu->getBinning(
"hypoPoints").binLow(i));
1953 obs_cls->SetPoint(obs_cls->GetN(), getLimit(*obs_pcls), 0.05);
1954 for (
auto &s : expSig) {
1955 exp_cls[s].SetPoint(exp_cls[s].GetN(), getLimit(exp_pcls[s]), 0.05);
1959 if (exp_pcls[2].GetN() > 1) {
1965 band2down->
SetNameTitle(
".pCLs_2sigma_downUncert",
"");
1971 for (
int i = 0; i < exp_pcls[2].GetN(); i++) {
1972 band2->
SetPoint(band2->
GetN(), exp_pcls[2].GetPointX(i),
1973 exp_pcls[2].GetPointY(i) - exp_pcls[2].GetErrorYlow(i));
1974 band2up->
SetPoint(band2up->
GetN(), exp_pcls[2].GetPointX(i),
1975 exp_pcls[2].GetPointY(i) + exp_pcls[2].GetErrorYhigh(i));
1977 for (
int i = exp_pcls[2].GetN() - 1; i >= 0; i--) {
1978 band2up->
SetPoint(band2up->
GetN(), exp_pcls[2].GetPointX(i),
1979 exp_pcls[2].GetPointY(i) - exp_pcls[2].GetErrorYlow(i));
1981 for (
int i = 0; i < exp_pcls[-2].GetN(); i++) {
1982 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-2].GetPointX(i),
1983 exp_pcls[-2].GetPointY(i) + exp_pcls[-2].GetErrorYhigh(i));
1985 for (
int i = exp_pcls[-2].GetN() - 1; i >= 0; i--) {
1986 band2->
SetPoint(band2->
GetN(), exp_pcls[-2].GetPointX(i),
1987 exp_pcls[-2].GetPointY(i) + exp_pcls[-2].GetErrorYhigh(i));
1988 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-2].GetPointX(i),
1989 exp_pcls[-2].GetPointY(i) - exp_pcls[-2].GetErrorYlow(i));
1994 auto ax =
static_cast<TNamed *
>(band2->
Clone(
".axis"));
1999 band2down->
Draw(
"F");
2002 if (exp_pcls[1].GetN() > 1) {
2008 band2down->
SetNameTitle(
".pCLs_1sigma_downUncert",
"");
2014 for (
int i = 0; i < exp_pcls[1].GetN(); i++) {
2015 band2->
SetPoint(band2->
GetN(), exp_pcls[1].GetPointX(i),
2016 exp_pcls[1].GetPointY(i) - exp_pcls[1].GetErrorYlow(i));
2017 band2up->
SetPoint(band2up->
GetN(), exp_pcls[1].GetPointX(i),
2018 exp_pcls[1].GetPointY(i) + exp_pcls[1].GetErrorYhigh(i));
2020 for (
int i = exp_pcls[1].GetN() - 1; i >= 0; i--) {
2021 band2up->
SetPoint(band2up->
GetN(), exp_pcls[1].GetPointX(i),
2022 exp_pcls[1].GetPointY(i) - exp_pcls[1].GetErrorYlow(i));
2024 for (
int i = 0; i < exp_pcls[-1].GetN(); i++) {
2025 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-1].GetPointX(i),
2026 exp_pcls[-1].GetPointY(i) + exp_pcls[-1].GetErrorYhigh(i));
2028 for (
int i = exp_pcls[-1].GetN() - 1; i >= 0; i--) {
2029 band2->
SetPoint(band2->
GetN(), exp_pcls[-1].GetPointX(i),
2030 exp_pcls[-1].GetPointY(i) + exp_pcls[-1].GetErrorYhigh(i));
2031 band2down->
SetPoint(band2down->
GetN(), exp_pcls[-1].GetPointX(i),
2032 exp_pcls[-1].GetPointY(i) - exp_pcls[-1].GetErrorYlow(i));
2039 band2down->
Draw(
"F");
2043 if (exp_cls[0].GetN() > 0) {
2044 exp_pcls[0].SetLineStyle(2);
2045 exp_pcls[0].SetFillColor(
kGreen);
2046 exp_pcls[0].SetMarkerStyle(0);
2047 expPlot = exp_pcls[0].DrawClone(
"L");
2050 obs_pcls->Draw(
gPad->GetListOfPrimitives()->IsEmpty() ?
"ALP" :
"LP");
2052 obs_ts->SetLineColor(
kRed);
2053 obs_ts->SetMarkerColor(
kRed);
2057 auto l =
new TLegend(0.5, 0.6, 1. -
gPad->GetRightMargin(), 1. -
gPad->GetTopMargin());
2058 l->SetName(
"legend");
2059 l->AddEntry(obs_ts, obs_ts->GetTitle(),
"LPE");
2060 l->AddEntry(obs_pcls, obs_pcls->GetTitle(),
"LPE");
2062 l->AddEntry(expPlot,
"Expected",
"LFE");
2066 obs_cls->SetMarkerStyle(29);
2067 obs_cls->SetEditable(
false);
2068 obs_cls->Draw(
"LP");
2069 for (
auto s : expSig) {
2070 exp_cls[s].SetMarkerStyle(29);
2071 exp_cls[s].SetEditable(
false);
2072 exp_cls[s].DrawClone(
"LP");
2086 double factor = pow(10.0, digits - ceil(log10(std::abs(
value))));
2087 return std::round(
value * factor) / factor;
2091 const double multiplier = std::pow(10.0, decimal_places);
2092 return std::round(
value * multiplier) / multiplier;
2099 if (!std::isinf(out.second)) {
2100 auto tmp = out.second;
2102 int expo = (out.second == 0) ? 0 : (
int)std::floor(std::log10(std::abs(out.second)));
2105 out.first = (expo >= 0) ? round(out.first) :
round_to_decimal(out.first, -expo);
2106 }
else if (out.second != 0) {
2107 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.
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
! In which workspace do I live, if any
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
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.
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.
RooArgSet * selectByAttrib(const char *name, bool value) const
Use RooAbsCollection::selectByAttrib(), 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)
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.
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/...".
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
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 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.
void RedrawAxis(Option_t *option="") override
Redraw the frame axis.
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.
void writeStdoutLine(const char *msg)
bool isPythonInitialized()
void writeStderrLine(const char *msg)
#define BEGIN_XROOFIT_NAMESPACE
#define END_XROOFIT_NAMESPACE
double round_to_decimal(double value, int decimal_places)
void printCout(const char *msg)
void printCerr(const char *msg)
double round_to_digits(double value, int digits)