Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
FitHelpers.cxx
Go to the documentation of this file.
1/// \cond ROOFIT_INTERNAL
2
3/*
4 * Project: RooFit
5 * Authors:
6 * Jonas Rembser, CERN 2023
7 *
8 * Copyright (c) 2023, CERN
9 *
10 * Redistribution and use in source and binary forms,
11 * with or without modification, are permitted according to the terms
12 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
13 */
14
15#include "FitHelpers.h"
16
17#include <RooAbsData.h>
18#include <RooAbsPdf.h>
19#include <RooAbsReal.h>
20#include <RooAddition.h>
21#include <RooBatchCompute.h>
22#include <RooBinSamplingPdf.h>
23#include <RooCategory.h>
24#include <RooCmdConfig.h>
25#include <RooConstraintSum.h>
26#include <RooDataHist.h>
27#include <RooDataSet.h>
28#include <RooDerivative.h>
29#include <RooFit/Evaluator.h>
32#include <RooFitResult.h>
33#include <RooLinkedList.h>
34#include <RooMinimizer.h>
35#include <RooConstVar.h>
36#include <RooRealVar.h>
37#include <RooSimultaneous.h>
38#include <RooFormulaVar.h>
39
40#include <Math/CholeskyDecomp.h>
41#include <Math/Util.h>
42
43#include "ConstraintHelpers.h"
44#include "RooEvaluatorWrapper.h"
45#include "RooFitImplHelpers.h"
47
48#ifdef ROOFIT_MULTIPROCESS
50#endif
51
52#include <sstream>
53
54using RooFit::Detail::RooNLLVarNew;
55
56namespace {
57
58constexpr int extendedFitDefault = 2;
59
60/// Nested RooSimultaneous are only supported in "switch mode", i.e., if their
61/// index category is not an observable. Throw an error otherwise.
62void checkNestedSimultaneous(RooAbsArg const &top, RooArgSet const &observables)
63{
64 RooArgList branches;
65 top.branchNodeServerList(&branches);
66 for (RooAbsArg *outer : branches) {
67 if (!dynamic_cast<RooSimultaneous const *>(outer)) {
68 continue;
69 }
70 RooArgList outerBranches;
71 outer->branchNodeServerList(&outerBranches);
72 for (RooAbsArg *arg : outerBranches) {
73 auto *nested = dynamic_cast<RooSimultaneous const *>(arg);
74 if (arg == outer || !nested || !nested->indexCatIsObservable(observables)) {
75 continue;
76 }
77 std::stringstream errMsg;
78 errMsg << "RooSimultaneous \"" << outer->GetName() << "\" contains the RooSimultaneous \"" << nested->GetName()
79 << "\", whose index category \"" << nested->indexCat().GetName()
80 << "\" is in the dataset. Nested RooSimultaneous are only supported if their index category is a "
81 "parameter (switch mode). To combine channels, use one RooSimultaneous over a RooCategory with one "
82 "state per channel.";
83 oocoutE(&top, InputArguments) << errMsg.str() << std::endl;
84 throw std::runtime_error(errMsg.str());
85 }
86 }
87}
88
89////////////////////////////////////////////////////////////////////////////////
90/// Use the asymptotically correct approach to estimate errors in the presence of weights.
91/// This is slower but more accurate than `SumW2Error`. See also https://arxiv.org/abs/1911.01303).
92/// Applies the calculated covaraince matrix to the RooMinimizer and returns
93/// the quality of the covariance matrix.
94/// See also the documentation of RooAbsPdf::fitTo(), where this function is used.
95/// \param[in] minimizer The RooMinimizer to get the fit result from. The state
96/// of the minimizer will be altered by this function: the covariance
97/// matrix caltulated here will be applied to it via
98/// RooMinimizer::applyCovarianceMatrix().
99/// \param[in] data The dataset that was used for the fit.
100int calcAsymptoticCorrectedCovariance(RooAbsReal &pdf, RooMinimizer &minimizer, RooAbsData const &data)
101{
102 RooFormulaVar logpdf("logpdf", "log(pdf)", "log(@0)", pdf);
103 RooArgSet obs;
104 logpdf.getObservables(data.get(), obs);
105
106 // Warning if the dataset is binned. TODO: in some cases,
107 // people also use RooDataSet to encode binned data,
108 // e.g. for simultaneous fits. It would be useful to detect
109 // this in this future as well.
110 if (dynamic_cast<RooDataHist const *>(&data)) {
111 oocoutW(&pdf, InputArguments)
112 << "RooAbsPdf::fitTo(" << pdf.GetName()
113 << ") WARNING: Asymptotic error correction is requested for a binned data set. "
114 "This method is not designed to handle binned data. A standard chi2 fit will likely be more suitable.";
115 };
116
117 // Calculated corrected errors for weighted likelihood fits
118 std::unique_ptr<RooFitResult> rw(minimizer.save());
119 // Weighted inverse Hessian matrix
120 const TMatrixDSym &matV = rw->covarianceMatrix();
121 oocoutI(&pdf, Fitting)
122 << "RooAbsPdf::fitTo(" << pdf.GetName()
123 << ") Calculating covariance matrix according to the asymptotically correct approach. If you find this "
124 "method useful please consider citing https://arxiv.org/abs/1911.01303.\n";
125
126 // Initialise matrix containing first derivatives
127 int nFloatPars = rw->floatParsFinal().size();
128 TMatrixDSym num(nFloatPars);
129 for (int k = 0; k < nFloatPars; k++) {
130 for (int l = 0; l < nFloatPars; l++) {
131 num(k, l) = 0.0;
132 }
133 }
134
135 // Create derivative objects
136 std::vector<std::unique_ptr<RooDerivative>> derivatives;
137 const RooArgList &floated = rw->floatParsFinal();
138 RooArgSet allparams;
139 logpdf.getParameters(data.get(), allparams);
140 std::unique_ptr<RooArgSet> floatingparams{allparams.selectByAttrib("Constant", false)};
141
142 const double eps = 1.0e-4;
143
144 // Calculate derivatives of logpdf
145 for (const auto paramresult : floated) {
146 auto paraminternal = static_cast<RooRealVar *>(floatingparams->find(*paramresult));
147 assert(floatingparams->find(*paramresult)->IsA() == RooRealVar::Class());
148 double error = static_cast<RooRealVar *>(paramresult)->getError();
149 derivatives.emplace_back(logpdf.derivative(*paraminternal, obs, 1, eps * error));
150 }
151
152 // Calculate derivatives for number of expected events, needed for extended ML fit
153 RooAbsPdf *extended_pdf = dynamic_cast<RooAbsPdf *>(&pdf);
154 std::vector<double> diffs_expected(floated.size(), 0.0);
155 if (extended_pdf && extended_pdf->expectedEvents(obs) != 0.0) {
156 for (std::size_t k = 0; k < floated.size(); k++) {
157 const auto paramresult = static_cast<RooRealVar *>(floated.at(k));
158 auto paraminternal = static_cast<RooRealVar *>(floatingparams->find(*paramresult));
159
160 *paraminternal = paramresult->getVal();
161 double error = paramresult->getError();
162 paraminternal->setVal(paramresult->getVal() + eps * error);
163 double expected_plus = log(extended_pdf->expectedEvents(obs));
164 paraminternal->setVal(paramresult->getVal() - eps * error);
165 double expected_minus = log(extended_pdf->expectedEvents(obs));
166 *paraminternal = paramresult->getVal();
167 double diff = (expected_plus - expected_minus) / (2.0 * eps * error);
168 diffs_expected[k] = diff;
169 }
170 }
171
172 // Loop over data
173 for (int j = 0; j < data.numEntries(); j++) {
174 // Sets obs to current data point, this is where the pdf will be evaluated
175 obs.assign(*data.get(j));
176 // Determine first derivatives
177 std::vector<double> diffs(floated.size(), 0.0);
178 for (std::size_t k = 0; k < floated.size(); k++) {
179 const auto paramresult = static_cast<RooRealVar *>(floated.at(k));
180 auto paraminternal = static_cast<RooRealVar *>(floatingparams->find(*paramresult));
181 // first derivative to parameter k at best estimate point for this measurement
182 double diff = derivatives[k]->getVal();
183 // need to reset to best fit point after differentiation
184 *paraminternal = paramresult->getVal();
185 diffs[k] = diff;
186 }
187
188 // Fill numerator matrix
189 for (std::size_t k = 0; k < floated.size(); k++) {
190 for (std::size_t l = 0; l < floated.size(); l++) {
191 num(k, l) += data.weightSquared() * (diffs[k] + diffs_expected[k]) * (diffs[l] + diffs_expected[l]);
192 }
193 }
194 }
195 num.Similarity(matV);
196
197 // Propagate corrected errors to parameters objects
198 minimizer.applyCovarianceMatrix(num);
199
200 // The derivatives are found in RooFit and not with the minimizer (e.g.
201 // minuit), so the quality of the corrected covariance matrix corresponds to
202 // the quality of the original covariance matrix
203 return rw->covQual();
204}
205
206////////////////////////////////////////////////////////////////////////////////
207/// Apply correction to errors and covariance matrix. This uses two covariance
208/// matrices, one with the weights, the other with squared weights, to obtain
209/// the correct errors for weighted likelihood fits.
210/// Applies the calculated covaraince matrix to the RooMinimizer and returns
211/// the quality of the covariance matrix.
212/// See also the documentation of RooAbsPdf::fitTo(), where this function is used.
213/// \param[in] minimizer The RooMinimizer to get the fit result from. The state
214/// of the minimizer will be altered by this function: the covariance
215/// matrix caltulated here will be applied to it via
216/// RooMinimizer::applyCovarianceMatrix().
217/// \param[in] nll The NLL object that was used for the fit.
218int calcSumW2CorrectedCovariance(RooAbsReal const &pdf, RooMinimizer &minimizer, RooAbsReal &nll)
219{
220 // Calculated corrected errors for weighted likelihood fits
221 std::unique_ptr<RooFitResult> rw{minimizer.save()};
222 nll.applyWeightSquared(true);
223 oocoutI(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName()
224 << ") Calculating sum-of-weights-squared correction matrix for covariance matrix\n";
225 minimizer.hesse();
226 std::unique_ptr<RooFitResult> rw2{minimizer.save()};
227 nll.applyWeightSquared(false);
228
229 // Apply correction matrix
230 const TMatrixDSym &matV = rw->covarianceMatrix();
231 TMatrixDSym matC = rw2->covarianceMatrix();
233 if (!decomp) {
234 oocoutE(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName()
235 << ") ERROR: Cannot apply sum-of-weights correction to covariance matrix: correction "
236 "matrix calculated with weight-squared is singular\n";
237 return -1;
238 }
239
240 // replace C by its inverse
241 decomp.Invert(matC);
242 // the class lies about the matrix being symmetric, so fill in the
243 // part above the diagonal
244 for (int i = 0; i < matC.GetNrows(); ++i) {
245 for (int j = 0; j < i; ++j) {
246 matC(j, i) = matC(i, j);
247 }
248 }
249 matC.Similarity(matV);
250 // C now contains V C^-1 V
251 // Propagate corrected errors to parameters objects
252 minimizer.applyCovarianceMatrix(matC);
253
254 return std::min(rw->covQual(), rw2->covQual());
255}
256
257/// Configuration struct for RooAbsPdf::minimizeNLL with all the default values
258/// that also should be taken as the default values for RooAbsPdf::fitTo.
259struct MinimizerConfig {
260 double recoverFromNaN = 10.;
261 int verbose = 0;
262 int doSave = 0;
263 int doTimer = 0;
264 int printLevel = 1;
265 int strategy = 1;
266 int initHesse = 0;
267 int hesse = 1;
268 int minos = 0;
269 int numee = 10;
270 int doEEWall = 1;
271 int doWarn = 1;
272 int doSumW2 = -1;
273 int doAsymptotic = -1;
274 int maxCalls = -1;
275 int doOffset = -1;
276 int parallelize = 0;
277 bool enableParallelGradient = false;
278 bool enableParallelDescent = false;
279 int parallelDescentNumSplits = 0;
280 int parallelDescentSplitStrategy = 0;
281 bool timingAnalysis = false;
282 const RooArgSet *minosSet = nullptr;
283 std::string minType;
284 std::string minAlg = "minuit";
285};
286
287/// Validates the NumCPU() argument for the given evaluation backend and returns
288/// the effective number of worker threads for the RooFit::Evaluator.
289int effectiveNumWorkers(RooAbsArg const &arg, RooFit::EvalBackend::Value evalBackend, int numCpu)
290{
292
293 if (numCpu <= 1) {
294 return 1;
295 }
296 if (evalBackend == Value::Cuda) {
297 oocoutW(&arg, Fitting) << "The NumCPU() option is ignored by the CUDA evaluation backend." << std::endl;
298 return 1;
299 }
300 if (evalBackend == Value::CodegenNoGrad) {
301 oocoutW(&arg, Fitting) << "The NumCPU() option has no effect with EvalBackend(\"codegen_no_grad\"), "
302 "because the test statistic is evaluated with single-threaded generated code."
303 << std::endl;
304 return 1;
305 }
306 if (evalBackend == Value::Codegen) {
307 oocxcoutI(&arg, Fitting) << "NumCPU(" << numCpu << ") enables multi-threaded evaluation of large batches "
308 << "for test statistic values. The generated gradient code is not affected."
309 << std::endl;
310 return numCpu;
311 }
312 oocxcoutI(&arg, Fitting) << "NumCPU(" << numCpu << ") enables multi-threaded evaluation of large batches in "
313 << "the RooBatchCompute library. The interleaving strategy argument of NumCPU() is "
314 << "ignored." << std::endl;
315 return numCpu;
316}
317
318bool interpretExtendedCmdArg(RooAbsPdf const &pdf, int extendedCmdArg)
319{
320 // Process automatic extended option
321 if (extendedCmdArg == extendedFitDefault) {
323 if (ext) {
324 oocoutI(&pdf, Minimization)
325 << "p.d.f. provides expected number of events, including extended term in likelihood." << std::endl;
326 }
327 return ext;
328 }
329 // If Extended(false) was explicitly set, but the pdf MUST be extended, then
330 // it's time to print an error. This happens when you're fitting a RooAddPdf
331 // with coefficient that represent yields, and without the additional
332 // constraint these coefficients are degenerate because the RooAddPdf
333 // normalizes itself. Nothing correct can come out of this.
334 if (extendedCmdArg == 0) {
336 std::string errMsg = "You used the Extended(false) option on a pdf where the fit MUST be extended! "
337 "The parameters are not well defined and you're getting nonsensical results.";
338 oocoutE(&pdf, InputArguments) << errMsg << std::endl;
339 }
340 }
341 return extendedCmdArg;
342}
343
344/// To set the fitrange attribute of the PDF and custom ranges for the
345/// observables so that RooPlot can automatically plot the fitting range.
346void resetFitrangeAttributes(RooAbsArg &pdf, RooAbsData const &data, std::string const &baseName, const char *rangeName,
347 bool splitRange)
348{
349 // Clear possible range attributes from previous fits.
350 pdf.removeStringAttribute("fitrange");
351
352 // No fitrange was specified, so we do nothing. Or "SplitRange" is used, and
353 // then there are no uniquely defined ranges for the observables (as they
354 // are different in each category).
355 if (!rangeName || splitRange)
356 return;
357
358 RooArgSet observables;
359 pdf.getObservables(data.get(), observables);
360
361 std::string fitrangeValue;
362 auto subranges = ROOT::Split(rangeName, ",");
363 for (auto const &subrange : subranges) {
364 if (subrange.empty())
365 continue;
366 std::string fitrangeValueSubrange = std::string("fit_") + baseName;
367 if (subranges.size() > 1) {
368 fitrangeValueSubrange += "_" + subrange;
369 }
370 fitrangeValue += fitrangeValueSubrange + ",";
371 for (RooAbsArg *arg : observables) {
372
373 if (arg->isCategory())
374 continue;
375 auto &observable = static_cast<RooRealVar &>(*arg);
376
377 observable.setRange(fitrangeValueSubrange.c_str(), observable.getMin(subrange.c_str()),
378 observable.getMax(subrange.c_str()));
379 }
380 }
381 pdf.setStringAttribute("fitrange", fitrangeValue.substr(0, fitrangeValue.size() - 1).c_str());
382}
383
384/// Iterate the simultaneous pdf's categories and build one test-statistic term
385/// per channel via `makeTerm`. Channels excluded by the (optional) category
386/// range are skipped. The per-channel term's special variables are prefixed
387/// with `_<catName>_`. The terms are summed into a RooAddition named
388/// `combinedName`.
389template <typename TermFactory>
390std::unique_ptr<RooAddition> createSimultaneousStat(RooSimultaneous const &simPdf, std::string const &rangeName,
391 std::string const &combinedName, TermFactory &&makeTerm)
392{
393 RooAbsCategoryLValue const &simCat = simPdf.indexCat();
394
395 RooArgList terms;
396 for (auto const &catState : simCat) {
397 std::string const &catName = catState.first;
398 RooAbsCategory::value_type catIndex = catState.second;
399
400 // Skip channels excluded by a category range (only RooCategory supports
401 // ranges on categorical values).
402 if (!rangeName.empty()) {
403 auto simCatAsRooCategory = dynamic_cast<RooCategory const *>(&simCat);
404 if (simCatAsRooCategory && !simCatAsRooCategory->isStateInRange(rangeName.c_str(), catIndex)) {
405 continue;
406 }
407 }
408
409 RooAbsPdf *channelPdf = simPdf.getPdf(catName.c_str());
410 if (!channelPdf) {
411 continue;
412 }
413 std::unique_ptr<RooArgSet> observables{
414 std::unique_ptr<RooArgSet>(channelPdf->getVariables())->selectByAttrib("__obs__", true)};
415 std::unique_ptr<RooNLLVarNew> term = makeTerm(*channelPdf, *observables);
416 term->setPrefix(std::string("_") + catName + "_");
417 terms.addOwned(std::move(term));
418 }
419
420 auto combined = std::make_unique<RooAddition>(combinedName.c_str(), combinedName.c_str(), terms);
421 combined->addOwnedComponents(std::move(terms));
422 return combined;
423}
424
425std::unique_ptr<RooAbsArg> createSimultaneousChi2(RooSimultaneous const &simPdf, std::string const &rangeName,
426 bool isSimPdfExtended, RooDataHist::ErrorType etype)
427{
428 auto chi2 =
429 createSimultaneousStat(simPdf, rangeName, "simChi2", [&](RooAbsPdf &channelPdf, RooArgSet const &observables) {
430 RooNLLVarNew::Config cfg;
431 cfg.statistic = RooNLLVarNew::Statistic::Chi2;
432 cfg.extended = isSimPdfExtended && channelPdf.extendMode() != RooAbsPdf::CanNotBeExtended;
433 cfg.chi2ErrorType = etype;
434 auto name = std::string("chi2_") + channelPdf.GetName();
435 return std::make_unique<RooNLLVarNew>(name.c_str(), name.c_str(), channelPdf, observables, cfg);
436 });
437 // Flag the top node so RooEvaluatorWrapper knows not to skip zero-weight bins
438 chi2->setAttribute("Chi2EvaluationActive");
439 return chi2;
440}
441
442std::unique_ptr<RooAbsArg> createSimultaneousNLL(RooSimultaneous const &simPdf, bool isSimPdfExtended,
443 std::string const &rangeName, RooFit::OffsetMode offset)
444{
445 auto nll =
446 createSimultaneousStat(simPdf, rangeName, "mynll", [&](RooAbsPdf &channelPdf, RooArgSet const &observables) {
447 RooNLLVarNew::Config cfg;
448 // Only request extended NLLs for channels that can be extended.
449 cfg.extended = isSimPdfExtended && channelPdf.extendMode() != RooAbsPdf::CanNotBeExtended;
450 cfg.offsetMode = offset;
451 auto name = std::string("nll_") + channelPdf.GetName();
452 return std::make_unique<RooNLLVarNew>(name.c_str(), name.c_str(), channelPdf, observables, cfg);
453 });
454
455 const int simCount = nll->list().size();
456 for (auto *child : static_range_cast<RooNLLVarNew *>(nll->list())) {
457 child->setSimCount(simCount);
458 }
459 return nll;
460}
461
462/// Apply the `IntegrateBins` precision to either a single pdf or in-place to
463/// the component pdfs of a RooSimultaneous. Newly-allocated wrapper pdfs are
464/// appended to `ownedOut`. The returned reference points either at one of
465/// those wrappers or at the input pdf itself.
466RooAbsPdf &applyIntegrateBinsWrapping(RooAbsPdf &pdf, RooAbsData const &data, double precision, RooArgList &ownedOut)
467{
468 if (auto *simPdf = dynamic_cast<RooSimultaneous *>(&pdf)) {
469 simPdf->wrapPdfsInBinSamplingPdfs(data, precision);
470 return pdf;
471 }
472 if (std::unique_ptr<RooAbsPdf> wrapped = RooBinSamplingPdf::create(pdf, data, precision)) {
473 RooAbsPdf &ref = *wrapped;
474 ownedOut.addOwned(std::move(wrapped));
475 return ref;
476 }
477 return pdf;
478}
479
480/// RAII helper for the `setNormRange` + SplitRange/RangeName attribute setting
481/// that must be done around `compileForNormSet` so that the compiled pdf sees
482/// the restricted normalization range. All mutations are reverted on
483/// destruction.
484class NormRangeScope {
485public:
486 NormRangeScope(RooAbsPdf &pdf, const char *rangeName, bool splitRange) : _pdf{&pdf}
487 {
488 if (pdf.normRange()) {
489 _oldNormRange = pdf.normRange();
490 }
491 pdf.setNormRange(rangeName);
492 pdf.setAttribute("SplitRange", splitRange);
493 pdf.setStringAttribute("RangeName", rangeName);
494 }
495 NormRangeScope(NormRangeScope const &) = delete;
496 NormRangeScope &operator=(NormRangeScope const &) = delete;
497 ~NormRangeScope()
498 {
499 _pdf->setAttribute("SplitRange", false);
500 _pdf->setStringAttribute("RangeName", nullptr);
501 _pdf->setNormRange(_oldNormRange.empty() ? nullptr : _oldNormRange.c_str());
502 }
503
504private:
505 RooAbsPdf *_pdf;
506 std::string _oldNormRange;
507};
508
509/// Shared `compileForNormSet` sequence used by both the NLL and chi2 CPU
510/// backends. Sets up the reduced normalization range via `NormRangeScope`,
511/// then runs the graph compilation. When `likelihoodMode` is true the
512/// CompileContext is flagged accordingly (enabling binned-likelihood
513/// optimisations in the compiled pdf). The returned compiled pdf has
514/// `fixAddCoefRange` already applied when `addCoefRangeName` is non-empty.
515std::unique_ptr<RooAbsPdf> compilePdfForFit(RooAbsPdf &pdf, RooArgSet const &normSet, const char *rangeName,
516 bool splitRange, const char *addCoefRangeName, bool likelihoodMode)
517{
518 NormRangeScope scope{pdf, rangeName, splitRange};
519
521 ctx.setLikelihoodMode(likelihoodMode);
522 std::unique_ptr<RooAbsArg> head = pdf.compileForNormSet(normSet, ctx);
523 std::unique_ptr<RooAbsPdf> pdfClone{&dynamic_cast<RooAbsPdf &>(*head.release())};
524
525 if (addCoefRangeName && *addCoefRangeName) {
526 pdfClone->fixAddCoefRange(addCoefRangeName, false);
527 }
528 return pdfClone;
529}
530
531std::unique_ptr<RooAbsReal> createNLLNew(RooAbsPdf &pdf, RooAbsData &data, std::unique_ptr<RooAbsReal> &&constraints,
532 std::string const &rangeName, RooArgSet const &projDeps, bool isExtended,
533 double integrateOverBinsPrecision, RooFit::OffsetMode offset)
534{
535 if (constraints) {
536 // The computation graph for the constraints is very small, no need to do
537 // the tracking of clean and dirty nodes here.
538 constraints->setOperMode(RooAbsArg::ADirty);
539 }
540
541 RooArgSet observables;
542 pdf.getObservables(data.get(), observables);
543 observables.remove(projDeps, true, true);
544
545 oocxcoutI(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName()
546 << ") fixing normalization set for coefficient determination to observables in data"
547 << "\n";
548 pdf.fixAddCoefNormalization(observables, false);
549
550 RooArgList binSamplingPdfs;
551 RooAbsPdf &finalPdf = applyIntegrateBinsWrapping(pdf, data, integrateOverBinsPrecision, binSamplingPdfs);
552
553 RooArgList nllTerms;
554 auto *simPdf = dynamic_cast<RooSimultaneous *>(&finalPdf);
555 // A RooSimultaneous whose index category is not among the data columns is
556 // a "switch" pdf selecting the component given by the current index state
557 // (analogous to RooMultiPdf): there are no channels to split the NLL into,
558 // so it is treated like an ordinary pdf.
559 if (simPdf && simPdf->indexCatIsObservable(*data.get())) {
560 nllTerms.addOwned(createSimultaneousNLL(*simPdf, isExtended, rangeName, offset));
561 } else {
562 RooNLLVarNew::Config cfg;
563 cfg.extended = isExtended;
564 cfg.offsetMode = offset;
565 nllTerms.addOwned(std::make_unique<RooNLLVarNew>("RooNLLVarNew", "RooNLLVarNew", finalPdf, observables, cfg));
566 }
567 if (constraints) {
568 nllTerms.addOwned(std::move(constraints));
569 }
570
571 std::string nllName = std::string("nll_") + pdf.GetName() + "_" + data.GetName();
572 auto nll = std::make_unique<RooAddition>(nllName.c_str(), nllName.c_str(), nllTerms);
573 nll->addOwnedComponents(std::move(binSamplingPdfs));
574 nll->addOwnedComponents(std::move(nllTerms));
575
576 return nll;
577}
578
579} // namespace
580
581namespace RooFit::FitHelpers {
582
583void defineMinimizationOptions(RooCmdConfig &pc)
584{
585 // Default-initialized instance of MinimizerConfig to get the default
586 // minimizer parameter values.
587 MinimizerConfig minimizerDefaults;
588
589 pc.defineDouble("RecoverFromUndefinedRegions", "RecoverFromUndefinedRegions", 0, minimizerDefaults.recoverFromNaN);
590 pc.defineInt("verbose", "Verbose", 0, minimizerDefaults.verbose);
591 pc.defineInt("doSave", "Save", 0, minimizerDefaults.doSave);
592 pc.defineInt("doTimer", "Timer", 0, minimizerDefaults.doTimer);
593 pc.defineInt("printLevel", "PrintLevel", 0, minimizerDefaults.printLevel);
594 pc.defineInt("strategy", "Strategy", 0, minimizerDefaults.strategy);
595 pc.defineInt("initHesse", "InitialHesse", 0, minimizerDefaults.initHesse);
596 pc.defineInt("hesse", "Hesse", 0, minimizerDefaults.hesse);
597 pc.defineInt("minos", "Minos", 0, minimizerDefaults.minos);
598 pc.defineInt("numee", "PrintEvalErrors", 0, minimizerDefaults.numee);
599 pc.defineInt("doEEWall", "EvalErrorWall", 0, minimizerDefaults.doEEWall);
600 pc.defineInt("doWarn", "Warnings", 0, minimizerDefaults.doWarn);
601 pc.defineInt("doSumW2", "SumW2Error", 0, minimizerDefaults.doSumW2);
602 pc.defineInt("doAsymptoticError", "AsymptoticError", 0, minimizerDefaults.doAsymptotic);
603 pc.defineInt("maxCalls", "MaxCalls", 0, minimizerDefaults.maxCalls);
604 pc.defineInt("doOffset", "OffsetLikelihood", 0, minimizerDefaults.doOffset);
605 pc.defineInt("parallelize", "Parallelize", 0, minimizerDefaults.parallelize); // Three parallelize arguments
606 pc.defineInt("enableParallelGradient", "ParallelGradientOptions", 0, minimizerDefaults.enableParallelGradient);
607 pc.defineInt("enableParallelDescent", "ParallelDescentOptions", 0, minimizerDefaults.enableParallelDescent);
608 pc.defineInt("parallelDescentNumSplits", "ParallelDescentOptions", 1, minimizerDefaults.parallelDescentNumSplits);
609 pc.defineInt("parallelDescentSplitStrategy", "ParallelDescentOptions", 2,
610 minimizerDefaults.parallelDescentSplitStrategy);
611 pc.defineInt("timingAnalysis", "TimingAnalysis", 0, minimizerDefaults.timingAnalysis);
612 pc.defineString("mintype", "Minimizer", 0, minimizerDefaults.minType.c_str());
613 pc.defineString("minalg", "Minimizer", 1, minimizerDefaults.minAlg.c_str());
614 pc.defineSet("minosSet", "Minos", 0, minimizerDefaults.minosSet);
615}
616
617////////////////////////////////////////////////////////////////////////////////
618/// Minimizes a given NLL variable by finding the optimal parameters with the
619/// RooMinimzer. The NLL variable can be created with RooAbsPdf::createNLL.
620/// If you are looking for a function that combines likelihood creation with
621/// fitting, see RooAbsPdf::fitTo.
622/// \param[in] nll The negative log-likelihood variable to minimize.
623/// \param[in] data The dataset that was also used for the NLL. It's a necessary
624/// parameter because it is used in the asymptotic error correction.
625/// \param[in] cfg Configuration struct with all the configuration options for
626/// the RooMinimizer. These are a subset of the options that you can
627/// also pass to RooAbsPdf::fitTo via the RooFit command arguments.
628std::unique_ptr<RooFitResult>
629minimize(RooAbsReal &model, RooAbsReal &nll, RooAbsData const &data, RooCmdConfig const &pc)
630{
631 MinimizerConfig cfg;
632 cfg.recoverFromNaN = pc.getDouble("RecoverFromUndefinedRegions");
633 cfg.verbose = pc.getInt("verbose");
634 cfg.doSave = pc.getInt("doSave");
635 cfg.doTimer = pc.getInt("doTimer");
636 cfg.printLevel = pc.getInt("printLevel");
637 cfg.strategy = pc.getInt("strategy");
638 cfg.initHesse = pc.getInt("initHesse");
639 cfg.hesse = pc.getInt("hesse");
640 cfg.minos = pc.getInt("minos");
641 cfg.numee = pc.getInt("numee");
642 cfg.doEEWall = pc.getInt("doEEWall");
643 cfg.doWarn = pc.getInt("doWarn");
644 cfg.doSumW2 = pc.getInt("doSumW2");
645 cfg.doAsymptotic = pc.getInt("doAsymptoticError");
646 cfg.maxCalls = pc.getInt("maxCalls");
647 cfg.minosSet = pc.getSet("minosSet");
648 cfg.minType = pc.getString("mintype", "");
649 cfg.minAlg = pc.getString("minalg", "minuit");
650 cfg.doOffset = pc.getInt("doOffset");
651 cfg.parallelize = pc.getInt("parallelize");
652 cfg.enableParallelGradient = pc.getInt("enableParallelGradient");
653 cfg.enableParallelDescent = pc.getInt("enableParallelDescent");
654 cfg.parallelDescentNumSplits = pc.getInt("parallelDescentNumSplits");
655 cfg.parallelDescentSplitStrategy = pc.getInt("parallelDescentSplitStrategy");
656 cfg.timingAnalysis = pc.getInt("timingAnalysis");
657
658 // Determine if the dataset has weights
659 bool weightedData = data.isNonPoissonWeighted();
660
661 // The weighted-data uncertainty correction options only apply to likelihood
662 // fits. Skip the NLL-only paths when minimizing a chi-squared test statistic.
663 const bool isChi2 = nll.getAttribute("Chi2EvaluationActive");
664
665 std::string msgPrefix = std::string{"RooAbsPdf::fitTo("} + model.GetName() + "): ";
666
667 // Warn user that a method to determine parameter uncertainties should be provided if weighted data is offered
668 if (!isChi2 && weightedData && cfg.doSumW2 == -1 && cfg.doAsymptotic == -1) {
669 oocoutW(&model, InputArguments) << msgPrefix <<
670 R"(WARNING: a likelihood fit is requested of what appears to be weighted data.
671 While the estimated values of the parameters will always be calculated taking the weights into account,
672 there are multiple ways to estimate the errors of the parameters. You are advised to make an
673 explicit choice for the error calculation:
674 - Either provide SumW2Error(true), to calculate a sum-of-weights-corrected HESSE error matrix
675 (error will be proportional to the number of events in MC).
676 - Or provide SumW2Error(false), to return errors from original HESSE error matrix
677 (which will be proportional to the sum of the weights, i.e., a dataset with <sum of weights> events).
678 - Or provide AsymptoticError(true), to use the asymptotically correct expression
679 (for details see https://arxiv.org/abs/1911.01303)."
680)";
681 }
682
683 if (cfg.minos && (cfg.doSumW2 == 1 || cfg.doAsymptotic == 1)) {
684 oocoutE(&model, InputArguments)
685 << msgPrefix
686 << " sum-of-weights and asymptotic error correction do not work with MINOS errors. Not fitting.\n";
687 return nullptr;
688 }
689 if (cfg.doAsymptotic == 1 && cfg.minos) {
690 oocoutW(&model, InputArguments) << msgPrefix << "WARNING: asymptotic correction does not apply to MINOS errors\n";
691 }
692
693 // avoid setting both SumW2 and Asymptotic for uncertainty correction
694 if (cfg.doSumW2 == 1 && cfg.doAsymptotic == 1) {
695 oocoutE(&model, InputArguments) << msgPrefix
696 << "ERROR: Cannot compute both asymptotically correct and SumW2 errors.\n";
697 return nullptr;
698 }
699
700 // Apply the experimental likelihood-splitting settings from
701 // ParallelDescentOptions(). A numSplits value of zero keeps the automatic
702 // task-splitting defaults of RooFit::MultiProcess.
703 if (cfg.parallelDescentNumSplits > 0) {
704#ifdef ROOFIT_MULTIPROCESS
705 if (cfg.parallelDescentSplitStrategy == 0) {
707 } else {
709 }
710#else
711 oocoutW(&model, InputArguments) << "Likelihood-splitting settings passed via ParallelDescentOptions() are "
712 "ignored, because ROOT was built without RooFit::MultiProcess support"
713 << std::endl;
714#endif
715 }
716
717 // Instantiate RooMinimizer
718 RooMinimizer::Config minimizerConfig;
719 minimizerConfig.enableParallelGradient = cfg.enableParallelGradient;
720 minimizerConfig.enableParallelDescent = cfg.enableParallelDescent;
721 minimizerConfig.parallelize = cfg.parallelize;
722 minimizerConfig.timingAnalysis = cfg.timingAnalysis;
723 minimizerConfig.offsetting = cfg.doOffset;
724 RooMinimizer m(nll, minimizerConfig);
725
726 m.setMinimizerType(cfg.minType);
727 m.setEvalErrorWall(cfg.doEEWall);
728 m.setRecoverFromNaNStrength(cfg.recoverFromNaN);
729 m.setPrintEvalErrors(cfg.numee);
730 if (cfg.maxCalls > 0)
731 m.setMaxFunctionCalls(cfg.maxCalls);
732 if (cfg.printLevel != 1)
733 m.setPrintLevel(cfg.printLevel);
734 if (cfg.verbose)
735 m.setVerbose(true); // Activate verbose options
736 if (cfg.doTimer)
737 m.setProfile(true); // Activate timer options
738 if (cfg.strategy != 1)
739 m.setStrategy(cfg.strategy); // Modify fit strategy
740 if (cfg.initHesse)
741 m.hesse(); // Initialize errors with hesse
742 m.minimize(cfg.minType.c_str(), cfg.minAlg.c_str()); // Minimize using chosen algorithm
743 if (cfg.hesse)
744 m.hesse(); // Evaluate errors with Hesse
745
746 int corrCovQual = -1;
747
748 if (!isChi2 && m.getNPar() > 0) {
749 if (cfg.doAsymptotic == 1)
750 corrCovQual = calcAsymptoticCorrectedCovariance(model, m, data); // Asymptotically correct
751 if (cfg.doSumW2 == 1)
752 corrCovQual = calcSumW2CorrectedCovariance(model, m, nll);
753 }
754
755 if (cfg.minos)
756 cfg.minosSet ? m.minos(*cfg.minosSet) : m.minos(); // Evaluate errs with Minos
757
758 // Optionally return fit result
759 std::unique_ptr<RooFitResult> ret;
760 if (cfg.doSave) {
761 auto name = std::string("fitresult_") + model.GetName() + "_" + data.GetName();
762 auto title = std::string("Result of fit of p.d.f. ") + model.GetName() + " to dataset " + data.GetName();
763 ret = std::unique_ptr<RooFitResult>{m.save(name.c_str(), title.c_str())};
764 if ((cfg.doSumW2 == 1 || cfg.doAsymptotic == 1) && m.getNPar() > 0)
765 ret->setCovQual(corrCovQual);
766 }
767
768 return ret;
769}
770
771std::unique_ptr<RooAbsReal> createNLL(RooAbsPdf &pdf, RooAbsData &data, const RooLinkedList &cmdList)
772{
773 checkNestedSimultaneous(pdf, *data.get());
774
775 auto timingScope = std::make_unique<ROOT::Math::Util::TimingScope>(
776 [&pdf](std::string const &msg) { oocoutI(&pdf, Fitting) << msg << std::endl; }, "Creation of NLL object took");
777
778 auto baseName = std::string("nll_") + pdf.GetName() + "_" + data.GetName();
779
780 // Select the pdf-specific commands
781 RooCmdConfig pc("RooAbsPdf::createNLL(" + std::string(pdf.GetName()) + ")");
782
783 pc.defineString("rangeName", "RangeWithName", 0, "", true);
784 pc.defineString("addCoefRange", "SumCoefRange", 0, "");
785 pc.defineString("globstag", "GlobalObservablesTag", 0, "");
786 pc.defineString("globssource", "GlobalObservablesSource", 0, "data");
787 pc.defineDouble("rangeLo", "Range", 0, -999.);
788 pc.defineDouble("rangeHi", "Range", 1, -999.);
789 pc.defineInt("splitRange", "SplitRange", 0, 0);
790 pc.defineInt("ext", "Extended", 0, extendedFitDefault);
791 pc.defineInt("numcpu", "NumCPU", 0, 1);
792 pc.defineInt("interleave", "NumCPU", 1, 0);
793 pc.defineInt("verbose", "Verbose", 0, 0);
794 pc.defineInt("cloneData", "CloneData", 0, 0);
795 pc.defineSet("projDepSet", "ProjectedObservables", 0, nullptr);
796 pc.defineSet("cPars", "Constrain", 0, nullptr);
797 pc.defineSet("glObs", "GlobalObservables", 0, nullptr);
798 pc.defineInt("doOffset", "OffsetLikelihood", 0, 0);
799 pc.defineSet("extCons", "ExternalConstraints", 0, nullptr);
800 pc.defineInt("EvalBackend", "EvalBackend", 0, static_cast<int>(RooFit::EvalBackend::defaultValue()));
801 pc.defineDouble("IntegrateBins", "IntegrateBins", 0, -1.);
802 pc.defineMutex("Range", "RangeWithName");
803 pc.defineMutex("GlobalObservables", "GlobalObservablesTag");
804 pc.defineInt("ModularL", "ModularL", 0, 0);
805
806 // New style likelihoods define parallelization through Parallelize(...) on fitTo or attributes on
807 // RooMinimizer::Config.
808 pc.defineMutex("ModularL", "NumCPU");
809
810 // New style likelihoods define offsetting on minimizer, not on likelihood
811 pc.defineMutex("ModularL", "OffsetLikelihood");
812
813 // Process and check varargs
814 pc.process(cmdList);
815 if (!pc.ok(true)) {
816 return nullptr;
817 }
818
819 if (pc.getInt("ModularL")) {
820 int lut[3] = {2, 1, 0};
822 static_cast<RooFit::TestStatistics::RooAbsL::Extended>(lut[pc.getInt("ext")])};
823
824 RooArgSet cParsSet;
825 RooArgSet extConsSet;
826 RooArgSet glObsSet;
827
828 if (auto tmp = pc.getSet("cPars"))
829 cParsSet.add(*tmp);
830
831 if (auto tmp = pc.getSet("extCons"))
832 extConsSet.add(*tmp);
833
834 if (auto tmp = pc.getSet("glObs"))
835 glObsSet.add(*tmp);
836
837 const std::string rangeName = pc.getString("globstag", "", false);
838
840 builder.Extended(ext)
841 .ConstrainedParameters(cParsSet)
842 .ExternalConstraints(extConsSet)
843 .GlobalObservables(glObsSet)
844 .GlobalObservablesTag(rangeName.c_str())
845 .EvalBackend(RooFit::EvalBackend(static_cast<RooFit::EvalBackend::Value>(pc.getInt("EvalBackend"))));
846
847 return std::make_unique<RooFit::TestStatistics::RooRealL>("likelihood", "", builder.build());
848 }
849
850 // Decode command line arguments
851 const char *rangeName = pc.getString("rangeName", nullptr, true);
852 const char *addCoefRangeName = pc.getString("addCoefRange", nullptr, true);
853 const bool ext = interpretExtendedCmdArg(pdf, pc.getInt("ext"));
854
855 int splitRange = pc.getInt("splitRange");
856 auto offset = static_cast<RooFit::OffsetMode>(pc.getInt("doOffset"));
857
858 if (pc.hasProcessed("Range")) {
859 double rangeLo = pc.getDouble("rangeLo");
860 double rangeHi = pc.getDouble("rangeHi");
861
862 // Create range with name 'fit' with above limits on all observables
863 RooArgSet obs;
864 pdf.getObservables(data.get(), obs);
865 for (auto *rrv : dynamic_range_cast<RooRealVar *>(obs)) {
866 if (rrv)
867 rrv->setRange("fit", rangeLo, rangeHi);
868 }
869
870 // Set range name to be fitted to "fit"
871 rangeName = "fit";
872 }
873
874 // Set the fitrange attribute of th PDF, add observables ranges for plotting
875 resetFitrangeAttributes(pdf, data, baseName, rangeName, splitRange);
876
877 RooArgSet projDeps;
878 auto tmp = pc.getSet("projDepSet");
879 if (tmp) {
880 projDeps.add(*tmp);
881 }
882
883 const std::string globalObservablesSource = pc.getString("globssource", "data", false);
884 if (globalObservablesSource != "data" && globalObservablesSource != "model") {
885 std::string errMsg = "RooAbsPdf::fitTo: GlobalObservablesSource can only be \"data\" or \"model\"!";
886 oocoutE(&pdf, InputArguments) << errMsg << std::endl;
887 throw std::invalid_argument(errMsg);
888 }
889 const bool takeGlobalObservablesFromData = globalObservablesSource == "data";
890
891 // Lambda function to create the correct constraint term for a PDF. In old
892 // RooFit, we use this PDF itself as the argument, for the new BatchMode
893 // we're passing a clone.
894 auto createConstr = [&]() -> std::unique_ptr<RooAbsReal> {
895 return createConstraintTerm(baseName + "_constr", // name
896 pdf, // pdf
897 data, // data
898 pc.getSet("cPars"), // Constrain RooCmdArg
899 pc.getSet("extCons"), // ExternalConstraints RooCmdArg
900 pc.getSet("glObs"), // GlobalObservables RooCmdArg
901 pc.getString("globstag", nullptr, true), // GlobalObservablesTag RooCmdArg
902 takeGlobalObservablesFromData); // From GlobalObservablesSource RooCmdArg
903 };
904
905 auto evalBackend = static_cast<RooFit::EvalBackend::Value>(pc.getInt("EvalBackend"));
906
907 RooArgSet normSet;
908 pdf.getObservables(data.get(), normSet);
909
910 auto *simPdfForProjDeps = dynamic_cast<RooSimultaneous const *>(&pdf);
911 if (simPdfForProjDeps && simPdfForProjDeps->indexCatIsObservable(normSet)) {
912 for (auto i : projDeps) {
913 auto res = normSet.find(i->GetName());
914 if (res != nullptr) {
915 res->setAttribute("__conditional__");
916 }
917 }
918 } else {
919 normSet.remove(projDeps);
920 }
921
922 std::unique_ptr<RooAbsPdf> pdfClone =
923 compilePdfForFit(pdf, normSet, rangeName, splitRange, addCoefRangeName, /*likelihoodMode=*/true);
924
925 if (addCoefRangeName) {
926 oocxcoutI(&pdf, Fitting) << "RooAbsPdf::fitTo(" << pdf.GetName()
927 << ") fixing interpretation of coefficients of any component to range "
928 << addCoefRangeName << "\n";
929 }
930
931 std::unique_ptr<RooAbsReal> compiledConstr;
932 if (std::unique_ptr<RooAbsReal> constr = createConstr()) {
933 compiledConstr = RooFit::Detail::compileForNormSet(*constr, *data.get());
934 compiledConstr->addOwnedComponents(std::move(constr));
935 }
936
937 auto nll = createNLLNew(*pdfClone, data, std::move(compiledConstr), rangeName ? rangeName : "", projDeps, ext,
938 pc.getDouble("IntegrateBins"), offset);
939
940 const double correction = pdfClone->getCorrection();
941
942 if (correction > 0) {
943 oocoutI(&pdf, Fitting) << "[FitHelpers] Detected correction term from RooAbsPdf::getCorrection(). "
944 << "Adding penalty to NLL." << std::endl;
945
946 // Convert the multiplicative correction to an additive term in -log L
947 auto penaltyTerm = std::make_unique<RooConstVar>((baseName + "_Penalty").c_str(),
948 "Penalty term from getCorrection()", correction);
949
950 // add penalty and NLL
951 auto correctedNLL = std::make_unique<RooAddition>((baseName + "_corrected").c_str(), "NLL + penalty",
952 RooArgSet{*nll, *penaltyTerm});
953
954 // transfer ownership of terms
955 correctedNLL->addOwnedComponents(std::move(nll), std::move(penaltyTerm));
956 nll = std::move(correctedNLL);
957 }
958
959 const int nWorkers = effectiveNumWorkers(pdf, evalBackend, pc.getInt("numcpu"));
960
961 auto nllWrapper = std::make_unique<RooFit::Experimental::RooEvaluatorWrapper>(
962 *nll, &data, evalBackend == RooFit::EvalBackend::Value::Cuda, rangeName ? rangeName : "", pdfClone.get(),
963 takeGlobalObservablesFromData, nWorkers);
964
965 // We destroy the timing scrope for createNLL prematurely, because we
966 // separately measure the time for jitting and gradient creation
967 // inside the RooFuncWrapper.
968 timingScope.reset();
969
970 if (evalBackend == RooFit::EvalBackend::Value::Codegen) {
971 nllWrapper->generateGradient();
972 }
974 nllWrapper->setUseGeneratedFunctionCode(true);
975 }
976
977 nllWrapper->addOwnedComponents(std::move(nll));
978 nllWrapper->addOwnedComponents(std::move(pdfClone));
979
980 return nllWrapper;
981}
982
983std::unique_ptr<RooAbsReal> createChi2(RooAbsReal &real, RooDataHist &data, const RooLinkedList &cmdList)
984{
985 checkNestedSimultaneous(real, *data.get());
986
987 RooCmdConfig pc("createChi2(" + std::string(real.GetName()) + ")");
988
989 pc.defineInt("EvalBackend", "EvalBackend", 0, static_cast<int>(RooFit::EvalBackend::defaultValue()));
990 pc.defineInt("numcpu", "NumCPU", 0, 1);
991 pc.defineInt("verbose", "Verbose", 0, 0);
992 pc.defineString("rangeName", "RangeWithName", 0, "", true);
993 pc.defineDouble("rangeLo", "Range", 0, -999.);
994 pc.defineDouble("rangeHi", "Range", 1, -999.);
995 pc.defineMutex("Range", "RangeWithName");
996 pc.defineInt("etype", "DataError", 0, (Int_t)RooDataHist::Auto);
997 pc.defineInt("extended", "Extended", 0, extendedFitDefault);
998 pc.defineInt("splitRange", "SplitRange", 0, 0);
999 pc.defineDouble("integrate_bins", "IntegrateBins", 0, -1);
1000 pc.defineString("addCoefRange", "SumCoefRange", 0, "");
1001 pc.allowUndefined();
1002
1003 pc.process(cmdList);
1004 if (!pc.ok(true)) {
1005 return nullptr;
1006 }
1007
1008 // Clear possible range attributes from previous fits.
1009 real.removeStringAttribute("fitrange");
1010
1011 std::string baseName = "chi2_" + std::string(real.GetName()) + "_" + data.GetName();
1012
1013 auto evalBackend = static_cast<RooFit::EvalBackend::Value>(pc.getInt("EvalBackend"));
1014
1015 RooDataHist::ErrorType etype = static_cast<RooDataHist::ErrorType>(pc.getInt("etype"));
1016 // Resolve Auto to a concrete mode so it's consistent across backends.
1017 if (etype == RooDataHist::Auto) {
1018 etype = data.isNonPoissonWeighted() ? RooDataHist::SumW2 : RooDataHist::Expected;
1019 }
1020
1021 auto *pdf = dynamic_cast<RooAbsPdf *>(&real);
1022 const char *rangeName = pc.getString("rangeName", nullptr, true);
1023
1024 // Translate Range(lo, hi) into a "fit" named range on all observables.
1025 if (pc.hasProcessed("Range")) {
1026 const double rangeLo = pc.getDouble("rangeLo");
1027 const double rangeHi = pc.getDouble("rangeHi");
1028 RooArgSet obs;
1029 real.getObservables(data.get(), obs);
1030 for (auto *rrv : dynamic_range_cast<RooRealVar *>(obs)) {
1031 if (rrv) {
1032 rrv->setRange("fit", rangeLo, rangeHi);
1033 }
1034 }
1035 rangeName = "fit";
1036 }
1037
1039
1040 const int splitRange = pc.getInt("splitRange");
1041 resetFitrangeAttributes(real, data, baseName, rangeName, splitRange);
1042
1043 std::unique_ptr<RooFit::Experimental::RooEvaluatorWrapper> wrapper;
1044
1045 const int nWorkers = effectiveNumWorkers(real, evalBackend, pc.getInt("numcpu"));
1046
1047 // Function mode: the input is a non-pdf RooAbsReal. We can short-circuit
1048 // the pdf-compilation pipeline since there's no real pdf to normalize.
1049 if (!pdf) {
1050 RooArgSet observables;
1051 real.getObservables(data.get(), observables);
1052 RooNLLVarNew::Config cfg;
1053 cfg.statistic = RooNLLVarNew::Statistic::Chi2;
1054 cfg.chi2ErrorType = etype;
1055 auto chi2 = std::make_unique<RooNLLVarNew>(baseName.c_str(), baseName.c_str(), real, observables, cfg);
1056 wrapper = std::make_unique<RooFit::Experimental::RooEvaluatorWrapper>(
1057 *chi2, &data, evalBackend == RooFit::EvalBackend::Value::Cuda, rangeName ? rangeName : "",
1058 /*simPdf=*/nullptr,
1059 /*takeGlobalObservablesFromData=*/true, nWorkers);
1060 wrapper->addOwnedComponents(std::move(chi2));
1061 } else {
1062 const bool extended = interpretExtendedCmdArg(*pdf, pc.getInt("extended"));
1063
1064 RooArgSet normSet;
1065 pdf->getObservables(data.get(), normSet);
1066
1067 oocxcoutI(pdf, Fitting) << "createChi2(" << pdf->GetName()
1068 << ") fixing normalization set for coefficient determination to observables in data\n";
1069 pdf->fixAddCoefNormalization(normSet, false);
1070
1071 std::unique_ptr<RooAbsPdf> pdfClone =
1072 compilePdfForFit(*pdf, normSet, rangeName, splitRange, pc.getString("addCoefRange", nullptr, true),
1073 /*likelihoodMode=*/false);
1074
1075 RooArgList binSamplingPdfs;
1076 RooAbsPdf &finalPdf = applyIntegrateBinsWrapping(*pdfClone, data, pc.getDouble("integrate_bins"), binSamplingPdfs);
1077
1078 std::unique_ptr<RooAbsReal> chi2;
1079 auto *simPdfClone = dynamic_cast<RooSimultaneous *>(&finalPdf);
1080 // Like in createNLLNew(): a "switch"-mode RooSimultaneous (index
1081 // category not among the data columns) is treated as an ordinary pdf.
1082 if (simPdfClone && simPdfClone->indexCatIsObservable(*data.get())) {
1083 chi2 = std::unique_ptr<RooAbsReal>{dynamic_cast<RooAbsReal *>(
1084 createSimultaneousChi2(*simPdfClone, rangeName ? rangeName : "", extended, etype).release())};
1085 } else {
1086 RooArgSet observables;
1087 finalPdf.getObservables(data.get(), observables);
1088 RooNLLVarNew::Config cfg;
1089 cfg.statistic = RooNLLVarNew::Statistic::Chi2;
1090 cfg.extended = extended;
1091 cfg.chi2ErrorType = etype;
1092 chi2 = std::make_unique<RooNLLVarNew>(baseName.c_str(), baseName.c_str(), finalPdf, observables, cfg);
1093 }
1094
1095 wrapper = std::make_unique<RooFit::Experimental::RooEvaluatorWrapper>(
1096 *chi2, &data, evalBackend == RooFit::EvalBackend::Value::Cuda, rangeName ? rangeName : "", pdfClone.get(),
1097 /*takeGlobalObservablesFromData=*/true, nWorkers);
1098 wrapper->addOwnedComponents(std::move(binSamplingPdfs));
1099 wrapper->addOwnedComponents(std::move(chi2));
1100 wrapper->addOwnedComponents(std::move(pdfClone));
1101 }
1102
1103 if (evalBackend == RooFit::EvalBackend::Value::Codegen) {
1104 wrapper->generateGradient();
1105 }
1106 if (evalBackend == RooFit::EvalBackend::Value::CodegenNoGrad) {
1107 wrapper->setUseGeneratedFunctionCode(true);
1108 }
1109
1111 return wrapper;
1112}
1113
1114std::unique_ptr<RooFitResult> fitTo(RooAbsReal &real, RooAbsData &data, const RooLinkedList &cmdList, bool chi2)
1115{
1116 const bool isDataHist = dynamic_cast<RooDataHist const *>(&data);
1117
1118 RooCmdConfig pc("fitTo(" + std::string(real.GetName()) + ")");
1119
1120 RooLinkedList fitCmdList(cmdList);
1121 std::string nllCmdListString;
1122
1123 // Check on the raw command list whether parallel minimization is requested,
1124 // because in that case ModularL(true) is implied below. The check needs to
1125 // happen before filtering the command list: with a modular likelihood,
1126 // offsetting is configured on the minimizer instead of the likelihood, so
1127 // the OffsetLikelihood argument must not be forwarded to createNLL(), where
1128 // it is mutually exclusive with ModularL.
1129 auto cmdEnabled = [&cmdList](const char *cmdName) {
1130 auto *arg = static_cast<RooCmdArg *>(cmdList.FindObject(cmdName));
1131 return arg && arg->getInt(0) != 0;
1132 };
1133 const bool parallelRequested =
1134 cmdEnabled("Parallelize") || cmdEnabled("ParallelGradientOptions") || cmdEnabled("ParallelDescentOptions");
1135
1136 if (!chi2) {
1137 nllCmdListString = "ProjectedObservables,Extended,Range,"
1138 "RangeWithName,SumCoefRange,NumCPU,SplitRange,Constrained,Constrain,ExternalConstraints,"
1139 "CloneData,GlobalObservables,GlobalObservablesSource,GlobalObservablesTag,"
1140 "EvalBackend,IntegrateBins,ModularL";
1141
1142 if (!parallelRequested && !cmdEnabled("ModularL")) {
1143 nllCmdListString += ",OffsetLikelihood";
1144 }
1145 } else {
1146 auto createChi2DataHistCmdArgs = "Range,RangeWithName,NumCPU,IntegrateBins,ProjectedObservables,"
1147 "AddCoefRange,SplitRange,DataError,Extended,EvalBackend";
1148 auto createChi2DataSetCmdArgs = "YVar,Integrate,RangeWithName,NumCPU,Verbose";
1149 nllCmdListString += isDataHist ? createChi2DataHistCmdArgs : createChi2DataSetCmdArgs;
1150 }
1151
1152 RooLinkedList nllCmdList = pc.filterCmdList(fitCmdList, nllCmdListString.c_str());
1153
1154 pc.defineDouble("prefit", "Prefit", 0, 0);
1155 defineMinimizationOptions(pc);
1156
1157 // Process and check varargs
1158 pc.process(fitCmdList);
1159 if (!pc.ok(true)) {
1160 return nullptr;
1161 }
1162
1163 // TimingAnalysis works only for RooSimultaneous.
1164 if (pc.getInt("timingAnalysis") && !real.InheritsFrom("RooSimultaneous")) {
1165 oocoutW(&real, Minimization) << "The timingAnalysis feature was built for minimization with RooSimultaneous "
1166 "and is not implemented for other PDF's. Please create a RooSimultaneous to "
1167 "enable this feature."
1168 << std::endl;
1169 }
1170
1171 // Decode command line arguments
1172 double prefit = pc.getDouble("prefit");
1173
1174 if (prefit != 0) {
1175 size_t nEvents = static_cast<size_t>(prefit * data.numEntries());
1176 if (prefit > 0.5 || nEvents < 100) {
1177 oocoutW(&real, InputArguments) << "PrefitDataFraction should be in suitable range."
1178 << "With the current PrefitDataFraction=" << prefit
1179 << ", the number of events would be " << nEvents << " out of "
1180 << data.numEntries() << ". Skipping prefit..." << std::endl;
1181 } else {
1182 size_t step = data.numEntries() / nEvents;
1183
1184 RooDataSet tiny("tiny", "tiny", *data.get(), data.isWeighted() ? RooFit::WeightVar() : RooCmdArg());
1185
1186 for (int i = 0; i < data.numEntries(); i += step) {
1187 const RooArgSet *event = data.get(i);
1188 tiny.add(*event, data.weight());
1189 }
1190 RooLinkedList tinyCmdList(cmdList);
1191 pc.filterCmdList(tinyCmdList, "Prefit,Hesse,Minos,Verbose,Save,Timer");
1192 RooCmdArg hesse_option = RooFit::Hesse(false);
1193 RooCmdArg print_option = RooFit::PrintLevel(-1);
1194
1195 tinyCmdList.Add(&hesse_option);
1196 tinyCmdList.Add(&print_option);
1197
1198 fitTo(real, tiny, tinyCmdList, chi2);
1199 }
1200 }
1201
1202 RooCmdArg modularL_option;
1203 if (parallelRequested) {
1204 // Set to new style likelihood if parallelization is requested
1205 modularL_option = RooFit::ModularL(true);
1206 nllCmdList.Add(&modularL_option);
1207 }
1208
1209 std::unique_ptr<RooAbsReal> nll;
1210 if (chi2) {
1211 if (isDataHist) {
1212 nll = std::unique_ptr<RooAbsReal>{real.createChi2(static_cast<RooDataHist &>(data), nllCmdList)};
1213 }
1214 } else {
1215 nll = std::unique_ptr<RooAbsReal>{dynamic_cast<RooAbsPdf &>(real).createNLL(data, nllCmdList)};
1216 }
1217
1218 if (!nll) {
1219 oocoutE(&real, InputArguments) << "RooFit::FitHelpers::fitTo(" << real.GetName()
1220 << ") could not create the test statistic, no fit performed" << std::endl;
1221 return nullptr;
1222 }
1223
1224 return RooFit::FitHelpers::minimize(real, *nll, data, pc);
1225}
1226
1227} // namespace RooFit::FitHelpers
1228
1229/// \endcond
header file containing the templated implementation of matrix inversion routines for use with ROOT's ...
ROOT::RRangeCast< T, true, Range_t > dynamic_range_cast(Range_t &&coll)
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
cudaEvent_t event
#define oocoutW(o, a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define oocxcoutI(o, a)
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
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 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 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 child
char name[80]
Definition TGX11.cxx:142
class to compute the Cholesky decomposition of a matrix
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
virtual bool isCategory() const
Definition RooAbsArg.h:515
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.
void branchNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all branch nodes of the arg tree starting with ourself as top node.
Abstract base class for objects that represent a discrete value that can be set from the outside,...
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.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
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)
@ CanBeExtended
Definition RooAbsPdf.h:208
@ MustBeExtended
Definition RooAbsPdf.h:208
@ CanNotBeExtended
Definition RooAbsPdf.h:208
const char * normRange() const
Definition RooAbsPdf.h:246
virtual ExtendMode extendMode() const
Returns ability of PDF to provide extended likelihood terms.
Definition RooAbsPdf.h:212
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
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...
virtual void fixAddCoefRange(const char *rangeName=nullptr, 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.
RooFit::OwningPtr< RooAbsReal > createChi2(RooDataHist &data, CmdArgs_t const &... cmdArgs)
Create a variable from a histogram and this function.
Definition RooAbsReal.h:190
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooArgSet * selectByAttrib(const char *name, bool value) const
Use RooAbsCollection::selectByAttrib(), but return as RooArgSet.
Definition RooArgSet.h:144
static std::unique_ptr< RooAbsPdf > create(RooAbsPdf &pdf, RooAbsData const &data, double precision)
Creates a wrapping RooBinSamplingPdf if appropriate.
Object to represent discrete states.
Definition RooCategory.h:28
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
Configurable parser for RooCmdArg named arguments.
bool defineSet(const char *name, const char *argName, int setNum, const RooArgSet *defVal=nullptr)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
double getDouble(const char *name, double defVal=0.0) const
Return double property registered with name 'name'.
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.
int getInt(const char *name, int defVal=0) const
Return integer property registered with name 'name'.
RooArgSet * getSet(const char *name, RooArgSet *defVal=nullptr) const
Return RooArgSet 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...
bool ok(bool verbose) const
Return true of parsing was successful.
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...
const char * getString(const char *name, const char *defVal="", bool convEmptyToNull=false) const
Return string property registered with name 'name'.
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.
RooLinkedList filterCmdList(RooLinkedList &cmdInList, const char *cmdNameList, bool removeFromInList=true) const
Utility function to filter commands listed in cmdNameList from cmdInList.
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
Container class to hold unbinned data.
Definition RooDataSet.h:32
static Value & defaultValue()
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
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::Math::Minimizer that provides a seamless interface between the minimizer f...
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.
Definition RooRealVar.h:37
static TClass * Class()
void setRange(const char *name, double min, double max, bool shared=true)
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.
bool indexCatIsObservable(RooArgSet const &vars) const
Check if the index category is among the variables vars, matching by name.
const RooAbsCategoryLValue & indexCat() const
Int_t GetNrows() 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.
Definition TNamed.h:49
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:548
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Hesse(bool flag=true)
RooCmdArg ModularL(bool flag=false)
RooCmdArg PrintLevel(Int_t level)
RVec< PromoteType< T > > log(const RVec< T > &v)
Definition RVec.hxx:1821
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
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 doBinOffset)
The negative log-likelihood of one bin in a binned fit.
Definition MathFuncs.h:444
std::unique_ptr< T > compileForNormSet(T const &arg, RooArgSet const &normSet)
OffsetMode
For setting the offset mode with the Offset() command argument to RooAbsPdf::fitTo()
const char * Value
Definition TXMLSetup.cxx:72
static std::size_t defaultNComponentTasks
Definition Config.h:38
Config argument to RooMinimizer constructor.
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4