Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
ModelInspector.C File Reference

Detailed Description

RooStats Model Inspector.

Usage: The usage is the same as the StandardXxxDemo.C macros. The macro expects a root file containing a workspace with a ModelConfig and a dataset

$ root
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.

Drag the sliders to adjust the parameters of the model. the min and max range of the sliders are used to define the upper & lower variation the pointer position of the slider is the central blue curve.

Click the FIT button to

To Do:

  • check boxes to specify which nuisance parameters used in making variation
  • a button to make the profile inspector plots
  • a check button to use MINOS errors
  • have fit button show the covariance matrix from the fit
  • a button to make the log likelihood plots
  • a dialog to open the desired file
  • ability to see the signal and background contributions?
#include "TGButton.h"
#include "TGLayout.h"
#include "TF1.h"
#include "TMath.h"
#include "TSystem.h"
#include "TCanvas.h"
#include "TGTextEntry.h"
#include "TGLabel.h"
#include "TGTripleSlider.h"
#include "RooWorkspace.h"
#include "TFile.h"
#include "RooArgSet.h"
#include "TList.h"
#include "RooAbsPdf.h"
#include "RooRealVar.h"
#include "RooPlot.h"
#include "TGButton.h"
#include <map>
#include "RooFitResult.h"
#include "TROOT.h"
#include <TApplication.h>
#include "RooCategory.h"
};
using std::map, std::vector, std::cout, std::endl;
using namespace RooFit;
using namespace RooStats;
private:
RooPlot *fPlot;
TFile *fFile;
RooAbsData *fData;
TGButton *fFitButton;
// BB: a TGCanvas and a vertical frame are needed for using scrollbars
TGCanvas *fCan;
public:
~ModelInspectorGUI() override;
void CloseWindow() override;
void DoText(const char *text);
void DoSlider();
void DoSlider(const char *);
void DoFit();
void DoExit();
void HandleButtons();
};
//______________________________________________________________________________
ModelInspectorGUI::ModelInspectorGUI(RooWorkspace *w, ModelConfig *mc, RooAbsData *data)
: TGMainFrame(gClient->GetRoot(), 100, 100)
{
RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
fWS = w;
fMC = mc;
fData = data;
RooSimultaneous *simPdf = nullptr;
if (strcmp(fMC->GetPdf()->ClassName(), "RooSimultaneous") == 0) {
cout << "Is a simultaneous PDF" << endl;
simPdf = (RooSimultaneous *)(fMC->GetPdf());
RooCategory *channelCat = (RooCategory *)(&simPdf->indexCat());
cout << " with " << channelCat->numTypes() << " categories" << endl;
numCats = channelCat->numTypes();
} else {
cout << "Is not a simultaneous PDF" << endl;
}
fFitRes = nullptr;
SetCleanup(kDeepCleanup);
// Create an embedded canvas and add to the main frame, centered in x and y
// and with 30 pixel margins all around
fCanvas = new TRootEmbeddedCanvas("Canvas", this, 600, 400);
AddFrame(fCanvas, fLcan);
fPlotList.resize(numCats);
if (numCats > 1) {
fCanvas->GetCanvas()->Divide(numCats);
for (int i = 0; i < numCats; ++i) {
fCanvas->GetCanvas()->cd(i + 1)->SetBorderMode(0);
fCanvas->GetCanvas()->cd(i + 1)->SetGrid();
}
}
fHframe0 = new TGHorizontalFrame(this, 0, 0, 0);
fCheck1 = new TGCheckButton(fHframe0, "&Constrained", HCId1);
fCheck2 = new TGCheckButton(fHframe0, "&Relative", HCId2);
fCheck1->SetState(kButtonUp);
fCheck2->SetState(kButtonUp);
fCheck1->SetToolTipText("Pointer position constrained to slider sides");
fCheck2->SetToolTipText("Pointer position relative to slider position");
fHframe0->Resize(200, 50);
fHframe2 = new TGHorizontalFrame(this, 0, 0, 0);
fFitButton = new TGTextButton(fHframe2, "Fit");
fFitButton->Connect("Clicked()", "ModelInspectorGUI", this, "DoFit()");
fExitButton->Connect("Clicked()", "ModelInspectorGUI", this, "DoExit()");
fCheck1->Connect("Clicked()", "ModelInspectorGUI", this, "HandleButtons()");
fCheck2->Connect("Clicked()", "ModelInspectorGUI", this, "HandleButtons()");
fHframe2->Resize(100, 25);
//--- layout for buttons: top align, equally expand horizontally
//--- layout for the frame: place at bottom, right aligned
fHframe2->AddFrame(fFitButton, fBfly2);
AddFrame(fHframe0, fBly);
AddFrame(fHframe2, fBly);
// Loop over POI & NP, create slider
// need maps of NP->slider? or just slider->NP
RooArgSet parameters;
parameters.add(*fMC->GetParametersOfInterest());
parameters.add(*fMC->GetNuisanceParameters());
// BB: This is the part needed in order to have scrollbars
fCan = new TGCanvas(this, 100, 100, kFixedSize);
fVFrame = new TGVerticalFrame(fCan->GetViewPort(), 10, 10);
fCan->SetContainer(fVFrame);
// And that't it!
// Obviously, the parent of other subframes is now fVFrame instead of "this"...
for (auto *param : static_range_cast<RooRealVar *>(parameters)) {
cout << "Adding Slider for " << param->GetName() << endl;
new TGLabel(hframek, Form("%s = %.3f +%.3f", param->GetName(), param->getVal(), param->getError()));
GetDefaultFrameBackground(), kFALSE, kFALSE, kFALSE, kFALSE);
hsliderk->Connect("PointerPositionChanged()", "ModelInspectorGUI", this, "DoSlider()");
hsliderk->Connect("PositionChanged()", "ModelInspectorGUI", this, "DoSlider()");
hsliderk->SetRange(param->getMin(), param->getMax());
hframek->Resize(200, 25);
hsliderk->SetPosition(param->getVal() - param->getError(), param->getVal() + param->getError());
hsliderk->SetPointerPosition(param->getVal());
hframek->AddFrame(hlabel, fBly);
hframek->AddFrame(hsliderk, fBly);
fVFrame->AddFrame(hframek, fBly);
fSliderMap[hsliderk] = param->GetName();
}
// Set main frame name, map sub windows (buttons), initialize layout
// algorithm via Resize() and map main frame
SetWindowName("RooFit/RooStats Model Inspector");
Resize(GetDefaultSize());
MapWindow();
DoSlider();
}
//______________________________________________________________________________
ModelInspectorGUI::~ModelInspectorGUI()
{
// Clean up
Cleanup();
}
//______________________________________________________________________________
void ModelInspectorGUI::CloseWindow()
{
// Called when window is closed via the window manager.
delete this;
}
//______________________________________________________________________________
void ModelInspectorGUI::DoText(const char * /*text*/)
{
// Handle text entry widgets.
Int_t id = te->WidgetId();
switch (id) {
case HId1: fHslider1->SetPosition(atof(fTbh1->GetString()), static_cast<double>(fHslider1->GetMaxPosition())); break;
case HId2: fHslider1->SetPointerPosition(atof(fTbh2->GetString())); break;
case HId3: fHslider1->SetPosition(static_cast<double>(fHslider1->GetMinPosition()), atof(fTbh1->GetString())); break;
default: break;
}
DoSlider();
}
//______________________________________________________________________________
void ModelInspectorGUI::DoFit()
{
fFitRes = fMC->GetPdf()->fitTo(*fData, Save());
map<TGTripleHSlider *, const char *>::iterator it;
;
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
RooRealVar *param = fWS->var(it->second);
param = (RooRealVar *)fFitRes->floatParsFinal().find(it->second);
it->first->SetPosition(param->getVal() - param->getError(), param->getVal() + param->getError());
it->first->SetPointerPosition(param->getVal());
}
DoSlider();
}
//______________________________________________________________________________
void ModelInspectorGUI::DoSlider(const char *text)
{
cout << "." << text << endl;
}
//______________________________________________________________________________
void ModelInspectorGUI::DoSlider()
{
// Handle slider widgets.
// char buf[32];
RooSimultaneous *simPdf = nullptr;
if (strcmp(fMC->GetPdf()->ClassName(), "RooSimultaneous") == 0) {
simPdf = (RooSimultaneous *)(fMC->GetPdf());
RooCategory *channelCat = (RooCategory *)(&simPdf->indexCat());
numCats = channelCat->numTypes();
} else {
}
/////////////////////////////////////////////
if (!simPdf) {
/////////////////////////////////////////////
// if not SimPdf
/////////////////////////////////////////////
// pre loop
map<TGTripleHSlider *, const char *>::iterator it;
;
delete fPlot;
fPlot = ((RooRealVar *)fMC->GetObservables()->first())->frame();
fData->plotOn(fPlot);
double normCount;
// high loop
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
const char *name = it->second;
fWS->var(name)->setVal(it->first->GetMaxPosition());
RooRealVar *param = fWS->var(name);
fLabelMap[it->first]->SetText(Form("%s = %.3f [%.3f,%.3f]", param->GetName(), it->first->GetPointerPosition(),
it->first->GetMinPosition(), it->first->GetMaxPosition()));
}
normCount = fMC->GetPdf()->expectedEvents(*fMC->GetObservables());
// low loop
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
const char *name = it->second;
fWS->var(name)->setVal(it->first->GetMinPosition());
}
normCount = fMC->GetPdf()->expectedEvents(*fMC->GetObservables());
// central oop
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
const char *name = it->second;
fWS->var(name)->setVal(it->first->GetPointerPosition());
}
normCount = fMC->GetPdf()->expectedEvents(*fMC->GetObservables());
fPlot->Draw();
fCanvas->GetCanvas()->Modified();
fCanvas->GetCanvas()->Update();
////////////////////////////////////////////////////////////////////////////
} else {
////////////////////////////////////////////////////////////////////////////
// else (is simpdf)
////////////////////////////////////////////////////////////////////////////
RooCategory *channelCat = (RooCategory *)(&simPdf->indexCat());
// TIterator* iter = simPdf->indexCat().typeIterator() ;
for (auto const& tt : *channelCat) {
auto const& catName = tt.first;
fCanvas->GetCanvas()->cd(frameIndex);
// pre loop
RooAbsPdf *pdftmp = simPdf->getPdf(catName.c_str());
RooArgSet *obstmp = pdftmp->getObservables(*fMC->GetObservables());
RooRealVar *obs = ((RooRealVar *)obstmp->first());
fPlot = fPlotList.at(frameIndex - 1);
if (fPlot)
delete fPlot;
fPlot = obs->frame();
fPlotList.at(frameIndex - 1) = fPlot;
fData->plotOn(fPlot, MarkerSize(1),
Cut(Form("%s==%s::%s", channelCat->GetName(), channelCat->GetName(), catName.c_str())),
RooMsgService::instance().setGlobalKillBelow(msglevel);
map<TGTripleHSlider *, const char *>::iterator it;
;
double normCount;
// high loop
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
const char *name = it->second;
fWS->var(name)->setVal(it->first->GetMaxPosition());
RooRealVar *param = fWS->var(name);
fLabelMap[it->first]->SetText(Form("%s = %.3f [%.3f,%.3f]", param->GetName(),
it->first->GetPointerPosition(), it->first->GetMinPosition(),
it->first->GetMaxPosition()));
}
normCount = pdftmp->expectedEvents(*obs);
// low loop
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
const char *name = it->second;
fWS->var(name)->setVal(it->first->GetMinPosition());
RooRealVar *param = fWS->var(name);
fLabelMap[it->first]->SetText(Form("%s = %.3f [%.3f,%.3f]", param->GetName(),
it->first->GetPointerPosition(), it->first->GetMinPosition(),
it->first->GetMaxPosition()));
}
normCount = pdftmp->expectedEvents(*obs);
// central loop
it = fSliderMap.begin();
for (; it != fSliderMap.end(); ++it) {
const char *name = it->second;
fWS->var(name)->setVal(it->first->GetPointerPosition());
RooRealVar *param = fWS->var(name);
fLabelMap[it->first]->SetText(Form("%s = %.3f [%.3f,%.3f]", param->GetName(),
it->first->GetPointerPosition(), it->first->GetMinPosition(),
it->first->GetMaxPosition()));
}
normCount = pdftmp->expectedEvents(*obs);
if (!fFitRes)
else {
VisualizeError(*fFitRes, *fMC->GetNuisanceParameters()), FillColor(kYellow));
msglevel = RooMsgService::instance().globalKillBelow();
fData->plotOn(fPlot, MarkerSize(1),
Cut(Form("%s==%s::%s", channelCat->GetName(), channelCat->GetName(), catName.c_str())),
RooMsgService::instance().setGlobalKillBelow(msglevel);
}
fPlot->Draw();
}
fCanvas->GetCanvas()->Modified();
fCanvas->GetCanvas()->Update();
///////////////////////////////////////////
// end if(simPdf)
}
}
//______________________________________________________________________________
void ModelInspectorGUI::HandleButtons()
{
// Handle different buttons.
Int_t id = btn->WidgetId();
switch (id) {
case HCId1: fHslider1->SetConstrained(fCheck1->GetState()); break;
case HCId2: fHslider1->SetRelative(fCheck2->GetState()); break;
default: break;
}
}
void ModelInspectorGUI::DoExit()
{
printf("Exit application...");
}
void ModelInspector(const char *infile = "", const char *workspaceName = "combined",
const char *modelConfigName = "ModelConfig", const char *dataName = "obsData")
{
// -------------------------------------------------------
// First part is just to access a user-defined file
// or create the standard example file if it doesn't exist
const char *filename = "";
if (!strcmp(infile, "")) {
filename = "results/example_combined_GaussExample_model.root";
bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
// if file does not exists generate with histfactory
if (!fileExist) {
// Normally this would be run on the command line
cout << "will run standard hist2workspace example" << endl;
gROOT->ProcessLine(".! prepareHistFactory .");
gROOT->ProcessLine(".! hist2workspace config/example.xml");
cout << "\n\n---------------------" << endl;
cout << "Done creating example input" << endl;
cout << "---------------------\n\n" << endl;
}
} else
// Try to open the file
// if input file was specified byt not found, quit
if (!file) {
cout << "StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
return;
}
// -------------------------------------------------------
// Tutorial starts here
// -------------------------------------------------------
// get the workspace out of the file
if (!w) {
cout << "workspace not found" << endl;
return;
}
// get the modelConfig out of the file
// get the modelConfig out of the file
// make sure ingredients are found
if (!data || !mc) {
w->Print();
cout << "data or ModelConfig was not found" << endl;
return;
}
}
@ kHorizontalFrame
Definition GuiTypes.h:382
@ kFixedSize
Definition GuiTypes.h:390
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
int Int_t
Definition RtypesCore.h:45
constexpr Bool_t kFALSE
Definition RtypesCore.h:101
@ kRed
Definition Rtypes.h:66
@ kGreen
Definition Rtypes.h:66
@ kBlue
Definition Rtypes.h:66
@ kYellow
Definition Rtypes.h:66
R__EXTERN TApplication * gApplication
@ kButtonUp
Definition TGButton.h:53
#define gClient
Definition TGClient.h:156
@ kDoubleScaleBoth
@ kDeepCleanup
Definition TGFrame.h:42
@ kLHintsRight
Definition TGLayout.h:26
@ kLHintsExpandY
Definition TGLayout.h:31
@ kLHintsLeft
Definition TGLayout.h:24
@ kLHintsCenterX
Definition TGLayout.h:25
@ kLHintsTop
Definition TGLayout.h:27
@ kLHintsExpandX
Definition TGLayout.h:30
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 data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize MapSubwindows
Option_t Option_t TPoint TPoint const char text
char name[80]
Definition TGX11.cxx:110
R__EXTERN void * gTQSender
Definition TQObject.h:46
#define gROOT
Definition TROOT.h:406
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
R__EXTERN TSystem * gSystem
Definition TSystem.h:566
const_iterator begin() const
const_iterator end() const
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
RooPlot * frame(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 new RooPlot on the heap with a drawing frame initialized for this object,...
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:103
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
Object to represent discrete states.
Definition RooCategory.h:28
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
static RooMsgService & instance()
Return reference to singleton instance.
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:45
Variable that can be changed from the outside.
Definition RooRealVar.h:37
double getError() const
Definition RooRealVar.h:58
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition ModelConfig.h:35
Persistable container for RooFit projects.
virtual void Terminate(Int_t status=0)
Terminate the application by call TSystem::Exit() unless application has been told to return from Run...
TObject * Get(const char *namecycle) override
Return pointer to object identified by namecycle.
1-Dim function class
Definition TF1.h:233
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
Definition TFile.h:53
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4094
A button abstract base class.
Definition TGButton.h:68
A frame containing two scrollbars (a horizontal and a vertical) and a viewport.
Definition TGCanvas.h:192
Selects different options.
Definition TGButton.h:264
A composite frame that layout their children in horizontal way.
Definition TGFrame.h:385
This class handles GUI labels.
Definition TGLabel.h:24
This class describes layout hints used by the layout classes.
Definition TGLayout.h:50
Defines top level windows that interact with the system Window Manager.
Definition TGFrame.h:397
A text buffer is used in several widgets, like TGTextEntry, TGFileDialog, etc.
Yield an action as soon as it is clicked.
Definition TGButton.h:142
A TGTextEntry is a one line text input widget.
Definition TGTextEntry.h:24
TripleSlider inherit from DoubleSlider widgets and allow easy selection of a min, max and pointer val...
A composite frame that layout their children in vertical way.
Definition TGFrame.h:374
A doubly linked list.
Definition TList.h:38
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
This class creates a TGCanvas in which a TCanvas is created.
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:1296
RooCmdArg Save(bool flag=true)
RooCmdArg DataError(Int_t)
RooCmdArg FillColor(Color_t color)
RooCmdArg LineWidth(Width_t width)
RooCmdArg Normalization(double scaleFactor)
RooCmdArg VisualizeError(const RooDataSet &paramData, double Z=1)
RooCmdArg MarkerSize(Size_t size)
RooCmdArg Cut(const char *cutSpec)
RooCmdArg LineColor(Color_t color)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26
MsgLevel
Verbosity level for RooMsgService::StreamConfig in RooMsgService.
@ NumIntegration
Namespace for the RooStats classes.
Definition Asimov.h:19
auto * tt
Definition textangle.C:16
  • Version 1, October 2011
    • based on tutorial macro by Bertrand Bellenot, Ilka Antcheva
  • Version 2, November 2011
    • fixes from Bertrand Bellenot for scrolling window for many parameters
Author
Kyle Cranmer

Definition in file ModelInspector.C.