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