31from warnings
import warn
39 def __init__(self, **entries):
40 self.__dict__.
update(entries)
43HypoTestOptions = Struct(
50 enableDetailedOutput=
True,
53optHT = HypoTestOptions
58 workspaceName="combined",
59 modelSBName="ModelConfig",
69 noSystematics = optHT.noSystematics
70 nToysRatio = optHT.nToysRatio
71 poiValue = optHT.poiValue
72 printLevel = optHT.printLevel
73 generateBinned = optHT.generateBinned
74 enableDetOutput = optHT.enableDetailedOutput
106 ROOT.RooStats.SimpleLikelihoodRatioTestStat.SetAlwaysReuseNLL(
True)
107 ROOT.RooStats.ProfileLikelihoodTestStat.SetAlwaysReuseNLL(
True)
108 ROOT.RooStats.RatioOfProfiledLikelihoodsTestStat.SetAlwaysReuseNLL(
True)
124 filename =
"results/example_combined_GaussExample_model.root"
125 fileExist =
not ROOT.gSystem.AccessPathName(filename, ROOT.kFileExists)
129 print(
"will run standard hist2workspace example")
130 ROOT.gROOT.ProcessLine(
".! prepareHistFactory .")
131 ROOT.gROOT.ProcessLine(
".! hist2workspace config/example.xml")
132 print(
"\n\n---------------------")
133 print(
"Done creating example input")
134 print(
"---------------------\n\n")
140 file = ROOT.TFile.Open(filename)
144 print(f
"StandardRooStatsDemoMacro: Input file {filename} is not found")
152 w = file.Get(workspaceName)
154 print(f
"workspace not found")
160 sbModel = w.obj(modelSBName)
163 data = w.data(dataName)
166 if not data
or not sbModel:
168 print(f
"data or ModelConfig was not found")
172 bModel = w.obj(modelBName)
177 nuisPar = sbModel.GetNuisanceParameters()
178 if nuisPar
and nuisPar.getSize() > 0:
179 print(f
"StandardHypoTestInvDemo")
180 print(
" - Switch off all systematics by setting them constant to their initial values")
184 bnuisPar = bModel.GetNuisanceParameters()
189 ROOT.Info(
"StandardHypoTestInvDemo",
"The background model {} does not exist".
format(modelBName))
190 ROOT.Info(
"StandardHypoTestInvDemo",
"Copy it from ModelConfig {} and set POI to zero".
format(modelSBName))
191 bModel = sbModel.Clone()
192 bModel.SetName(modelSBName +
"B_only")
193 var = bModel.GetParametersOfInterest().first()
196 oldval = var.getVal()
199 bModel.SetSnapshot(ROOT.RooArgSet(var))
202 if not sbModel.GetSnapshot()
or (poiValue > 0):
203 ROOT.Info(
"StandardHypoTestDemo",
"Model {} has no snapshot - make one using model poi".
format(modelSBName))
204 var = sbModel.GetParametersOfInterest().first()
207 oldval = var.getVal()
211 sbModel.SetSnapshot(ROOT.RooArgSet(var))
217 slrts = ROOT.RooStats.SimpleLikelihoodRatioTestStat(bModel.GetPdf(), sbModel.GetPdf())
219 nullParams = ROOT.RooArgSet(bModel.GetSnapshot())
220 if bModel.GetNuisanceParameters():
221 nullParams.add(bModel.GetNuisanceParameters())
223 slrts.SetNullParameters(nullParams)
224 altParams = ROOT.RooArgSet(sbModel.GetSnapshot())
225 if sbModel.GetNuisanceParameters():
226 altParams.add(sbModel.GetNuisanceParameters())
227 slrts.SetAltParameters(altParams)
229 profll = ROOT.RooStats.ProfileLikelihoodTestStat(bModel.GetPdf())
231 ropl = ROOT.RooStats.RatioOfProfiledLikelihoodsTestStat(bModel.GetPdf(), sbModel.GetPdf(), sbModel.GetSnapshot())
232 ropl.SetSubtractMLE(
False)
234 if testStatType == 3:
235 profll.SetOneSidedDiscovery(1)
236 profll.SetPrintLevel(printLevel)
239 slrts.EnableDetailedOutput()
240 profll.EnableDetailedOutput()
241 ropl.EnableDetailedOutput()
247 ROOT.RooStats.AsymptoticCalculator.SetPrintLevel(printLevel)
252 hypoCalc = ROOT.RooStats.FrequentistCalculator(data, sbModel, bModel)
254 hypoCalc = ROOT.RooStats.HybridCalculator(data, sbModel, bModel)
256 hypoCalc = ROOT.RooStats.AsymptoticCalculator(data, sbModel, bModel)
259 hypoCalc.SetToys(ntoys,
int(ntoys / nToysRatio))
261 (hypoCalc).StoreFitInfo(
True)
264 hypoCalc.SetToys(ntoys, ntoys / nToysRatio)
268 if testStatType == 3:
269 hypoCalc.SetOneSidedDiscovery(
True)
270 elif testStatType != 2
and testStatType != 3:
272 "StandardHypoTestDemo",
273 "Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL",
277 if calcType == 1
and (bModel.GetNuisanceParameters()
or sbModel.GetNuisanceParameters()):
280 nuisPdf = w.pdf(nuisPriorName)
284 "StandardHypoTestDemo",
285 "No nuisance pdf given for the HybridCalculator - try to deduce pdf from the model",
287 if bModel.GetPdf()
and bModel.GetObservables():
288 nuisPdf = ROOT.RooStats.MakeNuisancePdf(bModel,
"nuisancePdf_bmodel")
290 nuisPdf = ROOT.RooStats.MakeNuisancePdf(sbModel,
"nuisancePdf_sbmodel")
293 if bModel.GetPriorPdf():
294 nuisPdf = bModel.GetPriorPdf()
296 "StandardHypoTestDemo",
297 "No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",
302 "StandardHypoTestDemo",
303 "Cannot run Hybrid calculator because no prior on the nuisance parameter is "
304 "specified or can be derived",
309 ROOT.Info(
"StandardHypoTestDemo",
"Using as nuisance Pdf ... ")
313 bModel.GetNuisanceParameters()
if bModel.GetNuisanceParameters()
else sbModel.GetNuisanceParameters()
315 nuisParsInPdf = nuisPdf.getObservables(nuisParams)
316 if nuisParsInPdf.getSize() == 0:
318 "StandardHypoTestDemo",
319 "Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range",
323 hypoCalc.ForcePriorNuisanceAlt(nuisPdf)
324 hypoCalc.ForcePriorNuisanceNull(nuisPdf)
329 sampler = hypoCalc.GetTestStatSampler()
331 if sampler
and (calcType == 0
or calcType == 1):
334 if sbModel.GetPdf().canBeExtended():
336 warn(
"StandardHypoTestDemo",
"Pdf is extended: but number counting flag is set: ignore it ")
340 nEvents =
int(data.numEntries())
342 "StandardHypoTestDemo",
343 "Pdf is not extended: number of events to generate taken from observed data set is {nEvents}",
345 sampler.SetNEventsPerToy(nEvents)
347 ROOT.Info(
"StandardHypoTestDemo",
"using a number counting pdf")
348 sampler.SetNEventsPerToy(1)
350 if data.isWeighted()
and not generateBinned:
351 msgfmt =
"Data set is weighted, nentries = {} and sum of weights = {:8.1f} but toy ".
format(
352 data.numEntries(), data.sumEntries()
354 msgfmt +=
"generation is unbinned - it would be faster to set generateBinned to True\n"
356 ROOT.Info(
"StandardHypoTestDemo", msgfmt)
359 sampler.SetGenerateBinned(generateBinned)
362 if testStatType == 0:
363 sampler.SetTestStatistic(slrts)
364 if testStatType == 1:
365 sampler.SetTestStatistic(ropl)
366 if testStatType == 2
or testStatType == 3:
367 sampler.SetTestStatistic(profll)
369 htr = hypoCalc.GetHypoTest()
370 htr.SetPValueIsRightTail(
True)
371 htr.SetBackgroundAsAlt(
False)
381 c1 = ROOT.TCanvas(
"myc1",
"myc1")
382 plot = ROOT.RooStats.HypoTestPlot(htr, 100)
383 plot.SetLogYaxis(
True)
387 c1.SaveAs(
"StandardHypoTestDemo.png")
389 print(
"Asymptotic results ")
395 altDist = htr.GetAltDistribution()
396 htExp = ROOT.RooStats.HypoTestResult(
"Expected Result")
399 p = np.array([i
for i
in range(5)], dtype=float)
400 q = np.array([0.5
for i
in range(5)], dtype=float)
405 values = altDist.GetSamplingDistribution()
406 ROOT.TMath.Quantiles(values.size(), 5, values.data(), q, p,
False)
409 htExp.SetTestStatisticData(q[i])
412 " Expected p -value and significance at ",
417 htExp.Significance(),
426 pval = ROOT.RooStats.AsymptoticCalculator.GetExpectedPValues(
427 htr.NullPValue(), htr.AlternatePValue(), -sig,
False
430 " Expected p -value and significance at ",
440 writeResult = calcType != 2
444 ROOT.Info(
"StandardHypoTestDemo",
"Detailed output will be written in output result file")
446 if htr != ROOT.kNone
and writeResult:
449 calcTypeName =
"Freq" if (calcType == 0)
else (
"Hybr" if (calcType == 1)
else (
"Asym"))
450 resultFileName = ROOT.TString.Format(
"{}_HypoTest_ts{}_".
format(calcTypeName, testStatType))
453 name = ROOT.TString(infile)
454 name.Replace(0, name.Last(
"/") + 1,
"")
455 resultFileName += name
457 fileOut = ROOT.TFile(str(resultFileName),
"RECREATE")
462 "StandardHypoTestDemo",
"HypoTestResult has been written in the file {}".
format(resultFileName.Data())
470workspaceName =
"combined"
471modelSBName =
"ModelConfig"
483 infile, workspaceName, modelSBName, modelBName, dataName, calcType, testStatType, ntoys, useNC, nuisPriorName
static void update(gsl_integration_workspace *workspace, double a1, double b1, double area1, double error1, double a2, double b2, double area2, double error2)
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
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 format
double normal_cdf(double x, double sigma=1, double x0=0)
Cumulative distribution function of the normal (Gaussian) distribution (lower tail).
double normal_quantile_c(double z, double sigma)
Inverse ( ) of the cumulative distribution function of the upper tail of the normal (Gaussian) distri...
bool SetAllConstant(const RooAbsCollection &coll, bool constant=true)
utility function to set all variable constant in a collection (from G.