Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HistFactoryModelUtils.cxx
Go to the documentation of this file.
1/**
2 * \ingroup HistFactory
3 */
4
5// A set of utils for navegating HistFactory models
6#include <stdexcept>
7#include <typeinfo>
8
10#include "RooAbsPdf.h"
11#include "RooArgSet.h"
12#include "RooArgList.h"
13#include "RooSimultaneous.h"
14#include "RooCategory.h"
15#include "RooRealVar.h"
16#include "RooProdPdf.h"
17#include "TH1.h"
18
20
21namespace RooStats{
22namespace HistFactory{
23
24
25 std::string channelNameFromPdf( RooAbsPdf* channelPdf ) {
26 std::string channelPdfName = channelPdf->GetName();
27 std::string ChannelName = channelPdfName.substr(6, channelPdfName.size() );
28 return ChannelName;
29 }
30
32
33 bool verbose=false;
34
35 if(verbose) std::cout << "Getting the RooRealSumPdf for the channel: "
36 << sim_channel->GetName() << std::endl;
37
38 // Now, get the RooRealSumPdf
39 // ie the channel WITHOUT constraints
40 RooAbsPdf* sum_pdf = nullptr;
41 bool FoundSumPdf=false;
42 std::unique_ptr<RooArgSet> components{sim_channel->getComponents()};
43 for (auto *sum_pdf_arg : *components) {
44 std::string NodeClassName = sum_pdf_arg->ClassName();
45 if( NodeClassName == std::string("RooRealSumPdf") ) {
46 FoundSumPdf=true;
47 sum_pdf = static_cast<RooAbsPdf*>(sum_pdf_arg);
48 break;
49 }
50 }
51 if( ! FoundSumPdf ) {
52 if(verbose) {
53 std::cout << "Failed to find RooRealSumPdf for channel: " << sim_channel->GetName() << std::endl;
54 components->Print("V");
55 }
56 sum_pdf=nullptr;
57 //throw std::runtime_error("Failed to find RooRealSumPdf for channel");
58 }
59 else {
60 if(verbose) std::cout << "Found RooRealSumPdf: " << sum_pdf->GetName() << std::endl;
61 }
62
63 return sum_pdf;
64
65 }
66
67
68 void FactorizeHistFactoryPdf(const RooArgSet &observables, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) {
69 // utility function to factorize constraint terms from a pdf
70 // (from G. Petrucciani)
71 const std::type_info & id = typeid(pdf);
72 if (id == typeid(RooProdPdf)) {
73 RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf);
74 RooArgList list(prod->pdfList());
75 for (int i = 0, n = list.size(); i < n; ++i) {
76 RooAbsPdf *pdfi = static_cast<RooAbsPdf *>(list.at(i));
77 FactorizeHistFactoryPdf(observables, *pdfi, obsTerms, constraints);
78 }
79 } else if (id == typeid(RooSimultaneous)) { //|| id == typeid(RooSimultaneousOpt)) {
80 RooSimultaneous *sim = dynamic_cast<RooSimultaneous *>(&pdf);
81 std::unique_ptr<RooAbsCategoryLValue> cat{static_cast<RooAbsCategoryLValue *>(sim->indexCat().Clone())};
82 for (int ic = 0, nc = cat->numBins((const char *)nullptr); ic < nc; ++ic) {
83 cat->setBin(ic);
84 FactorizeHistFactoryPdf(observables, *sim->getPdf(cat->getCurrentLabel()), obsTerms, constraints);
85 }
86 } else if (pdf.dependsOn(observables)) {
87 if (!obsTerms.contains(pdf)) obsTerms.add(pdf);
88 } else {
89 if (!constraints.contains(pdf)) constraints.add(pdf);
90 }
91 }
92
93
94 bool getStatUncertaintyFromChannel( RooAbsPdf* channel, ParamHistFunc*& paramfunc, RooArgList* gammaList ) {
95
96 bool verbose=false;
97
98 // Find the servers of this channel
99 bool FoundParamHistFunc=false;
100 std::unique_ptr<RooArgSet> components{channel->getComponents()};
101 for( auto *paramfunc_arg : *components) {
102 std::string NodeName = paramfunc_arg->GetName();
103 std::string NodeClassName = paramfunc_arg->ClassName();
104 if( NodeClassName != std::string("ParamHistFunc") ) continue;
105 if( NodeName.find("mc_stat_") != std::string::npos ) {
106 FoundParamHistFunc=true;
107 paramfunc = static_cast<ParamHistFunc*>(paramfunc_arg);
108 break;
109 }
110 }
111 if( ! FoundParamHistFunc || !paramfunc ) {
112 if(verbose) std::cout << "Failed to find ParamHistFunc for channel: " << channel->GetName() << std::endl;
113 return false;
114 }
115
116 // Now, get the set of gamma's
117 gammaList = const_cast<RooArgList*>(&( paramfunc->paramList()));
118 if(verbose) gammaList->Print("V");
119
120 return true;
121
122 }
123
124
125 void getDataValuesForObservables( std::map< std::string, std::vector<double> >& ChannelBinDataMap,
126 RooAbsData* data, RooAbsPdf* pdf ) {
127
128 bool verbose=false;
129
130 RooSimultaneous* simPdf = static_cast<RooSimultaneous*>(pdf);
131
132 // get category label
133 RooCategory* cat = nullptr;
134 for (auto* temp : *data->get()) {
135 if( strcmp(temp->ClassName(),"RooCategory")==0){
136 cat = static_cast<RooCategory*>(temp);
137 break;
138 }
139 }
140 if(verbose) {
141 if(!cat) std::cout <<"didn't find category"<< std::endl;
142 else std::cout <<"found category"<< std::endl;
143 }
144
145 if (!cat) {
146 std::cerr <<"Category not found"<< std::endl;
147 return;
148 }
149
150 // split dataset
151 std::vector<std::unique_ptr<RooAbsData>> dataByCategory{data->split(*cat)};
152
153 // loop over channels
154 auto channelCat = static_cast<RooCategory const*>(&simPdf->indexCat());
155 for (const auto& nameIdx : *channelCat) {
156
157 // Get pdf associated with state from simpdf
158 RooAbsPdf* pdftmp = simPdf->getPdf(nameIdx.first.c_str());
159
160 std::string ChannelName = pdftmp->GetName(); //tt->GetName();
161 if(verbose) std::cout << "Getting data for channel: " << ChannelName << std::endl;
162 ChannelBinDataMap[ ChannelName ] = std::vector<double>();
163
164 auto found = std::find_if(dataByCategory.begin(), dataByCategory.end(), [&](auto const &item) {
165 return nameIdx.first == item->GetName();
166 });
167 RooAbsData *dataForChan = found != dataByCategory.end() ? found->get() : nullptr;
168 if(verbose) dataForChan->Print();
169
170 // Generate observables defined by the pdf associated with this state
171 std::unique_ptr<RooArgSet> obstmp{pdftmp->getObservables(*dataForChan->get())};
172 RooRealVar* obs = (static_cast<RooRealVar*>(obstmp->first()));
173 if(verbose) obs->Print();
174
175 //double expected = pdftmp->expectedEvents(*obstmp);
176
177 // set value to desired value (this is just an example)
178 // double obsVal = obs->getVal();
179 // set obs to desired value of observable
180 // obs->setVal( obsVal );
181 //double fracAtObsValue = pdftmp->getVal(*obstmp);
182
183 // get num events expected in bin for obsVal
184 // double nu = expected * fracAtObsValue;
185
186 // multidimensional way to get n
187 // credit goes to P. Hamilton
188 std::vector<double> &channelBin = ChannelBinDataMap[ChannelName];
189 channelBin.reserve(dataForChan->numEntries());
190 for (int i = 0; i < dataForChan->numEntries(); i++) {
191 const RooArgSet *tmpargs = dataForChan->get(i);
192 if (verbose)
193 tmpargs->Print();
194 const double n = dataForChan->weight();
195 if (verbose)
196 std::cout << "n" << i << " = " << n << std::endl;
197 channelBin.push_back(n);
198 }
199
200 } // End Loop Over Categories
201 }
202
203
205 RooAbsReal*& pois_nom, RooRealVar*& tau ) {
206 // Given a set of constraint terms,
207 // find the poisson constraint for the
208 // given gamma and return the mean
209 // as well as the 'tau' parameter
210
211 bool verbose=false;
212
213 // To get the constraint term, loop over all constraint terms
214 // and look for the gamma_stat name as well as '_constraint'
215
216 bool FoundConstraintTerm=false;
217 RooAbsPdf* constraintTerm=nullptr;
218 for (auto *term_constr : *constraints) {
219 std::string TermName = term_constr->GetName();
220 if( term_constr->dependsOn( *gamma_stat) ) {
221 if( TermName.find("_constraint")!=std::string::npos ) {
222 FoundConstraintTerm=true;
223 constraintTerm = static_cast<RooAbsPdf*>(term_constr);
224 break;
225 }
226 }
227 }
228 if( FoundConstraintTerm==false ) {
229 std::cout << "Error: Couldn't find constraint term for parameter: " << gamma_stat->GetName()
230 << " among constraints: " << constraints->GetName() << std::endl;
231 constraints->Print("V");
232 throw std::runtime_error("Failed to find Gamma ConstraintTerm");
233 return -1;
234 }
235
236 /*
237 RooAbsPdf* constraintTerm = (RooAbsPdf*) constraints->find( constraintTermName.c_str() );
238 if( constraintTerm == nullptr ) {
239 std::cout << "Error: Couldn't find constraint term: " << constraintTermName
240 << " for parameter: " << gamma_stat->GetName()
241 << std::endl;
242 throw std::runtime_error("Failed to find Gamma ConstraintTerm");
243 return -1;
244 }
245 */
246
247 // Find the "data" of the poisson term
248 // This is the nominal value
249 bool FoundNomMean=false;
250 for (RooAbsArg * term_pois : constraintTerm->servers()) {
251 std::string serverName = term_pois->GetName();
252 //std::cout << "Checking Server: " << serverName << std::endl;
253 if( serverName.find("nom_")!=std::string::npos ) {
254 FoundNomMean = true;
255 pois_nom = static_cast<RooRealVar*>(term_pois);
256 }
257 }
258 if( !FoundNomMean || !pois_nom ) {
259 std::cout << "Error: Did not find Nominal Pois Mean parameter in gamma constraint term PoissonMean: "
260 << constraintTerm->GetName() << std::endl;
261 throw std::runtime_error("Failed to find Nom Pois Mean");
262 }
263 else {
264 if(verbose) std::cout << "Found Poisson 'data' term: " << pois_nom->GetName() << std::endl;
265 }
266
267 // Taking the constraint term (a Poisson), find
268 // the "mean" which is the product: gamma*tau
269 // Then, from that mean, find tau
270 RooAbsArg * pois_mean_arg = nullptr;
271 for (RooAbsArg * arg : constraintTerm->servers()) {
272 if( arg->dependsOn( *gamma_stat ) ) {
273 pois_mean_arg = arg;
274 break;
275 }
276 }
277 if( !pois_mean_arg ) {
278 std::cout << "Error: Did not find PoissonMean parameter in gamma constraint term: "
279 << constraintTerm->GetName() << std::endl;
280 throw std::runtime_error("Failed to find PoissonMean");
281 return -1;
282 }
283 else {
284 if(verbose) std::cout << "Found Poisson 'mean' term: " << pois_mean_arg->GetName() << std::endl;
285 }
286
287 bool FoundTau=false;
288 for(RooAbsArg* term_in_product : pois_mean_arg->servers()) {
289 std::string serverName = term_in_product->GetName();
290 //std::cout << "Checking Server: " << serverName << std::endl;
291 if( serverName.find("_tau")!=std::string::npos ) {
292 FoundTau = true;
293 tau = static_cast<RooRealVar*>(term_in_product);
294 }
295 }
296 if( !FoundTau || !tau ) {
297 std::cout << "Error: Did not find Tau parameter in gamma constraint term PoissonMean: "
298 << pois_mean_arg->GetName() << std::endl;
299 throw std::runtime_error("Failed to find Tau");
300 }
301 else {
302 if(verbose) std::cout << "Found Poisson 'tau' term: " << tau->GetName() << std::endl;
303 }
304
305 return 0;
306
307 }
308
309
310
311} // close RooStats namespace
312} // close HistFactory namespace
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
const RooArgList & paramList() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
void Print(Option_t *options=nullptr) const override
Print the object to the defaultPrintStream().
Definition RooAbsArg.h:239
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
RooFit::OwningPtr< RooArgSet > getComponents() const
Create a RooArgSet with all components (branch nodes) of the expression tree headed by this object.
const RefCountList_t & servers() const
List of all servers of this object.
Definition RooAbsArg.h:146
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:89
Abstract base class for objects that represent a discrete value that can be set from the outside,...
void setBin(Int_t ibin, const char *rangeName=nullptr) override
Set category to i-th fit bin, which is the i-th registered state.
bool contains(const char *name) const
Check if collection contains an argument with a specific name.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
virtual double weight() const =0
virtual const RooArgSet * get() const
Definition RooAbsData.h:99
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
Definition RooAbsData.h:207
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
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
Object to represent discrete states.
Definition RooCategory.h:28
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:35
const RooArgList & pdfList() const
Definition RooProdPdf.h:70
Variable that can be changed from the outside.
Definition RooRealVar.h:37
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
RooAbsPdf * getPdf(RooStringView catName) const
Return the p.d.f associated with the given index category name.
const RooAbsCategoryLValue & indexCat() const
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
bool getStatUncertaintyFromChannel(RooAbsPdf *channel, ParamHistFunc *&paramfunc, RooArgList *gammaList)
void FactorizeHistFactoryPdf(const RooArgSet &, RooAbsPdf &, RooArgList &, RooArgList &)
void getDataValuesForObservables(std::map< std::string, std::vector< double > > &ChannelBinDataMap, RooAbsData *data, RooAbsPdf *simPdf)
int getStatUncertaintyConstraintTerm(RooArgList *constraints, RooRealVar *gamma_stat, RooAbsReal *&pois_nom, RooRealVar *&tau)
RooAbsPdf * getSumPdfFromChannel(RooAbsPdf *channel)
std::string channelNameFromPdf(RooAbsPdf *channelPdf)
const Int_t n
Definition legend1.C:16
Namespace for the RooStats classes.
Definition CodegenImpl.h:67