90 fSystToFix( measurement.GetConstantParams() ),
91 fParamValues( measurement.GetParamValues() ),
92 fNomLumi( measurement.GetLumi() ),
93 fLumiError( measurement.GetLumi()*measurement.GetLumiRelErr() ),
94 fLowBin( measurement.GetBinLow() ),
95 fHighBin( measurement.GetBinHigh() ),
111 if( proto_config ==
nullptr ) {
112 std::cout <<
"Error: Did not find 'ModelConfig' object in file: " << ws_single->
GetName()
118 cxcoutWHF <<
"No Parametetrs of interest are set" << std::endl;
122 std::stringstream sstream;
123 sstream <<
"Setting Parameter(s) of Interest as: ";
124 for(
auto const& item : measurement.
GetPOIList()) {
125 sstream << item <<
" ";
130 for(
auto const& poi_name : measurement.
GetPOIList()) {
135 std::cout <<
"WARNING: Can't find parameter of interest: " << poi_name
136 <<
" in Workspace. Not setting in ModelConfig." << std::endl;
143 std::string NewModelName =
"newSimPdf";
148 std::cout <<
"Error: Failed to find dataset: " << expData
149 <<
" in workspace" << std::endl;
164 if( !pdf ) pdf = ws_single->
pdf( ModelName );
165 const RooArgSet* observables = ws_single->
set(
"observables");
168 std::string SnapShotName =
"NominalParamValues";
175 std::string AsimovName = asimov.
GetName();
177 cxcoutPHF <<
"Generating additional Asimov Dataset: " << AsimovName << std::endl;
181 cxcoutPHF <<
"Importing Asimov dataset" << std::endl;
182 bool failure = ws_single->
import(*asimov_dataset,
Rename(AsimovName.c_str()));
184 std::cout <<
"Error: Failed to import Asimov dataset: " << AsimovName
212 string ch_name = channel.
GetName();
216 if( ws_single ==
nullptr ) {
217 cxcoutF(
HistFactory) <<
"Error: Failed to make Single-Channel workspace for channel: " << ch_name
218 <<
" and measurement: " << measurement.
GetName() << std::endl;
248 vector<std::unique_ptr<RooWorkspace>> channel_workspaces;
249 vector<string> channel_names;
253 if( ! channel.CheckHistograms() ) {
254 cxcoutFHF <<
"MakeModelAndMeasurementsFast: Channel: " << channel.GetName()
255 <<
" has uninitialized histogram pointers" << std::endl;
259 string ch_name = channel.GetName();
260 channel_names.push_back(ch_name);
284 for (
unsigned int idx=0; idx <
fObsNameVec.size(); ++idx) {
297 obs->setBinning(binning);
319 unsigned int histndim(1);
320 std::string classname = hist->
ClassName();
321 if (classname.find(
"TH1")==0) { histndim=1; }
322 else if (classname.find(
"TH2")==0) { histndim=2; }
323 else if (classname.find(
"TH3")==0) { histndim=3; }
326 prefix +=
"_Hist_alphanominal";
328 RooDataHist histDHist((prefix +
"DHist").c_str(),
"",observables,hist);
329 RooHistFunc histFunc(prefix.c_str(),
"",observables,histDHist,0);
340 std::vector<std::string> & constraintTermNames) {
341 std::string paramName = param.
GetName();
342 std::string constraintName = paramName +
"Constraint";
345 if(
proto.pdf(constraintName))
return;
349 const double gaussSigma = isUniform ? 100. : 1.0;
351 cxcoutIHF <<
"Added a uniform constraint for " << paramName <<
" as a Gaussian constraint with a very large sigma " << std::endl;
354 std::stringstream command;
355 command <<
"Gaussian::" << constraintName <<
"(" << paramName <<
",nom_" << paramName <<
"[0.,-10,10],"
356 << gaussSigma <<
")";
357 constraintTermNames.emplace_back(
proto.factory(command.str())->GetName());
358 auto * normParam =
proto.var(std::string(
"nom_") + paramName);
359 normParam->setConstant();
360 const_cast<RooArgSet*
>(
proto.set(
"globalObservables"))->add(*normParam);
367 for(
auto const& histoSys : histoSysList) {
379 const string& prefix,
384 vector<double> low, high;
387 for(
unsigned int j=0; j<histoSysList.size(); ++j){
388 std::stringstream str;
391 const HistoSys& histoSys = histoSysList.at(j);
394 lowSet.
add(*
new RooHistFunc((prefix+str.str()+
"low").c_str(),
"",observables,*lowDHist,0));
395 highSet.
add(*
new RooHistFunc((prefix+str.str()+
"high").c_str(),
"",observables,*highDHist,0));
400 interp.setPositiveDefinite();
401 interp.setAllInterpCodes(4);
404 interp.setBinIntegrator(observableSet);
405 interp.forceNumInt();
409 return proto->arg(prefix.c_str());
417 std::vector<string> prodNames;
420 vector<string> normFactorNames, rangeNames;
423 string overallNorm_times_sigmaEpsilon = sample.
GetName() +
"_" + channel +
"_scaleFactors";
424 auto sigEps =
proto->arg(sigmaEpsilon.c_str());
426 auto normFactor = std::make_unique<RooProduct>(overallNorm_times_sigmaEpsilon.c_str(), overallNorm_times_sigmaEpsilon.c_str(),
RooArgList(*sigEps));
428 if(!normList.empty()){
431 string varname = norm.GetName();
433 varname +=
"_" + channel;
439 std::stringstream range;
440 range <<
"[" << norm.GetVal() <<
"," << norm.GetLow() <<
"," << norm.GetHigh() <<
"]";
442 if(
proto->obj(varname) ==
nullptr) {
445 proto->factory(varname + range.str());
448 prodNames.push_back(varname);
449 rangeNames.push_back(range.str());
450 normFactorNames.push_back(varname);
454 for (
const auto&
name : prodNames) {
457 normFactor->addTerm(arg);
462 unsigned int rangeIndex=0;
463 for( vector<string>::iterator nit = normFactorNames.begin(); nit!=normFactorNames.end(); ++nit){
464 if( count (normFactorNames.begin(), normFactorNames.end(), *nit) > 1 ){
465 cxcoutI(
HistFactory) <<
"<NormFactor Name =\""<<*nit<<
"\"> is duplicated for <Sample Name=\""
466 << sample.
GetName() <<
"\">, but only one factor will be included. \n Instead, define something like"
467 <<
"\n\t<Function Name=\""<<*nit<<
"Squared\" Expression=\""<<*nit<<
"*"<<*nit<<
"\" Var=\""<<*nit<<rangeNames.at(rangeIndex)
468 <<
"\"> \nin your top-level XML's <Measurment> entry and use <NormFactor Name=\""<<*nit<<
"Squared\" in your channel XML file."<< endl;
478 std::vector<OverallSys>& systList,
479 vector<string>& constraintTermNames,
480 vector<string>& totSystTermNames) {
483 totSystTermNames.push_back(prefix);
486 vector<double> lowVec, highVec;
488 std::map<std::string, double>::iterator itconstr;
489 for(
unsigned int i = 0; i < systList.size(); ++i) {
492 std::string strname = sys.
GetName();
493 const char *
name = strname.c_str();
504 cxcoutI(
HistFactory) <<
"HistoToWorkspaceFast::AddConstraintTerm - zero uncertainty assigned - skip systematic " << sys.
GetName() << std::endl;
507 double tauVal = 1./(relerr*relerr);
508 double sqtau = 1./relerr;
522 alphaOfBeta->
Print(
"t");
525 constraintTermNames.push_back(gamma->GetName());
529 const_cast<RooArgSet*
>(
proto->set(
"globalObservables"))->add(*yvar);
532 params.
add(*alphaOfBeta);
540 makeGaussianConstraint(*alpha, *
proto, isUniform, constraintTermNames);
551 double tauVal = 1./relerr;
552 std::string tauName =
"tau_" + sys.
GetName();
554 double kappaVal = 1. + relerr;
555 std::string kappaName =
"kappa_" + sys.
GetName();
557 const char * alphaName = alpha->
GetName();
559 std::string alphaOfBetaName =
"alphaOfBeta_" + sys.
GetName();
561 tauName.c_str(),kappaName.c_str(),alphaName,
562 tauName.c_str(),kappaName.c_str(),alphaName ) );
566 alphaOfBeta->
Print(
"t");
567 params.
add(*alphaOfBeta);
572 double low = sys.
GetLow();
574 lowVec.push_back(low);
575 highVec.push_back(high);
579 if(systList.size() > 0){
583 assert(!params.
empty());
584 assert(
int(lowVec.size()) == params.
getSize() );
586 FlexibleInterpVar interp( (interpName).c_str(),
"", params, 1., lowVec, highVec);
589 proto->import(interp);
594 proto->import(interp);
604 const vector<RooProduct*>& sampleScaleFactors, std::vector<vector<RooAbsArg*>>& sampleHistFuncs)
const {
605 assert(sampleScaleFactors.size() == sampleHistFuncs.size());
610 throw std::logic_error(
"HistFactory didn't process the observables correctly. Please file a bug report.");
612 auto firstHistFunc =
dynamic_cast<const RooHistFunc*
>(sampleHistFuncs.front().front());
613 if (!firstHistFunc) {
615 firstHistFunc =
dynamic_cast<const RooHistFunc*
>(piecewiseInt->nominalHist());
617 assert(firstHistFunc);
620 const std::string binWidthFunctionName = totName +
"_binWidth";
621 RooBinWidthFunction binWidth(binWidthFunctionName.c_str(),
"Divide by bin width to obtain probability density", *firstHistFunc,
true);
622 proto->import(binWidth);
623 auto binWidthWS =
proto->function(binWidthFunctionName.c_str());
629 for (
unsigned int i=0; i < sampleHistFuncs.size(); ++i) {
630 assert(!sampleHistFuncs[i].empty());
631 coefList.
add(*sampleScaleFactors[i]);
633 std::vector<RooAbsArg*>& thisSampleHistFuncs = sampleHistFuncs[i];
634 thisSampleHistFuncs.push_back(binWidthWS);
636 if (thisSampleHistFuncs.size() == 1) {
638 shapeList.
add(*thisSampleHistFuncs.front());
641 std::string
name = thisSampleHistFuncs.front()->GetName();
642 auto pos =
name.find(
"Hist_alpha");
643 if (pos != std::string::npos) {
644 name =
name.substr(0, pos) +
"shapes";
645 }
else if ( (pos =
name.find(
"nominal")) != std::string::npos) {
646 name =
name.substr(0, pos) +
"shapes";
649 RooProduct shapeProduct(
name.c_str(), thisSampleHistFuncs.front()->GetTitle(),
RooArgSet(thisSampleHistFuncs.begin(), thisSampleHistFuncs.end()));
656 RooRealSumPdf tot(totName.c_str(), totName.c_str(), shapeList, coefList,
true);
677 FILE* covFile = fopen ((
filename).c_str(),
"w");
678 fprintf(covFile,
" ") ;
679 for (
auto const *myargi : static_range_cast<RooRealVar *>(*params)) {
680 if(myargi->isConstant())
continue;
681 fprintf(covFile,
" & %s", myargi->GetName());
683 fprintf(covFile,
"\\\\ \\hline \n" );
684 for (
auto const *myargi : static_range_cast<RooRealVar *>(*params)) {
685 if(myargi->isConstant())
continue;
686 fprintf(covFile,
"%s", myargi->GetName());
687 for (
auto const *myargj : static_range_cast<RooRealVar *>(*params)) {
688 if(myargj->isConstant())
continue;
689 cout << myargi->GetName() <<
"," << myargj->GetName();
690 fprintf(covFile,
" & %.2f",
result->correlation(*myargi, *myargj));
693 fprintf(covFile,
" \\\\\n");
706 Error(
"MakeSingleChannelWorkspace",
707 "The input Channel does not contain any sample - return a nullptr");
711 const TH1* channel_hist_template = channel.
GetSamples().front().GetHisto();
712 if (channel_hist_template ==
nullptr) {
714 channel_hist_template = channel.
GetSamples().front().GetHisto();
716 if (channel_hist_template ==
nullptr) {
717 std::ostringstream stream;
718 stream <<
"The sample " << channel.
GetSamples().front().GetName()
719 <<
" in channel " << channel.
GetName() <<
" does not contain a histogram. This is the channel:\n";
720 channel.
Print(stream);
721 Error(
"MakeSingleChannelWorkspace",
"%s", stream.str().c_str());
726 std::cout <<
"MakeSingleChannelWorkspace: Channel: " << channel.
GetName()
727 <<
" has uninitialized histogram pointers" << std::endl;
741 string channel_name = channel.
GetName();
751 for (
unsigned int idx=0; idx<
fObsNameVec.size(); ++idx ) {
761 throw hf_exc(
"HistFactory is limited to 1- to 3-dimensional histograms.");
765 <<
"\tStarting to process '"
766 << channel_name <<
"' channel with " <<
fObsNameVec.size() <<
" observables"
767 <<
"\n-----------------------------------------\n" << endl;
773 auto proto_config = make_unique<ModelConfig>(
"ModelConfig",
proto);
774 proto_config->SetWorkspace(*
proto);
779 proto->factory(func);
783 RooArgSet likelihoodTerms(
"likelihoodTerms"), constraintTerms(
"constraintTerms");
784 vector<string> likelihoodTermNames, constraintTermNames, totSystTermNames;
786 std::vector<std::vector<RooAbsArg*>> allSampleHistFuncs;
787 std::vector<RooProduct*> sampleScaleFactors;
789 std::vector< pair<string,string> > statNamePairs;
790 std::vector< pair<const TH1*, std::unique_ptr<TH1>> > statHistPairs;
791 const std::string statFuncName =
"mc_stat_" + channel_name;
793 string prefix, range;
800 std::stringstream lumiErrorStr;
802 proto->factory(
"Gaussian::lumiConstraint(Lumi,"+lumiErrorStr.str()+
")");
803 proto->var(
"nominalLumi")->setConstant();
804 proto->defineSet(
"globalObservables",
"nominalLumi");
806 constraintTermNames.push_back(
"lumiConstraint");
814 string overallSystName = sample.GetName() +
"_" + channel_name +
"_epsilon";
816 string systSourcePrefix =
"alpha_";
821 sample.GetOverallSysList(), constraintTermNames , totSystTermNames);
823 allSampleHistFuncs.emplace_back();
824 std::vector<RooAbsArg*>& sampleHistFuncs = allSampleHistFuncs.back();
837 const TH1* nominal = sample.GetHisto();
849 string expPrefix = sample.
GetName() +
"_" + channel_name;
853 assert(nominalHistFunc);
855 if(sample.GetHistoSysList().empty()) {
857 cxcoutI(
HistFactory) << sample.GetName() +
"_" + channel_name +
" has no variation histograms " << endl;
859 sampleHistFuncs.push_back(nominalHistFunc);
863 string constraintPrefix = sample.GetName() +
"_" + channel_name +
"_Hist_alpha";
866 RooArgList interpParams = makeInterpolationParameters(sample.GetHistoSysList(), *
proto);
869 for(std::size_t i = 0; i < interpParams.
size(); ++i) {
870 bool isUniform = measurement.
GetUniformSyst().count(sample.GetHistoSysList()[i].GetName()) > 0;
871 makeGaussianConstraint(interpParams[i], *
proto, isUniform, constraintTermNames);
875 sampleHistFuncs.push_back( makeLinInterp(interpParams, nominalHistFunc,
proto,
876 sample.GetHistoSysList(), constraintPrefix, observables) );
879 sampleHistFuncs.front()->SetTitle( (nominal && strlen(nominal->
GetTitle())>0) ? nominal->
GetTitle() : sample.GetName().c_str() );
885 if( sample.GetStatError().GetActivate() ) {
888 cxcoutF(
HistFactory) <<
"Cannot include Stat Error for histograms of more than 3 dimensions."
897 cxcoutI(
HistFactory) <<
"Sample: " << sample.GetName() <<
" to be included in Stat Error "
898 <<
"for channel " << channel_name
901 string UncertName = sample.GetName() +
"_" + channel_name +
"_StatAbsolUncert";
902 std::unique_ptr<TH1> statErrorHist;
904 if( sample.GetStatError().GetErrorHist() ==
nullptr ) {
907 <<
" Channel: " << channel_name
908 <<
" Sample: " << sample.GetName()
915 statErrorHist.reset(
static_cast<TH1*
>(sample.GetStatError().GetErrorHist()->Clone()));
920 <<
"\tChannel: " << channel_name
921 <<
"\tSample: " << sample.GetName()
922 <<
"\tError Histogram: " << statErrorHist->GetName() << std::endl;
925 statErrorHist->Multiply( nominal );
926 statErrorHist->SetName( UncertName.c_str() );
931 statHistPairs.emplace_back(nominal, std::move(statErrorHist));
949 if( paramHist ==
nullptr ) {
955 for (
int idx=0; itr!=
fObsNameVec.end(); ++itr, ++idx ) {
956 theObservables.
add( *
proto->var(*itr) );
961 std::string ParamSetPrefix =
"gamma_stat_" + channel_name;
962 double gammaMin = 0.0;
963 double gammaMax = 10.0;
965 ParamSetPrefix.c_str(),
969 ParamHistFunc statUncertFunc(statFuncName.c_str(), statFuncName.c_str(),
970 theObservables, statFactorParams );
978 sampleHistFuncs.push_back(paramHist);
987 if( !sample.GetShapeFactorList().empty() ) {
990 cxcoutF(
HistFactory) <<
"Cannot include Stat Error for histograms of more than 3 dimensions."
995 cxcoutI(
HistFactory) <<
"Sample: " << sample.GetName() <<
" in channel: " << channel_name
996 <<
" to be include a ShapeFactor."
999 for(
ShapeFactor& shapeFactor : sample.GetShapeFactorList()) {
1001 std::string funcName = channel_name +
"_" + shapeFactor.GetName() +
"_shapeFactor";
1003 if( paramHist ==
nullptr ) {
1007 theObservables.
add( *
proto->var(varName) );
1011 std::string funcParams =
"gamma_" + shapeFactor.GetName();
1017 theObservables, 0, 1000);
1020 ParamHistFunc shapeFactorFunc( funcName.c_str(), funcName.c_str(),
1021 theObservables, shapeFactorParams );
1024 if( shapeFactor.GetInitialShape() !=
nullptr ) {
1025 TH1* initialShape =
static_cast<TH1*
>(shapeFactor.GetInitialShape()->Clone());
1027 <<
" to have initial shape from hist: "
1030 shapeFactorFunc.
setShape( initialShape );
1034 if( shapeFactor.IsConstant() ) {
1036 <<
" to be constant" << std::endl;
1045 sampleHistFuncs.push_back(paramHist);
1055 if( !sample.GetShapeSysList().empty() ) {
1058 cxcoutF(
HistFactory) <<
"Cannot include Stat Error for histograms of more than 3 dimensions."
1064 std::vector<string> ShapeSysNames;
1077 cxcoutI(
HistFactory) <<
"Sample: " << sample.GetName() <<
" in channel: " << channel_name
1078 <<
" to include a ShapeSys." << std::endl;
1080 std::string funcName = channel_name +
"_" + shapeSys.GetName() +
"_ShapeSys";
1081 ShapeSysNames.push_back( funcName );
1083 if( paramHist ==
nullptr ) {
1090 theObservables.
add( *
proto->var(varName) );
1094 std::string funcParams =
"gamma_" + shapeSys.GetName();
1097 theObservables, 0, 10);
1100 ParamHistFunc shapeFactorFunc( funcName.c_str(), funcName.c_str(),
1101 theObservables, shapeFactorParams );
1113 const TH1* shapeErrorHist = shapeSys.GetErrorHist();
1124 double minShapeUncertainty = 0.0;
1126 *paramHist, shapeErrorHist,
1128 minShapeUncertainty);
1136 for(std::string
const&
name : ShapeSysNames) {
1137 sampleHistFuncs.push_back(
proto->function(
name));
1148 auto lumi =
proto->arg(
"Lumi");
1149 if( !sample.GetNormalizeByTheory() ) {
1152 lumiParamString += measurement.
GetLumi();
1154 lumi =
proto->factory((
"Lumi[" + lumiParamString +
"]").Data());
1160 normFactors->addTerm(lumi);
1166 auto normFactorsInWS =
dynamic_cast<RooProduct*
>(
proto->arg(normFactors->GetName()));
1167 assert(normFactorsInWS);
1169 sampleScaleFactors.push_back(normFactorsInWS);
1174 if(!statHistPairs.empty()) {
1179 if( fracStatError ==
nullptr ) {
1181 << channel_name +
"_StatUncert" +
"_RelErr" << std::endl;
1189 << chanStatUncertFunc->
GetName()
1190 <<
" params: " << chanStatUncertFunc->
paramList()
1209 *chanStatUncertFunc, fracStatError.
get(),
1211 statRelErrorThreshold);
1219 sampleScaleFactors, allSampleHistFuncs);
1220 likelihoodTermNames.push_back(channel_name+
"_model");
1224 for(
unsigned int i=0; i<systToFix.size(); ++i){
1228 <<
" could not set it to constant" << endl;
1236 for(
unsigned int i=0; i<constraintTermNames.size(); ++i){
1237 RooAbsArg* proto_arg = (
proto->arg(constraintTermNames[i].c_str()));
1238 if( proto_arg==
nullptr ) {
1243 constraintTerms.
add( *proto_arg );
1246 for(
unsigned int i=0; i<likelihoodTermNames.size(); ++i){
1247 RooAbsArg* proto_arg = (
proto->arg(likelihoodTermNames[i].c_str()));
1248 if( proto_arg==
nullptr ) {
1253 likelihoodTerms.add( *proto_arg );
1255 proto->defineSet(
"constraintTerms",constraintTerms);
1256 proto->defineSet(
"likelihoodTerms",likelihoodTerms);
1260 std::string observablesStr;
1264 if (!observablesStr.empty()) { observablesStr +=
","; }
1265 observablesStr +=
name;
1277 <<
"\timport model into workspace"
1278 <<
"\n-----------------------------------------\n" << endl;
1280 auto model = make_unique<RooProdPdf>(
1281 (
"model_"+channel_name).c_str(),
1282 "product of Poissons accross bins for a single channel",
1283 constraintTerms,
Conditional(likelihoodTerms,observables));
1290 proto_config->SetPdf(*model);
1291 proto_config->SetObservables(observables);
1292 proto_config->SetGlobalObservables(*
proto->set(
"globalObservables"));
1296 proto->import(*proto_config,proto_config->GetName());
1297 proto->importClassCode();
1304 int asymcalcPrintLevel = 0;
1317 proto->import(dataset);
1322 if(
data.GetName().empty()) {
1324 <<
" has no name! The name always needs to be set for additional datasets, "
1325 <<
"either via the \"Name\" tag in the XML or via RooStats::HistFactory::Data::SetName()." << std::endl;
1328 std::string
const& dataName =
data.GetName();
1329 TH1 const* mnominal =
data.GetHisto();
1332 <<
" with name: " << dataName <<
" is nullptr" << std::endl;
1339 proto->import(dataset);
1351 TH1 const& mnominal,
1353 std::vector<std::string>
const& obsNameVec) {
1359 if (obsNameVec.empty() ) {
1360 Error(
"ConfigureHistFactoryDataset",
"Invalid input - return");
1368 for (
int i=1; i<=ax->
GetNbins(); ++i) {
1371 proto.var( obsNameVec[0] )->setVal( xval );
1373 if(obsNameVec.size()==1) {
1375 obsDataUnbinned.
add( *
proto.set(
"observables"), fval );
1378 for(
int j=1; j<=ay->
GetNbins(); ++j) {
1380 proto.var( obsNameVec[1] )->setVal( yval );
1382 if(obsNameVec.size()==2) {
1384 obsDataUnbinned.
add( *
proto.set(
"observables"), fval );
1387 for(
int k=1; k<=az->
GetNbins(); ++k) {
1389 proto.var( obsNameVec[2] )->setVal( zval );
1391 obsDataUnbinned.
add( *
proto.set(
"observables"), fval );
1411 if (ch_names.empty() || chs.empty() ) {
1412 Error(
"MakeCombinedModel",
"Input vectors are empty - return a nullptr");
1415 if (chs.size() < ch_names.size() ) {
1416 Error(
"MakeCombinedModel",
"Input vector of workspace has an invalid size - return a nullptr");
1424 map<string, RooAbsPdf*> pdfMap;
1425 vector<RooAbsPdf*> models;
1428 for(
unsigned int i = 0; i< ch_names.size(); ++i){
1429 obsList.
add(*
static_cast<ModelConfig *
>(chs[i]->obj(
"ModelConfig"))->GetObservables());
1434 stringstream channelString;
1435 channelString <<
"channelCat[";
1436 for(
unsigned int i = 0; i< ch_names.size(); ++i){
1437 string channel_name=ch_names[i];
1438 if (i == 0 && isdigit(channel_name[0])) {
1439 throw std::invalid_argument(
"The first channel name for HistFactory cannot start with a digit. Got " + channel_name);
1441 if (channel_name.find(
',') != std::string::npos) {
1442 throw std::invalid_argument(
"Channel names for HistFactory cannot contain ','. Got " + channel_name);
1445 if (i == 0) channelString << channel_name ;
1446 else channelString <<
',' << channel_name ;
1450 if(!model) cout <<
"failed to find model for channel"<<endl;
1452 models.push_back(model);
1453 globalObs.
add(*ch->
set(
"globalObservables"),
true);
1456 pdfMap[channel_name]=model;
1458 channelString <<
"]";
1461 <<
"\tEntering combination"
1462 <<
"\n-----------------------------------------\n" << endl;
1468 if (!channelCat)
throw std::runtime_error(
"Unable to construct a category from string " + channelString.str());
1470 auto simPdf= std::make_unique<RooSimultaneous>(
"simPdf",
"",pdfMap, *channelCat);
1471 auto combined_config = std::make_unique<ModelConfig>(
"ModelConfig", combined);
1472 combined_config->SetWorkspace(*combined);
1475 combined->
import(globalObs);
1476 combined->
defineSet(
"globalObservables",globalObs);
1477 combined_config->SetGlobalObservables(*combined->
set(
"globalObservables"));
1479 combined->
defineSet(
"observables",{obsList, *channelCat},
true);
1480 combined_config->SetObservables(*combined->
set(
"observables"));
1487 if(std::string(
"asimovData") ==
data->GetName()) {
1492 std::map<std::string, RooAbsData*> dataMap;
1493 for(
unsigned int i = 0; i < ch_names.size(); ++i){
1494 dataMap[ch_names[i]] = chs[i]->data(
data->GetName());
1504 <<
"\tImporting combined model"
1505 <<
"\n-----------------------------------------\n" << endl;
1510 std::string paramName = param_itr.first;
1511 double paramVal = param_itr.second;
1514 temp->setVal( paramVal );
1515 cxcoutI(
HistFactory) <<
"setting " << paramName <<
" to the value: " << paramVal << endl;
1517 cxcoutE(
HistFactory) <<
"could not find variable " << paramName <<
" could not set its value" << endl;
1521 for(
unsigned int i=0; i<
fSystToFix.size(); ++i){
1524 temp->setConstant();
1535 combined_config->SetPdf(*simPdf);
1538 combined->
import(*combined_config,combined_config->GetName());
1546 <<
"\tcreate toy data for " << channelString.str()
1547 <<
"\n-----------------------------------------\n" << endl;
1555 *combined->
pdf(
"simPdf"),
1557 if( asimov_combined ) {
1558 combined->
import( *asimov_combined,
Rename(
"asimovData"));
1561 std::cout <<
"Error: Failed to create combined asimov dataset" << std::endl;
1579 Int_t binNumber = 0;
1582 for(
Int_t i_bin = 0; i_bin < numBins; ++i_bin) {
1590 double histError = Nominal->
GetBinError( binNumber );
1593 if( histError != histError ) {
1594 std::cout <<
"Warning: In histogram " << Nominal->
GetName()
1595 <<
" bin error for bin " << i_bin
1596 <<
" is NAN. Not using Error!!!"
1604 if( histError < 0 ) {
1605 std::cout <<
"Warning: In histogram " << Nominal->
GetName()
1606 <<
" bin error for bin " << binNumber
1607 <<
" is < 0. Setting Error to 0"
1632 unsigned int numHists = HistVec.size();
1634 if( numHists == 0 ) {
1635 cxcoutE(
HistFactory) <<
"Warning: Empty Hist Vector, cannot create total uncertainty" << std::endl;
1639 const TH1* HistTemplate = HistVec.at(0).first;
1644 for(
unsigned int i = 0; i < HistVec.size(); ++i ) {
1646 const TH1* nominal = HistVec.at(i).first;
1647 const TH1* error = HistVec.at(i).second.get();
1659 std::vector<double> TotalBinContent( numBins, 0.0);
1660 std::vector<double> HistErrorsSqr( numBins, 0.0);
1662 Int_t binNumber = 0;
1665 for(
Int_t i_bins = 0; i_bins < numBins; ++i_bins) {
1672 for(
unsigned int i_hist = 0; i_hist < numHists; ++i_hist ) {
1674 const TH1* nominal = HistVec.at(i_hist).first;
1675 const TH1* error = HistVec.at(i_hist).second.get();
1682 if( histError != histError ) {
1684 <<
" bin error for bin " << binNumber
1685 <<
" is NAN. Not using error!!";
1689 TotalBinContent.at(i_bins) += histValue;
1690 HistErrorsSqr.at(i_bins) += histError*histError;
1702 for(
Int_t i = 0; i < numBins; ++i) {
1710 double ErrorsSqr = HistErrorsSqr.at(i);
1711 double TotalVal = TotalBinContent.at(i);
1713 if( TotalVal <= 0 ) {
1715 <<
" is <= 0. Setting error to 0"
1722 double RelativeError = sqrt(ErrorsSqr) / TotalVal;
1726 if( RelativeError != RelativeError ) {
1728 <<
" HistErrorsSqr: " << ErrorsSqr
1729 <<
" TotalVal: " << TotalVal;
1743 <<
" Error = " << sqrt(ErrorsSqr)
1744 <<
" CentralVal = " << TotalVal
1745 <<
" RelativeError = " << RelativeError <<
"\n";
1749 return std::unique_ptr<TH1>(ErrorHist);
1785 if( numBins != numParams ) {
1786 std::cout <<
"Error: In createStatConstraintTerms, encountered bad number of bins" << std::endl;
1787 std::cout <<
"Given histogram with " << numBins <<
" bins,"
1788 <<
" but require exactly " << numParams << std::endl;
1792 Int_t TH1BinNumber = 0;
1804 <<
". Type of constraint: " <<
type << std::endl;
1808 const double sigmaRel = uncertHist->
GetBinContent(TH1BinNumber);
1812 if( sigmaRel <= 0 ){
1815 <<
" because sigma = " << sigmaRel
1817 <<
" (TH1 bin number = " << TH1BinNumber <<
")"
1819 gamma.setConstant(
true);
1824 gamma.setMax( 1 + 5*sigmaRel );
1828 std::string constrName = string(gamma.GetName()) +
"_constraint";
1829 std::string nomName = string(
"nom_") + gamma.GetName();
1830 std::string sigmaName = string(gamma.GetName()) +
"_sigma";
1831 std::string poisMeanName = string(gamma.GetName()) +
"_poisMean";
1839 RooConstVar constrSigma( sigmaName.c_str(), sigmaName.c_str(), sigmaRel );
1842 RooRealVar constrNom(nomName.c_str(), nomName.c_str(), 1.0,0,10);
1846 getOrCreate<RooGaussian>(*
proto, constrName, constrNom, gamma, constrSigma);
1850 gamma.setError(sigmaRel);
1853 double tau = 1/sigmaRel/sigmaRel;
1856 RooRealVar constrNom(nomName.c_str(), nomName.c_str(), tau);
1861 std::string scalingName = string(gamma.GetName()) +
"_tau";
1862 RooConstVar poissonScaling( scalingName.c_str(), scalingName.c_str(), tau);
1865 RooProduct constrMean( poisMeanName.c_str(), poisMeanName.c_str(),
RooArgSet(gamma, poissonScaling) );
1868 getOrCreate<RooPoisson>(*
proto, constrName, constrNom, constrMean).setNoRounding(
true);
1870 if (std::string(gamma.GetName()).find(
"gamma_stat") != std::string::npos) {
1873 gamma.setError(sigmaRel);
1878 std::cout <<
"Error: Did not recognize Stat Error constraint term type: "
1879 <<
type <<
" for : " << paramHist.
GetName() << std::endl;
1886 if( sigmaRel < minSigma ) {
1888 <<
" and is < " << minSigma
1889 <<
". Setting: " << gamma.GetName() <<
" to constant"
1891 gamma.setConstant(
true);
1894 constraintTermNames.push_back( constrName );
1895 ConstraintTerms.
add( *
proto->pdf(constrName) );
1902 if( ! globalSet->
contains(*nomVarInWorkspace) ) {
1903 globalSet->
add( *nomVarInWorkspace );
1908 return ConstraintTerms;
constexpr double alphaHigh
constexpr double alphaLow
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
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 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 char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
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
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
const RooArgSet * get(Int_t masterIdx) const
void setConstant(bool constant)
const RooArgList & paramList() const
static RooArgList createParamSet(RooWorkspace &w, const std::string &, const RooArgList &Vars)
Create the list of RooRealVar parameters which represent the height of the histogram bins.
void setShape(TH1 *shape)
The PiecewiseInterpolation is a class that can morph distributions into each other,...
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
void Print(Option_t *options=nullptr) const override
Print the object to the defaultPrintStream().
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
bool contains(const RooAbsArg &var) const
Check if collection contains an argument with the same name as var.
Int_t getSize() const
Return the number of elements in the collection.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
const_iterator begin() const
RooAbsData is the common abstract base class for binned and unbinned datasets.
RooAbsRealLValue is the common abstract base class for objects that represent a real value that may a...
void setConstant(bool value=true)
RooNumIntConfig * specialIntegratorConfig() const
Returns the specialized integrator configuration for this RooAbsReal.
virtual void forceNumInt(bool flag=true)
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
RooBinWidthFunction is a class that returns the bin width (or volume) given a RooHistFunc.
Class RooBinning is an implements RooAbsBinning in terms of an array of boundary values,...
RooCategory is an object to represent discrete states.
bool setLabel(const char *label, bool printError=true) override
Set value by specifying the name of the desired state.
RooConstVar represent a constant real-valued object.
The RooDataHist is a container class to hold N-dimensional binned data.
RooDataSet is a container class to hold unbinned data.
void add(const RooArgSet &row, double weight=1.0, double weightError=0.0) override
Add one ore more rows of data.
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Switches the message service to a different level while the instance is alive.
RooHistFunc implements a real-valued function sampled from a multidimensional histogram.
static RooMsgService & instance()
Return reference to singleton instance.
bool isActive(const RooAbsArg *self, RooFit::MsgTopic facility, RooFit::MsgLevel level)
Check if logging is active for given object/topic/RooFit::MsgLevel combination.
A RooProduct represents the product of a given set of RooAbsReal objects.
The class RooRealSumPdf implements a PDF constructed from a sum of functions:
RooRealVar represents a variable that can be changed from the outside.
void setMin(const char *name, double value)
Set minimum of name range to given value.
static void SetPrintLevel(int level)
set print level (static function)
static RooAbsData * GenerateAsimovData(const RooAbsPdf &pdf, const RooArgSet &observables)
generate the asimov data for the observables (not the global ones) need to deal with the case of a si...
TODO Here, we are missing some documentation.
void ConfigureWorkspace(RooWorkspace *)
This class encapsulates all information for the statistical interpretation of one experiment.
std::vector< RooStats::HistFactory::Data > & GetAdditionalData()
retrieve vector of additional data objects
void Print(std::ostream &=std::cout)
HistFactory::StatErrorConfig & GetStatErrorConfig()
get information about threshold for statistical uncertainties and constraint term
RooStats::HistFactory::Data & GetData()
get data object
bool CheckHistograms() const
std::vector< RooStats::HistFactory::Sample > & GetSamples()
get vector of samples for this channel
std::string GetName() const
get name of channel
void setAllInterpCodes(int code)
Configuration for a constrained, coherent shape variation of affected samples.
This class provides helper functions for creating likelihood models from histograms.
std::unique_ptr< RooProduct > CreateNormFactor(RooWorkspace *proto, std::string &channel, std::string &sigmaEpsilon, Sample &sample, bool doRatio)
RooWorkspace * MakeSingleChannelModel(Measurement &measurement, Channel &channel)
RooWorkspace * MakeSingleChannelWorkspace(Measurement &measurement, Channel &channel)
void GuessObsNameVec(const TH1 *hist)
RooArgList createStatConstraintTerms(RooWorkspace *proto, std::vector< std::string > &constraintTerms, ParamHistFunc ¶mHist, const TH1 *uncertHist, Constraint::Type type, double minSigma)
std::unique_ptr< TH1 > MakeScaledUncertaintyHist(const std::string &Name, std::vector< std::pair< const TH1 *, std::unique_ptr< TH1 > > > const &HistVec) const
std::vector< std::string > fPreprocessFunctions
void SetFunctionsToPreprocess(std::vector< std::string > lines)
std::vector< std::string > fObsNameVec
RooHistFunc * MakeExpectedHistFunc(const TH1 *hist, RooWorkspace *proto, std::string prefix, const RooArgList &observables) const
Create the nominal hist function from hist, and register it in the workspace.
TH1 * MakeAbsolUncertaintyHist(const std::string &Name, const TH1 *Hist)
std::map< std::string, double > fParamValues
static void ConfigureWorkspaceForMeasurement(const std::string &ModelName, RooWorkspace *ws_single, Measurement &measurement)
void MakeTotalExpected(RooWorkspace *proto, const std::string &totName, const std::vector< RooProduct * > &sampleScaleFactors, std::vector< std::vector< RooAbsArg * > > &sampleHistFuncs) const
void ConfigureHistFactoryDataset(RooDataSet &obsData, TH1 const &nominal, RooWorkspace &proto, std::vector< std::string > const &obsNameVec)
static void PrintCovarianceMatrix(RooFitResult *result, RooArgSet *params, std::string filename)
std::vector< std::string > fSystToFix
void AddConstraintTerms(RooWorkspace *proto, Measurement &measurement, std::string prefix, std::string interpName, std::vector< OverallSys > &systList, std::vector< std::string > &likelihoodTermNames, std::vector< std::string > &totSystTermNames)
RooArgList createObservables(const TH1 *hist, RooWorkspace *proto) const
Create observables of type RooRealVar. Creates 1 to 3 observables, depending on the type of the histo...
HistoToWorkspaceFactoryFast()
RooWorkspace * MakeCombinedModel(std::vector< std::string >, std::vector< std::unique_ptr< RooWorkspace > > &)
const TH1 * GetHistoHigh() const
const TH1 * GetHistoLow() const
The RooStats::HistFactory::Measurement class can be used to construct a model by combining multiple R...
std::map< std::string, double > & GetGammaSyst()
std::map< std::string, double > & GetLogNormSyst()
std::map< std::string, double > & GetNoSyst()
std::vector< std::string > & GetPOIList()
get vector of PoI names
std::map< std::string, double > & GetUniformSyst()
std::vector< std::string > & GetConstantParams()
get vector of all constant parameters
std::vector< RooStats::HistFactory::Channel > & GetChannels()
std::vector< RooStats::HistFactory::Asimov > & GetAsimovDatasets()
get vector of defined Asimov Datasets
std::vector< std::string > GetPreprocessFunctions() const
Returns a list of defined preprocess function expressions.
double GetLumi()
retrieve integrated luminosity
Configuration for an un- constrained overall systematic to scale sample normalisations.
Configuration for a constrained overall systematic to scale sample normalisations.
const std::string & GetName() const
std::string GetName() const
get name of sample
std::vector< RooStats::HistFactory::NormFactor > & GetNormFactorList()
*Un*constrained bin-by-bin variation of affected histogram.
Constrained bin-by-bin variation of affected histogram.
double GetRelErrorThreshold() const
Constraint::Type GetConstraintType() const
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
void GuessObsAndNuisance(const RooAbsData &data, bool printModelConfig=true)
Makes sensible guesses of observables, parameters of interest and nuisance parameters if one or multi...
virtual void SetParametersOfInterest(const RooArgSet &set)
Specify parameters of interest.
The RooWorkspace is a persistable container for RooFit projects.
TObject * obj(RooStringView name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
void Print(Option_t *opts=nullptr) const override
Print contents of the workspace.
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooArgSet allVars() const
Return set with all variable objects.
const RooArgSet * set(RooStringView name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
bool import(const RooAbsArg &arg, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg())
Import a RooAbsArg object, e.g.
bool saveSnapshot(RooStringView, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
bool importClassCode(const char *pat="*", bool doReplace=false)
Inport code of all classes in the workspace that have a class name that matches pattern 'pat' and whi...
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.
RooAbsData * data(RooStringView name) const
Retrieve dataset (binned or unbinned) with given name. A null pointer is returned if not found.
bool loadSnapshot(const char *name)
Load the values and attributes of the parameters in the snapshot saved with the given name.
bool defineSet(const char *name, const RooArgSet &aset, bool importMissing=false)
Define a named RooArgSet with given constituents.
const Double_t * GetArray() const
Class to manage histogram axis.
Bool_t IsVariableBinSize() const
const char * GetTitle() const override
Returns title of object.
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
const TArrayD * GetXbins() const
TH1 is the base class of all histogram classes in ROOT.
virtual Int_t GetNbinsY() const
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
virtual Int_t GetNbinsZ() const
virtual Int_t GetDimension() const
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
virtual Int_t GetNbinsX() const
virtual void SetBinError(Int_t bin, Double_t error)
Set the bin Error Note that this resets the bin eror option to be of Normal Type and for the non-empt...
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
TObject * Clone(const char *newname="") const override
Make a complete copy of the underlying object.
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
const char * GetName() const override
Returns name of object.
const char * GetTitle() const override
Returns title of object.
Mother of all ROOT objects.
virtual const char * ClassName() const
Returns name of class to which the object belongs.
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
TString & ReplaceAll(const TString &s1, const TString &s2)
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
RooCmdArg RecycleConflictNodes(bool flag=true)
RooCmdArg Rename(const char *suffix)
RooCmdArg Conditional(const RooArgSet &pdfSet, const RooArgSet &depSet, bool depsAreCond=false)
RooCmdArg Index(RooCategory &icat)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Import(const char *state, TH1 &histo)
RooCmdArg Name(const char *name)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Namespace for the RooStats classes.
bool binnedFitOptimization