REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
TRestDataSetOdds.cxx
1/*************************************************************************
2 * This file is part of the REST software framework. *
3 * *
4 * Copyright (C) 2016 GIFNA/TREX (University of Zaragoza) *
5 * For more information see https://gifna.unizar.es/trex *
6 * *
7 * REST is free software: you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation, either version 3 of the License, or *
10 * (at your option) any later version. *
11 * *
12 * REST is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have a copy of the GNU General Public License along with *
18 * REST in $REST_PATH/LICENSE. *
19 * If not, see https://www.gnu.org/licenses/. *
20 * For the list of contributors see $REST_PATH/CREDITS. *
21 *************************************************************************/
22
103
104#include "TRestDataSetOdds.h"
105
106#include "TRestDataSet.h"
107#include "TRestTools.h"
108
109ClassImp(TRestDataSetOdds);
110
115
130TRestDataSetOdds::TRestDataSetOdds(const char* configFilename, std::string name)
131 : TRestMetadata(configFilename) {
133 Initialize();
134
136}
137
142
147void TRestDataSetOdds::Initialize() { SetSectionName(this->ClassName()); }
148
154 Initialize();
156
157 TiXmlElement* obsDefinition = GetElement("observable");
158 while (obsDefinition != nullptr) {
159 std::string obsName = GetFieldValue("name", obsDefinition);
160 if (obsName.empty() || obsName == "Not defined") {
161 RESTError << "< observable variable key does not contain a name!" << RESTendl;
162 exit(1);
163 } else {
164 fObsName.push_back(obsName);
165 }
166
167 std::string range = GetFieldValue("range", obsDefinition);
168 if (range.empty() || range == "Not defined") {
169 RESTError << "< observable key does not contain a range value!" << RESTendl;
170 exit(1);
171 } else {
172 TVector2 roi = StringTo2DVector(range);
173 fObsRange.push_back(roi);
174 }
175
176 std::string nBins = GetFieldValue("nBins", obsDefinition);
177 if (nBins.empty() || nBins == "Not defined") {
178 RESTError << "< observable key does not contain a nBins value!" << RESTendl;
179 exit(1);
180 } else {
181 fObsNbins.push_back(StringToInteger(nBins));
182 }
183
184 obsDefinition = GetNextElement(obsDefinition);
185 }
186
187 if (fObsName.empty() || fObsRange.empty()) {
188 RESTError << "No observables provided, exiting..." << RESTendl;
189 exit(1);
190 }
191
192 if (fOutputFileName == "") fOutputFileName = GetParameter("outputFileName", "");
193
194 fCut = (TRestCut*)InstantiateChildMetadata("TRestCut");
195}
196
208
209 TRestDataSet dataSet;
210 dataSet.Import(fDataSetName);
211
212 if (fOddsFile.empty()) {
213 auto DF = dataSet.MakeCut(fCut);
214 RESTInfo << "Generating PDFs for dataset: " << fDataSetName << RESTendl;
215 for (size_t i = 0; i < fObsName.size(); i++) {
216 const std::string obsName = fObsName[i];
217 const TVector2 range = fObsRange[i];
218 const std::string histName = "h" + std::string(GetName()) + "_" + obsName;
219 const int nBins = fObsNbins[i];
220 RESTDebug << "\tGenerating PDF for " << obsName << " with range: (" << range.X() << ", "
221 << range.Y() << ") and nBins: " << nBins << RESTendl;
222 auto histo =
223 DF.Histo1D({histName.c_str(), histName.c_str(), nBins, range.X(), range.Y()}, obsName);
224 TH1F* h = static_cast<TH1F*>(histo->DrawClone());
225 RESTDebug << "\tNormalizing by integral = " << h->Integral() << RESTendl;
226 h->Scale(1. / h->Integral());
227 fHistos[obsName] = h;
228 }
229 } else {
230 TFile* f = TFile::Open(fOddsFile.c_str());
231 if (f == nullptr) {
232 RESTError << "Cannot open calibration odds file " << fOddsFile << RESTendl;
233 exit(1);
234 }
235 RESTInfo << "Opening " << fOddsFile << " as oddsFile." << RESTendl;
236 for (size_t i = 0; i < fObsName.size(); i++) {
237 const std::string obsName = fObsName[i];
238 const std::string histName = "h" + std::string(GetName()) + "_" + obsName;
239 TH1F* h = (TH1F*)f->Get(histName.c_str());
240 fHistos[obsName] = h;
241 }
242 }
243
244 auto df = dataSet.GetDataFrame();
245 std::string totName = "";
246 RESTDebug << "Computing log odds from " << fDataSetName << RESTendl;
247 for (const auto& [obsName, histo] : fHistos) {
248 const std::string oddsName = std::string(GetName()) + "_" + obsName;
249 auto GetLogOdds = [&histo = histo](double val) {
250 double odds = histo->GetBinContent(histo->GetXaxis()->FindBin(val));
251 if (odds == 0) return 1000.;
252 return log(1. - odds) - log(odds);
253 };
254
255 if (df.GetColumnType(obsName) != "Double_t") {
256 RESTWarning << "Column " << obsName << " is not of type 'double'. It will be converted."
257 << RESTendl;
258 df = df.Redefine(obsName, "static_cast<double>(" + obsName + ")");
259 }
260 df = df.Define(oddsName, GetLogOdds, {obsName});
261 auto h = df.Histo1D(oddsName);
262
263 if (!totName.empty()) totName += "+";
264 totName += oddsName;
265 }
266
267 RESTDebug << "Computing total log odds" << RESTendl;
268 RESTDebug << "\tTotal log odds = " << totName << RESTendl;
269 df = df.Define(std::string(GetName()) + "_total", totName);
270
271 dataSet.SetDataFrame(df);
272
273 if (!fOutputFileName.empty()) {
275 RESTDebug << "Exporting dataset to " << fOutputFileName << RESTendl;
276 dataSet.Export(fOutputFileName);
277 auto file = TRestRootFileHandle::Open(fOutputFileName, TRestRootFileMode::Update);
278 if (!file) {
279 RESTError << file.Error() << RESTendl;
280 return;
281 }
282 this->Write();
283 RESTDebug << "Writing histograms to " << fOutputFileName << RESTendl;
284 for (const auto& [obsName, histo] : fHistos) histo->Write();
285 if (!file.Close()) RESTError << file.Error() << RESTendl;
286 }
287 }
288}
289
290std::vector<std::tuple<std::string, TVector2, int>> TRestDataSetOdds::GetOddsObservables() {
291 std::vector<std::tuple<std::string, TVector2, int>> obs;
292 for (size_t i = 0; i < fObsName.size(); i++) {
293 if (i >= fObsName.size() || i >= fObsRange.size() || i >= fObsNbins.size()) {
294 RESTError << "Sizes for observables names, ranges and bins do not match!" << RESTendl;
295 break;
296 }
297 obs.push_back(std::make_tuple(fObsName[i], fObsRange[i], fObsNbins[i]));
298 }
299 return obs;
300}
301
302void TRestDataSetOdds::AddOddsObservable(const std::string& name, const TVector2& range, int nbins) {
303 fObsName.push_back(name);
304 fObsRange.push_back(range);
305 fObsNbins.push_back(nbins);
306}
307
308void TRestDataSetOdds::SetOddsObservables(const std::vector<std::tuple<std::string, TVector2, int>>& obs) {
309 fObsName.clear();
310 fObsRange.clear();
311 fObsNbins.clear();
312 for (const auto& [name, range, nbins] : obs) AddOddsObservable(name, range, nbins);
313}
314
315void TRestDataSetOdds::WriteHistograms(TFile* f) const {
316 if (!f) return;
317 f->cd();
318 for (const auto& [name, histo] : fHistos) {
319 if (histo) histo->Write();
320 }
321}
322
328
329 // if (fCut) fCut->PrintMetadata();
330 if (!fOddsFile.empty()) RESTMetadata << " Odds file: " << fOddsFile << RESTendl;
331 RESTMetadata << " DataSet file: " << fDataSetName << RESTendl;
332
333 RESTMetadata << " Observables to compute: " << RESTendl;
334 for (size_t i = 0; i < fObsName.size(); i++) {
335 RESTMetadata << fObsName[i] << "; Range: (" << fObsRange[i].X() << ", " << fObsRange[i].Y()
336 << "); nBins: " << fObsNbins[i] << RESTendl;
337 }
338 RESTMetadata << "----" << RESTendl;
339}
A class to help on cuts definitions. To be used with TRestAnalysisTree.
Definition: TRestCut.h:31
This class is meant to compute the log odds for different datasets.
std::string fOddsFile
Name of the odds file to be used to get the PDF.
std::vector< std::string > fObsName
Vector containing different obserbable names.
TRestDataSetOdds()
Default constructor.
void PrintMetadata() override
Prints on screen the information about the metadata members of TRestDataSetOdds.
std::map< std::string, TH1F * > fHistos
Map containing the PDF of the different observables.
std::vector< TVector2 > fObsRange
Vector containing different obserbable ranges.
void Initialize() override
Function to initialize input/output event members and define the section name.
~TRestDataSetOdds()
Default destructor.
TRestCut * fCut
Cuts over the dataset for PDF selection.
void ComputeLogOdds()
This function computes the log odds for a given dataSet. If no calibration odds file is provided it c...
std::string fOutputFileName
Name of the output file.
std::string fDataSetName
Name of the dataSet inside the config file.
std::vector< int > fObsNbins
Vector containing number of bins for the different observables.
void InitFromConfigFile() override
Function to initialize some variables from configfile.
It allows to group a number of runs that satisfy given metadata conditions.
Definition: TRestDataSet.h:34
void Import(const std::string &fileName)
This function imports metadata from a root file it import metadata info from the previous dataSet whi...
ROOT::RDF::RNode GetDataFrame() const
Gives access to the RDataFrame.
Definition: TRestDataSet.h:126
ROOT::RDF::RNode MakeCut(const TRestCut *cut)
This function applies a TRestCut to the dataframe and returns a dataframe with the applied cuts....
void Export(const std::string &filename, std::vector< std::string > excludeColumns={})
It will generate an output file with the dataset compilation. Only the selected branches and the file...
A base class for any REST metadata class.
Definition: TRestMetadata.h:74
virtual void PrintMetadata()
Implemented it in the derived metadata class to print out specific metadata information.
endl_t RESTendl
Termination flag object for TRestStringOutput.
TiXmlElement * GetElement(std::string eleDeclare, TiXmlElement *e=nullptr)
Get an xml element from a given parent element, according to its declaration.
Int_t LoadConfigFromFile(const std::string &configFilename, const std::string &sectionName="")
Give the file name, find out the corresponding section. Then call the main starter.
TRestMetadata * InstantiateChildMetadata(int index, std::string pattern="")
This method will retrieve a new TRestMetadata instance of a child element of the present TRestMetadat...
virtual void InitFromConfigFile()
To make settings from rml file. This method must be implemented in the derived class.
TRestStringOutput::REST_Verbose_Level GetVerboseLevel()
returns the verboselevel in type of REST_Verbose_Level enumerator
std::string GetFieldValue(std::string parName, TiXmlElement *e)
Returns the field value of an xml element which has the specified name.
void SetSectionName(std::string sName)
set the section name, clear the section content
std::string fConfigFileName
Full name of the rml file.
virtual Int_t Write(const char *name=nullptr, Int_t option=0, Int_t bufsize=0)
overwriting the write() method with fStore considered
TiXmlElement * GetNextElement(TiXmlElement *e)
Get the next sibling xml element of this element, with same eleDeclare.
std::string GetParameter(std::string parName, TiXmlElement *e, TString defaultValue=PARAMETER_NOT_FOUND_STR)
Returns the value for the parameter named parName in the given section.
static TRestRootFileHandle Open(const std::string &filename, TRestRootFileMode mode)
Definition: TRestTools.cxx:597
@ REST_Info
+show most of the information for each steps
static std::string GetFileNameExtension(const std::string &fullname)
Gets the file extension as the substring found after the latest ".".
Int_t StringToInteger(std::string in)
Gets an integer from a string.
TVector2 StringTo2DVector(std::string in)
Gets a 2D-vector from a string.