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