Logo ROOT   6.16/01
Reference Guide
Measurement.cxx
Go to the documentation of this file.
1// @(#)root/roostats:$Id$
2// Author: Kyle Cranmer, George Lewis
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::HistFactory::Measurement
12 * \ingroup HistFactory
13The RooStats::HistFactory::Measurement class can be used to construct a model
14by combining multiple RooStats::HistFactory::Channel objects. It also allows
15to set some general properties like the integrated luminosity, its relative
16uncertainty or the functional form of constraints on nuisance parameters.
17*/
18
19
20#include <ctime>
21#include <iostream>
22#include <algorithm>
23#include <sys/stat.h>
24#include "TSystem.h"
25#include "TTimeStamp.h"
26
29
30using namespace std;
31
33
34
36 fPOI(), fLumi( 1.0 ), fLumiRelErr( .10 ),
37 fBinLow( 0 ), fBinHigh( 1 ), fExportOnly( false )
38{
39 // standard constructor
40}
41
42/*
43RooStats::HistFactory::Measurement::Measurement(const Measurement& other) :
44 POI( other.POI ), Lumi( other.Lumi ), LumiRelErr( other.LumiRelErr ),
45 BinLow( other.BinLow ), BinHigh( other.BinHigh ), ExportOnly( other.ExportOnly ),
46 channels( other.channels ), OutputFilePrefix( other.outputFilePrefix ),
47 constantParams( other.constantParams ), { ; }
48*/
49
51 TNamed( Name, Title ),
52 fPOI(), fLumi( 1.0 ), fLumiRelErr( .10 ),
53 fBinLow( 0 ), fBinHigh( 1 ), fExportOnly( false )
54{
55 // standard constructor specifying name and title of measurement
56}
57
58
60{
61 // set a parameter in the model to be constant
62 // the parameter does not have to exist yet, the information will be used when
63 // the model is actually created
64
65 // Check if the parameter is already set constant
66 // We don't need to set it constant twice,
67 // and we issue a warning in case this is a hint
68 // of a possible bug
69
70 if( std::find(fConstantParams.begin(), fConstantParams.end(), param) != fConstantParams.end() ) {
71 std::cout << "Warning: Setting parameter: " << param
72 << " to constant, but it is already listed as constant. "
73 << "You may ignore this warning."
74 << std::endl;
75 return;
76 }
77
78 fConstantParams.push_back( param );
79
80}
81
82void RooStats::HistFactory::Measurement::SetParamValue( const std::string& param, double value )
83{
84 // set parameter of the model to given value
85
86 // Check if this parameter is already set to a value
87 // If so, issue a warning
88 // (Not sure if we want to throw an exception here, or
89 // issue a warning and move along. Thoughts?)
90 if( fParamValues.find(param) != fParamValues.end() ) {
91 std::cout << "Warning: Chainging parameter: " << param
92 << " value from: " << fParamValues[param]
93 << " to: " << value
94 << std::endl;
95 }
96
97 // Store the parameter and its value
98 std::cout << "Setting parameter: " << param
99 << " value to " << value
100 << std::endl;
101
102 fParamValues[param] = value;
103
104}
105
106void RooStats::HistFactory::Measurement::AddPreprocessFunction( std::string name, std::string expression, std::string dependencies )
107{
108 // Add a preprocessed function by giving the function a name,
109 // a functional expression, and a string with a bracketed list of dependencies (eg "SigXsecOverSM[0,3]")
110
111 PreprocessFunction func(name, expression, dependencies);
112 AddFunctionObject(func);
113
114}
115
116
118{
119 // returns a list of defined proprocess function expressions
120
121 std::vector<std::string> PreprocessFunctionExpressions;
122 for( unsigned int i = 0; i < fFunctionObjects.size(); ++i ) {
123 std::string expression = fFunctionObjects.at(i).GetCommand();
124 PreprocessFunctionExpressions.push_back( expression );
125 }
126 return PreprocessFunctionExpressions;
127}
128
129void RooStats::HistFactory::Measurement::AddGammaSyst(std::string syst, double uncert)
130{
131 // set constraint term for given systematic to Gamma distribution
132
133 fGammaSyst[syst] = uncert;
134}
135
136void RooStats::HistFactory::Measurement::AddLogNormSyst(std::string syst, double uncert)
137{
138 // set constraint term for given systematic to LogNormal distribution
139
140 fLogNormSyst[syst] = uncert;
141}
142
144{
145 // set constraint term for given systematic to uniform distribution
146
147 fUniformSyst[syst] = 1.0; // Is this parameter simply a dummy?
148}
149
151{
152 // define given systematics to have no external constraint
153
154 fNoSyst[syst] = 1.0; // dummy value
155}
156
157
159{
160 // is the given channel part of this measurement
161
162 for( unsigned int i = 0; i < fChannels.size(); ++i ) {
163
164 Channel& chan = fChannels.at(i);
165 if( chan.GetName() == ChanName ) {
166 return true;
167 }
168
169 }
170
171 return false;
172
173}
174
176{
177 // get channel with given name from this measurement
178 // throws an exception in case the channel is not found
179
180 for( unsigned int i = 0; i < fChannels.size(); ++i ) {
181
182 Channel& chan = fChannels.at(i);
183 if( chan.GetName() == ChanName ) {
184 return chan;
185 }
186
187 }
188
189 // If we get here, we didn't find the channel
190
191 std::cout << "Error: Did not find channel: " << ChanName
192 << " in measurement: " << GetName() << std::endl;
193 throw hf_exc();
194
195 // No Need to return after throwing exception
196 // return RooStats::HistFactory::BadChannel;
197
198
199}
200
201/*
202 void RooStats::HistFactory::Measurement::Print( Option_t* option ) const {
203 RooStats::HistFactory::Measurement::Print( std::cout );
204 return;
205 }
206*/
207
209{
210 // print information about measurement object in tree-like structure to given stream
211
212 stream << "Measurement Name: " << GetName()
213 << "\t OutputFilePrefix: " << fOutputFilePrefix
214 << "\t POI: ";
215 for(unsigned int i = 0; i < fPOI.size(); ++i) {
216 stream << fPOI.at(i);
217 }
218 stream << "\t Lumi: " << fLumi
219 << "\t LumiRelErr: " << fLumiRelErr
220 << "\t BinLow: " << fBinLow
221 << "\t BinHigh: " << fBinHigh
222 << "\t ExportOnly: " << fExportOnly
223 << std::endl;
224
225
226 if( fConstantParams.size() != 0 ) {
227 stream << "Constant Params: ";
228 for( unsigned int i = 0; i < fConstantParams.size(); ++i ) {
229 stream << " " << fConstantParams.at(i);
230 }
231 stream << std::endl;
232 }
233
234 if( fFunctionObjects.size() != 0 ) {
235 stream << "Preprocess Functions: ";
236 for( unsigned int i = 0; i < fFunctionObjects.size(); ++i ) {
237 stream << " " << fFunctionObjects.at(i).GetCommand();
238 }
239 stream << std::endl;
240 }
241
242 if( fChannels.size() != 0 ) {
243 stream << "Channels:" << std::endl;
244 for( unsigned int i = 0; i < fChannels.size(); ++i ) {
245 fChannels.at(i).Print( stream );
246 }
247 }
248
249 std::cout << "End Measurement: " << GetName() << std::endl;
250
251}
252
253
254
255void RooStats::HistFactory::Measurement::PrintXML( std::string directory, std::string newOutputPrefix )
256{
257 // create XML files for this measurement in the given directory
258 // XML files can be configured with a different output prefix
259
260 // Create an XML file for this measurement
261 // First, create the XML driver
262 // Then, create xml files for each channel
263
264 // First, check that the directory exists:
265 auto testExists = [](const std::string& theDirectory) {
266 void* dir = gSystem->OpenDirectory(theDirectory.c_str());
267 bool exists = dir != nullptr;
268 if (exists)
270
271 return exists;
272 };
273
274 if ( !directory.empty() && !testExists(directory) ) {
275 int success = gSystem->MakeDirectory(directory.c_str() );
276 if( success != 0 ) {
277 std::cout << "Error: Failed to make directory: " << directory << std::endl;
278 throw hf_exc();
279 }
280 }
281
282 // If supplied new Prefix, use that one:
283
284 std::cout << "Printing XML Files for measurement: " << GetName() << std::endl;
285
286 std::string XMLName = std::string(GetName()) + ".xml";
287 if( directory != "" ) XMLName = directory + "/" + XMLName;
288
289 ofstream xml( XMLName.c_str() );
290
291 if( ! xml.is_open() ) {
292 std::cout << "Error opening xml file: " << XMLName << std::endl;
293 throw hf_exc();
294 }
295
296
297 // Add the time
298 xml << "<!--" << std::endl;
299 xml << "This xml file created automatically on: " << std::endl;
300/*
301 time_t t = time(0); // get time now
302 struct tm * now = localtime( &t );
303 xml << (now->tm_year + 1900) << '-'
304 << (now->tm_mon + 1) << '-'
305 << now->tm_mday
306 << std::endl;
307*/
308 // LM: use TTimeStamp
309 TTimeStamp t;
310 UInt_t year = 0;
311 UInt_t month = 0;
312 UInt_t day = 0;
313 t.GetDate(true, 0, &year, &month, &day);
314 xml << year << '-'
315 << month << '-'
316 << day
317 << std::endl;
318
319 xml << "-->" << std::endl;
320
321 // Add the doctype
322 xml << "<!DOCTYPE Combination SYSTEM 'HistFactorySchema.dtd'>" << std::endl << std::endl;
323
324 // Add the combination name
325 if (newOutputPrefix.empty() ) newOutputPrefix = fOutputFilePrefix;
326 xml << "<Combination OutputFilePrefix=\"" << newOutputPrefix /*OutputFilePrefix*/ << "\" >" << std::endl << std::endl;
327
328 // Add the Preprocessed Functions
329 for( unsigned int i = 0; i < fFunctionObjects.size(); ++i ) {
330 RooStats::HistFactory::PreprocessFunction func = fFunctionObjects.at(i);
331 func.PrintXML(xml);
332 /*
333 xml << "<Function Name=\"" << func.GetName() << "\" "
334 << "Expression=\"" << func.GetExpression() << "\" "
335 << "Dependents=\"" << func.GetDependents() << "\" "
336 << "/>" << std::endl;
337 */
338 }
339
340 xml << std::endl;
341
342 // Add the list of channels
343 for( unsigned int i = 0; i < fChannels.size(); ++i ) {
344 xml << " <Input>" << "./";
345 if (!directory.empty() ) xml << directory << "/";
346 xml << GetName() << "_" << fChannels.at(i).GetName() << ".xml" << "</Input>" << std::endl;
347 }
348
349 xml << std::endl;
350
351 // Open the Measurement, Set Lumi
352 xml << " <Measurement Name=\"" << GetName() << "\" "
353 << "Lumi=\"" << fLumi << "\" "
354 << "LumiRelErr=\"" << fLumiRelErr << "\" "
355 //<< "BinLow=\"" << fBinLow << "\" "
356 // << "BinHigh=\"" << fBinHigh << "\" "
357 << "ExportOnly=\"" << (fExportOnly ? std::string("True") : std::string("False")) << "\" "
358 << " >" << std::endl;
359
360
361 // Set the POI
362 xml << " <POI>" ;
363 for(unsigned int i = 0; i < fPOI.size(); ++i) {
364 if(i==0) xml << fPOI.at(i);
365 else xml << " " << fPOI.at(i);
366 }
367 xml << "</POI> " << std::endl;
368
369 // Set the Constant Parameters
370 if(fConstantParams.size()) {
371 xml << " <ParamSetting Const=\"True\">";
372 for( unsigned int i = 0; i < fConstantParams.size(); ++i ) {
373 if (i==0) xml << fConstantParams.at(i);
374 else xml << " " << fConstantParams.at(i);;
375 }
376 xml << "</ParamSetting>" << std::endl;
377 }
378
379 // Set the Parameters with new Constraint Terms
380 std::map<std::string, double>::iterator ConstrItr;
381
382 // Gamma
383 for( ConstrItr = fGammaSyst.begin(); ConstrItr != fGammaSyst.end(); ++ConstrItr ) {
384 xml << "<ConstraintTerm Type=\"Gamma\" RelativeUncertainty=\""
385 << ConstrItr->second << "\">" << ConstrItr->first
386 << "</ConstraintTerm>" << std::endl;
387 }
388 // Uniform
389 for( ConstrItr = fUniformSyst.begin(); ConstrItr != fUniformSyst.end(); ++ConstrItr ) {
390 xml << "<ConstraintTerm Type=\"Uniform\" RelativeUncertainty=\""
391 << ConstrItr->second << "\">" << ConstrItr->first
392 << "</ConstraintTerm>" << std::endl;
393 }
394 // LogNormal
395 for( ConstrItr = fLogNormSyst.begin(); ConstrItr != fLogNormSyst.end(); ++ConstrItr ) {
396 xml << "<ConstraintTerm Type=\"LogNormal\" RelativeUncertainty=\""
397 << ConstrItr->second << "\">" << ConstrItr->first
398 << "</ConstraintTerm>" << std::endl;
399 }
400 // NoSyst
401 for( ConstrItr = fNoSyst.begin(); ConstrItr != fNoSyst.end(); ++ConstrItr ) {
402 xml << "<ConstraintTerm Type=\"NoSyst\" RelativeUncertainty=\""
403 << ConstrItr->second << "\">" << ConstrItr->first
404 << "</ConstraintTerm>" << std::endl;
405 }
406
407
408 // Close the Measurement
409 xml << " </Measurement> " << std::endl << std::endl;
410
411 // Close the combination
412 xml << "</Combination>" << std::endl;
413
414 xml.close();
415
416 // Now, make the xml files
417 // for the individual channels:
418
419 std::string prefix = std::string(GetName()) + "_";
420
421 for( unsigned int i = 0; i < fChannels.size(); ++i ) {
422 fChannels.at(i).PrintXML( directory, prefix );
423 }
424
425
426 std::cout << "Finished printing XML files" << std::endl;
427
428}
429
430
431
433{
434 // A measurement, once fully configured, can be saved into a ROOT
435 // file. This will persitify the Measurement object, along with any
436 // channels and samples that have been added to it. It can then be
437 // loaded, potentially modified, and used to create new models.
438
439 // Write every histogram to the file.
440 // Edit the measurement to point to this file
441 // and to point to each histogram in this file
442 // Then write the measurement itself.
443
444 // Create a tempory measurement
445 // (This is the one that is actually written)
446 RooStats::HistFactory::Measurement outMeas( *this );
447
448 std::string OutputFileName = file->GetName();
449
450 // Collect all histograms from file:
451 // HistCollector collector;
452
453
454 for( unsigned int chanItr = 0; chanItr < outMeas.fChannels.size(); ++chanItr ) {
455
456 // Go to the main directory
457 // in the file
458 file->cd();
459 file->Flush();
460
461 // Get the name of the channel:
462 RooStats::HistFactory::Channel& channel = outMeas.fChannels.at( chanItr );
463 std::string chanName = channel.GetName();
464
465
466 if( ! channel.CheckHistograms() ) {
467 std::cout << "Measurement.writeToFile(): Channel: " << chanName
468 << " has uninitialized histogram pointers" << std::endl;
469 throw hf_exc();
470 return;
471 }
472
473 // Get and cache the histograms for this channel:
474 //collector.CollectHistograms( channel );
475 // Do I need this...?
476 // channel.CollectHistograms();
477
478 // Make a directory to store the histograms
479 // for this channel
480
481 TDirectory* chanDir = file->mkdir( (chanName + "_hists").c_str() );
482 if( chanDir == NULL ) {
483 std::cout << "Error: Cannot create channel " << (chanName + "_hists")
484 << std::endl;
485 throw hf_exc();
486 }
487 chanDir->cd();
488
489 // Save the data:
490 TDirectory* dataDir = chanDir->mkdir( "data" );
491 if( dataDir == NULL ) {
492 std::cout << "Error: Cannot make directory " << chanDir << std::endl;
493 throw hf_exc();
494 }
495 dataDir->cd();
496
497 channel.fData.writeToFile( OutputFileName, GetDirPath(dataDir) );
498
499 /*
500 // Write the data file to this directory
501 TH1* hData = channel.data.GetHisto();
502 hData->Write();
503
504 // Set the location of the data
505 // in the output measurement
506
507 channel.data.InputFile = OutputFileName;
508 channel.data.HistoName = hData->GetName();
509 channel.data.HistoPath = GetDirPath( dataDir );
510 */
511
512 // Loop over samples:
513
514 for( unsigned int sampItr = 0; sampItr < channel.GetSamples().size(); ++sampItr ) {
515
516 RooStats::HistFactory::Sample& sample = channel.GetSamples().at( sampItr );
517 std::string sampName = sample.GetName();
518
519 std::cout << "Writing sample: " << sampName << std::endl;
520
521 file->cd();
522 chanDir->cd();
523 TDirectory* sampleDir = chanDir->mkdir( sampName.c_str() );
524 if( sampleDir == NULL ) {
525 std::cout << "Error: Directory " << sampName << " not created properly" << std::endl;
526 throw hf_exc();
527 }
528 std::string sampleDirPath = GetDirPath( sampleDir );
529
530 if( ! sampleDir ) {
531 std::cout << "Error making directory: " << sampName
532 << " in directory: " << chanName
533 << std::endl;
534 throw hf_exc();
535 }
536
537 // Write the data file to this directory
538 sampleDir->cd();
539
540 sample.writeToFile( OutputFileName, sampleDirPath );
541 /*
542 TH1* hSample = sample.GetHisto();
543 if( ! hSample ) {
544 std::cout << "Error getting histogram for sample: "
545 << sampName << std::endl;
546 throw -1;
547 }
548 sampleDir->cd();
549 hSample->Write();
550
551 sample.InputFile = OutputFileName;
552 sample.HistoName = hSample->GetName();
553 sample.HistoPath = sampleDirPath;
554 */
555
556 // Write the histograms associated with
557 // systematics
558
559 /* THIS IS WHAT I"M COMMENTING
560 sample.GetStatError().writeToFile( OutputFileName, sampleDirPath );
561
562 // Must write all systematics that contain internal histograms
563 // (This is not all systematics)
564
565 for( unsigned int i = 0; i < sample.GetHistoSysList().size(); ++i ) {
566 sample.GetHistoSysList().at(i).writeToFile( OutputFileName, sampleDirPath );
567 }
568 for( unsigned int i = 0; i < sample.GetHistoFactorList().size(); ++i ) {
569 sample.GetHistoFactorList().at(i).writeToFile( OutputFileName, sampleDirPath );
570 }
571 for( unsigned int i = 0; i < sample.GetShapeSysList().size(); ++i ) {
572 sample.GetShapeSysList().at(i).writeToFile( OutputFileName, sampleDirPath );
573 }
574 END COMMENT */
575 /*
576 sample.statError.writeToFile( OutputFileName, sampleDirPath );
577
578 // Now, get the Stat config histograms
579 if( sample.statError.HistoName != "" ) {
580 TH1* hStatError = sample.statError.GetErrorHist();
581 if( ! hStatError ) {
582 std::cout << "Error getting stat error histogram for sample: "
583 << sampName << std::endl;
584 throw -1;
585 }
586 hStatError->Write();
587
588 sample.statError.InputFile = OutputFileName;
589 sample.statError.HistoName = hStatError->GetName();
590 sample.statError.HistoPath = sampleDirPath;
591
592 }
593 */
594
595 }
596
597 }
598
599
600 // Finally, write the measurement itself:
601
602 std::cout << "Saved all histograms" << std::endl;
603
604 file->cd();
605 outMeas.Write();
606
607 std::cout << "Saved Measurement" << std::endl;
608
609}
610
611
613{
614 // Return the directory's path,
615 // stripped of unnecessary prefixes
616
617 std::string path = dir->GetPath();
618
619 if( path.find(":") != std::string::npos ) {
620 size_t index = path.find(":");
621 path.replace( 0, index+1, "" );
622 }
623
624 path = path + "/";
625
626 return path;
627
628 /*
629 if( path.find(":") != std::string::npos ) {
630 size_t index = path.find(":");
631 SampleName.replace( 0, index, "" );
632 }
633
634 // Remove the file:
635 */
636
637}
638
639
640
642{
643 // The most common way to add histograms to channels is to have them
644 // stored in ROOT files and to give HistFactory the location of these
645 // files. This means providing the path to the ROOT file and the path
646 // and name of the histogram within that file. When providing these
647 // in a script, HistFactory doesn't load the histogram from the file
648 // right away. Instead, once all such histograms have been supplied,
649 // one should run this method to open all ROOT files and to copy and
650 // save all necessary histograms.
651
652 for( unsigned int chanItr = 0; chanItr < fChannels.size(); ++chanItr) {
653
654 RooStats::HistFactory::Channel& chan = fChannels.at( chanItr );
655
656 chan.CollectHistograms();
657
658 }
659
660}
661
662
663
unsigned int UInt_t
Definition: RtypesCore.h:42
#define ClassImp(name)
Definition: Rtypes.h:363
R__EXTERN TSystem * gSystem
Definition: TSystem.h:540
This class encapsulates all information for the statistical interpretation of one experiment.
Definition: Channel.h:26
HistFactory::Data fData
Definition: Channel.h:85
std::string GetName()
get name of channel
Definition: Channel.h:39
std::vector< RooStats::HistFactory::Sample > & GetSamples()
get vector of samples for this channel
Definition: Channel.h:71
void writeToFile(std::string FileName, std::string DirName)
Definition: Data.cxx:52
The RooStats::HistFactory::Measurement class can be used to construct a model by combining multiple R...
Definition: Measurement.h:30
void AddGammaSyst(std::string syst, double uncert)
std::string GetDirPath(TDirectory *dir)
void AddLogNormSyst(std::string syst, double uncert)
void PrintXML(std::string Directory="", std::string NewOutputPrefix="")
Print to a stream.
RooStats::HistFactory::Channel & GetChannel(std::string)
void SetParamValue(const std::string &param, double value)
Set a parameter to a specific value (And optionally fix it)
Definition: Measurement.cxx:82
void AddUniformSyst(std::string syst)
void PrintTree(std::ostream &=std::cout)
void AddNoSyst(std::string syst)
void AddConstantParam(const std::string &param)
Add a parameter to be set as constant (Similar to ParamSetting method below)
Definition: Measurement.cxx:59
void AddPreprocessFunction(std::string name, std::string expression, std::string dependencies)
std::vector< std::string > GetPreprocessFunctions()
std::vector< RooStats::HistFactory::Channel > fChannels
Channels that make up this measurement.
Definition: Measurement.h:140
std::string GetName()
get name of sample
Definition: Sample.h:82
void writeToFile(std::string FileName, std::string DirName)
Definition: Sample.cxx:75
Describe directory structure in memory.
Definition: TDirectory.h:34
virtual const char * GetPath() const
Returns the full path of the directory.
Definition: TDirectory.cxx:987
virtual Bool_t cd(const char *path=0)
Change current directory to "this" directory.
Definition: TDirectory.cxx:497
virtual TDirectory * mkdir(const char *name, const char *title="")
Create a sub-directory "a" or a hierarchy of sub-directories "a/b/c/...".
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
virtual Int_t Write(const char *name=0, Int_t option=0, Int_t bufsize=0)
Write this object to the current directory.
Definition: TObject.cxx:785
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition: TSystem.cxx:852
virtual void * OpenDirectory(const char *name)
Open a directory. Returns 0 if directory does not exist.
Definition: TSystem.cxx:843
virtual int MakeDirectory(const char *name)
Make a directory.
Definition: TSystem.cxx:834
The TTimeStamp encapsulates seconds and ns since EPOCH.
Definition: TTimeStamp.h:71
UInt_t GetDate(Bool_t inUTC=kTRUE, Int_t secOffset=0, UInt_t *year=0, UInt_t *month=0, UInt_t *day=0) const
Return date in form of 19971224 (i.e.
Definition: TTimeStamp.cxx:353
std::string GetName(const std::string &scope_name)
Definition: Cppyy.cxx:146
Definition: file.py:1
STL namespace.
const char * Name
Definition: TXMLSetup.cxx:66
const char * Title
Definition: TXMLSetup.cxx:67