REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
Loading...
Searching...
No Matches
TRestDataSetGainMap.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
139
140#include "TRestDataSetGainMap.h"
141
142#include "TRestTools.h"
143
144ClassImp(TRestDataSetGainMap);
149
164TRestDataSetGainMap::TRestDataSetGainMap(const char* configFilename, std::string name)
165 : TRestMetadata(configFilename) {
168}
169
174
181 this->Initialize();
183
184 // Load Module from RML
185 TiXmlElement* moduleDefinition = GetElement("module");
186 while (moduleDefinition != nullptr) {
187 fModulesCal.push_back(Module(*this));
188 fModulesCal.back().LoadConfigFromTiXmlElement(moduleDefinition);
189
190 moduleDefinition = GetNextElement(moduleDefinition);
191 }
192
193 fCut = (TRestCut*)InstantiateChildMetadata("TRestCut");
194
196}
197
202 for (auto& mod : fModulesCal) {
203 RESTInfo << "Generating gain map of plane " << mod.GetPlaneId() << " module " << mod.GetModuleId()
204 << RESTendl;
205 mod.GenerateGainMap();
207 mod.DrawSpectrum();
208 mod.DrawFullSpectrum();
209 mod.DrawGainMap();
210 }
211 }
212}
213
228void TRestDataSetGainMap::CalibrateDataSet(const std::string& dataSetFileName, std::string outputFileName,
229 std::vector<std::string> excludeColumns) {
230 if (fModulesCal.empty()) {
231 RESTError << "TRestDataSetGainMap::CalibrateDataSet: No modules defined." << RESTendl;
232 return;
233 }
234
235 TRestDataSet dataSet;
236 dataSet.EnableMultiThreading(true);
237
238 if (TRestTools::isDataSet(dataSetFileName)) {
239 dataSet.Import(dataSetFileName);
240 } else {
241 RESTWarning << dataSetFileName << " is not a dataset. Generating a temporal one..." << RESTendl;
242 // generate the dataset with the needed observables
243 dataSet.SetFilePattern(dataSetFileName);
244 dataSet.SetObservablesList({"*"}); // get all observables
245 dataSet.GenerateDataSet();
246 }
247
248 auto dataFrame = dataSet.GetDataFrame();
249
250 // Define a new column with the identifier (pmID) of the module for each row (event)
251 std::string pmIDname = (std::string)GetName() + "_pmID";
252 std::string modCut = fModulesCal[0].GetModuleDefinitionCut();
253 if (modCut.empty()) modCut = "1"; // if no cut is defined, use "1" (all events)
254 int pmID = fModulesCal[0].GetPlaneId() * 10 + fModulesCal[0].GetModuleId();
255
256 auto columnList = dataFrame.GetColumnNames();
257 if (std::find(columnList.begin(), columnList.end(), pmIDname) == columnList.end())
258 dataFrame = dataFrame.Define(pmIDname, modCut + " ? " + std::to_string(pmID) + " : -1");
259 else
260 dataFrame = dataFrame.Redefine(pmIDname, modCut + " ? " + std::to_string(pmID) + " : -1");
261
262 for (size_t n = 1; n < fModulesCal.size(); n++) {
263 modCut = fModulesCal[n].GetModuleDefinitionCut();
264 if (modCut.empty()) modCut = "1"; // if no cut is defined, use "1" (all events)
265 pmID = fModulesCal[n].GetPlaneId() * 10 + fModulesCal[n].GetModuleId();
266 dataFrame = dataFrame.Redefine(pmIDname, (modCut + " ? " + std::to_string(pmID) + " : " + pmIDname));
267 }
268
269 // Define a new column with the calibrated observable
270 auto calibrate = [this](double val, double x, double y, int pmID) {
271 for (auto& m : fModulesCal) {
272 if (pmID == m.GetPlaneId() * 10 + m.GetModuleId())
273 return m.GetSlope(x, y) * val + m.GetIntercept(x, y);
274 }
275 // RESTError << "TRestDataSetGainMap::CalibrateDataSet: Module not found for pmID " << pmID <<
276 // RESTendl;
277 return std::numeric_limits<double>::quiet_NaN();
278 };
279 std::string calibObsName = (std::string)GetName() + "_";
280 calibObsName += GetObservable().erase(0, GetObservable().find("_") + 1); // remove the "rawAna_" part
281 dataFrame = dataFrame.Define(calibObsName, calibrate,
283
284 // Define a new column with the calibrated observable for the whole module calibration
285 auto calibrateFullSpc = [this](double val, int pmID) {
286 for (auto& m : fModulesCal) {
287 if (pmID == m.GetPlaneId() * 10 + m.GetModuleId())
288 return m.GetSlopeFullSpc() * val + m.GetInterceptFullSpc();
289 }
290 // RESTError << "TRestDataSetGainMap::CalibrateDataSet: Module not found for pmID " << pmID <<
291 // RESTendl;
292 return std::numeric_limits<double>::quiet_NaN();
293 };
294 std::string calibObsNameFullSpc = (std::string)GetName() + "_";
295 calibObsNameFullSpc +=
296 GetObservable().erase(0, GetObservable().find("_") + 1); // remove the "rawAna_" part
297 calibObsNameFullSpc += "_NoSegmentation";
298 dataFrame = dataFrame.Define(calibObsNameFullSpc, calibrateFullSpc, {fObservable, pmIDname});
299
300 dataSet.SetDataFrame(dataFrame);
301
302 // Format the output file name and export the dataSet
303 if (outputFileName.empty()) outputFileName = dataSetFileName;
304 if (outputFileName == dataSetFileName) { // TRestDataSet cannot be overwritten
305 std::string gmName = GetName();
306 outputFileName = outputFileName.substr(0, outputFileName.find_last_of(".")); // remove extension
307 outputFileName += "_" + gmName + "." + TRestTools::GetFileNameExtension(dataSetFileName);
308 }
309
310 // Export dataset. Exclude columns if requested.
311 auto columns = dataSet.GetDataFrame().GetColumnNames();
312 std::set<std::string> excludeCol = TRestTools::GetMatchingStrings(columns, excludeColumns);
313 // Never exclude the calibObsName, calibObsNameFullSpc and pmIDname
314 excludeCol.erase(calibObsName);
315 excludeCol.erase(calibObsNameFullSpc);
316 excludeCol.erase(pmIDname);
317
318 RESTDebug << "Excluding columns: ";
319 for (auto& c : excludeCol) RESTDebug << c << ", ";
320 RESTDebug << RESTendl;
321
322 dataSet.Export(outputFileName, std::vector<std::string>(excludeCol.begin(), excludeCol.end()));
323
324 // Add this TRestDataSetGainMap metadata to the output file
325 auto file = TRestRootFileHandle::Open(outputFileName, TRestRootFileMode::Update);
326 if (!file) {
327 RESTError << file.Error() << RESTendl;
328 return;
329 }
330 this->Write();
331 if (!file.Close()) RESTError << file.Error() << RESTendl;
332}
333
339 if (index < fModulesCal.size()) return &fModulesCal[index];
340
341 RESTError << "No ModuleCalibration with index " << index;
342 if (fModulesCal.empty())
343 RESTError << ". There are no modules defined." << RESTendl;
344 else
345 RESTError << ". Max index is " << fModulesCal.size() - 1 << RESTendl;
346 return nullptr;
347}
348
353TRestDataSetGainMap::Module* TRestDataSetGainMap::GetModule(const int planeID, const int moduleID) {
354 for (auto& i : fModulesCal) {
355 if (i.GetPlaneId() == planeID && i.GetModuleId() == moduleID) return &i;
356 }
357 RESTError << "No ModuleCalibration with planeID " << planeID << " and moduleID " << moduleID << RESTendl;
358 return nullptr;
359}
360
366double TRestDataSetGainMap::GetSlopeParameter(const int planeID, const int moduleID, const double x,
367 const double y) {
368 Module* moduleCal = GetModule(planeID, moduleID);
369 if (moduleCal == nullptr) return 0; // return numeric_limits<double>::quiet_NaN()
370 return moduleCal->GetSlope(x, y);
371}
372
377double TRestDataSetGainMap::GetSlopeParameterFullSpc(const int planeID, const int moduleID) {
378 Module* moduleCal = GetModule(planeID, moduleID);
379 if (moduleCal == nullptr) return 0; // return numeric_limits<double>::quiet_NaN()
380 return moduleCal->GetSlopeFullSpc();
381}
382
388double TRestDataSetGainMap::GetInterceptParameter(const int planeID, const int moduleID, const double x,
389 const double y) {
390 Module* moduleCal = GetModule(planeID, moduleID);
391 if (moduleCal == nullptr) return 0; // return numeric_limits<double>::quiet_NaN()
392 return moduleCal->GetIntercept(x, y);
393}
394
399double TRestDataSetGainMap::GetInterceptParameterFullSpc(const int planeID, const int moduleID) {
400 Module* moduleCal = GetModule(planeID, moduleID);
401 if (moduleCal == nullptr) return 0; // return numeric_limits<double>::quiet_NaN()
402 return moduleCal->GetInterceptFullSpc();
403}
404
409std::set<int> TRestDataSetGainMap::GetPlaneIDs() const {
410 std::set<int> planeIDs;
411 for (const auto& mc : fModulesCal) planeIDs.insert(mc.GetPlaneId());
412 return planeIDs;
413}
414
419std::set<int> TRestDataSetGainMap::GetModuleIDs(const int planeId) const {
420 std::set<int> moduleIDs;
421 for (const auto& mc : fModulesCal)
422 if (mc.GetPlaneId() == planeId) moduleIDs.insert(mc.GetModuleId());
423 return moduleIDs;
424}
425
429std::map<int, std::set<int>> TRestDataSetGainMap::GetModuleIDs() const {
430 std::map<int, std::set<int>> moduleIds;
431 for (const int planeId : GetPlaneIDs())
432 moduleIds.insert(std::pair<int, std::set<int>>(planeId, GetModuleIDs(planeId)));
433 return moduleIds;
434}
435
436TRestDataSetGainMap& TRestDataSetGainMap::operator=(TRestDataSetGainMap& src) {
437 SetName(src.GetName());
438 fOutputFileName = src.GetOutputFileName();
439 fObservable = src.GetObservable();
440 fSpatialObservableX = src.GetSpatialObservableX();
441 fSpatialObservableY = src.GetSpatialObservableY();
442 fSpatialObservableXSecondary = src.GetSpatialObservableXSecondary();
443 fSpatialObservableYSecondary = src.GetSpatialObservableYSecondary();
444 fCut = src.GetCut();
445 fModulesCal.clear();
446 for (auto pID : src.GetPlaneIDs())
447 for (auto mID : src.GetModuleIDs(pID)) fModulesCal.push_back(*src.GetModule(pID, mID));
448 return *this;
449}
450
456 for (auto& i : fModulesCal) {
457 if (i.GetPlaneId() == moduleCal.GetPlaneId() && i.GetModuleId() == moduleCal.GetModuleId()) {
458 i = moduleCal;
459 return;
460 }
461 }
462 fModulesCal.push_back(moduleCal);
463}
464
469void TRestDataSetGainMap::Import(const std::string& fileName) {
470 if (fileName.empty()) {
471 RESTError << "No input calibration file defined" << RESTendl;
472 return;
473 }
474
475 if (TRestTools::isRootFile(fileName)) {
476 RESTInfo << "Opening " << fileName << RESTendl;
477 TFile* f = TFile::Open(fileName.c_str(), "READ");
478 if (f == nullptr) {
479 RESTError << "Cannot open calibration file " << fileName << RESTendl;
480 return;
481 }
482
483 TRestDataSetGainMap* cal = nullptr;
484 if (f != nullptr) {
485 TIter nextkey(f->GetListOfKeys());
486 TKey* key;
487 while ((key = (TKey*)nextkey())) {
488 std::string kName = key->GetClassName();
489 if (REST_Reflection::GetClassQuick(kName.c_str()) != nullptr &&
490 REST_Reflection::GetClassQuick(kName.c_str())->InheritsFrom("TRestDataSetGainMap")) {
491 cal = f->Get<TRestDataSetGainMap>(key->GetName());
492 *this = *cal;
493 }
494 }
495 }
496 } else
497 RESTError << "File extension not supported for " << fileName << RESTendl;
499}
500
507void TRestDataSetGainMap::Export(const std::string& fileName) {
508 if (!fileName.empty()) fOutputFileName = fileName;
509 if (fOutputFileName.empty()) {
510 RESTError << "No output file defined" << RESTendl;
511 return;
512 }
513
515 auto file = TRestRootFileHandle::Open(fOutputFileName, TRestRootFileMode::Update);
516 if (!file) {
517 RESTError << file.Error() << RESTendl;
518 return;
519 }
520 this->Write(GetName());
521 if (!file.Close()) {
522 RESTError << file.Error() << RESTendl;
523 return;
524 }
525 RESTInfo << "Calibration saved to " << fOutputFileName << RESTendl;
526 } else
527 RESTError << "File extension for " << fOutputFileName << "is not supported." << RESTendl;
528}
529
535 RESTMetadata << " Calibration dataset: " << fCalibFileName << RESTendl;
536 if (fCut) {
537 RESTMetadata << " Cuts applied: ";
538 /* print only cutStrings and paramCut because
539 TRestDataSet::MakeCut() uses fCut->GetCutStrings() and fCut->GetParamCut() */
540 for (const auto& cut : fCut->GetCutStrings()) RESTMetadata << cut << ", " << RESTendl;
541 for (const auto& cut : fCut->GetParamCut())
542 RESTMetadata << cut.first << " " << cut.second << ", " << RESTendl;
543 }
544 RESTMetadata << " Output file: " << fOutputFileName << RESTendl;
545 RESTMetadata << RESTendl;
546 RESTMetadata << " Number of planes: " << GetNumberOfPlanes() << RESTendl;
547 RESTMetadata << " Number of modules: " << GetNumberOfModules() << RESTendl;
548 RESTMetadata << " Calibration observable: " << fObservable << RESTendl;
549 RESTMetadata << " Spatial observable X: " << fSpatialObservableX << RESTendl;
550 RESTMetadata << " Spatial observable Y: " << fSpatialObservableY << RESTendl;
551 if (!fSpatialObservableXSecondary.empty())
552 RESTMetadata << " Secondary spatial observable X: " << fSpatialObservableXSecondary << RESTendl;
553 if (!fSpatialObservableYSecondary.empty())
554 RESTMetadata << " Secondary spatial observable Y: " << fSpatialObservableYSecondary << RESTendl;
555 RESTMetadata << "-----------------------------------------------" << RESTendl;
556 for (auto& i : fModulesCal) i.Print();
557 RESTMetadata << "***********************************************" << RESTendl;
558 RESTMetadata << RESTendl;
559}
560
568std::pair<int, int> TRestDataSetGainMap::Module::GetIndexMatrix(const double x, const double y) const {
569 int index_x = -1, index_y = -1;
570
571 if (fSplitX.upper_bound(x) != fSplitX.end()) {
572 index_x = std::distance(fSplitX.begin(), fSplitX.upper_bound(x)) - 1;
573 if (index_x < 0) {
574 RESTWarning << "index_x < 0 for x = " << x << " and fSplitX[0]=" << *fSplitX.begin()
575 << p->RESTendl;
576 index_x = 0;
577 }
578 } else {
579 RESTWarning << "x is out of split for x = " << x << p->RESTendl;
580 index_x = fSplitX.size() - 2;
581 }
582
583 if (fSplitY.upper_bound(y) != fSplitY.end()) {
584 index_y = std::distance(fSplitY.begin(), fSplitY.upper_bound(y)) - 1;
585 if (index_y < 0) {
586 RESTWarning << "index_y < 0 for y = " << y << " and fSplitY[0]=" << *fSplitY.begin()
587 << p->RESTendl;
588 index_y = 0;
589 }
590 } else {
591 RESTWarning << "y is out of split for y = " << y << p->RESTendl;
592 index_y = fSplitY.size() - 2;
593 }
594
595 return std::make_pair(index_x, index_y);
596}
597
604double TRestDataSetGainMap::Module::GetSlope(const double x, const double y) const {
605 auto [index_x, index_y] = GetIndexMatrix(x, y);
606 if (fSlope.empty()) {
607 RESTError << "Calibration slope matrix is empty. Returning 0" << p->RESTendl;
608 return 0;
609 }
610
611 if (index_x > (int)fSlope.size() || index_y > (int)fSlope.at(0).size()) {
612 RESTError << "Index out of range. Returning 0" << p->RESTendl;
613 return 0;
614 }
615
616 return fSlope[index_x][index_y];
617}
618
626double TRestDataSetGainMap::Module::GetIntercept(const double x, const double y) const {
627 auto [index_x, index_y] = GetIndexMatrix(x, y);
628 if (fIntercept.empty()) {
629 RESTError << "Calibration constant matrix is empty. Returning 0" << p->RESTendl;
630 return 0;
631 }
632
633 if (index_x > (int)fIntercept.size() || index_y > (int)fIntercept.at(0).size()) {
634 RESTError << "Index out of range. Returning 0" << p->RESTendl;
635 return 0;
636 }
637
638 return fIntercept[index_x][index_y];
639}
640
648
655 if (fNumberOfSegmentsX < 1) {
656 RESTError << "SetSplitX: fNumberOfSegmentsX must be >=1." << p->RESTendl;
657 return;
658 }
659 std::set<double> split;
660 for (int i = 0; i <= fNumberOfSegmentsX; i++) { // <= so that the last segment is included
661 double x =
662 fReadoutRange.X() + ((fReadoutRange.Y() - fReadoutRange.X()) / (float)fNumberOfSegmentsX) * i;
663 split.insert(x);
664 }
665 SetSplitX(split);
666}
667
668void TRestDataSetGainMap::Module::SetSplitX(const std::set<double>& splitX) {
669 if (splitX.size() < 2) {
670 RESTError << "SetSplitX: split size must be >=2 (start and end of range must be included)."
671 << p->RESTendl;
672 return;
673 }
674 if (!fSlope.empty())
675 RESTWarning << "SetSplitX: changing split but current gain map and calibration paremeters correspond "
676 "to previous splitting. Use GenerateGainMap() to update them."
677 << p->RESTendl;
678 fSplitX = splitX;
679 fNumberOfSegmentsX = fSplitX.size() - 1;
680}
688 if (fNumberOfSegmentsY < 1) {
689 RESTError << "SetSplitY: fNumberOfSegmentsY must be >=1." << p->RESTendl;
690 return;
691 }
692 std::set<double> split;
693 for (int i = 0; i <= fNumberOfSegmentsY; i++) { // <= so that the last segment is included
694 double y =
695 fReadoutRange.X() + ((fReadoutRange.Y() - fReadoutRange.X()) / (float)fNumberOfSegmentsY) * i;
696 split.insert(y);
697 }
698 SetSplitY(split);
699}
700
701void TRestDataSetGainMap::Module::SetSplitY(const std::set<double>& splitY) {
702 if (splitY.size() < 2) {
703 RESTError << "SetSplitY: split size must be >=2 (start and end of range must be included)."
704 << p->RESTendl;
705 return;
706 }
707 if (!fSlope.empty())
708 RESTWarning << "SetSplitY: changing split but current gain map and calibration paremeters correspond "
709 "to previous splitting. Use GenerateGainMap() to update them."
710 << p->RESTendl;
711 fSplitY = splitY;
712 fNumberOfSegmentsY = fSplitY.size() - 1;
713}
714
732 //--- Initial checks and settings ---
733 std::string dsFileName = fDataSetFileName;
734 if (dsFileName.empty()) dsFileName = p->GetCalibrationFileName();
735 if (dsFileName.empty()) {
736 RESTError << "No calibration file defined" << p->RESTendl;
737 return;
738 }
739
740 TRestDataSet dataSet;
741 dataSet.EnableMultiThreading(true);
742 if (TRestTools::isDataSet(dsFileName)) {
743 dataSet.Import(dsFileName);
744 fDataSetFileName = dsFileName;
745 } else {
746 RESTWarning << dsFileName << " is not a dataset. Generating a temporal one..." << p->RESTendl;
747 // get all the observables needed for the gain map
748 std::vector<std::string> obsList;
749
750 obsList.push_back(p->GetObservable());
751 obsList.push_back(p->GetSpatialObservableX());
752 obsList.push_back(p->GetSpatialObservableY());
753 if (!p->GetSpatialObservableXSecondary().empty())
754 obsList.push_back(p->GetSpatialObservableXSecondary());
755 if (!p->GetSpatialObservableYSecondary().empty())
756 obsList.push_back(p->GetSpatialObservableYSecondary());
757
758 // look for observables (characterized by having a _ in the name) in the definition cut
759 auto modDefCutObs = TRestTools::GetObservablesInString(fDefinitionCut, true);
760 obsList.insert(obsList.end(), modDefCutObs.begin(), modDefCutObs.end());
761
762 // look for observables in the cut
763 for (const auto& cut : p->GetCut()->GetCutStrings()) {
764 auto cutObs = TRestTools::GetObservablesInString(cut, true);
765 obsList.insert(obsList.end(), cutObs.begin(), cutObs.end());
766 }
767 for (const auto& [variable, condition] : p->GetCut()->GetParamCut()) {
768 auto cutObs = TRestTools::GetObservablesInString(variable, true);
769 obsList.insert(obsList.end(), cutObs.begin(), cutObs.end());
770 // not sure if any obs can be in the condition. Just in case...
771 cutObs = TRestTools::GetObservablesInString(condition, true);
772 obsList.insert(obsList.end(), cutObs.begin(), cutObs.end());
773 }
774
775 // remove duplicates
776 std::sort(obsList.begin(), obsList.end());
777 obsList.erase(std::unique(obsList.begin(), obsList.end()), obsList.end());
778
779 // generate the dataset with the needed observables
780 dataSet.SetFilePattern(dsFileName);
781 dataSet.SetObservablesList(obsList);
782 dataSet.GenerateDataSet();
783 fDataSetFileName = dsFileName;
784 }
785
786 dataSet.SetDataFrame(dataSet.MakeCut(p->GetCut()));
787
788 if (fSplitX.empty()) SetSplitX();
789 if (fSplitY.empty()) SetSplitY();
790
791 //--- Get the calibration range if not provided (default is 0,0) ---
792 if (fCalibRange.X() >= fCalibRange.Y()) {
793 // Get spectrum for this file
794 std::string cut = fDefinitionCut;
795 if (cut.empty()) cut = "1";
796 auto histo = dataSet.GetDataFrame().Filter(cut).Histo1D({"temp", "", fNBins, 0, 0}, GetObservable());
797 std::unique_ptr<TH1F> hpunt = std::unique_ptr<TH1F>(static_cast<TH1F*>(histo->Clone()));
798 // double xMin = hpunt->GetXaxis()->GetXmin();
799 double xMax = hpunt->GetXaxis()->GetXmax();
800
801 // Reduce the range to avoid the possible empty (nCounts<1%) end part of the spectrum
802 double fraction = 1, nAtEndSpc = 0, step = 0.66;
803 while (nAtEndSpc * 1. / hpunt->Integral() < 0.01 && fraction > 0.001) {
804 fraction *= step;
805 nAtEndSpc = hpunt->Integral(hpunt->FindFixBin(hpunt->GetXaxis()->GetXmax() * fraction),
806 hpunt->FindFixBin(hpunt->GetXaxis()->GetXmax()));
807 }
808 xMax = hpunt->GetXaxis()->GetXmax() * fraction /
809 step; // previous step is the last one that nAtEndSpc<1%
810 // Set the calibration range if needed
811 // fCalibRange.SetX(xMin);
812 fCalibRange.SetY(xMax);
813 hpunt.reset(); // delete hpunt;
814 RESTDebug << "Calibration range (auto)set to (" << fCalibRange.X() << "," << fCalibRange.Y() << ")"
815 << p->RESTendl;
816 }
817
818 // --- Definition of histogram whole module ---
819 std::string hModuleName = "hSpc_" + std::to_string(fPlaneId) + "_" + std::to_string(fModuleId);
820 delete fFullSpectrum;
821 fFullSpectrum = new TH1F(hModuleName.c_str(), "", fNBins, fCalibRange.X(), fCalibRange.Y());
822
823 // build the spectrum for the whole module
824 std::string cut = fDefinitionCut;
825 if (cut.empty()) cut = "1";
826 auto histoMod = dataSet.GetDataFrame().Filter(cut).Histo1D(
827 {"tempMod", "", fNBins, fCalibRange.X(), fCalibRange.Y()}, GetObservable());
828 std::unique_ptr<TH1F> hpuntMod = std::unique_ptr<TH1F>(static_cast<TH1F*>(histoMod->Clone()));
829 fFullSpectrum->Add(hpuntMod.get());
830
831 //--- Definition of histogram matrix ---
832 std::vector<std::vector<TH1F*>> h(fNumberOfSegmentsX, std::vector<TH1F*>(fNumberOfSegmentsY, nullptr));
833 for (size_t i = 0; i < h.size(); i++) {
834 for (size_t j = 0; j < h.at(0).size(); j++) {
835 std::string name = hModuleName + "_" + std::to_string(i) + "_" + std::to_string(j);
836 h[i][j] = new TH1F(name.c_str(), "", fNBins, fCalibRange.X(),
837 fCalibRange.Y()); // h[column][row] equivalent to h[x][y]
838 }
839 }
840
841 // build the spectrum for each segment
842 auto itX = fSplitX.begin();
843 for (size_t i = 0; i < h.size(); i++) {
844 auto itY = fSplitY.begin();
845 for (size_t j = 0; j < h.at(0).size(); j++) {
846 // Get the segment limits from the splits
847 auto xLower = *itX;
848 auto xUpper = *std::next(itX);
849 auto yLower = *itY;
850 auto yUpper = *std::next(itY);
851
852 std::string segment_cut = "";
853 if (!GetSpatialObservableX().empty())
854 segment_cut += GetSpatialObservableX() + ">=" + std::to_string(xLower) + "&&" +
855 GetSpatialObservableX() + "<" + std::to_string(xUpper);
856 if (!GetSpatialObservableY().empty())
857 segment_cut += "&&" + GetSpatialObservableY() + ">=" + std::to_string(yLower) + "&&" +
858 GetSpatialObservableY() + "<" + std::to_string(yUpper);
859 if (!GetSpatialObservableXSecondary().empty())
860 segment_cut += "&&" + GetSpatialObservableXSecondary() + ">=" + std::to_string(xLower) +
861 "&&" + GetSpatialObservableXSecondary() + "<" + std::to_string(xUpper);
862 if (!GetSpatialObservableYSecondary().empty())
863 segment_cut += "&&" + GetSpatialObservableYSecondary() + ">=" + std::to_string(yLower) +
864 "&&" + GetSpatialObservableYSecondary() + "<" + std::to_string(yUpper);
865 if (!fDefinitionCut.empty()) segment_cut += "&&" + fDefinitionCut;
866 if (segment_cut.empty()) segment_cut = "1";
867 RESTExtreme << "Segment[" << i << "][" << j << "] cut: " << segment_cut << p->RESTendl;
868 auto histo = dataSet.GetDataFrame()
869 .Filter(segment_cut)
870 .Histo1D({"temp", "", h[i][j]->GetNbinsX(), h[i][j]->GetXaxis()->GetXmin(),
871 h[i][j]->GetXaxis()->GetXmax()},
872 GetObservable());
873 std::unique_ptr<TH1F> hpunt = std::unique_ptr<TH1F>(static_cast<TH1F*>(histo->Clone()));
874 h[i][j]->Add(hpunt.get());
875 hpunt.reset(); // delete hpunt;
876 itY++;
877 }
878 itX++;
879 }
880
881 //--- Fit every peak energy for every segment ---
882 std::vector<std::vector<double>> calParSlope(fNumberOfSegmentsX,
883 std::vector<double>(fNumberOfSegmentsY, 0));
884 std::vector<std::vector<double>> calParIntercept(fNumberOfSegmentsX,
885 std::vector<double>(fNumberOfSegmentsY, 0));
886 fSegLinearFit = std::vector(h.size(), std::vector<TGraph*>(h.at(0).size(), nullptr));
887 for (size_t i = 0; i < h.size(); i++)
888 for (int j = 0; j < (int)h.at(0).size(); j++) {
889 fSegLinearFit[i][j] = new TGraph();
890 auto [intercept, slope] = FitPeaks(h[i][j], fSegLinearFit[i][j]);
891 calParSlope[i][j] = slope;
892 calParIntercept[i][j] = intercept;
893 }
894 fSlope = calParSlope;
895 fIntercept = calParIntercept;
896 fSegSpectra = h;
897
898 //--- Fit every peak energy for the whole module ---
899 delete fFullLinearFit;
900 fFullLinearFit = new TGraph();
901 auto [intercept, slope] = FitPeaks(fFullSpectrum, fFullLinearFit);
902 fFullSlope = slope;
903 fFullIntercept = intercept;
904}
905
906std::pair<double, double> TRestDataSetGainMap::Module::FitPeaks(TH1F* hSeg, TGraph* gr) {
907 if (!hSeg) {
908 RESTError << "No histogram for fitting" << p->RESTendl;
909 return std::make_pair(0, 0);
910 }
911 if (hSeg->Integral() == 0) {
912 RESTError << "Empty spectrum " << hSeg->GetName() << p->RESTendl;
913 return std::make_pair(0, 0);
914 }
915 std::shared_ptr<TGraph> graph = std::shared_ptr<TGraph>(new TGraph());
916 RESTExtreme << "Fitting peaks for " << hSeg->GetName() << p->RESTendl;
917
918 // Search for peaks --> peakPos
919 std::unique_ptr<TSpectrum> s(new TSpectrum(2 * fEnergyPeaks.size() + 1));
920 std::vector<double> peakPos;
921 s->Search(hSeg, 2, "goff", 0.1);
922 for (int k = 0; k < s->GetNPeaks(); k++) peakPos.push_back(s->GetPositionX()[k]);
923 std::sort(peakPos.begin(), peakPos.end(), std::greater<double>());
924 const double ratio =
925 peakPos.size() == 0 ? 1 : peakPos.front() / fEnergyPeaks.front(); // to estimate peak position
926
927 // Initialize graph for linear fit
928 graph->SetName("grFit");
929 graph->SetTitle((";" + GetObservable() + ";energy").c_str());
930
931 // Fit every energy peak
932 int c = 0;
933 double mu = 0;
934 for (const auto& energy : fEnergyPeaks) {
935 RESTExtreme << "\t fitting energy " << DoubleToString(energy, "%g") << p->RESTendl;
936 // estimation of the peak position is between start and end
937 double pos = energy * ratio;
938 double start = pos * 0.8;
939 double end = pos * 1.2;
940 if (fRangePeaks.at(c).X() < fRangePeaks.at(c).Y()) { // if range is defined use it
941 start = fRangePeaks.at(c).X();
942 end = fRangePeaks.at(c).Y();
943 }
944
945 do {
946 if (fAutoRangePeaks) {
947 if (peakPos.size() > 0) {
948 // Find the peak position that is between start and end
949 pos = peakPos.at(0);
950 while (!(start < pos && pos < end)) {
951 // if none of the peak position is
952 // between start and end, use the greater one.
953 if (pos == peakPos.back()) {
954 pos = peakPos.at(0);
955 break;
956 }
957 pos = *std::next(std::find(peakPos.begin(), peakPos.end(),
958 pos)); // get next peak position
959 }
960 peakPos.erase(std::find(peakPos.begin(), peakPos.end(),
961 pos)); // remove this peak position from the list
962 // final estimation of the peak range (idem fitting window) with this peak
963 // position pos
964 start = pos * 0.8;
965 end = pos * 1.2;
966 const double relDist = peakPos.size() > 0 ? (pos - peakPos.front()) / pos : 999;
967 if (relDist < 0.2) { // if the next peak is too close reduce the window width
968 start = pos * (1 - relDist / 2);
969 end = pos * (1 + relDist / 2);
970 }
971 }
972 }
973
974 std::string name = "g" + std::to_string(c);
975 TF1* g = new TF1(name.c_str(), "gaus", start, end);
976 RESTExtreme << "\t\tat " << DoubleToString(pos, "%.3g") << ". Range("
977 << DoubleToString(start, "%.3g") << ", " << DoubleToString(end, "%.3g") << ")"
978 << p->RESTendl;
979
980 if (hSeg->GetFunction(name.c_str())) // remove previous fit
981 hSeg->GetListOfFunctions()->Remove(hSeg->GetFunction(name.c_str()));
982
983 hSeg->Fit(g, "R+Q0"); // use 0 to not draw the fit but save it
984 mu = g->GetParameter(1);
985 RESTExtreme << "\t\tgaus mean " << DoubleToString(mu, "%g") << p->RESTendl;
986 } while (fAutoRangePeaks && peakPos.size() > 0 &&
987 !(start < mu && mu < end)); // avoid small peaks on main peak tail
988 graph->SetPoint(c++, mu, energy);
989 }
990 s.reset(); // delete s;
991
992 if (fZeroPoint) graph->SetPoint(c++, 0, 0);
993 while (graph->GetN() < 2) { // minimun 2 points needed for linear fit
994 graph->SetPoint(c++, 0, 0);
995 SetZeroPoint(true);
996 RESTDebug << "Not enough points for linear fit. Adding and setting zero point to true" << p->RESTendl;
997 }
998
999 // Linear fit
1000 std::unique_ptr<TF1> linearFit;
1001 linearFit = std::unique_ptr<TF1>(new TF1("linearFit", "pol1"));
1002 graph->Fit("linearFit", "SQ"); // Q for quiet mode
1003
1004 if (gr) *gr = *(TGraph*)graph->Clone(); // if nullptr is passed, do not copy the graph
1005 return std::make_pair(linearFit->GetParameter(0), linearFit->GetParameter(1));
1006}
1007
1015void TRestDataSetGainMap::Module::Refit(const TVector2& position, const double energyPeak,
1016 const TVector2& range) {
1017 auto [index_x, index_y] = GetIndexMatrix(position.X(), position.Y());
1018 int peakNumber = -1;
1019 for (size_t i = 0; i < fEnergyPeaks.size(); i++)
1020 if (fEnergyPeaks.at(i) == energyPeak) {
1021 peakNumber = i;
1022 break;
1023 }
1024 if (peakNumber == -1) {
1025 RESTError << "Energy " << energyPeak << " not found in the list of energy peaks" << p->RESTendl;
1026 return;
1027 }
1028 Refit((size_t)index_x, (size_t)index_y, (size_t)peakNumber, range);
1029}
1030
1040void TRestDataSetGainMap::Module::Refit(const size_t x, const size_t y, const size_t peakNumber,
1041 const TVector2& range) {
1042 if (fSegSpectra.empty()) {
1043 RESTError << "No gain map found. Use GenerateGainMap() first." << p->RESTendl;
1044 return;
1045 }
1046 if (x >= fSegSpectra.size() || y >= fSegSpectra.at(0).size()) {
1047 RESTError << "Segment with index (" << x << ", " << y << ") not found" << p->RESTendl;
1048 return;
1049 }
1050 if (peakNumber >= fEnergyPeaks.size()) {
1051 RESTError << "Peak with index " << peakNumber << " not found" << p->RESTendl;
1052 return;
1053 }
1054
1055 // Refit the desired peak
1056 std::string name = "g" + std::to_string(peakNumber);
1057 TF1* g = new TF1(name.c_str(), "gaus", range.X(), range.Y());
1058 TH1F* h = fSegSpectra.at(x).at(y);
1059 while (h->GetFunction(name.c_str())) // clear previous fits for this peakNumber
1060 h->GetListOfFunctions()->Remove(h->GetFunction(name.c_str()));
1061 h->Fit(g, "R+Q0"); // use 0 to not draw the fit but save it
1062
1063 // Change the point of the graph
1064 UpdateCalibrationFits(x, y);
1065}
1066
1074void TRestDataSetGainMap::Module::RefitFullSpc(const double energyPeak, const TVector2& range) {
1075 int peakNumber = -1;
1076 for (size_t i = 0; i < fEnergyPeaks.size(); i++)
1077 if (fEnergyPeaks.at(i) == energyPeak) {
1078 peakNumber = i;
1079 break;
1080 }
1081 if (peakNumber == -1) {
1082 RESTError << "Energy " << energyPeak << " not found in the list of energy peaks" << p->RESTendl;
1083 return;
1084 }
1085 RefitFullSpc((size_t)peakNumber, range);
1086}
1087
1095void TRestDataSetGainMap::Module::RefitFullSpc(const size_t peakNumber, const TVector2& range) {
1096 if (!fFullSpectrum) {
1097 RESTError << "No gain map found. Use GenerateGainMap() first." << p->RESTendl;
1098 return;
1099 }
1100 if (peakNumber >= fEnergyPeaks.size()) {
1101 RESTError << "Peak with index " << peakNumber << " not found" << p->RESTendl;
1102 return;
1103 }
1104
1105 // Refit the desired peak
1106 std::string name = "g" + std::to_string(peakNumber);
1107 TF1* g = new TF1(name.c_str(), "gaus", range.X(), range.Y());
1108 while (fFullSpectrum->GetFunction(name.c_str())) // clear previous fits for this peakNumber
1109 fFullSpectrum->GetListOfFunctions()->Remove(fFullSpectrum->GetFunction(name.c_str()));
1110 fFullSpectrum->Fit(g, "R+Q0"); // use 0 to not draw the fit but save it
1111
1112 // Change the point of the graph
1114}
1115
1124void TRestDataSetGainMap::Module::UpdateCalibrationFits(const size_t x, const size_t y) {
1125 if (fSegSpectra.empty()) {
1126 RESTError << "No gain map found. Use GenerateGainMap() first." << p->RESTendl;
1127 return;
1128 }
1129 if (x >= fSegSpectra.size() || y >= fSegSpectra.at(0).size()) {
1130 RESTError << "Segment with index (" << x << ", " << y << ") not found" << p->RESTendl;
1131 return;
1132 }
1133
1134 TH1F* h = fSegSpectra.at(x).at(y);
1135 TGraph* gr = fSegLinearFit.at(x).at(y);
1136
1137 auto [intercept, slope] = UpdateCalibrationFits(h, gr);
1138 fSlope[x][y] = slope;
1139 fIntercept[x][y] = intercept;
1140}
1141
1142std::pair<double, double> TRestDataSetGainMap::Module::UpdateCalibrationFits(TH1F* h, TGraph* gr) {
1143 if (!h) {
1144 RESTError << "No histogram for updating fits" << p->RESTendl;
1145 return std::make_pair(0, 0);
1146 }
1147 if (!gr) {
1148 RESTError << "No graph for updating fits" << p->RESTendl;
1149 return std::make_pair(0, 0);
1150 }
1151 if (h->Integral() == 0) {
1152 RESTError << "Empty spectrum " << h->GetName() << p->RESTendl;
1153 return std::make_pair(0, 0);
1154 }
1155
1156 // Clear the points of the graph
1157 for (size_t i = 0; i < fEnergyPeaks.size(); i++) gr->RemovePoint(i);
1158 // Add the new points to the graph
1159 int c = 0;
1160 for (size_t i = 0; i < fEnergyPeaks.size(); i++) {
1161 std::string fitName = (std::string) "g" + std::to_string(i);
1162 TF1* g = h->GetFunction(fitName.c_str());
1163 if (!g) {
1164 RESTWarning << "No fit ( " << fitName << " ) found for energy peak " << fEnergyPeaks[i]
1165 << " in histogram " << h->GetName() << p->RESTendl;
1166 continue;
1167 }
1168 gr->SetPoint(c++, g->GetParameter(1), fEnergyPeaks[i]);
1169 }
1170
1171 // Add zero points if needed (if there are less than 2 points)
1172 while (gr->GetN() < 2) {
1173 gr->SetPoint(c++, 0, 0);
1174 }
1175
1176 // Refit the calibration curve
1177 TF1* lf = nullptr;
1178 if (gr->GetFunction("linearFit"))
1179 lf = gr->GetFunction("linearFit");
1180 else
1181 lf = new TF1("linearFit", "pol1");
1182 gr->Fit(lf, "SQ"); // Q for quiet mode
1183
1184 return std::make_pair(lf->GetParameter(0), lf->GetParameter(1));
1185}
1186
1193 auto [intercept, slope] = UpdateCalibrationFits(fFullSpectrum, fFullLinearFit);
1194 fFullSlope = slope;
1195 fFullIntercept = intercept;
1196}
1197
1213 if (module == nullptr) {
1214 RESTError << "TRestDataSetGainMap::Module::LoadConfigFromTiXmlElement: module is nullptr"
1215 << p->RESTendl;
1216 return;
1217 }
1218
1219 std::string el = !module->Attribute("planeId") ? "Not defined" : module->Attribute("planeId");
1220 if (!(el.empty() || el == "Not defined")) this->SetPlaneId(StringToInteger(el));
1221 el = !module->Attribute("moduleId") ? "Not defined" : module->Attribute("moduleId");
1222 if (!(el.empty() || el == "Not defined")) this->SetModuleId(StringToInteger(el));
1223
1224 el = !module->Attribute("moduleDefinitionCut") ? "Not defined" : module->Attribute("moduleDefinitionCut");
1225 if (!(el.empty() || el == "Not defined")) this->SetModuleDefinitionCut(el);
1226
1227 el = !module->Attribute("numberOfSegmentsX") ? "Not defined" : module->Attribute("numberOfSegmentsX");
1228 if (!(el.empty() || el == "Not defined")) this->SetNumberOfSegmentsX(StringToInteger(el));
1229 el = !module->Attribute("numberOfSegmentsY") ? "Not defined" : module->Attribute("numberOfSegmentsY");
1230 if (!(el.empty() || el == "Not defined")) this->SetNumberOfSegmentsY(StringToInteger(el));
1231 el = !module->Attribute("readoutRange") ? "Not defined" : module->Attribute("readoutRange");
1232 if (!(el.empty() || el == "Not defined")) this->SetReadoutRange(StringTo2DVector(el));
1233
1234 el = !module->Attribute("calibRange") ? "Not defined" : module->Attribute("calibRange");
1235 if (!(el.empty() || el == "Not defined")) this->SetCalibrationRange(StringTo2DVector(el));
1236 el = !module->Attribute("nBins") ? "Not defined" : module->Attribute("nBins");
1237 if (!(el.empty() || el == "Not defined")) this->SetNBins(StringToInteger(el));
1238
1239 el = !module->Attribute("dataSetFileName") ? "Not defined" : module->Attribute("dataSetFileName");
1240 if (!(el.empty() || el == "Not defined")) this->SetDataSetFileName(el);
1241
1242 el = !module->Attribute("zeroPoint") ? "Not defined" : module->Attribute("zeroPoint");
1243 if (!(el.empty() || el == "Not defined")) this->SetZeroPoint(ToLower(el) == "true");
1244 el = !module->Attribute("autoRangePeaks") ? "Not defined" : module->Attribute("autoRangePeaks");
1245 if (!(el.empty() || el == "Not defined")) this->SetAutoRangePeaks(ToLower(el) == "true");
1246
1247 // Get peaks energy and range
1248 TiXmlElement* peakDefinition = (TiXmlElement*)module->FirstChildElement("peak");
1249 while (peakDefinition != nullptr) {
1250 double energy = 0;
1251 TVector2 range = TVector2(0, 0);
1252
1253 std::string ell =
1254 !peakDefinition->Attribute("energy") ? "Not defined" : peakDefinition->Attribute("energy");
1255 if (ell.empty() || ell == "Not defined") {
1256 RESTError << "< peak variable key does not contain energy!" << p->RESTendl;
1257 exit(1);
1258 }
1259 energy = StringToDouble(ell);
1260
1261 ell = !peakDefinition->Attribute("range") ? "Not defined" : peakDefinition->Attribute("range");
1262 if (!(ell.empty() || ell == "Not defined")) range = StringTo2DVector(ell);
1263
1264 this->AddPeak(energy, range);
1265 peakDefinition = (TiXmlElement*)peakDefinition->NextSiblingElement();
1266 }
1267}
1268
1269void TRestDataSetGainMap::Module::DrawSpectrum(const TVector2& position, bool drawFits, int color,
1270 TCanvas* c) {
1271 std::pair<size_t, size_t> index = GetIndexMatrix(position.X(), position.Y());
1272 DrawSpectrum(index.first, index.second, drawFits, color, c);
1273}
1274
1275void TRestDataSetGainMap::Module::DrawSpectrum(const int index_x, const int index_y, bool drawFits, int color,
1276 TCanvas* c) {
1277 if (fSegSpectra.size() == 0) {
1278 RESTError << "Spectra matrix is empty." << p->RESTendl;
1279 return;
1280 }
1281 if (index_x < 0 || index_y < 0 || index_x >= (int)fSegSpectra.size() ||
1282 index_y >= (int)fSegSpectra.at(index_x).size()) {
1283 RESTError << "Index out of range." << p->RESTendl;
1284 return;
1285 }
1286 if (!fSegSpectra[index_x][index_y]) {
1287 RESTError << "No Spectrum for segment (" << index_x << ", " << index_y << ")." << p->RESTendl;
1288 return;
1289 }
1290
1291 if (!c) {
1292 std::string t = "spectrum_" + std::to_string(fPlaneId) + "_" + std::to_string(fModuleId) + "_" +
1293 std::to_string(index_x) + "_" + std::to_string(index_y);
1294 c = new TCanvas(t.c_str(), t.c_str());
1295 }
1296
1297 auto xLower = *std::next(fSplitX.begin(), index_x);
1298 auto xUpper = *std::next(fSplitX.begin(), index_x + 1);
1299 auto yLower = *std::next(fSplitY.begin(), index_y);
1300 auto yUpper = *std::next(fSplitY.begin(), index_y + 1);
1301 std::string tH = "Spectrum x=[" + DoubleToString(xLower, "%g") + ", " + DoubleToString(xUpper, "%g") +
1302 ") y=[" + DoubleToString(yLower, "%g") + ", " + DoubleToString(yUpper, "%g") + ");" +
1303 GetObservable() + ";counts";
1304 fSegSpectra[index_x][index_y]->SetTitle(tH.c_str());
1305
1306 if (color > 0) fSegSpectra[index_x][index_y]->SetLineColor(color);
1307 size_t colorT = fSegSpectra[index_x][index_y]->GetLineColor();
1308 fSegSpectra[index_x][index_y]->Draw("same");
1309
1310 if (drawFits)
1311 for (size_t c = 0; c < fEnergyPeaks.size(); c++) {
1312 auto fit = fSegSpectra[index_x][index_y]->GetFunction(("g" + std::to_string(c)).c_str());
1313 if (!fit)
1314 RESTWarning << "Fit for energy peak " << fEnergyPeaks[c] << " not found." << p->RESTendl;
1315 if (!fit) continue;
1316 fit->SetLineColor(c + 2 != colorT ? c + 2 : ++colorT); /* does not work with kRed, kBlue, etc.
1317 as they are not defined with the same number as the first 10 basic colors. See
1318 https://root.cern.ch/doc/master/classTColor.html#C01 and
1319 https://root.cern.ch/doc/master/classTColor.html#C02 */
1320 fit->Draw("same");
1321 }
1322}
1323
1343void TRestDataSetGainMap::Module::DrawSpectrum(const bool drawFits, const int color, TCanvas* c) {
1344 if (fSegSpectra.size() == 0) {
1345 RESTError << "Spectra matrix is empty." << p->RESTendl;
1346 return;
1347 }
1348 if (!c) {
1349 std::string t = "spectrum_" + std::to_string(fPlaneId) + "_" + std::to_string(fModuleId);
1350 c = new TCanvas(t.c_str(), t.c_str());
1351 }
1352
1353 size_t nPads = 0;
1354 for (const auto& object : *c->GetListOfPrimitives())
1355 if (object->InheritsFrom(TVirtualPad::Class())) ++nPads;
1356 if (nPads != 0 && nPads != fSegSpectra.size() * fSegSpectra.at(0).size()) {
1357 RESTError << "Canvas " << c->GetName() << " has " << nPads << " pads, but "
1358 << fSegSpectra.size() * fSegSpectra.at(0).size() << " are needed." << p->RESTendl;
1359 return;
1360 } else if (nPads == 0)
1361 c->Divide(fSegSpectra.size(), fSegSpectra.at(0).size());
1362
1363 for (size_t i = 0; i < fSegSpectra.size(); i++) {
1364 for (size_t j = 0; j < fSegSpectra[i].size(); j++) {
1365 int pad = fSegSpectra.size() * (fSegSpectra[i].size() - 1) + 1 + i - fSegSpectra.size() * j;
1366 c->cd(pad);
1367 DrawSpectrum(i, j, drawFits, color, c);
1368 }
1369 }
1370}
1371void TRestDataSetGainMap::Module::DrawFullSpectrum(const bool drawFits, const int color, TCanvas* c) {
1372 if (!fFullSpectrum) {
1373 RESTError << "Spectrum is empty." << p->RESTendl;
1374 return;
1375 }
1376
1377 if (!c) {
1378 std::string t = "fullSpc_" + std::to_string(fPlaneId) + "_" + std::to_string(fModuleId);
1379 c = new TCanvas(t.c_str(), t.c_str());
1380 }
1381 c->cd();
1382
1383 fFullSpectrum->SetTitle(("Full spectrum;" + GetObservable() + ";counts").c_str());
1384
1385 if (color > 0) fFullSpectrum->SetLineColor(color);
1386 size_t colorT = fFullSpectrum->GetLineColor();
1387 fFullSpectrum->Draw("same");
1388
1389 if (drawFits)
1390 for (size_t c = 0; c < fEnergyPeaks.size(); c++) {
1391 auto fit = fFullSpectrum->GetFunction(("g" + std::to_string(c)).c_str());
1392 if (!fit) RESTWarning << "Fit for energy peak" << fEnergyPeaks[c] << " not found." << p->RESTendl;
1393 if (!fit) continue;
1394 fit->SetLineColor(c + 2 != colorT ? c + 2 : ++colorT); /* does not work with kRed, kBlue, etc.
1395 as they are not defined with the same number as the first 10 basic colors. See
1396 https://root.cern.ch/doc/master/classTColor.html#C01 and
1397 https://root.cern.ch/doc/master/classTColor.html#C02 */
1398 fit->Draw("same");
1399 }
1400}
1401
1402void TRestDataSetGainMap::Module::DrawLinearFit(const TVector2& position, TCanvas* c) {
1403 std::pair<size_t, size_t> index = GetIndexMatrix(position.X(), position.Y());
1404 DrawLinearFit(index.first, index.second, c);
1405}
1406
1407void TRestDataSetGainMap::Module::DrawLinearFit(const int index_x, const int index_y, TCanvas* c) {
1408 if (fSegLinearFit.size() == 0) {
1409 RESTError << "Spectra matrix is empty." << p->RESTendl;
1410 return;
1411 }
1412 if (index_x < 0 || index_y < 0 || index_x >= (int)fSegLinearFit.size() ||
1413 index_y >= (int)fSegLinearFit.at(index_x).size()) {
1414 RESTError << "Index out of range." << p->RESTendl;
1415 return;
1416 }
1417 if (!fSegLinearFit[index_x][index_y]) {
1418 RESTError << "No linear fit for segment (" << index_x << ", " << index_y << ")." << p->RESTendl;
1419 return;
1420 }
1421
1422 if (!c) {
1423 std::string t = "linearFit_" + std::to_string(fPlaneId) + "_" + std::to_string(fModuleId) + "_" +
1424 std::to_string(index_x) + "_" + std::to_string(index_y);
1425 c = new TCanvas(t.c_str(), t.c_str());
1426 }
1427 auto xLower = *std::next(fSplitX.begin(), index_x);
1428 auto xUpper = *std::next(fSplitX.begin(), index_x + 1);
1429 auto yLower = *std::next(fSplitY.begin(), index_y);
1430 auto yUpper = *std::next(fSplitY.begin(), index_y + 1);
1431 std::string tH = "Linear Fit x=[" + DoubleToString(xLower, "%g") + ", " + DoubleToString(xUpper, "%g") +
1432 ") y=[" + DoubleToString(yLower, "%g") + ", " + DoubleToString(yUpper, "%g") + ");" +
1433 GetObservable() + ";energy";
1434 fSegLinearFit[index_x][index_y]->SetTitle(tH.c_str());
1435 fSegLinearFit[index_x][index_y]->Draw("AL*");
1436}
1437
1438void TRestDataSetGainMap::Module::DrawLinearFit(TCanvas* c) {
1439 if (fSegLinearFit.size() == 0) {
1440 RESTError << "Spectra matrix is empty." << p->RESTendl;
1441 return;
1442 }
1443 if (!c) {
1444 std::string t = "linearFits_" + std::to_string(fPlaneId) + "_" + std::to_string(fModuleId);
1445 c = new TCanvas(t.c_str(), t.c_str());
1446 }
1447
1448 size_t nPads = 0;
1449 for (const auto& object : *c->GetListOfPrimitives())
1450 if (object->InheritsFrom(TVirtualPad::Class())) ++nPads;
1451 if (nPads != 0 && nPads != fSegLinearFit.size() * fSegLinearFit.at(0).size()) {
1452 RESTError << "Canvas " << c->GetName() << " has " << nPads << " pads, but "
1453 << fSegLinearFit.size() * fSegLinearFit.at(0).size() << " are needed." << p->RESTendl;
1454 return;
1455 } else if (nPads == 0)
1456 c->Divide(fSegLinearFit.size(), fSegLinearFit.at(0).size());
1457
1458 for (size_t i = 0; i < fSegLinearFit.size(); i++) {
1459 for (size_t j = 0; j < fSegLinearFit[i].size(); j++) {
1460 int pad = fSegLinearFit.size() * (fSegLinearFit[i].size() - 1) + 1 + i - fSegLinearFit.size() * j;
1461 c->cd(pad);
1462 DrawLinearFit(i, j, c);
1463 }
1464 }
1465}
1466
1476void TRestDataSetGainMap::Module::DrawGainMap(const int peakNumber, const bool fullModuleAsRef,
1477 const bool showText) {
1478 if (peakNumber < 0 || peakNumber >= (int)fEnergyPeaks.size()) {
1479 RESTError << "Peak number out of range (peakNumber should be between 0 and "
1480 << fEnergyPeaks.size() - 1 << " )" << p->RESTendl;
1481 return;
1482 }
1483 if (fSegLinearFit.size() == 0) {
1484 RESTError << "Linear fit matrix is empty." << p->RESTendl;
1485 return;
1486 }
1487 if (!fFullLinearFit) {
1488 RESTError << "Full linear fit is empty." << p->RESTendl;
1489 return;
1490 }
1491
1492 double peakEnergy = fEnergyPeaks[peakNumber];
1493 std::string title = "Gain map for energy " + DoubleToString(peakEnergy, "%g") + ";" +
1494 GetSpatialObservableX() + ";" + GetSpatialObservableY(); // + " keV";
1495 std::string t = "gainMap" + std::to_string(peakNumber) + "_" + std::to_string(fPlaneId) + "_" +
1496 std::to_string(fModuleId);
1497 TCanvas* gainMap = new TCanvas(t.c_str(), t.c_str());
1498 gainMap->cd();
1499 TH2F* hGainMap = new TH2F(("h" + t).c_str(), title.c_str(), fNumberOfSegmentsX, fReadoutRange.X(),
1501
1502 double peakPosRef = fFullLinearFit->GetPointX(peakNumber);
1503 if (!fullModuleAsRef) {
1504 int index_x = fNumberOfSegmentsX > 0 ? (fNumberOfSegmentsX - 1) / 2 : 0;
1505 int index_y = fNumberOfSegmentsY > 0 ? (fNumberOfSegmentsY - 1) / 2 : 0;
1506 peakPosRef = fSegLinearFit[index_x][index_y]->GetPointX(peakNumber);
1507 }
1508
1509 auto itX = fSplitX.begin();
1510 for (size_t i = 0; i < fSegLinearFit.size(); i++) {
1511 auto itY = fSplitY.begin();
1512 for (size_t j = 0; j < fSegLinearFit.at(0).size(); j++) {
1513 auto xLower = *itX;
1514 auto xUpper = *std::next(itX);
1515 auto yLower = *itY;
1516 auto yUpper = *std::next(itY);
1517 float xMean = (xUpper + xLower) / 2.;
1518 float yMean = (yUpper + yLower) / 2.;
1519 auto [index_x, index_y] = GetIndexMatrix(xMean, yMean);
1520 if (!fSegLinearFit[index_x][index_y]) continue;
1521 hGainMap->Fill(xMean, yMean, fSegLinearFit[index_x][index_y]->GetPointX(peakNumber) / peakPosRef);
1522 itY++;
1523 }
1524 itX++;
1525 }
1526 hGainMap->SetStats(0);
1527 hGainMap->Draw("colz");
1528 hGainMap->SetBarOffset(0.2);
1529 if (showText) {
1530 hGainMap->Draw("TEXT SAME");
1531 }
1532}
1533
1539 RESTMetadata << "-----------------------------------------------" << p->RESTendl;
1540 RESTMetadata << " Plane ID: " << fPlaneId << p->RESTendl;
1541 RESTMetadata << " Module ID: " << fModuleId << p->RESTendl;
1542 RESTMetadata << " Definition cut: " << fDefinitionCut << p->RESTendl;
1543 RESTMetadata << p->RESTendl;
1544
1545 RESTMetadata << " Calibration dataset: " << fDataSetFileName << p->RESTendl;
1546 RESTMetadata << p->RESTendl;
1547
1548 RESTMetadata << " Energy peaks: ";
1549 for (const auto& peak : fEnergyPeaks) RESTMetadata << peak << ", ";
1550 RESTMetadata << p->RESTendl;
1551 bool anyRange = false;
1552 for (const auto& r : fRangePeaks)
1553 if (r.X() < r.Y()) {
1554 RESTMetadata << " Range peaks: ";
1555 anyRange = true;
1556 break;
1557 }
1558 if (anyRange)
1559 for (const auto& r : fRangePeaks) RESTMetadata << "(" << r.X() << ", " << r.Y() << ") ";
1560 if (anyRange) RESTMetadata << p->RESTendl;
1561 RESTMetadata << " Auto range peaks: " << (fAutoRangePeaks ? "true" : "false") << p->RESTendl;
1562 RESTMetadata << " Zero point: " << (fZeroPoint ? "true" : "false") << p->RESTendl;
1563 RESTMetadata << " Calibration range: (" << fCalibRange.X() << ", " << fCalibRange.Y() << " )"
1564 << p->RESTendl;
1565 RESTMetadata << " Number of bins: " << fNBins << p->RESTendl;
1566 RESTMetadata << p->RESTendl;
1567
1568 RESTMetadata << " Number of segments X: " << fNumberOfSegmentsX << p->RESTendl;
1569 RESTMetadata << " Number of segments Y: " << fNumberOfSegmentsY << p->RESTendl;
1570 // RESTMetadata << " Draw: " << (fDrawVar ? "true" : "false") << p->RESTendl;
1571 RESTMetadata << " Readout range (" << fReadoutRange.X() << ", " << fReadoutRange.Y() << " )"
1572 << p->RESTendl;
1573 RESTMetadata << "SplitX: ";
1574 for (auto& i : fSplitX) {
1575 RESTMetadata << " " << i;
1576 }
1577 RESTMetadata << p->RESTendl;
1578 RESTMetadata << "SplitY: ";
1579 for (auto& i : fSplitY) {
1580 RESTMetadata << " " << i;
1581 }
1582 RESTMetadata << p->RESTendl;
1583 RESTMetadata << p->RESTendl;
1584
1585 RESTMetadata << " Slope: " << p->RESTendl;
1586 size_t maxSize = 0;
1587 for (auto& x : fSlope)
1588 if (maxSize < x.size()) maxSize = x.size();
1589 for (size_t j = 0; j < maxSize; j++) {
1590 for (size_t k = 0; k < fSlope.size(); k++) {
1591 if (j < fSlope[k].size())
1592 RESTMetadata << DoubleToString(fSlope[k][fSlope[k].size() - 1 - j], "%.3e") << " ";
1593 else
1594 RESTMetadata << " ";
1595 }
1596 RESTMetadata << p->RESTendl;
1597 }
1598 RESTMetadata << " Intercept: " << p->RESTendl;
1599 maxSize = 0;
1600 for (auto& x : fIntercept)
1601 if (maxSize < x.size()) maxSize = x.size();
1602 for (size_t j = 0; j < maxSize; j++) {
1603 for (size_t k = 0; k < fIntercept.size(); k++) {
1604 if (j < fIntercept[k].size())
1605 RESTMetadata << DoubleToString(fIntercept[k][fIntercept[k].size() - 1 - j], "%+.3e") << " ";
1606 else
1607 RESTMetadata << " ";
1608 }
1609 RESTMetadata << p->RESTendl;
1610 }
1611 RESTMetadata << p->RESTendl;
1612 RESTMetadata << " Full slope: " << DoubleToString(fFullSlope, "%.3e") << p->RESTendl;
1613 RESTMetadata << " Full intercept: " << DoubleToString(fFullIntercept, "%+.3e") << p->RESTendl;
1614
1615 RESTMetadata << "-----------------------------------------------" << p->RESTendl;
1616}
A class to help on cuts definitions. To be used with TRestAnalysisTree.
Definition TRestCut.h:31
double fFullIntercept
Intercept of the calibration linear fit of whole module.
std::vector< std::vector< double > > fIntercept
Array containing the intercept of the linear fit for each segment.
Int_t fNumberOfSegmentsY
Number of segments in the y direction.
void SetSplitY()
Function to set the class members for segmentation of the detector plane along the Y axis.
std::vector< std::vector< TGraph * > > fSegLinearFit
Array containing the calibration linear fit for each segment.
void SetSplits()
Function to set the class members for segmentation of the detector plane along the X and Y axis.
void SetSplitX()
Function to set the class members for segmentation of the detector plane along the X axis.
std::vector< std::vector< TH1F * > > fSegSpectra
Array containing the observable spectrum for each segment.
void DrawSpectrum(const bool drawFits=true, const int color=-1, TCanvas *c=nullptr)
Function to draw the spectrum for each segment of the module on the same canvas. The canvas is divide...
void LoadConfigFromTiXmlElement(const TiXmlElement *module)
Function to read the parameters from the RML element (TiXmlElement) and set those class members.
void GenerateGainMap()
Function that calculates the calibration parameters for each segment defined at fSplitX and fSplitY a...
double fFullSlope
Slope of the calibration linear fit of whole module.
void DrawGainMap(const int peakNumber=0, const bool fullModuleAsRef=true, const bool showText=true)
Function to draw the relative gain map for a given energy peak of the module.
double GetSlope(const double x, const double y) const
Function to get the calibration parameter slope for a given x and y position on the detector plane.
std::set< double > fSplitX
Split points in the x direction.
void Print() const
Prints on screen the information about the members of Module.
void Refit(const TVector2 &position, const double energy, const TVector2 &range)
Function to fit again manually a peak for a given segment of the module.
std::set< double > fSplitY
Split points in the y direction.
void RefitFullSpc(const double energy, const TVector2 &range)
Function to fit again manually a peak for the whole module spectrum. The calibration curve is updated...
std::vector< TVector2 > fRangePeaks
Range of the peaks to be used for the calibration. If empty it will be automatically calculated.
const TRestDataSetGainMap * p
Pointer to the parent class.
void UpdateCalibrationFitsFullSpc()
Function to update the calibration curve for the whole module. The calibration curve is cleared and t...
std::vector< std::vector< double > > fSlope
Array containing the slope of the linear fit for each segment.
Int_t fNumberOfSegmentsX
Number of segments in the x direction.
Int_t fNBins
Number of bins for the spectrum histograms.
TVector2 fCalibRange
Calibration range. If fCalibRange.X()>=fCalibRange.Y() the range will be automatically calculated.
std::string fDefinitionCut
Cut that defines which events are from this module. Default is "1" (all events).
TGraph * fFullLinearFit
Calibration linear fit for the whole module.
TH1F * fFullSpectrum
Spectrum of the observable for the whole module.
bool fAutoRangePeaks
Automatic range for the peaks fitting. See GenerateGainMap() for more information of the logic.
double GetIntercept(const double x, const double y) const
Function to get the calibration parameter intercept for a given x and y position on the detector plan...
TVector2 fReadoutRange
Readout dimensions.
std::pair< int, int > GetIndexMatrix(const double x, const double y) const
Function to get the index of the matrix of calibration parameters for a given x and y position on the...
std::vector< double > fEnergyPeaks
Energy of the peaks to be used for the calibration.
Metadata class to calculate,store and apply the gain corrected calibration of a group of detectors.
double GetInterceptParameter(const int planeID, const int moduleID, const double x, const double y)
Function to get the intercept parameter of the module with planeID and moduleID at physical position ...
double GetSlopeParameter(const int planeID, const int moduleID, const double x, const double y)
Function to get the slope parameter of the module with planeID and moduleID at physical position (x,...
std::string fObservable
Observable that will be used to calculate the gain map.
std::set< int > GetModuleIDs(const int planeId) const
Function to get a list (set) of the module IDs of the plane with planeID.
double GetInterceptParameterFullSpc(const int planeID, const int moduleID)
Function to get the intercept parameter of the whole module with planeID and moduleID.
void CalibrateDataSet(const std::string &dataSetFileName, std::string outputFileName="", std::vector< std::string > excludeColumns={})
Function to calibrate a dataset with this gain map.
~TRestDataSetGainMap()
Default destructor.
void GenerateGainMap()
Function to calculate the calibration parameters of all modules.
std::string fSpatialObservableXSecondary
Secondary observable that will be used to segmentize the gain map in the x direction (if needed).
TRestDataSetGainMap()
Default constructor.
void Initialize() override
Making default settings.
std::vector< Module > fModulesCal
List of modules.
void SetModule(const Module &moduleCal)
Function to set a module calibration. If the module calibration already exists (same planeId and modu...
void InitFromConfigFile() override
Initialization of TRestDataSetGainMap members through a RML file.
double GetSlopeParameterFullSpc(const int planeID, const int moduleID)
Function to get the slope parameter of the whole module with planeID and moduleID.
void Export(const std::string &fileName="")
Function to export the calibration to the file fileName.
void PrintMetadata() override
Prints on screen the information about the metadata members.
std::map< int, std::set< int > > GetModuleIDs() const
Function to get the map of the module IDs for each plane ID.
std::string fSpatialObservableY
Observable that will be used to segmentize the gain map in the y direction.
std::string fCalibFileName
Name of the file that contains the calibration data.
TRestCut * fCut
Cut to be applied to the calibration data.
std::string fOutputFileName
Name of the file where the gain map was (or will be) exported.
std::string fSpatialObservableYSecondary
Secondary observable that will be used to segmentize the gain map in the y direction (if needed).
std::set< int > GetPlaneIDs() const
Function to get a list (set) of the plane IDs.
std::string fSpatialObservableX
Observable that will be used to segmentize the gain map in the x direction.
Module * GetModule(const size_t index=0)
Function to retrieve the module calibration by index. Default is 0.
void Import(const std::string &fileName)
Function to import the calibration parameters from the root file fileName.
It allows to group a number of runs that satisfy given metadata conditions.
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.
ROOT::RDF::RNode MakeCut(const TRestCut *cut)
This function applies a TRestCut to the dataframe and returns a dataframe with the applied cuts....
void GenerateDataSet()
This function generates the data frame with the filelist and column names (or observables) that have ...
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.
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
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.
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 ".".
static std::set< std::string > GetMatchingStrings(const std::vector< std::string > &stack, const std::vector< std::string > &wantedStrings)
Returns a set of strings that match the wanted strings from the stack. The wanted strings can contain...
static bool isDataSet(const std::string &filename)
It checks if the file contains a dataset object.
static std::vector< std::string > GetObservablesInString(const std::string &observablesStr, bool removeDuplicates=true)
Returns a vector with the observables names found in the input string. The observables names must con...
static bool isRootFile(const std::string &filename)
Returns true if the filename has .root extension.
TClass * GetClassQuick(std::string type)
Double_t StringToDouble(std::string in)
Gets a double from a string.
Int_t StringToInteger(std::string in)
Gets an integer from a string.
std::string DoubleToString(Double_t d, std::string format="%8.6e")
Gets a string from a double.
TVector2 StringTo2DVector(std::string in)
Gets a 2D-vector from a string.
std::string ToLower(std::string in)
Convert string to its lower case. Alternative of TString::ToLower.