89 HistoToWorkspaceFactoryFast::Configuration
const &cfg)
91 std::unique_ptr<TFile> outFile;
92 std::ofstream tableFile;
97 cxcoutIHF <<
"Making Model and Measurements (Fast) for measurement: " << measurement.
GetName() << std::endl;
101 cxcoutIHF <<
"using lumi = " << measurement.
GetLumi() <<
" and lumiError = " << lumiError
102 <<
" including bins between " << measurement.
GetBinLow() <<
" and " << measurement.
GetBinHigh() << std::endl;
104 std::ostringstream parameterMessage;
105 parameterMessage <<
"fixing the following parameters:" << std::endl;
108 parameterMessage <<
" " << *itr <<
'\n';
110 cxcoutIHF << parameterMessage.str();
112 std::string rowTitle = measurement.
GetName();
114 std::vector<std::unique_ptr<RooWorkspace>> channel_workspaces;
115 std::vector<std::string> channel_names;
124 size_t pos = prefix.rfind(
'/');
125 if (pos != std::string::npos) {
126 std::string outputDir = prefix.substr(0,pos);
127 cxcoutDHF <<
"Checking if output directory : " << outputDir <<
" - exists" << std::endl;
129 cxcoutDHF <<
"Output directory : " << outputDir <<
" - does not exist, try to create" << std::endl;
132 std::string fullOutputDir = std::string(
gSystem->
pwd()) + std::string(
"/") + outputDir;
133 cxcoutEHF <<
"Error: Failed to make output directory: " << fullOutputDir << std::endl;
141 cxcoutIHF <<
"Creating the output file: " << outputFileName << std::endl;
142 outFile = std::make_unique<TFile>(outputFileName.c_str(),
"recreate");
145 tableFile.open(measurement.
GetOutputFilePrefix() +
"_results.table", std::ios::out | std::ios::app);
147 cxcoutIHF <<
"Creating the HistoToWorkspaceFactoryFast factory" << std::endl;
148 HistoToWorkspaceFactoryFast factory{measurement, cfg};
152 cxcoutIHF <<
"Setting preprocess functions" << std::endl;
156 tableFile <<
" " << rowTitle <<
" &";
159 for(
unsigned int chanItr = 0; chanItr < measurement.
GetChannels().
size(); ++chanItr ) {
161 HistFactory::Channel& channel = measurement.
GetChannels().at( chanItr );
162 if( ! channel.CheckHistograms() ) {
163 cxcoutEHF <<
"MakeModelAndMeasurementsFast: Channel: " << channel.GetName()
164 <<
" has uninitialized histogram pointers" << std::endl;
169 std::string ch_name = channel.GetName();
170 cxcoutPHF <<
"Starting to process channel: " << ch_name << std::endl;
171 channel_names.push_back(ch_name);
172 std::unique_ptr<RooWorkspace> ws_single{factory.MakeSingleChannelModel( measurement, channel )};
174 if (cfg.createPerRegionWorkspaces) {
177 + ch_name +
"_" + rowTitle +
"_model.root";
178 cxcoutIHF <<
"Opening File to hold channel: " << ChannelFileName << std::endl;
179 std::unique_ptr<TFile> chanFile{
TFile::Open( ChannelFileName.c_str(),
"RECREATE" )};
184 meas_chan.GetChannels().clear();
185 meas_chan.GetChannels().push_back( channel );
186 cxcoutIHF <<
"About to write channel measurement to file" << std::endl;
187 meas_chan.writeToFile( chanFile.get() );
188 cxcoutPHF <<
"Successfully wrote channel to file" << std::endl;
197 cxcoutWHF <<
"Can't do fit for: " << measurement.
GetName()
198 <<
", no parameter of interest" << std::endl;
200 if(ws_single->data(
"obsData")) {
202 ch_name,
"obsData", *outFile, tableFile);
205 ch_name,
"asimovData", *outFile, tableFile);
212 channel_workspaces.emplace_back(std::move(ws_single));
222 std::unique_ptr<RooWorkspace> ws{factory.MakeCombinedModel(channel_names, channel_workspaces)};
225 HistoToWorkspaceFactoryFast::ConfigureWorkspaceForMeasurement(
"simPdf", ws.get(), measurement);
232 + rowTitle +
"_model.root";
233 cxcoutPHF <<
"Writing combined workspace to file: " << CombinedFileName << std::endl;
234 std::unique_ptr<TFile> combFile{
TFile::Open( CombinedFileName.c_str(),
"RECREATE" )};
235 if( combFile ==
nullptr ) {
236 cxcoutEHF <<
"Error: Failed to open file " << CombinedFileName << std::endl;
239 combFile->WriteTObject(ws.get());
240 cxcoutPHF <<
"Writing combined measurement to file: " << CombinedFileName << std::endl;
247 cxcoutWHF <<
"Can't do fit for: " << measurement.
GetName()
248 <<
", no parameter of interest" << std::endl;
251 if(ws->data(
"obsData")){
253 "obsData", *outFile, tableFile);
257 "asimovData", *outFile, tableFile);
262 tableFile <<
" \\\\ \n";
272 RooWorkspace &combined, std::string channel, std::string data_name,
273 TFile &outFile, std::ostream &tableStream)
277 auto combined_config =
static_cast<ModelConfig *
>(combined.
obj(
"ModelConfig"));
278 if(!combined_config){
279 cxcoutEHF <<
"Error: no ModelConfig found in Measurement: "
280 << MeasurementName << std::endl;
286 cxcoutEHF <<
"Error: Failed to get dataset: " << data_name
287 <<
" in measurement: " << MeasurementName << std::endl;
291 const RooArgSet* POIs = combined_config->GetParametersOfInterest();
293 cxcoutEHF <<
"Not Fitting Model for measurement: " << MeasurementName
294 <<
", no poi found" << std::endl;
299 RooAbsPdf* model = combined_config->GetPdf();
300 if( model==
nullptr ) {
301 cxcoutEHF <<
"Error: Failed to find pdf in ModelConfig: " << combined_config->
GetName()
308 if( combined_config->GetNuisanceParameters() ) {
309 PoiPlusNuisance.
add( *combined_config->GetNuisanceParameters() );
311 PoiPlusNuisance.
add( *combined_config->GetParametersOfInterest() );
312 combined.
saveSnapshot(
"InitialValues", PoiPlusNuisance);
316 cxcoutPHF <<
"\n---------------"
317 <<
"\nDoing "<< channel <<
" Fit"
318 <<
"\n---------------\n\n" << std::endl;
320 model->
fitTo(*simData, Minos(
true), PrintLevel(printLevel));
324 if( POIs->
empty() ) {
325 cxcoutWHF <<
"WARNING: No POIs found in measurement: " << MeasurementName << std::endl;
330 for (
auto const *poi : static_range_cast<RooRealVar *>(*POIs)) {
331 cxcoutIHF <<
"printing results for " << poi->
GetName()
332 <<
" at " << poi->
getVal()<<
" high "
342 const auto oldPrecision = tableStream.precision();
343 tableStream.precision(4);
345 tableStream.precision(oldPrecision);
348 std::unique_ptr<RooAbsReal> nll{model->
createNLL(*simData)};
349 std::unique_ptr<RooAbsReal> profile{nll->createProfile(*poi)};
351 std::unique_ptr<RooPlot> frame{poi->
frame()};
356 TCanvas profileLikelihoodCanvas{channel.c_str(),
"",800,600};
357 nll->plotOn(frame.get(), ShiftToZero(), LineColor(
kRed), LineStyle(
kDashed));
358 profile->plotOn(frame.get());
359 frame->SetMinimum(0);
360 frame->SetMaximum(2.);
362 std::string profilePlotName = FileNamePrefix+
"_"+channel+
"_"+MeasurementName+
"_profileLR.eps";
363 profileLikelihoodCanvas.SaveAs( profilePlotName.c_str() );
373 if( channel_dir ==
nullptr ) {
374 cxcoutEHF <<
"Error: Failed to make channel directory: " << channel << std::endl;
378 if( summary_dir ==
nullptr ) {
379 cxcoutEHF <<
"Error: Failed to make Summary directory for channel: "
380 << channel << std::endl;
388 double* curve_x=curve->
GetX();
390 std::vector<double> x_arr(curve_N);
391 std::vector<double> y_arr_nll(curve_N);
393 for(
int i=0; i<curve_N; i++){
397 y_arr_nll[i]=nll->getVal();
400 TGraph g{curve_N, x_arr.data(), y_arr_nll.data()};
401 g.SetName( (FileNamePrefix +
"_nll").c_str() );
414 cxcoutIHF <<
"In Fit Model" << std::endl;
416 if(!combined_config){
417 cxcoutEHF <<
"no model config " <<
"ModelConfig" <<
" exiting" << std::endl;
423 cxcoutEHF <<
"no data " << data_name <<
" exiting" << std::endl;
429 cxcoutEHF <<
"no poi " << data_name <<
" exiting" << std::endl;
434 model->
fitTo(*simData, Minos(
true), PrintLevel(1));
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
R__EXTERN TStyle * gStyle
R__EXTERN TSystem * gSystem
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
RooAbsArg * first() const
Abstract base class for binned and unbinned datasets.
Abstract interface for all probability density functions.
RooFit::OwningPtr< RooAbsReal > createNLL(RooAbsData &data, CmdArgs_t const &... cmdArgs)
Construct representation of -log(L) of PDF with given dataset.
RooFit::OwningPtr< RooFitResult > fitTo(RooAbsData &data, CmdArgs_t const &... cmdArgs)
Fit PDF to given dataset.
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual double getMax(const char *name=nullptr) const
Get maximum of currently defined range.
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
RooPlot * frame(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
Create a new RooPlot on the heap with a drawing frame initialized for this object,...
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
One-dimensional graphical representation of a real-valued function.
static RooMsgService & instance()
Return reference to singleton instance.
bool isActive(T self, RooFit::MsgTopic topic, RooFit::MsgLevel level)
Check if logging is active for given object/topic/RooFit::MsgLevel combination.
Plot frame and a container for graphics objects within that frame.
void SetTitle(const char *name) override
Set the title of the RooPlot to 'title'.
void addObject(TObject *obj, Option_t *drawOptions="", bool invisible=false)
Add a generic object to this plot.
RooAbsRealLValue * getPlotVar() const
Variable that can be changed from the outside.
void setVal(double value) override
Set value of variable to 'value'.
double getErrorLo() const
double getErrorHi() const
The RooStats::HistFactory::Measurement class can be used to construct a model by combining multiple R...
void writeToFile(TFile *file)
A measurement, once fully configured, can be saved into a ROOT file.
double GetLumiRelErr()
retrieve relative uncertainty on luminosity
std::vector< std::string > & GetConstantParams()
get vector of all constant parameters
std::vector< RooStats::HistFactory::Channel > & GetChannels()
std::string GetOutputFilePrefix()
retrieve prefix for output files
std::vector< std::string > GetPreprocessFunctions() const
Returns a list of defined preprocess function expressions.
double GetLumi()
retrieve integrated luminosity
std::string GetPOI(unsigned int i=0)
get name of PoI at given index
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return nullptr if not existing)
RooAbsPdf * GetPdf() const
get model PDF (return nullptr if pdf has not been specified or does not exist)
Persistable container for RooFit projects.
TObject * obj(RooStringView name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
bool saveSnapshot(RooStringView, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
RooAbsData * data(RooStringView name) const
Retrieve dataset (binned or unbinned) with given name. A null pointer is returned if not found.
bool loadSnapshot(const char *name)
Load the values and attributes of the parameters in the snapshot saved with the given name.
virtual void SetLineColor(Color_t lcolor)
Set the line color.
TDirectory * mkdir(const char *name, const char *title="", Bool_t returnExistingDirectory=kFALSE) override
Create a sub-directory "a" or a hierarchy of sub-directories "a/b/c/...".
Int_t WriteTObject(const TObject *obj, const char *name=nullptr, Option_t *option="", Int_t bufsize=0) override
Write object obj to this directory.
Describe directory structure in memory.
virtual Bool_t cd()
Change current directory to "this" directory.
virtual TDirectory * mkdir(const char *name, const char *title="", Bool_t returnExistingDirectory=kFALSE)
Create a sub-directory "a" or a hierarchy of sub-directories "a/b/c/...".
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
A TGraph is an object made of two arrays X and Y with npoints each.
Use the TLine constructor to create a simple line.
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
const char * GetName() const override
Returns name of object.
const char * GetTitle() const override
Returns title of object.
void SetPadBorderMode(Int_t mode=1)
void SetCanvasBorderMode(Int_t mode=1)
virtual void * OpenDirectory(const char *name)
Open a directory. Returns 0 if directory does not exist.
virtual int MakeDirectory(const char *name)
Make a directory.
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
void FitModelAndPlot(const std::string &measurementName, const std::string &fileNamePrefix, RooWorkspace &, std::string, std::string, TFile &, std::ostream &)
RooFit::OwningPtr< RooWorkspace > MakeModelAndMeasurementFast(RooStats::HistFactory::Measurement &measurement, HistoToWorkspaceFactoryFast::Configuration const &cfg={})
void FitModel(RooWorkspace *, std::string data_name="obsData")
void FormatFrameForLikelihood(RooPlot *frame, std::string xTitle=std::string("#sigma / #sigma_{SM}"), std::string yTitle=std::string("-log likelihood"))