Skip to content

Instantly share code, notes, and snippets.

@VanyaBelyaev
Created August 25, 2022 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanyaBelyaev/2f385ea57efa04a618e1b39f01b39cbe to your computer and use it in GitHub Desktop.
Save VanyaBelyaev/2f385ea57efa04a618e1b39f01b39cbe to your computer and use it in GitHub Desktop.
Treatment of errors for fits to unbinned/.binned/weighted datasets
import ROOT, random
## 1) create Gaussian fit models
xvar = ROOT.RooRealVar( 'x' , 'x-observable' , 0 , 10 )
mean = ROOT.RooRealVar( 'mean' , 'mean-value for Gaussian' , 5 , 2 , 8 )
sigma = ROOT.RooRealVar( 'sigma' , 'sigma-value for Gaussian' , 1 , 0.5 , 2.0 )
gauss = ROOT.RooGaussian( 'G' , 'Gaussian model' , xvar , mean , sigma )
## 2) create and fill dataste & histogram
varset = ROOT.RooArgSet( xvar )
dataset = ROOT.RooDataSet ( 'data' , 'unbineed dataset' , varset )
histo = ROOT.TH1D( 'h1000' , 'Test histogram' , 200 , 0 , 10 )
for i in range ( 1000 ) :
value = random.gauss ( 5 , 1 )
xvar.setVal ( value )
dataset.add ( varset )
histo.Fill ( value )
## 4) convert histogram into RooDataHist
vlst = ROOT.RooArgList ( xvar )
hdset = ROOT.RooDataHist ( 'bdset' , '(binned) data as RooFataHist' , vlst , ROOT.RooFit.Import ( histo ) )
## 4) convert historgam into weighted dataset
wvar = ROOT.RooRealVar ('weight' , 'weight-variable' , 1 , -100 , +1e+6 )
wset = ROOT.RooArgSet ( wvar )
vset = ROOT.RooArgSet ( xvar , wvar )
wargs = ROOT.RooFit.WeightVar ( wvar ) , ROOT.RooFit.StoreError ( wset )
wdset = ROOT.RooDataSet ( 'wdset' , '(binned) data as Weighted RooDataSet' , vset , *wargs )
for ibin in range ( 1 , histo.GetNbinsX()+1 ) :
value = histo.GetBinContent ( ibin )
error = histo.GetBinError ( ibin )
xvalue = histo.GetBinCenter ( ibin )
xvar.setVal ( xvalue )
wdset.add ( vset , value , error )
# 5) make reference fit to unbinned RooDataHist
r0 = gauss.fitTo ( dataset , ROOT.RooFit.Save() )
r0.Print ()
# 6) make fit to the binned dataset (as RooDataHist)
rh = gauss.fitTo ( hdset , ROOT.RooFit.Save() )
rh.Print ()
# 7) make fit to the binned datatset (as weighted RooDataSet with no special treatment of errors)
rw1 = gauss.fitTo ( wdset , ROOT.RooFit.Save() )
rw1.Print ()
# 8) make fit to the binned datatset (as weighted RooDataSet with SumW2 options)
rw2 = gauss.fitTo ( wdset , ROOT.RooFit.Save() , ROOT.RooFit.SumW2Error ( True ) )
rw2.Print ()
# 9) make fit to the binned datatset (as weighted RooDataSet with "correct" treatment of weights&errors)
rw3 = gauss.fitTo ( wdset , ROOT.RooFit.Save() , ROOT.RooFit.AsymptoticError ( True ) )
rw3.Print ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment