Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
xRooNode.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::xRooNode
14\ingroup xroofit
15
16The xRooNode class is designed to wrap over a TObject and provide functionality to aid with interacting with that
17object, particularly in the case where the object is a RooFit class instance. It is a smart pointer to the object, so
18you have access to all the methods of the object too.
19
20xRooNode is designed to work in both python and C++, but examples below are given in python because that is imagined
21 be the most common way to use the xRooFit API.
22
23-# [Exploring workspaces](\ref exploring-workspaces)
24
25\anchor exploring-workspaces
26## Exploring workspaces
27
28An existing workspace file (either a ROOT file containing a RooWorkspace, or a json HS3 file) can be opened using
29 xRooNode like this:
30
31\code{.py}
32from ROOT.Experimental import XRooFit
33w = XRooFit.xRooNode("workspace.root") # or can use workspace.json for HS3
34\endcode
35
36 You can explore the content of the workspace somewhat like you would a file system: each node contains sub-nodes,
37 which you can interact with to explore ever deeper. The most relevant methods for navigating the workspace and
38exploring the content are:
39
40
41
42
43 */
44
45#include "ROOT/RVersion.hxx"
46
47#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
48
49#define protected public
50#include "TRootBrowser.h"
52#define private public
53#include "RooAbsArg.h"
54#include "RooWorkspace.h"
57#include "RooProdPdf.h"
58#include "TGFileBrowser.h"
59#include "RooFitResult.h"
60#include "TPad.h"
61#undef private
62#include "RooAddPdf.h"
63#include "RooRealSumPdf.h"
64#include "RooProduct.h"
65#include "RooHistFunc.h"
66#include "RooConstVar.h"
67#include "RooSimultaneous.h"
68#undef protected
69
70#define GETWS(a) a->_myws
71#define GETWSSETS(w) w->_namedSets
72#define GETWSSNAPSHOTS(w) w->_snapshots
73#define GETACTBROWSER(b) b->fActBrowser
74#define GETROOTDIR(b) b->fRootDir
75#define GETLISTTREE(b) b->fListTree
76#define GETDMP(o, m) o->m
77
78#else
79
80#include "RooAbsArg.h"
81#include "RooWorkspace.h"
82#include "RooFitResult.h"
83#include "RooConstVar.h"
84#include "RooHistFunc.h"
85#include "RooRealSumPdf.h"
86#include "RooSimultaneous.h"
87#include "RooAddPdf.h"
88#include "RooProduct.h"
89#include "TPad.h"
93#include "RooProdPdf.h"
94#include "TRootBrowser.h"
95#include "TGFileBrowser.h"
96#include "TF1.h"
98
100{
101 return a->workspace();
102}
104{
105 return w->sets();
106}
108{
109 return w->getSnapshots();
110}
112{
113 return b->GetActBrowser();
114}
116{
117 return b->GetRootDir();
118}
120{
121 return b->GetListTree();
122}
123#define GETDMP(o, m) \
124 *reinterpret_cast<void **>(reinterpret_cast<unsigned char *>(o) + o->Class()->GetDataMemberOffset(#m))
125
126#endif
127
128#include "RooAddition.h"
129
130#include "RooCategory.h"
131#include "RooRealVar.h"
132#include "RooStringVar.h"
133#include "RooBinning.h"
134#include "RooUniformBinning.h"
135
136#include "RooAbsData.h"
137#include "RooDataHist.h"
138#include "RooDataSet.h"
139
140#include "xRooFit/xRooNode.h"
141#include "xRooFit/xRooFit.h"
142
143#include "TH1.h"
144#include "TBrowser.h"
145#include "TROOT.h"
146#include "TQObject.h"
147#include "TAxis.h"
148#include "TGraphAsymmErrors.h"
149#include "TMath.h"
150#include "TPRegexp.h"
151#include "TRegexp.h"
152#include "TExec.h"
153#include "TPaveText.h"
154#include "TLatex.h"
155
156#include "TGListTree.h"
157#include "TGMsgBox.h"
158#include "TGedEditor.h"
159#include "TGMimeTypes.h"
160#include "TH2.h"
161#include "RooExtendPdf.h"
162#include "RooExtendedBinding.h"
163
165
166#include "coutCapture.h"
167
168// #include "RooFitTrees/RooFitResultTree.h"
169// #include "RooFitTrees/RooDataTree.h"
170#include "TFile.h"
171#include "TSystem.h"
172#include "TKey.h"
173#include "TEnv.h"
174#include "TStyle.h"
175
176#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
178#endif
179
180#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00)
181#include "RooBinSamplingPdf.h"
182#endif
183
184#if ROOT_VERSION_CODE > ROOT_VERSION(6, 37, 00)
185#include "RooMultiReal.h"
186#include "RooMultiPdf.h"
187#endif
188
189#include "RooPoisson.h"
190#include "RooGaussian.h"
191#include "RooFormulaVar.h"
192#include "RooGenericPdf.h"
193#include "TVectorD.h"
194#include "TStopwatch.h"
195#include "TTimeStamp.h"
196
197#include <csignal>
198
199#include "TCanvas.h"
200#include "THStack.h"
201
202#include "TLegend.h"
203#include "TLegendEntry.h"
204#include "TGraphErrors.h"
205#include "TMultiGraph.h"
206#include "TFrame.h"
207#include "RooProjectedPdf.h"
208#include "TMemFile.h"
209#include "TGaxis.h"
210#include "TPie.h"
211// #include <thread>
212// #include <future>
213
214#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
215#include "RooNaNPacker.h"
216#endif
217
219
220xRooNode::InteractiveObject *xRooNode::gIntObj = nullptr;
221std::map<std::string, std::tuple<std::function<double(double, double, double)>, bool>> xRooNode::auxFunctions;
222void xRooNode::SetAuxFunction(const char *title, const std::function<double(double, double, double)> &func,
223 bool symmetrize)
224{
225 auxFunctions[title] = std::make_tuple(func, symmetrize);
226}
227
228template <typename T>
229const T &_or_func(const T &a, const T &b)
230{
231 if (a)
232 return a;
233 return b;
234}
235
236////////////////////////////////////////////////////////////////////////////////
237/// Create new object of type classname, with given name and title, and own-wrap it
238/// i.e. the xRooNode will delete the object when the node (and any that reference it) is destroyed
239///
240/// \param classname : the type of the object to create
241/// \param name : the name to give the object
242/// \param title : the title to give the object
243
244xRooNode::xRooNode(const char *classname, const char *name, const char *title)
245 : xRooNode(name, std::shared_ptr<TObject>(TClass::GetClass(classname)
246 ? reinterpret_cast<TObject *>(TClass::GetClass(classname)->New())
247 : nullptr,
248 [](TObject *o) {
249 if (auto w = dynamic_cast<RooWorkspace *>(o); w) {
250#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
251 w->_embeddedDataList.Delete();
252#endif
253 xRooNode(*w, std::make_shared<xRooNode>()).sterilize();
254 }
255 if (o)
256 delete o;
257 }))
258{
259 if (auto a = get<TNamed>(); a)
260 a->SetName(name);
261 SetTitle(title);
262}
263
264xRooNode::xRooNode(const char *name, const std::shared_ptr<TObject> &comp, const std::shared_ptr<xRooNode> &parent)
265 : TNamed(name, ""), fComp(comp), fParent(parent)
266{
267
268 if (!fComp && !fParent && name && strlen(name) > 0) {
269 char *_path = gSystem->ExpandPathName(name);
270 TString pathName = TString(_path);
271 delete[] _path;
272 if (!gSystem->AccessPathName(pathName)) {
273 // if file is json can try to read
274 if (pathName.EndsWith(".json")) {
275#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
276 fComp = std::make_shared<RooWorkspace>("workspace", name);
277 RooJSONFactoryWSTool tool(*get<RooWorkspace>());
280 if (!tool.importJSON(pathName.Data())) {
281 Error("xRooNode", "Error reading json workspace %s", name);
282 fComp.reset();
283 }
285#else
286 Error("xRooNode", "json format workspaces available only in ROOT 6.26 onwards");
287#endif
288 } else {
289
290 // using acquire in the constructor seems to cause a mem leak according to valgrind ... possibly because
291 // (*this) gets called on it before the node is fully constructed
292 auto _file = std::make_shared<TFile>(
293 pathName); // acquire<TFile>(name); // acquire file to ensure stays open while we have the workspace
294 // actually it appears we don't need to keep the file open once we've loaded the workspace, but should be
295 // no harm doing so
296 // otherwise the workspace doesn't saveas
297 auto keys = _file->GetListOfKeys();
298 if (keys) {
299 for (auto &&k : *keys) {
300 auto cl = TClass::GetClass((static_cast<TKey *>(k))->GetClassName());
301 if (cl == RooWorkspace::Class() || cl->InheritsFrom("RooWorkspace")) {
302 fComp.reset(_file->Get<RooWorkspace>(k->GetName()), [](TObject *ws) {
303 // memory leak in workspace, some RooLinkedLists aren't cleared, fixed in ROOT 6.28
304 if (ws) {
305#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
306 dynamic_cast<RooWorkspace *>(ws)->_embeddedDataList.Delete();
307#endif
308 xRooNode(*ws, std::make_shared<xRooNode>()).sterilize();
309 delete ws;
310 }
311 });
312 if (fComp) {
313 TNamed::SetNameTitle(fComp->GetName(), fComp->GetTitle());
314 fParent = std::make_shared<xRooNode>(
315 _file); // keep file alive - seems necessary to save workspace again in some cases
316 break;
317 }
318 }
319 }
320 }
321 }
322 } else if (pathName.EndsWith(".root") || pathName.EndsWith(".json")) {
323 throw std::runtime_error(TString::Format("%s does not exist", name));
324 }
325 }
326
327 if (auto _ws = get<RooWorkspace>(); _ws && (!parent || parent->get<TFile>())) {
331#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 37, 00)
333#else
335#endif
336 ); // stop info message every time
337
338 // check if any of the open files have version numbers greater than our major version
339 // may not read correctly
340 for (auto f : *gROOT->GetListOfFiles()) {
341 if ((dynamic_cast<TFile *>(f)->GetVersion() / 100) > (gROOT->GetVersionInt() / 100)) {
342 Warning("xRooNode", "There is file open with version %d > current version %d ... results may be wrong",
343 dynamic_cast<TFile *>(f)->GetVersion(), gROOT->GetVersionInt());
344 }
345 }
346
347 // load list of colors if there is one
348 if (auto colors = dynamic_cast<TSeqCollection *>(_ws->obj(gROOT->GetListOfColors()->GetName()))) {
350 // gROOT->GetListOfColors()->Clear(); - was getting warnings about colors already defined when overwriting
351 // existing list
352 for (auto col : *colors) {
353 if (!gROOT->GetListOfColors()->FindObject(col->GetName())) {
354 gROOT->GetListOfColors()->Add(gROOT->GetListOfColors()->IsOwner() ? col->Clone() : col);
355 }
356
357 // gROOT->GetListOfColors()->Add(gROOT->GetListOfColors()->IsOwner() ? col->Clone() : col); // in 6.36 root,
358 // colors list became owning
359 }
360 }
361
362 // use the datasets if any to 'mark' observables
363 int checkCount = 0;
364 for (auto &d : _ws->allData()) {
365 for (auto &a : *d->get()) {
366 if (auto v = _ws->var(a->GetName()); v) {
367 v->setAttribute("obs");
368 } else if (auto c = _ws->cat(a->GetName()); c) {
369 c->setAttribute("obs");
370 }
371 }
372 // count how many ds are checked ... if none are checked will check the first
373 checkCount += d->TestBit(1 << 20);
374 }
375
376 if (checkCount == 0 && !_ws->allData().empty())
377 _ws->allData().back()->SetBit(1 << 20, true);
378
379 if (auto _set = dynamic_cast<RooArgSet *>(GETWSSNAPSHOTS(_ws).find("NominalParamValues")); _set) {
380 for (auto s : *_set) {
381 if (auto v = dynamic_cast<RooRealVar *>(s); v) {
382 _ws->var(s->GetName())->setStringAttribute("nominal", TString::Format("%f", v->getVal()));
383 }
384 }
385 }
386
387 // also flag global observables ... relies on ModelConfig existences
388 RooArgSet _allGlobs;
389 for (auto &[k, v] : GETWSSETS(_ws)) {
390 if (k == "globalObservables" || TString(k).EndsWith("_GlobalObservables")) {
391 for (auto &s : v) {
392 _allGlobs.add(*s);
393 s->setAttribute("obs");
394 s->setAttribute("global");
395 }
396 } else if (TString(k).EndsWith("_Observables")) {
397 const_cast<RooArgSet &>(v).setAttribAll("obs");
398 } else if (TString(k).EndsWith("_POI")) {
399 for (auto &s : v) {
400 s->setAttribute("poi");
401 auto _v = dynamic_cast<RooRealVar *>(s);
402 if (!_v)
403 continue;
404 // if (!_v->hasRange("physical")) {
405 // _v->setRange("physical", 0, std::numeric_limits<double>::infinity());
406 // // ensure range of poi is also straddling 0
407 // if (_v->getMin() >= 0)
408 // _v->setMin(-1e-5);
409 // }
410 }
411 } else if (TString(k).EndsWith("_NuisParams")) {
412 const_cast<RooArgSet &>(v).setAttribAll("np");
413 }
414 }
415 if (!_allGlobs.empty() && GETWSSETS(_ws).count("globalObservables") == 0) {
416 _ws->defineSet("globalObservables", _allGlobs);
417 }
418
419 // now check if any pars don't have errors defined (not same as error=0) ... if so, use the first pdf (if there is
420 // one) to try setting values from
421 if (!_ws->allPdfs().empty()) {
422 std::set<RooRealVar *> noErrorPars;
423 std::string parNames;
424 for (auto &p : np()) { // infer errors on all floating non-poi parameters
425 auto v = p->get<RooRealVar>();
426 if (!v)
427 continue;
428 if (!v->hasError()) {
429 noErrorPars.insert(v);
430 if (!parNames.empty())
431 parNames += ",";
432 parNames += v->GetName();
433 }
434 }
435 if (!noErrorPars.empty()) {
436 Warning("xRooNode",
437 "Inferring initial errors of %d parameters (%s%s) (give all nuisance parameters an error to avoid "
438 "this msg)",
439 int(noErrorPars.size()), (*noErrorPars.begin())->GetName(), (noErrorPars.size() > 1) ? ",..." : "");
440 if (gEnv->GetValue("XRooFit.SkipInitParErrorInference", false)) {
441 Warning("xRooNode", "Skipping because XRooFit.SkipInitParErrorInference=true. This is expert-only, you "
442 "should fix your workspaces!");
443 } else {
444 // get the first top-level pdf
445 browse();
446 for (auto &a : *this) {
447 if (noErrorPars.empty()) {
448 break;
449 }
450 if (a->fFolder == "!pdfs") {
451 try {
452 auto fr = a->floats().reduced(parNames).fitResult("prefit");
453 if (auto _fr = fr.get<RooFitResult>(); _fr) {
454 std::set<RooRealVar *> foundPars;
455 for (auto &v : noErrorPars) {
456 if (auto arg = dynamic_cast<RooRealVar *>(_fr->floatParsFinal().find(v->GetName()));
457 arg && arg->hasError()) {
458 v->setError(arg->getError());
459 foundPars.insert(v);
460 }
461 }
462 for (auto &v : foundPars) {
463 noErrorPars.erase(v);
464 }
465 }
466 } catch (...) {
467 }
468 }
469 }
470 }
471 }
472 }
473 }
474
475 if (strlen(GetTitle()) == 0) {
476 if (fComp) {
477 TNamed::SetTitle(fComp->GetTitle());
478 } else {
480 }
481 }
482}
483
484xRooNode::xRooNode(const TObject &comp, const std::shared_ptr<xRooNode> &parent)
485 : xRooNode(/*[](const TObject& c) {
486c.InheritsFrom("RooAbsArg");
487if (s) {
488return (s->getStringAttribute("alias")) ? s->getStringAttribute("alias") : c.GetName();
489}
490return c.GetName();
491}(comp)*/
492 (comp.InheritsFrom("RooAbsArg") && dynamic_cast<const RooAbsArg *>(&comp)->getStringAttribute("alias"))
493 ? dynamic_cast<const RooAbsArg *>(&comp)->getStringAttribute("alias")
494 : comp.GetName(),
495 std::shared_ptr<TObject>(const_cast<TObject *>(&comp), [](TObject *) {}), parent)
496{
497}
498
499xRooNode::xRooNode(const std::shared_ptr<TObject> &comp, const std::shared_ptr<xRooNode> &parent)
500 : xRooNode(
501 [&]() {
502 if (auto a = std::dynamic_pointer_cast<RooAbsArg>(comp); a && a->getStringAttribute("alias"))
503 return a->getStringAttribute("alias");
504 if (comp)
505 return comp->GetName();
506 return "";
507 }(),
508 comp, parent)
509{
510}
511
513
514void xRooNode::_SetAttribute_(const char *name, const char *value)
515{
516 TString v(value);
517 v.ToUpper();
518 bool isBool = (v == "TRUE" || v == "FALSE");
519 if (auto a = get<RooAbsArg>(); a) {
520 if (value == nullptr || v == "NULLPTR") {
521 if (a->getAttribute(name))
522 a->setAttribute(name, false);
523 else if (a->getStringAttribute(name))
524 a->setStringAttribute(name, nullptr);
525 } else {
526 if (isBool)
527 a->setAttribute(name, (v == "TRUE"));
528 else
529 a->setStringAttribute(name, value);
530 }
531 } else {
532 RooArgList l = argList();
533 for (auto a2 : l) {
534 xRooNode(*a2)._SetAttribute_(name, value);
535 }
536 }
537 // should update this node's state in any browsers ...
538 for (auto a : *gROOT->GetListOfBrowsers()) {
539 TBrowser *b = dynamic_cast<TBrowser *>(a);
540 if (b && GetTreeItem(b)) {
541 if (auto bi = dynamic_cast<TRootBrowser *>(b->GetBrowserImp())) {
542 if (auto fb = dynamic_cast<TGFileBrowser *>(bi->GetActBrowser())) {
543 fb->DoubleClicked(GetTreeItem(b), 0);
544 }
545 }
546 }
547 }
548}
549
550void xRooNode::Checked(TObject *obj, bool val)
551{
552 if (obj != this)
553 return;
554
555 // cycle through states:
556 // unhidden and selected: tick, no uline
557 // hidden and unselected: notick, uline
558 // unhidden and unselected: tick, uline
559 if (auto o = get<RooAbsReal>(); o) {
560 if (o->isSelectedComp() && !val) {
561 // deselecting and hiding
562 o->selectComp(val);
563 o->setAttribute("hidden");
564 } else if (!o->isSelectedComp() && !val) {
565 // selecting
566 o->selectComp(!val);
567 } else if (val) {
568 // unhiding but keeping unselected
569 o->setAttribute("hidden", false);
570 }
571 auto item = GetTreeItem(nullptr);
572 item->CheckItem(!o->getAttribute("hidden"));
573 if (o->isSelectedComp()) {
574 item->ClearColor();
575 } else {
576 item->SetColor(kGray);
577 }
578 return;
579 }
580
581 if (auto o = get(); o) {
582 // if (o->TestBit(1<<20)==val) return; // do nothing
583 o->SetBit(1 << 20, val); // TODO: check is 20th bit ok to play with?
584 if (auto fr = get<RooFitResult>(); fr) {
585 if (auto _ws = ws(); _ws) {
586 if (val) {
587 // ensure fit result is in genericObjects list or snapshots ... if not, add a copy ...
588 if (fr->numStatusHistory() && !_ws->genobj(fr->GetName())) {
589 _ws->import(*fr);
590 if (auto wfr = dynamic_cast<RooFitResult *>(_ws->genobj(fr->GetName()))) {
591 fr = wfr;
592 }
593 }
594 RooArgSet _allVars = _ws->allVars();
595 _allVars = fr->floatParsFinal();
596 _allVars = fr->constPars();
597 for (auto &i : fr->floatParsInit()) {
598 auto v = dynamic_cast<RooRealVar *>(_allVars.find(i->GetName()));
599 if (v)
600 v->setStringAttribute("initVal", TString::Format("%f", dynamic_cast<RooRealVar *>(i)->getVal()));
601 }
602 // uncheck all other fit results
603 for (auto oo : _ws->allGenericObjects()) {
604 if (auto ffr = dynamic_cast<RooFitResult *>(oo); ffr && ffr != fr) {
605 ffr->ResetBit(1 << 20);
606 }
607 }
608 } else
609 _ws->allVars() = fr->floatParsInit();
610 }
611
612 TBrowser *b = nullptr;
613 for (auto a : *gROOT->GetListOfBrowsers()) {
614 b = dynamic_cast<TBrowser *>(a);
615 if (b && GetTreeItem(b)) {
616 break;
617 }
618 }
619 if (b) {
620 auto p = GetTreeItem(b);
621
622 if (p) {
623 // update check marks on siblings
624 if (auto first = p->GetParent()->GetFirstChild()) {
625 do {
626 if (first->HasCheckBox()) {
627 auto _obj = static_cast<xRooNode *>(first->GetUserData());
628 first->CheckItem(_obj->get() && _obj->get()->TestBit(1 << 20));
629 }
630 } while ((first = first->GetNextSibling()));
631 }
632 }
633
634 // also since const status of pars could have changed, refresh all 'poi' and 'np' open nodes
635 if (auto bi = dynamic_cast<TRootBrowser *>(b->GetBrowserImp())) {
636 if (auto fb = dynamic_cast<TGFileBrowser *>(bi->GetActBrowser())) {
637 while (p) {
638 if (TString(p->GetText()).BeginsWith("RooWorkspace::")) {
639 std::function<void(TGListTreeItem *)> rfunc;
640
641 rfunc = [&](TGListTreeItem *i) {
642 if (auto first = i->GetFirstChild()) {
643 do {
644 if (first->IsOpen() &&
645 (TString(first->GetText()) == "poi" || TString(first->GetText()) == "np")) {
646 fb->DoubleClicked(first, 0);
647 } else
648 rfunc(first);
649 } while ((first = first->GetNextSibling()));
650 }
651 };
652 rfunc(p);
653 break;
654 } else {
655 p = p->GetParent();
656 }
657 }
658 }
659 }
660 }
661 }
662 }
663}
664
666{
667 static bool blockBrowse = false;
668 if (blockBrowse)
669 return;
670 if (b == nullptr) {
671 auto b2 = dynamic_cast<TBrowser *>(gROOT->GetListOfBrowsers()->Last());
672 if (!b2 || !b2->GetBrowserImp()) { // no browser imp if browser was closed
673 blockBrowse = true;
674 gEnv->SetValue("X11.UseXft", "no"); // for faster x11
675 gEnv->SetValue("X11.Sync", "no");
676 gEnv->SetValue("X11.FindBestVisual", "no");
677 gEnv->SetValue("Browser.Name", "TRootBrowser"); // forces classic root browser (in 6.26 onwards)
678 gEnv->SetValue("Canvas.Name", "TRootCanvas");
679 b2 = new TBrowser("nodeBrowser", this, "RooFit Browser");
680 blockBrowse = false;
681 } else if (strcmp(b2->GetName(), "nodeBrowser") == 0) {
682 blockBrowse = true;
683 b2->BrowseObject(this);
684 blockBrowse = false;
685 } else {
686 auto _b = dynamic_cast<TGFileBrowser *>(GETACTBROWSER(dynamic_cast<TRootBrowser *>(b2->GetBrowserImp())));
687 if (_b) {
688 _b->AddFSDirectory("Workspaces", nullptr, "SetRootDir");
689 _b->GotoDir(nullptr);
690 _b->Add(this, GetName());
691 }
692 }
693 return;
694 }
695
696 if (auto item = GetTreeItem(b); item) {
697 if (!item->IsOpen() && IsFolder())
698 return; // no need to rebrowse if closing
699 // update check marks on any child items
700 if (auto first = item->GetFirstChild()) {
701 do {
702 if (first->HasCheckBox()) {
703 auto _obj = static_cast<xRooNode *>(first->GetUserData());
704 first->CheckItem(_obj->get() &&
705 (_obj->get()->TestBit(1 << 20) ||
706 (_obj->get<RooAbsArg>() && !_obj->get<RooAbsArg>()->getAttribute("hidden"))));
707 }
708 } while ((first = first->GetNextSibling()));
709 }
710 }
711
712 browse();
713
714 // for top-level pdfs default to having the .vars browsable too
715 if (get<RooAbsPdf>() && fFolder == "!pdfs" && !_IsShowVars_()) {
716 fBrowsables.push_back(std::make_shared<xRooNode>(vars()));
717 }
718
719 if (auto _fr = get<RooFitResult>(); _fr && fBrowsables.empty()) {
720 // have some common drawing options
721 fBrowsables.push_back(std::make_shared<xRooNode>(".Draw(\"pull\")", nullptr, *this));
722 fBrowsables.push_back(std::make_shared<xRooNode>(".Draw(\"corr10colztext\")", nullptr, *this));
723 if (std::unique_ptr<RooAbsCollection>(_fr->floatParsFinal().selectByAttrib("poi", true))->size() == 1) {
724 fBrowsables.push_back(std::make_shared<xRooNode>(".Draw(\"impact\")", nullptr, *this));
725 }
726 }
727
728 if (empty() && fBrowsables.empty()) {
729 try {
730 if (auto s = get<TStyle>()) {
731 s->SetFillAttributes();
732 if (auto ed = dynamic_cast<TGedEditor *>(TVirtualPadEditor::GetPadEditor())) {
733 ed->SetModel(gPad, s, kButton1Down, true);
734 }
735 } else if (TString(GetName()).BeginsWith(".Draw(\"") && fParent) {
736 fParent->Draw(TString(TString(GetName())(7, strlen(GetName()) - 9)) + b->GetDrawOption());
737 } else {
738 Draw(b->GetDrawOption());
739 }
740 } catch (const std::exception &e) {
741 new TGMsgBox(
742 gClient->GetRoot(),
743 (gROOT->GetListOfBrowsers()->At(0))
744 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
745 : gClient->GetRoot(),
746 "Exception", e.what(),
747 kMBIconExclamation); // deletes self on dismiss?
748 }
749 }
750
751 bool hasFolders = false;
752 if (strlen(GetName()) > 0 && GetName()[0] != '!') { // folders don't have folders
753 for (auto &c : *this) {
754 if (!c->fFolder.empty()) {
755 hasFolders = true;
756 break;
757 }
758 }
759 }
760 // auto _ws = get<RooWorkspace>();
761 if (/*_ws*/ hasFolders) {
762 // organize in folders
763 auto _folders = find(".folders");
764 if (!_folders) {
765 _folders = emplace_back(std::make_shared<xRooNode>(".folders", nullptr, *this));
766 }
767 // ensure entry in folders for every folder type ...
768 for (auto &v : *this) {
769 if (!v->fFolder.empty() && !_folders->find(v->fFolder, false)) {
770 _folders->emplace_back(std::make_shared<xRooNode>(v->fFolder.c_str(), nullptr, *this));
771 }
772 }
773 // now just add all the folders
774 for (auto &v : *_folders) {
775 TString _name = v->GetName();
776 if (_name.BeginsWith('!'))
777 _name = _name(1, _name.Length()); // strip ! from display
778 b->Add(v.get(), _name);
779 }
780 }
781
782 for (auto &v : *this) {
783 if (hasFolders && !v->fFolder.empty())
784 continue; // in the folders
785 if (strcmp(v->GetName(), ".folders") == 0)
786 continue; // never 'browse' the folders property
787 auto _fr = v->get<RooFitResult>();
788 int _checked = (v->get<RooAbsData>() || _fr) ? v->get()->TestBit(1 << 20) : -1;
789 if (_fr && ((_fr->status() == 0 && _fr->numStatusHistory() == 0) || (_fr->floatParsFinal().empty()))) {
790 // this is a "PARTIAL" fit result ... don't allow it to be selected
791 _checked = -1;
792 }
793 if (v->get<RooAbsPdf>() && get<RooSimultaneous>())
794 _checked = !v->get<RooAbsArg>()->getAttribute("hidden");
795 TString _name = v->GetName();
796 if (v->get() && _name.BeginsWith(TString(v->get()->ClassName()) + "::")) {
797 _name = _name(strlen(v->get()->ClassName()) + 2, _name.Length());
798 }
799 if (_name.BeginsWith(".")) {
800 // property node -- display the name of the contained object
801 if (v->get()) {
802 _name = TString::Format("%s: %s::%s", _name.Data(), v->get()->ClassName(),
803 (v->get<RooAbsArg>() && v->get<RooAbsArg>()->getStringAttribute("alias"))
804 ? v->get<RooAbsArg>()->getStringAttribute("alias")
805 : v->get()->GetName());
806 }
807 } else if (v->get() && !v->get<TFile>() && !TString(v->GetName()).BeginsWith('/'))
808 _name = TString::Format("%s::%s", v->get()->ClassName(), _name.Data());
809 if (auto _type = v->GetNodeType(); strlen(_type)) {
810 // decided not to show const values until figure out how to update if value changes
811 /*if (TString(_type)=="Const") _name += TString::Format(" [%s=%g]",_type,v->get<RooConstVar>()->getVal());
812 else*/
813 _name += TString::Format(" [%s]", _type);
814 }
815 if (auto fv = v->get<RooFormulaVar>()) {
816 TString formu = TString::Format(" [%s]", fv->expression());
817 for (size_t i = 0; i < fv->dependents().size(); i++) {
818 formu.ReplaceAll(TString::Format("x[%zu]", i), fv->dependents()[i].GetName());
819 }
820 _name += formu;
821 } else if (auto gv = v->get<RooGenericPdf>()) {
822 TString formu = TString::Format(" [%s]", gv->expression());
823 for (size_t i = 0; i < gv->dependents().size(); i++) {
824 formu.ReplaceAll(TString::Format("x[%zu]", i), gv->dependents()[i].GetName());
825 }
826 _name += formu;
827 } else if (auto pi = v->get<PiecewiseInterpolation>()) {
828 // check if all interpCodes are the same.
829 std::set<int> interpCodes;
830 for (auto &c : pi->interpolationCodes())
831 interpCodes.insert(c);
832 if (interpCodes.size() == 1) {
833 _name += TString::Format(" [InterpCode=%d]", *interpCodes.begin());
834 }
835 } else if (auto fiv = v->get<RooStats::HistFactory::FlexibleInterpVar>()) {
836 // check if all interpCodes are the same.
837 std::set<int> interpCodes;
838 for (auto &c : fiv->interpolationCodes())
839 interpCodes.insert(c == 4 ? 5 : c); // in definition of FlexibleInterpVar 4 gets replaced with 5
840 if (interpCodes.size() == 1) {
841 _name += TString::Format(" [InterpCode=%d]", *interpCodes.begin());
842 }
843 }
844 // tool tip defaults to displaying name and title, so temporarily set name to obj name if has one
845 // and set title to the object type
846 TString nameSave(v->TNamed::GetName());
847 TString titleSave(v->TNamed::GetTitle());
848 if (auto o = v->get(); o)
849 v->TNamed::SetNameTitle(o->GetName(), o->ClassName());
850 b->Add(v.get(), _name, _checked);
851 if (auto o = v->get(); o)
852 v->TNamed::SetNameTitle(nameSave, titleSave);
853 if (_checked != -1) {
854 dynamic_cast<TQObject *>(b->GetBrowserImp())
855 ->Connect("Checked(TObject *, bool)", ClassName(), v.get(), "Checked(TObject *, bool)");
856 }
857 if (_fr) {
858 if (_fr->status() || _fr->covQual() != 3) { // snapshots or bad fits
859 v->GetTreeItem(b)->SetColor((_fr->numStatusHistory() && !_fr->floatParsFinal().empty()) ? kRed : kBlue);
860 } else if (_fr->numStatusHistory() == 0) { // partial fit result ..
861 v->GetTreeItem(b)->SetColor(kGray);
862 }
863 }
864 if ((v->fFolder == "!np" || v->fFolder == "!poi")) {
865 if (v->get<RooAbsArg>()->getAttribute("Constant")) {
866 v->GetTreeItem(b)->SetColor(kGray);
867 } else
868 v->GetTreeItem(b)->ClearColor();
869 }
870 if (auto _htr = v->get<RooStats::HypoTestResult>(); _htr) {
871 // check for fit statuses
872 if (auto fits = _htr->GetFitInfo()) {
873 for (int i = 0; i < fits->numEntries(); i++) {
874 // if any fit (other than a genFit) is bad, flag point as bad
875 if (fits->get(i)->getCatIndex("type") != 5 && fits->get(i)->getRealValue("status") != 0) {
876 v->GetTreeItem(b)->SetColor(kRed);
877 break;
878 }
879 }
880 } else {
881 v->GetTreeItem(b)->SetColor(kBlue); // unknown fit status
882 }
883 }
884
885 // v.fBrowsers.insert(b);
886 }
887
888 // for pdfs, check for datasets too and add to list
889 /*if (get<RooAbsPdf>()) {
890 auto dsets = datasets();
891 if (!dsets.empty()) {
892 // check if already have .datasets() in browsables
893 bool found(false);
894 for(auto& p : fBrowsables) {
895 if (TString(p->GetName())==".datasets()") {found=true;
896 // add
897 break;
898 }
899 }
900 if (!found) {
901 fBrowsables.push_back(std::make_shared<xRooNode>(dsets));
902 }
903 }
904 }*/
905 // browse the browsables too
906 for (auto &v : fBrowsables) {
907 TString _name = v->GetName();
908 if (_name == ".memory")
909 continue; // hide the memory from browsing, if put in browsables
910 TString nameSave(v->TNamed::GetName());
911 TString titleSave(v->TNamed::GetTitle());
912 if (auto o = v->get(); o)
913 v->TNamed::SetNameTitle(o->GetName(), o->ClassName());
914 b->Add(v.get(), _name, -1);
915 if (auto o = v->get(); o)
916 v->TNamed::SetNameTitle(nameSave, titleSave);
917 }
918
919 b->SetSelected(this);
920}
921
923{
924 if (!set) {
925 // can't remove as causes a crash, need to remove from the browser first
926 /*for(auto itr = fBrowsables.begin(); itr != fBrowsables.end(); ++itr) {
927 if (strcmp((*itr)->GetName(),".vars")==0) {
928 fBrowsables.erase(itr);
929 }
930 }*/
931 } else {
932 auto v = std::make_shared<xRooNode>(vars());
933 fBrowsables.push_back(v);
934 if (auto l = GetListTree(nullptr)) {
935 l->AddItem(GetTreeItem(nullptr), v->GetName(), v.get());
936 }
937 }
938}
939
941{
942 for (auto &b : fBrowsables) {
943 if (strcmp(b->GetName(), ".vars") == 0)
944 return true;
945 }
946 return false;
947}
948
950{
951 if (strlen(GetName()) > 0 && GetName()[0] == '!')
952 return true;
953 if (strlen(GetName()) > 0 && GetName()[0] == '.' && !(TString(GetName()).BeginsWith(".Draw(\"")))
954 return true;
955 if (empty())
956 const_cast<xRooNode *>(this)->browse();
957 return !empty();
958}
959
960class Axis2 : public TAxis {
961
962public:
963 using TAxis::TAxis;
964 double GetBinWidth(Int_t bin) const override
965 {
966 if (auto v = var(); v)
967 return v->getBinWidth(bin - 1, GetName());
968 return 1;
969 }
970 double GetBinLowEdge(Int_t bin) const override
971 {
972 if (auto v = rvar(); v) {
973 return (bin == v->getBinning(GetName()).numBins() + 1) ? v->getBinning(GetName()).binHigh(bin - 2)
974 : v->getBinning(GetName()).binLow(bin - 1);
975 }
976 return bin - 1;
977 }
978 double GetBinUpEdge(Int_t bin) const override
979 {
980 if (auto v = rvar(); v)
981 return (bin == 0) ? v->getBinning(GetName()).binLow(bin) : v->getBinning(GetName()).binHigh(bin - 1);
982 return bin;
983 }
984
985 const char *GetTitle() const override
986 {
987 return (binning() && strlen(binning()->GetTitle())) ? binning()->GetTitle() : GetParent()->GetTitle();
988 }
989 void SetTitle(const char *title) override
990 {
991 if (binning()) {
992 const_cast<RooAbsBinning *>(binning())->SetTitle(title);
993 } else {
994 dynamic_cast<TNamed *>(GetParent())->SetTitle(title);
995 }
996 }
997
998 void Set(Int_t nbins, const double *xbins) override
999 {
1000 if (auto v = dynamic_cast<RooRealVar *>(rvar()))
1001 v->setBinning(RooBinning(nbins, xbins), GetName());
1002 TAxis::Set(nbins, xbins);
1003 }
1004 void Set(Int_t nbins, const float *xbins) override
1005 {
1006 std::vector<double> bins(nbins + 1);
1007 for (int i = 0; i <= nbins; i++)
1008 bins.at(i) = xbins[i];
1009 return Set(nbins, &bins[0]);
1010 }
1011 void Set(Int_t nbins, double xmin, double xmax) override
1012 {
1013 if (auto v = dynamic_cast<RooRealVar *>(rvar()))
1014 v->setBinning(RooUniformBinning(xmin, xmax, nbins), GetName());
1015 TAxis::Set(nbins, xmin, xmax);
1016 }
1017
1018 const RooAbsBinning *binning() const { return var()->getBinningPtr(GetName()); }
1019
1020 Int_t FindFixBin(const char *label) const override { return TAxis::FindFixBin(label); }
1021 Int_t FindFixBin(double x) const override { return (binning()) ? (binning()->binNumber(x) + 1) : x; }
1022
1023private:
1024 RooAbsLValue *var() const { return dynamic_cast<RooAbsLValue *>(GetParent()); }
1025 RooAbsRealLValue *rvar() const { return dynamic_cast<RooAbsRealLValue *>(GetParent()); }
1026};
1027
1028std::shared_ptr<TObject> xRooNode::getObject(const std::string &name, const std::string &type) const
1029{
1030 // if (fParent) return fParent->getObject(name);
1031
1032 if (auto _owned = find(".memory"); _owned) {
1033 for (auto &o : *_owned) {
1034 if (name == o->GetName()) {
1035 if (type.empty() || o->get()->InheritsFrom(type.c_str()))
1036 return o->fComp;
1037 }
1038 }
1039 }
1040
1041 // see if have a provider
1042 auto _provider = fProvider;
1043 auto _parent = fParent;
1044 while (!_provider && _parent) {
1045 _provider = _parent->fProvider;
1046 _parent = _parent->fParent;
1047 }
1048 if (_provider)
1049 return _provider->getObject(name, type);
1050
1051 if (ws()) {
1052 std::shared_ptr<TObject> out;
1053 if (auto arg = ws()->arg(name.c_str()); arg) {
1054 auto _tmp = std::shared_ptr<TObject>(arg, [](TObject *) {});
1055 if (!type.empty() && arg->InheritsFrom(type.c_str()))
1056 return _tmp;
1057 if (!out)
1058 out = _tmp;
1059 }
1060 if (auto arg = ws()->data(name.c_str()); arg) {
1061 auto _tmp = std::shared_ptr<TObject>(arg, [](TObject *) {});
1062 if (!type.empty() && arg->InheritsFrom(type.c_str()))
1063 return _tmp;
1064 if (!out)
1065 out = _tmp;
1066 }
1067 if (auto arg = ws()->genobj(name.c_str()); arg) {
1068 auto _tmp = std::shared_ptr<TObject>(arg, [](TObject *) {});
1069 if (!type.empty() && arg->InheritsFrom(type.c_str()))
1070 return _tmp;
1071 if (!out)
1072 out = _tmp;
1073 }
1074 if (auto arg = ws()->embeddedData(name.c_str()); arg) {
1075 auto _tmp = std::shared_ptr<TObject>(arg, [](TObject *) {});
1076 if (!type.empty() && arg->InheritsFrom(type.c_str()))
1077 return _tmp;
1078 if (!out)
1079 out = _tmp;
1080 }
1081 if (auto arg = GETWSSNAPSHOTS(ws()).find(name.c_str()); arg) {
1082 auto _tmp = std::shared_ptr<TObject>(arg, [](TObject *) {});
1083 if (!type.empty() && arg->InheritsFrom(type.c_str()))
1084 return _tmp;
1085 if (!out)
1086 out = _tmp;
1087 }
1088 return out;
1089 }
1090 if (auto arg = get<RooAbsArg>()) {
1091 // can try all nodes
1092 RooArgSet nodes;
1093 arg->treeNodeServerList(&nodes);
1094 if (auto server = nodes.find(name.c_str())) {
1095 return std::shared_ptr<TObject>(server, [](TObject *) {});
1096 }
1097 }
1098 return nullptr;
1099}
1100
1102{
1103 if (fXAxis) {
1104 // check if num bins needs update or not
1105 if (auto cat = dynamic_cast<RooAbsCategory *>(fXAxis->GetParent());
1106 cat && cat->numTypes() != fXAxis->GetNbins()) {
1107 fXAxis.reset();
1108 } else {
1109 return fXAxis.get();
1110 }
1111 }
1112 RooAbsLValue *x = nullptr;
1113 if (auto a = get<RooAbsArg>(); a && a->isFundamental())
1114 x = dynamic_cast<RooAbsLValue *>(a); // self-axis
1115
1116 auto _parentX = (!x && fParent && !fParent->get<RooSimultaneous>()) ? fParent->GetXaxis() : nullptr;
1117
1118 auto o = get<RooAbsReal>();
1119 if (!o)
1120 return _parentX;
1121
1122 if (auto xName = o->getStringAttribute("xvar"); xName) {
1123 x = dynamic_cast<RooAbsLValue *>(getObject(xName).get());
1124 }
1125
1126 // if xvar has become set equal to an arg and this is a pdf, we will allow a do-over
1127 if (!x) {
1128 // need to choose from dependent fundamentals, in following order:
1129 // parentX (if not a glob), robs, globs, vars, args
1130
1131 if (_parentX && !dynamic_cast<RooAbsArg *>(_parentX->GetParent())->getAttribute("global") &&
1132 (o->dependsOn(*dynamic_cast<RooAbsArg *>(_parentX->GetParent())) || vars().empty())) {
1133 x = dynamic_cast<RooAbsLValue *>(_parentX->GetParent());
1134 } else if (auto _obs = obs(); !_obs.empty()) {
1135 for (auto &v : _obs) {
1136 if (!v->get<RooAbsArg>()->getAttribute("global")) {
1137 x = v->get<RooAbsLValue>();
1138 if (x)
1139 break;
1140 } else if (!x) {
1141 x = v->get<RooAbsLValue>();
1142 }
1143 }
1144 } else if (auto _pars = pars(); !_pars.empty()) {
1145 for (auto &v : _pars) {
1146 if (!v->get<RooAbsArg>()->getAttribute("Constant")) {
1147 x = v->get<RooAbsLValue>();
1148 if (x)
1149 break;
1150 } else if (!x) {
1151 x = v->get<RooAbsLValue>();
1152 }
1153 }
1154 }
1155
1156 if (!x) {
1157 return nullptr;
1158 }
1159 }
1160
1161 /* no longer 'remembering' xvars when call GetXaxis(), as was causing incorrect obs to go onto node
1162 * when e.g. adding histogram with bin errors to a channel - the statFactor and constraint terms were
1163 * created first, causing the channel's xaxis to become equal to a globs at some point because of a GetXaxis call
1164 * Alternatively we could clear the xvar attribute of all client nodes whenever we 'modify' something
1165 * Should do that if processing large workspaces becomes slow
1166 if (o != dynamic_cast<TObject *>(x)) {
1167 o->setStringAttribute("xvar", dynamic_cast<TObject *>(x)->GetName());
1168 } */
1169
1170 // decide binning to use
1171 TString binningName = o->getStringAttribute("binning");
1172 auto _bnames = x->getBinningNames();
1173 bool hasBinning = false;
1174 for (auto &b : _bnames) {
1175 if (b == binningName) {
1176 hasBinning = true;
1177 break;
1178 }
1179 }
1180 if (!hasBinning) {
1181 // doesn't have binning, so clear binning attribute
1182 // this can happen after Combine of models because binning don't get combined yet (should fix this)
1183 Warning("GetXaxis", "Binning %s not defined on %s - clearing", binningName.Data(),
1184 dynamic_cast<TObject *>(x)->GetName());
1185 o->setStringAttribute("binning", nullptr);
1186 binningName = "";
1187 }
1188
1189 if (binningName == "" && o != dynamic_cast<TObject *>(x)) {
1190 // has var has a binning matching this nodes name then use that
1191 auto __bnames = x->getBinningNames();
1192 for (auto &b : __bnames) {
1193 if (b == GetName())
1194 binningName = GetName();
1195 if (b == o->GetName()) {
1196 binningName = o->GetName();
1197 break;
1198 } // best match
1199 }
1200 if (binningName == "") {
1201 // if we are binned in this var then will define that as a binning
1202 if (/*o->isBinnedDistribution(*dynamic_cast<RooAbsArg *>(x))*/
1203 auto bins = _or_func(
1204 /*o->plotSamplingHint(*dynamic_cast<RooAbsRealLValue
1205 *>(x),-std::numeric_limits<double>::infinity(),std::numeric_limits<double>::infinity())*/
1206 (std::list<double> *)(nullptr),
1207 (dynamic_cast<RooAbsRealLValue *>(x))
1208 ? o->binBoundaries(*dynamic_cast<RooAbsRealLValue *>(x), -std::numeric_limits<double>::infinity(),
1209 std::numeric_limits<double>::infinity())
1210 : nullptr);
1211 bins) {
1212 std::vector<double> _bins;
1213 for (auto &b : *bins) {
1214 if (_bins.empty() || std::abs(_bins.back() - b) > 1e-5 * _bins.back())
1215 _bins.push_back(b);
1216 }
1217 fXAxis = std::make_shared<Axis2>(_bins.size() - 1, &_bins[0]);
1218 // add this binning to the var to avoid recalling ...
1219 if (auto _v = dynamic_cast<RooRealVar *>(x); _v) {
1220 _v->setBinning(RooBinning(_bins.size() - 1, &_bins[0], o->GetName()), o->GetName());
1221 _v->getBinning(o->GetName())
1222 .SetTitle(""); // indicates to use the current var title when building histograms etc
1223 //_v->getBinning(o->GetName()).SetTitle(strlen(dynamic_cast<TObject*>(x)->GetTitle()) ?
1224 // dynamic_cast<TObject*>(x)->GetTitle() : dynamic_cast<TObject*>(x)->GetName());
1225 }
1226 binningName = o->GetName();
1227 delete bins;
1228 } else if (_parentX) {
1229 // use parent axis binning if defined, otherwise we will default
1230 binningName = _parentX->GetName();
1231 }
1232 }
1233 }
1234
1235 if (!fXAxis) {
1236 if (auto r = dynamic_cast<RooAbsRealLValue *>(x); r) {
1237 if (r->getBinning(binningName).isUniform()) {
1238 fXAxis = std::make_shared<Axis2>(x->numBins(binningName), r->getMin(binningName), r->getMax(binningName));
1239 } else {
1240 fXAxis = std::make_shared<Axis2>(x->numBins(binningName), r->getBinning(binningName).array());
1241 }
1242 } else if (auto cat = dynamic_cast<RooCategory *>(x)) {
1243 std::vector<double> bins = {};
1244 for (int i = 0; i <= x->numBins(binningName); i++)
1245 bins.push_back(i);
1246 fXAxis = std::make_shared<Axis2>(x->numBins(binningName), &bins[0]);
1247 // TODO have to load current state of bin labels if was a category (sadly not a virtual method)
1248 int i = 1;
1249 std::map<int, std::string> cats; // fill into a map to preserve index ordering
1250 for (auto &c : *cat) {
1251 if (cat->isStateInRange(binningName, c.first.c_str())) {
1252 cats[c.second] = c.first;
1253 }
1254 }
1255 for (auto &[_, label] : cats) {
1256 fXAxis->SetBinLabel(i++, label.c_str());
1257 }
1258 }
1259 }
1260
1261 fXAxis->SetName(binningName);
1262 fXAxis->SetParent(dynamic_cast<TObject *>(x));
1263 return fXAxis.get();
1264}
1265
1266const char *xRooNode::GetIconName() const
1267{
1268 if (auto o = get(); o) {
1269 if (o->InheritsFrom("RooWorkspace"))
1270 return "TFile";
1271 if (o->InheritsFrom("RooAbsData"))
1272 return "TProfile";
1273 if (o->InheritsFrom("RooSimultaneous"))
1274 return "TH3D";
1275
1276 if (o->InheritsFrom("RooProdPdf"))
1277 return "a.C"; // or nullptr for folder
1278 if (o->InheritsFrom("RooRealSumPdf") || o->InheritsFrom("RooAddPdf"))
1279 return "TH2D";
1280 // if(o->InheritsFrom("RooProduct")) return "TH1D";
1281 if (o->InheritsFrom("RooFitResult")) {
1282 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitRooFitResult", true)) {
1283 gClient->GetMimeTypeList()->AddType("xRooFitRooFitResult", "xRooFitRooFitResult", "package.xpm",
1284 "package.xpm", "->Browse()");
1285 }
1286 return "xRooFitRooFitResult";
1287 }
1288 if (o->InheritsFrom("RooRealVar") || o->InheritsFrom("RooCategory")) {
1289 if (get<RooAbsArg>()->getAttribute("obs")) {
1290 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitObs", true)) {
1291 gClient->GetMimeTypeList()->AddType("xRooFitObs", "xRooFitObs", "x_pic.xpm", "x_pic.xpm", "->Browse()");
1292 }
1293 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitGlobs", true)) {
1294 gClient->GetMimeTypeList()->AddType("xRooFitGlobs", "xRooFitGlobs", "z_pic.xpm", "z_pic.xpm",
1295 "->Browse()");
1296 }
1297 return (get<RooAbsArg>()->getAttribute("global") ? "xRooFitGlobs" : "xRooFitObs");
1298 }
1299 return "TLeaf";
1300 }
1301 if (o->InheritsFrom("TStyle")) {
1302 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitTStyle", true)) {
1303 gClient->GetMimeTypeList()->AddType("xRooFitTStyle", "xRooFitTStyle", "bld_colorselect.xpm",
1304 "bld_colorselect.xpm", "->Browse()");
1305 }
1306 return "xRooFitTStyle";
1307 }
1308 if (o->InheritsFrom("RooConstVar")) {
1309 /*if (!gClient->GetMimeTypeList()->GetIcon("xRooFitRooConstVar",true)) {
1310 gClient->GetMimeTypeList()->AddType("xRooFitRooConstVar", "xRooFitRooConstVar", "stop_t.xpm", "stop_t.xpm",
1311 "->Browse()");
1312 }
1313 return "xRooFitRooConstVar";*/
1314 return "TMethodBrowsable-leaf";
1315 }
1316 if (o->InheritsFrom("RooStats::HypoTestInverterResult")) {
1317 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitScanStyle", true)) {
1318 gClient->GetMimeTypeList()->AddType("xRooFitScanStyle", "xRooFitScanStyle", "f2_s.xpm", "f2_s.xpm",
1319 "->Browse()");
1320 }
1321 return "xRooFitScanStyle";
1322 }
1323 if (o->InheritsFrom("RooStats::HypoTestResult")) {
1324 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitTestStyle", true)) {
1325 gClient->GetMimeTypeList()->AddType("xRooFitTestStyle", "xRooFitTestStyle", "diamond.xpm", "diamond.xpm",
1326 "->Browse()");
1327 }
1328 return "xRooFitTestStyle";
1329 }
1330 if (o->InheritsFrom("RooStats::HistFactory::FlexibleInterpVar"))
1331 return "TBranchElement-folder";
1332 if (o->InheritsFrom("RooAbsPdf")) {
1333 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitPDFStyle", true)) {
1334 gClient->GetMimeTypeList()->AddType("xRooFitPDFStyle", "xRooFitPDFStyle", "pdf.xpm", "pdf.xpm",
1335 "->Browse()");
1336 }
1337 return "xRooFitPDFStyle";
1338 }
1339 if (o->InheritsFrom("RooStats::ModelConfig")) {
1340 if (!gClient->GetMimeTypeList()->GetIcon("xRooFitMCStyle", true)) {
1341 gClient->GetMimeTypeList()->AddType("xRooFitMCStyle", "xRooFitMCStyle", "app_t.xpm", "app_t.xpm",
1342 "->Browse()");
1343 }
1344 return "xRooFitMCStyle";
1345 }
1346 if (auto a = dynamic_cast<RooAbsReal *>(o); a) {
1347 if (auto _ax = GetXaxis();
1348 _ax && (a->isBinnedDistribution(*dynamic_cast<RooAbsArg *>(_ax->GetParent())) ||
1349 (dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()) &&
1350 std::unique_ptr<std::list<double>>(a->binBoundaries(
1351 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), -std::numeric_limits<double>::infinity(),
1352 std::numeric_limits<double>::infinity()))))) {
1353 return "TH1D";
1354 }
1355 return "TF1";
1356 }
1357 return o->ClassName();
1358 }
1359 if (!IsFolder()) {
1360 return "Unknown";
1361 }
1362 return nullptr;
1363}
1364
1365const char *xRooNode::GetNodeType() const
1366{
1367 if (auto rrs = get<RooRealSumPdf>(); rrs) {
1368 // if is BinnedLikelihood show that option
1369 if (rrs->getAttribute("BinnedLikelihood"))
1370 return "BinnedLikelihood";
1371 }
1372 if (auto o = get(); o && fParent && (fParent->get<RooProduct>() || fParent->get<RooRealSumPdf>())) {
1373 if (o->InheritsFrom("RooStats::HistFactory::FlexibleInterpVar"))
1374 return "Overall";
1375 if (o->InheritsFrom("PiecewiseInterpolation")) {
1376 // check if children are all RooHistFunc ... if so, it's a HistoFactor, otherwise it's a Varied
1377 bool isHisto = true;
1378 for (auto c : const_cast<xRooNode *>(this)->browse()) {
1379 if (!c->get<RooHistFunc>()) {
1380 isHisto = false;
1381 break;
1382 }
1383 }
1384 if (isHisto) {
1385 return (dynamic_cast<RooAbsArg *>(o)->getAttribute("density")) ? "HistoDensity" : "Histo";
1386 } else {
1387 return (dynamic_cast<RooAbsArg *>(o)->getAttribute("density")) ? "VariedDensity" : "Varied";
1388 }
1389 }
1390 if (o->InheritsFrom("RooHistFunc"))
1391 return (dynamic_cast<RooAbsArg *>(o)->getAttribute("density")) ? "SimpleDensity" : "Simple";
1392 if (o->InheritsFrom("RooBinWidthFunction"))
1393 return "Density";
1394 if (o->InheritsFrom("ParamHistFunc"))
1395 return "Shape";
1396 if (o->InheritsFrom("RooRealVar"))
1397 return "Norm";
1398 if (o->InheritsFrom("RooConstVar"))
1399 return "Const";
1400 }
1401 return "";
1402}
1403
1404xRooNode xRooNode::coords(bool setVals) const
1405{
1406 xRooNode out(".coords", nullptr, *this);
1407 // go up through parents looking for slice obs
1408 auto _p = std::shared_ptr<xRooNode>(const_cast<xRooNode *>(this), [](xRooNode *) {});
1409 while (_p) {
1410 TString pName(_p->GetName());
1411 // following is commented out while still considering, but idea is to include category in coords
1412 /*if (auto s = _p->get<RooSimultaneous>(); s && s->indexCat().InheritsFrom("RooCategory") &&
1413 !out.find(s->indexCat().GetName())) { auto cat = const_cast<RooCategory*>(dynamic_cast<const
1414 RooCategory*>(&s->indexCat()));
1415 // check if we have a pdf for every category ... if not then add to cut
1416 cat->clearRange("coordRange",true);
1417 bool hasMissing = false;
1418 std::string includedStates;
1419 for (auto state : *cat) {
1420 if (!s->getPdf(state.first.c_str())) {
1421 hasMissing = true;
1422 } else {
1423 if (!includedStates.empty()) {
1424 includedStates += ",";
1425 }
1426 includedStates += state.first;
1427 }
1428 }
1429 if (hasMissing) {
1430 if(includedStates.find(",") != std::string::npos) {
1431 cat->addToRange("coordRange",includedStates.c_str());
1432 } else {
1433 cat->setLabel(includedStates);
1434 }
1435 out.emplace_back(std::make_shared<xRooNode>(cat->GetName(),_p->getObject<RooAbsArg>(cat->GetName()),_p));
1436 }
1437 } else*/
1438 if (auto pos = pName.Index('='); pos != -1) {
1439 if (pos > 0 && pName(pos - 1) == '<') {
1440 // should be a range on a real lvalue, of form low<=name<high
1441 double low = TString(pName(0, pos - 1)).Atof();
1442 pName = pName(pos + 1, pName.Length());
1443 double high = TString(pName(pName.Index('<') + 1, pName.Length())).Atof();
1444 pName = pName(0, pName.Index('<'));
1445 if (auto _obs = _p->getObject<RooAbsRealLValue>(pName.Data()); _obs) {
1446 if (setVals) {
1447 _obs->setVal((high + low) / 2.);
1448 static_cast<RooRealVar *>(_obs.get())->setRange("coordRange", low, high);
1449 _obs->setStringAttribute(
1450 "coordRange", "coordRange"); // will need if we allow multi disconnected regions, need comma list
1451 }
1452 out.emplace_back(std::make_shared<xRooNode>(_obs->GetName(), _obs, _p));
1453 } else {
1454 throw std::runtime_error(TString::Format("Unknown observable: %s", pName.Data()));
1455 }
1456
1457 } else if (auto _obs = _p->getObject<RooAbsArg>(pName(0, pos)); _obs) {
1458 if (setVals) {
1459 if (auto _cat = dynamic_cast<RooAbsCategoryLValue *>(_obs.get()); _cat) {
1460 _cat->setLabel(pName(pos + 1, pName.Length()));
1461 } else if (auto _var = dynamic_cast<RooAbsRealLValue *>(_obs.get()); _var) {
1462 _var->setVal(TString(pName(pos + 1, pName.Length())).Atof());
1463 }
1464 }
1465 out.emplace_back(std::make_shared<xRooNode>(_obs->GetName(), _obs, _p));
1466 } else {
1467 throw std::runtime_error("Unknown observable, could not find");
1468 }
1469 }
1470 _p = _p->fParent;
1471 }
1472 return out;
1473}
1474
1475void xRooNode::_Add_(const char *name, const char *opt)
1476{
1477 try {
1478 Add(name, opt);
1479 } catch (const std::exception &e) {
1480 new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(),
1481 kMBIconExclamation); // deletes self on dismiss?
1482 }
1483}
1484void xRooNode::_Vary_(const char *what)
1485{
1486 try {
1487 Vary(what);
1488 } catch (const std::exception &e) {
1489 new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(),
1490 kMBIconExclamation); // deletes self on dismiss?
1491 }
1492}
1493
1495{
1496
1497 if (strcmp(GetName(), ".poi") == 0) {
1498 // demote a parameter from being a poi
1499 auto toRemove =
1500 (child.get<RooAbsArg>() || !find(child.GetName())) ? child : xRooNode(find(child.GetName())->fComp);
1501 if (toRemove) {
1502 if (!toRemove.get<RooAbsArg>()->getAttribute("poi")) {
1503 throw std::runtime_error(TString::Format("%s is not a poi", toRemove.GetName()));
1504 }
1505 toRemove.get<RooAbsArg>()->setAttribute("poi", false);
1506 return toRemove;
1507 }
1508 } else if (strcmp(GetName(), ".factors") == 0 || strcmp(GetName(), ".constraints") == 0 ||
1509 strcmp(GetName(), ".components") == 0) {
1510 auto toRemove =
1511 (child.get<RooAbsArg>() || !find(child.GetName())) ? child : xRooNode(find(child.GetName())->fComp);
1512 if (auto p = fParent->get<RooProdPdf>(); p) {
1513 auto pdf = toRemove.get<RooAbsArg>();
1514 if (!pdf)
1515 pdf = p->pdfList().find(child.GetName());
1516 if (!pdf)
1517 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1518 auto i = p->pdfList().index(*pdf);
1519 if (i >= 0) {
1520#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
1521 const_cast<RooArgList &>(p->pdfList()).remove(*pdf);
1522#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
1523 p->_pdfNSetList.erase(p->_pdfNSetList.begin() + i);
1524#else
1525 auto nset = p->_pdfNSetList.At(i);
1526 p->_pdfNSetList.Remove(nset);
1527 delete nset; // I don't think the RooLinkedList owned it so must delete ourself
1528#endif
1529 if (p->_extendedIndex == i)
1530 p->_extendedIndex = -1;
1531 else if (p->_extendedIndex > i)
1532 p->_extendedIndex--;
1533#else
1534 p->removePdfs(RooArgSet(*pdf));
1535#endif
1536 sterilize();
1537 return xRooNode(*pdf);
1538 } else {
1539 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1540 }
1541 } else if (auto p2 = fParent->get<RooProduct>(); p2) {
1542 auto arg = toRemove.get<RooAbsArg>();
1543 if (!arg)
1544 arg = p2->components().find(child.GetName());
1545 if (!arg)
1546 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1547 // remove server ... doesn't seem to trigger removal from proxy
1548#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
1549 p2->_compRSet.remove(*arg);
1550#else
1551 const_cast<RooArgList &>(p2->realComponents()).remove(*arg);
1552#endif
1553 p2->removeServer(*arg, true);
1554 sterilize();
1555 return xRooNode(*arg);
1556 } else if (fParent->get<RooSimultaneous>()) {
1557 // remove from all channels
1558 bool removed = false;
1559 for (auto &c : fParent->bins()) {
1560 try {
1561 c->constraints().Remove(toRemove);
1562 removed = true;
1563 } catch (std::runtime_error &) { /* wasn't a constraint in channel */
1564 }
1565 }
1566 sterilize();
1567 if (!removed)
1568 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1569 return toRemove;
1570 } else if (auto p4 = fParent->get<RooRealSumPdf>(); p4) {
1571 auto arg = toRemove.get<RooAbsArg>();
1572 if (!arg)
1573 arg = p4->funcList().find(child.GetName());
1574 if (!arg)
1575 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1576 // remove, including coef removal ....
1577 auto idx = p4->funcList().index(arg);
1578
1579 if (idx != -1) {
1580
1581 const_cast<RooArgList &>(p4->funcList()).remove(*arg);
1582 p4->removeServer(*arg, true);
1583 // have to be careful removing coef because if shared will end up removing them all!!
1584 std::vector<RooAbsArg *> _coefs;
1585 for (size_t ii = 0; ii < const_cast<RooArgList &>(p4->coefList()).size(); ii++) {
1586 if (ii != size_t(idx))
1587 _coefs.push_back(const_cast<RooArgList &>(p4->coefList()).at(ii));
1588 }
1589 const_cast<RooArgList &>(p4->coefList()).removeAll();
1590 for (auto &a : _coefs)
1591 const_cast<RooArgList &>(p4->coefList()).add(*a);
1592
1593 sterilize();
1594 } else {
1595 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1596 }
1597 return xRooNode(*arg);
1598 } else if (auto p5 = fParent->get<RooAddPdf>(); p5) {
1599 auto arg = toRemove.get<RooAbsArg>();
1600 if (!arg)
1601 arg = p5->pdfList().find(child.GetName());
1602 if (!arg)
1603 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1604 // remove, including coef removal ....
1605 auto idx = p5->pdfList().index(arg);
1606
1607 if (idx != -1) {
1608
1609 const_cast<RooArgList &>(p5->pdfList()).remove(*arg);
1610 p5->removeServer(*arg, true);
1611 // have to be careful removing coef because if shared will end up removing them all!!
1612 std::vector<RooAbsArg *> _coefs;
1613 for (size_t ii = 0; ii < const_cast<RooArgList &>(p5->coefList()).size(); ii++) {
1614 if (ii != size_t(idx))
1615 _coefs.push_back(const_cast<RooArgList &>(p5->coefList()).at(ii));
1616 }
1617 const_cast<RooArgList &>(p5->coefList()).removeAll();
1618 for (auto &a : _coefs)
1619 const_cast<RooArgList &>(p5->coefList()).add(*a);
1620
1621 sterilize();
1622 } else {
1623 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1624 }
1625 return xRooNode(*arg);
1626 } else if (auto p6 = fParent->get<RooAddition>(); p6) {
1627 auto arg = toRemove.get<RooAbsArg>();
1628 if (!arg)
1629 arg = p6->list().find(child.GetName());
1630 if (!arg)
1631 throw std::runtime_error(TString::Format("Cannot find %s in %s", child.GetName(), fParent->GetName()));
1632 // remove server ... doesn't seem to trigger removal from proxy
1633 const_cast<RooArgList &>(p6->list()).remove(*arg);
1634 p6->removeServer(*arg, true);
1635 sterilize();
1636 return xRooNode(*arg);
1637 }
1638 }
1639
1640 if (auto w = get<RooWorkspace>(); w) {
1641 xRooNode out(child.GetName());
1642 auto arg = w->components().find(child.GetName());
1643 if (!arg)
1644 arg = operator[](child.GetName())->get<RooAbsArg>();
1645 if (!arg) {
1646 throw std::runtime_error(TString::Format("Cannot find %s in workspace %s", child.GetName(), GetName()));
1647 }
1648 // check has no clients ... if so, cannot delete
1649 if (arg->hasClients()) {
1650 throw std::runtime_error(
1651 TString::Format("Cannot remove %s from workspace %s, because it has dependencies - first remove from those",
1652 child.GetName(), GetName()));
1653 }
1654 const_cast<RooArgSet &>(w->components()).remove(*arg); // deletes arg
1655 Info("Remove", "Deleted %s from workspace %s", out.GetName(), GetName());
1656 return out;
1657 } else if (get<RooProduct>() || get<RooProdPdf>()) {
1658 return factors().Remove(child);
1659 } else if (get<RooRealSumPdf>() || get<RooAddPdf>() || get<RooAddition>()) {
1660 return components().Remove(child);
1661 }
1662
1663 throw std::runtime_error("Removal not implemented for object type " +
1664 std::string(get() ? get()->ClassName() : "null"));
1665}
1666
1668{
1669
1670 class AutoUpdater {
1671 public:
1672 AutoUpdater(xRooNode &_n) : n(_n) {}
1673 ~AutoUpdater() { n.browse(); }
1674 xRooNode &n;
1675 };
1676 AutoUpdater xxx(*this);
1677
1678 TString sOpt(opt);
1679 bool considerType(sOpt == "+");
1680
1681 if (strlen(GetName()) > 0 && GetName()[0] == '!' && fParent) {
1682 // folder .. pass onto parent and add folder to child folder list
1683 const_cast<xRooNode &>(child).fFolder += GetName();
1684 return fParent->Add(child, opt);
1685 }
1686 // this is how to get the first real parent ... may be useful at some point?
1687 /*auto realParent = fParent;
1688 while(!realParent->get()) {
1689 realParent = realParent->fParent;
1690 if (!realParent) throw std::runtime_error("No parentage");
1691 }*/
1692
1693 // adding to a collection node will incorporate the child into the parent of the collection
1694 // in the appropriate way
1695 if (strcmp(GetName(), ".factors") == 0) {
1696 // multiply the parent
1697 return fParent->Multiply(child, opt);
1698 } else if (strcmp(GetName(), ".components") == 0) {
1699 // add to the parent
1700 return fParent->Add(child, opt);
1701 } else if (strcmp(GetName(), ".variations") == 0) {
1702 // vary the parent
1703 return fParent->Vary(child);
1704 } else if (strcmp(GetName(), ".constraints") == 0) {
1705 // constrain the parent
1706 return fParent->Constrain(child);
1707 } else if (strcmp(GetName(), ".bins") == 0 && fParent->get<RooSimultaneous>()) {
1708 // adding a channel (should adding a 'bin' be an 'Extend' operation?)
1709 return fParent->Vary(child);
1710 } else if ((strcmp(GetName(), ".globs") == 0)) {
1711 if (child.get<RooAbsArg>() || (!child.fComp && getObject<RooAbsArg>(child.GetName()))) {
1712 auto out = (child.get<RooAbsArg>()) ? child.get<RooAbsArg>() : getObject<RooAbsArg>(child.GetName()).get();
1713 out->setAttribute("obs");
1714 out->setAttribute("global");
1715 return xRooNode(*out, *this);
1716 }
1717 throw std::runtime_error("Failed to add global observable");
1718 } else if ((strcmp(GetName(), ".poi") == 0)) {
1719 if (child.get<RooAbsLValue>() || (!child.fComp && getObject<RooAbsLValue>(child.GetName()))) {
1720 auto out = (child.get<RooAbsArg>()) ? child.get<RooAbsArg>() : getObject<RooAbsArg>(child.GetName()).get();
1721 out->setAttribute("poi");
1722 return xRooNode(*out, *this);
1723 } else if (!child.get() && fParent->get<RooWorkspace>()) {
1724 // may be creating poi at same time as adding, try add to parent
1725 auto res = fParent->Add(child);
1726 if (res.get<RooAbsLValue>())
1727 return Add(res);
1728 }
1729 throw std::runtime_error("Failed to add parameter of interest");
1730 } else if ((strcmp(GetName(), ".pars") == 0 || strcmp(GetName(), ".vars") == 0) && fParent->get<RooWorkspace>()) {
1731 // adding a parameter, interpret as factory string unless no "[" then create RooRealVar
1732 TString fac(child.GetName());
1733 if (!fac.Contains("[") && !fac.Contains("("))
1734 fac += "[1]";
1735 return xRooNode(*fParent->get<RooWorkspace>()->factory(fac), fParent);
1736 } else if (strcmp(GetName(), ".datasets()") == 0) {
1737
1738 if (auto _data = child.get<RooAbsData>(); _data) {
1739 if (find(_data->GetName())) {
1740 throw std::runtime_error(TString::Format("Cannot add dataset %s, already exists for %s. If intending to "
1741 "combine datasets, please add directly to dataset",
1742 child->GetName(), GetName()));
1743 }
1744 return fParent->Add(child); // add the dataset to the parent
1745 }
1746
1747 // create a dataset - only allowed for pdfs or workspaces
1748 if (auto _ws = ws(); _ws && fParent) {
1749 sOpt.ToLower();
1750 if (!fParent->get<RooAbsPdf>() && (!fParent->get<RooWorkspace>() || sOpt == "asimov")) {
1751 throw std::runtime_error(
1752 "Datasets can only be created for pdfs or workspaces (except if generated dataset, then must be pdf)");
1753 }
1754
1755 if (sOpt == "asimov" || sOpt == "toy") {
1756 // generate expected dataset - note that globs will be frozen at this time
1757 auto _fr = fParent->fitResult();
1758 if (strlen(_fr->GetName()) == 0) { // ensure fit result has a name so that name is saved inside dataset
1759 _fr.get<RooFitResult>()->SetName(TUUID().AsString());
1760 }
1761 auto ds = fParent->generate(_fr, sOpt == "asimov");
1762 if (strlen(child.GetName())) {
1763 ds.SetName(child.GetName());
1764 ds.get<TNamed>()->SetName(child.GetName());
1765 }
1766 if (auto _ds = ds.get<RooAbsData>()) {
1767 _ws->import(*_ds);
1768 }
1769 if (_fr.get<RooFitResult>()->numStatusHistory() == 0) {
1770 if (!GETWSSNAPSHOTS(_ws).find(_fr->GetName())) {
1771 const_cast<RooLinkedList &>(GETWSSNAPSHOTS(_ws)).Add(_fr->Clone());
1772 }
1773 } else if (!_ws->obj(_fr->GetName())) {
1774 _ws->import((*_fr.get<RooFitResult>()));
1775 } // save fr to workspace, for later retrieval
1776 return xRooNode(*_ws->data(ds.GetName()), fParent);
1777 }
1778
1779 auto parentObs = fParent->obs(); // may own globs so keep alive
1780 auto _obs = parentObs.argList();
1781 // put globs in a snapshot
1782 std::unique_ptr<RooAbsCollection> _globs(_obs.selectByAttrib("global", true));
1783 // RooArgSet _tmp; _tmp.add(*_globs);_ws->saveSnapshot(child.GetName(),_tmp);
1784 _obs.remove(*_globs);
1785
1786 // include any coords
1787 _obs.add(coords(false).argList(), true);
1788 // include axis var too, provided it's an observable
1789 if (auto ax = GetXaxis(); ax && dynamic_cast<RooAbsArg *>(ax->GetParent())->getAttribute("obs")) {
1790 _obs.add(*dynamic_cast<RooAbsArg *>(ax->GetParent()));
1791 }
1792 // check if ws already has a dataset with this name, if it does we may need to extend columns
1793 if (auto _d = _ws->data(child.GetName()); _d) {
1794 // add any missing obs
1795 RooArgSet l(_obs);
1796 l.remove(*_d->get(), true, true);
1797 if (!l.empty()) {
1798 auto _dd = dynamic_cast<RooDataSet *>(_d);
1799 if (!_dd)
1800 throw std::runtime_error("Cannot extend dataset with new columns");
1801 for (auto &x : l) {
1802 _dd->addColumn(*x);
1803 }
1804 }
1805 } else {
1806 RooRealVar w("weightVar", "weightVar", 1);
1807 _obs.add(w);
1808 RooDataSet d(child.GetName(), child.GetTitle(), _obs, RooFit::WeightVar("weightVar"));
1809 _ws->import(d);
1810 // seems have to set bits after importing, not before
1811 if (auto __d = _ws->data(child.GetName()))
1812 __d->SetBit(1 << 20, _ws->allData().size() == 1); // sets as selected if is only ds
1813 }
1814 /*if(!_ws->data(child.GetName())) {
1815 RooRealVar w("weightVar", "weightVar", 1);
1816 RooArgSet _obs; _obs.add(w);
1817 RooDataSet d(child.GetName(), child.GetTitle(), _obs, "weightVar");
1818 _ws->import(d);
1819 }*/
1820 auto out = std::shared_ptr<TObject>(_ws->data(child.GetName()), [](TObject *) {});
1821
1822 if (out) {
1823 xRooNode o(out, fParent);
1824 if (child.get<TH1>())
1825 o = *child.get();
1826 return o;
1827 }
1828 }
1829 throw std::runtime_error("Cannot create dataset");
1830 }
1831
1832 if (!get()) {
1833 if (!fParent)
1834 throw std::runtime_error("Cannot add to null object with no parentage");
1835
1836 auto _ref = emplace_back(std::shared_ptr<xRooNode>(&const_cast<xRooNode &>(child), [](TObject *) {}));
1837 try {
1838 fComp = fParent->Add(*this, "+").fComp;
1839 } catch (...) {
1840 resize(size() - 1);
1841 std::rethrow_exception(std::current_exception());
1842 }
1843 resize(size() - 1); // remove the temporarily added node
1844
1845 if (!fComp) {
1846 throw std::runtime_error("No object");
1847 }
1848 }
1849
1850 if (auto p = get<RooAbsData>(); p) {
1851 if (auto bb = getBrowsable(".sourceds"))
1852 bb->Add(child, opt);
1853 if (auto _data = child.get<RooDataSet>()) {
1854 auto ds = dynamic_cast<RooDataSet *>(p);
1855 if (!ds) {
1856 throw std::runtime_error("Can only add datasets to a dataset");
1857 }
1858
1859 // append any missing globs, and check any existing globs have matching values
1860 RooArgList globsToAdd;
1861 auto _globs = globs();
1862 for (auto &glob : child.globs()) {
1863 if (auto g = _globs.find(glob->GetName()); !g) {
1864 globsToAdd.addClone(*glob->get<RooAbsArg>());
1865 } else if (g->GetContent() != glob->GetContent()) {
1866 Warning("Add", "Global observable %s=%g in dataset %s mismatches %s value %g ... ignoring latter",
1867 g->GetName(), g->GetContent(), GetName(), child.GetName(), glob->GetContent());
1868 }
1869 }
1870 // add any existing globs to list then set the list
1871 if (auto _dglobs = p->getGlobalObservables()) {
1872 globsToAdd.addClone(*_dglobs);
1873 } else {
1874 for (auto g : _globs)
1875 globsToAdd.addClone(*g->get<RooAbsArg>());
1876 }
1877 p->setGlobalObservables(globsToAdd);
1878
1879 // append any missing observables to our dataset, then append the dataset
1880
1881 std::set<std::pair<RooAbsCategory *, RooCategory *>> cats;
1882
1883 for (auto col : *_data->get()) {
1884 if (!p->get()->contains(*col)) {
1885 ds->addColumn(*col);
1886 } else if (auto c = dynamic_cast<RooAbsCategory *>(col)) {
1887 // check if any of the states of c have different index to c2
1888 auto c2 = dynamic_cast<RooCategory *>(p->get()->find(*col));
1889 if (!c2) {
1890 throw std::runtime_error(
1891 TString::Format("unexpected type for regular observable: %s", col->GetName()));
1892 }
1893 bool iMatches = true;
1894 for (const auto &nameIdx : *c) {
1895 if (!c2->hasLabel(nameIdx.first) && !c2->hasIndex(nameIdx.second)) {
1896 // can define the state
1897 c2->defineType(nameIdx.first, nameIdx.second);
1898 } else if (c2->lookupIndex(nameIdx.first) != nameIdx.second) {
1899 iMatches = false;
1900 break; // state exists, but with different index!
1901 }
1902 }
1903 if (!iMatches)
1904 cats.insert({c, c2});
1905 }
1906 }
1907 if (cats.empty()) {
1908 ds->append(*_data);
1909 } else {
1910 // cannot use append, because if categoricals use same idx for different states, will not do correct thing
1911 for (int i = 0; i < _data->numEntries(); i++) {
1912 auto row = _data->get(i);
1913 auto w = _data->weight();
1914 ds->get()->assign(*row);
1915 for (auto [c, c2] : cats) {
1916 c2->setLabel(row->getCatLabel(c->GetName()));
1917 }
1918 ds->add(*ds->get(), w);
1919 }
1920 }
1921
1922 ds->SetTitle(TString(ds->GetTitle()) + " + " + _data->GetTitle());
1923 SetTitle(TString(GetTitle()) + " + " + child.GetTitle());
1924 return *this;
1925 }
1926 auto _arg = child.get<RooAbsArg>();
1927 if (auto _ds = dynamic_cast<RooDataSet *>(p); _arg && _ds) {
1928 // can add var or function of existing obs to dataset as a column
1929 _ds->addColumn(*_arg);
1930 _arg->setAttribute("obs");
1931 return xRooNode(*_arg, *this);
1932 }
1933 auto _h = child.get<TH1>();
1934 if (!_h) {
1935 throw std::runtime_error("Can only add histogram or var/expr or dataset to data");
1936 }
1937 auto _pdf = parentPdf();
1938 if (!_pdf)
1939 throw std::runtime_error("Could not find pdf");
1940 auto _ax = _pdf->GetXaxis();
1941 if (!_ax) {
1942 throw std::runtime_error("Cannot determine binning to add data");
1943 }
1944
1945 RooArgSet obs;
1946 obs.add(*dynamic_cast<RooAbsArg *>(_ax->GetParent()));
1947 obs.add(coords().argList()); // will also move obs to coords
1948
1949 // add any missing obs
1950 RooArgSet l(obs);
1951 l.remove(*p->get(), true, true);
1952 if (!l.empty()) {
1953 auto _d = dynamic_cast<RooDataSet *>(p);
1954 if (!_d)
1955 throw std::runtime_error("Cannot extend dataset with new columns");
1956 for (auto &x : l) {
1957 _d->addColumn(*x);
1958 }
1959 }
1960
1961 // before adding, ensure range is good to cover
1962 for (auto &o : obs) {
1963 if (auto v = dynamic_cast<RooRealVar *>(o); v) {
1964 if (auto dv = dynamic_cast<RooRealVar *>(p->get()->find(v->GetName())); dv) {
1965 if (v->getMin() < dv->getMin())
1966 dv->setMin(v->getMin());
1967 if (v->getMax() > dv->getMax())
1968 dv->setMax(v->getMax());
1969 }
1970 } else if (auto c = dynamic_cast<RooCategory *>(o); c) {
1971 if (auto dc = dynamic_cast<RooCategory *>(p->get()->find(c->GetName())); dc) {
1972 for (const auto &nameIdx : *c) {
1973 if (!dc->hasLabel(nameIdx.first)) {
1974 dc->defineType(nameIdx.first, nameIdx.second);
1975 }
1976 }
1977 }
1978 }
1979 }
1980
1981 for (int i = 1; i <= _h->GetNbinsX(); i++) {
1982 if (auto cat = dynamic_cast<RooAbsCategoryLValue *>(_ax->GetParent())) {
1983 if (!_h->GetXaxis()->GetBinLabel(i)) {
1984 throw std::runtime_error(
1985 TString::Format("Categorical observable %s requires bin labels", _ax->GetParent()->GetName()));
1986 } else if (!cat->hasLabel(_h->GetXaxis()->GetBinLabel(i))) {
1987 throw std::runtime_error(TString::Format("Categorical observable %s does not have label %s",
1988 _ax->GetParent()->GetName(), _h->GetXaxis()->GetBinLabel(i)));
1989 } else {
1990 cat->setLabel(_h->GetXaxis()->GetBinLabel(i));
1991 }
1992 } else {
1993 dynamic_cast<RooAbsRealLValue *>(_ax->GetParent())->setVal(_h->GetBinCenter(i));
1994 }
1995 p->add(obs, _h->GetBinContent(i));
1996 }
1997
1998 return *this;
1999 }
2000
2001 if (auto p = get<RooAddPdf>(); p) {
2002 auto cc = child.fComp;
2003 // bool isConverted = (cc != child.convertForAcquisition(*this, sOpt));
2004 child.convertForAcquisition(*this, sOpt);
2005 if ((child.get<RooAbsPdf>() || (!child.fComp && getObject<RooAbsPdf>(child.GetName())))) {
2006 auto out = (child.fComp) ? acquire(child.fComp) : getObject<RooAbsArg>(child.GetName());
2007 // don't add a coef if in 'all-extended' mode and this pdf is extendable
2008 auto _pdf = std::dynamic_pointer_cast<RooAbsPdf>(out);
2009 if (!_pdf) {
2010 throw std::runtime_error("Something went wrong with pdf acquisition");
2011 }
2012
2013 if (auto _ax = GetXaxis(); _ax && dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()) &&
2014 _pdf->dependsOn(*static_cast<RooAbsArg *>(_ax->GetParent()))) {
2015 auto _p = _pdf;
2016
2017 if (auto _boundaries = std::unique_ptr<std::list<double>>(_p->binBoundaries(
2018 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), -std::numeric_limits<double>::infinity(),
2019 std::numeric_limits<double>::infinity()));
2020 !_boundaries && _ax->GetNbins() > 0) {
2021#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00)
2022 Warning("Add", "Adding unbinned pdf %s to binned %s - will wrap with RooBinSamplingPdf(...)",
2023 _p->GetName(), GetName());
2024 _p = acquireNew<RooBinSamplingPdf>(TString::Format("%s_binned", _p->GetName()), _p->GetTitle(),
2025 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), *_p);
2026 _p->setStringAttribute("alias", std::dynamic_pointer_cast<RooAbsArg>(out)->getStringAttribute("alias"));
2027 if (!_p->getStringAttribute("alias"))
2028 _p->setStringAttribute("alias", out->GetName());
2029#else
2030 throw std::runtime_error(
2031 "unsupported addition of unbinned pdf to binned model - please upgrade to at least ROOT 6.24");
2032#endif
2033 _pdf = _p;
2034 }
2035 }
2036
2037 if (!(_pdf->canBeExtended() && p->coefList().empty())) {
2038 // if extended, use an extended binding as the coef
2039 // otherwise e.g. if adding a RooRealSumPdf the stacked histograms will be above the
2040 // actual pdf histogram because the pdf histogram is just normalized down
2041 if (_pdf->canBeExtended()) {
2042 // FIXME: ExtendedBinding needs the obs list passing to it ... should be fixed in RooFit
2043 std::cout << " warning " << _pdf->GetName() << " wont be correctly normalized" << std::endl;
2044 // until then, this will return "1" and so the pdf's histograms wont be normalized properly in relation
2045 // to stacks of its comps
2046 const_cast<RooArgList &>(p->coefList())
2047 .add(*acquireNew<RooExtendedBinding>(TString::Format("%s_extBind", _pdf->GetName()),
2048 TString::Format("Expected Events of %s", _pdf->GetTitle()),
2049 *_pdf));
2050 } else {
2051
2052 // need to create a coefficient for each existing pdf first, like above
2053 for (auto i = p->coefList().size(); i < p->pdfList().size(); i++) {
2054 const_cast<RooArgList &>(p->coefList())
2055 .add(*acquireNew<RooExtendedBinding>(
2056 TString::Format("%s_extBind", p->pdfList().at(i)->GetName()),
2057 TString::Format("Expected Events of %s", p->pdfList().at(i)->GetTitle()),
2058 *static_cast<RooAbsPdf *>(p->pdfList().at(i))));
2059 }
2060
2061 const_cast<RooArgList &>(p->coefList()).add(*acquire2<RooAbsArg, RooRealVar>("1", "1", 1));
2062 }
2063 // ensure not in no-coef mode any more
2064 *reinterpret_cast<bool *>(reinterpret_cast<unsigned char *>(p) +
2065 p->Class()->GetDataMemberOffset("_allExtendable")) = false;
2066 *reinterpret_cast<bool *>(reinterpret_cast<unsigned char *>(p) +
2067 p->Class()->GetDataMemberOffset("_haveLastCoef")) = true;
2068 }
2069 const_cast<RooArgList &>(p->pdfList()).add(*_pdf);
2070 sterilize();
2071 return xRooNode(*_pdf, *this);
2072 } else if ((child.get<TH1>() || child.get<RooAbsReal>() ||
2073 (!child.get() && getObject<RooAbsReal>(child.GetName()))) &&
2074 !child.get<RooAbsPdf>()) {
2075 RooRealSumPdf *_pdf = nullptr;
2076 bool tooMany(false);
2077 for (auto &pp : factors()) {
2078 if (auto _p = pp->get<RooRealSumPdf>(); _p) {
2079 if (_pdf) {
2080 _pdf = nullptr;
2081 tooMany = true;
2082 break;
2083 } // more than one!
2084 _pdf = _p;
2085 }
2086 }
2087 if (_pdf) {
2088 return xRooNode(*_pdf, *this).Add(child);
2089 } else if (!tooMany) {
2090 // create a RooRealSumPdf to hold the child
2091 auto _sumpdf = Add(*acquireNew<RooRealSumPdf>(TString::Format("%s_samples", p->GetName()),
2092 TString::Format("%s samples", GetTitle()), RooArgList(),
2093 RooArgList(), true));
2094 _sumpdf.get<RooAbsArg>()->setStringAttribute("alias", "samples");
2095 return _sumpdf.Add(child);
2096 }
2097 }
2098 }
2099
2100 if (auto p = get<RooRealSumPdf>(); p) {
2101 std::shared_ptr<TObject> out;
2102 auto cc = child.fComp;
2103 bool isConverted = (cc != child.convertForAcquisition(*this, sOpt));
2104 if (child.get<RooAbsReal>()) {
2105 out = acquire(child.fComp);
2106 if (std::dynamic_pointer_cast<TH1>(cc) && !TString(cc->GetOption()).Contains("nostyle")) {
2107 xRooNode(out, *this).styles(cc.get()); // transfer style if adding a histogram
2108 }
2109 }
2110 if (!child.fComp && getObject<RooAbsReal>(child.GetName())) {
2111 Info("Add", "Adding existing function %s to %s", child.GetName(), p->GetName());
2112 out = getObject<RooAbsReal>(child.GetName());
2113 }
2114
2115 if (!out && !child.fComp) {
2116 std::shared_ptr<RooAbsArg> _func;
2117 // a null node .. so create either a new RooProduct or RooHistFunc if has observables (or no deps but has
2118 // x-axis)
2119 auto _obs = robs();
2120 if (!_obs.empty() || GetXaxis()) {
2121 if (_obs.empty()) {
2122 // using X axis to construct hist
2123 auto _ax = dynamic_cast<Axis2 *>(GetXaxis());
2124 std::unique_ptr<TH1D> h;
2125 {
2126 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
2127 h = std::make_unique<TH1D>(child.GetName(), child.GetTitle(), _ax->GetNbins(),
2128 _ax->binning()->array());
2129 }
2130 h->GetXaxis()->SetName(TString::Format("%s;%s", _ax->GetParent()->GetName(), _ax->GetName()));
2131 // technically convertForAcquisition has already acquired so no need to re-acquire but should be harmless
2132 _func = std::dynamic_pointer_cast<RooAbsArg>(acquire(xRooNode(*h).convertForAcquisition(*this)));
2133 } else if (_obs.size() == 1) {
2134 // use the single obs to make a TH1D
2135 auto _x = _obs.at(0)->get<RooAbsLValue>();
2136 auto _bnames = _x->getBinningNames();
2137 TString binningName = p->getStringAttribute("binning");
2138 for (auto &b : _bnames) {
2139 if (b == p->GetName()) {
2140 binningName = p->GetName();
2141 break;
2142 }
2143 }
2144 std::unique_ptr<TH1D> h;
2145 {
2146 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
2147 h = std::make_unique<TH1D>(child.GetName(), child.GetTitle(), _x->numBins(binningName),
2148 _x->getBinningPtr(binningName)->array());
2149 }
2150 h->GetXaxis()->SetName(
2151 TString::Format("%s;%s", dynamic_cast<TObject *>(_x)->GetName(), binningName.Data()));
2152 // technically convertForAcquisition has already acquired so no need to re-acquire but should be harmless
2153 _func = std::dynamic_pointer_cast<RooAbsArg>(acquire(xRooNode(*h).convertForAcquisition(*this)));
2154 Info("Add", "Created SimpleDensity factor %s (xaxis=%s) for %s", _func->GetName(), _obs.at(0)->GetName(),
2155 p->GetName());
2156 } else {
2157 throw std::runtime_error("Unsupported creation of new component in SumPdf for this many obs");
2158 }
2159 } else {
2160 _func = acquireNew<RooProduct>(TString::Format("%s_%s", p->GetName(), child.GetName()), child.GetTitle(),
2161 RooArgList());
2162 }
2163 _func->setStringAttribute("alias", child.GetName());
2164 out = _func;
2165 }
2166
2167 if (auto _f = std::dynamic_pointer_cast<RooHistFunc>(
2168 (child.get<RooProduct>()) ? child.factors()[child.GetName()]->fComp : out);
2169 _f) {
2170 // adding a histfunc directly to a sumpdf, should be a density
2171 _f->setAttribute("density");
2172 if (_f->getAttribute("autodensity")) {
2173 // need to divide by bin widths first
2174 for (int i = 0; i < _f->dataHist().numEntries(); i++) {
2175 auto bin_pars = _f->dataHist().get(i);
2176 _f->dataHist().set(*bin_pars, _f->dataHist().weight(i) / _f->dataHist().binVolume(*bin_pars));
2177 }
2178 _f->setAttribute("autodensity", false);
2179 _f->setValueDirty();
2180 }
2181
2182 // promote the axis vars to observables
2183 // can't use original child as might refer to unacquired deps
2184 for (auto &x : xRooNode("tmp", _f).vars()) {
2185 x->get<RooAbsArg>()->setAttribute("obs");
2186 }
2187 if (isConverted) {
2188 Info("Add", "Created %s factor RooHistFunc::%s for %s",
2189 _f->getAttribute("density") ? "SimpleDensity" : "Simple", _f->GetName(), p->GetName());
2190 }
2191 }
2192
2193 if (auto _p = std::dynamic_pointer_cast<RooAbsPdf>(out); _p) {
2194 // adding a pdf to a RooRealSumPdf will replace it with a RooAddPdf and put the RooRealSumPdf inside that
2195 // if pdf is extended will use in the "no coefficients" state, where the expectedEvents are taking from
2196 // the pdf integrals
2197 TString newName(p->GetName());
2198 newName.ReplaceAll("_samples", "");
2199 newName += "_components";
2200 Warning("Add", "converting samples to components");
2201
2202 if (auto _ax = GetXaxis(); _ax && dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()) &&
2203 _p->dependsOn(*static_cast<RooAbsArg *>(_ax->GetParent()))) {
2204
2205 if (auto _boundaries = std::unique_ptr<std::list<double>>(_p->binBoundaries(
2206 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), -std::numeric_limits<double>::infinity(),
2207 std::numeric_limits<double>::infinity()));
2208 !_boundaries && _ax->GetNbins() > 0) {
2209#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00)
2210 Warning("Add", "Adding unbinned pdf %s to binned %s - will wrap with RooBinSamplingPdf(...)",
2211 _p->GetName(), GetName());
2212 _p = acquireNew<RooBinSamplingPdf>(TString::Format("%s_binned", _p->GetName()), _p->GetTitle(),
2213 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), *_p);
2214 _p->setStringAttribute("alias", std::dynamic_pointer_cast<RooAbsArg>(out)->getStringAttribute("alias"));
2215 if (!_p->getStringAttribute("alias"))
2216 _p->setStringAttribute("alias", out->GetName());
2217#else
2218 throw std::runtime_error(
2219 "unsupported addition of unbinned pdf to binned model - please upgrade to at least ROOT 6.24");
2220#endif
2221 }
2222 }
2223
2224 // require to be extended to be in coefficient-free mode ...
2225 // otherwise would lose the integral of the sumPdf (can't think of way to have a coef be the integral)
2226 if (!_p->canBeExtended()) {
2227 _p = acquireNew<RooExtendPdf>(TString::Format("%s_extended", _p->GetName()), _p->GetTitle(), *_p,
2228 *acquire2<RooAbsReal, RooRealVar>("1", "1", 1));
2229 }
2230
2231 return *(Replace(*acquireNew<RooAddPdf>(newName, _p->GetTitle(), RooArgList(*p, *_p)))
2232 .browse()[1]); // returns second node.
2233 }
2234
2235 if (auto _f = std::dynamic_pointer_cast<RooAbsReal>(out); _f) {
2236
2237 // todo: if adding a pdf, should actually replace RooRealSumPdf with a RooAddPdf and put
2238 // the sumPdf and *this* pdf inside that pdf
2239 // only exception is the binSamplingPdf below to integrate unbinned functions across bins
2240
2241 if (auto _ax = GetXaxis(); _ax && dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()) &&
2242 _f->dependsOn(*static_cast<RooAbsArg *>(_ax->GetParent()))) {
2243
2244 if (auto _boundaries = std::unique_ptr<std::list<double>>(_f->binBoundaries(
2245 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), -std::numeric_limits<double>::infinity(),
2246 std::numeric_limits<double>::infinity()));
2247 !_boundaries && _ax->GetNbins() > 0) {
2248#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 24, 00)
2249 Warning(
2250 "Add",
2251 "Adding unbinned function %s to binned %s - will wrap with RooRealSumPdf(RooBinSamplingPdf(...))",
2252 _f->GetName(), GetName());
2253 auto sumPdf = acquireNew<RooRealSumPdf>(TString::Format("%s_pdfWrapper", _f->GetName()), _f->GetTitle(),
2254 *_f, *acquire2<RooAbsArg, RooRealVar>("1", "1", 1), true);
2255 sumPdf->setStringAttribute("alias", _f->getStringAttribute("alias"));
2256 if (!sumPdf->getStringAttribute("alias"))
2257 sumPdf->setStringAttribute("alias", out->GetName());
2258 _f = acquireNew<RooBinSamplingPdf>(TString::Format("%s_binned", _f->GetName()), _f->GetTitle(),
2259 *dynamic_cast<RooAbsRealLValue *>(_ax->GetParent()), *sumPdf);
2260 _f->setStringAttribute("alias", std::dynamic_pointer_cast<RooAbsArg>(out)->getStringAttribute("alias"));
2261 if (!_f->getStringAttribute("alias"))
2262 _f->setStringAttribute("alias", out->GetName());
2263#else
2264 throw std::runtime_error(
2265 "unsupported addition of unbinned function to binned model - please upgrade to at least ROOT 6.24");
2266#endif
2267 }
2268 }
2269
2270 const_cast<RooArgList &>(p->coefList()).add(*acquire2<RooAbsArg, RooRealVar>("1", "1", 1));
2271 const_cast<RooArgList &>(p->funcList()).add(*_f);
2272 // inherit binning if we dont have one yet
2273 if (!p->getStringAttribute("binning"))
2274 p->setStringAttribute("binning", _f->getStringAttribute("binning"));
2275
2276 xRooNode _out(_f, *this);
2277 if (auto gf = p->getStringAttribute("global_factors"); gf) {
2278 TStringToken pattern(gf, ";");
2279 while (pattern.NextToken()) {
2280 auto fac = getObject<RooAbsReal>(pattern.Data());
2281 if (!fac) {
2282 throw std::runtime_error(TString::Format("Could not find global factor %s", pattern.Data()));
2283 }
2284 _out.Multiply(fac);
2285 }
2286 }
2287 sterilize();
2288 // clear children for reload and update shared axis
2289 clear();
2290 fXAxis.reset();
2291 p->setStringAttribute("xvar", nullptr);
2292 browse();
2293 return _out;
2294 }
2295 } else if (auto p2 = get<RooProdPdf>(); p2) {
2296 // can "add" to a RooProdPdf provided trying to add a RooAbsReal not a RooAbsPdf and have a zero or 1
2297 // RooRealSumPdf child.convertForAcquisition(*this); - don't convert here because want generated objects named
2298 // after roorealsumpdf
2299 // would like exception is if child is a factory string! - TODO
2300 if (child.get<RooAbsPdf>() || (!child.get() && getObject<RooAbsPdf>(child.GetName()))) {
2301 // can add if 0 or 1 RooAddPdf ....
2302 RooAddPdf *_pdf = nullptr;
2303 bool tooMany(false);
2304 for (auto &pp : factors()) {
2305 if (auto _p = pp->get<RooAddPdf>(); _p) {
2306 if (_pdf) {
2307 _pdf = nullptr;
2308 tooMany = true;
2309 break;
2310 } // more than one!
2311 _pdf = _p;
2312 }
2313 }
2314 if (_pdf) {
2315 return xRooNode(*_pdf, *this).Add(child);
2316 } else if (!tooMany) {
2317 auto out = this->operator[]("components")->Add(child);
2318 return out;
2319 }
2320 } else if ((child.get<TH1>() || child.get<RooAbsReal>() ||
2321 (!child.get() && getObject<RooAbsReal>(child.GetName()))) &&
2322 !child.get<RooAbsPdf>()) {
2323 RooRealSumPdf *_pdf = nullptr;
2324 RooAddPdf *_backup = nullptr;
2325 bool tooMany(false);
2326 for (auto &pp : factors()) {
2327 if (auto _p = pp->get<RooRealSumPdf>(); _p) {
2328 if (_pdf) {
2329 _pdf = nullptr;
2330 tooMany = true;
2331 break;
2332 } // more than one!
2333 _pdf = _p;
2334 } else if (auto _p2 = pp->get<RooAddPdf>(); _p2) {
2335 _backup = _p2;
2336 for (auto &_pdfa : pp->components()) {
2337 if (auto _p3 = _pdfa->get<RooRealSumPdf>(); _p3) {
2338 if (_pdf) {
2339 _pdf = nullptr;
2340 tooMany = true;
2341 break;
2342 } // more than one!
2343 _pdf = _p3;
2344 }
2345 }
2346 }
2347 }
2348 if (_pdf) {
2349 return xRooNode(*_pdf, *this).Add(child);
2350 } else if (_backup) {
2351 // added *INSIDE* the addPdf -- will create a RooRealSumPdf to hold it
2352 return xRooNode(*_backup, *this).Add(child);
2353 } else if (!tooMany) {
2354 auto out = this->operator[]("samples")->Add(child);
2355 // clear our x-axis to re-evaluate
2356 fXAxis.reset();
2357 p2->setStringAttribute("xvar", nullptr);
2358 return out;
2359 }
2360 }
2361 } else if (auto s = get<RooSimultaneous>(); s) {
2362
2363 // adding to a simultaneous means adding a bin
2364 return bins().Add(child);
2365
2366 // if the child is a RooAbsPdf can just add it as a new channel using name of pdf as the channel name
2367 // if child is a histogram, will create a RooProdPdf
2368
2369 } else if (auto w = get<RooWorkspace>(); w) {
2370 child.convertForAcquisition(
2371 *this, child.get() ? "" : "func" /* if child is a string, allow it to be passed to factory */);
2372 if (child.get()) {
2373 if (auto _d = child.get<RooAbsData>()) {
2374 // don't use acquire method to import, because that adds datasets as Embeddded
2375 if (!w->import(*_d)) {
2376 // should upgrade vars with any obs from the dataset
2377 if (_d->get()) {
2378 std::unique_ptr<RooAbsCollection>(w->allVars().selectCommon(*_d->get()))->setAttribAll("obs");
2379 }
2380 if (_d->getGlobalObservables()) {
2381 std::unique_ptr<RooAbsCollection> globs(w->allVars().selectCommon(*_d->getGlobalObservables()));
2382 globs->setAttribAll("obs");
2383 globs->setAttribAll("global");
2384 }
2385 return xRooNode(child.GetName(), *w->data(child.GetName()), *this);
2386 } else {
2387 throw std::runtime_error(
2388 TString::Format("Could not import dataset %s into workspace %s", child.GetName(), w->GetName())
2389 .Data());
2390 }
2391 } else {
2392 auto out = acquire(child.fComp);
2393 if (out)
2394 return xRooNode(child.GetName(), out, *this);
2395 }
2396 }
2397
2398 if (!child.empty() || child.fFolder == "!pdfs") {
2399 // create a RooSimultaneous using the children as the channels
2400 // children either have "=" in name if specifying channel cat name or otherwise assume
2401 std::string catName = "channelCat";
2402 if (!child.empty()) {
2403 if (TString ss = child.at(0)->GetName(); ss.Contains("=")) {
2404 catName = ss(0, ss.Index('='));
2405 }
2406 }
2407 auto _cat = acquire<RooCategory>(catName.c_str(), catName.c_str());
2408 _cat->setAttribute("obs");
2409 auto out = acquireNew<RooSimultaneous>(child.GetName(), child.GetTitle(), *_cat);
2410 Info("Add", "Created pdf RooSimultaneous::%s in workspace %s", out->GetName(), w->GetName());
2411 return xRooNode(out, *this);
2412 }
2413 } else if (auto coll = get<RooAbsCollection>(); coll && child.get<RooAbsArg>()) {
2414 if (coll->isOwning()) {
2415 coll->addOwned(*static_cast<RooAbsArg *>(child.get<RooAbsArg>()->Clone()));
2416 } else if (child.ws() != ws()) {
2417 coll->add(*static_cast<RooAbsArg *>(acquire(child.fComp).get()));
2418 } else {
2419 coll->add(*child.get<RooAbsArg>());
2420 }
2421 return xRooNode(child.GetName(), *coll->find(child.GetName()), *this);
2422 }
2423
2424 if (sOpt == "pdf") {
2425 // can only add a pdf to a workspace
2426 if (get<RooWorkspace>()) {
2427 const_cast<xRooNode &>(child).fFolder = "!pdfs";
2428 return Add(child);
2429 }
2430 } else if (sOpt == "channel") {
2431 // can add to a model or to a workspace (creates a RooProdPdf either way)
2432 if (get<RooSimultaneous>()) {
2433 return Vary(child);
2434 } else if (get<RooWorkspace>()) {
2435 std::shared_ptr<TObject> out;
2436 child.convertForAcquisition(*this);
2437 if (child.get<RooAbsPdf>()) {
2438 out = acquire(child.fComp);
2439 } else if (!child.fComp) {
2440 out = acquireNew<RooProdPdf>(child.GetName(),
2441 (strlen(child.GetTitle())) ? child.GetTitle() : child.GetName(), RooArgList());
2442 Info("Add", "Created channel RooProdPdf::%s in workspace %s", out->GetName(), get()->GetName());
2443 }
2444 return xRooNode(out, *this);
2445 }
2446 } else if (sOpt == "sample" || sOpt == "func") {
2447 if (get<RooProdPdf>()) {
2448 auto _mainChild = mainChild();
2449 if (_mainChild.get<RooRealSumPdf>()) {
2450 return _mainChild.Add(child, sOpt == "func" ? "func" : "");
2451 } else {
2452 return (*this)["samples"]->Add(child, sOpt == "func" ? "func" : "");
2453 }
2454 }
2455 } else if (sOpt == "dataset") {
2456 if (get<RooWorkspace>()) {
2457 // const_cast<xRooNode&>(child).fFolder = "!datasets";return Add(child);
2458 return (*this).datasets().Add(child);
2459 }
2460 }
2461
2462 if (considerType) {
2463
2464 // interpret 'adding' here as dependent on the object type ...
2465 if (get<RooSimultaneous>()) {
2466 return bins().Add(child);
2467 } else if (TString(child.GetName()).Contains('=')) {
2468 return variations().Add(child);
2469 } else if (get<RooProduct>() || get<RooProdPdf>()) {
2470 return factors().Add(child);
2471 }
2472 }
2473
2474 // Nov 2022 - removed ability to add placeholders ... could bring back if rediscover need for them
2475 // if (!child.get() && child.empty() && strlen(child.GetName())) {
2476 // // can add a 'placeholder' node, note it will be deleted at the next browse
2477 // xRooNode out(child.GetName(),nullptr,*this);
2478 // out.SetTitle(child.GetTitle());
2479 // emplace_back(std::make_shared<xRooNode>(out));
2480 // // update the parent in the out node so that it's copy of the parent knows it has itself in it
2481 // // actually maybe not want this :-/
2482 // //out.fParent = std::make_shared<Node2>(*this);
2483 // for(auto o : *gROOT->GetListOfBrowsers()) {
2484 // if(auto b = dynamic_cast<TBrowser*>(o); b && b->GetBrowserImp()){
2485 // if(auto _b = dynamic_cast<TGFileBrowser*>(
2486 // dynamic_cast<TRootBrowser*>(b->GetBrowserImp())->fActBrowser ); _b) {
2487 // auto _root = _b->fRootDir;
2488 // if (!_root) _root = _b->fListTree->GetFirstItem();
2489 // if (auto item = _b->fListTree->FindItemByObj(_root,this); item) {
2490 // _b->fListTree->AddItem(item,back()->GetName(),back().get());
2491 // }
2492 // }
2493 // }
2494 // }
2495 // return out;
2496 // }
2497
2498 throw std::runtime_error(TString::Format("Cannot add %s to %s", child.GetName(), GetName()));
2499}
2500
2501std::string xRooNode::GetPath() const
2502{
2503 if (!fParent)
2504 return GetName();
2505 return fParent->GetPath() + "/" + GetName();
2506}
2507
2509{
2510 // std::cout << "deleting " << GetPath() << std::endl;
2511}
2512
2514{
2515 if (auto a = get<RooAbsArg>()) {
2516 a->setAttribute("hidden", set);
2517 // if(auto item = GetTreeItem(nullptr); item) {
2518 // if(set) item->SetColor(kRed);
2519 // else item->ClearColor();
2520 // }
2521 }
2522}
2524{
2525 auto a = get<RooAbsArg>();
2526 if (a)
2527 return a->getAttribute("hidden");
2528 return false;
2529}
2530
2531xRooNode xRooNode::Combine(const xRooNode &rhs, bool silent)
2532{
2533
2534 if (get() == rhs.get()) {
2535 // nothing to do because objects are identical
2536 return *this;
2537 }
2538
2539 if (auto lhsa = get<RooAbsArg>(), rhsa = rhs.get<RooAbsArg>(); lhsa && rhsa && lhsa->isIdentical(*rhsa)) {
2540 return *this;
2541 }
2542
2543 if (get<RooWorkspace>() && rhs.get<RooWorkspace>()) {
2544
2545 // report which top-level pdfs will be combined
2546 std::set<std::string> pdfs;
2547 for (auto &c : rhs.components()) {
2548 if ((*this)["pdfs"]->find(c->GetName())) {
2549 pdfs.insert(c->GetName());
2550 }
2551 }
2552 if (pdfs.empty()) {
2553 Warning("Combine", "No pdfs will be combined. Please check and/or rename pdfs to match");
2554 } else {
2555 std::stringstream s;
2556 for (auto &p : pdfs)
2557 s << p << ",";
2558 Info("Combine", "pdfs that will be combined: %s", s.str().c_str());
2559 }
2560
2561 std::set<std::string> _np;
2562 auto mynp = np();
2563 for (auto &c : rhs.np()) {
2564 if (mynp.find(c->GetName())) {
2565 _np.insert(c->GetName());
2566 }
2567 }
2568 if (_np.empty()) {
2569 Warning("Combine", "No correlated np");
2570 } else {
2571 std::stringstream s;
2572 for (auto &p : _np)
2573 s << p << ",";
2574 Info("Combine", "np that will be shared (correlated): %s", s.str().c_str());
2575 }
2576 std::set<std::string> _poi;
2577 auto mypoi = poi();
2578 for (auto &c : rhs.poi()) {
2579 if (mypoi.find(c->GetName())) {
2580 _poi.insert(c->GetName());
2581 }
2582 }
2583 if (_poi.empty()) {
2584 Warning("Combine", "No correlated poi");
2585 } else {
2586 std::stringstream s;
2587 for (auto &p : _poi)
2588 s << p << ",";
2589 Info("Combine", "poi that will be shared (correlated): %s", s.str().c_str());
2590 }
2591
2592 // TODO: Check for derived components that have matching names and aren't top-level pdfs
2593 //
2594 // const auto comps = get<RooWorkspace>()->components();
2595 //
2596 // std::set<std::string> leafs;
2597 //
2598 // for(auto& c : rhs.get<RooWorkspace>()->components()) {
2599 // if(comps.find(c->GetName())) {
2600 //
2601 // }
2602 // }
2603 }
2604
2605 // combine components, factors, and variations ... when there is a name clash will combine on that object
2606 for (auto &c : rhs.components()) {
2607 if (get<RooWorkspace>() &&
2608 (c->fFolder == "!scratch" || c->fFolder == "!sets" || c->fFolder == "!snapshots" || c->fFolder == "!models"))
2609 continue;
2610 if (auto _c = components().find(c->GetName()); _c) {
2611 if (!silent) {
2612 Info("Combine", "Combining %s into %s", c->GetPath().c_str(), _c->GetPath().c_str());
2613 }
2614 _c->Combine(*c, true);
2615 } else {
2616 try {
2617 if (!silent) {
2618 Info("Combine", "Adding %s into %s", c->GetPath().c_str(), GetPath().c_str());
2619 }
2620 Add(*c);
2621 } catch (std::exception &e) {
2622 Warning("Combine", "Could not combine %s into %s", c->GetPath().c_str(), GetPath().c_str());
2623 }
2624 }
2625 }
2626
2627 if (!get<RooWorkspace>()) { // don't combine factors of a workspace
2628 for (auto &f : rhs.factors()) {
2629 if (auto _f = factors().find(f->GetName()); _f) {
2630 if (!silent) {
2631 Info("Combine", "Combining %s into %s", f->GetPath().c_str(), _f->GetPath().c_str());
2632 }
2633 _f->Combine(*f, true);
2634 } else {
2635 if (!silent) {
2636 Info("Combine", "Multiplying %s into %s", f->GetPath().c_str(), GetPath().c_str());
2637 }
2638 Multiply(*f);
2639 }
2640 }
2641 } else {
2642 // todo: go back through components, doing sets, snapshots, models, ....
2643 // do after import of pdfs etc so that can acquire the copies from the workspace
2644 for (auto &c : rhs.components()) {
2645 if (c->fFolder == "!sets") {
2646 if (components().find(c->GetName())) {
2647 Info("Combine", "Extending set %s", c->GetName());
2648 get<RooWorkspace>()->extendSet(c->GetName(), c->get<RooAbsCollection>()->contentsString().c_str());
2649 } else {
2650 Info("Combine", "Defining set %s", c->GetName());
2651 get<RooWorkspace>()->defineSet(c->GetName(), c->get<RooAbsCollection>()->contentsString().c_str());
2652 }
2653 }
2654 }
2655
2656 // also transfer datasets
2657 for (auto &ds : rhs.datasets()) {
2658 if (auto _ds = datasets().find(ds->GetName()); _ds) {
2659 if (!silent) {
2660 Info("Combine", "Combining %s into %s", ds->GetPath().c_str(), _ds->GetPath().c_str());
2661 }
2662 _ds->Add(*ds);
2663 } else {
2664 if (!silent) {
2665 Info("Combine", "Adding %s into %s", ds->GetPath().c_str(), GetPath().c_str());
2666 }
2667 datasets().Add(*ds);
2668 }
2669 }
2670 }
2671
2672 for (auto &v : rhs.variations()) {
2673 if (auto _v = variations().find(v->GetName()); _v) {
2674 if (!silent) {
2675 Info("Combine", "Combining variation %s into %s", v->GetPath().c_str(), _v->GetPath().c_str());
2676 }
2677 _v->Combine(*v, true);
2678 } else {
2679 if (!silent) {
2680 Info("Combine", "Varying %s into %s", v->GetPath().c_str(), GetPath().c_str());
2681 }
2682 Vary(*v);
2683 }
2684 }
2685
2686 if (get<RooSimultaneous>()) {
2687 // combine bins (channels) ... special case, never done silently
2688 for (auto &b : rhs.bins()) {
2689 if (auto _b = bins().find(b->GetName()); _b) {
2690 Info("Combine", "Combining %s into %s", b->GetPath().c_str(), _b->GetPath().c_str());
2691 _b->Combine(*b, true);
2692 } else {
2693 Info("Combine", "Extending with %s into %s", b->GetPath().c_str(), GetPath().c_str());
2694 Vary(*b); // extending channels currently done through Vary method
2695 }
2696 }
2697 }
2698
2699 // todo: Should also transfer over binnings of observables
2700
2701 return *this;
2702}
2703
2704xRooNode xRooNode::shallowCopy(const std::string &name, std::shared_ptr<xRooNode> parent)
2705{
2706 xRooNode out(name.c_str(), nullptr,
2707 parent /*? parent : fParent -- was passing fParent for getObject benefit before fProvider concept*/);
2708 // if(!parent) out.fAcquirer = true;
2709 if (!parent)
2710 out.fProvider = fParent;
2711
2712 auto o = get();
2713 if (!o) {
2714 return out;
2715 }
2716
2717 if (auto s = get<RooSimultaneous>(); s) {
2718 auto chans = bins();
2719 if (!chans.empty()) {
2720 // create a new RooSimultaneous with shallow copies of each channel
2721
2722 std::shared_ptr<RooSimultaneous> pdf = out.acquire<RooSimultaneous>(
2723 name.c_str(), o->GetTitle(), const_cast<RooAbsCategoryLValue &>(s->indexCat()));
2724
2725 for (auto &c : chans) {
2726 TString cName(c->GetName());
2727 cName = cName(cName.Index('=') + 1, cName.Length());
2728 // by passing out as the parent, will ensure out acquires everything created
2729 auto c_copy =
2730 c->shallowCopy(name + "_" + c->get()->GetName(), std::shared_ptr<xRooNode>(&out, [](xRooNode *) {}));
2731 pdf->addPdf(*dynamic_cast<RooAbsPdf *>(c_copy.get()), cName);
2732 }
2733 out.fComp = pdf;
2734 return out;
2735 }
2736 } else if (auto p = dynamic_cast<RooProdPdf *>(o); p) {
2737 // main pdf will be copied too
2738 std::shared_ptr<RooProdPdf> pdf =
2739 std::dynamic_pointer_cast<RooProdPdf>(out.acquire(std::shared_ptr<TObject>(p->Clone(/*name.c_str()*/)), false,
2740 true)); // use clone to copy all attributes etc too
2741 auto main = mainChild();
2742 if (main) {
2743 auto newMain =
2744 std::dynamic_pointer_cast<RooAbsArg>(out.acquire(std::shared_ptr<TObject>(main->Clone()), false, true));
2745 std::cout << newMain << " " << newMain->GetName() << std::endl;
2746 // pdf->replaceServer(*pdf->pdfList().find(main->GetName()), *newMain, true, true);
2747 // const_cast<RooArgList&>(pdf->pdfList()).replace(*pdf->pdfList().find(main->GetName()), *newMain);
2748 pdf->redirectServers(RooArgList(*newMain));
2749 }
2750 out.fComp = pdf;
2751 out.sterilize();
2752 return out;
2753 }
2754
2755 return out;
2756}
2757
2759{
2760 static std::unique_ptr<cout_redirect> capture;
2761 std::string captureStr;
2762 bool doCapture = false;
2763 if (!capture && gROOT->FromPopUp()) { // FromPopUp means user executed from the context menu
2764 capture = std::make_unique<cout_redirect>(captureStr);
2765 doCapture = true;
2766 }
2767
2768 TString sOpt(opt);
2769 int depth = 0;
2770 if (sOpt.Contains("depth=")) {
2771 depth = TString(sOpt(sOpt.Index("depth=") + 6, sOpt.Length())).Atoi();
2772 sOpt.ReplaceAll(TString::Format("depth=%d", depth), "");
2773 }
2774 int indent = 0;
2775 if (sOpt.Contains("indent=")) {
2776 indent = TString(sOpt(sOpt.Index("indent=") + 7, sOpt.Length())).Atoi();
2777 sOpt.ReplaceAll(TString::Format("indent=%d", indent), "");
2778 }
2779 bool _more = sOpt.Contains("m");
2780 if (_more)
2781 sOpt.Replace(sOpt.Index("m"), 1, "");
2782 if (sOpt != "")
2783 _more = true;
2784
2785 if (indent == 0) { // only print self if not indenting (will already be printed above if tree traverse)
2786 std::cout << GetPath();
2787 if (get() && get() != this) {
2788 std::cout << ": ";
2789 if (_more || (get<RooAbsArg>() && get<RooAbsArg>()->isFundamental()) || get<RooConstVar>() ||
2790 get<RooAbsData>() || get<RooProduct>() || get<RooFitResult>()) {
2791 auto _deps = coords(false).argList(); // want to revert coords after print
2792 auto _snap = std::unique_ptr<RooAbsCollection>(_deps.snapshot());
2793 coords(); // move to coords before printing (in case this matters)
2794 get()->Print(sOpt);
2795 if (auto _fr = get<RooFitResult>(); _fr && dynamic_cast<RooStringVar *>(_fr->constPars().find(".log"))) {
2796 std::cout << "Minimization Logs:" << std::endl;
2797 std::cout << dynamic_cast<RooStringVar *>(_fr->constPars().find(".log"))->getVal() << std::endl;
2798 }
2799 _deps.assignValueOnly(*_snap);
2800 // std::cout << std::endl;
2801 } else {
2802 TString _suffix = "";
2803 if (auto _type = GetNodeType(); strlen(_type)) {
2804 // decided not to show const values until figure out how to update if value changes
2805 /*if (TString(_type)=="Const") _name += TString::Format("
2806 [%s=%g]",_type,v->get<RooConstVar>()->getVal()); else*/
2807 _suffix += TString::Format(" [%s]", _type);
2808 }
2809 if (auto fv = get<RooFormulaVar>()) {
2810 TString formu = TString::Format(" [%s]", fv->expression());
2811 for (size_t i = 0; i < fv->dependents().size(); i++) {
2812 formu.ReplaceAll(TString::Format("x[%zu]", i), fv->dependents()[i].GetName());
2813 }
2814 _suffix += formu;
2815 } else if (auto gv = get<RooGenericPdf>()) {
2816 TString formu = TString::Format(" [%s]", gv->expression());
2817 for (size_t i = 0; i < gv->dependents().size(); i++) {
2818 formu.ReplaceAll(TString::Format("x[%zu]", i), gv->dependents()[i].GetName());
2819 }
2820 _suffix += formu;
2821 } else if (auto pi = get<PiecewiseInterpolation>()) {
2822 // check if all interpCodes are the same. Will include in the NodeType
2823 std::set<int> interpCodes;
2824 for (auto &c : pi->interpolationCodes())
2825 interpCodes.insert(c);
2826 if (interpCodes.size() == 1) {
2827 _suffix += TString::Format(" [InterpCode=%d]", *interpCodes.begin());
2828 }
2829 } else if (auto fiv = get<RooStats::HistFactory::FlexibleInterpVar>()) {
2830 // check if all interpCodes are the same.
2831 std::set<int> interpCodes;
2832 for (auto &c : fiv->interpolationCodes())
2833 interpCodes.insert(c == 4 ? 5 : c); // in definition of FlexibleInterpVar 4 gets replaced with 5
2834 if (interpCodes.size() == 1) {
2835 _suffix += TString::Format(" [InterpCode=%d]", *interpCodes.begin());
2836 }
2837 }
2838 std::cout << get()->ClassName() << "::" << get()->GetName() << _suffix.Data() << std::endl;
2839 }
2840
2841 } else if (!get()) {
2842 std::cout << std::endl;
2843 }
2844 }
2845 const_cast<xRooNode *>(this)->browse();
2846 std::vector<std::string> folderNames;
2847 for (auto &k : *this) {
2848 if (std::find(folderNames.begin(), folderNames.end(), k->fFolder) == folderNames.end()) {
2849 folderNames.push_back(k->fFolder);
2850 }
2851 }
2852 for (auto &f : folderNames) {
2853 int i = 0;
2854 int iindent = indent;
2855 if (!f.empty()) {
2856 for (int j = 0; j < indent; j++)
2857 std::cout << " ";
2858 std::cout << f << std::endl;
2859 iindent += 1;
2860 }
2861 for (auto &k : *this) {
2862 if (k->fFolder != f) {
2863 i++;
2864 continue;
2865 }
2866 for (int j = 0; j < iindent; j++)
2867 std::cout << " ";
2868 std::cout << i++ << ") " << k->GetName() << " : ";
2869 if (k->get()) {
2870 if (_more || (k->get<RooAbsArg>() && k->get<RooAbsArg>()->isFundamental()) || k->get<RooConstVar>() ||
2871 k->get<RooAbsData>() /*|| k->get<RooProduct>()*/) {
2872 auto _deps = k->coords(false).argList();
2873 auto _snap = std::unique_ptr<RooAbsCollection>(_deps.snapshot());
2874 k->coords(); // move to coords before printing (in case this matters)
2875 k->get()->Print(sOpt); // assumes finishes with an endl
2876 _deps.assignValueOnly(*_snap);
2877 } else {
2878 TString _suffix = "";
2879 if (auto _type = k->GetNodeType(); strlen(_type)) {
2880 // decided not to show const values until figure out how to update if value changes
2881 /*if (TString(_type)=="Const") _name += TString::Format("
2882 [%s=%g]",_type,v->get<RooConstVar>()->getVal()); else*/
2883 _suffix += TString::Format(" [%s]", _type);
2884 }
2885 if (auto fv = k->get<RooFormulaVar>()) {
2886 TString formu = TString::Format(" [%s]", fv->expression());
2887 for (size_t j = 0; j < fv->dependents().size(); j++) {
2888 formu.ReplaceAll(TString::Format("x[%zu]", j), fv->dependents()[j].GetName());
2889 }
2890 _suffix += formu;
2891 } else if (auto gv = k->get<RooGenericPdf>()) {
2892 TString formu = TString::Format(" [%s]", gv->expression());
2893 for (size_t j = 0; j < gv->dependents().size(); j++) {
2894 formu.ReplaceAll(TString::Format("x[%zu]", j), gv->dependents()[j].GetName());
2895 }
2896 _suffix += formu;
2897 } else if (auto pi = k->get<PiecewiseInterpolation>()) {
2898 // check if all interpCodes are the same. Will include in the NodeType
2899 std::set<int> interpCodes;
2900 for (auto &c : pi->interpolationCodes())
2901 interpCodes.insert(c);
2902 if (interpCodes.size() == 1) {
2903 _suffix += TString::Format(" [InterpCode=%d]", *interpCodes.begin());
2904 }
2905 } else if (auto fiv = k->get<RooStats::HistFactory::FlexibleInterpVar>()) {
2906 // check if all interpCodes are the same.
2907 std::set<int> interpCodes;
2908 for (auto &c : fiv->interpolationCodes())
2909 interpCodes.insert(c == 4 ? 5 : c); // in definition of FlexibleInterpVar 4 gets replaced with 5
2910 if (interpCodes.size() == 1) {
2911 _suffix += TString::Format(" [InterpCode=%d]", *interpCodes.begin());
2912 }
2913 }
2914 std::cout << k->get()->ClassName() << "::" << k->get()->GetName() << _suffix.Data() << std::endl;
2915 }
2916 if (depth != 0) {
2917 k->Print(sOpt + TString::Format("depth=%dindent=%d", depth - 1, iindent + 1));
2918 }
2919 } else
2920 std::cout << " NULL " << std::endl;
2921 }
2922 }
2923 if (doCapture) {
2924 capture.reset(); // no captureStr has the string to display
2925 // inject line breaks to avoid msgbox being too wide
2926 size_t lastBreak = 0;
2927 std::string captureStrWithBreaks;
2928 for (size_t i = 0; i < captureStr.size(); i++) {
2929 captureStrWithBreaks += captureStr[i];
2930 if (captureStr[i] == '\n') {
2931 lastBreak = i;
2932 }
2933 if (i - lastBreak > 150) {
2934 captureStrWithBreaks += '\n';
2935 lastBreak = i;
2936 }
2937 }
2938 const TGWindow *w =
2939 (gROOT->GetListOfBrowsers()->At(0))
2940 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
2941 : gClient->GetRoot();
2942 new TGMsgBox(gClient->GetRoot(), w, GetName(),
2943 captureStrWithBreaks.c_str()); //,nullptr,kMBDismiss,nullptr,kVerticalFrame,kTextLeft|kTextCenterY);
2944 }
2945}
2946
2948{
2949 if (!child.get()) {
2950
2951 if (auto v = get<RooRealVar>(); v) {
2952
2953 TString constrType = child.GetName();
2954 double mean = std::numeric_limits<double>::quiet_NaN();
2955 double sigma = mean;
2956 if (constrType.BeginsWith("gaussian(")) {
2957 // extract the mean and stddev parameters
2958 // if only one given, it is the stddev
2959 if (constrType.Contains(",")) {
2960 mean = TString(constrType(9, constrType.Index(',') - 9)).Atof();
2961 sigma = TString(constrType(constrType.Index(',') + 1, constrType.Index(')') - constrType.Index(',') + 1))
2962 .Atof();
2963 } else {
2964 mean = std::numeric_limits<double>::quiet_NaN(); // will use the var current value below to set mean
2965 sigma = TString(constrType(9, constrType.Index(')') - 9)).Atof();
2966 }
2967 constrType = "normal";
2968 } else if (constrType == "normal") {
2969 mean = 0;
2970 sigma = 1;
2971 } else if (constrType == "gaussian") {
2972 // extract parameters from the variable
2973 // use current value and error on v as constraint
2974 if (!v->hasError())
2975 throw std::runtime_error("No error on parameter for gaussian constraint");
2976 sigma = v->getError();
2977 mean = v->getVal();
2978 constrType = "normal";
2979 } else if (constrType == "poisson") {
2980 if (!v->hasError())
2981 throw std::runtime_error("No error on parameter for poisson constraint");
2982 mean = 1;
2983 sigma = pow(v->getVal() / v->getError(), 2);
2984 }
2985
2986 if (constrType == "poisson") {
2987 // use current value and error on v as constraint
2988 double tau_val = sigma;
2989 auto globs = acquire<RooRealVar>(Form("globs_%s", v->GetName()), Form("globs_%s", v->GetName()),
2990 v->getVal() * tau_val, (v->getVal() - 5 * v->getError()) * tau_val,
2991 (v->getVal() + 5 * v->getError()) * tau_val);
2992 globs->setConstant();
2993 globs->setAttribute("obs");
2994 globs->setAttribute("global");
2995 globs->setStringAttribute("nominal", TString::Format("%f", tau_val));
2996 auto tau = acquireNew<RooConstVar>(TString::Format("tau_%s", v->GetName()), "", tau_val);
2997 auto constr = acquireNew<RooPoisson>(
2998 Form("pois_%s", v->GetName()), TString::Format("Poisson Constraint of %s", v->GetTitle()), *globs,
2999 *acquireNew<RooProduct>(TString::Format("mean_%s", v->GetName()),
3000 TString::Format("Poisson Constraint of %s", globs->GetTitle()),
3001 RooArgList(*v, *tau)),
3002 true /* no rounding */);
3003
3004 auto out = Constrain(xRooNode(Form("pois_%s", GetName()), constr));
3005 if (!v->hasError())
3006 v->setError(mean / sqrt(tau_val)); // if v doesnt have an uncert, will put one on it now
3007 Info("Constrain", "Added poisson constraint pdf RooPoisson::%s (tau=%g) for %s", out->GetName(), tau_val,
3008 GetName());
3009 return out;
3010 } else if (constrType == "normal") {
3011
3012 auto globs = acquire<RooRealVar>(Form("globs_%s", v->GetName()), Form("globs_%s", v->GetName()), mean,
3013 mean - 10 * sigma, mean + 10 * sigma);
3014 globs->setAttribute("obs");
3015 globs->setAttribute("global");
3016 globs->setConstant();
3017
3018 globs->setStringAttribute("nominal", TString::Format("%f", mean));
3019 auto constr = acquireNew<RooGaussian>(
3020 Form("gaus_%s", v->GetName()), TString::Format("Gaussian Constraint of %s", v->GetTitle()), *globs, *v,
3021 *acquireNew<RooConstVar>(TString::Format("sigma_%s", v->GetName()), "", sigma));
3022 auto out = Constrain(xRooNode(Form("gaus_%s", GetName()), constr));
3023 if (!v->hasError())
3024 v->setError(sigma); // if v doesnt have an uncert, will put one on it now
3025 Info("Constrain", "Added gaussian constraint pdf RooGaussian::%s (mean=%g,sigma=%g) for %s", out->GetName(),
3026 mean, sigma, GetName());
3027 return out;
3028 }
3029 }
3030 } else if (auto p = child.get<RooAbsPdf>(); p) {
3031
3032 auto _me = get<RooAbsArg>();
3033 if (!_me) {
3034 throw std::runtime_error("Cannot constrain non arg");
3035 }
3036
3037 if (!p->dependsOn(*_me)) {
3038 throw std::runtime_error("Constraint does not depend on constrainee");
3039 }
3040
3041 // find a parent that can swallow this pdf ... either a RooProdPdf or a RooWorkspace
3042 auto x = fParent;
3043 while (x && !x->get<RooProdPdf>() && !x->get<RooSimultaneous>() && !x->get<RooWorkspace>()) {
3044 x = x->fParent;
3045 }
3046 if (!x) {
3047 throw std::runtime_error("Nowhere to put constraint");
3048 }
3049 // get datasets of the swallower, and add glob to any globs lists
3050 auto childGlobs = child.globs();
3051 if (!childGlobs.empty()) {
3052 for (auto d : x->datasets()) {
3053 if (auto globs = d->get<RooAbsData>()->getGlobalObservables()) {
3054 RooArgSet newGlobs(*globs);
3055 newGlobs.add(*childGlobs.get<RooArgList>());
3056 d->get<RooAbsData>()->setGlobalObservables(newGlobs);
3057 }
3058 }
3059 // also add to the workspaces globalObservables lists
3060 if (x->ws()) {
3061 for (auto &[k, v] : GETWSSETS(x->ws())) {
3062 if (k == "globalObservables" || TString(k).EndsWith("_GlobalObservables")) {
3063 const_cast<RooArgSet &>(v).add(*childGlobs.get<RooArgList>());
3064 }
3065 }
3066 }
3067 }
3068 if (auto s = x->get<RooSimultaneous>(); s) {
3069 // put into every channel that features parameter
3070 x->browse();
3071 for (auto &c : *x) {
3072 if (auto a = c->get<RooAbsArg>(); a->dependsOn(*_me))
3073 c->Multiply(child);
3074 }
3075 return child;
3076 } else if (x->get<RooProdPdf>()) {
3077 return x->Multiply(child);
3078 } else {
3079 return x->Add(child, "+");
3080 }
3081 }
3082
3083 throw std::runtime_error(TString::Format("Cannot constrain %s", GetName()));
3084}
3085
3087{
3088
3089 class AutoUpdater {
3090 public:
3091 AutoUpdater(xRooNode &_n) : n(_n) {}
3092 ~AutoUpdater() { n.browse(); }
3093 xRooNode &n;
3094 };
3095 AutoUpdater xxx(*this);
3096
3097 if (fBinNumber != -1) {
3098 // scaling a bin ...
3099 if (child.get<RooAbsReal>()) { // if not child then let fall through to create a child and call self again below
3100 // doing a bin-multiplication .. the parent should have a ParamHistFunc called binFactors
3101 // if it doesn't then create one
3102 auto o = std::dynamic_pointer_cast<RooAbsReal>(acquire(child.fComp));
3103
3104 // get binFactor unless parent is a ParamHistFunc already ...
3105
3106 auto binFactors = (fParent->get<ParamHistFunc>()) ? fParent : fParent->factors().find("binFactors");
3107
3108 // it can happen in a loop over bins() that another node has moved fParent inside a product
3109 // so check for fParent having a client with the ORIGNAME:<name> attribute
3110 if (!binFactors && fParent->get<RooAbsArg>()) {
3111 for (auto c : fParent->get<RooAbsArg>()->clients()) {
3112 if (c->IsA() == RooProduct::Class() &&
3113 c->getAttribute(TString::Format("ORIGNAME:%s", fParent->get()->GetName()))) {
3114 // try getting binFactors out of this
3115 binFactors = xRooNode(*c).factors().find("binFactors");
3116 break;
3117 }
3118 }
3119 }
3120
3121 if (!binFactors) {
3122 fParent
3123 ->Multiply(TString::Format("%s_binFactors",
3124 (fParent->mainChild().get())
3125 ? fParent->mainChild()->GetName()
3126 : (fParent->get() ? fParent->get()->GetName() : fParent->GetName()))
3127 .Data(),
3128 "blankshape")
3129 .SetName("binFactors"); // creates ParamHistFunc with all pars = 1 (shared const)
3130 binFactors = fParent->factors().find("binFactors");
3131 if (!binFactors) {
3132 throw std::runtime_error(
3133 TString::Format("Could not create binFactors in parent %s", fParent->GetName()));
3134 }
3135 // auto phf = binFactors->get<ParamHistFunc>();
3136
3137 // create RooProducts for all the bins ... so that added factors don't affect selves
3138 int i = 1;
3139 for (auto &b : binFactors->bins()) {
3140 auto p = acquireNew<RooProduct>(TString::Format("%s_bin%d", binFactors->get()->GetName(), i),
3141 TString::Format("binFactors of bin %d", i), RooArgList());
3142 p->setStringAttribute("alias", TString::Format("%s=%g", binFactors->GetXaxis()->GetParent()->GetName(),
3143 binFactors->GetXaxis()->GetBinCenter(i)));
3144 b->Multiply(*p);
3145 i++;
3146 }
3147 }
3148 // then scale the relevant bin ... if the relevant bin is a "1" then just drop in our factor (inside a
3149 // RooProduct though, to avoid it getting modified by subsequent multiplies)
3150 auto _bin = binFactors->bins().at(fBinNumber - 1);
3151 if (auto phf = binFactors->get<ParamHistFunc>(); phf && _bin) {
3152#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3153 RooArgList &pSet = phf->_paramSet;
3154#else
3155 RooArgList &pSet = const_cast<RooArgList &>(phf->paramList());
3156#endif
3157 if (strcmp(_bin->GetName(), "1") == 0) {
3158 RooArgList all;
3159 for (std::size_t i = 0; i < pSet.size(); i++) {
3160 if (int(i) != fBinNumber - 1) {
3161 all.add(*pSet.at(i));
3162 } else {
3163 all.add(*o);
3164 }
3165 }
3166 pSet.removeAll();
3167 pSet.add(all);
3168 } else {
3169 _bin->fBinNumber = -1; // to avoid infinite loop
3170 return _bin->Multiply(child, opt);
3171 }
3172 // } else {else if(_bin->get<RooProduct>()) {
3173 // // multiply the element which will just add it as a factor in the rooproduct
3174 // return _bin->Multiply(child,opt);
3175 // } else {
3176 // // not a rooproduct in this bin yet ... so need to replace with a rooproduct and
3177 // multiply that
3178 // // this avoids the undesired behaviour of shared binFactors getting all impacted by
3179 // mulitplies RooArgList all; auto new_p =
3180 // acquireNew<RooProduct>(TString::Format("%s_bin%d",binFactors->get()->GetName(),fBinNumber),TString::Format("binFactors
3181 // of bin %d",fBinNumber),RooArgList(*_bin->get<RooAbsArg>()));
3182 // new_p->setStringAttribute("alias","")
3183 // for (int i = 0; i < phf->_paramSet.size(); i++) {
3184 // if (i != fBinNumber - 1) all.add(*phf->_paramSet.at(i));
3185 // else all.add(*new_p);
3186 // }
3187 // phf->_paramSet.removeAll();
3188 // phf->_paramSet.add(all);
3189 // // now multiply that bin having converted it to RooProduct
3190 // return binFactors->bins().at(fBinNumber - 1)->Multiply(child,opt);
3191 // }
3192 }
3193 return xRooNode(*o, binFactors);
3194 }
3195 } else if (!get() && fParent) {
3196 // try to 'create' object based on parentage
3197 // add child as a temporary child to help with decision making
3198 auto _ref = emplace_back(std::shared_ptr<xRooNode>(&const_cast<xRooNode &>(child), [](TObject *) {}));
3199 try {
3200 fComp = fParent->Add(*this, "+").fComp;
3201 } catch (...) {
3202 resize(size() - 1);
3203 std::rethrow_exception(std::current_exception());
3204 }
3205 resize(size() - 1); // remove the temporarily added node
3206 }
3207
3208 if (!child.get()) {
3209 TString sOpt(opt);
3210 sOpt.ToLower();
3211 if (auto o = getObject<RooAbsReal>(child.GetName())) {
3212 auto out = Multiply(xRooNode(o, child.fParent));
3213 // have to protect bin case where get() is null (could change but then must change logic above too)
3214 if (get()) {
3215 Info("Multiply", "Scaled %s by existing factor %s::%s",
3216 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), o->ClassName(), o->GetName());
3217 }
3218 return out;
3219 } else if (sOpt == "const") {
3220 auto out = Multiply(RooConstVar(child.GetName(), child.GetTitle(), 1));
3221 if (get()) {
3222 Info("Multiply", "Scaled %s by new const factor %s",
3223 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName());
3224 }
3225 return out;
3226 } else if (sOpt == "norm") {
3227 if (TString(child.GetName()).Contains("[") && ws()) {
3228 // assume factory method wanted
3229 auto arg = ws()->factory(child.GetName());
3230 if (arg) {
3231 auto out = Multiply(*arg);
3232 if (get()) {
3233 Info("Multiply", "Scaled %s by new norm factor %s",
3234 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName());
3235 }
3236 return out;
3237 }
3238 throw std::runtime_error(TString::Format("Failed to create new normFactor %s", child.GetName()));
3239 }
3240 auto out = Multiply(RooRealVar(child.GetName(), child.GetTitle(), 1, -1e-5, 100));
3241 if (get()) {
3242 Info("Multiply", "Scaled %s by new norm factor %s",
3243 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName());
3244 }
3245 return out;
3246 } else if (sOpt == "shape" || sOpt == "simple" || sOpt == "blankshape") {
3247 // needs axis defined
3248 if (auto ax = GetXaxis(); ax) {
3249 auto h = std::shared_ptr<TH1>(BuildHistogram(dynamic_cast<RooAbsLValue *>(ax->GetParent()), true));
3250 h->Reset();
3251 for (int i = 1; i <= h->GetNbinsX(); i++) {
3252 h->SetBinContent(i, 1);
3253 }
3254 h->SetMinimum(0);
3255 h->SetMaximum(100);
3256 h->SetName(TString::Format(";%s", child.GetName())); // ; char indicates don't "rename" this thing
3257 h->SetTitle(child.GetTitle());
3258 if (sOpt.Contains("shape"))
3259 h->SetOption(sOpt);
3260 auto out = Multiply(*h);
3261 if (get()) {
3262 Info("Multiply", "Scaled %s by new %s factor %s",
3263 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), sOpt.Data(), out->GetName());
3264 }
3265 return out;
3266 }
3267 } else if (sOpt == "overall") {
3268 auto out = Multiply(acquireNew<RooStats::HistFactory::FlexibleInterpVar>(
3269 child.GetName(), child.GetTitle(), RooArgList(), 1, std::vector<double>(), std::vector<double>()));
3270 if (get() /* can happen this is null if on a bin node with no shapeFactors*/) {
3271 Info("Multiply", "Scaled %s by new overall factor %s",
3272 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName());
3273 }
3274 return out;
3275 } else if (sOpt == "func" && ws()) {
3276 // need to get way to get dependencies .. can't pass all as causes circular dependencies issues.
3277 if (auto arg = ws()->factory(TString("expr::") + child.GetName())) {
3278 auto out = Multiply(*arg);
3279 if (get() /* can happen this is null if on a bin node with no shapeFactors*/) {
3280 Info("Multiply", "Scaled %s by new func factor %s",
3281 mainChild().get() ? mainChild().get()->GetName() : get()->GetName(), out->GetName());
3282 }
3283 return out;
3284 }
3285 }
3286 }
3287 if (auto h = child.get<TH1>(); h && strlen(h->GetOption()) == 0 && strlen(opt) > 0) {
3288 // put the option in the hist
3289 h->SetOption(opt);
3290 }
3291 if (auto w = get<RooWorkspace>(); w) {
3292 // just acquire
3293 std::shared_ptr<TObject> out;
3294 child.convertForAcquisition(*this);
3295 if (child.get<RooAbsReal>())
3296 out = acquire(child.fComp);
3297 return out;
3298 }
3299
3300 if (strcmp(GetName(), ".coef") == 0) { // covers both .coef and .coefs
3301 // need to add this into the relevant coef ... if its not a RooProduct, replace it with one first
3302 if (auto p = fParent->fParent->get<RooAddPdf>()) {
3303 // may be in no-coef mode ... in which case must create coefs (use "ExtendedBindings" but note that these need
3304 // obs list passing to them
3305 if (p->coefList().empty() && !p->pdfList().empty()) {
3306 for (auto _pdf : p->pdfList()) {
3307 const_cast<RooArgList &>(p->coefList())
3308 .add(*acquireNew<RooExtendedBinding>(TString::Format("%s_extBind", _pdf->GetName()),
3309 TString::Format("Expected Events of %s", _pdf->GetTitle()),
3310 *static_cast<RooAbsPdf *>(_pdf)));
3311 }
3312 Info("Multiply", "Created RooExtendedBinding coefficients for all pdfs of %s so that can multiply coef",
3313 p->GetName());
3314 *reinterpret_cast<bool *>(reinterpret_cast<unsigned char *>(p) +
3315 p->Class()->GetDataMemberOffset("_allExtendable")) = false;
3316 *reinterpret_cast<bool *>(reinterpret_cast<unsigned char *>(p) +
3317 p->Class()->GetDataMemberOffset("_haveLastCoef")) = true;
3318 }
3319 for (size_t i = 0; i < p->pdfList().size(); i++) {
3320 if (p->pdfList().at(i) == fParent->get<RooAbsArg>()) {
3321 auto coefs = p->coefList().at(i);
3322 if (!coefs->InheritsFrom("RooProduct")) {
3323 RooArgList oldCoef;
3324 if (!(strcmp(coefs->GetName(), "1") == 0 || strcmp(coefs->GetName(), "ONE") == 0))
3325 oldCoef.add(*coefs);
3326 auto newCoefs = fParent->acquireNew<RooProduct>(
3327 TString::Format("coefs_%s", fParent->GetName()),
3328 TString::Format("coefficients for %s", fParent->GetName()), oldCoef);
3329 RooArgList oldCoefs;
3330 for (size_t j = 0; j < p->coefList().size(); j++) {
3331 if (i == j) {
3332 oldCoefs.add(*newCoefs);
3333 } else {
3334 oldCoefs.add(*p->coefList().at(j));
3335 }
3336 }
3337 const_cast<RooArgList &>(p->coefList()).removeAll();
3338 const_cast<RooArgList &>(p->coefList()).add(oldCoefs);
3339 coefs = newCoefs.get();
3340 }
3341 return xRooNode(*coefs, fParent).Multiply(child);
3342 }
3343 }
3344 } else if (auto p2 = fParent->fParent->get<RooRealSumPdf>()) {
3345 // find our function in the funcList, and then update the coefs of it
3346
3347 for (size_t i = 0; i < p2->funcList().size(); i++) {
3348 if (p2->funcList().at(i) == fParent->get<RooAbsArg>()) {
3349 auto coefs = p2->coefList().at(i);
3350 if (!coefs->InheritsFrom("RooProduct")) {
3351 RooArgList oldCoef;
3352 if (!(strcmp(coefs->GetName(), "1") == 0 || strcmp(coefs->GetName(), "ONE") == 0))
3353 oldCoef.add(*coefs);
3354 auto newCoefs = fParent->acquireNew<RooProduct>(
3355 TString::Format("coefs_%s", fParent->GetName()),
3356 TString::Format("coefficients for %s", fParent->GetName()), oldCoef);
3357 RooArgList oldCoefs;
3358 for (size_t j = 0; j < p2->coefList().size(); j++) {
3359 if (i == j) {
3360 oldCoefs.add(*newCoefs);
3361 } else {
3362 oldCoefs.add(*p2->coefList().at(j));
3363 }
3364 }
3365 const_cast<RooArgList &>(p2->coefList()).removeAll();
3366 const_cast<RooArgList &>(p2->coefList()).add(oldCoefs);
3367 coefs = newCoefs.get();
3368 }
3369 return xRooNode(*coefs, fParent).Multiply(child);
3370 }
3371 }
3372 }
3373 throw std::runtime_error("this coefs case is not supported");
3374 }
3375
3376 if (auto p = get<RooProduct>(); p) {
3377 std::shared_ptr<TObject> out;
3378 auto cc = child.fComp;
3379 bool isConverted = (child.convertForAcquisition(*this) != cc);
3380 if (child.get<RooAbsReal>())
3381 out = acquire(child.fComp);
3382
3383 // child may be a histfunc or a rooproduct of a histfunc and a paramhist if has stat errors
3384 if (auto _f = std::dynamic_pointer_cast<RooHistFunc>(
3385 (child.get<RooProduct>()) ? child.factors()[child.GetName()]->fComp : out);
3386 _f && _f->getAttribute("autodensity")) {
3387 // should we flag this as a density? yes if there's no other term marked as the density
3388 bool hasDensity = false;
3389 for (auto &f : factors()) {
3390 if (f->get<RooAbsArg>()->getAttribute("density")) {
3391 hasDensity = true;
3392 break;
3393 }
3394 }
3395 _f->setAttribute("density", !hasDensity && fParent && fParent->get<RooRealSumPdf>());
3396 if (_f->getAttribute("density")) {
3397
3398 // need to divide by bin widths first
3399 for (int i = 0; i < _f->dataHist().numEntries(); i++) {
3400 auto bin_pars = _f->dataHist().get(i);
3401 _f->dataHist().set(*bin_pars, _f->dataHist().weight(i) / _f->dataHist().binVolume(*bin_pars));
3402 }
3403 _f->setValueDirty();
3404
3405 // promote the axis vars to observables
3406 for (auto &x : xRooNode("tmp", _f).vars()) {
3407 x->get<RooAbsArg>()->setAttribute("obs");
3408 }
3409 }
3410 _f->setAttribute("autodensity", false);
3411 }
3412
3413 if (isConverted && child.get<RooHistFunc>()) {
3414 Info("Multiply", "Created %s factor %s in %s",
3415 child.get<RooAbsArg>()->getAttribute("density") ? "SimpleDensity" : "Simple", child->GetName(),
3416 p->GetName());
3417 } else if (isConverted && child.get<ParamHistFunc>()) {
3418 Info("Multiply", "Created Shape factor %s in %s", child->GetName(), p->GetName());
3419 }
3420
3421 if (auto _f = std::dynamic_pointer_cast<RooAbsReal>(out); _f) {
3422#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3423 p->_compRSet.add(*_f);
3424#else
3425 const_cast<RooArgList &>(p->realComponents()).add(*_f);
3426#endif
3427 p->setValueDirty();
3428
3429 browse();
3430 xRooNode _out(_f, *this);
3431 for (auto &_par : _out.pars()) {
3432 if (auto s = _par->get<RooAbsArg>()->getStringAttribute("boundConstraint"); s) {
3433 bool found = false;
3434 for (auto &_constr : _par->constraints()) {
3435 if (strcmp(s, _constr->get()->GetName()) == 0) {
3436 // constraint is already included
3437 found = true;
3438 break;
3439 }
3440 }
3441 if (!found) {
3442 Info("Multiply", "Pulling in %s boundConstraint: %s", _par->GetName(), s);
3443 auto _pdf = getObject<RooAbsPdf>(s);
3444 if (!_pdf) {
3445 throw std::runtime_error("Couldn't find boundConstraint");
3446 }
3447 _par->Constrain(_pdf);
3448 }
3449 }
3450 }
3451 sterilize();
3452 return _out;
3453 }
3454 } else if (auto p2 = get<RooProdPdf>(); p2) {
3455
3456 std::shared_ptr<TObject> out;
3457 child.convertForAcquisition(*this);
3458 if (child.get<RooAbsPdf>()) {
3459 out = acquire(child.fComp);
3460 } else if (child.get<RooAbsReal>() && mainChild().get<RooRealSumPdf>()) {
3461 // cannot multiply a RooProdPdf by a non pdf
3462 throw std::runtime_error(TString::Format("Cannot multiply %s by non-pdf %s", GetName(), child.GetName()));
3463 // return mainChild().Add(child); - nov 2022 - used to do this but now replaced with exception above
3464 } else if (!child.get() || child.get<RooAbsReal>()) {
3465 // need to create or hide inside a sumpdf or rooadpdf
3466 std::shared_ptr<RooAbsPdf> _pdf;
3467 if (!child.get() && strcmp(child.GetName(), "components") == 0) {
3468 auto _sumpdf = acquireNew<RooAddPdf>(
3469 Form("%s_%s", p2->GetName(), child.GetName()),
3470 (strlen(child.GetTitle()) && strcmp(child.GetTitle(), child.GetName())) ? child.GetTitle()
3471 : p2->GetTitle(),
3472 RooArgList() /*, RooArgList() forces coef-mode if we specify this list */);
3473 _pdf = _sumpdf;
3474 } else {
3475 auto _sumpdf = acquireNew<RooRealSumPdf>(
3476 Form("%s_%s", p2->GetName(), child.GetName()),
3477 (strlen(child.GetTitle()) && strcmp(child.GetTitle(), child.GetName())) ? child.GetTitle()
3478 : p2->GetTitle(),
3479 RooArgList(), RooArgList(), true);
3480 _sumpdf->setFloor(true);
3481 _pdf = _sumpdf;
3482 }
3483 _pdf->setStringAttribute("alias", child.GetName());
3484 // transfer axis attributes if present (TODO: should GetXaxis look beyond the immediate parent?)
3485 _pdf->setStringAttribute("xvar", p2->getStringAttribute("xvar"));
3486 _pdf->setStringAttribute("binning", p2->getStringAttribute("binning"));
3487 out = _pdf;
3488 Info("Multiply", "Created %s::%s in channel %s", _pdf->ClassName(), _pdf->GetName(), p2->GetName());
3489 if (child.get<RooAbsReal>())
3490 xRooNode(*out, *this).Add(child);
3491 }
3492
3493 if (auto _pdf = std::dynamic_pointer_cast<RooAbsPdf>(out); _pdf) {
3494#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3495 const_cast<RooArgList &>(p2->pdfList()).add(*_pdf);
3496#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
3497 p2->_pdfNSetList.emplace_back(std::make_unique<RooArgSet>("nset"));
3498#else
3499 p->_pdfNSetList.Add(new RooArgSet("nset"));
3500#endif
3501 if (!p2->canBeExtended() && _pdf->canBeExtended()) {
3502 p2->_extendedIndex = p2->_pdfList.size() - 1;
3503 }
3504#else
3505 p2->addPdfs(RooArgSet(*_pdf));
3506#endif
3507 sterilize();
3508 browse();
3509 return xRooNode(_pdf, *this);
3510 }
3511 } else if (auto p3 = get<RooRealSumPdf>(); p3) {
3512 // multiplying all current and future components
3513 std::shared_ptr<TObject> out;
3514 child.convertForAcquisition(*this);
3515 if (child.get<RooAbsReal>()) {
3516 out = acquire(child.fComp);
3517 for (auto &c : components()) {
3518 c->Multiply(out);
3519 }
3520 TString s = p3->getStringAttribute("global_factors");
3521 if (s != "")
3522 s += ";";
3523 s += out->GetName();
3524 p3->setStringAttribute("global_factors", s);
3525 Info(
3526 "Multiply",
3527 "Flagged %s as a global factor in channel %s (is applied to all current and future samples in the channel)",
3528 out->GetName(), p3->GetName());
3529 return xRooNode(out, *this);
3530 }
3531
3532 } else if (auto p4 = get<RooAbsPdf>(); p4 && !(fParent && fParent->get<RooRealSumPdf>())) {
3533 // multiply the coefs (if this isn't part of a RooAddPdf or RooRealSumPdf then we will eventually throw exception
3534 return coefs().Multiply(child);
3535 } else if (auto p5 = get<RooAbsReal>(); p5 && (!get<RooAbsPdf>() || (fParent && fParent->get<RooRealSumPdf>()))) {
3536 // replace this obj with a RooProduct to allow for multiplication
3537
3538 // get the list of clients BEFORE creating the new interpolation ... seems list of clients is inaccurate after
3539 std::set<RooAbsArg *> cl;
3540 for (auto &arg : p5->clients()) {
3541 cl.insert(arg);
3542 }
3543
3544 // if multiple clients, see if only one client is in parentage route
3545 // if so, then assume thats the only client we should replace in
3546 if (cl.size() > 1) {
3547 if (cl.count(fParent->get<RooAbsArg>()) > 0) {
3548 cl.clear();
3549 cl.insert(fParent->get<RooAbsArg>());
3550 } else {
3551 Warning("Multiply", "Scaling %s that has multiple clients", p5->GetName());
3552 }
3553 }
3554
3555 auto new_p = acquireNew<RooProduct>(TString::Format("prod_%s", p5->GetName()), p5->GetTitle(), RooArgList(*p5));
3556 // copy attributes over
3557 for (auto &a : p5->attributes())
3558 new_p->setAttribute(a.c_str());
3559 for (auto &a : p5->stringAttributes())
3560 new_p->setStringAttribute(a.first.c_str(), a.second.c_str());
3561 if (!new_p->getStringAttribute("alias"))
3562 new_p->setStringAttribute("alias", p5->GetName());
3563 auto old_p = p5;
3564 new_p->setAttribute(Form("ORIGNAME:%s", old_p->GetName())); // used in redirectServers to say what this replaces
3565 for (auto arg : cl) {
3566 arg->redirectServers(RooArgSet(*new_p), false, true);
3567 }
3568
3569 fComp = new_p;
3570 return Multiply(child);
3571 }
3572
3573 // before giving up here, assume user wanted a norm factor type if child is just a name
3574 if (!child.get() && strlen(opt) == 0)
3575 return Multiply(child, "norm");
3576
3577 throw std::runtime_error(
3578 TString::Format("Cannot multiply %s by %s%s", GetPath().c_str(), child.GetName(),
3579 (!child.get() && strlen(opt) == 0) ? " (forgot to specify factor type?)" : ""));
3580}
3581
3583{
3584
3585 auto p5 = get<RooAbsArg>();
3586 if (!p5) {
3587 throw std::runtime_error("Only replacement of RooAbsArg is supported");
3588 }
3589 node.convertForAcquisition(*this, "func");
3590
3591 auto new_p = node.get<RooAbsArg>();
3592 if (!new_p) {
3593 throw std::runtime_error(TString::Format("Cannot replace with %s", node.GetName()));
3594 }
3595 auto out = acquire(node.fComp);
3596 new_p = std::dynamic_pointer_cast<RooAbsArg>(out).get();
3597
3598 std::set<RooAbsArg *> cl;
3599 for (auto &arg : p5->clients()) {
3600 if (arg == new_p)
3601 continue; // do not replace in self ... although redirectServers will prevent that anyway
3602 cl.insert(arg);
3603 }
3604
3605 // if multiple clients, see if only one client is in parentage route
3606 // if so, then assume thats the only client we should replace in
3607 if (cl.size() > 1) {
3608 if (fParent && fParent->get<RooAbsArg>() && cl.count(fParent->get<RooAbsArg>()) > 0) {
3609 cl.clear();
3610 cl.insert(fParent->get<RooAbsArg>());
3611 } else {
3612 std::stringstream clientList;
3613 for (auto c : cl)
3614 clientList << c->GetName() << ",";
3615 Warning("Replace", "Replacing %s in all clients: %s", p5->GetName(), clientList.str().c_str());
3616 }
3617 }
3618
3619 new_p->setAttribute(Form("ORIGNAME:%s", p5->GetName())); // used in redirectServers to say what this replaces
3620 for (auto arg : cl) {
3621 // if RooFormulaVar need to ensure the internal formula has been "constructed" otherwise will try to construct
3622 // it from the original expression that may have old parameter in it.
3623 if (auto p = dynamic_cast<RooFormulaVar *>(arg))
3624 p->ok(); // triggers creation of RooFormula
3625 arg->redirectServers(RooArgSet(*new_p), false, true);
3626 }
3627 return node;
3628}
3629
3631{
3632
3633 class AutoUpdater {
3634 public:
3635 AutoUpdater(xRooNode &_n) : n(_n) {}
3636 ~AutoUpdater() { n.browse(); }
3637 xRooNode &n;
3638 };
3639 AutoUpdater xxx(*this);
3640
3641 if (!get() && fParent) {
3642 // try to 'create' object based on parentage
3643 // add child as a temporary child to help with decision making
3644 auto _ref = emplace_back(std::shared_ptr<xRooNode>(&const_cast<xRooNode &>(child), [](TObject *) {}));
3645 try {
3646 fComp = fParent->Add(*this, "+").fComp;
3647 } catch (...) {
3648 resize(size() - 1);
3649 std::rethrow_exception(std::current_exception());
3650 }
3651 resize(size() - 1); // remove the temporarily added node
3652 }
3653
3654 if (auto p = mainChild(); p) {
3655 // variations applied to the main child if has one
3656 return p.Vary(child);
3657 }
3658
3659 if (auto s = get<RooSimultaneous>(); s && s->indexCat().IsA() == RooCategory::Class()) {
3660 // name is used as cat label
3661 std::string label = child.GetName();
3662 if (auto pos = label.find('='); pos != std::string::npos)
3663 label = label.substr(pos + 1);
3664 if (!s->indexCat().hasLabel(label)) {
3665 // auto idx = static_cast<const RooCategory &>(s->indexCat()).nextAvailableStateIndex(); - can't access,
3666 // protected method ... will have to just assume indices stay in sync
3667 // ensure added to category in any of our datasets too
3668 for (auto _ds : datasets()) {
3669 if (auto bb = _ds->getBrowsable(".sourceds")) {
3670 _ds = bb;
3671 } // shouldn't happen
3672 auto dsCat = _ds->robs()[s->indexCat().GetName()]->get<RooCategory>();
3673 if (!dsCat) {
3674 throw std::runtime_error(TString::Format("Failed to find %s regular observable in %s dataset",
3675 s->indexCat().GetName(), _ds->GetName()));
3676 }
3677 dsCat->defineType(label.c_str());
3678 }
3679 // adding to the index cat after, so that we don't need to generate subdatasets in the call to datasets() above
3680 // (missing cat will trigger cut)
3681 static_cast<RooCategory &>(const_cast<RooAbsCategoryLValue &>(s->indexCat())).defineType(label.c_str());
3682 }
3683 std::shared_ptr<TObject> out;
3684 child.convertForAcquisition(*this);
3685 if (child.get<RooAbsPdf>()) {
3686 out = acquire(child.fComp); // may create a channel from a histogram
3687 } else if (!child.fComp) {
3688 out = acquireNew<RooProdPdf>(TString::Format("%s_%s", s->GetName(), label.c_str()),
3689 (strlen(child.GetTitle())) ? child.GetTitle() : label.c_str(), RooArgList());
3690 Info("Vary", "Created channel RooProdPdf::%s in model %s", out->GetName(), s->GetName());
3691 }
3692
3693 if (auto _pdf = std::dynamic_pointer_cast<RooAbsPdf>(out); _pdf) {
3694 // before adding the channel, we need to see if we are about to add any globs, and if necessary we must update
3695 // the dataset globs
3696 std::set<RooAbsData *> dsToUpdate;
3697 for (auto _ds : datasets()) {
3698 if (auto bb = _ds->getBrowsable(".sourceds")) {
3699 _ds = bb;
3700 } // shouldn't happen
3701 if (_ds->get<RooAbsData>()->getGlobalObservables()) {
3702 dsToUpdate.insert(_ds->get<RooAbsData>());
3703 }
3704 }
3705 if (!dsToUpdate.empty()) {
3706 RooArgSet leafs;
3707 _pdf->leafNodeServerList(&leafs);
3708 std::unique_ptr<RooAbsCollection> globals(leafs.selectByAttrib("global", true));
3709 for (auto _ds : dsToUpdate) {
3710 std::string alist;
3712 globs.addClone(*_ds->getGlobalObservables());
3713 for (auto &aa : *globals) {
3714 if (!globs.contains(*aa)) {
3715 globs.addClone(*aa);
3716 alist += std::string(aa->GetName()) + ",";
3717 }
3718 }
3719 if (!alist.empty()) {
3720 Warning("Vary", "Adding %s to global observables of %s", alist.c_str(), _ds->GetName());
3721 _ds->setGlobalObservables(globs);
3722 }
3723 }
3724 }
3725
3726 s->addPdf(*_pdf, label.c_str());
3727 sterilize();
3728 // clear children for reload and update shared axis
3729 clear();
3730 fXAxis.reset();
3731 browse();
3732 return xRooNode(TString::Format("%s=%s", s->indexCat().GetName(), label.data()), _pdf, *this);
3733 }
3734
3735 } else if (auto p = get<RooStats::HistFactory::FlexibleInterpVar>(); p) {
3736
3737 // child needs to be a constvar ...
3738 child.convertForAcquisition(*this);
3739 auto _c = child.get<RooConstVar>();
3740 if (!_c && child.get()) {
3741 throw std::runtime_error("Only pure consts can be set as variations of a flexible interpvar");
3742 }
3743#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3744 double value = (_c ? _c->getVal() : p->_nominal);
3745 double nomVal = p->_nominal;
3746#else
3747 double value = (_c ? _c->getVal() : p->nominal());
3748 double nomVal = p->nominal();
3749#endif
3750
3751 TString cName(child.GetName());
3752 if (cName == "nominal") {
3753 p->setNominal(value);
3754 return *(this->variations().at(cName.Data()));
3755 }
3756 if (cName.CountChar('=') != 1) {
3757 throw std::runtime_error("unsupported variation form");
3758 }
3759 std::string parName = cName(0, cName.Index('='));
3760 double parVal = TString(cName(cName.Index('=') + 1, cName.Length())).Atof();
3761 if (parVal != 1 && parVal != -1) {
3762 throw std::runtime_error("unsupported variation magnitude");
3763 }
3764 bool high = parVal > 0;
3765
3766 if (parName.empty()) {
3767 p->setNominal(value);
3768 } else {
3769 auto v = fParent->getObject<RooRealVar>(parName);
3770 if (!v)
3771 v = fParent->acquire<RooRealVar>(parName.c_str(), parName.c_str(), -5, 5);
3772 if (!v->hasError())
3773 v->setError(1);
3774
3775 if (!p->findServer(*v)) {
3776#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3777 p->_paramList.add(*v);
3778 p->_low.push_back(0);
3779 p->_high.push_back(0);
3780 p->_interpCode.push_back(4);
3781#else
3782 const_cast<RooListProxy &>(p->variables()).add(*v);
3783 const_cast<std::vector<double> &>(p->low()).push_back(0);
3784 const_cast<std::vector<double> &>(p->high()).push_back(0);
3785 const_cast<std::vector<int> &>(p->interpolationCodes()).push_back(4);
3786#endif
3787 v->setAttribute(Form("SYMMETRIC%s_%s", high ? "+" : "-", GetName())); // flag for symmetrized
3788 }
3789
3790 if (high) {
3791 p->setHigh(*v, value);
3792 if (v->getAttribute(Form("SYMMETRIC+_%s", GetName()))) {
3793 p->setLow(*v, 2 * nomVal - value);
3794 }
3795 v->setAttribute(Form("SYMMETRIC-_%s", GetName()), false);
3796 } else {
3797 p->setLow(*v, value);
3798 if (v->getAttribute(Form("SYMMETRIC-_%s", GetName()))) {
3799 p->setHigh(*v, 2 * nomVal - value);
3800 }
3801 v->setAttribute(Form("SYMMETRIC+_%s", GetName()), false);
3802 }
3803
3804 /*if (!unconstrained && fParent->pars()[v->GetName()].constraints().empty()) {
3805 fParent->pars()[v->GetName()].constraints().add("normal");
3806 }*/
3807 }
3808 return *(this->variations().at(cName.Data()));
3809 } else if (auto p2 = get<PiecewiseInterpolation>(); p2) {
3810 TString cName(child.GetName());
3811 if (cName.CountChar('=') != 1) {
3812 throw std::runtime_error("unsupported variation form");
3813 }
3814 TString parName = cName(0, cName.Index('='));
3815 double parVal = TString(cName(cName.Index('=') + 1, cName.Length())).Atof();
3816 if (parVal != 1 && parVal != -1) {
3817 throw std::runtime_error("unsupported variation magnitude");
3818 }
3819#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3820 RooHistFunc *f = dynamic_cast<RooHistFunc *>(p2->_nominal.absArg());
3821 if (!f) {
3822 throw std::runtime_error(
3823 TString::Format("Interpolating %s instead of RooHistFunc", p2->_nominal.absArg()->ClassName()));
3824 }
3825#else
3826 RooHistFunc *f = dynamic_cast<RooHistFunc *>(const_cast<RooAbsReal *>(p2->nominalHist()));
3827 if (!f) {
3828 throw std::runtime_error(
3829 TString::Format("Interpolating %s instead of RooHistFunc", p2->nominalHist()->ClassName()));
3830 }
3831#endif
3832 RooHistFunc *nomf = f;
3833 RooHistFunc *otherf = nullptr;
3834 size_t i = 0;
3835 for (auto par : p2->paramList()) {
3836 if (parName == par->GetName()) {
3837 f = dynamic_cast<RooHistFunc *>((parVal > 0 ? p2->highList() : p2->lowList()).at(i));
3838 otherf = dynamic_cast<RooHistFunc *>((parVal > 0 ? p2->lowList() : p2->highList()).at(i));
3839 break;
3840 }
3841 i++;
3842 }
3843 if (i == p2->paramList().size() && !child.get<RooAbsReal>()) {
3844
3845 // need to add the parameter
3846 auto v = acquire<RooRealVar>(parName, parName, -5, 5);
3847 if (!v->hasError())
3848 v->setError(1);
3849
3850 auto upName = TString::Format("%s_%s_up", f->GetName(), parName.Data());
3851 auto upHistName = TString::Format("hist_%s", upName.Data());
3852 auto downName = TString::Format("%s_%s_down", f->GetName(), parName.Data());
3853 auto downHistName = TString::Format("hist_%s", downName.Data());
3854
3855 // RooHistFunc doesn't clone it's data hist ... do it ourself
3856 // (will be cloned again if imported into a ws)
3857 auto up = std::make_shared<RooHistFunc>(upName, f->GetTitle(), f->variables(),
3858 std::make_unique<RooDataHist>(f->dataHist(), upHistName),
3859 f->getInterpolationOrder());
3860 up->setCdfBoundaries(f->getCdfBoundaries());
3861
3862 auto down = std::make_shared<RooHistFunc>(downName, f->GetTitle(), f->variables(),
3863
3864 std::make_unique<RooDataHist>(f->dataHist(), downHistName),
3865 f->getInterpolationOrder());
3866 down->setCdfBoundaries(f->getCdfBoundaries());
3867
3868 auto ups = std::dynamic_pointer_cast<RooHistFunc>(acquire(up, false, true));
3869 auto downs = std::dynamic_pointer_cast<RooHistFunc>(acquire(down, false, true));
3870#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
3871 p2->_highSet.add(*ups.get());
3872 p2->_lowSet.add(*downs.get());
3873 p2->_interpCode.push_back(4);
3874 p2->_paramSet.add(*v);
3875#else
3876 const_cast<RooArgList &>(p2->highList()).add(*ups);
3877 const_cast<RooArgList &>(p2->lowList()).add(*downs);
3878 const_cast<std::vector<int> &>(p2->interpolationCodes()).push_back(4);
3879 const_cast<RooArgList &>(p2->paramList()).add(*v);
3880#endif
3881 p2->setValueDirty();
3882 f = ((parVal > 0) ? ups : downs).get();
3883 otherf = ((parVal > 0) ? downs : ups).get();
3884 // start off with everything being symmetric
3885 f->setStringAttribute("symmetrizes", otherf->GetName());
3886 f->setStringAttribute("symmetrize_nominal", nomf->GetName());
3887 otherf->setStringAttribute("symmetrized_by", f->GetName());
3888
3889 // constrain par if required
3890 /*if (!unconstrained && fParent->pars()[v->GetName()].constraints().empty()) {
3891 fParent->pars()[v->GetName()].constraints().add("normal");
3892 }*/
3893 }
3894
3895 // child.convertForAcquisition(*this);
3896 if (f) {
3897 if (child.get())
3898 xRooNode("tmp", *f, *this) = *child.get();
3899 f->setValueDirty();
3900 xRooNode out(*f, *this);
3901 out.sterilize();
3902 return out;
3903 }
3904
3905#if ROOT_VERSION_CODE > ROOT_VERSION(6, 37, 00)
3906 } else if (auto pmr = get<RooMultiReal>(); pmr) {
3907 TString cName(child.GetName());
3908 if (cName.CountChar('=') != 1) {
3909 throw std::runtime_error("unsupported variation form");
3910 }
3911 TString parName = cName(0, cName.Index('='));
3912 TString parVal = TString(cName(cName.Index('=') + 1, cName.Length()));
3913
3914 // add parVal to categorical if not already there
3915 if (!pmr->indexCategory()->hasLabel(parVal.Data())) {
3916 dynamic_cast<RooCategory &>(*(pmr->indexCategory())).defineType(parVal);
3917 }
3918 auto idx = pmr->indexCategory()->lookupIndex(parVal.Data());
3919 if (idx < 0) {
3920 throw std::runtime_error("Invalid index");
3921 }
3922 // add child to list ... use copy of "nominal" (0th) if child is empty
3923 child.convertForAcquisition(*this);
3924 auto _c = child.get<RooAbsReal>();
3925 if (!_c) {
3926 if (pmr->getModelList().empty()) {
3927 throw std::runtime_error("No real function given for variation, and no nominal function to clone");
3928 }
3929 _c = std::dynamic_pointer_cast<RooAbsReal>(
3930 acquire(std::shared_ptr<TObject>(pmr->getModelList().at(0)->Clone(
3931 TString::Format("%s_%s", get()->GetName(), child.GetName()))),
3932 false, true))
3933 .get();
3934 _c->setStringAttribute("alias", child.GetName());
3935 }
3936 const_cast<RooListProxy &>(pmr->getModelList()).add(*_c);
3937 return xRooNode(*_c, *this);
3938
3939#endif
3940
3941 } else if (auto p3 = get<RooConstVar>(); p3) {
3942
3943 // never vary the universal consts ... its too dangerous
3944 if (p3->getAttribute("RooRealConstant_Factory_Object")) {
3945 throw std::runtime_error("Cannot vary pure constants");
3946 }
3947
3948 // inject a FlexibleInterpVar ...
3949
3950 // get the list of clients BEFORE creating the new interpolation ... seems list of clients is inaccurate after
3951 std::set<RooAbsArg *> cl;
3952 for (auto &arg : p3->clients()) {
3953 cl.insert(arg);
3954 }
3955 // if multiple clients, see if only one client is in parentage route
3956 // if so, then assume thats the only client we should replace in
3957 if (cl.size() > 1) {
3958 if (cl.count(fParent->get<RooAbsArg>()) > 0) {
3959 cl.clear();
3960 cl.insert(fParent->get<RooAbsArg>());
3961 } else {
3962 Warning("Vary", "Varying %s that has multiple clients", p3->GetName());
3963 }
3964 }
3965 p3->setStringAttribute("origName", p3->GetName());
3966 TString n = p3->GetName();
3967 p3->SetName(Form("%s_nominal", p3->GetName())); // if problems should perhaps not rename here
3968
3969 auto new_p = acquireNew<RooStats::HistFactory::FlexibleInterpVar>(n, p3->GetTitle(), RooArgList(), p3->getVal(),
3970 std::vector<double>(), std::vector<double>());
3971
3972 // copy attributes over
3973 for (auto &a : p3->attributes())
3974 new_p->setAttribute(a.c_str());
3975 for (auto &a : p3->stringAttributes())
3976 new_p->setStringAttribute(a.first.c_str(), a.second.c_str());
3977 // if (!new_p->getStringAttribute("alias")) new_p->setStringAttribute("alias",p->GetName());
3978 auto old_p = p3;
3979 new_p->setAttribute(Form("ORIGNAME:%s", old_p->GetName())); // used in redirectServers to say what this replaces
3980 for (auto arg : cl) {
3981 arg->redirectServers(RooArgSet(*new_p), false, true);
3982 }
3983
3984 fComp = new_p;
3985 return Vary(child);
3986
3987 } else if (auto p4 = get<RooAbsReal>(); p4) {
3988 // inject an interpolation node
3989
3990 // get the list of clients BEFORE creating the new interpolation ... seems list of clients is inaccurate after
3991 std::set<RooAbsArg *> cl;
3992 for (auto &arg : p4->clients()) {
3993 cl.insert(arg);
3994 }
3995 // if multiple clients, see if only one client is in parentage route
3996 // if so, then assume thats the only client we should replace in
3997 if (cl.size() > 1) {
3998 if (cl.count(fParent->get<RooAbsArg>()) > 0) {
3999 cl.clear();
4000 cl.insert(fParent->get<RooAbsArg>());
4001 } else {
4002 Warning("Vary", "Varying %s that has multiple clients", p4->GetName());
4003 }
4004 }
4005 p4->setStringAttribute("origName", p4->GetName());
4006 TString n = p4->GetName();
4007 p4->SetName(Form("%s_nominal", p4->GetName())); // if problems should perhaps not rename here
4008
4009#if ROOT_VERSION_CODE > ROOT_VERSION(6, 37, 00)
4010 std::shared_ptr<RooAbsArg> new_p;
4011 // if alphanumeric variation name is not a 1 or -1, inject a RooMultiReal not a PiecewiseInterpolation ...
4012 TString cName(child.GetName());
4013 if (cName.CountChar('=') == 1) {
4014 TString parName = cName(0, cName.Index('='));
4015 double parVal = TString(cName(cName.Index('=') + 1, cName.Length())).Atof();
4016 if (parVal != 1 && parVal != -1) {
4017 // get the idxCat ...
4018 auto idxCat = acquire<RooCategory>(parName, parName);
4019 if (!idxCat) {
4020 throw std::runtime_error("Failed to acquire categorical index for RooMultiReal");
4021 }
4022 // add an index if none already
4023 if (idxCat->numTypes() == 0) {
4024 idxCat->defineType("nominal");
4025 }
4026 Info("Vary", "Creating a RooMultiReal with category %s", idxCat->GetName());
4027 auto newFunc = acquireNew<RooMultiReal>(
4028 n, p4->GetTitle(), *idxCat,
4029 RooArgList()); // can't pass nominal model as that will force defining types on category
4030 const_cast<RooListProxy &>(newFunc->getModelList()).add(*p4);
4031 new_p = newFunc;
4032 }
4033 }
4034 if (!new_p) {
4035 new_p = acquireNew<PiecewiseInterpolation>(n, p4->GetTitle(), *p4, RooArgList(), RooArgList(), RooArgList());
4036 }
4037
4038#else
4039 auto new_p = acquireNew<PiecewiseInterpolation>(n, p4->GetTitle(), *p4, RooArgList(), RooArgList(), RooArgList());
4040#endif
4041
4042 // copy attributes over
4043 for (auto &a : p4->attributes())
4044 new_p->setAttribute(a.c_str());
4045 for (auto &a : p4->stringAttributes())
4046 new_p->setStringAttribute(a.first.c_str(), a.second.c_str());
4047 // if (!new_p->getStringAttribute("alias")) new_p->setStringAttribute("alias",p->GetName());
4048 auto old_p = p4;
4049 new_p->setAttribute(Form("ORIGNAME:%s", old_p->GetName())); // used in redirectServers to say what this replaces
4050 for (auto arg : cl) {
4051 arg->redirectServers(RooArgSet(*new_p), false, true);
4052 }
4053
4054 fComp = new_p;
4055 return Vary(child);
4056 }
4057
4058 Print();
4059 throw std::runtime_error(TString::Format("Cannot vary %s with %s", GetName(), child.GetName()));
4060}
4061
4063{
4065}
4066
4067bool xRooNode::SetContent(double value, const char *par, double val)
4068{
4069 return SetContents(RooConstVar(GetName(), GetTitle(), value), par, val);
4070}
4071
4074 {
4075 if (x && b)
4076 x->setBinning(*b);
4077 if (b)
4078 delete b;
4079 }
4080 RooRealVar *x = nullptr;
4081 RooAbsBinning *b = nullptr;
4082};
4083
4085{
4086
4087 if (!get()) {
4088 fComp = std::shared_ptr<TObject>(const_cast<TObject *>(&o), [](TObject *) {});
4089 if (fParent && !fParent->find(GetName())) {
4090 // either a temporary or a placeholder so need to try genuinely adding
4091 fComp = fParent->Add(*this, "+").fComp;
4092 if (auto a = get<RooAbsArg>(); a && strcmp(a->GetName(), GetName()) && !a->getStringAttribute("alias")) {
4093 a->setStringAttribute("alias", GetName());
4094 }
4095 if (!fComp)
4096 throw std::runtime_error("Cannot determine type");
4097 return *this;
4098 }
4099 }
4100
4101 if (auto h = dynamic_cast<const TH1 *>(&o); h) {
4102 /*auto f = get<RooHistFunc>();
4103 if (!f) {
4104 // if it's a RooProduct locate child with the same name
4105 if (get<RooProduct>()) {
4106 f = factors()[GetName()]->get<RooHistFunc>();
4107 }
4108
4109
4110
4111 }*/
4112 bool _isData = get<RooAbsData>();
4113 BinningRestorer _b;
4114 if (_isData) {
4115 // need to ensure x-axis matches this h
4116 auto ax = GetXaxis();
4117 if (!ax)
4118 throw std::runtime_error("no xaxis");
4119 auto _v = dynamic_cast<RooRealVar *>(ax->GetParent());
4120 if (_v) {
4121 _b.x = _v;
4122 _b.b = dynamic_cast<RooAbsBinning *>(_v->getBinningPtr(nullptr)->Clone());
4123 if (h->GetXaxis()->IsVariableBinSize()) {
4124 _v->setBinning(RooBinning(h->GetNbinsX(), h->GetXaxis()->GetXbins()->GetArray()));
4125 } else {
4126 _v->setBinning(RooUniformBinning(h->GetXaxis()->GetXmin(), h->GetXaxis()->GetXmax(), h->GetNbinsX()));
4127 }
4128 }
4129 }
4130
4131 if (true) {
4132 for (int bin = 1; bin <= h->GetNbinsX(); bin++) {
4133 SetBinContent(bin, h->GetBinContent(bin));
4134 /*double value = h->GetBinContent(bin);
4135 auto bin_pars = f->dataHist().get(bin - 1);
4136 if (f->getAttribute("density")) {
4137 value /= f->dataHist().binVolume(*bin_pars);
4138 }
4139 f->dataHist().set(*bin_pars, value);*/
4140 if (!_isData && h->GetSumw2N() && !SetBinError(bin, h->GetBinError(bin)))
4141 throw std::runtime_error("Failed setting stat error");
4142 }
4143 return *this;
4144 }
4145 } else if (auto _c = dynamic_cast<const RooConstVar *>(&o); _c) {
4146
4147 if (auto a = get<RooAbsArg>();
4148 (a && a->isFundamental()) || get<RooConstVar>() || get<RooStats::HistFactory::FlexibleInterpVar>()) {
4149 SetBinContent(1, _c->getVal());
4150 return *this;
4151 } else if (get<RooAbsData>()) { // try to do assignment to a dataset (usually setting a bin content)
4152 SetBinContent(0, _c->getVal());
4153 return *this;
4154 }
4155 }
4156
4157 throw std::runtime_error("Assignment failed");
4158
4159 /*
4160
4161 if (fParent && !fParent->mk()) {
4162 throw std::runtime_error("mk failure");
4163 }
4164
4165 if (fComp) return *this;
4166
4167 if (o.InheritsFrom("RooAbsArg")) {
4168 fComp = acquire(std::shared_ptr<TObject>(const_cast<TObject*>(&o),[](TObject* o){}));
4169 std::dynamic_pointer_cast<RooAbsArg>(fComp)->setStringAttribute("alias",GetName());
4170 }
4171
4172 if (fComp && fParent) {
4173 fParent->incorporate(fComp);
4174 }
4175
4176
4177 return *this;
4178 */
4179}
4180
4181void xRooNode::_fit_(const char *constParValues, const char *options)
4182{
4183 try {
4184 // re-float all poi and np before fitting
4185 np().get<RooArgList>()->setAttribAll("Constant", false);
4186 poi().get<RooArgList>()->setAttribAll("Constant", false);
4187 auto _pars = pars();
4188 // std::unique_ptr<RooAbsCollection> snap(_pars.argList().snapshot());
4189 TStringToken pattern(constParValues, ",");
4190 std::map<RooAbsRealLValue *, double> valsToSet;
4191 while (pattern.NextToken()) {
4192 auto idx = pattern.Index('=');
4193 TString pat = (idx == -1) ? TString(pattern) : TString(pattern(0, idx));
4194 double val =
4195 (idx == -1) ? std::numeric_limits<double>::quiet_NaN() : TString(pattern(idx + 1, pattern.Length())).Atof();
4196 bool foundArg = false;
4197 for (auto p : _pars.argList()) {
4198 if (TString(p->GetName()).Contains(TRegexp(pat, true))) {
4199 foundArg = true;
4200 p->setAttribute("Constant", true);
4201 if (!std::isnan(val)) {
4202 valsToSet[dynamic_cast<RooAbsRealLValue *>(p)] = val;
4203 // dynamic_cast<RooAbsRealLValue *>(p)->setVal(val); // don't set yet, to allow for asimov dataset
4204 // creation based on current values
4205 }
4206 }
4207 }
4208 if (!foundArg) {
4209 throw std::runtime_error(std::string("Unrecognised parameter: ") + pat.Data());
4210 }
4211 }
4212
4213 // parse options
4214 TStringToken pattern2(options, ",");
4215 auto defaultOpts = xRooFit::createNLLOptions();
4216 while (pattern2.NextToken()) {
4217 auto idx = pattern2.Index('=');
4218 TString pat = (idx == -1) ? TString(pattern2) : TString(pattern2(0, idx));
4219 TString val = TString(pattern2(idx + 1, pattern2.Length()));
4220 if (auto o = defaultOpts->FindObject(pat)) {
4221 defaultOpts->Remove(o);
4222 delete o;
4223 }
4224 defaultOpts->Add(new RooCmdArg(pat, val.IsDec() ? val.Atoi() : 0, 0, val.IsFloat() ? val.Atof() : 0., 0.,
4225 val.IsAlpha() ? val : nullptr));
4226 }
4227
4228 // use the first selected dataset
4229 auto _dsets = datasets();
4230 TString dsetName = "";
4231 for (auto &d : _dsets) {
4232 if (d->get()->TestBit(1 << 20)) {
4233 dsetName = d->get()->GetName();
4234 break;
4235 }
4236 }
4237 auto _nll = nll(dsetName.Data(), *defaultOpts);
4238 // can now set the values
4239 for (auto [p, v] : valsToSet) {
4240 p->setVal(v);
4241 }
4242 _nll.fitConfigOptions()->SetValue("LogSize", 65536);
4243 _nll.fitConfig()->MinimizerOptions().SetPrintLevel(0);
4244 auto fr = _nll.minimize();
4245 //_pars.argList() = *snap; // restore values - irrelevant as SetFitResult will restore values
4246 if (!fr.get())
4247 throw std::runtime_error("Fit Failed");
4248 SetFitResult(fr.get());
4249 TString statusCodes;
4250 for (unsigned int i = 0; i < fr->numStatusHistory(); i++) {
4251 statusCodes += TString::Format("\n%s = %d", fr->statusLabelHistory(i), fr->statusCodeHistory(i));
4252 }
4253 // add poi to list of statusCodes too if was good fit
4254 if(fr->status() == 0) {
4255 auto _poi = poi();
4256 if (!_poi.empty()) {
4257 statusCodes += "\n\nPOI Post Fit Values\n-------------";
4258 for (auto p : _poi) {
4259 auto arg = dynamic_cast<RooRealVar *>(fr->floatParsFinal().find(p->GetName()));
4260 if (!arg)
4261 continue; // must have been held constant
4262 statusCodes += TString::Format("\n%s : %g +/- %g", arg->GetName(), arg->getVal(), arg->getError());
4263 }
4264 }
4265 }
4266 const TGWindow *w =
4267 (gROOT->GetListOfBrowsers()->At(0))
4268 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
4269 : gClient->GetRoot();
4270 TString gofResult = "";
4271 if (_nll.fOpts->find("GoF")) {
4272 gofResult = TString::Format("GoF p-value = %g (mainTerm = %g)\n", fr->constPars().getRealValue(".pgof"),
4273 fr->constPars().getRealValue(".mainterm_pgof"));
4274 }
4275 if (fr->status() != 0) {
4276 new TGMsgBox(gClient->GetRoot(), w, "Fit Finished with Bad Status Code",
4277 TString::Format("%s\nData = %s\nFit Status Code = %d\nCov Quality = %d\n%s-------------%s",
4278 fr->GetName(), dsetName.Data(), fr->status(), fr->covQual(), gofResult.Data(),
4279 statusCodes.Data()),
4281 } else if (fr->covQual() != 3 && _nll.fitConfig()->ParabErrors()) {
4282 new TGMsgBox(gClient->GetRoot(), w, "Fit Finished with Bad Covariance Quality",
4283 TString::Format("%s\nData = %s\nFit Status Code = %d\nCov Quality = %d\n%s-------------%s",
4284 fr->GetName(), dsetName.Data(), fr->status(), fr->covQual(), gofResult.Data(),
4285 statusCodes.Data()),
4287 } else {
4288 new TGMsgBox(gClient->GetRoot(), w, "Fit Finished Successfully",
4289 TString::Format("%s\nData = %s\nFit Status Code = %d\nCov Quality = %d\n%s-------------%s",
4290 fr->GetName(), dsetName.Data(), fr->status(), fr->covQual(), gofResult.Data(),
4291 statusCodes.Data()));
4292 }
4293 TBrowser *b = nullptr;
4294 for (auto a : *gROOT->GetListOfBrowsers()) {
4295 b = dynamic_cast<TBrowser *>(a);
4296 if (b && GetTreeItem(b)) {
4297 break;
4298 }
4299 }
4300 if (b) {
4301 auto p = GetTreeItem(b);
4302 while (p) {
4303 if (TString(p->GetText()).BeginsWith("RooWorkspace::")) {
4304 // found the workspace ... refresh this node, and if there's a fits node, refresh that
4305 if (auto bi = dynamic_cast<TRootBrowser *>(b->GetBrowserImp())) {
4306 if (auto fb = dynamic_cast<TGFileBrowser *>(bi->GetActBrowser())) {
4307 fb->DoubleClicked(p, 0);
4308 if (auto first = p->GetFirstChild()) {
4309 do {
4310 if (first->IsOpen() && TString(first->GetText()) == "fits") {
4311 fb->DoubleClicked(first, 0);
4312 }
4313 } while ((first = first->GetNextSibling()));
4314 }
4315 }
4316 }
4317 break;
4318 } else {
4319 p = p->GetParent();
4320 }
4321 }
4322 }
4323 } catch (const std::exception &e) {
4324 new TGMsgBox(
4325 gClient->GetRoot(),
4326 (gROOT->GetListOfBrowsers()->At(0))
4327 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
4328 : gClient->GetRoot(),
4329 "Exception", e.what(), kMBIconExclamation, kMBOk); // deletes self on dismiss?
4330 }
4331}
4332
4333void xRooNode::_generate_(const char *datasetName, bool expected)
4334{
4335 try {
4336 datasets().Add(datasetName, expected ? "asimov" : "toy");
4337 // refresh datasets folder of workspace
4338 TBrowser *b = nullptr;
4339 for (auto a : *gROOT->GetListOfBrowsers()) {
4340 b = dynamic_cast<TBrowser *>(a);
4341 if (b && GetTreeItem(b)) {
4342 break;
4343 }
4344 }
4345 if (b) {
4346 auto p = GetTreeItem(b);
4347 while (p) {
4348 if (TString(p->GetText()).BeginsWith("RooWorkspace::")) {
4349 // found the workspace ... refresh this node, and if there's a datasets node, refresh that
4350 if (auto bi = dynamic_cast<TRootBrowser *>(b->GetBrowserImp())) {
4351 if (auto fb = dynamic_cast<TGFileBrowser *>(bi->GetActBrowser())) {
4352 fb->DoubleClicked(p, 0);
4353 if (auto first = p->GetFirstChild()) {
4354 do {
4355 if (first->IsOpen() && TString(first->GetText()) == "datasets") {
4356 fb->DoubleClicked(first, 0);
4357 }
4358 } while ((first = first->GetNextSibling()));
4359 }
4360 }
4361 }
4362 break;
4363 } else {
4364 p = p->GetParent();
4365 }
4366 }
4367 }
4368 } catch (const std::exception &e) {
4369 new TGMsgBox(
4370 gClient->GetRoot(),
4371 (gROOT->GetListOfBrowsers()->At(0))
4372 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
4373 : gClient->GetRoot(),
4374 "Exception", e.what(),
4375 kMBIconExclamation); // deletes self on dismiss?
4376 }
4377}
4378
4379void xRooNode::_scan_(const char *what, double nToys, const char *xvar, int nBinsX, double lowX,
4380 double highX /*, const char*, int, double, double*/, const char *constParValues,
4381 const char *options)
4382{
4383 try {
4384 TString sXvar(xvar);
4385 TString sWhat(what);
4386
4387 // use the first selected dataset
4388 auto _dsets = datasets();
4389 TString dsetName = "";
4390 for (auto &d : _dsets) {
4391 if (d->get()->TestBit(1 << 20)) {
4392 dsetName = d->get()->GetName();
4393 break;
4394 }
4395 }
4396 auto _pars = pars();
4397 std::unique_ptr<RooAbsCollection> snap(_pars.argList().snapshot());
4398 TStringToken pattern(constParValues, ",");
4399 while (pattern.NextToken()) {
4400 auto idx = pattern.Index('=');
4401 TString pat = (idx == -1) ? TString(pattern) : TString(pattern(0, idx));
4402 double val =
4403 (idx == -1) ? std::numeric_limits<double>::quiet_NaN() : TString(pattern(idx + 1, pattern.Length())).Atof();
4404 bool foundArg = false;
4405 for (auto par : _pars.argList()) {
4406 if (TString(par->GetName()).Contains(TRegexp(pat, true))) {
4407 foundArg = true;
4408 par->setAttribute("Constant", true);
4409 if (!std::isnan(val)) {
4410 dynamic_cast<RooAbsRealLValue *>(par)->setVal(val);
4411 }
4412 }
4413 }
4414 if (!foundArg) {
4415 throw std::runtime_error(std::string("Unrecognised parameter: ") + pat.Data());
4416 }
4417 }
4418
4419 // parse options
4420 TStringToken pattern2(options, ",");
4421 auto defaultOpts = xRooFit::createNLLOptions();
4422 while (pattern2.NextToken()) {
4423 auto idx = pattern2.Index('=');
4424 TString pat = (idx == -1) ? TString(pattern2) : TString(pattern2(0, idx));
4425 TString val = TString(pattern2(idx + 1, pattern2.Length()));
4426 if (auto o = defaultOpts->FindObject(pat)) {
4427 defaultOpts->Remove(o);
4428 delete o;
4429 }
4430 defaultOpts->Add(new RooCmdArg(pat, val.IsDec() ? val.Atoi() : 0, 0, val.IsFloat() ? val.Atof() : 0., 0.,
4431 val.IsAlpha() ? val : nullptr));
4432 }
4433
4434 auto hs = nll(dsetName.Data(), *defaultOpts).hypoSpace(sXvar);
4435 hs.SetName(TUUID().AsString());
4436 if (nToys) {
4437 sWhat += " toys";
4438 if (nToys > 0) {
4439 sWhat += TString::Format("=%g", nToys);
4440 }
4441 }
4442 hs.SetTitle(sWhat + " scan" + ((dsetName != "") ? TString::Format(" [data=%s]", dsetName.Data()) : ""));
4443 int scanStatus = hs.scan(sWhat + " visualize", nBinsX, lowX, highX);
4444 if (scanStatus != 0) {
4445 new TGMsgBox(
4446 gClient->GetRoot(),
4447 (gROOT->GetListOfBrowsers()->At(0))
4448 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
4449 : gClient->GetRoot(),
4450 "Scan Finished with Bad Status Code",
4451 TString::Format("%s\nData = %s\nScan Status Code = %d", hs.GetName(), dsetName.Data(), scanStatus),
4453 }
4454 if (ws()) {
4455 if (auto res = hs.result())
4456 ws()->import(*res);
4457 }
4458
4459 _pars.argList() = *snap; // restore pars
4460
4461 TBrowser *b = nullptr;
4462 for (auto a : *gROOT->GetListOfBrowsers()) {
4463 b = dynamic_cast<TBrowser *>(a);
4464 if (b && GetTreeItem(b)) {
4465 break;
4466 }
4467 }
4468 if (b) {
4469 auto p = GetTreeItem(b);
4470 while (p) {
4471 if (TString(p->GetText()).BeginsWith("RooWorkspace::")) {
4472 // found the workspace ... refresh this node, and if there's a scans node, refresh that
4473 if (auto bi = dynamic_cast<TRootBrowser *>(b->GetBrowserImp())) {
4474 if (auto fb = dynamic_cast<TGFileBrowser *>(bi->GetActBrowser())) {
4475 fb->DoubleClicked(p, 0);
4476 if (auto first = p->GetFirstChild()) {
4477 do {
4478 if (first->IsOpen() && TString(first->GetText()) == "scans") {
4479 fb->DoubleClicked(first, 0);
4480 }
4481 } while ((first = first->GetNextSibling()));
4482 }
4483 }
4484 }
4485 break;
4486 } else {
4487 p = p->GetParent();
4488 }
4489 }
4490 }
4491
4492 } catch (const std::exception &e) {
4493 new TGMsgBox(
4494 gClient->GetRoot(),
4495 (gROOT->GetListOfBrowsers()->At(0))
4496 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
4497 : gClient->GetRoot(),
4498 "Exception", e.what(), kMBIconExclamation);
4499 }
4500}
4501
4502void xRooNode::_SetBinContent_(int bin, double value, const char *par, double parVal)
4503{
4504 try {
4505 SetBinContent(bin, value, strlen(par) > 0 ? par : nullptr, parVal);
4506 } catch (const std::exception &e) {
4507 new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(),
4508 kMBIconExclamation); // deletes self on dismiss?
4509 }
4510}
4511
4513{
4514 try {
4515#if ROOT_VERSION_CODE > ROOT_VERSION(6, 29, 00)
4516 // if this is a collection of values, populate a TF1 and display as a dialog
4517 if (!get() && TString(GetName()).BeginsWith("!")) {
4518 browse();
4520 for (auto a : *this) {
4521 if (auto arg = a->get<RooRealVar>())
4522 args.add(*arg);
4523 }
4524 TF1 f(GetName(), 0.0, 1.0, std::min(int(args.size()), 10));
4525 int i = 0;
4526 int j = 0;
4527 for (auto c : args) {
4528 j++;
4529 if (j < value) {
4530 continue;
4531 }
4532 auto v = dynamic_cast<RooRealVar *>(c);
4533 f.SetParName(i, c->GetName());
4534 if (v) {
4535 f.SetParLimits(i, v->getMin(), v->getMax());
4536 if (v->isConstant())
4537 f.FixParameter(i, v->getVal());
4538 else {
4539 f.SetParameter(i, v->getVal());
4540 f.SetParError(i, v->getError());
4541 }
4542 }
4543 i++;
4544 if (i == 10) {
4545 break; // max 10 pars shown
4546 }
4547 }
4548 int ret = 0;
4550 gClient->GetDefaultRoot(),
4551 (gROOT->GetListOfBrowsers()->At(0))
4552 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
4553 : gClient->GetDefaultRoot(),
4554 &f, nullptr, &ret);
4555 if (ret) {
4556 // user has changed parameter values etc, propagate back to parameters
4557 for (i = 0; i < f.GetNpar(); i++) {
4558 auto c = args.find(f.GetParName(i));
4559 auto v = dynamic_cast<RooRealVar *>(c);
4560 if (v) {
4561 v->setVal(f.GetParameter(i));
4562 double low, high;
4563 f.GetParLimits(i, low, high);
4564 if (low == high) {
4565 v->setConstant(low); // if low==high==0 then is not marked constant
4566 } else {
4567 v->setRange(low, high);
4568 }
4569 }
4570 }
4571 }
4572 return;
4573 }
4574#endif
4575
4576 if (!SetContent(value))
4577 throw std::runtime_error("Failed to SetContent");
4578 } catch (const std::exception &e) {
4579 new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(),
4580 kMBIconExclamation); // deletes self on dismiss?
4581 }
4582}
4583
4584bool xRooNode::SetBinContent(int bin, double value, const char *par, double parVal)
4585{
4586
4587 // create if needed
4588 if (!get()) {
4589 if (fParent && !find(GetName())) {
4590 // if have a binning we create a histogram to match it
4591 if (auto ax = GetXaxis(); ax) {
4592 std::shared_ptr<TH1D> h;
4593 auto _b = dynamic_cast<Axis2 *>(ax)->binning();
4594 if (_b->isUniform()) {
4595 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
4596 h.reset(new TH1D(GetName(), GetTitle(), _b->numBins(), _b->lowBound(), _b->highBound()));
4597 } else {
4598 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
4599 h.reset(new TH1D(GetName(), GetTitle(), _b->numBins(), _b->array()));
4600 }
4601 h->SetOption("nostyle"); // don't transfer style when added
4602 h->GetXaxis()->SetName(TString::Format("%s;%s", ax->GetParent()->GetName(), ax->GetName()));
4603 fComp = h;
4604 }
4605 fComp = fParent->Add(*this, "sample").fComp;
4606 }
4607 }
4608
4609 // if it's a RooProduct locate child with the same name
4610 if (get<RooProduct>()) {
4611 return factors()[GetName()]->SetBinContent(bin, value, par, parVal);
4612 }
4613
4614 if (get<RooAbsData>()) {
4615 if (auto _data = get<RooDataSet>(); _data) {
4616 auto _ax = (bin) ? GetXaxis() : nullptr;
4617 if (!_ax && bin) {
4618 throw std::runtime_error("Cannot determine binning to fill data");
4619 }
4620 if (_ax && _ax->GetNbins() < bin) {
4621 throw std::out_of_range(TString::Format("%s range %s only has %d bins", _ax->GetParent()->GetName(),
4622 _ax->GetName(), _ax->GetNbins()));
4623 }
4624 RooArgSet obs;
4625
4626 TString cut = "";
4627
4628 for (auto _c : coords()) { // coords() moves vars to their respective coordinates too
4629 if (auto _cat = _c->get<RooAbsCategoryLValue>(); _cat) {
4630 if (cut != "")
4631 cut += " && ";
4632 cut += TString::Format("%s==%d", _cat->GetName(), _cat->getCurrentIndex());
4633 obs.add(*_cat); // note: if we ever changed coords to return clones, would need to keep coords alive
4634 } else if (auto _rv = _c->get<RooAbsRealLValue>(); _rv) {
4635 // todo: check coordRange is a single range rather than multirange
4636 if (cut != "")
4637 cut += " && ";
4638 cut +=
4639 TString::Format("%s>=%f&&%s<%f", _rv->GetName(), _rv->getMin(_rv->getStringAttribute("coordRange")),
4640 _rv->GetName(), _rv->getMax(_rv->getStringAttribute("coordRange")));
4641 obs.add(*_rv); // note: if we ever changed coords to return clones, would need to keep coords alive
4642 } else {
4643 throw std::runtime_error("SetBinContent of data: Unsupported coordinate type");
4644 }
4645 }
4646
4647 RooFormulaVar cutFormula("cut1", cut, obs); // doing this to avoid complaints about unused vars
4648 RooFormulaVar icutFormula("icut1", TString::Format("!(%s)", cut.Data()), obs);
4649
4650 TString cut2;
4651 if (_ax) {
4652 cut2 = TString::Format("%s >= %f && %s < %f", _ax->GetParent()->GetName(), _ax->GetBinLowEdge(bin),
4653 _ax->GetParent()->GetName(), _ax->GetBinUpEdge(bin));
4654 obs.add(*dynamic_cast<RooAbsArg *>(_ax->GetParent()));
4655 } else {
4656 cut2 = "1==1";
4657 }
4658 RooFormulaVar cutFormula2("cut2", cut + " && " + cut2, obs);
4659 RooFormulaVar icutFormula2("icut2", TString::Format("!(%s && %s)", cut.Data(), cut2.Data()), obs);
4660
4661 // // go up through parents looking for slice obs
4662 // auto _p = fParent;
4663 // while(_p) {
4664 // TString pName(_p->GetName());
4665 // if (auto pos = pName.Index('='); pos != -1) {
4666 // if(auto _obs = _p->getObject<RooAbsLValue>(pName(0,pos)); _obs) {
4667 // if(auto _cat = dynamic_cast<RooAbsCategoryLValue*>(_obs.get()); _cat) {
4668 // _cat->setLabel(pName(pos+1,pName.Length()));
4669 // cut += TString::Format("%s%s==%d", (cut=="")?"":" && ",_cat->GetName(),
4670 // _cat->getCurrentIndex());
4671 // } else if(auto _var = dynamic_cast<RooAbsRealLValue*>(_obs.get()); _var) {
4672 // _var->setVal(TString(pName(pos+1,pName.Length())).Atof());
4673 // // TODO: Cut for this!!
4674 // }
4675 // obs.add(*dynamic_cast<RooAbsArg*>(_obs.get()));
4676 // } else {
4677 // throw std::runtime_error("Unknown observable, could not find");
4678 // }
4679 // }
4680 // _p = _p->fParent;
4681 // }
4682
4683 // add observables to dataset if necessary
4684 RooArgSet l(obs);
4685 l.remove(*_data->get(), true, true);
4686 if (!l.empty()) {
4687 // addColumns method is buggy: https://github.com/root-project/root/issues/8787
4688 // incredibly though, addColumn works??
4689 for (auto &x : l) {
4690 _data->addColumn(*x);
4691 }
4692 // instead create a copy dataset and merge it into current
4693 // cant use merge because it drops weightVar
4694 /*RooDataSet tmp("tmp","tmp",l);
4695 for(int i=0;i<_data->numEntries();i++) tmp.add(l);
4696 _data->merge(&tmp);*/
4697 // delete _data->addColumns(l);
4698 }
4699 // before adding, ensure range is good to cover
4700 for (auto &o : obs) {
4701 if (auto v = dynamic_cast<RooRealVar *>(o); v) {
4702 if (auto dv = dynamic_cast<RooRealVar *>(_data->get()->find(v->GetName())); dv) {
4703 if (v->getMin() < dv->getMin())
4704 dv->setMin(v->getMin());
4705 if (v->getMax() > dv->getMax())
4706 dv->setMax(v->getMax());
4707 }
4708 } else if (auto c = dynamic_cast<RooCategory *>(o); c) {
4709 if (auto dc = dynamic_cast<RooCategory *>(_data->get()->find(c->GetName())); dc) {
4710 if (!dc->hasLabel(c->getCurrentLabel())) {
4711 dc->defineType(c->getCurrentLabel(), c->getCurrentIndex());
4712 }
4713 }
4714 }
4715 }
4716
4717 // using SetBinContent means dataset must take on a binned form at these coordinates
4718 // if number of entries doesnt match number of bins then will 'bin' the data
4719 if (bin) {
4720 if (auto _nentries = std::unique_ptr<RooAbsData>(_data->reduce(cutFormula))->numEntries();
4721 _nentries != _ax->GetNbins()) {
4722 auto _contents = GetBinContents(1, _ax->GetNbins());
4723
4724 if (_nentries > 0) {
4725 Info("SetBinContent", "Binning %s in channel: %s", GetName(), cut.Data());
4726 auto _reduced = std::unique_ptr<RooAbsData>(_data->reduce(icutFormula));
4727 _data->reset();
4728 for (int j = 0; j < _reduced->numEntries(); j++) {
4729 auto _obs = _reduced->get(j);
4730 _data->add(*_obs, _reduced->weight());
4731 }
4732 }
4733 for (int i = 1; i <= _ax->GetNbins(); i++) {
4734 // can skip over the bin we will be setting to save a reduce step below
4735 if (i == bin)
4736 continue;
4737 dynamic_cast<RooAbsLValue *>(_ax->GetParent())->setBin(i - 1, _ax->GetName());
4738 _data->add(obs, _contents.at(i - 1));
4739 }
4740 }
4741 }
4742 // remove existing entries
4743 if (std::unique_ptr<RooAbsData>(_data->reduce(cutFormula2))->numEntries() > 0) {
4744 auto _reduced = std::unique_ptr<RooAbsData>(_data->reduce(icutFormula2));
4745 _data->reset();
4746 for (int j = 0; j < _reduced->numEntries(); j++) {
4747 auto _obs = _reduced->get(j);
4748 _data->add(*_obs, _reduced->weight());
4749 }
4750 }
4751 if (_ax)
4752 dynamic_cast<RooAbsLValue *>(_ax->GetParent())->setBin(bin - 1, _ax->GetName());
4753 _data->add(obs, value);
4754 if (auto bb = getBrowsable(".sourceds"))
4755 return bb->SetBinContent(bin, value, par, parVal); // apply to source ds if we have one
4756 return true;
4757
4758 } else if (get<RooDataHist>()) {
4759 throw std::runtime_error("RooDataHist not supported yet");
4760 }
4761 }
4762
4763 if (auto _varies = variations(); !_varies.empty() || (par && strlen(par))) {
4764 if (!par || strlen(par) == 0) {
4765 return _varies["nominal"]->SetBinContent(bin, value, par, parVal);
4766 } else if (auto it = _varies.find(Form("%s=%g", par, parVal)); it) {
4767 return it->SetBinContent(bin, value);
4768 } else {
4769 // need to create the variation : note - if no variations existed up to now this will inject a new node
4770 // so we should redirect ourself to the new node
4771 // TODO: Do we need to redirect parents?
4772 TString s = Form("%s=%g", par, parVal);
4773 return Vary(s.Data()).SetBinContent(bin, value);
4774 }
4775 }
4776
4777 auto o = get();
4778 if (auto p = dynamic_cast<RooRealVar *>(o); p) {
4779 if (!par || strlen(par) == 0) {
4780 if (p->getMax() < value)
4781 p->setMax(value);
4782 if (p->getMin() > value)
4783 p->setMin(value);
4784 p->setVal(value);
4785 sterilize();
4786 return true;
4787 }
4788
4789 } else if (auto c = dynamic_cast<RooConstVar *>(o); c) {
4790
4791 // if parent is a FlexibleInterpVar, change the value in that .
4792 if (strcmp(c->GetName(), Form("%g", c->getVal())) == 0) {
4793 c->SetNameTitle(Form("%g", value), Form("%g", value));
4794 }
4795#if ROOT_VERSION_CODE < ROOT_VERSION(6, 24, 00)
4796 c->_value = value; // in future ROOT versions there is a changeVal method!
4797#else
4798 c->changeVal(value);
4799#endif
4800
4802 fParent->Vary(*this);
4803 }
4804
4805 sterilize();
4806 return true;
4807 } else if (auto f = dynamic_cast<RooHistFunc *>(o); f) {
4808 auto bin_pars = f->dataHist().get(bin - 1);
4809 if (f->getAttribute("density")) {
4810 value /= f->dataHist().binVolume(*bin_pars);
4811 }
4812 f->dataHist().set(*bin_pars, value);
4813 f->setValueDirty();
4814
4815 if (auto otherfName = f->getStringAttribute("symmetrized_by"); otherfName) {
4816 // broken symmetry, so update flags ...
4817 f->setStringAttribute("symmetrized_by", nullptr);
4818 if (auto x = getObject<RooAbsArg>(otherfName); x) {
4819 x->setStringAttribute("symmetrizes", nullptr);
4820 x->setStringAttribute("symmetrize_nominal", nullptr);
4821 }
4822 } else if (auto otherfName2 = f->getStringAttribute("symmetrizes"); otherfName2) {
4823 auto nomf = getObject<RooHistFunc>(f->getStringAttribute("symmetrize_nominal"));
4824 auto otherf = getObject<RooHistFunc>(otherfName2);
4825 if (nomf && otherf) {
4826 otherf->dataHist().set(*bin_pars, 2 * nomf->dataHist().weight(bin - 1) - value);
4827 otherf->setValueDirty();
4828 }
4829 }
4830 sterilize();
4831 return true;
4832 } else if (auto f2 = dynamic_cast<RooStats::HistFactory::FlexibleInterpVar *>(o); f2) {
4833 // changing nominal value
4834 f2->setNominal(value);
4835 }
4836 throw std::runtime_error(TString::Format("unable to set bin content of %s", GetPath().c_str()));
4837}
4838
4839bool xRooNode::SetBinData(int bin, double value, const xRooNode &data)
4840{
4841 if (data.get<RooAbsData>()) {
4842 // attach as a child before calling datasets(), so that is included in the list
4843 push_back(std::make_shared<xRooNode>(data));
4844 }
4845 auto node = datasets()[data.GetName()];
4846 if (data.get<RooAbsData>()) {
4847 // remove the child we attached
4848 resize(size() - 1);
4849 }
4850 return node->SetBinContent(bin, value);
4851}
4852
4853bool xRooNode::SetData(const TObject &obj, const xRooNode &data)
4854{
4855 if (data.get<RooAbsData>()) {
4856 // attach as a child before calling datasets(), so that is included in the list
4857 push_back(std::make_shared<xRooNode>(data));
4858 }
4859 auto node = datasets()[data.GetName()];
4860 if (data.get<RooAbsData>()) {
4861 // remove the child we attached
4862 resize(size() - 1);
4863 }
4864 return node->SetContents(obj);
4865}
4866
4867bool xRooNode::SetBinError(int bin, double value)
4868{
4869
4870 // if it's a RooProduct locate child with the same name
4871 if (get<RooProduct>()) {
4872 return factors()[GetName()]->SetBinError(bin, value);
4873 }
4874
4875 if (auto _varies = variations(); !_varies.empty()) {
4876 return _varies["nominal"]->SetBinError(bin, value);
4877 }
4878
4879 auto o = get();
4880
4881 if (auto f = dynamic_cast<RooHistFunc *>(o); f) {
4882
4883 // if (f->getAttribute("density")) { value /= f->dataHist().binVolume(*bin_pars); } - commented out because DON'T
4884 // convert .. sumw and sumw2 attributes will be stored not as densities
4885
4886 // NOTE: Can only do this because factors() makes parents of its children it's own parent (it isn't the parent)
4887 // If ever make factors etc part of the parentage then this would need tweaking to get to the true parent
4888 // find first parent that is a RooProduct, that is where the statFactor would live
4889 // stop as soon as we reach pdf object
4890 auto _prodParent = fParent;
4891 while (_prodParent && !_prodParent->get<RooProduct>() && !_prodParent->get<RooAbsPdf>()) {
4892 if (_prodParent->get<PiecewiseInterpolation>() && strcmp(GetName(), "nominal")) {
4893 _prodParent.reset();
4894 break; // only the 'nominal' variation can look for a statFactor outside the variation container
4895 }
4896 _prodParent = _prodParent->fParent;
4897 }
4898 auto _f_stat =
4899 (_prodParent && !_prodParent->get<RooAbsPdf>()) ? _prodParent->factors().find("statFactor") : nullptr;
4900 auto f_stat = (_f_stat) ? _f_stat->get<ParamHistFunc>() : nullptr;
4901 if (_f_stat && _f_stat->get() && !f_stat) {
4902 throw std::runtime_error("stat factor must be a paramhistfunc");
4903 }
4904
4905 // stat uncertainty lives in the "statFactor" factor, each sample has its own one,
4906 // but they can share parameters
4907 if (!f_stat) {
4908 if (value == 0)
4909 return true;
4910 TString parNames;
4911 for (auto &p : xRooNode("tmp", *f, std::shared_ptr<xRooNode>(nullptr)).vars()) {
4912 if (parNames != "")
4913 parNames += ",";
4914 parNames += p->get()->GetName();
4915 }
4916 auto h = std::unique_ptr<TH1>(f->dataHist().createHistogram(parNames
4917#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 27, 00)
4918 ,
4920#endif
4921 ));
4922 h->Reset();
4923 h->SetName("statFactor");
4924 h->SetTitle(TString::Format("StatFactor of %s", f->GetTitle()));
4925 h->SetOption("blankshape");
4926
4927 // multiply parent if is nominal
4928 auto toMultiply = this;
4929 if (strcmp(GetName(), "nominal") == 0 && fParent && fParent->get<PiecewiseInterpolation>())
4930 toMultiply = fParent.get();
4931
4932 f_stat = dynamic_cast<ParamHistFunc *>(toMultiply->Multiply(*h).get());
4933 if (!f_stat) {
4934 throw std::runtime_error("Failed creating stat shapeFactor");
4935 }
4936 }
4937
4938 auto phf = f_stat;
4939
4940 TString prefix = f->getStringAttribute("statPrefix");
4941 if (value && prefix == "") {
4942 // find the first parent that can hold components (RooAddPdf, RooRealSumPdf, RooAddition, RooWorkspace) ... use
4943 // that name for the stat factor
4944 auto _p = fParent;
4945 while (_p && !(_p->get()->InheritsFrom("RooRealSumPdf") || _p->get()->InheritsFrom("RooAddPdf") ||
4946 _p->get()->InheritsFrom("RooWorkspace") || _p->get()->InheritsFrom("RooAddition"))) {
4947 _p = _p->fParent;
4948 }
4949 prefix = TString::Format("stat_%s", (_p && _p->get<RooAbsReal>()) ? _p->get()->GetName() : f->GetName());
4950 }
4951 auto newVar = (value == 0) ? getObject<RooRealVar>("1")
4952 : acquire<RooRealVar>(Form("%s_bin%d", prefix.Data(), bin),
4953 Form("#gamma^{%s}_{%d}", prefix.Data(), bin), 1);
4954#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
4955 RooArgList &pSet = phf->_paramSet;
4956#else
4957 RooArgList &pSet = const_cast<RooArgList &>(phf->paramList());
4958#endif
4959 auto var = dynamic_cast<RooRealVar *>(&pSet[bin - 1]);
4960
4961 if (newVar.get() != var) {
4962 // need to swap out var for newVar
4963 // replace ith element in list with new func, or inject into RooProduct
4964 RooArgList all;
4965 for (std::size_t i = 0; i < pSet.size(); i++) {
4966 if (int(i) != bin - 1) {
4967 all.add(*pSet.at(i));
4968 } else {
4969 all.add(*newVar);
4970 }
4971 }
4972 pSet.removeAll();
4973 pSet.add(all);
4974 }
4975
4976 xRooNode v((value == 0) ? *var : *newVar, *this);
4977 auto rrv = dynamic_cast<RooRealVar *>(v.get());
4978 if (strcmp(rrv->GetName(), "1") != 0) {
4979 TString origName = (f->getStringAttribute("origName")) ? f->getStringAttribute("origName") : GetName();
4980 rrv->setStringAttribute(Form("sumw2_%s", origName.Data()), TString::Format("%f", pow(value, 2)));
4981 auto bin_pars = f->dataHist().get(bin - 1);
4982 auto _binContent = f->dataHist().weight(bin - 1);
4983 if (f->getAttribute("density")) {
4984 _binContent *= f->dataHist().binVolume(*bin_pars);
4985 }
4986 rrv->setStringAttribute(Form("sumw_%s", origName.Data()), TString::Format("%f", _binContent));
4987 double sumw2 = 0;
4988 double sumw = 0;
4989 for (auto &[s, sv] : rrv->stringAttributes()) {
4990 if (s.find("sumw_") == 0) {
4991 sumw += TString(sv).Atof();
4992 } else if (s.find("sumw2_") == 0) {
4993 sumw2 += TString(sv).Atof();
4994 }
4995 }
4996 if (sumw2 && sumw2 != std::numeric_limits<double>::infinity()) {
4997 double tau = pow(sumw, 2) / sumw2;
4998 rrv->setError((tau < 1e-15) ? 1e15 : (/*rrv->getVal()*/ 1. / sqrt(tau))); // not sure why was rrv->getVal()?
4999 rrv->setConstant(false);
5000 // parameter must be constrained
5001 auto _constr = v.constraints();
5002 // std::cout << " setting constraint " << v.GetName() << " nomin=" << tau << std::endl;
5003 if (_constr.empty()) {
5004 rrv->setStringAttribute("boundConstraint", _constr.Add("poisson").get()->GetName());
5005 } else {
5006 auto _glob = _constr.at(0)->obs().at(0)->get<RooRealVar>();
5007 // TODO: Update any globs snapshots that are designed to match the nominal
5008 _glob->setStringAttribute("nominal", TString::Format("%f", tau));
5009 double _min = tau * (1. - 5. * sqrt(1. / tau));
5010 double _max = tau * (1. + 5. * sqrt(1. / tau));
5011 _glob->setRange(_min, _max);
5012 _glob->setVal(tau);
5013 _constr.at(0)->pp().at(0)->SetBinContent(0, tau);
5014 rrv->setStringAttribute("boundConstraint", _constr.at(0)->get()->GetName());
5015 }
5016 rrv->setRange(std::max((1. - 5. * sqrt(1. / tau)), 1e-15), 1. + 5. * sqrt(1. / tau));
5017 } else {
5018 // remove constraint
5019 if (auto _constr = v.constraints(); !_constr.empty()) {
5020 v.constraints().Remove(*_constr.at(0));
5021 }
5022 // set const if sumw2 is 0 (i.e. no error)
5023 rrv->setVal(1);
5024 rrv->setError(0);
5025 rrv->setConstant(sumw2 == 0);
5026 }
5027 }
5028
5029 return true;
5030 }
5031
5032 throw std::runtime_error(TString::Format("%s SetBinError failed", GetName()));
5033}
5034
5035std::shared_ptr<xRooNode> xRooNode::at(const std::string &name, bool browseResult) const
5036{
5037 auto res = find(name, browseResult);
5038 if (res == nullptr)
5039 throw std::out_of_range(name + " does not exist");
5040 return res;
5041}
5042
5043////////////////////////////////////////////////////////////////////////////////
5044/// The RooWorkspace this node belong to, if any
5045
5047{
5048 if (auto _w = get<RooWorkspace>(); _w)
5049 return _w;
5050 if (auto a = get<RooAbsArg>(); a && GETWS(a)) {
5051 return GETWS(a);
5052 }
5053 if (fParent)
5054 return fParent->ws();
5055 return nullptr;
5056}
5057
5059{
5060
5061 xRooNode out(".constraints", nullptr, *this);
5062
5063 std::function<RooAbsPdf *(const xRooNode &n, RooAbsArg &par, std::set<RooAbsPdf *> ignore)> getConstraint;
5064 getConstraint = [&](const xRooNode &n, RooAbsArg &par, std::set<RooAbsPdf *> ignore) {
5065 if (auto _pdf = n.get<RooAbsPdf>()) {
5066 if (ignore.count(_pdf))
5067 return (RooAbsPdf *)nullptr;
5068 ignore.insert(_pdf);
5069 }
5070 auto o = n.get<RooProdPdf>();
5071 if (!o) {
5072 if (n.get<RooSimultaneous>()) {
5073 // check all channels for a constraint if is simultaneous
5074 for (auto &c : n.bins()) {
5075 if (auto oo = getConstraint(*c, par, ignore); oo) {
5076 return oo;
5077 }
5078 }
5079 return (RooAbsPdf *)nullptr;
5080 } else if (n.get<RooAbsPdf>() && n.fParent && n.fParent->get<RooWorkspace>()) {
5081 // reached top-level pdf, which wasn't a simultaneous, so stop here
5082 return (RooAbsPdf *)nullptr;
5083 } else if (auto _ws = n.get<RooWorkspace>(); _ws) {
5084 // reached a workspace, check for any pdf depending on parameter that isnt the ignore
5085 for (auto p : _ws->allPdfs()) {
5086 if (ignore.count(static_cast<RooAbsPdf *>(p)))
5087 continue;
5088 if (p->dependsOn(par)) {
5089 out.emplace_back(std::make_shared<xRooNode>(par.GetName(), *p, *this));
5090 }
5091 }
5092 }
5093 if (!n.fParent)
5094 return (RooAbsPdf *)nullptr;
5095 return getConstraint(*n.fParent, par, ignore);
5096 }
5097 for (auto p : o->pdfList()) {
5098 if (ignore.count(static_cast<RooAbsPdf *>(p)))
5099 continue;
5100 if (p->dependsOn(par)) {
5101 out.emplace_back(std::make_shared<xRooNode>(par.GetName(), *p, *this));
5102 }
5103 }
5104 return (RooAbsPdf *)nullptr;
5105 };
5106
5107 for (auto &p : vars()) {
5108 auto v = dynamic_cast<RooAbsReal *>(p->get());
5109 if (!v)
5110 continue;
5111 if (v->getAttribute("Constant") && v != get<RooAbsReal>())
5112 continue; // skip constants unless we are getting the constraints of a parameter itself
5113 if (v->getAttribute("obs"))
5114 continue; // skip observables ... constraints constrain pars not obs
5115 getConstraint(*this, *v, {get<RooAbsPdf>()});
5116 /*if (auto c = ; c) {
5117 out.emplace_back(std::make_shared<Node2>(p->GetName(), *c, *this));
5118 }*/
5119 }
5120
5121 // finish by removing any constraint that contains another constraint for the same par
5122 // and consolidate common pars
5123 auto it = out.std::vector<std::shared_ptr<xRooNode>>::begin();
5124 while (it != out.std::vector<std::shared_ptr<xRooNode>>::end()) {
5125 bool removeIt = false;
5126 for (auto &c : out) {
5127 if (c.get() == it->get())
5128 continue;
5129 if ((*it)->get<RooAbsArg>()->dependsOn(*c->get<RooAbsArg>())) {
5130 removeIt = true;
5131 std::set<std::string> parNames;
5132 std::string _cName = c->GetName();
5133 do {
5134 parNames.insert(_cName.substr(0, _cName.find(';')));
5135 _cName = _cName.substr(_cName.find(';') + 1);
5136 } while (_cName.find(';') != std::string::npos);
5137 parNames.insert(_cName);
5138 _cName = it->get()->GetName();
5139 do {
5140 parNames.insert(_cName.substr(0, _cName.find(';')));
5141 _cName = _cName.substr(_cName.find(';') + 1);
5142 } while (_cName.find(';') != std::string::npos);
5143 parNames.insert(_cName);
5144 _cName = "";
5145 for (auto &x : parNames) {
5146 if (!_cName.empty())
5147 _cName += ";";
5148 _cName += x;
5149 }
5150 c->TNamed::SetName(_cName.c_str());
5151 break;
5152 }
5153 }
5154 if (removeIt) {
5155 it = out.erase(it);
5156 } else {
5157 ++it;
5158 }
5159 }
5160
5161 // if getting constraints of a fundamental then use the constraint names instead of the par name (because would be
5162 // all same otherwise)
5163 if (get<RooAbsArg>() && get<RooAbsArg>()->isFundamental()) {
5164 for (auto &o : out) {
5165 o->TNamed::SetName(o->get()->GetName());
5166 }
5167 }
5168
5169 return out;
5170}
5171
5172std::shared_ptr<TObject> xRooNode::convertForAcquisition(xRooNode &acquirer, const char *opt) const
5173{
5174
5175 TString sOpt(opt);
5176 sOpt.ToLower();
5177 TString sName(GetName());
5178 if (sOpt == "func")
5179 sName = TString("factory:") + sName;
5180
5181 // if arg is a histogram, will acquire it as a RooHistFunc unless no conversion
5182 // todo: could flag not to convert
5183 if (auto h = get<TH1>(); h) {
5184 TString sOpt2(h->GetOption());
5185 std::map<std::string, std::string> stringAttrs;
5186 while (sOpt2.Contains("=")) {
5187 auto pos = sOpt2.Index("=");
5188 auto start = sOpt2.Index(";") + 1;
5189 if (start > pos)
5190 start = 0;
5191 auto end = sOpt2.Index(";", pos);
5192 if (end == -1)
5193 end = sOpt2.Length();
5194 stringAttrs[sOpt2(start, pos - start)] = sOpt2(pos + 1, end - pos - 1);
5195 sOpt2 = TString(sOpt2(0, start)) + TString(sOpt2(end + 1, sOpt2.Length()));
5196 }
5197 TString newObjName = GetName();
5198 TString origName = GetName();
5199 if (origName.BeginsWith(';'))
5200 origName = origName(1, origName.Length());
5201 if (newObjName.BeginsWith(';')) {
5202 newObjName =
5203 newObjName(1, newObjName.Length()); // special case if starts with ';' then don't create a fancy name
5204 } else if (acquirer.get() && !acquirer.get<RooWorkspace>()) {
5205 newObjName = TString::Format(
5206 "%s_%s", (acquirer.mainChild().get()) ? acquirer.mainChild()->GetName() : acquirer->GetName(),
5207 newObjName.Data());
5208 }
5209 // can convert to a RooHistFunc, or RooParamHist if option contains 'shape'
5210 TString varName = h->GetXaxis()->GetName();
5211 std::string binningName = newObjName.Data();
5212 if (auto pos = varName.Index(';'); pos != -1) {
5213 binningName = varName(pos + 1, varName.Length());
5214 varName = varName(0, pos);
5215 }
5216
5217 if (varName == "xaxis" &&
5218 !acquirer.get<RooSimultaneous>()) { // default case, try to take axis var and binning from the acquirer
5219 if (auto ax = acquirer.GetXaxis(); ax) {
5220 varName = ax->GetParent()->GetName();
5221 // TODO: check the binning is consistent before using - at least will check nBins below
5222 binningName = ax->GetName();
5223 } else if (acquirer.obs().size() == 1)
5224 varName = acquirer.obs().at(0)->get()->GetName(); // TODO what if no obs but Xaxis var is defined?
5225 }
5226 auto x = acquirer.acquire<RooRealVar>(varName, h->GetXaxis()->GetTitle(), h->GetXaxis()->GetXmin(),
5227 h->GetXaxis()->GetXmax());
5228 if (x->getMin() > h->GetXaxis()->GetXmin())
5229 x->setMin(h->GetXaxis()->GetXmin());
5230 if (x->getMax() < h->GetXaxis()->GetXmax())
5231 x->setMax(h->GetXaxis()->GetXmax());
5232 if (!x->hasBinning(binningName.c_str())) {
5233 if (h->GetXaxis()->IsVariableBinSize()) {
5234 x->setBinning(RooBinning(h->GetNbinsX(), h->GetXaxis()->GetXbins()->GetArray()), binningName.c_str());
5235 } else {
5236 x->setBinning(
5237 RooUniformBinning(h->GetXaxis()->GetXmin(), h->GetXaxis()->GetXmax(), h->GetXaxis()->GetNbins()),
5238 binningName.c_str());
5239 }
5240 x->getBinning(binningName.c_str()).SetTitle(h->GetXaxis()->GetTitle());
5241 if (x->getBinningNames().size() == 2) {
5242 // this was the first binning, so copy it over to be the default binning too
5243 x->setBinning(x->getBinning(binningName.c_str()));
5244 }
5245 } else {
5246 // TODO check binning is compatible with histogram
5247 if (x->getBinning(binningName.c_str()).numBins() != h->GetNbinsX()) {
5248 throw std::runtime_error(
5249 TString::Format("binning mismatch for binning %s of %s", binningName.c_str(), x->GetName()));
5250 }
5251 }
5252
5253 std::shared_ptr<RooAbsArg> _f;
5254
5255 // if acquirer is a RooSimultaneous, will use histogram to define a channel
5256 if (acquirer.get<RooSimultaneous>()) {
5257 _f = acquirer.acquireNew<RooProdPdf>(newObjName, (strlen(h->GetTitle())) ? h->GetTitle() : h->GetName(),
5258 RooArgList());
5259 for (auto &[k, v] : stringAttrs) {
5260 _f->setStringAttribute(k.c_str(), v.c_str());
5261 }
5262 x->setAttribute("obs", true);
5263 } else if (sOpt2.Contains("shape")) {
5264 RooArgList list;
5265 for (int i = 0; i < x->getBinning(binningName.c_str()).numBins(); i++) {
5266 std::shared_ptr<RooAbsArg> arg;
5267 if (sOpt2.Contains("blankshape")) {
5268 arg = acquirer.acquire2<RooAbsArg, RooRealVar>("1", "1", 1);
5269 } else {
5270 if (!h) {
5271 arg = acquirer.acquireNew<RooRealVar>(TString::Format("%s_bin%d", newObjName.Data(), i + 1), "", 1);
5272 } else if (h->GetMinimumStored() != -1111 || h->GetMaximumStored() != -1111) {
5273 arg = acquirer.acquireNew<RooRealVar>(TString::Format("%s_bin%d", newObjName.Data(), i + 1),
5274 TString::Format("%s_{%d}", h->GetTitle(), i + 1),
5275 h->GetBinContent(i + 1), h->GetMinimumStored(),
5276 h->GetMaximumStored());
5277 } else {
5278 arg = acquirer.acquireNew<RooRealVar>(TString::Format("%s_bin%d", newObjName.Data(), i + 1),
5279 TString::Format("%s_{%d}", h->GetTitle(), i + 1),
5280 h->GetBinContent(i + 1));
5281 }
5282 }
5283 list.add(*arg);
5284 }
5285 // paramhistfunc requires the binnings to be loaded as default at construction time
5286 // so load binning temporarily
5287 auto tmp = dynamic_cast<RooAbsBinning *>(x->getBinningPtr(nullptr)->Clone());
5288 x->setBinning(x->getBinning(binningName.c_str()));
5289 _f = acquirer.acquireNew<ParamHistFunc>(newObjName, h->GetTitle(), *x, list);
5290#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
5291 dynamic_cast<ParamHistFunc *>(_f.get())->_paramSet.setName("paramSet"); // so can see when print
5292#else
5293 const_cast<RooArgList &>(dynamic_cast<ParamHistFunc *>(_f.get())->paramList())
5294 .setName("paramSet"); // so can see when print
5295#endif
5296 x->setBinning(*tmp); // restore binning
5297 delete tmp;
5298 for (auto &[k, v] : stringAttrs) {
5299 _f->setStringAttribute(k.c_str(), v.c_str());
5300 }
5301 } else {
5302 auto dh = acquirer.acquireNew<RooDataHist>(Form("hist_%s", newObjName.Data()), h->GetTitle(), *x,
5303 binningName.c_str() /* binning name*/);
5304 if (!dh) {
5305 throw std::runtime_error("Couldn't make data hist");
5306 }
5307 auto f = acquirer.acquireNew<RooHistFunc>(newObjName, h->GetTitle(), *x, *dh,
5308 0 /*interpolation order between bins*/);
5309 f->forceNumInt();
5310 f->setAttribute("autodensity"); // where it gets inserted will determine if this is a density or not
5311 _f = f;
5312
5313 for (auto &[k, v] : stringAttrs) {
5314 _f->setStringAttribute(k.c_str(), v.c_str());
5315 }
5316
5317 // need to do these settings here because used in the assignment step
5318 _f->setStringAttribute("xvar", x->GetName());
5319 _f->setStringAttribute("binning", binningName.c_str());
5320 if (strcmp(_f->GetName(), origName.Data()) && !_f->getStringAttribute("alias"))
5321 _f->setStringAttribute("alias", origName);
5322
5323 // copy values over using the assignment operator - may convert to a RooProduct if there are stat uncerts
5324 xRooNode tmp(h->GetName(), _f, acquirer);
5325 tmp = *h;
5326 _f = std::dynamic_pointer_cast<RooAbsArg>(tmp.fComp); // in case got upgrade to a RooProduct
5327 }
5328
5329 _f->setStringAttribute("xvar", x->GetName());
5330 _f->setStringAttribute("binning", binningName.c_str());
5331 // style(h); // will transfer styling to object if necessary - not doing because this method used with plane hists
5332 // frequently
5333 if (strcmp(_f->GetName(), origName.Data()) && !_f->getStringAttribute("alias"))
5334 _f->setStringAttribute("alias", origName);
5335
5336 fComp = _f;
5337 return _f;
5338 } else if (!get() && (sName.BeginsWith("factory:") || sName.Contains("::")) && acquirer.ws()) {
5339 TString s(sName);
5340 if (sName.BeginsWith("factory:"))
5341 s = TString(s(8, s.Length()));
5342 fComp.reset(acquirer.ws()->factory(s), [](TObject *) {});
5343 if (fComp) {
5344 const_cast<xRooNode *>(this)->TNamed::SetName(fComp->GetName());
5345 }
5346 return fComp;
5347 }
5348
5349 return fComp;
5350}
5351
5352std::shared_ptr<TStyle> xRooNode::style(TObject *initObject, bool autoCreate) const
5353{
5354 return std::dynamic_pointer_cast<TStyle>(styles(initObject, autoCreate).fComp);
5355}
5356
5357xRooNode xRooNode::styles(TObject *initObject, bool autoCreate) const
5358{
5359 TString t = GetTitle();
5360
5361 auto arg = get<RooAbsArg>();
5362 if (!initObject && !arg && !gROOT->GetStyle(t)) {
5363 return nullptr;
5364 }
5365
5366 std::unique_ptr<TObject> argInitObject;
5367
5368 if (initObject) {
5369 t = (strlen(initObject->GetTitle())) ? initObject->GetTitle() : initObject->GetName();
5370 } else if (arg) {
5371 if (arg->getStringAttribute("style")) {
5372 t = arg->getStringAttribute("style");
5373 } else if (autoCreate) {
5374 // args will default to histo's object styling, whatever that currently may be
5375 argInitObject = std::make_unique<TH1D>(GetName(), GetTitle(), 1, 0, 1);
5376 initObject = argInitObject.get();
5377 } else {
5378 return nullptr;
5379 }
5380 }
5381
5382 std::shared_ptr<TStyle> style; // use to keep alive for access from GetStyle below, in case getObject has decided to
5383 // return the owning ptr (for some reason)
5384 if (!gROOT->GetStyle(t)) {
5385 if ((style = getObject<TStyle>(t.Data()))) {
5386 // loaded style (from workspace?) so put in list and use that
5387 gROOT->GetListOfStyles()->Add(style.get());
5388 } else {
5389 if (!autoCreate)
5390 return nullptr;
5391 // create new style - gets put in style list automatically so don't have to delete
5392 // acquire them so saved to workspaces for auto reload ...
5393 style = const_cast<xRooNode &>(*this).acquireNew<TStyle>(t.Data(),
5394 TString::Format("Style for %s component", t.Data()));
5395 if (auto x = dynamic_cast<TAttLine *>(initObject))
5396 ((TAttLine &)*style) = *x;
5397 if (auto x = dynamic_cast<TAttFill *>(initObject))
5398 ((TAttFill &)*style) = *x;
5399 if (auto x = dynamic_cast<TAttMarker *>(initObject))
5400 ((TAttMarker &)*style) = *x;
5401 gROOT->GetListOfStyles()->Add(style.get());
5402 }
5403 } else {
5404 style = std::shared_ptr<TStyle>(gROOT->GetStyle(t), [](TStyle *) {});
5405 }
5406
5407 if (arg && !arg->getStringAttribute("style")) {
5408 arg->setStringAttribute("style", style->GetName());
5409 }
5410
5411 return xRooNode(style, *this);
5412}
5413
5414std::shared_ptr<TObject> xRooNode::acquire(const std::shared_ptr<TObject> &arg, bool checkFactory, bool mustBeNew)
5415{
5416 if (!arg)
5417 return nullptr;
5418 if (!fAcquirer && !get<RooWorkspace>() && fParent)
5419 return fParent->acquire(arg, checkFactory, mustBeNew);
5420
5421 // if has a workspace and our object is the workspace or is in the workspace then add this object to workspace
5422 auto _ws = (fAcquirer) ? nullptr : ws();
5423 if (_ws && (get() == _ws || _ws->arg(GetName()) || (arg && strcmp(arg->GetName(), GetName()) == 0))) {
5426 if (auto a = dynamic_cast<RooAbsArg *>(arg.get()); a) {
5427 auto out_arg = _ws->arg(a->GetName());
5428 TString aName = arg->GetName();
5429 int ii = 1;
5430 while (out_arg && mustBeNew) {
5431 a->SetName(TString::Format("%s_%d", aName.Data(), ii++));
5432 out_arg = _ws->arg(a->GetName());
5433 }
5434 if (aName != a->GetName())
5435 Warning("acquire", "Renaming to %s", a->GetName());
5436 if (!out_arg) {
5437 bool done = false;
5438 if (checkFactory) {
5439 if (auto res = _ws->factory(arg->GetName()); res) {
5440 a = res;
5441 done = true;
5442 }
5443 }
5444 if (!done && _ws->import(*a, RooFit::RecycleConflictNodes())) {
5445 if (GETWS(a) != _ws) {
5446 Info("acquire", "A copy of %s has been added to workspace %s", a->GetName(), _ws->GetName());
5447 }
5449 return nullptr;
5450 }
5451 // sanitizeWS(); // clears the caches that might exist up to now, as well interfere with getParameters calls
5452 std::set<std::string> setNames;
5453 for (auto &aa : GETWSSETS(_ws)) {
5454 if (TString(aa.first.c_str()).BeginsWith("CACHE_")) {
5455 setNames.insert(aa.first);
5456 }
5457 }
5458 for (auto &aa : setNames)
5459 ws()->removeSet(aa.c_str());
5460 out_arg = _ws->arg(a->GetName());
5461 if (GETWS(out_arg) != _ws) { // seems that when objects imported their ws isn't set
5462 out_arg->setWorkspace(*_ws);
5463 }
5464 // if any of the leaf nodes of the imported object have "global" label on them, ensure propagate to
5465 // "globalObservables" list if ws has one
5466 if (auto globs = const_cast<RooArgSet *>(ws()->set("globalObservables")); globs) {
5467 RooArgSet leafs;
5468 out_arg->leafNodeServerList(&leafs);
5469 std::unique_ptr<RooAbsCollection> globals(leafs.selectByAttrib("global", true));
5470 for (auto &aa : *globals) {
5471 if (!globs->contains(*aa)) {
5472 globs->add(*aa);
5473 }
5474 }
5475 }
5476 }
5478 return std::shared_ptr<TObject>(out_arg, [](TObject *) {});
5479 } else if (auto a2 = dynamic_cast<RooAbsData *>(arg.get()); a2) {
5480 if (_ws->import(*a2, RooFit::Embedded())) {
5482 return nullptr;
5483 }
5485 return std::shared_ptr<TObject>(_ws->embeddedData(arg->GetName()), [](TObject *) {});
5486 } else if (arg->InheritsFrom("TNamed")) { // can add any TNamed to a workspace
5487 TObject *out_arg = nullptr;
5488 if (auto fr = dynamic_cast<RooFitResult *>(&*arg); fr && fr->numStatusHistory() == 0) {
5489 // fit results without a status history are treated as snapshots
5490 out_arg = fr->Clone();
5491 const_cast<RooLinkedList &>(GETWSSNAPSHOTS(_ws)).Add(out_arg);
5492 } else {
5493 // ensure will have a unique name for import if must be new
5494 TNamed *aNamed = dynamic_cast<TNamed *>(arg.get());
5495 TString aName = arg->GetName();
5496 out_arg = _ws->genobj(arg->GetName());
5497 int ii = 1;
5498 while (aNamed && out_arg && mustBeNew) {
5499 aNamed->SetName(TString::Format("%s;%d", aName.Data(), ii++));
5500 out_arg = _ws->genobj(aNamed->GetName());
5501 }
5502 if (!out_arg) {
5503 if (aName != arg->GetName()) {
5504 Warning("acquire", "Renaming to %s", arg->GetName());
5505 }
5506 if (_ws->import(*arg, false /*replace existing*/)) {
5508 return nullptr;
5509 }
5510 out_arg = _ws->genobj(arg->GetName());
5511 }
5512 }
5514
5515 return std::shared_ptr<TObject>(out_arg, [](TObject *) {});
5516 }
5518 // Warning("acquire","Not implemented acquisition of object %s",arg->GetName());
5519 // return nullptr;
5520 }
5521 if (!mustBeNew && fProvider) {
5522 auto out = fProvider->getObject(arg->GetName(), arg->ClassName());
5523 if (out)
5524 return out;
5525 }
5526 auto _owned = find(".memory");
5527 if (!_owned) {
5528 _owned = emplace_back(std::make_shared<xRooNode>(".memory", nullptr, *this));
5529 }
5530 // look for exact name, dont use 'find' because doesnt work if trying to find "1" and it doesn't exist, will get back
5531 // idx 1 instead
5532 if (!mustBeNew) {
5533 for (auto &r : *_owned) {
5534 if (strcmp(r->GetName(), arg->GetName()) == 0 && strcmp(r->get()->ClassName(), arg->ClassName()) == 0) {
5535 return r->fComp;
5536 }
5537 }
5538 }
5539 if (!fProvider)
5540 std::cout << GetName() << " taking over " << arg->ClassName() << "::" << arg->GetName() << std::endl;
5541 /*emplace_back(std::make_shared<Node2>(".memory",nullptr,*this))*/
5542 return _owned->emplace_back(std::make_shared<xRooNode>(arg->GetName(), arg, *this))->fComp;
5543 // return arg;
5544}
5545
5546bool xRooNode::SetXaxis(const char *name, const char *title, int nbins, double low, double high)
5547{
5548 RooUniformBinning b(low, high, nbins, name);
5549 b.SetTitle(title);
5550 return SetXaxis(b);
5551}
5552
5553bool xRooNode::SetXaxis(const char *name, const char *title, int nbins, const double *bins)
5554{
5555 RooBinning b(nbins, bins, name);
5556 b.SetTitle(title);
5557 return SetXaxis(b);
5558}
5559
5561{
5562
5563 auto name = binning.GetName();
5564 double high = binning.highBound();
5565 double low = binning.lowBound();
5566 // int nbins = binning.numBins();
5567 auto title = binning.GetTitle();
5568
5569 // if have any dependents and name isn't one of them then stop
5570 auto _deps = vars();
5571 /*if(!_deps.empty() && !_deps.find(name)) {
5572 throw std::runtime_error(TString::Format("%s Does not depend on %s",GetName(),name));
5573 }*/
5574
5575 // object will need to exist
5576 if (!get()) {
5577 if (fParent && !find(GetName())) {
5578 fComp = fParent->Add(*this, "+").fComp;
5579 }
5580 }
5581
5582 auto a = get<RooAbsArg>();
5583 if (!a)
5584 throw std::runtime_error("Cannot SetXaxis of non-arg");
5585
5586 auto _x = acquire<RooRealVar>(name, title, low, high);
5587 _x->setBinning(binning, a->GetName());
5588 _x->getBinning(a->GetName()).SetTitle(title);
5589 if (_x->getBinningNames().size() == 2) {
5590 // this was the first binning, so copy it over to be the default binning too
5591 _x->setBinning(_x->getBinning(a->GetName()));
5592 } else {
5593 // ensure the default binning is wide enough to cover this range
5594 // the alternative to this would be to ensure setNormRange of all pdfs
5595 // are set to correct range (then default can be narrower than some of the named binnings)
5596 if (_x->getMax() < high)
5597 _x->setMax(high);
5598 if (_x->getMin() > low)
5599 _x->setMin(low);
5600 }
5601
5602 if (!_deps.find(name) && get<RooAbsPdf>()) {
5603 // creating a variable for a pdf we will assume it should be an observable
5604 _x->setAttribute("obs");
5605 }
5606
5607 a->setStringAttribute("xvar", _x->GetName());
5608 a->setStringAttribute("binning", a->GetName());
5609 fXAxis.reset(); // remove any existing xaxis
5610
5611 return true;
5612}
5613
5615{
5616 if (!ax)
5617 return false;
5618 if (ax->IsVariableBinSize()) {
5619 return SetXaxis(ax->GetName(), ax->GetTitle(), ax->GetNbins(), ax->GetXbins()->GetArray());
5620 } else {
5621 return SetXaxis(ax->GetName(), ax->GetTitle(), ax->GetNbins(), ax->GetXmin(), ax->GetXmax());
5622 }
5623}
5624
5625bool xRooNode::contains(const std::string &name) const
5626{
5627 return find(name, false) != nullptr;
5628}
5629
5630std::shared_ptr<xRooNode> xRooNode::find(const std::string &name, bool browseResult) const
5631{
5632 std::string partname = (name.find('/') != std::string::npos) ? name.substr(0, name.find('/')) : name;
5633 auto _s = (!get() && fParent) ? fParent->get<RooSimultaneous>()
5634 : get<RooSimultaneous>(); // makes work if doing simPdf.bins()["blah"]
5635 std::string extra = (_s) ? _s->indexCat().GetName() : "";
5636 for (auto &child : *this) {
5637 if (auto _obj = child->get(); name == child->GetName() || partname == child->GetName() ||
5638 (_obj && name == _obj->GetName()) || (_obj && partname == _obj->GetName()) ||
5639 (!extra.empty() && ((extra + "=" + name) == child->GetName() ||
5640 (extra + "=" + partname) == child->GetName()))) {
5641 if (browseResult)
5642 child->browse(); // needed so can go at()->at()->at()...
5643 if (partname != name && name != child->GetName()) {
5644 return child->at(name.substr(partname.length() + 1));
5645 }
5646 return child;
5647 }
5648 if (partname.find('.') != 0) { // do not allow mainChild browsing if trying to find a "." child ... as is done in
5649 // getObject for ".memory"
5650 if (auto x = mainChild(); x && strcmp(child->GetName(), x.GetName()) == 0) {
5651 // can browse directly into main children as if their children were our children
5652 for (auto &child2 : x.browse()) {
5653 if (auto _obj = child2->get(); name == child2->GetName() || partname == child2->GetName() ||
5654 (_obj && name == _obj->GetName()) ||
5655 (_obj && partname == _obj->GetName())) {
5656 if (browseResult)
5657 child2->browse(); // needed for onward read (or is it? there's a browse above too??)
5658 if (partname != name && name != child2->GetName()) {
5659 return child2->at(name.substr(partname.length() + 1));
5660 }
5661 return child2;
5662 }
5663 }
5664 }
5665 }
5666 }
5667 // before giving up see if partName is numeric and indexes within the range
5668 if (TString s(partname); s.IsDec() && size_t(s.Atoi()) < size()) {
5669 auto child2 = at(s.Atoi());
5670 if (partname != name) {
5671 return child2->at(name.substr(partname.length() + 1));
5672 }
5673 return child2;
5674 }
5675 // allow calling of find on a RooWorkspace to access getObject objects ...
5676 if (get<RooWorkspace>() && name != ".memory") {
5677 if (auto obj = getObject(name)) {
5678 auto out = std::make_shared<xRooNode>(obj, *this);
5679 if (browseResult)
5680 out->browse();
5681 return out;
5682 }
5683 }
5684 return nullptr;
5685}
5686
5687std::shared_ptr<xRooNode> xRooNode::operator[](const std::string &name)
5688{
5689 std::string partname = (name.find('/') != std::string::npos) ? name.substr(0, name.find('/')) : name;
5690 browse();
5691 auto _s = (!get() && fParent) ? fParent->get<RooSimultaneous>()
5692 : get<RooSimultaneous>(); // makes work if doing simPdf.bins()["blah"]
5693 std::string extra = (_s) ? _s->indexCat().GetName() : "";
5694 std::shared_ptr<xRooNode> folderNode;
5695 for (auto &child : *this) {
5696 if (name == child->GetName() || partname == child->GetName() ||
5697 (!extra.empty() &&
5698 ((extra + "=" + name) == child->GetName() || (extra + "=" + partname) == child->GetName()))) {
5699 child->browse(); // needed for onward read (or is it? there's a browse above too??)
5700 if (partname != name && name != child->GetName()) {
5701 return child->operator[](name.substr(partname.length() + 1));
5702 }
5703 return child;
5704 }
5705 if (auto x = mainChild(); strcmp(child->GetName(), x.GetName()) == 0) {
5706 // can browse directly into main children as if their children were our children
5707 for (auto &child2 : x.browse()) {
5708 if (name == child2->GetName() || partname == child2->GetName()) {
5709 child2->browse(); // needed for onward read (or is it? there's a browse above too??)
5710 if (partname != name && name != child2->GetName()) {
5711 return child2->operator[](name.substr(partname.length() + 1));
5712 }
5713 return child2;
5714 }
5715 }
5716 }
5717 if (child->fFolder == (std::string("!") + partname)) {
5718 if (!folderNode)
5719 folderNode = std::make_shared<xRooNode>(child->fFolder.c_str(), nullptr, *this);
5720 folderNode->push_back(child);
5721 }
5722 }
5723 if (folderNode) {
5724 if (partname != name) {
5725 return folderNode->operator[](name.substr(partname.length() + 1));
5726 }
5727 return folderNode;
5728 }
5729 // before giving up see if partName is numeric and indexes within the range
5730 if (TString s(partname); s.IsDec() && size_t(s.Atoi()) < size()) {
5731 auto child2 = at(s.Atoi());
5732 if (partname != name) {
5733 return child2->operator[](name.substr(partname.length() + 1));
5734 }
5735 return child2;
5736 }
5737 auto out = std::make_shared<xRooNode>(partname.c_str(), nullptr, *this); // not adding as child yeeet
5738 // special case, if creating a node in the workspace with a specific name, it's a folder node ...
5739 if (get<RooWorkspace>() && partname == "pdfs") {
5740 out->SetName("!pdfs");
5741 }
5742 if (partname != name) {
5743 return out->operator[](name.substr(partname.length() + 1));
5744 }
5745 return out;
5746}
5747
5749{
5750 if (!b) {
5751 for (auto o : *gROOT->GetListOfBrowsers()) {
5752 b = dynamic_cast<TBrowser *>(o);
5753 if (!b || !b->GetBrowserImp())
5754 continue;
5755 if (auto out = GetTreeItem(b); out)
5756 return out;
5757 }
5758 return nullptr;
5759 }
5760 if (!b->GetBrowserImp())
5761 return nullptr;
5762 if (auto _b = dynamic_cast<TGFileBrowser *>(GETACTBROWSER(dynamic_cast<TRootBrowser *>(b->GetBrowserImp()))); _b) {
5763 auto _root = GETROOTDIR(_b);
5764 ;
5765 if (!_root)
5766 _root = GETLISTTREE(_b)->GetFirstItem();
5768 return GETLISTTREE(_b)->FindItemByObj(_root, const_cast<xRooNode *>(this));
5769 }
5770 return nullptr;
5771}
5772
5774{
5775 if (!b) {
5776 for (auto o : *gROOT->GetListOfBrowsers()) {
5777 b = dynamic_cast<TBrowser *>(o);
5778 if (!b || !b->GetBrowserImp())
5779 continue;
5780 if (auto out = GetListTree(b); out)
5781 return out;
5782 }
5783 return nullptr;
5784 }
5785 if (b->GetBrowserImp()) {
5786 if (auto _b = dynamic_cast<TGFileBrowser *>(GETACTBROWSER(dynamic_cast<TRootBrowser *>(b->GetBrowserImp())));
5787 _b) {
5788 auto _root = GETROOTDIR(_b);
5789 if (!_root)
5790 _root = GETLISTTREE(_b)->GetFirstItem();
5791 if (auto item = GETLISTTREE(_b)->FindItemByObj(_root, const_cast<xRooNode *>(this)); item) {
5792 return GETLISTTREE(_b);
5793 }
5794 }
5795 }
5796 return nullptr;
5797}
5798
5799void xRooNode::SetName(const char *name)
5800{
5802 if (auto a = get<RooAbsArg>(); a)
5803 a->setStringAttribute("alias", name);
5804 for (auto o : *gROOT->GetListOfBrowsers()) {
5805 if (auto b = dynamic_cast<TBrowser *>(o); b) {
5806 if (auto item = GetTreeItem(b); item) {
5807 item->SetText(name);
5808 }
5809 }
5810 }
5811}
5812
5813void xRooNode::SetTitle(const char *title)
5814{
5815 if (auto o = (get<TNamed>()); o) {
5816 if (auto c = mainChild(); c.get()) {
5817 c.SetTitle(title);
5818 }
5819 o->SetTitle(title);
5820 }
5821 TNamed::SetTitle(title);
5822}
5823
5825{
5826 if (get<RooArgList>() || (!get() && !(strlen(GetName()) > 0 && (GetName()[0] == '!')) && !fBrowseOperation))
5827 return *this; // nothing to browse - 'collection' nodes should already be populated except for folders
5828 // alternative could have been to mandate that the 'components' of a collection node are the children it has.
5829
5830 auto findByObj = [&](const std::shared_ptr<xRooNode> &n) {
5831 std::vector<std::shared_ptr<xRooNode>> &nn = *this;
5832 for (auto &c : nn) {
5833 if (c->get() == n->get() && strcmp(n->GetName(), c->GetName()) == 0)
5834 return c;
5835 }
5836 return std::shared_ptr<xRooNode>(nullptr);
5837 };
5838
5839 auto appendChildren = [&](const xRooNode &n) {
5840 size_t out = 0;
5841 const std::vector<std::shared_ptr<xRooNode>> &nn(n);
5842 for (auto &c : nn) {
5843 if (auto existing = findByObj(c); existing) {
5844 existing->fTimes++;
5845 existing->fFolder = c->fFolder; // transfer folder assignment
5846 } else {
5847 emplace_back(c);
5848 }
5849 if (!TString(c->GetName()).BeginsWith(".coef"))
5850 out++; // don't count .coef as a child, as technically part of parent
5851 }
5852 return out;
5853 };
5854
5855 const std::vector<std::shared_ptr<xRooNode>> &nn2(*this);
5856 for (auto &c : nn2) {
5857 if (strlen(c->GetName()) > 0 && (c->GetName()[0] == '.')) {
5858 c->fTimes = 1;
5859 continue;
5860 } // never auto-cleanup property children
5861 if (strcmp(c->GetName(), "!.pars") == 0) {
5862 c->fTimes = 1;
5863 continue;
5864 } // special collection, also not cleaned up
5865 if (c->get<RooWorkspace>() || c->get<TFile>()) {
5866 c->fTimes = 1;
5867 continue;
5868 } // workspaces and files not cleaned up: TODO have a nocleanup flag instead
5869 c->fTimes = 0;
5870 }
5871
5872 size_t addedChildren = 0;
5873 if (fBrowseOperation) {
5874 addedChildren += appendChildren(fBrowseOperation(this));
5875 } else {
5876 if (get<RooWorkspace>()) {
5877 addedChildren += appendChildren(datasets());
5878 }
5879
5880 // if (get<RooAbsPdf>() && ((fParent && fParent->get<RooWorkspace>()) || !fParent)) {
5881 // // top-level pdfs will also list the ".vars" property for -- should make this updateable
5882 // //if (auto x = find("!.vars"); !x) { // this is slower because it triggers a browse of !.vars
5883 // if(!contains("!.vars")) {
5884 // emplace_back(std::make_shared<Node2>("!.vars",nullptr,*this));
5885 // } /*else {
5886 // x->fTimes++;
5887 // }*/
5888 // }
5889
5890 // go through components factors and variations, adding all as children if required
5891 addedChildren += appendChildren(components());
5892 if (!get<RooWorkspace>())
5893 addedChildren += appendChildren(factors());
5894 // include coefs if any
5895 auto _coefs = coefs();
5896 if (_coefs.get() && strcmp(_coefs->GetName(), "1") != 0 && strcmp(_coefs->GetName(), "ONE") != 0) {
5897 if (_coefs.size() == 1 && _coefs.get<RooAddition>()) {
5898 if (strcmp(_coefs.at(0)->GetName(), "1") != 0 &&
5899 strcmp(_coefs.at(0)->GetName(), "ONE") != 0) { // don't add the "1"
5900 auto coef = std::make_shared<xRooNode>(".coef", *_coefs.at(0)->get(), *this);
5901 if (auto existing = findByObj(coef); existing) {
5902 existing->fTimes++;
5903 existing->fFolder = _coefs.at(0)->fFolder; // transfer folder assignment
5904 } else {
5905 emplace_back(coef);
5906 }
5907 }
5908 } else {
5909 if (auto existing = find(_coefs.GetName()); existing) {
5910 existing->fTimes++;
5911 existing->fFolder = _coefs.fFolder; // transfer folder assignment
5912 } else {
5913 emplace_back(std::make_shared<xRooNode>(_coefs));
5914 }
5915 }
5916 }
5917 addedChildren += appendChildren(variations());
5918 if (get<ParamHistFunc>() || get<RooSimultaneous>())
5919 addedChildren += appendChildren(bins());
5920 if (get<RooAbsData>())
5921 addedChildren += appendChildren(obs());
5922 }
5923 // if has no children and is a RooAbsArg, add all the proxies
5924 if (auto arg = get<RooAbsArg>(); arg && addedChildren == 0) {
5925 for (int i = 0; i < arg->numProxies(); i++) {
5926 auto _proxy = arg->getProxy(i);
5927 if (auto a = dynamic_cast<RooArgProxy *>(_proxy)) {
5928 auto c = std::make_shared<xRooNode>(TString::Format(".%s", _proxy->name()), *(a->absArg()), *this);
5929 if (auto existing = findByObj(c); existing) {
5930 existing->fTimes++;
5931 existing->fFolder = c->fFolder; // transfer folder assignment
5932 } else {
5933 // mark any existing children with the same name for cleanup - this happens e.g. if did a Replace on one
5934 // of these nodes note that the child nodes will still become reordered (the old node will be deleted,
5935 // new node will appear at end)
5936 for (auto &child : *this) {
5937 if (strcmp(child->GetName(), c->GetName()) == 0) {
5938 child->fTimes = 0;
5939 }
5940 }
5941 emplace_back(c);
5942 }
5943 } else if (auto s = dynamic_cast<RooAbsCollection *>(_proxy)) {
5944 for (auto a2 : *s) {
5945 auto c = std::make_shared<xRooNode>(*a2, *this);
5946 if (arg->numProxies() != 1) {
5947 c->fFolder = std::string("!.") +
5948 _proxy->name(); // don't put in a folder if there's just 1 proxy (the collection)
5949 }
5950 if (auto existing = findByObj(c); existing) {
5951 existing->fTimes++;
5952 existing->fFolder = c->fFolder; // transfer folder assignment
5953 } else {
5954 emplace_back(c);
5955 }
5956 }
5957 }
5958 }
5959 /*for(auto& s : arg->servers()) {
5960 auto c = std::make_shared<xRooNode>(*s,*this);
5961 if (auto existing = findByObj(c); existing) {
5962 existing->fTimes++;
5963 existing->fFolder = c->fFolder; // transfer folder assignment
5964 } else {
5965 emplace_back(c);
5966 }
5967 }*/
5968 } else if (auto ir = get<RooStats::HypoTestInverterResult>()) {
5969 // check if we already have a hypoSpace in our memory
5970 bool hasHS = false;
5971 for (auto &c : fBrowsables) {
5972 if (strcmp(c->GetName(), ".memory") == 0 && c->get<xRooHypoSpace>()) {
5973 hasHS = true;
5974 break;
5975 }
5976 }
5977 if (!hasHS) {
5978 // add the HS
5979 auto hs =
5980 fBrowsables.emplace_back(std::make_shared<xRooNode>(".memory", std::make_shared<xRooHypoSpace>(ir), *this));
5981 // add the hypoPoints first so they appear first
5982 auto _axes = hs->get<xRooHypoSpace>()->axes();
5983
5984 int i = 0;
5985 for (auto &hp : *hs->get<xRooHypoSpace>()) {
5986 TString coordString;
5987 for (auto a : _axes) {
5988 if (a != _axes.first())
5989 coordString += ",";
5990 coordString +=
5991 TString::Format("%s=%g", a->GetName(), hp.coords->getRealValue(a->GetName(), ir->GetXValue(i)));
5992 }
5993 auto hpn = emplace_back(std::make_shared<xRooNode>(coordString, hp.hypoTestResult, hs));
5994 hpn->fTimes++;
5995 hpn->fBrowsables.emplace_back(std::make_shared<xRooNode>(
5996 ".memory", std::shared_ptr<xRooNLLVar::xRooHypoPoint>(&hp, [](xRooNLLVar::xRooHypoPoint *) {}), hpn));
5997 i++;
5998 }
5999 } else {
6000 // ensure all hypoTestResults are flagged as keep-alive
6001 std::vector<std::shared_ptr<xRooNode>> &nn = *this;
6002 for (auto &c : nn) {
6003 if (c->get<RooStats::HypoTestResult>())
6004 c->fTimes++;
6005 }
6006 }
6007 // xRooNode tests;
6008 // for(int i=0;i<ir->ArraySize();i++) {
6009 // tests.push_back(std::make_shared<xRooNode>(TString::Format("%g",ir->GetXValue(i)),*ir->GetResult(i),*this));
6010 // }
6011 // appendChildren(tests);
6012 } else if (get<RooStats::HypoTestResult>()) {
6013
6014 // create the xRooHypoPoint if necessary
6015 xRooNLLVar::xRooHypoPoint *hp = nullptr;
6016 for (auto &c : fBrowsables) {
6017 if (strcmp(c->GetName(), ".memory") == 0 && c->get<xRooNLLVar::xRooHypoPoint>()) {
6018 hp = c->get<xRooNLLVar::xRooHypoPoint>();
6019 c->fTimes++; // keep it alive
6020 break;
6021 }
6022 }
6023 if (!hp) {
6024 auto shp =
6025 std::make_shared<xRooNLLVar::xRooHypoPoint>(std::dynamic_pointer_cast<RooStats::HypoTestResult>(fComp));
6026 fBrowsables.emplace_back(std::make_shared<xRooNode>(".memory", shp, *this));
6027 hp = shp.get();
6028 }
6029
6030 xRooNode fits;
6031
6032 if (auto fit = hp->ufit()) {
6033 fits.emplace_back(std::make_shared<xRooNode>(fit, *this))->TNamed::SetName("ufit");
6034 }
6035 if (auto fit = hp->cfit_null()) {
6036 fits.emplace_back(std::make_shared<xRooNode>(fit, *this))->TNamed::SetName("cfit_null");
6037 }
6038 if (auto fit = hp->cfit_alt()) {
6039 fits.emplace_back(std::make_shared<xRooNode>(fit, *this))->TNamed::SetName("cfit_alt");
6040 }
6041 if (auto fit = hp->gfit()) {
6042 fits.emplace_back(std::make_shared<xRooNode>(fit, *this))->TNamed::SetName("gfit");
6043 }
6044 if (auto asi = hp->asimov()) {
6045 auto asiP = fits.emplace_back(std::make_shared<xRooNode>(
6046 asi->hypoTestResult ? asi->hypoTestResult : std::make_shared<RooStats::HypoTestResult>(asi->result()),
6047 *this));
6048 asiP->TNamed::SetName("asimov");
6049 asiP->fBrowsables.emplace_back(std::make_shared<xRooNode>(".memory", asi, asiP));
6050 }
6051 appendChildren(fits);
6052 }
6053
6054 // clear anything that has fTimes = 0 still
6055 auto it = std::vector<std::shared_ptr<xRooNode>>::begin();
6056 while (it != std::vector<std::shared_ptr<xRooNode>>::end()) {
6057 if (it->get()->fTimes == 0) {
6058 for (auto o : *gROOT->GetListOfBrowsers()) {
6059 auto b = dynamic_cast<TBrowser *>(o);
6060 if (b && b->GetBrowserImp()) { // browserImp is null if browser was closed
6061 // std::cout << GetPath() << " Removing " << it->get()->GetPath() << std::endl;
6062
6063 if (auto _b =
6064 dynamic_cast<TGFileBrowser *>(GETACTBROWSER(dynamic_cast<TRootBrowser *>(b->GetBrowserImp())));
6065 _b) {
6066 auto _root = GETROOTDIR(_b);
6067 if (!_root)
6068 _root = GETLISTTREE(_b)->GetFirstItem();
6069 if (auto item = GETLISTTREE(_b)->FindItemByObj(_root, this); item) {
6070 GETLISTTREE(_b)->OpenItem(item);
6071 }
6072 }
6073
6074 b->RecursiveRemove(
6075 it->get()); // problem: if obj is living in a collapsed node it wont actually get deleted
6076 /*auto _b = dynamic_cast<TGFileBrowser*>( dynamic_cast<TRootBrowser*>(b->GetBrowserImp())->fActBrowser );
6077 if (_b) {
6078 std::cout << _b->fRootDir->GetText() << std::endl;
6079 if (auto item = _b->fListTree->FindItemByObj(_b->fRootDir,it->get()); item) {
6080 std::cout << "Found obj: " << item << " " << item->GetText() << std::endl;
6081 _b->fListTree->RecursiveDeleteItem(_b->fRootDir,it->get());
6082 }
6083
6084 //b->RecursiveRemove(it->get());
6085 if (auto item = _b->fListTree->FindItemByObj(_b->fRootDir,it->get()); item) {
6086 std::cout << "Still Found obj: " << item << std::endl;
6087 }
6088 _b->fListTree->ClearViewPort();
6089
6090 }*/
6091 }
6092 }
6093 /*it->get()->ResetBit(TObject::kNotDeleted); ++it;*/ it = erase(it);
6094 } else {
6095 ++it;
6096 }
6097 }
6098
6099 return *this;
6100}
6101
6102////////////////////////////////////////////////////////////////////////////////
6103/// List of observables (global and regular) of this node.
6104
6106{
6107 xRooNode out(".obs", std::make_shared<RooArgList>(), *this);
6108 out.get<RooArgList>()->setName((GetPath() + ".obs").c_str());
6109 for (auto o : vars()) {
6110 if (o->get<RooAbsArg>()->getAttribute("obs")) {
6111 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6112 out.emplace_back(o);
6113 }
6114 }
6115 return out;
6116}
6117
6118////////////////////////////////////////////////////////////////////////////////
6119/// List of global observables of this node.
6120
6122{
6123 xRooNode out(".globs", std::make_shared<RooArgList>(), *this);
6124 out.get<RooArgList>()->setName((GetPath() + ".globs").c_str());
6125 for (auto o : obs()) {
6126 if (o->get<RooAbsArg>()->getAttribute("global")) {
6127 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6128 out.emplace_back(o);
6129 }
6130 }
6131 return out;
6132}
6133
6134////////////////////////////////////////////////////////////////////////////////
6135/// List of regular observables of this node.
6136
6138{
6139 xRooNode out(".robs", std::make_shared<RooArgList>(), *this);
6140 out.get<RooArgList>()->setName((GetPath() + ".robs").c_str());
6141 for (auto o : obs()) {
6142 if (!o->get<RooAbsArg>()->getAttribute("global")) {
6143 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6144 out.emplace_back(o);
6145 }
6146 }
6147 return out;
6148}
6149
6150////////////////////////////////////////////////////////////////////////////////
6151/// List of parameters (non-observables) of this node.
6152
6154{
6155 if (strcmp(GetName(), ".bins") == 0 && fParent) {
6156 // return pars of the parent - this method is used by covariances() if e.g. do node.bins().covariances()
6157 return fParent->pars();
6158 }
6159 xRooNode out(".pars", std::make_shared<RooArgList>(), *this);
6160 out.get<RooArgList>()->setName((GetPath() + ".pars").c_str());
6161 for (auto o : vars()) {
6162 if (!o->get<RooAbsArg>()->getAttribute("obs")) {
6163 out.get<RooArgList>()->add(*(o->get<RooAbsArg>()));
6164 out.emplace_back(o);
6165 }
6166 }
6167 return out;
6168}
6169
6170////////////////////////////////////////////////////////////////////////////////
6171/// List of parameters that are currently constant
6172
6174{
6175 xRooNode out(".consts", std::make_shared<RooArgList>(), *this);
6176 out.get<RooArgList>()->setName((GetPath() + ".consts").c_str());
6177 for (auto o : pars()) {
6178 if (o->get<RooAbsArg>()->getAttribute("Constant") || o->get<RooConstVar>()) {
6179 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6180 out.emplace_back(o);
6181 }
6182 }
6183 return out;
6184}
6185
6186////////////////////////////////////////////////////////////////////////////////
6187/// List of parameters that are currently non-constant
6188/// These parameters do not have the "Constant" attribute
6189
6191{
6192 xRooNode out(".floats", std::make_shared<RooArgList>(), *this);
6193 out.get<RooArgList>()->setName((GetPath() + ".floats").c_str());
6194 for (auto o : pars()) {
6195 if (!o->get<RooAbsArg>()->getAttribute("Constant") && !o->get<RooConstVar>()) {
6196 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6197 out.emplace_back(o);
6198 }
6199 }
6200 return out;
6201}
6202
6203////////////////////////////////////////////////////////////////////////////////
6204/// List of parameters of interest: parameters marked as "of interest"
6205/// These parameters have the "poi" attribute
6206
6208{
6209 xRooNode out(".poi", std::make_shared<RooArgList>(), *this);
6210 out.get<RooArgList>()->setName((GetPath() + ".poi").c_str());
6211 for (auto o : pars()) {
6212 if (o->get<RooAbsArg>()->getAttribute("poi")) {
6213 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6214 out.emplace_back(o);
6215 }
6216 }
6217 return out;
6218}
6219
6220////////////////////////////////////////////////////////////////////////////////
6221/// List of nuisance parameters: non-constant parameters that are not marked of interest,
6222/// as well as any parameters that have been marked by the "np" attribute
6223
6225{
6226 xRooNode out(".np", std::make_shared<RooArgList>(), *this);
6227 out.get<RooArgList>()->setName((GetPath() + ".np").c_str());
6228 for (auto o : pars()) {
6229 if (o->get<RooAbsArg>()->getAttribute("np") ||
6230 (!o->get<RooAbsArg>()->getAttribute("Constant") && !o->get<RooAbsArg>()->getAttribute("poi") &&
6231 !o->get<RooConstVar>())) {
6232 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6233 out.emplace_back(o);
6234 }
6235 }
6236 return out;
6237}
6238
6239////////////////////////////////////////////////////////////////////////////////
6240/// List of prespecified parameters: non-floatable parameters
6241
6243{
6244 xRooNode out(".pp", std::make_shared<RooArgList>(), *this);
6245 out.get<RooArgList>()->setName((GetPath() + ".pp").c_str());
6246 for (auto o : pars()) {
6247 if (!o->get<RooAbsArg>()->getAttribute("np") && !o->get<RooAbsArg>()->getAttribute("poi") &&
6248 (o->get<RooAbsArg>()->getAttribute("Constant") || o->get<RooConstVar>())) {
6249 out.get<RooArgList>()->add(*o->get<RooAbsArg>());
6250 out.emplace_back(o);
6251 }
6252 }
6253 return out;
6254}
6255
6256////////////////////////////////////////////////////////////////////////////////
6257/// List of variables (observables and parameters) of this node
6258
6260{
6261 xRooNode out(".vars", std::make_shared<RooArgList>(), *this);
6262 out.get<RooArgList>()->setName((GetPath() + ".vars").c_str());
6263 if (auto coll = get<RooAbsCollection>(); coll) {
6264 for (auto &x : *this) {
6265 for (auto &y : x->vars()) {
6266 out.push_back(y);
6267 }
6268 }
6269 return out;
6270 }
6271 if (auto p = get<RooAbsArg>(); p) {
6272 // also need to get all constPars so use leafNodeServerList .. will include self if is fundamental, which is what
6273 // we want
6274 // ensure all globs appear after robs, as we rely on this ordering for picking "x" var in "reduced" method
6275 xRooNode _globs;
6276 RooArgSet allLeaves;
6277 p->leafNodeServerList(&allLeaves);
6278 for (auto &c : allLeaves) {
6279 if (c->isFundamental() || (dynamic_cast<RooConstVar *>(c) && !TString(c->GetName()).IsFloat())) {
6280 if (!c->getAttribute("global")) {
6281 out.get<RooArgList>()->add(*c);
6282 out.emplace_back(std::make_shared<xRooNode>(*c, *this));
6283 }
6284 if (c->getAttribute("global")) {
6285 _globs.emplace_back(std::make_shared<xRooNode>(*c, *this));
6286 _globs.back()->fFolder = "!globs";
6287 } else if (c->getAttribute("obs")) {
6288 out.back()->fFolder = "!robs";
6289 } else if (c->getAttribute("poi")) {
6290 out.back()->fFolder = "!poi";
6291 } else if (c->getAttribute("np") ||
6292 (!c->getAttribute("Constant") && !c->getAttribute("poi") && c->IsA() != RooConstVar::Class())) {
6293 out.back()->fFolder = "!np";
6294 } else if (!c->getAttribute("Constant") && c->IsA() != RooConstVar::Class()) {
6295 out.back()->fFolder = "!floats";
6296 } else {
6297 out.back()->fFolder = "!pp";
6298 }
6299 }
6300 }
6301 for (auto g : _globs) {
6302 out.get<RooArgList>()->add(*g->get<RooAbsArg>());
6303 out.emplace_back(g);
6304 }
6305 } else if (auto p2 = get<RooAbsData>(); p2) {
6306 for (auto a : *p2->get()) {
6307 a->setAttribute("obs");
6308 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6309 out.get<RooArgList>()->add(*a);
6310 }
6311 if (auto _dglobs = p2->getGlobalObservables()) {
6312 for (auto &a : *_dglobs) {
6313 a->setAttribute("obs");
6314 a->setAttribute("global");
6315 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6316 out.get<RooArgList>()->add(*a);
6317 }
6318 } else if (auto _globs = find(".globs"); _globs && _globs->get<RooAbsCollection>()) {
6319 for (auto &a : *_globs->get<RooAbsCollection>()) {
6320 a->setAttribute("obs");
6321 a->setAttribute("global");
6322 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6323 out.get<RooArgList>()->add(*a);
6324 }
6325 } else if (auto _ws = ws(); _ws) {
6326 if (auto _globs2 = dynamic_cast<RooArgSet *>(GETWSSNAPSHOTS(_ws).find(p2->GetName())); _globs2) {
6327 for (auto a : *_globs2) {
6328 a->setAttribute("obs");
6329 a->setAttribute("global");
6330 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6331 out.get<RooArgList>()->add(*a);
6332 }
6333 } else if (auto _gl = GETWSSETS(_ws).find("globalObservables"); _gl != GETWSSETS(_ws).end()) {
6334 for (auto &_g : _gl->second) {
6335 auto _clone = std::shared_ptr<RooAbsArg>(dynamic_cast<RooAbsArg *>(_g->Clone(_g->GetName())));
6336 if (auto v = std::dynamic_pointer_cast<RooAbsRealLValue>(_clone); v && _g->getStringAttribute("nominal"))
6337 v->setVal(TString(_g->getStringAttribute("nominal")).Atof());
6338 out.emplace_back(std::make_shared<xRooNode>(_clone, *this));
6339 out.get<RooArgList>()->add(*_clone);
6340 }
6341 } else if (fParent) {
6342 // note: this is slow in large workspaces ... too many obs to look through?
6343 std::unique_ptr<RooAbsCollection> _globs3(fParent->obs().get<RooArgList>()->selectByAttrib("global", true));
6344 // std::unique_ptr<RooAbsCollection> _globs(_ws->allVars().selectByAttrib("global",true)); - tried this to
6345 // be quicker but it wasn't
6346 for (auto &_g : *_globs3) {
6347 auto _clone = std::shared_ptr<RooAbsArg>(dynamic_cast<RooAbsArg *>(_g->Clone(_g->GetName())));
6348 if (auto v = std::dynamic_pointer_cast<RooAbsRealLValue>(_clone); v && _g->getStringAttribute("nominal"))
6349 v->setVal(TString(_g->getStringAttribute("nominal")).Atof());
6350 out.emplace_back(std::make_shared<xRooNode>(_clone, *this));
6351 out.get<RooArgList>()->add(*_clone);
6352 }
6353 }
6354 }
6355 } else if (auto w = get<RooWorkspace>(); w) {
6356 for (auto a : w->components()) {
6357 if (a->InheritsFrom(RooRealVar::Class()) || a->InheritsFrom(RooCategory::Class()) ||
6358 a->InheritsFrom(RooConstVar::Class())) {
6359 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6360 }
6361 }
6362 }
6363 return out;
6364}
6365
6367{
6368 xRooNode out(".components", nullptr, *this);
6369
6370 if (auto p = get<RooAddPdf>(); p) {
6371 // only add each pdf once (the coefs will be accumulated in coefs() method) ...
6372 std::set<RooAbsArg *> donePdfs;
6373 for (auto &o : p->pdfList()) {
6374 if (donePdfs.count(o))
6375 continue;
6376 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6377 donePdfs.insert(o);
6378 }
6379 } else if (auto p2 = get<RooRealSumPdf>(); p2) {
6380 // check for common prefixes and suffixes, will use to define aliases to shorten names
6381 // if have more than 1 function
6382 // TString commonPrefix=""; TString commonSuffix="";
6383 // if (p->funcList().size() > 1) {
6384 // bool checked=false;
6385 // for(auto& o : p->funcList()) {
6386 // if (!checked) {
6387 // commonPrefix = o->GetName(); commonSuffix = o->GetName(); checked=true;
6388 // } else {
6389 //
6390 // }
6391 // }
6392 // }
6393 std::set<RooAbsArg *> doneFuncs;
6394 for (auto &o : p2->funcList()) {
6395 if (doneFuncs.count(o))
6396 continue;
6397 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6398 doneFuncs.insert(o);
6399 }
6400 } else if (auto p3 = get<RooAddition>(); p3) {
6401 for (auto &o : p3->list()) {
6402 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6403 }
6404 } else if (auto p4 = get<RooAbsCollection>(); p4) {
6405 for (auto &a : *p4) {
6406 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6407 }
6408 } else if (auto p5 = get<RooWorkspace>(); p5) {
6409 for (auto &o : p5->components()) {
6410 // only top-level nodes (only clients are integrals or things that aren't part of the workspace)
6411 // if (o->hasClients()) continue;
6412 bool hasClients = false;
6413 for (auto &c : o->clients()) {
6414 if (!c->InheritsFrom("RooRealIntegral") && p5 == GETWS(c)) {
6415 hasClients = true;
6416 break;
6417 }
6418 }
6419 if (hasClients)
6420 continue;
6421 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6422 if (o->InheritsFrom("RooAbsPdf")) {
6423 out.back()->fFolder = "!pdfs";
6424 } else {
6425 out.back()->fFolder = "!scratch";
6426 }
6427 }
6428 for (auto &o : p5->allGenericObjects()) {
6429 if (auto fr = dynamic_cast<RooFitResult *>(o); fr) {
6430 TString s(fr->GetTitle());
6431 if (s.Contains(';'))
6432 s = s(0, s.Index(';'));
6433 if (auto _pdf = out.find(s.Data()); _pdf) {
6434 // std::cout << " type = " << _pdf->get()->ClassName() << std::endl;
6435 out.emplace_back(std::make_shared<xRooNode>(fr->GetName(), *fr, _pdf));
6436 // for a while, this node's parent pointed to something of type Node2!!
6437 // how to fix??? - I fxied it with a new constructor to avoid the shared_ptr<Node2> calling the const
6438 // Node2& constructor via getting wrapped in a Node2(shared_ptr<TObject>) call
6439 // out.back()->fParent = _pdf;
6440 // std::cout << " type2 = " << out.back()->fParent->get()->ClassName() << std::endl;
6441 } else {
6442 out.emplace_back(std::make_shared<xRooNode>(fr->GetName(), *fr, *this));
6443 }
6444 out.back()->fFolder = "!fits";
6445 } else {
6446 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6447 if (strcmp(out.back()->get()->ClassName(), "TStyle") == 0) {
6448 out.back()->fFolder = "!styles";
6449 } else if (strcmp(out.back()->get()->ClassName(), "RooStats::HypoTestInverterResult") == 0) {
6450 out.back()->fFolder = "!scans";
6451 } else if (strcmp(out.back()->get()->ClassName(), "RooStats::ModelConfig") == 0) {
6452 out.back()->fFolder = "!models";
6453 } else {
6454 out.back()->fFolder = "!objects";
6455 }
6456 }
6457 }
6458 for (auto &[k, v] : GETWSSETS(p5)) {
6459 // skip 'CACHE' sets because they are auto-removed when sanitizing workspaces, which will invalidate these
6460 // children
6461 if (k.find("CACHE_") == 0)
6462 continue;
6463 out.emplace_back(std::make_shared<xRooNode>(k.c_str(), v, *this));
6464 out.back()->fFolder = "!sets";
6465 }
6466
6467 RooLinkedList snaps = GETWSSNAPSHOTS(p5);
6468 std::unique_ptr<TIterator> iter(snaps.MakeIterator());
6469 TObject *snap;
6470 while ((snap = iter->Next())) {
6471 out.emplace_back(std::make_shared<xRooNode>(*snap, *this));
6472 out.back()->fFolder = "!snapshots";
6473 }
6474 } else if (auto mc = get<RooStats::ModelConfig>()) {
6475 // add the pdf as a child, and the external constraints set if its there
6476 if (mc->GetPdf()) {
6477 out.emplace_back(std::make_shared<xRooNode>(".pdf", *mc->GetPdf(), *this));
6478 }
6479 if (mc->GetExternalConstraints()) {
6480 out.emplace_back(std::make_shared<xRooNode>(".extCons", *mc->GetExternalConstraints(), *this));
6481 }
6482 } else if (strlen(GetName()) > 0 && GetName()[0] == '!' && fParent) {
6483 // special case of dynamic property
6484 if (TString(GetName()) == "!.pars") {
6485 for (auto &c : fParent->pars()) {
6486 out.emplace_back(c);
6487 }
6488 } else {
6489 // the components of a folder are the children of the parent (after browsing) that live in this folder
6490 fParent->browse();
6491 for (auto &c : *fParent) {
6492 if (c->fFolder == GetName()) {
6493 out.emplace_back(c);
6494 }
6495 }
6496 }
6497 }
6498
6499 return out;
6500}
6501
6502////////////////////////////////////////////////////////////////////////////////
6503/// bins of a channel or sample, or channels of a multi-channel pdf
6504
6506{
6507 xRooNode out(".bins", nullptr, *this);
6508
6509 if (auto p = get<RooSimultaneous>(); p) {
6510 std::map<int, std::shared_ptr<xRooNode>> cats; // fill into a map to preserve index ordering
6511 for (auto &c : p->indexCat()) { // is alphabetical in labels
6512 auto pp = p->getPdf(c.first.c_str());
6513 if (!pp)
6514 continue;
6515 cats[c.second] =
6516 std::make_shared<xRooNode>(TString::Format("%s=%s", p->indexCat().GetName(), c.first.c_str()), *pp, *this);
6517 }
6518 for (auto &[_, n] : cats)
6519 out.emplace_back(n);
6520 } else if (auto phf = get<ParamHistFunc>(); phf) {
6521 int i = 1;
6522#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
6523 auto &pSet = phf->_paramSet;
6524#else
6525 auto &pSet = phf->paramList();
6526#endif
6527 for (auto par : pSet) {
6528 out.emplace_back(std::make_shared<xRooNode>(*par, *this));
6529 out.back()->fBinNumber = i;
6530 i++;
6531 }
6532 } else if (auto ax = GetXaxis(); ax) {
6533 for (int i = 1; i <= ax->GetNbins(); i++) {
6534 // create a RooProduct of all bin-specific factors of all shapeFactors
6535 std::vector<RooAbsArg *> _factors;
6536 for (auto f : factors()) {
6537 if (f->get<ParamHistFunc>()) {
6538 if (f->bins()[i - 1]->get<RooProduct>()) {
6539 for (auto &ss : f->bins()[i - 1]->factors())
6540 _factors.push_back(ss->get<RooAbsArg>());
6541 } else {
6542 _factors.push_back(f->bins()[i - 1]->get<RooAbsArg>());
6543 }
6544 }
6545 }
6546 out.emplace_back(std::make_shared<xRooNode>(
6547 TString::Format("%g<=%s<%g", ax->GetBinLowEdge(i), ax->GetParent()->GetName(), ax->GetBinLowEdge(i + 1)),
6548 _factors.empty() ? nullptr
6549 : std::make_shared<RooProduct>(TString::Format("%s.binFactors.bin%d", GetName(), i),
6550 "binFactors", RooArgList()),
6551 *this));
6552 for (auto f : _factors) {
6553#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
6554 out.back()->get<RooProduct>()->_compRSet.add(*f);
6555#else
6556 const_cast<RooArgList &>(out.back()->get<RooProduct>()->realComponents()).add(*f);
6557#endif
6558 }
6559 out.back()->fBinNumber = i;
6560 }
6561 }
6562
6563 return out;
6564}
6565
6566xRooNode xRooNode::coefs(bool recurse) const
6567{
6569
6570 if (recurse && fParent) {
6571 // get our coefs and multiply it by the parents coefs ...
6572 auto ourCoefs = xRooNode::coefs(false);
6573 auto parentCoefs = fParent->coefs(true);
6574 if (!parentCoefs.get<RooAbsReal>()) {
6575 // no coefs to include, just return our coefs
6576 return ourCoefs;
6577 }
6578 if (!ourCoefs.get<RooAbsReal>()) {
6579 // just return the parent's coefs
6580 return parentCoefs;
6581 }
6582 // if got here, must combine parentCoefs and outCoefs into a RooProduct
6583 xRooNode out(".recursiveCoefs",
6584 std::make_shared<RooProduct>(".recursiveCoefs",
6585 TString::Format("Recursive Coefficients of %s", GetName()),
6586 *ourCoefs.get<RooAbsReal>(), *parentCoefs.get<RooAbsReal>()),
6587 *this);
6588 // keep alive the two coef nodes by adding to out's memory
6589 auto mem = out.emplace_back(std::make_shared<xRooNode>(".memory", nullptr, *this));
6590 mem->emplace_back(std::make_shared<xRooNode>(ourCoefs));
6591 mem->emplace_back(std::make_shared<xRooNode>(parentCoefs));
6592 return out;
6593 }
6594
6595 bool isResidual = false;
6596
6597 // if parent is a sumpdf or addpdf then include the coefs
6598 // if func appears multiple times then coefs must be combined into a RooAddition temporary
6599 if (fParent) {
6600 // handle case where filters are applied .. need to pass through these
6601 // do this by iterating while fComp is null
6602 auto parent = fParent;
6603 if (!parent->fComp) {
6604 while (!parent->fComp && parent->fParent) {
6605 parent = parent->fParent;
6606 }
6607 // parent should now be node above the filters ... need parent of that
6608 parent = parent->fParent;
6609 if (!parent)
6610 parent = fParent; // revert t original parent in case something went wrong
6611 }
6612 if (auto p = parent->get<RooRealSumPdf>(); p) {
6613 std::size_t i = 0;
6614 for (auto &o : p->funcList()) {
6615 if (o == get()) {
6616 if (i >= p->coefList().size()) {
6617 isResidual = true;
6618 coefs.add(p->coefList());
6619 } else {
6620 coefs.add(*p->coefList().at(i));
6621 }
6622 }
6623 i++;
6624 }
6625 } else if (auto p2 = parent->get<RooAddPdf>(); p2) {
6626 std::size_t i = 0;
6627 if (p2->coefList().empty()) {
6628 // this can happen if all pdfs are extended then the coef is effectively the
6629 // expected number of events
6630 // TODO: test behaviour of xRooNode under this scenario (are histograms correct?)
6631 } else {
6632 for (auto &o : p2->pdfList()) {
6633 if (o == get()) {
6634 if (i >= p2->coefList().size()) {
6635 isResidual = true;
6636 coefs.add(p2->coefList());
6637 } else {
6638 coefs.add(*p2->coefList().at(i));
6639 }
6640 }
6641 i++;
6642 }
6643 }
6644 }
6645 }
6646 if (isResidual) {
6647 // return a node representing 1.-sumOfCoefs
6648 // involves creating sumOfCoefs unless there is only 1 coef, then just use that
6649 auto coefSum = coefs.empty()
6650 ? nullptr
6651 : (coefs.size() == 1 ? std::shared_ptr<RooAbsArg>(coefs.at(0), [](RooAbsArg *) {})
6652 : std::make_shared<RooAddition>((isResidual) ? ".sumOfCoefs" : ".coefs",
6653 "Coefficients of", coefs));
6654 xRooNode out(".coef", coefSum ? std::dynamic_pointer_cast<RooAbsArg>(std::make_shared<RooFormulaVar>(
6655 ".coef", "1-sum(otherCoefs)", "1. - @0", *coefSum))
6656 : nullptr /* should we return a "1." instead? */);
6657 if (coefSum && coefs.size() != 1) {
6658 out.emplace_back(std::make_shared<xRooNode>(".memory", nullptr, *this))
6659 ->emplace_back(
6660 std::make_shared<xRooNode>(".sumOfCoefs", coefSum, out)); // added to keep the sum alive! with the node
6661 }
6662 if (!coefs.empty()) {
6663 out.browse();
6664 }
6665 return out;
6666 } else if (coefs.size() == 1) {
6667 xRooNode out(".coef", std::shared_ptr<RooAbsArg>(coefs.at(0), [](RooAbsArg *) {}), *this);
6668 if (!coefs.empty()) {
6669 out.browse();
6670 }
6671 return out;
6672 } else {
6673 auto coefSum =
6674 coefs.empty()
6675 ? nullptr
6676 : std::make_shared<RooAddition>(".coefs", TString::Format("Coefficients of %s", GetName()), coefs);
6677 xRooNode out(".coefs", coefSum, *this);
6678 if (!coefs.empty())
6679 out.browse();
6680
6681 return out;
6682 }
6683}
6684
6686{
6687 xRooNode out(".factors", nullptr, *this);
6688
6689 if (auto p = get<RooProdPdf>(); p) {
6690 auto _main = mainChild();
6691 if (auto a = _main.get<RooRealSumPdf>(); a && !a->getStringAttribute("alias")) {
6692 a->setStringAttribute("alias", "samples");
6693 } else if (auto a2 = _main.get<RooAddPdf>(); a2 && !a2->getStringAttribute("alias")) {
6694 a2->setStringAttribute("alias", "components");
6695 }
6696 int _npdfs = p->pdfList().size();
6697 for (auto &o : p->pdfList()) {
6698 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6699 if (_npdfs > 5 && o != _main.get() && out.back()->robs().size() == 0) // constraints have no robs in them
6700 out.back()->fFolder = "!constraints";
6701 }
6702 } else if (auto p2 = get<RooProduct>(); p2) {
6703 for (auto &o : p2->components()) {
6704 if (o->InheritsFrom("RooProduct")) {
6705 // get factors of this term
6706 auto x = xRooNode("tmp", *o, *this).factors();
6707 for (auto &n : x) {
6708 out.emplace_back(std::make_shared<xRooNode>(n->GetName(), n->fComp, *this));
6709 }
6710 } else {
6711 out.emplace_back(std::make_shared<xRooNode>(*o, *this));
6712 }
6713 }
6714 } else if (auto w = get<RooWorkspace>(); w) {
6715 // if workspace, return all functions (not pdfs) that have a RooProduct as one of their clients
6716 // or not clients
6717 // exclude obs and globs
6718 auto oo = obs(); // need to keep alive as may contain owning globs
6719 auto &_obs = *(oo.get<RooArgList>());
6720 for (auto a : w->allFunctions()) {
6721 if (_obs.contains(*a))
6722 continue;
6723 bool show(true);
6724 for (auto c : a->clients()) {
6725 show = false;
6726 if (c->InheritsFrom("RooProduct")) {
6727 show = true;
6728 break;
6729 }
6730 }
6731 if (show)
6732 out.emplace_back(std::make_shared<xRooNode>(*a, *this));
6733 }
6734 }
6735
6736 /*
6737 // if parent is a sumpdf or addpdf then include the coefs
6738 // if func appears multiple times then coefs must be combined into a RooAddition temporary
6739 if (fParent) {
6740 RooArgList coefs;
6741 if(auto p = fParent->get<RooRealSumPdf>();p) {
6742 int i=0;
6743 for(auto& o : p->funcList()) {
6744 if (o == get()) {
6745 coefs.add( *p->coefList().at(i) );
6746 }
6747 i++;
6748 }
6749 } else if(auto p = fParent->get<RooAddPdf>(); p) {
6750 int i=0;
6751 for(auto& o : p->pdfList()) {
6752 if (o == get()) {
6753 coefs.add( *p->coefList().at(i) );
6754 }
6755 i++;
6756 }
6757 }
6758 if (!coefs.empty()) {
6759 if (coefs.size() == 1) {
6760 if (strcmp(coefs.at(0)->GetName(),"1")) { // don't add the "1"
6761 out.emplace_back(std::make_shared<Node2>(".coef", *coefs.at(0), *this));
6762 }
6763 } else {
6764 out.emplace_back(std::make_shared<Node2>(".coefs",
6765 std::make_shared<RooAddition>(".coefs", "Coefficients of",
6766 coefs), *this));
6767 }
6768 }
6769 }
6770 */
6771 return out;
6772}
6773
6775{
6776 xRooNode out(".variations", nullptr, *this);
6777
6778 // if (auto p = get<RooSimultaneous>(); p) {
6779 // for (auto &c : p->indexCat()) {
6780 // auto pp = p->getPdf(c.first.c_str());
6781 // if (!pp)
6782 // continue;
6783 // out.emplace_back(
6784 // std::make_shared<xRooNode>(TString::Format("%s=%s", p->indexCat().GetName(), c.first.c_str()), *pp,
6785 // *this));
6786 // }
6787 // } else
6788 if (auto p2 = get<PiecewiseInterpolation>(); p2) {
6789#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
6790 out.emplace_back(std::make_shared<xRooNode>("nominal", p2->_nominal.arg(), *this));
6791#else
6792 out.emplace_back(std::make_shared<xRooNode>("nominal", *(p2->nominalHist()), *this));
6793#endif
6794 for (size_t i = 0; i < p2->paramList().size(); i++) {
6795 // TODO: should we only return one if we find they are symmetrized?
6796 out.emplace_back(std::make_shared<xRooNode>(TString::Format("%s=1", p2->paramList().at(i)->GetName()),
6797 *p2->highList().at(i), *this));
6798 out.emplace_back(std::make_shared<xRooNode>(TString::Format("%s=-1", p2->paramList().at(i)->GetName()),
6799 *p2->lowList().at(i), *this));
6800 }
6801 } else if (auto p3 = get<RooStats::HistFactory::FlexibleInterpVar>(); p3) {
6802#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
6803 out.emplace_back(std::make_shared<xRooNode>("nominal", RooFit::RooConst(p3->_nominal), *this));
6804 for (size_t i = 0; i < p3->_paramList.size(); i++) {
6805 out.emplace_back(std::make_shared<xRooNode>(TString::Format("%s=1", p3->_paramList.at(i)->GetName()),
6806 RooFit::RooConst(p3->_high.at(i)), *this));
6807 out.emplace_back(std::make_shared<xRooNode>(TString::Format("%s=-1", p3->_paramList.at(i)->GetName()),
6808 RooFit::RooConst(p3->_low.at(i)), *this));
6809 }
6810#else
6811 out.emplace_back(std::make_shared<xRooNode>("nominal", RooFit::RooConst(p3->nominal()), *this));
6812 for (size_t i = 0; i < p3->variables().size(); i++) {
6813 out.emplace_back(std::make_shared<xRooNode>(TString::Format("%s=1", p3->variables().at(i)->GetName()),
6814 RooFit::RooConst(p3->high().at(i)), *this));
6815 out.emplace_back(std::make_shared<xRooNode>(TString::Format("%s=-1", p3->variables().at(i)->GetName()),
6816 RooFit::RooConst(p3->low().at(i)), *this));
6817 }
6818#endif
6819
6820 } else if (auto p4 = get<ParamHistFunc>(); p4) {
6821 // I *think* I put this here so that can browse into a ParamHistFunc
6822 // int i = 0;
6823 // for (auto par : p4->_paramSet) {
6824 // TString _name = par->GetName();
6825 // // if(auto _v = dynamic_cast<RooRealVar*>(p->_dataSet.get(i)->first()); _v) {
6826 // // _name = TString::Format("%s=%g",_v->GetName(),_v->getVal());
6827 // // }
6828 // // out.emplace_back(std::make_shared<xRooNode>(_name,*par,*this)); -- -removed cos now have bin()
6829 // method i++;
6830 // }
6831 }
6832 return out;
6833}
6834
6836{
6837 RooArgList out;
6838 out.setName(GetName());
6839 for (auto &k : *this) {
6840 if (auto o = k->get<RooAbsArg>(); o)
6841 out.add(*o);
6842 }
6843 return out;
6844}
6845
6847{
6848 xRooNode out(".datasets()", nullptr, *this);
6849 // removed the browse operation since no longer showing '.datasets()' in browser
6850 // and otherwise this means dataset reduction operation will be called every time we 'browse()' the datasets node
6851 // out.fBrowseOperation = [](xRooNode *f) { return f->fParent->datasets(); };
6852
6853 if (auto _ws = get<RooWorkspace>(); _ws) {
6854 for (auto &d : _ws->allData()) {
6855 out.emplace_back(std::make_shared<xRooNode>(*d, *this));
6856 out.back()->fFolder = "!datasets";
6857 }
6858 } else if (get<RooAbsPdf>() ||
6859 (!get() && fParent &&
6860 fParent->get<RooAbsPdf>())) { // second condition handles 'bins' nodes of pdf, which have null ptr
6861 // only add datasets that have observables that cover all our observables
6862 auto oo = obs(); // must keep alive in case is owning the globs
6863 RooArgSet _obs(*oo.get<RooArgList>());
6864 //_obs.add(coords(true).argList(), true); // include coord observables too, and current xaxis if there's one -
6865 // added in loop below
6866
6867 TString cut;
6868 RooArgSet cutobs;
6869 for (auto _c : coords()) { // coords() moves vars to their respective coordinates too
6870 if (auto _cat = _c->get<RooAbsCategoryLValue>(); _cat) {
6871 if (cut != "")
6872 cut += " && ";
6873 cut += TString::Format("%s==%d", _cat->GetName(), _cat->getCurrentIndex());
6874 _obs.add(*_cat,
6875 true); // note: if we ever changed coords to return clones, would need to keep coords alive
6876 cutobs.add(*_cat);
6877 } else if (auto _rv = _c->get<RooAbsRealLValue>(); _rv) {
6878 // todo: check coordRange is a single range rather than multirange
6879 if (cut != "")
6880 cut += " && ";
6881 cut += TString::Format("%s>=%f&&%s<%f", _rv->GetName(), _rv->getMin(_rv->getStringAttribute("coordRange")),
6882 _rv->GetName(), _rv->getMax(_rv->getStringAttribute("coordRange")));
6883 _obs.add(*_rv,
6884 true); // note: if we ever changed coords to return clones, would need to keep coords alive
6885 cutobs.add(*_rv);
6886 } else {
6887 throw std::runtime_error("datasets(): Unsupported coordinate type");
6888 }
6889 }
6890 if (auto s = get<RooSimultaneous>()) {
6891 // check if we have a pdf for every category ... if not then add to cut
6892 bool hasMissing = false;
6893 TString extraCut = "";
6894 for (auto cat : s->indexCat()) {
6895 if (!s->getPdf(cat.first.c_str())) {
6896 hasMissing = true;
6897 } else {
6898 if (extraCut != "")
6899 extraCut += " || ";
6900 extraCut += TString::Format("%s==%d", s->indexCat().GetName(), cat.second);
6901 }
6902 }
6903 if (hasMissing) {
6904 if (cut != "")
6905 cut += " && ";
6906 cut += "(" + extraCut + ")";
6907 cutobs.add(s->indexCat());
6908 }
6909 }
6910
6911 if (auto ax = GetXaxis(); ax && dynamic_cast<RooAbsArg *>(ax->GetParent())->getAttribute("obs")) {
6912 auto a = dynamic_cast<RooAbsArg *>(ax->GetParent());
6913 _obs.add(*a, true);
6914 }
6915 xRooNode _datasets; // will be any child datasets, along with datasets of the workspace
6916 for (auto &child : *this) {
6917 if (child->get<RooAbsData>())
6918 _datasets.push_back(child);
6919 }
6920 if (auto __ws = ws(); __ws) {
6921 xRooNode _wsNode(*__ws, *this);
6922 for (auto &d : _wsNode.datasets()) {
6923 _datasets.push_back(d);
6924 }
6925 }
6926
6927 for (auto &d : _datasets) {
6928 if (std::unique_ptr<RooAbsCollection>(d->obs().argList().selectCommon(_obs))->size() == _obs.size()) {
6929 // all obs present .. include
6930
6931 if (cut != "") {
6932 RooFormulaVar cutFormula("cut1", cut, cutobs); // doing this to avoid complaints about unused vars
6933 // TODO: Could consider using a 'filter' node (see filter() method) applied to the dataset instead
6934 // of creating and using a reduced dataset here
6935 out.emplace_back(std::make_shared<xRooNode>(
6936 std::shared_ptr<RooAbsData>(d->get<RooAbsData>()->reduce(
6937 *std::unique_ptr<RooAbsCollection>(d->robs().get<RooArgList>()->selectCommon(_obs)), cutFormula)),
6938 *this));
6939 // put a subset of the globs in the returned dataset too
6940 out.back()->get<RooAbsData>()->setGlobalObservables(*std::unique_ptr<RooAbsCollection>(
6941 d->globs().get<RooArgList>()->selectCommon(*globs().get<RooArgList>())));
6942 if (d->get()->TestBit(1 << 20))
6943 out.back()->get()->SetBit(1 << 20);
6944 // need to attach the original dataset so that things like SetBinContent can interact with it
6945 out.back()->fBrowsables.emplace_back(std::make_shared<xRooNode>(".sourceds", d->fComp, *this));
6946 } else {
6947 out.emplace_back(std::make_shared<xRooNode>(d->fComp, *this));
6948 }
6949 }
6950 }
6951 /*else if(auto p = get<RooFitResult>(); p) {
6952 // look for datasets in workspace that match the fit result name after hashing
6953 for(auto& _d : xRooNode(*_ws,*this).datasets()) {
6954 auto _hash = RooAbsTree::nameToHash(_d->get()->GetName());
6955 if (TString::Format("%d;%d",_hash.first,_hash.second) == p->GetTitle()) {
6956 out.emplace_back(std::make_shared<xRooNode>(_d->fComp, *this));
6957 }
6958 }
6959 }*/
6960 } else if (auto mc = get<RooStats::ModelConfig>()) {
6961 return xRooNode(*mc->GetPdf(), fParent).datasets();
6962 }
6963
6964 return out;
6965}
6966
6968{
6969 xRooNode out(".parents", nullptr, *this);
6970 if (auto a = get<RooAbsArg>()) {
6971 for (auto c : a->clients()) {
6972 out.push_back(std::make_shared<xRooNode>(*c, *this));
6973 }
6974 }
6975 return out;
6976}
6977
6979{
6980 if (auto w = get<RooWorkspace>()) {
6981 xRooNode out(".args", w->components(), *this);
6982 out.browse(); // populate
6983 return out;
6984 } else if (auto a = get<RooAbsArg>()) {
6985 xRooNode out(".args", std::make_shared<RooArgList>(), *this);
6986 out.get<RooArgList>()->setName((GetPath() + ".args").c_str());
6987 a->treeNodeServerList(out.get<RooArgList>());
6988 out.browse(); // populate
6989 return out;
6990 }
6991 return nullptr;
6992}
6993
6994std::shared_ptr<xRooNode> xRooNode::getBrowsable(const char *name) const
6995{
6996 for (auto b : fBrowsables) {
6997 if (b && strcmp(b->GetName(), name) == 0)
6998 return b;
6999 }
7000 return nullptr;
7001}
7002
7003TGraph *xRooNode::BuildGraph(RooAbsLValue *v, bool includeZeros, TVirtualPad *fromPad) const
7004{
7005
7006 if (auto fr = get<RooFitResult>(); fr) {
7007 return nullptr;
7008 }
7009
7010 if (auto theData = get<RooDataSet>(); theData) {
7011
7012 TH1 *theHist = nullptr;
7013
7014 if (fromPad) {
7015 // find first histogram in pad
7016 for (auto o : *fromPad->GetListOfPrimitives()) {
7017 theHist = dynamic_cast<TH1 *>(o);
7018 if (theHist) {
7019 theHist = static_cast<TH1 *>(theHist->Clone());
7020 theHist->Reset();
7021 break;
7022 } // clone because theHist gets deleted below
7023 }
7024 }
7025
7026 if (!theHist) {
7027 auto _parentPdf = parentPdf();
7028 if (!_parentPdf) {
7029 // can still build graph if v is an obs ... will use v binning
7030 auto vo = dynamic_cast<TObject *>(v);
7031 if (v && obs().find(vo->GetName())) {
7032 if (auto cat = dynamic_cast<RooAbsCategoryLValue *>(v)) {
7033 theHist = new TH1D(
7034 TString::Format("%s_%s", GetName(), vo->GetName()),
7035 TString::Format("my temp hist;%s", strlen(vo->GetTitle()) ? vo->GetTitle() : vo->GetName()),
7036 cat->numTypes(), 0, cat->numTypes());
7037 int i = 1;
7038 std::map<int, std::string> cats; // fill into a map to preserve index ordering
7039 for (auto &c : *cat) {
7040 cats[c.second] = c.first;
7041 }
7042 for (auto &[_, label] : cats) {
7043 theHist->GetXaxis()->SetBinLabel(i++, label.c_str());
7044 }
7045 } else {
7046 auto _binning = v->getBinningPtr(nullptr);
7047 if (_binning->isUniform()) {
7048 theHist = new TH1D(
7049 TString::Format("%s_%s", GetName(), vo->GetName()),
7050 TString::Format("my temp hist;%s", strlen(vo->GetTitle()) ? vo->GetTitle() : vo->GetName()),
7051 v->numBins(), _binning->lowBound(), _binning->highBound());
7052 } else {
7053 theHist = new TH1D(
7054 TString::Format("%s_%s", GetName(), vo->GetName()),
7055 TString::Format("my temp hist;%s", strlen(vo->GetTitle()) ? vo->GetTitle() : vo->GetName()),
7056 v->numBins(), _binning->array());
7057 }
7058 }
7059 } else {
7060 throw std::runtime_error("Cannot draw dataset without parent PDF");
7061 }
7062 } else {
7063 theHist = _parentPdf->BuildHistogram(v, true);
7064 }
7065 }
7066 if (!theHist)
7067 return nullptr;
7068 // this hist will get filled with w*x to track weighted x position per bin
7069 TH1 *xPos = static_cast<TH1 *>(theHist->Clone("xPos"));
7070 xPos->Reset();
7071 TH1 *xPos2 = static_cast<TH1 *>(theHist->Clone("xPos2"));
7072 xPos2->Reset();
7073 auto nHist = std::unique_ptr<TH1>(static_cast<TH1 *>(theHist->Clone("nEntries")));
7074 nHist->Reset();
7075
7076 auto dataGraph = new TGraphAsymmErrors;
7077 dataGraph->SetEditable(false);
7078 dataGraph->SetName(GetName());
7079 dataGraph->SetTitle(strlen(theData->GetTitle()) ? theData->GetTitle() : theData->GetName());
7080 // next line triggers creation of the histogram inside the graph, in root 6.22 that isn't protected from being
7081 // added to gDirectory
7082 dataGraph->SetTitle(TString::Format("%s;%s;Events", dataGraph->GetTitle(), theHist->GetXaxis()->GetTitle()));
7083 *static_cast<TAttMarker *>(dataGraph) = *static_cast<TAttMarker *>(theHist);
7084 *static_cast<TAttLine *>(dataGraph) = *static_cast<TAttLine *>(theHist);
7085
7086 // default style based on if generated or not
7087
7088 if (auto w = theData->weightVar(); w && w->getStringAttribute("fitResult")) {
7089 // is generated
7090 dataGraph->SetLineColor(kGreen + 2);
7091 if (w->getAttribute("expected")) {
7092 // is asimov
7093 dataGraph->SetLineColor(kBlue);
7094 }
7095 } else {
7096 dataGraph->SetLineColor(kBlack);
7097 }
7098 dataGraph->SetMarkerStyle(20);
7099 dataGraph->SetMarkerColor(dataGraph->GetLineColor());
7100 dataGraph->SetMarkerSize(gStyle->GetMarkerSize());
7101
7102 auto _obs = obs();
7103
7104 // auto x = theData->get()->find((v) ? dynamic_cast<TObject*>(v)->GetName() : theHist->GetXaxis()->GetName());
7105 // const RooAbsReal* xvar = (x) ? dynamic_cast<RooAbsReal*>(x) : nullptr;
7106 // const RooAbsCategory* xcat = (x && !xvar) ? dynamic_cast<RooAbsCategory*>(x) : nullptr;
7107 auto x = _obs.find((v) ? dynamic_cast<TObject *>(v)->GetName()
7108 : (theHist->GetXaxis()->IsAlphanumeric() ? theHist->GetXaxis()->GetTimeFormatOnly()
7109 : theHist->GetXaxis()->GetName()));
7110 if (x && x->get<RooAbsArg>()->getAttribute("global")) {
7111 // is global observable ...
7112 dataGraph->SetPoint(0, x->get<RooAbsReal>()->getVal(), 1e-15);
7113 dataGraph->SetTitle(TString::Format("%s = %f", dataGraph->GetTitle(), dataGraph->GetPointX(0)));
7114 delete xPos;
7115 delete xPos2;
7116 delete theHist;
7117 return dataGraph;
7118 }
7119
7120 const RooAbsReal *xvar = (x) ? x->get<RooAbsReal>() : nullptr;
7121 const RooAbsCategory *xcat = (x && !xvar) ? x->get<RooAbsCategory>() : nullptr;
7122
7123 auto _coords = coords();
7124
7125 TString pName((fromPad) ? fromPad->GetName() : "");
7126 auto _pos = pName.Index('=');
7127
7128 int nevent = theData->numEntries();
7129 for (int i = 0; i < nevent; i++) {
7130 theData->get(i);
7131 bool _skip = false;
7132 for (auto _c : _coords) {
7133 if (auto cat = _c->get<RooAbsCategoryLValue>(); cat) {
7134 if (cat->getIndex() != theData->get()->getCatIndex(cat->GetName())) {
7135 _skip = true;
7136 break;
7137 }
7138 } else if (auto rv = _c->get<RooAbsRealLValue>(); rv) {
7139 // must be in range
7140 if (!rv->inRange(theData->get()->getRealValue(rv->GetName()), rv->getStringAttribute("coordRange"))) {
7141 _skip = true;
7142 break;
7143 }
7144 }
7145 }
7146 if (_pos != -1) {
7147 if (auto cat = dynamic_cast<RooAbsCategory *>(theData->get()->find(TString(pName(0, _pos))));
7148 cat && cat->getLabel() != pName(_pos + 1, pName.Length())) {
7149 _skip = true;
7150 }
7151 }
7152 if (_skip)
7153 continue;
7154
7155 if (xvar) {
7156 xPos->Fill(xvar->getVal(), xvar->getVal() * theData->weight());
7157 xPos2->Fill(xvar->getVal(), pow(xvar->getVal(), 2) * theData->weight());
7158 }
7159
7160 if (xcat) {
7161 theHist->Fill(xcat->getLabel(), theData->weight());
7162 nHist->Fill(xcat->getLabel(), 1);
7163 } else {
7164 theHist->Fill((x) ? xvar->getVal() : 0.5, theData->weight());
7165 nHist->Fill((x) ? xvar->getVal() : 0.5, 1);
7166 }
7167 }
7168
7169 xPos->Divide(theHist);
7170 xPos2->Divide(theHist);
7171
7172 // update the x positions to the means for each bin and use poisson asymmetric errors for data ..
7173 for (int i = 0; i < theHist->GetNbinsX(); i++) {
7174 if (includeZeros || nHist->GetBinContent(i + 1)) {
7175 double val = theHist->GetBinContent(i + 1);
7176
7177 dataGraph->SetPoint(dataGraph->GetN(),
7178 (xvar && val) ? xPos->GetBinContent(i + 1) : theHist->GetBinCenter(i + 1), val);
7179
7180 // x-error will be the (weighted) standard deviation of the x values ...
7181 double xErr = xPos2->GetBinContent(i + 1) - pow(xPos->GetBinContent(i + 1), 2);
7182 xErr = (xErr <= 0) ? 0. : sqrt(xErr); // protects against floating point rounding effects
7183
7184 if (xErr || val) {
7185 dataGraph->SetPointError(dataGraph->GetN() - 1, xErr, xErr,
7186 val - 0.5 * TMath::ChisquareQuantile(TMath::Prob(1, 1) / 2., 2. * (val)),
7187 0.5 * TMath::ChisquareQuantile(1. - TMath::Prob(1, 1) / 2., 2. * (val + 1)) -
7188 val);
7189 }
7190 }
7191 }
7192
7193 // transfer limits from theHist to dataGraph hist
7194 dataGraph->GetHistogram()->GetXaxis()->SetLimits(theHist->GetXaxis()->GetXmin(), theHist->GetXaxis()->GetXmax());
7195 // and bin labels, if any
7196 if (xcat) {
7197 dataGraph->GetHistogram()->GetXaxis()->Set(theHist->GetNbinsX(), 0, theHist->GetNbinsX());
7198 for (int i = 1; i <= theHist->GetNbinsX(); i++)
7199 dataGraph->GetHistogram()->GetXaxis()->SetBinLabel(i, theHist->GetXaxis()->GetBinLabel(i));
7200 }
7201
7202 delete xPos;
7203 delete xPos2;
7204 delete theHist;
7205
7206 // std::shared_ptr<TStyle> style; // use to keep alive for access from GetStyle below, in case getObject
7207 // has decided to return the owning ptr (for some reason) std::string _title =
7208 // strlen(dataGraph->GetTitle()) ? dataGraph->GetTitle() : GetName(); if (!gROOT->GetStyle(_title.c_str()))
7209 // {
7210 // if ( (style = getObject<TStyle>(_title)) ) {
7211 // // loaded style (from workspace?) so put in list and use that
7212 // gROOT->GetListOfStyles()->Add(style.get());
7213 // } else {
7214 // // create new style - gets put in style list automatically so don't have to delete
7215 // // acquire them so saved to workspaces for auto reload ...
7216 // style = const_cast<xRooNode&>(*this).acquireNew<TStyle>(_title.c_str(),
7217 // TString::Format("Style for %s component", _title.c_str()));
7218 // (TAttLine &) (*style) = *dynamic_cast<TAttLine *>(dataGraph);
7219 // (TAttFill &) (*style) = *dynamic_cast<TAttFill *>(dataGraph);
7220 // (TAttMarker &) (*style) = *dynamic_cast<TAttMarker *>(dataGraph);
7221 // gROOT->GetListOfStyles()->Add(style.get());
7222 // }
7223 // }
7224 auto _styleNode = styles(dataGraph);
7225 if (auto _style = _styleNode.get<TStyle>()) {
7226 *dynamic_cast<TAttLine *>(dataGraph) = *_style;
7227 *dynamic_cast<TAttFill *>(dataGraph) = *_style;
7228 *dynamic_cast<TAttMarker *>(dataGraph) = *_style;
7229 }
7230 return dataGraph;
7231 }
7232
7233 throw std::runtime_error("Cannot build graph");
7234}
7235
7237{
7238 if (fr) {
7239 if (auto _w = ws(); _w) {
7240 auto res = acquire(std::shared_ptr<RooFitResult>(const_cast<RooFitResult *>(fr), [](RooFitResult *) {}));
7241 for (auto o : _w->allGenericObjects()) {
7242 if (auto _fr = dynamic_cast<RooFitResult *>(o); _fr) {
7243 _fr->ResetBit(1 << 20);
7244 }
7245 }
7246 res->SetBit(1 << 20);
7247 // assign values
7248 auto allVars = _w->allVars();
7249 allVars = fr->floatParsFinal();
7250 allVars = fr->constPars();
7251 } else {
7252 // need to add to memory as a specific name
7253 throw std::runtime_error("Not supported yet"); // complication is how to replace an existing fitResult in
7254 // .memory auto _clone = std::make_shared<RooFitResult>(*fr);
7255 //_clone->SetName("fitResult");
7256 }
7257 } else {
7258 SetFitResult(fitResult("prefit").get<RooFitResult>());
7259 }
7260}
7261
7263{
7264 if (auto _fr = fr.get<const RooFitResult>()) {
7265 SetFitResult(_fr);
7266 } else
7267 throw std::runtime_error("Not a RooFitResult");
7268}
7269
7270xRooNode xRooNode::fitResult(const char *opt) const
7271{
7272
7273 if (get<RooFitResult>())
7274 return *this;
7275 if (get<RooAbsData>()) {
7276 if (auto _fr = find(".fitResult"); _fr)
7277 return _fr;
7278#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
7279 // check if weightVar of RooAbsData has fitResult attribute on it, will be the generation fit result
7280 if (get<RooDataSet>() && get<RooDataSet>()->weightVar() &&
7281 get<RooDataSet>()->weightVar()->getStringAttribute("fitResult")) {
7282 return xRooNode(getObject<const RooFitResult>(get<RooDataSet>()->weightVar()->getStringAttribute("fitResult")),
7283 *this);
7284 }
7285#endif
7286 return xRooNode();
7287 }
7288
7289 TString sOpt(opt);
7290 if (sOpt == "prefit") {
7291 // build a fitResult using nominal values and infer errors from constraints
7292 // that aren't the 'main' constraints
7293 // Warning("fitResult","Building prefitResult by examining pdf. Consider setting an explicit prefitResult
7294 // (SetFitResult(fr)) where fr name is prefitResult");
7295
7296 // ensure coefs are included if there are any
7297 auto _coefs = coefs();
7298 if (_coefs.get()) {
7299 return xRooNode(RooProduct("tmp", "tmp", RooArgList(*get<RooAbsArg>(), *_coefs.get<RooAbsReal>())))
7300 .fitResult(opt);
7301 }
7302
7303 std::unique_ptr<RooArgList> _pars(dynamic_cast<RooArgList *>(pars().argList().selectByAttrib("Constant", false)));
7304 auto fr = std::make_shared<RooFitResult>("prefitResult", "Prefit");
7305 fr->setFinalParList(*_pars);
7306 for (auto &p : fr->floatParsFinal()) {
7307 auto _v = dynamic_cast<RooRealVar *>(p);
7308 if (!_v)
7309 continue;
7310 if (auto s = _v->getStringAttribute("nominal"); s)
7311 _v->setVal(TString(s).Atof());
7312 auto _constr = xRooNode(fParent->getObject<RooRealVar>(p->GetName()), *this).constraints();
7313 std::shared_ptr<xRooNode> pConstr;
7314 for (auto &c : _constr) {
7315 if (c->get<RooPoisson>() || c->get<RooGaussian>()) {
7316 // require parameter to be a direct server of the constraint pdf to count
7317 bool isServer = true;
7318 if (c->get<RooGaussian>()) {
7319 isServer = false;
7320 for (auto s : c->get<RooAbsArg>()->servers()) {
7321 if (strcmp(s->GetName(), p->GetName()) == 0) {
7322 isServer = true;
7323 break;
7324 }
7325 }
7326 }
7327 if (isServer) {
7328 pConstr = c;
7329 break;
7330 }
7331 }
7332 }
7333 if (pConstr) {
7334 // there will be 3 deps, one will be this par, the other two are the mean and error (or error^2 in case of
7335 // poisson use the one that's a ConstVar as the error to break a tie ...
7336 double prefitVal = 0;
7337 double prefitError = 0;
7338 for (auto &_d : pConstr->vars()) {
7339 if (strcmp(p->GetName(), _d->get()->GetName()) == 0)
7340 continue;
7341 if (auto _c = _d->get<RooConstVar>(); _c && _c->getVal() != 0) {
7342 if (prefitError)
7343 prefitVal = prefitError; // loading val into error already, so move it over
7344 prefitError = _c->getVal();
7345 } else if (prefitError == 0) {
7346 prefitError = _d->get<RooAbsReal>()->getVal();
7347 } else {
7348 prefitVal = _d->get<RooAbsReal>()->getVal();
7349 }
7350 }
7351
7352 if (pConstr->get<RooGaussian>() && pConstr->browse().find(".sigma")) {
7353 prefitError = pConstr->find(".sigma")->get<RooAbsReal>()->getVal();
7354 }
7355 // std::cout << p->GetName() << " extracted " << prefitVal << " " << prefitError << " from ";
7356 // pConstr->deps().Print();
7357 if (pConstr->get<RooPoisson>()) {
7358 // prefitVal will be the global observable value, need to divide that by tau
7359 prefitVal /= prefitError;
7360 // prefiterror will be tau ... need 1/sqrt(tau) for error
7361 prefitError = 1. / sqrt(prefitError);
7362 }
7363 if (!_v->getStringAttribute("nominal"))
7364 _v->setVal(prefitVal);
7365 _v->setError(prefitError);
7366 } else {
7367 // unconstrained, remove error
7368 _v->removeError();
7369 }
7370 }
7371 auto _args = consts().argList();
7372 _args.add(pp().argList());
7373 // global obs are added to constPars list too
7374 auto _globs = globs(); // keep alive as may own glob
7375 _args.add(_globs.argList());
7376 fr->setConstParList(_args);
7377 std::unique_ptr<RooArgList> _snap(dynamic_cast<RooArgList *>(_pars->snapshot()));
7378 for (auto &p : *_snap) {
7379 if (auto atr = p->getStringAttribute("initVal"); atr && dynamic_cast<RooRealVar *>(p))
7380 dynamic_cast<RooRealVar *>(p)->setVal(TString(atr).Atof());
7381 }
7382 fr->setInitParList(*_snap);
7383 return xRooNode(fr, *this);
7384 }
7385
7386 // return first checked fit result present in the workspace
7387 if (auto _w = ws(); _w) {
7388 auto checkFr = [&](TObject *o) {
7389 if (auto _fr = dynamic_cast<RooFitResult *>(o); _fr && _fr->TestBit(1 << 20)) {
7390 // check all pars match final/const values ... if mismatch need to create a new RooFitResult
7391 RooArgList oldFloats;
7392 RooArgList newFloats;
7393 RooArgList newConsts;
7394 for (auto p : pars()) {
7395 if (p->get<RooAbsArg>()->getAttribute("Constant") || p->get<RooConstVar>()) {
7396 // par must not be in the float list or have different value to what is in constPars (if it is there)
7397 if (_fr->floatParsFinal().find(p->GetName()) ||
7398 (p->get<RooAbsReal>() &&
7399 std::abs(_fr->constPars().getRealValue(p->GetName(), std::numeric_limits<double>::quiet_NaN()) -
7400 p->get<RooAbsReal>()->getVal()) > 1e-15) ||
7401 (p->get<RooAbsCategory>() &&
7402 p->get<RooAbsCategory>()->getCurrentIndex() !=
7403 _fr->constPars().getCatIndex(p->GetName(), std::numeric_limits<int>().max()))) {
7404 newConsts.add(*p->get<RooAbsArg>());
7405 }
7406 } else {
7407 // floating par must be present in the floatPars list with the same value
7408 if (!_fr->floatParsFinal().find(p->GetName())) {
7409 newFloats.add(*p->get<RooAbsArg>());
7410 } else if ((p->get<RooAbsReal>() &&
7411 std::abs(_fr->floatParsFinal().getRealValue(p->GetName(),
7412 std::numeric_limits<double>::quiet_NaN()) -
7413 p->get<RooAbsReal>()->getVal()) > 1e-15) ||
7414 (p->get<RooAbsCategory>() &&
7415 p->get<RooAbsCategory>()->getCurrentIndex() !=
7416 _fr->floatParsFinal().getCatIndex(p->GetName(), std::numeric_limits<int>().max()))) {
7417 // value of existing float changed
7418 oldFloats.add(*p->get<RooAbsArg>());
7419 }
7420 }
7421 }
7422 if (!oldFloats.empty() || !newFloats.empty() || !newConsts.empty()) {
7423 // create new fit result using covariance from the fit result
7424 // remove any new consts from the list before extracting covariance matrix
7425 RooArgList existingFloats(_fr->floatParsFinal());
7426 existingFloats.remove(newConsts, true, true /* match name*/);
7427 auto cov = _fr->reducedCovarianceMatrix(existingFloats);
7428 if (!newFloats.empty()) {
7429 // extend the covariance matrix and add variances using current parameter errors
7430 size_t oldSize = existingFloats.size();
7431 cov.ResizeTo(oldSize + newFloats.size(), oldSize + newFloats.size());
7432 for (size_t i = 0; i < newFloats.size(); i++) {
7433 existingFloats.add(*newFloats.at(i));
7434 auto v = dynamic_cast<RooRealVar *>(newFloats.at(i));
7435 if (v)
7436 cov(oldSize + i, oldSize + i) = std::pow(v->getError(), 2);
7437 }
7438 }
7439 RooArgList existingConsts(_fr->constPars());
7440 existingConsts.remove(newFloats, true, true);
7441 existingConsts.add(newConsts);
7442
7443 // do we need to add our remaining const pars to the const par list? or the globs?
7444 // for speed we wont bother
7445 // note that generating datasets needs the globs in the const pars list so the robs can be determined
7446 // at the moment this check is done in the generate() method (along with check for missing pars)
7447
7448 auto fr = std::make_shared<RooFitResult>(TString::Format("%s-dirty", _fr->GetName()));
7449 fr->setFinalParList(existingFloats);
7450 fr->setConstParList(existingConsts);
7451 fr->setCovarianceMatrix(cov);
7452 fr->setInitParList(_fr->floatParsInit()); // will only be the pars that were actually float for the fit
7453
7454 return xRooNode(fr, *this);
7455 } else {
7456 // all matching, can return the fit result as-is
7457 return xRooNode(*_fr, std::make_shared<xRooNode>(*_w, std::make_shared<xRooNode>()));
7458 }
7459 }
7460 return xRooNode();
7461 };
7462 for (auto o : _w->allGenericObjects()) {
7463 auto out = checkFr(o);
7464 if (out)
7465 return out;
7466 }
7467 for (auto o : GETWSSNAPSHOTS(_w)) {
7468 auto out = checkFr(o);
7469 if (out)
7470 return out;
7471 }
7472 } else {
7473 // objects not in workspaces are allowed to have a fitResult set in their memory
7474 // use getObject to get it
7475 if (auto fr = getObject<RooFitResult>(".fitResult"); fr) {
7476 return xRooNode(fr, *this);
7477 }
7478 }
7479
7480 // ensure coefs are included if there are any
7481 auto _coefs = coefs();
7482 if (_coefs.get()) {
7483 return xRooNode(RooProduct("tmp", "tmp", RooArgList(*get<RooAbsArg>(), *_coefs.get<RooAbsReal>())))
7484 .fitResult(opt);
7485 }
7486
7487 std::unique_ptr<RooArgList> _pars(dynamic_cast<RooArgList *>(pars().argList().selectByAttrib("Constant", false)));
7488 auto fr = std::make_shared<RooFitResult>(TUUID().AsString());
7489 fr->SetTitle(TString::Format("%s uncorrelated parameter snapshot", GetName()));
7490 fr->setFinalParList(*_pars);
7491 fr->setStatus(-1);
7492
7493 TMatrixDSym cov(fr->floatParsFinal().size());
7494 TMatrixTSym<double> *prevCov = static_cast<TMatrixTSym<double> *>(GETDMP(fr.get(), _VM));
7495 if (prevCov) {
7496 for (int i = 0; i < prevCov->GetNcols(); i++) {
7497 for (int j = 0; j < prevCov->GetNrows(); j++) {
7498 cov(i, j) = (*prevCov)(i, j);
7499 }
7500 }
7501 }
7502 int i = 0;
7503 for (auto &p : fr->floatParsFinal()) {
7504 if (!prevCov || i >= prevCov->GetNcols()) {
7505 if (auto v = dynamic_cast<RooRealVar *>(p)) {
7506 cov(i, i) = pow(v->getError(), 2);
7507 } else {
7508 cov(i, i) = 0;
7509 }
7510 }
7511 i++;
7512 }
7513 int covQualBackup = fr->covQual();
7514 fr->setCovarianceMatrix(cov);
7515 fr->setCovQual(covQualBackup);
7516
7517 auto _args = consts().argList();
7518 _args.add(pp().argList());
7519 // global obs are added to constPars list too
7520 auto _globs = globs(); // keep alive as may own glob
7521 _args.add(_globs.argList());
7522 fr->setConstParList(_args);
7523 std::unique_ptr<RooArgList> _snap(dynamic_cast<RooArgList *>(_pars->snapshot()));
7524 for (auto &p : *_snap) {
7525 if (auto atr = p->getStringAttribute("initVal"); atr && dynamic_cast<RooRealVar *>(p))
7526 dynamic_cast<RooRealVar *>(p)->setVal(TString(atr).Atof());
7527 }
7528 fr->setInitParList(*_snap);
7529
7530 // return *const_cast<Node2*>(this)->emplace_back(std::make_shared<Node2>(".fitResult",fr,*this));
7531 return xRooNode(fr, *this);
7532}
7533
7534// xRooNode xRooNode::fitTo_(const char* datasetName) const {
7535// try {
7536// return fitTo(datasetName);
7537// } catch(const std::exception& e) {
7538// new TGMsgBox(gClient->GetRoot(), gClient->GetRoot(), "Exception", e.what(),kMBIconExclamation); // deletes
7539// self on dismiss? return xRooNode();
7540// }
7541// }
7542//
7543// xRooNode xRooNode::fitTo(const char* datasetName) const {
7544// return fitTo(*datasets().at(datasetName));
7545// }
7546
7547void xRooNode::SetRange(const char *range, double low, double high)
7548{
7549 if (!std::isnan(low) && !std::isnan(high) && get<RooRealVar>()) {
7550 if (range && strlen(range)) {
7551 get<RooRealVar>()->setRange(range, low, high);
7552 } else {
7553 get<RooRealVar>()->setRange(low, high);
7554 }
7555 return;
7556 }
7557 if (auto o = get<RooAbsArg>(); o)
7558 o->setStringAttribute("range", range);
7559 // todo: clear the range attribute on all servers
7560 // could make this controlled by a flag but probably easiest to enforce so you must set range
7561 // in children after if you wanted to override
7562}
7563const char *xRooNode::GetRange() const
7564{
7565 std::string &out = fRange;
7566 if (auto o = get<RooAbsArg>(); o && o->getStringAttribute("range"))
7567 out = o->getStringAttribute("range");
7568 auto _parent = fParent;
7569 while (out.empty() && _parent) {
7570 if (auto o = _parent->get<RooAbsArg>(); o && o->getStringAttribute("range"))
7571 out = o->getStringAttribute("range");
7572 _parent = _parent->fParent;
7573 }
7574 return out.c_str();
7575}
7576
7577xRooNLLVar xRooNode::nll(const char *_data, std::initializer_list<RooCmdArg> nllOpts) const
7578{
7579 return nll(xRooNode(_data), nllOpts);
7580}
7581
7583{
7584 return nll(_data, *xRooFit::createNLLOptions());
7585}
7586
7587xRooNLLVar xRooNode::nll(const xRooNode &_data, std::initializer_list<RooCmdArg> nllOpts) const
7588{
7589 auto defaultOpts = xRooFit::createNLLOptions(); // smart pointer will cleanup the list
7590 // add user-specified options to list ... if already existing in default list, override and warn
7592 for (auto opt : *defaultOpts) {
7593 l.Add(opt);
7594 }
7595 for (auto &i : nllOpts) {
7596 if (auto o = l.FindObject(i.GetName())) {
7597 Info("nll", "Overriding NLL Option: %s", o->GetName());
7598 l.Remove(o);
7599 }
7600 l.Add(const_cast<RooCmdArg *>(&i));
7601 }
7602
7603 return nll(_data, l);
7604}
7605
7606xRooNode xRooNode::generate(const xRooNode &fr, bool expected, int seed)
7607{
7608 if (auto mc = get<RooStats::ModelConfig>()) {
7609 return xRooNode(*mc->GetPdf(), fParent).generate(fr, expected, seed);
7610 }
7611
7612 if (!get<RooAbsPdf>()) {
7613 // before giving up, if this is a workspace we can proceed if we only have one model
7614 if (get<RooWorkspace>()) {
7615 std::shared_ptr<xRooNode> mainModel;
7616 for (auto &c : const_cast<xRooNode *>(this)->browse()) {
7617 if (c->get<RooAbsPdf>()) {
7618 if (!mainModel) {
7619 mainModel = c;
7620 } else {
7621 throw std::runtime_error(TString::Format("Workspace has multiple models, you must specify which to "
7622 "generate with (found at least %s and %s)",
7623 mainModel->GetName(), c->GetName()));
7624 }
7625 }
7626 }
7627 if (mainModel)
7628 return mainModel->generate(fr, expected, seed);
7629 }
7630 throw std::runtime_error(TString::Format("%s is not a pdf", GetName()));
7631 }
7632
7633 // when generating, will only include channels that are selected
7634 // any unselected but not hidden channel will have data from the only selected dataset added to it
7635 if (get<RooSimultaneous>()) {
7636 std::string selected;
7637 std::string fromds; // list of channels to take from selected ds
7638 bool hasDeselected = false;
7639 for (auto c : bins()) {
7640 TString cName(c->GetName());
7641 cName = cName(cName.Index('=') + 1, cName.Length());
7642 if (!c->get<RooAbsReal>()->isSelectedComp()) {
7643 hasDeselected = true;
7644 if (!c->get<RooAbsArg>()->getAttribute("hidden")) {
7645 if (!fromds.empty())
7646 fromds += ",";
7647 fromds += cName.Data();
7648 }
7649 } else {
7650 if (!selected.empty())
7651 selected += ",";
7652 selected += cName.Data();
7653 }
7654 }
7655 if (hasDeselected) {
7656 std::string dsetName = "";
7657 if (!fromds.empty()) {
7658 // use the first selected dataset as protodata
7659 auto _dsets = datasets();
7660 for (auto &d : _dsets) {
7661 if (d->get()->TestBit(1 << 20)) {
7662 dsetName = d->get()->GetName();
7663 break;
7664 }
7665 }
7666 if (dsetName.empty()) {
7667 throw std::runtime_error(
7668 "Need at least one dataset selected (SetChecked) to use for deselected regions");
7669 }
7670 }
7671 auto result = reduced(selected).generate(fr, expected, seed);
7672 if (!fromds.empty()) {
7673 auto ds = reduced(fromds).datasets()[dsetName];
7674 result.Add(*ds);
7675 result.SetName(TString(result.GetName()) + "_and_" + dsetName.c_str());
7676 }
7677 return result;
7678 }
7679 }
7680
7681 auto _fr = fr.get<RooFitResult>();
7682 xRooNode fr2;
7683 if (!_fr) {
7684 fr2 = fitResult();
7685 _fr = fr2.get<RooFitResult>();
7686 }
7687
7688 // must ensure fr has all the globs in its constPars list ... any missing must be added
7689 // otherwise generateFrom method wont determine globs properly
7690 // same for any missing pars
7691 auto _globs = globs();
7692 bool missingGlobs(false);
7693 for (auto glob : _globs) {
7694 if (!_fr->constPars().find(*glob->get<RooAbsArg>())) {
7695 missingGlobs = true;
7696 break;
7697 }
7698 }
7699
7700 std::unique_ptr<RooFitResult> newFr;
7701 if (missingGlobs) {
7702 newFr = std::make_unique<RooFitResult>(*_fr);
7703 for (auto glob : _globs) {
7704 if (!newFr->constPars().find(*glob->get<RooAbsArg>())) {
7705 const_cast<RooArgList &>(newFr->constPars()).addClone(*glob->get<RooAbsArg>());
7706 }
7707 }
7708 _fr = newFr.get();
7709 }
7710
7711 // check for missing fundamental pars (consts are not fundamentals)
7712 auto _pars = pars();
7713 bool missingPars(false);
7714 for (auto par : _pars) {
7715 if (!par->get<RooAbsArg>()->isFundamental())
7716 continue;
7717 if (!_fr->constPars().find(*par->get<RooAbsArg>()) && !_fr->floatParsFinal().find(*par->get<RooAbsArg>())) {
7718 missingPars = true;
7719 break;
7720 }
7721 }
7722
7723 if (missingPars) {
7724 newFr = std::make_unique<RooFitResult>(*_fr);
7725 for (auto par : _pars) {
7726 if (!par->get<RooAbsArg>()->isFundamental())
7727 continue;
7728 if (!newFr->constPars().find(*par->get<RooAbsArg>()) &&
7729 !newFr->floatParsFinal().find(*par->get<RooAbsArg>())) {
7730 const_cast<RooArgList &>(newFr->constPars()).addClone(*par->get<RooAbsArg>());
7731 }
7732 }
7733 _fr = newFr.get();
7734 }
7735
7736 return xRooNode(xRooFit::generateFrom(*get<RooAbsPdf>(), *_fr, expected, seed).first, *this);
7737
7738 // should add coords to the dataset too?
7739 // e.g. in the case of generating a dataset for a single channel, include the channelCat
7740 // this will allow datasets to then be combined.
7741 // could just say users must use 'reduced' on the simPdf, even if reducing to a single channel
7742}
7743
7744xRooNLLVar xRooNode::nll(const xRooNode &_data, const RooLinkedList &opts) const
7745{
7746 if (auto mc = get<RooStats::ModelConfig>()) {
7747 if (mc->GetExternalConstraints()) {
7748 RooLinkedList optsWithConstraints;
7749 for (auto o : opts) {
7750 optsWithConstraints.Add(o->Clone(nullptr));
7751 }
7752 optsWithConstraints.Add(RooFit::ExternalConstraints(*mc->GetExternalConstraints()).Clone(nullptr));
7753 return xRooNode(*mc->GetPdf(), fParent).nll(_data, optsWithConstraints);
7754 } else {
7755 return xRooNode(*mc->GetPdf(), fParent).nll(_data, opts);
7756 }
7757 }
7758
7759 if (!get<RooAbsPdf>()) {
7760 // before giving up, if this is a workspace we can proceed if we only have one model or pdf
7761 if (get<RooWorkspace>()) {
7762 std::shared_ptr<xRooNode> mainPdf, mainModel, otherPdf;
7763 for (auto &c : const_cast<xRooNode *>(this)->browse()) {
7764 if (c->get<RooAbsPdf>()) {
7765 if (!mainPdf) {
7766 mainPdf = c;
7767 } else {
7768 otherPdf = c;
7769 }
7770 } else if (c->get<RooStats::ModelConfig>()) {
7771 if (!mainModel) {
7772 mainModel = c;
7773 } else {
7774 throw std::runtime_error(TString::Format("Workspace has multiple models, you must specify which to "
7775 "build nll with (found at least %s and %s)",
7776 mainModel->GetName(), c->GetName()));
7777 }
7778 }
7779 }
7780 if (mainModel)
7781 return mainModel->nll(_data, opts);
7782 if (mainPdf) {
7783 if (otherPdf) {
7784 throw std::runtime_error(TString::Format("Workspace has multiple pdfs, you must specify which to "
7785 "build nll with (found at least %s and %s)",
7786 mainPdf->GetName(), otherPdf->GetName()));
7787 }
7788 return mainPdf->nll(_data, opts);
7789 }
7790 }
7791 throw std::runtime_error(TString::Format("%s is not a pdf", GetName()));
7792 }
7793
7794 // if simultaneous and any channels deselected then reduce and return
7795 if (get<RooSimultaneous>()) {
7796 std::string selected;
7797 bool hasDeselected = false;
7798 for (auto c : bins()) {
7799 if (!c->get<RooAbsReal>()->isSelectedComp()) {
7800 hasDeselected = true;
7801 } else {
7802 TString cName(c->GetName());
7803 cName = cName(cName.Index('=') + 1, cName.Length());
7804 if (!selected.empty())
7805 selected += ",";
7806 selected += cName.Data();
7807 }
7808 }
7809 if (hasDeselected)
7810 return reduced(selected).nll(_data, opts);
7811 }
7812
7813 if (!_data.get<RooAbsData>()) {
7814 // use node name to find dataset and recall
7815 auto _d = strlen(_data.GetName()) ? datasets().find(_data.GetName()) : nullptr;
7816 if (strlen(_data.GetName()) == 0) {
7817 // create the EXPECTED (asimov) dataset with the observables
7818 auto asi = xRooFit::generateFrom(*get<RooAbsPdf>(), *(fitResult().get<RooFitResult>()), true);
7819 _d = std::make_shared<xRooNode>(asi.first, *this);
7820 if (asi.second) {
7821 _d->emplace_back(
7822 std::make_shared<xRooNode>(".globs", std::const_pointer_cast<RooAbsCollection>(asi.second), *_d));
7823 }
7824 } else if (!_d) {
7825 throw std::runtime_error(TString::Format("Cannot find dataset %s", _data.GetName()));
7826 }
7827 return nll(*_d, opts);
7828 } else if (!_data.fParent || _data.fParent->fComp != fComp) {
7829 // dataset is not parented by this node ... meaning it may need to be reduced,
7830 // do this via the datasets() method by attaching and detaching the dataset
7831 xRooNode me(*this); // since we are in a const method, need to create a copy node.
7832 me.push_back(std::make_shared<xRooNode>(_data));
7833 return nll(*me.datasets().at(_data.GetName()), opts);
7834 }
7835
7836 auto _globs = _data.globs(); // keep alive because may own the globs
7837
7838 auto _opts = std::shared_ptr<RooLinkedList>(new RooLinkedList, [](RooLinkedList *l) {
7839 if (l)
7840 l->Delete();
7841 delete l;
7842 });
7843 RooArgSet _globsSet(_globs.argList());
7844 _opts->Add(RooFit::GlobalObservables(_globsSet).Clone());
7845 if (GetRange() && strlen(GetRange()))
7846 _opts->Add(RooFit::Range(GetRange()).Clone());
7847
7848 // copy over opts ... need to clone each so can safely delete when _opts destroyed
7849 for (int i = 0; i < opts.GetSize(); i++) {
7850 if (strlen(opts.At(i)->GetName()) == 0)
7851 continue; // skipping "none" cmds
7852 if (strcmp(opts.At(i)->GetName(), "GlobalObservables") == 0) {
7853 // maybe warn here?
7854 } else {
7855 _opts->Add(opts.At(i)->Clone(nullptr)); // nullptr needed because accessing Clone via TObject base class puts
7856 // "" instead, so doesnt copy names
7857 }
7858 }
7859
7860 // use shared_ptr method so NLLVar will take ownership of datasets etc if created above
7861 // snapshots the globs out of the nllOpts (see specific constructor of xRooNLLVar)
7862 auto out = xRooFit::createNLL(std::dynamic_pointer_cast<RooAbsPdf>(fComp),
7863 std::dynamic_pointer_cast<RooAbsData>(_data.fComp), *_opts);
7864 return out;
7865}
7866
7867// xRooNode xRooNode::fitTo(const xRooNode& _data) const {
7868//
7869//
7870// auto _pdf = get<RooAbsPdf>();
7871// if (!_pdf) throw std::runtime_error("Not a pdf");
7872//
7873// auto _globs = _data.globs(); // keep alive because may own the globs
7874// RooArgSet globsSet(_globs.argList());
7875//
7876// std::shared_ptr<RooSimultaneous> newPdf;
7877// if(auto s = get<RooSimultaneous>(); s) {
7878// auto rangeName = GetRange();
7879// if (rangeName) {
7880// // need to reduce the RooSimultaneous until fix: https://github.com/root-project/root/issues/8231
7881// std::vector<TString> chanPatterns;
7882// TStringToken pattern(rangeName, ",");
7883// while (pattern.NextToken()) {
7884// chanPatterns.emplace_back(pattern);
7885// }
7886// auto& _cat = const_cast<RooAbsCategoryLValue&>(s->indexCat());
7887// newPdf = std::make_shared<RooSimultaneous>(TString::Format("%s_reduced",GetName()),"Reduced model",_cat);
7888// for(auto& c : variations()) {
7889// TString cName(c->GetName());
7890// cName = cName(cName.Index('=')+1,cName.Length());
7891// _cat.setLabel(cName);
7892// bool matchAny=false;
7893// for(auto& p : chanPatterns) {
7894// if (cName.Contains(TRegexp(p,true))) { matchAny=true; break; }
7895// if (_cat.hasRange(p) && _cat.inRange(p)) { matchAny=true; break; }
7896// }
7897// if(matchAny) {
7898// newPdf->addPdf( *c->get<RooAbsPdf>(), cName );
7899// }
7900// }
7901// RooFitResultTree t(newPdf->GetName(),"",*newPdf);
7902// auto _fr = std::const_pointer_cast<RooFitResult>(t.fitTo(_data.get<RooAbsData>(), &globsSet));
7903// xRooNode parent(_data.GetName(),nullptr,*this);
7904// xRooNode out(_fr->GetName(),/*acquire(_fr)*/ _fr,parent);
7905// // do full propagation by 'checking' the fr ...
7906// out.Checked(&out,true);
7907// return out;
7908// }
7909// }
7910//
7911//
7912//
7913// std::string treeName = TString::Format("fits_%s",GetName()).Data();
7914//
7915// auto _frt = getObject<TTree>(treeName); // get existing frt
7916//
7917// std::shared_ptr<RooFitResultTree> t;
7918// if (_frt) {
7919// t = std::make_shared<RooFitResultTree>(_frt.get());
7920// } else {
7921// t = std::make_shared<RooFitResultTree>(treeName.c_str(),"",*_pdf);
7922// }
7923// //t->SetProgress(true);
7924// auto _fr = std::const_pointer_cast<RooFitResult>(t->fitTo(_data.get<RooAbsData>(), &globsSet));
7925//
7926//
7927//
7928// /*
7929// obs().argList() = s; // sets global observables to their values
7930// auto _fr =
7931// std::shared_ptr<RooFitResult>(_pdf->fitTo(*_data->get<RooAbsData>(),RooFit::GlobalObservables(s),RooFit::Offset(true),RooFit::Save()));
7932// _fr->SetName(TUUID().AsString());
7933// // restore parameters before returning
7934// *std::unique_ptr<RooArgSet>(_pdf->getDependents(_fr->floatParsFinal())) = _fr->floatParsInit();
7935// */
7936//
7937// //_fr->SetTitle(TString::Format("%s;%s",GetName(),datasetName));
7938// if (!_frt) {
7939// t =
7940// std::make_shared<RooFitResultTree>(std::dynamic_pointer_cast<TTree>(const_cast<xRooNode*>(this)->acquire(t->fTree)).get());
7941// }
7942// xRooNode parent(_data.GetName(),nullptr,xRooNode(t,*this));
7943// xRooNode out(_fr->GetName(),/*acquire(_fr)*/ _fr,parent);
7944// // do full propagation by 'checking' the fr ...
7945// out.Checked(&out,true);
7946// return out;
7947// }
7948
7949std::shared_ptr<xRooNode> xRooNode::parentPdf() const
7950{
7951 // find first parent that is a pdf
7952 auto out = fParent;
7953 while (out && !out->get<RooAbsPdf>()) {
7954 out = out->fParent;
7955 }
7956 return out;
7957}
7958
7959xRooNode xRooNode::reduced(const std::string &_range, bool invert) const
7960{
7961 auto rangeName = (_range.empty()) ? GetRange() : _range;
7962 if (!rangeName.empty()) {
7963 std::vector<TString> patterns;
7964 TStringToken pattern(rangeName, ",");
7965 while (pattern.NextToken()) {
7966 patterns.emplace_back(pattern);
7967 }
7968 if (auto s = get<RooSimultaneous>(); s) {
7969 // need to reduce the RooSimultaneous until fix: https://github.com/root-project/root/issues/8231
7970 auto &_cat = const_cast<RooAbsCategoryLValue &>(s->indexCat());
7971 auto newPdf =
7972 std::make_shared<RooSimultaneous>(TString::Format("%s_reduced", GetName()), "Reduced model", _cat);
7973 for (auto &c : bins()) {
7974 TString cName(c->GetName());
7975 cName = cName(cName.Index('=') + 1, cName.Length());
7976 _cat.setLabel(cName);
7977 bool matchAny = false;
7978 for (auto &p : patterns) {
7979 TString pNoCatName(p);
7980 if (pNoCatName.Contains('='))
7981 pNoCatName = pNoCatName(pNoCatName.Index('=') + 1, pNoCatName.Length());
7982 if (cName.Contains(TRegexp(p, true)) || cName.Contains(TRegexp(pNoCatName, true))) {
7983 matchAny = true;
7984 break;
7985 }
7986 if (_cat.hasRange(p) && _cat.inRange(p)) {
7987 matchAny = true;
7988 break;
7989 }
7990 }
7991 if ((matchAny && !invert) || (!matchAny && invert)) {
7992 newPdf->addPdf(*c->get<RooAbsPdf>(), cName);
7993 }
7994 }
7995 return xRooNode(newPdf, fParent);
7996 } else if (get() && !get<RooAbsCollection>() && !components().empty()) {
7997 // create a new obj and remove non-matching components
7998 xRooNode out(std::shared_ptr<TObject>(get()->Clone(TString::Format("%s_reduced", get()->GetName()))), fParent);
7999 // go through components and remove any that don't match pattern
8000 std::vector<TObject *> funcs; // to be removed
8001 for (auto &c : out.components()) {
8002 bool matchAny = false;
8003 for (auto &p : patterns) {
8004 if (TString(c->GetName()).Contains(TRegexp(p, true))) {
8005 matchAny = true;
8006 break;
8007 }
8008 }
8009 if (!((matchAny && !invert) || (!matchAny && invert)))
8010 funcs.push_back(c->get());
8011 }
8012 for (auto &c : funcs)
8013 out.Remove(*c);
8014 if (!funcs.empty()) {
8015 if (auto _pdf = out.get<RooRealSumPdf>(); _pdf) {
8016 _pdf->setFloor(false); // remove floor if removed some functions, which allows evaluation of negative
8017 // valued components
8018 }
8019 }
8020 out.browse();
8021 return out;
8022 } else if (auto fr = get<RooFitResult>()) {
8023 // reduce the fit result by moving unselected float pars into the constPars list and dropping their covariances
8024 xRooNode out(std::shared_ptr<TObject>(fr->Clone(TString::Format("%s_reduced", fr->GetName()))), fParent);
8025 fr = out.get<RooFitResult>();
8026 RooArgList _pars = fr->floatParsFinal();
8027 RooArgList _remPars;
8028 for (auto c : _pars) {
8029 bool matchAny = false;
8030 for (auto &p : patterns) {
8031 if (TString(c->GetName()).Contains(TRegexp(p, true))) {
8032 matchAny = true;
8033 break;
8034 }
8035 }
8036 if (!((matchAny && !invert) || (!matchAny && invert))) {
8037 _remPars.add(*c);
8038 }
8039 }
8040 _pars.remove(_remPars, true);
8041
8042 auto _tmp = fr->reducedCovarianceMatrix(_pars);
8043 int covQualBackup = fr->covQual();
8044 fr->setCovarianceMatrix(_tmp);
8045 fr->setCovQual(covQualBackup);
8046 const_cast<RooArgList &>(fr->floatParsFinal())
8047 .remove(_remPars, true); // is this a memory leak ... should delete the remPars?
8048 return out;
8049
8050 } else if (!get() || get<RooAbsCollection>()) {
8051 // filter the children .... handle special case of filtering ".vars" with "x" option too
8052 xRooNode out(std::make_shared<RooArgList>(), fParent);
8053 out.SetName(TString(GetName()) + "_reduced");
8054 size_t nobs = 0;
8055 bool notAllArgs = false;
8056 bool isVars = (strcmp(GetName(), ".vars") == 0);
8057 for (auto c : *this) {
8058 nobs += (c->fFolder == "!robs" || c->fFolder == "!globs");
8059 bool matchAny = false;
8060 for (auto &p : patterns) {
8061 if (TString(c->GetName()).Contains(TRegexp(p, true)) ||
8062 (isVars && p == "x" && (c->fFolder == "!robs" || c->fFolder == "!globs") && nobs == 1)) {
8063 matchAny = true;
8064 break;
8065 }
8066 }
8067 if ((matchAny && !invert) || (!matchAny && invert)) {
8068 out.push_back(c);
8069 if (auto a = c->get<RooAbsArg>()) {
8070 out.get<RooArgList>()->add(*a);
8071 } else {
8072 notAllArgs = true;
8073 }
8074 }
8075 }
8076 if (notAllArgs) {
8077 out.fComp.reset();
8078 }
8079 return out;
8080 }
8081 }
8082
8083 return get<RooArgList>() ? xRooNode(std::make_shared<RooArgList>(), fParent) : *this;
8084}
8085
8086xRooNode xRooNode::reduced(const std::function<bool(const xRooNode &)> selector) const
8087{
8088 if (empty()) {
8089 const_cast<xRooNode &>(*this).browse();
8090 }
8091 // build a list of children to keep
8092 std::string noName = "___"; // assume this is never a name
8093 std::string childNames;
8094 for (auto &c : *this) {
8095 if (selector(*c)) {
8096 if (!childNames.empty())
8097 childNames += ",";
8098 childNames += c->GetName();
8099 }
8100 }
8101 if (childNames.empty())
8102 childNames = noName; // if childNames was blank it would return the full list;
8103 return reduced(childNames); // calls main method above ... this will ensure we construct a reduced version of ourself
8104}
8105
8106// xRooNode xRooNode::generate(bool expected) const {
8107//
8108// auto fr = fitResult();
8109// auto _fr = fr.get<RooFitResult>();
8110//
8111// auto _pdf = (get<RooAbsPdf>()) ? std::shared_ptr<const xRooNode>(this, [](const xRooNode*){}) : parentPdf();
8112// if (!_pdf) {
8113// throw std::runtime_error("Could not find pdf");
8114// }
8115//
8116// std::shared_ptr<RooDataTree> t;
8117//
8118// std::shared_ptr<RooSimultaneous> newPdf;
8119// if(auto s = _pdf->get<RooSimultaneous>(); s) {
8120// auto rangeName = GetRange();
8121// if (rangeName) {
8122// // need to reduce the RooSimultaneous until fix: https://github.com/root-project/root/issues/8231
8123// std::vector<TString> chanPatterns;
8124// TStringToken pattern(rangeName, ",");
8125// while (pattern.NextToken()) {
8126// chanPatterns.emplace_back(pattern);
8127// }
8128// auto& _cat = const_cast<RooAbsCategoryLValue&>(s->indexCat());
8129// newPdf = std::make_shared<RooSimultaneous>(TString::Format("%s_reduced",GetName()),"Reduced model",_cat);
8130// for(auto& c : _pdf->variations()) {
8131// TString cName(c->GetName());
8132// cName = cName(cName.Index('=')+1,cName.Length());
8133// _cat.setLabel(cName);
8134// bool matchAny=false;
8135// for(auto& p : chanPatterns) {
8136// if (cName.Contains(TRegexp(p,true))) { matchAny=true; break; }
8137// if (_cat.hasRange(p) && _cat.inRange(p)) { matchAny=true; break; }
8138// }
8139// if(matchAny) {
8140// newPdf->addPdf( *c->get<RooAbsPdf>(), cName );
8141// }
8142// }
8143// t = std::make_shared<RooDataTree>(newPdf->GetName(),"",*newPdf);
8144// RooArgSet s1(_pdf->obs().argList());
8145// RooArgSet s2(_pdf->globs().argList());s1.remove(s2);
8146// t->SetObservables(&s1,&s2);
8147// auto _data = t->generate(_fr,expected);
8148//
8149// xRooNode parent(_fr ? _fr->GetName() : "unknown",nullptr,xRooNode(t,*this));
8150// xRooNode out(_data.first->GetName(),/*acquire(_fr)*/ _data.first,parent);
8151// out.emplace_back(std::make_shared<xRooNode>(".globs",std::const_pointer_cast<RooArgSet>(_data.second),out));
8152// return out;
8153// }
8154// }
8155//
8156//
8157// std::string treeName = TString::Format("gen_%s",_pdf->GetName()).Data();
8158//
8159// auto _frt = getObject<TTree>(treeName); // get existing frt
8160//
8161//
8162// if (_frt) {
8163// t = std::make_shared<RooDataTree>(_frt.get());
8164// } else {
8165// t = std::make_shared<RooDataTree>(treeName.c_str(),"",*_pdf->get<RooAbsPdf>());
8166// RooArgSet s1(_pdf->obs().argList());
8167// RooArgSet s2(_pdf->globs().argList());s1.remove(s2);
8168// t->SetObservables(&s1,&s2);
8169// }
8170// auto _data = t->generate(_fr,expected);
8171// if (!_frt) {
8172// t =
8173// std::make_shared<RooDataTree>(std::dynamic_pointer_cast<TTree>(const_cast<xRooNode*>(this)->acquire(t->fTree)).get());
8174// }
8175// xRooNode parent(_fr ? _fr->GetName() : "unknown",nullptr,xRooNode(t,*this));
8176// xRooNode out(_data.first->GetName(),/*acquire(_fr)*/ _data.first,parent);
8177// out.emplace_back(std::make_shared<xRooNode>(".globs",std::const_pointer_cast<RooArgSet>(_data.second),out));
8178// return out;
8179// }
8180
8182public:
8184 double expectedEvents(const RooArgSet *nset) const override
8185 {
8186 return static_cast<RooAbsPdf *>(intpdf.absArg())->expectedEvents(nset);
8187 }
8188 ExtendMode extendMode() const override { return static_cast<RooAbsPdf *>(intpdf.absArg())->extendMode(); }
8189 TObject *clone(const char *newname) const override { return new xRooProjectedPdf(*this, newname); }
8190
8191protected:
8192 double evaluate() const override
8193 {
8194 int code;
8195 return getProjection(&intobs, _normSet, (_normRange.Length() > 0 ? _normRange.Data() : nullptr), code)->getVal();
8196 }
8197};
8198
8199std::vector<double> new_getPropagatedErrors(const RooAbsReal &f, const RooFitResult &fr, const RooArgSet &nset,
8200 RooArgList **pars, bool asymHi, bool asymLo, const std::vector<int> &bins,
8201 const std::function<void(int)> &setBin)
8202{
8203 const size_t nBins = bins.size();
8204 std::vector<double> out(nBins, 0.);
8205 if (nBins == 0)
8206 return out;
8207
8208 // Build the list of parameters f depends on that have a non-zero error.
8209 // The result is cached in *pars so it is only computed once across repeated
8210 // calls (e.g. the separate Hi and Lo passes of an asymmetric error band).
8211 RooArgList *_pars = (pars) ? *pars : nullptr;
8212
8213 if (!_pars) {
8214
8215 RooArgSet allParamsInAbsReal;
8216 f.getParameters(&nset, allParamsInAbsReal);
8217
8218 _pars = new RooArgList;
8219 for (auto *rrvFitRes : static_range_cast<RooRealVar *>(fr.floatParsFinal())) {
8220
8221 auto rrvInAbsReal = static_cast<RooRealVar const *>(allParamsInAbsReal.find(*rrvFitRes));
8222
8223 // Strip out parameters with zero error
8224 if (rrvFitRes->getError() <= std::abs(rrvFitRes->getVal()) * std::numeric_limits<double>::epsilon())
8225 continue;
8226
8227 // Ignore parameters in the fit result that this RooAbsReal doesn't depend on
8228 if (!rrvInAbsReal)
8229 continue;
8230
8231 // Checking for float equality is a bad. We check if the values are
8232 // negligibly far away from each other, relative to the uncertainty.
8233 if (std::abs(rrvInAbsReal->getVal() - rrvFitRes->getVal()) > 0.01 * rrvFitRes->getError()) {
8234 std::stringstream errMsg;
8235 errMsg << "RooAbsReal::getPropagatedError(): the parameters of the RooAbsReal don't have"
8236 << " the same values as in the fit result! The logic of getPropagatedError is broken in this case."
8237 << " \n " << rrvInAbsReal->GetName() << " : " << rrvInAbsReal->getVal() << " vs "
8238 << rrvFitRes->getVal();
8239
8240 throw std::runtime_error(errMsg.str());
8241 }
8242
8243 _pars->add(*rrvInAbsReal);
8244 }
8245 }
8246
8247 const size_t nPars = _pars->size();
8248
8249 // Covariance and correlation matrices depend only on the fit result and the
8250 // parameter set, so build them (including the matrix reduction) once for all
8251 // bins rather than once per bin.
8252 // TODO: if _pars includes pars not in fr, need to extend matrix with uncorrelated errors of those pars
8253 // (as built above, _pars is a subset of fr.floatParsFinal(), so such pars are currently dropped silently).
8254 TMatrixDSym V(nPars == fr.floatParsFinal().size() ? fr.covarianceMatrix() : fr.reducedCovarianceMatrix(*_pars));
8255
8256 TMatrixDSym C(nPars);
8257 for (size_t i = 0; i < nPars; i++) {
8258 for (size_t j = i; j < nPars; j++) {
8259 C(i, j) = V(i, j) / std::sqrt(V(i, i) * V(j, j));
8260 C(j, i) = C(i, j);
8261 }
8262 }
8263
8264 // Nominal value of each bin (only needed to symmetrize asymmetric errors).
8265 std::vector<double> nomVals;
8266 if (asymHi || asymLo) {
8267 nomVals.resize(nBins);
8268 for (size_t k = 0; k < nBins; k++) {
8269 setBin(bins[k]);
8270 nomVals[k] = f.getVal(nset);
8271 }
8272 }
8273
8274 // F[k] holds, for bin k, the vector of (signed) variations w.r.t. each
8275 // parameter - i.e. the column of the Jacobian times the parameter error.
8276 std::vector<TVectorD> F(nBins, TVectorD(nPars));
8277
8278 std::vector<double> plusVar(nBins), minusVar(nBins);
8279
8280 double ERROR_FACTOR = 1.;
8281 for (size_t ivar = 0; ivar < nPars; ivar++) {
8282
8283 auto &rrv = static_cast<RooRealVar &>((*_pars)[ivar]);
8284 auto *frrrv = static_cast<RooRealVar *>(fr.floatParsFinal().find(rrv));
8285
8286 double cenVal = rrv.getVal();
8287 ERROR_FACTOR = 1;//(1e-2)*std::max(1.,std::abs(cenVal));
8288
8289 if (asymHi || asymLo) {
8290 double errValHi = frrrv->getErrorHi();
8291 rrv.setVal(errValHi > 0 ? std::min(cenVal + errValHi*ERROR_FACTOR, rrv.getMax())
8292 : std::max(cenVal + errValHi*ERROR_FACTOR, rrv.getMin()));
8293 for (size_t k = 0; k < nBins; k++) {
8294 setBin(bins[k]);
8295 plusVar[k] = f.getVal(nset);
8296 }
8297 double errValLo = frrrv->getErrorLo();
8298 rrv.setVal(errValLo > 0 ? std::min(cenVal + errValLo*ERROR_FACTOR, rrv.getMax())
8299 : std::max(cenVal + errValLo*ERROR_FACTOR, rrv.getMin()));
8300 for (size_t k = 0; k < nBins; k++) {
8301 setBin(bins[k]);
8302 minusVar[k] = f.getVal(nset);
8303 }
8304 rrv.setVal(cenVal);
8305 for (size_t k = 0; k < nBins; k++) {
8306 double hi = plusVar[k];
8307 double lo = minusVar[k];
8308 if (asymHi) {
8309 // pick the one that moved result 'up' most
8310 hi = std::max(plusVar[k], minusVar[k]);
8311 lo = 2 * nomVals[k] - hi; // symmetrizes
8312 } else {
8313 // pick the one that moved result 'down' most
8314 lo = std::min(plusVar[k], minusVar[k]);
8315 hi = 2 * nomVals[k] - lo; // symmetrizes
8316 }
8317 F[k][ivar] = (hi - lo) * 0.5 / ERROR_FACTOR;
8318 }
8319 } else {
8320 double errVal = sqrt(V(ivar, ivar));//frrrv->getError(); //sqrt(V(ivar, ivar));
8321 // Make Plus variation
8322 rrv.setVal(std::min(cenVal + errVal*ERROR_FACTOR, rrv.getMax()));
8323 for (size_t k = 0; k < nBins; k++) {
8324 setBin(bins[k]);
8325 plusVar[k] = f.getVal(nset);
8326 }
8327 // Make Minus variation
8328 rrv.setVal(std::max(cenVal - errVal*ERROR_FACTOR, rrv.getMin()));
8329 for (size_t k = 0; k < nBins; k++) {
8330 setBin(bins[k]);
8331 minusVar[k] = f.getVal(nset);
8332 }
8333 rrv.setVal(cenVal);
8334 for (size_t k = 0; k < nBins; k++) {
8335 F[k][ivar] = (plusVar[k] - minusVar[k]) * 0.5 / ERROR_FACTOR;
8336 }
8337 }
8338 }
8339
8340 // Re-evaluate f with the central parameters just to be extra-safe that this
8341 // call doesn't leave any state changed. It should not be necessary because
8342 // thanks to the dirty flag propagation f is re-evaluated anyway the next
8343 // time getVal() is called, but there are imaginable corner cases where that
8344 // would not be triggered (e.g. if the caller changes the RooFit operation
8345 // mode after the error propagation).
8346 setBin(bins[nBins - 1]);
8347 f.getVal(nset);
8348
8349 // Calculate error in linear approximation from variations and correlation
8350 // coefficients - this is pure arithmetic (no function evaluations).
8351 for (size_t k = 0; k < nBins; k++) {
8352 out[k] = std::sqrt(F[k] * (C * F[k]));
8353 }
8354
8355 if (!pars) {
8356 delete _pars;
8357 } else {
8358 *pars = _pars;
8359 }
8360
8361 return out;
8362}
8363
8364class PdfWrapper : public RooAbsPdf {
8365public:
8366 // need expPdf option while RooProjectedPdf doesn't support keeping things extended
8367 PdfWrapper(RooAbsReal &f, RooAbsReal *coef, bool expEvMode = false, RooAbsPdf *expPdf = nullptr)
8368 : RooAbsPdf(Form("exp_%s", f.GetName())),
8369 fFunc("func", "func", this, f),
8370 fCoef("coef", "coef", this),
8371 fExpPdf("expPdf", "expPdf", this)
8372 {
8373 // don't treat pdf as extended if it has a coefficient and is RooAddPdf: RooAddPdf doesn't extend them unless no
8374 // coefs for any (and all are extendable)
8375 if (coef) {
8376 fCoef.setArg(*coef);
8377 }
8378 if (expPdf && expPdf->canBeExtended() && !(coef && dynamic_cast<RooAddPdf *>(expPdf))) {
8379 fExpPdf.setArg(*expPdf);
8380 } else if (auto _p = dynamic_cast<RooAbsPdf *>(&f);
8381 _p && _p->canBeExtended() && !(coef && dynamic_cast<RooAddPdf *>(_p))) {
8382 fExpPdf.setArg(f); // using self for expectation
8383 }
8384 fExpectedEventsMode = expEvMode;
8385 }
8386 ~PdfWrapper() override {};
8387 PdfWrapper(const PdfWrapper &other, const char *name = nullptr)
8388 : RooAbsPdf(other, name),
8389 fFunc("func", this, other.fFunc),
8390 fCoef("coef", this, other.fCoef),
8391 fExpPdf("expPdf", this, other.fExpPdf),
8392 fExpectedEventsMode(other.fExpectedEventsMode)
8393 {
8394 }
8395 TObject *clone(const char *newname) const override { return new PdfWrapper(*this, newname); }
8396 bool isBinnedDistribution(const RooArgSet &obs) const override { return fFunc->isBinnedDistribution(obs); }
8397 std::list<double> *binBoundaries(RooAbsRealLValue &obs, double xlo, double xhi) const override
8398 {
8399 return fFunc->binBoundaries(obs, xlo, xhi);
8400 }
8401
8402 double evaluate() const override
8403 {
8404 return (fExpectedEventsMode ? 1. : fFunc) *
8405 ((fExpPdf.absArg()) ? static_cast<RooAbsPdf *>(fExpPdf.absArg())->expectedEvents(_normSet) : 1.) *
8406 (fCoef.absArg() ? fCoef : 1.);
8407 }
8408
8409 bool selfNormalized() const override
8410 {
8411 return true;
8412 } // so that doesn't try to do an integral because we are passing integration onto fFunc in evaluate
8413
8414 // faster than full evaluation because doesnt make the integral dependent on the full expression
8415 double getSimplePropagatedError(const RooFitResult &fr, const RooArgSet &nset_in) const
8416 {
8417#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 28, 00)
8418 double oo = getPropagatedError(fr, nset_in); // method was improved in 6.28 so use this instead
8419 if (std::isnan(oo)) {
8420 // may be consequence of zero uncerts
8421 // Calling getParameters() might be costly, but necessary to get the right
8422 // parameters in the RooAbsReal. The RooFitResult only stores snapshots.
8423 RooArgSet allParamsInAbsReal;
8424 getParameters(&nset_in, allParamsInAbsReal);
8425
8426 RooArgList paramList;
8427 for (auto *rrvFitRes : static_range_cast<RooRealVar *>(fr.floatParsFinal())) {
8428
8429 auto rrvInAbsReal = static_cast<RooRealVar const *>(allParamsInAbsReal.find(*rrvFitRes));
8430
8431 // If this RooAbsReal is a RooRealVar in the fit result, we don't need to
8432 // propagate anything and can just return the error in the fit result
8433 if (rrvFitRes->namePtr() == namePtr())
8434 return rrvFitRes->getError();
8435
8436 // Strip out parameters with zero error
8437 if (!rrvFitRes->hasError() ||
8438 rrvFitRes->getError() <= std::abs(rrvFitRes->getVal()) * std::numeric_limits<double>::epsilon())
8439 continue;
8440
8441 // Ignore parameters in the fit result that this RooAbsReal doesn't depend on
8442 if (!rrvInAbsReal)
8443 continue;
8444
8445 // Checking for float equality is a bad. We check if the values are
8446 // negligibly far away from each other, relative to the uncertainty.
8447 if (std::abs(rrvInAbsReal->getVal() - rrvFitRes->getVal()) > 0.01 * rrvFitRes->getError()) {
8448 std::stringstream errMsg;
8449 errMsg
8450 << "RooAbsReal::getPropagatedError(): the parameters of the RooAbsReal don't have"
8451 << " the same values as in the fit result! The logic of getPropagatedError is broken in this case.";
8452
8453 throw std::runtime_error(errMsg.str());
8454 }
8455
8456 paramList.add(*rrvInAbsReal);
8457 }
8458 if (paramList.empty())
8459 return 0.;
8460
8461 std::vector<double> plusVar;
8462 std::vector<double> minusVar;
8463 plusVar.reserve(paramList.size());
8464 minusVar.reserve(paramList.size());
8465
8466 // Create std::vector of plus,minus variations for each parameter
8467 TMatrixDSym V(paramList.size() == fr.floatParsFinal().size() ? fr.covarianceMatrix()
8468 : fr.reducedCovarianceMatrix(paramList));
8469
8470 for (std::size_t ivar = 0; ivar < paramList.size(); ivar++) {
8471
8472 auto &rrv = static_cast<RooRealVar &>(paramList[ivar]);
8473
8474 double cenVal = rrv.getVal();
8475 double errVal = sqrt(V(ivar, ivar));
8476
8477 // this next thing happens if the par has errors but the covariance matrix is empty
8478 // this only happens if the fit was dodgy, so perhaps best to not even try to recover from this
8479 // screwup ... hence I've commented out this fixup here and will let the errors be nan
8480 // if(errVal==0) {
8481 // Warning("getPropagatedError","Missing variance for %s",rrv.GetName());
8482 // errVal = rrv.getError();
8483 // V(ivar,ivar) = errVal*errVal;
8484 // }
8485
8486 // Make Plus variation
8487 rrv.setVal(cenVal + errVal);
8488 plusVar.push_back(getVal(nset_in));
8489
8490 // Make Minus variation
8491 rrv.setVal(cenVal - errVal);
8492 minusVar.push_back(getVal(nset_in));
8493#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
8494 // can try to recover nans ... this stopped being possible in 6.27 onwards because NaNPacker made private
8495 if (std::isnan(plusVar.back()) && RooNaNPacker::isNaNWithPayload(plusVar.back())) {
8496 plusVar.back() = -RooNaNPacker::unpackNaN(plusVar.back());
8497 }
8498 if (std::isnan(minusVar.back()) && RooNaNPacker::isNaNWithPayload(minusVar.back())) {
8499 minusVar.back() = -RooNaNPacker::unpackNaN(minusVar.back());
8500 }
8501#endif
8502 // std::cout << plusVar.back() << " and " << minusVar.back() << std::endl;
8503
8504 rrv.setVal(cenVal);
8505 }
8506
8507 // Re-evaluate this RooAbsReal with the central parameters just to be
8508 // extra-safe that a call to `getPropagatedError()` doesn't change any state.
8509 // It should not be necessary because thanks to the dirty flag propagation
8510 // the RooAbsReal is re-evaluated anyway the next time getVal() is called.
8511 // Still there are imaginable corner cases where it would not be triggered,
8512 // for example if the user changes the RooFit operation more after the error
8513 // propagation.
8514 getVal(nset_in);
8515
8516 TMatrixDSym C(paramList.size());
8517 std::vector<double> errVec(paramList.size());
8518 for (std::size_t i = 0; i < paramList.size(); i++) {
8519 errVec[i] = std::sqrt(V(i, i));
8520 for (std::size_t j = i; j < paramList.size(); j++) {
8521 C(i, j) = V(i, j) / std::sqrt(V(i, i) * V(j, j));
8522 C(j, i) = C(i, j);
8523 }
8524 }
8525
8526 // Make std::vector of variations
8527 TVectorD F(plusVar.size());
8528 for (unsigned int j = 0; j < plusVar.size(); j++) {
8529 F[j] = (plusVar[j] - minusVar[j]) / 2;
8530 }
8531
8532 // Calculate error in linear approximation from variations and correlation coefficient
8533 double sum = F * (C * F);
8534
8535 return sqrt(sum);
8536 }
8537 return oo;
8538#else
8539
8540 // Strip out parameters with zero error
8541 RooArgList fpf_stripped;
8542 for (auto *frv : static_range_cast<RooRealVar *>(fr.floatParsFinal())) {
8543 if (frv->getError() > 1e-20) {
8544 fpf_stripped.add(*frv);
8545 }
8546 }
8547
8548 // Clone self for internal use
8549 RooAbsReal *cloneFunc = const_cast<PdfWrapper *>(this); // (RooAbsReal *)fFunc.absArg()->cloneTree();
8550 // RooAbsPdf *clonePdf = dynamic_cast<RooAbsPdf *>(cloneFunc);
8551 RooArgSet *errorParams = cloneFunc->getObservables(fpf_stripped);
8552
8553 RooArgSet *nset =
8554 nset_in.size() == 0 ? cloneFunc->getParameters(*errorParams) : cloneFunc->getObservables(nset_in);
8555
8556 // Make list of parameter instances of cloneFunc in order of error matrix
8557 RooArgList paramList;
8558 const RooArgList &fpf = fpf_stripped;
8559 std::vector<int> fpf_idx;
8560 for (Int_t i = 0; i < fpf.size(); i++) {
8561 RooAbsArg *par = errorParams->find(fpf[i].GetName());
8562 if (par) {
8563 paramList.add(*par);
8564 fpf_idx.push_back(i);
8565 }
8566 }
8567
8568 std::vector<double> plusVar, minusVar;
8569
8570 // Create vector of plus,minus variations for each parameter
8571 TMatrixDSym V(paramList.size() == fr.floatParsFinal().size() ? fr.covarianceMatrix()
8572 : fr.reducedCovarianceMatrix(paramList));
8573
8574 for (Int_t ivar = 0; ivar < paramList.size(); ivar++) {
8575
8576 RooRealVar &rrv = (RooRealVar &)fpf[fpf_idx[ivar]];
8577
8578 double cenVal = rrv.getVal();
8579 double errVal = sqrt(V(ivar, ivar));
8580
8581 // Make Plus variation
8582 ((RooRealVar *)paramList.at(ivar))->setVal(cenVal + errVal);
8583 // plusVar.push_back((fExpectedEventsMode ? 1. : cloneFunc->getVal(nset)) *
8584 // (clonePdf ? clonePdf->expectedEvents(nset) : 1.));
8585 plusVar.push_back(cloneFunc->getVal(nset));
8586
8587 // Make Minus variation
8588 ((RooRealVar *)paramList.at(ivar))->setVal(cenVal - errVal);
8589 // minusVar.push_back((fExpectedEventsMode ? 1. : cloneFunc->getVal(nset)) *
8590 // (clonePdf ? clonePdf->expectedEvents(nset) : 1.));
8591 minusVar.push_back(cloneFunc->getVal(nset));
8592
8593 ((RooRealVar *)paramList.at(ivar))->setVal(cenVal);
8594 }
8595
8596 getVal(nset); // reset state
8597
8598 TMatrixDSym C(paramList.size());
8599 std::vector<double> errVec(paramList.size());
8600 for (int i = 0; i < paramList.size(); i++) {
8601 errVec[i] = sqrt(V(i, i));
8602 for (int j = i; j < paramList.size(); j++) {
8603 C(i, j) = V(i, j) / sqrt(V(i, i) * V(j, j));
8604 C(j, i) = C(i, j);
8605 }
8606 }
8607
8608 // Make vector of variations
8609 TVectorD F(plusVar.size());
8610 for (unsigned int j = 0; j < plusVar.size(); j++) {
8611 F[j] = (plusVar[j] - minusVar[j]) / 2;
8612 }
8613
8614 // Calculate error in linear approximation from variations and correlation coefficient
8615 double sum = F * (C * F);
8616
8617 // delete cloneFunc;
8618 delete errorParams;
8619 delete nset;
8620
8621 return sqrt(sum);
8622#endif
8623 }
8624
8625private:
8629 bool fExpectedEventsMode = false;
8630};
8631
8632const xRooNode *runningNode = nullptr;
8634
8636{
8637 std::cout << "Got signal " << signum << std::endl;
8638 if (signum == SIGINT) {
8639 std::cout << "Keyboard interrupt while building histogram" << std::endl;
8640 // TODO: create a global mutex for this
8641 runningNode->fInterrupted = true;
8642 } else {
8643 gOldHandlerr(signum);
8644 }
8645}
8646
8648{
8649 auto _doSterilize = [](RooAbsArg *obj) {
8650 if (!obj)
8651 return;
8652 for (int i = 0; i < obj->numCaches(); i++) {
8653 if (auto cache = dynamic_cast<RooObjCacheManager *>(obj->getCache(i))) {
8654 cache->reset();
8655 }
8656 }
8657 if (RooAbsPdf *p = dynamic_cast<RooAbsPdf *>(obj); p) {
8658 p->setNormRange(p->normRange());
8659 }
8660#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
8661 if (RooAbsReal *p = dynamic_cast<RooAbsReal *>(obj); p) {
8662 // need to forget about any normSet that was passed to getVal(...)
8663 // doesn't seem necessary in 6.28
8664
8665 p->setProxyNormSet(nullptr);
8666 p->_lastNSet = nullptr;
8667 }
8668#endif
8669 obj->setValueDirty();
8670 };
8671 if (auto w = get<RooWorkspace>(); w) {
8672 // sterilizing all nodes
8673 for (auto &c : w->components()) {
8674 _doSterilize(c);
8675 }
8676 return;
8677 }
8678 // recursive through all clients and sterlize their normalization caches
8679 std::function<void(RooAbsArg *)> func;
8680 func = [&](RooAbsArg *a) {
8681 if (!a) {
8682 return;
8683 }
8684 _doSterilize(a); // sterilize first so that cache elements don't appear in the client list
8685 // safety net in case sterilizing one client deletes another one of our clients
8686 // monitor for change in clients list size
8687 // found this was only case in 6.26 (valgrind shows invalid read), in 6.28 these went away
8688 // might be in 6.28 the client list iterator became able to handle in-loop edits but didn't see
8689 // in test case that client count changed so just resterilizing if that's the case.
8690 size_t nClients;
8691 do {
8692 nClients = a->clients().size();
8693 for (auto obj : a->clients()) {
8694 func(dynamic_cast<RooAbsArg *>(obj));
8695 if (a->clients().size() != nClients) {
8696 break; // means sterilizing a client changed our clients, so don't trust the client iterator at this
8697 // point
8698 }
8699 }
8700 } while (a->clients().size() != nClients);
8701 };
8702 func(get<RooAbsArg>());
8703}
8704
8705// observables not in the axisVars are automatically projected over
8706xRooNode xRooNode::histo(const xRooNode &vars, const xRooNode &fr, bool content, bool errors, bool stack, bool errorsHi,
8707 bool errorsLo, int nErrorToys) const
8708{
8709
8710 if (!vars.fComp && strlen(vars.GetName())) {
8711 return histo(xRooNode::vars().reduced(vars.GetName()), fr, content, errors,stack,errorsHi,errorsLo,nErrorToys);
8712 }
8713
8714 xRooNode out(TString::Format("%s.histo", GetName()), nullptr, *this);
8715
8716 RooAbsLValue *v = nullptr;
8717 if (vars.empty()) {
8718 // does an integral
8719 out.fComp = std::shared_ptr<TH1>(
8720 BuildHistogram(nullptr, !content, errors, -1, -1, fr, errorsHi, errorsLo, nErrorToys, nullptr, !stack, false));
8721 } else if (vars.size() == 1) {
8722 v = vars.at(0)->get<RooAbsLValue>();
8723 out.fComp = std::shared_ptr<TH1>(
8724 BuildHistogram(v, !content, errors, 1, 0, fr, errorsHi, errorsLo, nErrorToys, nullptr, !stack, true));
8725 } else {
8726 throw std::runtime_error("multi-dim histo not yet supported");
8727 }
8728
8729 return out;
8730}
8731
8733{
8734 return xRooNode(fComp, xRooNode(range.GetName(), nullptr, *this));
8735}
8736
8737TH1 *xRooNode::BuildHistogram(RooAbsLValue *v, bool empty, bool errors, int binStart, int binEnd, const xRooNode &_fr,
8738 bool errorsHi, bool errorsLo, int nErrorToys, TH1 *templateHist, bool nostack,
8739 bool setInterp) const
8740{
8741 auto rar = get<RooAbsReal>();
8742 if (!rar) {
8743 if (get<TH1>()) {
8744 return dynamic_cast<TH1 *>(get()->Clone());
8745 }
8746 return nullptr;
8747 }
8748
8749 TObject *vv = rar;
8750
8751 TH1 *h = nullptr;
8752 if (!v) {
8753 if (binStart != -1 || binEnd != -1) { // allow v to stay nullptr if doing integral (binStart=binEnd=-1)
8754 if (auto _ax = GetXaxis())
8755 v = dynamic_cast<RooAbsLValue *>(_ax->GetParent());
8756 } else {
8757 // don't need to integrate if doing a self-histogram
8758 v = dynamic_cast<RooRealVar *>(rar);
8759 }
8760 if (v) {
8761 vv = dynamic_cast<TObject *>(v);
8762 } else {
8763 // make a single-bin histogram of just this value
8764 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8765 h = new TH1D(rar->GetName(), rar->GetTitle(), 1, 0, 1);
8766 h->GetXaxis()->SetBinLabel(1, rar->GetName());
8767 h->GetXaxis()->SetTimeFormat(rar->GetName());
8768 }
8769 }
8770
8771 auto x = dynamic_cast<RooRealVar *>(v);
8772 bool setTitle = false;
8773 if (templateHist) {
8774 // using template hist for the binning
8775 {
8776 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8777 h = static_cast<TH1 *>(templateHist->Clone(rar->GetName()));
8778 }
8779 h->SetTitle(rar->GetTitle());
8780 h->Reset();
8781 } else if (x) {
8782 if (x == rar) {
8783 // self histogram ...
8784 {
8785 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8786 h = new TH1D(rar->GetName(), rar->GetTitle(), 1, 0, 1);
8787 }
8788 h->Sumw2();
8789 h->GetXaxis()->SetBinLabel(1, rar->GetName());
8790 h->SetBinContent(1, rar->getVal());
8791 if (x->getError()) {
8792 h->SetBinError(1, x->getError());
8793 h->SetFillStyle(3005);
8794 h->SetFillColor(h->GetLineColor());
8795 }
8796 h->SetMaximum(x->hasMax() ? x->getMax()
8797 : (h->GetBinContent(1) + std::max(std::abs(h->GetBinContent(1) * 0.1), 50.)));
8798 h->SetMinimum(x->hasMin() ? x->getMin()
8799 : (h->GetBinContent(1) - std::max(std::abs(h->GetBinContent(1) * 0.1), 50.)));
8800 h->GetXaxis()->SetName(dynamic_cast<TObject *>(v)->GetName());
8801 h->SetOption("e2");
8802 h->SetMarkerSize(0);
8803 h->SetMarkerStyle(0);
8804
8805 return h;
8806 }
8807 auto _ax = GetXaxis();
8808 TString binningName = (_ax && _ax->GetParent() == x) ? _ax->GetName() : rar->getStringAttribute("binning");
8809 if (binningName == "")
8810 binningName = rar->GetName();
8811 if (x->hasBinning(binningName)) {
8812 if (x->getBinning(binningName).isUniform()) {
8813 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8814 h = new TH1D(rar->GetName(), rar->GetTitle(), x->numBins(binningName) <= 0 ? 100 : x->numBins(binningName),
8815 x->getMin(binningName), x->getMax(binningName));
8816 } else {
8817 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8818 h = new TH1D(rar->GetName(), rar->GetTitle(), x->numBins(binningName), x->getBinning(binningName).array());
8819 }
8820 h->GetXaxis()->SetTitle(x->getBinning(binningName).GetTitle());
8821 setTitle = true;
8822 } else if (auto _boundaries =
8823 _or_func(/*rar->plotSamplingHint(*x,x->getMin(),x->getMax())*/ (std::list<double> *)(nullptr),
8824 rar->binBoundaries(*x, -std::numeric_limits<double>::infinity(),
8825 std::numeric_limits<double>::infinity()));
8826 _boundaries) {
8827 std::vector<double> _bins;
8828 for (auto &b : *_boundaries) {
8829 if (_bins.empty() || std::abs(_bins.back() - b) > 1e-5 * _bins.back())
8830 _bins.push_back(b);
8831 } // found sometimes get virtual duplicates in the binning
8832 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8833 h = new TH1D(rar->GetName(), rar->GetTitle(), _bins.size() - 1, &_bins[0]);
8834 delete _boundaries;
8835 } else if (!x->hasMax() || !x->hasMin()) {
8836 // use current value of x to estimate range with
8837 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8838 h = new TH1D(rar->GetName(), rar->GetTitle(), v->numBins(), x->getVal() * 0.2, x->getVal() * 5);
8839 } else {
8840 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8841 h = new TH1D(rar->GetName(), rar->GetTitle(), v->numBins(), x->getBinning().array());
8842 }
8843 h->Sumw2();
8844 } else if (!h) {
8845 {
8846 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
8847 h = new TH1D(rar->GetName(), rar->GetTitle(), v->numBins(rar->GetName()), 0, v->numBins(rar->GetName()));
8848 }
8849 if (auto cat = dynamic_cast<RooAbsCategoryLValue *>(v)) {
8850 int i = 1;
8851 std::map<int, std::string> cats; // fill into a map to preserve index ordering
8852 for (auto &c : *cat) {
8853 cats[c.second] = c.first;
8854 }
8855 for (auto &[_, label] : cats) {
8856 h->GetXaxis()->SetBinLabel(i++, label.c_str());
8857 }
8858 }
8859 h->Sumw2();
8860 }
8861 if (auto o = dynamic_cast<TObject *>(v); o && !setTitle) {
8862 h->GetXaxis()->SetTitle(o->GetTitle());
8863 }
8864
8865 if (v) {
8866 if (h->GetXaxis()->IsAlphanumeric()) {
8867 // store the variable name in the TimeFormat property as well, b.c. alphanumeric requires axis name to be
8868 // "xaxis"
8869 h->GetXaxis()->SetTimeFormat(dynamic_cast<TObject *>(v)->GetName());
8870 } else {
8871 h->GetXaxis()->SetName(dynamic_cast<TObject *>(v)->GetName()); // WARNING: messes up display of bin labels
8872 }
8873 }
8874
8875 if (auto s = styles(nullptr, false); s) {
8876 auto _style = s.get<TStyle>();
8877 static_cast<TAttLine &>(*h) = *_style;
8878 static_cast<TAttFill &>(*h) = *_style;
8879 static_cast<TAttMarker &>(*h) = *_style;
8880 }
8881 if (strlen(h->GetXaxis()->GetTitle()) == 0)
8882 h->GetXaxis()->SetTitle(vv->GetTitle());
8883 auto p = dynamic_cast<RooAbsPdf *>(rar);
8884
8885 // possible speed improvement:
8886 // if(auto spdf = dynamic_cast<RooRealSumPdf*>(p); spdf && spdf->canBeExtended()) {
8887 // p = nullptr; // faster to evaluate sumpdf as a function not a pdf
8888 // }
8889
8890 if (empty && !errors) {
8891 return h;
8892 }
8893
8894 // if (!empty) {
8895
8896 auto _coefs = coefs();
8897
8898 RooFitResult *fr = nullptr;
8899 if (errors) {
8900 // must ensure the fit result we obtain includes pars from coefficients if present
8901 if (_fr.get<RooFitResult>()) {
8902 fr = static_cast<RooFitResult *>(_fr.get<RooFitResult>()->Clone());
8903 } else {
8904 auto frn =
8905 (!_coefs.get() ? *this : xRooNode(RooProduct("tmp", "tmp", RooArgList(*rar, *_coefs.get<RooAbsReal>()))))
8906 .fitResult();
8907 if (strlen(_fr.GetName()))
8908 frn = frn.reduced(_fr.GetName());
8909 fr = dynamic_cast<RooFitResult *>(frn->Clone());
8910 }
8911 if (!GETDMP(fr, _finalPars)) {
8913 }
8914
8915 /// Oct2022: No longer doing this because want to allow fitResult to be used to get partial error
8916 // // need to add any floating parameters not included somewhere already in the fit result ...
8917 // now done in the fitResult() method, where a fit result from the workspace can be automatically extended
8918
8919 TMatrixTSym<double> *prevCov = static_cast<TMatrixTSym<double> *>(GETDMP(fr, _VM));
8920
8921 if (!prevCov || size_t(fr->covarianceMatrix().GetNcols()) < fr->floatParsFinal().size()) {
8922 TMatrixDSym cov(fr->floatParsFinal().size());
8923 if (prevCov) {
8924 for (int i = 0; i < prevCov->GetNcols(); i++) {
8925 for (int j = 0; j < prevCov->GetNrows(); j++) {
8926 cov(i, j) = (*prevCov)(i, j);
8927 }
8928 }
8929 }
8930 int i = 0;
8931 for (auto &p2 : fr->floatParsFinal()) {
8932 if (!prevCov || i >= prevCov->GetNcols()) {
8933 cov(i, i) = pow(dynamic_cast<RooRealVar *>(p2)->getError(), 2);
8934 }
8935 i++;
8936 }
8937 int covQualBackup = fr->covQual();
8938 fr->setCovarianceMatrix(cov);
8939 fr->setCovQual(covQualBackup);
8940 }
8941
8942 if (v) {
8943 // need to remove v from result as we are plotting as function of v
8944 if (auto _p = fr->floatParsFinal().find(dynamic_cast<TObject *>(v)->GetName()); _p) {
8945 RooArgList _pars = fr->floatParsFinal();
8946 _pars.remove(*_p, true);
8947 auto _tmp = fr->reducedCovarianceMatrix(_pars);
8948 int covQualBackup = fr->covQual();
8949 fr->setCovarianceMatrix(_tmp);
8950 fr->setCovQual(covQualBackup);
8951 const_cast<RooArgList &>(fr->floatParsFinal())
8952 .remove(*_p, true); // NOTE: I think this might be a memory leak, should delete _p after removal
8953 }
8954 }
8955 // finally check at least one float has errors defined (might not be cause if in prefit state)
8956 bool hasErrors = false;
8957 for (auto pp : fr->floatParsFinal()) {
8958 if (dynamic_cast<RooRealVar *>(pp)->hasError()) {
8959 hasErrors = true;
8960 break;
8961 }
8962 }
8963 if (!hasErrors) {
8964 errors = false;
8965 delete fr;
8966 }
8967 }
8968
8969 RooArgSet normSet;
8970 if (v)
8971 normSet.add(*dynamic_cast<RooAbsArg *>(v));
8972
8973 if (binEnd == 0)
8974 binEnd = h->GetNbinsX();
8975
8976 bool needBinWidth = false;
8977 // may have MULTIPLE coefficients for the same pdf!
8978
8979 if (x && (p || _coefs.get() || rar->getAttribute("density"))) {
8980 // pdfs of samples embedded in a sumpdf (aka have a coef) will convert their density value to a content
8981 needBinWidth = true;
8982 }
8983
8984 if (auto spdf = dynamic_cast<RooRealSumPdf *>(p);
8985 spdf && spdf->canBeExtended() && !spdf->getFloor() && !_coefs.get()) {
8986 p = nullptr; // if pdf has no floor, will evaluate it as a function to allow it to be negative - evaluation should
8987 // also be faster (no integral)
8988 // exception is if RooRealSumPdf is embedded in a RooAddPdf (detected by presence of coefs) ... then it must be
8989 // evaluated as a pdf technically should check parent is a RooAddPdf, because if was inside a RooRealSumPdf then
8990 // would be evaluated as a function!
8991 }
8992
8993 // check if we need to do any projecting of other observables
8994 RooAbsReal *oldrar = nullptr;
8995 auto _obs = obs();
8996
8997 for (auto o : _obs) {
8998 if (auto rr = o->get<RooRealVar>(); rr && rr->hasRange("coordRange")) {
8999 rr->removeMin();
9000 rr->removeMax(); // rr->removeRange("coordRange"); // doesn't actually remove, just sets to
9001 // -inf->+inf
9002 rr->setStringAttribute("coordRange", nullptr); // removes the attribute
9003 }
9004 }
9005 // probably should also remove any range on the x-axis variable too, if there is one
9006 if (auto rr = dynamic_cast<RooRealVar *>(v); rr && rr->hasRange("coordRange")) {
9007 rr->removeMin();
9008 rr->removeMax(); // rr->removeRange("coordRange"); // doesn't actually remove, just sets to
9009 // -inf->+inf
9010 rr->setStringAttribute("coordRange", nullptr); // removes the attribute
9011 }
9012 coords(); // loads current coordinates and populates coordRange, if any
9013
9014 if (auto a = dynamic_cast<RooAbsArg *>(v))
9015 _obs.get<RooArgList>()->remove(*a);
9016 if (!_obs.get<RooArgList>()->empty()) {
9017 oldrar = rar;
9018 normSet.add(*_obs.get<RooArgList>());
9019 // check if any obs are restricted range
9020 bool hasRange = false;
9021 for (auto o : normSet) {
9022 if (auto rr = dynamic_cast<RooRealVar *>(o);
9023 rr && (rr->getStringAttribute("coordRange")) && strlen(rr->getStringAttribute("coordRange"))) {
9024 hasRange = true;
9025 break;
9026 }
9027 }
9028 if (p) {
9029 // need to handle special case of RooSimultaneous ... each pdf needs individually projecting over just its
9030 // dependent obs
9031 if (auto s = dynamic_cast<RooSimultaneous *>(p)) {
9032 auto newrar = new RooSimultaneous("projSim", "projSim", const_cast<RooAbsCategoryLValue &>(s->indexCat()));
9033 for (auto pdf : bins()) {
9034 // auto _pdf =
9035 // pdf->get<RooAbsPdf>()->createProjection(*pdf->get<RooAbsPdf>()->getObservables(*_obs.get<RooArgList>()));
9036 std::unique_ptr<RooArgSet> projObs{pdf->get<RooAbsPdf>()->getObservables(*_obs.get<RooArgList>())};
9037 auto _pdf = new xRooProjectedPdf(TString::Format("%s_projection", pdf->GetName()), "",
9038 *pdf->get<RooAbsPdf>(), *projObs);
9039 if (hasRange) {
9040 dynamic_cast<RooAbsPdf *>(_pdf)->setNormRange("coordRange");
9041 }
9042 newrar->addPdf(*_pdf, pdf->coords()[s->indexCat().GetName()]->get<RooCategory>()->getLabel());
9043 }
9044 rar = newrar;
9045 } else {
9046 rar = p->createProjection(
9047 *_obs.get<RooArgList>()); // TODO should use xRooProjectedPdf here too, because not fixed range and
9048 // extend behaviour of RooProjectedPdf in ROOT yet
9049 if (hasRange) {
9050 dynamic_cast<RooAbsPdf *>(rar)->setNormRange("coordRange");
9051 }
9052 }
9053 if (hasRange)
9054 p->setNormRange("coordRange"); // should get cleared when we sterilize
9055 } else {
9056 if (hasRange) {
9057 // commented out passing of normset so that getVal of non-pdf is always a 'raw' value (needed for raw eval
9058 // of RooRealSumPdf)
9059 rar = std::unique_ptr<RooAbsReal>{rar->createIntegral(
9060 *_obs.get<RooArgList>(),
9061 /*RooFit::NormSet(normSet),*/ RooFit::Range("coordRange"))}
9062 .release();
9063 } else {
9064 rar =
9065 std::unique_ptr<RooAbsReal>{rar->createIntegral(*_obs.get<RooArgList>() /*, RooFit::NormSet(normSet)*/)}
9066 .release();
9067 }
9068 }
9069 }
9070
9071 bool scaleExpected = (p && p->canBeExtended() && !_coefs.get());
9072 // Note about above: if pdf has coefficients then its embedded in a RooAddPdf that has coefs defined ...
9073 // in this case we should *not* scale by expected, since the coefs become the scaling instead
9074 // we should also not build a stack for this (may be a RooRealSumPdf inside a RooAddPdf, but the
9075 // samples of the RooRealSumPdf wont be correctly scaled to line up with overall RooRealSumPdf
9076 // which will be normalized to its coefficient
9077 if (!nostack && p && p->canBeExtended() && _coefs.get()) {
9078 nostack = true;
9079 // if wanted to still hve a stack, would need to scale the stack subcomponents by
9080 // coefs-value / p_integral(raw) ... since raw p-integral will be what stack integrates to
9081 }
9082
9083 std::unique_ptr<RooArgSet> snap(normSet.snapshot());
9084 TStopwatch timeIt;
9085 std::vector<double> lapTimes;
9086 bool warned = false;
9087 if (binStart == -1 && binEnd == -1) {
9088 binEnd = 1;
9089 }
9090 auto cat = (!x) ? dynamic_cast<RooAbsCategoryLValue *>(v) : nullptr;
9091 RooArgList *errorPars = nullptr;
9092 std::unique_ptr<RooAbsCollection> errorParsSnap;
9093
9094 if (!v) {
9095 setInterp = false;
9096 }
9097
9098 if (setInterp) {
9099 RooAbsArg *vvv = dynamic_cast<RooAbsArg *>(v);
9100 // determining if histogram should have interpolation drawing options set on it
9101 // need to strip namespace to discount the "HistFactory" namespace classes from all being treated as binned
9102 TString clNameNoNamespace = rar->ClassName();
9103 clNameNoNamespace = clNameNoNamespace(clNameNoNamespace.Last(':') + 1, clNameNoNamespace.Length());
9104 setInterp = (clNameNoNamespace.Contains("Hist") || vvv->isCategory() || rar->isBinnedDistribution(*vvv) ||
9105 h->GetNbinsX() == 1 || rar->getAttribute("BinnedLikelihood") ||
9106 (dynamic_cast<RooAbsRealLValue *>(vvv) &&
9107 std::unique_ptr<std::list<double>>(rar->binBoundaries(*dynamic_cast<RooAbsRealLValue *>(vvv),
9108 -std::numeric_limits<double>::infinity(),
9109 std::numeric_limits<double>::infinity()))))
9110 ? false
9111 : true;
9112 if (auto d = dynamic_cast<RooHistFunc *>(rar); d && !d->isBinnedDistribution(*vvv) && h->GetNbinsX() != 1) {
9113 setInterp = true; // hist func is interpolated, so draw it as such
9114 }
9115 if (setInterp && !components().empty()) {
9116 // check if all components of dOpt are "Hist" type (CMS model support)
9117 // if so then don't interp;
9118 bool allHist = true;
9119 for (auto &s : components()) {
9120 TString _clName = s->get()->ClassName();
9121 _clName = _clName(_clName.Last(':') + 1, _clName.Length());
9122 if (!(s->get() && _clName.Contains("Hist"))) {
9123 allHist = false;
9124 break;
9125 }
9126 }
9127 if (allHist)
9128 setInterp = false;
9129 }
9130 if (setInterp) {
9131 h->SetOption("l"); // does linear interpolation between points
9132 }
9133 }
9134
9135 if (errors) {
9136 // may be computing potentially asymmetric errors
9137 // the main histogram will be the error band, and the nominal histogram will be added as a function
9138 // so that it is drawn over the top of the error band
9139 // note that this means GetBinContent on returned histogram will return midpoint of the up and down error
9140 auto l = static_cast<TH1 *>(h->Clone("nominal"));
9141 l->SetDirectory(0);
9142 l->SetFillStyle(0);
9143 h->GetListOfFunctions()->Add(l, (setInterp) ? "lsame" : "histsame");
9144 h->SetOption(setInterp ? "e3" : "e2"); // default draw option E2 or E3 so error band shown .. could have used
9145 // 'EX0' to draw "classic style"
9146 // could take this from the 'band' style object if we create one in future?
9147 h->SetMarkerSize(0);
9148 h->SetFillStyle(3005);
9149 h->SetFillColor(h->GetLineColor());
9150 }
9151
9152 if (nErrorToys > 0) {
9153 errors = false; // wont evaluate error on each toy, will estimate for std.dev or normiles of toys
9154 // need list of errorPars
9155 auto allPars =
9156 (!_coefs.get() ? *this : xRooNode(RooProduct("tmp", "tmp", RooArgList(*rar, *_coefs.get<RooAbsReal>()))))
9157 .pars();
9158 errorPars = new RooArgList; // will be in same order as appear in fr.
9159 for (auto a : fr->floatParsFinal()) {
9160 if (auto par = allPars.get<RooArgList>()->find(*a)) {
9161 errorPars->add(*par);
9162 }
9163 }
9164 errorParsSnap.reset(errorPars->snapshot());
9165 auto l = static_cast<TH1 *>(h->Clone("toys"));
9166 l->Reset(); // removes any functions
9167 l->SetDirectory(0);
9168 h->GetListOfFunctions()->Add(
9169 l, "histsame"); // ensures just this empty hist will be drawn, and not each individual toy
9170
9171 if (errorsLo || errorsHi)
9172 empty = false; // must not be empty b.c. calculation of error relies on knowing nominal (see after loop)
9173 }
9174
9175 std::vector<int> errorBins; // bins (in-range) for which to compute the propagated error band, filled below
9176 for (int toy = 0; toy < (nErrorToys + 1); toy++) {
9177
9178 TH1 *main_h = h;
9179 if (toy > 0) {
9180 h = static_cast<TH1 *>(main_h->Clone(TString::Format("toy_%d", toy)));
9181 h->SetDirectory(0);
9182 h->Reset();
9183 static_cast<TH1 *>(main_h->GetListOfFunctions()->FindObject("toys"))->GetListOfFunctions()->Add(h);
9184 // randomize the parameter values according to the fr's covariance matrix
9185 errorPars->assignValueOnly(fr->randomizePars());
9186 // if any par has 0 error, randomizePars can end up assigning a nan, so replace
9187 // all zero errors with value
9188 for (auto pp : fr->floatParsFinal()) {
9189 auto _vv = dynamic_cast<RooRealVar *>(pp);
9190 if (!_vv)
9191 continue;
9192 if (_vv->getError() == 0)
9193 errorPars->setRealValue(pp->GetName(), _vv->getVal());
9194 }
9195 }
9196
9197 for (int i = std::max(1, binStart); i <= std::min(h->GetNbinsX(), binEnd); i++) {
9198 timeIt.Start(true);
9199 if (x) {
9200 x->setVal(h->GetBinCenter(i));
9201 } else if (cat) {
9202 cat->setLabel(h->GetXaxis()->GetBinLabel(i)); // because order might not match "binning" order
9203 } else if (v) {
9204 v->setBin(i - 1);
9205 }
9206 if (x && !x->inRange("coordRange"))
9207 continue;
9208
9209 double r = 0;
9210 if (!empty || toy > 0) {
9211 r = /*(p && p->selfNormalized())*/ rar->getVal(p ? &normSet : nullptr);
9212#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
9213 if (std::isnan(r) && RooNaNPacker::isNaNWithPayload(r)) {
9215 }
9216#endif
9217 if (r && _coefs.get()) {
9218 r *= _coefs.get<RooAbsReal>()->getVal(normSet);
9219 }
9220 if (needBinWidth) {
9221 r *= h->GetBinWidth(i);
9222 }
9223 if (scaleExpected) {
9224 // std::cout << r << " exp = " << p->expectedEvents(normSet) << " for normRange " << (p->normRange() ?
9225 // p->normRange() : "null") << std::endl; p->Print();rar->Print();
9226 r *= (p->expectedEvents(normSet));
9227 } // do in here in case dependency on var
9228 }
9229 h->SetBinContent(i, r);
9230
9231 if (errors) {
9232 static_cast<TH1 *>(h->FindObject("nominal"))->SetBinContent(i, r); // transfer nominal to nominal hist
9233 // Record for which bins to compute the error later.
9234 if (toy == 0) {
9235 errorBins.push_back(i);
9236 }
9237 }
9238 timeIt.Stop();
9239 lapTimes.push_back(timeIt.RealTime());
9240 double time_estimate =
9241 (lapTimes.size() > 1)
9242 ? (h->GetNbinsX() * (std::accumulate(lapTimes.begin() + 1, lapTimes.end(), 0.) / (lapTimes.size() - 1)))
9243 : 0.;
9244 if (!warned && (lapTimes.at(0) > 10 || (lapTimes.size() > 2 && time_estimate > 60.))) {
9245 TTimeStamp t2;
9246 t2.Add(time_estimate);
9247 Warning("BuildHistogram", "Building this histogram will take until %s", t2.AsString());
9248 if (errors) {
9249 // install interrupt handler
9250 runningNode = this;
9251 gOldHandlerr = signal(SIGINT, buildHistogramInterrupt);
9252 }
9253 warned = true;
9254 }
9255 if (fInterrupted) {
9256 if (errors) {
9257 Warning("BuildHistogram", "Skipping errors for remaining bins");
9258 errors = false;
9259 }
9260 fInterrupted = false;
9261 }
9262 }
9263 if (toy > 0) {
9264 h = main_h;
9265 }
9266 }
9267
9268 if (errors && !errorBins.empty()) {
9269 // Batched linear error propagation over all (in-range) bins recorded above. By varying each parameter only
9270 // once and sweeping the observable inside that variation, the normalization / expected-events integrals are
9271 // reused across bins instead of being recomputed for every bin (see new_getPropagatedErrors).
9272 std::unique_ptr<RooAbsReal> errFunc;
9273 RooArgSet emptyNormSet;
9274 if (p) {
9275 errFunc =
9276 std::make_unique<PdfWrapper>((oldrar) ? *rar : *p, _coefs.get<RooAbsReal>(), !v, oldrar ? p : nullptr);
9277 } else {
9278 // especially important not to pass a normSet in the case we are evaluating a RooRealSumPdf as a function!
9279 // otherwise the error will be wrong
9280 errFunc = std::make_unique<RooProduct>(
9281 "errorEval", "errorEval",
9282 RooArgList(*rar, !_coefs.get() ? RooFit::RooConst(1) : *_coefs.get<RooAbsReal>()));
9283 }
9284 const RooArgSet &errNormSet = p ? normSet : emptyNormSet;
9285
9286 auto setBin = [&](int i) {
9287 if (x) {
9288 x->setVal(h->GetBinCenter(i));
9289 } else if (cat) {
9290 cat->setLabel(h->GetXaxis()->GetBinLabel(i));
9291 } else if (v) {
9292 v->setBin(i - 1);
9293 }
9294 };
9295
9296 bool doAsym = (errorsHi && errorsLo);
9297 // For asymmetric bands we need both the Lo and Hi propagated errors; otherwise a single (possibly one-sided)
9298 // pass. errorPars is reused across both passes so the parameter list is only built once.
9299 std::vector<double> errLo = new_getPropagatedErrors(
9300 *errFunc, *fr, errNormSet, &errorPars, doAsym ? false : errorsHi, doAsym ? true : errorsLo, errorBins, setBin);
9301 std::vector<double> errHi;
9302 if (doAsym) {
9303 errHi = new_getPropagatedErrors(*errFunc, *fr, errNormSet, &errorPars, true, false, errorBins, setBin);
9304 }
9305#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
9306 if (p) {
9307 // improved normSet invalidity checking, so assuming no longer need this in 6.28 onwards
9308 p->_normSet = nullptr;
9309 }
9310#endif
9311
9312 for (size_t k = 0; k < errorBins.size(); k++) {
9313 int i = errorBins[k];
9314 double resLo = errLo[k];
9315 if (needBinWidth)
9316 resLo *= h->GetBinWidth(i);
9317 h->SetBinError(i, resLo);
9318 if (doAsym) {
9319 double resHi = errHi[k];
9320 if (needBinWidth)
9321 resHi *= h->GetBinWidth(i);
9322 // lowVal = content - resLo, highVal = content + resHi
9323 // => band/2 = (resHi+resLo)/2 and band-mid = content + (resHi-resLo)/2
9324 h->SetBinContent(i, h->GetBinContent(i) + (resHi - resLo) * 0.5);
9325 h->SetBinError(i, (resHi + resLo) * 0.5);
9326 }
9327 }
9328 }
9329
9330 if (gOldHandlerr) {
9331 signal(SIGINT, gOldHandlerr);
9332 gOldHandlerr = nullptr;
9333 }
9334 normSet = *snap;
9335
9336 if (errorPars) {
9337 if (errorParsSnap)
9338 *errorPars = *errorParsSnap;
9339 delete errorPars;
9340 }
9341 if (nErrorToys) {
9342 // compute main histogram error bar from toys
9343 // if not doing asymmetric, then will display std.dev
9344 // otherwise will copy main to nominal and make main error bar s.t. it shows +/-1sigma vals
9345 if (errorsLo && errorsHi) {
9346 auto nomHist = static_cast<TH1 *>(h->FindObject("nominal"));
9347 nomHist->Add(h);
9348 }
9349 for (int i = 1; i <= h->GetNbinsX(); i++) {
9350 std::vector<double> vals;
9351 vals.reserve(nErrorToys);
9352 for (int j = 1; j < (nErrorToys + 1); j++) {
9353 vals.push_back(
9354 static_cast<TH1 *>(h->FindObject("toys")->FindObject(TString::Format("toy_%d", j)))->GetBinContent(i));
9355 }
9356 double upVal, downVal;
9357 if (errorsLo || errorsHi) {
9358 std::sort(vals.begin(), vals.end());
9359 upVal = vals.at(std::floor(vals.size() * ROOT::Math::gaussian_cdf(1)));
9360 downVal = vals.at(std::floor(vals.size() * ROOT::Math::gaussian_cdf(-1)));
9361 if (!errorsLo)
9362 downVal = 2. * h->GetBinContent(i) - upVal;
9363 if (!errorsHi)
9364 upVal = 2. * h->GetBinContent(i) - downVal;
9365 } else {
9366 double err = TMath::StdDev(vals.begin(), vals.end());
9367 upVal = h->GetBinContent(i) + err;
9368 downVal = h->GetBinContent(i) - err;
9369 }
9370 h->SetBinContent(i, (upVal + downVal) * 0.5);
9371 h->SetBinError(i, (upVal - downVal) * 0.5);
9372 }
9373 }
9374#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 41, 00)
9375 // We evaluated the above with `normSet`, which lives on this function's stack.
9376 // RooFit proxies only cache a bare pointer to the last normSet and re-use it
9377 // later (e.g. RooProduct::evaluate reads back _compRSet.nset()), so before it
9378 // goes out of scope we must clear it everywhere it could have been cached,
9379 // otherwise a later evaluation dereferences freed stack ("use of uninitialised
9380 // value" in valgrind). sterilize() only walks clients, but getVal() propagates
9381 // the normSet to the servers of the evaluated function, so reset those here.
9382 // setProxyNormSet made public in 6.41
9383
9384 {
9385 RooArgSet evaluatedNodes;
9386 for (RooAbsArg *treeRoot : {static_cast<RooAbsArg *>(rar), static_cast<RooAbsArg *>(p),
9387 static_cast<RooAbsArg *>(oldrar), _coefs.get<RooAbsArg>()}) {
9388 if (treeRoot)
9389 treeRoot->treeNodeServerList(&evaluatedNodes);
9390 }
9391 for (RooAbsArg *node : evaluatedNodes) {
9392 node->setProxyNormSet(nullptr);
9393 }
9394 }
9395#endif
9396 if (oldrar) {
9397 std::vector<RooAbsArg *> extra;
9398 if (auto s = dynamic_cast<RooSimultaneous *>(rar)) {
9399 // need to delete all the subpdfs we created too
9400 for (auto _pdf : s->servers()) {
9401 if (dynamic_cast<RooAbsPdf *>(_pdf))
9402 extra.push_back(_pdf);
9403 }
9404 }
9405 extra.push_back(rar);
9406 rar = oldrar;
9407 xRooNode(*rar).sterilize(); // need to clear the cache of the created integral - do this before deleting things!
9408 for (auto a : extra)
9409 delete a;
9410 } else {
9411 sterilize(); // needed to forget about the normSet that was passed to getVal()
9412 }
9413
9414 if (!p && !rar->getAttribute("density") && !needBinWidth) {
9415 h->GetYaxis()->SetTitle(rar->getStringAttribute("units"));
9416 } else if ((p && p->canBeExtended()) || (!p && needBinWidth)) {
9417 h->GetYaxis()->SetTitle("Events");
9418 } else {
9419 h->GetYaxis()->SetTitle("Probability Mass");
9420 }
9421 h->GetYaxis()->SetMaxDigits(3);
9422
9423 if (errors) {
9424 delete fr;
9425 }
9426
9427 // build a stack unless not requested
9428 if (!nostack) {
9429 // need to draw copy of hist so shown over the stack
9430 auto hCopy = static_cast<TH1 *>(h->Clone("copy"));
9431 hCopy->Reset();
9432 hCopy->Add(h); // use Reset and Add to clear the function list (dont clear directly as may double-delete if same
9433 // object added twice)
9434 hCopy->SetStats(false);
9435 h->GetListOfFunctions()->Add(hCopy, TString(h->GetOption()) + "same");
9436 h->GetListOfFunctions()->Add(hCopy, "axissame"); // prevents stack covering axis
9437 TString dOpt = (setInterp) ? "LF2" : ""; // should become lf2 if interpolation of histogram is appropriate
9438
9439 const xRooNode *rarNode = this;
9440 RooAbsReal *sf = nullptr;
9441 if (get()->InheritsFrom("RooExtendPdf")) {
9442 const_cast<xRooNode *>(this)->browse();
9443 rarNode = find(".pdf").get();
9444 // rar = rarNode->get<RooAbsReal>();
9445 sf = find(".n")->get<RooAbsReal>();
9446 }
9447
9448 THStack *stack = new THStack("stack", TString::Format("%s;%s", rar->GetTitle(), h->GetXaxis()->GetTitle()));
9449 int count = 0;
9450 std::map<std::string, int> colorByTitle; // TODO: should fill from any existing legend
9451 std::set<std::string> allTitles;
9452 bool titleMatchName = true;
9453 std::map<std::string, TH1 *> histGroups;
9454 std::vector<TH1 *> hhs;
9455 std::set<std::pair<size_t, TH1 *>> ordered_hhs;
9456 std::set<TH1 *> histsWithBadTitles; // these histograms will have their titles autoFormatted
9457
9458 // support for CMS model case where has single component containing many coeffs
9459 // will build stack by setting each coeff equal to 0 in turn, rebuilding the histogram
9460 // the difference from the "full" histogram will be the component
9461 RooArgList cms_coefs;
9462 if (!rarNode->components().empty()) {
9463 auto comps = rarNode->components()[0];
9464 for (auto &c : *comps) {
9465 if (c->fFolder == "!.coeffs" || c->fFolder == "!.coeffpars")
9466 cms_coefs.add(*c->get<RooAbsArg>());
9467 }
9468 }
9469 if (!cms_coefs.empty()) {
9470 RooRealVar zero("zero", "", 0);
9471 std::shared_ptr<TH1> prevHist(static_cast<TH1 *>(h->Clone()));
9472 prevHist->Reset();
9473 prevHist->Add(h);
9474 // Nov25: discovered cms CMSHistSum has really heavy caching, that wont clear until I clone
9475 // i.e. I must first copy the function, then redirect the server, then copy that function
9476 // the copy of the copy will give the correct results, not the copy
9477 // This wasn't necessary for the CMSHistErrorPropagator class that I had before.
9478 std::unique_ptr<RooAbsReal> forig(
9479 dynamic_cast<RooAbsReal *>(rarNode->components()[0]->get()->Clone("tmpCopy0")));
9480 for (auto c : cms_coefs) {
9481 // seems I have to remake the function each time, as haven't figured out what cache needs clearing?
9482
9483 zero.setAttribute(Form("ORIGNAME:%s", c->GetName())); // used in redirectServers to say what this replaces
9484 forig->redirectServers(RooArgSet(zero), false, true); // each time will replace one additional coef
9485 std::unique_ptr<RooAbsReal> f(dynamic_cast<RooAbsReal *>(forig->Clone("tmpCopy")));
9486
9487 // zero.setAttribute(Form("ORIGNAME:%s",c->GetName()),false); (commented out so that on next iteration
9488 // will still replace all prev)
9489 auto hh = xRooNode(*f, *this).BuildHistogram(v);
9490 hh->SetName(c->GetName());
9491 if (sf)
9492 hh->Scale(sf->getVal());
9493 if (strlen(hh->GetTitle()) == 0) {
9494 hh->SetTitle(c->GetName()); // ensure all hists has titles
9495 // special case for CMS ... if find "_proc_" in the title, take whatever is after that
9496 auto idx = TString(hh->GetTitle()).Index("_proc_");
9497 if (idx >= 0) {
9498 hh->SetTitle(TString(TString(hh->GetTitle())(idx + 6, strlen(hh->GetTitle()))));
9499 }
9500 histsWithBadTitles.insert(hh);
9501 } else if (strcmp(hh->GetName(), hh->GetTitle()) == 0) {
9502 histsWithBadTitles.insert(hh);
9503 }
9504 titleMatchName &= (TString(c->GetName()) == hh->GetTitle() ||
9505 TString(hh->GetTitle()).BeginsWith(TString(c->GetName()) + "_"));
9506 std::shared_ptr<TH1> nextHist(static_cast<TH1 *>(hh->Clone()));
9507 hh->Add(prevHist.get(), -1.);
9508 hh->Scale(-1.);
9509 // remove the errors ... the above lines will have introduced errors
9510 hh->TH1::Reset("ICE"); // calling the base class method explicitly will only clear errors
9511 ordered_hhs.insert(std::pair(ordered_hhs.size(), hh));
9512 prevHist = nextHist;
9513 }
9514 } else if (get<RooSimultaneous>()) {
9515 // need to create a histogram for each sample across all the channels - will rely on functionality below to
9516 // merge them based on titles
9517
9518 for (auto &chan : bins()) {
9519 TString chanName(chan->GetName());
9520 chanName = chanName(chanName.Index("=") + 1, chanName.Length());
9521 auto samps = chan->mainChild();
9522 if (!samps)
9523 samps = *chan;
9524 for (auto &samp : samps.components()) {
9525 auto hh = static_cast<TH1 *>(h->Clone(samp->GetName()));
9526 hh->Reset();
9527 hh->SetTitle(samp->GetTitle());
9528 if (strlen(hh->GetTitle()) == 0) {
9529 hh->SetTitle(samp->GetName());
9530 histsWithBadTitles.insert(hh);
9531 } else if (strcmp(hh->GetName(), hh->GetTitle()) == 0) {
9532 histsWithBadTitles.insert(hh);
9533 }
9534 hh->SetTitle(TString(hh->GetTitle())
9535 .ReplaceAll(TString(chan->get()->GetName()) + "_",
9536 "")); // remove occurance of channelname_ in title (usually prefix)
9537 titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() ||
9538 TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_"));
9539 hh->SetBinContent(hh->GetXaxis()->FindFixBin(chanName), samp->GetContent());
9540 ordered_hhs.insert(std::pair(ordered_hhs.size(), hh));
9541 }
9542 }
9543 } else {
9544 for (auto &samp : rarNode->components()) {
9545 auto hh = samp->BuildHistogram(
9546 v, empty, false /* no errors for stack*/, binStart, binEnd, _fr, false, false, 0, h, true,
9547 setInterp); // passing h to ensure binning is the same for all subcomponent hists
9548 hh->SetName(samp->GetName());
9549 if (sf)
9550 hh->Scale(sf->getVal());
9551 ordered_hhs.insert(
9552 std::pair((samp->get<RooAbsArg>() && samp->get<RooAbsArg>()->getStringAttribute("StackOrder"))
9553 ? TString(samp->get<RooAbsArg>()->getStringAttribute("StackOrder")).Atoi()
9554 : ordered_hhs.size(),
9555 hh));
9556 if (strlen(hh->GetTitle()) == 0) {
9557 hh->SetTitle(samp->GetName()); // ensure all hists has titles
9558 histsWithBadTitles.insert(hh);
9559 } else if (strcmp(hh->GetName(), hh->GetTitle()) == 0) {
9560 histsWithBadTitles.insert(hh);
9561 }
9562 titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() ||
9563 TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_"));
9564 }
9565 }
9566
9567 // pull histograms in their order
9568 for (auto &[_, hh] : ordered_hhs) {
9569 hhs.push_back(hh);
9570 }
9571
9572 if (!hhs.empty()) {
9573 for (auto &hh : hhs) {
9574 allTitles.insert(hh->GetTitle());
9575 }
9576
9577 // get common prefix to strip off only if all titles match names and
9578 // any title is longer than 10 chars
9579 size_t e = std::min(allTitles.begin()->size(), allTitles.rbegin()->size());
9580 size_t ii = 0;
9581 bool goodPrefix = false;
9582 std::string commonSuffix;
9583 if (titleMatchName && hhs.size() > 1) {
9584 while (ii < e - 1 && allTitles.begin()->at(ii) == allTitles.rbegin()->at(ii)) {
9585 ii++;
9586 if (allTitles.begin()->at(ii) == '_' || allTitles.begin()->at(ii) == ' ')
9587 goodPrefix = true;
9588 }
9589
9590 // find common suffix if there is one .. must start with a "_"
9591 bool stop = false;
9592 while (!stop && commonSuffix.size() < size_t(e - 1)) {
9593 commonSuffix = allTitles.begin()->substr(allTitles.begin()->length() - commonSuffix.length() - 1);
9594 for (auto &tt : allTitles) {
9595 if (!TString(tt).EndsWith(commonSuffix.c_str())) {
9596 commonSuffix = commonSuffix.substr(1);
9597 stop = true;
9598 break;
9599 }
9600 }
9601 }
9602 if (commonSuffix.find('_') == std::string::npos) {
9603 commonSuffix = "";
9604 } else {
9605 commonSuffix = commonSuffix.substr(commonSuffix.find('_'));
9606 }
9607 }
9608 if (!goodPrefix)
9609 ii = 0;
9610
9611 // also find how many characters are needed to distinguish all entries (that dont have the same name)
9612 // then carry on up to first space or underscore
9613 size_t jj = 0;
9614 std::map<std::string, std::string> reducedTitles;
9615 while (reducedTitles.size() != allTitles.size()) {
9616 jj++;
9617 std::map<std::string, int> titlesMap;
9618 for (auto &s : allTitles) {
9619 if (reducedTitles.count(s))
9620 continue;
9621 titlesMap[s.substr(0, jj)]++;
9622 }
9623 for (auto &s : allTitles) {
9624 if (titlesMap[s.substr(0, jj)] == 1 && (jj >= s.length() || s.at(jj) == ' ' || s.at(jj) == '_')) {
9625 reducedTitles[s] = s.substr(0, jj);
9626 }
9627 }
9628 }
9629
9630 // strip common prefix and suffix before adding
9631 for (auto ritr = hhs.rbegin(); ritr != hhs.rend(); ++ritr) { // go in reverse order
9632 if (!histsWithBadTitles.count((*ritr))) {
9633 continue;
9634 }
9635 auto _title = (hhs.size() > 5) ? reducedTitles[(*ritr)->GetTitle()] : (*ritr)->GetTitle();
9636 _title = _title.substr(ii < _title.size() ? ii : 0);
9637 if (!commonSuffix.empty() && TString(_title).EndsWith(commonSuffix.c_str()))
9638 _title = _title.substr(0, _title.length() - commonSuffix.length());
9639 (*ritr)->SetTitle(_title.c_str());
9640 }
9641 }
9642
9643 for (auto &hh : hhs) {
9644 // automatically group hists that all have the same title
9645 if (histGroups.find(hh->GetTitle()) == histGroups.end()) {
9646 histGroups[hh->GetTitle()] = hh;
9647 } else {
9648 // add it into this group
9649 histGroups[hh->GetTitle()]->Add(hh);
9650 delete hh;
9651 hh = nullptr;
9652 continue;
9653 }
9654 auto hhMin = (hh->GetMinimum() == 0) ? hh->GetMinimum(1e-9) : hh->GetMinimum();
9655 if (!stack->GetHists() && h->GetMinimum() > hhMin) {
9656 auto newMin = hhMin - (h->GetMaximum() - hhMin) * gStyle->GetHistTopMargin();
9657 if (hhMin >= 0 && newMin < 0)
9658 newMin = hhMin * 0.99;
9659 // adjustYRange(newMin, h->GetMaximum());
9660 }
9661
9662 /*if(stack->GetHists() && stack->GetHists()->GetEntries()>0) {
9663 // to remove rounding effects on bin boundaries, see if binnings compatible
9664 auto _h1 = dynamic_cast<TH1*>(stack->GetHists()->At(0));
9665 if(_h1->GetNbinsX()==hh->GetNbinsX()) TODO ... finish dealing with silly rounding effects
9666 }*/
9667 TString thisOpt = TString(hh->GetOption()) == "l" ? "LF2" : ""; // need LF2 to get smooth line with fill
9668 // uncomment next line to blend continuous with discrete components .. get some unpleasant "poke through"
9669 // effects though
9670 // if(auto s = samp->get<RooAbsReal>(); s) thisOpt = s->isBinnedDistribution(*dynamic_cast<RooAbsArg*>(v)) ?
9671 // "" : "LF2";
9672 stack->Add(hh, thisOpt);
9673 }
9674 // stack->SetBit(kCanDelete); // should delete its sub histograms
9675 h->GetListOfFunctions()->AddFirst(stack, "noclear same");
9676 // stack->Draw("noclear same");
9677 // h->Draw(
9678 // dOpt + sOpt +
9679 // "same"); // overlay again .. if stack would cover original hist (negative components) we still see
9680 // integral
9681 // h->Draw("axissame"); // redraws axis
9682
9683 TList *ll = stack->GetHists();
9684 if (ll && ll->GetEntries()) {
9685
9686 // finally, ensure all hists are styled
9687 for (auto ho : *ll) {
9688 TH1 *hh = dynamic_cast<TH1 *>(ho);
9689 if (!hh)
9690 continue;
9691 bool createdStyle = (xRooNode(*hh, *this).styles(nullptr, false).get<TStyle>() == nullptr);
9692
9693 if (createdStyle) {
9694 // give hist a color, that isn't the same as any other hists color
9695 hh->SetFillStyle(1001); // solid fill style
9696 bool used = false;
9697 do {
9698 hh->SetFillColor(gEnv->GetValue("XRooFit.MinFillColor", kP10Blue /* was previously 2*/) + (count++));
9699 if (!gROOT->GetColor(hh->GetFillColor())) {
9700 // color doesn't exist, default it to transparent?
9701 hh->SetFillColor(0);
9702 }
9703 // check not already used this color
9704 used = false;
9705 for (auto ho2 : *ll) {
9706 TH1 *hh2 = dynamic_cast<TH1 *>(ho2);
9707 if (!hh2)
9708 continue;
9709 auto _styleNode = xRooNode(*hh2, *this).styles(hh2, false);
9710 auto _style = _styleNode.get<TStyle>();
9711 if (hh != hh2 && _style && _style->GetFillColor() == hh->GetFillColor()) {
9712 used = true;
9713 break;
9714 }
9715 }
9716 } while (used);
9717 }
9718
9719 auto _styleNode = xRooNode(*hh, *this).styles(hh);
9720 if (auto _style = _styleNode.get<TStyle>()) {
9721 *dynamic_cast<TAttLine *>(hh) = *_style;
9722 *dynamic_cast<TAttFill *>(hh) = *_style;
9723 *dynamic_cast<TAttMarker *>(hh) = *_style;
9724 }
9725 // for stacks, fill color of white should be color 10 unless fill style is 0
9726 if (hh->GetFillColor() == kWhite && hh->GetFillStyle() != 0) {
9727 // kWhite means 'transparent' in ROOT ... should really use a FillStyle of 0 for that
9728 // so assume user wanted actual white, which is color 10
9729 hh->SetFillColor(10);
9730 }
9731 }
9732 }
9733 }
9734
9735 return h;
9736}
9737
9738double xRooNode::GetBinData(int bin, const xRooNode &data)
9739{
9740 if (data.get<RooAbsData>()) {
9741 // attach as a child before calling datasets(), so that is included in the list
9742 push_back(std::make_shared<xRooNode>(data));
9743 }
9744 auto node = datasets().find(data.GetName());
9745 if (data.get<RooAbsData>()) {
9746 // remove the child we attached
9747 resize(size() - 1);
9748 }
9749 if (!node)
9750 return std::numeric_limits<double>::quiet_NaN();
9751 return node->GetBinContent(bin);
9752}
9753
9754std::vector<double> xRooNode::GetBinContents(int binStart, int binEnd) const
9755{
9756 if (fBinNumber != -1) {
9757 if (binStart != binEnd || !fParent) {
9758 throw std::runtime_error(TString::Format("%s is a bin - only has one value", GetName()));
9759 }
9760 return fParent->GetBinContents(fBinNumber, fBinNumber);
9761 }
9762 std::vector<double> out;
9763 if (get<RooAbsData>()) {
9764 auto g = BuildGraph(
9765 nullptr,
9766 (binStart != -1 ||
9767 binEnd != -1) /*include points for zeros unless we are asking for a single point with start=end=-1*/);
9768 if (!g) {
9769 return out;
9770 }
9771 if (binStart == binEnd && binStart == -1) {
9772 // integral over all bins if getting bin content -1
9773 double integral(0);
9774 for (int i = 0; i < g->GetN(); i++)
9775 integral += g->GetPointY(i);
9776 out.push_back(integral);
9777 delete g;
9778 return out;
9779 }
9780 for (int i = binStart - 1; i < g->GetN() && (binEnd == 0 || i < binEnd); i++) {
9781 out.push_back(g->GetPointY(i));
9782 }
9783 delete g;
9784 return out;
9785 }
9786
9787 bool doIntegral = false;
9788 if (binStart == binEnd && binStart == -1) {
9789 binStart = -1;
9790 binEnd = -1;
9791 doIntegral = true;
9792 } // return integral if request bin -1
9793 auto h = BuildHistogram(nullptr, false, false, binStart, binEnd);
9794 if (!h) {
9795 throw std::runtime_error(TString::Format("%s has no content", GetName()));
9796 }
9797 if (binEnd == 0) {
9798 binEnd = h->GetNbinsX();
9799 }
9800 if (doIntegral) {
9801 double tot = 0;
9802 for (int i = 1; i <= h->GetNbinsX(); i++) {
9803 tot += h->GetBinContent(i);
9804 }
9805 out.push_back(tot);
9806 } else {
9807 for (int i = binStart; i <= binEnd; i++) {
9808 out.push_back(h->GetBinContent(i));
9809 }
9810 }
9811 delete h;
9812 return out;
9813}
9814
9816{
9817 if (auto a = get<RooAbsArg>(); a) {
9818 // go through servers looking for 'main' thing
9819 for (auto &l : a->servers()) {
9820 if (l->getAttribute("MAIN_MEASUREMENT") || l->InheritsFrom("RooRealSumPdf") || l->InheritsFrom("RooAddPdf")) {
9821 return xRooNode(*l, *this);
9822 }
9823 }
9824 // the main child of a RooProduct is one that has the same name (/alias) as the product (except if is a bin
9825 // factor)
9826 if (a->IsA() == RooProduct::Class() && fBinNumber == -1) {
9827 for (auto &l : factors()) {
9828 if (strcmp(l->GetName(), GetName()) == 0) {
9829 return *l;
9830 }
9831 }
9832 }
9833 }
9834 return xRooNode();
9835}
9836
9838{
9839 if (auto o = get(); o) {
9840 o->Inspect();
9841 } else {
9843 }
9844}
9845
9846bool TopRightPlaceBox(TPad *p, TObject *o, double w, double h, double &xl, double &yb)
9847{
9848#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
9849 // reinitialize collide grid because the filling depends on fUxmin and fUxmax (and ymin ymax too)
9850 // and these aren't filled on the first time we do the placement (they init to 0 and 1), but will be filled
9851 // subsequently
9852 for (int i = 0; i < p->fCGnx; i++) {
9853 for (int j = 0; j < p->fCGny; j++) {
9854 p->fCollideGrid[i + j * p->fCGnx] = true;
9855 }
9856 }
9857 p->FillCollideGrid(o);
9858 Int_t iw = (int)(p->fCGnx * w);
9859 Int_t ih = (int)(p->fCGny * h);
9860
9861 Int_t nxmax = p->fCGnx - iw - 1 - p->fCGnx * p->GetRightMargin();
9862 Int_t nymax = p->fCGny - ih - 1 - p->fCGny * p->GetTopMargin();
9863
9864 for (Int_t j = nymax; j >= 0; j--) {
9865 for (Int_t i = nxmax; i >= 0; i--) {
9866 if (p->Collide(i, j, iw, ih)) {
9867 continue;
9868 } else {
9869 xl = (double)(i) / (double)(p->fCGnx);
9870 yb = (double)(j) / (double)(p->fCGny);
9871 return true;
9872 }
9873 }
9874 }
9875 return false;
9876#else
9877 return p->PlaceBox(o, w, h, xl, yb, "trw");
9878#endif
9879}
9880
9881TPaveText *getPave(const char *name = "labels", bool create = true, bool doPaint = false)
9882{
9883 if (auto p = dynamic_cast<TPaveText *>(gPad->GetPrimitive(name)); p) {
9884 if (doPaint)
9885 gPad->PaintModified(); //-- slows down x11 so trying to avoid
9886 return p;
9887 }
9888 if (!create) {
9889 return nullptr;
9890 }
9891 auto l = new TPaveText(gPad->GetLeftMargin() + 0.02, 1. - gPad->GetTopMargin() - 0.08, 0.6,
9892 1. - gPad->GetTopMargin() - 0.08);
9893 l->SetBorderSize(0);
9894 if (l->GetTextSize() == 0)
9895 l->SetTextSize(gStyle->GetTitleYSize());
9896
9898 // l->SetMargin(0);
9899 l->SetFillStyle(0);
9900 l->SetName(name);
9901 l->Draw();
9902 l->ConvertNDCtoPad();
9903 return l;
9904}
9905
9906TLegend *getLegend(bool create = true, bool doPaint = false)
9907{
9908 if (auto p = dynamic_cast<TLegend *>(gPad->GetPrimitive("legend")); p) {
9909 double x;
9910 double y;
9911 double w = p->GetX2NDC() - p->GetX1NDC();
9912 double h = p->GetY2NDC() - p->GetY1NDC();
9913 if (doPaint)
9914 gPad->PaintModified(); //-- slows down x11 so trying to avoid
9915 if (TopRightPlaceBox(dynamic_cast<TPad *>(gPad), p, w, h, x, y)) {
9916 // squash inside the frame ..
9917 // std::cout << gPad->GetName() << ":" << x << " , " << y << " , " << w << " , " << h << std::endl;
9918 x = std::max(x, (gPad->GetLeftMargin() + 0.02));
9919 y = std::max(y, (gPad->GetBottomMargin() + 0.02));
9920 x = std::min(x, (1. - gPad->GetRightMargin() - 0.02) - w);
9921 y = std::min(y, (1. - gPad->GetTopMargin() - 0.02) - h);
9922 h = std::min(h, (1. - gPad->GetTopMargin() - 0.02) - y);
9923 w = std::min(w, (1. - gPad->GetRightMargin() - 0.02) - x);
9924 // std::cout << gPad->GetName() << ":" << x << " , " << y << " , " << h << " , " << w << std::endl;
9925 p->SetX1NDC(x);
9926 p->SetY1NDC(y);
9927 p->SetX2NDC(x + w);
9928 p->SetY2NDC(y + h);
9929 gPad->Modified();
9930 }
9931 return p;
9932 }
9933 // look for a parent pad called 'legend' and create it there if existing
9934 auto p = gPad;
9935 while ((p != p->GetMother()) && (p = p->GetMother())) {
9936 if (auto q = dynamic_cast<TVirtualPad *>(p->GetPrimitive("legend")); q) {
9937 q->Modified();
9938 p = q;
9939 break;
9940 }
9941 }
9942 auto tmpPad = gPad;
9943 TLegend *l = nullptr;
9944 if (p && strcmp(p->GetName(), "legend") == 0) {
9945 if (l = dynamic_cast<TLegend *>(p->GetPrimitive("legend")); l || !create)
9946 return l;
9947 p->cd();
9948 l = new TLegend(gPad->GetLeftMargin(), 1. - gPad->GetTopMargin(), 1. - gPad->GetRightMargin(),
9949 gPad->GetBottomMargin());
9950 l->SetBorderSize(1); // ensure has a border
9951 } else {
9952 if (!create)
9953 return nullptr;
9954 l = new TLegend(0.6, 1. - gPad->GetTopMargin() - 0.08, 0.75, 1. - gPad->GetTopMargin() - 0.08);
9955 l->SetBorderSize(0);
9956 // legend text will be required to match y-axis
9957 if (l->GetTextSize() == 0) {
9958 l->SetTextSize(gStyle->GetTitleYSize());
9959 l->SetTextFont(gStyle->GetTitleFont("Y"));
9960 }
9961 }
9963 // l->SetMargin(0);
9964 l->SetFillStyle(0);
9965 l->SetName("legend");
9966 l->Draw();
9967 l->ConvertNDCtoPad();
9968 tmpPad->cd();
9969 return l;
9970}
9971
9972std::string formatLegendString(const std::string &s)
9973{
9974 auto i = s.find("\n");
9975 if (i == std::string::npos) {
9976 return s;
9977 }
9978 return std::string("#splitline{") + s.substr(0, i) + "}{" + formatLegendString(s.substr(i + 1)) + "}";
9979}
9980
9981void addLegendEntry(TObject *o, const char *title, const char *opt)
9982{
9983 auto l = getLegend();
9984 if (!l)
9985 return;
9986 // check for entry already existing with same title
9987 for (auto a : *l->GetListOfPrimitives()) {
9988 if (formatLegendString(title) == dynamic_cast<TLegendEntry *>(a)->GetLabel())
9989 return;
9990 }
9991 if (l->GetListOfPrimitives()->GetEntries() > 20)
9992 return; // todo: create an 'other' entry?
9993
9994 auto e = l->AddEntry(o, formatLegendString(title).c_str(), opt);
9995 // move to top of the legend (we add things in at the top)
9996 l->GetListOfPrimitives()->RemoveLast();
9997 l->GetListOfPrimitives()->AddFirst(e);
9998 if (auto nObj = l->GetListOfPrimitives()->GetEntries(); nObj > 0) {
9999 // each entry takes up 0.05 ... maximum of N*(N+4) (where N is # cols) before next column
10000 int nn = l->GetNColumns();
10001 nn *= (nn + 4);
10002 if (nObj > 1 && (nObj % nn) == 1) {
10003 l->SetNColumns(l->GetNColumns() + 1);
10004 if (l->GetBorderSize() == 0) {
10005 l->SetX1NDC(l->GetX2NDC() - 0.15 * l->GetNColumns());
10006 }
10007 }
10008 if (l->GetBorderSize() == 0) {
10009 l->SetY1NDC(l->GetY2NDC() - 0.05 * gPad->GetHNDC() * std::ceil((double(nObj) / l->GetNColumns())));
10010 }
10011 }
10012
10013 getLegend(); // to mark modified
10014}
10015
10016// this exists to avoid calling update excessively because it slows down x11 ... but still
10017// need to call update twice if have a legend drawn in order to relocate it.
10019public:
10020 PadRefresher(TVirtualPad *p) : fPad(p) { nExisting++; }
10022 {
10023 if (fPad) {
10024 getLegend(false, true);
10025 fPad->GetCanvas()->Paint();
10026 fPad->GetCanvas()->Update();
10027#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 30, 00)
10028 fPad->GetCanvas()->ResetUpdated(); // stops previous canvas being replaced in a jupyter notebook
10029#endif
10030 fPad->cd();
10031 }
10032 nExisting--;
10033 }
10034 TVirtualPad *fPad = nullptr;
10035 static int nExisting;
10036};
10037
10039
10041{
10042 // in order to catch exceptions to prevent crash of GUI, do this:
10043 if (gROOT->FromPopUp()) {
10044 gROOT->SetFromPopUp(false);
10045 try {
10046 Draw(opt);
10047 } catch (const std::exception &e) {
10048 new TGMsgBox(
10049 gClient->GetRoot(),
10050 (gROOT->GetListOfBrowsers()->At(0))
10051 ? dynamic_cast<TGWindow *>(static_cast<TBrowser *>(gROOT->GetListOfBrowsers()->At(0))->GetBrowserImp())
10052 : gClient->GetRoot(),
10053 "Exception", e.what(),
10054 kMBIconExclamation); // deletes self on dismiss?
10055 }
10056 gROOT->SetFromPopUp(true);
10057 return;
10058 }
10059
10060 TString sOpt2(opt);
10061 sOpt2.ToLower();
10062 if (!get() && !IsFolder() && !sOpt2.Contains("x="))
10063 return;
10064
10065 if (auto mc = get<RooStats::ModelConfig>()) {
10066 xRooNode(*mc->GetPdf(), fParent).Draw(opt); // draw the pdf of the config
10067 } else if (auto ir = get<RooStats::HypoTestInverterResult>()) {
10068 xRooHypoSpace(ir).Draw(opt);
10070 return;
10071 } else if (get<RooStats::HypoTestResult>()) {
10072 if (gPad)
10073 gPad->Clear();
10074 xRooNLLVar::xRooHypoPoint(std::dynamic_pointer_cast<RooStats::HypoTestResult>(fComp)).Draw(opt);
10075 {
10076 PadRefresher p(gPad); // refreshes the pad
10077 }
10079 return;
10080 }
10081
10082 if (sOpt2 == "pcls" && get<RooRealVar>() && fParent && fParent->get<RooAbsPdf>()) {
10083 // use the first selected dataset
10084 auto _dsets = fParent->datasets();
10085 // bool _drawn=false;
10086 TString dsetName = "";
10087 for (auto &d : _dsets) {
10088 if (d->get()->TestBit(1 << 20)) {
10089 dsetName = d->get()->GetName();
10090 break;
10091 }
10092 }
10093 auto hs = fParent->nll(dsetName.Data()).hypoSpace(get<RooRealVar>()->GetName());
10094 hs.limits("cls visualize");
10095 hs.SetName(TUUID().AsString());
10096 if (ws()) {
10097 ws()->import(*hs.result());
10098 }
10099 return;
10100 }
10101
10102 if (auxFunctions.empty()) {
10103 // add the defaults: Ratio and Signif
10105 "Ratio",
10106 [](double a, double b, double) {
10107 if (a == 0)
10108 return 0.;
10109 if (b == 0 && a == 0)
10110 return 1.;
10111 return a / b;
10112 },
10113 true);
10115 "Signif",
10116 [](double n, double b, double sigma) {
10117 double t0 = 0;
10118 if (sigma <= 0.) {
10119 // use simplified expression ...
10120 t0 = 2. * (((n == 0) ? 0 : n * log(n / b)) - (n - b));
10121 } else {
10122 double sigma2 = sigma * sigma;
10123 double b_hathat = 0.5 * (b - sigma2 + sqrt(pow(b - sigma2, 2) + 4 * n * sigma2));
10124 // double s_hat = n - m;
10125 // double b_hat = m;
10126 t0 = 2. * (((n == 0) ? 0 : n * log(n / b_hathat)) + b_hathat - n + pow(b - b_hathat, 2) / (2. * sigma2));
10127 }
10128 if (t0 < 0)
10129 return 0.; // can happen from numerical precision
10130 return (n >= b) ? sqrt(t0) : -sqrt(t0);
10131 },
10132 false);
10133 }
10134
10135 TString sOpt(opt);
10136
10137 RooAbsLValue *v = nullptr;
10138 std::vector<double> xPoints;
10139 if (sOpt2.Contains("x=")) {
10140 // specifying a particular var to scan over ...
10141 int _idx = sOpt2.Index("x=");
10142 int _eidx = sOpt2.Index(';', _idx);
10143 TString varPart = sOpt(_idx + 2, (_eidx < 0 ? sOpt2.Length() : _eidx) - (_idx + 2));
10144 TString varName = varPart;
10145 // if varName is of form str(num,num,num) then can infer scan points
10146 if (auto _idx2 = varPart.Index("("); _idx2 > 0) {
10147 varName = varPart(0, _idx2);
10148 TStringToken pattern(TString(varPart(_idx2 + 1, varPart.Length() - _idx2 - 2)), ",");
10149 double min(0);
10150 double max(0);
10151 int nBins = 0;
10152 int ii = 0;
10153 while (pattern.NextToken()) {
10154 TString s = pattern;
10155 if (ii == 0) {
10156 nBins = s.Atoi();
10157 } else if (ii == 1) {
10158 min = s.Atof();
10159 } else if (ii == 2) {
10160 max = s.Atof();
10161 }
10162 ii++;
10163 }
10164 if (nBins > 100)
10165 nBins = 100; // limit scanning to 100 points
10166 if (nBins > 1) {
10167 for (double x = min; x <= max; x += (max - min) / (nBins - 1)) {
10168 xPoints.push_back(x);
10169 }
10170 } else if (nBins == 1)
10171 xPoints.push_back((min + max) / 2.);
10172 }
10173 v = getObject<RooAbsLValue>(varName.Data()).get();
10174 if (!v) {
10175 throw std::runtime_error(TString::Format("Could not find variable %s", varName.Data()));
10176 }
10177 if (xPoints.empty() && !obs().find(varName.Data()) &&
10178 dynamic_cast<RooAbsRealLValue *>(v)) { // will draw obs as regular (e.g. hist)
10179 double tmp = static_cast<RooAbsRealLValue *>(v)->getVal();
10180 for (int i = 0; i < v->numBins(GetName()); i++) {
10181 v->setBin(i, GetName());
10182 xPoints.push_back(static_cast<RooAbsRealLValue *>(v)->getVal());
10183 }
10184 static_cast<RooAbsRealLValue *>(v)->setVal(tmp);
10185 }
10186 sOpt2 = TString(sOpt2(0, _idx)) + sOpt2(_idx + 2 + varPart.Length() + 1, sOpt2.Length());
10187 sOpt = TString(sOpt(0, _idx)) + sOpt(_idx + 2 + varPart.Length() + 1, sOpt.Length());
10188 }
10189 TString forceNames = "";
10190 if (sOpt2.Contains("force")) {
10191 // force plots show how much NLL changes wrt to a change of variables
10192 if (get<RooRealVar>() && fParent && fParent->get<RooAbsPdf>()) {
10193 // assume want force of this parameter from the parent pdf
10194 TString ff = sOpt(sOpt2.Index("force"), sOpt2.Index("force") + 5);
10195 sOpt.ReplaceAll(ff, TString::Format("force%s", get()->GetName()));
10196 fParent->Draw(sOpt);
10197 return;
10198 } else if (get<RooAbsPdf>()) {
10199 // extract the parameter(s) to calculate force for
10200 forceNames = sOpt(sOpt2.Index("force") + 5, sOpt2.Length());
10201 sOpt = sOpt(0, sOpt2.Index("force"));
10202 sOpt2 = sOpt2(0, sOpt2.Index("force"));
10203 } else {
10204 Error("Draw", "Can only compute forces with PDFs");
10205 return; // don't throw because will cause browser to exit if done from there
10206 }
10207 }
10208 bool hasOverlay = sOpt2.Contains("overlay");
10209 TString overlayName = "";
10210 if (hasOverlay) {
10211 // whatever follows overlay is the variation name
10212 overlayName = sOpt(sOpt2.Index("overlay") + 7, sOpt2.Length());
10213 sOpt = sOpt(0, sOpt2.Index("overlay"));
10214 sOpt2 = sOpt2(0, sOpt2.Index("overlay"));
10215 }
10216 if (sOpt2.Contains("ratio") && !sOpt2.Contains("auxratio"))
10217 sOpt += "auxRatio";
10218 if (sOpt2.Contains("significance") && !sOpt2.Contains("auxsignif"))
10219 sOpt += "auxSignif";
10220
10221 std::string auxPlotTitle;
10222 for (auto &[k, _] : auxFunctions) {
10223 if (sOpt.Contains(TString::Format("aux%s", k.c_str()))) {
10224 auxPlotTitle = k;
10225 }
10226 sOpt.ReplaceAll(TString::Format("aux%s", k.c_str()), "");
10227 }
10228
10229 sOpt.ToLower();
10230 sOpt.ReplaceAll("ratio", "");
10231 sOpt.ReplaceAll("significance", ""); // remove old option if still given
10232 bool nostack = sOpt.Contains("nostack");
10233 sOpt.ReplaceAll("nostack", "");
10234 bool hasSame = sOpt.Contains("same");
10235 sOpt.ReplaceAll("same", "");
10236 bool hasGoff = sOpt.Contains("goff");
10237 sOpt.ReplaceAll("goff", "");
10238 bool hasFR = sOpt.Contains("pull") && !get<RooFitResult>();
10239 sOpt.ReplaceAll("pull", "");
10240 bool hasText = sOpt.Contains("text");
10241 bool hasTexte = sOpt.Contains("texte");
10242 bool hasErrorOpt = sOpt.Contains("e");
10243 sOpt.ReplaceAll("e", "");
10244 if (hasTexte) {
10245 sOpt.ReplaceAll("txt", "texte");
10246 } else if (hasText) {
10247 sOpt.ReplaceAll("txt", "text");
10248 }
10249 if (auxPlotTitle == "Signif")
10250 hasErrorOpt = true; // must calculate error to calculate significance
10251 if (hasOverlay)
10252 hasSame = true; // when overlaying must be putting on same
10253
10254 TVirtualPad *pad = gPad;
10255
10256 TH1 *hAxis = nullptr;
10257
10258 auto clearPad = []() {
10259 gPad->Clear();
10260 if (gPad->GetNumber() == 0) {
10261 gPad->SetBottomMargin(gStyle->GetPadBottomMargin());
10262 gPad->SetTopMargin(gStyle->GetPadTopMargin());
10263 gPad->SetLeftMargin(gStyle->GetPadLeftMargin());
10264 gPad->SetRightMargin(gStyle->GetPadRightMargin());
10265 }
10266 // if (gPad == gPad->GetCanvas()) {
10267 // gPad->GetCanvas()->SetCanvasSize( gPad->GetCanvas()->GetWindowWidth() - 4,
10268 // gPad->GetCanvas()->GetWindowHeight() - 28 );
10269 // }
10270 };
10271
10272 if (!hasSame || !pad) {
10273 if (!pad) {
10275 pad = gPad;
10276 }
10277
10278 } else {
10279 // get the histogram representing the axes
10280 hAxis = dynamic_cast<TH1 *>(pad->GetPrimitive("axis"));
10281 if (!hAxis) {
10282 for (auto o : *pad->GetListOfPrimitives()) {
10283 if (hAxis = dynamic_cast<TH1 *>(o); hAxis)
10284 break;
10285 }
10286 }
10287 if (hAxis && !v) {
10288 v = getObject<RooAbsLValue>(hAxis->GetXaxis()->IsAlphanumeric() ? hAxis->GetXaxis()->GetTimeFormatOnly()
10289 : hAxis->GetXaxis()->GetName())
10290 .get();
10291 }
10292 }
10293
10294 if (!hasSame) {
10295 if (gPad != gPad->GetCanvas()) {
10296 gPad->SetName(GetName()); // only rename the pad if its not the parent canvas
10297 }
10298 gPad->SetTitle(GetTitle());
10299 }
10300
10301 PadRefresher padRefresh(((!hasSame || hasOverlay || PadRefresher::nExisting == 0) && !hasGoff) ? gPad : nullptr);
10302
10303 auto adjustYRange = [&](double min, double max, TH1 *hh = nullptr, bool symmetrize = false) {
10304 if (!hh)
10305 hh = hAxis;
10306 // give max and min a buffer ...
10307 max += gStyle->GetHistTopMargin() * (max - min);
10308 if (min > 0)
10309 min = std::max(min * 0.9, min - gStyle->GetHistTopMargin() * (max - min));
10310 if (hh) {
10311 double ymin = hh->GetMinimum();
10312 double ymax = hh->GetMaximum();
10313 if (hh->GetMaximumStored() == -1111)
10314 ymax += gStyle->GetHistTopMargin() * (ymax - ymin);
10315 if (hh->GetMinimumStored() == -1111) {
10316 if (gStyle->GetHistMinimumZero() && ymax >= 0) {
10317 ymin = 0;
10318 } else if (ymin < 0) {
10319 ymin -= gStyle->GetHistTopMargin() * (ymax - ymin);
10320 } else {
10321 ymin = std::max(ymin * 0.9, ymin - gStyle->GetHistTopMargin() * (ymax - ymin));
10322 }
10323 // see TGLPlotPainter to complete the mimic, but we leave off here truncating @ 0 if ymax>0
10324 }
10325 // make ymax at least 3x bigger than biggest error if has error
10326 if (hh->GetSumw2()) {
10327 double smallestErrDown3 = -std::numeric_limits<double>::infinity();
10328 double smallestErrUp3 = std::numeric_limits<double>::infinity();
10329 for (int i = 1; i <= hh->GetNbinsX(); i++) {
10330 smallestErrDown3 = std::max(smallestErrDown3, hh->GetBinContent(i) - 3 * hh->GetBinError(i));
10331 smallestErrUp3 = std::min(smallestErrUp3, hh->GetBinContent(i) + 3 * hh->GetBinError(i));
10332 }
10333 max = std::max(max, smallestErrUp3);
10334 min = std::min(min, smallestErrDown3);
10335 }
10336 bool change = false;
10337 if (min < ymin) {
10338 ymin = min;
10339 change = true;
10340 }
10341 if (max > ymax) {
10342 ymax = max;
10343 change = true;
10344 }
10345 if (change) {
10346 // note: unfortunately when user 'unzooms' y axis it resets stored minimum to -1111, so lose range
10347 if (symmetrize) {
10348 double down = hh->GetBinContent(1) - ymin;
10349 double up = ymax - hh->GetBinContent(1);
10350 if (down > up) {
10351 ymax = hh->GetBinContent(1) + down;
10352 } else {
10353 ymin = hh->GetBinContent(1) - up;
10354 }
10355 }
10356 if (hh == hAxis && pad && !pad->GetLogy() && ymin > 0 && (log10(ymax) - log10(max)) >= 3) {
10357 // auto-log the pad
10358 pad->SetLogy();
10359 }
10360 if (hh == hAxis && pad && ymin == 0 && pad->GetLogy()) {
10361 ymin = 1e-2;
10362 }
10363 if (ymin == 0 && ymax > 10)
10364 ymin = 0.1; // adjust min so if user activates log scale it isn't bad
10365 hh->SetMinimum(ymin);
10366 hh->SetMaximum(ymax);
10367 hh->GetYaxis()->Set(1, ymin, ymax);
10368 hh->SetAxisRange(ymin, ymax, "Y");
10369 }
10370 }
10371 };
10372
10373 auto graphMinMax = [](TGraphAsymmErrors *gr) {
10374 double ymax = -std::numeric_limits<double>::infinity();
10375 double ymin = std::numeric_limits<double>::infinity();
10376 for (int i = 0; i < gr->GetN(); i++) {
10377 ymax = std::max(ymax, gr->GetPointY(i) + gr->GetErrorYhigh(i));
10378 ymin = std::min(ymin, gr->GetPointY(i) - gr->GetErrorYlow(i));
10379 }
10380 return std::make_pair(ymin, ymax);
10381 };
10382
10383 if (!xPoints.empty()) {
10384 // create a graph using GetContent
10386 out->SetName(GetName());
10387 out->SetTitle(GetTitle());
10388 out->SetFillColor(out->GetLineColor());
10389 out->SetMarkerStyle(0);
10390 out->SetFillStyle(hasErrorOpt ? 3005 : 0);
10391 double tmp = static_cast<RooAbsRealLValue *>(v)->getVal();
10392 for (auto &x : xPoints) {
10393 static_cast<RooAbsRealLValue *>(v)->setVal(x);
10394 out->AddPoint(x, GetContent());
10395 if (hasErrorOpt) {
10396 out->SetPointEYlow(out->GetN() - 1, GetError());
10397 out->SetPointEYhigh(out->GetN() - 1, out->GetErrorYlow(out->GetN() - 1)); // symmetric error for now
10398 }
10399 }
10400 static_cast<RooAbsRealLValue *>(v)->setVal(tmp);
10401 out->GetHistogram()->GetXaxis()->SetTitle(static_cast<RooAbsRealLValue *>(v)->GetTitle());
10402 out->SetBit(kCanDelete);
10403 out->Draw(TString(hasSame ? "L" : "AL") + (hasErrorOpt ? "3" : ""));
10404 return;
10405 }
10406
10407 if (hasFR) {
10408 // drawing the fitresult as a pull plot on a subpad, and rest of the draw elsewhere
10409 clearPad();
10410 pad->Divide(1, 2, 1e-9, 1e-9); //,0,0);
10411 pad->GetPad(1)->SetPad(0, 0.2, 1, 1);
10412 pad->GetPad(2)->SetPad(0, 0, 1, 0.2);
10413 TString optNoFR(opt);
10414 optNoFR.ReplaceAll("pull", "");
10415 pad->cd(1);
10416 Draw(optNoFR);
10417 pad->cd(2);
10418 auto _fr = fitResult();
10419 _fr.Draw();
10420 // switch into subpad
10421 gPad->cd(1);
10422 gPad->SetFillColor(kGray);
10423 gPad->GetFrame()->SetFillColor(kWhite);
10424 gPad->GetFrame()->SetFillStyle(1001);
10425 gPad->SetTopMargin(0);
10426 gPad->SetBottomMargin(0);
10427 gPad->SetName("pull");
10428 // split the pull graph into individual points -- for benefit of GUI status bar
10429 auto pullGraph = dynamic_cast<TGraphAsymmErrors *>(gPad->GetPrimitive("pulls"));
10430 if (!pullGraph) {
10431 Error("Draw", "Couldn't find pull graph");
10432 return;
10433 }
10434 pullGraph->SetName("nominal");
10435 TMultiGraph *mg = new TMultiGraph;
10436 mg->SetName("editables");
10437
10438 auto scaleHist = static_cast<TH1 *>(pullGraph->FindObject("scales"));
10439 if (!scaleHist)
10440 throw std::runtime_error("Could not find scales in fit result");
10441
10442 for (auto i = 0; i < pullGraph->GetN(); i++) {
10443 auto g = new TGraphAsymmErrors;
10444 g->SetName(scaleHist->GetXaxis()->GetBinLabel(i + 1));
10445 auto _p = dynamic_cast<RooRealVar *>(_fr.get<RooFitResult>()->floatParsFinal().find(g->GetName()));
10446 if (!_p) {
10447 Warning("Draw", "Found a non-var in the floatParsFinal list: %s - this shouldn't happen", g->GetName());
10448 continue;
10449 }
10450 g->SetTitle(TString::Format(
10451 "%s=%g +/- %s [%g,%g]", strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName(), _p->getVal(),
10452 _p->hasAsymError() ? TString::Format("(%g,%g)", _p->getAsymErrorHi(), _p->getAsymErrorLo()).Data()
10453 : TString::Format("%g", _p->getError()).Data(),
10454 scaleHist->GetBinContent(i + 1), scaleHist->GetBinError(i + 1)));
10455 g->SetPoint(0, pullGraph->GetPointX(i), pullGraph->GetPointY(i));
10456 g->SetPointEYhigh(0, pullGraph->GetErrorYhigh(i));
10457 g->SetPointEYlow(0, pullGraph->GetErrorYlow(i));
10458 g->SetEditable(true);
10459 g->SetHighlight(true);
10460 g->SetMarkerStyle(20);
10461 g->SetMarkerSize(0.5);
10462 mg->Add(g);
10463 }
10464 // gPad->GetListOfPrimitives()->Remove(pullGraph); delete pullGraph;
10465 mg->Draw("z0p");
10466 mg->SetBit(kCanDelete);
10467 auto _thisClone = new xRooNode("node", fComp, fParent);
10468 _thisClone->SetBit(kCanDelete);
10469 _thisClone->AppendPad();
10470
10471 // ensure statusbar visible for interactive plot
10472 // turned this off for now ... as not needed if doing through browser, status bar already there
10473 // if (gPad->GetCanvas() && !gPad->GetCanvas()->TestBit(TCanvas::kShowEventStatus)) {
10474 // gPad->GetCanvas()->ToggleEventStatus();
10475 // }
10476 gPad->AddExec("interactivePull", TString::Format("%s::Interactive_Pull()", ClassName()));
10477
10478 pad->cd();
10479 return;
10480 }
10481
10482 if (auto _simPdf = get<RooSimultaneous>();
10483 _simPdf && !(v && strcmp(_simPdf->indexCat().GetName(), dynamic_cast<TObject *>(v)->GetName()) == 0)) {
10484 auto _channels = bins();
10485 int _size = 0;
10486 for (auto &_v : _channels) {
10487 if (!_v->IsHidden())
10488 _size++;
10489 }
10490 if (!hasSame) {
10491 if (_size > 4) {
10492 // add a pad for the common legends
10493 _size++;
10494 }
10495 clearPad();
10496 pad->SetBorderSize(0);
10497 // if (pad->GetCanvas() == pad) {
10498 // if(_size>4) {
10499 // int n = _size;
10500 // Int_t w = 1, h = 1;
10501 // if (pad->GetCanvas()->GetWindowWidth() > pad->GetCanvas()->GetWindowHeight()) {
10502 // w = TMath::Ceil(TMath::Sqrt(n));
10503 // h = TMath::Floor(TMath::Sqrt(n));
10504 // if (w*h < n) w++;
10505 // } else {
10506 // h = TMath::Ceil(TMath::Sqrt(n));
10507 // w = TMath::Floor(TMath::Sqrt(n));
10508 // if (w*h < n) h++;
10509 // }
10510 // // adjust the window size to display only 4 in the window, with scroll bars
10511 // pad->GetCanvas()->SetCanvasSize( w*((pad->GetCanvas()->GetWindowWidth()-4)/2.) -16
10512 // ,h*((pad->GetCanvas()->GetWindowHeight()-28)/2.) - 16 );
10513 // } else {
10514 // //pad->GetCanvas()->Set(
10515 // w*(pad->GetCanvas()->GetWindowWidth()/2.),h*(pad->GetCanvas()->GetWindowHeight()/2.)) )
10516 // }
10517 // }
10518 int ncols = _simPdf->getStringAttribute("ncols") ? TString(_simPdf->getStringAttribute("ncols")).Atoi() : 0;
10519 if (ncols > 0) {
10520 dynamic_cast<TPad *>(pad)->Divide(ncols, std::ceil(double(_size) / ncols), 1e-9, 1e-9);
10521 } else {
10522 dynamic_cast<TPad *>(pad)->DivideSquare(_size, 1e-9, 1e-9);
10523 }
10524 if (_size > 5) {
10525 auto _pad = pad->GetPad(_size); // will use as the legend pad
10526 _pad->SetName("legend");
10527 // stretch the pad all the way to the left
10528 _pad->SetPad(_pad->GetXlowNDC(), _pad->GetYlowNDC(), 1.0, _pad->GetYlowNDC() + _pad->GetHNDC());
10529 // and make all the remaining pads transparent
10530 int x = _size;
10531 while (pad->GetPad(x + 1)) {
10532 pad->GetPad(x + 1)->SetFillStyle(0);
10533 x++;
10534 }
10535 }
10536 }
10537 int i = 0;
10538 auto &chanVar = const_cast<RooAbsCategoryLValue &>(_simPdf->indexCat());
10539 // auto _idx = chanVar.getIndex();
10540 auto _range = GetRange();
10541 std::vector<TString> chanPatterns;
10542 if (_range && strlen(_range)) {
10543 TStringToken pattern(_range, ",");
10544 while (pattern.NextToken()) {
10545 chanPatterns.emplace_back(pattern);
10546 }
10547 }
10548 for (auto &_v : _channels) {
10549 if (_v->IsHidden())
10550 continue;
10551 TString s(_v->GetName());
10552 pad->cd(++i);
10553 gPad->SetName(s);
10554 TString cName = s(s.Index('=') + 1, s.Length());
10555 chanVar.setLabel(cName);
10556 bool inRange = chanPatterns.empty();
10557 for (auto &p : chanPatterns) {
10558 if (chanVar.inRange(p)) {
10559 inRange = true;
10560 break;
10561 }
10562 }
10563 if (!inRange || !_v->get<RooAbsReal>()->isSelectedComp())
10564 gPad->SetFillColor(kGray);
10565 if (!hasSame && _size > 1 && (gStyle->GetTitleFont("Y") % 10) == 3)
10566 gPad->SetLeftMargin(std::min(gPad->GetLeftMargin() * (1. / gPad->GetWNDC()), 0.3));
10567 _v->Draw(opt);
10569 }
10570 pad->cd(0);
10571 gPad->Modified();
10572 // gPad->Update();
10573 return;
10574 }
10575
10576 if (!get() || get<RooArgList>()) {
10577 // is a group draw all the submembers
10578 browse();
10579 int _size = 0;
10580 // int _size = _channels.size(); // size(); if (find("!.vars")) _size--;
10581 for (auto &_v : *this) {
10582 if (_v->IsHidden())
10583 continue;
10584 if (strcmp(GetName(), ".vars") == 0) {
10585 // auto hide obs and "1" and const var
10586 if (_v->get<RooAbsArg>()->getAttribute("obs"))
10587 continue;
10588 if (strcmp(_v->get()->GetName(), "1") == 0 || strcmp(_v->get()->GetName(), "ONE") == 0 ||
10589 TString(_v->get()->GetName()).BeginsWith("binWidth_"))
10590 continue;
10591 if (_v->get()->InheritsFrom("RooConstVar"))
10592 continue;
10593 }
10594 TString s(_v->GetName());
10595 if (s.BeginsWith(".") || s.BeginsWith("!"))
10596 continue;
10597 _size++;
10598 }
10599 if (!hasSame) {
10600 clearPad();
10601 pad->SetBorderSize(0);
10602 dynamic_cast<TPad *>(pad)->DivideSquare(_size, 1e-9, 1e-9);
10603 }
10604 int i = 0;
10605 for (auto &_v : *this) {
10606 if (_v->IsHidden())
10607 continue;
10608 if (strcmp(GetName(), ".vars") == 0) {
10609 // auto hide obs and "1" and const var
10610 if (_v->get<RooAbsArg>()->getAttribute("obs"))
10611 continue;
10612 if (strcmp(_v->get()->GetName(), "1") == 0 || strcmp(_v->get()->GetName(), "ONE") == 0 ||
10613 TString(_v->get()->GetName()).BeginsWith("binWidth_"))
10614 continue;
10615 if (_v->get()->InheritsFrom("RooConstVar"))
10616 continue;
10617 }
10618 TString s(_v->GetName());
10619 if (s.BeginsWith(".") || s.BeginsWith("!"))
10620 continue;
10621 pad->cd(++i);
10622 gPad->SetName(s);
10623 if (!hasSame && _size > 1 && (gStyle->GetTitleFont("Y") % 10) == 3)
10624 gPad->SetLeftMargin(std::min(gPad->GetLeftMargin() * (1. / gPad->GetWNDC()), 0.3));
10625 _v->Draw(opt);
10626 // pad->Modified();//pad->Update();
10628 }
10629 pad->cd(0);
10630 gPad->Modified();
10631 // gPad->Update();
10632 return;
10633 }
10634
10635 if (get()->InheritsFrom("RooProdPdf")) {
10636 // draw the main pdf, if there is one...
10637 auto _mainChild = mainChild();
10638 if (_mainChild) {
10639 _mainChild.Draw(opt);
10640 gPad->SetName(GetName());
10641 return;
10642 }
10643 }
10644
10645 if (auto fr = get<RooFitResult>(); fr) {
10646 if (sOpt.Contains("corr")) {
10647 // do correlation matrix
10648 // if a number follows 'corr', reduce the correlation matrix to show only the most extreme correlations
10649 int numCorrs = TString(sOpt(sOpt.Index("corr") + 4, sOpt.Length())).Atoi();
10650 if (numCorrs == 0)
10651 numCorrs = fr->correlationMatrix().GetNcols();
10652
10653 TH2 *hist = nullptr;
10654 if (numCorrs < fr->correlationMatrix().GetNcols()) {
10655 // need to reduce
10656 std::set<std::pair<double, size_t>> maxCorrs;
10657 for (int i = 0; i < fr->correlationMatrix().GetNcols(); i++) {
10658 double maxCorr = 0;
10659 for (int j = 0; j < fr->correlationMatrix().GetNcols(); j++) {
10660 if (j == i)
10661 continue;
10662 maxCorr = std::max(std::abs(fr->correlationMatrix()(i, j)), maxCorr);
10663 }
10664 maxCorrs.insert({maxCorr, i});
10665 }
10666 std::vector<size_t> topN;
10667 int c = 0;
10668 for (auto itr = maxCorrs.rbegin(); itr != maxCorrs.rend(); ++itr) {
10669 topN.push_back(itr->second);
10670 c++;
10671 if (c == numCorrs)
10672 break;
10673 }
10674 hist = new TH2D(fr->GetName(), TString::Format("%s - Top %d correlations", fr->GetTitle(), numCorrs),
10675 numCorrs, 0, numCorrs, numCorrs, 0, numCorrs);
10676 for (size_t i = 0; i < topN.size(); i++) {
10677 hist->GetXaxis()->SetBinLabel(i + 1, fr->floatParsFinal().at(topN.at(i))->GetTitle());
10678 hist->GetYaxis()->SetBinLabel(numCorrs - i, fr->floatParsFinal().at(topN.at(i))->GetTitle());
10679 for (size_t j = 0; j < topN.size(); j++) {
10680 hist->Fill(i + 0.5, numCorrs - j - 0.5, fr->correlationMatrix()(topN.at(i), topN.at(j)));
10681 }
10682 }
10683 hist->SetMinimum(-1);
10684 hist->SetMaximum(1);
10685
10686 } else {
10687 hist = fr->correlationHist(fr->GetName());
10688 hist->SetTitle(fr->GetTitle());
10689 }
10690
10691 hist->SetBit(kCanDelete);
10692 hist->Scale(100);
10693 hist->SetStats(false);
10694 hist->SetDirectory(nullptr);
10696 gStyle->SetPaintTextFormat(".1f");
10697 hist->GetXaxis()->SetTickSize(0);
10698 hist->GetYaxis()->SetTickSize(0);
10699 hist->SetMinimum(-100);
10700 hist->Draw(sOpt);
10702 gPad->SetGrid(1, 1);
10703 gPad->SetLogy(0);
10704 gPad->SetLogx(0);
10705 return;
10706 }
10707
10708 if (sOpt.Contains("brakdown")) { // e will have been removed above
10709
10710 // breakdown is quadrature difference between total error and conditional error
10711 // group by 'group' attribute
10712
10713 std::string poiName;
10714 if (sOpt.Contains("brakdown:")) {
10715 TString sOpt3(opt);
10716 poiName = sOpt3(sOpt3.Index("breakdown:") + 10, sOpt3.Length());
10717 } else {
10718 std::unique_ptr<RooAbsCollection> _poi(fr->floatParsFinal().selectByAttrib("poi", true));
10719 if (_poi->empty()) {
10720 throw std::runtime_error("No floating poi in the fit");
10721 } else if (_poi->size() != 1) {
10722 throw std::runtime_error("Multiple poi in the fit");
10723 }
10724 poiName = _poi->first()->GetName();
10725 }
10726 RooRealVar *poi = dynamic_cast<RooRealVar *>(fr->floatParsFinal().find(poiName.c_str()));
10727 if (!poi) {
10728 throw std::runtime_error(TString::Format("Cannot find parameter %s", poiName.c_str()));
10729 }
10730 std::set<std::string> groups;
10731 for (auto p : fr->floatParsFinal()) {
10732 if (p == poi) {
10733 continue;
10734 } else if (p->getStringAttribute("group")) {
10735 groups.insert(p->getStringAttribute("group"));
10736 } else {
10737 groups.insert(p->GetTitle());
10738 }
10739 }
10740
10741 auto roundedVal = xRooFit::matchPrecision(std::pair(poi->getVal(), poi->getError()));
10742
10743 TPie *pie = new TPie(TString::Format("breakdown:%s", poi->GetName()),
10744 TString::Format("%s: %g #pm %g", poi->GetTitle(), roundedVal.first, roundedVal.second),
10745 groups.size() + 1);
10746
10747 // for display of errors will go to one extra dp ...
10748 roundedVal.second *= .1;
10749
10750 // do breakdown by removing parameters in blocks according to groups and seeing impact on variance
10751 // this will give the correct sum but will be order-dependent if there are correlations between
10752 // groups. therefore we will stick with group-by-group
10753 // RooArgList pars(fr->floatParsFinal()); // pars to not condition on
10754 // double variance = pow(dynamic_cast<RooRealVar*>(poi)->getError(),2);
10755 int i = 0;
10756 for (auto group : groups) {
10757 RooArgList pars(fr->floatParsFinal()); // pars to not condition on
10758 double variance = pow(dynamic_cast<RooRealVar *>(poi)->getError(), 2);
10759 for (auto p : fr->floatParsFinal()) {
10760 if (p == poi) {
10761 continue;
10762 } else if ((p->getStringAttribute("group") && group == p->getStringAttribute("group")) ||
10763 (!p->getStringAttribute("group") && group == p->GetTitle())) {
10764 // conditioning on this parameter ... remove from pars list
10765 pars.remove(*p);
10766 }
10767 }
10768 int idx = pars.index(poiName.c_str());
10769 double reducedVar = fr->conditionalCovarianceMatrix(pars)(idx, idx);
10770 if (reducedVar > variance) {
10771 Warning("Draw", "breakdown group %s variance bigger than preceding?", group.c_str());
10772 pie->SetEntryVal(i, 0);
10773 pie->SetEntryLabel(i, TString::Format("%s: NaN", group.c_str()));
10774 } else {
10775 pie->SetEntryVal(i, variance - reducedVar);
10777 std::pair(sqrt(variance - reducedVar), roundedVal.second)); // r.first will be the rounded error
10778 if (r.first > 0) {
10779 pie->SetEntryLabel(i, TString::Format("%s: %g", group.c_str(), r.first));
10780 } else {
10781 pie->SetEntryLabel(i, group.c_str()); // suppress labels for negligible errors.
10782 }
10783 }
10785 // variance = reducedVar;
10786 i++;
10787 }
10788 // remaining variance is statistical=
10789 double variance = fr->conditionalCovarianceMatrix(*poi)(0, 0);
10790 auto r =
10791 xRooFit::matchPrecision(std::pair(sqrt(variance), roundedVal.second)); // r.first will be the rounded error
10792 pie->SetEntryVal(i, variance);
10793 pie->SetEntryLabel(i, TString::Format("stat: %g", r.first));
10795 pie->SetBit(kCanDelete);
10796 pie->SetRadius(0.17);
10798 pie->Draw("NOL");
10799 return;
10800 }
10801
10802 // plot pull or impact
10804 out->SetName(TString::Format("%s_pull", fr->GetName()));
10805 out->SetTitle("Fit Result Pulls");
10806 std::vector<TString> graphLabels;
10808 ugraph->SetName(TString::Format("%s_pull_unconstrained", fr->GetName()));
10809 ugraph->SetTitle("Fit Result Pulls");
10810 std::vector<TString> ugraphLabels;
10811 std::map<std::string, double> scale;
10812 std::map<std::string, double> offset;
10813 for (auto &p : fr->floatParsFinal()) {
10814 auto _v = dynamic_cast<RooRealVar *>(p);
10815 if (!_v)
10816 continue;
10817
10818 if (std::isnan(_v->getErrorHi()) || std::isnan(_v->getErrorLo())) {
10819 Warning("Draw", "%s error is invalid", _v->GetName());
10820 }
10821
10822 // need to get constraint mean and error parameters ....
10823 // look for normal gaussian and poisson cases
10824 double prefitError = 0;
10825 double prefitVal = 0;
10826 double customScale = 0;
10827 if (auto ip =
10828 dynamic_cast<RooRealVar *>(fr->floatParsInit().find(p->GetName()))) { // handles if no prefit available
10829 prefitError = ip->getError();
10830 prefitVal = ip->getVal();
10831 };
10832
10833 std::shared_ptr<xRooNode> pConstr;
10834 if (fParent && fParent->getObject<RooRealVar>(p->GetName())) {
10835 auto _vv = fParent->getObject<RooRealVar>(p->GetName());
10836 if (_vv->hasRange("pullScale")) {
10837 customScale = (_vv->getMax("pullScale") - _vv->getMin("pullScale")) / 2.;
10838 }
10839 auto _constr = xRooNode(_vv, *this).constraints();
10840 for (auto &c : _constr) {
10841 if (c->get<RooPoisson>() || c->get<RooGaussian>()) {
10842 // require parameter to be a direct server of the constraint pdf to count if its a gaussian
10843 bool isServer = true;
10844 if (c->get<RooGaussian>()) {
10845 isServer = false;
10846 for (auto s : c->get<RooAbsArg>()->servers()) {
10847 if (strcmp(s->GetName(), p->GetName()) == 0) {
10848 isServer = true;
10849 break;
10850 }
10851 }
10852 }
10853 if (isServer) {
10854 pConstr = c;
10855 break;
10856 }
10857 }
10858 }
10859 }
10860 if (pConstr) {
10861
10862 // there will be 3 deps, one will be this par, the other two are the mean and error (or error^2 in case of
10863 // poisson
10864
10865 // std::cout << p->GetName() << " extracted " << prefitVal << " " << prefitError << " from ";
10866 // pConstr->deps().Print();
10867 pConstr->browse();
10868 if (pConstr->get<RooPoisson>() && pConstr->find(".x")) {
10869 std::string xName = pConstr->find(".x")->get()->GetName();
10870 prefitVal = pConstr->find(".x")->get<RooAbsReal>()->getVal();
10871 for (auto &_d : pConstr->vars()) {
10872 if (strcmp(p->GetName(), _d->get()->GetName()) == 0)
10873 continue;
10874 if (xName == _d->get()->GetName())
10875 continue;
10876 if (_d->get<RooAbsReal>()->getVal())
10877 prefitError = _d->get<RooAbsReal>()->getVal();
10878 }
10879 if (fr->constPars().find(pConstr->find(".x")->get()->GetName())) {
10880 // globs was saved to fr, use that instead of current value
10881 prefitVal = fr->constPars().getRealValue(pConstr->find(".x")->get()->GetName());
10882 }
10883 // prefitVal will be the global observable value, need to divide that by tau
10884 prefitVal /= prefitError;
10885 // prefiterror will be tau ... need 1/sqrt(tau) for error
10886 prefitError = 1. / sqrt(prefitError);
10887 } else if (auto _g = pConstr->get<RooGaussian>(); _g) {
10888 prefitError =
10889 (pConstr->find(".sigma")) ? pConstr->find(".sigma")->get<RooAbsReal>()->getVal() : prefitError;
10890 prefitVal =
10891 (pConstr->find(".x")) ? pConstr->find(".x")->get<RooAbsReal>()->getVal() : 0; // usually the globs
10892 if (pConstr->find(".x") && fr->constPars().find(pConstr->find(".x")->get()->GetName())) {
10893 // globs was saved to fr, use that instead of current value
10894 prefitVal = fr->constPars().getRealValue(pConstr->find(".x")->get()->GetName());
10895 }
10896 if (pConstr->find(".x") &&
10897 strcmp(p->GetName(), pConstr->find(".x")->get<RooAbsReal>()->GetName()) == 0) {
10898 // hybrid construction case,
10899 prefitVal = pConstr->find(".mean")->get<RooAbsReal>()->getVal();
10900 if (fr->constPars().find(pConstr->find(".mean")->get()->GetName())) {
10901 // globs was saved to fr, use that instead of current value
10902 prefitVal = fr->constPars().getRealValue(pConstr->find(".mean")->get()->GetName());
10903 }
10904 }
10905 }
10906
10907 if (customScale)
10908 prefitError = customScale;
10909 if (prefitError == 0) {
10910 Warning("Draw", "failed to determine prefit error of %s, using post-fit error", p->GetName());
10911 prefitError = _v->getError();
10912 }
10913 out->SetPoint(out->GetN(), out->GetN(), (_v->getVal() - prefitVal) / prefitError);
10914 out->SetPointError(out->GetN() - 1, 0, 0, (-_v->getErrorLo()) / prefitError,
10915 (_v->getErrorHi()) / prefitError);
10916 graphLabels.push_back(p->GetName());
10917 scale[p->GetName()] = prefitError;
10918 offset[p->GetName()] = prefitVal;
10919 } else if (!fParent) {
10920 // no parent to determine constraints from ... prefitError=0 will be the unconstrained ones
10921 if (customScale)
10922 prefitError = customScale;
10923 if (prefitError == 0) {
10924 // uses range of var
10925 prefitError = (std::max({_v->getMax() - _v->getVal(), _v->getVal() - _v->getMin(), 4.}) / 4);
10926 ugraph->SetPoint(ugraph->GetN(), ugraph->GetN(), (_v->getVal() - prefitVal) / prefitError);
10927 ugraph->SetPointError(ugraph->GetN() - 1, 0, 0, (-_v->getErrorLo()) / prefitError,
10928 (_v->getErrorHi()) / prefitError);
10929 ugraphLabels.push_back(p->GetName());
10930 } else {
10931 out->SetPoint(out->GetN(), out->GetN(), (_v->getVal() - prefitVal) / prefitError);
10932 out->SetPointError(out->GetN() - 1, 0, 0, (-_v->getErrorLo()) / prefitError,
10933 (_v->getErrorHi()) / prefitError);
10934 graphLabels.push_back(p->GetName());
10935 }
10936 scale[p->GetName()] = prefitError;
10937 offset[p->GetName()] = prefitVal;
10938
10939 } else {
10940 // unconstrained (or at least couldn't determine constraint) ... use par range if no prefit error
10941 if (customScale)
10942 prefitError = customScale;
10943 if (prefitError == 0) {
10944 prefitError = (std::max({_v->getMax() - _v->getVal(), _v->getVal() - _v->getMin(), 4.}) / 4);
10945 }
10946 ugraph->SetPoint(ugraph->GetN(), ugraph->GetN(), (_v->getVal() - prefitVal) / prefitError);
10947 ugraph->SetPointError(ugraph->GetN() - 1, 0, 0, (-_v->getErrorLo()) / prefitError,
10948 (_v->getErrorHi()) / prefitError);
10949 ugraphLabels.push_back(p->GetName());
10950 scale[p->GetName()] = prefitError;
10951 offset[p->GetName()] = prefitVal;
10952 }
10953 }
10954 auto graph = out;
10955
10956 // append ugraph points to end of graph
10957 for (int i = 0; i < ugraph->GetN(); i++)
10958 ugraph->SetPointX(i, i + graph->GetN());
10959 int nUnconstrained = ugraph->GetN();
10960 TList tmpList;
10961 tmpList.SetName("tmpList");
10962 tmpList.Add(ugraph);
10963 graph->Merge(&tmpList);
10964 tmpList.RemoveAll();
10965 delete ugraph;
10966 for (auto &l : ugraphLabels) {
10967 graphLabels.push_back(l);
10968 }
10969
10970 graph->SetBit(kCanDelete);
10971 graph->SetMarkerStyle(20);
10972 graph->SetMarkerSize(0.5);
10973
10974 graph->SetMaximum(4);
10975 graph->SetMinimum(-4);
10976
10977 bool doHorizontal =
10978 (!sOpt.Contains("impact") && sOpt.Contains("v")) || (sOpt.Contains("impact") && !sOpt.Contains("himpact"));
10979
10980 std::vector<std::pair<double, std::string>> covariances;
10981 /*double poiError = 0;*/ std::string poiName;
10982 double maxImpact = 0;
10983 if (sOpt.Contains("impact")) {
10984 if (sOpt.Contains("impact:")) {
10985 TString sOpt3(opt);
10986 poiName = sOpt3(sOpt3.Index("impact:") + 7, sOpt3.Length());
10987 } else {
10988 std::unique_ptr<RooAbsCollection> _poi(fr->floatParsFinal().selectByAttrib("poi", true));
10989 if (_poi->empty()) {
10990 throw std::runtime_error("No floating poi in the fit");
10991 } else if (_poi->size() != 1) {
10992 throw std::runtime_error("Multiple poi in the fit");
10993 }
10994 poiName = _poi->first()->GetName();
10995 }
10996 RooAbsArg *poi = fr->floatParsFinal().find(poiName.c_str());
10997 if (!poi) {
10998 throw std::runtime_error(TString::Format("Cannot find parameter %s", poiName.c_str()));
10999 }
11000 size_t poiIdx = fr->floatParsFinal().index(*poi);
11001 // put parameters in order of impact on the poi
11002
11003 // impact is regression coefficient * npError
11004 // relevant regression coefficient is cov / (npVariance)
11005 // i.e. DeltaX/sigmaX = [cov(X,Y)/(sigmaXsigmaY)]DeltaY/sigmaY
11006 // ... DeltaX = [cov(X,Y)/(sigmaY^2)]DeltaY
11007 // if DeltaY is just sigmaY then DeltaX = cov(X,Y)/sigmaY
11008
11009 for (auto &label : graphLabels) {
11010 covariances.emplace_back(fr->covarianceMatrix()(poiIdx, fr->floatParsFinal().index(label)) /
11011 dynamic_cast<RooRealVar *>(fr->floatParsFinal().find(label))->getError(),
11012 label);
11013 }
11014 std::sort(covariances.begin(), covariances.end(),
11015 [&](std::pair<double, std::string> i, std::pair<double, std::string> j) {
11016 return doHorizontal ? (std::abs(i.first) < std::abs(j.first))
11017 : (std::abs(i.first) > std::abs(j.first));
11018 });
11019
11020 TGraphAsymmErrors sortedGraph;
11021 std::vector<TString> sortedLabels;
11022 maxImpact = (doHorizontal) ? covariances.back().first
11023 : covariances.front().first; // note: max impact is likely to be self variance
11024 for (auto &c : covariances) {
11025 if (c.second == poi->GetName()) {
11026 // poiError = sqrt(c.first);
11027 continue; // skip self
11028 }
11029 c.first *= 4. / (maxImpact * 1.2);
11030 sortedLabels.push_back(c.second);
11031 size_t i = 0;
11032 for (; i < graphLabels.size(); i++) {
11033 if (graphLabels[i] == c.second) {
11034 break;
11035 }
11036 }
11037 sortedGraph.AddPoint(sortedGraph.GetN(), graph->GetPointY(i));
11038 sortedGraph.SetPointError(sortedGraph.GetN() - 1, 0, 0, graph->GetErrorYlow(i), graph->GetErrorYhigh(i));
11039 }
11040 graph->Set(0);
11041 TList tmpList2;
11042 tmpList2.SetName("tmpList");
11043 tmpList2.Add(&sortedGraph);
11044 graph->Merge(&tmpList2);
11045 tmpList2.RemoveAll();
11046 graphLabels = sortedLabels;
11047 graph->SetTitle("Fit Result Impact");
11048 }
11049
11050 // create a framing histogram
11051 TH2D *hist;
11052 if (doHorizontal) {
11053 hist = new TH2D(GetName(), fr->GetTitle(), 100, -4, 4, std::max(graph->GetN(), 1), -0.5,
11054 std::max(graph->GetN(), 1) - 0.5);
11055 int i = 1;
11056 for (auto &l : graphLabels) {
11057 hist->GetYaxis()->SetBinLabel(i++, l);
11058 }
11059 if (!graphLabels.empty())
11060 hist->GetYaxis()->LabelsOption("v");
11061 hist->GetXaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}");
11062 } else {
11063 hist = new TH2D(GetName(), fr->GetTitle(), std::max(graph->GetN(), 1), -0.5, std::max(graph->GetN(), 1) - 0.5,
11064 100, -4, 4);
11065 int i = 1;
11066 for (auto &l : graphLabels) {
11067 hist->GetXaxis()->SetBinLabel(i++, l);
11068 }
11069 if (!graphLabels.empty())
11070 hist->GetXaxis()->LabelsOption("v");
11071 hist->GetYaxis()->SetNdivisions(8, 0, 0);
11072 hist->GetYaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}");
11073 }
11074 hist->SetStats(false);
11075 hist->SetDirectory(nullptr);
11076 hist->SetBit(kCanDelete);
11077 auto histCopy = dynamic_cast<TH1 *>(hist->Clone(".axis"));
11078 histCopy->SetDirectory(nullptr);
11079 histCopy->SetBit(kCanDelete);
11080 auto _axis = (doHorizontal ? histCopy->GetYaxis() : histCopy->GetXaxis());
11081
11082 graph->GetHistogram()->GetXaxis()->Set(std::max(graph->GetN(), 1), -0.5, std::max(graph->GetN(), 1) - 0.5);
11083 for (int ii = 1; ii <= _axis->GetNbins(); ii++) {
11084 graph->GetHistogram()->GetXaxis()->SetBinLabel(ii, _axis->GetBinLabel(ii));
11085 }
11086 // int i = 1;
11087 // for (auto &l : graphLabels) {
11088 // hist->GetXaxis()->SetBinLabel(i++, l);
11089 // }
11090 // hist->SetMaximum(4);
11091 // hist->SetMinimum(-4);
11092 // if (graph->GetN())
11093 // hist->GetXaxis()->LabelsOption("v");
11094 // hist->GetYaxis()->SetNdivisions(8, 0, 0);
11095 // hist->GetYaxis()->SetTitle("(#hat{#theta}-#theta_{i})/#sigma_{i}");
11096 clearPad();
11097 // create a new pad because adjust the margins ...
11098 auto oldPad = gPad;
11099 gPad->Divide(1, 1, 1e-9, 1e-9);
11100 gPad->cd(1);
11101
11102 if (doHorizontal) {
11103 gPad->SetLeftMargin(0.4);
11104 } else {
11105 gPad->SetBottomMargin(0.4);
11106 }
11107
11108 auto pNamesHist = dynamic_cast<TH1F *>(graph->GetHistogram()->Clone("scales")); // used by interactive "pull" plot
11109 pNamesHist->Sumw2();
11110 pNamesHist->SetDirectory(nullptr);
11111
11112 for (int ii = 1; ii <= graph->GetN(); ii++) { // use graph->GetN() to protect against the 0 pars case
11113 auto _p = fr->floatParsFinal().find(_axis->GetBinLabel(ii));
11114 pNamesHist->SetBinContent(ii, offset[_p->GetName()]);
11115 pNamesHist->SetBinError(ii, scale[_p->GetName()]);
11116 _axis->SetBinLabel(ii, strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName());
11117 }
11118
11119 // hist->Draw(); -- now just draw the graph
11120
11121 if (!sOpt.Contains("impact")) {
11122 for (int ii = 2; ii >= 1; ii--) {
11123 auto pullBox = new TGraphErrors;
11124 pullBox->SetName(TString::Format("%dsigmaBand", ii));
11125 pullBox->SetBit(kCanDelete);
11126 pullBox->SetPoint(0, (doHorizontal) ? -ii : -0.5, (doHorizontal) ? -0.5 : 0);
11127 pullBox->SetPoint(1, (doHorizontal) ? ii : (_axis->GetNbins() - 0.5 - nUnconstrained),
11128 (doHorizontal) ? -0.5 : 0);
11129 pullBox->SetPointError(0, 0, (doHorizontal) ? (_axis->GetNbins() - nUnconstrained) : ii);
11130 pullBox->SetPointError(1, 0, (doHorizontal) ? (_axis->GetNbins() - nUnconstrained) : ii);
11131 pullBox->SetFillColor((ii == 2) ? kYellow : kGreen);
11132 hist->GetListOfFunctions()->Add(pullBox, "3"); // pullBox->Draw("3");
11133 }
11134 auto pullLine = new TGraph;
11135 pullLine->SetName("0sigmaLine");
11136 pullLine->SetBit(kCanDelete);
11137 pullLine->SetPoint(0, -0.5, 0);
11138 pullLine->SetPoint(1, _axis->GetNbins() - 0.5, 0);
11139 pullLine->SetLineStyle(2);
11140 pullLine->SetEditable(false);
11141 hist->GetListOfFunctions()->Add(pullLine, "l"); // pullLine->Draw("l");
11142
11143 // also draw vertical line separating constrained from unconstrained, if necessary
11144 if (nUnconstrained > 0) {
11145 pullLine = new TGraph;
11146 pullLine->SetName("dividerLine");
11147 pullLine->SetBit(kCanDelete);
11148 pullLine->SetPoint(0, graph->GetN() - 0.5 - nUnconstrained, -100);
11149 pullLine->SetPoint(1, graph->GetN() - 0.5 - nUnconstrained, 100);
11150 pullLine->SetLineStyle(2);
11151 pullLine->SetEditable(false);
11152 hist->GetListOfFunctions()->Add(pullLine, "l"); // pullLine->Draw("l");
11153 }
11154
11155 // and draw a pave with fr status info
11156 TPaveText *pave =
11157 new TPaveText(gPad->GetLeftMargin(), 1. - gPad->GetTopMargin(), 1. - gPad->GetRightMargin(), 0.98, "NDCNB");
11158 pave->SetFillStyle(0);
11159 pave->SetBorderSize(0);
11160 pave->SetMargin(0.);
11161 pave->SetName("status");
11162 pave->SetTextAlign(31);
11163 pave->AddText(TString::Format("minNLL: %g edm: %g", fr->minNll(), fr->edm()))
11164 ->SetTextColor((fr->status() == 3) ? kRed : kBlack);
11165 std::string covQualTxt;
11166 switch (fr->covQual()) {
11167 case -1: covQualTxt = "Unknown"; break;
11168 case 0: covQualTxt = "Not calculated"; break;
11169 case 1: covQualTxt = "Approximate"; break;
11170 case 2: covQualTxt = "Forced Positive-Definite"; break;
11171 case 3: covQualTxt = "Accurate"; break;
11172 }
11173 pave->AddText(TString::Format("Cov. Quality: %d (%s)", fr->covQual(), covQualTxt.c_str()))
11174 ->SetTextColor((fr->covQual() == 3) ? kBlack : kRed);
11175
11176 std::string statusCodes;
11177 for (unsigned int i = 0; i < fr->numStatusHistory(); i++) {
11178 statusCodes += TString::Format(" %s = %d", fr->statusLabelHistory(i), fr->statusCodeHistory(i));
11179 }
11180 pave->AddText(statusCodes.c_str())->SetTextColor(fr->status() == 0 ? kBlack : kRed);
11181
11182 hist->GetListOfFunctions()->Add(pave);
11183
11184 } else {
11185 gPad->SetTicks(0, 0); // ensure mirrored ticks aren't drawn in this pad
11186
11187 if (doHorizontal) {
11188 // ensure canvas height big enough
11189 if (int(gPad->GetCanvas()->GetWh()) < pNamesHist->GetNbinsX() * 15) {
11190 gPad->GetCanvas()->SetCanvasSize(gPad->GetCanvas()->GetWw(), pNamesHist->GetNbinsX() * 15);
11191 }
11192 }
11193
11194 double factor = 475. / gPad->GetCanvas()->GetWh(); // Wh is the full canvas height, not window height
11195 gPad->SetTopMargin(gStyle->GetPadTopMargin() * factor); // fixed margin height
11196 gPad->SetBottomMargin(gStyle->GetPadBottomMargin() * factor); // fixed margin height
11197
11198 TGaxis *axis =
11199 new TGaxis(_axis->GetXmin(), -4, _axis->GetXmin(), 4, -1.2 * maxImpact, 1.2 * maxImpact, 510, "-S");
11200
11201 if (doHorizontal) {
11202 // _axis->SetLabelSize(
11203 // (_axis->GetLabelFont() % 10 > 2)
11204 // ? (20 / factor)
11205 // : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(20 / factor)) / (gPad->GetY2() -
11206 // gPad->GetY1())));
11207 // histCopy->GetXaxis()->SetTickLength(histCopy->GetXaxis()->GetTickLength() * factor);
11208 // hist->GetXaxis()->SetTickLength(hist->GetXaxis()->GetTickLength() * factor);
11209 // histCopy->GetYaxis()->SetTickLength(histCopy->GetYaxis()->GetTickLength() * factor);
11210 // hist->GetYaxis()->SetTickLength(hist->GetYaxis()->GetTickLength() * factor);
11211 // histCopy->GetXaxis()->SetTitleOffset(histCopy->GetXaxis()->GetTitleOffset() * factor);
11212 // histCopy->GetXaxis()->SetLabelOffset(histCopy->GetXaxis()->GetLabelOffset() * factor);
11213 // hist->GetXaxis()->SetTitleOffset(hist->GetXaxis()->GetTitleOffset() * factor);
11214 // hist->GetXaxis()->SetLabelOffset(hist->GetXaxis()->GetLabelOffset() * factor);
11215 // histCopy->GetXaxis()->SetTitleOffset(histCopy->GetXaxis()->GetTitleOffset() * factor);
11216 // histCopy->GetXaxis()->SetLabelOffset(histCopy->GetXaxis()->GetLabelOffset() * factor);
11217 }
11218 // copy attributes from TAxis to TGaxis
11219 axis->ImportAxisAttributes((doHorizontal) ? histCopy->GetXaxis() : histCopy->GetYaxis());
11220 axis->SetTitle(TString::Format("#Delta %s", fr->floatParsFinal().find(poiName.c_str())->GetTitle()));
11221
11222 // create impact bar charts
11223 for (int tt = 0; tt < 2; tt++) {
11224 auto impact = static_cast<TH1 *>(
11225 graph->GetHistogram()->Clone(TString::Format("%s_impact+", tt == 0 ? "prefit" : "postfit")));
11226 impact->SetDirectory(nullptr);
11227 impact->GetYaxis()->SetTitle(TString::Format("#Delta%s/#sigma", poiName.c_str()));
11228 impact->SetBarWidth(0.9);
11229 impact->SetBarOffset(0.05);
11230 impact->SetLineColor(kBlack);
11231 impact->SetFillColor(kAzure - 4);
11232 impact->SetFillStyle(tt == 0 ? 3013 : 1001);
11233 auto impact2 =
11234 static_cast<TH1 *>(impact->Clone(TString::Format("%s_impact-", tt == 0 ? "prefit" : "postfit")));
11235 impact2->SetDirectory(nullptr);
11236 impact2->SetFillColor(kCyan);
11237 for (int ii = 1; ii <= pNamesHist->GetNbinsX(); ii++) {
11238 for (auto &c : covariances) {
11239 if (c.second != pNamesHist->GetXaxis()->GetBinLabel(ii))
11240 continue;
11241 auto vv = dynamic_cast<RooRealVar *>(fr->floatParsFinal().find(c.second.c_str()));
11242 auto vv_init = dynamic_cast<RooRealVar *>(fr->floatParsInit().find(c.second.c_str()));
11243 impact->SetBinContent(ii, ((tt == 0 && !vv_init->hasError()) || !vv->hasError())
11244 ? 0.
11245 : c.first * vv->getError() / vv->getErrorHi() *
11246 (tt == 0 ? (vv_init->getErrorHi() / vv->getErrorHi()) : 1.));
11247 impact2->SetBinContent(ii, ((tt == 0 && !vv_init->hasError()) || !vv->hasError())
11248 ? 0.
11249 : c.first * vv->getError() / vv->getErrorLo() *
11250 (tt == 0 ? (vv_init->getErrorLo() / vv->getErrorLo()) : 1.));
11251 }
11252 }
11253 hist->GetListOfFunctions()->Add(impact, (doHorizontal) ? "hbarsamemin0" : "bsamey+");
11254 hist->GetListOfFunctions()->Add(impact2, (doHorizontal) ? "hbarsamemin0" : "bsamey+");
11255 }
11256 // add three lines
11257 for (int ii = -1; ii <= 1; ii++) {
11258 auto pullLine = new TGraph;
11259 pullLine->SetName(TString::Format("%dsigmaLine", ii));
11260 pullLine->SetBit(kCanDelete);
11261 pullLine->SetPoint(0, -0.5, ii);
11262 pullLine->SetPoint(1, hist->GetNbinsY() - 0.5, ii);
11263 pullLine->SetLineStyle(2);
11264 pullLine->SetEditable(false);
11265 hist->GetListOfFunctions()->Add(pullLine, "l");
11266 }
11267 hist->GetListOfFunctions()->Add(axis); // draw axis last
11268 TLegend *leg1 =
11269 new TLegend(0.02, doHorizontal ? (1. - 0.22 * factor) : 0.02, 0.27, (doHorizontal ? 1. : 0.24));
11270 leg1->SetFillStyle(0);
11271 leg1->SetBorderSize(0);
11272 leg1->SetMargin(0.25);
11273 leg1->SetNColumns(2);
11274
11275 leg1->SetTextSize(_axis->GetLabelSize());
11276 leg1->SetTextFont(_axis->GetLabelFont());
11277 leg1->AddEntry((TObject *)nullptr, "Hessian Pre-fit", "");
11278 leg1->AddEntry((TObject *)nullptr, "Impact:", "");
11279 leg1->AddEntry(hist->FindObject("prefit_impact+"), "#theta = #hat{#theta}+#Delta#theta", "f");
11280 leg1->AddEntry(hist->FindObject("prefit_impact-"), "#theta = #hat{#theta}-#Delta#theta", "f");
11281 leg1->AddEntry((TObject *)nullptr, "Hessian Post-fit", "");
11282 leg1->AddEntry((TObject *)nullptr, "Impact:", "");
11283 leg1->AddEntry(hist->FindObject("postfit_impact+"), "#theta = #hat{#theta}+#Delta#theta", "f");
11284 leg1->AddEntry(hist->FindObject("postfit_impact-"), "#theta = #hat{#theta}-#Delta#theta", "f");
11285
11286 hist->GetListOfFunctions()->Add(leg1);
11287 if (gStyle->GetOptTitle()) {
11288 histCopy->SetBit(TH1::kNoTitle);
11289 TPaveText *title =
11290 new TPaveText(gPad->GetLeftMargin(), 1. - gPad->AbsPixeltoY(14), 1. - gPad->GetRightMargin(), 1., "NDC");
11291 title->ConvertNDCtoPad();
11292 title->SetY1NDC(1. - gPad->GetTopMargin() * 0.6);
11293 title->SetY2NDC(1);
11294 title->SetTextSize(
11295 (title->GetTextFont() % 10 > 2)
11296 ? (14 / factor)
11297 : ((gPad->AbsPixeltoY(0) - gPad->AbsPixeltoY(10 / factor)) / (gPad->GetY2() - gPad->GetY1())));
11298 title->SetFillStyle(0);
11299 title->SetBorderSize(0);
11300 title->AddText(histCopy->GetTitle());
11301 hist->GetListOfFunctions()->Add(title);
11302 }
11303 }
11304
11305 graph->SetEditable(false);
11306 pNamesHist->SetLineWidth(0);
11307 pNamesHist->SetMarkerSize(0);
11308 pNamesHist->SetMarkerStyle(0);
11309 graph->GetListOfFunctions()->Add(pNamesHist, "same"); // graph->SetHistogram(pNamesHist);
11310 if (doHorizontal) {
11311
11312 // flip the graph and contained graphs
11313 for (int p = 0; p < graph->GetN(); p++) {
11314 graph->SetPoint(p, graph->GetPointY(p), graph->GetPointX(p));
11315 graph->SetPointError(p, graph->GetErrorYlow(p), graph->GetErrorYhigh(p), graph->GetErrorXlow(p),
11316 graph->GetErrorXhigh(p));
11317 }
11318 for (auto f : *hist->GetListOfFunctions()) {
11319 if (f->InheritsFrom("TH1")) {
11320 // f->Draw("hbarsamemin0");
11321 } /*else if (auto g2 = dynamic_cast<TGraphErrors *>(f)) {
11322 for (int p = 0; p < g2->GetN(); p++) {
11323 g2->SetPoint(p, g2->GetPointY(p), g2->GetPointX(p));
11324 g2->SetPointError(p, g2->GetErrorY(p), _axis->GetNbins());
11325 }
11326 //g2->Draw("3");
11327 } */
11328 else if (auto g = dynamic_cast<TGraph *>(f)) {
11329 for (int p = 0; p < g->GetN(); p++) {
11330 g->SetPoint(p, g->GetPointY(p), g->GetPointX(p));
11331 }
11332 // g->Draw("l");
11333 } else if (auto l = dynamic_cast<TLine *>(f)) {
11334 l->SetX1(l->GetY1());
11335 l->SetX2(l->GetY2());
11336 l->SetY1(_axis->GetXmax());
11337 l->SetY2(_axis->GetXmax());
11338 // l->Draw();
11339 }
11340 }
11341 }
11342
11343 if (!sOpt.Contains("impact")) {
11344 // add labels to graph for unconstrained parameters
11345 for (size_t i = 0; i < ugraphLabels.size(); i++) {
11346 int bin = pNamesHist->GetNbinsX() - ugraphLabels.size() + i + 1;
11347 auto p = dynamic_cast<RooRealVar *>(fr->floatParsFinal().find(pNamesHist->GetXaxis()->GetBinLabel(bin)));
11348 if (!p)
11349 continue;
11350 auto x = graph->GetPointX(graph->GetN() - ugraphLabels.size() + i);
11351 auto y = graph->GetPointY(graph->GetN() - ugraphLabels.size() + i) +
11352 graph->GetErrorYhigh(graph->GetN() - ugraphLabels.size() + i);
11353 auto l = xRooFit::matchPrecision({p->getVal(), p->getError()});
11354 auto t = new TLatex(x, y, TString::Format("%g #pm %g", l.first, l.second));
11355 t->SetBit(kCanDelete);
11356 t->SetTextSize(0.025);
11357 t->SetTextAngle(90);
11358 graph->GetListOfFunctions()->Add(t);
11359 }
11360 }
11361
11362 graph->SetName("pulls");
11363 hist->GetListOfFunctions()->Add(graph, "z0p");
11364 // hist->GetListOfFunctions()->Add(histCopy->Clone(".axis"),(sOpt.Contains("impact") &&
11365 // !doHorizontal)?"axissamey+":"axissame"); // doesn't display right when zoom the axis
11366 if (!hasSame) {
11367 histCopy->Draw((sOpt.Contains("impact") && !doHorizontal)
11368 ? "axisy+"
11369 : "axis"); // draws the axis, called ".axis" for easy access
11370 }
11371 hist->Draw("same");
11372 //
11373 // if(sOpt.Contains("impact")) {
11374 // // make main object the histogram
11375 // auto h = (TH1*)graph->GetHistogram()->Clone("impact");
11376 // graph->GetListOfFunctions()->RemoveAll();
11377 // for(int ii=1;ii<=h->GetNbinsX();ii++) h->SetBinContent(ii,-4);
11378 // h->GetListOfFunctions()->Add(graph,"z0p");
11379 // h->Draw("hbar");
11380 // } else {
11381 // graph->Draw(sOpt.Contains("impact") ? "az0py+" : "az0p");
11382 // }
11383 auto hh = dynamic_cast<TH1 *>(histCopy->Clone(".axiscopy"));
11384 hh->SetDirectory(nullptr);
11385 hh->SetBit(kCanDelete);
11386 hh->Draw(
11387 (sOpt.Contains("impact") && !doHorizontal)
11388 ? "axissamey+"
11389 : "axissame"); // overlay axis again -- important is last so can remove if don't pad->Update before reclear
11390 gPad->Modified();
11391 oldPad->cd();
11392 // gPad->Update();
11393 return;
11394 }
11395
11396 if (get()->InheritsFrom("RooAbsData")) {
11397 auto s = parentPdf();
11398 if (s && s->get<RooSimultaneous>()) {
11399 // drawing dataset associated to a simultaneous means must find subpads with variation names
11400 // may not have subpads if drawning a "Yield" plot ...
11401 bool doneDraw = false;
11402 // in the case of hybrid datasets, the parentPdf will be a reducedPdf ...
11403 // but if the dataset has been added to, then there may be additional entries
11404 // in other channels ... so loop over all labels of the categorical
11405 // and for ones we don't have a channel for, just draw directly on
11406
11407 for (auto [catName, catVal] : s->get<RooSimultaneous>()->indexCat()) {
11408 auto _pad = dynamic_cast<TPad *>(gPad->GetPrimitive(
11409 TString::Format("%s=%s", s->get<RooSimultaneous>()->indexCat().GetName(), catName.c_str())));
11410 if (!_pad)
11411 continue; // channel was hidden?
11412 // attach as a child before calling datasets(), so that if this dataset is external to workspace it is
11413 // included still attaching the dataset ensures dataset reduction for the channel is applied
11414 auto tmp = gPad;
11415 _pad->cd();
11416 if (auto c = s->bins().find(catName)) {
11417 c->push_back(std::make_shared<xRooNode>(*this));
11418 auto ds = c->datasets().find(GetName());
11419 c->resize(c->size() - 1); // remove the child we attached
11420 if (!ds) {
11421 std::cout << " no ds " << GetName() << " - this should never happen!" << std::endl;
11422 continue;
11423 }
11424 ds->Draw(opt);
11425 } else {
11426 Draw(opt);
11427 }
11428 doneDraw = true;
11429 tmp->cd();
11430 }
11431 if (doneDraw) {
11432 gPad->Modified();
11433 return;
11434 }
11435 }
11436
11437 if (!s && hasSame) {
11438 // draw onto all subpads with = in the name
11439 // if has no such subpads, draw onto this pad
11440 bool doneDraw = false;
11441 for (auto o : *gPad->GetListOfPrimitives()) {
11442 if (auto p = dynamic_cast<TPad *>(o); p && TString(p->GetName()).Contains('=')) {
11443 auto _tmp = gPad;
11444 p->cd();
11445 Draw(opt);
11446 _tmp->cd();
11447 doneDraw = true;
11448 }
11449 }
11450 if (doneDraw) {
11451 gPad->Modified();
11452 return;
11453 }
11454 }
11455
11456 auto dataGraph = BuildGraph(v, false, (!s && hasSame) ? gPad : nullptr);
11457 if (!dataGraph)
11458 return;
11459
11460 dataGraph->SetBit(kCanDelete); // will be be deleted when pad is cleared
11461 dataGraph->SetMarkerSize(dataGraph->GetMarkerSize() * gPad->GetWNDC()); // scale marker sizes to pad size
11462
11463 if (s && !s->get<RooAbsPdf>()->canBeExtended()) {
11464 // normalize dataGraph to 1
11465 double tot = 0;
11466 for (int i = 0; i < dataGraph->GetN(); i++)
11467 tot += dataGraph->GetPointY(i);
11468 dataGraph->Scale(1. / tot);
11469 }
11470
11471 if (!hasSame) {
11472 clearPad();
11473 dataGraph->Draw("Az0p");
11474 addLegendEntry(dataGraph, strlen(dataGraph->GetTitle()) ? dataGraph->GetTitle() : GetName(), "pEX0");
11475 gPad->Modified();
11476 // gPad->Update();
11477 return;
11478 }
11479
11480 bool noPoint = false;
11481 if (v && dynamic_cast<RooAbsArg *>(v)->getAttribute("global") && dataGraph->GetN() == 1) {
11482 // global observable ... if graph has only 1 data point line it up on the histogram value
11483 for (auto o : *gPad->GetListOfPrimitives()) {
11484 if (auto h = dynamic_cast<TH1 *>(o);
11485 h && strcmp(h->GetXaxis()->GetName(), dynamic_cast<TObject *>(v)->GetName()) == 0) {
11486 dataGraph->SetPointY(0, h->Interpolate(dataGraph->GetPointX(0)));
11487 noPoint = true;
11488 break;
11489 }
11490 }
11491 }
11492
11493 if (auto _pad = dynamic_cast<TPad *>(gPad->FindObject("auxPad")); _pad) {
11494 if (auto h = dynamic_cast<TH1 *>(_pad->GetPrimitive("auxHist")); h) {
11495 TString histName = h->GetTitle(); // split it by | char
11496 TString histType = histName(histName.Index('|') + 1, histName.Length());
11497 histName = histName(0, histName.Index('|'));
11498 if (auto mainHist = dynamic_cast<TH1 *>(gPad->GetPrimitive(histName));
11499 mainHist && auxFunctions.find(h->GetYaxis()->GetTitle()) != auxFunctions.end()) {
11500 // decide what to do based on title of auxHist (previously used name of y-axis but that changed axis
11501 // behaviour) use title instead
11502 auto ratioGraph = dynamic_cast<TGraphAsymmErrors *>(dataGraph->Clone(dataGraph->GetName()));
11503 ratioGraph->SetBit(kCanDelete);
11504 for (int i = 0; i < ratioGraph->GetN(); i++) {
11505 double val = ratioGraph->GetPointY(i);
11506 int binNum = mainHist->FindFixBin(ratioGraph->GetPointX(i));
11507 double nom = mainHist->GetBinContent(binNum);
11508 double nomerr = mainHist->GetBinError(binNum);
11509 double yval =
11510 std::get<0>(auxFunctions[h->GetYaxis()->GetTitle()])(ratioGraph->GetPointY(i), nom, nomerr);
11511 double yup = std::get<0>(auxFunctions[h->GetYaxis()->GetTitle()])(val + ratioGraph->GetErrorYhigh(i),
11512 nom, nomerr) -
11513 yval;
11514 double ydown = yval - std::get<0>(auxFunctions[h->GetYaxis()->GetTitle()])(
11515 val - ratioGraph->GetErrorYlow(i), nom, nomerr);
11516 if (!std::isnan(yval)) {
11517 ratioGraph->SetPointY(i, yval);
11518 if (!std::isnan(yup))
11519 ratioGraph->SetPointEYhigh(i, yup);
11520 if (!std::isnan(ydown))
11521 ratioGraph->SetPointEYlow(i, ydown);
11522 }
11523 }
11524 // remove the zero points
11525 int i = 0;
11526 while (i < ratioGraph->GetN()) {
11527 if (ratioGraph->GetPointY(i) == 0 && ratioGraph->GetErrorYhigh(i) == 0 &&
11528 ratioGraph->GetErrorYlow(i) == 0) {
11529 ratioGraph->RemovePoint(i);
11530 } else {
11531 i++;
11532 }
11533 }
11534 auto _tmpPad = gPad;
11535 _pad->cd();
11536 ratioGraph->Draw("z0psame");
11537 auto minMax = graphMinMax(ratioGraph);
11538 adjustYRange(minMax.first, minMax.second, h, std::get<1>(auxFunctions[h->GetYaxis()->GetTitle()]));
11539 _tmpPad->cd();
11540 }
11541 }
11542 }
11543
11544 dataGraph->Draw("z0p same");
11545 addLegendEntry((noPoint) ? nullptr : dataGraph, strlen(dataGraph->GetTitle()) ? dataGraph->GetTitle() : GetName(),
11546 noPoint ? "" : "pEX0");
11547
11548 auto minMax = graphMinMax(dynamic_cast<TGraphAsymmErrors *>(dataGraph));
11549 adjustYRange(minMax.first, minMax.second);
11550
11551 gPad->Modified();
11552 // gPad->Update();
11553 return;
11554 }
11555
11556 // auto _ax = GetXaxis();
11557 // auto v = (_ax) ? dynamic_cast<RooRealVar*>(/*possibleObs.first()*/_ax->GetParent()) : nullptr;
11558 // if (!v) { v = get<RooRealVar>(); } // self-axis
11559 // if (!v) return;
11560
11561 if (auto lv = get<RooAbsLValue>(); lv && fParent && fParent->get<RooAbsData>()) {
11562 // drawing an observable from a dataset ... build graph, and exit
11563 auto gr = fParent->BuildGraph(lv, true);
11565 gr->Draw(hasSame ? "P" : "AP");
11566 return;
11567 }
11568
11569 if (forceNames != "") {
11570 // drawing a force plot ... build nll and fill a histogram with force terms
11571 auto _dsets = datasets();
11572 bool _drawn = false;
11573 auto _coords = coords();
11574 auto _fr = fitResult();
11575 auto initPar = dynamic_cast<RooRealVar *>(_fr.get<RooFitResult>()->floatParsInit().find(forceNames));
11576 if (!initPar)
11577 return;
11578 std::vector<double> valuesToDo = {initPar->getVal()};
11579 if (initPar->hasError() || initPar->hasAsymError()) {
11580 valuesToDo.push_back(initPar->getVal() + initPar->getErrorLo());
11581 valuesToDo.push_back(initPar->getVal() + initPar->getErrorHi());
11582 }
11583 int ii = 0;
11584 for (auto valueToDo : valuesToDo) {
11585 ii++;
11586 for (auto &d : _dsets) {
11587 if (!d->get()->TestBit(1 << 20))
11588 continue;
11589 auto emptyHist = BuildHistogram(v, true);
11590 emptyHist->SetBit(kCanDelete);
11591 auto _obs = d->obs();
11592 auto x = _obs.find((v) ? dynamic_cast<TObject *>(v)->GetName() : emptyHist->GetXaxis()->GetName());
11593 auto _nll = nll(d);
11594 auto theData = d->get<RooAbsData>();
11595 int nevent = theData->numEntries();
11596 for (int i = 0; i < nevent; i++) {
11597 theData->get(i);
11598 bool _skip = false;
11599 for (const auto &_c : _coords) {
11600 if (auto cat = _c->get<RooAbsCategoryLValue>(); cat) {
11601 if (cat->getIndex() != theData->get()->getCatIndex(cat->GetName())) {
11602 _skip = true;
11603 break;
11604 }
11605 }
11606 }
11607 if (_skip)
11608 continue;
11609
11610 if (x) {
11611 auto val = _nll.pars()->getRealValue(initPar->GetName());
11612 if (ii > 1)
11613 _nll.pars()->setRealValue(initPar->GetName(), valueToDo);
11614 auto nllVal = _nll.getEntryVal(i);
11615 _nll.pars()->setRealValue(initPar->GetName(), initPar->getVal());
11616 auto nllVal2 = _nll.getEntryVal(i);
11617 _nll.pars()->setRealValue(initPar->GetName(), val);
11618 emptyHist->Fill(x->get<RooAbsReal>()->getVal(), (nllVal2 - nllVal));
11619 }
11620 }
11621 // include the extendedTerm, distributed evenly over the bins
11622 // probably should be somehow dependent on data density though (i.e. bins with more data get more of it?)
11623 auto val = _nll.pars()->getRealValue(initPar->GetName());
11624 if (ii > 1)
11625 _nll.pars()->setRealValue(initPar->GetName(), valueToDo);
11626 auto _extTerm = _nll.extendedTermVal();
11627 _nll.pars()->setRealValue(initPar->GetName(), initPar->getVal());
11628 auto _extTerm2 = _nll.extendedTermVal();
11629 _nll.pars()->setRealValue(initPar->GetName(), val);
11630 for (int i = 1; i <= emptyHist->GetNbinsX(); i++) {
11631 emptyHist->SetBinContent(i,
11632 emptyHist->GetBinContent(i) + (_extTerm2 - _extTerm) / emptyHist->GetNbinsX());
11633 emptyHist->SetBinError(i, 0);
11634 }
11635 emptyHist->GetYaxis()->SetTitle("log (L(#theta)/L(#theta_{0}))");
11636 emptyHist->SetTitle(TString::Format("#theta = %g", (ii > 1) ? valueToDo : val));
11637 if (ii == 1)
11638 emptyHist->SetLineColor(kBlack);
11639 if (ii == 2) {
11640 emptyHist->SetLineColor(kRed);
11641 } else if (ii == 3) {
11642 emptyHist->SetLineColor(kBlue);
11643 }
11644 emptyHist->Draw(_drawn ? "same" : "");
11645 _drawn = true;
11646 }
11647 }
11648 return;
11649 }
11650
11651 auto rar = get<RooAbsReal>();
11652 const xRooNode *rarNode = this;
11653 if (!rar) {
11654 // draw a deleteable clone of the object we wrap (since we might own the object)
11655 get()->DrawClone(opt);
11656 return;
11657 }
11658 // RooAbsReal *sf = nullptr;
11659 if (get()->InheritsFrom("RooExtendPdf")) {
11660 browse();
11661 rarNode = find(".pdf").get();
11662 // rar = rarNode->get<RooAbsReal>();
11663 // sf = find(".n")->get<RooAbsReal>();
11664 }
11665
11666 if (!nostack && !hasOverlay &&
11667 (rarNode->get()->InheritsFrom("RooRealSumPdf") || rarNode->get()->InheritsFrom("RooAddPdf") ||
11668 (v && rarNode->get()->InheritsFrom("RooSimultaneous") &&
11669 strcmp(dynamic_cast<TObject *>(v)->GetName(), rarNode->get<RooSimultaneous>()->indexCat().GetName()) == 0))) {
11670 nostack = false;
11671 } else {
11672 // in all other cases, we do not build a stack
11673 nostack = true;
11674 }
11675
11676 auto h = BuildHistogram(v, false, hasErrorOpt, 1, 0, "", false, false, 0, nullptr, nostack, true /*setInterp*/);
11677 if (!h) {
11678 if (get()) {
11679 // draw a deleteable clone of the object we wrap (since we might own the object)
11680 get()->DrawClone(opt);
11681 }
11682 return;
11683 }
11685
11686 if (!v)
11687 v = getObject<RooAbsLValue>(h->GetXaxis()->IsAlphanumeric() ? h->GetXaxis()->GetTimeFormatOnly()
11688 : h->GetXaxis()->GetName())
11689 .get();
11690 RooAbsArg *vv = (v) ? dynamic_cast<RooAbsArg *>(v) : rar;
11691 if (h->GetXaxis()->IsAlphanumeric()) {
11692 // do this to get bin labels
11693 h->GetXaxis()->SetName("xaxis"); // WARNING -- this messes up anywhere we GetXaxis()->GetName()
11694 }
11695
11696 // get style now, before we mess with histogram title
11697 // auto _styleNode = styles(h);
11698
11699 if (rar->InheritsFrom("RooAbsPdf") && !(rar->InheritsFrom("RooRealSumPdf") || rar->InheritsFrom("RooAddPdf") ||
11700 rar->InheritsFrom("RooSimultaneous"))) {
11701 // append parameter values to title if has such
11702 RooArgSet s;
11703 rar->leafNodeServerList(&s);
11704 if (v)
11705 s.remove(*dynamic_cast<RooAbsArg *>(v));
11706 if (!s.empty()) {
11707 TString ss = h->GetTitle();
11708 ss += " [";
11709 bool first = true;
11710 for (auto _p : s) {
11711 auto _v = dynamic_cast<RooRealVar *>(_p);
11712 if (!_v)
11713 continue;
11714 if (!first)
11715 ss += ",";
11716 first = false;
11717 ss += TString::Format("%s=%g", strlen(_p->GetTitle()) ? _p->GetTitle() : _p->GetName(), _v->getVal());
11718 if (_v->hasError()) {
11719 ss += TString::Format("#pm %g", _v->getError());
11720 }
11721 }
11722 ss += "]";
11723 h->SetTitle(ss);
11724 }
11725 }
11726
11727 if (!hasSame) {
11728 if (obs().find(vv->GetName())) {
11729 gPad->SetGrid(0, 0);
11730 } else {
11731 gPad->SetGrid(1, 1);
11732 }
11733 }
11734 TString dOpt = h->GetOption();
11735 if (dOpt == "l")
11736 h->SetFillStyle(0);
11737 // // need to strip namespace to discount the "HistFactory" namespace classes from all being treated as binned
11738 // TString clNameNoNamespace = rar->ClassName();
11739 // clNameNoNamespace = clNameNoNamespace(clNameNoNamespace.Last(':') + 1, clNameNoNamespace.Length());
11740 // TString dOpt = (clNameNoNamespace.Contains("Hist") || vv->isCategory() || rar->isBinnedDistribution(*vv) ||
11741 // h->GetNbinsX() == 1 || rar->getAttribute("BinnedLikelihood") ||
11742 // (dynamic_cast<RooAbsRealLValue *>(vv) &&
11743 // std::unique_ptr<std::list<double>>(rar->binBoundaries(*dynamic_cast<RooAbsRealLValue *>(vv),
11744 // -std::numeric_limits<double>::infinity(),
11745 // std::numeric_limits<double>::infinity()))))
11746 // ? ""
11747 // : "LF2";
11748 // if (auto d = dynamic_cast<RooHistFunc *>(rar); d && !d->isBinnedDistribution(*vv) && h->GetNbinsX() != 1) {
11749 // dOpt = "LF2"; // hist func is interpolated, so draw it as such
11750 // }
11751 // if (dOpt == "LF2" && !components().empty()) {
11752 // // check if all components of dOpt are "Hist" type (CMS model support)
11753 // // if so then dOpt="";
11754 // bool allHist = true;
11755 // for (auto &s : components()) {
11756 // TString _clName = s->get()->ClassName();
11757 // _clName = _clName(_clName.Last(':') + 1, _clName.Length());
11758 // if (!(s->get() && _clName.Contains("Hist"))) {
11759 // allHist = false;
11760 // break;
11761 // }
11762 // }
11763 // if (allHist)
11764 // dOpt = "";
11765 // }
11766 //
11767 // if(dOpt=="LF2") {
11768 // // ensure any sub hists have lf2 option
11769 // TObjLink *lnk = h->GetListOfFunctions()->FirstLink();
11770 // while (lnk) {
11771 // if(auto hh = dynamic_cast<TH1*>(lnk->GetObject())) {
11772 // if(TString(hh->GetName())=="band" && TString(lnk->GetOption())=="e2same") {
11773 // lnk->SetOption("LF2 e3same");
11774 // } else if(TString(hh->GetName())=="nominal") {
11775 // lnk->SetOption("L same");
11776 // }
11777 // }
11778 // lnk = lnk->Next();
11779 // }
11780 // }
11781
11782 if (rar == vv && rar->IsA() == RooRealVar::Class()) {
11783 dOpt += "TEXT";
11784 // add a TExec to the histogram so that when edited it will propagate to var
11785 gROOT->SetEditHistograms(true);
11786 } else {
11787 gROOT->SetEditHistograms(false);
11788 }
11789
11790 if (hasSame) {
11791 dOpt += " same";
11792 } else {
11793 hAxis = h;
11794 }
11795
11796 if (dOpt.Contains("TEXT") || sOpt.Contains("text")) {
11797 // adjust marker size so text is good
11798 h->SetMarkerSize(gStyle->GetLabelSize("Z") / (0.02 * gPad->GetHNDC()));
11799 }
11800
11801 bool hasError(false);
11802 for (int i = 0; i < h->GetSumw2N(); i++) {
11803 if (h->GetSumw2()->At(i)) {
11804 hasError = true;
11805 break;
11806 }
11807 }
11808
11809 /** This doesn't seem necessary in at least 6.26 any more - pads seem adjusted on their own
11810 if (!hasSame && h->GetYaxis()->GetTitleFont()%10 == 2) {
11811 h->GetYaxis()->SetTitleOffset( gPad->GetLeftMargin() / gStyle->GetPadLeftMargin() );
11812 } */
11813 // don't this instead - dont want to leave as zero (auto) in case show aux plot
11814 if (!hasSame && h->GetYaxis()->GetTitleFont() % 10 == 2) {
11815 h->GetYaxis()->SetTitleOffset(1.);
11816 }
11817
11818 TH1 *errHist = nullptr;
11819
11820 if (!hasSame)
11821 clearPad();
11822
11823 if (rar->getAttribute("Logy")) {
11824 gPad->SetLogy(1);
11825 }
11826
11827 if (rar == vv && rar->IsA() == RooRealVar::Class()) {
11828 // add a TExec to the histogram so that when edited it will propagate to var
11829 // h->GetListOfFunctions()->Add(h->Clone("self"),"TEXTHIST");
11830 dOpt = "TEXT";
11831 auto node = new xRooNode(*this);
11832 auto _hist = (errHist) ? errHist : h;
11833 auto hCopy = (errHist) ? nullptr : dynamic_cast<TH1 *>(h->Clone());
11834 if (hCopy) {
11835 hCopy->Reset();
11836 hCopy->Add(_hist);
11837 hCopy->SetDirectory(nullptr);
11838 }
11839 _hist->GetListOfFunctions()->Add(node);
11840 _hist->GetListOfFunctions()->Add(new TExec(
11841 ".update",
11843 "gROOT->SetEditHistograms(true);auto h = dynamic_cast<TH1*>(gPad->GetPrimitive(\"%s\")); if(h) { double "
11844 "range= h->GetMaximum()-h->GetMinimum(); if(auto n "
11845 "= dynamic_cast<xRooNode*>(h->GetListOfFunctions()->FindObject(\"%s\")); n && "
11846 "n->TestBit(TObject::kNotDeleted) && n->get<RooRealVar>()->getVal() != h->GetBinContent(1)) {"
11847 "h->SetBinContent(1, "
11848 "TString::Format(\"%%.2g\",int(h->GetBinContent(1)/(range*0.01))*range*0.01).Atof());n->SetContent( "
11849 "h->GetBinContent(1) ); for(auto pp : *h->GetListOfFunctions()) if(auto hh = "
11850 "dynamic_cast<TH1*>(pp))hh->SetBinContent(1,h->GetBinContent(1));} if(h->GetBinContent(1)==0.) "
11851 "h->SetBinContent(1,range*0.005); gPad->Modified();gPad->Update(); }",
11852 _hist->GetName(), node->GetName())));
11853 if (errHist) {
11854 errHist->GetListOfFunctions()->Add(h, "TEXT HIST same");
11855 errHist->SetFillColor(h->GetLineColor());
11856 } else {
11857 hCopy->SetBit(kCanDelete);
11858 hCopy->SetFillStyle(0);
11859 _hist->GetListOfFunctions()->Add(hCopy, "TEXT HIST same");
11860 //_hist->SetBinError(1, 0);
11861 }
11862 _hist->SetStats(false);
11863 // if (_hist->GetBinContent(1)==0.) _hist->SetBinContent(1,(_hist->GetMaximum()-_hist->GetMinimum())*0.005);
11864 _hist->Draw(); //_hist->Draw(((hasError) ? "e2" : ""));
11865 gPad->Modified();
11866 return;
11867 }
11868
11869 bool overlayExisted = false;
11870 if (hasOverlay) {
11871 h->SetName(TString::Format("%s%s", h->GetName(), overlayName.Data()));
11872 if (auto existing = dynamic_cast<TH1 *>(gPad->GetPrimitive(h->GetName())); existing) {
11873 existing->Reset();
11874 existing->Add(h);
11875 delete h;
11876 h = existing;
11877 overlayExisted = true;
11878 } else {
11879 TString oldStyle = (rar && rar->getStringAttribute("style")) ? rar->getStringAttribute("style") : "";
11880 h->SetTitle(overlayName);
11881 // for overlays will take style from current gStyle before overriding with personal style
11882 // this ensures initial style will be whatever gStyle is, rather than whatever ours is
11883 static_cast<TAttLine &>(*h) = *gStyle;
11884 static_cast<TAttFill &>(*h) = *gStyle;
11885 static_cast<TAttMarker &>(*h) = *gStyle;
11886 h->SetFillStyle(0); // explicit default for overlays will be transparent fill
11887
11888 // std::shared_ptr<TStyle> style; // use to keep alive for access from GetStyle below, in case
11889 // getObject has decided to return the owning ptr (for some reason) if
11890 // (!gROOT->GetStyle(h->GetTitle())) {
11891 // if ( (style = getObject<TStyle>(h->GetTitle())) ) {
11892 // // loaded style (from workspace?) so put in list and use that
11893 // gROOT->GetListOfStyles()->Add(style.get());
11894 // } else {
11895 // // create new style - gets put in style list automatically so don't have to delete
11896 // // acquire them so saved to workspaces for auto reload ...
11897 // style = acquireNew<TStyle>(h->GetTitle(),
11898 // TString::Format("Style for %s component", h->GetTitle()));
11899 // (TAttLine &) (*style) = *dynamic_cast<TAttLine *>(h);
11900 // (TAttFill &) (*style) = *dynamic_cast<TAttFill *>(h);
11901 // (TAttMarker &) (*style) = *dynamic_cast<TAttMarker *>(h);
11902 // gROOT->GetListOfStyles()->Add(style.get());
11903 // }
11904 // }
11905 // (TAttLine&)(*h) = *(gROOT->GetStyle(h->GetTitle()) ? gROOT->GetStyle(h->GetTitle()) : gStyle);
11906 // (TAttFill&)(*h) = *(gROOT->GetStyle(h->GetTitle()) ? gROOT->GetStyle(h->GetTitle()) : gStyle);
11907 // (TAttMarker&)(*h) = *(gROOT->GetStyle(h->GetTitle()) ? gROOT->GetStyle(h->GetTitle()) : gStyle);
11908 auto _styleNode = styles(h);
11909 rar->setStringAttribute("style", oldStyle == "" ? nullptr : oldStyle.Data()); // restores old style
11910 if (auto _style = _styleNode.get<TStyle>()) {
11911 (TAttLine &)(*h) = *_style;
11912 (TAttFill &)(*h) = *_style;
11913 (TAttMarker &)(*h) = *_style;
11914 }
11915 h->Draw(dOpt == "LF2" ? "e3" : dOpt);
11916 if (errHist) {
11917 errHist->SetTitle(overlayName);
11918 (TAttLine &)(*errHist) = *h;
11919 errHist->SetFillColor(h->GetLineColor());
11920 }
11921 }
11922 } else {
11923 // if (auto _style = _styleNode.get<TStyle>()) {
11924 // (TAttLine &)(*h) = *_style;
11925 // (TAttFill &)(*h) = *_style;
11926 // (TAttMarker &)(*h) = *_style;
11927 // if (errHist) {
11928 // (TAttLine &)(*errHist) = *h;
11929 // errHist->SetFillColor(h->GetLineColor());
11930 // }
11931 // }
11932 h->Draw(dOpt);
11933 }
11934
11935 if (!hasOverlay && (rarNode->get()->InheritsFrom("RooRealSumPdf") || rarNode->get()->InheritsFrom("RooAddPdf") ||
11936 (rarNode->get()->InheritsFrom("RooSimultaneous") &&
11937 strcmp(vv->GetName(), rarNode->get<RooSimultaneous>()->indexCat().GetName()) == 0))) {
11938 if (auto stack = dynamic_cast<THStack *>(h->FindObject("stack"))) {
11939 // access the stack and set draw options, adjust ranges etc
11940 TObjLink *lnk = stack->GetHists()->FirstLink();
11941 while (lnk) {
11942 TH1 *hh = static_cast<TH1 *>(lnk->GetObject());
11943 // lnk->SetOption(dOpt); - not needed
11944 auto hhMin = (hh->GetMinimum() == 0) ? hh->GetMinimum(1e-9) : hh->GetMinimum();
11945 if (lnk == stack->GetHists()->FirstLink() && h->GetMinimum() > hhMin) {
11946 auto newMin = hhMin - (h->GetMaximum() - hhMin) * gStyle->GetHistTopMargin();
11947 if (hhMin >= 0 && newMin < 0)
11948 newMin = hhMin * 0.99;
11949 adjustYRange(newMin, h->GetMaximum());
11950 }
11951 addLegendEntry(hh, hh->GetTitle(), "f");
11952 lnk = lnk->Next();
11953 }
11954 }
11955
11956 // // build a stack unless not requested
11957 // if (!nostack) {
11958 // THStack *stack = new THStack(TString::Format("%s_stack", rar->GetName()),
11959 // TString::Format("%s;%s", rar->GetTitle(), h->GetXaxis()->GetTitle()));
11960 // int count = 2;
11961 // std::map<std::string, int> colorByTitle; // TODO: should fill from any existing legend
11962 // std::set<std::string> allTitles;
11963 // bool titleMatchName = true;
11964 // std::map<std::string, TH1 *> histGroups;
11965 // std::vector<TH1 *> hhs;
11966 // std::set<TH1 *> histsWithBadTitles; // these histograms will have their titles autoFormatted
11967 //
11968 // // support for CMS model case where has single component containing many coeffs
11969 // // will build stack by setting each coeff equal to 0 in turn, rebuilding the histogram
11970 // // the difference from the "full" histogram will be the component
11971 // RooArgList cms_coefs;
11972 // if (!rarNode->components().empty()) {
11973 // auto comps = rarNode->components()[0];
11974 // for (auto &c : *comps) {
11975 // if (c->fFolder == "!.coeffs")
11976 // cms_coefs.add(*c->get<RooAbsArg>());
11977 // }
11978 // }
11979 // if (!cms_coefs.empty()) {
11980 // RooRealVar zero("zero", "", 0);
11981 // std::shared_ptr<TH1> prevHist(static_cast<TH1 *>(h->Clone()));
11982 // for (auto c : cms_coefs) {
11983 // // seems I have to remake the function each time, as haven't figured out what cache needs
11984 // clearing? std::unique_ptr<RooAbsReal> f(
11985 // dynamic_cast<RooAbsReal *>(rarNode->components()[0]->get()->Clone("tmpCopy")));
11986 // zero.setAttribute(
11987 // Form("ORIGNAME:%s", c->GetName())); // used in redirectServers to say what this
11988 // replaces
11989 // f->redirectServers(RooArgSet(zero), false, true); // each time will replace one additional coef
11990 // // zero.setAttribute(Form("ORIGNAME:%s",c->GetName()),false); (commented out so that on next
11991 // iteration
11992 // // will still replace all prev)
11993 // auto hh = xRooNode(*f, *this).BuildHistogram(v);
11994 // hh->SetName(c->GetName());
11995 // if (sf)
11996 // hh->Scale(sf->getVal());
11997 // if (strlen(hh->GetTitle()) == 0) {
11998 // hh->SetTitle(c->GetName()); // ensure all hists has titles
11999 // histsWithBadTitles.insert(hh);
12000 // } else if (strcmp(hh->GetName(), hh->GetTitle()) == 0) {
12001 // histsWithBadTitles.insert(hh);
12002 // }
12003 // titleMatchName &= (TString(c->GetName()) == hh->GetTitle() ||
12004 // TString(hh->GetTitle()).BeginsWith(TString(c->GetName()) + "_"));
12005 // std::shared_ptr<TH1> nextHist(static_cast<TH1 *>(hh->Clone()));
12006 // hh->Add(prevHist.get(), -1.);
12007 // hh->Scale(-1.);
12008 // hhs.push_back(hh);
12009 // prevHist = nextHist;
12010 // }
12011 // } else if (get<RooSimultaneous>()) {
12012 // // need to create a histogram for each sample across all the channels - will rely on functionality
12013 // below to
12014 // // merge them based on titles
12015 //
12016 // for (auto &chan : bins()) {
12017 // TString chanName(chan->GetName());
12018 // chanName = chanName(chanName.Index("=") + 1, chanName.Length());
12019 // auto samps = chan->mainChild();
12020 // if (!samps)
12021 // samps = *chan;
12022 // for (auto &samp : samps.components()) {
12023 // auto hh = static_cast<TH1 *>(h->Clone(samp->GetName()));
12024 // hh->Reset();
12025 // hh->SetTitle(samp->GetTitle());
12026 // if (strlen(hh->GetTitle()) == 0) {
12027 // hh->SetTitle(samp->GetName());
12028 // histsWithBadTitles.insert(hh);
12029 // } else if (strcmp(hh->GetName(), hh->GetTitle()) == 0) {
12030 // histsWithBadTitles.insert(hh);
12031 // }
12032 // hh->SetTitle(TString(hh->GetTitle())
12033 // .ReplaceAll(TString(chan->get()->GetName()) + "_",
12034 // "")); // remove occurance of channelname_ in title (usually
12035 // prefix)
12036 // titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() ||
12037 // TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_"));
12038 // hh->SetBinContent(hh->GetXaxis()->FindFixBin(chanName), samp->GetContent());
12039 // hhs.push_back(hh);
12040 // }
12041 // }
12042 // } else {
12043 // for (auto &samp : rarNode->components()) {
12044 // auto hh = samp->BuildHistogram(v,false,false,1,0,"",false,false,0,h); // passing h to ensure
12045 // binning is the same for all subcomponent hists if (sf)
12046 // hh->Scale(sf->getVal());
12047 // hhs.push_back(hh);
12048 // if (strlen(hh->GetTitle()) == 0) {
12049 // hh->SetTitle(samp->GetName()); // ensure all hists has titles
12050 // histsWithBadTitles.insert(hh);
12051 // } else if (strcmp(hh->GetName(), hh->GetTitle()) == 0) {
12052 // histsWithBadTitles.insert(hh);
12053 // }
12054 // titleMatchName &= (TString(samp->GetName()) == hh->GetTitle() ||
12055 // TString(hh->GetTitle()).BeginsWith(TString(samp->GetName()) + "_"));
12056 // }
12057 // }
12058 //
12059 // if (!hhs.empty()) {
12060 // for (auto &hh : hhs) {
12061 // allTitles.insert(hh->GetTitle());
12062 // }
12063 //
12064 // // get common prefix to strip off only if all titles match names and
12065 // // any title is longer than 10 chars
12066 // size_t e = std::min(allTitles.begin()->size(), allTitles.rbegin()->size());
12067 // size_t ii = 0;
12068 // bool goodPrefix = false;
12069 // std::string commonSuffix;
12070 // if (titleMatchName && hhs.size() > 1) {
12071 // while (ii < e - 1 && allTitles.begin()->at(ii) == allTitles.rbegin()->at(ii)) {
12072 // ii++;
12073 // if (allTitles.begin()->at(ii) == '_' || allTitles.begin()->at(ii) == ' ')
12074 // goodPrefix = true;
12075 // }
12076 //
12077 // // find common suffix if there is one .. must start with a "_"
12078 // bool stop = false;
12079 // while (!stop && commonSuffix.size() < size_t(e - 1)) {
12080 // commonSuffix = allTitles.begin()->substr(allTitles.begin()->length() - commonSuffix.length() -
12081 // 1); for (auto &t : allTitles) {
12082 // if (!TString(t).EndsWith(commonSuffix.c_str())) {
12083 // commonSuffix = commonSuffix.substr(1);
12084 // stop = true;
12085 // break;
12086 // }
12087 // }
12088 // }
12089 // if (commonSuffix.find('_') == std::string::npos) {
12090 // commonSuffix = "";
12091 // } else {
12092 // commonSuffix = commonSuffix.substr(commonSuffix.find('_'));
12093 // }
12094 // }
12095 // if (!goodPrefix)
12096 // ii = 0;
12097 //
12098 // // also find how many characters are needed to distinguish all entries (that dont have the same
12099 // name)
12100 // // then carry on up to first space or underscore
12101 // size_t jj = 0;
12102 // std::map<std::string, std::string> reducedTitles;
12103 // while (reducedTitles.size() != allTitles.size()) {
12104 // jj++;
12105 // std::map<std::string, int> titlesMap;
12106 // for (auto &s : allTitles) {
12107 // if (reducedTitles.count(s))
12108 // continue;
12109 // titlesMap[s.substr(0, jj)]++;
12110 // }
12111 // for (auto &s : allTitles) {
12112 // if (titlesMap[s.substr(0, jj)] == 1 && (jj >= s.length() || s.at(jj) == ' ' || s.at(jj) ==
12113 // '_')) {
12114 // reducedTitles[s] = s.substr(0, jj);
12115 // }
12116 // }
12117 // }
12118 //
12119 // // strip common prefix and suffix before adding
12120 // for (auto ritr = hhs.rbegin(); ritr != hhs.rend(); ++ritr) { // go in reverse order
12121 // if (!histsWithBadTitles.count((*ritr))) {
12122 // continue;
12123 // }
12124 // auto _title = (hhs.size() > 5) ? reducedTitles[(*ritr)->GetTitle()] : (*ritr)->GetTitle();
12125 // _title = _title.substr(ii < _title.size() ? ii : 0);
12126 // if (!commonSuffix.empty() && TString(_title).EndsWith(commonSuffix.c_str()))
12127 // _title = _title.substr(0, _title.length() - commonSuffix.length());
12128 // (*ritr)->SetTitle(_title.c_str());
12129 // }
12130 // }
12131 //
12132 // for (auto &hh : hhs) {
12133 // // automatically group hists that all have the same title
12134 // if (histGroups.find(hh->GetTitle()) == histGroups.end()) {
12135 // histGroups[hh->GetTitle()] = hh;
12136 // } else {
12137 // // add it into this group
12138 // histGroups[hh->GetTitle()]->Add(hh);
12139 // delete hh;
12140 // hh = nullptr;
12141 // continue;
12142 // }
12143 // auto hhMin = (hh->GetMinimum() == 0) ? hh->GetMinimum(1e-9) : hh->GetMinimum();
12144 // if (!stack->GetHists() && h->GetMinimum() > hhMin) {
12145 // auto newMin = hhMin - (h->GetMaximum() - hhMin) * gStyle->GetHistTopMargin();
12146 // if (hhMin >= 0 && newMin < 0)
12147 // newMin = hhMin * 0.99;
12148 // adjustYRange(newMin, h->GetMaximum());
12149 // }
12150 //
12151 // /*if(stack->GetHists() && stack->GetHists()->GetEntries()>0) {
12152 // // to remove rounding effects on bin boundaries, see if binnings compatible
12153 // auto _h1 = dynamic_cast<TH1*>(stack->GetHists()->At(0));
12154 // if(_h1->GetNbinsX()==hh->GetNbinsX()) TODO ... finish dealing with silly rounding effects
12155 // }*/
12156 // TString thisOpt = dOpt;
12157 // // uncomment next line to blend continuous with discrete components .. get some unpleasant "poke
12158 // through"
12159 // // effects though
12160 // // if(auto s = samp->get<RooAbsReal>(); s) thisOpt =
12161 // s->isBinnedDistribution(*dynamic_cast<RooAbsArg*>(v)) ?
12162 // // "" : "LF2";
12163 // stack->Add(hh, thisOpt);
12164 // }
12165 // stack->SetBit(kCanDelete); // should delete its sub histograms
12166 // stack->Draw("noclear same");
12167 // h->Draw(
12168 // dOpt + sOpt +
12169 // "same"); // overlay again .. if stack would cover original hist (negative components) we still see
12170 // integral
12171 // h->Draw("axissame"); // redraws axis
12172 //
12173 // TList *ll = stack->GetHists();
12174 // if (ll && ll->GetEntries()) {
12175 //
12176 // // finally, ensure all hists are styled
12177 // for (auto ho : *ll) {
12178 // TH1 *hh = dynamic_cast<TH1 *>(ho);
12179 // if (!hh)
12180 // continue;
12181 // bool createdStyle = (xRooNode(*hh, *this).styles(nullptr, false).get<TStyle>() == nullptr);
12182 //
12183 // if (createdStyle) {
12184 // // give hist a color, that isn't the same as any other hists color
12185 // hh->SetFillStyle(1001); // solid fill style
12186 // bool used = false;
12187 // do {
12188 // hh->SetFillColor((count++));
12189 // // check not already used this color
12190 // used = false;
12191 // for (auto ho2 : *ll) {
12192 // TH1 *hh2 = dynamic_cast<TH1 *>(ho2);
12193 // if (!hh2)
12194 // continue;
12195 // auto _styleNode = xRooNode(*hh2, *this).styles(hh2, false);
12196 // auto _style = _styleNode.get<TStyle>();
12197 // if (hh != hh2 && _style && _style->GetFillColor() == hh->GetFillColor()) {
12198 // used = true;
12199 // break;
12200 // }
12201 // }
12202 // } while (used);
12203 // }
12204 //
12205 // auto _styleNode = xRooNode(*hh, *this).styles(hh);
12206 // if (auto _style = _styleNode.get<TStyle>()) {
12207 // *dynamic_cast<TAttLine *>(hh) = *_style;
12208 // *dynamic_cast<TAttFill *>(hh) = *_style;
12209 // *dynamic_cast<TAttMarker *>(hh) = *_style;
12210 // }
12211 // // for stacks, fill color of white should be color 10 unless fill style is 0
12212 // if (hh->GetFillColor() == kWhite && hh->GetFillStyle() != 0) {
12213 // // kWhite means 'transparent' in ROOT ... should really use a FillStyle of 0 for that
12214 // // so assume user wanted actual white, which is color 10
12215 // hh->SetFillColor(10);
12216 // }
12217 // addLegendEntry(hh, hh->GetTitle(), "f");
12218 // }
12219 // }
12220 // }
12221 } else if (!overlayExisted) {
12222
12223 if (errHist) {
12224 addLegendEntry(errHist, strlen(errHist->GetTitle()) ? errHist->GetTitle() : GetName(), "fl");
12225 } else {
12226 addLegendEntry(h, strlen(h->GetTitle()) ? h->GetTitle() : GetName(), (hasError) ? "fl" : "l");
12227 }
12228 }
12229
12230 if (errHist) {
12231 dOpt.ReplaceAll("TEXT", "");
12232 errHist->Draw(dOpt + (dOpt.Contains("LF2") ? "e3same" : "e2same"));
12233 double ymax = -std::numeric_limits<double>::infinity();
12234 double ymin = std::numeric_limits<double>::infinity();
12235 for (int i = 1; i <= errHist->GetNbinsX(); i++) {
12236 ymax = std::max(ymax, errHist->GetBinContent(i) + errHist->GetBinError(i));
12237 ymin = std::min(ymin, errHist->GetBinContent(i) - errHist->GetBinError(i));
12238 }
12239 adjustYRange(ymin, ymax);
12240 } else {
12241 adjustYRange(h->GetMinimum() * 0.9, h->GetMaximum() * 1.1);
12242 }
12243
12244 if ((!auxPlotTitle.empty()) && !hasSame) {
12245 // create a pad for the ratio ... shift the bottom margin of this pad to make space for it
12246 double padFrac = 0.3;
12247 auto _tmpPad = gPad;
12248 gPad->SetBottomMargin(padFrac);
12249 auto ratioPad = new TPad("auxPad", "aux plot", 0, 0, 1, padFrac);
12250 ratioPad->SetFillColor(_tmpPad->GetFillColor());
12251 ratioPad->SetNumber(1);
12252 ratioPad->SetBottomMargin(ratioPad->GetBottomMargin() / padFrac);
12253 ratioPad->SetTopMargin(0.04);
12254 ratioPad->SetLeftMargin(gPad->GetLeftMargin());
12255 ratioPad->SetRightMargin(gPad->GetRightMargin());
12256 ratioPad->cd();
12257 TH1 *ratioHist = dynamic_cast<TH1 *>((errHist) ? errHist->Clone("auxHist") : h->Clone("auxHist"));
12258 ratioHist->Reset();
12259 ratioHist->Add(h); // removes function list
12260 ratioHist->SetDirectory(nullptr);
12261 ratioHist->SetTitle((errHist) ? errHist->GetName()
12262 : h->GetName()); // abuse the title string to hold the name of the main hist
12263
12264 ratioHist->GetYaxis()->SetNdivisions(5, 0, 0);
12265 ratioHist->GetYaxis()->SetTitle(auxPlotTitle.c_str());
12266 ratioHist->SetTitle(
12267 TString::Format("%s|%s", ratioHist->GetTitle(),
12268 auxPlotTitle.c_str())); // used when plotting data (above) to decide what to calculate
12269 ratioHist->SetMaximum();
12270 ratioHist->SetMinimum(); // resets min and max
12271 ratioPad->SetGridy();
12272
12273 for (int i = 1; i <= ratioHist->GetNbinsX(); i++) {
12274 double val = ratioHist->GetBinContent(i);
12275 double err = ratioHist->GetBinError(i);
12276 ratioHist->SetBinContent(i, std::get<0>(auxFunctions[auxPlotTitle])(val, val, err));
12277 ratioHist->SetBinError(i, std::get<0>(auxFunctions[auxPlotTitle])(val + err, val, err) -
12278 ratioHist->GetBinContent(i));
12279 }
12280
12281 double rHeight = (1. - padFrac) / padFrac; //(_tmpPad->GetWNDC())/(gPad->GetHNDC());
12282 if (ratioHist->GetYaxis()->GetTitleFont() % 10 == 2) {
12283 ratioHist->GetYaxis()->SetTitleSize(ratioHist->GetYaxis()->GetTitleSize() * rHeight);
12284 ratioHist->GetYaxis()->SetLabelSize(ratioHist->GetYaxis()->GetLabelSize() * rHeight);
12285 ratioHist->GetXaxis()->SetTitleSize(ratioHist->GetXaxis()->GetTitleSize() * rHeight);
12286 ratioHist->GetXaxis()->SetLabelSize(ratioHist->GetXaxis()->GetLabelSize() * rHeight);
12287 ratioHist->GetYaxis()->SetTitleOffset(ratioHist->GetYaxis()->GetTitleOffset() / rHeight);
12288 } else {
12289#if ROOT_VERSION_CODE < ROOT_VERSION(6, 26, 00)
12290 ratioHist->GetYaxis()->SetTitleOffset(ratioHist->GetYaxis()->GetTitleOffset() / rHeight);
12291#endif
12292 }
12293 ratioHist->GetXaxis()->SetTickLength(ratioHist->GetXaxis()->GetTickLength() * rHeight);
12294 ratioHist->SetStats(false);
12295 ratioHist->SetBit(TH1::kNoTitle);
12296 ratioHist->SetBit(kCanDelete);
12297 if (errHist) {
12298 auto _h = dynamic_cast<TH1 *>(ratioHist->Clone("auxHist_clone"));
12299 _h->SetDirectory(nullptr);
12300 _h->SetFillColor(0);
12301 ratioHist->GetListOfFunctions()->Add(_h, "histsame");
12302 //_h->Draw("histsame");
12303 }
12304 ratioHist->GetListOfFunctions()->Add(new TExec(
12305 ".updateAxis",
12306 TString::Format("auto h1 = (TH1*)%p; auto h2 = (TH1*)%p; if(h2->GetXaxis()->GetFirst() != "
12307 "h1->GetXaxis()->GetFirst() || h1->GetXaxis()->GetLast()!=h2->GetXaxis()->GetLast()) "
12308 "{h2->GetXaxis()->SetRange(h1->GetXaxis()->GetFirst(),h1->GetXaxis()->GetLast());if(gPad) "
12309 "{gPad->GetCanvas()->Paint();gPad->GetCanvas()->Update();}}",
12310 (void *)ratioHist, (void *)(h))));
12311 ratioHist->Draw((errHist ? "e2" : ""));
12312
12313 _tmpPad->cd();
12314 ratioPad->Draw();
12315 } else if (auto ratioPad = dynamic_cast<TPad *>(gPad->GetPrimitive("auxPad")); hasSame && ratioPad) {
12316 // need to draw histogram in the ratio pad ...
12317 // if doing overlay need to update histogram
12318
12319 if (auto hr = dynamic_cast<TH1 *>(ratioPad->GetPrimitive("auxHist"));
12320 hr && auxFunctions.find(hr->GetYaxis()->GetTitle()) != auxFunctions.end()) {
12321 TString histName = hr->GetTitle(); // split it by | char
12322 TString histType = histName(histName.Index('|') + 1, histName.Length());
12323 histName = histName(0, histName.Index('|'));
12324
12325 if (auto hnom = dynamic_cast<TH1 *>(gPad->GetPrimitive(histName)); hnom) {
12326 h = dynamic_cast<TH1 *>(h->Clone(h->GetName()));
12327 h->SetDirectory(nullptr);
12328 h->SetBit(kCanDelete);
12329 for (int i = 1; i <= hnom->GetNbinsX(); i++) {
12330 double val = h->GetBinContent(i);
12331 double err = h->GetBinError(i);
12332 h->SetBinContent(i, std::get<0>(auxFunctions[hr->GetYaxis()->GetTitle()])(
12333 h->GetBinContent(i), hnom->GetBinContent(i), hnom->GetBinError(i)));
12334 h->SetBinError(i, std::get<0>(auxFunctions[hr->GetYaxis()->GetTitle()])(
12335 val + err, hnom->GetBinContent(i), hnom->GetBinError(i)) -
12336 h->GetBinContent(i));
12337 }
12338 auto _tmpPad = gPad;
12339 ratioPad->cd();
12340 if (hasOverlay) {
12341 if (auto existing = dynamic_cast<TH1 *>(ratioPad->GetPrimitive(h->GetName())); existing) {
12342 existing->Reset();
12343 existing->Add(h);
12344 delete h;
12345 h = existing;
12346 overlayExisted = true;
12347 } else {
12348 h->Draw(dOpt);
12349 }
12350 } else {
12351 h->Draw(dOpt);
12352 }
12353 double ymax = -std::numeric_limits<double>::infinity();
12354 double ymin = std::numeric_limits<double>::infinity();
12355 for (int i = 1; i <= h->GetNbinsX(); i++) {
12356 ymax = std::max(ymax, h->GetBinContent(i) + h->GetBinError(i));
12357 ymin = std::min(ymin, h->GetBinContent(i) - h->GetBinError(i));
12358 }
12359 adjustYRange(ymin, ymax, hr, std::get<1>(auxFunctions[hr->GetYaxis()->GetTitle()]));
12360 // adjustYRange(h->GetMinimum() * (h->GetMinimum()<0 ? 1.1 : 0.9), h->GetMaximum() * (h->GetMinimum()<0 ?
12361 // 0.9 : 1.1), hr, std::get<1>(auxFunctions[hr->GetYaxis()->GetTitle()]));
12362 gPad->Modified();
12363 _tmpPad->cd();
12364 }
12365 }
12366 }
12367
12368 // see if it's in a simultaneous so need to select a cat
12369 /*auto _parent = fParent;
12370 auto _me = rar;
12371 while(_parent) {
12372 if (auto s = _parent->get<RooSimultaneous>(); s) {
12373 for (auto c : s->indexCat()) {
12374 if (auto p = s->getPdf(c.first.c_str());_me==p) {
12375 gPad->SetName(c.first.c_str());
12376 break;
12377 }
12378 }
12379 break;
12380 }
12381 _me = _parent->get<RooAbsReal>();
12382 _parent = _parent->fParent;
12383 }*/
12384
12385 // now draw selected datasets on top if this was a pdf
12386 if (auto _pdf = get<RooAbsPdf>();
12387 !hasSame && _pdf /*&& (_pdf->canBeExtended() || robs().empty())*/ && coefs(true).empty()) {
12388 auto _dsets = datasets();
12389 // bool _drawn=false;
12390 for (auto &d : _dsets) {
12391 if (d->get()->TestBit(1 << 20)) {
12392 d->Draw("same");
12393 //_drawn=true;
12394 }
12395 }
12396 // if (!_drawn && !_dsets.empty()) _dsets[0]->Draw("same"); // always draw if has a dataset
12397 }
12398
12399 gPad->Modified();
12400 // gPad->Update();
12401 getLegend();
12402 gPad->Modified();
12403 // gPad->Update();
12404}
12405
12406void xRooNode::SaveAs(const char *filename, Option_t *option) const
12407{
12408 TString sOpt(option);
12409 sOpt.ToLower();
12410 TString sFilename(filename);
12411 TString objName = GetName();
12412 if (sFilename.Contains(".root:")) {
12413 objName = TString(sFilename(sFilename.Index(".root:") + 6, sFilename.Length()));
12414 sFilename = sFilename(0, sFilename.Index(".root:") + 5);
12415 }
12416
12417 if (auto pdf = get<RooAbsPdf>(); pdf) {
12418 // if saving a pdf, will put it inside a workspace, with its datasets, and a modelconfig
12419 // then save the workspace
12420 RooWorkspace w(objName, TString::Format("Workspace of %s", GetTitle()));
12421 xRooNode ws(w);
12422 auto addedPdf = ws.Add(*this);
12423 for (auto ds : datasets()) {
12424 ws.Add(*ds);
12425 }
12426 RooStats::ModelConfig mc("ModelConfig", GetTitle(), &w);
12427 mc.SetPdf(addedPdf->GetName());
12428 mc.SetObservables(*addedPdf.robs().get<RooArgList>());
12429 mc.SetGlobalObservables(*addedPdf.globs().get<RooArgList>());
12430 mc.SetNuisanceParameters(*addedPdf.np().get<RooArgList>());
12431 mc.SetParametersOfInterest(*addedPdf.poi().get<RooArgList>());
12432 ws.Add(mc);
12433
12434 // save the workspace
12436
12437 } else if (auto w = get<RooWorkspace>(); w) {
12438 // ensure the current color set is saved in the workspace
12439 w->import(*gROOT->GetListOfColors(), true);
12440
12441 if (sFilename.EndsWith(".json")) {
12442#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 26, 00)
12443 // stream with json tool
12444 RooJSONFactoryWSTool tool(*w);
12445 if (tool.exportJSON(sFilename.Data())) {
12446 Info("SaveAs", "%s saved to %s", w->GetName(), sFilename.Data());
12447 } else {
12448 Error("SaveAs", "Unable to save to %s", sFilename.Data());
12449 }
12450#else
12451 Error("SaveAs", "json format workspaces only in ROOT 6.26 onwards");
12452#endif
12453 return;
12454 }
12455
12456#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
12457 // before saving, clear the eocache of all owned nodes
12458 // because causes memory leak when read back in (workspace streamer immediately overwrites the caches)
12459 // fixed in: https://github.com/root-project/root/pull/12024
12460 for (auto &c : w->components()) {
12461 c->_eocache = nullptr;
12462 }
12463#endif
12464 // const_cast<Node2*>(this)->sterilize(); - tried this to reduce mem leak on readback but no improve
12465#if ROOT_VERSION_CODE < ROOT_VERSION(6, 38, 00)
12466 if (!w->writeToFile(sFilename, sOpt != "update")) {
12467#else
12468 if (w->writeToFile(sFilename, sOpt != "update")) {
12469#endif
12470 Info("SaveAs", "%s saved to %s", w->GetName(), sFilename.Data());
12471 // save any fitDatabase that is loaded in memory too
12472 // TODO: We should do this as well for SaveAs on a scan object
12473 std::function<void(TDirectory *, TDirectory *)> CopyDir;
12474
12475 CopyDir = [&](TDirectory *source, TDirectory *dest) {
12476 auto dir = dest->GetDirectory(source->GetName());
12477 if (!dir) {
12478 dir = dest->mkdir(source->GetName());
12479 }
12480 for (auto k : *source->GetListOfKeys()) {
12481 auto key = dynamic_cast<TKey *>(k);
12482 const char *classname = key->GetClassName();
12483 TClass *cl = gROOT->GetClass(classname);
12484 // std::cout << "processing " << key->GetName() << " " << classname << std::endl;
12485 if (!cl) {
12486 continue;
12487 } else if (cl->InheritsFrom(TDirectory::Class())) {
12488 CopyDir(source->GetDirectory(key->GetName()), dir);
12489 } else {
12490 // don't write object if it already exists
12491 if (dir->FindKey(key->GetName()))
12492 continue;
12493 // support FitConfigs ....
12494 if (strcmp(classname, "ROOT::Fit::FitConfig") == 0) {
12495 auto fc = key->ReadObject<ROOT::Fit::FitConfig>();
12496 dir->WriteObject(fc, key->GetName());
12497 delete fc;
12498 } else {
12499 TObject *obj = key->ReadObj();
12500 if (obj) {
12501 dir->WriteTObject(obj, key->GetName());
12502 delete obj;
12503 }
12504 }
12505 }
12506 }
12507 };
12508 if (gROOT->GetListOfFiles()) {
12509 for (auto key : *gROOT->GetListOfFiles()) {
12510 if (auto fitDb = dynamic_cast<TMemFile *>(key);
12511 fitDb /*&& TString(key->GetName()).BeginsWith("fitDatabase_")*/) {
12512 CopyDir(fitDb, std::make_unique<TFile>(sFilename, "UPDATE").get());
12513 Info("SaveAs", "Saved %s to %s", fitDb->GetName(), sFilename.Data());
12514 }
12515 }
12516 }
12517 } else {
12518 Error("SaveAs", "Unable to save to %s", sFilename.Data());
12519 }
12520#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
12521 // restore the cache to every node
12522 for (auto &c : w->components()) {
12523 c->setExpensiveObjectCache(w->expensiveObjectCache());
12524 }
12525#endif
12526 }
12527}
12528
12529double xRooNode::GetBinError(int bin, const xRooNode &fr, int nToys, bool errorsHi, bool errorsLo) const
12530{
12531 auto res = GetBinErrors(bin, bin, fr, nToys, errorsHi, errorsLo);
12532 if (res.empty())
12533 return std::numeric_limits<double>::quiet_NaN();
12534 return res.at(0);
12535}
12536
12537std::vector<double> xRooNode::contents() const
12538{
12539 std::vector<double> out;
12540 out.reserve(size());
12541 for (auto child : *this) {
12542 out.push_back(child->GetContent());
12543 }
12544 return out;
12545}
12546
12548{
12549
12550 auto _fr = fr.get<RooFitResult>();
12551
12552 if (!_fr) {
12553 return covariances(fitResult());
12554 }
12555
12556 auto rho = _fr->correlationMatrix();
12557
12558 TMatrixDSym out(size());
12559
12560 auto _pars = pars();
12561
12562 // formula for covariance is: C_ij = sum_m[sum_n[ (1/2)(nu[theta_m_up] - nu[theta_m_down])rho_mn(1/2)(nu[theta_n_up]
12563 // - nu[theta_n_down]) consistent with propagatedError formula
12564
12565 for (int m = 0; m < rho.GetNrows(); m++) {
12566 auto p_m = dynamic_cast<RooRealVar *>(_fr->floatParsFinal().at(m));
12567 if (!p_m)
12568 continue; // skip categoricals
12569 auto _p = dynamic_cast<RooAbsRealLValue *>(_pars.get<RooArgList>()->find(p_m->GetName()));
12570 if (!_p)
12571 continue;
12572 auto tmp = _p->getVal();
12573 _p->setVal(p_m->getVal() + p_m->getErrorHi());
12574 auto nu_m = contents();
12575 _p->setVal(p_m->getVal() + p_m->getErrorLo());
12576 auto nu_m2 = contents();
12577 _p->setVal(tmp);
12578 for (int n = 0; n < rho.GetNrows(); n++) {
12579 auto p_n = dynamic_cast<RooRealVar *>(_fr->floatParsFinal().at(n));
12580 if (!p_n)
12581 continue; // skip categoricals
12582 auto _p2 = dynamic_cast<RooAbsRealLValue *>(_pars.get<RooArgList>()->find(p_n->GetName()));
12583 if (!_p2)
12584 continue;
12585 auto tmp2 = _p2->getVal();
12586 _p2->setVal(p_n->getVal() + p_n->getErrorHi());
12587 auto nu_n = (p_n == p_m) ? nu_m : contents();
12588 _p2->setVal(p_n->getVal() + p_n->getErrorLo());
12589 auto nu_n2 = (p_n == p_m) ? nu_m2 : contents();
12590 _p2->setVal(tmp2);
12591 for (int i = 0; i < out.GetNrows(); i++) {
12592 for (int j = 0; j < out.GetNrows(); j++) {
12593 out(i, j) += 0.25 * (nu_m[i] - nu_m2[i]) * rho(m, n) * (nu_n[j] - nu_n2[j]);
12594 }
12595 }
12596 }
12597 }
12598 return out;
12599}
12600
12601std::pair<double, double>
12602xRooNode::IntegralAndError(const xRooNode &fr, const char *rangeName, int nToys, bool errorsHi, bool errorsLo) const
12603{
12604 double out = 1.;
12605 double err = std::numeric_limits<double>::quiet_NaN();
12606
12607 std::unique_ptr<RooAbsCollection> _snap;
12608 RooArgList _pars;
12609 if (auto _fr = fr.get<RooFitResult>()) {
12610 _pars.add(pars().argList());
12611 _snap.reset(_pars.snapshot());
12612 _pars = _fr->floatParsFinal();
12613 _pars = _fr->constPars();
12614 }
12615
12616 auto _obs = obs();
12617 RooArgSet sobs(*_obs.get<RooArgList>()); // need to make explicit RooArgSet for ROOT 6.36 onwards
12618 auto _coefs = coefs(); // need here to keep alive owned RooProduct
12619 if (auto c = _coefs.get<RooAbsReal>(); c) {
12620 out = c->getVal(sobs); // assumes independent of observables!
12621 }
12622
12623 if (auto p = dynamic_cast<RooAbsPdf *>(get()); p) {
12624 // prefer to use expectedEvents for integrals of RooAbsPdf e.g. for RooProdPdf wont include constraint terms
12625 if (rangeName)
12626 p->setNormRange(rangeName);
12627#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 27, 00)
12629#endif
12630 out *= p->expectedEvents(*_obs.get<RooArgList>());
12631#if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
12632 // improved normSet invalidity checking, so assuming no longer need this in 6.28 onwards
12633 p->_normSet = nullptr;
12634#endif
12635 err = GetBinError(-1, fr, nToys, errorsHi, errorsLo);
12636 if (rangeName)
12637 p->setNormRange(nullptr);
12638 } else if (auto p2 = dynamic_cast<RooAbsReal *>(get()); p2) {
12639 // only integrate over observables we actually depend on
12640 auto f = std::shared_ptr<RooAbsReal>(
12641 p2->createIntegral(*std::unique_ptr<RooArgSet>(p2->getObservables(*_obs.get<RooArgList>())),
12642 rangeName)); // did use x here before using obs
12643 RooProduct pr("int_x_coef", "int_x_coef",
12644 RooArgList(*f, !_coefs.get() ? RooFit::RooConst(1) : *_coefs.get<RooAbsReal>()));
12645 out *= f->getVal();
12646 err = xRooNode(pr, *this).GetBinError(-1, fr, nToys, errorsHi, errorsLo);
12647 sterilize(); // needed so that we can forget properly about the integral we just created (and are deleting)
12648 } else if (get<RooAbsData>()) {
12649 out = 0;
12650 auto vals = GetBinContents(1, 0); // returns all bins
12651 auto ax = (rangeName) ? GetXaxis() : nullptr;
12652 auto rv = (ax) ? dynamic_cast<RooRealVar *>(ax->GetParent()) : nullptr;
12653 auto cv = (ax && !rv) ? dynamic_cast<RooCategory *>(ax->GetParent()) : nullptr;
12654 int i = 0;
12655 for (auto &v : vals) {
12656 i++;
12657 if (rangeName) {
12658 if (rv && !rv->inRange(ax->GetBinCenter(i), rangeName))
12659 continue;
12660 if (cv && !cv->isStateInRange(rangeName, ax->GetBinLabel(i)))
12661 continue;
12662 }
12663 out += v;
12664 }
12665 err = 0; // should this be sqrt(sum(v^2)) or something similar
12666 } else {
12667 out = std::numeric_limits<double>::quiet_NaN();
12668 }
12669 if (_snap) {
12670 _pars.RooAbsCollection::operator=(*_snap);
12671 }
12672 return std::make_pair(out, err);
12673}
12674
12675std::vector<double>
12676xRooNode::GetBinErrors(int binStart, int binEnd, const xRooNode &_fr, int nToys, bool errorHi, bool errorLo) const
12677{
12678 // note: so far this method is inconsistent with the BuildHistogram in ways:
12679 // no projection over other variables
12680 // July2023: made RooRealSumPdf evaluate as a function if doesn't have a floor
12681 // but this method will still evaluate it as a pdf (uses PdfWrapper)
12682 // but can get away with it while added NaN recovery to getSimplePropagatedError to pickup raw values
12683
12684 if (fBinNumber != -1) {
12685 if (binStart != binEnd || !fParent) {
12686 throw std::runtime_error(TString::Format("%s is a bin - only has one value", GetName()));
12687 }
12688 return fParent->GetBinErrors(fBinNumber, fBinNumber, _fr, nToys, errorHi, errorLo);
12689 }
12690
12691 std::vector<double> out;
12692
12693 auto _hist = BuildHistogram(nullptr, true, true, binStart, binEnd, _fr, errorHi, errorLo, nToys);
12694 if (!_hist)
12695 return out;
12696 if (binEnd == 0) {
12697 binEnd = _hist->GetNbinsX();
12698 } else if (binEnd == binStart && binEnd == -1) {
12699 binStart = 1;
12700 binEnd = 1; // done an integral, so histogram has only 1 bin
12701 }
12702 for (int bin = binStart; bin <= binEnd; bin++) {
12703 out.push_back(((errorLo && !errorHi) ? (-1.) : 1.) *
12704 _hist->GetBinError(bin)); // using same convention as RooFit that Lo errors are negative
12705 }
12706 delete _hist;
12707 return out;
12708
12709 // auto o = dynamic_cast<RooAbsReal *>(get());
12710 // if (!o)
12711 // return out;
12712 //
12713 // std::shared_ptr<RooFitResult> fr = std::dynamic_pointer_cast<RooFitResult>(_fr.fComp);
12714 // //= dynamic_cast<RooFitResult*>( _fr.get<RooFitResult>() ? _fr->Clone() : fitResult()->Clone());
12715 //
12716 // auto _coefs = coefs();
12717 //
12718 // if (!fr) {
12719 // // need to ensure coefs, if any, are included in fit result retrieval so all pars are loaded
12720 // auto frn = (!_coefs.get() ? *this : xRooNode(RooProduct("tmp", "tmp", RooArgList(*o,
12721 // *_coefs.get<RooAbsReal>()))))
12722 // .fitResult();
12723 // if (strlen(_fr.GetName()))
12724 // frn = frn.reduced(_fr.GetName());
12725 //
12726 // // use name to reduce the fit result, if one given
12727 // fr = std::dynamic_pointer_cast<RooFitResult>(frn.fComp);
12728 // }
12729 //
12730 // if (!GETDMP(fr.get(), _finalPars)) {
12731 // fr->setFinalParList(RooArgList());
12732 // }
12733 //
12734 // /// Oct2022: No longer doing this because want to allow fitResult to be used to get partial error
12735 // // // need to add any floating parameters not included somewhere already in the fit result ...
12736 // // RooArgList l;
12737 // // for(auto& p : pars()) {
12738 // // auto v = p->get<RooRealVar>();
12739 // // if (!v) continue;
12740 // // if (v->isConstant()) continue;
12741 // // if (fr->floatParsFinal().find(v->GetName())) continue;
12742 // // if (fr->_constPars && fr->_constPars->find(v->GetName())) continue;
12743 // // l.add(*v);
12744 // // }
12745 // //
12746 // // if (!l.empty()) {
12747 // // RooArgList l2; l2.addClone(fr->floatParsFinal());
12748 // // l2.addClone(l);
12749 // // fr->setFinalParList(l2);
12750 // // }
12751 //
12752 // TMatrixTSym<double> *prevCov = static_cast<TMatrixTSym<double> *>(GETDMP(fr.get(), _VM));
12753 //
12754 // if (!prevCov || size_t(prevCov->GetNcols()) < fr->floatParsFinal().size()) {
12755 // TMatrixDSym cov(fr->floatParsFinal().size());
12756 // if (prevCov) {
12757 // for (int i = 0; i < prevCov->GetNcols(); i++) {
12758 // for (int j = 0; j < prevCov->GetNrows(); j++) {
12759 // cov(i, j) = (*prevCov)(i, j);
12760 // }
12761 // }
12762 // }
12763 // int i = 0;
12764 // for (auto &p : fr->floatParsFinal()) {
12765 // if (!prevCov || i >= prevCov->GetNcols()) {
12766 // cov(i, i) = pow(dynamic_cast<RooRealVar *>(p)->getError(), 2);
12767 // }
12768 // i++;
12769 // }
12770 // int covQualBackup = fr->covQual();
12771 // fr->setCovarianceMatrix(cov);
12772 // fr->setCovQual(covQualBackup);
12773 // }
12774 //
12775 // bool doBinWidth = false;
12776 // auto ax = (binStart == -1 && binEnd == -1) ? nullptr : GetXaxis();
12777 //
12778 // auto _obs = obs(); // may own an obs so keep alive here
12779 // RooArgList normSet = _obs.argList();
12780 // // to give consistency with BuildHistogram method, should be only the axis var if defined
12781 // if (ax) {
12782 // normSet.clear();
12783 // normSet.add(*dynamic_cast<RooAbsArg *>(ax->GetParent()));
12784 // }
12785 //
12786 // if (auto p = dynamic_cast<RooAbsPdf *>(o); ax && (p || _coefs.get() || o->getAttribute("density"))) {
12787 // // pdfs of samples embedded in a sumpdf (aka have a coef) will convert their density value to a content
12788 // doBinWidth = true;
12789 // }
12790 // if (binEnd == 0) {
12791 // if (ax) {
12792 // binEnd = ax->GetNbins();
12793 // } else {
12794 // binEnd = binStart;
12795 // }
12796 // }
12797 // for (int bin = binStart; bin <= binEnd; bin++) {
12798 // if (ax)
12799 // dynamic_cast<RooAbsLValue *>(ax->GetParent())->setBin(bin - 1, ax->GetName());
12800 // // if (!SetBin(bin)) { return out; }
12801 //
12802 // double res;
12803 // if (auto p = dynamic_cast<RooAbsPdf *>(o); p) {
12804 // // fr->covarianceMatrix().Print();
12805 // res = PdfWrapper(*p, _coefs.get<RooAbsReal>(), !ax).getSimplePropagatedError(*fr, normSet);
12806 // #if ROOT_VERSION_CODE < ROOT_VERSION(6, 27, 00)
12807 // // improved normSet invalidity checking, so assuming no longer need this in 6.28 onwards
12808 // p->_normSet = nullptr;
12809 // #endif
12810 // } else {
12811 // // res = o->getPropagatedError(*fr, normSet);
12812 // // // TODO: What if coef has error? - probably need a FuncWrapper class
12813 // // if (auto c = _coefs.get<RooAbsReal>(); c) {
12814 // // res *= c->getVal(normSet);
12815 // // }
12816 // res = RooProduct("errorEval", "errorEval",
12817 // RooArgList(*o, !_coefs.get() ? RooFit::RooConst(1) : *_coefs.get<RooAbsReal>()))
12818 // .getPropagatedError(*fr, normSet);
12819 // }
12820 // if (doBinWidth) {
12821 // res *= ax->GetBinWidth(bin);
12822 // }
12823 // out.push_back(res);
12824 // }
12825 //
12826 // return out;
12827}
12828
12830
12831std::string cling::printValue(const XROOFIT_NAMESPACE_NAME::xRooNode *v)
12832{
12833 if (!v)
12834 return "nullptr\n";
12835 if (!v->empty()) {
12836 std::string out;
12837 size_t left = v->size();
12838 for (auto n : *v) {
12839 left--;
12840 if (!out.empty())
12841 out += ",";
12842 else
12843 out += "{";
12844 out += n->GetName();
12845 if (out.length() > 100 && left > 0) {
12846 out += TString::Format(",... and %lu more", left);
12847 break;
12848 }
12849 }
12850 out += "}\n";
12851 out = std::string(Form("<%s> %s", v->get() ? v->get()->ClassName() : "nullptr", v->GetName())) + out;
12852 return out;
12853 }
12854 std::string out;
12855 if (!(*v)) {
12856 return "<nullptr>";
12857 } else {
12858 return Form("<%s> %s", v->get() ? v->get()->ClassName() : "nullptr", v->GetName());
12859 }
12860
12861 return out;
12862}
@ kButton1Down
Definition Buttons.h:17
#define d(i)
Definition RSha256.hxx:102
#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
#define ROOT_VERSION(a, b, c)
Definition RVersion.hxx:26
#define ROOT_VERSION_CODE
Definition RVersion.hxx:27
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
@ kGray
Definition Rtypes.h:65
@ kRed
Definition Rtypes.h:66
@ kBlack
Definition Rtypes.h:65
@ kGreen
Definition Rtypes.h:66
@ kWhite
Definition Rtypes.h:65
@ kCyan
Definition Rtypes.h:66
@ kBlue
Definition Rtypes.h:66
@ kAzure
Definition Rtypes.h:67
@ kYellow
Definition Rtypes.h:66
@ kP10Blue
Definition Rtypes.h:71
static void indent(ostringstream &buf, int indent_level)
R__EXTERN TEnv * gEnv
Definition TEnv.h:126
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
#define gClient
Definition TGClient.h:157
@ kMBOk
Definition TGMsgBox.h:33
@ kMBIconExclamation
Definition TGMsgBox.h:24
winID h TVirtualViewer3D TVirtualGLPainter p
winID h TVirtualViewer3D vv
Option_t Option_t option
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 dest
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 filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t 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 char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t child
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 funcs
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
Option_t Option_t style
char name[80]
Definition TGX11.cxx:142
float xmin
#define hi
float * q
float ymin
float xmax
float ymax
@ kCanDelete
Definition TObject.h:375
#define gROOT
Definition TROOT.h:417
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2571
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
TVectorT< Double_t > TVectorD
Definition TVectorDfwd.h:23
#define gPad
#define _(A, B)
Definition cfortran.h:112
double GetBinLowEdge(Int_t bin) const override
Return low edge of bin.
Definition xRooNode.cxx:970
double GetBinUpEdge(Int_t bin) const override
Return up edge of bin.
Definition xRooNode.cxx:978
Int_t FindFixBin(double x) const override
Find bin number corresponding to abscissa x
void Set(Int_t nbins, const double *xbins) override
Initialize axis with variable bins.
Definition xRooNode.cxx:998
RooAbsRealLValue * rvar() const
void SetTitle(const char *title) override
Set the title of the TNamed.
Definition xRooNode.cxx:989
void Set(Int_t nbins, double xmin, double xmax) override
Initialize axis with fix bins.
Int_t FindFixBin(const char *label) const override
Find bin number with label.
RooAbsLValue * var() const
const RooAbsBinning * binning() const
void Set(Int_t nbins, const float *xbins) override
Initialize axis with variable bins.
const char * GetTitle() const override
Returns title of object.
Definition xRooNode.cxx:985
double GetBinWidth(Int_t bin) const override
Return bin width.
Definition xRooNode.cxx:964
PadRefresher(TVirtualPad *p)
static int nExisting
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
bool isBinnedDistribution(const RooArgSet &obs) const override
Tests if the distribution is binned. Unless overridden by derived classes, this always returns false.
bool selfNormalized() const override
Shows if a PDF is self-normalized, which means that no attempt is made to add a normalization term.
~PdfWrapper() override
double getSimplePropagatedError(const RooFitResult &fr, const RooArgSet &nset_in) const
RooRealProxy fCoef
double evaluate() const override
Evaluate this PDF / function / constant. Needs to be overridden by all derived classes.
TObject * clone(const char *newname) const override
std::list< double > * binBoundaries(RooAbsRealLValue &obs, double xlo, double xhi) const override
Retrieve bin boundaries if this distribution is binned in obs.
PdfWrapper(const PdfWrapper &other, const char *name=nullptr)
RooRealProxy fExpPdf
PdfWrapper(RooAbsReal &f, RooAbsReal *coef, bool expEvMode=false, RooAbsPdf *expPdf=nullptr)
RooRealProxy fFunc
The PiecewiseInterpolation is a class that can morph distributions into each other,...
static std::shared_ptr< RooLinkedList > createNLLOptions()
Definition xRooFit.cxx:468
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:154
static xRooNLLVar createNLL(const std::shared_ptr< RooAbsPdf > pdf, const std::shared_ptr< RooAbsData > data, const RooLinkedList &nllOpts)
Definition xRooFit.cxx:105
static std::pair< double, double > matchPrecision(const std::pair< double, double > &in)
Definition xRooFit.cxx:2096
void Draw(Option_t *opt="") override
Default Draw method for all objects.
std::shared_ptr< xRooHypoPoint > asimov(bool readOnly=false)
std::shared_ptr< const RooFitResult > ufit(bool readOnly=false)
std::shared_ptr< const RooFitResult > cfit_null(bool readOnly=false)
std::shared_ptr< const RooFitResult > cfit_alt(bool readOnly=false)
std::shared_ptr< const RooFitResult > gfit()
Definition xRooNLLVar.h:179
void Draw(Option_t *opt="") override
Default Draw method for all objects.
This xRooNLLVar object has several special methods, e.g.
Definition xRooNLLVar.h:59
xRooHypoSpace hypoSpace(const char *parName, int nPoints, double low, double high, double alt_value=std::numeric_limits< double >::quiet_NaN(), const xRooFit::Asymptotics::PLLType &pllType=xRooFit::Asymptotics::Unknown, int tsType=0)
The xRooNode class is designed to wrap over a TObject and provide functionality to aid with interacti...
Definition xRooNode.h:52
void _Add_(const char *name, const char *opt)
TH1 * BuildHistogram(RooAbsLValue *v=nullptr, bool empty=false, bool errors=false, int binStart=1, int binEnd=0, const xRooNode &fr="", bool errorsHi=false, bool errorsLo=false, int nErrorToys=0, TH1 *templateHist=nullptr, bool nostack=true, bool setInterp=false) const
xRooNode filter(const xRooNode &range) const
std::vector< std::shared_ptr< xRooNode > > fBrowsables
Definition xRooNode.h:551
xRooNLLVar nll(const xRooNode &_data, std::initializer_list< RooCmdArg > nllOpts) const
xRooNode poi() const
List of parameters of interest: parameters marked as "of interest" These parameters have the "poi" at...
void SetName(const char *name) override
Set the name of the TNamed.
TGListTreeItem * GetTreeItem(TBrowser *b) const
void SetTitle(const char *title) override
Set the title of the TNamed.
xRooNode Multiply(const xRooNode &child, Option_t *opt="")
xRooNode Replace(const xRooNode &node)
bool SetData(const TObject &obj, const xRooNode &data="obsData")
xRooNode Remove(const xRooNode &child)
xRooNode globs() const
List of global observables of this node.
xRooNode Add(const xRooNode &child, Option_t *opt="")
xRooNode(const char *type, const char *name, const char *title="")
const char * GetIconName() const override
Returns mime type name of object.
void Draw(Option_t *opt="") override
Default Draw method for all objects.
TGraph * BuildGraph(RooAbsLValue *v=nullptr, bool includeZeros=false, TVirtualPad *fromPad=nullptr) const
const std::shared_ptr< xRooNode > & at(size_t idx, bool browseResult=true) const
Definition xRooNode.h:147
std::string fRange
! only here so can have char* GetRange return so can return nullptr for no range set !...
Definition xRooNode.h:535
xRooNode reduced(const std::string &range="", bool invert=false) const
void _fit_(const char *constParValues="", const char *options="GoF")
bool SetBinContent(int bin, double value, const char *par=nullptr, double parVal=1)
std::shared_ptr< xRooNode > operator[](size_t idx)
Definition xRooNode.h:164
void Checked(TObject *obj, bool val)
Definition xRooNode.cxx:550
void Print(Option_t *opt="") const override
Print TNamed name and title.
std::shared_ptr< T > acquireNew(Args &&...args)
Definition xRooNode.h:290
std::shared_ptr< T > acquire2(Args &&...args)
Definition xRooNode.h:284
void SaveAs(const char *filename="", Option_t *option="") const override
Save this object in the file specified by filename.
xRooNode bins() const
bins of a channel or sample, or channels of a multi-channel pdf
std::shared_ptr< xRooNode > find(const std::string &name, bool browseResult=true) const
TGListTree * GetListTree(TBrowser *b) const
xRooNode styles(TObject *initObject=nullptr, bool autoCreate=true) const
xRooNode generate(const xRooNode &fr="", bool expected=false, int seed=0)
void Inspect() const override
Dump contents of this object in a graphics canvas.
std::shared_ptr< xRooNode > getBrowsable(const char *name) const
bool SetXaxis(const RooAbsBinning &binning)
double GetBinError(int bin, const xRooNode &fr="", int nToys=0, bool errorsHi=false, bool errorsLo=false) const
bool SetBinData(int bin, double value, const xRooNode &data="obsData")
std::vector< double > GetBinContents(int binStart=1, int binEnd=0) const
xRooNode pp() const
List of prespecified parameters: non-floatable parameters.
double GetError(const xRooNode &fr="", int nToys=0, bool errorsHi=false, bool errorsLo=false) const
Definition xRooNode.h:439
std::shared_ptr< xRooNode > fProvider
! like a parent but only for use by getObject
Definition xRooNode.h:544
std::shared_ptr< TStyle > style(TObject *initObject=nullptr, bool autoCreate=true) const
xRooNode fitResult(const char *opt="") const
std::shared_ptr< TAxis > fXAxis
! appears that if was fXaxis then dialog box for SetXaxis will take as current value
Definition xRooNode.h:539
xRooNode coords(bool setVals=true) const
xRooNode Vary(const xRooNode &child)
xRooNode Constrain(const xRooNode &child)
static std::map< std::string, std::tuple< std::function< double(double, double, double)>, bool > > auxFunctions
Definition xRooNode.h:58
xRooNode pars() const
List of parameters (non-observables) of this node.
void SetFitResult(const RooFitResult *fr=nullptr)
xRooNode coefs(bool recurse=false) const
bool IsFolder() const override
Returns kTRUE in case object contains browsable objects (like containers or lists of other objects).
Definition xRooNode.cxx:949
double GetBinData(int bin, const xRooNode &data="obsData")
bool SetBinError(int bin, double value)
bool SetContents(const TObject &obj)
Definition xRooNode.h:369
std::shared_ptr< TObject > fComp
!
Definition xRooNode.h:526
std::pair< double, double > IntegralAndError(const xRooNode &fr="", const char *rangeName=nullptr, int nToys=0, bool errorsHi=false, bool errorsLo=false) const
std::vector< double > contents() const
RooWorkspace * ws() const
The RooWorkspace this node belong to, if any.
xRooNode shallowCopy(const std::string &name, std::shared_ptr< xRooNode > parent=nullptr)
void _generate_(const char *name="", bool expected=false)
std::shared_ptr< TObject > getObject(const std::string &name, const std::string &type="") const
xRooNode np() const
List of nuisance parameters: non-constant parameters that are not marked of interest,...
xRooNode Combine(const xRooNode &rhs, bool silent=false)
xRooNode floats() const
List of parameters that are currently non-constant These parameters do not have the "Constant" attrib...
bool contains(const std::string &name) const
double GetBinContent(int bin) const
Definition xRooNode.h:411
std::vector< double > GetBinErrors(int binStart=1, int binEnd=0, const xRooNode &fr="", int nToys=0, bool errorsHi=false, bool errorsLo=false) const
auto begin() const -> xRooNodeIterator
Definition xRooNode.h:200
std::shared_ptr< xRooNode > parentPdf() const
void _scan_(const char *what="plr", double nToys=0, const char *xvar="", int nPointsX=0, double lowX=0, double highX=0, const char *constParValues="", const char *options="")
std::shared_ptr< xRooNode > fParent
!
Definition xRooNode.h:529
xRooNode robs() const
List of regular observables of this node.
TClass * IsA() const override
Definition xRooNode.h:557
xRooNode & operator=(const TObject &o)
auto end() const -> xRooNodeIterator
Definition xRooNode.h:217
xRooNode consts() const
List of parameters that are currently constant.
void _SetBinContent_(int bin, double value, const char *par="", double parVal=1)
std::shared_ptr< TObject > acquire(const std::shared_ptr< TObject > &arg, bool checkFactory=false, bool mustBeNew=false)
std::function< xRooNode(xRooNode *) fBrowseOperation)
Definition xRooNode.h:552
void _SetAttribute_(const char *name, const char *value=nullptr)
Definition xRooNode.cxx:514
xRooNode histo(const xRooNode &vars="x", const xRooNode &fr="", bool content=true, bool errors=true, bool stack=true, bool errorsHi=false, bool errorsLo=false, int nErrorToys=0) const
void Browse(TBrowser *b=nullptr) override
Browse object. May be overridden for another default action.
Definition xRooNode.cxx:665
xRooNode obs() const
List of observables (global and regular) of this node.
void SetRange(const char *range, double low=std::numeric_limits< double >::quiet_NaN(), double high=std::numeric_limits< double >::quiet_NaN())
static void SetAuxFunction(const char *title, const std::function< double(double, double, double)> &func, bool symmetrize=false)
Definition xRooNode.cxx:222
std::shared_ptr< TObject > convertForAcquisition(xRooNode &acquirer, const char *opt="") const
xRooNode vars() const
List of variables (observables and parameters) of this node.
TMatrixDSym covariances(const xRooNode &fr="") const
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition FitConfig.h:49
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.
virtual bool isCategory() const
Definition RooAbsArg.h:515
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
void SetName(const char *name) override
Set the name of the TNamed.
const Text_t * getStringAttribute(const Text_t *key) const
Get string attribute mapped under key 'key'.
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:89
virtual bool isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
Definition RooAbsArg.h:176
Abstract base class for RooRealVar binning definitions.
virtual double highBound() const =0
virtual double lowBound() const =0
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
const char * getLabel() const
Retrieve current label. Use getCurrentLabel() for more clarity.
Abstract container object that can hold multiple RooAbsArg objects.
RooAbsCollection * selectByAttrib(const char *name, bool value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
double getRealValue(const char *name, double defVal=0.0, bool verbose=false) const
Get value of a RooAbsReal stored in set with given name.
virtual void removeAll()
Remove all arguments from our set, deleting them if we own them.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
RooAbsCollection & assignValueOnly(const RooAbsCollection &other, bool forceIfSizeOne=false)
Sets the value of any argument in our set that also appears in the other set.
RooAbsCollection * snapshot(bool deepCopy=true) const
Take a snap shot of current collection contents.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
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
bool setRealValue(const char *name, double newVal=0.0, bool verbose=false)
Set value of a RooAbsRealLValue stored in set with given name to newVal No error messages are printed...
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
bool selectCommon(const RooAbsCollection &refColl, RooAbsCollection &outColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
std::string contentsString() const
Return comma separated list of contained object names as STL string.
void setName(const char *name)
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
RooFit::OwningPtr< RooAbsData > reduce(const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}) const
Create a reduced copy of this dataset.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
RooArgSet const * getGlobalObservables() const
Returns snapshot of global observables stored in this data.
Definition RooAbsData.h:272
Abstract base class for objects that are lvalues, i.e.
virtual std::list< std::string > getBinningNames() const =0
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
bool canBeExtended() const
If true, PDF can provide extended likelihood term.
Definition RooAbsPdf.h:214
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
void setBin(Int_t ibin, const char *rangeName=nullptr) override
Set value to center of bin 'ibin' of binning 'rangeName' (or of default binning if no range is specif...
bool hasRange(const char *name) const override
Check if variable has a binning with given name.
Context to temporarily change the error logging mode as long as the context is alive.
Definition RooAbsReal.h:317
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
bool isSelectedComp() const
If true, the current pdf is a selected component (for use in plotting)
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
virtual void forceNumInt(bool flag=true)
Definition RooAbsReal.h:175
Efficient implementation of a sum of PDFs of the form.
Definition RooAddPdf.h:32
Calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition RooAddition.h:27
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
Abstract interface for RooAbsArg proxy classes.
Definition RooArgProxy.h:24
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:159
RooArgSet * selectByAttrib(const char *name, bool value) const
Use RooAbsCollection::selectByAttrib(), but return as RooArgSet.
Definition RooArgSet.h:144
Implements a RooAbsBinning in terms of an array of boundary values, posing no constraints on the choi...
Definition RooBinning.h:27
Object to represent discrete states.
Definition RooCategory.h:28
bool defineType(const std::string &label)
Define a state with given name.
static TClass * Class()
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
static const RooCmdArg & none()
Return reference to null argument.
Definition RooCmdArg.cxx:48
TObject * Clone(const char *newName=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooCmdArg.h:58
Represents a constant real-valued object.
Definition RooConstVar.h:23
static TClass * Class()
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
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.
TMatrixDSym conditionalCovarianceMatrix(const RooArgList &params) const
Return a reduced covariance matrix, which is calculated as.
void setCovQual(Int_t val)
const TMatrixDSym & covarianceMatrix() const
Return covariance matrix.
Int_t statusCodeHistory(UInt_t icycle) const
const RooArgList & floatParsInit() const
Return list of floating parameters before fit.
TMatrixDSym reducedCovarianceMatrix(const RooArgList &params) const
Return a reduced covariance matrix (Note that Vred is a simple sub-matrix of V, row/columns are order...
const RooArgList & randomizePars() const
Generate random perturbations of the final parameters using the covariance matrix.
void setCovarianceMatrix(TMatrixDSym &V)
Store externally provided correlation matrix in this RooFitResult ;.
double edm() const
Return estimated distance to minimum.
const RooArgList & constPars() const
Return list of constant parameters.
const char * statusLabelHistory(UInt_t icycle) const
Int_t covQual() const
Return MINUIT quality code of covariance matrix.
TH2 * correlationHist(const char *name="correlation_matrix") const
Return TH2D of correlation matrix.
const RooArgList & floatParsFinal() const
Return list of floating parameters after fit.
Int_t status() const
Return MINUIT status code.
void setFinalParList(const RooArgList &list)
Fill the list of final values of the floating parameters.
UInt_t numStatusHistory() const
const TMatrixDSym & correlationMatrix() const
Return correlation matrix ;.
double minNll() const
Return minimized -log(L) value.
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
Implementation of a probability density function that takes a RooArgList of servers and a C++ express...
A real-valued function sampled from a multidimensional histogram.
Definition RooHistFunc.h:29
bool isBinnedDistribution(const RooArgSet &) const override
Tests if the distribution is binned. Unless overridden by derived classes, this always returns false.
Definition RooHistFunc.h:89
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
bool importJSON(std::string const &filename)
Import the HS3 document of a JSON file into the workspace. Returns true; errors are exceptions.
bool exportJSON(std::string const &fileName)
Export the workspace as an HS3 document, and write it to a JSON file. Returns true; errors are except...
Collection class for internal use, storing a collection of TObject pointers in a vector.
Int_t GetSize() const
TObject * At(int index) const
Return object stored in sequential position given by index.
virtual void Add(TObject *arg)
Insert object into collection.
TIterator * MakeIterator(bool forward=true) const
Create a TIterator for this list.
static RooMsgService & instance()
Return reference to singleton instance.
StreamConfig & getStream(Int_t id)
void setGlobalKillBelow(RooFit::MsgLevel level)
RooFit::MsgLevel globalKillBelow() const
Implementation of a RooCacheManager<RooAbsCacheElement> that specializes in the storage of cache elem...
Poisson pdf.
Definition RooPoisson.h:18
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:35
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
static TClass * Class()
A RooAbsPdf implementation that represent a projection of a given input p.d.f and the object returned...
RooProjectedPdf()
Default constructor.
Implements a PDF constructed from a sum of functions:
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setVal(double value) override
Set value of variable to 'value'.
void setError(double value)
Definition RooRealVar.h:61
static TClass * Class()
double getError() const
Definition RooRealVar.h:59
bool hasError(bool allowZero=true) const
Definition RooRealVar.h:60
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
const RooAbsCategoryLValue & indexCat() const
HypoTestResult is a base class for results from hypothesis tests.
< A class that holds configuration information for a model using a workspace as a store
Definition ModelConfig.h:34
void SetParametersOfInterest(const RooArgSet &set)
Specify parameters of interest.
void SetObservables(const RooArgSet &set)
Specify the observables.
void SetPdf(const RooAbsPdf &pdf)
Set the Pdf, add to the workspace if not already there.
Definition ModelConfig.h:87
void SetNuisanceParameters(const RooArgSet &set)
Specify the nuisance parameters (parameters that are not POI).
void SetGlobalObservables(const RooArgSet &set)
Specify the global observables.
A RooAbsArg implementing string values.
Implementation of RooAbsBinning that provides a uniform binning in 'n' bins between the range end poi...
Persistable container for RooFit projects.
const std::map< std::string, RooArgSet > & sets() const
bool removeSet(const char *name)
Remove a named set from the workspace.
static TClass * Class()
RooFactoryWSTool & factory()
Return instance to factory tool.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}, const RooCmdArg &arg9={})
Import a RooAbsArg object, e.g.
const Double_t * GetArray() const
Definition TArrayD.h:43
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title.
Definition TAttAxis.cxx:279
virtual Style_t GetTitleFont() const
Definition TAttAxis.h:48
virtual void SetLabelSize(Float_t size=0.04)
Set size of axis labels.
Definition TAttAxis.cxx:184
virtual void SetTitleSize(Float_t size=0.04)
Set size of axis title.
Definition TAttAxis.cxx:290
virtual Float_t GetTitleSize() const
Definition TAttAxis.h:45
virtual void SetTickSize(Float_t size=0.03)
Definition TAttAxis.h:60
virtual Float_t GetLabelSize() const
Definition TAttAxis.h:42
virtual Float_t GetTickLength() const
Definition TAttAxis.h:46
virtual Float_t GetTitleOffset() const
Definition TAttAxis.h:44
virtual void SetTickLength(Float_t length=0.03)
Set tick mark length.
Definition TAttAxis.cxx:265
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition TAttAxis.cxx:214
Fill Area Attributes class.
Definition TAttFill.h:21
virtual Color_t GetFillColor() const
Return the fill area color.
Definition TAttFill.h:32
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition TAttFill.h:33
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition TAttFill.h:40
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition TAttFill.h:42
Line Attributes class.
Definition TAttLine.h:21
virtual Color_t GetLineColor() const
Return the line color.
Definition TAttLine.h:36
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:44
Marker Attributes class.
Definition TAttMarker.h:22
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition TAttMarker.h:36
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
virtual void SetTextAlign(Short_t align=11)
Set the text alignment.
Definition TAttText.h:48
virtual Font_t GetTextFont() const
Return the text font.
Definition TAttText.h:38
virtual void SetTextColor(Color_t tcolor=1)
Set the text color.
Definition TAttText.h:50
virtual void SetTextFont(Font_t tfont=62)
Set the text font.
Definition TAttText.h:52
virtual void SetTextSize(Float_t tsize=1)
Set the text size.
Definition TAttText.h:53
Class to manage histogram axis.
Definition TAxis.h:32
virtual void LabelsOption(Option_t *option="h")
Set option(s) to draw axis with labels option can be:
Definition TAxis.cxx:674
virtual void SetBinLabel(Int_t bin, const char *label)
Set label for bin.
Definition TAxis.cxx:898
Bool_t IsAlphanumeric() const
Definition TAxis.h:90
Bool_t IsVariableBinSize() const
Definition TAxis.h:144
const char * GetTitle() const override
Returns title of object.
Definition TAxis.h:137
TAxis()
Default constructor.
Definition TAxis.cxx:50
const TArrayD * GetXbins() const
Definition TAxis.h:138
Double_t GetXmax() const
Definition TAxis.h:142
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition TAxis.cxx:444
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition TAxis.cxx:797
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x
Definition TAxis.cxx:422
virtual const char * GetTimeFormatOnly() const
Return only the time format from the string fTimeFormat.
Definition TAxis.cxx:611
Double_t GetXmin() const
Definition TAxis.h:141
Int_t GetNbins() const
Definition TAxis.h:127
Using a TBrowser one can browse all ROOT objects.
Definition TBrowser.h:37
TBrowserImp * GetBrowserImp() const
Definition TBrowser.h:94
static TCanvas * MakeDefCanvas()
Static function to build a default canvas.
Definition TCanvas.cxx:1549
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
Longptr_t GetDataMemberOffset(const char *membername) const
return offset for member name.
Definition TClass.cxx:3544
Bool_t InheritsFrom(const char *cl) const override
Return kTRUE if this class inherits from a class with name "classname".
Definition TClass.cxx:4991
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2999
void SetName(const char *name)
virtual Int_t GetEntries() const
virtual void RemoveAll(TCollection *col)
Remove all objects in collection col from this collection.
static Int_t GetColorPalette(Int_t i)
Static function returning the color number i in current palette.
Definition TColor.cxx:1523
static void InitializeColors()
Initialize colors used by the TCanvas based graphics (via TColor objects).
Definition TColor.cxx:1186
static Int_t GetNumberOfColors()
Static function returning number of colors in the color palette.
Definition TColor.cxx:1543
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
Describe directory structure in memory.
Definition TDirectory.h:45
static TClass * Class()
virtual TDirectory * GetDirectory(const char *namecycle, Bool_t printError=false, const char *funcname="GetDirectory")
Find a directory using apath.
virtual TList * GetListOfKeys() const
Definition TDirectory.h:224
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:511
virtual void SetValue(const char *name, const char *value, EEnvLevel level=kEnvChange, const char *type=nullptr)
Set the value of a resource or create a new resource.
Definition TEnv.cxx:753
TExec is a utility class that can be used to execute a C++ command when some event happens in a pad.
Definition TExec.h:26
1-Dim function class
Definition TF1.h:182
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
Create a dialog for fit function parameter settings.
System file browser, used as TRootBrowser plug-in.
void AddFSDirectory(const char *entry, const char *path=nullptr, Option_t *opt="")
Add file system directory in the list tree.
A list tree is a widget that can contain a number of items arranged in a tree structure.
Definition TGListTree.h:197
ROOT GUI Window base class.
Definition TGWindow.h:23
The axis painter class.
Definition TGaxis.h:26
virtual void SetTitle(const char *title="")
Change the title of the axis.
Definition TGaxis.cxx:2910
virtual void ImportAxisAttributes(TAxis *axis)
Internal method to import TAxis attributes to this TGaxis.
Definition TGaxis.cxx:953
TGraph with asymmetric error bars.
virtual void SetPointEYlow(Int_t i, Double_t eyl)
Set EYlow for point i.
virtual void SetPointError(Double_t exl, Double_t exh, Double_t eyl, Double_t eyh)
Set ex and ey values for point pointed by the mouse.
virtual void SetPointEYhigh(Int_t i, Double_t eyh)
Set EYhigh for point i.
Double_t GetErrorYlow(Int_t i) const override
Get low error on Y.
A TGraphErrors is a TGraph with error bars.
Double_t GetErrorYlow(Int_t bin) const override
It returns the error along Y at point i.
Double_t GetErrorYhigh(Int_t bin) const override
It returns the error along Y at point i.
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
virtual void AddPoint(Double_t x, Double_t y)
Append a new point to the graph.
Definition TGraph.h:97
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
Definition TGraph.cxx:2386
Int_t GetN() const
Definition TGraph.h:131
void SetName(const char *name="") override
Set graph name.
Definition TGraph.cxx:2425
void Draw(Option_t *chopt="") override
Draw this graph with its current attributes.
Definition TGraph.cxx:859
virtual TH1F * GetHistogram() const
Returns a pointer to the histogram used to draw the axis Takes into account the two following cases.
Definition TGraph.cxx:1457
virtual Double_t GetPointY(Int_t i) const
Get y value for point i.
Definition TGraph.cxx:1584
void SetTitle(const char *title="") override
Change (i.e.
Definition TGraph.cxx:2441
virtual void SetPointX(Int_t i, Double_t x)
Set x value for point i.
Definition TGraph.cxx:2410
virtual void SetEditable(Bool_t editable=kTRUE)
if editable=kFALSE, the graph cannot be modified with the mouse by default a TGraph is editable
Definition TGraph.cxx:2338
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:956
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:908
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:126
virtual void SetDirectory(TDirectory *dir)
By default, when a histogram is created, it is added to the list of histogram objects in the current ...
Definition TH1.cxx:9170
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition TH1.cxx:9371
void SetTitle(const char *title) override
Change/set the title.
Definition TH1.cxx:6932
virtual Int_t GetNbinsY() const
Definition TH1.h:572
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition TH1.cxx:9293
@ kNoTitle
Don't draw the histogram title.
Definition TH1.h:438
virtual Double_t GetMinimum(Double_t minval=-std::numeric_limits< float >::max()) const
Return minimum value larger than minval of bins in the range, unless the value has been overridden by...
Definition TH1.cxx:8868
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition TH1.cxx:7324
TAxis * GetXaxis()
Definition TH1.h:601
TObject * FindObject(const char *name) const override
Search object named name in the list of functions.
Definition TH1.cxx:4008
virtual Int_t GetNbinsX() const
Definition TH1.h:571
virtual void SetMaximum(Double_t maximum=-1111)
Definition TH1.h:682
virtual Bool_t Add(TF1 *h1, Double_t c1=1, Option_t *option="")
Performs the operation: this = this + c1*f1 if errors are defined (see TH1::Sumw2),...
Definition TH1.cxx:852
virtual void SetBinError(Int_t bin, Double_t error)
Set the bin Error Note that this resets the bin eror option to be of Normal Type and for the non-empt...
Definition TH1.cxx:9436
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition TH1.cxx:3489
TAxis * GetYaxis()
Definition TH1.h:602
void Draw(Option_t *option="") override
Draw this histogram with options.
Definition TH1.cxx:3193
virtual void SetMinimum(Double_t minimum=-1111)
Definition TH1.h:683
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition TH1.cxx:9452
TList * GetListOfFunctions() const
Definition TH1.h:518
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition TH1.cxx:5239
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition TH1.cxx:6815
TObject * Clone(const char *newname="") const override
Make a complete copy of the underlying object.
Definition TH1.cxx:2882
virtual Bool_t Divide(TF1 *f1, Double_t c1=1)
Performs the operation: this = this/(c1*f1) if errors are defined (see TH1::Sumw2),...
Definition TH1.cxx:2969
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition TH1.cxx:9253
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition TH1.cxx:9223
2-D histogram with a double per channel (see TH1 documentation)
Definition TH2.h:400
Service class for 2-D histogram classes.
Definition TH2.h:30
Int_t Fill(Double_t) override
Invalid Fill method.
Definition TH2.cxx:369
The Histogram stack class.
Definition THStack.h:40
TList * GetHists() const
Definition THStack.h:72
virtual void Add(TH1 *h, Option_t *option="")
Add a new histogram to the list.
Definition THStack.cxx:364
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
To draw Mathematical Formula.
Definition TLatex.h:20
Storage class for one entry of a TLegend.
This class displays a legend box (TPaveText) containing several legend entries.
Definition TLegend.h:23
TLegendEntry * AddEntry(const TObject *obj, const char *label="", Option_t *option="lpf")
Add a new entry to this legend.
Definition TLegend.cxx:319
void SetNColumns(Int_t nColumns)
Set the number of columns for the legend.
Definition TLegend.cxx:605
void SetMargin(Float_t margin)
Definition TLegend.h:69
Use the TLine constructor to create a simple line.
Definition TLine.h:22
virtual void SetY2(Double_t y2)
Definition TLine.h:70
virtual void SetX2(Double_t x2)
Definition TLine.h:68
Double_t GetY1() const
Definition TLine.h:52
virtual void SetX1(Double_t x1)
Definition TLine.h:67
virtual void SetY1(Double_t y1)
Definition TLine.h:69
Double_t GetY2() const
Definition TLine.h:53
A doubly linked list.
Definition TList.h:38
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void Add(TObject *obj) override
Definition TList.h:81
Int_t GetNrows() const
Int_t GetNcols() const
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:27
A TMultiGraph is a collection of TGraph (or derived) objects.
Definition TMultiGraph.h:34
virtual void Add(TGraph *graph, Option_t *chopt="")
Add a new graph to the list of graphs.
void Draw(Option_t *chopt="") override
Draw this multigraph with its current attributes.
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
TObject * Clone(const char *newname="") const override
Make a clone of an object using the Streamer facility.
Definition TNamed.cxx:73
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:173
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
void Clear(Option_t *option="") override
Set name and title to empty strings ("").
Definition TNamed.cxx:63
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:149
virtual void SetNameTitle(const char *name, const char *title)
Set all the TNamed parameters (name and title).
Definition TNamed.cxx:163
Mother of all ROOT objects.
Definition TObject.h:42
virtual void Inspect() const
Dump contents of this object in a graphics canvas.
Definition TObject.cxx:569
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition TObject.cxx:242
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1082
virtual TObject * DrawClone(Option_t *option="") const
Draw a clone of this object in the current selected pad with: gROOT->SetSelectedPad(c1).
Definition TObject.cxx:318
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:424
virtual void SaveAs(const char *filename="", Option_t *option="") const
Save this object in the file specified by filename.
Definition TObject.cxx:707
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:886
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:548
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
virtual const char * GetTitle() const
Returns title of object.
Definition TObject.cxx:506
virtual void Draw(Option_t *option="")
Default Draw method for all objects.
Definition TObject.cxx:292
virtual void Print(Option_t *option="") const
This method must be overridden when a class wants to print itself.
Definition TObject.cxx:660
@ kCanDelete
if object in a list can be deleted
Definition TObject.h:71
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1070
The most important graphics class in the ROOT system.
Definition TPad.h:32
TVirtualPad * cd(Int_t subpadnumber=0) override
Set Current pad.
Definition TPad.cxx:758
A Pave (see TPave) with text, lines or/and boxes inside.
Definition TPaveText.h:21
virtual TText * AddText(Double_t x1, Double_t y1, const char *label)
Add a new Text line to this pavetext at given coordinates.
virtual void SetMargin(Float_t margin=0.05)
Definition TPaveText.h:62
virtual void SetY1NDC(Double_t y1)
Definition TPave.h:86
virtual void ConvertNDCtoPad()
Convert pave coordinates from NDC to Pad coordinates.
Definition TPave.cxx:138
virtual void SetName(const char *name="")
Definition TPave.h:81
virtual void SetBorderSize(Int_t bordersize=4)
Sets the border size of the TPave box and shadow.
Definition TPave.h:79
virtual void SetY2NDC(Double_t y2)
Definition TPave.h:87
Define a Pie Chart.
Definition TPie.h:26
void SetEntryVal(Int_t, Double_t)
Set the value of a slice.
Definition TPie.cxx:1180
Int_t GetEntries() const
Definition TPie.h:92
void SetEntryFillColor(Int_t, Int_t)
Set the color for the slice "i".
Definition TPie.cxx:1156
void SetRadius(Double_t)
Set the pie chart's radius' value.
Definition TPie.cxx:1262
void SetEntryLabel(Int_t, const char *text="Slice")
Set slice number "i" label.
Definition TPie.cxx:1123
void Draw(Option_t *option="l") override
Draw the pie chart.
Definition TPie.cxx:295
/**
Definition TQObject.h:48
Regular expression class.
Definition TRegexp.h:31
This class creates a ROOT object browser, constituted by three main tabs.
Sequenceable collection abstract base class.
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 Stop()
Stop the stopwatch.
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:137
Ssiz_t Length() const
Definition TString.h:426
Bool_t IsDec() const
Returns true if all characters in string are decimal digits (0-9).
Definition TString.cxx:2021
void ToLower()
Change string to lower-case.
Definition TString.cxx:1190
Int_t Atoi() const
Return integer value of string.
Definition TString.cxx:2069
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition TString.cxx:2325
Double_t Atof() const
Return floating-point value contained in string.
Definition TString.cxx:2135
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
Definition TString.cxx:1939
TString & Replace(Ssiz_t pos, Ssiz_t n, const char *s)
Definition TString.h:704
const char * Data() const
Definition TString.h:385
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:714
Bool_t IsAlpha() const
Returns true if all characters in string are alphabetic.
Definition TString.cxx:1879
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition TString.cxx:939
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition TString.h:633
Int_t CountChar(Int_t c) const
Return number of times character c occurs in the string.
Definition TString.cxx:523
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:2460
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:642
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:661
TStyle objects may be created to define special styles.
Definition TStyle.h:29
void SetPaintTextFormat(const char *format="g")
Definition TStyle.h:390
Int_t GetOptTitle() const
Definition TStyle.h:248
Float_t GetLabelSize(Option_t *axis="X") const
Return label size.
Definition TStyle.cxx:1146
Float_t GetPadRightMargin() const
Definition TStyle.h:216
Style_t GetTitleFont(Option_t *axis="X") const
Return title font.
Definition TStyle.cxx:1217
Bool_t GetHistMinimumZero() const
Definition TStyle.h:239
Float_t GetPadLeftMargin() const
Definition TStyle.h:215
Float_t GetTitleYSize() const
Definition TStyle.h:281
Double_t GetHistTopMargin() const
Definition TStyle.h:240
Float_t GetPadBottomMargin() const
Definition TStyle.h:213
const char * GetPaintTextFormat() const
Definition TStyle.h:252
Float_t GetPadTopMargin() const
Definition TStyle.h:214
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1297
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1319
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition TSystem.cxx:420
The TTimeStamp encapsulates seconds and ns since EPOCH.
Definition TTimeStamp.h:45
void Add(const TTimeStamp &offset)
Add "offset" as a delta time.
const char * AsString(const Option_t *option="") const
Return the date & time as a string.
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
const char * AsString() const
Return UUID as string. Copy string immediately since it will be reused.
Definition TUUID.cxx:602
static TVirtualPadEditor * GetPadEditor(Bool_t load=kTRUE)
Returns the pad editor dialog. Static method.
TVirtualPad is an abstract base class for the Pad and Canvas classes.
Definition TVirtualPad.h:53
virtual void Modified(Bool_t flag=1)=0
virtual TList * GetListOfPrimitives() const =0
virtual void SetPad(const char *name, const char *title, Double_t xlow, Double_t ylow, Double_t xup, Double_t yup, Color_t color=35, Short_t bordersize=5, Short_t bordermode=-1)=0
virtual TVirtualPad * cd(Int_t subpadnumber=0)=0
const char * GetName() const override=0
Returns name of object.
virtual TVirtualPad * GetPad(Int_t subpadnumber) const =0
virtual void Divide(Int_t nx=1, Int_t ny=1, Float_t xmargin=0.01, Float_t ymargin=0.01, Int_t color=0)=0
virtual Int_t GetLogy() const =0
virtual void SetLogy(Int_t value=1)=0
virtual TObject * GetPrimitive(const char *name) const =0
virtual void SetBorderSize(Short_t bordersize)=0
virtual void SetName(const char *name)=0
static TClass * Class()
TClass * IsA() const override
double evaluate() const override
Evaluate projected p.d.f.
TObject * clone(const char *newname) const override
double expectedEvents(const RooArgSet *nset) const override
Return expected number of events to be used in calculation of extended likelihood.
ExtendMode extendMode() const override
Returns ability of PDF to provide extended likelihood terms.
pt SetTextColor(4)
RooCmdArg RecycleConflictNodes(bool flag=true)
RooConstVar & RooConst(double val)
RooCmdArg Embedded(bool flag=true)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg GlobalObservables(Args_t &&... argsOrArgSet)
RooCmdArg ExternalConstraints(const RooArgSet &constraintPdfs)
RooCmdArg Range(const char *rangeName, bool adjustNorm=true)
const Double_t sigma
int main()
Definition main.cpp:18
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
TGraphErrors * gr
Definition legend1.C:25
return c2
Definition legend2.C:14
double gaussian_cdf(double x, double sigma=1, double x0=0)
Alternative name for same function.
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
bool EndsWith(std::string_view string, std::string_view suffix)
TClass * GetClass(T *)
Definition TClass.h:683
auto find(Objects_t &objects, std::string const &name) -> decltype(std::get_if< Body_t >(&objects.begin() ->body))
The body of the object name if it is a Body_t, e.g. find<CombinedData>(doc.data, "obsData"),...
Definition HS3Document.h:77
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
static constexpr auto NumIntegration
Alias of MsgLevel::NumericIntegration for backwards compatibility.
MsgLevel
Verbosity level for RooMsgService::StreamConfig in RooMsgService.
@ NumericIntegration
Double_t Prob(Double_t chi2, Int_t ndf)
Computation of the probability for a certain Chi-squared (chi2) and number of degrees of freedom (ndf...
Definition TMath.cxx:637
Double_t ChisquareQuantile(Double_t p, Double_t ndf)
Evaluate the quantiles of the chi-squared probability distribution function.
Definition TMath.cxx:2196
Double_t StdDev(Long64_t n, const T *a, const Double_t *w=nullptr)
Same as RMS.
Definition TMath.h:536
std::string GetName(TCppScope_t)
#define BEGIN_XROOFIT_NAMESPACE
Definition Config.h:24
#define END_XROOFIT_NAMESPACE
Definition Config.h:25
static const char * what
Definition stlLoader.cc:5
RooAbsBinning * b
RooRealVar * x
void removeTopic(RooFit::MsgTopic oldTopic)
bool isNaNWithPayload() const
Test if this struct has a float packed into its mantissa.
static float unpackNaN(double val)
If val is NaN and a this NaN has been tagged as containing a payload, unpack the float from the manti...
th1 Draw()
TLine lv
Definition textalign.C:5
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
auto * tt
Definition textangle.C:16
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335
#define GETWS(a)
#define GETWSSETS(w)
void(* gOldHandlerr)(int)
void addLegendEntry(TObject *o, const char *title, const char *opt)
void buildHistogramInterrupt(int signum)
auto GETACTBROWSER(TRootBrowser *b)
Definition xRooNode.cxx:111
auto & GETWSSNAPSHOTS(RooWorkspace *w)
Definition xRooNode.cxx:107
bool TopRightPlaceBox(TPad *p, TObject *o, double w, double h, double &xl, double &yb)
#define GETDMP(o, m)
Definition xRooNode.cxx:123
TPaveText * getPave(const char *name="labels", bool create=true, bool doPaint=false)
std::string formatLegendString(const std::string &s)
auto GETROOTDIR(TGFileBrowser *b)
Definition xRooNode.cxx:115
const xRooNode * runningNode
auto GETLISTTREE(TGFileBrowser *b)
Definition xRooNode.cxx:119
const T & _or_func(const T &a, const T &b)
Definition xRooNode.cxx:229
std::vector< double > new_getPropagatedErrors(const RooAbsReal &f, const RooFitResult &fr, const RooArgSet &nset, RooArgList **pars, bool asymHi, bool asymLo, const std::vector< int > &bins, const std::function< void(int)> &setBin)
TLegend * getLegend(bool create=true, bool doPaint=false)