Logo ROOT  
Reference Guide
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#ifndef __CINT__
23#include "RooGlobalFunc.h"
24#endif
25
26#include "RooDataSet.h"
27#include "RooRealVar.h"
28#include "RooConstVar.h"
29#include "RooAddition.h"
30#include "RooProduct.h"
31#include "RooProdPdf.h"
32#include "RooAddPdf.h"
33#include "RooGaussian.h"
34#include "RooPoisson.h"
35#include "RooExponential.h"
36#include "RooRandom.h"
37#include "RooCategory.h"
38#include "RooSimultaneous.h"
39#include "RooMultiVarGaussian.h"
40#include "RooNumIntConfig.h"
41#include "RooProfileLL.h"
42#include "RooFitResult.h"
43#include "RooDataHist.h"
44#include "RooHistFunc.h"
45#include "RooHistPdf.h"
46#include "RooRealSumPdf.h"
47#include "RooWorkspace.h"
48#include "RooCustomizer.h"
49#include "RooPlot.h"
50#include "RooHelpers.h"
51#include "RooBinning.h"
52#include "RooBinWidthFunction.h"
58#include "HFMsgService.h"
59
60#include "TH1.h"
61#include "TStopwatch.h"
62#include "TVectorD.h"
63#include "TMatrixDSym.h"
64
65// specific to this package
71
72#include <algorithm>
73#include <memory>
74#include <utility>
75
76#define VERBOSE
77
78#define alpha_Low "-5"
79#define alpha_High "5"
80#define NoHistConst_Low "0"
81#define NoHistConst_High "2000"
82
83// use this order for safety on library loading
84using namespace RooFit ;
85using namespace RooStats ;
86using namespace std ;
87
89
90namespace RooStats{
91namespace HistFactory{
92
95
97 Configuration const& cfg) :
98 fSystToFix( measurement.GetConstantParams() ),
99 fParamValues( measurement.GetParamValues() ),
100 fNomLumi( measurement.GetLumi() ),
101 fLumiError( measurement.GetLumi()*measurement.GetLumiRelErr() ),
102 fLowBin( measurement.GetBinLow() ),
103 fHighBin( measurement.GetBinHigh() ),
104 fCfg{cfg} {
105
106 // Set Preprocess functions
108
109 }
110
111 void HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( const std::string& ModelName, RooWorkspace* ws_single, Measurement& measurement ) {
112
113 // Configure a workspace by doing any
114 // necessary post-processing and by
115 // creating a ModelConfig
116
117 // Make a ModelConfig and configure it
118 ModelConfig * proto_config = (ModelConfig *) ws_single->obj("ModelConfig");
119 if( proto_config == nullptr ) {
120 std::cout << "Error: Did not find 'ModelConfig' object in file: " << ws_single->GetName()
121 << std::endl;
122 throw hf_exc();
123 }
124
125 std::vector<std::string> poi_list = measurement.GetPOIList();
126 if( poi_list.empty() ) {
127 cxcoutWHF << "No Parametetrs of interest are set" << std::endl;
128 }
129
130
131 std::stringstream sstream;
132 sstream << "Setting Parameter(s) of Interest as: ";
133 for(unsigned int i = 0; i < poi_list.size(); ++i) {
134 sstream << poi_list.at(i) << " ";
135 }
136 cxcoutIHF << sstream.str() << endl;
137
138 RooArgSet params;
139 for( unsigned int i = 0; i < poi_list.size(); ++i ) {
140 std::string poi_name = poi_list.at(i);
141 RooRealVar* poi = (RooRealVar*) ws_single->var(poi_name);
142 if(poi){
143 params.add(*poi);
144 }
145 else {
146 std::cout << "WARNING: Can't find parameter of interest: " << poi_name
147 << " in Workspace. Not setting in ModelConfig." << std::endl;
148 //throw hf_exc();
149 }
150 }
151 proto_config->SetParametersOfInterest(params);
152
153 // Name of an 'edited' model, if necessary
154 std::string NewModelName = "newSimPdf"; // <- This name is hard-coded in HistoToWorkspaceFactoryFast::EditSyt. Probably should be changed to : std::string("new") + ModelName;
155
156 // Set the ModelConfig's Params of Interest
157 RooAbsData* expData = ws_single->data("asimovData");
158 if( !expData ) {
159 std::cout << "Error: Failed to find dataset: " << expData
160 << " in workspace" << std::endl;
161 throw hf_exc();
162 }
163 if(poi_list.size()!=0){
164 proto_config->GuessObsAndNuisance(*expData, RooMsgService::instance().isActive(static_cast<TObject*>(nullptr), RooFit::HistFactory, RooFit::INFO));
165 }
166
167 // Now, let's loop over any additional asimov datasets
168 // that we need to make
169
170 // Get the pdf
171 // Notice that we get the "new" pdf, this is the one that is
172 // used in the creation of these asimov datasets since they
173 // are fitted (or may be, at least).
174 RooAbsPdf* pdf = ws_single->pdf(NewModelName);
175 if( !pdf ) pdf = ws_single->pdf( ModelName );
176 const RooArgSet* observables = ws_single->set("observables");
177
178 // Create a SnapShot of the nominal values
179 std::string SnapShotName = "NominalParamValues";
180 ws_single->saveSnapshot(SnapShotName.c_str(), ws_single->allVars());
181
182 for( unsigned int i=0; i<measurement.GetAsimovDatasets().size(); ++i) {
183
184 // Set the variable values and "const" ness with the workspace
185 RooStats::HistFactory::Asimov& asimov = measurement.GetAsimovDatasets().at(i);
186 std::string AsimovName = asimov.GetName();
187
188 cxcoutPHF << "Generating additional Asimov Dataset: " << AsimovName << std::endl;
189 asimov.ConfigureWorkspace(ws_single);
190 std::unique_ptr<RooDataSet> asimov_dataset{static_cast<RooDataSet*>(AsymptoticCalculator::GenerateAsimovData(*pdf, *observables))};
191
192 cxcoutPHF << "Importing Asimov dataset" << std::endl;
193 bool failure = ws_single->import(*asimov_dataset, Rename(AsimovName.c_str()));
194 if( failure ) {
195 std::cout << "Error: Failed to import Asimov dataset: " << AsimovName
196 << std::endl;
197 throw hf_exc();
198 }
199
200 // Load the snapshot at the end of every loop iteration
201 // so we start each loop with a "clean" snapshot
202 ws_single->loadSnapshot(SnapShotName.c_str());
203 }
204
205 // Cool, we're done
206 return; // ws_single;
207 }
208
209
210 // We want to eliminate this interface and use the measurment directly
212
213 // This is a pretty light-weight wrapper function
214 //
215 // Take a fully configured measurement as well as
216 // one of its channels
217 //
218 // Return a workspace representing that channel
219 // Do this by first creating a vector of EstimateSummary's
220 // and this by configuring the workspace with any post-processing
221
222 // Get the channel's name
223 string ch_name = channel.GetName();
224
225 // Create a workspace for a SingleChannel from the Measurement Object
226 RooWorkspace* ws_single = this->MakeSingleChannelWorkspace(measurement, channel);
227 if( ws_single == nullptr ) {
228 cxcoutF(HistFactory) << "Error: Failed to make Single-Channel workspace for channel: " << ch_name
229 << " and measurement: " << measurement.GetName() << std::endl;
230 throw hf_exc();
231 }
232
233 // Finally, configure that workspace based on
234 // properties of the measurement
235 HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement( "model_"+ch_name, ws_single, measurement );
236
237 return ws_single;
238
239 }
240
242
243 // This function takes a fully configured measurement
244 // which may contain several channels and returns
245 // a workspace holding the combined model
246 //
247 // This can be used, for example, within a script to produce
248 // a combined workspace on-the-fly
249 //
250 // This is a static function (for now) to make
251 // it a one-liner
252
254
255 // First, we create an instance of a HistFactory
256 HistoToWorkspaceFactoryFast factory( measurement );
257
258 // Loop over the channels and create the individual workspaces
259 vector<std::unique_ptr<RooWorkspace>> channel_workspaces;
260 vector<string> channel_names;
261
262 for( unsigned int chanItr = 0; chanItr < measurement.GetChannels().size(); ++chanItr ) {
263
264 HistFactory::Channel& channel = measurement.GetChannels().at( chanItr );
265
266 if( ! channel.CheckHistograms() ) {
267 cxcoutFHF << "MakeModelAndMeasurementsFast: Channel: " << channel.GetName()
268 << " has uninitialized histogram pointers" << std::endl;
269 throw hf_exc();
270 }
271
272 string ch_name = channel.GetName();
273 channel_names.push_back(ch_name);
274
275 // GHL: Renaming to 'MakeSingleChannelWorkspace'
276 RooWorkspace* ws_single = factory.MakeSingleChannelModel( measurement, channel );
277
278 channel_workspaces.emplace_back(ws_single);
279
280 }
281
282
283 // Now, combine the individual channel workspaces to
284 // form the combined workspace
285 RooWorkspace* ws = factory.MakeCombinedModel( channel_names, channel_workspaces );
286
287
288 // Configure the workspace
290
291 // Done. Return the pointer
292 return ws;
293
294 }
295
296/// Create observables of type RooRealVar. Creates 1 to 3 observables, depending on the type of the histogram.
298 RooArgList observables;
299
300 for (unsigned int idx=0; idx < fObsNameVec.size(); ++idx) {
301 if (!proto->var(fObsNameVec[idx])) {
302 const TAxis *axis = (idx == 0) ? hist->GetXaxis() : (idx == 1 ? hist->GetYaxis() : hist->GetZaxis());
303 Int_t nbins = axis->GetNbins();
304 double xmin = axis->GetXmin();
305 double xmax = axis->GetXmax();
306 // create observable
307 auto obs = static_cast<RooRealVar*>(proto->factory(
308 Form("%s[%f,%f]", fObsNameVec[idx].c_str(), xmin, xmax)));
309 obs->setBins(nbins);
310 if (axis->IsVariableBinSize()) {
311 RooBinning binning(nbins, axis->GetXbins()->GetArray());
312 obs->setBinning(binning);
313 }
314 }
315
316 observables.add(*proto->var(fObsNameVec[idx]));
317 }
318
319 return observables;
320}
321
322 /// Create the nominal hist function from `hist`, and register it in the workspace.
324 const RooArgList& observables) const {
325 if(hist) {
326 cxcoutI(HistFactory) << "processing hist " << hist->GetName() << endl;
327 } else {
328 cxcoutF(HistFactory) << "hist is empty" << endl;
329 R__ASSERT(hist != 0);
330 return nullptr;
331 }
332
333 // determine histogram dimensionality
334 unsigned int histndim(1);
335 std::string classname = hist->ClassName();
336 if (classname.find("TH1")==0) { histndim=1; }
337 else if (classname.find("TH2")==0) { histndim=2; }
338 else if (classname.find("TH3")==0) { histndim=3; }
339 R__ASSERT( histndim==fObsNameVec.size() );
340
341 prefix += "_Hist_alphanominal";
342
343 RooDataHist histDHist((prefix + "DHist").c_str(),"",observables,hist);
344 RooHistFunc histFunc(prefix.c_str(),"",observables,histDHist,0);
345
346 proto->import(histFunc, RecycleConflictNodes());
347 auto histFuncInWS = static_cast<RooHistFunc*>(proto->arg(prefix.c_str()));
348
349 return histFuncInWS;
350 }
351
352 namespace {
353
354 void makeGaussianConstraint(RooAbsArg& param, RooWorkspace& proto, bool isUniform,
355 std::vector<std::string> & constraintTermNames) {
356 std::string paramName = param.GetName();
357 std::string constraintName = paramName + "Constraint";
358
359 // do nothing if the constraint term already exists
360 if(proto.pdf(constraintName)) return;
361
362 // case systematic is uniform (asssume they are like a Gaussian but with
363 // a large width (100 instead of 1)
364 const double gaussSigma = isUniform ? 100. : 1.0;
365 if (isUniform) {
366 cxcoutIHF << "Added a uniform constraint for " << paramName << " as a Gaussian constraint with a very large sigma " << std::endl;
367 }
368
369 std::stringstream command;
370 command << "Gaussian::" << constraintName << "(" << paramName << ",nom_" << paramName << "[0.,-10,10],"
371 << gaussSigma << ")";
372 constraintTermNames.emplace_back(proto.factory(command.str())->GetName());
373 auto * normParam = proto.var(std::string("nom_") + paramName);
374 normParam->setConstant();
375 const_cast<RooArgSet*>(proto.set("globalObservables"))->add(*normParam);
376 }
377
378 /// Make list of abstract parameters that interpolate in space of variations.
379 RooArgList makeInterpolationParameters(std::vector<HistoSys> const& histoSysList, RooWorkspace& proto) {
380 RooArgList params( ("alpha_Hist") );
381
382 // range is set using defined macro (see top of the page)
383 string range=string("[")+alpha_Low+","+alpha_High+"]";
384
385 for(auto const& histoSys : histoSysList) {
386 const std::string histoSysName = histoSys.GetName();
387 RooRealVar* temp = proto.var("alpha_" + histoSysName);
388 if(!temp){
389 temp = (RooRealVar*) proto.factory("alpha_" + histoSysName + range);
390 }
391 params.add(* temp );
392 }
393
394 return params;
395 }
396
397 /// Create a linear interpolation object that holds nominal and systematics, import it into the workspace,
398 /// and return a pointer to it.
399 RooAbsArg* makeLinInterp(RooArgList const& interpolationParams,
400 RooHistFunc* nominalFunc,
401 RooWorkspace* proto, const std::vector<HistoSys>& histoSysList,
402 const string& prefix,
403 const RooArgList& observables) {
404
405 // now make function that linearly interpolates expectation between variations
406 // get low/high variations to interpolate between
407 vector<double> low, high;
408 RooArgSet lowSet, highSet;
409 //ES// for(unsigned int j=0; j<lowHist.size(); ++j){
410 for(unsigned int j=0; j<histoSysList.size(); ++j){
411 std::stringstream str;
412 str<<"_"<<j;
413
414 const HistoSys& histoSys = histoSysList.at(j);
415 RooDataHist* lowDHist = new RooDataHist((prefix+str.str()+"lowDHist").c_str(),"",observables, histoSys.GetHistoLow());
416 RooDataHist* highDHist = new RooDataHist((prefix+str.str()+"highDHist").c_str(),"",observables, histoSys.GetHistoHigh());
417 RooHistFunc* lowFunc = new RooHistFunc((prefix+str.str()+"low").c_str(),"",observables,*lowDHist,0) ;
418 RooHistFunc* highFunc = new RooHistFunc((prefix+str.str()+"high").c_str(),"",observables,*highDHist,0) ;
419 lowSet.add(*lowFunc);
420 highSet.add(*highFunc);
421 }
422
423 // this is sigma(params), a piece-wise linear interpolation
424 PiecewiseInterpolation interp(prefix.c_str(),"",*nominalFunc,lowSet,highSet,interpolationParams);
425 interp.setPositiveDefinite();
426 interp.setAllInterpCodes(4); // LM: change to 4 (piece-wise linear to 6th order polynomial interpolation + linear extrapolation )
427 // KC: interpo codes 1 etc. don't have proper analytic integral.
428 RooArgSet observableSet(observables);
429 interp.setBinIntegrator(observableSet);
430 interp.forceNumInt();
431
432 proto->import(interp, RecycleConflictNodes()); // individual params have already been imported in first loop of this function
433
434 auto interpInWS = proto->arg(prefix.c_str());
435 assert(interpInWS);
436
437 return interpInWS;
438 }
439
440 }
441
442 // GHL: Consider passing the NormFactor list instead of the entire sample
443 std::unique_ptr<RooProduct> HistoToWorkspaceFactoryFast::CreateNormFactor(RooWorkspace* proto, string& channel, string& sigmaEpsilon, Sample& sample, bool doRatio){
444
445 std::vector<string> prodNames;
446
447 vector<NormFactor> normList = sample.GetNormFactorList();
448 vector<string> normFactorNames, rangeNames;
449
450
451 string overallNorm_times_sigmaEpsilon = sample.GetName() + "_" + channel + "_scaleFactors";
452 auto sigEps = proto->arg(sigmaEpsilon.c_str());
453 assert(sigEps);
454 auto normFactor = std::make_unique<RooProduct>(overallNorm_times_sigmaEpsilon.c_str(), overallNorm_times_sigmaEpsilon.c_str(), RooArgList(*sigEps));
455
456 if(normList.size() > 0){
457
458 for(vector<NormFactor>::iterator itr = normList.begin(); itr != normList.end(); ++itr){
459
460 NormFactor& norm = *itr;
461
462 string varname;
463 if(doRatio) {
464 varname = norm.GetName() + "_" + channel;
465 }
466 else {
467 varname=norm.GetName();
468 }
469
470 // GHL: Check that the NormFactor doesn't already exist
471 // (it may have been created as a function expression
472 // during preprocessing)
473 std::stringstream range;
474 range << "[" << norm.GetVal() << "," << norm.GetLow() << "," << norm.GetHigh() << "]";
475
476 if( proto->obj(varname) == nullptr) {
477 cxcoutI(HistFactory) << "making normFactor: " << norm.GetName() << endl;
478 // remove "doRatio" and name can be changed when ws gets imported to the combined model.
479 proto->factory(varname + range.str());
480 }
481
482 prodNames.push_back(varname);
483 rangeNames.push_back(range.str());
484 normFactorNames.push_back(varname);
485 }
486
487
488 for (const auto& name : prodNames) {
489 auto arg = proto->arg(name.c_str());
490 assert(arg);
491 normFactor->addTerm(arg);
492 }
493
494 }
495
496 unsigned int rangeIndex=0;
497 for( vector<string>::iterator nit = normFactorNames.begin(); nit!=normFactorNames.end(); ++nit){
498 if( count (normFactorNames.begin(), normFactorNames.end(), *nit) > 1 ){
499 cxcoutI(HistFactory) <<"<NormFactor Name =\""<<*nit<<"\"> is duplicated for <Sample Name=\""
500 << sample.GetName() << "\">, but only one factor will be included. \n Instead, define something like"
501 << "\n\t<Function Name=\""<<*nit<<"Squared\" Expression=\""<<*nit<<"*"<<*nit<<"\" Var=\""<<*nit<<rangeNames.at(rangeIndex)
502 << "\"> \nin your top-level XML's <Measurment> entry and use <NormFactor Name=\""<<*nit<<"Squared\" in your channel XML file."<< endl;
503 }
504 ++rangeIndex;
505 }
506
507 return normFactor;
508 }
509
511 string interpName,
512 std::vector<OverallSys>& systList,
513 vector<string>& constraintTermNames,
514 vector<string>& totSystTermNames) {
515
516 // add variables for all the relative overall uncertainties we expect
517 // range is set using defined macro (see top of the page)
518
519 string range=string("[0,")+alpha_Low+","+alpha_High+"]";
520 totSystTermNames.push_back(prefix);
521
522 RooArgSet params(prefix.c_str());
523 vector<double> lowVec, highVec;
524
525 std::map<std::string, double>::iterator itconstr;
526 for(unsigned int i = 0; i < systList.size(); ++i) {
527
528 OverallSys& sys = systList.at(i);
529 std::string strname = sys.GetName();
530 const char * name = strname.c_str();
531
532 // case of no systematic (is it possible)
533 if (meas.GetNoSyst().count(sys.GetName()) > 0 ) {
534 cxcoutI(HistFactory) << "HistoToWorkspaceFast::AddConstraintTerm - skip systematic " << sys.GetName() << std::endl;
535 continue;
536 }
537 // case systematic is a gamma constraint
538 if (meas.GetGammaSyst().count(sys.GetName()) > 0 ) {
539 double relerr = meas.GetGammaSyst().find(sys.GetName() )->second;
540 if (relerr <= 0) {
541 cxcoutI(HistFactory) << "HistoToWorkspaceFast::AddConstraintTerm - zero uncertainty assigned - skip systematic " << sys.GetName() << std::endl;
542 continue;
543 }
544 double tauVal = 1./(relerr*relerr);
545 double sqtau = 1./relerr;
546 RooAbsArg * beta = proto->factory(TString::Format("beta_%s[1,0,10]",name) );
547 // the global observable (y_s)
548 RooAbsArg * yvar = proto->factory(TString::Format("nom_%s[%f,0,10]",beta->GetName(),tauVal)) ;
549 // the rate of the gamma distribution (theta)
550 RooAbsArg * theta = proto->factory(TString::Format("theta_%s[%f]",name,1./tauVal));
551 // find alpha as function of beta
552 RooAbsArg* alphaOfBeta = proto->factory(TString::Format("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",name,name,-sqtau,sqtau));
553
554 // add now the constraint itself Gamma_beta_constraint(beta, y+1, tau, 0 )
555 // build the gamma parameter k = as y_s + 1
556 RooAbsArg * kappa = proto->factory(TString::Format("sum::k_%s(%s,1.)",name,yvar->GetName()) );
557 RooAbsArg * gamma = proto->factory(TString::Format("Gamma::%sConstraint(%s, %s, %s, 0.0)",beta->GetName(),beta->GetName(), kappa->GetName(), theta->GetName() ) );
559 alphaOfBeta->Print("t");
560 gamma->Print("t");
561 }
562 constraintTermNames.push_back(gamma->GetName());
563 // set global observables
564 RooRealVar * gobs = dynamic_cast<RooRealVar*>(yvar); assert(gobs);
565 gobs->setConstant(true);
566 const_cast<RooArgSet*>(proto->set("globalObservables"))->add(*yvar);
567
568 // add alphaOfBeta in the list of params to interpolate
569 params.add(*alphaOfBeta);
570 cxcoutI(HistFactory) << "Added a gamma constraint for " << name << std::endl;
571
572 }
573 else {
574 RooRealVar* alpha = (RooRealVar*) proto->var(prefix + sys.GetName());
575 if(!alpha) {
576 alpha = (RooRealVar*) proto->factory(prefix + sys.GetName() + range);
577 }
578 // add the Gaussian constraint part
579 const bool isUniform = meas.GetUniformSyst().count(sys.GetName()) > 0;
580 makeGaussianConstraint(*alpha, *proto, isUniform, constraintTermNames);
581
582 // check if exists a log-normal constraint
583 if (meas.GetLogNormSyst().count(sys.GetName()) == 0 && meas.GetGammaSyst().count(sys.GetName()) == 0 ) {
584 // just add the alpha for the parameters of the FlexibleInterpVar function
585 params.add(*alpha);
586 }
587 // case systematic is a log-normal constraint
588 if (meas.GetLogNormSyst().count(sys.GetName()) > 0 ) {
589 // log normal constraint for parameter
590 double relerr = meas.GetLogNormSyst().find(sys.GetName() )->second;
591 double tauVal = 1./relerr;
592 std::string tauName = "tau_" + sys.GetName();
593 proto->factory(TString::Format("%s[%f]",tauName.c_str(),tauVal ) );
594 double kappaVal = 1. + relerr;
595 std::string kappaName = "kappa_" + sys.GetName();
596 proto->factory(TString::Format("%s[%f]",kappaName.c_str(),kappaVal ) );
597 const char * alphaName = alpha->GetName();
598
599 std::string alphaOfBetaName = "alphaOfBeta_" + sys.GetName();
600 RooAbsArg * alphaOfBeta = proto->factory(TString::Format("expr::%s('%s*(pow(%s,%s)-1.)',%s,%s,%s)",alphaOfBetaName.c_str(),
601 tauName.c_str(),kappaName.c_str(),alphaName,
602 tauName.c_str(),kappaName.c_str(),alphaName ) );
603
604 cxcoutI(HistFactory) << "Added a log-normal constraint for " << name << std::endl;
605 if (RooMsgService::instance().isActive(static_cast<TObject*>(nullptr), RooFit::HistFactory, RooFit::DEBUG))
606 alphaOfBeta->Print("t");
607 params.add(*alphaOfBeta);
608 }
609
610 }
611 // add low/high vectors
612 double low = sys.GetLow();
613 double high = sys.GetHigh();
614 lowVec.push_back(low);
615 highVec.push_back(high);
616
617 } // end sys loop
618
619 if(systList.size() > 0){
620 // this is epsilon(alpha_j), a piece-wise linear interpolation
621 // LinInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec);
622
623 assert(!params.empty());
624 assert(int(lowVec.size()) == params.getSize() );
625
626 FlexibleInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec);
627 interp.setAllInterpCodes(4); // LM: change to 4 (piece-wise linear to 6th order polynomial interpolation + linear extrapolation )
628 //interp.setAllInterpCodes(0); // simple linear interpolation
629 proto->import(interp); // params have already been imported in first loop of this function
630 } else{
631 // some strange behavior if params,lowVec,highVec are empty.
632 //cout << "WARNING: No OverallSyst terms" << endl;
633 RooConstVar interp( (interpName).c_str(), "", 1.);
634 proto->import(interp); // params have already been imported in first loop of this function
635 }
636
637 // std::cout << "after creating FlexibleInterpVar " << std::endl;
638 // proto->Print();
639
640 }
641
642
644 const vector<RooProduct*>& sampleScaleFactors, std::vector<vector<RooAbsArg*>>& sampleHistFuncs) const {
645 assert(sampleScaleFactors.size() == sampleHistFuncs.size());
646
647 // for ith bin calculate totN_i = lumi * sum_j expected_j * syst_j
648
649 if (fObsNameVec.empty() && !fObsName.empty())
650 throw std::logic_error("HistFactory didn't process the observables correctly. Please file a bug report.");
651
652 auto firstHistFunc = dynamic_cast<const RooHistFunc*>(sampleHistFuncs.front().front());
653 if (!firstHistFunc) {
654 auto piecewiseInt = dynamic_cast<const PiecewiseInterpolation*>(sampleHistFuncs.front().front());
655 firstHistFunc = dynamic_cast<const RooHistFunc*>(piecewiseInt->nominalHist());
656 }
657 assert(firstHistFunc);
658
659 // Prepare a function to divide all bin contents by bin width to get a density:
660 const std::string binWidthFunctionName = totName + "_binWidth";
661 RooBinWidthFunction binWidth(binWidthFunctionName.c_str(), "Divide by bin width to obtain probability density", *firstHistFunc, true);
662 proto->import(binWidth);
663 auto binWidthWS = proto->function(binWidthFunctionName.c_str());
664 assert(binWidthWS);
665
666 // Loop through samples and create products of their functions:
667 RooArgSet coefList;
668 RooArgSet shapeList;
669 for (unsigned int i=0; i < sampleHistFuncs.size(); ++i) {
670 assert(!sampleHistFuncs[i].empty());
671 coefList.add(*sampleScaleFactors[i]);
672
673 std::vector<RooAbsArg*>& thisSampleHistFuncs = sampleHistFuncs[i];
674 thisSampleHistFuncs.push_back(binWidthWS);
675
676 if (thisSampleHistFuncs.size() == 1) {
677 // Just one function. Book it.
678 shapeList.add(*thisSampleHistFuncs.front());
679 } else {
680 // Have multiple functions. We need to multiply them.
681 std::string name = thisSampleHistFuncs.front()->GetName();
682 auto pos = name.find("Hist_alpha");
683 if (pos != std::string::npos) {
684 name = name.substr(0, pos) + "shapes";
685 } else if ( (pos = name.find("nominal")) != std::string::npos) {
686 name = name.substr(0, pos) + "shapes";
687 }
688
689 RooProduct shapeProduct(name.c_str(), name.c_str(), RooArgSet(thisSampleHistFuncs.begin(), thisSampleHistFuncs.end()));
690 proto->import(shapeProduct, RecycleConflictNodes());
691 shapeList.add(*proto->function(name.c_str()));
692 }
693 }
694
695 // Sum all samples
696 RooRealSumPdf tot(totName.c_str(), totName.c_str(), shapeList, coefList, true);
697 tot.specialIntegratorConfig(true)->method1D().setLabel("RooBinIntegrator") ;
698 tot.specialIntegratorConfig(true)->method2D().setLabel("RooBinIntegrator") ;
699 tot.specialIntegratorConfig(true)->methodND().setLabel("RooBinIntegrator") ;
700 tot.forceNumInt();
701
702 // for mixed generation in RooSimultaneous
703 tot.setAttribute("GenerateBinned"); // for use with RooSimultaneous::generate in mixed mode
704
705 // Enable the binned likelihood optimization
707 tot.setAttribute("BinnedLikelihood");
708 }
709
710 proto->import(tot, RecycleConflictNodes());
711 }
712
713 //////////////////////////////////////////////////////////////////////////////
714
716
717 FILE* covFile = fopen ((filename).c_str(),"w");
718 fprintf(covFile," ") ;
719 for (auto const *myargi : static_range_cast<RooRealVar *>(*params)) {
720 if(myargi->isConstant()) continue;
721 fprintf(covFile," & %s", myargi->GetName());
722 }
723 fprintf(covFile,"\\\\ \\hline \n" );
724 for (auto const *myargi : static_range_cast<RooRealVar *>(*params)) {
725 if(myargi->isConstant()) continue;
726 fprintf(covFile,"%s", myargi->GetName());
727 for (auto const *myargj : static_range_cast<RooRealVar *>(*params)) {
728 if(myargj->isConstant()) continue;
729 cout << myargi->GetName() << "," << myargj->GetName();
730 fprintf(covFile, " & %.2f", result->correlation(*myargi, *myargj));
731 }
732 cout << endl;
733 fprintf(covFile, " \\\\\n");
734 }
735 fclose(covFile);
736
737 }
738
739
740 ///////////////////////////////////////////////
742
743 // check inputs (see JIRA-6890 )
744
745 if (channel.GetSamples().empty()) {
746 Error("MakeSingleChannelWorkspace",
747 "The input Channel does not contain any sample - return a nullptr");
748 return 0;
749 }
750
751 const TH1* channel_hist_template = channel.GetSamples().front().GetHisto();
752 if (channel_hist_template == nullptr) {
753 channel.CollectHistograms();
754 channel_hist_template = channel.GetSamples().front().GetHisto();
755 }
756 if (channel_hist_template == nullptr) {
757 std::ostringstream stream;
758 stream << "The sample " << channel.GetSamples().front().GetName()
759 << " in channel " << channel.GetName() << " does not contain a histogram. This is the channel:\n";
760 channel.Print(stream);
761 Error("MakeSingleChannelWorkspace", "%s", stream.str().c_str());
762 return 0;
763 }
764
765 if( ! channel.CheckHistograms() ) {
766 std::cout << "MakeSingleChannelWorkspace: Channel: " << channel.GetName()
767 << " has uninitialized histogram pointers" << std::endl;
768 throw hf_exc();
769 }
770
771
772
773 // Set these by hand inside the function
774 vector<string> systToFix = measurement.GetConstantParams();
775 bool doRatio=false;
776
777 // to time the macro
778 TStopwatch t;
779 t.Start();
780 //ES// string channel_name=summary[0].channel;
781 string channel_name = channel.GetName();
782
783 /// MB: reset observable names for each new channel.
784 fObsNameVec.clear();
785
786 /// MB: label observables x,y,z, depending on histogram dimensionality
787 /// GHL: Give it the first sample's nominal histogram as a template
788 /// since the data histogram may not be present
789 if (fObsNameVec.empty()) { GuessObsNameVec(channel_hist_template); }
790
791 for ( unsigned int idx=0; idx<fObsNameVec.size(); ++idx ) {
792 fObsNameVec[idx] = "obs_" + fObsNameVec[idx] + "_" + channel_name ;
793 }
794
795 if (fObsNameVec.empty()) {
796 fObsName= "obs_" + channel_name; // set name ov observable
797 fObsNameVec.push_back( fObsName );
798 }
799
800 if (fObsNameVec.empty() || fObsNameVec.size() >= 3) {
801 throw hf_exc("HistFactory is limited to 1- to 3-dimensional histograms.");
802 }
803
804 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
805 << "\tStarting to process '"
806 << channel_name << "' channel with " << fObsNameVec.size() << " observables"
807 << "\n-----------------------------------------\n" << endl;
808
809 //
810 // our main workspace that we are using to construct the model
811 //
812 RooWorkspace* proto = new RooWorkspace(channel_name.c_str(), (channel_name+" workspace").c_str());
813 auto proto_config = make_unique<ModelConfig>("ModelConfig", proto);
814 proto_config->SetWorkspace(*proto);
815
816 // preprocess functions
817 vector<string>::iterator funcIter = fPreprocessFunctions.begin();
818 for(;funcIter!= fPreprocessFunctions.end(); ++funcIter){
819 cxcoutI(HistFactory) << "will preprocess this line: " << *funcIter <<endl;
820 proto->factory(*funcIter);
821 proto->Print();
822 }
823
824 RooArgSet likelihoodTerms("likelihoodTerms"), constraintTerms("constraintTerms");
825 vector<string> likelihoodTermNames, constraintTermNames, totSystTermNames;
826 // All histogram functions to be multiplied in each sample
827 std::vector<std::vector<RooAbsArg*>> allSampleHistFuncs;
828 std::vector<RooProduct*> sampleScaleFactors;
829
830 std::vector< pair<string,string> > statNamePairs;
831 std::vector< pair<const TH1*, std::unique_ptr<TH1>> > statHistPairs; // <nominal, error>
832 const std::string statFuncName = "mc_stat_" + channel_name;
833
834 string prefix, range;
835
836 /////////////////////////////
837 // shared parameters
838 // this is ratio of lumi to nominal lumi. We will include relative uncertainty in model
839 std::stringstream lumiStr;
840 // lumi range
841 lumiStr << "Lumi[" << fNomLumi << ",0," << 10.*fNomLumi << "]";
842 proto->factory(lumiStr.str());
843 cxcoutI(HistFactory) << "lumi str = " << lumiStr.str() << endl;
844
845 std::stringstream lumiErrorStr;
846 lumiErrorStr << "nominalLumi["<<fNomLumi << ",0,"<<fNomLumi+10*fLumiError<<"]," << fLumiError ;
847 proto->factory("Gaussian::lumiConstraint(Lumi,"+lumiErrorStr.str()+")");
848 proto->var("nominalLumi")->setConstant();
849 proto->defineSet("globalObservables","nominalLumi");
850 //likelihoodTermNames.push_back("lumiConstraint");
851 constraintTermNames.push_back("lumiConstraint");
852 cxcoutI(HistFactory) << "lumi Error str = " << lumiErrorStr.str() << endl;
853
854 //proto->factory("SigXsecOverSM[1.,0.5,1..8]");
855 ///////////////////////////////////
856 // loop through estimates, add expectation, floating bin predictions,
857 // and terms that constrain floating to expectation via uncertainties
858 // GHL: Loop over samples instead, which doesn't contain the data
859 for (Sample& sample : channel.GetSamples()) {
860 string overallSystName = sample.GetName() + "_" + channel_name + "_epsilon";
861
862 string systSourcePrefix = "alpha_";
863
864 // constraintTermNames and totSystTermNames are vectors that are passed
865 // by reference and filled by this method
866 AddConstraintTerms(proto,measurement, systSourcePrefix, overallSystName,
867 sample.GetOverallSysList(), constraintTermNames , totSystTermNames);
868
869 allSampleHistFuncs.emplace_back();
870 std::vector<RooAbsArg*>& sampleHistFuncs = allSampleHistFuncs.back();
871
872 // GHL: Consider passing the NormFactor list instead of the entire sample
873 auto normFactors = CreateNormFactor(proto, channel_name, overallSystName, sample, doRatio);
874 assert(normFactors);
875
876 // Create the string for the object
877 // that is added to the RooRealSumPdf
878 // for this channel
879// string syst_x_expectedPrefix = "";
880
881 // get histogram
882 //ES// TH1* nominal = it->nominal;
883 const TH1* nominal = sample.GetHisto();
884
885 // MB : HACK no option to have both non-hist variations and hist variations ?
886 // get histogram
887 // GHL: Okay, this is going to be non-trivial.
888 // We will loop over histosys's, which contain both
889 // the low hist and the high hist together.
890
891 // Logic:
892 // - If we have no HistoSys's, do part A
893 // - else, if the histo syst's don't match, return (we ignore this case)
894 // - finally, we take the syst's and apply the linear interpolation w/ constraint
895 string expPrefix = sample.GetName() + "_" + channel_name;
896 // create roorealvar observables
897 RooArgList observables = createObservables(sample.GetHisto(), proto);
898 RooHistFunc* nominalHistFunc = MakeExpectedHistFunc(sample.GetHisto(), proto, expPrefix, observables);
899 assert(nominalHistFunc);
900
901 if(sample.GetHistoSysList().empty()) {
902 // If no HistoSys
903 cxcoutI(HistFactory) << sample.GetName() + "_" + channel_name + " has no variation histograms " << endl;
904
905 sampleHistFuncs.push_back(nominalHistFunc);
906 } else {
907 // If there ARE HistoSys(s)
908 // name of source for variation
909 string constraintPrefix = sample.GetName() + "_" + channel_name + "_Hist_alpha";
910
911 // make list of abstract parameters that interpolate in space of variations
912 RooArgList interpParams = makeInterpolationParameters(sample.GetHistoSysList(), *proto);
913
914 // next, cerate the constraint terms
915 for(std::size_t i = 0; i < interpParams.size(); ++i) {
916 bool isUniform = measurement.GetUniformSyst().count(sample.GetHistoSysList()[i].GetName()) > 0;
917 makeGaussianConstraint(interpParams[i], *proto, isUniform, constraintTermNames);
918 }
919
920 // finally, create the interpolated function
921 sampleHistFuncs.push_back( makeLinInterp(interpParams, nominalHistFunc, proto,
922 sample.GetHistoSysList(), constraintPrefix, observables) );
923 }
924
925 ////////////////////////////////////
926 // Add StatErrors to this Channel //
927 ////////////////////////////////////
928
929 if( sample.GetStatError().GetActivate() ) {
930
931 if( fObsNameVec.size() > 3 ) {
932 cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions."
933 << std::endl;
934 throw hf_exc();
935 } else {
936
937 // If we are using StatUncertainties, we multiply this object
938 // by the ParamHistFunc and then pass that to the
939 // RooRealSumPdf by appending it's name to the list
940
941 cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " to be included in Stat Error "
942 << "for channel " << channel_name
943 << std::endl;
944
945 string UncertName = sample.GetName() + "_" + channel_name + "_StatAbsolUncert";
946 std::unique_ptr<TH1> statErrorHist;
947
948 if( sample.GetStatError().GetErrorHist() == nullptr ) {
949 // Make the absolute stat error
950 cxcoutI(HistFactory) << "Making Statistical Uncertainty Hist for "
951 << " Channel: " << channel_name
952 << " Sample: " << sample.GetName()
953 << std::endl;
954 statErrorHist.reset(MakeAbsolUncertaintyHist( UncertName, nominal));
955 } else {
956 // clone the error histograms because in case the sample has not error hist
957 // it is created in MakeAbsolUncertainty
958 // we need later to clean statErrorHist
959 statErrorHist.reset(static_cast<TH1*>(sample.GetStatError().GetErrorHist()->Clone()));
960 // We assume the (relative) error is provided.
961 // We must turn it into an absolute error
962 // using the nominal histogram
963 cxcoutI(HistFactory) << "Using external histogram for Stat Errors for "
964 << "\tChannel: " << channel_name
965 << "\tSample: " << sample.GetName()
966 << "\tError Histogram: " << statErrorHist->GetName() << std::endl;
967 // Multiply the relative stat uncertainty by the
968 // nominal to get the overall stat uncertainty
969 statErrorHist->Multiply( nominal );
970 statErrorHist->SetName( UncertName.c_str() );
971 }
972
973 // Save the nominal and error hists
974 // for the building of constraint terms
975 statHistPairs.emplace_back(nominal, std::move(statErrorHist));
976
977 // To do the 'conservative' version, we would need to do some
978 // intervention here. We would probably need to create a different
979 // ParamHistFunc for each sample in the channel. The would nominally
980 // use the same gamma's, so we haven't increased the number of parameters
981 // However, if a bin in the 'nominal' histogram is 0, we simply need to
982 // change the parameter in that bin in the ParamHistFunc for this sample.
983 // We also need to add a constraint term.
984 // Actually, we'd probably not use the ParamHistFunc...?
985 // we could remove the dependence in this ParamHistFunc on the ith gamma
986 // and then create the poisson term: Pois(tau | n_exp)Pois(data | n_exp)
987
988
989 // Next, try to get the common ParamHistFunc (it may have been
990 // created by another sample in this channel)
991 // or create it if it doesn't yet exist:
992 ParamHistFunc* paramHist = dynamic_cast<ParamHistFunc*>( proto->function(statFuncName.c_str()) );
993 if( paramHist == nullptr ) {
994
995 // Get a RooArgSet of the observables:
996 // Names in the list fObsNameVec:
997 RooArgList theObservables;
998 std::vector<std::string>::iterator itr = fObsNameVec.begin();
999 for (int idx=0; itr!=fObsNameVec.end(); ++itr, ++idx ) {
1000 theObservables.add( *proto->var(*itr) );
1001 }
1002
1003 // Create the list of terms to
1004 // control the bin heights:
1005 std::string ParamSetPrefix = "gamma_stat_" + channel_name;
1006 double gammaMin = 0.0;
1007 double gammaMax = 10.0;
1009 ParamSetPrefix.c_str(),
1010 theObservables,
1011 gammaMin, gammaMax);
1012
1013 ParamHistFunc statUncertFunc(statFuncName.c_str(), statFuncName.c_str(),
1014 theObservables, statFactorParams );
1015
1016 proto->import( statUncertFunc, RecycleConflictNodes() );
1017
1018 paramHist = (ParamHistFunc*) proto->function( statFuncName.c_str() );
1019 }
1020
1021 // apply stat function to sample
1022 sampleHistFuncs.push_back(paramHist);
1023 }
1024 } // END: if DoMcStat
1025
1026
1027 ///////////////////////////////////////////
1028 // Create a ShapeFactor for this channel //
1029 ///////////////////////////////////////////
1030
1031 if( sample.GetShapeFactorList().size() > 0 ) {
1032
1033 if( fObsNameVec.size() > 3 ) {
1034 cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions."
1035 << std::endl;
1036 throw hf_exc();
1037 } else {
1038
1039 cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " in channel: " << channel_name
1040 << " to be include a ShapeFactor."
1041 << std::endl;
1042
1043 for(unsigned int i=0; i < sample.GetShapeFactorList().size(); ++i) {
1044
1045 ShapeFactor& shapeFactor = sample.GetShapeFactorList().at(i);
1046
1047 std::string funcName = channel_name + "_" + shapeFactor.GetName() + "_shapeFactor";
1048 ParamHistFunc* paramHist = (ParamHistFunc*) proto->function( funcName.c_str() );
1049 if( paramHist == nullptr ) {
1050
1051 RooArgList theObservables;
1052 std::vector<std::string>::iterator itr = fObsNameVec.begin();
1053 for (int idx=0; itr!=fObsNameVec.end(); ++itr, ++idx ) {
1054 theObservables.add( *proto->var(*itr) );
1055 }
1056
1057 // Create the Parameters
1058 std::string funcParams = "gamma_" + shapeFactor.GetName();
1059
1060 // GHL: Again, we are putting hard ranges on the gamma's
1061 // We should change this to range from 0 to /inf
1062 RooArgList shapeFactorParams = ParamHistFunc::createParamSet(*proto,
1063 funcParams.c_str(),
1064 theObservables, 0, 1000);
1065
1066 // Create the Function
1067 ParamHistFunc shapeFactorFunc( funcName.c_str(), funcName.c_str(),
1068 theObservables, shapeFactorParams );
1069
1070 // Set an initial shape, if requested
1071 if( shapeFactor.GetInitialShape() != nullptr ) {
1072 TH1* initialShape = static_cast<TH1*>(shapeFactor.GetInitialShape()->Clone());
1073 cxcoutI(HistFactory) << "Setting Shape Factor: " << shapeFactor.GetName()
1074 << " to have initial shape from hist: "
1075 << initialShape->GetName()
1076 << std::endl;
1077 shapeFactorFunc.setShape( initialShape );
1078 }
1079
1080 // Set the variables constant, if requested
1081 if( shapeFactor.IsConstant() ) {
1082 cxcoutI(HistFactory) << "Setting Shape Factor: " << shapeFactor.GetName()
1083 << " to be constant" << std::endl;
1084 shapeFactorFunc.setConstant(true);
1085 }
1086
1087 proto->import( shapeFactorFunc, RecycleConflictNodes() );
1088 paramHist = (ParamHistFunc*) proto->function( funcName.c_str() );
1089
1090 } // End: Create ShapeFactor ParamHistFunc
1091
1092 sampleHistFuncs.push_back(paramHist);
1093 } // End loop over ShapeFactor Systematics
1094 }
1095 } // End: if ShapeFactorName!=""
1096
1097
1098 ////////////////////////////////////////
1099 // Create a ShapeSys for this channel //
1100 ////////////////////////////////////////
1101
1102 if( !sample.GetShapeSysList().empty() ) {
1103
1104 if( fObsNameVec.size() > 3 ) {
1105 cxcoutF(HistFactory) << "Cannot include Stat Error for histograms of more than 3 dimensions."
1106 << std::endl;
1107 throw hf_exc();
1108 } else {
1109
1110 // List of ShapeSys ParamHistFuncs
1111 std::vector<string> ShapeSysNames;
1112
1113 for( unsigned int i = 0; i < sample.GetShapeSysList().size(); ++i) {
1114
1115 // Create the ParamHistFunc's
1116 // Create their constraint terms and add them
1117 // to the list of constraint terms
1118
1119 // Create a single RooProduct over all of these
1120 // paramHistFunc's
1121
1122 // Send the name of that product to the RooRealSumPdf
1123
1124 RooStats::HistFactory::ShapeSys& shapeSys = sample.GetShapeSysList().at(i);
1125
1126 cxcoutI(HistFactory) << "Sample: " << sample.GetName() << " in channel: " << channel_name
1127 << " to include a ShapeSys." << std::endl;
1128
1129 std::string funcName = channel_name + "_" + shapeSys.GetName() + "_ShapeSys";
1130 ShapeSysNames.push_back( funcName );
1131 ParamHistFunc* paramHist = (ParamHistFunc*) proto->function( funcName.c_str() );
1132 if( paramHist == nullptr ) {
1133
1134 //std::string funcParams = "gamma_" + it->shapeFactorName;
1135 //paramHist = CreateParamHistFunc( proto, fObsNameVec, funcParams, funcName );
1136
1137 RooArgList theObservables;
1138 std::vector<std::string>::iterator itr = fObsNameVec.begin();
1139 for(; itr!=fObsNameVec.end(); ++itr ) {
1140 theObservables.add( *proto->var(*itr) );
1141 }
1142
1143 // Create the Parameters
1144 std::string funcParams = "gamma_" + shapeSys.GetName();
1145 RooArgList shapeFactorParams = ParamHistFunc::createParamSet(*proto,
1146 funcParams.c_str(),
1147 theObservables, 0, 10);
1148
1149 // Create the Function
1150 ParamHistFunc shapeFactorFunc( funcName.c_str(), funcName.c_str(),
1151 theObservables, shapeFactorParams );
1152
1153 proto->import( shapeFactorFunc, RecycleConflictNodes() );
1154 paramHist = (ParamHistFunc*) proto->function( funcName.c_str() );
1155
1156 } // End: Create ShapeFactor ParamHistFunc
1157
1158 // Create the constraint terms and add
1159 // them to the workspace (proto)
1160 // as well as the list of constraint terms (constraintTermNames)
1161
1162 // The syst should be a fractional error
1163 const TH1* shapeErrorHist = shapeSys.GetErrorHist();
1164
1165 // Constraint::Type shapeConstraintType = Constraint::Gaussian;
1166 Constraint::Type systype = shapeSys.GetConstraintType();
1167 if( systype == Constraint::Gaussian) {
1168 systype = Constraint::Gaussian;
1169 }
1170 if( systype == Constraint::Poisson ) {
1171 systype = Constraint::Poisson;
1172 }
1173
1174 double minShapeUncertainty = 0.0;
1175 RooArgList shapeConstraints = createStatConstraintTerms(proto, constraintTermNames,
1176 *paramHist, shapeErrorHist,
1177 systype,
1178 minShapeUncertainty);
1179
1180 } // End: Loop over ShapeSys vector in this EstimateSummary
1181
1182 // Now that we have the list of ShapeSys ParamHistFunc names,
1183 // we create the total RooProduct
1184 // we multiply the expected functio
1185
1186
1187 for( unsigned int i = 0; i < ShapeSysNames.size(); ++i ) {
1188 auto func = proto->function(ShapeSysNames.at(i).c_str());
1189 assert(func);
1190 sampleHistFuncs.push_back(func);
1191 }
1192
1193 } // End: NumObsVar == 1
1194
1195 } // End: !GetShapeSysList.empty()
1196
1197
1198 // GHL: This was pretty confusing before,
1199 // hopefully using the measurement directly
1200 // will improve it
1201 auto lumi = proto->arg("Lumi");
1202 if( !sample.GetNormalizeByTheory() ) {
1203 if (!lumi) {
1204 TString lumiParamString;
1205 lumiParamString += measurement.GetLumi();
1206 lumiParamString.ReplaceAll(' ', TString());
1207 lumi = proto->factory(("Lumi[" + lumiParamString + "]").Data());
1208 } else {
1209 static_cast<RooAbsRealLValue*>(lumi)->setVal(measurement.GetLumi());
1210 }
1211 }
1212 assert(lumi);
1213 normFactors->addTerm(lumi);
1214
1215 // Append the name of the "node"
1216 // that is to be summed with the
1217 // RooRealSumPdf
1218 proto->import(*normFactors, RecycleConflictNodes());
1219 auto normFactorsInWS = dynamic_cast<RooProduct*>(proto->arg(normFactors->GetName()));
1220 assert(normFactorsInWS);
1221
1222 sampleScaleFactors.push_back(normFactorsInWS);
1223 } // END: Loop over EstimateSummaries
1224
1225 // If a non-zero number of samples call for
1226 // Stat Uncertainties, create the statFactor functions
1227 if(!statHistPairs.empty()) {
1228
1229 // Create the histogram of (binwise)
1230 // stat uncertainties:
1231 unique_ptr<TH1> fracStatError( MakeScaledUncertaintyHist( channel_name + "_StatUncert" + "_RelErr", statHistPairs) );
1232 if( fracStatError == nullptr ) {
1233 cxcoutE(HistFactory) << "Error: Failed to make ScaledUncertaintyHist for: "
1234 << channel_name + "_StatUncert" + "_RelErr" << std::endl;
1235 throw hf_exc();
1236 }
1237
1238 // Using this TH1* of fractinal stat errors,
1239 // create a set of constraint terms:
1240 ParamHistFunc* chanStatUncertFunc = (ParamHistFunc*) proto->function( statFuncName.c_str() );
1241 cxcoutI(HistFactory) << "About to create Constraint Terms from: "
1242 << chanStatUncertFunc->GetName()
1243 << " params: " << chanStatUncertFunc->paramList()
1244 << std::endl;
1245
1246 // Get the constraint type and the
1247 // rel error threshold from the (last)
1248 // EstimateSummary looped over (but all
1249 // should be the same)
1250
1251 // Get the type of StatError constraint from the channel
1252 Constraint::Type statConstraintType = channel.GetStatErrorConfig().GetConstraintType();
1253 if( statConstraintType == Constraint::Gaussian) {
1254 cxcoutI(HistFactory) << "Using Gaussian StatErrors in channel: " << channel.GetName() << std::endl;
1255 }
1256 if( statConstraintType == Constraint::Poisson ) {
1257 cxcoutI(HistFactory) << "Using Poisson StatErrors in channel: " << channel.GetName() << std::endl;
1258 }
1259
1260 double statRelErrorThreshold = channel.GetStatErrorConfig().GetRelErrorThreshold();
1261 RooArgList statConstraints = createStatConstraintTerms(proto, constraintTermNames,
1262 *chanStatUncertFunc, fracStatError.get(),
1263 statConstraintType,
1264 statRelErrorThreshold);
1265
1266 } // END: Loop over stat Hist Pairs
1267
1268
1269 ///////////////////////////////////
1270 // for ith bin calculate totN_i = lumi * sum_j expected_j * syst_j
1271 MakeTotalExpected(proto, channel_name+"_model",
1272 sampleScaleFactors, allSampleHistFuncs);
1273 likelihoodTermNames.push_back(channel_name+"_model");
1274
1275 //////////////////////////////////////
1276 // fix specified parameters
1277 for(unsigned int i=0; i<systToFix.size(); ++i){
1278 RooRealVar* temp = proto->var(systToFix.at(i));
1279 if(temp) {
1280 // set the parameter constant
1281 temp->setConstant();
1282
1283 // remove the corresponding auxiliary observable from the global observables
1284 RooRealVar* auxMeas = nullptr;
1285 if(systToFix.at(i)=="Lumi"){
1286 auxMeas = proto->var("nominalLumi");
1287 } else {
1288 auxMeas = proto->var(std::string("nom_") + temp->GetName());
1289 }
1290
1291 if(auxMeas){
1292 const_cast<RooArgSet*>(proto->set("globalObservables"))->remove(*auxMeas);
1293 } else{
1294 cxcoutE(HistFactory) << "could not corresponding auxiliary measurement "
1295 << TString::Format("nom_%s",temp->GetName()) << endl;
1296 }
1297 } else {
1298 cxcoutE(HistFactory) << "could not find variable " << systToFix.at(i)
1299 << " could not set it to constant" << endl;
1300 }
1301 }
1302
1303 //////////////////////////////////////
1304 // final proto model
1305 for(unsigned int i=0; i<constraintTermNames.size(); ++i){
1306 RooAbsArg* proto_arg = (proto->arg(constraintTermNames[i].c_str()));
1307 if( proto_arg==nullptr ) {
1308 cxcoutF(HistFactory) << "Error: Cannot find arg set: " << constraintTermNames.at(i)
1309 << " in workspace: " << proto->GetName() << std::endl;
1310 throw hf_exc();
1311 }
1312 constraintTerms.add( *proto_arg );
1313 // constraintTerms.add(* proto_arg(proto->arg(constraintTermNames[i].c_str())) );
1314 }
1315 for(unsigned int i=0; i<likelihoodTermNames.size(); ++i){
1316 RooAbsArg* proto_arg = (proto->arg(likelihoodTermNames[i].c_str()));
1317 if( proto_arg==nullptr ) {
1318 cxcoutF(HistFactory) << "Error: Cannot find arg set: " << likelihoodTermNames.at(i)
1319 << " in workspace: " << proto->GetName() << std::endl;
1320 throw hf_exc();
1321 }
1322 likelihoodTerms.add( *proto_arg );
1323 }
1324 proto->defineSet("constraintTerms",constraintTerms);
1325 proto->defineSet("likelihoodTerms",likelihoodTerms);
1326
1327 // list of observables
1328 RooArgList observables;
1329 std::string observablesStr;
1330
1331 std::vector<std::string>::iterator itr = fObsNameVec.begin();
1332 for(; itr!=fObsNameVec.end(); ++itr ) {
1333 observables.add( *proto->var(*itr) );
1334 if (!observablesStr.empty()) { observablesStr += ","; }
1335 observablesStr += *itr;
1336 }
1337
1338 // We create two sets, one for backwards compatability
1339 // The other to make a consistent naming convention
1340 // between individual channels and the combined workspace
1341 proto->defineSet("observables", TString::Format("%s",observablesStr.c_str()));
1342 proto->defineSet("observablesSet", TString::Format("%s",observablesStr.c_str()));
1343
1344 // Create the ParamHistFunc
1345 // after observables have been made
1346 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1347 << "\timport model into workspace"
1348 << "\n-----------------------------------------\n" << endl;
1349
1350 auto model = make_unique<RooProdPdf>(
1351 ("model_"+channel_name).c_str(), // MB : have changed this into conditional pdf. Much faster for toys!
1352 "product of Poissons accross bins for a single channel",
1353 constraintTerms, Conditional(likelihoodTerms,observables));
1354 proto->import(*model,RecycleConflictNodes());
1355
1356 proto_config->SetPdf(*model);
1357 proto_config->SetObservables(observables);
1358 proto_config->SetGlobalObservables(*proto->set("globalObservables"));
1359 // proto->writeToFile(("results/model_"+channel+".root").c_str());
1360 // fill out nuisance parameters in model config
1361 // proto_config->GuessObsAndNuisance(*proto->data("asimovData"));
1362 proto->import(*proto_config,proto_config->GetName());
1363 proto->importClassCode();
1364
1365 ///////////////////////////
1366 // make data sets
1367 // THis works and is natural, but the memory size of the simultaneous dataset grows exponentially with channels
1368 const char* weightName="weightVar";
1369 proto->factory(TString::Format("%s[0,-1e10,1e10]",weightName));
1370 proto->defineSet("obsAndWeight",TString::Format("%s,%s",weightName,observablesStr.c_str()));
1371
1372 // New Asimov Generation: Use the code in the Asymptotic calculator
1373 // Need to get the ModelConfig...
1374 int asymcalcPrintLevel = 0;
1375 if (RooMsgService::instance().isActive(static_cast<TObject*>(nullptr), RooFit::HistFactory, RooFit::INFO)) asymcalcPrintLevel = 1;
1376 if (RooMsgService::instance().isActive(static_cast<TObject*>(nullptr), RooFit::HistFactory, RooFit::DEBUG)) asymcalcPrintLevel = 2;
1377 AsymptoticCalculator::SetPrintLevel(asymcalcPrintLevel);
1378 unique_ptr<RooAbsData> asimov_dataset(AsymptoticCalculator::GenerateAsimovData(*model, observables));
1379 proto->import(dynamic_cast<RooDataSet&>(*asimov_dataset), Rename("asimovData"));
1380
1381 // GHL: Determine to use data if the hist isn't 'nullptr'
1382 if(TH1 const* mnominal = channel.GetData().GetHisto()) {
1383 // This works and is natural, but the memory size of the simultaneous
1384 // dataset grows exponentially with channels.
1385 RooDataSet dataset{"obsData","",*proto->set("obsAndWeight"),weightName};
1386 ConfigureHistFactoryDataset( dataset, *mnominal, *proto, fObsNameVec );
1387 proto->import(dataset);
1388 } // End: Has non-null 'data' entry
1389
1390
1391 for(auto const& data : channel.GetAdditionalData()) {
1392 if(data.GetName().empty()) {
1393 cxcoutF(HistFactory) << "Error: Additional Data histogram for channel: " << channel.GetName()
1394 << " has no name! The name always needs to be set for additional datasets, "
1395 << "either via the \"Name\" tag in the XML or via RooStats::HistFactory::Data::SetName()." << std::endl;
1396 throw hf_exc();
1397 }
1398 std::string const& dataName = data.GetName();
1399 TH1 const* mnominal = data.GetHisto();
1400 if( !mnominal ) {
1401 cxcoutF(HistFactory) << "Error: Additional Data histogram for channel: " << channel.GetName()
1402 << " with name: " << dataName << " is nullptr" << std::endl;
1403 throw hf_exc();
1404 }
1405
1406 // THis works and is natural, but the memory size of the simultaneous dataset grows exponentially with channels
1407 RooDataSet dataset{dataName.c_str(), "", *proto->set("obsAndWeight"), weightName};
1408 ConfigureHistFactoryDataset( dataset, *mnominal, *proto, fObsNameVec );
1409 proto->import(dataset);
1410
1411 }
1412
1413 if (RooMsgService::instance().isActive(static_cast<TObject*>(nullptr), RooFit::HistFactory, RooFit::INFO))
1414 proto->Print();
1415
1416 return proto;
1417 }
1418
1419
1421 TH1 const& mnominal,
1423 std::vector<std::string> const& obsNameVec) {
1424
1425 // Take a RooDataSet and fill it with the entries
1426 // from a TH1*, using the observable names to
1427 // determine the columns
1428
1429 if (obsNameVec.empty() ) {
1430 Error("ConfigureHistFactoryDataset","Invalid input - return");
1431 return;
1432 }
1433
1434 TAxis const* ax = mnominal.GetXaxis();
1435 TAxis const* ay = mnominal.GetYaxis();
1436 TAxis const* az = mnominal.GetZaxis();
1437
1438 for (int i=1; i<=ax->GetNbins(); ++i) { // 1 or more dimension
1439
1440 double xval = ax->GetBinCenter(i);
1441 proto.var( obsNameVec[0] )->setVal( xval );
1442
1443 if(obsNameVec.size()==1) {
1444 double fval = mnominal.GetBinContent(i);
1445 obsDataUnbinned.add( *proto.set("obsAndWeight"), fval );
1446 } else { // 2 or more dimensions
1447
1448 for(int j=1; j<=ay->GetNbins(); ++j) {
1449 double yval = ay->GetBinCenter(j);
1450 proto.var( obsNameVec[1] )->setVal( yval );
1451
1452 if(obsNameVec.size()==2) {
1453 double fval = mnominal.GetBinContent(i,j);
1454 obsDataUnbinned.add( *proto.set("obsAndWeight"), fval );
1455 } else { // 3 dimensions
1456
1457 for(int k=1; k<=az->GetNbins(); ++k) {
1458 double zval = az->GetBinCenter(k);
1459 proto.var( obsNameVec[2] )->setVal( zval );
1460 double fval = mnominal.GetBinContent(i,j,k);
1461 obsDataUnbinned.add( *proto.set("obsAndWeight"), fval );
1462 }
1463 }
1464 }
1465 }
1466 }
1467 }
1468
1470 {
1471 fObsNameVec.clear();
1472
1473 // determine histogram dimensionality
1474 unsigned int histndim(1);
1475 std::string classname = hist->ClassName();
1476 if (classname.find("TH1")==0) { histndim=1; }
1477 else if (classname.find("TH2")==0) { histndim=2; }
1478 else if (classname.find("TH3")==0) { histndim=3; }
1479
1480 for ( unsigned int idx=0; idx<histndim; ++idx ) {
1481 if (idx==0) { fObsNameVec.push_back("x"); }
1482 if (idx==1) { fObsNameVec.push_back("y"); }
1483 if (idx==2) { fObsNameVec.push_back("z"); }
1484 }
1485 }
1486
1487
1488 RooWorkspace* HistoToWorkspaceFactoryFast::MakeCombinedModel(vector<string> ch_names, vector<std::unique_ptr<RooWorkspace>>& chs)
1489 {
1491
1492 // check first the inputs (see JIRA-6890)
1493 if (ch_names.empty() || chs.empty() ) {
1494 Error("MakeCombinedModel","Input vectors are empty - return a nullptr");
1495 return 0;
1496 }
1497 if (chs.size() < ch_names.size() ) {
1498 Error("MakeCombinedModel","Input vector of workspace has an invalid size - return a nullptr");
1499 return 0;
1500 }
1501
1502 //
1503 /// These things were used for debugging. Maybe useful in the future
1504 //
1505
1506 map<string, RooAbsPdf*> pdfMap;
1507 vector<RooAbsPdf*> models;
1508
1509 RooArgList obsList;
1510 for(unsigned int i = 0; i< ch_names.size(); ++i){
1511 ModelConfig * config = (ModelConfig *) chs[i]->obj("ModelConfig");
1512 obsList.add(*config->GetObservables());
1513 }
1514 cxcoutI(HistFactory) <<"full list of observables:\n" << obsList << std::endl;
1515
1516 RooArgSet globalObs;
1517 stringstream channelString;
1518 channelString << "channelCat[";
1519 for(unsigned int i = 0; i< ch_names.size(); ++i){
1520 string channel_name=ch_names[i];
1521 if (i == 0 && isdigit(channel_name[0])) {
1522 throw std::invalid_argument("The first channel name for HistFactory cannot start with a digit. Got " + channel_name);
1523 }
1524 if (channel_name.find(',') != std::string::npos) {
1525 throw std::invalid_argument("Channel names for HistFactory cannot contain ','. Got " + channel_name);
1526 }
1527
1528 if (i == 0) channelString << channel_name ;
1529 else channelString << ',' << channel_name ;
1530 RooWorkspace * ch=chs[i].get();
1531
1532 RooAbsPdf* model = ch->pdf("model_"+channel_name);
1533 if(!model) cout <<"failed to find model for channel"<<endl;
1534 // cout << "int = " << model->createIntegral(*obsN)->getVal() << endl;;
1535 models.push_back(model);
1536 globalObs.add(*ch->set("globalObservables"), /*silent=*/true); // silent because observables might exist in other channel.
1537
1538 // constrainedParams->add( * ch->set("constrainedParams") );
1539 pdfMap[channel_name]=model;
1540 }
1541 channelString << "]";
1542
1543 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1544 << "\tEntering combination"
1545 << "\n-----------------------------------------\n" << endl;
1546 RooWorkspace* combined = new RooWorkspace("combined");
1547 // RooWorkspace* combined = chs[0];
1548
1549
1550 RooCategory* channelCat = dynamic_cast<RooCategory*>( combined->factory(channelString.str()) );
1551 if (!channelCat) throw std::runtime_error("Unable to construct a category from string " + channelString.str());
1552
1553 auto simPdf= std::make_unique<RooSimultaneous>("simPdf","",pdfMap, *channelCat);
1554 auto combined_config = std::make_unique<ModelConfig>("ModelConfig", combined);
1555 combined_config->SetWorkspace(*combined);
1556 // combined_config->SetNuisanceParameters(*constrainedParams);
1557
1558 combined->import(globalObs);
1559 combined->defineSet("globalObservables",globalObs);
1560 combined_config->SetGlobalObservables(*combined->set("globalObservables"));
1561
1562 combined->factory("weightVar[0,-1e10,1e10]");
1563 obsList.add(*combined->var("weightVar"));
1564 combined->defineSet("observables",{obsList, *channelCat}, /*importMissing=*/true);
1565 combined_config->SetObservables(*combined->set("observables"));
1566
1567
1568 // Now merge the observable datasets across the channels
1569 for(RooAbsData * data : chs[0]->allData()) {
1570 // We are excluding the Asimov data, because it needs to be regenerated
1571 // later after the parameter values are set.
1572 if(std::string("asimovData") != data->GetName()) {
1573 MergeDataSets(combined, chs, ch_names, data->GetName(), obsList, channelCat);
1574 }
1575 }
1576
1577
1578 if (RooMsgService::instance().isActive(static_cast<TObject*>(nullptr), RooFit::HistFactory, RooFit::INFO))
1579 combined->Print();
1580
1581 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1582 << "\tImporting combined model"
1583 << "\n-----------------------------------------\n" << endl;
1584 combined->import(*simPdf,RecycleConflictNodes());
1585
1586 std::map< std::string, double>::iterator param_itr = fParamValues.begin();
1587 for( ; param_itr != fParamValues.end(); ++param_itr ){
1588 // make sure they are fixed
1589 std::string paramName = param_itr->first;
1590 double paramVal = param_itr->second;
1591
1592 if(RooRealVar* temp = combined->var( paramName )) {
1593 temp->setVal( paramVal );
1594 cxcoutI(HistFactory) <<"setting " << paramName << " to the value: " << paramVal << endl;
1595 } else
1596 cxcoutE(HistFactory) << "could not find variable " << paramName << " could not set its value" << endl;
1597 }
1598
1599
1600 for(unsigned int i=0; i<fSystToFix.size(); ++i){
1601 // make sure they are fixed
1602 if(RooRealVar* temp = combined->var(fSystToFix[i])) {
1603 temp->setConstant();
1604 cxcoutI(HistFactory) <<"setting " << fSystToFix.at(i) << " constant" << endl;
1605 } else
1606 cxcoutE(HistFactory) << "could not find variable " << fSystToFix.at(i) << " could not set it to constant" << endl;
1607 }
1608
1609 ///
1610 /// writing out the model in graphViz
1611 ///
1612 // RooAbsPdf* customized=combined->pdf("simPdf");
1613 //combined_config->SetPdf(*customized);
1614 combined_config->SetPdf(*simPdf);
1615 // combined_config->GuessObsAndNuisance(*simData);
1616 // customized->graphVizTree(("results/"+fResultsPrefixStr.str()+"_simul.dot").c_str());
1617 combined->import(*combined_config,combined_config->GetName());
1618 combined->importClassCode();
1619 // combined->writeToFile("results/model_combined.root");
1620
1621
1622 ////////////////////////////////////////////
1623 // Make toy simultaneous dataset
1624 cxcoutP(HistFactory) << "\n-----------------------------------------\n"
1625 << "\tcreate toy data for " << channelString.str()
1626 << "\n-----------------------------------------\n" << endl;
1627
1628
1629 // now with weighted datasets
1630 // First Asimov
1631
1632 // Create Asimov data for the combined dataset
1633 std::unique_ptr<RooDataSet> asimov_combined{static_cast<RooDataSet*>(AsymptoticCalculator::GenerateAsimovData(
1634 *combined->pdf("simPdf"),
1635 obsList))};
1636 if( asimov_combined ) {
1637 combined->import( *asimov_combined, Rename("asimovData"));
1638 }
1639 else {
1640 std::cout << "Error: Failed to create combined asimov dataset" << std::endl;
1641 throw hf_exc();
1642 }
1643
1644 return combined;
1645 }
1646
1647
1649 std::vector<std::unique_ptr<RooWorkspace>>& wspace_vec,
1650 std::vector<std::string> const& channel_names,
1651 std::string const& dataSetName,
1652 RooArgList const& obsList,
1653 RooCategory* channelCat) {
1654
1655 // Create the total dataset
1656 std::unique_ptr<RooDataSet> simData;
1657
1658 // Loop through channels, get their individual datasets,
1659 // and add them to the combined dataset
1660 for(unsigned int i = 0; i< channel_names.size(); ++i){
1661
1662 // Grab the dataset for the existing channel
1663 cxcoutPHF << "Merging data for channel " << channel_names[i].c_str() << std::endl;
1664 RooDataSet* obsDataInChannel = (RooDataSet*) wspace_vec[i]->data(dataSetName.c_str());
1665 if( !obsDataInChannel ) {
1666 std::cout << "Error: Can't find DataSet: " << dataSetName
1667 << " in channel: " << channel_names.at(i)
1668 << std::endl;
1669 throw hf_exc();
1670 }
1671
1672 // Create the new Dataset
1673 auto tempData = std::make_unique<RooDataSet>(channel_names[i].c_str(),"",
1674 obsList, Index(*channelCat),
1675 WeightVar("weightVar"),
1676 Import(channel_names[i].c_str(),*obsDataInChannel));
1677 if(simData) {
1678 simData->append(*tempData);
1679 }
1680 else {
1681 simData = std::move(tempData);
1682 }
1683 } // End Loop Over Channels
1684
1685 // Check that we successfully created the dataset
1686 // and import it into the workspace
1687 if(simData) {
1688 combined->import(*simData, Rename(dataSetName.c_str()));
1689 return static_cast<RooDataSet*>(combined->data(dataSetName));
1690 }
1691 else {
1692 std::cout << "Error: Unable to merge observable datasets" << std::endl;
1693 throw hf_exc();
1694 return nullptr;
1695 }
1696 }
1697
1698
1700
1701 // Take a nominal TH1* and create
1702 // a TH1 representing the binwise
1703 // errors (taken from the nominal TH1)
1704
1705 TH1* ErrorHist = (TH1*) Nominal->Clone( Name.c_str() );
1706 ErrorHist->Reset();
1707
1708 Int_t numBins = Nominal->GetNbinsX()*Nominal->GetNbinsY()*Nominal->GetNbinsZ();
1709 Int_t binNumber = 0;
1710
1711 // Loop over bins
1712 for( Int_t i_bin = 0; i_bin < numBins; ++i_bin) {
1713
1714 binNumber++;
1715 // Ignore underflow / overflow
1716 while( Nominal->IsBinUnderflow(binNumber) || Nominal->IsBinOverflow(binNumber) ){
1717 binNumber++;
1718 }
1719
1720 double histError = Nominal->GetBinError( binNumber );
1721
1722 // Check that histError != NAN
1723 if( histError != histError ) {
1724 std::cout << "Warning: In histogram " << Nominal->GetName()
1725 << " bin error for bin " << i_bin
1726 << " is NAN. Not using Error!!!"
1727 << std::endl;
1728 throw hf_exc();
1729 //histError = sqrt( histContent );
1730 //histError = 0;
1731 }
1732
1733 // Check that histError ! < 0
1734 if( histError < 0 ) {
1735 std::cout << "Warning: In histogram " << Nominal->GetName()
1736 << " bin error for bin " << binNumber
1737 << " is < 0. Setting Error to 0"
1738 << std::endl;
1739 //histError = sqrt( histContent );
1740 histError = 0;
1741 }
1742
1743 ErrorHist->SetBinContent( binNumber, histError );
1744
1745 }
1746
1747 return ErrorHist;
1748
1749 }
1750
1751 // Take a list of < nominal, absolError > TH1* pairs
1752 // and construct a single histogram representing the
1753 // total fractional error as:
1754
1755 // UncertInQuad(bin i) = Sum: absolUncert*absolUncert
1756 // Total(bin i) = Sum: Value
1757 //
1758 // TotalFracError(bin i) = Sqrt( UncertInQuad(i) ) / TotalBin(i)
1759 std::unique_ptr<TH1> HistoToWorkspaceFactoryFast::MakeScaledUncertaintyHist( const std::string& Name, std::vector< std::pair<const TH1*, std::unique_ptr<TH1>> > const& HistVec ) const {
1760
1761
1762 unsigned int numHists = HistVec.size();
1763
1764 if( numHists == 0 ) {
1765 cxcoutE(HistFactory) << "Warning: Empty Hist Vector, cannot create total uncertainty" << std::endl;
1766 return nullptr;
1767 }
1768
1769 const TH1* HistTemplate = HistVec.at(0).first;
1770 Int_t numBins = HistTemplate->GetNbinsX()*HistTemplate->GetNbinsY()*HistTemplate->GetNbinsZ();
1771
1772 // Check that all histograms
1773 // have the same bins
1774 for( unsigned int i = 0; i < HistVec.size(); ++i ) {
1775
1776 const TH1* nominal = HistVec.at(i).first;
1777 const TH1* error = HistVec.at(i).second.get();
1778
1779 if( nominal->GetNbinsX()*nominal->GetNbinsY()*nominal->GetNbinsZ() != numBins ) {
1780 cxcoutE(HistFactory) << "Error: Provided hists have unequal bins" << std::endl;
1781 return nullptr;
1782 }
1783 if( error->GetNbinsX()*error->GetNbinsY()*error->GetNbinsZ() != numBins ) {
1784 cxcoutE(HistFactory) << "Error: Provided hists have unequal bins" << std::endl;
1785 return nullptr;
1786 }
1787 }
1788
1789 std::vector<double> TotalBinContent( numBins, 0.0);
1790 std::vector<double> HistErrorsSqr( numBins, 0.0);
1791
1792 Int_t binNumber = 0;
1793
1794 // Loop over bins
1795 for( Int_t i_bins = 0; i_bins < numBins; ++i_bins) {
1796
1797 binNumber++;
1798 while( HistTemplate->IsBinUnderflow(binNumber) || HistTemplate->IsBinOverflow(binNumber) ){
1799 binNumber++;
1800 }
1801
1802 for( unsigned int i_hist = 0; i_hist < numHists; ++i_hist ) {
1803
1804 const TH1* nominal = HistVec.at(i_hist).first;
1805 const TH1* error = HistVec.at(i_hist).second.get();
1806
1807 //Int_t binNumber = i_bins + 1;
1808
1809 double histValue = nominal->GetBinContent( binNumber );
1810 double histError = error->GetBinContent( binNumber );
1811 /*
1812 std::cout << " Getting Bin content for Stat Uncertainty"
1813 << " Nom name: " << nominal->GetName()
1814 << " Err name: " << error->GetName()
1815 << " HistNumber: " << i_hist << " bin: " << binNumber
1816 << " Value: " << histValue << " Error: " << histError
1817 << std::endl;
1818 */
1819
1820 if( histError != histError ) {
1821 cxcoutE(HistFactory) << "In histogram " << error->GetName()
1822 << " bin error for bin " << binNumber
1823 << " is NAN. Not using error!!";
1824 throw hf_exc();
1825 }
1826
1827 TotalBinContent.at(i_bins) += histValue;
1828 HistErrorsSqr.at(i_bins) += histError*histError; // Add in quadrature
1829
1830 }
1831 }
1832
1833 binNumber = 0;
1834
1835 // Creat the output histogram
1836 TH1* ErrorHist = (TH1*) HistTemplate->Clone( Name.c_str() );
1837 ErrorHist->Reset();
1838
1839 // Fill the output histogram
1840 for( Int_t i = 0; i < numBins; ++i) {
1841
1842 // Int_t binNumber = i + 1;
1843 binNumber++;
1844 while( ErrorHist->IsBinUnderflow(binNumber) || ErrorHist->IsBinOverflow(binNumber) ){
1845 binNumber++;
1846 }
1847
1848 double ErrorsSqr = HistErrorsSqr.at(i);
1849 double TotalVal = TotalBinContent.at(i);
1850
1851 if( TotalVal <= 0 ) {
1852 cxcoutW(HistFactory) << "Warning: Sum of histograms for bin: " << binNumber
1853 << " is <= 0. Setting error to 0"
1854 << std::endl;
1855
1856 ErrorHist->SetBinContent( binNumber, 0.0 );
1857 continue;
1858 }
1859
1860 double RelativeError = sqrt(ErrorsSqr) / TotalVal;
1861
1862 // If we otherwise get a NAN
1863 // it's an error
1864 if( RelativeError != RelativeError ) {
1865 cxcoutE(HistFactory) << "Error: bin " << i << " error is NAN\n"
1866 << " HistErrorsSqr: " << ErrorsSqr
1867 << " TotalVal: " << TotalVal;
1868 throw hf_exc();
1869 }
1870
1871 // 0th entry in vector is
1872 // the 1st bin in TH1
1873 // (we ignore underflow)
1874
1875 // Error and bin content are interchanged because for some reason, the other functions
1876 // use the bin content to convey the error ...
1877 ErrorHist->SetBinError(binNumber, TotalVal);
1878 ErrorHist->SetBinContent(binNumber, RelativeError);
1879
1880 cxcoutI(HistFactory) << "Making Total Uncertainty for bin " << binNumber
1881 << " Error = " << sqrt(ErrorsSqr)
1882 << " CentralVal = " << TotalVal
1883 << " RelativeError = " << RelativeError << "\n";
1884
1885 }
1886
1887 return std::unique_ptr<TH1>(ErrorHist);
1888}
1889
1890
1891
1893 createStatConstraintTerms( RooWorkspace* proto, vector<string>& constraintTermNames,
1894 ParamHistFunc& paramHist, const TH1* uncertHist,
1895 Constraint::Type type, double minSigma ) {
1896
1897
1898 // Take a RooArgList of RooAbsReal's and
1899 // create N constraint terms (one for
1900 // each gamma) whose relative uncertainty
1901 // is the value of the ith RooAbsReal
1902 //
1903 // The integer "type" controls the type
1904 // of constraint term:
1905 //
1906 // type == 0 : NONE
1907 // type == 1 : Gaussian
1908 // type == 2 : Poisson
1909 // type == 3 : LogNormal
1910
1911 RooArgList ConstraintTerms;
1912
1913 RooArgList paramSet = paramHist.paramList();
1914
1915 // Must get the full size of the TH1
1916 // (No direct method to do this...)
1917 Int_t numBins = uncertHist->GetNbinsX()*uncertHist->GetNbinsY()*uncertHist->GetNbinsZ();
1918 Int_t numParams = paramSet.getSize();
1919 // Int_t numBins = uncertHist->GetNbinsX()*uncertHist->GetNbinsY()*uncertHist->GetNbinsZ();
1920
1921 // Check that there are N elements
1922 // in the RooArgList
1923 if( numBins != numParams ) {
1924 std::cout << "Error: In createStatConstraintTerms, encountered bad number of bins" << std::endl;
1925 std::cout << "Given histogram with " << numBins << " bins,"
1926 << " but require exactly " << numParams << std::endl;
1927 throw hf_exc();
1928 }
1929
1930 Int_t TH1BinNumber = 0;
1931 for( Int_t i = 0; i < paramSet.getSize(); ++i) {
1932
1933 TH1BinNumber++;
1934
1935 while( uncertHist->IsBinUnderflow(TH1BinNumber) || uncertHist->IsBinOverflow(TH1BinNumber) ){
1936 TH1BinNumber++;
1937 }
1938
1939 RooRealVar& gamma = (RooRealVar&) (paramSet[i]);
1940
1941 cxcoutI(HistFactory) << "Creating constraint for: " << gamma.GetName()
1942 << ". Type of constraint: " << type << std::endl;
1943
1944 // Get the sigma from the hist
1945 // (the relative uncertainty)
1946 const double sigmaRel = uncertHist->GetBinContent(TH1BinNumber);
1947
1948 // If the sigma is <= 0,
1949 // do cont create the term
1950 if( sigmaRel <= 0 ){
1951 cxcoutI(HistFactory) << "Not creating constraint term for "
1952 << gamma.GetName()
1953 << " because sigma = " << sigmaRel
1954 << " (sigma<=0)"
1955 << " (TH1 bin number = " << TH1BinNumber << ")"
1956 << std::endl;
1957 gamma.setConstant(true);
1958 continue;
1959 }
1960
1961 // set reasonable ranges for gamma parameters
1962 gamma.setMax( 1 + 5*sigmaRel );
1963 gamma.setMin( 0. );
1964
1965 // Make Constraint Term
1966 std::string constrName = string(gamma.GetName()) + "_constraint";
1967 std::string nomName = string("nom_") + gamma.GetName();
1968 std::string sigmaName = string(gamma.GetName()) + "_sigma";
1969 std::string poisMeanName = string(gamma.GetName()) + "_poisMean";
1970
1971 if( type == Constraint::Gaussian ) {
1972
1973 // Type 1 : RooGaussian
1974
1975 // Make sigma
1976
1977 RooConstVar constrSigma( sigmaName.c_str(), sigmaName.c_str(), sigmaRel );
1978
1979 // Make "observed" value
1980 RooRealVar constrNom(nomName.c_str(), nomName.c_str(), 1.0,0,10);
1981 constrNom.setConstant( true );
1982
1983 // Make the constraint:
1984 RooGaussian gauss( constrName.c_str(), constrName.c_str(),
1985 constrNom, gamma, constrSigma );
1986
1987 proto->import( gauss, RecycleConflictNodes() );
1988
1989 // Give reasonable starting point for pre-fit errors by setting it to the absolute sigma
1990 // Mostly useful for pre-fit plotting.
1991 gamma.setError(sigmaRel);
1992 } else if( type == Constraint::Poisson ) {
1993
1994 double tau = 1/sigmaRel/sigmaRel; // this is correct Poisson equivalent to a Gaussian with mean 1 and stdev sigma
1995
1996 // Make nominal "observed" value
1997 RooRealVar constrNom(nomName.c_str(), nomName.c_str(), tau);
1998 constrNom.setMin(0);
1999 constrNom.setConstant( true );
2000
2001 // Make the scaling term
2002 std::string scalingName = string(gamma.GetName()) + "_tau";
2003 RooConstVar poissonScaling( scalingName.c_str(), scalingName.c_str(), tau);
2004
2005 // Make mean for scaled Poisson
2006 RooProduct constrMean( poisMeanName.c_str(), poisMeanName.c_str(), RooArgSet(gamma, poissonScaling) );
2007 //proto->import( constrSigma, RecycleConflictNodes() );
2008 //proto->import( constrSigma );
2009
2010 // Type 2 : RooPoisson
2011 RooPoisson pois(constrName.c_str(), constrName.c_str(), constrNom, constrMean);
2012 pois.setNoRounding(true);
2013 proto->import( pois, RecycleConflictNodes() );
2014
2015 if (std::string(gamma.GetName()).find("gamma_stat") != std::string::npos) {
2016 // Give reasonable starting point for pre-fit errors.
2017 // Mostly useful for pre-fit plotting.
2018 gamma.setError(sigmaRel);
2019 }
2020
2021 } else {
2022
2023 std::cout << "Error: Did not recognize Stat Error constraint term type: "
2024 << type << " for : " << paramHist.GetName() << std::endl;
2025 throw hf_exc();
2026 }
2027
2028 // If the sigma value is less
2029 // than a supplied threshold,
2030 // set the variable to constant
2031 if( sigmaRel < minSigma ) {
2032 cxcoutW(HistFactory) << "Warning: Bin " << i << " = " << sigmaRel
2033 << " and is < " << minSigma
2034 << ". Setting: " << gamma.GetName() << " to constant"
2035 << std::endl;
2036 gamma.setConstant(true);
2037 }
2038
2039 constraintTermNames.push_back( constrName );
2040 ConstraintTerms.add( *proto->pdf(constrName) );
2041
2042 // Add the "observed" value to the
2043 // list of global observables:
2044 RooArgSet* globalSet = const_cast<RooArgSet*>(proto->set("globalObservables"));
2045
2046 RooRealVar* nomVarInWorkspace = proto->var(nomName);
2047 if( ! globalSet->contains(*nomVarInWorkspace) ) {
2048 globalSet->add( *nomVarInWorkspace );
2049 }
2050
2051 } // end loop over parameters
2052
2053 return ConstraintTerms;
2054
2055}
2056
2057} // namespace RooStats
2058} // namespace HistFactory
2059
#define cxcoutPHF
Definition: HFMsgService.h:18
#define cxcoutFHF
Definition: HFMsgService.h:21
#define cxcoutIHF
Definition: HFMsgService.h:17
#define cxcoutWHF
Definition: HFMsgService.h:19
#define alpha_Low
#define alpha_High
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define cxcoutI(a)
Definition: RooMsgService.h:89
#define cxcoutW(a)
Definition: RooMsgService.h:97
#define cxcoutF(a)
#define cxcoutE(a)
#define cxcoutP(a)
Definition: RooMsgService.h:93
#define ClassImp(name)
Definition: Rtypes.h:375
#define R__ASSERT(e)
Definition: TError.h:118
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 name[80]
Definition: TGX11.cxx:110
float xmin
Definition: THbookFile.cxx:95
float xmax
Definition: THbookFile.cxx:95
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition: TString.cxx:2456
const char * proto
Definition: civetweb.c:17502
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
Definition: ParamHistFunc.h:24
const RooArgSet * get(Int_t masterIdx) const
Definition: ParamHistFunc.h:46
void setConstant(bool constant)
const RooArgList & paramList() const
Definition: ParamHistFunc.h:34
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...
Definition: RooAbsArg.h:71
void Print(Option_t *options=nullptr) const override
Print the object to the defaultPrintStream().
Definition: RooAbsArg.h:321
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
Definition: RooAbsArg.cxx:246
bool contains(const RooAbsArg &var) const
Check if collection contains an argument with the same name as var.
bool empty() const
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
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition: RooAbsData.h:62
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)
Definition: RooAbsReal.h:173
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:56
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,...
Definition: RooBinning.h:27
RooCategory is an object to represent discrete states.
Definition: RooCategory.h:28
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.
Definition: RooConstVar.h:26
The RooDataHist is a container class to hold N-dimensional binned data.
Definition: RooDataHist.h:39
RooDataSet is a container class to hold unbinned data.
Definition: RooDataSet.h:55
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.
Definition: RooFitResult.h:40
Plain Gaussian p.d.f.
Definition: RooGaussian.h:24
Switches the message service to a different level while the instance is alive.
Definition: RooHelpers.h:42
RooHistFunc implements a real-valued function sampled from a multidimensional histogram.
Definition: RooHistFunc.h:31
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.
RooCategory & method2D()
RooCategory & methodND()
RooCategory & method1D()
Poisson pdf.
Definition: RooPoisson.h:19
void setNoRounding(bool flag=true)
Switch off/on rounding of x to the nearest integer.
Definition: RooPoisson.h:34
A RooProduct represents the product of a given set of RooAbsReal objects.
Definition: RooProduct.h:29
The class RooRealSumPdf implements a PDF constructed from a sum of functions:
Definition: RooRealSumPdf.h:24
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:40
void setVal(double value) override
Set value of variable to 'value'.
Definition: RooRealVar.cxx:254
void setMin(const char *name, double value)
Set minimum of name range to given value.
Definition: RooRealVar.cxx:460
void setBins(Int_t nBins, const char *name=nullptr)
Create a uniform binning under name 'name' for this variable.
Definition: RooRealVar.cxx:407
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
std::string GetName()
Definition: Asimov.h:31
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:65
void Print(std::ostream &=std::cout)
Definition: Channel.cxx:75
HistFactory::StatErrorConfig & GetStatErrorConfig()
get information about threshold for statistical uncertainties and constraint term
Definition: Channel.h:72
RooStats::HistFactory::Data & GetData()
get data object
Definition: Channel.h:59
std::vector< RooStats::HistFactory::Sample > & GetSamples()
get vector of samples for this channel
Definition: Channel.h:77
std::string GetName() const
get name of channel
Definition: Channel.h:43
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)
RooArgList createStatConstraintTerms(RooWorkspace *proto, std::vector< std::string > &constraintTerms, ParamHistFunc &paramHist, 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
void SetFunctionsToPreprocess(std::vector< std::string > lines)
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)
RooDataSet * MergeDataSets(RooWorkspace *combined, std::vector< std::unique_ptr< RooWorkspace > > &wspace_vec, std::vector< std::string > const &channel_names, std::string const &dataSetName, RooArgList const &obsList, RooCategory *channelCat)
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)
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...
RooWorkspace * MakeCombinedModel(std::vector< std::string >, std::vector< std::unique_ptr< RooWorkspace > > &)
The RooStats::HistFactory::Measurement class can be used to construct a model by combining multiple R...
Definition: Measurement.h:31
std::map< std::string, double > & GetGammaSyst()
Definition: Measurement.h:122
std::map< std::string, double > & GetLogNormSyst()
Definition: Measurement.h:124
std::map< std::string, double > & GetNoSyst()
Definition: Measurement.h:125
std::vector< std::string > & GetPOIList()
get vector of PoI names
Definition: Measurement.h:51
std::map< std::string, double > & GetUniformSyst()
Definition: Measurement.h:123
std::vector< std::string > & GetConstantParams()
get vector of all constant parameters
Definition: Measurement.h:60
std::vector< RooStats::HistFactory::Channel > & GetChannels()
Definition: Measurement.h:105
std::vector< RooStats::HistFactory::Asimov > & GetAsimovDatasets()
get vector of defined Asimov Datasets
Definition: Measurement.h:80
std::vector< std::string > GetPreprocessFunctions() const
Returns a list of defined preprocess function expressions.
double GetLumi()
retrieve integrated luminosity
Definition: Measurement.h:89
Configuration for an un- constrained overall systematic to scale sample normalisations.
Definition: Systematics.h:77
std::string GetName() const
Definition: Systematics.h:84
Configuration for a constrained overall systematic to scale sample normalisations.
Definition: Systematics.h:49
const std::string & GetName() const
Definition: Systematics.h:56
std::string GetName() const
get name of sample
Definition: Sample.h:82
std::vector< RooStats::HistFactory::NormFactor > & GetNormFactorList()
Definition: Sample.h:109
*Un*constrained bin-by-bin variation of affected histogram.
Definition: Systematics.h:270
const TH1 * GetInitialShape() const
Definition: Systematics.h:286
Constrained bin-by-bin variation of affected histogram.
Definition: Systematics.h:221
Constraint::Type GetConstraintType() const
Definition: Systematics.h:260
const TH1 * GetErrorHist() const
Definition: Systematics.h:252
Constraint::Type GetConstraintType() const
Definition: Systematics.h:384
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition: ModelConfig.h:30
void GuessObsAndNuisance(const RooAbsData &data, bool printModelConfig=true)
Makes sensible guesses of observables, parameters of interest and nuisance parameters if one or multi...
Definition: ModelConfig.cxx:66
virtual void SetParametersOfInterest(const RooArgSet &set)
Specify parameters of interest.
Definition: ModelConfig.h:100
const RooArgSet * GetObservables() const
get RooArgSet for observables (return nullptr if not existing)
Definition: ModelConfig.h:246
The RooWorkspace is a persistable container for RooFit projects.
Definition: RooWorkspace.h:43
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.
bool saveSnapshot(const char *name, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
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 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.
const RooArgSet * set(const char *name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
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
Definition: TArrayD.h:43
Class to manage histogram axis.
Definition: TAxis.h:30
Bool_t IsVariableBinSize() const
Definition: TAxis.h:137
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:478
const TArrayD * GetXbins() const
Definition: TAxis.h:131
Double_t GetXmax() const
Definition: TAxis.h:135
Double_t GetXmin() const
Definition: TAxis.h:134
Int_t GetNbins() const
Definition: TAxis.h:121
TH1 is the base class of all histogram classes in ROOT.
Definition: TH1.h:58
TAxis * GetZaxis()
Definition: TH1.h:324
virtual Int_t GetNbinsY() const
Definition: TH1.h:296
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8930
virtual Int_t GetNbinsZ() const
Definition: TH1.h:297
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:7091
TAxis * GetXaxis()
Definition: TH1.h:322
virtual Int_t GetNbinsX() const
Definition: TH1.h:295
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...
Definition: TH1.cxx:9073
TAxis * GetYaxis()
Definition: TH1.h:323
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition: TH1.cxx:5178
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition: TH1.cxx:5146
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...
Definition: TH1.cxx:9089
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:5025
TObject * Clone(const char *newname="") const override
Make a complete copy of the underlying object.
Definition: TH1.cxx:2727
const char * GetName() const override
Returns name of object.
Definition: TNamed.h:47
Mother of all ROOT objects.
Definition: TObject.h:41
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:207
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:970
Stopwatch class.
Definition: TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
Definition: TStopwatch.cxx:58
Basic string class.
Definition: TString.h:136
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:692
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:2345
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 Import(const char *state, TH1 &histo)
RooCmdArg WeightVar(const char *name, bool reinterpretAsWeight=false)
double beta(double x, double y)
Calculates the beta function.
double gamma(double x)
VecExpr< UnaryOp< Sqrt< T >, VecExpr< A, T, D >, T >, T, D > sqrt(const VecExpr< A, T, D > &rhs)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition: Common.h:18
@ HistFactory
Definition: RooGlobalFunc.h:63
@ ObjectHandling
Definition: RooGlobalFunc.h:62
Namespace for the RooStats classes.
Definition: Asimov.h:19
static constexpr double gauss
const char * Name
Definition: TXMLSetup.cxx:67