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