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