41class HypoTestInvOptions:
43 plotHypoTestResult =
True
50 generateBinned =
False
55 enableDetailedOutput = (
61 rebuildParamValues = 0
82optHTInv = HypoTestInvOptions()
86large_declaration =
""" \
89class HypoTestInvTool {
95 HypoTestInverterResult *RunInverter(RooWorkspace *w, const char *modelSBName, const char *modelBName,
96 const char *dataName, int type, int testStatType, bool useCLs, int npoints,
97 double poimin, double poimax, int ntoys, bool useNumberCounting = false,
98 const char *nuisPriorName = 0);
100 void AnalyzeResult(HypoTestInverterResult *r, int calculatorType, int testStatType, bool useCLs, int npoints,
101 const char *fileNameBase = 0);
103 void SetParameter(const char *name, const char *value);
104 void SetParameter(const char *name, bool value);
105 void SetParameter(const char *name, int value);
106 void SetParameter(const char *name, double value);
110 bool mPlotHypoTestResult;
113 bool mUseVectorStore;
114 bool mGenerateBinned;
117 bool mEnableDetOutput;
119 int mRebuildParamValues;
126 std::string mMassValue;
128 mMinimizerType; // minimizer type (default is what is in ROOT::Math::MinimizerOptions::DefaultMinimizerType())
129 TString mResultFileName;
132} // end using RooStats namespace
134RooStats::HypoTestInvTool::HypoTestInvTool()
135 : mPlotHypoTestResult(true), mWriteResult(false), mOptimize(true), mUseVectorStore(true), mGenerateBinned(false),
136 mEnableDetOutput(false), mRebuild(false), mReuseAltToys(false),
137 mNToyToRebuild(100), mRebuildParamValues(0), mPrintLevel(0), mInitialFit(-1), mRandomSeed(-1), mNToysRatio(2),
138 mMaxPoi(-1), mAsimovBins(0), mMassValue(""), mMinimizerType(""), mResultFileName()
143ROOT.gInterpreter.Declare(large_declaration)
147class HypoTestInvTool_plus(ROOT.RooStats.HypoTestInvTool):
149 def SetParameter(self, name, value):
150 if (
type(name)
is str)
and (
type(value)
is str):
155 s_name = ROOT.std.string(name)
157 if s_name.find(
"PlotHypoTestResult") != ROOT.std.string.npos:
158 self.mPlotHypoTestResult = value
159 if s_name.find(
"WriteResult") != ROOT.std.string.npos:
160 self.mWriteResult = value
161 if s_name.find(
"Optimize") != ROOT.std.string.npos:
162 self.mOptimize = value
163 if s_name.find(
"UseVectorStore") != ROOT.std.string.npos:
164 self.mUseVectorStore = value
165 if s_name.find(
"GenerateBinned") != ROOT.std.string.npos:
166 self.mGenerateBinned = value
167 if s_name.find(
"EnableDetailedOutput") != ROOT.std.string.npos:
168 self.mEnableDetOutput = value
169 if s_name.find(
"Rebuild") != ROOT.std.string.npos:
170 self.mRebuild = value
171 if s_name.find(
"ReuseAltToys") != ROOT.std.string.npos:
172 self.mReuseAltToys = value
179 elif (
type(name)
is str)
and (
type(value)
is bool):
185 s_name = ROOT.std.string(name)
187 if s_name.find(
"NToyToRebuild") != ROOT.std.string.npos:
188 self.mNToyToRebuild = value
189 if s_name.find(
"RebuildParamValues") != ROOT.std.string.npos:
190 self.mRebuildParamValues = value
191 if s_name.find(
"PrintLevel") != ROOT.std.string.npos:
192 self.mPrintLevel = value
193 if s_name.find(
"InitialFit") != ROOT.std.string.npos:
194 self.mInitialFit = value
195 if s_name.find(
"RandomSeed") != ROOT.std.string.npos:
196 self.mRandomSeed = value
197 if s_name.find(
"AsimovBins") != ROOT.std.string.npos:
198 self.mAsimovBins = value
205 elif (
type(name)
is str)
and (
type(value)
is int):
211 s_name = ROOT.std.string(name)
213 if s_name.find(
"NToysRatio") != ROOT.std.string.npos:
214 self.mNToysRatio = value
215 if s_name.find(
"MaxPOI") != ROOT.std.string.npos:
223 elif (
type(name)
is str)
and (
type(value)
is (float
or double)):
229 s_name = ROOT.std.string(name)
231 if s_name.find(
"MassValue") != ROOT.std.string.npos:
232 global gselfmMassValue
233 gselfmMassValue = self.mMassValue
234 self.mMassValue = value
235 if s_name.find(
"MinimizerType") != ROOT.std.string.npos:
236 self.mMassValue = value
237 if s_name.find(
"ResultFileName") != ROOT.std.string.npos:
238 self.mResultFileName = value
242 ROOT.RooStats.HypoTestInvTool.SetParameter = SetParameter
248 def AnalyzeResult(self, r, calculatorType, testStatType, useCLs, npoints, fileNameBase):
257 lowerLimit = r.LowerLimit()
258 llError = r.LowerLimitEstimatedError()
261 lowerLimit = r.LowerLimit()
262 llError = r.LowerLimitEstimatedError()
265 upperLimit = r.UpperLimit()
266 ulError = r.UpperLimitEstimatedError()
270 if lowerLimit < upperLimit * (1.0 - 1.0e-4)
and lowerLimit != 0:
271 print(f
"The computed lower limit is: ", lowerLimit,
" +/- ", llError)
273 print(f
"The computed upper limit is: {upperLimit} +/- ", ulError)
276 print(f
"Expected upper limits, using the B (alternate) model : ")
277 print(f
" expected limit (median) ", r.GetExpectedUpperLimit(0))
278 print(f
" expected limit (-1 sig) ", r.GetExpectedUpperLimit(-1))
279 print(f
" expected limit (+1 sig) ", r.GetExpectedUpperLimit(1))
280 print(f
" expected limit (-2 sig) ", r.GetExpectedUpperLimit(-2))
281 print(f
" expected limit (+2 sig) ", r.GetExpectedUpperLimit(2))
284 if self.mEnableDetOutput:
285 self.mWriteResult =
True
286 ROOT.Info(
"StandardHypoTestInvDemo",
"detailed output will be written in output result file")
289 if r != ROOT.kNone
and self.mWriteResult:
292 calcType =
"Freq" if (calculatorType == 0)
else (
"Hybr" if (calculatorType == 1)
else "Asym")
293 limitType =
"CLs" if (useCLs)
else "Cls+b"
294 scanType =
"auto" if (npoints < 0)
else "grid"
295 if self.mResultFileName.IsNull():
296 self.mResultFileName = ROOT.TString.Format(
297 "%s_%s_%s_ts%d_", calcType, limitType, scanType, testStatType
300 if self.mMassValue.
size() > 0:
301 self.mResultFileName += self.mMassValue
302 self.mResultFileName +=
"_"
305 name.Replace(0, name.Last(
"/") + 1,
"")
306 self.mResultFileName += name
309 uldistFile =
"RULDist.root"
311 existULDist =
not ROOT.gSystem.AccessPathName(uldistFile)
315 ulDist = fileULDist.Get(
"RULDist")
317 fileOut =
TFile(self.mResultFileName,
"RECREATE")
322 "StandardHypoTestInvDemo",
323 "HypoTestInverterResult has been written in the file %s",
324 self.mResultFileName.Data(),
331 if calculatorType == 0:
332 typeName =
"Frequentist"
333 if calculatorType == 1:
335 elif calculatorType == 2
or calculatorType == 3:
336 typeName =
"Asymptotic"
337 self.mPlotHypoTestResult =
False
339 resultName = r.GetName()
340 plotTitle =
"{} CL Scan for workspace {}".
format(str(typeName), resultName)
343 plot = ROOT.RooStats.HypoTestInverterPlot(
"HTI_Result_Plot", plotTitle, r)
346 c1Name =
"{}_Scan".
format(typeName)
347 c1 = ROOT.TCanvas(c1Name)
357 c1.SaveAs(
"StandardHypoTestInvDemo.c1.png")
359 nEntries = r.ArraySize()
362 if self.mPlotHypoTestResult:
363 c2 = ROOT.TCanvas(
"c2")
365 ny = ROOT.TMath.CeilNint(ROOT.TMath.Sqrt(nEntries))
366 nx = ROOT.TMath.CeilNint(float(nEntries) / ny)
369 for i
in range(nEntries):
372 pl = plot.MakeTestStatPlot(i)
377 c2.SaveAs(
"StandardHypoTestInvDemo.c2.png")
381 ROOT.RooStats.HypoTestInvTool.AnalyzeResult = AnalyzeResult
402 print(f
"Running HypoTestInverter on the workspace ", w.GetName())
406 data = w.data(dataName)
408 Error(
"StandardHypoTestDemo",
"Not existing data {}".
format(dataName))
411 print(f
"Using data set ", dataName)
413 if self.mUseVectorStore:
414 ROOT.RooAbsData.setDefaultStorageType(ROOT.RooAbsData.Vector)
415 data.convertToVectorStore()
419 bModel = w.obj(modelBName)
420 sbModel = w.obj(modelSBName)
423 Error(
"StandardHypoTestDemo",
"Not existing ModelConfig %s", modelSBName)
427 if not sbModel.GetPdf():
428 Error(
"StandardHypoTestDemo",
"Model %s has no pdf ", modelSBName)
431 if not sbModel.GetParametersOfInterest():
432 Error(
"StandardHypoTestDemo",
"Model %s has no poi ", modelSBName)
435 if not sbModel.GetObservables():
436 Error(
"StandardHypoTestInvDemo",
"Model %s has no observables ", modelSBName)
439 if not sbModel.GetSnapshot():
441 "StandardHypoTestInvDemo",
"Model {} has no snapshot - make one using model poi".
format(modelSBName)
443 sbModel.SetSnapshot(sbModel.GetParametersOfInterest())
447 if optHTInv.noSystematics:
448 nuisPar = sbModel.GetNuisanceParameters()
449 if nuisPar
and nuisPar.getSize() > 0:
451 f
"StandardHypoTestInvDemo",
452 " - Switch off all systematics by setting them constant to their initial values",
454 ROOT.RooStats.SetAllConstant(nuisPar)
457 bnuisPar = bModel.GetNuisanceParameters()
459 ROOT.RooStats.SetAllConstant(bnuisPar)
461 if (
not bModel)
or (bModel == sbModel):
462 ROOT.Info(
"StandardHypoTestInvDemo",
"The background model {} does not exist".
format(modelBName))
463 ROOT.Info(
"StandardHypoTestInvDemo",
"Copy it from ModelConfig {} and set POI to zero".
format(modelSBName))
464 bModel = sbModel.Clone()
465 bModel.SetName(modelSBName +
"_with_poi_0")
466 var = bModel.GetParametersOfInterest().first()
469 oldval = var.getVal()
471 bModel.SetSnapshot(ROOT.RooArgSet(var))
474 if not bModel.GetSnapshot():
476 "StandardHypoTestInvDemo",
477 "Model %s has no snapshot - make one using model poi and 0 values ",
480 var = bModel.GetParametersOfInterest().first()
482 oldval = var.getVal()
484 bModel.SetSnapshot(ROOT.RooArgSet(var))
487 Error(
"StandardHypoTestInvDemo",
"Model %s has no valid poi", modelBName)
493 hasNuisParam = sbModel.GetNuisanceParameters()
and sbModel.GetNuisanceParameters().getSize() > 0
494 hasGlobalObs = sbModel.GetGlobalObservables()
and sbModel.GetGlobalObservables().getSize() > 0
495 if hasNuisParam
and not hasGlobalObs:
500 "StandardHypoTestInvDemo",
501 "Model %s has nuisance parameters but no global observables associated",
505 "StandardHypoTestInvDemo",
506 "\tThe effect of the nuisance parameters will not be treated correctly ",
510 initialParameters = ROOT.RooArgSet()
511 allParams = sbModel.GetPdf().getParameters(data)
512 allParams.snapshot(initialParameters)
516 poiSet = sbModel.GetParametersOfInterest()
519 print(
"StandardHypoTestInvDemo : POI initial value: ", poi.GetName(),
" = ", poi.getVal())
522 tw = ROOT.TStopwatch()
524 doFit = self.mInitialFit
525 if testStatType == 0
and self.mInitialFit == -1:
527 if type == 3
and self.mInitialFit == -1:
531 if len(self.mMinimizerType) == 0:
537 "StandardHypoTestInvDemo",
538 "Using {} as minimizer for computing the test statistic".
format(
549 ROOT.Info(
"StandardHypoTestInvDemo",
" Doing a first fit to the observed data ")
551 if sbModel.GetNuisanceParameters():
552 constrainParams.add(sbModel.GetNuisanceParameters())
555 fitres = sbModel.GetPdf().fitTo(
559 Minimizer(str(self.mMinimizerType),
"Migrad"),
561 PrintLevel(self.mPrintLevel),
562 Constrain(constrainParams),
567 if fitres.status() != 0:
569 "StandardHypoTestInvDemo",
570 "Fit to the model failed - try with strategy 1 and perform first an Hesse computation",
572 fitres = sbModel.GetPdf().fitTo(
576 Minimizer(self.mMinimizerType,
"Migrad"),
578 PrintLevel(self.mPrintLevel + 1),
579 Constrain(constrainParams),
584 if fitres.status() != 0:
585 Warning(
"StandardHypoTestInvDemo",
" Fit still failed - continue anyway.....")
587 print(
"StandardHypoTestInvDemo - Best Fit value : ", poi.GetName(),
" = ", poihat,
" +/- ", poi.getError())
588 print(f
"Time for fitting : ")
592 sbModel.SetSnapshot(sbModel.GetParametersOfInterest())
593 print(f
"StandardHypoTestInvo: snapshot of S+B Model ", sbModel.GetName(),
" is set to the best fit value")
596 if testStatType == 0:
599 "StandardHypoTestInvDemo",
600 "Using LEP test statistic - an initial fit is not done and the TS will use "
601 +
"the nuisances at the model value",
605 "StandardHypoTestInvDemo",
606 "Using LEP test statistic - an initial fit has been done and the TS will use "
607 +
"the nuisances at the best fit value",
612 slrts = ROOT.RooStats.SimpleLikelihoodRatioTestStat(sbModel.GetPdf(), bModel.GetPdf())
615 nullParams = ROOT.RooArgSet(sbModel.GetSnapshot())
616 if sbModel.GetNuisanceParameters():
617 nullParams.add(sbModel.GetNuisanceParameters())
618 if sbModel.GetSnapshot():
619 slrts.SetNullParameters(nullParams)
620 altParams = ROOT.RooArgSet(bModel.GetSnapshot())
621 if bModel.GetNuisanceParameters():
622 altParams.add(bModel.GetNuisanceParameters())
623 if bModel.GetSnapshot():
624 slrts.SetAltParameters(altParams)
625 if self.mEnableDetOutput:
626 slrts.EnableDetailedOutput()
629 ropl = ROOT.RooStats.RatioOfProfiledLikelihoodsTestStat(sbModel.GetPdf(), bModel.GetPdf(), bModel.GetSnapshot())
630 ropl.SetSubtractMLE(
False)
631 if testStatType == 11:
632 ropl.SetSubtractMLE(
True)
633 ropl.SetPrintLevel(self.mPrintLevel)
634 ropl.SetMinimizer(self.mMinimizerType.c_str())
635 if self.mEnableDetOutput:
636 ropl.EnableDetailedOutput()
638 profll = ROOT.RooStats.ProfileLikelihoodTestStat(sbModel.GetPdf())
639 if testStatType == 3:
640 profll.SetOneSided(
True)
641 if testStatType == 4:
642 profll.SetSigned(
True)
643 profll.SetMinimizer(self.mMinimizerType.c_str())
644 profll.SetPrintLevel(self.mPrintLevel)
645 if self.mEnableDetOutput:
646 profll.EnableDetailedOutput()
648 profll.SetReuseNLL(self.mOptimize)
649 slrts.SetReuseNLL(self.mOptimize)
650 ropl.SetReuseNLL(self.mOptimize)
653 profll.SetStrategy(0)
658 poi.setMax(self.mMaxPoi)
660 maxll = ROOT.RooStats.MaxLikelihoodEstimateTestStat(sbModel.GetPdf(), poi)
661 nevtts = ROOT.RooStats.NumEventsTestStat()
663 ROOT.RooStats.AsymptoticCalculator.SetPrintLevel(self.mPrintLevel)
668 hc = ROOT.RooStats.FrequentistCalculator(data, bModel, sbModel)
670 hc = ROOT.RooStats.HybridCalculator(data, bModel, sbModel)
677 hc = ROOT.RooStats.AsymptoticCalculator(data, bModel, sbModel,
False)
679 hc = ROOT.RooStats.AsymptoticCalculator(
680 data, bModel, sbModel,
True
684 "StandardHypoTestInvDemo",
685 "Invalid - calculator type = {Type}supported values are only :\n\t\t\t 0 "
686 +
"(Frequentist) , 1 (Hybrid) , 2 (Asymptotic) ",
693 if testStatType == 0:
695 if testStatType == 1
or testStatType == 11:
697 if testStatType == 2
or testStatType == 3
or testStatType == 4:
699 if testStatType == 5:
701 if testStatType == 6:
706 "StandardHypoTestInvDemo",
707 "Invalid - test statistic type = {testStatType} supported values are only :\n\t\t\t 0 (SLR) "
708 +
", 1 (Tevatron) , 2 (PLR), 3 (PLR1), 4(MLE)",
713 toymcs = hc.GetTestStatSampler()
714 if toymcs
and (Type == 0
or Type == 1):
716 if sbModel.GetPdf().canBeExtended():
717 if useNumberCounting:
718 Warning(
"StandardHypoTestInvDemo",
"Pdf is extended: but number counting flag is set: ignore it ")
721 if not useNumberCounting:
722 nEvents = data.numEntries()
724 "StandardHypoTestInvDemo",
725 "Pdf is not extended: number of events to generate taken from observed data set is {nEvents}",
727 toymcs.SetNEventsPerToy(nEvents)
729 ROOT.Info(
"StandardHypoTestInvDemo",
"using a number counting pdf")
730 toymcs.SetNEventsPerToy(1)
732 toymcs.SetTestStatistic(testStat)
734 if data.isWeighted()
and not self.mGenerateBinned:
736 "StandardHypoTestInvDemo",
738 "Data set is weighted, nentries = {} and sum of weights = {:8.1f} but toy"
739 +
"generation is unbinned - it would be faster to set self.mGenerateBinned to true\n"
740 ).
format(data.numEntries(), data.sumEntries()),
743 toymcs.SetGenerateBinned(self.mGenerateBinned)
745 toymcs.SetUseMultiGen(self.mOptimize)
747 if self.mGenerateBinned
and sbModel.GetObservables().getSize() > 2:
749 "StandardHypoTestInvDemo",
751 "generate binned is activated but the number of observable is {}. Too much "
752 +
"memory could be needed for allocating all the bins"
753 ).
format(sbModel.GetObservables().getSize()),
757 if self.mRandomSeed >= 0:
761 if self.mReuseAltToys:
765 hhc = HybridCalculator(hc)
768 hhc.SetToys(ntoys, ntoys / self.mNToysRatio)
772 sbModel.SetGlobalObservables(
RooArgSet())
775 if bModel.GetNuisanceParameters()
or sbModel.GetNuisanceParameters():
778 toymcs.SetUseMultiGen(
False)
779 ToyMCSampler.SetAlwaysUseMultiGen(
False)
783 nuisPdf = w.pdf(nuisPriorName)
787 "StandardHypoTestInvDemo",
788 "No nuisance pdf given for the HybridCalculator - try to deduce pdf from the model",
790 if bModel.GetPdf()
and bModel.GetObservables():
796 if bModel.GetPriorPdf():
797 nuisPdf = bModel.GetPriorPdf()
799 "StandardHypoTestInvDemo",
800 "No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",
805 "StandardHypoTestInvDemo",
806 "Cannot run Hybrid calculator because no prior on the nuisance "
807 "parameter is specified or can be derived",
812 ROOT.Info(
"StandardHypoTestInvDemo",
"Using as nuisance Pdf ... ")
816 ibModel.GetNuisanceParameters()
817 if (bModel.GetNuisanceParameters())
818 else (sbModel.GetNuisanceParameters())
820 npnuisPdf.getObservables(nuisParams)
821 if np.getSize() == 0:
823 "StandardHypoTestInvDemo",
824 "Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range",
827 hhc.ForcePriorNuisanceAlt(nuisPdf)
828 hhc.ForcePriorNuisanceNull(nuisPdf)
830 elif type == 2
or type == 3:
831 if testStatType == 3:
833 if testStatType != 2
and testStatType != 3:
835 "StandardHypoTestInvDemo",
836 "Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL",
839 hc.SetToys(ntoys, ntoys / self.mNToysRatio)
841 if self.mEnableDetOutput:
842 hc.StoreFitInfo(
True)
844 hc.SetToys(ntoys, ntoys / self.mNToysRatio)
850 ROOT.RooMsgService.instance().getStream(1).removeTopic(ROOT.RooFit.NumIntegration)
852 calc = ROOT.RooStats.HypoTestInverter(hc)
853 calc.SetConfidenceLevel(optHTInv.confLevel)
856 calc.SetVerbose(
True)
862 poimax =
int(poihat + 4 * poi.getError())
864 print(f
"Doing a fixed scan in interval : {poimin}, {poimax} ")
865 calc.SetFixedScan(npoints, poimin, poimax)
868 print(f
"Doing an automatic scan in interval : {poi.getMin()} , ", poi.getMax())
871 r = calc.GetInterval()
872 print(f
"Time to perform limit scan \n")
879 f
"Rebuild the upper limit distribution by re-generating new set of pseudo-experiment and re-compute "
880 +
"for each of them a new upper limit\n\n"
883 allParams = sbModel.GetPdf().getParameters(data)
888 if self.mRebuildParamValues != 0:
890 allParams.assign(initialParameters)
892 if self.mRebuildParamValues == 0
or self.mRebuildParamValues == 1:
894 if sbModel.GetNuisanceParameters():
895 constrainParams.add(sbModel.GetNuisanceParameters())
898 poiModel = sbModel.GetParametersOfInterest()
899 bModel.LoadSnapshot()
902 if self.mRebuildParamValues == 0:
906 sbModel.GetPdf().fitTo(
910 Minimizer(self.mMinimizerType,
"Migrad"),
912 PrintLevel(self.mPrintLevel),
913 Constrain(constrainParams),
917 print(f
"rebuild using fitted parameter value for B-model snapshot")
918 constrainParams.Print(
"v")
922 print(f
"StandardHypoTestInvDemo: Initial parameters used for rebuilding: ")
926 limDist = calc.GetUpperLimitDistribution(
True, self.mNToyToRebuild)
927 print(f
"Time to rebuild distributions :")
931 print(f
"Expected limits after rebuild distribution ")
932 print(f
"expected upper limit (median of limit distribution) ", limDist.InverseCDF(0.5))
934 f
"expected -1 sig limit (0.16% quantile of limit dist) ",
938 f
"expected +1 sig limit (0.84% quantile of limit dist) ",
942 f
"expected -2 sig limit (.025% quantile of limit dist) ",
946 f
"expected +2 sig limit (.975% quantile of limit dist) ",
951 limPlot = SamplingDistPlot(50
if (self.mNToyToRebuild < 200)
else 100)
952 limPlot.AddSamplingDistribution(limDist)
953 limPlot.GetTH1F().SetStats(
True)
954 limPlot.SetLineColor(kBlue)
955 c1 =
TCanvas(
"limPlot",
"Upper Limit Distribution")
959 c1.SaveAs(
"StandardHypoTestInvDemo.1.png")
962 limDist.SetName(
"RULDist")
963 fileOut =
TFile(
"RULDist.root",
"RECREATE")
971 r = calc.GetInterval()
974 print(f
"ERROR : failed to re-build distributions ")
978 ROOT.RooStats.HypoTestInvTool.RunInverter = RunInverter
983ROOT.RooStats.HypoTestInvTool = HypoTestInvTool_plus
991 modelSBName="ModelConfig",
1001 useNumberCounting=False,
1006 Other Parameter to pass in tutorial
1007 apart from standard for filename, ws, modelconfig and data
1009 type = 0 Freq calculator
1010 type = 1 Hybrid calculator
1011 type = 2 Asymptotic calculator
1012 type = 3 Asymptotic calculator using nominal Asimov data sets (not using fitted parameter values but nominal ones)
1014 testStatType = 0 LEP
1022 useCLs scan for CLs (otherwise for CLs+b)
1026 poimin,poimax: min/max value to scan in case of fixed scans
1027 (if min > max, try to find automatically)
1029 ntoys: number of toys to use
1031 useNumberCounting: set to True when using number counting events
1033 nuisPriorName: name of prior for the nuisance. This is often expressed as constraint term in the global model
1034 HybridCalculator (type=1)
1035 If not given by default the prior pdf from ModelConfig is used.
1037 extra options are available as global parameters of the macro. They major ones are:
1039 plotHypoTestResult plot result of tests at each point (TS distributions) (default is True)
1040 writeResult write result of scan (default is True)
1041 rebuild rebuild scan for expected limits (require extra toys) (default is False)
1042 generateBinned generate binned data sets for toys (default is False) - be careful not to activate with
1043 large (>=3) number of observables
1044 nToyRatio ratio of S+B/B toys (default is 2)
1047 filename = ROOT.TString(infile)
1048 if filename.IsNull():
1049 filename =
"results/example_combined_GaussExample_model.root"
1050 fileExist =
not ROOT.gSystem.AccessPathName(filename)
1054 print(
"HistFactory file cannto be generated on Windows - exit")
1057 print(f
"will run standard hist2workspace example")
1058 ROOT.gROOT.ProcessLine(
".! prepareHistFactory .")
1059 ROOT.gROOT.ProcessLine(
".! hist2workspace config/example.xml")
1060 print(f
"\n\n---------------------")
1061 print(f
"Done creating example input")
1062 print(f
"---------------------\n\n")
1068 file = ROOT.TFile.Open(filename)
1072 print(f
"StandardRooStatsDemoMacro: Input file {filename} is not found")
1075 calc = ROOT.RooStats.HypoTestInvTool()
1079 calc.SetParameter(
"PlotHypoTestResult", optHTInv.plotHypoTestResult)
1080 calc.SetParameter(
"WriteResult", optHTInv.writeResult)
1081 calc.SetParameter(
"Optimize", optHTInv.optimize)
1082 calc.SetParameter(
"UseVectorStore", optHTInv.useVectorStore)
1083 calc.SetParameter(
"GenerateBinned", optHTInv.generateBinned)
1084 calc.SetParameter(
"NToysRatio", optHTInv.nToysRatio)
1085 calc.SetParameter(
"MaxPOI", optHTInv.maxPOI)
1086 calc.SetParameter(
"EnableDetailedOutput", optHTInv.enableDetailedOutput)
1087 calc.SetParameter(
"Rebuild", optHTInv.rebuild)
1088 calc.SetParameter(
"ReuseAltToys", optHTInv.reuseAltToys)
1089 calc.SetParameter(
"NToyToRebuild", optHTInv.nToyToRebuild)
1090 calc.SetParameter(
"RebuildParamValues", optHTInv.rebuildParamValues)
1091 calc.SetParameter(
"MassValue", optHTInv.massValue)
1092 calc.SetParameter(
"MinimizerType", optHTInv.minimizerType)
1093 calc.SetParameter(
"PrintLevel", optHTInv.printLevel)
1094 calc.SetParameter(
"InitialFit", optHTInv.initialFit)
1095 calc.SetParameter(
"ResultFileName", optHTInv.resultFileName)
1096 calc.SetParameter(
"RandomSeed", optHTInv.randomSeed)
1097 calc.SetParameter(
"AsimovBins", optHTInv.nAsimovBins)
1100 if optHTInv.useNLLOffset:
1103 w = file.Get(wsName)
1105 print(w,
"\t", filename)
1107 r = calc.RunInverter(
1123 raise RuntimeError(
"Error running the HypoTestInverter - Exit ")
1128 print(f
"Reading an HypoTestInverterResult with name {wsName} from file " << filename)
1129 r = file.Get(wsName)
1131 raise RuntimeError(
"File {filename} does not contain a workspace or an HypoTestInverterResult - Exit ")
1136 calc.AnalyzeResult(r, calculatorType, testStatType, useCLs, npoints, infile)
1144def ReadResult(fileName, resultName="", useCLs=True):
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
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 UChar_t len
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
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
static void SetDefaultMinimizer(const char *type, const char *algo=nullptr)
Set the default Minimizer type and corresponding algorithms.
static void SetDefaultStrategy(int strat)
Set the default strategy.
static const std::string & DefaultMinimizerType()
RooArgSet is a container object that can hold multiple RooAbsArg objects.
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
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.
double normal_cdf(double x, double sigma=1, double x0=0)
Cumulative distribution function of the normal (Gaussian) distribution (lower tail).
bool SetAllConstant(const RooAbsCollection &coll, bool constant=true)
utility function to set all variable constant in a collection (from G.
void RemoveConstantParameters(RooArgSet *set)
RooAbsPdf * MakeNuisancePdf(RooAbsPdf &pdf, const RooArgSet &observables, const char *name)
extract constraint terms from pdf
void UseNLLOffset(bool on)
function to set a global flag in RooStats to use NLL offset when performing nll computations Note tha...
bool IsNLLOffset()
function returning if the flag to check if the flag to use NLLOffset is set
void PrintListContent(const RooArgList &l, std::ostream &os=std::cout)
useful function to print in one line the content of a set with their values