REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
Loading...
Searching...
No Matches
TRestDataSetCalibration.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
99
100#include "TRestDataSetCalibration.h"
101
102#include "TRestDataSet.h"
103#include "TRestTools.h"
104
106
111
126TRestDataSetCalibration::TRestDataSetCalibration(const char* configFilename, std::string name)
127 : TRestMetadata(configFilename) {
129 Initialize();
130
132}
133
138
144
151 Initialize();
153
154 TiXmlElement* peakDefinition = GetElement("peak");
155 while (peakDefinition != nullptr) {
156 std::string energy = GetFieldValue("energy", peakDefinition);
157 if (energy.empty() || energy == "Not defined") {
158 RESTError << "< peak variable key does not contain energy!" << RESTendl;
159 exit(1);
160 } else {
161 fEnergyPeaks.push_back(StringToDouble(energy));
162 }
163
164 peakDefinition = GetNextElement(peakDefinition);
165 }
166
167 if (fEnergyPeaks.empty()) {
168 RESTError << "Energy peaks not provided, exiting..." << RESTendl;
169 exit(1);
170 }
171
172 if (fOutputFileName == "") fOutputFileName = GetParameter("outputFileName", "");
173}
174
184
185 TRestDataSet dataSet;
186 dataSet.Import(fDataSetName);
187
188 dataSet.PrintMetadata();
189
190 std::unique_ptr<TH1F> spectrum;
191 std::unique_ptr<TGraph> gr;
192 std::unique_ptr<TF1> linearFit;
193
194 if (fCalibFile.empty()) {
195 auto histo = dataSet.GetDataFrame().Histo1D(
196 {"spectrum", "spectrum", fNBins, fCalibRange.X(), fCalibRange.Y()}, fCalObservable);
197 spectrum = std::unique_ptr<TH1F>(static_cast<TH1F*>(histo->DrawClone()));
198
199 // Get position of the maximum
200 const double max = spectrum->GetBinCenter(spectrum->GetMaximumBin());
201 // Get ratio between maximum and energy peak
202 const double ratio = max / fEnergyPeaks.front();
203
204 RESTDebug << "Max peak position " << max << RESTendl;
205
206 std::vector<TF1*> gauss;
207 gr = std::unique_ptr<TGraph>(new TGraph());
208 gr->SetName("grFit");
209
210 int c = 0;
211 for (const auto& energy : fEnergyPeaks) {
212 std::string fName = "g" + std::to_string(c);
213 double pos = energy * ratio;
214 double start = pos * 0.85;
215 double end = pos * 1.15;
216 TF1* g = new TF1(fName.c_str(), "gaus", start, end);
217 RESTDebug << "Fitting gaussian " << pos << " " << start << " " << end << RESTendl;
218 spectrum->Fit(g, "R+");
219 gauss.emplace_back(g);
220 gr->SetPoint(c, g->GetParameter(1), energy);
221 fCalibPeaks.push_back(g->GetParameter(1));
222 fCalibFWHM.push_back(g->GetParameter(2) * 235. / g->GetParameter(1));
223 c++;
224 }
225
227
228 gr->SetPoint(c, 0, 0);
229
230 gr->Draw("AP");
231 linearFit = std::unique_ptr<TF1>(new TF1("linearFit", "pol1"));
232 gr->Fit("linearFit", "S");
233 } else {
234 TFile* f = TFile::Open(fCalibFile.c_str());
235 if (f == nullptr) {
236 RESTError << "Cannot open calibration file " << fCalibFile << RESTendl;
237 exit(1);
238 }
239 RESTInfo << "Opening " << fCalibFile << RESTendl;
240 gr = std::unique_ptr<TGraph>(f->Get<TGraph>("grFit"));
241 linearFit = std::unique_ptr<TF1>(f->Get<TF1>("linearFit"));
242 }
243
244 fSlope = linearFit->GetParameter(1);
245 fIntercept = linearFit->GetParameter(0);
246
247 RESTDebug << "Slope " << fSlope << " Intercept " << fIntercept << RESTendl;
248
249 auto df = dataSet.GetDataFrame();
250
251 auto calibrate = [&linearFit](double val) {
252 return linearFit->GetParameter(1) * val + linearFit->GetParameter(0);
253 };
254 df = df.Define("calib_Energy", calibrate, {fCalObservable});
255
256 dataSet.SetDataFrame(df);
257
258 if (!fOutputFileName.empty()) {
260 dataSet.Export(fOutputFileName);
261 auto file = TRestRootFileHandle::Open(fOutputFileName, TRestRootFileMode::Update);
262 if (!file) {
263 RESTError << file.Error() << RESTendl;
264 return;
265 }
266 this->Write();
267 if (gr) gr->Write();
268 if (linearFit) linearFit->Write();
269 // if(lFit)lFit->Write();
270 // spectrumFit->Write();
271 if (spectrum) spectrum->Write();
272 if (!file.Close()) RESTError << file.Error() << RESTendl;
273 }
274 }
275}
276
282
283 RESTMetadata << " Energy peaks to calibrate: ";
284 for (const auto& peak : fEnergyPeaks) RESTMetadata << peak << " keV; ";
285 RESTMetadata << RESTendl;
286 RESTMetadata << " Calibrated peak position: ";
287 for (const auto& peak : fCalibPeaks) RESTMetadata << peak << " ADC; ";
288 RESTMetadata << RESTendl;
289 RESTMetadata << " Calibrated FWHM: ";
290 for (const auto& fwhm : fCalibFWHM) RESTMetadata << fwhm << " %; ";
291 RESTMetadata << RESTendl;
292 RESTMetadata << "Observable to calibrate: " << fCalObservable << RESTendl;
293 RESTMetadata << "Calibration range: (" << fCalibRange.X() << ", " << fCalibRange.Y() << ")" << RESTendl;
294 RESTMetadata << "Number of bins: " << fNBins << RESTendl;
295 RESTMetadata << "Slope: " << fSlope << " keV/ADC" << RESTendl;
296 RESTMetadata << "Intercept: " << fIntercept << " keV" << RESTendl;
297 RESTMetadata << "----" << RESTendl;
298}
This class is meant to perform the calibration of different runs.
void Calibrate()
Performs the calibration of a given dataSet. If no calibration file is provided, it performs the gaus...
TVector2 fCalibRange
Range to be calibrated.
Double_t fIntercept
Intercept of the calibration fit.
TRestDataSetCalibration()
Default constructor.
Int_t fNBins
Number of bins used in the calibration.
std::string fCalibFile
Name of the calibration file to be used.
void Initialize() override
Function to initialize input/output event members and define the section name.
~TRestDataSetCalibration()
Default destructor.
std::string fDataSetName
Name of the dataSet inside the config file.
void PrintMetadata() override
Prints on screen the information about the metadata members of TRestDataSetCalibration.
Double_t fSlope
Slope from the calibration fit.
std::vector< double > fCalibPeaks
Vector containing calibrated peaks in ADCs.
std::vector< double > fEnergyPeaks
Vector containing expected energy peaks in keV must be sorted.
std::string fOutputFileName
Name of the output file.
std::vector< double > fCalibFWHM
Vector containing calibrated sigma in ADCs.
void InitFromConfigFile() override
Function to initialize some variables from configfile, in case that the variable is not found in the ...
std::string fCalObservable
Calibration variable to be used.
It allows to group a number of runs that satisfy given metadata conditions.
void PrintMetadata() override
Prints on screen the information about the metadata members of TRestDataSet.
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.
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...
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.
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.
TRestMetadata()
TRestMetadata default constructor.
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)
@ REST_Info
+show most of the information for each steps
@ REST_Debug
+show the defined debug messages
static std::string GetFileNameExtension(const std::string &fullname)
Gets the file extension as the substring found after the latest ".".
Int_t GetChar(std::string hint="Press a KEY to continue ...")
Helps to pause the program, printing a message before pausing.
Double_t StringToDouble(std::string in)
Gets a double from a string.