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