Logo ROOT  
Reference Guide
ModelConfig.cxx
Go to the documentation of this file.
1// @(#)root/roostats:$Id$
2// Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke, Sven Kreiss
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/** \class RooStats::ModelConfig
12 \ingroup Roostats
13
14ModelConfig is a simple class that holds configuration information specifying how a model
15should be used in the context of various RooStats tools. A single model can be used
16in different ways, and this class should carry all that is needed to specify how it should be used.
17ModelConfig requires a workspace to be set.
18
19A ModelConfig holds sets of parameters of the likelihood function that have different interpretations:
20- **Parameter of interest** Parameters that are measured (*i.e.* fitted).
21- **Nuisance parameters** Parameters that are fitted, but their post-fit value is not interesting. Often,
22they might be constrained because external knowledge about them exists, *e.g.* from external measurements.
23- **Constraint parameters** No direct use in RooFit/RooStats. Can be used by the user for bookkeeping.
24- **Observables** Parameters that have been measured externally, *i.e.* they exist in a dataset. These are not fitted,
25but read during fitting from the entries of a dataset.
26- **Conditional observables** Observables that are not integrated when the normalisation of the PDF is calculated.
27See *e.g.* `rf306_condpereventerrors` in the RooFit tutorials.
28- **Global observables** Observables that to the fit look like "constant" values, *i.e.* they are not being
29fitted and they are not loaded from a dataset, but some knowledge exists that allows to set them to a
30specific value. Examples:
31-- A signal efficiency measured in a Monte Carlo study.
32-- When constraining a parameter \f$ b \f$, the target value (\f$ b_0 \f$) that this parameter is constrained to:
33\f[
34 \mathrm{Constraint}_b = \mathrm{Gauss}(b_0 \, | \, b, 0.2)
35\f]
36*/
37
39
40#include "RooMsgService.h"
41
43
44#include <sstream>
45
46
48
49using namespace std;
50
51namespace RooStats {
52
53////////////////////////////////////////////////////////////////////////////////
54/// Makes sensible guesses of observables, parameters of interest
55/// and nuisance parameters if one or multiple have been set by the creator of this ModelConfig.
56///
57/// Defaults:
58/// - Observables: determined from data,
59/// - Global observables: explicit obs - obs from data - constant observables
60/// - Parameters of interest: empty,
61/// - Nuisance parameters: all parameters except parameters of interest
62///
63/// We use nullptr to mean not set, so we don't want to fill
64/// with empty RooArgSets.
65
66void ModelConfig::GuessObsAndNuisance(const RooAbsData& data, bool printModelConfig) {
67
68 // observables
69 if (!GetObservables()) {
70 const RooArgSet * obs = GetPdf()->getObservables(data);
71 SetObservables(*obs);
72 delete obs;
73 }
74 // global observables
75 if (!GetGlobalObservables()) {
77 const RooArgSet * obs = GetPdf()->getObservables(data);
78 co.remove(*obs);
80 if(co.getSize()>0)
82
83 // TODO BUG This does not work as observables with the same name are already in the workspace.
84 /*
85 RooArgSet o(*GetObservables());
86 o.remove(co);
87 SetObservables(o);
88 */
89 delete obs;
90 }
91
92 // parameters
93 // if (!GetParametersOfInterest()) {
94 // SetParametersOfInterest(RooArgSet());
95 // }
96 if (!GetNuisanceParameters()) {
97 const RooArgSet * params = GetPdf()->getParameters(data);
98 RooArgSet p(*params);
99 p.remove(*GetParametersOfInterest());
101 if(p.getSize()>0)
103 delete params;
104 }
105
106 // print Modelconfig as an info message
107
108 if (printModelConfig) {
109 std::ostream& oldstream = RooPrintable::defaultPrintStream(&ccoutI(InputArguments));
110 Print();
112 }
113}
114
115////////////////////////////////////////////////////////////////////////////////
116/// print contents of Model on the default print stream
117/// It can be changed using RooPrintable
118
120 ostream& os = RooPrintable::defaultPrintStream();
121
122 os << endl << "=== Using the following for " << GetName() << " ===" << endl;
123
124
125 // args
126 if(GetObservables()){
127 os << "Observables: ";
128 GetObservables()->Print("");
129 }
131 os << "Parameters of Interest: ";
133 }
135 os << "Nuisance Parameters: ";
137 }
139 os << "Global Observables: ";
141 }
143 os << "Constraint Parameters: ";
145 }
147 os << "Conditional Observables: ";
149 }
150 if(GetProtoData()){
151 os << "Proto Data: ";
152 GetProtoData()->Print("");
153 }
154
155 // pdfs
156 if(GetPdf()) {
157 os << "PDF: ";
158 GetPdf()->Print("");
159 }
160 if(GetPriorPdf()) {
161 os << "Prior PDF: ";
162 GetPriorPdf()->Print("");
163 }
164
165 // snapshot
166 const RooArgSet * snapshot = GetSnapshot();
167 if(snapshot) {
168 os << "Snapshot: " << endl;
169 snapshot->Print("v");
170 delete snapshot;
171 }
172
173 os << endl;
174}
175
176////////////////////////////////////////////////////////////////////////////////
177/// If a workspace already exists in this ModelConfig, RooWorkspace::merge(ws) will be called
178/// on the existing workspace.
179
181 if( !fRefWS.GetObject() ) {
182 fRefWS = &ws;
183 fWSName = ws.GetName();
184 }
185 else{
188 GetWS()->merge(ws);
190 }
191}
192
193////////////////////////////////////////////////////////////////////////////////
194/// get from TRef
195
197 RooWorkspace *ws = dynamic_cast<RooWorkspace *>(fRefWS.GetObject() );
198 if(!ws) {
199 coutE(ObjectHandling) << "workspace not set" << endl;
200 return nullptr;
201 }
202 return ws;
203}
204
205////////////////////////////////////////////////////////////////////////////////
206/// save snapshot in the workspace
207/// and use values passed with the set
208
210 if ( !GetWS() ) return;
211
213 if (fSnapshotName.size() > 0) fSnapshotName += "_";
214 fSnapshotName += set.GetName();
215 if (fSnapshotName.size() > 0) fSnapshotName += "_";
216 fSnapshotName += "snapshot";
217 GetWS()->saveSnapshot(fSnapshotName.c_str(), set, true); // import also the given parameter values
218 DefineSetInWS(fSnapshotName.c_str(), set);
219}
220
221////////////////////////////////////////////////////////////////////////////////
222/// Load the snapshot from ws and return the corresponding set with the snapshot values.
223/// User must delete returned RooArgSet.
224
226 if ( !GetWS() ) return 0;
227 if (!fSnapshotName.length()) return 0;
228 // calling loadSnapshot will also copy the current parameter values in the workspaces
229 // since we do not want to change the model parameters - we restore the previous ones
230 if (! GetWS()->set(fSnapshotName.c_str() ) )return 0;
231 RooArgSet snapshotVars(*GetWS()->set(fSnapshotName.c_str() ) );
232 if (snapshotVars.empty()) return 0;
233 // make my snapshot which will contain a copy of the snapshot variables
234 RooArgSet tempSnapshot;
235 snapshotVars.snapshot(tempSnapshot);
236 // load snapshot value from the workspace
237 if (!(GetWS()->loadSnapshot(fSnapshotName.c_str())) ) return 0;
238 // by doing this snapshotVars will have the snapshot values - make the snapshot to return
239 const RooArgSet * modelSnapshot = dynamic_cast<const RooArgSet*>( snapshotVars.snapshot());
240 // restore now the variables of snapshot in ws to their original values
241 // need to const cast since assign is not const (but in reality in just assign values and does not change the set)
242 // and anyway the set is const
243 snapshotVars.assignFast(tempSnapshot);
244 return modelSnapshot;
245}
246
247////////////////////////////////////////////////////////////////////////////////
248/// load the snapshot from ws if it exists
249
251 if ( !GetWS() ) return;
252 GetWS()->loadSnapshot(fSnapshotName.c_str());
253}
254
255////////////////////////////////////////////////////////////////////////////////
256/// helper functions to avoid code duplication
257
258void ModelConfig::DefineSetInWS(const char* name, const RooArgSet& set) {
259 if ( !GetWS() ) return;
260
261 const RooArgSet * prevSet = GetWS()->set(name);
262 if ( prevSet ) {
263 //be careful not to remove passed set in case it is the same updated
264 if (prevSet != &set)
265 GetWS()->removeSet(name);
266 }
267
268 // suppress warning when we re-define a previously defined set (when set == prevSet )
269 // and set is not removed in that case
272
273
274 GetWS()->defineSet(name, set,true);
275
277
278}
279
280////////////////////////////////////////////////////////////////////////////////
281/// internal function to import Pdf in WS
282
284 if ( !GetWS() ) return;
285
286 if (! GetWS()->pdf( pdf.GetName() ) ){
291 }
292}
293
294////////////////////////////////////////////////////////////////////////////////
295/// internal function to import data in WS
296
298 if ( !GetWS() ) return;
299
300 if (! GetWS()->data( data.GetName() ) ){
303 GetWS()->import(data);
305 }
306}
307
308////////////////////////////////////////////////////////////////////////////////
309
310bool ModelConfig::SetHasOnlyParameters(const RooArgSet& set, const char* errorMsgPrefix) {
311
312 RooArgSet nonparams ;
313 for (auto const *arg : set) {
314 if (!arg->isFundamental()) {
315 nonparams.add(*arg) ;
316 }
317 }
318
319 if (errorMsgPrefix && nonparams.getSize()>0) {
320 cout << errorMsgPrefix << " ERROR: specified set contains non-parameters: " << nonparams << endl ;
321 }
322 return (nonparams.empty()) ;
323 }
324
325} // end namespace RooStats
#define coutE(a)
Definition: RooMsgService.h:37
#define ccoutI(a)
Definition: RooMsgService.h:42
const char Option_t
Definition: RtypesCore.h:66
#define ClassImp(name)
Definition: Rtypes.h:375
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
char name[80]
Definition: TGX11.cxx:110
RooArgSet * getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
Definition: RooAbsArg.h:312
void Print(Option_t *options=0) const override
Print the object to the defaultPrintStream().
Definition: RooAbsArg.h:340
RooArgSet * getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
Definition: RooAbsArg.cxx:565
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
void assignFast(const RooAbsCollection &other, bool setValDirty=true) const
Functional equivalent of assign() but assumes this and other collection have same layout.
bool empty() const
void Print(Option_t *options=0) const override
This method must be overridden when a class wants to print itself.
Int_t getSize() const
Return the number of elements in the collection.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition: RooAbsData.h:62
void Print(Option_t *options=0) const override
Print TNamed name and title.
Definition: RooAbsData.h:239
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:57
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition: RooArgSet.h:180
static RooMsgService & instance()
Return reference to singleton instance.
void setGlobalKillBelow(RooFit::MsgLevel level)
RooFit::MsgLevel globalKillBelow() const
static std::ostream & defaultPrintStream(std::ostream *os=0)
Return a reference to the current default stream to use in Print().
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition: ModelConfig.h:30
bool SetHasOnlyParameters(const RooArgSet &set, const char *errorMsgPrefix=0)
helper function to check that content of a given set is exclusively parameters
virtual void SetSnapshot(const RooArgSet &set)
Set parameter values for a particular hypothesis if using a common PDF by saving a snapshot in the wo...
virtual void SetObservables(const RooArgSet &set)
Specify the observables.
Definition: ModelConfig.h:146
std::string fSnapshotName
name for RooArgSet that specifies a particular hypothesis
Definition: ModelConfig.h:301
void ImportPdfInWS(const RooAbsPdf &pdf)
internal function to import Pdf in WS
RooAbsData * GetProtoData() const
get Proto data set (return nullptr if not existing)
Definition: ModelConfig.h:255
void DefineSetInWS(const char *name, const RooArgSet &set)
helper functions to define a set in the WS
std::string fWSName
name of the WS
Definition: ModelConfig.h:287
const RooArgSet * GetConditionalObservables() const
get RooArgSet for conditional observables (return nullptr if not existing)
Definition: ModelConfig.h:249
void GuessObsAndNuisance(const RooAbsData &data, bool printModelConfig=true)
Makes sensible guesses of observables, parameters of interest and nuisance parameters if one or multi...
Definition: ModelConfig.cxx:66
const RooArgSet * GetGlobalObservables() const
get RooArgSet for global observables (return nullptr if not existing)
Definition: ModelConfig.h:252
TRef fRefWS
WS reference used in the file.
Definition: ModelConfig.h:285
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return nullptr if not existing)
Definition: ModelConfig.h:234
const RooArgSet * GetNuisanceParameters() const
get RooArgSet containing the nuisance parameters (return nullptr if not existing)
Definition: ModelConfig.h:237
virtual void SetGlobalObservables(const RooArgSet &set)
Specify the global observables.
Definition: ModelConfig.h:172
void LoadSnapshot() const
load the snapshot from ws if it exists
void Print(Option_t *option="") const override
overload the print method
void ImportDataInWS(RooAbsData &data)
internal function to import data in WS
void SetWS(RooWorkspace &ws) override
Set a workspace that owns all the necessary components for the analysis.
const RooArgSet * GetObservables() const
get RooArgSet for observables (return nullptr if not existing)
Definition: ModelConfig.h:246
const RooArgSet * GetSnapshot() const
get RooArgSet for parameters for a particular hypothesis (return nullptr if not existing)
const RooArgSet * GetConstraintParameters() const
get RooArgSet containing the constraint parameters (return nullptr if not existing)
Definition: ModelConfig.h:240
RooWorkspace * GetWS() const override
get from TRef
RooAbsPdf * GetPdf() const
get model PDF (return nullptr if pdf has not been specified or does not exist)
Definition: ModelConfig.h:231
virtual void SetNuisanceParameters(const RooArgSet &set)
Specify the nuisance parameters (parameters that are not POI).
Definition: ModelConfig.h:119
RooAbsPdf * GetPriorPdf() const
get parameters prior pdf (return nullptr if not existing)
Definition: ModelConfig.h:243
The RooWorkspace is a persistable container for RooFit projects.
Definition: RooWorkspace.h:43
bool saveSnapshot(const char *name, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg())
Import a RooAbsArg object, e.g.
void merge(const RooWorkspace &)
Definition: RooWorkspace.h:99
bool removeSet(const char *name)
Remove a named set from the workspace.
const RooArgSet * set(const char *name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
bool loadSnapshot(const char *name)
Load the values and attributes of the parameters in the snapshot saved with the given name.
bool defineSet(const char *name, const RooArgSet &aset, bool importMissing=false)
Define a named RooArgSet with given constituents.
const char * GetName() const override
Returns name of object.
Definition: TNamed.h:47
TObject * GetObject() const
Return a pointer to the referenced object.
Definition: TRef.cxx:377
RooCmdArg RecycleConflictNodes(bool flag=true)
MsgLevel
Verbosity level for RooMsgService::StreamConfig in RooMsgService.
Definition: RooGlobalFunc.h:61
@ InputArguments
Definition: RooGlobalFunc.h:64
@ ObjectHandling
Definition: RooGlobalFunc.h:64
Namespace for the RooStats classes.
Definition: Asimov.h:19
void RemoveConstantParameters(RooArgSet *set)
Definition: RooStatsUtils.h:69
void ws()
Definition: ws.C:66