Logo ROOT  
Reference Guide
ModelConfig.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Kyle Cranmer,
5 * Lorenzo Moneta,
6 * Gregory Schott,
7 * Wouter Verkerke,
8 * Sven Kreiss
9 *
10 * Copyright (c) 2023, CERN
11 *
12 * Redistribution and use in source and binary forms,
13 * with or without modification, are permitted according to the terms
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
15 */
16
17/** \class RooStats::ModelConfig
18 \ingroup Roostats
19
20ModelConfig is a simple class that holds configuration information specifying how a model
21should be used in the context of various RooStats tools. A single model can be used
22in different ways, and this class should carry all that is needed to specify how it should be used.
23ModelConfig requires a workspace to be set.
24
25A ModelConfig holds sets of parameters of the likelihood function that have different interpretations:
26- **Parameter of interest** Parameters that are measured (*i.e.* fitted).
27- **Nuisance parameters** Parameters that are fitted, but their post-fit value is not interesting. Often,
28they might be constrained because external knowledge about them exists, *e.g.* from external measurements.
29- **Constraint parameters** No direct use in RooFit/RooStats. Can be used by the user for bookkeeping.
30- **Observables** Parameters that have been measured externally, *i.e.* they exist in a dataset. These are not fitted,
31but read during fitting from the entries of a dataset.
32- **Conditional observables** Observables that are not integrated when the normalisation of the PDF is calculated.
33See *e.g.* `rf306_condpereventerrors` in the RooFit tutorials.
34- **Global observables** Observables that to the fit look like "constant" values, *i.e.* they are not being
35fitted and they are not loaded from a dataset, but some knowledge exists that allows to set them to a
36specific value. Examples:
37-- A signal efficiency measured in a Monte Carlo study.
38-- When constraining a parameter \f$ b \f$, the target value (\f$ b_0 \f$) that this parameter is constrained to:
39\f[
40 \mathrm{Constraint}_b = \mathrm{Gauss}(b_0 \, | \, b, 0.2)
41\f]
42*/
43
44#include <RooFit/ModelConfig.h>
45
46#include <RooMsgService.h>
47#include <RooRealVar.h>
48
49#include <sstream>
50
52
53namespace {
54
55void removeConstantParameters(RooAbsCollection &coll)
56{
57 RooArgSet constSet;
58 for (auto const *myarg : static_range_cast<RooRealVar *>(coll)) {
59 if (myarg->isConstant())
60 constSet.add(*myarg);
61 }
62 coll.remove(constSet);
63}
64
65} // namespace
66
67using namespace std;
68
69namespace RooStats {
70
71////////////////////////////////////////////////////////////////////////////////
72/// Makes sensible guesses of observables, parameters of interest
73/// and nuisance parameters if one or multiple have been set by the creator of this ModelConfig.
74///
75/// Defaults:
76/// - Observables: determined from data,
77/// - Global observables: explicit obs - obs from data - constant observables
78/// - Parameters of interest: empty,
79/// - Nuisance parameters: all parameters except parameters of interest
80///
81/// We use nullptr to mean not set, so we don't want to fill
82/// with empty RooArgSets.
83
84void ModelConfig::GuessObsAndNuisance(const RooAbsData &data, bool printModelConfig)
85{
86
87 // observables
88 if (!GetObservables()) {
89 const RooArgSet *obs = GetPdf()->getObservables(data);
90 SetObservables(*obs);
91 delete obs;
92 }
93 // global observables
94 if (!GetGlobalObservables()) {
96 const RooArgSet *obs = GetPdf()->getObservables(data);
97 co.remove(*obs);
98 removeConstantParameters(co);
99 if (co.getSize() > 0)
101
102 // TODO BUG This does not work as observables with the same name are already in the workspace.
103 /*
104 RooArgSet o(*GetObservables());
105 o.remove(co);
106 SetObservables(o);
107 */
108 delete obs;
109 }
110
111 // parameters
112 // if (!GetParametersOfInterest()) {
113 // SetParametersOfInterest(RooArgSet());
114 // }
115 if (!GetNuisanceParameters()) {
116 const RooArgSet *params = GetPdf()->getParameters(data);
117 RooArgSet p(*params);
118 p.remove(*GetParametersOfInterest());
119 removeConstantParameters(p);
120 if (p.getSize() > 0)
122 delete params;
123 }
124
125 // print Modelconfig as an info message
126
127 if (printModelConfig) {
128 std::ostream &oldstream = RooPrintable::defaultPrintStream(&ccoutI(InputArguments));
129 Print();
131 }
132}
133
134////////////////////////////////////////////////////////////////////////////////
135/// print contents of Model on the default print stream
136/// It can be changed using RooPrintable
137
139{
140 ostream &os = RooPrintable::defaultPrintStream();
141
142 os << endl << "=== Using the following for " << GetName() << " ===" << endl;
143
144 // args
145 if (GetObservables()) {
146 os << "Observables: ";
147 GetObservables()->Print("");
148 }
150 os << "Parameters of Interest: ";
152 }
153 if (GetNuisanceParameters()) {
154 os << "Nuisance Parameters: ";
156 }
157 if (GetGlobalObservables()) {
158 os << "Global Observables: ";
160 }
162 os << "Constraint Parameters: ";
164 }
166 os << "Conditional Observables: ";
168 }
169 if (GetProtoData()) {
170 os << "Proto Data: ";
171 GetProtoData()->Print("");
172 }
173
174 // pdfs
175 if (GetPdf()) {
176 os << "PDF: ";
177 GetPdf()->Print("");
178 }
179 if (GetPriorPdf()) {
180 os << "Prior PDF: ";
181 GetPriorPdf()->Print("");
182 }
183
184 // snapshot
185 const RooArgSet *snapshot = GetSnapshot();
186 if (snapshot) {
187 os << "Snapshot: " << endl;
188 snapshot->Print("v");
189 delete snapshot;
190 }
191
192 os << endl;
193}
194
195////////////////////////////////////////////////////////////////////////////////
196/// If a workspace already exists in this ModelConfig, RooWorkspace::merge(ws) will be called
197/// on the existing workspace.
198
200{
201 if (!fRefWS.GetObject()) {
202 fRefWS = &ws;
203 fWSName = ws.GetName();
204 } else {
207 GetWS()->merge(ws);
209 }
210}
211
212////////////////////////////////////////////////////////////////////////////////
213/// get from TRef
214
216{
217 RooWorkspace *ws = dynamic_cast<RooWorkspace *>(fRefWS.GetObject());
218 if (!ws) {
219 coutE(ObjectHandling) << "workspace not set" << endl;
220 return nullptr;
221 }
222 return ws;
223}
224
225////////////////////////////////////////////////////////////////////////////////
226/// save snapshot in the workspace
227/// and use values passed with the set
228
230{
231 if (!GetWS())
232 return;
233
235 if (fSnapshotName.size() > 0)
236 fSnapshotName += "_";
237 fSnapshotName += set.GetName();
238 if (fSnapshotName.size() > 0)
239 fSnapshotName += "_";
240 fSnapshotName += "snapshot";
241 GetWS()->saveSnapshot(fSnapshotName.c_str(), set, true); // import also the given parameter values
242 DefineSetInWS(fSnapshotName.c_str(), set);
243}
244
245////////////////////////////////////////////////////////////////////////////////
246/// Load the snapshot from ws and return the corresponding set with the snapshot values.
247/// User must delete returned RooArgSet.
248
250{
251 if (!GetWS())
252 return 0;
253 if (!fSnapshotName.length())
254 return 0;
255 // calling loadSnapshot will also copy the current parameter values in the workspaces
256 // since we do not want to change the model parameters - we restore the previous ones
257 if (!GetWS()->set(fSnapshotName.c_str()))
258 return 0;
259 RooArgSet snapshotVars(*GetWS()->set(fSnapshotName.c_str()));
260 if (snapshotVars.empty())
261 return 0;
262 // make my snapshot which will contain a copy of the snapshot variables
263 RooArgSet tempSnapshot;
264 snapshotVars.snapshot(tempSnapshot);
265 // load snapshot value from the workspace
266 if (!(GetWS()->loadSnapshot(fSnapshotName.c_str())))
267 return 0;
268 // by doing this snapshotVars will have the snapshot values - make the snapshot to return
269 const RooArgSet *modelSnapshot = dynamic_cast<const RooArgSet *>(snapshotVars.snapshot());
270 // restore now the variables of snapshot in ws to their original values
271 // need to const cast since assign is not const (but in reality in just assign values and does not change the set)
272 // and anyway the set is const
273 snapshotVars.assignFast(tempSnapshot);
274 return modelSnapshot;
275}
276
277////////////////////////////////////////////////////////////////////////////////
278/// load the snapshot from ws if it exists
279
281{
282 if (!GetWS())
283 return;
284 GetWS()->loadSnapshot(fSnapshotName.c_str());
285}
286
287////////////////////////////////////////////////////////////////////////////////
288/// helper functions to avoid code duplication
289
290void ModelConfig::DefineSetInWS(const char *name, const RooArgSet &set)
291{
292 if (!GetWS())
293 return;
294
295 const RooArgSet *prevSet = GetWS()->set(name);
296 if (prevSet) {
297 // be careful not to remove passed set in case it is the same updated
298 if (prevSet != &set)
299 GetWS()->removeSet(name);
300 }
301
302 // suppress warning when we re-define a previously defined set (when set == prevSet )
303 // and set is not removed in that case
306
307 GetWS()->defineSet(name, set, true);
308
310}
311
312////////////////////////////////////////////////////////////////////////////////
313/// internal function to import Pdf in WS
314
316{
317 if (!GetWS())
318 return;
319
320 if (!GetWS()->pdf(pdf.GetName())) {
325 }
326}
327
328////////////////////////////////////////////////////////////////////////////////
329/// internal function to import data in WS
330
332{
333 if (!GetWS())
334 return;
335
336 if (!GetWS()->data(data.GetName())) {
339 GetWS()->import(data);
341 }
342}
343
344////////////////////////////////////////////////////////////////////////////////
345
346bool ModelConfig::SetHasOnlyParameters(const RooArgSet &set, const char *errorMsgPrefix)
347{
348
349 RooArgSet nonparams;
350 for (auto const *arg : set) {
351 if (!arg->isFundamental()) {
352 nonparams.add(*arg);
353 }
354 }
355
356 if (errorMsgPrefix && nonparams.getSize() > 0) {
357 cout << errorMsgPrefix << " ERROR: specified set contains non-parameters: " << nonparams << endl;
358 }
359 return (nonparams.empty());
360}
361
362} // 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
void Print(Option_t *options=nullptr) const override
Print the object to the defaultPrintStream().
Definition: RooAbsArg.h:329
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:301
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:562
RooAbsCollection is an abstract container object that can hold multiple RooAbsArg objects.
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
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.
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition: RooAbsData.h:61
void Print(Option_t *options=nullptr) const override
Print TNamed name and title.
Definition: RooAbsData.h:232
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:56
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition: RooArgSet.h:179
static RooMsgService & instance()
Return reference to singleton instance.
void setGlobalKillBelow(RooFit::MsgLevel level)
RooFit::MsgLevel globalKillBelow() const
static std::ostream & defaultPrintStream(std::ostream *os=nullptr)
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:35
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:166
std::string fSnapshotName
name for RooArgSet that specifies a particular hypothesis
Definition: ModelConfig.h:344
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:299
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:330
const RooArgSet * GetConditionalObservables() const
get RooArgSet for conditional observables (return nullptr if not existing)
Definition: ModelConfig.h:290
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:84
const RooArgSet * GetGlobalObservables() const
get RooArgSet for global observables (return nullptr if not existing)
Definition: ModelConfig.h:296
TRef fRefWS
WS reference used in the file.
Definition: ModelConfig.h:328
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return nullptr if not existing)
Definition: ModelConfig.h:269
const RooArgSet * GetNuisanceParameters() const
get RooArgSet containing the nuisance parameters (return nullptr if not existing)
Definition: ModelConfig.h:272
virtual void SetGlobalObservables(const RooArgSet &set)
Specify the global observables.
Definition: ModelConfig.h:200
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.
bool SetHasOnlyParameters(const RooArgSet &set, const char *errorMsgPrefix=nullptr)
helper function to check that content of a given set is exclusively parameters
const RooArgSet * GetObservables() const
get RooArgSet for observables (return nullptr if not existing)
Definition: ModelConfig.h:287
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:278
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:266
virtual void SetNuisanceParameters(const RooArgSet &set)
Specify the nuisance parameters (parameters that are not POI).
Definition: ModelConfig.h:131
RooAbsPdf * GetPriorPdf() const
get parameters prior pdf (return nullptr if not existing)
Definition: ModelConfig.h:284
The RooWorkspace is a persistable container for RooFit projects.
Definition: RooWorkspace.h:43
bool import(const RooAbsArg &arg, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg())
Import a RooAbsArg object, e.g.
bool saveSnapshot(RooStringView, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
void merge(const RooWorkspace &)
Definition: RooWorkspace.h:100
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:60
@ InputArguments
Definition: RooGlobalFunc.h:63
@ ObjectHandling
Definition: RooGlobalFunc.h:63
Namespace for the RooStats classes.
Definition: Asimov.h:19