Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HistoToWorkspaceFactoryFast.cxx
Go to the documentation of this file.
1// @(#)root/roostats:$Id: cranmer $
2// Author: Kyle Cranmer, Akira Shibata
3/*************************************************************************
4 * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
5 * All rights reserved. *
6 * *
7 * For the licensing terms see $ROOTSYS/LICENSE. *
8 * For the list of contributors see $ROOTSYS/README/CREDITS. *
9 *************************************************************************/
10
11////////////////////////////////////////////////////////////////////////////////
12
13/** \class RooStats::HistFactory::HistoToWorkspaceFactoryFast
14 * \ingroup HistFactory
15 * This class provides helper functions for creating likelihood models from histograms.
16 * It is used by RooStats::HistFactory::MakeModelAndMeasurementFast.
17 *
18 * A tutorial showing how to create a HistFactory model is hf001_example.C
19 */
20
21
22#include <RooAddition.h>
23#include <RooBinWidthFunction.h>
24#include <RooBinning.h>
25#include <RooCategory.h>
26#include <RooConstVar.h>
27#include <RooDataHist.h>
28#include <RooDataSet.h>
29#include <RooFit/ModelConfig.h>
30#include <RooFitResult.h>
31#include <RooFormulaVar.h>
32#include <RooGamma.h>
33#include <RooGaussian.h>
34#include <RooGlobalFunc.h>
35#include <RooHelpers.h>
36#include <RooHistFunc.h>
37#include <RooMultiVarGaussian.h>
38#include <RooNumIntConfig.h>
39#include <RooPoisson.h>
40#include <RooPolyVar.h>
41#include <RooProdPdf.h>
42#include <RooProduct.h>
43#include <RooProfileLL.h>
44#include <RooRandom.h>
45#include <RooRealSumPdf.h>
46#include <RooRealVar.h>
47#include <RooSimultaneous.h>
48#include <RooWorkspace.h>
49
54
55#include "HFMsgService.h"
56
57#include "TH1.h"
58#include "TStopwatch.h"
59#include "TVectorD.h"
60#include "TMatrixDSym.h"
61
62// specific to this package
69
70#include <algorithm>
71#include <fstream>
72#include <iomanip>
73#include <memory>
74#include <utility>
75
76constexpr double alphaLow = -5.0;
77constexpr double alphaHigh = 5.0;
78
79std::vector<double> histToVector(TH1 const &hist)
80{
81 // Must get the full size of the TH1 (No direct method to do this...)
82 int numBins = hist.GetNbinsX() * hist.GetNbinsY() * hist.GetNbinsZ();
83 std::vector<double> out(numBins);
84 int histIndex = 0;
85 for (int i = 0; i < numBins; ++i) {
86 while (hist.IsBinUnderflow(histIndex) || hist.IsBinOverflow(histIndex)) {
87 ++histIndex;
88 }
89 out[i] = hist.GetBinContent(histIndex);
90 ++histIndex;
91 }
92 return out;
93}
94
95// use this order for safety on library loading
96using namespace RooStats;
97using std::string, std::vector, std::make_unique, std::pair, std::unique_ptr, std::map;
98
99using namespace RooStats::HistFactory::Detail;
101
102
103namespace RooStats{
104namespace HistFactory{
105
108
110 Configuration const& cfg) :
111 fSystToFix( measurement.GetConstantParams() ),
112 fParamValues( measurement.GetParamValues() ),
113 fNomLumi( measurement.GetLumi() ),
114 fLumiError( measurement.GetLumi()*measurement.GetLumiRelErr() ),
115 fLowBin( measurement.GetBinLow() ),
116 fHighBin( measurement.GetBinHigh() ),
117 fCfg{cfg} {
118
119 // Set Preprocess functions
120 SetFunctionsToPreprocess( measurement.GetPreprocessFunctions() );
121
122 }
123
125
126 // Configure a workspace by doing any
127 // necessary post-processing and by
128 // creating a ModelConfig
129
130 // Make a ModelConfig and configure it
131 ModelConfig * proto_config = static_cast<ModelConfig *>(ws_single->obj("ModelConfig"));
132 if( proto_config == nullptr ) {
133 std::cout << "Error: Did not find 'ModelConfig' object in file: " << ws_single->GetName()
134 << std::endl;
135 throw hf_exc();
136 }
137
138 if( measurement.GetPOIList().empty() ) {
139 cxcoutWHF << "No Parametetrs of interest are set" << std::endl;
140 }
141
142
143 std::stringstream sstream;
144 sstream << "Setting Parameter(s) of Interest as: ";
145 for(auto const& item : measurement.GetPOIList()) {
146 sstream << item << " ";
147 }
148 cxcoutIHF << sstream.str() << std::endl;
149
150 RooArgSet params;
151 for(auto const& poi_name : measurement.GetPOIList()) {
152 if(RooRealVar* poi = (RooRealVar*) ws_single->var(poi_name)){
153 params.add(*poi);
154 }
155 else {
156 std::cout << "WARNING: Can't find parameter of interest: " << poi_name
157 << " in Workspace. Not setting in ModelConfig." << std::endl;
158 //throw hf_exc();
159 }
160 }
161 proto_config->SetParametersOfInterest(params);
162
163 // Name of an 'edited' model, if necessary
164 std::string NewModelName = "newSimPdf"; // <- This name is hard-coded in HistoToWorkspaceFactoryFast::EditSyt. Probably should be changed to : std::string("new") + ModelName;
165
166 // Get the pdf
167 // Notice that we get the "new" pdf, this is the one that is
168 // used in the creation of these asimov datasets since they
169 // are fitted (or may be, at least).
170 RooAbsPdf* pdf = ws_single->pdf(NewModelName);
171 if( !pdf ) pdf = ws_single->pdf( ModelName );
172 const RooArgSet* observables = ws_single->set("observables");
173
174 // Set the ModelConfig's Params of Interest
175 if(!measurement.GetPOIList().empty()){
176 proto_config->GuessObsAndNuisance(*observables, RooMsgService::instance().isActive(nullptr, RooFit::HistFactory, RooFit::INFO));
177 }
178
179 // Now, let's loop over any additional asimov datasets
180 // that we need to make
181
182 // Create a SnapShot of the nominal values
183 std::string SnapShotName = "NominalParamValues";
184 ws_single->saveSnapshot(SnapShotName, ws_single->allVars());
185
186 for( unsigned int i=0; i<measurement.GetAsimovDatasets().size(); ++i) {
187
188 // Set the variable values and "const" ness with the workspace
189 RooStats::HistFactory::Asimov& asimov = measurement.GetAsimovDatasets().at(i);
190 std::string AsimovName = asimov.GetName();
191
192 cxcoutPHF << "Generating additional Asimov Dataset: " << AsimovName << std::endl;
194 std::unique_ptr<RooAbsData> asimov_dataset{AsymptoticCalculator::GenerateAsimovData(*pdf, *observables)};
195
196 cxcoutPHF << "Importing Asimov dataset" << std::endl;
197 bool failure = ws_single->import(*asimov_dataset, RooFit::Rename(AsimovName.c_str()));
198 if( failure ) {
199 std::cout << "Error: Failed to import Asimov dataset: " << AsimovName
200 << std::endl;
201 throw hf_exc();
202 }
203
204 // Load the snapshot at the end of every loop iteration
205 // so we start each loop with a "clean" snapshot
206 ws_single->loadSnapshot(SnapShotName.c_str());
207 }
208
209 // Cool, we're done
210 return; // ws_single;
211 }
212
213
214 // We want to eliminate this interface and use the measurement directly
216
217 // This is a pretty light-weight wrapper function
218 //
219 // Take a fully configured measurement as well as
220 // one of its channels
221 //
222 // Return a workspace representing that channel
223 // Do this by first creating a vector of EstimateSummary's
224 // and this by configuring the workspace with any post-processing
225
226 // Get the channel's name
227 string ch_name = channel.GetName();
228
229 // Create a workspace for a SingleChannel from the Measurement Object
230 std::unique_ptr<RooWorkspace> ws_single{this->MakeSingleChannelWorkspace(measurement, channel)};
231 if( ws_single == nullptr ) {
232 cxcoutF(HistFactory) << "Error: Failed to make Single-Channel workspace for channel: " << ch_name
233 << " and measurement: " << measurement.GetName() << std::endl;
234 throw hf_exc();
235 }
236
237 // Finally, configure that workspace based on
238 // properties of the measurement
240
241 return RooFit::makeOwningPtr(std::move(ws_single));
242
243 }
244
246
247 // This function takes a fully configured measurement
248 // which may contain several channels and returns
249 // a workspace holding the combined model
250 //
251 // This can be used, for example, within a script to produce
252 // a combined workspace on-the-fly
253 //
254 // This is a static function (for now) to make
255 // it a one-liner
256
257
258 Configuration config;
259 return MakeCombinedModel(measurement,config);
260 }
261
263
264 // This function takes a fully configured measurement
265 // which may contain several channels and returns
266 // a workspace holding the combined model
267 //
268 // This can be used, for example, within a script to produce
269 // a combined workspace on-the-fly
270 //
271 // This is a static function (for now) to make
272 // it a one-liner
273
275
276 // First, we create an instance of a HistFactory
278
279 // Loop over the channels and create the individual workspaces
282
283 for(HistFactory::Channel& channel : measurement.GetChannels()) {
284
285 if( ! channel.CheckHistograms() ) {
286 cxcoutFHF << "MakeModelAndMeasurementsFast: Channel: " << channel.GetName()
287 << " has uninitialized histogram pointers" << std::endl;
288 throw hf_exc();
289 }
290
291 string ch_name = channel.GetName();
292 channel_names.push_back(ch_name);
293
294 // GHL: Renaming to 'MakeSingleChannelWorkspace'
295 channel_workspaces.emplace_back(histFactory.MakeSingleChannelModel(measurement, channel));
296 }
297
298
299 // Now, combine the individual channel workspaces to
300 // form the combined workspace
301 std::unique_ptr<RooWorkspace> ws{histFactory.MakeCombinedModel( channel_names, channel_workspaces )};
302
303
304 // Configure the workspace
306
307 // Done. Return the pointer
308 return RooFit::makeOwningPtr(std::move(ws));
309
310 }
311
312namespace {
313
314template <class Arg_t, typename... Args_t>
315Arg_t &emplace(RooWorkspace &ws, std::string const &name, Args_t &&...args)
316{
317 Arg_t arg{name.c_str(), name.c_str(), std::forward<Args_t>(args)...};
319 return *dynamic_cast<Arg_t *>(ws.arg(name));
320}
321
322} // namespace
323
324/// Create observables of type RooRealVar. Creates 1 to 3 observables, depending on the type of the histogram.
326 RooArgList observables;
327
328 for (unsigned int idx=0; idx < fObsNameVec.size(); ++idx) {
329 if (!proto.var(fObsNameVec[idx])) {
330 const TAxis *axis = (idx == 0) ? hist->GetXaxis() : (idx == 1 ? hist->GetYaxis() : hist->GetZaxis());
331 int nbins = axis->GetNbins();
332 // create observable
333 RooRealVar &obs = emplace<RooRealVar>(proto, fObsNameVec[idx], axis->GetXmin(), axis->GetXmax());
334 if(strlen(axis->GetTitle())>0) obs.SetTitle(axis->GetTitle());
335 obs.setBins(nbins);
336 if (axis->IsVariableBinSize()) {
337 RooBinning binning(nbins, axis->GetXbins()->GetArray());
338 obs.setBinning(binning);
339 }
340 }
341
342 observables.add(*proto.var(fObsNameVec[idx]));
343 }
344
345 return observables;
346}
347
348 /// Create the nominal hist function from `hist`, and register it in the workspace.
350 const RooArgList& observables) const {
351 if(hist) {
352 cxcoutI(HistFactory) << "processing hist " << hist->GetName() << std::endl;
353 } else {
354 cxcoutF(HistFactory) << "hist is empty" << std::endl;
355 R__ASSERT(hist != nullptr);
356 return nullptr;
357 }
358
359 // determine histogram dimensionality
360 unsigned int histndim(1);
361 std::string classname = hist->ClassName();
362 if (classname.find("TH1")==0) { histndim=1; }
363 else if (classname.find("TH2")==0) { histndim=2; }
364 else if (classname.find("TH3")==0) { histndim=3; }
365 R__ASSERT( histndim==fObsNameVec.size() );
366
367 prefix += "_Hist_alphanominal";
368
369 RooDataHist histDHist(prefix + "DHist","",observables,hist);
370
371 return &emplace<RooHistFunc>(proto, prefix, observables,histDHist,0);
372 }
373
374 namespace {
375
376 void makeGaussianConstraint(RooAbsArg& param, RooWorkspace& proto, bool isUniform,
377 std::vector<std::string> & constraintTermNames) {
378 std::string paramName = param.GetName();
379 std::string nomName = "nom_" + paramName;
380 std::string constraintName = paramName + "Constraint";
381
382 // do nothing if the constraint term already exists
383 if(proto.pdf(constraintName)) return;
384
385 // case systematic is uniform (assume they are like a Gaussian but with
386 // a large width (100 instead of 1)
387 const double gaussSigma = isUniform ? 100. : 1.0;
388 if (isUniform) {
389 cxcoutIHF << "Added a uniform constraint for " << paramName << " as a Gaussian constraint with a very large sigma " << std::endl;
390 }
391
395 nomParam.setConstant();
397 paramVar.setError(gaussSigma); // give param initial error to match gaussSigma
398 const_cast<RooArgSet*>(proto.set("globalObservables"))->add(nomParam);
399 }
400
401 /// Make list of abstract parameters that interpolate in space of variations.
403 RooArgList params( ("alpha_Hist") );
404
405 for(auto const& histoSys : histoSysList) {
406 params.add(getOrCreate<RooRealVar>(proto, "alpha_" + histoSys.GetName(), alphaLow, alphaHigh));
407 }
408
409 return params;
410 }
411
412 /// Create a linear interpolation object that holds nominal and systematics, import it into the workspace,
413 /// and return a pointer to it.
416 RooWorkspace& proto, const std::vector<HistoSys>& histoSysList,
417 const string& prefix,
418 const RooArgList& obsList) {
419
420 // now make function that linearly interpolates expectation between variations
421 // get low/high variations to interpolate between
422 std::vector<double> low;
423 std::vector<double> high;
426 for(unsigned int j=0; j<histoSysList.size(); ++j){
427 std::string str = prefix + "_" + std::to_string(j);
428
429 const HistoSys& histoSys = histoSysList.at(j);
430 auto lowDHist = std::make_unique<RooDataHist>(str+"lowDHist","",obsList, histoSys.GetHistoLow());
431 auto highDHist = std::make_unique<RooDataHist>(str+"highDHist","",obsList, histoSys.GetHistoHigh());
432 lowSet.addOwned(std::make_unique<RooHistFunc>((str+"low").c_str(),"",obsList,std::move(lowDHist),0));
433 highSet.addOwned(std::make_unique<RooHistFunc>((str+"high").c_str(),"",obsList,std::move(highDHist),0));
434 }
435
436 // this is sigma(params), a piece-wise linear interpolation
438 interp.setPositiveDefinite();
439 interp.setAllInterpCodes(4); // LM: change to 4 (piece-wise linear to 6th order polynomial interpolation + linear extrapolation )
440 // KC: interpo codes 1 etc. don't have proper analytic integral.
442 interp.setBinIntegrator(obsSet);
443 interp.forceNumInt();
444
445 proto.import(interp, RooFit::RecycleConflictNodes()); // individual params have already been imported in first loop of this function
446
447 return proto.arg(prefix);
448 }
449
450 }
451
452 // GHL: Consider passing the NormFactor list instead of the entire sample
453 std::unique_ptr<RooProduct> HistoToWorkspaceFactoryFast::CreateNormFactor(RooWorkspace& proto, string& channel, string& sigmaEpsilon, Sample& sample, bool doRatio){
454
455 std::vector<string> prodNames;
456
457 vector<NormFactor> normList = sample.GetNormFactorList();
460
461 string overallNorm_times_sigmaEpsilon = sample.GetName() + "_" + channel + "_scaleFactors";
462 auto sigEps = proto.arg(sigmaEpsilon);
463 assert(sigEps);
464 auto normFactor = std::make_unique<RooProduct>(overallNorm_times_sigmaEpsilon.c_str(), overallNorm_times_sigmaEpsilon.c_str(), RooArgList(*sigEps));
465
466 if(!normList.empty()){
467
468 for(NormFactor &norm : normList) {
469 string varname = norm.GetName();
470 if(doRatio) {
471 varname += "_" + channel;
472 }
473
474 // GHL: Check that the NormFactor doesn't already exist
475 // (it may have been created as a function expression
476 // during preprocessing)
477 std::stringstream range;
478 range << "[" << norm.GetVal() << "," << norm.GetLow() << "," << norm.GetHigh() << "]";
479
480 if( proto.obj(varname) == nullptr) {
481 cxcoutI(HistFactory) << "making normFactor: " << norm.GetName() << std::endl;
482 // remove "doRatio" and name can be changed when ws gets imported to the combined model.
483 emplace<RooRealVar>(proto, varname, norm.GetVal(), norm.GetLow(), norm.GetHigh());
484 proto.var(varname)->setError(0); // ensure factor is assigned an initial error, even if its zero
485 }
486
487 prodNames.push_back(varname);
488 rangeNames.push_back(range.str());
489 normFactorNames.push_back(varname);
490 }
491
492
493 for (const auto& name : prodNames) {
494 auto arg = proto.arg(name);
495 assert(arg);
496 normFactor->addTerm(arg);
497 }
498
499 }
500
501 unsigned int rangeIndex=0;
502 for( vector<string>::iterator nit = normFactorNames.begin(); nit!=normFactorNames.end(); ++nit){
503 if( count (normFactorNames.begin(), normFactorNames.end(), *nit) > 1 ){
504 cxcoutI(HistFactory) <<"<NormFactor Name =\""<<*nit<<"\"> is duplicated for <Sample Name=\""
505 << sample.GetName() << "\">, but only one factor will be included. \n Instead, define something like"
506 << "\n\t<Function Name=\""<<*nit<<"Squared\" Expression=\""<<*nit<<"*"<<*nit<<"\" Var=\""<<*nit<<rangeNames.at(rangeIndex)
507 << "\"> \nin your top-level XML's <Measurement> entry and use <NormFactor Name=\""<<*nit<<"Squared\" in your channel XML file."<< std::endl;
508 }
509 ++rangeIndex;
510 }
511
512 return normFactor;
513 }
514
516 string interpName,
517 std::vector<OverallSys>& systList,
520
521 // add variables for all the relative overall uncertainties we expect
522 totSystTermNames.push_back(prefix);
523
524 RooArgSet params(prefix.c_str());
527
528 std::map<std::string, double>::iterator itconstr;
529 for(unsigned int i = 0; i < systList.size(); ++i) {
530
531 OverallSys& sys = systList.at(i);
532 std::string strname = sys.GetName();
533 const char * name = strname.c_str();
534
535 // case of no systematic (is it possible)
536 if (meas.GetNoSyst().count(sys.GetName()) > 0 ) {
537 cxcoutI(HistFactory) << "HistoToWorkspaceFast::AddConstraintTerm - skip systematic " << sys.GetName() << std::endl;
538 continue;
539 }
540 // case systematic is a gamma constraint
541 if (meas.GetGammaSyst().count(sys.GetName()) > 0 ) {
542 double relerr = meas.GetGammaSyst().find(sys.GetName() )->second;
543 if (relerr <= 0) {
544 cxcoutI(HistFactory) << "HistoToWorkspaceFast::AddConstraintTerm - zero uncertainty assigned - skip systematic " << sys.GetName() << std::endl;
545 continue;
546 }
547 const double tauVal = 1./(relerr*relerr);
548 const double sqtau = 1./relerr;
549 RooRealVar &beta = emplace<RooRealVar>(proto, "beta_" + strname, 1., 0., 10.);
550 // the global observable (y_s)
551 RooRealVar &yvar = emplace<RooRealVar>(proto, "nom_" + std::string{beta.GetName()}, tauVal, 0., 10.);
552 // the rate of the gamma distribution (theta)
553 RooRealVar &theta = emplace<RooRealVar>(proto, "theta_" + strname, 1./tauVal);
554 // find alpha as function of beta
556
557 // add now the constraint itself Gamma_beta_constraint(beta, y+1, tau, 0 )
558 // build the gamma parameter k = as y_s + 1
559 RooAddition &kappa = emplace<RooAddition>(proto, "k_" + std::string{yvar.GetName()}, RooArgList{yvar, 1.0});
560 RooGamma &gamma = emplace<RooGamma>(proto, std::string{beta.GetName()} + "Constraint", beta, kappa, theta, RooFit::RooConst(0.0));
562 alphaOfBeta.Print("t");
563 gamma.Print("t");
564 }
565 constraintTermNames.push_back(gamma.GetName());
566 // set global observables
567 yvar.setConstant(true);
568 const_cast<RooArgSet*>(proto.set("globalObservables"))->add(yvar);
569
570 // add alphaOfBeta in the list of params to interpolate
571 params.add(alphaOfBeta);
572 cxcoutI(HistFactory) << "Added a gamma constraint for " << name << std::endl;
573
574 }
575 else {
576 RooRealVar& alpha = getOrCreate<RooRealVar>(proto, prefix + sys.GetName(), 0, alphaLow, alphaHigh);
577 // add the Gaussian constraint part
578 const bool isUniform = meas.GetUniformSyst().count(sys.GetName()) > 0;
580
581 // check if exists a log-normal constraint
582 if (meas.GetLogNormSyst().count(sys.GetName()) == 0 && meas.GetGammaSyst().count(sys.GetName()) == 0 ) {
583 // just add the alpha for the parameters of the FlexibleInterpVar function
584 params.add(alpha);
585 }
586 // case systematic is a log-normal constraint
587 if (meas.GetLogNormSyst().count(sys.GetName()) > 0 ) {
588 // log normal constraint for parameter
589 const double relerr = meas.GetLogNormSyst().find(sys.GetName() )->second;
590
592 proto, "alphaOfBeta_" + sys.GetName(), "x[0]*(pow(x[1],x[2])-1.)",
593 RooArgList{emplace<RooRealVar>(proto, "tau_" + sys.GetName(), 1. / relerr),
594 emplace<RooRealVar>(proto, "kappa_" + sys.GetName(), 1. + relerr), alpha});
595
596 cxcoutI(HistFactory) << "Added a log-normal constraint for " << name << std::endl;
598 alphaOfBeta.Print("t");
599 }
600 params.add(alphaOfBeta);
601 }
602
603 }
604 // add low/high vectors
605 lowVec.push_back(sys.GetLow());
606 highVec.push_back(sys.GetHigh());
607
608 } // end sys loop
609
610 if(!systList.empty()){
611 // this is epsilon(alpha_j), a piece-wise linear interpolation
612 // LinInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec);
613
614 assert(!params.empty());
615 assert(lowVec.size() == params.size());
616
617 FlexibleInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec);
618 interp.setAllInterpCodes(4); // LM: change to 4 (piece-wise exponential to 6th order polynomial interpolation + exponential extrapolation )
619 //interp.setAllInterpCodes(0); // simple linear interpolation
620 proto.import(interp); // params have already been imported in first loop of this function
621 } else{
622 // some strange behavior if params,lowVec,highVec are empty.
623 //cout << "WARNING: No OverallSyst terms" << std::endl;
624 emplace<RooConstVar>(proto, interpName, 1.); // params have already been imported in first loop of this function
625 }
626 }
627
628
631 assert(sampleScaleFactors.size() == sampleHistFuncs.size());
632
633 // for ith bin calculate totN_i = lumi * sum_j expected_j * syst_j
634
635 if (fObsNameVec.empty() && !fObsName.empty())
636 throw std::logic_error("HistFactory didn't process the observables correctly. Please file a bug report.");
637
638 auto firstHistFunc = dynamic_cast<const RooHistFunc*>(sampleHistFuncs.front().front());
639 if (!firstHistFunc) {
640 auto piecewiseInt = dynamic_cast<const PiecewiseInterpolation*>(sampleHistFuncs.front().front());
641 firstHistFunc = dynamic_cast<const RooHistFunc*>(piecewiseInt->nominalHist());
642 }
644
645 // Prepare a function to divide all bin contents by bin width to get a density:
646 auto &binWidth = emplace<RooBinWidthFunction>(proto, totName + "_binWidth", *firstHistFunc, true);
647
648 // Loop through samples and create products of their functions:
649 RooArgSet coefList;
651 for (unsigned int i=0; i < sampleHistFuncs.size(); ++i) {
652 assert(!sampleHistFuncs[i].empty());
653 coefList.add(*sampleScaleFactors[i]);
654
655 std::vector<RooAbsArg*>& thisSampleHistFuncs = sampleHistFuncs[i];
656 thisSampleHistFuncs.push_back(&binWidth);
657
658 if (thisSampleHistFuncs.size() == 1) {
659 // Just one function. Book it.
660 shapeList.add(*thisSampleHistFuncs.front());
661 } else {
662 // Have multiple functions. We need to multiply them.
663 std::string name = thisSampleHistFuncs.front()->GetName();
664 auto pos = name.find("Hist_alpha");
665 if (pos != std::string::npos) {
666 name = name.substr(0, pos) + "shapes";
667 } else if ( (pos = name.find("nominal")) != std::string::npos) {
668 name = name.substr(0, pos) + "shapes";
669 }
670
673 shapeList.add(*proto.function(name));
674 }
675 }
676
677 // Sum all samples
678 RooRealSumPdf tot(totName.c_str(), totName.c_str(), shapeList, coefList, true);
679 tot.specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator") ;
680 tot.specialIntegratorConfig(true)->method2D().setLabel("RooBinIntegrator") ;
681 tot.specialIntegratorConfig(true)->methodND().setLabel("RooBinIntegrator") ;
682 tot.forceNumInt();
683
684 // for mixed generation in RooSimultaneous
685 tot.setAttribute("GenerateBinned"); // for use with RooSimultaneous::generate in mixed mode
686
687 // Enable the binned likelihood optimization
688 if(fCfg.binnedFitOptimization) {
689 tot.setAttribute("BinnedLikelihood");
690 }
691
693 }
694
695 //////////////////////////////////////////////////////////////////////////////
696
698
699 std::ofstream covFile(filename);
700
701 covFile << " ";
702 for (auto const *myargi : static_range_cast<RooRealVar *>(*params)) {
703 if (myargi->isConstant())
704 continue;
705 covFile << " & " << myargi->GetName();
706 }
707 covFile << "\\\\ \\hline \n";
708 for (auto const *myargi : static_range_cast<RooRealVar *>(*params)) {
709 if(myargi->isConstant()) continue;
710 covFile << myargi->GetName();
711 for (auto const *myargj : static_range_cast<RooRealVar *>(*params)) {
712 if(myargj->isConstant()) continue;
713 std::cout << myargi->GetName() << "," << myargj->GetName();
714 double corr = result->correlation(*myargi, *myargj);
715 covFile << " & " << std::fixed << std::setprecision(2) << corr;
716 }
717 std::cout << std::endl;
718 covFile << " \\\\\n";
719 }
720
721 covFile.close();
722 }
723
724
725 ///////////////////////////////////////////////
727
728 // check inputs (see JIRA-6890 )
729
730 if (channel.GetSamples().empty()) {
731 Error("MakeSingleChannelWorkspace",
732 "The input Channel does not contain any sample - return a nullptr");
733 return nullptr;
734 }
735
736 const TH1* channel_hist_template = channel.GetSamples().front().GetHisto();
737 if (channel_hist_template == nullptr) {
738 channel.CollectHistograms();
739 channel_hist_template = channel.GetSamples().front().GetHisto();
740 }
741 if (channel_hist_template == nullptr) {
742 std::ostringstream stream;
743 stream << "The sample " << channel.GetSamples().front().GetName()
744 << " in channel " << channel.GetName() << " does not contain a histogram. This is the channel:\n";
745 channel.Print(stream);
746 Error("MakeSingleChannelWorkspace", "%s", stream.str().c_str());
747 return nullptr;
748 }
749
750 if( ! channel.CheckHistograms() ) {
751 std::cout << "MakeSingleChannelWorkspace: Channel: " << channel.GetName()
752 << " has uninitialized histogram pointers" << std::endl;
753 throw hf_exc();
754 }
755
756
757
758 // Set these by hand inside the function
759 vector<string> systToFix = measurement.GetConstantParams();
760 bool doRatio=false;
761
762 // to time the macro
763 TStopwatch t;
764 t.Start();
765 //ES// string channel_name=summary[0].channel;
766 string channel_name = channel.GetName();
767
768 /// MB: reset observable names for each new channel.
769 fObsNameVec.clear();
770
771 /// MB: label observables x,y,z, depending on histogram dimensionality
772 /// GHL: Give it the first sample's nominal histogram as a template
773 /// since the data histogram may not be present
775
776 for ( unsigned int idx=0; idx<fObsNameVec.size(); ++idx ) {
777 fObsNameVec[idx] = "obs_" + fObsNameVec[idx] + "_" + channel_name ;
778 }
779
780 if (fObsNameVec.empty()) {
781 fObsName= "obs_" + channel_name; // set name ov observable
782 fObsNameVec.push_back( fObsName );
783 }
784
785 if (fObsNameVec.empty() || fObsNameVec.size() > 3) {
786 throw hf_exc("HistFactory is limited to 1- to 3-dimensional histograms.");
787 }
788
789 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
790 << "\tStarting to process '"
791 << channel_name << "' channel with " << fObsNameVec.size() << " observables"
792 << "\n-----------------------------------------\n" << std::endl;
793
794 //
795 // our main workspace that we are using to construct the model
796 //
797 auto protoOwner = std::make_unique<RooWorkspace>(channel_name.c_str(), (channel_name+" workspace").c_str());
799 auto proto_config = make_unique<ModelConfig>("ModelConfig", &proto);
800 proto_config->SetWorkspace(proto);
801
802 // preprocess functions
803 for(auto const& func : fPreprocessFunctions){
804 cxcoutI(HistFactory) << "will preprocess this line: " << func << std::endl;
805 proto.factory(func);
806 proto.Print();
807 }
808
809 RooArgSet likelihoodTerms("likelihoodTerms");
810 RooArgSet constraintTerms("constraintTerms");
814 // All histogram functions to be multiplied in each sample
815 std::vector<std::vector<RooAbsArg*>> allSampleHistFuncs;
816 std::vector<RooProduct*> sampleScaleFactors;
817
818 std::vector< pair<string,string> > statNamePairs;
819 std::vector< pair<const TH1*, std::unique_ptr<TH1>> > statHistPairs; // <nominal, error>
820 const std::string statFuncName = "mc_stat_" + channel_name;
821
822 string prefix;
823 string range;
824
825 /////////////////////////////
826 // shared parameters
827 // this is ratio of lumi to nominal lumi. We will include relative uncertainty in model
828 auto &lumiVar = getOrCreate<RooRealVar>(proto, "Lumi", fNomLumi, 0.0, 10 * fNomLumi);
829
830 // only include a lumiConstraint if there's a lumi uncert, otherwise just set the lumi constant
831 if(fLumiError != 0) {
832 auto &nominalLumiVar = emplace<RooRealVar>(proto, "nominalLumi", fNomLumi, 0., fNomLumi + 10. * fLumiError);
834 proto.var("Lumi")->setError(fLumiError/fNomLumi); // give initial error value
835 proto.var("nominalLumi")->setConstant();
836 proto.defineSet("globalObservables","nominalLumi");
837 //likelihoodTermNames.push_back("lumiConstraint");
838 constraintTermNames.push_back("lumiConstraint");
839 } else {
840 proto.var("Lumi")->setConstant();
841 proto.defineSet("globalObservables",RooArgSet()); // create empty set as is assumed it exists later
842 }
843 ///////////////////////////////////
844 // loop through estimates, add expectation, floating bin predictions,
845 // and terms that constrain floating to expectation via uncertainties
846 // GHL: Loop over samples instead, which doesn't contain the data
847 for (Sample& sample : channel.GetSamples()) {
848 string overallSystName = sample.GetName() + "_" + channel_name + "_epsilon";
849
850 string systSourcePrefix = "alpha_";
851
852 // constraintTermNames and totSystTermNames are vectors that are passed
853 // by reference and filled by this method
855 sample.GetOverallSysList(), constraintTermNames , totSystTermNames);
856
857 allSampleHistFuncs.emplace_back();
858 std::vector<RooAbsArg*>& sampleHistFuncs = allSampleHistFuncs.back();
859
860 // GHL: Consider passing the NormFactor list instead of the entire sample
863
864 // Create the string for the object
865 // that is added to the RooRealSumPdf
866 // for this channel
867// string syst_x_expectedPrefix = "";
868
869 // get histogram
870 //ES// TH1* nominal = it->nominal;
871 const TH1* nominal = sample.GetHisto();
872
873 // MB : HACK no option to have both non-hist variations and hist variations ?
874 // get histogram
875 // GHL: Okay, this is going to be non-trivial.
876 // We will loop over histosys's, which contain both
877 // the low hist and the high hist together.
878
879 // Logic:
880 // - If we have no HistoSys's, do part A
881 // - else, if the histo syst's don't match, return (we ignore this case)
882 // - finally, we take the syst's and apply the linear interpolation w/ constraint
883 string expPrefix = sample.GetName() + "_" + channel_name;
884 // create roorealvar observables
885 RooArgList observables = createObservables(sample.GetHisto(), proto);
888
889 if(sample.GetHistoSysList().empty()) {
890 // If no HistoSys
891 cxcoutI(HistFactory) << sample.GetName() + "_" + channel_name + " has no variation histograms " << std::endl;
892
894 } else {
895 // If there ARE HistoSys(s)
896 // name of source for variation
897 string constraintPrefix = sample.GetName() + "_" + channel_name + "_Hist_alpha";
898
899 // make list of abstract parameters that interpolate in space of variations
901
902 // next, create the constraint terms
903 for(std::size_t i = 0; i < interpParams.size(); ++i) {
904 bool isUniform = measurement.GetUniformSyst().count(sample.GetHistoSysList()[i].GetName()) > 0;
906 }
907
908 // finally, create the interpolated function
910 sample.GetHistoSysList(), constraintPrefix, observables) );
911 }
912
913 sampleHistFuncs.front()->SetTitle( (nominal && strlen(nominal->GetTitle())>0) ? nominal->GetTitle() : sample.GetName().c_str() );
914
915 ////////////////////////////////////
916 // Add StatErrors to this Channel //
917 ////////////////////////////////////
918
919 if( sample.GetStatError().GetActivate() ) {
920
921 if( fObsNameVec.size() > 3 ) {
922 cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions."
923 << std::endl;
924 throw hf_exc();
925 } else {
926
927 // If we are using StatUncertainties, we multiply this object
928 // by the ParamHistFunc and then pass that to the
929 // RooRealSumPdf by appending it's name to the list
930
931 cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " to be included in Stat Error "
932 << "for channel " << channel_name
933 << std::endl;
934
935 string UncertName = sample.GetName() + "_" + channel_name + "_StatAbsolUncert";
936 std::unique_ptr<TH1> statErrorHist;
937
938 if( sample.GetStatError().GetErrorHist() == nullptr ) {
939 // Make the absolute stat error
940 cxcoutI(HistFactory) << "Making Statistical Uncertainty Hist for "
941 << " Channel: " << channel_name
942 << " Sample: " << sample.GetName()
943 << std::endl;
945 } else {
946 // clone the error histograms because in case the sample has not error hist
947 // it is created in MakeAbsolUncertainty
948 // we need later to clean statErrorHist
949 statErrorHist.reset(static_cast<TH1*>(sample.GetStatError().GetErrorHist()->Clone()));
950 // We assume the (relative) error is provided.
951 // We must turn it into an absolute error
952 // using the nominal histogram
953 cxcoutI(HistFactory) << "Using external histogram for Stat Errors for "
954 << "\tChannel: " << channel_name
955 << "\tSample: " << sample.GetName()
956 << "\tError Histogram: " << statErrorHist->GetName() << std::endl;
957 // Multiply the relative stat uncertainty by the
958 // nominal to get the overall stat uncertainty
959 statErrorHist->Multiply( nominal );
960 statErrorHist->SetName( UncertName.c_str() );
961 }
962
963 // Save the nominal and error hists
964 // for the building of constraint terms
965 statHistPairs.emplace_back(nominal, std::move(statErrorHist));
966
967 // To do the 'conservative' version, we would need to do some
968 // intervention here. We would probably need to create a different
969 // ParamHistFunc for each sample in the channel. The would nominally
970 // use the same gamma's, so we haven't increased the number of parameters
971 // However, if a bin in the 'nominal' histogram is 0, we simply need to
972 // change the parameter in that bin in the ParamHistFunc for this sample.
973 // We also need to add a constraint term.
974 // Actually, we'd probably not use the ParamHistFunc...?
975 // we could remove the dependence in this ParamHistFunc on the ith gamma
976 // and then create the poisson term: Pois(tau | n_exp)Pois(data | n_exp)
977
978
979 // Next, try to get the common ParamHistFunc (it may have been
980 // created by another sample in this channel)
981 // or create it if it doesn't yet exist:
982 RooAbsReal* paramHist = dynamic_cast<ParamHistFunc*>(proto.function(statFuncName) );
983 if( paramHist == nullptr ) {
984
985 // Get a RooArgSet of the observables:
986 // Names in the list fObsNameVec:
988 std::vector<std::string>::iterator itr = fObsNameVec.begin();
989 for (int idx=0; itr!=fObsNameVec.end(); ++itr, ++idx ) {
990 theObservables.add( *proto.var(*itr) );
991 }
992
993 // Create the list of terms to
994 // control the bin heights:
995 std::string ParamSetPrefix = "gamma_stat_" + channel_name;
1000
1003
1005
1006 paramHist = proto.function( statFuncName);
1007 }
1008
1009 // apply stat function to sample
1010 sampleHistFuncs.push_back(paramHist);
1011 }
1012 } // END: if DoMcStat
1013
1014
1015 ///////////////////////////////////////////
1016 // Create a ShapeFactor for this channel //
1017 ///////////////////////////////////////////
1018
1019 if( !sample.GetShapeFactorList().empty() ) {
1020
1021 if( fObsNameVec.size() > 3 ) {
1022 cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions."
1023 << std::endl;
1024 throw hf_exc();
1025 } else {
1026
1027 cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " in channel: " << channel_name
1028 << " to be include a ShapeFactor."
1029 << std::endl;
1030
1031 for(ShapeFactor& shapeFactor : sample.GetShapeFactorList()) {
1032
1033 std::string funcName = channel_name + "_" + shapeFactor.GetName() + "_shapeFactor";
1034 RooAbsArg *paramHist = proto.function(funcName);
1035 if( paramHist == nullptr ) {
1036
1038 for(std::string const& varName : fObsNameVec) {
1039 theObservables.add( *proto.var(varName) );
1040 }
1041
1042 // Create the Parameters
1043 std::string funcParams = "gamma_" + shapeFactor.GetName();
1044
1045 // GHL: Again, we are putting hard ranges on the gamma's
1046 // We should change this to range from 0 to /inf
1048 funcParams,
1050
1051 // Create the Function
1054
1055 // Set an initial shape, if requested
1056 if( shapeFactor.GetInitialShape() != nullptr ) {
1057 TH1* initialShape = static_cast<TH1*>(shapeFactor.GetInitialShape()->Clone());
1058 cxcoutI(HistFactory) << "Setting Shape Factor: " << shapeFactor.GetName()
1059 << " to have initial shape from hist: "
1060 << initialShape->GetName()
1061 << std::endl;
1062 shapeFactorFunc.setShape( initialShape );
1063 }
1064
1065 // Set the variables constant, if requested
1066 if( shapeFactor.IsConstant() ) {
1067 cxcoutI(HistFactory) << "Setting Shape Factor: " << shapeFactor.GetName()
1068 << " to be constant" << std::endl;
1069 shapeFactorFunc.setConstant(true);
1070 }
1071
1073 paramHist = proto.function(funcName);
1074
1075 } // End: Create ShapeFactor ParamHistFunc
1076
1077 sampleHistFuncs.push_back(paramHist);
1078 } // End loop over ShapeFactor Systematics
1079 }
1080 } // End: if ShapeFactorName!=""
1081
1082
1083 ////////////////////////////////////////
1084 // Create a ShapeSys for this channel //
1085 ////////////////////////////////////////
1086
1087 if( !sample.GetShapeSysList().empty() ) {
1088
1089 if( fObsNameVec.size() > 3 ) {
1090 cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions."
1091 << std::endl;
1092 throw hf_exc();
1093 }
1094
1095 // List of ShapeSys ParamHistFuncs
1096 std::vector<string> ShapeSysNames;
1097
1098 for(RooStats::HistFactory::ShapeSys& shapeSys : sample.GetShapeSysList()) {
1099
1100 // Create the ParamHistFunc's
1101 // Create their constraint terms and add them
1102 // to the list of constraint terms
1103
1104 // Create a single RooProduct over all of these
1105 // paramHistFunc's
1106
1107 // Send the name of that product to the RooRealSumPdf
1108
1109 cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " in channel: " << channel_name
1110 << " to include a ShapeSys." << std::endl;
1111
1112 std::string funcName = channel_name + "_" + shapeSys.GetName() + "_ShapeSys";
1113 ShapeSysNames.push_back( funcName );
1114 auto paramHist = static_cast<ParamHistFunc*>(proto.function(funcName));
1115 if( paramHist == nullptr ) {
1116
1117 //std::string funcParams = "gamma_" + it->shapeFactorName;
1118 //paramHist = CreateParamHistFunc( proto, fObsNameVec, funcParams, funcName );
1119
1121 for(std::string const& varName : fObsNameVec) {
1122 theObservables.add( *proto.var(varName) );
1123 }
1124
1125 // Create the Parameters
1126 std::string funcParams = "gamma_" + shapeSys.GetName();
1128 funcParams,
1130
1131 // Create the Function
1134
1136 paramHist = static_cast<ParamHistFunc*>(proto.function(funcName));
1137
1138 } // End: Create ShapeFactor ParamHistFunc
1139
1140 // Create the constraint terms and add
1141 // them to the workspace (proto)
1142 // as well as the list of constraint terms (constraintTermNames)
1143
1144 // The syst should be a fractional error
1145 const TH1* shapeErrorHist = shapeSys.GetErrorHist();
1146
1147 // Constraint::Type shapeConstraintType = Constraint::Gaussian;
1148 Constraint::Type systype = shapeSys.GetConstraintType();
1151 }
1152 if( systype == Constraint::Poisson ) {
1154 }
1155
1157 paramHist->paramList(), histToVector(*shapeErrorHist),
1159 systype);
1160 for (auto const& term : shapeConstraintsInfo.constraints) {
1162 constraintTermNames.emplace_back(term->GetName());
1163 }
1164 // Add the "observed" value to the list of global observables:
1165 RooArgSet *globalSet = const_cast<RooArgSet *>(proto.set("globalObservables"));
1166 for (RooAbsArg * glob : shapeConstraintsInfo.globalObservables) {
1167 globalSet->add(*proto.var(glob->GetName()));
1168 }
1169
1170
1171 } // End: Loop over ShapeSys vector in this EstimateSummary
1172
1173 // Now that we have the list of ShapeSys ParamHistFunc names,
1174 // we create the total RooProduct
1175 // we multiply the expected function
1176
1177 for(std::string const& name : ShapeSysNames) {
1178 sampleHistFuncs.push_back(proto.function(name));
1179 }
1180
1181 } // End: !GetShapeSysList.empty()
1182
1183
1184 // GHL: This was pretty confusing before,
1185 // hopefully using the measurement directly
1186 // will improve it
1187 RooAbsArg *lumi = proto.arg("Lumi");
1188 if( !sample.GetNormalizeByTheory() ) {
1189 if (!lumi) {
1190 lumi = &emplace<RooRealVar>(proto, "Lumi", measurement.GetLumi());
1191 } else {
1192 static_cast<RooAbsRealLValue*>(lumi)->setVal(measurement.GetLumi());
1193 }
1194 }
1195 assert(lumi);
1196 normFactors->addTerm(lumi);
1197
1198 // Append the name of the "node"
1199 // that is to be summed with the
1200 // RooRealSumPdf
1202 auto normFactorsInWS = dynamic_cast<RooProduct*>(proto.arg(normFactors->GetName()));
1204
1206 } // END: Loop over EstimateSummaries
1207
1208 // If a non-zero number of samples call for
1209 // Stat Uncertainties, create the statFactor functions
1210 if(!statHistPairs.empty()) {
1211
1212 // Create the histogram of (binwise)
1213 // stat uncertainties:
1215 if( fracStatError == nullptr ) {
1216 cxcoutE(HistFactory) << "Error: Failed to make ScaledUncertaintyHist for: "
1217 << channel_name + "_StatUncert" + "_RelErr" << std::endl;
1218 throw hf_exc();
1219 }
1220
1221 // Using this TH1* of fractinal stat errors,
1222 // create a set of constraint terms:
1223 auto chanStatUncertFunc = static_cast<ParamHistFunc*>(proto.function( statFuncName ));
1224 cxcoutI(HistFactory) << "About to create Constraint Terms from: "
1225 << chanStatUncertFunc->GetName()
1226 << " params: " << chanStatUncertFunc->paramList()
1227 << std::endl;
1228
1229 // Get the constraint type and the
1230 // rel error threshold from the (last)
1231 // EstimateSummary looped over (but all
1232 // should be the same)
1233
1234 // Get the type of StatError constraint from the channel
1237 cxcoutI(HistFactory) << "Using Gaussian StatErrors in channel: " << channel.GetName() << std::endl;
1238 }
1240 cxcoutI(HistFactory) << "Using Poisson StatErrors in channel: " << channel.GetName() << std::endl;
1241 }
1242
1248 for (auto const& term : statConstraintsInfo.constraints) {
1250 constraintTermNames.emplace_back(term->GetName());
1251 }
1252 // Add the "observed" value to the list of global observables:
1253 RooArgSet *globalSet = const_cast<RooArgSet *>(proto.set("globalObservables"));
1254 for (RooAbsArg * glob : statConstraintsInfo.globalObservables) {
1255 globalSet->add(*proto.var(glob->GetName()));
1256 }
1257
1258 } // END: Loop over stat Hist Pairs
1259
1260
1261 ///////////////////////////////////
1262 // for ith bin calculate totN_i = lumi * sum_j expected_j * syst_j
1265 likelihoodTermNames.push_back(channel_name+"_model");
1266
1267 //////////////////////////////////////
1268 // fix specified parameters
1269 for(unsigned int i=0; i<systToFix.size(); ++i){
1270 RooRealVar* temp = proto.var(systToFix.at(i));
1271 if(!temp) {
1272 cxcoutW(HistFactory) << "could not find variable " << systToFix.at(i)
1273 << " could not set it to constant" << std::endl;
1274 } else {
1275 // set the parameter constant
1276 temp->setConstant();
1277 }
1278 }
1279
1280 //////////////////////////////////////
1281 // final proto model
1282 for(unsigned int i=0; i<constraintTermNames.size(); ++i){
1284 if( proto_arg==nullptr ) {
1285 cxcoutF(HistFactory) << "Error: Cannot find arg set: " << constraintTermNames.at(i)
1286 << " in workspace: " << proto.GetName() << std::endl;
1287 throw hf_exc();
1288 }
1289 constraintTerms.add( *proto_arg );
1290 // constraintTerms.add(* proto_arg(proto.arg(constraintTermNames[i].c_str())) );
1291 }
1292 for(unsigned int i=0; i<likelihoodTermNames.size(); ++i){
1294 if( proto_arg==nullptr ) {
1295 cxcoutF(HistFactory) << "Error: Cannot find arg set: " << likelihoodTermNames.at(i)
1296 << " in workspace: " << proto.GetName() << std::endl;
1297 throw hf_exc();
1298 }
1299 likelihoodTerms.add( *proto_arg );
1300 }
1301 proto.defineSet("constraintTerms",constraintTerms);
1302 proto.defineSet("likelihoodTerms",likelihoodTerms);
1303
1304 // list of observables
1305 RooArgList observables;
1306 std::string observablesStr;
1307
1308 for(std::string const& name : fObsNameVec) {
1309 observables.add( *proto.var(name) );
1310 if (!observablesStr.empty()) { observablesStr += ","; }
1312 }
1313
1314 // We create two sets, one for backwards compatibility
1315 // The other to make a consistent naming convention
1316 // between individual channels and the combined workspace
1317 proto.defineSet("observables", observablesStr.c_str());
1318 proto.defineSet("observablesSet", observablesStr.c_str());
1319
1320 // Create the ParamHistFunc
1321 // after observables have been made
1322 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1323 << "\timport model into workspace"
1324 << "\n-----------------------------------------\n" << std::endl;
1325
1326 auto model = make_unique<RooProdPdf>(
1327 ("model_"+channel_name).c_str(), // MB : have changed this into conditional pdf. Much faster for toys!
1328 "product of Poissons across bins for a single channel",
1330 // can give channel a title by setting title of corresponding data histogram
1331 if (channel.GetData().GetHisto() && strlen(channel.GetData().GetHisto()->GetTitle())>0) {
1332 model->SetTitle(channel.GetData().GetHisto()->GetTitle());
1333 }
1334 proto.import(*model,RooFit::RecycleConflictNodes());
1335
1336 proto_config->SetPdf(*model);
1337 proto_config->SetObservables(observables);
1338 proto_config->SetGlobalObservables(*proto.set("globalObservables"));
1339 // proto.writeToFile(("results/model_"+channel+".root").c_str());
1340 // fill out nuisance parameters in model config
1341 // proto_config->GuessObsAndNuisance(*proto.data("asimovData"));
1342 proto.import(*proto_config,proto_config->GetName());
1343 proto.importClassCode();
1344
1345 ///////////////////////////
1346 // make data sets
1347 // THis works and is natural, but the memory size of the simultaneous dataset grows exponentially with channels
1348 // New Asimov Generation: Use the code in the Asymptotic calculator
1349 // Need to get the ModelConfig...
1350 int asymcalcPrintLevel = 0;
1354 if (fCfg.createPerRegionWorkspaces) {
1355 // Creating the per-channel asimov dataset is only meaningful if we
1356 // actually create the files with the stored per-channel workspaces.
1357 // Otherwise, we just spend time calculating something that gets thrown
1358 // away anyway (for the combined workspace, we'll create a new Asimov).
1360 proto.import(*asimov_dataset, RooFit::Rename("asimovData"));
1361 }
1362
1363 // GHL: Determine to use data if the hist isn't 'nullptr'
1364 if(TH1 const* mnominal = channel.GetData().GetHisto()) {
1365 // This works and is natural, but the memory size of the simultaneous
1366 // dataset grows exponentially with channels.
1367 std::unique_ptr<RooDataSet> dataset;
1368 if(!fCfg.storeDataError){
1369 dataset = std::make_unique<RooDataSet>("obsData","",*proto.set("observables"), RooFit::WeightVar("weightVar"));
1370 } else {
1371 const char* weightErrName="weightErr";
1372 proto.factory(TString::Format("%s[0,-1e10,1e10]",weightErrName));
1373 dataset = std::make_unique<RooDataSet>("obsData","",*proto.set("observables"), RooFit::WeightVar("weightVar"), RooFit::StoreError(*proto.var(weightErrName)));
1374 }
1376 proto.import(*dataset);
1377 } // End: Has non-null 'data' entry
1378
1379
1380 for(auto const& data : channel.GetAdditionalData()) {
1381 if(data.GetName().empty()) {
1382 cxcoutF(HistFactory) << "Error: Additional Data histogram for channel: " << channel.GetName()
1383 << " has no name! The name always needs to be set for additional datasets, "
1384 << "either via the \"Name\" tag in the XML or via RooStats::HistFactory::Data::SetName()." << std::endl;
1385 throw hf_exc();
1386 }
1387 std::string const& dataName = data.GetName();
1388 TH1 const* mnominal = data.GetHisto();
1389 if( !mnominal ) {
1390 cxcoutF(HistFactory) << "Error: Additional Data histogram for channel: " << channel.GetName()
1391 << " with name: " << dataName << " is nullptr" << std::endl;
1392 throw hf_exc();
1393 }
1394
1395 // THis works and is natural, but the memory size of the simultaneous dataset grows exponentially with channels
1396 RooDataSet dataset{dataName, "", *proto.set("observables"), RooFit::WeightVar("weightVar")};
1398 proto.import(dataset);
1399
1400 }
1401
1402 if (RooMsgService::instance().isActive(nullptr, RooFit::HistFactory, RooFit::INFO)) {
1403 proto.Print();
1404 }
1405
1406 return protoOwner;
1407 }
1408
1409
1411 TH1 const& mnominal,
1413 std::vector<std::string> const& obsNameVec) {
1414
1415 // Take a RooDataSet and fill it with the entries
1416 // from a TH1*, using the observable names to
1417 // determine the columns
1418
1419 if (obsNameVec.empty() ) {
1420 Error("ConfigureHistFactoryDataset","Invalid input - return");
1421 return;
1422 }
1423
1424 TAxis const* ax = mnominal.GetXaxis();
1425 TAxis const* ay = mnominal.GetYaxis();
1426 TAxis const* az = mnominal.GetZaxis();
1427
1428 // check whether the dataset needs the errors stored explicitly
1429 const bool storeWeightErr = obsDataUnbinned.weightVar()->getAttribute("StoreError");
1430
1431 for (int i=1; i<=ax->GetNbins(); ++i) { // 1 or more dimension
1432
1433 double xval = ax->GetBinCenter(i);
1434 proto.var( obsNameVec[0] )->setVal( xval );
1435
1436 if(obsNameVec.size()==1) {
1437 double fval = mnominal.GetBinContent(i);
1438 double ferr = storeWeightErr ? mnominal.GetBinError(i) : 0.;
1439 obsDataUnbinned.add( *proto.set("observables"), fval, ferr );
1440 } else { // 2 or more dimensions
1441
1442 for(int j=1; j<=ay->GetNbins(); ++j) {
1443 double yval = ay->GetBinCenter(j);
1444 proto.var( obsNameVec[1] )->setVal( yval );
1445
1446 if(obsNameVec.size()==2) {
1447 double fval = mnominal.GetBinContent(i,j);
1448 double ferr = storeWeightErr ? mnominal.GetBinError(i, j) : 0.;
1449 obsDataUnbinned.add( *proto.set("observables"), fval, ferr );
1450 } else { // 3 dimensions
1451
1452 for(int k=1; k<=az->GetNbins(); ++k) {
1453 double zval = az->GetBinCenter(k);
1454 proto.var( obsNameVec[2] )->setVal( zval );
1455 double fval = mnominal.GetBinContent(i,j,k);
1456 double ferr = storeWeightErr ? mnominal.GetBinError(i, j, k) : 0.;
1457 obsDataUnbinned.add( *proto.set("observables"), fval, ferr );
1458 }
1459 }
1460 }
1461 }
1462 }
1463 }
1464
1466 {
1467 fObsNameVec = std::vector<string>{"x", "y", "z"};
1468 fObsNameVec.resize(hist->GetDimension());
1469 }
1470
1471
1474 std::vector<std::unique_ptr<RooWorkspace>> &chs)
1475 {
1477
1478 // check first the inputs (see JIRA-6890)
1479 if (ch_names.empty() || chs.empty() ) {
1480 Error("MakeCombinedModel","Input vectors are empty - return a nullptr");
1481 return nullptr;
1482 }
1483 if (chs.size() < ch_names.size() ) {
1484 Error("MakeCombinedModel","Input vector of workspace has an invalid size - return a nullptr");
1485 return nullptr;
1486 }
1487
1488 //
1489 /// These things were used for debugging. Maybe useful in the future
1490 //
1491
1494
1496 for(unsigned int i = 0; i< ch_names.size(); ++i){
1497 obsList.add(*static_cast<ModelConfig *>(chs[i]->obj("ModelConfig"))->GetObservables());
1498 }
1499 cxcoutI(HistFactory) <<"full list of observables:\n" << obsList << std::endl;
1500
1502 std::map<std::string, int> channelMap;
1503 for(unsigned int i = 0; i< ch_names.size(); ++i){
1504 string channel_name=ch_names[i];
1505 if (i == 0 && isdigit(channel_name[0])) {
1506 throw std::invalid_argument("The first channel name for HistFactory cannot start with a digit. Got " + channel_name);
1507 }
1508 if (channel_name.find(',') != std::string::npos) {
1509 throw std::invalid_argument("Channel names for HistFactory cannot contain ','. Got " + channel_name);
1510 }
1511
1513 RooWorkspace * ch=chs[i].get();
1514
1515 RooAbsPdf* model = ch->pdf("model_"+channel_name);
1516 if(!model) std::cout <<"failed to find model for channel"<< std::endl;
1517 // std::cout << "int = " << model->createIntegral(*obsN)->getVal() << std::endl;
1518 models.push_back(model);
1519 globalObs.add(*ch->set("globalObservables"), /*silent=*/true); // silent because observables might exist in other channel.
1520
1521 // constrainedParams->add( * ch->set("constrainedParams") );
1522 pdfMap[channel_name]=model;
1523 }
1524
1525 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1526 << "\tEntering combination"
1527 << "\n-----------------------------------------\n" << std::endl;
1528 auto combined = std::make_unique<RooWorkspace>("combined");
1529
1530
1532
1533 auto simPdf= std::make_unique<RooSimultaneous>("simPdf","",pdfMap, channelCat);
1534 auto combined_config = std::make_unique<ModelConfig>("ModelConfig", combined.get());
1535 combined_config->SetWorkspace(*combined);
1536 // combined_config->SetNuisanceParameters(*constrainedParams);
1537
1538 combined->import(globalObs);
1539 combined->defineSet("globalObservables",globalObs);
1540 combined_config->SetGlobalObservables(*combined->set("globalObservables"));
1541
1542 combined->defineSet("observables",{obsList, channelCat}, /*importMissing=*/true);
1543 combined_config->SetObservables(*combined->set("observables"));
1544
1545
1546 // Now merge the observable datasets across the channels
1547 for(RooAbsData * data : chs[0]->allData()) {
1548 // We are excluding the Asimov data, because it needs to be regenerated
1549 // later after the parameter values are set.
1550 if(std::string("asimovData") == data->GetName()) {
1551 continue;
1552 }
1553 // Loop through channels, get their individual datasets,
1554 // and add them to the combined dataset
1555 std::map<std::string, RooAbsData*> dataMap;
1556 for(unsigned int i = 0; i < ch_names.size(); ++i){
1557 dataMap[ch_names[i]] = chs[i]->data(data->GetName());
1558 }
1559 combined->import(RooDataSet{data->GetName(), "", obsList, RooFit::Index(channelCat),
1560 RooFit::WeightVar("weightVar"), RooFit::Import(dataMap)});
1561 }
1562
1563
1565 combined->Print();
1566
1567 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1568 << "\tImporting combined model"
1569 << "\n-----------------------------------------\n" << std::endl;
1571
1572 for(auto const& param_itr : fParamValues) {
1573 // make sure they are fixed
1574 std::string paramName = param_itr.first;
1575 double paramVal = param_itr.second;
1576
1577 if(RooRealVar* temp = combined->var( paramName )) {
1578 temp->setVal( paramVal );
1579 cxcoutI(HistFactory) <<"setting " << paramName << " to the value: " << paramVal << std::endl;
1580 } else
1581 cxcoutE(HistFactory) << "could not find variable " << paramName << " could not set its value" << std::endl;
1582 }
1583
1584
1585 for(unsigned int i=0; i<fSystToFix.size(); ++i){
1586 // make sure they are fixed
1587 if(RooRealVar* temp = combined->var(fSystToFix[i])) {
1588 temp->setConstant();
1589 cxcoutI(HistFactory) <<"setting " << fSystToFix.at(i) << " constant" << std::endl;
1590 } else
1591 cxcoutE(HistFactory) << "could not find variable " << fSystToFix.at(i) << " could not set it to constant" << std::endl;
1592 }
1593
1594 ///
1595 /// writing out the model in graphViz
1596 ///
1597 // RooAbsPdf* customized=combined->pdf("simPdf");
1598 //combined_config->SetPdf(*customized);
1599 combined_config->SetPdf(*simPdf);
1600 // combined_config->GuessObsAndNuisance(*simData);
1601 // customized->graphVizTree(("results/"+fResultsPrefixStr.str()+"_simul.dot").c_str());
1602 combined->import(*combined_config,combined_config->GetName());
1603 combined->importClassCode();
1604 // combined->writeToFile("results/model_combined.root");
1605
1606
1607 ////////////////////////////////////////////
1608 // Make toy simultaneous dataset
1609 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1610 << "\tcreate toy data"
1611 << "\n-----------------------------------------\n" << std::endl;
1612
1613
1614 // now with weighted datasets
1615 // First Asimov
1616
1617 // Create Asimov data for the combined dataset
1619 *combined->pdf("simPdf"),
1620 obsList)};
1621 if( asimov_combined ) {
1622 combined->import( *asimov_combined, RooFit::Rename("asimovData"));
1623 }
1624 else {
1625 std::cout << "Error: Failed to create combined asimov dataset" << std::endl;
1626 throw hf_exc();
1627 }
1628
1629 return RooFit::makeOwningPtr(std::move(combined));
1630 }
1631
1632
1634
1635 // Take a nominal TH1* and create
1636 // a TH1 representing the binwise
1637 // errors (taken from the nominal TH1)
1638
1639 auto ErrorHist = static_cast<TH1*>(Nominal->Clone( Name.c_str() ));
1640 ErrorHist->Reset();
1641
1642 int numBins = Nominal->GetNbinsX()*Nominal->GetNbinsY()*Nominal->GetNbinsZ();
1643 int binNumber = 0;
1644
1645 // Loop over bins
1646 for( int i_bin = 0; i_bin < numBins; ++i_bin) {
1647
1648 binNumber++;
1649 // Ignore underflow / overflow
1650 while( Nominal->IsBinUnderflow(binNumber) || Nominal->IsBinOverflow(binNumber) ){
1651 binNumber++;
1652 }
1653
1654 double histError = Nominal->GetBinError( binNumber );
1655
1656 // Check that histError != NAN
1657 if( histError != histError ) {
1658 std::cout << "Warning: In histogram " << Nominal->GetName()
1659 << " bin error for bin " << i_bin
1660 << " is NAN. Not using Error!!!"
1661 << std::endl;
1662 throw hf_exc();
1663 //histError = sqrt( histContent );
1664 //histError = 0;
1665 }
1666
1667 // Check that histError ! < 0
1668 if( histError < 0 ) {
1669 std::cout << "Warning: In histogram " << Nominal->GetName()
1670 << " bin error for bin " << binNumber
1671 << " is < 0. Setting Error to 0"
1672 << std::endl;
1673 //histError = sqrt( histContent );
1674 histError = 0;
1675 }
1676
1677 ErrorHist->SetBinContent( binNumber, histError );
1678
1679 }
1680
1681 return ErrorHist;
1682
1683 }
1684
1685 // Take a list of < nominal, absolError > TH1* pairs
1686 // and construct a single histogram representing the
1687 // total fractional error as:
1688
1689 // UncertInQuad(bin i) = Sum: absolUncert*absolUncert
1690 // Total(bin i) = Sum: Value
1691 //
1692 // TotalFracError(bin i) = Sqrt( UncertInQuad(i) ) / TotalBin(i)
1693 std::unique_ptr<TH1> HistoToWorkspaceFactoryFast::MakeScaledUncertaintyHist( const std::string& Name, std::vector< std::pair<const TH1*, std::unique_ptr<TH1>> > const& HistVec ) const {
1694
1695
1696 unsigned int numHists = HistVec.size();
1697
1698 if( numHists == 0 ) {
1699 cxcoutE(HistFactory) << "Warning: Empty Hist Vector, cannot create total uncertainty" << std::endl;
1700 return nullptr;
1701 }
1702
1703 const TH1* HistTemplate = HistVec.at(0).first;
1704 int numBins = HistTemplate->GetNbinsX()*HistTemplate->GetNbinsY()*HistTemplate->GetNbinsZ();
1705
1706 // Check that all histograms
1707 // have the same bins
1708 for( unsigned int i = 0; i < HistVec.size(); ++i ) {
1709
1710 const TH1* nominal = HistVec.at(i).first;
1711 const TH1* error = HistVec.at(i).second.get();
1712
1713 if( nominal->GetNbinsX()*nominal->GetNbinsY()*nominal->GetNbinsZ() != numBins ) {
1714 cxcoutE(HistFactory) << "Error: Provided hists have unequal bins" << std::endl;
1715 return nullptr;
1716 }
1717 if( error->GetNbinsX()*error->GetNbinsY()*error->GetNbinsZ() != numBins ) {
1718 cxcoutE(HistFactory) << "Error: Provided hists have unequal bins" << std::endl;
1719 return nullptr;
1720 }
1721 }
1722
1723 std::vector<double> TotalBinContent( numBins, 0.0);
1724 std::vector<double> HistErrorsSqr( numBins, 0.0);
1725
1726 int binNumber = 0;
1727
1728 // Loop over bins
1729 for( int i_bins = 0; i_bins < numBins; ++i_bins) {
1730
1731 binNumber++;
1732 while( HistTemplate->IsBinUnderflow(binNumber) || HistTemplate->IsBinOverflow(binNumber) ){
1733 binNumber++;
1734 }
1735
1736 for( unsigned int i_hist = 0; i_hist < numHists; ++i_hist ) {
1737
1738 const TH1* nominal = HistVec.at(i_hist).first;
1739 const TH1* error = HistVec.at(i_hist).second.get();
1740
1741 //int binNumber = i_bins + 1;
1742
1743 double histValue = nominal->GetBinContent( binNumber );
1744 double histError = error->GetBinContent( binNumber );
1745
1746 if( histError != histError ) {
1747 cxcoutE(HistFactory) << "In histogram " << error->GetName()
1748 << " bin error for bin " << binNumber
1749 << " is NAN. Not using error!!";
1750 throw hf_exc();
1751 }
1752
1754 HistErrorsSqr.at(i_bins) += histError*histError; // Add in quadrature
1755
1756 }
1757 }
1758
1759 binNumber = 0;
1760
1761 // Creat the output histogram
1762 TH1* ErrorHist = static_cast<TH1*>(HistTemplate->Clone( Name.c_str() ));
1763 ErrorHist->Reset();
1764
1765 // Fill the output histogram
1766 for( int i = 0; i < numBins; ++i) {
1767
1768 // int binNumber = i + 1;
1769 binNumber++;
1770 while( ErrorHist->IsBinUnderflow(binNumber) || ErrorHist->IsBinOverflow(binNumber) ){
1771 binNumber++;
1772 }
1773
1774 double ErrorsSqr = HistErrorsSqr.at(i);
1775 double TotalVal = TotalBinContent.at(i);
1776
1777 if( TotalVal <= 0 ) {
1778 cxcoutW(HistFactory) << "Warning: Sum of histograms for bin: " << binNumber
1779 << " is <= 0. Setting error to 0"
1780 << std::endl;
1781
1782 ErrorHist->SetBinContent( binNumber, 0.0 );
1783 continue;
1784 }
1785
1786 double RelativeError = sqrt(ErrorsSqr) / TotalVal;
1787
1788 // If we otherwise get a NAN
1789 // it's an error
1790 if( RelativeError != RelativeError ) {
1791 cxcoutE(HistFactory) << "Error: bin " << i << " error is NAN\n"
1792 << " HistErrorsSqr: " << ErrorsSqr
1793 << " TotalVal: " << TotalVal;
1794 throw hf_exc();
1795 }
1796
1797 // 0th entry in vector is
1798 // the 1st bin in TH1
1799 // (we ignore underflow)
1800
1801 // Error and bin content are interchanged because for some reason, the other functions
1802 // use the bin content to convey the error ...
1803 ErrorHist->SetBinError(binNumber, TotalVal);
1804 ErrorHist->SetBinContent(binNumber, RelativeError);
1805
1806 cxcoutI(HistFactory) << "Making Total Uncertainty for bin " << binNumber
1807 << " Error = " << sqrt(ErrorsSqr)
1808 << " CentralVal = " << TotalVal
1809 << " RelativeError = " << RelativeError << "\n";
1810
1811 }
1812
1813 return std::unique_ptr<TH1>(ErrorHist);
1814}
1815
1816
1817} // namespace RooStats
1818} // namespace HistFactory
1819
#define cxcoutPHF
#define cxcoutFHF
#define cxcoutIHF
#define cxcoutWHF
std::vector< double > histToVector(TH1 const &hist)
constexpr double alphaHigh
constexpr double alphaLow
#define cxcoutI(a)
#define cxcoutW(a)
#define cxcoutF(a)
#define cxcoutE(a)
#define cxcoutP(a)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
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
char name[80]
Definition TGX11.cxx:110
const char * proto
Definition civetweb.c:18822
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
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.
The PiecewiseInterpolation is a class that can morph distributions into each other,...
const_iterator begin() const
const_iterator end() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:76
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
void setConstant(bool value=true)
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
Calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition RooAddition.h:27
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
Object to represent discrete states.
Definition RooCategory.h:28
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
Container class to hold unbinned data.
Definition RooDataSet.h:32
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
Implementation of the Gamma PDF for RooFit/RooStats.
Definition RooGamma.h:20
Switches the message service to a different level while the instance is alive.
Definition RooHelpers.h:37
A real-valued function sampled from a multidimensional histogram.
Definition RooHistFunc.h:31
static RooMsgService & instance()
Return reference to singleton instance.
A RooAbsReal implementing a polynomial in terms of a list of RooAbsReal coefficients.
Definition RooPolyVar.h:25
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
Implements a PDF constructed from a sum of functions:
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setBinning(const RooAbsBinning &binning, const char *name=nullptr)
Add given binning under name 'name' with this variable.
void setBins(Int_t nBins, const char *name=nullptr)
Create a uniform binning under name 'name' for this variable.
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.
Definition Asimov.h:22
void ConfigureWorkspace(RooWorkspace *)
Definition Asimov.cxx:22
This class encapsulates all information for the statistical interpretation of one experiment.
Definition Channel.h:30
std::vector< RooStats::HistFactory::Data > & GetAdditionalData()
retrieve vector of additional data objects
Definition Channel.h:64
void Print(std::ostream &=std::cout)
Definition Channel.cxx:59
HistFactory::StatErrorConfig & GetStatErrorConfig()
get information about threshold for statistical uncertainties and constraint term
Definition Channel.h:71
RooStats::HistFactory::Data & GetData()
get data object
Definition Channel.h:58
std::vector< RooStats::HistFactory::Sample > & GetSamples()
get vector of samples for this channel
Definition Channel.h:76
std::string GetName() const
get name of channel
Definition Channel.h:42
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)
std::unique_ptr< RooWorkspace > MakeSingleChannelWorkspace(Measurement &measurement, Channel &channel)
void MakeTotalExpected(RooWorkspace &proto, const std::string &totName, const std::vector< RooProduct * > &sampleScaleFactors, std::vector< std::vector< RooAbsArg * > > &sampleHistFuncs) const
std::unique_ptr< TH1 > MakeScaledUncertaintyHist(const std::string &Name, std::vector< std::pair< const TH1 *, std::unique_ptr< TH1 > > > const &HistVec) const
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.
void SetFunctionsToPreprocess(std::vector< std::string > lines)
RooFit::OwningPtr< RooWorkspace > MakeSingleChannelModel(Measurement &measurement, Channel &channel)
RooFit::OwningPtr< RooWorkspace > MakeCombinedModel(std::vector< std::string >, std::vector< std::unique_ptr< RooWorkspace > > &)
TH1 * MakeAbsolUncertaintyHist(const std::string &Name, const TH1 *Hist)
static void ConfigureWorkspaceForMeasurement(const std::string &ModelName, RooWorkspace *ws_single, Measurement &measurement)
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)
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)
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...
The RooStats::HistFactory::Measurement class can be used to construct a model by combining multiple R...
Definition Measurement.h:31
Configuration for an un- constrained overall systematic to scale sample normalisations.
Definition Systematics.h:63
Configuration for a constrained overall systematic to scale sample normalisations.
Definition Systematics.h:35
*Un*constrained bin-by-bin variation of affected histogram.
Constrained bin-by-bin variation of affected histogram.
Constraint::Type GetConstraintType() const
< A class that holds configuration information for a model using a workspace as a store
Definition ModelConfig.h:34
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.
const RooArgSet * set(RooStringView name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is 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.
Class to manage histogram axis.
Definition TAxis.h:32
Bool_t IsVariableBinSize() const
Definition TAxis.h:144
const char * GetTitle() const override
Returns title of object.
Definition TAxis.h:137
const TArrayD * GetXbins() const
Definition TAxis.h:138
Double_t GetXmax() const
Definition TAxis.h:142
Double_t GetXmin() const
Definition TAxis.h:141
Int_t GetNbins() const
Definition TAxis.h:127
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
TAxis * GetZaxis()
Definition TH1.h:574
virtual Int_t GetNbinsY() const
Definition TH1.h:543
virtual Int_t GetNbinsZ() const
Definition TH1.h:544
virtual Int_t GetDimension() const
Definition TH1.h:528
TAxis * GetXaxis()
Definition TH1.h:572
virtual Int_t GetNbinsX() const
Definition TH1.h:542
TAxis * GetYaxis()
Definition TH1.h:573
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition TH1.cxx:5217
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition TH1.cxx:5185
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition TH1.cxx:5064
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:174
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:227
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1072
Stopwatch class.
Definition TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2385
RooCmdArg RecycleConflictNodes(bool flag=true)
RooCmdArg Rename(const char *suffix)
RooCmdArg Conditional(const RooArgSet &pdfSet, const RooArgSet &depSet, bool depsAreCond=false)
RooConstVar & RooConst(double val)
RooCmdArg Index(RooCategory &icat)
RooCmdArg StoreError(const RooArgSet &aset)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Import(const char *state, TH1 &histo)
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Definition Config.h:35
@ ObjectHandling
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
Definition Config.h:40
CreateGammaConstraintsOutput createGammaConstraints(RooArgList const &paramList, std::span< const double > relSigmas, double minSigma, Constraint::Type type)
Namespace for the RooStats classes.
Definition CodegenImpl.h:61