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);
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];
629 RESTError <<
"Calibration constant matrix is empty. Returning 0" <<
p->RESTendl;
634 RESTError <<
"Index out of range. Returning 0" <<
p->RESTendl;
656 RESTError <<
"SetSplitX: fNumberOfSegmentsX must be >=1." <<
p->RESTendl;
659 std::set<double> split;
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;
689 RESTError <<
"SetSplitY: fNumberOfSegmentsY must be >=1." <<
p->RESTendl;
692 std::set<double> split;
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;
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);
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);
786 dataSet.SetDataFrame(dataSet.
MakeCut(
p->GetCut()));
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 /
819 std::string hModuleName =
"hSpc_" + std::to_string(
fPlaneId) +
"_" + std::to_string(fModuleId);
825 if (cut.empty()) cut =
"1";
826 auto histoMod = dataSet.
GetDataFrame().Filter(cut).Histo1D(
828 std::unique_ptr<TH1F> hpuntMod = std::unique_ptr<TH1F>(
static_cast<TH1F*
>(histoMod->Clone()));
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);
843 for (
size_t i = 0; i < h.size(); i++) {
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);
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());
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++) {
890 auto [intercept, slope] = FitPeaks(h[i][j],
fSegLinearFit[i][j]);
891 calParSlope[i][j] = slope;
892 calParIntercept[i][j] = 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;
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) {
1043 RESTError <<
"No gain map found. Use GenerateGainMap() first." <<
p->RESTendl;
1047 RESTError <<
"Segment with index (" << x <<
", " << y <<
") not found" <<
p->RESTendl;
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());
1059 while (h->GetFunction(name.c_str()))
1060 h->GetListOfFunctions()->Remove(h->GetFunction(name.c_str()));
1064 UpdateCalibrationFits(x, y);
1075 int peakNumber = -1;
1081 if (peakNumber == -1) {
1082 RESTError <<
"Energy " << energyPeak <<
" not found in the list of energy peaks" <<
p->RESTendl;
1097 RESTError <<
"No gain map found. Use GenerateGainMap() first." <<
p->RESTendl;
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());
1124void TRestDataSetGainMap::Module::UpdateCalibrationFits(
const size_t x,
const size_t y) {
1126 RESTError <<
"No gain map found. Use GenerateGainMap() first." <<
p->RESTendl;
1130 RESTError <<
"Segment with index (" << x <<
", " << y <<
") not found" <<
p->RESTendl;
1137 auto [intercept, slope] = UpdateCalibrationFits(h, gr);
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));
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);
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;
1357 RESTError <<
"Canvas " << c->GetName() <<
" has " << nPads <<
" pads, but "
1360 }
else if (nPads == 0)
1364 for (
size_t j = 0; j <
fSegSpectra[i].size(); j++) {
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 "
1484 RESTError <<
"Linear fit matrix is empty." <<
p->RESTendl;
1488 RESTError <<
"Full linear fit is empty." <<
p->RESTendl;
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());
1503 if (!fullModuleAsRef) {
1506 peakPosRef =
fSegLinearFit[index_x][index_y]->GetPointX(peakNumber);
1514 auto xUpper = *std::next(itX);
1516 auto yUpper = *std::next(itY);
1517 float xMean = (xUpper + xLower) / 2.;
1518 float yMean = (yUpper + yLower) / 2.;
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;
1543 RESTMetadata <<
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;
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;
1565 RESTMetadata <<
" Number of bins: " <<
fNBins <<
p->RESTendl;
1566 RESTMetadata <<
p->RESTendl;
1573 RESTMetadata <<
"SplitX: ";
1575 RESTMetadata <<
" " << i;
1577 RESTMetadata <<
p->RESTendl;
1578 RESTMetadata <<
"SplitY: ";
1580 RESTMetadata <<
" " << i;
1582 RESTMetadata <<
p->RESTendl;
1583 RESTMetadata <<
p->RESTendl;
1585 RESTMetadata <<
" Slope: " <<
p->RESTendl;
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())
1594 RESTMetadata <<
" ";
1596 RESTMetadata <<
p->RESTendl;
1598 RESTMetadata <<
" Intercept: " <<
p->RESTendl;
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++) {
1607 RESTMetadata <<
" ";
1609 RESTMetadata <<
p->RESTendl;
1611 RESTMetadata <<
p->RESTendl;
1615 RESTMetadata <<
"-----------------------------------------------" <<
p->RESTendl;
A class to help on cuts definitions. To be used with TRestAnalysisTree.
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::string fDataSetFileName
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...
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.