Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rf616_morphing.C File Reference

Detailed Description

View in nbviewer Open in SWAN
Use Morphing in RooFit.

This tutorial shows how to use template morphing inside RooFit. As input we have several Gaussian distributions. The output is one gaussian, with a specific mean value. Since likelihoods are often used within the framework of morphing, we provide a way to estimate the negative log likelihood (nll).

Based on example of Kyle Cranmer https://gist.github.com/cranmer/b67830e46d53d5f7cf2d.

#include "RooRealVar.h"
#include "RooRealVar.h"
#include "RooWorkspace.h"
#include "RooGaussian.h"
#include "RooUniform.h"
#include "RooDataSet.h"
#include "RooPlot.h"
#include "RooAbsPdf.h"
using namespace RooFit;
// Number of samples to fill the histograms
const int n_samples = 1000;
// Kills warning massages
// Define the morphing routine
RooPlot *perform_morphing(RooWorkspace &ws, RooMomentMorphFuncND::Setting setting, double sigma)
{
// Get Variables from the workspace
RooRealVar *x_var = ws.var("x");
RooRealVar *mu_var = ws.var("mu");
RooAbsPdf *gauss = ws.pdf("gauss");
// Initialize a plot
RooPlot *frame1 = x_var->frame();
// Define binning for morphing
// Set binning of histograms, has to be customized for optimal results
x_var->setBins(50);
std::vector<int> parampoints = {0, 1, 2, 3, 4};
for (auto i : parampoints) {
// Define the sampled gaussians
RooRealVar mu_help(Form("mu%d", i), Form("mu%d", i), i);
// Use * because RooGaussian expects objects no pointers
RooGaussian help(Form("g%d", i), Form("g%d", i), *x_var, mu_help, sigma);
ws.import(help, Silence(true));
// Fill the histograms use a unique pointer to prevent memory leaks
std::unique_ptr<RooDataHist> hist1{
dynamic_cast<RooDataHist *>(ws.pdf(Form("g%d", i))->generateBinned(*x_var, 100 * n_samples))};
// Add the value 1 to each bin
for (int i_bin = 0; i_bin < hist1->numEntries(); ++i_bin) {
const RooArgSet *binContent = hist1->get(i_bin);
hist1->add(*binContent, 1.0);
}
// Add the pdf to the workspace, the inOrder of 1 is necessary for calculation of the nll
// Adjust it to 0 to see binning
ws.import(RooHistPdf(Form("histpdf%d", i), Form("histpdf%d", i), *x_var, *hist1, 1), Silence(true));
// Plot and add the pdf to the grid
RooAbsPdf *pdf = ws.pdf(Form("histpdf%d", i));
pdf->plotOn(frame1);
grid.addPdf(*pdf, i);
}
// Create the morphing
RooMomentMorphFuncND morph_func("morpf_func", "morph_func", RooArgList(*mu_var), RooArgList(*x_var), grid, setting);
// Normalizing the morphed object to be a pdf, set it false to prevent warning messages and gain computational speed
// up
morph_func.setPdfMode();
// Creating the morphed pdf
RooWrapperPdf morph("morph", "morph", morph_func, true);
ws.import(morph, Silence(true));
RooAbsPdf *morph_ = ws.pdf("morph");
morph_->plotOn(frame1, LineColor(kRed));
return frame1;
}
// Define the workspace
std::unique_ptr<RooWorkspace> build_ws(double mu_observed, double sigma)
{
auto ws = std::make_unique<RooWorkspace>();
ws->factory(Form("Gaussian::gauss(x[-5,15],mu[%f,0,4], %f)", mu_observed, sigma));
return ws;
}
// Do the example
{
// Define the 'observed' mu
double mu_observed = 2.5;
double sigma = 1.5;
// Import variables from workspace
std::unique_ptr<RooWorkspace> ws = build_ws(mu_observed, sigma);
RooPlot *frame1 = perform_morphing(*ws, RooMomentMorphFuncND::Linear, sigma);
RooRealVar *x_var = ws->var("x");
RooRealVar *mu_var = ws->var("mu");
RooAbsPdf *gauss = ws->pdf("gauss");
RooDataSet *obs_data = gauss->generate(*x_var, n_samples);
// Create the exact negative log likelihood function for Gaussian model
RooAbsReal *nll_gauss = gauss->createNLL(*obs_data);
// Create the morphed negative log likelihood function
// TODO: Fix RooAddPdf::fixCoefNormalization(nset) warnings with new CPU backend
RooAbsReal *nll_morph = ws->pdf("morph")->createNLL(*obs_data, RooFit::EvalBackend("legacy"));
// Plot the negative logarithmic summed likelihood
RooPlot *frame2 = mu_var->frame(Title("Negative log Likelihood"));
nll_gauss->plotOn(frame2, LineColor(kBlue), ShiftToZero(), Name("gauss"));
nll_morph->plotOn(frame2, LineColor(kRed), ShiftToZero(), Name("morph"));
TCanvas *c = new TCanvas("rf616_morphing", "rf616_morphing", 800, 400);
c->Divide(2);
c->cd(1);
gPad->SetLeftMargin(0.15);
frame1->GetYaxis()->SetTitleOffset(1.4);
frame1->Draw();
c->cd(2);
gPad->SetLeftMargin(0.15);
frame2->GetYaxis()->SetTitleOffset(1.8);
frame2->Draw();
// Compute the minimum of the nll via minuit
std::vector<RooAbsReal *> nlls = {nll_gauss, nll_morph};
for (auto nll : nlls) {
RooMinimizer minimizer(*nll);
minimizer.setPrintLevel(-1);
minimizer.minimize("Minuit2");
RooFitResult *result = minimizer.save();
result->Print();
}
}
#define c(i)
Definition RSha256.hxx:101
@ kRed
Definition Rtypes.h:66
@ kBlue
Definition Rtypes.h:66
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
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
#define gPad
Storage_t const & get() const
Const access to the underlying stl container.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
RooFit::OwningPtr< RooAbsReal > createNLL(RooAbsData &data, CmdArgs_t const &... cmdArgs)
Construct representation of -log(L) of PDF with given dataset.
Definition RooAbsPdf.h:163
RooPlot * plotOn(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 RooCmdArg &arg9={}, const RooCmdArg &arg10={}) const override
Helper calling plotOn(RooPlot*, RooLinkedList&) const.
Definition RooAbsPdf.h:124
RooFit::OwningPtr< RooDataSet > generate(const RooArgSet &whatVars, Int_t nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={})
See RooAbsPdf::generate(const RooArgSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,...
Definition RooAbsPdf.h:57
virtual RooFit::OwningPtr< RooDataHist > generateBinned(const RooArgSet &whatVars, double nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}) const
As RooAbsPdf::generateBinned(const RooArgSet&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,...
Definition RooAbsPdf.h:110
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,...
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
virtual RooPlot * plotOn(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 RooCmdArg &arg9={}, const RooCmdArg &arg10={}) const
Plot (project) PDF on specified frame.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
Implements a RooAbsBinning in terms of an array of boundary values, posing no constraints on the choi...
Definition RooBinning.h:27
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
Container class to hold unbinned data.
Definition RooDataSet.h:34
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
A propability density function sampled from a multidimensional histogram.
Definition RooHistPdf.h:30
Wrapper class around ROOT::Math::Minimizer that provides a seamless interface between the minimizer f...
static RooMsgService & instance()
Return reference to singleton instance.
void setGlobalKillBelow(RooFit::MsgLevel level)
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
TAxis * GetYaxis() const
Definition RooPlot.cxx:1224
void Draw(Option_t *options=nullptr) override
Draw this plot and all of the elements it contains.
Definition RooPlot.cxx:597
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setBins(Int_t nBins, const char *name=nullptr)
Create a uniform binning under name 'name' for this variable.
Persistable container for RooFit projects.
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooFactoryWSTool & factory()
Return instance to factory tool.
RooRealVar * var(RooStringView name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
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.
The RooWrapperPdf is a class that can be used to convert a function into a PDF.
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title.
Definition TAttAxis.cxx:298
The Canvas class.
Definition TCanvas.h:23
RooCmdArg Silence(bool flag=true)
RooCmdArg ShiftToZero()
RooCmdArg LineColor(Color_t color)
const Double_t sigma
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:64
const char * Name
Definition TXMLSetup.cxx:67
const char * Title
Definition TXMLSetup.cxx:68
RooFitResult: minimized FCN value: 1805.81, estimated distance to minimum: 1.13014e-08
covariance matrix quality: Full, accurate covariance matrix
Status : MINIMIZE=0
Floating Parameter FinalValue +/- Error
-------------------- --------------------------
mu 2.4940e+00 +/- 4.74e-02
RooFitResult: minimized FCN value: 1806.33, estimated distance to minimum: 1.41682e-05
covariance matrix quality: Full, accurate covariance matrix
Status : MINIMIZE=0
Floating Parameter FinalValue +/- Error
-------------------- --------------------------
mu 2.4899e+00 +/- 4.59e-02
Date
August 2024
Author
Robin Syring

Definition in file rf616_morphing.C.