47#ifdef ROOFIT_LEGACY_EVAL_BACKEND
55constexpr int extendedFitDefault = 2;
72 logpdf.getObservables(
data.get(), obs);
80 <<
"RooAbsPdf::fitTo(" << pdf.
GetName()
81 <<
") WARNING: Asymptotic error correction is requested for a binned data set. "
82 "This method is not designed to handle binned data. A standard chi2 fit will likely be more suitable.";
86 std::unique_ptr<RooFitResult> rw(minimizer.
save());
90 <<
"RooAbsPdf::fitTo(" << pdf.
GetName()
91 <<
") Calculating covariance matrix according to the asymptotically correct approach. If you find this "
92 "method useful please consider citing https://arxiv.org/abs/1911.01303.\n";
95 int nFloatPars = rw->floatParsFinal().size();
97 for (
int k = 0; k < nFloatPars; k++) {
98 for (
int l = 0;
l < nFloatPars;
l++) {
104 std::vector<std::unique_ptr<RooDerivative>> derivatives;
105 const RooArgList &floated = rw->floatParsFinal();
107 logpdf.getParameters(
data.get(), allparams);
108 std::unique_ptr<RooArgSet> floatingparams{
static_cast<RooArgSet *
>(allparams.
selectByAttrib(
"Constant",
false))};
110 const double eps = 1.0e-4;
113 for (
const auto paramresult : floated) {
114 auto paraminternal =
static_cast<RooRealVar *
>(floatingparams->find(*paramresult));
116 double error =
static_cast<RooRealVar *
>(paramresult)->getError();
117 derivatives.emplace_back(logpdf.derivative(*paraminternal, obs, 1, eps * error));
122 std::vector<double> diffs_expected(floated.
size(), 0.0);
124 for (std::size_t k = 0; k < floated.
size(); k++) {
125 const auto paramresult =
static_cast<RooRealVar *
>(floated.
at(k));
126 auto paraminternal =
static_cast<RooRealVar *
>(floatingparams->find(*paramresult));
128 *paraminternal = paramresult->
getVal();
129 double error = paramresult->getError();
130 paraminternal->setVal(paramresult->getVal() + eps * error);
132 paraminternal->setVal(paramresult->getVal() - eps * error);
134 *paraminternal = paramresult->getVal();
135 double diff = (expected_plus - expected_minus) / (2.0 * eps * error);
136 diffs_expected[k] = diff;
141 for (
int j = 0; j <
data.numEntries(); j++) {
145 std::vector<double> diffs(floated.
size(), 0.0);
146 for (std::size_t k = 0; k < floated.
size(); k++) {
147 const auto paramresult =
static_cast<RooRealVar *
>(floated.
at(k));
148 auto paraminternal =
static_cast<RooRealVar *
>(floatingparams->find(*paramresult));
150 double diff = derivatives[k]->
getVal();
152 *paraminternal = paramresult->getVal();
157 for (std::size_t k = 0; k < floated.
size(); k++) {
158 for (std::size_t
l = 0;
l < floated.
size();
l++) {
159 num(k,
l) +=
data.weightSquared() * (diffs[k] + diffs_expected[k]) * (diffs[
l] + diffs_expected[
l]);
163 num.Similarity(matV);
171 return rw->covQual();
189 std::unique_ptr<RooFitResult> rw{minimizer.
save()};
190 nll.applyWeightSquared(
true);
192 <<
") Calculating sum-of-weights-squared correction matrix for covariance matrix\n";
194 std::unique_ptr<RooFitResult> rw2{minimizer.
save()};
195 nll.applyWeightSquared(
false);
203 <<
") ERROR: Cannot apply sum-of-weights correction to covariance matrix: correction "
204 "matrix calculated with weight-squared is singular\n";
212 for (
int i = 0; i < matC.
GetNrows(); ++i) {
213 for (
int j = 0; j < i; ++j) {
214 matC(j, i) = matC(i, j);
222 return std::min(rw->covQual(), rw2->covQual());
227struct MinimizerConfig {
228 double recoverFromNaN = 10.;
242 int doAsymptotic = -1;
246 bool enableParallelGradient =
true;
247 bool enableParallelDescent =
false;
248 bool timingAnalysis =
false;
251 std::string minAlg =
"minuit";
254bool interpretExtendedCmdArg(
RooAbsPdf const &pdf,
int extendedCmdArg)
257 if (extendedCmdArg == extendedFitDefault) {
261 <<
"p.d.f. provides expected number of events, including extended term in likelihood." << std::endl;
270 if (extendedCmdArg == 0) {
272 std::string errMsg =
"You used the Extended(false) option on a pdf where the fit MUST be extended! "
273 "The parameters are not well defined and you're getting nonsensical results.";
274 oocoutE(&pdf, InputArguments) << errMsg << std::endl;
277 return extendedCmdArg;
282void resetFitrangeAttributes(
RooAbsArg &pdf,
RooAbsData const &
data, std::string
const &baseName,
const char *rangeName,
291 if (!rangeName || splitRange)
297 std::string fitrangeValue;
299 for (
auto const &subrange : subranges) {
300 if (subrange.empty())
302 std::string fitrangeValueSubrange = std::string(
"fit_") + baseName;
303 if (subranges.size() > 1) {
304 fitrangeValueSubrange +=
"_" + subrange;
306 fitrangeValue += fitrangeValueSubrange +
",";
309 if (arg->isCategory())
311 auto &observable =
static_cast<RooRealVar &
>(*arg);
313 observable.
setRange(fitrangeValueSubrange.c_str(), observable.getMin(subrange.c_str()),
314 observable.getMax(subrange.c_str()));
317 pdf.
setStringAttribute(
"fitrange", fitrangeValue.substr(0, fitrangeValue.size() - 1).c_str());
320std::unique_ptr<RooAbsArg> createSimultaneousNLL(
RooSimultaneous const &simPdf,
bool isExtended,
327 for (
auto const &catState : simCat) {
328 std::string
const &catName = catState.
first;
333 if (!rangeName.empty()) {
336 auto simCatAsRooCategory =
dynamic_cast<RooCategory const *
>(&simCat);
337 if (simCatAsRooCategory && !simCatAsRooCategory->isStateInRange(rangeName.c_str(), catIndex)) {
344 std::unique_ptr<RooArgSet> observables(
345 static_cast<RooArgSet *
>(std::unique_ptr<RooArgSet>(pdf->
getVariables())->selectByAttrib(
"__obs__",
true)));
346 auto nll = std::make_unique<RooNLLVarNew>(
name.c_str(),
name.c_str(), *pdf, *observables, isExtended,
offset);
348 nll->setPrefix(std::string(
"_") + catName +
"_");
354 nll->setSimCount(nllTerms.
size());
358 auto nll = std::make_unique<RooAddition>(
"mynll",
"mynll", nllTerms);
359 nll->addOwnedComponents(std::move(nllTerms));
363std::unique_ptr<RooAbsReal> createNLLNew(
RooAbsPdf &pdf,
RooAbsData &
data, std::unique_ptr<RooAbsReal> &&constraints,
364 std::string
const &rangeName,
RooArgSet const &projDeps,
bool isExtended,
375 observables.
remove(projDeps,
true,
true);
378 <<
") fixing normalization set for coefficient determination to observables in data"
385 RooAbsPdf &finalPdf = wrappedPdf ? *wrappedPdf : pdf;
387 binSamplingPdfs.
addOwned(std::move(wrappedPdf));
396 nllTerms.
addOwned(createSimultaneousNLL(*simPdf, isExtended, rangeName,
offset));
399 std::make_unique<RooNLLVarNew>(
"RooNLLVarNew",
"RooNLLVarNew", finalPdf, observables, isExtended,
offset));
402 nllTerms.
addOwned(std::move(constraints));
405 std::string nllName = std::string(
"nll_") + pdf.
GetName() +
"_" +
data.GetName();
406 auto nll = std::make_unique<RooAddition>(nllName.c_str(), nllName.c_str(), nllTerms);
407 nll->addOwnedComponents(std::move(binSamplingPdfs));
408 nll->addOwnedComponents(std::move(nllTerms));
416namespace FitHelpers {
422 MinimizerConfig minimizerDefaults;
424 pc.
defineDouble(
"RecoverFromUndefinedRegions",
"RecoverFromUndefinedRegions", 0, minimizerDefaults.recoverFromNaN);
425 pc.
defineInt(
"optConst",
"Optimize", 0, minimizerDefaults.optConst);
426 pc.
defineInt(
"verbose",
"Verbose", 0, minimizerDefaults.verbose);
427 pc.
defineInt(
"doSave",
"Save", 0, minimizerDefaults.doSave);
428 pc.
defineInt(
"doTimer",
"Timer", 0, minimizerDefaults.doTimer);
429 pc.
defineInt(
"printLevel",
"PrintLevel", 0, minimizerDefaults.printLevel);
430 pc.
defineInt(
"strategy",
"Strategy", 0, minimizerDefaults.strategy);
431 pc.
defineInt(
"initHesse",
"InitialHesse", 0, minimizerDefaults.initHesse);
432 pc.
defineInt(
"hesse",
"Hesse", 0, minimizerDefaults.hesse);
433 pc.
defineInt(
"minos",
"Minos", 0, minimizerDefaults.minos);
434 pc.
defineInt(
"numee",
"PrintEvalErrors", 0, minimizerDefaults.numee);
435 pc.
defineInt(
"doEEWall",
"EvalErrorWall", 0, minimizerDefaults.doEEWall);
436 pc.
defineInt(
"doWarn",
"Warnings", 0, minimizerDefaults.doWarn);
437 pc.
defineInt(
"doSumW2",
"SumW2Error", 0, minimizerDefaults.doSumW2);
438 pc.
defineInt(
"doAsymptoticError",
"AsymptoticError", 0, minimizerDefaults.doAsymptotic);
439 pc.
defineInt(
"maxCalls",
"MaxCalls", 0, minimizerDefaults.maxCalls);
440 pc.
defineInt(
"doOffset",
"OffsetLikelihood", 0, 0);
441 pc.
defineInt(
"parallelize",
"Parallelize", 0, 0);
442 pc.
defineInt(
"enableParallelGradient",
"ParallelGradientOptions", 0, 0);
443 pc.
defineInt(
"enableParallelDescent",
"ParallelDescentOptions", 0, 0);
444 pc.
defineInt(
"timingAnalysis",
"TimingAnalysis", 0, 0);
445 pc.
defineString(
"mintype",
"Minimizer", 0, minimizerDefaults.minType.c_str());
446 pc.
defineString(
"minalg",
"Minimizer", 1, minimizerDefaults.minAlg.c_str());
447 pc.
defineSet(
"minosSet",
"Minos", 0, minimizerDefaults.minosSet);
464 cfg.recoverFromNaN = pc.
getDouble(
"RecoverFromUndefinedRegions");
465 cfg.optConst = pc.
getInt(
"optConst");
466 cfg.verbose = pc.
getInt(
"verbose");
467 cfg.doSave = pc.
getInt(
"doSave");
468 cfg.doTimer = pc.
getInt(
"doTimer");
469 cfg.printLevel = pc.
getInt(
"printLevel");
470 cfg.strategy = pc.
getInt(
"strategy");
471 cfg.initHesse = pc.
getInt(
"initHesse");
472 cfg.hesse = pc.
getInt(
"hesse");
473 cfg.minos = pc.
getInt(
"minos");
474 cfg.numee = pc.
getInt(
"numee");
475 cfg.doEEWall = pc.
getInt(
"doEEWall");
476 cfg.doWarn = pc.
getInt(
"doWarn");
477 cfg.doSumW2 = pc.
getInt(
"doSumW2");
478 cfg.doAsymptotic = pc.
getInt(
"doAsymptoticError");
479 cfg.maxCalls = pc.
getInt(
"maxCalls");
480 cfg.minosSet = pc.
getSet(
"minosSet");
481 cfg.minType = pc.
getString(
"mintype",
"");
482 cfg.minAlg = pc.
getString(
"minalg",
"minuit");
483 cfg.doOffset = pc.
getInt(
"doOffset");
484 cfg.parallelize = pc.
getInt(
"parallelize");
485 cfg.enableParallelGradient = pc.
getInt(
"enableParallelGradient");
486 cfg.enableParallelDescent = pc.
getInt(
"enableParallelDescent");
487 cfg.timingAnalysis = pc.
getInt(
"timingAnalysis");
490 bool weightedData =
data.isNonPoissonWeighted();
492 std::string msgPrefix = std::string{
"RooAbsPdf::fitTo("} + pdf.
GetName() +
"): ";
495 if (weightedData && cfg.doSumW2 == -1 && cfg.doAsymptotic == -1) {
496 oocoutW(&pdf, InputArguments) << msgPrefix <<
497 R
"(WARNING: a likelihood fit is requested of what appears to be weighted data.
498 While the estimated values of the parameters will always be calculated taking the weights into account,
499 there are multiple ways to estimate the errors of the parameters. You are advised to make an
500 explicit choice for the error calculation:
501 - Either provide SumW2Error(true), to calculate a sum-of-weights-corrected HESSE error matrix
502 (error will be proportional to the number of events in MC).
503 - Or provide SumW2Error(false), to return errors from original HESSE error matrix
504 (which will be proportional to the sum of the weights, i.e., a dataset with <sum of weights> events).
505 - Or provide AsymptoticError(true), to use the asymptotically correct expression
506 (for details see https://arxiv.org/abs/1911.01303)."
510 if (cfg.minos && (cfg.doSumW2 == 1 || cfg.doAsymptotic == 1)) {
513 <<
" sum-of-weights and asymptotic error correction do not work with MINOS errors. Not fitting.\n";
516 if (cfg.doAsymptotic == 1 && cfg.minos) {
517 oocoutW(&pdf, InputArguments) << msgPrefix <<
"WARNING: asymptotic correction does not apply to MINOS errors\n";
521 if (cfg.doSumW2 == 1 && cfg.doAsymptotic == 1) {
522 oocoutE(&pdf, InputArguments) << msgPrefix
523 <<
"ERROR: Cannot compute both asymptotically correct and SumW2 errors.\n";
536 m.setMinimizerType(cfg.minType);
537 m.setEvalErrorWall(cfg.doEEWall);
538 m.setRecoverFromNaNStrength(cfg.recoverFromNaN);
539 m.setPrintEvalErrors(cfg.numee);
540 if (cfg.maxCalls > 0)
541 m.setMaxFunctionCalls(cfg.maxCalls);
542 if (cfg.printLevel != 1)
543 m.setPrintLevel(cfg.printLevel);
545 m.optimizeConst(cfg.optConst);
550 if (cfg.strategy != 1)
551 m.setStrategy(cfg.strategy);
554 m.minimize(cfg.minType.c_str(), cfg.minAlg.c_str());
558 int corrCovQual = -1;
560 if (
m.getNPar() > 0) {
561 if (cfg.doAsymptotic == 1)
562 corrCovQual = calcAsymptoticCorrectedCovariance(pdf,
m,
data);
563 if (cfg.doSumW2 == 1)
564 corrCovQual = calcSumW2CorrectedCovariance(pdf,
m, nll);
568 cfg.minosSet ?
m.minos(*cfg.minosSet) :
m.minos();
571 std::unique_ptr<RooFitResult> ret;
573 auto name = std::string(
"fitresult_") + pdf.
GetName() +
"_" +
data.GetName();
574 auto title = std::string(
"Result of fit of p.d.f. ") + pdf.
GetName() +
" to dataset " +
data.GetName();
575 ret = std::unique_ptr<RooFitResult>{
m.save(
name.c_str(), title.c_str())};
576 if ((cfg.doSumW2 == 1 || cfg.doAsymptotic == 1) &&
m.getNPar() > 0)
577 ret->setCovQual(corrCovQual);
587 auto baseName = std::string(
"nll_") + pdf.
GetName() +
"_" +
data.GetName();
592 pc.
defineString(
"rangeName",
"RangeWithName", 0,
"",
true);
594 pc.
defineString(
"globstag",
"GlobalObservablesTag", 0,
"");
595 pc.
defineString(
"globssource",
"GlobalObservablesSource", 0,
"data");
598 pc.
defineInt(
"splitRange",
"SplitRange", 0, 0);
599 pc.
defineInt(
"ext",
"Extended", 0, extendedFitDefault);
601 pc.
defineInt(
"interleave",
"NumCPU", 1, 0);
602 pc.
defineInt(
"verbose",
"Verbose", 0, 0);
603 pc.
defineInt(
"optConst",
"Optimize", 0, 0);
604 pc.
defineInt(
"cloneData",
"CloneData", 0, 2);
605 pc.
defineSet(
"projDepSet",
"ProjectedObservables", 0,
nullptr);
606 pc.
defineSet(
"cPars",
"Constrain", 0,
nullptr);
607 pc.
defineSet(
"glObs",
"GlobalObservables", 0,
nullptr);
608 pc.
defineInt(
"doOffset",
"OffsetLikelihood", 0, 0);
609 pc.
defineSet(
"extCons",
"ExternalConstraints", 0,
nullptr);
611 pc.
defineDouble(
"IntegrateBins",
"IntegrateBins", 0, -1.);
613 pc.
defineMutex(
"GlobalObservables",
"GlobalObservablesTag");
614 pc.
defineInt(
"ModularL",
"ModularL", 0, 0);
629 if (pc.
getInt(
"ModularL")) {
630 int lut[3] = {2, 1, 0};
638 if (
auto tmp = pc.
getSet(
"cPars"))
641 if (
auto tmp = pc.
getSet(
"extCons"))
642 extConsSet.
add(*tmp);
644 if (
auto tmp = pc.
getSet(
"glObs"))
647 const std::string rangeName = pc.
getString(
"globstag",
"",
false);
650 builder.Extended(ext)
651 .ConstrainedParameters(cParsSet)
652 .ExternalConstraints(extConsSet)
653 .GlobalObservables(glObsSet)
654 .GlobalObservablesTag(rangeName.c_str());
656 return std::make_unique<RooFit::TestStatistics::RooRealL>(
"likelihood",
"", builder.build());
660 const char *rangeName = pc.
getString(
"rangeName",
nullptr,
true);
661 const char *addCoefRangeName = pc.
getString(
"addCoefRange",
nullptr,
true);
662 const bool ext = interpretExtendedCmdArg(pdf, pc.
getInt(
"ext"));
664 int splitRange = pc.
getInt(
"splitRange");
665 int optConst = pc.
getInt(
"optConst");
666 int cloneData = pc.
getInt(
"cloneData");
670 if (cloneData == 2) {
671 cloneData = optConst;
675 double rangeLo = pc.
getDouble(
"rangeLo");
676 double rangeHi = pc.
getDouble(
"rangeHi");
681 for (
auto arg : obs) {
684 rrv->
setRange(
"fit", rangeLo, rangeHi);
692 resetFitrangeAttributes(pdf,
data, baseName, rangeName, splitRange);
700 const std::string globalObservablesSource = pc.
getString(
"globssource",
"data",
false);
701 if (globalObservablesSource !=
"data" && globalObservablesSource !=
"model") {
702 std::string errMsg =
"RooAbsPdf::fitTo: GlobalObservablesSource can only be \"data\" or \"model\"!";
703 oocoutE(&pdf, InputArguments) << errMsg << std::endl;
704 throw std::invalid_argument(errMsg);
706 const bool takeGlobalObservablesFromData = globalObservablesSource ==
"data";
711 auto createConstr = [&](
bool removeConstraintsFromPdf =
false) -> std::unique_ptr<RooAbsReal> {
719 takeGlobalObservablesFromData,
720 removeConstraintsFromPdf);
730 std::string oldNormRange;
738 normSet.
remove(projDeps,
true,
true);
744 ctx.setLikelihoodMode(
true);
746 std::unique_ptr<RooAbsPdf> pdfClone = std::unique_ptr<RooAbsPdf>{
static_cast<RooAbsPdf *
>(head.release())};
755 if (addCoefRangeName) {
757 <<
") fixing interpretation of coefficients of any component to range "
758 << addCoefRangeName <<
"\n";
759 pdfClone->fixAddCoefRange(addCoefRangeName,
false);
762 std::unique_ptr<RooAbsReal> compiledConstr;
763 if (std::unique_ptr<RooAbsReal> constr = createConstr()) {
765 compiledConstr->addOwnedComponents(std::move(constr));
768 auto nll = createNLLNew(*pdfClone,
data, std::move(compiledConstr), rangeName ? rangeName :
"", projDeps, ext,
769 pc.getDouble(
"IntegrateBins"),
offset);
771 std::unique_ptr<RooAbsReal> nllWrapper;
777 nllWrapper = std::make_unique<RooFit::Experimental::RooFuncWrapper>(
"nll_func_wrapper",
"nll_func_wrapper",
778 *nll, &
data, simPdf, createGradient);
780 static_cast<Experimental::RooFuncWrapper &
>(*nllWrapper).createGradient();
782 nllWrapper = std::make_unique<RooEvaluatorWrapper>(
784 takeGlobalObservablesFromData);
787 nllWrapper->addOwnedComponents(std::move(nll));
788 nllWrapper->addOwnedComponents(std::move(pdfClone));
792 std::unique_ptr<RooAbsReal>
nll;
794#ifdef ROOFIT_LEGACY_EVAL_BACKEND
797 int numcpu = pc.
getInt(
"numcpu");
798 int numcpu_strategy = pc.
getInt(
"interleave");
800 if (numcpu_strategy == 3 && !pdf.
InheritsFrom(
"RooSimultaneous")) {
801 oocoutW(&pdf, Minimization) <<
"Cannot use a NumCpu Strategy = 3 when the pdf is not a RooSimultaneous, "
802 "falling back to default strategy = 0"
809 RooAbsPdf &actualPdf = binnedLInfo.binnedPdf ? *binnedLInfo.binnedPdf : pdf;
821 cfg.
binnedL = binnedLInfo.isBinnedL;
823 cfg.
rangeName = rangeName ? rangeName :
"";
824 auto nllVar = std::make_unique<RooNLLVar>(baseName.c_str(),
"-log(likelihood)", actualPdf,
data, projDeps, ext, cfg);
826 nll = std::move(nllVar);
830 if (std::unique_ptr<RooAbsReal> constraintTerm = createConstr()) {
842 constraintTerm->setData(
data,
false);
848 auto orignll = std::move(nll);
849 nll = std::make_unique<RooAddition>((baseName +
"_with_constr").c_str(),
"nllWithCons",
851 nll->addOwnedComponents(std::move(orignll), std::move(constraintTerm));
859 nll->enableOffsetting(
true);
862 throw std::runtime_error(
"RooFit was not built with the legacy evaluation backend");
870#ifdef ROOFIT_LEGACY_EVAL_BACKEND
876 pc.
defineInt(
"verbose",
"Verbose", 0, 0);
883 std::string baseName =
"chi2_" + std::string(real.
GetName()) +
"_" +
data.GetName();
889 pc.
defineInt(
"extended",
"Extended", 0, extendedFitDefault);
890 pc.
defineInt(
"split_range",
"SplitRange", 0, 0);
891 pc.
defineDouble(
"integrate_bins",
"IntegrateBins", 0, -1);
900 bool extended =
false;
901 if (
auto pdf =
dynamic_cast<RooAbsPdf const *
>(&real)) {
902 extended = interpretExtendedCmdArg(*pdf, pc.
getInt(
"extended"));
907 const char *rangeName = pc.
getString(
"rangeName",
nullptr,
true);
908 const char *addCoefRangeName = pc.
getString(
"addCoefRange",
nullptr,
true);
910 cfg.
rangeName = rangeName ? rangeName :
"";
918 auto chi2 = std::make_unique<RooChi2Var>(baseName.c_str(), baseName.c_str(), real,
925 pc.
defineInt(
"integrate",
"Integrate", 0, 0);
927 pc.
defineString(
"rangeName",
"RangeWithName", 0,
"",
true);
928 pc.
defineInt(
"interleave",
"NumCPU", 1, 0);
937 bool integrate = pc.
getInt(
"integrate");
939 const char *rangeName = pc.
getString(
"rangeName",
nullptr,
true);
943 if (numcpu_strategy == 3 && !real.
InheritsFrom(
"RooSimultaneous")) {
944 oocoutW(&real, Minimization) <<
"Cannot use a NumCpu Strategy = 3 when the pdf is not a RooSimultaneous, "
945 "falling back to default strategy = 0"
952 cfg.
rangeName = rangeName ? rangeName :
"";
958 std::string
name =
"chi2_" + std::string(real.
GetName()) +
"_" +
data.GetName();
960 return std::make_unique<RooXYChi2Var>(
name.c_str(),
name.c_str(), real,
static_cast<RooDataSet &
>(
data), yvar,
964 throw std::runtime_error(
"createChi2() is not supported without the legacy evaluation backend");
976 std::string nllCmdListString;
978 nllCmdListString =
"ProjectedObservables,Extended,Range,"
979 "RangeWithName,SumCoefRange,NumCPU,SplitRange,Constrained,Constrain,ExternalConstraints,"
980 "CloneData,GlobalObservables,GlobalObservablesSource,GlobalObservablesTag,"
981 "EvalBackend,IntegrateBins,ModularL";
984 nllCmdListString +=
",OffsetLikelihood";
987 auto createChi2DataHistCmdArgs =
"Range,RangeWithName,NumCPU,Optimize,IntegrateBins,ProjectedObservables,"
988 "AddCoefRange,SplitRange,DataError,Extended";
989 auto createChi2DataSetCmdArgs =
"YVar,Integrate,RangeWithName,NumCPU,Verbose";
990 nllCmdListString += isDataHist ? createChi2DataHistCmdArgs : createChi2DataSetCmdArgs;
996 defineMinimizationOptions(pc);
1006 oocoutW(&real, Minimization) <<
"The timingAnalysis feature was built for minimization with RooSimultaneous "
1007 "and is not implemented for other PDF's. Please create a RooSimultaneous to "
1008 "enable this feature."
1016 size_t nEvents =
static_cast<size_t>(prefit *
data.numEntries());
1017 if (prefit > 0.5 || nEvents < 100) {
1018 oocoutW(&real, InputArguments) <<
"PrefitDataFraction should be in suitable range."
1019 <<
"With the current PrefitDataFraction=" << prefit
1020 <<
", the number of events would be " << nEvents <<
" out of "
1021 <<
data.numEntries() <<
". Skipping prefit..." << std::endl;
1023 size_t step =
data.numEntries() / nEvents;
1027 for (
int i = 0; i <
data.numEntries(); i += step) {
1029 tiny.add(*event,
data.weight());
1032 pc.
filterCmdList(tinyCmdList,
"Prefit,Hesse,Minos,Verbose,Save,Timer");
1036 tinyCmdList.Add(&hesse_option);
1037 tinyCmdList.Add(&print_option);
1039 fitTo(real, tiny, tinyCmdList, chi2);
1044 if (pc.
getInt(
"parallelize") != 0 || pc.
getInt(
"enableParallelGradient") || pc.
getInt(
"enableParallelDescent")) {
1047 nllCmdList.
Add(&modularL_option);
1050 std::unique_ptr<RooAbsReal>
nll;
1055 nll = std::unique_ptr<RooAbsReal>{
dynamic_cast<RooAbsPdf &
>(real).createNLL(
data, nllCmdList)};
1058 return RooFit::FitHelpers::minimize(real, *nll,
data, pc);
header file containing the templated implementation of matrix inversion routines for use with ROOT's ...
std::unique_ptr< RooAbsReal > createConstraintTerm(std::string const &name, RooAbsPdf const &pdf, RooAbsData const &data, RooArgSet const *constrainedParameters, RooArgSet const *externalConstraints, RooArgSet const *globalObservables, const char *globalObservablesTag, bool takeGlobalObservablesFromData, bool removeConstraintsFromPdf)
Create the parameter constraint sum to add to the negative log-likelihood.
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
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 Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
class to compute the Cholesky decomposition of a matrix
Common abstract base class for objects that represent a value and a "shape" in RooFit.
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
void removeStringAttribute(const Text_t *key)
Delete a string attribute with a given key.
RooFit::OwningPtr< RooArgSet > getVariables(bool stripDisconnected=true) const
Return RooArgSet with all variables (tree leaf nodes of expression tree)
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
Abstract base class for objects that represent a discrete value that can be set from the outside,...
RooAbsCollection * selectByAttrib(const char *name, bool value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
Storage_t::size_type size() const
RooAbsArg * first() const
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
Abstract base class for binned and unbinned datasets.
Abstract interface for all probability density functions.
std::unique_ptr< RooAbsArg > compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const override
virtual double expectedEvents(const RooArgSet *nset) const
Return expected number of events to be used in calculation of extended likelihood.
void setNormRange(const char *rangeName)
const char * normRange() const
virtual ExtendMode extendMode() const
Returns ability of PDF to provide extended likelihood terms.
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 void fixAddCoefNormalization(const RooArgSet &addNormSet=RooArgSet(), bool force=true)
Fix the interpretation of the coefficient of any RooAddPdf component in the expression tree headed by...
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
virtual RooFit::OwningPtr< RooAbsReal > createChi2(RooDataHist &data, const RooLinkedList &cmdList)
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
static std::unique_ptr< RooAbsPdf > create(RooAbsPdf &pdf, RooAbsData const &data, double precision)
Creates a wrapping RooBinSamplingPdf if appropriate.
Object to represent discrete states.
Named container for two doubles, two integers two object points and three string pointers that can be...
Int_t getInt(Int_t idx) const
Configurable parser for RooCmdArg named arguments.
void defineMutex(const char *head, Args_t &&... tail)
Define arguments where any pair is mutually exclusive.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
bool hasProcessed(const char *cmdName) const
Return true if RooCmdArg with name 'cmdName' has been processed.
double getDouble(const char *name, double defaultValue=0.0) const
Return double property registered with name 'name'.
bool defineDouble(const char *name, const char *argName, int doubleNum, double defValue=0.0)
Define double property name 'name' mapped to double in slot 'doubleNum' in RooCmdArg with name argNam...
RooArgSet * getSet(const char *name, RooArgSet *set=nullptr) const
Return RooArgSet property registered with name 'name'.
bool defineSet(const char *name, const char *argName, int setNum, const RooArgSet *set=nullptr)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
bool ok(bool verbose) const
Return true of parsing was successful.
bool defineObject(const char *name, const char *argName, int setNum, const TObject *obj=nullptr, bool isArray=false)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
const char * getString(const char *name, const char *defaultValue="", bool convEmptyToNull=false) const
Return string property registered with name 'name'.
bool defineString(const char *name, const char *argName, int stringNum, const char *defValue="", bool appendMode=false)
Define double property name 'name' mapped to double in slot 'stringNum' in RooCmdArg with name argNam...
bool defineInt(const char *name, const char *argName, int intNum, int defValue=0)
Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName...
void allowUndefined(bool flag=true)
If flag is true the processing of unrecognized RooCmdArgs is not considered an error.
int getInt(const char *name, int defaultValue=0) const
Return integer property registered with name 'name'.
RooLinkedList filterCmdList(RooLinkedList &cmdInList, const char *cmdNameList, bool removeFromInList=true) const
Utility function to filter commands listed in cmdNameList from cmdInList.
TObject * getObject(const char *name, TObject *obj=nullptr) const
Return TObject property registered with name 'name'.
Container class to hold N-dimensional binned data.
Container class to hold unbinned data.
static Value & defaultValue()
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
virtual void Add(TObject *arg)
TObject * FindObject(const char *name) const override
Return pointer to object with given name.
Wrapper class around ROOT::Fit:Fitter that provides a seamless interface between the minimizer functi...
RooFit::OwningPtr< RooFitResult > save(const char *name=nullptr, const char *title=nullptr)
Save and return a RooFitResult snapshot of current minimizer status.
int hesse()
Execute HESSE.
void applyCovarianceMatrix(TMatrixDSym const &V)
Apply results of given external covariance matrix.
Variable that can be changed from the outside.
void setRange(const char *name, double min, double max)
Set a fit or plotting range.
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
RooAbsPdf * getPdf(RooStringView catName) const
Return the p.d.f associated with the given index category name.
void wrapPdfsInBinSamplingPdfs(RooAbsData const &data, double precision)
Wraps the components of this RooSimultaneous in RooBinSamplingPdfs.
const RooAbsCategoryLValue & indexCat() const
TMatrixTSym< Element > & Similarity(const TMatrixT< Element > &n)
Calculate B * (*this) * B^T , final matrix will be (nrowsb x nrowsb) This is a similarity transform w...
const char * GetName() const override
Returns name of object.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Hesse(bool flag=true)
RooCmdArg ModularL(bool flag=false)
RooCmdArg PrintLevel(Int_t code)
RVec< PromoteType< T > > log(const RVec< T > &v)
std::vector< std::string > Split(std::string_view str, std::string_view delims, bool skipEmpty=false)
Splits a string at each character in delims.
double nll(double pdf, double weight, int binnedL, int doBinOffset)
std::unique_ptr< T > compileForNormSet(T const &arg, RooArgSet const &normSet)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
OffsetMode
For setting the offset mode with the Offset() command argument to RooAbsPdf::fitTo()
std::unique_ptr< T > cloneTreeWithSameParameters(T const &arg, RooArgSet const *observables=nullptr)
Clone RooAbsArg object and reattach to original parameters.
BinnedLOutput getBinnedL(RooAbsPdf const &pdf)
std::string rangeName
Stores the configuration parameters for RooAbsTestStatistic.
std::string addCoefRangeName
bool takeGlobalObservablesFromData
double integrateOverBinsPrecision
RooFit::MPSplit interleave
Config argument to RooMinimizer constructor.
bool enableParallelDescent
bool enableParallelGradient