Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
xRooNLLVar.cxx
Go to the documentation of this file.
1/*
2 * Project: xRooFit
3 * Author:
4 * Will Buttinger, RAL 2022
5 *
6 * Copyright (c) 2022, CERN
7 *
8 * Redistribution and use in source and binary forms,
9 * with or without modification, are permitted according to the terms
10 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
11 */
12
13/** \class ROOT::Experimental::XRooFit::xRooNLLVar
14\ingroup xroofit
15
16This xRooNLLVar object has several special methods, e.g. for fitting and toy dataset generation.
17
18 */
19
20#include "RVersion.h"
21
22#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
23#define protected public
24#endif
25#include "RooFitResult.h"
26#include "RooNLLVar.h"
27#ifdef protected
28#undef protected
29#endif
30
31#include "xRooFit/xRooFit.h"
32
33#include "RooCmdArg.h"
34#include "RooAbsPdf.h"
35#include "RooAbsData.h"
36
37#include "RooConstraintSum.h"
38#include "RooSimultaneous.h"
40#include "TPRegexp.h"
41#include "TEfficiency.h"
42
43#include "RooRealVar.h"
44#include "Math/ProbFunc.h"
45#include "RooRandom.h"
46
47#include "TPad.h"
48#include "TSystem.h"
49
50#include "coutCapture.h"
51
52#include <chrono>
53
54#include "Math/GenAlgoOptions.h"
55
56#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
57#define private public
58#define GETWS(a) a->_myws
59#define GETWSSETS(w) w->_namedSets
60#else
61#define GETWS(a) a->workspace()
62#define GETWSSETS(w) w->sets()
63#endif
64#include "RooWorkspace.h"
65#ifdef private
66#undef private
67#endif
68
69#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
70#define protected public
71#endif
73#ifdef protected
74#undef protected
75#endif
76
77#include "TMultiGraph.h"
78#include "TCanvas.h"
79#include "TArrow.h"
80#include "RooStringVar.h"
81#include "TDirectory.h"
82#include "TStyle.h"
83#include "TH1D.h"
84#include "TLegend.h"
85#include "RooCategory.h"
86#include "TTree.h"
87#include "TGraph2D.h"
88
89#include "RooGaussian.h"
90#include "RooPoisson.h"
91
92#include "TROOT.h"
93#include "TKey.h"
94#include "TRegexp.h"
95
97
98std::set<int> xRooNLLVar::xRooHypoPoint::allowedStatusCodes = {0};
99
101public:
102 AutoRestorer(const RooAbsCollection &s, xRooNLLVar *nll = nullptr) : fSnap(s.snapshot()), fNll(nll)
103 {
104 fPars.add(s);
105 if (fNll) {
106 // if (!fNll->kReuseNLL) fOldNll = *fNll;
107 fOldData = fNll->getData();
108 fOldName = fNll->get()->GetName();
109 fOldTitle = fNll->get()->getStringAttribute("fitresultTitle");
110 }
111 }
113 {
115 if (fNll) {
116 // commented out code was attempt to speed up things avoid unnecessarily reinitializing things over and over
117 // if (!fNll->kReuseNLL) {
118 // // can be faster just by putting back in old nll
119 // fNll->std::shared_ptr<RooAbsReal>::operator=(fOldNll);
120 // fNll->fData = fOldData.first;
121 // fNll->fGlobs = fOldData.second;
122 // } else {
123 // fNll->setData(fOldData);
124 // fNll->get()->SetName(fOldName);
125 // fNll->get()->setStringAttribute("fitresultTitle", (fOldTitle == "") ? nullptr : fOldTitle);
126 // }
127 fNll->fGlobs = fOldData.second; // will mean globs matching checks are skipped in setData
128 fNll->setData(fOldData);
129 fNll->get()->SetName(fOldName);
130 fNll->get()->setStringAttribute("fitresultTitle", (fOldTitle == "") ? nullptr : fOldTitle);
131 }
132 }
134 std::unique_ptr<RooAbsCollection> fSnap;
135 xRooNLLVar *fNll = nullptr;
136 // std::shared_ptr<RooAbsReal> fOldNll;
137 std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> fOldData;
139};
140
141xRooNLLVar::~xRooNLLVar() {}
142
143xRooNLLVar::xRooNLLVar(RooAbsPdf &pdf, const std::pair<RooAbsData *, const RooAbsCollection *> &data,
144 const RooLinkedList &nllOpts)
145 : xRooNLLVar(std::shared_ptr<RooAbsPdf>(&pdf, [](RooAbsPdf *) {}),
146 std::make_pair(std::shared_ptr<RooAbsData>(data.first, [](RooAbsData *) {}),
147 std::shared_ptr<const RooAbsCollection>(data.second, [](const RooAbsCollection *) {})),
148 nllOpts)
149{
150}
151
152xRooNLLVar::xRooNLLVar(const std::shared_ptr<RooAbsPdf> &pdf,
153 const std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> &data,
154 const RooLinkedList &opts)
155 : fPdf(pdf), fData(data.first), fGlobs(data.second)
156{
157
159
160 fOpts = std::shared_ptr<RooLinkedList>(new RooLinkedList, [](RooLinkedList *l) {
161 if (l)
162 l->Delete();
163 delete l;
164 });
165 fOpts->SetName("");
166
167 // we *must* take global observables from the model even if they are included in the dataset
168 // this is because the way xRooNLLVar is coded up it assumes the globs in the funcVars *ARE*
169 // part of the model
170 fOpts->Add(RooFit::GlobalObservablesSource("model").Clone(nullptr));
171
172 for (int i = 0; i < opts.GetSize(); i++) {
173 if (strlen(opts.At(i)->GetName()) == 0)
174 continue; // skipping "none" cmds
175 if (strcmp(opts.At(i)->GetName(), "GlobalObservables") == 0) {
176 // will skip here to add with the obs from the function below
177 // must match global observables
178 auto gl = dynamic_cast<RooCmdArg *>(opts.At(i))->getSet(0);
179 if (!fGlobs || !fGlobs->equals(*gl)) {
180 throw std::runtime_error("GlobalObservables mismatch");
181 }
182 } else if (strcmp(opts.At(i)->GetName(), "Hesse") == 0) {
183 fitConfig()->SetParabErrors(dynamic_cast<RooCmdArg *>(opts.At(i))->getInt(0)); // controls hesse
184 } else if (strcmp(opts.At(i)->GetName(), "Strategy") == 0) {
185 fitConfig()->MinimizerOptions().SetStrategy(dynamic_cast<RooCmdArg *>(opts.At(i))->getInt(0));
186 } else if (strcmp(opts.At(i)->GetName(), "StrategySequence") == 0) {
187 fitConfigOptions()->SetNamedValue("StrategySequence", dynamic_cast<RooCmdArg *>(opts.At(i))->getString(0));
188 } else if (strcmp(opts.At(i)->GetName(), "Tolerance") == 0) {
189 fitConfig()->MinimizerOptions().SetTolerance(dynamic_cast<RooCmdArg *>(opts.At(i))->getInt(0));
190 } else if (strcmp(opts.At(i)->GetName(), "PrintLevel") == 0) {
191 fitConfig()->MinimizerOptions().SetPrintLevel(dynamic_cast<RooCmdArg *>(opts.At(i))->getInt(0));
192 } else {
193 if (strcmp(opts.At(i)->GetName(), "Optimize") == 0) {
194 // this flag will trigger constOptimizeTestStatistic to be called on the nll in createNLL method
195 // we should ensure that the fitconfig setting is consistent with it ...
196 fitConfigOptions()->SetValue("OptimizeConst", dynamic_cast<RooCmdArg *>(opts.At(i))->getInt(0));
197 }
198 fOpts->Add(opts.At(i)->Clone(nullptr)); // nullptr needed because accessing Clone via TObject base class puts
199 // "" instead, so doesnt copy names
200 }
201 }
202 if (fGlobs) {
203 // add global observables opt with function obs
204 auto _vars = std::unique_ptr<RooArgSet>(fPdf->getVariables());
205 if (auto extCon = dynamic_cast<RooCmdArg *>(fOpts->find("ExternalConstraints"))) {
206 for (auto con : *extCon->getSet(0)) {
207 _vars->add(*std::unique_ptr<RooArgSet>(con->getVariables()));
208 }
209 }
210 auto _funcGlobs = std::unique_ptr<RooArgSet>(dynamic_cast<RooArgSet *>(_vars->selectCommon(*fGlobs)));
211 fOpts->Add(RooFit::GlobalObservables(*_funcGlobs).Clone());
212 }
213
214 if (auto flag = dynamic_cast<RooCmdArg *>(fOpts->find("ReuseNLL"))) {
215 kReuseNLL = flag->getInt(0);
216 }
217
218 // if fit range specified, and pdf is a RooSimultaneous, may need to 'reduce' the model if some of the pdfs are in
219 // range and others are not
220 if (auto range = dynamic_cast<RooCmdArg *>(fOpts->find("RangeWithName"))) {
221 TString rangeName = range->getString(0);
222
223 // reduce the data here for convenience, not really necessary because will happen inside RooNLLVar but still
224 // fData.reset( fData->reduce(RooFit::SelectVars(*fData->get()),RooFit::CutRange(rangeName)) );
225
226 if (auto s = dynamic_cast<RooSimultaneous *>(fPdf.get()); s) {
227 auto &_cat = const_cast<RooAbsCategoryLValue &>(s->indexCat());
228 std::vector<TString> chanPatterns;
229 TStringToken pattern(rangeName, ",");
230 bool hasRange(false);
231 std::string noneCatRanges;
232 while (pattern.NextToken()) {
233 chanPatterns.emplace_back(pattern);
234 if (_cat.hasRange(chanPatterns.back()))
235 hasRange = true;
236 else {
237 if (!noneCatRanges.empty())
238 noneCatRanges += ",";
239 noneCatRanges += chanPatterns.back();
240 }
241 }
242 if (hasRange) {
243 // must remove the ranges that referred to selections on channel category
244 // otherwise RooFit will incorrectly evaluate the NLL (it creates a partition for each range given in the
245 // list, which all end up being equal) the NLL would become scaled by the number of ranges given
246 if (noneCatRanges.empty()) {
247 fOpts->Remove(range);
248 SafeDelete(range);
249 } else {
250 range->setString(0, noneCatRanges.c_str());
251 }
252 // must reduce because category var has one of the ranges
253 auto newPdf =
254 std::make_shared<RooSimultaneous>(TString::Format("%s_reduced", s->GetName()), "Reduced model", _cat);
255 for (auto &c : _cat) {
256 auto _pdf = s->getPdf(c.first.c_str());
257 if (!_pdf)
258 continue;
259 _cat.setIndex(c.second);
260 bool matchAny = false;
261 for (auto &p : chanPatterns) {
262 if (_cat.hasRange(p) && _cat.inRange(p)) {
263 matchAny = true;
264 break;
265 }
266 }
267 if (matchAny) {
268 newPdf->addPdf(*_pdf, c.first.c_str());
269 }
270 }
271 fPdf = newPdf;
272 }
273 }
274 }
275
276 // if (fGlobs) {
277 // // must check GlobalObservables is in the list
278 // }
279 //
280 // if (auto globs = dynamic_cast<RooCmdArg*>(fOpts->find("GlobalObservables"))) {
281 // // first remove any obs the pdf doesnt depend on
282 // auto _vars = std::unique_ptr<RooAbsCollection>( fPdf->getVariables() );
283 // auto _funcGlobs = std::unique_ptr<RooAbsCollection>(_vars->selectCommon(*globs->getSet(0)));
284 // fGlobs.reset( std::unique_ptr<RooAbsCollection>(globs->getSet(0)->selectCommon(*_funcGlobs))->snapshot() );
285 // globs->setSet(0,dynamic_cast<const RooArgSet&>(*_funcGlobs)); // globs in linked list has its own argset
286 // but args need to live as long as the func
287 // /*RooArgSet toRemove;
288 // for(auto a : *globs->getSet(0)) {
289 // if (!_vars->find(*a)) toRemove.add(*a);
290 // }
291 // const_cast<RooArgSet*>(globs->getSet(0))->remove(toRemove);
292 // fGlobs.reset( globs->getSet(0)->snapshot() );
293 // fGlobs->setAttribAll("Constant",true);
294 // const_cast<RooArgSet*>(globs->getSet(0))->replace(*fGlobs);*/
295 // }
296};
297
298xRooNLLVar::xRooNLLVar(const std::shared_ptr<RooAbsPdf> &pdf, const std::shared_ptr<RooAbsData> &data,
299 const RooLinkedList &opts)
300 : xRooNLLVar(
301 pdf,
302 std::make_pair(data, std::shared_ptr<const RooAbsCollection>(
303 (opts.find("GlobalObservables"))
304 ? dynamic_cast<RooCmdArg *>(opts.find("GlobalObservables"))->getSet(0)->snapshot()
305 : nullptr)),
306 opts)
307{
308}
309
311{
312 std::cout << "PDF: ";
313 if (fPdf)
314 fPdf->Print();
315 else
316 std::cout << "<null>" << std::endl;
317 std::cout << "Data: ";
318 if (fData)
319 fData->Print();
320 else
321 std::cout << "<null>" << std::endl;
322 std::cout << "NLL Options: " << std::endl;
323 for (int i = 0; i < fOpts->GetSize(); i++) {
324 auto c = dynamic_cast<RooCmdArg *>(fOpts->At(i));
325 if (!c)
326 continue;
327 std::cout << " " << c->GetName() << " : ";
328 if (c->getString(0))
329 std::cout << c->getString(0);
330 else if (c->getSet(0) && !c->getSet(0)->empty())
331 std::cout << (c->getSet(0)->contentsString());
332 else
333 std::cout << c->getInt(0);
334 std::cout << std::endl;
335 }
336 if (fFitConfig) {
337 std::cout << "Fit Config: " << std::endl;
338 std::cout << " UseParabErrors: " << (fFitConfig->ParabErrors() ? "True" : "False")
339 << " [toggles HESSE algorithm]" << std::endl;
340 std::cout << " MinimizerOptions: " << std::endl;
341 fFitConfig->MinimizerOptions().Print();
342 }
343 std::cout << "Last Rebuild Log Output: " << fFuncCreationLog << std::endl;
344}
345
347{
348 TString oldName = "";
349 if (std::shared_ptr<RooAbsReal>::get())
350 oldName = std::shared_ptr<RooAbsReal>::get()->GetName();
351 if (fPdf) {
353 // need to find all RooRealSumPdf nodes and mark them binned or unbinned as required
354 RooArgSet s;
355 fPdf->treeNodeServerList(&s, nullptr, true, false);
356 s.add(*fPdf.get()); // ensure include self in case fitting a RooRealSumPdf
357 bool isBinned = false;
358 bool hasBinned = false; // if no binned option then 'auto bin' ...
359 if (auto a = dynamic_cast<RooCmdArg *>(fOpts->find("Binned")); a) {
360 hasBinned = true;
361 isBinned = a->getInt(0);
362 }
363 std::map<RooAbsArg *, bool> origValues;
364 if (hasBinned) {
365 for (auto a : s) {
366 if (a->InheritsFrom("RooRealSumPdf")) {
367 // since RooNLLVar will assume binBoundaries available (not null), we should check bin boundaries
368 // available
369 bool setBinned = false;
370 if (isBinned) {
371 std::unique_ptr<RooArgSet> obs(a->getObservables(fData->get()));
372 if (obs->size() == 1) { // RooNLLVar requires exactly 1 obs
373 auto *var = static_cast<RooRealVar *>(obs->first());
374 std::unique_ptr<std::list<double>> boundaries{dynamic_cast<RooAbsReal *>(a)->binBoundaries(
375 *var, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity())};
376 if (boundaries) {
377 if (!std::shared_ptr<RooAbsReal>::get())
378 Info("xRooNLLVar", "%s will be evaluated as a Binned PDF (%d bins)", a->GetName(),
379 int(boundaries->size() - 1));
380 setBinned = true;
381 }
382 }
383 }
384 origValues[a] = a->getAttribute("BinnedLikelihood");
385 a->setAttribute("BinnedLikelihood", setBinned);
386 }
387 }
388 }
389 // before creating, clear away caches if any if pdf is in ws
390 if (GETWS(fPdf)) {
391 std::set<std::string> setNames;
392 for (auto &a : GETWSSETS(GETWS(fPdf))) {
393 if (TString(a.first.c_str()).BeginsWith("CACHE_")) {
394 setNames.insert(a.first);
395 }
396 }
397 for (auto &a : setNames) {
398 GETWS(fPdf)->removeSet(a.c_str());
399 }
400 }
401 std::set<std::string> attribs;
402 if (std::shared_ptr<RooAbsReal>::get())
403 attribs = std::shared_ptr<RooAbsReal>::get()->attributes();
404 this->reset(std::unique_ptr<RooAbsReal>{fPdf->createNLL(*fData, *fOpts)}.release());
405 std::shared_ptr<RooAbsReal>::get()->SetName(TString::Format("nll_%s/%s", fPdf->GetName(), fData->GetName()));
406 // RooFit only swaps in what it calls parameters, this misses out the RooConstVars which we treat as pars as well
407 // so swap those in ... question: is recursiveRedirectServers usage in RooAbsOptTestStatic (and here) a memory
408 // leak?? where do the replaced servers get deleted??
409
410 for (auto &a : attribs)
411 std::shared_ptr<RooAbsReal>::get()->setAttribute(a.c_str());
412 // create parent on next line to avoid triggering workspace initialization code in constructor of xRooNode
413 if (GETWS(fPdf)) {
414 xRooNode(*GETWS(fPdf), std::make_shared<xRooNode>()).sterilize();
415 } // there seems to be a nasty bug somewhere that can make the cache become invalid, so clear it here
416 if (oldName != "")
417 std::shared_ptr<RooAbsReal>::get()->SetName(oldName);
418 if (!origValues.empty()) {
419 // need to evaluate NOW so that slaves are created while the BinnedLikelihood settings are in place
420 std::shared_ptr<RooAbsReal>::get()->getVal();
421 for (auto &[o, v] : origValues)
422 o->setAttribute("BinnedLikelihood", v);
423 }
424 }
425
426 fFuncVars = std::unique_ptr<RooArgSet>{std::shared_ptr<RooAbsReal>::get()->getVariables()};
427 if (fGlobs) {
428 fFuncGlobs.reset(fFuncVars->selectCommon(*fGlobs));
429 fFuncGlobs->setAttribAll("Constant", true);
430 }
431 fConstVars.reset(fFuncVars->selectByAttrib("Constant", true)); // will check if any of these have floated
432}
433
434std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>>
435xRooNLLVar::generate(bool expected, int seed)
436{
437 if (!fPdf)
438 return std::pair(nullptr, nullptr);
439 auto fr = std::make_shared<RooFitResult>(TUUID().AsString());
440 fr->setFinalParList(RooArgList());
442 l.add((fFuncVars) ? *fFuncVars : *std::unique_ptr<RooAbsCollection>(fPdf->getParameters(*fData)));
443 fr->setConstParList(l);
444 const_cast<RooArgList &>(fr->constPars()).setAttribAll("global", false);
445 if (fGlobs)
446 std::unique_ptr<RooAbsCollection>(fr->constPars().selectCommon(*fGlobs))->setAttribAll("global", true);
447 return xRooFit::generateFrom(*fPdf, *fr, expected, seed);
448}
449
450xRooNLLVar::xRooFitResult::xRooFitResult(const std::shared_ptr<xRooNode> &in, const std::shared_ptr<xRooNLLVar> &nll)
451 : std::shared_ptr<const RooFitResult>(std::dynamic_pointer_cast<const RooFitResult>(in->fComp)),
452 fNode(in),
453 fNll(nll),
454 fCfits(std::make_shared<std::map<std::string, xRooFitResult>>())
455{
456}
458{
459 return fNode->get<RooFitResult>();
460}
461// xRooNLLVar::xRooFitResult::operator std::shared_ptr<const RooFitResult>() const { return
462// std::dynamic_pointer_cast<const RooFitResult>(fNode->fComp); }
463xRooNLLVar::xRooFitResult::operator const RooFitResult *() const
464{
465 return fNode->get<const RooFitResult>();
466}
468{
469 fNode->Draw(opt);
470}
471
472xRooNLLVar::xRooFitResult xRooNLLVar::xRooFitResult::cfit(const char *poiValues, const char *alias)
473{
474
475 // create a hypoPoint with ufit equal to this fit
476 // and poi equal to given poi
477 if (!fNll)
478 throw std::runtime_error("xRooFitResult::cfit: Cannot create cfit without nll");
479
480 // see if fit already done
481 if (alias) {
482 if (auto res = fCfits->find(alias); res != fCfits->end()) {
483 return res->second;
484 }
485 }
486 if (auto res = fCfits->find(poiValues); res != fCfits->end()) {
487 return res->second;
488 }
489
490 AutoRestorer s(*fNll->fFuncVars);
491 *fNll->fFuncVars = get()->floatParsFinal();
492 fNll->fFuncVars->assignValueOnly(get()->constPars());
493 std::unique_ptr<RooAbsCollection>(fNll->fFuncVars->selectCommon(get()->floatParsFinal()))
494 ->setAttribAll("Constant", false);
495 std::unique_ptr<RooAbsCollection>(fNll->fFuncVars->selectCommon(get()->constPars()))->setAttribAll("Constant", true);
496
497 auto hp = fNll->hypoPoint(poiValues, std::numeric_limits<double>::quiet_NaN(), xRooFit::Asymptotics::Unknown);
498 hp.fUfit = *this;
499 auto out = xRooNLLVar::xRooFitResult(std::make_shared<xRooNode>(hp.cfit_null(), fNode->fParent), fNll);
500 fCfits->insert(std::pair((alias) ? alias : poiValues, out));
501 return out;
502}
504{
505 RooRealVar *npVar = dynamic_cast<RooRealVar *>((prefit ? get()->floatParsInit() : get()->floatParsFinal()).find(np));
506 if (!npVar)
507 throw std::runtime_error("xRooFitResult::ifit: par not found");
508 return cfit(TString::Format("%s=%f", np, npVar->getVal() + (up ? npVar->getErrorHi() : npVar->getErrorLo())));
509}
510double xRooNLLVar::xRooFitResult::impact(const char *poi, const char *np, bool up, bool prefit, bool covApprox)
511{
512 if (!covApprox) {
513 // get the ifit and get the difference between the postFit poi values
514 RooRealVar *poiHat = dynamic_cast<RooRealVar *>((get()->floatParsFinal()).find(poi));
515 if (!poiHat)
516 throw std::runtime_error("xRooFitResult::impact: poi not found");
517 auto _ifit = ifit(np, up, prefit);
518 if (!_ifit)
519 throw std::runtime_error("xRooFitResult::impact: null ifit");
520 if (_ifit->status() != 0)
521 fNode->Warning("impact", "ifit status code is %d", _ifit->status());
522 return _ifit->floatParsFinal().getRealValue(poi) - poiHat->getVal();
523 } else {
524 // estimate impact from the covariance matrix ....
525 int iPoi = get()->floatParsFinal().index(poi);
526 int iNp = get()->floatParsFinal().index(np);
527 if (iPoi == -1)
528 throw std::runtime_error("xRooFitResult::impact: poi not found");
529 if (iNp == -1)
530 throw std::runtime_error("xRooFitResult::impact: np not found");
531 RooRealVar *npVar =
532 dynamic_cast<RooRealVar *>((prefit ? get()->floatParsInit() : get()->floatParsFinal()).find(np));
533 return get()->covarianceMatrix()(iPoi, iNp) / (up ? npVar->getErrorHi() : npVar->getErrorLo());
534 }
535 return std::numeric_limits<double>::quiet_NaN();
536}
537
538double xRooNLLVar::xRooFitResult::conditionalError(const char *poi, const char *nps, bool up, bool covApprox)
539{
540 // run a fit with given NPs held constant, return quadrature difference
541
542 TString npNames;
543 RooArgList vars;
544 RooAbsArg *poiVar = nullptr;
545 for (auto p : get()->floatParsFinal()) {
546 if (strcmp(p->GetName(), poi) == 0) {
547 vars.add(*p);
548 poiVar = p;
549 continue;
550 }
551 TStringToken pattern(nps, ",");
552 bool matches = false;
553 while (pattern.NextToken()) {
554 TString s(pattern);
555 if ((p->getStringAttribute("group") && s == p->getStringAttribute("group")) ||
556 TString(p->GetName()).Contains(TRegexp(s, true)) || p->getAttribute(s)) {
557 matches = true;
558 break;
559 }
560 }
561 if (matches) {
562 if (npNames.Length())
563 npNames += ",";
564 npNames += p->GetName();
565 } else {
566 vars.add(*p); // keeping in reduced cov matrix
567 }
568 }
569 if (!poiVar) {
570 throw std::runtime_error(TString::Format("Could not find poi: %s", poi));
571 }
572 if (npNames == "") {
573 fNode->Warning("conditionalError", "No parameters selected by: %s", nps);
574 return (up) ? static_cast<RooRealVar *>(poiVar)->getErrorHi() : static_cast<RooRealVar *>(poiVar)->getErrorLo();
575 }
576
577 if (covApprox) {
578 int idx = vars.index(poi);
579 return sqrt(get()->conditionalCovarianceMatrix(vars)(idx, idx));
580 }
581
582 auto _cfit = cfit(npNames.Data(), nps);
583
584 auto _poi = _cfit->floatParsFinal().find(poi);
585
586 return (up) ? static_cast<RooRealVar *>(_poi)->getErrorHi() : static_cast<RooRealVar *>(_poi)->getErrorLo();
587}
588
589RooArgList xRooNLLVar::xRooFitResult::ranknp(const char *poi, bool up, bool prefit, double approxThreshold)
590{
591
592 RooRealVar *poiHat = dynamic_cast<RooRealVar *>((get()->floatParsFinal()).find(poi));
593 if (!poiHat)
594 throw std::runtime_error("xRooFitResult::ranknp: poi not found");
595
596 std::vector<std::pair<std::string, double>> ranks;
597 // first do with the covariance approximation, since that's always available
598 for (auto par : get()->floatParsFinal()) {
599 if (par == poiHat)
600 continue;
601 ranks.emplace_back(std::pair(par->GetName(), impact(poi, par->GetName(), up, prefit, true)));
602 }
603
604 std::sort(ranks.begin(), ranks.end(), [](auto &left, auto &right) {
605 if (std::isnan(left.second) && !std::isnan(right.second))
606 return false;
607 if (!std::isnan(left.second) && std::isnan(right.second))
608 return true;
609 return fabs(left.second) > fabs(right.second);
610 });
611
612 // now redo the ones above the threshold
613 for (auto &[n, v] : ranks) {
614 if (v >= approxThreshold) {
615 try {
616 v = impact(poi, n.c_str(), up, prefit);
617 } catch (...) {
618 v = std::numeric_limits<double>::quiet_NaN();
619 };
620 }
621 }
622
623 // resort
624 std::sort(ranks.begin(), ranks.end(), [](auto &left, auto &right) {
625 if (std::isnan(left.second) && !std::isnan(right.second))
626 return false;
627 if (!std::isnan(left.second) && std::isnan(right.second))
628 return true;
629 return fabs(left.second) > fabs(right.second);
630 });
631
632 RooArgList out;
633 out.setName("rankings");
634 for (auto &[n, v] : ranks) {
635 out.addClone(*get()->floatParsFinal().find(n.c_str()));
636 auto vv = static_cast<RooRealVar *>(out.at(out.size() - 1));
637 vv->setVal(v);
638 vv->removeError();
639 vv->removeRange();
640 }
641 return out;
642}
643
644xRooNLLVar::xRooFitResult xRooNLLVar::minimize(const std::shared_ptr<ROOT::Fit::FitConfig> &_config)
645{
646 auto &nll = *get();
647 auto out = xRooFit::minimize(nll, (_config) ? _config : fitConfig(), fOpts);
648 // add any pars that are const here that aren't in constPars list because they may have been
649 // const-optimized and their values cached with the dataset, so if subsequently floated the
650 // nll wont evaluate correctly
651 // fConstVars.reset( fFuncVars->selectByAttrib("Constant",true) );
652
653 // before returning, flag which of the constPars were actually global observables
654 if (out) {
655 const_cast<RooArgList &>(out->constPars()).setAttribAll("global", false);
656 if (fGlobs)
657 std::unique_ptr<RooAbsCollection>(out->constPars().selectCommon(*fGlobs))->setAttribAll("global", true);
658 }
659 return xRooFitResult(std::make_shared<xRooNode>(out, fPdf), std::make_shared<xRooNLLVar>(*this));
660}
661
662std::shared_ptr<ROOT::Fit::FitConfig> xRooNLLVar::fitConfig()
663{
664 if (!fFitConfig)
666 return fFitConfig;
667}
668
670{
671 if (auto conf = fitConfig(); conf)
672 return const_cast<ROOT::Math::IOptions *>(conf->MinimizerOptions().ExtraOptions());
673 return nullptr;
674}
675
676double xRooNLLVar::getEntryVal(size_t entry) const
677{
678 auto _data = data();
679 if (!_data)
680 return 0;
681 if (size_t(_data->numEntries()) <= entry)
682 return 0;
683 auto _pdf = pdf();
684 *std::unique_ptr<RooAbsCollection>(_pdf->getObservables(_data)) = *_data->get(entry);
685 // if (auto s = dynamic_cast<RooSimultaneous*>(_pdf.get());s) return
686 // -_data->weight()*s->getPdf(s->indexCat().getLabel())->getLogVal(_data->get());
687 return -_data->weight() * _pdf->getLogVal(_data->get());
688}
689
690double xRooNLLVar::getEntryBinWidth(size_t entry) const
691{
692
693 auto _data = data();
694 if (!_data)
695 return 0;
696 if (size_t(_data->numEntries()) <= entry)
697 return 0;
698 auto _pdf = pdf().get();
699 *std::unique_ptr<RooAbsCollection>(_pdf->getObservables(_data->get())) = *_data->get(entry); // only set robs
700 if (auto s = dynamic_cast<RooSimultaneous *>(_pdf); s) {
701 _pdf = s->getPdf(s->indexCat().getCurrentLabel());
702 }
703 std::unique_ptr<RooAbsCollection> _robs(_pdf->getObservables(_data->get()));
704 double volume = 1.;
705 for (auto o : *_robs) {
706
707 if (auto a = dynamic_cast<RooAbsRealLValue *>(o); a) {
708 std::unique_ptr<std::list<double>> bins(
709 _pdf->binBoundaries(*a, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()));
710 if (bins) {
711 double lowEdge = -std::numeric_limits<double>::infinity();
712 for (auto b : *bins) {
713 if (b > a->getVal()) {
714 volume *= (b - lowEdge);
715 break;
716 }
717 lowEdge = b;
718 }
719 }
720 }
721 }
722
723 return volume;
724}
725
727{
728 // for each global observable in the dataset, determine which constraint term is associated to it
729 // and given its type, add the necessary saturated term...
730
731 double out = 0;
732
733 if (!fGlobs)
734 return 0;
735
736 auto cTerm = constraintTerm();
737 if (!cTerm)
738 return 0;
739
740 for (auto c : cTerm->list()) {
741 if (auto gaus = dynamic_cast<RooGaussian *>(c)) {
742 auto v = dynamic_cast<RooAbsReal *>(fGlobs->find(gaus->getX().GetName()));
743 if (!v) {
744 v = dynamic_cast<RooAbsReal *>(fGlobs->find(
745 gaus->getMean().GetName())); // shouldn't really happen but does for at least ws made by pyhf
746 }
747 if (!v)
748 continue;
749 out -= std::log(ROOT::Math::gaussian_pdf(v->getVal(), gaus->getSigma().getVal(), v->getVal()));
750 } else if (auto pois = dynamic_cast<RooPoisson *>(c)) {
751 auto v = dynamic_cast<RooAbsReal *>(fGlobs->find(pois->getX().GetName()));
752 if (!v)
753 continue;
754 out -= std::log(TMath::Poisson(v->getVal(), v->getVal()));
755 }
756 }
757
758 return out;
759}
760
761double xRooNLLVar::ndof() const
762{
763 return data()->numEntries() + (globs() ? globs()->size() : 0) -
764 std::unique_ptr<RooAbsCollection>(pars()->selectByAttrib("Constant", false))->size();
765}
766
767double xRooNLLVar::pgof() const
768{
769 // note that if evaluating this for a single channel, until 6.30 is available if you are using Binned mode the pdf
770 // will need to be part of a Simultaneous
771 return TMath::Prob(2. * (get()->getVal() - saturatedVal()), ndof());
772}
773
775{
777}
778
780{
781
782 // Use this term to create a goodness-of-fit metric, which is approx chi2 distributed with numEntries (data) d.o.f:
783 // prob = TMath::Prob( 2.*(nll.nllTerm()->getVal() - nll.saturatedNllTerm()), nll.data()->numEntries() )
784
785 // note that need to construct nll with explicit Binned(1 or 0) option otherwise will pick up nll eval
786 // from attributes in model already, so many get binned nllTerm eval when thinking not binned because didnt specify
787 // Binned(1)
788
789 auto _data = data();
790 if (!_data)
791 return std::numeric_limits<double>::quiet_NaN();
792
793 bool isBinned = false;
794 if (auto a = dynamic_cast<RooCmdArg *>(fOpts->find("Binned")); a) {
795 isBinned = a->getInt(0);
796 }
797
798 // for binned case each entry is: -(-N + Nlog(N) - TMath::LnGamma(N+1))
799 // for unbinned case each entry is: -(N*log(N/(sumN*binW))) = -N*logN + N*log(sumN) + N*log(binW)
800 // but unbinned gets extendedTerm = sumN - sumN*log(sumN)
801 // so resulting sum is just sumN - sum[ N*logN - N*log(binW) ]
802 // which is the same as the binned case without the LnGamma part and with the extra sum[N*log(binW)] part
803
804 double out = _data->sumEntries();
805 for (int i = 0; i < _data->numEntries(); i++) {
806 _data->get(i);
807 double w = _data->weight();
808 out -= w * std::log(w);
809 if (isBinned)
810 out += TMath::LnGamma(w + 1);
811 else
812 out += w * std::log(getEntryBinWidth(i));
813 }
814
815 out += simTerm();
816
817 return out;
818}
819
820std::shared_ptr<RooArgSet> xRooNLLVar::pars(bool stripGlobalObs) const
821{
822 auto out = std::shared_ptr<RooArgSet>(get()->getVariables());
823 if (stripGlobalObs && fGlobs) {
824 out->remove(*fGlobs, true, true);
825 }
826 return out;
827}
828
829TObject *
830xRooNLLVar::Scan(const char *scanPars, const std::vector<std::vector<double>> &coords, const RooArgList &profilePars)
831{
832 return Scan(*std::unique_ptr<RooAbsCollection>(get()->getVariables()->selectByName(scanPars)), coords, profilePars);
833}
834
835TObject *xRooNLLVar::Scan(const RooArgList &scanPars, const std::vector<std::vector<double>> &coords,
836 const RooArgList &profilePars)
837{
838
839 if (scanPars.size() > 2 || scanPars.empty())
840 return nullptr;
841
842 TGraph2D *out2d = (scanPars.size() == 2) ? new TGraph2D() : nullptr;
843 TGraph *out1d = (out2d) ? nullptr : new TGraph();
844 TNamed *out = (out2d) ? static_cast<TNamed *>(out2d) : static_cast<TNamed *>(out1d);
845 out->SetName(get()->GetName());
846 out->SetTitle(TString::Format("%s;%s%s%s", get()->GetTitle(), scanPars.first()->GetTitle(), out2d ? ";" : "",
847 out2d ? scanPars.at(1)->GetTitle() : ""));
848
849 std::unique_ptr<RooAbsCollection> funcVars(get()->getVariables());
850 AutoRestorer snap(*funcVars);
851
852 for (auto &coord : coords) {
853 if (coord.size() != scanPars.size()) {
854 throw std::runtime_error("Invalid coordinate");
855 }
856 for (size_t i = 0; i < coord.size(); i++) {
857 static_cast<RooAbsRealLValue &>(scanPars[i]).setVal(coord[i]);
858 }
859
860 if (profilePars.empty()) {
861 // just evaluate
862 if (out2d) {
863 out2d->SetPoint(out2d->GetN(), coord[0], coord[1], get()->getVal());
864 } else {
865 out1d->SetPoint(out1d->GetN(), coord[0], get()->getVal());
866 }
867 }
868 }
869
870 return out;
871}
872
874{
875 TString sOpt(opt);
876
877 auto _pars = pars();
878
879 if (sOpt == "sensitivity") {
880
881 // will make a plot of DeltaNLL
882 }
883
884 if (sOpt == "floating") {
885 // start scanning floating pars
886 auto floats = std::unique_ptr<RooAbsCollection>(_pars->selectByAttrib("Constant", false));
887 TVirtualPad *pad = gPad;
888 if (!pad) {
890 pad = gPad;
891 }
893 gr->SetName("multigraph");
894 gr->SetTitle(TString::Format("%s;Normalized Parameter Value;#Delta NLL", get()->GetTitle()));
895 /*((TPad*)pad)->DivideSquare(floats->size());
896 int i=0;
897 for(auto a : *floats) {
898 i++;
899 pad->cd(i);
900 Draw(a->GetName());
901 }*/
902 return;
903 }
904
905 RooArgList vars;
906 TStringToken pattern(sOpt, ":");
907 while (pattern.NextToken()) {
908 TString s(pattern);
909 if (auto a = _pars->find(s); a)
910 vars.add(*a);
911 }
912
913 if (vars.size() == 1) {
914 TGraph *out = new TGraph;
915 out->SetBit(kCanDelete);
916 TGraph *bad = new TGraph;
917 bad->SetBit(kCanDelete);
918 bad->SetMarkerColor(kRed);
919 bad->SetMarkerStyle(5);
920 TMultiGraph *gr = (gPad) ? dynamic_cast<TMultiGraph *>(gPad->GetPrimitive("multigraph")) : nullptr;
921 bool normRange = false;
922 if (!gr) {
923 gr = new TMultiGraph;
924 gr->Add(out, "LP");
926 } else {
927 normRange = true;
928 }
929 out->SetName(get()->GetName());
930 gr->SetTitle(TString::Format("%s;%s;#Delta NLL", get()->GetTitle(), vars.at(0)->GetTitle()));
931 // scan outwards from current value towards limits
932 auto v = dynamic_cast<RooRealVar *>(vars.at(0));
933 double low = v->getVal();
934 double high = low;
935 double step = (v->getMax() - v->getMin()) / 100;
936 double init = v->getVal();
937 double initVal = func()->getVal();
938 // double xscale = (normRange) ? (2.*(v->getMax() - v->getMin())) : 1.;
939 auto currTime = std::chrono::steady_clock::now();
940 while (out->GetN() < 100 && (low > v->getMin() || high < v->getMax())) {
941 if (out->GetN() == 0) {
942 out->SetPoint(out->GetN(), low, 0);
943 low -= step;
944 high += step;
945 if (!normRange) {
946 gr->Draw("A");
947 gPad->SetGrid();
948 }
949 continue;
950 }
951 if (low > v->getMin()) {
952 v->setVal(low);
953 auto _v = func()->getVal();
954 if (std::isnan(_v) || std::isinf(_v)) {
955 if (bad->GetN() == 0)
956 gr->Add(bad, "P");
957 bad->SetPoint(bad->GetN(), low, out->GetPointY(0));
958 } else {
959 out->SetPoint(out->GetN(), low, _v - initVal);
960 }
961 low -= step;
962 }
963 if (high < v->getMax()) {
964 v->setVal(high);
965 auto _v = func()->getVal();
966 if (std::isnan(_v) || std::isinf(_v)) {
967 if (bad->GetN() == 0)
968 gr->Add(bad, "P");
969 bad->SetPoint(bad->GetN(), high, out->GetPointY(0));
970 } else {
971 out->SetPoint(out->GetN(), high, _v - initVal);
972 }
973 high += step;
974 }
975 out->Sort();
976 // should only do processEvents once every second in case using x11 (which is slow)
977 gPad->Modified();
978 if (std::chrono::steady_clock::now() - currTime > std::chrono::seconds(1)) {
979 currTime = std::chrono::steady_clock::now();
980 gPad->Update();
982 }
983 }
984 // add arrow to show current par value
985 TArrow a;
986 a.DrawArrow(init, 0, init, -0.1);
987 gPad->Update();
988#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 30, 00)
989 gPad->GetCanvas()->ResetUpdated(); // stops previous canvas being replaced in a jupyter notebook
990#endif
992 v->setVal(init);
993 } else {
994 Error("Draw", "Name a parameter to scan over: Draw(<name>) , choose from: %s",
995 _pars->empty() ? "" : _pars->contentsString().c_str());
996 }
997}
998
999std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> xRooNLLVar::getData() const
1000{
1001 return std::make_pair(fData, fGlobs);
1002}
1003
1005{
1006 if (data.fComp && !data.get<RooAbsData>()) {
1007 return false;
1008 }
1009 return setData(std::dynamic_pointer_cast<RooAbsData>(data.fComp),
1010 std::shared_ptr<const RooAbsCollection>(data.globs().argList().snapshot()));
1011}
1012
1013bool xRooNLLVar::setData(const std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> &_data)
1014{
1015
1016 if (fData == _data.first && fGlobs == _data.second)
1017 return true;
1018
1019 auto _globs = fGlobs; // done to keep globs alive while NLL might still be alive.
1020
1021 auto _dglobs = (_data.second) ? _data.second
1022 : std::shared_ptr<const RooAbsCollection>(_data.first->getGlobalObservables(),
1023 [](const RooAbsCollection *) {});
1024
1025 if (fGlobs && !(fGlobs->empty() && !_dglobs) && _data.first &&
1026 fGlobs != _dglobs) { // second condition allows for no globs being a nullptr, third allow globs to remain if
1027 // nullifying data
1028 if (!_dglobs)
1029 throw std::runtime_error("Missing globs");
1030 // ignore 'extra' globs
1031 RooArgSet s;
1032 s.add(*fGlobs);
1033 std::unique_ptr<RooAbsCollection> _actualGlobs(fPdf->getObservables(s));
1034 RooArgSet s2;
1035 s2.add(*_dglobs);
1036 std::unique_ptr<RooAbsCollection> _actualGlobs2(fPdf->getObservables(s2));
1037 if (!_actualGlobs->equals(*_actualGlobs2)) {
1038 RooArgSet rC;
1039 rC.add(*_actualGlobs2);
1040 rC.remove(*std::unique_ptr<RooAbsCollection>(rC.selectCommon(*_actualGlobs)));
1041 TString r = (!rC.empty()) ? rC.contentsString() : "";
1042 RooArgSet lC;
1043 lC.add(*_actualGlobs);
1044 lC.remove(*std::unique_ptr<RooAbsCollection>(lC.selectCommon(*_actualGlobs2)));
1045 TString l = (!lC.empty()) ? lC.contentsString() : "";
1046 throw std::runtime_error(TString::Format("globs mismatch: adding %s removing %s", r.Data(), l.Data()));
1047 }
1048 fGlobs = _dglobs;
1049 }
1050
1051 if (!std::shared_ptr<RooAbsReal>::get()) {
1052 fData = _data.first;
1053 return true; // not loaded yet so nothing to do
1054 }
1055
1056 try {
1057 if (!kReuseNLL || nllTerm()->operMode() == RooAbsTestStatistic::MPMaster) {
1058 throw std::runtime_error("not supported");
1059 }
1060 bool out = false;
1061 if (_data.first) {
1062 if (_data.first->getGlobalObservables()) {
1063 // replace in all terms
1064 get()->setData(*_data.first, false);
1065 } else {
1066 // replace just in nllTerm ... note to self: why not just replace in all like above? should test!
1067 out = nllTerm()->setData(*_data.first, false /* clone data? */);
1068 }
1069 } else {
1070 reset();
1071 }
1072 fData = _data.first;
1073 return out;
1074 } catch (std::runtime_error &) {
1075 // happens when using MP need to rebuild the nll instead
1076 AutoRestorer snap(*fFuncVars);
1077 // ensure the const state is back where it was at nll construction time;
1078 fFuncVars->setAttribAll("Constant", false);
1079 fConstVars->setAttribAll("Constant", true);
1080 std::shared_ptr<RooAbsData> __data = fData; // do this just to keep fData alive while killing previous NLLVar
1081 // (can't kill data while NLL constructed with it)
1082 fData = _data.first;
1083 reinitialize();
1084 return true;
1085 }
1086 throw std::runtime_error("Unable to setData");
1087}
1088
1089std::shared_ptr<RooAbsReal> xRooNLLVar::func() const
1090{
1091 if (!(*this)) {
1092 const_cast<xRooNLLVar *>(this)->reinitialize();
1093 } else if (auto f = std::unique_ptr<RooAbsCollection>(fConstVars->selectByAttrib("Constant", false)); !f->empty()) {
1094 // have to reinitialize if const par values have changed - const optimization forces this
1095 // TODO: currently changes to globs also triggers this since the vars includes globs (vars are the non-obs pars)
1096 // std::cout << "Reinitializing because of change of const parameters:" << f->contentsString() << std::endl;
1097 const_cast<xRooNLLVar *>(this)->reinitialize();
1098
1099 // note ... it may be sufficient here to do:
1100 // nll.constOptimizeTestStatistic(RooAbsArg::ConfigChange, constOptimize>1 /* do tracking too if >1 */); //
1101 // trigger a re-evaluate of which nodes to cache-and-track nll.constOptimizeTestStatistic(RooAbsArg::ValueChange,
1102 // constOptimize>1); // update the cache values -- is this needed??
1103 // this forces the optimization to be redone
1104 // for now leave as a reinitialize though, until had a chance to test this properly
1105 }
1106 if (fGlobs && fFuncGlobs) {
1107 *fFuncGlobs = *fGlobs;
1108 fFuncGlobs->setAttribAll("Constant", true);
1109 }
1110 return *this;
1111}
1112
1114{
1115 fOpts->Add(opt.Clone(nullptr));
1116 if (std::shared_ptr<RooAbsReal>::get())
1117 reinitialize(); // do this way to keep name of nll if user set
1118 else
1119 reset(); // will trigger reinitialize
1120}
1121
1123{
1124 auto _nll = nllTerm();
1125 if (!_nll)
1126 return fData.get();
1127 RooAbsData *out = &_nll->data();
1128 if (!out)
1129 return fData.get();
1130 return out;
1131}
1132
1134{
1135 auto _func = func();
1136 if (auto a = dynamic_cast<RooNLLVar *>(_func.get()); a)
1137 return a;
1138 for (auto s : _func->servers()) {
1139 if (auto a = dynamic_cast<RooNLLVar *>(s); a)
1140 return a;
1141 }
1142 return nullptr;
1143}
1144
1146{
1147 // returns Nexp - Nobs*log(Nexp)
1148 return fPdf->extendedTerm(fData->sumEntries(), fData->get());
1149}
1150
1152{
1153 if (auto s = dynamic_cast<RooSimultaneous *>(fPdf.get()); s) {
1154 return fData->sumEntries() * log(1.0 * (s->servers().size() - 1)); // one of the servers is the cat
1155 }
1156 return 0;
1157}
1158
1160{
1161 // this is only relevant if BinnedLikelihood active
1162 // = sum[ N_i! ] since LnGamma(N_i+1) ~= N_i!
1163 // need to also subtract off sum[ N_i*log(width_i) ] in order to have formula: binnedLL = unbinnedLL + binnedDataTerm
1164 // note this is 0 if all the bin widths are 1
1165 double out = 0;
1166 for (int i = 0; i < fData->numEntries(); i++) {
1167 fData->get(i);
1168 out += TMath::LnGamma(fData->weight() + 1) - fData->weight() * std::log(getEntryBinWidth(i));
1169 }
1170
1171 return out;
1172}
1173
1175{
1176 auto _func = func();
1177 if (auto a = dynamic_cast<RooConstraintSum *>(_func.get()); a)
1178 return a;
1179 for (auto s : _func->servers()) {
1180 if (auto a = dynamic_cast<RooConstraintSum *>(s); a)
1181 return a;
1182 }
1183 return nullptr;
1184}
1185
1186/*xRooNLLVar::operator RooAbsReal &() const {
1187 // this works in c++ but not in python
1188 std::cout << "implicit conversion" << std::endl;
1189 return *fFunc;
1190}*/
1191
1192std::pair<double, double> xRooNLLVar::xRooHypoPoint::getVal(const char *what)
1193{
1194 TString sWhat(what);
1195 sWhat.ToLower();
1196 bool doTS = sWhat.Contains("ts");
1197 bool doCLs = sWhat.Contains("pcls");
1198 bool doNull = sWhat.Contains("pnull");
1199 bool doAlt = sWhat.Contains("palt");
1200 double nSigma = (sWhat.Contains("exp"))
1201 ? (TString(sWhat(sWhat.Index("exp") + 3, sWhat.Index(" ", sWhat.Index("exp")) == -1
1202 ? sWhat.Length()
1203 : sWhat.Index(" ", sWhat.Index("exp"))))
1204 .Atof())
1205 : std::numeric_limits<double>::quiet_NaN();
1206
1207 bool toys = sWhat.Contains("toys");
1208
1209 // bool asymp = sWhat.Contains("asymp");
1210
1211 bool readOnly = sWhat.Contains("readonly");
1212
1213 if (!readOnly) {
1214 if (toys) {
1215 sigma_mu(); // means we will be able to evaluate the asymptotic values too
1216 }
1217 // only add toys if actually required
1218 if (getVal(sWhat + " readonly").second != 0) {
1219 if (sWhat.Contains("toys=")) {
1220 // extract number of toys required ... format is "nullToys.altToysFraction" if altToysFraction=0 then use
1221 // same for both
1222 size_t nToys = TString(sWhat(sWhat.Index("toys=") + 5, sWhat.Length())).Atoi();
1223 size_t nToysAlt = (TString(sWhat(sWhat.Index("toys=") + 5, sWhat.Length())).Atof() - nToys) * nToys;
1224 if (nToysAlt == 0)
1225 nToysAlt = nToys;
1226 if (nullToys.size() < nToys) {
1227 addNullToys(nToys - nullToys.size());
1228 }
1229 if (altToys.size() < nToysAlt) {
1230 addAltToys(nToysAlt - altToys.size());
1231 }
1232 } else if (doCLs && toys) {
1233 // auto toy-generating for limits .. do in blocks of 100
1234 addCLsToys(100, 0, 0.05, nSigma);
1235 }
1236 }
1237 }
1238
1239 struct RestoreNll {
1240 RestoreNll(std::shared_ptr<xRooNLLVar> &v, bool r) : rr(r), var(v)
1241 {
1242 if (rr && var && var->get()) {
1243 _readOnly = var->get()->getAttribute("readOnly");
1244 var->get()->setAttribute("readOnly", rr);
1245 } else {
1246 rr = false;
1247 }
1248 };
1249 ~RestoreNll()
1250 {
1251 if (rr)
1252 var->get()->setAttribute("readOnly", _readOnly);
1253 };
1254
1255 bool rr = false;
1256 bool _readOnly = false;
1257
1258 std::shared_ptr<xRooNLLVar> &var;
1259 };
1260
1261 RestoreNll rest(nllVar, readOnly);
1262
1263 if (doTS)
1264 return (toys) ? ts_toys(nSigma) : ts_asymp(nSigma);
1265 if (doNull)
1266 return (toys) ? pNull_toys(nSigma) : pNull_asymp(nSigma);
1267 if (doAlt)
1268 return (toys) ? pAlt_toys(nSigma) : pAlt_asymp(nSigma);
1269 if (doCLs)
1270 return (toys) ? pCLs_toys(nSigma) : pCLs_asymp(nSigma);
1271
1272 throw std::runtime_error(std::string("Unknown: ") + what);
1273}
1274
1276{
1277 RooArgList out;
1278 out.setName("poi");
1279 out.add(*std::unique_ptr<RooAbsCollection>(coords->selectByAttrib("poi", true)));
1280 return out;
1281}
1282
1284{
1285 RooArgList out;
1286 out.setName("alt_poi");
1287 out.addClone(*std::unique_ptr<RooAbsCollection>(coords->selectByAttrib("poi", true)));
1288 for (auto a : out) {
1289 auto v = dynamic_cast<RooAbsRealLValue *>(a);
1290 if (!v)
1291 continue;
1292 if (auto s = a->getStringAttribute("altVal"); s && strlen(s)) {
1293 v->setVal(TString(s).Atof());
1294 } else {
1295 v->setVal(std::numeric_limits<double>::quiet_NaN());
1296 }
1297 }
1298 return out;
1299}
1300
1302{
1303 auto &me = const_cast<xRooHypoPoint &>(*this);
1304 int out = 0;
1305 if (me.ufit(true) && !allowedStatusCodes.count(me.ufit(true)->status()))
1306 out += 1;
1307 if (me.cfit_null(true) && !allowedStatusCodes.count(me.cfit_null(true)->status()))
1308 out += 1 << 1;
1309 if (me.cfit_alt(true) && !allowedStatusCodes.count(me.cfit_alt(true)->status()))
1310 out += 1 << 2;
1311 if (me.asimov(true))
1312 out += me.asimov(true)->status() << 3;
1313 return out;
1314}
1315
1317{
1318 std::cout << "POI: " << const_cast<xRooHypoPoint *>(this)->poi().contentsString()
1319 << " , null: " << dynamic_cast<RooAbsReal *>(const_cast<xRooHypoPoint *>(this)->poi().first())->getVal()
1320 << " , alt: "
1321 << dynamic_cast<RooAbsReal *>(const_cast<xRooHypoPoint *>(this)->alt_poi().first())->getVal();
1322 std::cout << " , pllType: " << fPllType << std::endl;
1323
1324 std::cout << " - ufit: ";
1325 if (fUfit) {
1326 std::cout << fUfit->GetName() << " " << fUfit->minNll() << " (status=" << fUfit->status() << ") ("
1327 << const_cast<xRooHypoPoint *>(this)->mu_hat().GetName()
1328 << "_hat: " << const_cast<xRooHypoPoint *>(this)->mu_hat().getVal() << " +/- "
1329 << const_cast<xRooHypoPoint *>(this)->mu_hat().getError() << ")" << std::endl;
1330 } else {
1331 std::cout << "Not calculated" << std::endl;
1332 }
1333 std::cout << " - null cfit: ";
1334 if (fNull_cfit) {
1335 std::cout << fNull_cfit->GetName() << " " << fNull_cfit->minNll() << " (status=" << fNull_cfit->status() << ")";
1336 } else {
1337 std::cout << "Not calculated";
1338 }
1339 if (!std::isnan(dynamic_cast<RooAbsReal *>(const_cast<xRooHypoPoint *>(this)->alt_poi().first())->getVal())) {
1340 std::cout << std::endl << " - alt cfit: ";
1341 if (fAlt_cfit) {
1342 std::cout << fAlt_cfit->GetName() << " " << fAlt_cfit->minNll() << " (status=" << fAlt_cfit->status() << ")"
1343 << std::endl;
1344 } else {
1345 std::cout << "Not calculated" << std::endl;
1346 }
1347 std::cout << " sigma_mu: ";
1348 const_cast<xRooHypoPoint *>(this)->asimov(true); // will trigger construction of fAsimov hypoPoint if possible
1349 if (!fAsimov || !fAsimov->fUfit || !fAsimov->fNull_cfit) {
1350 std::cout << "Not calculated";
1351 } else {
1352 std::cout << const_cast<xRooHypoPoint *>(this)->sigma_mu().first << " +/- "
1353 << const_cast<xRooHypoPoint *>(this)->sigma_mu().second;
1354 }
1355 if (fAsimov) {
1356 std::cout << std::endl;
1357 std::cout << " - asimov ufit: ";
1358 if (fAsimov->fUfit)
1359 std::cout << fAsimov->fUfit->GetName() << " " << fAsimov->fUfit->minNll()
1360 << " (status=" << fAsimov->fUfit->status() << ")";
1361 else
1362 std::cout << "Not calculated";
1363 std::cout << std::endl << " - asimov null cfit: ";
1364 if (fAsimov->fNull_cfit)
1365 std::cout << fAsimov->fNull_cfit->GetName() << " " << fAsimov->fNull_cfit->minNll()
1366 << " (status=" << fAsimov->fNull_cfit->status() << ")";
1367 else
1368 std::cout << "Not calculated";
1369 }
1370 std::cout << std::endl;
1371 } else {
1372 std::cout << std::endl;
1373 }
1374 if (fGenFit)
1375 std::cout << " - genFit: " << fGenFit->GetName() << std::endl;
1376 if (!nullToys.empty() || !altToys.empty()) {
1377 std::cout << " * null toys: " << nullToys.size();
1378 size_t firstToy = 0;
1379 while (firstToy < nullToys.size() && std::isnan(std::get<1>(nullToys[firstToy])))
1380 firstToy++;
1381 if (firstToy > 0)
1382 std::cout << " [ of which " << firstToy << " are bad]";
1383 std::cout << " , alt toys: " << altToys.size();
1384 firstToy = 0;
1385 while (firstToy < altToys.size() && std::isnan(std::get<1>(altToys[firstToy])))
1386 firstToy++;
1387 if (firstToy > 0)
1388 std::cout << " [ of which " << firstToy << " are bad]";
1389 std::cout << std::endl;
1390 }
1391 // std::cout << " nllVar: " << nllVar << std::endl;
1392}
1393
1395{
1396 if (ufit()) {
1397 auto var = dynamic_cast<RooRealVar *>(ufit()->floatParsFinal().find(fPOIName()));
1398 if (var)
1399 return *var;
1400 else
1401 throw std::runtime_error(TString::Format("Cannot find POI: %s",fPOIName()));
1402 }
1403 throw std::runtime_error("Unconditional fit unavailable");
1404}
1405
1406std::pair<std::shared_ptr<RooAbsData>, std::shared_ptr<const RooAbsCollection>> xRooNLLVar::xRooHypoPoint::data()
1407{
1408 if (fData.first)
1409 return fData;
1410 if (fGenFit && isExpected) {
1411 // std::cout << "Generating asimov" << std::endl;poi().Print("v");
1412 fData = xRooFit::generateFrom(*nllVar->fPdf, *fGenFit, true);
1413 }
1414 return fData;
1415}
1416
1417xRooNLLVar::xRooHypoPoint::xRooHypoPoint(std::shared_ptr<RooStats::HypoTestResult> htr, const RooAbsCollection *_coords)
1418 : TNamed(), hypoTestResult(htr)
1419{
1420 if (hypoTestResult) {
1421 // load the pllType
1422 fPllType =
1423 xRooFit::Asymptotics::PLLType(hypoTestResult->GetFitInfo()->getGlobalObservables()->getCatIndex("pllType"));
1424 isExpected = hypoTestResult->GetFitInfo()->getGlobalObservables()->getRealValue("isExpected");
1425
1426 // load the toys
1427 auto toys = hypoTestResult->GetNullDetailedOutput();
1428 if (toys) {
1429 // load coords from the nullDist globs list
1430 if (toys->getGlobalObservables()) {
1431 coords = std::shared_ptr<RooAbsCollection>(toys->getGlobalObservables()->snapshot());
1432 }
1433 for (int i = 0; i < toys->numEntries(); i++) {
1434 auto toy = toys->get(i);
1435 nullToys.emplace_back(
1436 std::make_tuple(int(toy->getRealValue("seed")), toy->getRealValue("ts"), toys->weight()));
1437 }
1438 }
1439 toys = hypoTestResult->GetAltDetailedOutput();
1440 if (toys) {
1441 for (int i = 0; i < toys->numEntries(); i++) {
1442 auto toy = toys->get(i);
1443 altToys.emplace_back(
1444 std::make_tuple(int(toy->getRealValue("seed")), toy->getRealValue("ts"), toys->weight()));
1445 }
1446 }
1447 }
1448 if (!coords && _coords)
1449 coords.reset(_coords->snapshot());
1450}
1451
1452std::shared_ptr<xRooNLLVar::xRooHypoPoint> xRooNLLVar::xRooHypoPoint::asimov(bool readOnly)
1453{
1454
1455 if (!fAsimov && (nllVar || hypoTestResult)) {
1456 auto theFit = (!fData.first && fGenFit && !isExpected)
1457 ? fGenFit
1458 : cfit_alt(readOnly); // first condition allows genFit to be used as the altFit *if* the data is
1459 // entirely absent, provided not expected data because we postpone data
1460 // creation til later in that case (see below)
1461 if (!theFit || allowedStatusCodes.find(theFit->status()) == allowedStatusCodes.end())
1462 return fAsimov;
1463 fAsimov = std::make_shared<xRooHypoPoint>(*this);
1464 fAsimov->coords.reset(fAsimov->coords->snapshot()); // create a copy so can remove the physical range below
1465 fAsimov->hypoTestResult.reset();
1466 fAsimov->fPllType = xRooFit::Asymptotics::TwoSided;
1467 for (auto p : fAsimov->poi()) {
1468 // dynamic_cast<RooRealVar *>(p)->removeRange("physical"); -- can't use this as will modify shared property
1469 if (auto v = dynamic_cast<RooRealVar *>(p)) {
1470 v->deleteSharedProperties(); // effectively removes all custom ranges
1471 }
1472 }
1473
1474 fAsimov->nullToys.clear();
1475 fAsimov->altToys.clear();
1476 fAsimov->fUfit = retrieveFit(3);
1477 fAsimov->fNull_cfit = retrieveFit(4);
1478 fAsimov->fAlt_cfit.reset();
1479 fAsimov->fData =
1480 std::make_pair(nullptr, nullptr); // postpone generating expected data until we definitely need it
1481 fAsimov->fGenFit = theFit;
1482 fAsimov->isExpected = true;
1483 }
1484
1485 return fAsimov;
1486}
1487
1488std::pair<double, double> xRooNLLVar::xRooHypoPoint::pNull_asymp(double nSigma)
1489{
1490 if (fPllType != xRooFit::Asymptotics::Uncapped && ts_asymp(nSigma).first == 0)
1491 return std::pair(1, 0);
1492 auto first_poi = dynamic_cast<RooRealVar *>(poi().first());
1493 if (!first_poi)
1494 return std::pair(std::numeric_limits<double>::quiet_NaN(), 0);
1495 auto _sigma_mu = sigma_mu();
1496 double nom = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fNullVal(), _sigma_mu.first,
1497 first_poi->getMin("physical"), first_poi->getMax("physical"));
1498 double up =
1499 xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first + ts_asymp(nSigma).second, fNullVal(), fNullVal(),
1500 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1501 double down =
1502 xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first - ts_asymp(nSigma).second, fNullVal(), fNullVal(),
1503 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1504 return std::pair(nom, std::max(std::abs(up - nom), std::abs(down - nom)));
1505}
1506
1507std::pair<double, double> xRooNLLVar::xRooHypoPoint::pAlt_asymp(double nSigma)
1508{
1509 if (fPllType != xRooFit::Asymptotics::Uncapped && ts_asymp(nSigma).first == 0)
1510 return std::pair(1, 0);
1511 auto first_poi = dynamic_cast<RooRealVar *>(poi().first());
1512 if (!first_poi)
1513 return std::pair(std::numeric_limits<double>::quiet_NaN(), 0);
1514 auto _sigma_mu = sigma_mu();
1515 double nom = xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first, fNullVal(), fAltVal(), _sigma_mu.first,
1516 first_poi->getMin("physical"), first_poi->getMax("physical"));
1517 double up =
1518 xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first + ts_asymp(nSigma).second, fNullVal(), fAltVal(),
1519 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1520 double down =
1521 xRooFit::Asymptotics::PValue(fPllType, ts_asymp(nSigma).first - ts_asymp(nSigma).second, fNullVal(), fAltVal(),
1522 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1523
1524 return std::pair(nom, std::max(std::abs(up - nom), std::abs(down - nom)));
1525}
1526
1527std::pair<double, double> xRooNLLVar::xRooHypoPoint::pCLs_asymp(double nSigma)
1528{
1529 if (fNullVal() == fAltVal())
1530 return std::pair(1, 0); // by construction
1531
1532 if (fPllType != xRooFit::Asymptotics::Uncapped && ts_asymp(nSigma).first == 0)
1533 return std::pair(1, 0);
1534 auto first_poi = dynamic_cast<RooRealVar *>(poi().first());
1535 if (!first_poi)
1536 return std::pair(std::numeric_limits<double>::quiet_NaN(), 0);
1537
1538 auto _ts_asymp = ts_asymp(nSigma);
1539 auto _sigma_mu = sigma_mu();
1540 double nom1 = xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first, fNullVal(), fNullVal(), _sigma_mu.first,
1541 first_poi->getMin("physical"), first_poi->getMax("physical"));
1542 double up1 =
1543 xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first + _ts_asymp.second, fNullVal(), fNullVal(),
1544 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1545 double down1 =
1546 xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first - _ts_asymp.second, fNullVal(), fNullVal(),
1547 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1548 double nom2 = xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first, fNullVal(), fAltVal(), _sigma_mu.first,
1549 first_poi->getMin("physical"), first_poi->getMax("physical"));
1550 double up2 =
1551 xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first + _ts_asymp.second, fNullVal(), fAltVal(), _sigma_mu.first,
1552 first_poi->getMin("physical"), first_poi->getMax("physical"));
1553 double down2 =
1554 xRooFit::Asymptotics::PValue(fPllType, _ts_asymp.first - _ts_asymp.second, fNullVal(), fAltVal(), _sigma_mu.first,
1555 first_poi->getMin("physical"), first_poi->getMax("physical"));
1556
1557 auto nom = (nom1 == 0) ? 0 : nom1 / nom2;
1558 auto up = (up1 == 0) ? 0 : up1 / up2;
1559 auto down = (down1 == 0) ? 0 : down1 / down2;
1560
1561 return std::make_pair(nom, std::max(std::abs(up - nom), std::abs(down - nom)));
1562}
1563
1564std::pair<double, double> xRooNLLVar::xRooHypoPoint::ts_asymp(double nSigma)
1565{
1566 if (std::isnan(nSigma))
1567 return pll();
1568 auto first_poi = dynamic_cast<RooRealVar *>(poi().first());
1569 auto _sigma_mu = sigma_mu();
1570 if (!first_poi || (!std::isnan(nSigma) && std::isnan(_sigma_mu.first)))
1571 return std::pair(std::numeric_limits<double>::quiet_NaN(), 0);
1572 double nom = xRooFit::Asymptotics::k(fPllType, ROOT::Math::gaussian_cdf(nSigma), fNullVal(), fAltVal(),
1573 _sigma_mu.first, first_poi->getMin("physical"), first_poi->getMax("physical"));
1574 double up = xRooFit::Asymptotics::k(fPllType, ROOT::Math::gaussian_cdf(nSigma), fNullVal(), fAltVal(),
1575 _sigma_mu.first + _sigma_mu.second, first_poi->getMin("physical"),
1576 first_poi->getMax("physical"));
1577 double down = xRooFit::Asymptotics::k(fPllType, ROOT::Math::gaussian_cdf(nSigma), fNullVal(), fAltVal(),
1578 _sigma_mu.first - _sigma_mu.second, first_poi->getMin("physical"),
1579 first_poi->getMax("physical"));
1580 return std::pair<double, double>(nom, std::max(std::abs(nom - up), std::abs(nom - down)));
1581}
1582
1583std::pair<double, double> xRooNLLVar::xRooHypoPoint::ts_toys(double nSigma)
1584{
1585 if (std::isnan(nSigma))
1586 return pll();
1587 // nans should appear in the alt toys first ... so loop until past nans
1588 size_t firstToy = 0;
1589 while (firstToy < altToys.size() && std::isnan(std::get<1>(altToys[firstToy])))
1590 firstToy++;
1591 if (firstToy >= altToys.size())
1592 return std::make_pair(std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN());
1593 int targetIdx =
1594 (altToys.size() - firstToy) * ROOT::Math::gaussian_cdf(nSigma) + firstToy; // TODO: Account for weights
1595 return std::make_pair(
1596 std::get<1>(altToys[targetIdx]),
1597 (std::get<1>(altToys[std::min(int(altToys.size()), targetIdx)]) - std::get<1>(altToys[std::max(0, targetIdx)])) /
1598 2.);
1599}
1600
1601std::pair<double, double> xRooNLLVar::xRooHypoPoint::pll(bool readOnly)
1602{
1603 auto _ufit = ufit(readOnly);
1604 if (!_ufit) {
1605 if (hypoTestResult)
1606 return std::make_pair(hypoTestResult->GetTestStatisticData(), 0);
1607 return std::make_pair(std::numeric_limits<double>::quiet_NaN(), 0);
1608 }
1609 if (allowedStatusCodes.find(_ufit->status()) == allowedStatusCodes.end()) {
1610 return std::make_pair(std::numeric_limits<double>::quiet_NaN(), 0);
1611 }
1612 if (auto _first_poi = dynamic_cast<RooRealVar *>(poi().first());
1613 _first_poi && _first_poi->getMin("physical") > _first_poi->getMin() &&
1614 mu_hat().getVal() < _first_poi->getMin("physical")) {
1615 // replace _ufit with fit "boundary" conditional fit
1616 _ufit = cfit_lbound(readOnly);
1617 if (!_ufit) {
1618 return std::make_pair(std::numeric_limits<double>::quiet_NaN(), 0);
1619 }
1620 }
1621 auto cFactor = (fPllType == xRooFit::Asymptotics::TwoSided)
1622 ? 1.
1623 : xRooFit::Asymptotics::CompatFactor(fPllType, fNullVal(), mu_hat().getVal());
1624 if (cFactor == 0)
1625 return std::make_pair(0, 0);
1626 if (!cfit_null(readOnly) || allowedStatusCodes.find(cfit_null(readOnly)->status()) == allowedStatusCodes.end())
1627 return std::make_pair(std::numeric_limits<double>::quiet_NaN(), 0);
1628 // std::cout << cfit->minNll() << ":" << cfit->edm() << " " << ufit->minNll() << ":" << ufit->edm() << std::endl;
1629 return std::make_pair(2. * cFactor * (cfit_null(readOnly)->minNll() - _ufit->minNll()),
1630 2. * cFactor * sqrt(pow(cfit_null(readOnly)->edm(), 2) + pow(_ufit->edm(), 2)));
1631 // return 2.*cFactor*(cfit->minNll()+cfit->edm() - ufit->minNll()+ufit->edm());
1632}
1633
1634std::shared_ptr<const RooFitResult> xRooNLLVar::xRooHypoPoint::retrieveFit(int type)
1635{
1636 if (!hypoTestResult)
1637 return nullptr;
1638 // see if can retrieve from that ....
1639 if (auto fits = hypoTestResult->GetFitInfo()) {
1640 for (int i = 0; i < fits->numEntries(); i++) {
1641 auto fit = fits->get(i);
1642 if (fit->getCatIndex("type") != type)
1643 continue;
1644 // found ufit ... construct
1645 std::string _name =
1646 fits->getGlobalObservables()->getStringValue(TString::Format("%s.name", fit->getCatLabel("type")));
1647 // see if can retrieve from any open file ....
1648 TDirectory *tmp = gDirectory;
1649 for (auto file : *gROOT->GetListOfFiles()) {
1650 if (auto k = static_cast<TDirectory *>(file)->FindKeyAny(_name.c_str())) {
1651 // use pre-retrieved fits if available
1652 xRooFit::StoredFitResult *storedFr =
1653 k->GetMotherDir()->GetList()
1654 ? dynamic_cast<xRooFit::StoredFitResult *>(k->GetMotherDir()->GetList()->FindObject(k->GetName()))
1655 : nullptr;
1656 if (auto cachedFit = (storedFr) ? storedFr->fr.get() : k->ReadObject<RooFitResult>(); cachedFit) {
1657 if (!storedFr) {
1658 storedFr = new xRooFit::StoredFitResult(cachedFit);
1659 k->GetMotherDir()->Add(storedFr);
1660 }
1661 gDirectory = tmp; // one of the above calls moves to key's directory ... i didn't check which
1662 return storedFr->fr;
1663 }
1664 }
1665 }
1666 auto rfit = std::make_shared<RooFitResult>(_name.c_str(), TUUID(_name.c_str()).GetTime().AsString());
1667 rfit->setStatus(fit->getRealValue("status"));
1668 rfit->setMinNLL(fit->getRealValue("minNll"));
1669 rfit->setEDM(fit->getRealValue("edm"));
1670 if (type == 0) {
1671 std::unique_ptr<RooAbsCollection> par_hats(
1672 hypoTestResult->GetFitInfo()->getGlobalObservables()->selectByName(coords->contentsString().c_str()));
1673 par_hats->setName("floatParsFinal");
1674 rfit->setFinalParList(*par_hats);
1675 } else {
1676 rfit->setFinalParList(RooArgList());
1677 }
1678 rfit->setConstParList(RooArgList());
1679 rfit->setInitParList(RooArgList());
1680 TMatrixDSym cov(0);
1681 rfit->setCovarianceMatrix(cov);
1682 return rfit;
1683 }
1684 }
1685 return nullptr;
1686}
1687
1688std::shared_ptr<const RooFitResult> xRooNLLVar::xRooHypoPoint::ufit(bool readOnly)
1689{
1690 if (fUfit)
1691 return fUfit;
1692 if (auto rfit = retrieveFit(0)) {
1693 return fUfit = rfit;
1694 }
1695 if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly")))
1696 return nullptr;
1697 if (!nllVar->fFuncVars)
1698 nllVar->reinitialize();
1699 AutoRestorer snap(*nllVar->fFuncVars, nllVar.get());
1700 if (!fData.first) {
1701 if (!readOnly && isExpected && fGenFit) {
1702 // can try to do a readOnly in case can load from cache
1703 bool tmp = nllVar->get()->getAttribute("readOnly");
1704 nllVar->get()->setAttribute("readOnly");
1705 auto out = ufit(true);
1706 nllVar->get()->setAttribute("readOnly", tmp);
1707 if (out) {
1708 // retrieve from cache worked, no need to generate dataset
1709 return out;
1710 } else if (!tmp) { // don't need to setData if doing a readOnly fit
1711 nllVar->setData(data());
1712 }
1713 }
1714 } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit
1715 nllVar->setData(fData);
1716 }
1717 nllVar->fFuncVars->setAttribAll("Constant", false);
1718 *nllVar->fFuncVars = *coords; // will reconst the coords
1719 if (nllVar->fFuncGlobs)
1720 nllVar->fFuncGlobs->setAttribAll("Constant", true);
1721 std::unique_ptr<RooAbsCollection>(nllVar->fFuncVars->selectCommon(poi()))
1722 ->setAttribAll("Constant", false); // float the poi
1723 if (fGenFit) {
1724 // make initial guess same as pars we generated with
1725 nllVar->fFuncVars->assignValueOnly(fGenFit->constPars());
1726 nllVar->fFuncVars->assignValueOnly(fGenFit->floatParsFinal());
1727 // rename nll so if caching fit results will cache into subdir
1728 nllVar->get()->SetName(
1729 TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys"));
1730 if (!isExpected)
1731 nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName()));
1732
1733 } else if (!std::isnan(fAltVal())) {
1734 // guess data given is expected to align with alt value, unless initVal attribute specified
1735 for (auto _poiCoord : poi()) {
1736 auto _poi = dynamic_cast<RooRealVar *>(nllVar->fFuncVars->find(_poiCoord->GetName()));
1737 if (_poi) {
1738 _poi->setVal(_poi->getStringAttribute("initVal") ? TString(_poi->getStringAttribute("initVal")).Atof()
1739 : fAltVal());
1740 }
1741 }
1742 }
1743 return (fUfit = nllVar->minimize());
1744}
1745
1746std::string collectionContents(const RooAbsCollection &coll)
1747{
1748 std::string out;
1749 for (auto &c : coll) {
1750 if (!out.empty())
1751 out += ",";
1752 out += c->GetName();
1753 if (auto v = dynamic_cast<RooAbsReal *>(c); v)
1754 out += TString::Format("=%g", v->getVal());
1755 else if (auto cc = dynamic_cast<RooAbsCategory *>(c); cc)
1756 out += TString::Format("=%s", cc->getLabel());
1757 else if (auto s = dynamic_cast<RooStringVar *>(c); v)
1758 out += TString::Format("=%s", s->getVal());
1759 }
1760 return out;
1761}
1762
1763std::shared_ptr<const RooFitResult> xRooNLLVar::xRooHypoPoint::cfit_null(bool readOnly)
1764{
1765 if (fNull_cfit)
1766 return fNull_cfit;
1767 if (auto rfit = retrieveFit(1)) {
1768 return fNull_cfit = rfit;
1769 }
1770 if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly")))
1771 return nullptr;
1772 if (!nllVar->fFuncVars)
1773 nllVar->reinitialize();
1774 AutoRestorer snap(*nllVar->fFuncVars, nllVar.get());
1775 if (!fData.first) {
1776 if (!readOnly && isExpected && fGenFit) {
1777 // can try to do a readOnly in case can load from cache
1778 bool tmp = nllVar->get()->getAttribute("readOnly");
1779 nllVar->get()->setAttribute("readOnly");
1780 auto out = cfit_null(true);
1781 nllVar->get()->setAttribute("readOnly", tmp);
1782 if (out) {
1783 // retrieve from cache worked, no need to generate dataset
1784 return out;
1785 } else if (!tmp) { // don't need to setData if doing a readOnly fit
1786 nllVar->setData(data());
1787 }
1788 }
1789 } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit
1790 nllVar->setData(fData);
1791 }
1792 if (fUfit) {
1793 // move to ufit coords before evaluating
1794 *nllVar->fFuncVars = fUfit->floatParsFinal();
1795 }
1796 nllVar->fFuncVars->setAttribAll("Constant", false);
1797 *nllVar->fFuncVars = *coords; // will reconst the coords
1798 if (nllVar->fFuncGlobs)
1799 nllVar->fFuncGlobs->setAttribAll("Constant", true);
1800 if (fPOIName())
1801 nllVar->fFuncVars->find(fPOIName())
1802 ->setStringAttribute("altVal", (!std::isnan(fAltVal())) ? TString::Format("%g", fAltVal()) : nullptr);
1803 if (fGenFit) {
1804 nllVar->get()->SetName(
1805 TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys"));
1806 if (!isExpected)
1807 nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName()));
1808 }
1809 nllVar->get()->setStringAttribute("fitresultTitle", collectionContents(poi()).c_str());
1810 return (fNull_cfit = nllVar->minimize());
1811}
1812
1813std::shared_ptr<const RooFitResult> xRooNLLVar::xRooHypoPoint::cfit_lbound(bool readOnly)
1814{
1815 auto _first_poi = dynamic_cast<RooRealVar *>(poi().first());
1816 if (!_first_poi)
1817 return nullptr;
1818 if (_first_poi->getMin("physical") <= _first_poi->getMin())
1819 return nullptr;
1820 if (fLbound_cfit)
1821 return fLbound_cfit;
1822 if (auto rfit = retrieveFit(6)) {
1823 return fLbound_cfit = rfit;
1824 }
1825 if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly")))
1826 return nullptr;
1827 if (!nllVar->fFuncVars)
1828 nllVar->reinitialize();
1829 AutoRestorer snap(*nllVar->fFuncVars, nllVar.get());
1830 if (!fData.first) {
1831 if (!readOnly && isExpected && fGenFit) {
1832 // can try to do a readOnly in case can load from cache
1833 bool tmp = nllVar->get()->getAttribute("readOnly");
1834 nllVar->get()->setAttribute("readOnly");
1835 auto out = cfit_lbound(true);
1836 nllVar->get()->setAttribute("readOnly", tmp);
1837 if (out) {
1838 // retrieve from cache worked, no need to generate dataset
1839 return out;
1840 } else if (!tmp) { // don't need to setData if doing a readOnly fit
1841 nllVar->setData(data());
1842 }
1843 }
1844 } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit
1845 nllVar->setData(fData);
1846 }
1847 if (fUfit) {
1848 // move to ufit coords before evaluating
1849 *nllVar->fFuncVars = fUfit->floatParsFinal();
1850 }
1851 nllVar->fFuncVars->setAttribAll("Constant", false);
1852 *nllVar->fFuncVars = *coords; // will reconst the coords
1853 nllVar->fFuncVars->setRealValue(_first_poi->GetName(), _first_poi->getMin("physical"));
1854 if (nllVar->fFuncGlobs)
1855 nllVar->fFuncGlobs->setAttribAll("Constant", true);
1856 if (fPOIName())
1857 nllVar->fFuncVars->find(fPOIName())
1858 ->setStringAttribute("altVal", (!std::isnan(fAltVal())) ? TString::Format("%g", fAltVal()) : nullptr);
1859 if (fGenFit) {
1860 nllVar->get()->SetName(
1861 TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys"));
1862 if (!isExpected)
1863 nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName()));
1864 }
1865 nllVar->get()->setStringAttribute(
1866 "fitresultTitle",
1867 collectionContents(*std::unique_ptr<RooAbsCollection>(nllVar->fFuncVars->selectCommon(poi()))).c_str());
1868 return (fLbound_cfit = nllVar->minimize());
1869}
1870
1871std::shared_ptr<const RooFitResult> xRooNLLVar::xRooHypoPoint::cfit_alt(bool readOnly)
1872{
1873 if (std::isnan(fAltVal()))
1874 return nullptr;
1875 if (fAlt_cfit)
1876 return fAlt_cfit;
1877 if (auto rfit = retrieveFit(2)) {
1878 return fAlt_cfit = rfit;
1879 }
1880 if (!nllVar || (readOnly && nllVar->get() && !nllVar->get()->getAttribute("readOnly")))
1881 return nullptr;
1882 if (!nllVar->fFuncVars)
1883 nllVar->reinitialize();
1884 AutoRestorer snap(*nllVar->fFuncVars, nllVar.get());
1885 if (!fData.first) {
1886 if (!readOnly && isExpected && fGenFit) {
1887 // can try to do a readOnly in case can load from cache
1888 bool tmp = nllVar->get()->getAttribute("readOnly");
1889 nllVar->get()->setAttribute("readOnly");
1890 auto out = cfit_alt(true);
1891 nllVar->get()->setAttribute("readOnly", tmp);
1892 if (out) {
1893 // retrieve from cache worked, no need to generate dataset
1894 return out;
1895 } else if (!tmp) { // don't need to setData if doing a readOnly fit
1896 nllVar->setData(data());
1897 }
1898 }
1899 } else if (!nllVar->get()->getAttribute("readOnly")) { // don't need to setData if doing a readOnly fit
1900 nllVar->setData(fData);
1901 }
1902 if (fUfit) {
1903 // move to ufit coords before evaluating
1904 *nllVar->fFuncVars = fUfit->floatParsFinal();
1905 }
1906 nllVar->fFuncVars->setAttribAll("Constant", false);
1907 *nllVar->fFuncVars = *coords; // will reconst the coords
1908 if (nllVar->fFuncGlobs)
1909 nllVar->fFuncGlobs->setAttribAll("Constant", true);
1910 *nllVar->fFuncVars = alt_poi();
1911 if (fGenFit) {
1912 nllVar->get()->SetName(
1913 TString::Format("%s/%s_%s", nllVar->get()->GetName(), fGenFit->GetName(), (isExpected) ? "asimov" : "toys"));
1914 if (!isExpected)
1915 nllVar->get()->SetName(TString::Format("%s/%s", nllVar->get()->GetName(), fData.first->GetName()));
1916 }
1917 nllVar->get()->setStringAttribute("fitresultTitle", collectionContents(alt_poi()).c_str());
1918 return (fAlt_cfit = nllVar->minimize());
1919}
1920
1921std::pair<double, double> xRooNLLVar::xRooHypoPoint::sigma_mu(bool readOnly)
1922{
1923
1924 auto asi = asimov(readOnly);
1925
1926 if (!asi) {
1927 return std::make_pair(std::numeric_limits<double>::quiet_NaN(), 0);
1928 }
1929
1930 auto out = asi->pll(readOnly);
1931 return std::make_pair(std::abs(fNullVal() - fAltVal()) / sqrt(out.first),
1932 out.second * 0.5 * std::abs(fNullVal() - fAltVal()) / (out.first * sqrt(out.first)));
1933}
1934
1935std::pair<double, double> xRooNLLVar::xRooHypoPoint::pX_toys(bool alt, double nSigma)
1936{
1937 auto _ts = ts_toys(nSigma);
1938 if (std::isnan(_ts.first))
1939 return _ts;
1940 if (fPllType != xRooFit::Asymptotics::Uncapped && _ts.first == 0)
1941 return std::pair(1, 0); // don't need toys to compute this point!
1942
1943 TEfficiency eff("", "", 1, 0, 1);
1944
1945 auto &_theToys = (alt) ? altToys : nullToys;
1946
1947 if (_theToys.empty()) {
1948 return std::pair(0.5, std::numeric_limits<double>::infinity());
1949 }
1950
1951 // loop over toys, count how many are > ts value
1952 // nans (mean bad ts evaluations) will count towards uncertainty
1953 int nans = 0;
1954 double result = 0;
1955 double result_err_up = 0;
1956 double result_err_down = 0;
1957 for (auto &toy : _theToys) {
1958 if (std::isnan(std::get<1>(toy)))
1959 nans++;
1960 else {
1961 bool res = std::get<1>(toy) >= _ts.first;
1962 if (std::get<2>(toy) != 1)
1963 eff.FillWeighted(res, 0.5, std::get<2>(toy));
1964 else
1965 eff.Fill(res, 0.5);
1966 if (res)
1967 result += std::get<2>(toy);
1968 if (std::get<1>(toy) >= _ts.first - _ts.second)
1969 result_err_up += std::get<2>(toy);
1970 if (std::get<1>(toy) >= _ts.first - _ts.second)
1971 result_err_down += std::get<2>(toy);
1972 }
1973 }
1974 // symmetrize the error
1975 result_err_up -= result;
1976 result_err_down -= result;
1977 double result_err = std::max(std::abs(result_err_up), std::abs(result_err_down));
1978 // assume the nans would "add" to the p-value, conservative scenario
1979 result_err += nans;
1980 result_err /= _theToys.size();
1981
1982 // don't include the nans for the central value though
1983 result /= (_theToys.size() - nans);
1984
1985 // add to the result_err (in quadrature) the uncert due to limited stats
1986 result_err = sqrt(result_err * result_err + eff.GetEfficiencyErrorUp(1) * eff.GetEfficiencyErrorUp(1));
1987 return std::make_pair(result, result_err);
1988}
1989
1990std::pair<double, double> xRooNLLVar::xRooHypoPoint::pNull_toys(double nSigma)
1991{
1992 return pX_toys(false, nSigma);
1993}
1994
1995std::pair<double, double> xRooNLLVar::xRooHypoPoint::pAlt_toys(double nSigma)
1996{
1997 if (!std::isnan(nSigma)) {
1998 return std::pair(ROOT::Math::gaussian_cdf(nSigma), 0); // by construction
1999 }
2000 return pX_toys(true, nSigma);
2001}
2002
2004{
2005 xRooHypoPoint out;
2006 out.coords = coords;
2007 out.fPllType = fPllType; // out.fPOIName = fPOIName; out.fNullVal=fNullVal; out.fAltVal = fAltVal;
2008 out.nllVar = nllVar;
2009 if (!nllVar)
2010 return out;
2011 auto _cfit = cfit_null();
2012 if (!_cfit)
2013 return out;
2014 if (!nllVar->fFuncVars)
2015 nllVar->reinitialize();
2016 //*nllVar->fFuncVars = cfit_null()->floatParsFinal();
2017 //*nllVar->fFuncVars = cfit_null()->constPars();
2018 out.fData = xRooFit::generateFrom(*nllVar->fPdf, *_cfit, false, seed); // nllVar->generate(false,seed);
2019 out.fGenFit = _cfit;
2020 return out;
2021}
2022
2024{
2025 xRooHypoPoint out;
2026 out.coords = coords;
2027 out.fPllType = fPllType; // out.fPOIName = fPOIName; out.fNullVal=fNullVal; out.fAltVal = fAltVal;
2028 out.nllVar = nllVar;
2029 if (!nllVar)
2030 return out;
2031 if (!cfit_alt())
2032 return out;
2033 if (!nllVar->fFuncVars)
2034 nllVar->reinitialize();
2035 //*nllVar->fFuncVars = cfit_alt()->floatParsFinal();
2036 //*nllVar->fFuncVars = cfit_alt()->constPars();
2037 out.fData =
2038 xRooFit::generateFrom(*nllVar->fPdf, *cfit_alt(), false, seed); // out.data = nllVar->generate(false,seed);
2039 out.fGenFit = cfit_alt();
2040 return out;
2041}
2042
2043size_t xRooNLLVar::xRooHypoPoint::addToys(bool alt, int nToys, int initialSeed, double target, double target_nSigma,
2044 bool targetCLs, double relErrThreshold, size_t maxToys)
2045{
2046 if ((alt && !cfit_alt()) || (!alt && !cfit_null())) {
2047 throw std::runtime_error("Cannot add toys, invalid conditional fit");
2048 }
2049
2050 auto condition = [&]() { // returns true if need more toys
2051 if (std::isnan(target))
2052 return false;
2053 auto obs = targetCLs ? pCLs_toys(target_nSigma) : (alt ? pAlt_toys(target_nSigma) : pNull_toys(target_nSigma));
2054 if (!std::isnan(obs.first)) {
2055 double diff = (target < 0) ? obs.first : std::abs(obs.first - target);
2056 double err = obs.second;
2057 if (err > 1e-4 && diff <= relErrThreshold * obs.second) {
2058 // return true; // more toys needed
2059 if (targetCLs) {
2060 // decide which type we'd want to generate and update alt flag
2061 auto pNull = pNull_toys(target_nSigma);
2062 auto pAlt = pAlt_toys(target_nSigma);
2063 // std::cout << obs.first << " +/- " << obs.second << ": " << pNull.first << " +/- " << pNull.second << "
2064 // , " << pAlt.first << " +/- " << pAlt.second << std::endl;
2065 alt = (pAlt.second * pNull.first > pNull.second * pAlt.first);
2066 if ((alt ? pAlt.second : pNull.second) < 1e-4)
2067 return false; // stop if error gets too small
2068 }
2069 return true;
2070 }
2071 }
2072 return false;
2073 };
2074
2075 if (!std::isnan(target) && std::isnan(ts_toys(target_nSigma).first)) {
2076 if (std::isnan(target_nSigma)) {
2077 throw std::runtime_error("Cannot target obs p-value because ts value unavailable");
2078 }
2079 if (targetCLs && pCLs_toys(target_nSigma).second == 0) {
2080 // this happens if the mu_test=mu_alt ... no toys needed
2081 return 0;
2082 }
2083
2084 // try generating 100 alt toys
2085 Info("addToys", "First generating 100 alt toys in order to determine expected ts value");
2086 addToys(true, 100, initialSeed);
2087 // if still null then exit
2088 if (std::isnan(ts_toys(target_nSigma).first)) {
2089 throw std::runtime_error("Unable to determine expected ts value");
2090 }
2091 }
2092
2093 size_t nans = 0;
2094 float lastTime = 0;
2095 int lasti = 0;
2096 auto g = gROOT->Get<TGraph>("toyTime");
2097 if (!g) {
2098 g = new TGraph;
2099 g->SetNameTitle("toyTime", "Time per toy;Toy;time [s]");
2100 gROOT->Add(g);
2101 }
2102 g->Set(0);
2103 TStopwatch s2;
2104 s2.Start();
2105 TStopwatch s;
2106 s.Start();
2107
2108 size_t toysAdded(0);
2109 size_t altToysAdded(0);
2110 if (initialSeed) {
2111 RooRandom::randomGenerator()->SetSeed(initialSeed);
2112 }
2113 do {
2114 auto &toys = (alt) ? altToys : nullToys;
2115 if (toys.size() >= maxToys) {
2116 // cannot generate more toys, reached limit already
2117 break;
2118 }
2119 // don't generate toys if reached target
2120 if (!std::isnan(target) && !condition()) {
2121 break;
2122 }
2123 auto currVal = std::isnan(target) ? std::pair(0., 0.)
2124 : (targetCLs ? pCLs_toys(target_nSigma)
2125 : (alt ? pAlt_toys(target_nSigma) : pNull_toys(target_nSigma)));
2126 size_t nnToys = std::min(size_t(nToys), (maxToys - toys.size()));
2127
2128 for (size_t i = 0; i < nnToys; i++) {
2129 int seed = RooRandom::randomGenerator()->Integer(std::numeric_limits<uint32_t>::max());
2130 auto toy = ((alt) ? generateAlt(seed) : generateNull(seed));
2131 TDirectory *tmp = gDirectory;
2132 gDirectory = nullptr; // disables any saving of fit results for toys
2133 toys.push_back(std::make_tuple(seed, toy.pll().first, 1.));
2134 gDirectory = tmp;
2135 (alt ? altToysAdded : toysAdded)++;
2136 if (std::isnan(std::get<1>(toys.back())))
2137 nans++;
2138 g->SetPoint(g->GetN(), g->GetN(), s.RealTime() - lastTime); // stops the clock
2139 lastTime = s.RealTime();
2140 if (s.RealTime() > 10) {
2141 std::cout << "\r"
2142 << TString::Format("Generated %d/%d %s hypothesis toys [%.2f toys/s]",
2143 int(alt ? altToysAdded : toysAdded), int(nnToys), alt ? "alt" : "null",
2144 double(altToysAdded + toysAdded - lasti) / s.RealTime());
2145 if (!std::isnan(target)) {
2146 std::cout << " [current=" << currVal.first << "+/-" << currVal.second << " target=" << target
2147 << " nSigma=" << target_nSigma << "]";
2148 }
2149 std::cout << "..." << std::flush;
2150 lasti = altToysAdded + toysAdded;
2151 s.Reset();
2152 Draw();
2153 if (gPad) {
2154 gPad->Update();
2156 }
2157 s.Start();
2158 // std::cout << "Generated " << i << "/" << nToys << (alt ? " alt " : " null ") << " hypothesis toys " ..."
2159 // << std::endl;
2160 }
2161 s.Continue();
2162 }
2163 // sort the toys ... put nans first - do by setting all as negative inf (is that still necessary with the custom
2164 // sort below??)
2165 for (auto &t : toys) {
2166 if (std::isnan(std::get<1>(t)))
2167 std::get<1>(t) = -std::numeric_limits<double>::infinity();
2168 }
2169 std::sort(toys.begin(), toys.end(),
2170 [](const decltype(nullToys)::value_type &a, const decltype(nullToys)::value_type &b) -> bool {
2171 if (std::isnan(std::get<1>(a)))
2172 return true;
2173 if (std::isnan(std::get<1>(b)))
2174 return false;
2175 return std::get<1>(a) < std::get<1>(b);
2176 });
2177 for (auto &t : toys) {
2178 if (std::isinf(std::get<1>(t)))
2179 std::get<1>(t) = std::numeric_limits<double>::quiet_NaN();
2180 }
2181 if (std::isnan(target)) {
2182 break; // no more toys if not doing a target
2183 }
2184 // if(condition()) {
2185 // Info("addToys","Generating more toys to determine p-value ... currently: %f +/-
2186 // %f",pNull_toys(target_nSigma).first,pNull_toys(target_nSigma).second);
2187 // }
2188 } while (condition());
2189 if (lasti) {
2190 std::cout << "\r"
2191 << "Finished Generating ";
2192 if (toysAdded) {
2193 std::cout << toysAdded << " null ";
2194 }
2195 if (altToysAdded) {
2196 std::cout << altToysAdded << " alt ";
2197 }
2198 std::cout << "toys " << TString::Format("[%.2f toys/s overall]", double(toysAdded + altToysAdded) / s2.RealTime())
2199 << std::endl;
2200 Draw();
2201 if (gPad) {
2202 gPad->Update();
2203#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 30, 00)
2204 gPad->GetCanvas()->ResetUpdated(); // stops previous canvas being replaced in a jupyter notebook
2205#endif
2207 }
2208 }
2209
2210 if (nans > 0) {
2211 std::cout << "Warning: " << nans << " toys were bad" << std::endl;
2212 }
2213 return toysAdded;
2214}
2215
2216void xRooNLLVar::xRooHypoPoint::addNullToys(int nToys, int seed, double target, double target_nSigma)
2217{
2218 addToys(false, nToys, seed, target, target_nSigma);
2219}
2220void xRooNLLVar::xRooHypoPoint::addAltToys(int nToys, int seed, double target, double target_nSigma)
2221{
2222 addToys(true, nToys, seed, target, target_nSigma);
2223}
2224
2225void xRooNLLVar::xRooHypoPoint::addCLsToys(int nToys, int seed, double target, double target_nSigma)
2226{
2227 addToys(false, nToys, seed, target, target_nSigma, true);
2228 return;
2229 //
2230 // auto condition = [&](bool doingAlt=false) { // returns true if need more toys
2231 // if(std::isnan(target)) return false;
2232 // auto pval = pCLs_toys(target_nSigma);
2233 // if (!std::isnan(pval.first)) {
2234 // double diff = std::abs(pval.first - target);
2235 // double err = pval.second;
2236 // if (err > 1e-4 && diff <= 2 * pval.second) {
2237 // return true; // more toys needed
2238 // // decide which type we'd want to generate
2239 // // if it matches the type we are generating, then return true
2240 // auto pNull = pNull_toys(target_nSigma);
2241 // auto pAlt = pAlt_toys(target_nSigma);
2242 // if ((doingAlt ? pAlt.second : pNull.second) < 1e-4) return false; // stop if error gets too small
2243 // bool doAlt = (pAlt.second * pNull.first > pNull.second * pAlt.first);
2244 // return doAlt == doingAlt;
2245 // }
2246 // }
2247 // return false;
2248 // };
2249 // while(condition()) {
2250 // bool doAlt = false;
2251 // double relErrThreshold = 2;
2252 // if(nullToys.size()<size_t(nToys)) {
2253 // addToys(false,nToys);continue;
2254 // } else if(altToys.size()<size_t(nToys)) {
2255 // addToys(true,nToys);continue;
2256 // } else {
2257 // // see which have bigger errors ... generate more of that ...
2258 // auto pNull = pNull_toys(target_nSigma);
2259 // auto pAlt = pAlt_toys(target_nSigma);
2260 // doAlt = (pAlt.second*pNull.first > pNull.second*pAlt.first);
2261 // if( (doAlt ? pAlt.second : pNull.second) < 1e-4 ) break; // stop if error gets too small
2262 // auto pCLs = pCLs_toys(target_nSigma);
2263 // relErrThreshold = (doAlt) ? (pNull.second/pNull.first) : (pAlt.second/pAlt.first);
2264 // relErrThreshold = std::min(2.,std::abs(relErrThreshold));
2265 // std::cout << "Current pCLs = " << pCLs.first << " +/- " << pCLs.second
2266 // << " (pNull = " << pNull.first << " +/- " << pNull.second
2267 // << " , pAlt = " << pAlt.first << " +/- " << pAlt.second << ") ... generating more " << (doAlt ?
2268 // "alt" : "null") << " toys " << relErrThreshold << std::endl;
2269 //
2270 // }
2271 // if( addToys(doAlt, nToys/*, seed, -1, target_nSigma,relErrThreshold*/) == 0) {
2272 // break; // no toys got added, so stop looping
2273 // }
2274 // }
2275}
2276
2278xRooNLLVar::hypoPoint(const char *poiValues, double alt_value, const xRooFit::Asymptotics::PLLType &pllType)
2279{
2280 xRooHypoPoint out;
2281 // out.fPOIName = parName; out.fNullVal = value; out.fAltVal = alt_value;
2282
2283 if (!fFuncVars) {
2284 reinitialize();
2285 }
2286 AutoRestorer snap(*fFuncVars);
2287
2288 out.nllVar = std::make_shared<xRooNLLVar>(*this);
2289 out.fData = getData();
2290
2291 TStringToken pattern(poiValues, ",");
2292 TString poiNames;
2293 while (pattern.NextToken()) {
2294 TString s = pattern.Data();
2295 TString cName = s;
2296 double val = std::numeric_limits<double>::quiet_NaN();
2297 auto i = s.Index("=");
2298 if (i != -1) {
2299 cName = s(0, i);
2300 TString cVal = s(i + 1, s.Length());
2301 if (!cVal.IsFloat())
2302 throw std::runtime_error("poiValues must contain value");
2303 val = cVal.Atof();
2304 }
2305 auto v = dynamic_cast<RooRealVar *>(fFuncVars->find(cName));
2306 if (!v)
2307 throw std::runtime_error("Cannot find poi");
2308 if (!std::isnan(val))
2309 v->setVal(val);
2310 v->setConstant(); // because will select constants as coords
2311 if (poiNames != "") {
2312 poiNames += ",";
2313 }
2314 poiNames += cName;
2315 }
2316 if (poiNames == "") {
2317 throw std::runtime_error("No poi");
2318 }
2319 if (!std::isnan(alt_value)) {
2320 std::unique_ptr<RooAbsCollection> thePoi(fFuncVars->selectByName(poiNames));
2321 for (auto b : *thePoi) {
2322 if (!static_cast<RooRealVar *>(b)->hasRange("physical")) {
2323 static_cast<RooRealVar *>(b)->setRange("physical", 0, std::numeric_limits<double>::infinity());
2324 }
2325 }
2326 }
2327 auto _snap = std::unique_ptr<RooAbsCollection>(fFuncVars->selectByAttrib("Constant", true))->snapshot();
2328 _snap->setAttribAll("poi", false);
2329 std::unique_ptr<RooAbsCollection> _poi(_snap->selectByName(poiNames));
2330 _poi->setAttribAll("poi", true);
2331 if (std::isnan(alt_value)) {
2332 for (auto a : *_poi)
2333 a->setStringAttribute("altVal", nullptr);
2334 } else {
2335 for (auto a : *_poi)
2336 a->setStringAttribute("altVal", TString::Format("%g", alt_value));
2337 }
2338 if (fGlobs)
2339 _snap->remove(*fGlobs, true, true);
2340 out.coords.reset(_snap);
2341
2342 auto _type = pllType;
2343 if (_type == xRooFit::Asymptotics::Unknown) {
2344 // decide based on values
2345 if (std::isnan(alt_value))
2347 else if (dynamic_cast<RooRealVar *>(_poi->first())->getVal() >= alt_value)
2349 else
2351 }
2352
2353 out.fPllType = _type;
2354
2355 return out;
2356}
2357
2358xRooNLLVar::xRooHypoPoint
2359xRooNLLVar::hypoPoint(double value, double alt_value, const xRooFit::Asymptotics::PLLType &pllType)
2360{
2361 if (!fFuncVars) {
2362 reinitialize();
2363 }
2364 std::unique_ptr<RooAbsCollection> _poi(fFuncVars->selectByAttrib("poi", true));
2365 if (_poi->empty()) {
2366 throw std::runtime_error("No POI specified in model");
2367 } else if (_poi->size() != 1) {
2368 throw std::runtime_error("Multiple POI specified in model");
2369 }
2370 return hypoPoint(_poi->first()->GetName(), value, alt_value, pllType);
2371}
2372
2374xRooNLLVar::hypoPoint(const char *parName, double value, double alt_value, const xRooFit::Asymptotics::PLLType &pllType)
2375{
2376 return hypoPoint(TString::Format("%s=%f", parName, value), alt_value, pllType);
2377}
2378
2380{
2381
2382 if (!nllVar && !hypoTestResult)
2383 return;
2384
2385 TString sOpt(opt);
2386 sOpt.ToLower();
2387 bool hasSame = sOpt.Contains("same");
2388 sOpt.ReplaceAll("same", "");
2389
2390 TVirtualPad *pad = gPad;
2391
2392 TH1 *hAxis = nullptr;
2393
2394 auto clearPad = []() {
2395 gPad->Clear();
2396 if (gPad->GetNumber() == 0) {
2397 gPad->SetBottomMargin(gStyle->GetPadBottomMargin());
2398 gPad->SetTopMargin(gStyle->GetPadTopMargin());
2399 gPad->SetLeftMargin(gStyle->GetPadLeftMargin());
2400 gPad->SetRightMargin(gStyle->GetPadRightMargin());
2401 }
2402 };
2403
2404 if (!hasSame || !pad) {
2405 if (!pad) {
2407 pad = gPad;
2408 }
2409 clearPad();
2410 } else {
2411 // get the histogram representing the axes
2412 hAxis = dynamic_cast<TH1 *>(pad->GetPrimitive(".axis"));
2413 if (!hAxis) {
2414 for (auto o : *pad->GetListOfPrimitives()) {
2415 if (hAxis = dynamic_cast<TH1 *>(o); hAxis)
2416 break;
2417 }
2418 }
2419 }
2420
2421 // get min and max values
2422 double _min = std::numeric_limits<double>::quiet_NaN();
2423 double _max = -std::numeric_limits<double>::quiet_NaN();
2424
2425 for (auto &p : nullToys) {
2426 if (std::get<2>(p) == 0)
2427 continue;
2428 if (std::isnan(std::get<1>(p)))
2429 continue;
2430 _min = std::min(std::get<1>(p), _min);
2431 _max = std::max(std::get<1>(p), _max);
2432 }
2433 for (auto &p : altToys) {
2434 if (std::get<2>(p) == 0)
2435 continue;
2436 if (std::isnan(std::get<1>(p)))
2437 continue;
2438 _min = std::min(std::get<1>(p), _min);
2439 _max = std::max(std::get<1>(p), _max);
2440 }
2441
2442 auto obs = pll();
2443 if (!std::isnan(obs.first)) {
2444 _min = std::min(obs.first - std::abs(obs.first) * 0.1, _min);
2445 _max = std::max(obs.first + std::abs(obs.first) * 0.1, _max);
2446 }
2447 // these are used down below to add obs p-values to legend, but up here because can trigger fits that create asimov
2448 auto pNull = pNull_toys();
2449 auto pAlt = pAlt_toys();
2450 auto pNullA = pNull_asymp();
2451 auto pAltA = pAlt_asymp();
2452 sigma_mu(true);
2453 auto asi = (fAsimov && fAsimov->fUfit && fAsimov->fNull_cfit) ? fAsimov->pll().first
2454 : std::numeric_limits<double>::quiet_NaN();
2455 if (!std::isnan(asi) && asi > 0 && fPllType != xRooFit::Asymptotics::Unknown) {
2456 // can calculate asymptotic distributions,
2457 _min = std::min(asi - std::abs(asi), _min);
2458 _max = std::max(asi + std::abs(asi), _max);
2459 }
2460 if (_min > 0)
2461 _min = 0;
2462
2463 auto _poi = dynamic_cast<RooRealVar *>(poi().first());
2464
2465 auto makeHist = [&](bool isAlt) {
2466 TString title;
2467 auto h = new TH1D((isAlt) ? "alt_toys" : "null_toys", "", 100, _min, _max + (_max - _min) * 0.01);
2468 h->SetDirectory(0);
2469 size_t nBadOrZero = 0;
2470 for (auto &p : (isAlt) ? altToys : nullToys) {
2471 double w = std::isnan(std::get<1>(p)) ? 0 : std::get<2>(p);
2472 if (w == 0)
2473 nBadOrZero++;
2474 if (!std::isnan(std::get<1>(p)))
2475 h->Fill(std::get<1>(p), w);
2476 }
2477 if (h->GetEntries() > 0)
2478 h->Scale(1. / h->Integral(0, h->GetNbinsX() + 1));
2479
2480 // add POI values to identify hypos
2481 // for(auto p : *fPOI) {
2482 // if (auto v = dynamic_cast<RooRealVar*>(p)) {
2483 // if (auto v2 = dynamic_cast<RooRealVar*>(fAltPoint->fCoords->find(*v)); v2 &&
2484 // v2->getVal()!=v->getVal()) {
2485 // // found point that differs in poi and altpoint value, so print my coords value for this
2486 // title += TString::Format("%s' = %g,
2487 // ",v->GetTitle(),dynamic_cast<RooRealVar*>(fCoords->find(*v))->getVal());
2488 // }
2489 // }
2490 // }
2491 if (fPOIName())
2492 title += TString::Format("%s' = %g", fPOIName(), (isAlt) ? fAltVal() : fNullVal());
2493 title += TString::Format(" , N_{toys}=%d", int((isAlt) ? altToys.size() : nullToys.size()));
2494 if (nBadOrZero > 0)
2495 title += TString::Format(" (N_{bad/0}=%d)", int(nBadOrZero));
2496 title += ";";
2497 title += tsTitle();
2498 title += TString::Format(";Probability Mass");
2499 h->SetTitle(title);
2500 h->SetLineColor(isAlt ? kRed : kBlue);
2501 h->SetLineWidth(2);
2502 h->SetMarkerSize(0);
2503 h->SetBit(kCanDelete);
2504 return h;
2505 };
2506
2507 auto nullHist = makeHist(false);
2508 auto altHist = makeHist(true);
2509
2510 TLegend *l = nullptr;
2511 auto h = (nullHist->GetEntries()) ? nullHist : altHist;
2512 if (!hasSame) {
2513 gPad->SetLogy();
2514 auto axis = static_cast<TH1 *>(h->Clone(".axis"));
2515 axis->SetBit(kCanDelete);
2516 axis->SetStats(false);
2517 axis->Reset("ICES");
2518 axis->SetTitle(TString::Format("%s HypoPoint", collectionContents(poi()).c_str()));
2519 axis->SetLineWidth(0);
2520 axis->Draw(""); // h->Draw("axis"); cant use axis option if want title drawn
2521 axis->SetMinimum(1e-7);
2522 axis->GetYaxis()->SetRangeUser(1e-7, 10);
2523 axis->SetMaximum(h->GetMaximum());
2524 hAxis = axis;
2525 l = new TLegend(0.4, 0.7, 1. - gPad->GetRightMargin(), 1. - gPad->GetTopMargin());
2526 l->SetName("legend");
2527 l->SetFillStyle(0);
2528 l->SetBorderSize(0);
2530 l->Draw();
2531 } else {
2532 for (auto o : *gPad->GetListOfPrimitives()) {
2533 l = dynamic_cast<TLegend *>(o);
2534 if (l)
2535 break;
2536 }
2537 }
2538
2539 if (h->GetEntries() > 0)
2540 h->Draw("esame");
2541 else
2542 h->Draw("axissame"); // for unknown reason if second histogram empty it still draws with two weird bars???
2543 h = altHist;
2544 if (h->GetEntries() > 0)
2545 h->Draw("esame");
2546 else
2547 h->Draw("axissame"); // for unknown reason if second histogram empty it still draws with two weird bars???
2548
2549 if (l) {
2550 l->AddEntry(nullHist);
2551 l->AddEntry(altHist);
2552 }
2553
2554 if (fAsimov && fAsimov->fUfit && fAsimov->fNull_cfit && !std::isnan(sigma_mu().first) && !std::isnan(fAltVal())) {
2555 auto hh = static_cast<TH1 *>(nullHist->Clone("null_asymp"));
2556 hh->SetBit(kCanDelete);
2557 hh->SetStats(false);
2558 hh->SetLineStyle(2);
2559 hh->Reset();
2560 for (int i = 1; i <= hh->GetNbinsX(); i++) {
2561 hh->SetBinContent(
2562 i, xRooFit::Asymptotics::PValue(fPllType, hh->GetBinLowEdge(i), fNullVal(), fNullVal(), sigma_mu().first,
2563 _poi->getMin("physical"), _poi->getMax("physical")) -
2564 xRooFit::Asymptotics::PValue(fPllType, hh->GetBinLowEdge(i + 1), fNullVal(), fNullVal(),
2565 sigma_mu().first, _poi->getMin("physical"), _poi->getMax("physical")));
2566 }
2567 hh->Draw("lsame");
2568 hh = static_cast<TH1 *>(altHist->Clone("alt_asymp"));
2569 hh->SetBit(kCanDelete);
2570 hh->SetStats(false);
2571 hh->SetLineStyle(2);
2572 hh->Reset();
2573 for (int i = 1; i <= hh->GetNbinsX(); i++) {
2574 hh->SetBinContent(
2575 i, xRooFit::Asymptotics::PValue(fPllType, hh->GetBinLowEdge(i), fNullVal(), fAltVal(), sigma_mu().first,
2576 _poi->getMin("physical"), _poi->getMax("physical")) -
2577 xRooFit::Asymptotics::PValue(fPllType, hh->GetBinLowEdge(i + 1), fNullVal(), fAltVal(),
2578 sigma_mu().first, _poi->getMin("physical"), _poi->getMax("physical")));
2579 }
2580 hh->Draw("lsame");
2581 }
2582
2583 // draw observed points
2584 TLine ll;
2585 ll.SetLineStyle(1);
2586 ll.SetLineWidth(3);
2587 // for(auto p : fObs) {
2588 auto tl = ll.DrawLine(obs.first, hAxis->GetMinimum(), obs.first, 0.1);
2589 auto label = TString::Format("obs ts = %.4f", obs.first);
2590 if (obs.second)
2591 label += TString::Format(" #pm %.4f", obs.second);
2592
2593 l->AddEntry(tl, label, "l");
2594 label = "";
2595 if (!std::isnan(pNull.first) || !std::isnan(pAlt.first)) {
2596 auto pCLs = pCLs_toys();
2597 label += " p_{toy}=(";
2598 label += (std::isnan(pNull.first)) ? "-" : TString::Format("%.4f #pm %.4f", pNull.first, pNull.second);
2599 label += (std::isnan(pAlt.first)) ? ",-" : TString::Format(",%.4f #pm %.4f", pAlt.first, pAlt.second);
2600 label += (std::isnan(pCLs.first)) ? ",-)" : TString::Format(",%.4f #pm %.4f)", pCLs.first, pCLs.second);
2601 }
2602 if (label.Length() > 0)
2603 l->AddEntry("", label, "");
2604 label = "";
2605 if (!std::isnan(pNullA.first) || !std::isnan(pAltA.first)) {
2606 auto pCLs = pCLs_asymp();
2607 label += " p_{asymp}=(";
2608 label += (std::isnan(pNullA.first)) ? "-" : TString::Format("%.4f #pm %.4f", pNullA.first, pNullA.second);
2609 label += (std::isnan(pAltA.first)) ? ",-" : TString::Format(",%.4f #pm %.4f", pAltA.first, pAltA.second);
2610 label += (std::isnan(pCLs.first)) ? ",-)" : TString::Format(",%.4f #pm %.4f)", pCLs.first, pCLs.second);
2611 }
2612 if (label.Length() > 0)
2613 l->AddEntry("", label, "");
2614
2615 if (auto ax = dynamic_cast<TH1 *>(gPad->GetPrimitive(".axis")))
2616 ax->GetYaxis()->SetRangeUser(1e-7, 1);
2617}
2618
2620{
2621 auto v = dynamic_cast<RooRealVar *>(poi().empty() ? nullptr : poi().first());
2623 if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits<double>::infinity())
2624 return (inWords) ? TString::Format("Lower-Bound One-Sided Limit PLR")
2625 : TString::Format("#tilde{q}_{%s=%g}", v->GetTitle(), v->getVal());
2626 else if (v)
2627 return (inWords) ? TString::Format("One-Sided Limit PLR")
2628 : TString::Format("q_{%s=%g}", v->GetTitle(), v->getVal());
2629 else
2630 return "q";
2631 } else if (fPllType == xRooFit::Asymptotics::TwoSided) {
2632 if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits<double>::infinity())
2633 return (inWords) ? TString::Format("Lower-Bound PLR")
2634 : TString::Format("#tilde{t}_{%s=%g}", v->GetTitle(), v->getVal());
2635 else if (v) {
2636 return (inWords) ? TString::Format("-2log[L(%s,#hat{#hat{#theta}})/L(#hat{%s},#hat{#theta})]", v->GetTitle(),
2637 v->GetTitle())
2638 : TString::Format("t_{%s=%g}", v->GetTitle(), v->getVal());
2639 } else
2640 return "t";
2641 } else if (fPllType == xRooFit::Asymptotics::OneSidedNegative) {
2642 if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits<double>::infinity())
2643 return (inWords) ? TString::Format("Lower-Bound One-Sided Discovery PLR")
2644 : TString::Format("#tilde{r}_{%s=%g}", v->GetTitle(), v->getVal());
2645 else if (v)
2646 return (inWords) ? TString::Format("One-Sided Discovery PLR")
2647 : TString::Format("r_{%s=%g}", v->GetTitle(), v->getVal());
2648 else
2649 return "r";
2650 } else if (fPllType == xRooFit::Asymptotics::Uncapped) {
2651 if (v && v->hasRange("physical") && v->getMin("physical") != -std::numeric_limits<double>::infinity())
2652 return (inWords) ? TString::Format("Lower-Bound Uncapped PLR")
2653 : TString::Format("#tilde{s}_{%s=%g}", v->GetTitle(), v->getVal());
2654 else if (v)
2655 return (inWords) ? TString::Format("Uncapped PLR") : TString::Format("s_{%s=%g}", v->GetTitle(), v->getVal());
2656 else
2657 return "s";
2658 } else {
2659 return "Test Statistic";
2660 }
2661}
2662
2664{
2665 return (poi().empty()) ? nullptr : (poi().first())->GetName();
2666}
2668{
2669 auto first_poi = dynamic_cast<RooAbsReal *>(poi().first());
2670 return (first_poi == nullptr) ? std::numeric_limits<double>::quiet_NaN() : first_poi->getVal();
2671}
2673{
2674 auto _alt_poi = alt_poi(); // need to keep alive as alt_poi owns its contents
2675 auto first_poi = dynamic_cast<RooAbsReal *>(_alt_poi.first());
2676 return (first_poi == nullptr) ? std::numeric_limits<double>::quiet_NaN() : first_poi->getVal();
2677}
2678
2679xRooNLLVar::xRooHypoSpace xRooNLLVar::hypoSpace(const char *parName, int nPoints, double low, double high,
2680 double alt_value, const xRooFit::Asymptotics::PLLType &pllType)
2681{
2682 if (nPoints < 0) {
2683 // catches case where pyROOT has converted TestStatistic enum to int
2684 int tsType = nPoints;
2685 double alt_val = std::numeric_limits<double>::quiet_NaN();
2687 alt_val = 0;
2688 } else if (tsType == xRooFit::TestStatistic::q0 || tsType == xRooFit::TestStatistic::uncappedq0) {
2689 alt_val = 1;
2690 }
2691
2692 auto out = hypoSpace(parName, pllType, alt_val);
2693
2694
2695 // TODO: things like the physical range and alt value can't be stored on the poi
2696 // because if they change they will change for all hypoSpaces at once, so cannot have
2697 // two hypoSpace with e.g. different physical ranges.
2698 // the hypoSpace should make a copy of them at some point
2699 for (auto p : out.poi()) {
2700 if (tsType == xRooFit::TestStatistic::qmutilde) {
2701 dynamic_cast<RooRealVar *>(p)->setRange("physical", 0, std::numeric_limits<double>::infinity());
2702 Info("xRooNLLVar::hypoSpace", "Setting physical range of %s to [0,inf]", p->GetName());
2703 } else if(dynamic_cast<RooRealVar *>(p)->hasRange("physical")) {
2704 dynamic_cast<RooRealVar *>(p)->removeRange("physical");
2705 Info("xRooNLLVar::hypoSpace", "Setting physical range of %s to [-inf,inf] (i.e. removed range)", p->GetName());
2706 }
2707 }
2708
2709
2710 // ensure pll type is set explicitly if known at this point
2712 out.fTestStatType = xRooFit::Asymptotics::OneSidedPositive;
2713 } else if (tsType == xRooFit::TestStatistic::uncappedq0) {
2714 out.fTestStatType = xRooFit::Asymptotics::Uncapped;
2715 } else if (tsType == xRooFit::TestStatistic::q0) {
2716 out.fTestStatType = xRooFit::Asymptotics::OneSidedNegative;
2717 }
2718
2719 // in this case the arguments are shifted over by one
2720 if (int(low + 0.5) > 0) {
2721 out.AddPoints(parName, int(low + 0.5), high, alt_value);
2722 } else {
2723 for (auto p : out.poi()) {
2724 dynamic_cast<RooRealVar *>(p)->setRange("scan", high, alt_value);
2725 }
2726 }
2727 return out;
2728 }
2729
2730 xRooNLLVar::xRooHypoSpace hs = hypoSpace(parName, pllType, alt_value);
2731 if (nPoints > 0)
2732 hs.AddPoints(parName, nPoints, low, high);
2733 else {
2734 for (auto p : hs.poi()) {
2735 dynamic_cast<RooRealVar *>(p)->setRange("scan", low, high);
2736 }
2737 }
2738 return hs;
2739}
2740
2741xRooNLLVar::xRooHypoSpace xRooNLLVar::hypoSpace(int nPoints, double low, double high, double alt_value,
2742 const xRooFit::Asymptotics::PLLType &pllType)
2743{
2744 auto _poi = std::unique_ptr<RooAbsCollection>(
2745 std::unique_ptr<RooAbsCollection>(pdf()->getVariables())->selectByAttrib("poi", true));
2746 if (_poi->empty())
2747 throw std::runtime_error("You must specify a POI for the hypoSpace");
2748 return hypoSpace(_poi->first()->GetName(), nPoints, low, high, alt_value, pllType);
2749}
2750
2752xRooNLLVar::hypoSpace(const char *parName, const xRooFit::Asymptotics::PLLType &pllType, double alt_value)
2753{
2754 xRooNLLVar::xRooHypoSpace s(parName, parName);
2755
2756 s.AddModel(pdf());
2757 if (strlen(parName)) {
2758 std::unique_ptr<RooAbsCollection> axes(s.pars()->selectByName(parName));
2759 if (axes->empty())
2760 throw std::runtime_error("parameter not found");
2761 axes->setAttribAll("axis", true);
2762 }
2763 /*if (std::unique_ptr<RooAbsCollection>(s.pars()->selectByAttrib("poi", true))->empty()) {
2764 throw std::runtime_error("You must specify at least one POI for the hypoSpace");
2765 }*/
2766 s.fNlls[s.fPdfs.begin()->second] = std::make_shared<xRooNLLVar>(*this);
2767 s.fTestStatType = pllType;
2768
2769 for (auto poi : s.poi()) {
2770 poi->setStringAttribute("altVal", std::isnan(alt_value) ? nullptr : TString::Format("%f", alt_value));
2771 }
2772
2773 return s;
2774}
2775
2777{
2778 if (hypoTestResult) {
2779 return *hypoTestResult;
2780 }
2782 out.SetBackgroundAsAlt(true);
2783 out.SetName(TUUID().AsString());
2784 out.SetTitle(TString::Format("%s HypoPoint", collectionContents(poi()).c_str()));
2785
2786 bool setReadonly = false;
2787 if (nllVar && !nllVar->get()->getAttribute("readOnly")) {
2788 setReadonly = true;
2789 nllVar->get()->setAttribute("readOnly");
2790 }
2791
2792 auto ts_obs = ts_asymp();
2793
2794 out.SetTestStatisticData(ts_obs.first);
2795
2796 // build a ds to hold all fits ... store coords in the globs list of the nullDist
2797 // also need to store at least mu_hat value(s)
2798 RooArgList fitDetails;
2799 RooArgList fitMeta;
2800 fitMeta.addClone(RooCategory(
2801 "pllType", "test statistic type",
2802 {{"TwoSided", 0}, {"OneSidedPositive", 1}, {"OneSidedNegative", 2}, {"Uncapped", 3}, {"Unknown", 4}}));
2803 if (ufit()) {
2804 fitMeta.addClone(ufit()->floatParsFinal());
2805 }
2806 fitMeta.setCatIndex("pllType", int(fPllType));
2807 fitMeta.addClone(RooRealVar("isExpected", "isExpected", int(isExpected)));
2808 fitDetails.addClone(RooCategory("type", "fit type",
2809 {{"ufit", 0},
2810 {"cfit_null", 1},
2811 {"cfit_alt", 2},
2812 {"asimov_ufit", 3},
2813 {"asimov_cfit_null", 4},
2814 {"gen", 5},
2815 {"cfit_lbound", 6}}));
2816 // fitDetails.addClone(RooStringVar("name", "Fit Name", "")); -- not supported properly in ROOT yet
2817 fitDetails.addClone(RooRealVar("status", "status", 0));
2818 fitDetails.addClone(RooRealVar("minNll", "minNll", 0));
2819 fitDetails.addClone(RooRealVar("edm", "edm", 0));
2820 auto fitDS = new RooDataSet("fits", "fit summary data", fitDetails);
2821 fitDS->convertToTreeStore(); // strings not stored properly in vector store, so do convert!
2822
2823 for (int i = 0; i < 7; i++) {
2824 std::shared_ptr<const RooFitResult> fit;
2825 switch (i) {
2826 case 0: fit = ufit(); break;
2827 case 1: fit = cfit_null(); break;
2828 case 2: fit = cfit_alt(); break;
2829 case 3: fit = asimov() ? asimov()->ufit(true) : nullptr; break;
2830 case 4: fit = asimov() ? asimov()->cfit_null(true) : nullptr; break;
2831 case 5: fit = fGenFit; break;
2832 case 6: fit = cfit_lbound(); break;
2833 }
2834 if (fit) {
2835 fitDetails.setCatIndex("type", i);
2836 fitMeta.addClone(RooStringVar(TString::Format("%s.name", fitDetails.getCatLabel("type")),
2837 fitDetails.getCatLabel("type"), fit->GetName()));
2838 // fitDetails.setStringValue("name",fit->GetName());
2839 fitDetails.setRealValue("status", fit->status());
2840 fitDetails.setRealValue("minNll", fit->minNll());
2841 fitDetails.setRealValue("edm", fit->edm());
2842 fitDS->add(fitDetails);
2843 }
2844 }
2845 fitDS->setGlobalObservables(fitMeta);
2846
2847 out.SetFitInfo(fitDS);
2848
2849 RooArgList nullDetails;
2850 RooArgList nullMeta;
2851 nullMeta.addClone(*coords);
2852 nullDetails.addClone(RooRealVar("seed", "Toy Seed", 0));
2853 nullDetails.addClone(RooRealVar("ts", "test statistic value", 0));
2854 nullDetails.addClone(RooRealVar("weight", "weight", 1));
2855 auto nullToyDS = new RooDataSet("nullToys", "nullToys", nullDetails, "weight");
2856 nullToyDS->setGlobalObservables(nullMeta);
2857 if (!nullToys.empty()) {
2858
2859 std::vector<double> values;
2860 std::vector<double> weights;
2861 values.reserve(nullToys.size());
2862 weights.reserve(nullToys.size());
2863
2864 for (auto &t : nullToys) {
2865 values.push_back(std::get<1>(t));
2866 weights.push_back(std::get<2>(t));
2867 nullDetails.setRealValue("seed", std::get<0>(t));
2868 nullDetails.setRealValue("ts", std::get<1>(t));
2869 nullToyDS->add(nullDetails, std::get<2>(t));
2870 }
2871 out.SetNullDistribution(new RooStats::SamplingDistribution("null", "Null dist", values, weights, tsTitle()));
2872#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
2873 out.fNullPValue = pNull_toys().first; // technically set above
2874 out.fNullPValueError =
2875 pNull_toys().second; // overrides binomial error used in SamplingDistribution::IntegralAndError
2876#else
2877 out.SetNullPValue(pNull_toys().first); // technically set above
2878 out.SetNullPValueError(
2879 pNull_toys().second); // overrides binomial error used in SamplingDistribution::IntegralAndError
2880#endif
2881 } else {
2882#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
2883 out.fNullPValue = pNull_asymp().first;
2884 out.fNullPValueError = pNull_asymp().second;
2885#else
2886 out.SetNullPValue(pNull_asymp().first);
2887 out.SetNullPValueError(pNull_asymp().second);
2888#endif
2889 }
2890 out.SetNullDetailedOutput(nullToyDS);
2891
2892 if (!altToys.empty()) {
2893 std::vector<double> values;
2894 std::vector<double> weights;
2895 values.reserve(altToys.size());
2896 weights.reserve(altToys.size());
2897 RooArgList altDetails;
2898 RooArgList altMeta;
2899 altDetails.addClone(RooRealVar("seed", "Toy Seed", 0));
2900 altDetails.addClone(RooRealVar("ts", "test statistic value", 0));
2901 altDetails.addClone(RooRealVar("weight", "weight", 1));
2902 auto altToyDS = new RooDataSet("altToys", "altToys", altDetails, "weight");
2903 altToyDS->setGlobalObservables(altMeta);
2904 for (auto &t : altToys) {
2905 values.push_back(std::get<1>(t));
2906 weights.push_back(std::get<2>(t));
2907 altDetails.setRealValue("seed", std::get<0>(t));
2908 altDetails.setRealValue("ts", std::get<1>(t));
2909 altToyDS->add(altDetails, std::get<2>(t));
2910 }
2911 out.SetAltDistribution(new RooStats::SamplingDistribution("alt", "Alt dist", values, weights, tsTitle()));
2912 out.SetAltDetailedOutput(altToyDS);
2913#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
2914 out.fAlternatePValue = pAlt_toys().first; // technically set above
2915 out.fAlternatePValueError =
2916 pAlt_toys().second; // overrides binomial error used in SamplingDistribution::IntegralAndError
2917#else
2918 out.SetAltPValue(pAlt_toys().first); // technically set above
2919 out.SetAltPValueError(
2920 pAlt_toys().second); // overrides binomial error used in SamplingDistribution::IntegralAndError
2921#endif
2922
2923 } else {
2924#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
2925 out.fAlternatePValue = pAlt_asymp().first;
2926 out.fAlternatePValueError = pAlt_asymp().second;
2927#else
2928 out.SetAltPValue(pAlt_asymp().first);
2929 out.SetAltPValueError(pAlt_asymp().second);
2930#endif
2931 }
2932
2933 if (setReadonly) {
2934 nllVar->get()->setAttribute("readOnly", false);
2935 }
2936
2937 return out;
2938}
2939
#define SafeDelete(p)
Definition RConfig.hxx:525
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
const char Option_t
Definition RtypesCore.h:66
@ kRed
Definition Rtypes.h:66
@ kBlue
Definition Rtypes.h:66
#define gDirectory
Definition TDirectory.h:384
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:218
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
winID h TVirtualViewer3D TVirtualGLPainter p
winID h TVirtualViewer3D vv
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 Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
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 np
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
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 Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
@ kCanDelete
Definition TObject.h:367
#define gROOT
Definition TROOT.h:407
static char * Format(const char *format, va_list ap)
Format a string in a circular formatting buffer (using a printf style format descriptor).
Definition TString.cxx:2420
R__EXTERN TStyle * gStyle
Definition TStyle.h:433
R__EXTERN TSystem * gSystem
Definition TSystem.h:560
#define gPad
AutoRestorer(const RooAbsCollection &s, xRooNLLVar *nll=nullptr)
RooArgSet fPars
TString fOldTitle
TString fOldName
std::pair< std::shared_ptr< RooAbsData >, std::shared_ptr< const RooAbsCollection > > fOldData
xRooNLLVar * fNll
std::unique_ptr< RooAbsCollection > fSnap
static double k(const IncompatFunc &compatRegions, double pValue, double poiVal, double poiPrimeVal, double sigma_mu=0, double mu_low=-std::numeric_limits< double >::infinity(), double mu_high=std::numeric_limits< double >::infinity())
static int CompatFactor(const IncompatFunc &func, double mu_hat)
static double PValue(const IncompatFunc &compatRegions, double k, double mu, double mu_prime, double sigma_mu=0, double mu_low=-std::numeric_limits< double >::infinity(), double mu_high=std::numeric_limits< double >::infinity())
static std::shared_ptr< const RooFitResult > minimize(RooAbsReal &nll, const std::shared_ptr< ROOT::Fit::FitConfig > &fitConfig=nullptr, const std::shared_ptr< RooLinkedList > &nllOpts=nullptr)
Definition xRooFit.cxx:645
static std::pair< std::shared_ptr< RooAbsData >, std::shared_ptr< const RooAbsCollection > > generateFrom(RooAbsPdf &pdf, const RooFitResult &fr, bool expected=false, int seed=0)
Definition xRooFit.cxx:135
static std::shared_ptr< ROOT::Fit::FitConfig > createFitConfig()
Definition xRooFit.cxx:470
double impact(const char *poi, const char *np, bool up=true, bool prefit=false, bool approx=false)
xRooFitResult ifit(const char *np, bool up, bool prefit=false)
double conditionalError(const char *poi, const char *nps, bool up=true, bool approx=false)
RooArgList ranknp(const char *poi, bool up=true, bool prefit=false, double approxThreshold=std::numeric_limits< double >::infinity())
xRooFitResult(const std::shared_ptr< xRooNode > &in, const std::shared_ptr< xRooNLLVar > &nll=nullptr)
xRooFitResult cfit(const char *poiValues, const char *alias=nullptr)
std::shared_ptr< RooStats::HypoTestResult > hypoTestResult
Definition xRooNLLVar.h:262
std::pair< double, double > getVal(const char *what)
std::shared_ptr< const RooFitResult > retrieveFit(int type)
std::pair< double, double > pNull_toys(double nSigma=std::numeric_limits< double >::quiet_NaN())
std::pair< double, double > pAlt_toys(double nSigma=std::numeric_limits< double >::quiet_NaN())
std::vector< std::tuple< int, double, double > > altToys
Definition xRooNLLVar.h:259
std::shared_ptr< const RooAbsCollection > coords
Definition xRooNLLVar.h:247
std::shared_ptr< const RooFitResult > cfit_lbound(bool readOnly=false)
void Draw(Option_t *opt="") override
Default Draw method for all objects.
std::pair< double, double > ts_asymp(double nSigma=std::numeric_limits< double >::quiet_NaN())
std::shared_ptr< const RooFitResult > fUfit
Definition xRooNLLVar.h:249
xRooHypoPoint(std::shared_ptr< RooStats::HypoTestResult > htr=nullptr, const RooAbsCollection *_coords=nullptr)
std::vector< std::tuple< int, double, double > > nullToys
Definition xRooNLLVar.h:257
std::shared_ptr< xRooHypoPoint > asimov(bool readOnly=false)
std::pair< double, double > pll(bool readOnly=false)
std::shared_ptr< const RooFitResult > ufit(bool readOnly=false)
void Print(Option_t *opt="") const override
Print TNamed name and title.
std::shared_ptr< const RooFitResult > cfit_null(bool readOnly=false)
std::pair< std::shared_ptr< RooAbsData >, std::shared_ptr< const RooAbsCollection > > data()
std::pair< double, double > sigma_mu(bool readOnly=false)
std::shared_ptr< const RooFitResult > cfit_alt(bool readOnly=false)
size_t addToys(bool alt, int nToys, int initialSeed=0, double target=std::numeric_limits< double >::quiet_NaN(), double target_nSigma=std::numeric_limits< double >::quiet_NaN(), bool targetCLs=false, double relErrThreshold=2., size_t maxToys=10000)
void addAltToys(int nToys=1, int seed=0, double target=std::numeric_limits< double >::quiet_NaN(), double target_nSigma=std::numeric_limits< double >::quiet_NaN())
std::pair< double, double > pX_toys(bool alt, double nSigma=std::numeric_limits< double >::quiet_NaN())
void addCLsToys(int nToys=1, int seed=0, double target=std::numeric_limits< double >::quiet_NaN(), double target_nSigma=std::numeric_limits< double >::quiet_NaN())
std::pair< double, double > pAlt_asymp(double nSigma=std::numeric_limits< double >::quiet_NaN())
std::pair< double, double > ts_toys(double nSigma=std::numeric_limits< double >::quiet_NaN())
std::pair< double, double > pNull_asymp(double nSigma=std::numeric_limits< double >::quiet_NaN())
void addNullToys(int nToys=1, int seed=0, double target=std::numeric_limits< double >::quiet_NaN(), double target_nSigma=std::numeric_limits< double >::quiet_NaN())
std::pair< double, double > pCLs_asymp(double nSigma=std::numeric_limits< double >::quiet_NaN())
std::shared_ptr< RooArgSet > pars() const
Definition xRooNLLVar.h:306
bool AddModel(const xRooNode &pdf, const char *validity="")
std::map< std::shared_ptr< xRooNode >, std::shared_ptr< xRooNLLVar > > fNlls
Definition xRooNLLVar.h:372
int AddPoints(const char *parName, size_t nPoints, double low, double high)
std::set< std::pair< std::shared_ptr< RooArgList >, std::shared_ptr< xRooNode > > > fPdfs
Definition xRooNLLVar.h:374
This xRooNLLVar object has several special methods, e.g.
Definition xRooNLLVar.h:59
std::shared_ptr< RooAbsCollection > fFuncGlobs
Definition xRooNLLVar.h:473
void AddOption(const RooCmdArg &opt)
std::shared_ptr< const RooAbsCollection > fGlobs
Definition xRooNLLVar.h:466
std::shared_ptr< RooLinkedList > fOpts
Definition xRooNLLVar.h:468
std::shared_ptr< RooAbsReal > func() const
ROOT::Math::IOptions * fitConfigOptions()
RooConstraintSum * constraintTerm() const
std::shared_ptr< ROOT::Fit::FitConfig > fFitConfig
Definition xRooNLLVar.h:469
xRooHypoSpace hypoSpace(const char *parName, int nPoints, double low, double high, double alt_value=std::numeric_limits< double >::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType=xRooFit::Asymptotics::Unknown)
TObject * Scan(const RooArgList &scanPars, const std::vector< std::vector< double > > &coords, const RooArgList &profilePars=RooArgList())
std::shared_ptr< RooAbsCollection > fConstVars
Definition xRooNLLVar.h:472
xRooNLLVar(RooAbsPdf &pdf, const std::pair< RooAbsData *, const RooAbsCollection * > &data, const RooLinkedList &nllOpts=RooLinkedList())
std::shared_ptr< RooAbsPdf > pdf() const
Definition xRooNLLVar.h:429
const RooAbsCollection * globs() const
Definition xRooNLLVar.h:431
std::pair< std::shared_ptr< RooAbsData >, std::shared_ptr< const RooAbsCollection > > generate(bool expected=false, int seed=0)
std::pair< std::shared_ptr< RooAbsData >, std::shared_ptr< const RooAbsCollection > > getData() const
double getEntryVal(size_t entry) const
std::shared_ptr< RooAbsCollection > fFuncVars
Definition xRooNLLVar.h:471
double getEntryBinWidth(size_t entry) const
std::shared_ptr< ROOT::Fit::FitConfig > fitConfig()
std::shared_ptr< RooArgSet > pars(bool stripGlobalObs=true) const
std::shared_ptr< RooAbsData > fData
Definition xRooNLLVar.h:465
std::shared_ptr< RooAbsPdf > fPdf
Definition xRooNLLVar.h:464
bool setData(const std::pair< std::shared_ptr< RooAbsData >, std::shared_ptr< const RooAbsCollection > > &_data)
xRooHypoPoint hypoPoint(const char *parName, double value, double alt_value=std::numeric_limits< double >::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType=xRooFit::Asymptotics::Unknown)
xRooFitResult minimize(const std::shared_ptr< ROOT::Fit::FitConfig > &=nullptr)
The xRooNode class is designed to wrap over a TObject and provide functionality to aid with interacti...
Definition xRooNode.h:51
Generic interface for defining configuration options of a numerical algorithm.
Definition IOptions.h:28
void SetValue(const char *name, double val)
generic methods for retrieving options
Definition IOptions.h:42
virtual void SetNamedValue(const char *, const char *)
Definition IOptions.cxx:50
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:79
void Print(Option_t *options=nullptr) const override
Print the object to the defaultPrintStream().
Definition RooAbsArg.h:322
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
Abstract container object that can hold multiple RooAbsArg objects.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
RooAbsCollection * snapshot(bool deepCopy=true) const
Take a snap shot of current collection contents.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void setAttribAll(const Text_t *name, bool value=true)
Set given attribute in each element of the collection by calling each elements setAttribute() functio...
Int_t index(const RooAbsArg *arg) const
Returns index of given arg, or -1 if arg is not in the collection.
Storage_t::size_type size() const
RooAbsArg * first() const
bool setCatIndex(const char *name, Int_t newVal=0, bool verbose=false)
Set index value of a RooAbsCategoryLValue stored in set with given name to newVal.
bool setRealValue(const char *name, double newVal=0.0, bool verbose=false)
Set value of a RooAbsRealLValue stored in set with given name to newVal No error messages are printed...
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
bool selectCommon(const RooAbsCollection &refColl, RooAbsCollection &outColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
const char * getCatLabel(const char *name, const char *defVal="", bool verbose=false) const
Get state name of a RooAbsCategory stored in set with given name.
std::string contentsString() const
Return comma separated list of contained object names as STL string.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
virtual const RooArgSet * get() const
Definition RooAbsData.h:101
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
RooAbsRealLValue is the common abstract base class for objects that represent a real value that may a...
virtual void setVal(double value)=0
Set the current value of the object. Needs to be overridden by implementations.
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:103
virtual bool setData(RooAbsData &, bool=true)
Definition RooAbsReal.h:374
bool setData(RooAbsData &data, bool cloneData=true) override
Change dataset that is used to given one.
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:55
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
Int_t getInt(Int_t idx) const
Definition RooCmdArg.h:86
TObject * Clone(const char *newName=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooCmdArg.h:57
const char * getString(Int_t idx) const
Return string stored in slot idx.
Definition RooCmdArg.h:95
Calculates the sum of the -(log) likelihoods of a set of RooAbsPfs that represent constraint function...
RooDataSet is a container class to hold unbinned data.
Definition RooDataSet.h:57
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
RooLinkedList is an collection class for internal use, storing a collection of RooAbsArg pointers in ...
Int_t GetSize() const
TObject * At(int index) const
Return object stored in sequential position given by index.
static RooMsgService & instance()
Return reference to singleton instance.
StreamConfig & getStream(Int_t id)
Class RooNLLVar implements a -log(likelihood) calculation from a dataset and a PDF.
Definition RooNLLVar.h:25
Poisson pdf.
Definition RooPoisson.h:19
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
Definition RooRandom.cxx:51
RooRealVar represents a variable that can be changed from the outside.
Definition RooRealVar.h:37
void setVal(double value) override
Set value of variable to 'value'.
double getErrorLo() const
Definition RooRealVar.h:67
double getErrorHi() const
Definition RooRealVar.h:68
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
HypoTestResult is a base class for results from hypothesis tests.
This class simply holds a sampling distribution of some test statistic.
RooStringVar is a RooAbsArg implementing string values.
Draw all kinds of Arrows.
Definition TArrow.h:29
virtual TArrow * DrawArrow(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Float_t arrowsize=0, Option_t *option="")
Draw this arrow with new coordinates.
Definition TArrow.cxx:135
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:42
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition TAttLine.h:43
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition TAttMarker.h:38
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition TAttMarker.h:40
static TCanvas * MakeDefCanvas()
Static function to build a default canvas.
Definition TCanvas.cxx:1514
const char * AsString() const
Return the date & time as a string (ctime() format).
Definition TDatime.cxx:102
Describe directory structure in memory.
Definition TDirectory.h:45
virtual TKey * FindKeyAny(const char *) const
Definition TDirectory.h:198
Class to handle efficiency histograms.
Definition TEfficiency.h:29
void FillWeighted(Bool_t bPassed, Double_t weight, Double_t x, Double_t y=0, Double_t z=0)
This function is used for filling the two histograms with a weight.
Double_t GetEfficiencyErrorUp(Int_t bin) const
Returns the upper error on the efficiency in the given global bin.
void Fill(Bool_t bPassed, Double_t x, Double_t y=0, Double_t z=0)
This function is used for filling the two histograms.
Graphics object made of three arrays X, Y and Z with the same number of points each.
Definition TGraph2D.h:41
Int_t GetN() const
Definition TGraph2D.h:120
virtual void SetPoint(Int_t point, Double_t x, Double_t y, Double_t z)
Sets point number n.
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
Definition TGraph.cxx:2315
Int_t GetN() const
Definition TGraph.h:130
void SetName(const char *name="") override
Set graph name.
Definition TGraph.cxx:2354
void Draw(Option_t *chopt="") override
Draw this graph with its current attributes.
Definition TGraph.cxx:809
void SetTitle(const char *title="") override
Change (i.e.
Definition TGraph.cxx:2370
void SetNameTitle(const char *name="", const char *title="") override
Set graph name and title.
Definition TGraph.cxx:2390
1-D histogram with a double per channel (see TH1 documentation)}
Definition TH1.h:620
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:58
virtual Double_t GetMinimum(Double_t minval=-FLT_MAX) const
Return minimum value larger than minval of bins in the range, unless the value has been overridden by...
Definition TH1.cxx:8552
This class displays a legend box (TPaveText) containing several legend entries.
Definition TLegend.h:23
void Draw(Option_t *option="") override
Draw this legend with its current attributes.
Definition TLegend.cxx:422
Use the TLine constructor to create a simple line.
Definition TLine.h:22
virtual TLine * DrawLine(Double_t x1, Double_t y1, Double_t x2, Double_t y2)
Draw this line with new coordinates.
Definition TLine.cxx:103
A TMultiGraph is a collection of TGraph (or derived) objects.
Definition TMultiGraph.h:34
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:48
void Clear(Option_t *option="") override
Set name and title to empty strings ("").
Definition TNamed.cxx:64
Mother of all ROOT objects.
Definition TObject.h:41
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:439
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition TObject.cxx:223
virtual void Delete(Option_t *option="")
Delete this object.
Definition TObject.cxx:248
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:780
virtual void Draw(Option_t *option="")
Default Draw method for all objects.
Definition TObject.cxx:274
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
Definition TRandom.cxx:608
virtual UInt_t Integer(UInt_t imax)
Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
Definition TRandom.cxx:360
Regular expression class.
Definition TRegexp.h:31
Stopwatch class.
Definition TStopwatch.h:28
Double_t RealTime()
Stop the stopwatch (if it is running) and return the realtime (in seconds) passed between the start a...
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void Continue()
Resume a stopped stopwatch.
void Reset()
Definition TStopwatch.h:52
Provides iteration through tokens of a given string.
Definition TPRegexp.h:143
Bool_t NextToken()
Get the next token, it is stored in this TString.
Definition TPRegexp.cxx:975
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:421
void ToLower()
Change string to lower-case.
Definition TString.cxx:1170
Int_t Atoi() const
Return integer value of string.
Definition TString.cxx:1966
Double_t Atof() const
Return floating-point value contained in string.
Definition TString.cxx:2032
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
Definition TString.cxx:1836
const char * Data() const
Definition TString.h:380
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition TString.h:627
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2356
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:636
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:651
Float_t GetPadRightMargin() const
Definition TStyle.h:212
Float_t GetPadLeftMargin() const
Definition TStyle.h:211
Float_t GetPadBottomMargin() const
Definition TStyle.h:209
Float_t GetPadTopMargin() const
Definition TStyle.h:210
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition TSystem.cxx:403
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
TDatime GetTime() const
Get time from UUID.
Definition TUUID.cxx:670
TVirtualPad is an abstract base class for the Pad and Canvas classes.
Definition TVirtualPad.h:51
virtual TList * GetListOfPrimitives() const =0
virtual TObject * GetPrimitive(const char *name) const =0
RooCmdArg GlobalObservables(Args_t &&... argsOrArgSet)
RooCmdArg GlobalObservablesSource(const char *sourceName)
double gaussian_pdf(double x, double sigma=1, double x0=0)
Probability density function of the normal (Gaussian) distribution.
const Int_t n
Definition legend1.C:16
TGraphErrors * gr
Definition legend1.C:25
double gaussian_cdf(double x, double sigma=1, double x0=0)
Alternative name for same function.
@ NumIntegration
Double_t Prob(Double_t chi2, Int_t ndf)
Computation of the probability for a certain Chi-squared (chi2) and number of degrees of freedom (ndf...
Definition TMath.cxx:637
Double_t Poisson(Double_t x, Double_t par)
Computes the Poisson distribution function for (x,par).
Definition TMath.cxx:587
Double_t LnGamma(Double_t z)
Computation of ln[gamma(z)] for all z.
Definition TMath.cxx:509
Definition file.py:1
Definition first.py:1
#define END_XROOFIT_NAMESPACE
Definition Config.h:25
static const char * what
Definition stlLoader.cc:6
void removeTopic(RooFit::MsgTopic oldTopic)
th1 Draw()
TLine l
Definition textangle.C:4
std::string collectionContents(const RooAbsCollection &coll)
BEGIN_XROOFIT_NAMESPACE
#define GETWS(a)
#define GETWSSETS(w)