140#include "TRestDataSetGainMap.h"
142#include "TRestTools.h"
185 TiXmlElement* moduleDefinition =
GetElement(
"module");
186 while (moduleDefinition !=
nullptr) {
188 fModulesCal.back().LoadConfigFromTiXmlElement(moduleDefinition);
203 RESTInfo <<
"Generating gain map of plane " << mod.GetPlaneId() <<
" module " << mod.GetModuleId()
205 mod.GenerateGainMap();
208 mod.DrawFullSpectrum();
229 std::vector<std::string> excludeColumns) {
231 RESTError <<
"TRestDataSetGainMap::CalibrateDataSet: No modules defined." <<
RESTendl;
236 dataSet.EnableMultiThreading(
true);
239 dataSet.
Import(dataSetFileName);
241 RESTWarning << dataSetFileName <<
" is not a dataset. Generating a temporal one..." <<
RESTendl;
243 dataSet.SetFilePattern(dataSetFileName);
244 dataSet.SetObservablesList({
"*"});
251 std::string pmIDname = (std::string)GetName() +
"_pmID";
252 std::string modCut =
fModulesCal[0].GetModuleDefinitionCut();
253 if (modCut.empty()) modCut =
"1";
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");
260 dataFrame = dataFrame.Redefine(pmIDname, modCut +
" ? " + std::to_string(pmID) +
" : -1");
264 if (modCut.empty()) modCut =
"1";
266 dataFrame = dataFrame.Redefine(pmIDname, (modCut +
" ? " + std::to_string(pmID) +
" : " + pmIDname));
270 auto calibrate = [
this](
double val,
double x,
double y,
int pmID) {
272 if (pmID == m.GetPlaneId() * 10 + m.GetModuleId())
273 return m.GetSlope(x, y) * val + m.GetIntercept(x, y);
277 return std::numeric_limits<double>::quiet_NaN();
279 std::string calibObsName = (std::string)GetName() +
"_";
280 calibObsName += GetObservable().erase(0, GetObservable().find(
"_") + 1);
281 dataFrame = dataFrame.Define(calibObsName, calibrate,
285 auto calibrateFullSpc = [
this](
double val,
int pmID) {
287 if (pmID == m.GetPlaneId() * 10 + m.GetModuleId())
288 return m.GetSlopeFullSpc() * val + m.GetInterceptFullSpc();
292 return std::numeric_limits<double>::quiet_NaN();
294 std::string calibObsNameFullSpc = (std::string)GetName() +
"_";
295 calibObsNameFullSpc +=
296 GetObservable().erase(0, GetObservable().find(
"_") + 1);
297 calibObsNameFullSpc +=
"_NoSegmentation";
298 dataFrame = dataFrame.Define(calibObsNameFullSpc, calibrateFullSpc, {
fObservable, pmIDname});
300 dataSet.SetDataFrame(dataFrame);
303 if (outputFileName.empty()) outputFileName = dataSetFileName;
304 if (outputFileName == dataSetFileName) {
305 std::string gmName = GetName();
306 outputFileName = outputFileName.substr(0, outputFileName.find_last_of(
"."));
314 excludeCol.erase(calibObsName);
315 excludeCol.erase(calibObsNameFullSpc);
316 excludeCol.erase(pmIDname);
318 RESTDebug <<
"Excluding columns: ";
319 for (
auto& c : excludeCol) RESTDebug << c <<
", ";
322 dataSet.
Export(outputFileName, std::vector<std::string>(excludeCol.begin(), excludeCol.end()));
327 RESTError << file.Error() <<
RESTendl;
331 if (!file.Close()) RESTError << file.Error() <<
RESTendl;
341 RESTError <<
"No ModuleCalibration with index " << index;
343 RESTError <<
". There are no modules defined." <<
RESTendl;
355 if (i.GetPlaneId() == planeID && i.GetModuleId() == moduleID)
return &i;
357 RESTError <<
"No ModuleCalibration with planeID " << planeID <<
" and moduleID " << moduleID <<
RESTendl;
369 if (moduleCal ==
nullptr)
return 0;
379 if (moduleCal ==
nullptr)
return 0;
380 return moduleCal->GetSlopeFullSpc();
391 if (moduleCal ==
nullptr)
return 0;
401 if (moduleCal ==
nullptr)
return 0;
402 return moduleCal->GetInterceptFullSpc();
410 std::set<int> planeIDs;
411 for (
const auto& mc :
fModulesCal) planeIDs.insert(mc.GetPlaneId());
420 std::set<int> moduleIDs;
422 if (mc.GetPlaneId() == planeId) moduleIDs.insert(mc.GetModuleId());
430 std::map<int, std::set<int>> moduleIds;
432 moduleIds.insert(std::pair<
int, std::set<int>>(planeId,
GetModuleIDs(planeId)));
437 SetName(src.GetName());
457 if (i.GetPlaneId() == moduleCal.GetPlaneId() && i.GetModuleId() == moduleCal.GetModuleId()) {
470 if (fileName.empty()) {
471 RESTError <<
"No input calibration file defined" <<
RESTendl;
476 RESTInfo <<
"Opening " << fileName <<
RESTendl;
477 TFile* f = TFile::Open(fileName.c_str(),
"READ");
479 RESTError <<
"Cannot open calibration file " << fileName <<
RESTendl;
485 TIter nextkey(f->GetListOfKeys());
487 while ((key = (TKey*)nextkey())) {
488 std::string kName = key->GetClassName();
497 RESTError <<
"File extension not supported for " << fileName <<
RESTendl;
510 RESTError <<
"No output file defined" <<
RESTendl;
517 RESTError << file.Error() <<
RESTendl;
520 this->
Write(GetName());
522 RESTError << file.Error() <<
RESTendl;
537 RESTMetadata <<
" Cuts applied: ";
540 for (
const auto& cut :
fCut->GetCutStrings()) RESTMetadata << cut <<
", " <<
RESTendl;
541 for (
const auto& cut :
fCut->GetParamCut())
542 RESTMetadata << cut.first <<
" " << cut.second <<
", " <<
RESTendl;
546 RESTMetadata <<
" Number of planes: " << GetNumberOfPlanes() <<
RESTendl;
547 RESTMetadata <<
" Number of modules: " << GetNumberOfModules() <<
RESTendl;
555 RESTMetadata <<
"-----------------------------------------------" <<
RESTendl;
557 RESTMetadata <<
"***********************************************" <<
RESTendl;
569 int index_x = -1, index_y = -1;
572 index_x = std::distance(
fSplitX.begin(),
fSplitX.upper_bound(x)) - 1;
574 RESTWarning <<
"index_x < 0 for x = " << x <<
" and fSplitX[0]=" << *
fSplitX.begin()
579 RESTWarning <<
"x is out of split for x = " << x <<
p->
RESTendl;
584 index_y = std::distance(
fSplitY.begin(),
fSplitY.upper_bound(y)) - 1;
586 RESTWarning <<
"index_y < 0 for y = " << y <<
" and fSplitY[0]=" << *
fSplitY.begin()
591 RESTWarning <<
"y is out of split for y = " << y <<
p->
RESTendl;
595 return std::make_pair(index_x, index_y);
605 auto [index_x, index_y] = GetIndexMatrix(x, y);
606 if (fSlope.empty()) {
607 RESTError <<
"Calibration slope matrix is empty. Returning 0" << p->RESTendl;
611 if (index_x > (
int)fSlope.size() || index_y > (
int)fSlope.at(0).size()) {
612 RESTError <<
"Index out of range. Returning 0" << p->RESTendl;
616 return fSlope[index_x][index_y];
627 auto [index_x, index_y] = GetIndexMatrix(x, y);
628 if (fIntercept.empty()) {
629 RESTError <<
"Calibration constant matrix is empty. Returning 0" << p->RESTendl;
633 if (index_x > (
int)fIntercept.size() || index_y > (
int)fIntercept.at(0).size()) {
634 RESTError <<
"Index out of range. Returning 0" << p->RESTendl;
638 return fIntercept[index_x][index_y];
655 if (fNumberOfSegmentsX < 1) {
656 RESTError <<
"SetSplitX: fNumberOfSegmentsX must be >=1." << p->RESTendl;
659 std::set<double> split;
660 for (
int i = 0; i <= fNumberOfSegmentsX; i++) {
662 fReadoutRange.X() + ((fReadoutRange.Y() - fReadoutRange.X()) / (
float)fNumberOfSegmentsX) * i;
669 if (splitX.size() < 2) {
670 RESTError <<
"SetSplitX: split size must be >=2 (start and end of range must be included)."
675 RESTWarning <<
"SetSplitX: changing split but current gain map and calibration paremeters correspond "
676 "to previous splitting. Use GenerateGainMap() to update them."
679 fNumberOfSegmentsX = fSplitX.size() - 1;
688 if (fNumberOfSegmentsY < 1) {
689 RESTError <<
"SetSplitY: fNumberOfSegmentsY must be >=1." << p->RESTendl;
692 std::set<double> split;
693 for (
int i = 0; i <= fNumberOfSegmentsY; i++) {
695 fReadoutRange.X() + ((fReadoutRange.Y() - fReadoutRange.X()) / (
float)fNumberOfSegmentsY) * i;
702 if (splitY.size() < 2) {
703 RESTError <<
"SetSplitY: split size must be >=2 (start and end of range must be included)."
708 RESTWarning <<
"SetSplitY: changing split but current gain map and calibration paremeters correspond "
709 "to previous splitting. Use GenerateGainMap() to update them."
712 fNumberOfSegmentsY = fSplitY.size() - 1;
733 std::string dsFileName = fDataSetFileName;
734 if (dsFileName.empty()) dsFileName = p->GetCalibrationFileName();
735 if (dsFileName.empty()) {
736 RESTError <<
"No calibration file defined" << p->RESTendl;
741 dataSet.EnableMultiThreading(
true);
743 dataSet.
Import(dsFileName);
744 fDataSetFileName = dsFileName;
746 RESTWarning << dsFileName <<
" is not a dataset. Generating a temporal one..." << p->RESTendl;
748 std::vector<std::string> obsList;
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());
760 obsList.insert(obsList.end(), modDefCutObs.begin(), modDefCutObs.end());
763 for (
const auto& cut : p->GetCut()->GetCutStrings()) {
765 obsList.insert(obsList.end(), cutObs.begin(), cutObs.end());
767 for (
const auto& [variable, condition] : p->GetCut()->GetParamCut()) {
769 obsList.insert(obsList.end(), cutObs.begin(), cutObs.end());
772 obsList.insert(obsList.end(), cutObs.begin(), cutObs.end());
776 std::sort(obsList.begin(), obsList.end());
777 obsList.erase(std::unique(obsList.begin(), obsList.end()), obsList.end());
780 dataSet.SetFilePattern(dsFileName);
781 dataSet.SetObservablesList(obsList);
783 fDataSetFileName = dsFileName;
786 dataSet.SetDataFrame(dataSet.
MakeCut(p->GetCut()));
788 if (fSplitX.empty()) SetSplitX();
789 if (fSplitY.empty()) SetSplitY();
792 if (fCalibRange.X() >= fCalibRange.Y()) {
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()));
799 double xMax = hpunt->GetXaxis()->GetXmax();
802 double fraction = 1, nAtEndSpc = 0, step = 0.66;
803 while (nAtEndSpc * 1. / hpunt->Integral() < 0.01 && fraction > 0.001) {
805 nAtEndSpc = hpunt->Integral(hpunt->FindFixBin(hpunt->GetXaxis()->GetXmax() * fraction),
806 hpunt->FindFixBin(hpunt->GetXaxis()->GetXmax()));
808 xMax = hpunt->GetXaxis()->GetXmax() * fraction /
812 fCalibRange.SetY(xMax);
814 RESTDebug <<
"Calibration range (auto)set to (" << fCalibRange.X() <<
"," << fCalibRange.Y() <<
")"
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());
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());
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(),
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++) {
848 auto xUpper = *std::next(itX);
850 auto yUpper = *std::next(itY);
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;
870 .Histo1D({
"temp",
"", h[i][j]->GetNbinsX(), h[i][j]->GetXaxis()->GetXmin(),
871 h[i][j]->GetXaxis()->GetXmax()},
873 std::unique_ptr<TH1F> hpunt = std::unique_ptr<TH1F>(
static_cast<TH1F*
>(histo->Clone()));
874 h[i][j]->Add(hpunt.get());
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;
894 fSlope = calParSlope;
895 fIntercept = calParIntercept;
899 delete fFullLinearFit;
900 fFullLinearFit =
new TGraph();
901 auto [intercept, slope] = FitPeaks(fFullSpectrum, fFullLinearFit);
903 fFullIntercept = intercept;
906std::pair<double, double> TRestDataSetGainMap::Module::FitPeaks(TH1F* hSeg, TGraph* gr) {
908 RESTError <<
"No histogram for fitting" << p->RESTendl;
909 return std::make_pair(0, 0);
911 if (hSeg->Integral() == 0) {
912 RESTError <<
"Empty spectrum " << hSeg->GetName() << p->RESTendl;
913 return std::make_pair(0, 0);
915 std::shared_ptr<TGraph> graph = std::shared_ptr<TGraph>(
new TGraph());
916 RESTExtreme <<
"Fitting peaks for " << hSeg->GetName() << p->RESTendl;
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>());
925 peakPos.size() == 0 ? 1 : peakPos.front() / fEnergyPeaks.front();
928 graph->SetName(
"grFit");
929 graph->SetTitle((
";" + GetObservable() +
";energy").c_str());
934 for (
const auto& energy : fEnergyPeaks) {
935 RESTExtreme <<
"\t fitting energy " <<
DoubleToString(energy,
"%g") << p->RESTendl;
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()) {
941 start = fRangePeaks.at(c).X();
942 end = fRangePeaks.at(c).Y();
946 if (fAutoRangePeaks) {
947 if (peakPos.size() > 0) {
950 while (!(start < pos && pos < end)) {
953 if (pos == peakPos.back()) {
957 pos = *std::next(std::find(peakPos.begin(), peakPos.end(),
960 peakPos.erase(std::find(peakPos.begin(), peakPos.end(),
966 const double relDist = peakPos.size() > 0 ? (pos - peakPos.front()) / pos : 999;
968 start = pos * (1 - relDist / 2);
969 end = pos * (1 + relDist / 2);
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("
980 if (hSeg->GetFunction(name.c_str()))
981 hSeg->GetListOfFunctions()->Remove(hSeg->GetFunction(name.c_str()));
983 hSeg->Fit(g,
"R+Q0");
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));
988 graph->SetPoint(c++, mu, energy);
992 if (fZeroPoint) graph->SetPoint(c++, 0, 0);
993 while (graph->GetN() < 2) {
994 graph->SetPoint(c++, 0, 0);
996 RESTDebug <<
"Not enough points for linear fit. Adding and setting zero point to true" << p->RESTendl;
1000 std::unique_ptr<TF1> linearFit;
1001 linearFit = std::unique_ptr<TF1>(
new TF1(
"linearFit",
"pol1"));
1002 graph->Fit(
"linearFit",
"SQ");
1004 if (gr) *gr = *(TGraph*)graph->Clone();
1005 return std::make_pair(linearFit->GetParameter(0), linearFit->GetParameter(1));
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) {
1024 if (peakNumber == -1) {
1025 RESTError <<
"Energy " << energyPeak <<
" not found in the list of energy peaks" << p->RESTendl;
1028 Refit((
size_t)index_x, (
size_t)index_y, (
size_t)peakNumber, range);
1041 const TVector2& range) {
1042 if (fSegSpectra.empty()) {
1043 RESTError <<
"No gain map found. Use GenerateGainMap() first." << p->RESTendl;
1046 if (x >= fSegSpectra.size() || y >= fSegSpectra.at(0).size()) {
1047 RESTError <<
"Segment with index (" << x <<
", " << y <<
") not found" << p->RESTendl;
1050 if (peakNumber >= fEnergyPeaks.size()) {
1051 RESTError <<
"Peak with index " << peakNumber <<
" not found" << p->RESTendl;
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()))
1060 h->GetListOfFunctions()->Remove(h->GetFunction(name.c_str()));
1064 UpdateCalibrationFits(x, y);
1075 int peakNumber = -1;
1076 for (
size_t i = 0; i < fEnergyPeaks.size(); i++)
1077 if (fEnergyPeaks.at(i) == energyPeak) {
1081 if (peakNumber == -1) {
1082 RESTError <<
"Energy " << energyPeak <<
" not found in the list of energy peaks" << p->RESTendl;
1085 RefitFullSpc((
size_t)peakNumber, range);
1096 if (!fFullSpectrum) {
1097 RESTError <<
"No gain map found. Use GenerateGainMap() first." << p->RESTendl;
1100 if (peakNumber >= fEnergyPeaks.size()) {
1101 RESTError <<
"Peak with index " << peakNumber <<
" not found" << p->RESTendl;
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()))
1109 fFullSpectrum->GetListOfFunctions()->Remove(fFullSpectrum->GetFunction(name.c_str()));
1110 fFullSpectrum->Fit(g,
"R+Q0");
1113 UpdateCalibrationFitsFullSpc();
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;
1129 if (x >= fSegSpectra.size() || y >= fSegSpectra.at(0).size()) {
1130 RESTError <<
"Segment with index (" << x <<
", " << y <<
") not found" << p->RESTendl;
1134 TH1F* h = fSegSpectra.at(x).at(y);
1135 TGraph* gr = fSegLinearFit.at(x).at(y);
1137 auto [intercept, slope] = UpdateCalibrationFits(h, gr);
1138 fSlope[x][y] = slope;
1139 fIntercept[x][y] = intercept;
1142std::pair<double, double> TRestDataSetGainMap::Module::UpdateCalibrationFits(TH1F* h, TGraph* gr) {
1144 RESTError <<
"No histogram for updating fits" << p->RESTendl;
1145 return std::make_pair(0, 0);
1148 RESTError <<
"No graph for updating fits" << p->RESTendl;
1149 return std::make_pair(0, 0);
1151 if (h->Integral() == 0) {
1152 RESTError <<
"Empty spectrum " << h->GetName() << p->RESTendl;
1153 return std::make_pair(0, 0);
1157 for (
size_t i = 0; i < fEnergyPeaks.size(); i++) gr->RemovePoint(i);
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());
1164 RESTWarning <<
"No fit ( " << fitName <<
" ) found for energy peak " << fEnergyPeaks[i]
1165 <<
" in histogram " << h->GetName() << p->RESTendl;
1168 gr->SetPoint(c++, g->GetParameter(1), fEnergyPeaks[i]);
1172 while (gr->GetN() < 2) {
1173 gr->SetPoint(c++, 0, 0);
1178 if (gr->GetFunction(
"linearFit"))
1179 lf = gr->GetFunction(
"linearFit");
1181 lf =
new TF1(
"linearFit",
"pol1");
1184 return std::make_pair(lf->GetParameter(0), lf->GetParameter(1));
1193 auto [intercept, slope] = UpdateCalibrationFits(fFullSpectrum, fFullLinearFit);
1195 fFullIntercept = intercept;
1213 if (module ==
nullptr) {
1214 RESTError <<
"TRestDataSetGainMap::Module::LoadConfigFromTiXmlElement: module is nullptr"
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));
1224 el = !module->Attribute(
"moduleDefinitionCut") ?
"Not defined" : module->Attribute(
"moduleDefinitionCut");
1225 if (!(el.empty() || el ==
"Not defined")) this->SetModuleDefinitionCut(el);
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));
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));
1239 el = !module->Attribute(
"dataSetFileName") ?
"Not defined" : module->Attribute(
"dataSetFileName");
1240 if (!(el.empty() || el ==
"Not defined")) this->SetDataSetFileName(el);
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");
1248 TiXmlElement* peakDefinition = (TiXmlElement*)module->FirstChildElement(
"peak");
1249 while (peakDefinition !=
nullptr) {
1251 TVector2 range = TVector2(0, 0);
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;
1261 ell = !peakDefinition->Attribute(
"range") ?
"Not defined" : peakDefinition->Attribute(
"range");
1264 this->AddPeak(energy, range);
1265 peakDefinition = (TiXmlElement*)peakDefinition->NextSiblingElement();
1271 std::pair<size_t, size_t> index = GetIndexMatrix(position.X(), position.Y());
1272 DrawSpectrum(index.first, index.second, drawFits, color, c);
1277 if (fSegSpectra.size() == 0) {
1278 RESTError <<
"Spectra matrix is empty." << p->RESTendl;
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;
1286 if (!fSegSpectra[index_x][index_y]) {
1287 RESTError <<
"No Spectrum for segment (" << index_x <<
", " << index_y <<
")." << p->RESTendl;
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());
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);
1303 GetObservable() +
";counts";
1304 fSegSpectra[index_x][index_y]->SetTitle(tH.c_str());
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");
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());
1314 RESTWarning <<
"Fit for energy peak " << fEnergyPeaks[c] <<
" not found." << p->RESTendl;
1316 fit->SetLineColor(c + 2 != colorT ? c + 2 : ++colorT);
1344 if (fSegSpectra.size() == 0) {
1345 RESTError <<
"Spectra matrix is empty." << p->RESTendl;
1349 std::string t =
"spectrum_" + std::to_string(fPlaneId) +
"_" + std::to_string(fModuleId);
1350 c =
new TCanvas(t.c_str(), t.c_str());
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;
1360 }
else if (nPads == 0)
1361 c->Divide(fSegSpectra.size(), fSegSpectra.at(0).size());
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;
1367 DrawSpectrum(i, j, drawFits, color, c);
1371void TRestDataSetGainMap::Module::DrawFullSpectrum(
const bool drawFits,
const int color, TCanvas* c) {
1372 if (!fFullSpectrum) {
1373 RESTError <<
"Spectrum is empty." << p->RESTendl;
1378 std::string t =
"fullSpc_" + std::to_string(fPlaneId) +
"_" + std::to_string(fModuleId);
1379 c =
new TCanvas(t.c_str(), t.c_str());
1383 fFullSpectrum->SetTitle((
"Full spectrum;" + GetObservable() +
";counts").c_str());
1385 if (color > 0) fFullSpectrum->SetLineColor(color);
1386 size_t colorT = fFullSpectrum->GetLineColor();
1387 fFullSpectrum->Draw(
"same");
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;
1394 fit->SetLineColor(c + 2 != colorT ? c + 2 : ++colorT);
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);
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;
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;
1417 if (!fSegLinearFit[index_x][index_y]) {
1418 RESTError <<
"No linear fit for segment (" << index_x <<
", " << index_y <<
")." << p->RESTendl;
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());
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);
1433 GetObservable() +
";energy";
1434 fSegLinearFit[index_x][index_y]->SetTitle(tH.c_str());
1435 fSegLinearFit[index_x][index_y]->Draw(
"AL*");
1438void TRestDataSetGainMap::Module::DrawLinearFit(TCanvas* c) {
1439 if (fSegLinearFit.size() == 0) {
1440 RESTError <<
"Spectra matrix is empty." << p->RESTendl;
1444 std::string t =
"linearFits_" + std::to_string(fPlaneId) +
"_" + std::to_string(fModuleId);
1445 c =
new TCanvas(t.c_str(), t.c_str());
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;
1455 }
else if (nPads == 0)
1456 c->Divide(fSegLinearFit.size(), fSegLinearFit.at(0).size());
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;
1462 DrawLinearFit(i, j, c);
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;
1483 if (fSegLinearFit.size() == 0) {
1484 RESTError <<
"Linear fit matrix is empty." << p->RESTendl;
1487 if (!fFullLinearFit) {
1488 RESTError <<
"Full linear fit is empty." << p->RESTendl;
1492 double peakEnergy = fEnergyPeaks[peakNumber];
1493 std::string title =
"Gain map for energy " +
DoubleToString(peakEnergy,
"%g") +
";" +
1494 GetSpatialObservableX() +
";" + GetSpatialObservableY();
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());
1499 TH2F* hGainMap =
new TH2F((
"h" + t).c_str(), title.c_str(), fNumberOfSegmentsX, fReadoutRange.X(),
1500 fReadoutRange.Y(), fNumberOfSegmentsY, fReadoutRange.X(), fReadoutRange.Y());
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);
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++) {
1514 auto xUpper = *std::next(itX);
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);
1526 hGainMap->SetStats(0);
1527 hGainMap->Draw(
"colz");
1528 hGainMap->SetBarOffset(0.2);
1530 hGainMap->Draw(
"TEXT SAME");
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;
1545 RESTMetadata <<
" Calibration dataset: " << fDataSetFileName << p->RESTendl;
1546 RESTMetadata << p->RESTendl;
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: ";
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() <<
" )"
1565 RESTMetadata <<
" Number of bins: " << fNBins << p->RESTendl;
1566 RESTMetadata << p->RESTendl;
1568 RESTMetadata <<
" Number of segments X: " << fNumberOfSegmentsX << p->RESTendl;
1569 RESTMetadata <<
" Number of segments Y: " << fNumberOfSegmentsY << p->RESTendl;
1571 RESTMetadata <<
" Readout range (" << fReadoutRange.X() <<
", " << fReadoutRange.Y() <<
" )"
1573 RESTMetadata <<
"SplitX: ";
1574 for (
auto& i : fSplitX) {
1575 RESTMetadata <<
" " << i;
1577 RESTMetadata << p->RESTendl;
1578 RESTMetadata <<
"SplitY: ";
1579 for (
auto& i : fSplitY) {
1580 RESTMetadata <<
" " << i;
1582 RESTMetadata << p->RESTendl;
1583 RESTMetadata << p->RESTendl;
1585 RESTMetadata <<
" Slope: " << p->RESTendl;
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") <<
" ";
1594 RESTMetadata <<
" ";
1596 RESTMetadata << p->RESTendl;
1598 RESTMetadata <<
" Intercept: " << p->RESTendl;
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") <<
" ";
1607 RESTMetadata <<
" ";
1609 RESTMetadata << p->RESTendl;
1611 RESTMetadata << p->RESTendl;
1612 RESTMetadata <<
" Full slope: " <<
DoubleToString(fFullSlope,
"%.3e") << p->RESTendl;
1613 RESTMetadata <<
" Full intercept: " <<
DoubleToString(fFullIntercept,
"%+.3e") << p->RESTendl;
1615 RESTMetadata <<
"-----------------------------------------------" << p->RESTendl;
A class to help on cuts definitions. To be used with TRestAnalysisTree.
void SetSplitY()
Function to set the class members for segmentation of the detector plane along the Y axis.
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.
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...
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...
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...
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...
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...
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...
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
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.