31 #include <fwk/CentralConfig.h>
32 #include <fwk/RunController.h>
34 #include <utl/Reader.h>
35 #include <utl/ErrorLogger.h>
37 #include <utl/TabulatedFunction.h>
39 #include <utl/UTMPoint.h>
40 #include <utl/ReferenceEllipsoid.h>
41 #include <utl/Vector.h>
42 #include <utl/AxialVector.h>
43 #include <utl/TimeStamp.h>
45 #include <utl/MathConstants.h>
46 #include <utl/PhysicalConstants.h>
47 #include <utl/AugerUnits.h>
48 #include <utl/CoordinateSystem.h>
49 #include <utl/AugerCoordinateSystem.h>
51 #include <utl/Trace.h>
53 #include <evt/Event.h>
54 #include <evt/ShowerRecData.h>
55 #include <evt/ShowerFRecData.h>
56 #include <evt/ShowerSimData.h>
57 #include <evt/VGaisserHillasParameter.h>
58 #include <evt/GaisserHillas2Parameter.h>
59 #include <evt/GaisserHillas4Parameter.h>
61 #include <fevt/FEvent.h>
63 #include <fevt/EyeHeader.h>
64 #include <fevt/Telescope.h>
65 #include <fevt/EyeRecData.h>
66 #include <fevt/TelescopeRecData.h>
67 #include <fevt/TelescopeSimData.h>
68 #include <fevt/PixelRecData.h>
69 #include <fevt/Pixel.h>
70 #include <fevt/Channel.h>
71 #include <fevt/FdConstants.h>
73 #include <det/Detector.h>
74 #include <atm/Atmosphere.h>
76 #include <fdet/FDetector.h>
78 #include <fdet/Pixel.h>
79 #include <fdet/Channel.h>
80 #include <fdet/Camera.h>
81 #include <fdet/Telescope.h>
83 #include <utl/AugerException.h>
84 #include <utl/Vector.h>
103 #include <TGraphErrors.h>
106 using namespace FdLightCollectionEfficiencyKG;
110 using namespace fevt;
112 using namespace fdet;
148 rayTracingB.
GetChild(
"minNRayTracePerBin").
GetData(fMinNRayTracePerBin);
149 rayTracingB.
GetChild(
"maxNRayTracePerBin").
GetData(fMaxNRayTracePerBin);
150 rayTracingB.
GetChild(
"extraRayTraceFactor").
GetData(fExtraRayTraceFactor);
153 rayTracingB.
GetChild(
"minRelevantEfficiency").
GetData(fMinRelevantEfficiency);
155 rayTracingB.
GetChild(
"targetApertureLightUncertaintyChange").
GetData(fTargetWorstCaseLAtApUncertaintyChange);
156 rayTracingB.
GetChild(
"lowerLimitOnUncertainty").
GetData(fLowerUncertaintyLimit);
158 std::string stopCondition;
160 if (stopCondition ==
"eFixed")
162 else if (stopCondition ==
"eTargetUncertainty")
163 fStopCondition = eTargetUncertainty;
164 else if (stopCondition ==
"eSmallEnough")
165 fStopCondition = eSmallEnough;
166 else if (stopCondition ==
"eBootstrap")
167 fStopCondition = eBootstrap;
174 if (fSubModulesList.size() == 0) {
175 fSubModulesList[
"FdProfileReconstructorKG"] =
SubModule(
"FdProfileReconstructorKG", fVerbosity);
176 fSubModulesList[
"ShowerLightSimulatorKG"] =
SubModule(
"ShowerLightSimulatorKG", fVerbosity);
177 fSubModulesList[
"LightAtDiaphragmSimulatorKG"] =
SubModule(
"LightAtDiaphragmSimulatorKG", fVerbosity);
178 fSubModulesList[
"ShowerPhotonGeneratorOG"] =
SubModule(
"ShowerPhotonGeneratorOG", fVerbosity);
179 fSubModulesList[
"TelescopeSimulatorKG"] =
SubModule(
"TelescopeSimulatorKG", fVerbosity);
180 fSubModulesList[
"FdElectronicsSimulatorOG"] =
SubModule(
"FdElectronicsSimulatorOG", fVerbosity);
184 for (map<string, SubModule>::iterator iModule = fSubModulesList.begin();
185 iModule != fSubModulesList.end(); ++iModule) {
189 std::ostringstream msg;
190 msg <<
"SubModule '" << subModule.
GetName() <<
"' failed Init()" << endl;
196 if (fVerbosity > 0) {
197 cout <<
"--[FdLightCollectionEfficiencyKG]--> Configuration:\n"
198 <<
" verbosity: " << fVerbosity <<
"\n"
199 <<
" simulated profile depth binning: " << fProfileXBinning/(
g/
cm/
cm) <<
"\n"
200 <<
" use only pixels within zeta: " << (fUseZeta ?
"true" :
"false") <<
"\n"
201 <<
" number of ray-tracing iterations: " << fNRayTracingIterations <<
"\n"
202 <<
" min no. ray traced photons per bin: " << fMinNRayTracePerBin <<
"\n"
203 <<
" max no. ray traced photons per bin: " << fMaxNRayTracePerBin <<
"\n"
204 <<
" extra-ray-tracing-factor: " << fMaxNRayTracePerBin <<
"\n"
208 if (fVerbosity > -1) {
210 WARNING(
"Not using the light collection angle Zeta for calculating the light collection"
211 " efficiency. If you are not debugging the FdLightCollectionEfficiencyKG module,"
212 " then this is very likely an error in your configuration");
227 return ProcessEvent(event);
236 typedef map<int, ShowerFRecData*> FRecMap;
244 for (FRecMap::iterator dataSetsIter = dataSets.begin(), end = dataSets.end();
245 dataSetsIter != end; ++dataSetsIter)
247 const int eyeId = dataSetsIter->first;
257 bool atLeastOneTel = myEvent.
PrepareEvent(eyeId, frecData, realEvent,
259 if (!atLeastOneTel) {
261 msg <<
"Skipping eye " << eyeId <<
": Either not in DAQ or no good telescope.";
267 status = fSubModulesList.find(
"ShowerLightSimulatorKG")->second.Run(myEvent.
GetEvent());
271 status = fSubModulesList.find(
"LightAtDiaphragmSimulatorKG")->second.Run(myEvent.
GetEvent());
276 SubModule& lightAtDiaMod = fSubModulesList.find(
"LightAtDiaphragmSimulatorKG")->second;
280 #warning THIS DOES NOT WORK LIKE THIS ANY MORE!!!!!!!!!!!!
294 for (
unsigned int iLightSource = 0; iLightSource < fLightComponents.size(); ++iLightSource)
298 fTimeCorrectedApertureTraces =
new std::map<unsigned int, utl::TraceD>();
303 std::pair<VModule::ResultFlag, unsigned int> tmp
304 = RunPhotonGenerationRayTracingLoop(myEvent.
GetEvent(), realEvent,
305 ( (fStopCondition==eTargetUncertainty
306 ||fStopCondition==eSmallEnough)
308 : (
unsigned int)fNRayTracingIterations ),
311 const unsigned int nRayTraced = tmp.second;
319 if (fStopCondition != eBootstrap)
320 CalculateEfficiency(myEvent.
GetEvent(), realEvent, eyeId,
321 nRayTraced, lightSource);
325 TFile* theFile = NULL;
326 if (fStopCondition == eBootstrap)
327 theFile =
new TFile(
"lightCollectionEfficiency.root",
"UPDATE");
339 iTel != realEye.
TelescopesEnd(ComponentSelector::eHasData); ++iTel)
388 if (fStopCondition == eBootstrap) {
390 componentIt != end; ++componentIt)
392 int component = componentIt->GetLabel();
394 TGraphErrors* relHist =
new TGraphErrors(thisLCEff.
GetNPoints());
395 for (
unsigned int i = 0; i < thisLCEff.
GetNPoints(); ++i) {
396 relHist->SetPoint(i+1, thisLCEff.
GetX(i), thisLCEff.
GetY(i));
397 relHist->SetPointError(i+1, thisLCEff.
GetXErr(i), thisLCEff.
GetYErr(i));
399 ostringstream relname;
400 relname <<
"relHistFinal_e" << iEye->GetId() <<
"_t" << iTel->GetId() <<
"_c" << component;
401 relHist->SetNameTitle(relname.str().c_str(), relname.str().c_str());
410 if (fStopCondition == eBootstrap)
427 for (map<string, SubModule>::iterator iModule = fSubModulesList.begin(), end = fSubModulesList.end();
428 iModule != end; ++iModule) {
432 cerr <<
"SubModule '" << subModule.
GetName() <<
"' failed Finish()" << endl;
450 const int eyeId,
const unsigned int nRayTracingIterations,
454 cout <<
"--[FdLightCollectionEfficiency]--> Calculating efficiency..." << endl;
458 msg <<
"Efficiency calculation for eye " << eyeId
459 <<
": FEvent doesn't have that eye after simulation";
468 iTel != realEye.
TelescopesEnd(ComponentSelector::eHasData); ++iTel) {
469 const unsigned int telId = iTel->
GetId();
477 if (!CalculateTelescopeEfficiency(simTel, *iTel, realEye, nRayTracingIterations, lightSource))
480 cout <<
"Caught exception: " << e.
GetMessage() <<
" => Skipping." << endl;
499 cout <<
"--[FdLightCollectionEfficiency]--> Skipping efficiency calculation for telescope "
500 << simTel.
GetId() <<
" of eye " << simTel.
GetEyeId() <<
" (lack of sim data)\n";
508 cout <<
"--[FdLightCollectionEfficiency]--> Skipping efficiency calculation for telescope "
509 << simTel.
GetId() <<
" of eye " << simTel.
GetEyeId() <<
" (lack of telescope total l@ap)\n";
514 if (fVerbosity > 0) {
515 cout <<
"--[FdLightCollectionEfficiency]--> Calculating efficiency for telescope "
526 msg <<
"Telescope " << realTel.
GetId() <<
" of eye " << realTel.
GetEyeId()
527 <<
" has no TelescopeRecData => Skipping.";
535 if (fTimeCorrectedApertureTraces->find(simTel.
GetId())
536 == fTimeCorrectedApertureTraces->end()) {
538 msg <<
"Telescope " << realTel.
GetId() <<
" of eye " << realTel.
GetEyeId()
539 <<
" has no corrected light at aperture trace!";
543 const utl::TraceD& correctedApTrace = (*fTimeCorrectedApertureTraces)[simTel.
GetId()];
549 TFile*
const theFile =
new TFile(
"lightCollectionEfficiency.root",
"UPDATE");
550 WARNING(
"ENABLED DEBUG OUTPUT TO ROOT FILE 'lightCollectionEfficiency.root'");
554 const fdet::Eye& detEye = det::Detector::GetInstance().GetFDetector().GetEye(realEye.
GetId());
562 if (fVerbosity > 2) {
568 cout <<
"================================================\n"
569 "= FdLightCollectionEfficiency debugging output =\n"
570 "================================================\n"
572 "Eye Trigger time: " << eyeTriggerTime
574 "Real Aperture start time: " << realApLightStartTime
575 <<
"(GPS nano: " << realApLightStartTime.GetGPSNanoSecond() <<
")\n"
576 "Calc. sim. start time: " << simApLightStartTime
578 "Sim. Aperture start time (from trace): " << simApertureStartTime
580 "Sim. Traces start time: " << tracesStartTime
582 "Diff (sim-real)/ns: " << (simApertureStartTime-realApLightStartTime).GetNanoSecond() <<
"\n"
588 const double simTimeOffset = (simApertureStartTime - eyeTriggerTime).GetInterval() /
ns;
590 cout <<
" Simulation time offset: " << simTimeOffset <<
"ns" << endl;
595 switch (lightSource) {
608 const utl::TraceD totalWlTrace2 = CalculateTelescopeTraceSum(simTel, lightSource, emode);
609 const utl::TraceD& totalWlTrace = correctedApTrace;
611 cout <<
"Size: " << totalWlTrace2.
GetSize() <<
" " << totalWlTrace.
GetSize() << endl;
612 cout <<
"Start: " << totalWlTrace2.
GetStart() <<
" " << totalWlTrace.
GetStart() << endl;
613 cout <<
"Stop: " << totalWlTrace2.
GetStop() <<
" " << totalWlTrace.
GetStop() << endl;
614 double sum1 = 0., sum2 = 0.;
615 for (
unsigned int i = 0; i< totalWlTrace.
GetSize();++i) {
616 sum1 +=totalWlTrace[i];
617 sum2 += totalWlTrace2[i];
619 cout <<
"Sum:" << sum1 <<
" " << sum2 << endl;
621 const double wlTraceBinSize = totalWlTrace.
GetBinning();
622 const double wlTraceBins = totalWlTrace.
GetSize();
623 if (wlTraceBins == 0) {
624 if (fVerbosity > 0) {
625 cout <<
"--[FdLightCollectionEfficiency]--> Skipping light component "
626 << lightSource <<
" for this telescope. No light-at-aperture trace.\n";
632 CalculatePixelTraceSum(simTel, lightSource, simTimeOffset, pixelsInZeta, realApLightFlux);
634 const double pixTraceBins = totalPixelTrace.
GetNPoints();
635 if (pixTraceBins == 0) {
636 if (fVerbosity > 0) {
637 cout <<
"--[FdLightCollectionEfficiency]--> Skipping light component "
638 << lightSource <<
" for this telescope. No pixel traces.\n";
643 if (fVerbosity > 1) {
644 cout <<
"Component " << lightSource <<
" wlTrace: nBins="
645 << wlTraceBins <<
", binSize=" << wlTraceBinSize <<
"\n"
646 "Component " << lightSource <<
" pixTrace: nBins="
647 << pixTraceBins <<
"\n"
648 "Component " << lightSource <<
" nRayTraced: nBins="
654 CalcTraceDivision(totalPixelTrace, totalWlTrace,
661 WriteDebugInfo(realEye.
GetId(), simTel.
GetId(), simTimeOffset, lightSource, totalPixelTrace, totalWlTrace, realApLightFlux, telEff);
668 if (lightCollEff.HasLabel(lightSource))
671 lightCollEff.AddTabulatedFunctionErrors(telEff, lightSource);
690 ostringstream pixname;
691 pixname <<
"pixHist_e" << eyeId <<
"_t" << simTelId <<
"_c" << component;
692 vector<double> pixHistX, pixHistY;
693 for (
unsigned int i = 0; i < totalPixelTrace.
GetNPoints(); ++i) {
694 pixHistX.push_back(totalPixelTrace.
GetX(i) + simTimeOffset);
695 pixHistY.push_back(totalPixelTrace.
GetY(i));
697 TGraph*
const pixHist =
698 new TGraph(totalPixelTrace.
GetNPoints(), &pixHistX.front(), &pixHistY.front());
699 pixHist->SetNameTitle(pixname.str().c_str(), pixname.str().c_str());
702 ostringstream apname;
703 apname <<
"apHist_e" << eyeId <<
"_t" << simTelId <<
"_c" << component;
705 new TH1D(apname.str().c_str(), apname.str().c_str(),
706 totalWlTrace.
GetSize(), simTimeOffset,
708 for (
unsigned int i = 1; i <= totalWlTrace.
GetSize(); ++i)
709 apHist->SetBinContent(i, totalWlTrace.
At(i-1));
712 ostringstream realapname;
713 realapname <<
"realApLight_e" << eyeId <<
"_t" << simTelId <<
"_c" << component;
714 TGraph*
const realAp =
717 realAp->SetNameTitle(realapname.str().c_str(), realapname.str().c_str());
720 ostringstream relname;
721 relname <<
"relHist_e" << eyeId <<
"_t" << simTelId <<
"_c" << component;
722 vector<double> relHistX, relHistXe, relHistY, relHistYe;
723 for (
unsigned int i = 0; i < telEff.
GetNPoints(); ++i) {
724 relHistX.push_back(telEff.
GetX(i) + simTimeOffset);
725 relHistXe.push_back(telEff.
GetXErr(i));
726 relHistY.push_back(telEff.
GetY(i));
727 relHistYe.push_back(telEff.
GetYErr(i));
729 TGraphErrors*
const relHist =
730 new TGraphErrors(telEff.
GetNPoints(), &relHistX.front(), &relHistY.front(),
731 &relHistXe.front(), &relHistYe.front());
732 relHist->SetNameTitle(relname.str().c_str(), relname.str().c_str());
747 const fdet::FDetector& fdetector = det::Detector::GetInstance().GetFDetector();
780 traceIter != end; ++traceIter) {
781 const utl::TraceD& wlTrace = traceIter->GetTrace();
786 const double wl = refWl;
789 if (wl < minWl || wl > maxWl) {
800 for (
unsigned int i = 0; i < wlTrace.
GetSize(); ++i)
816 for (
unsigned int i = 0; i < wlTrace.
GetSize(); ++i)
817 totalWlTrace[i] += wlTrace[i] * diaArea;
830 const double simTimeOffset,
831 const vector<vector<unsigned int> >& pixelsInZeta,
836 const fdet::FDetector& theFDet = det::Detector::GetInstance().GetFDetector();
838 const unsigned int telId = tel.
GetId();
840 const unsigned int nPoints = realApLight.
GetNPoints();
841 for (
unsigned int iTimeBin = 0; iTimeBin < nPoints; ++iTimeBin) {
842 const vector<unsigned int>& thisTimeZetaPixels = pixelsInZeta[iTimeBin];
843 const double timeBinCenter = realApLight.
GetX(iTimeBin) - simTimeOffset;
844 const double dtHalf = realApLight.
GetXErr(iTimeBin);
845 double timeBinSignal = 0.;
846 double timeBinSignalVar = 0.;
848 const unsigned int nPixels =
851 for (
unsigned int iPixId = 0; iPixId < nPixels; ++iPixId) {
852 const unsigned int pixId = fUseZeta ? thisTimeZetaPixels[iPixId] : iPixId + 1;
853 if (!tel.
HasPixel(pixId, ComponentSelector::eInDAQ))
857 double pixEffMod = fLightConverter->GetConversionConstant(telId, pixId);
867 const double pixSignalInBin =
868 CalcTraceBinContent<double>(pixTrace, timeBinCenter - dtHalf, timeBinCenter + dtHalf);
869 timeBinSignal += pixSignalInBin * pixEffMod;
872 const double pixSignalVarInBin =
873 CalcTraceBinContent<double>(pixWSTrace, timeBinCenter - dtHalf, timeBinCenter + dtHalf);
874 timeBinSignalVar += pixSignalVarInBin * pixEffMod*pixEffMod;
877 totalPixelTrace.
PushBack(timeBinCenter, dtHalf, timeBinSignal,
sqrt(timeBinSignalVar));
880 return totalPixelTrace;
888 SubModule& profRecMod = fSubModulesList.find(
"FdProfileReconstructorKG")->second;
913 if (!iEye->HasRecData()) {
915 cout <<
" Skipping eye " << iEye->GetId() <<
": no EyeRecData.\n";
922 cout <<
" Skipping eye " << iEye->GetId() <<
": no ShowerFRecData.\n";
931 cout <<
" Skipping eye " << iEye->GetId() <<
": no profile reconstruction.\n";
939 cout <<
" Skipping eye " << iEye->GetId() <<
": no profile GH parameters after profile reconstruction.\n";
945 cout <<
" Skipping eye " << iEye->GetId() <<
": unphysical profile reconstruction.\n";
949 dataSets[iEye->GetId()] = &frecData;
957 std::pair<fwk::VModule::ResultFlag, unsigned int>
960 unsigned int nRayTracingIterations,
966 SubModule& photGenMod = fSubModulesList.find(
"ShowerPhotonGeneratorOG")->second;
982 SubModule& telSimMod = fSubModulesList.find(
"TelescopeSimulatorKG")->second;
993 cout <<
"\n Performing at least " << nRayTracingIterations
994 <<
" ray-tracing iteration(s):" << endl;
996 typedef std::list<utl::TabulatedFunctionErrors> TelLCEfficiencies;
997 typedef std::map<unsigned int, TelLCEfficiencies> EyeLCEfficiences;
998 typedef std::map<unsigned int, EyeLCEfficiences> EventLCEfficiencies;
999 EventLCEfficiencies lcEfficiencies;
1002 for (
unsigned int iRayTrace = 1; iRayTrace <= (
unsigned int)nRayTracingIterations; ++iRayTrace) {
1004 bool needRepeat =
false;
1007 cout <<
"\n Ray-tracing iteration " << iRayTrace <<
" ..." << endl;
1011 status = photGenMod.
Run(event);
1017 err <<
"ShowerPhotonGenerator threw an exception."
1018 " Skipping the event for lack of better options...";
1020 status = eContinueLoop;
1027 status = telSimMod.
Run(event);
1038 iEye != end; ++iEye)
1045 const unsigned int eyeId = eyeEvent.
GetId();
1050 iTel != end; ++iTel)
1052 const unsigned int telId = iTel->GetId();
1057 utl::TraceD& apTrace = (*fTimeCorrectedApertureTraces)[telId];
1068 if (fStopCondition !=
eFixed)
1069 CalculateEfficiency(event, realEvent, eyeId, iRayTrace, lightSource);
1071 EyeLCEfficiences& eyeLCEff = lcEfficiencies[eyeId];
1076 iTel != end; ++iTel)
1078 const unsigned int telId = iTel->GetId();
1083 if (fStopCondition == eBootstrap) {
1094 iPix != end; ++iPix)
1096 iPix->GetSimData().ClearPhotonTraces();
1097 iPix->GetSimData().ClearPhotonWeightSquareTraces();
1100 TelLCEfficiencies& telLCEff = eyeLCEff[telId];
1101 if (!realEvent.
GetFEvent().
HasEye(eyeId, ComponentSelector::eHasData))
1105 if (!reye.
HasTelescope(telId, ComponentSelector::eHasData))
1117 if (iRayTrace == nRayTracingIterations) {
1118 cout <<
"Bootstrapping uncertainties..." << endl;
1136 if ((fStopCondition == eTargetUncertainty
1137 || fStopCondition == eSmallEnough)
1140 double targetRelUncertainty = 0.;
1141 if (fStopCondition == eSmallEnough) {
1143 targetRelUncertainty =
1144 CalculateTargetRelUncertainty(realEvent.
GetFEvent(),
1145 event.GetFEvent(), lightSource,
1146 fMinRelevantEfficiency,
1147 fTargetWorstCaseLAtApUncertaintyChange);
1149 if (targetRelUncertainty < fLowerUncertaintyLimit)
1150 targetRelUncertainty = fLowerUncertaintyLimit;
1153 targetRelUncertainty = fTargetUncertainty;
1155 const double additionalIter =
1156 CalculateAdditionalIterationsToMeetTarget(realEvent.
GetFEvent(),
1157 event.GetFEvent(), lightSource,
1158 targetRelUncertainty, fMinRelevantEfficiency);
1159 if (additionalIter > 0.) {
1161 unsigned int addIter = (
unsigned int)additionalIter;
1162 addIter = (additionalIter - (double)addIter > 0.) ? addIter+1 : addIter;
1164 msg <<
"Determined that at least " << additionalIter
1165 <<
" ray-tracing iterations are necessary to reach uncertainty target."
1168 nRayTracingIterations += addIter-1;
1171 INFO(
"Met uncertainty target for this light component for all bins.");
1178 if (iRayTrace == fMaxIterations) {
1179 cout <<
"Would need an additional iteration according to stop "
1180 <<
"criterion, but we hit the hard upper limit. Stopping iteration." << endl;
1181 nRayTracingIterations = iRayTrace;
1185 cout <<
"Performing additional iteration to meet uncertainty target..." << endl;
1186 nRayTracingIterations++;
1189 else if (fStopCondition !=
eFixed && iRayTrace == fMaxIterations) {
1190 cout <<
"Would need an additional iteration according to stop "
1191 <<
"criterion, but we hit the hard upper limit. Stopping iteration." << endl;
1192 nRayTracingIterations = iRayTrace;
1202 if (sourceSelection < 0)
1211 return std::make_pair(status, nRayTracingIterations);
1220 const double targetRelUncertainty,
1221 const double minRelevantEfficiency)
1223 double minNIterationsRequired = 0.;
1224 double photonsRayTracedAtMinimum = 0;
1225 double efficiencyAtMinimum = 0;
1226 double efficiencyUncertaintyAtMinimum = 0;
1230 iEye != end; ++iEye)
1243 iTel != end; ++iTel)
1245 if (!iTel->HasSimData())
1267 const unsigned int nPoints = lcEff.
GetNPoints();
1268 for (
unsigned int i = 0; i < nPoints; ++i) {
1269 if (lcEff.
GetY(i) >= minRelevantEfficiency) {
1270 if (nRayTraced[i] == 0)
1272 const double yerr = lcEff.
GetYErr(i);
1273 const double nPhotNow = nRayTraced[i];
1274 if (yerr > targetRelUncertainty) {
1280 const double nTarget =
pow(yerr/(targetRelUncertainty*lcEff.
GetY(i)), 2.) * nPhotNow;
1281 const double thisMinNPhot = nTarget - nPhotNow;
1282 const double thisMinNIter = thisMinNPhot / (double)nPhotNow;
1283 if (thisMinNIter > minNIterationsRequired) {
1284 minNIterationsRequired = thisMinNIter;
1285 photonsRayTracedAtMinimum = nPhotNow;
1286 efficiencyAtMinimum = lcEff.
GetY(i);
1287 efficiencyUncertaintyAtMinimum = yerr;
1296 if (fVerbosity > 0) {
1298 msg <<
"Calculated that we'll need " << minNIterationsRequired
1299 <<
" more iterations to meet uncertainty target.";
1300 if (fVerbosity > 1) {
1301 msg <<
" In the bin of the minimum, we ray-traced " << photonsRayTracedAtMinimum
1302 <<
" so far, therefore, we need "
1303 << (minNIterationsRequired+1)*photonsRayTracedAtMinimum
1304 <<
" photons in total to meet target. In this bin, the efficiency was: "
1305 << efficiencyAtMinimum <<
" +/- " << efficiencyUncertaintyAtMinimum;
1310 return minNIterationsRequired;
1319 const double minRelevantEfficiency,
1320 const double maxUncertaintyChangeFraction)
1322 unsigned int worstTel = 0;
1323 unsigned int worstBin = 0;
1324 double worstTime = 0.;
1325 double worstCaseRelUncertainty = 1.e9;
1329 iEye != end; ++iEye)
1342 iTel != end; ++iTel)
1344 if (!iTel->HasSimData())
1347 const unsigned int telId = iTel->
GetId();
1365 const unsigned int nPoints = lcEff.
GetNPoints();
1368 for (
unsigned int i = 0; i < nPoints; ++i) {
1369 const double eff = lcEff.
GetY(i);
1370 if (eff >= minRelevantEfficiency) {
1371 const double light = fabs(lAtAp.
GetY(i));
1372 const double lightErr = lAtAp.
GetYErr(i);
1373 const double requiredRelEff =
sqrt(
pow(maxUncertaintyChangeFraction+1, 2)-1 ) * lightErr / light;
1374 if (requiredRelEff < worstCaseRelUncertainty) {
1377 worstTime = lAtAp.
GetX(i);
1378 worstCaseRelUncertainty = requiredRelEff;
1379 cout << telId <<
" " << i <<
" " << maxUncertaintyChangeFraction <<
" "
1380 << lightErr <<
" " << light <<
" " << lightErr/light <<
" " << requiredRelEff
1389 if (fVerbosity > 0) {
1391 msg <<
"Calculated worst-case required relative uncertainty on efficiency is "
1392 << worstCaseRelUncertainty <<
". ";
1393 if (worstCaseRelUncertainty < fLowerUncertaintyLimit) {
1394 msg <<
" It is smaller than the lower bound for the rel. unc. ("
1395 << fLowerUncertaintyLimit <<
") and thus, we'll use the latter instead. ";
1397 msg <<
"This will be the basis for calculating the "
1398 "required number of iterations.";
1399 if (fVerbosity > 1) {
1400 msg <<
" The most stringent requirement was found in tel. " << worstTel
1401 <<
" for bin " << worstBin <<
" at time " << worstTime <<
".";
1406 return worstCaseRelUncertainty;
1415 const double nRayTracingIterations)
1417 const unsigned int nBins = pixelTrace.
GetNPoints();
1418 vector<double> vx(nBins), vxerr(nBins), vy(nBins), vyerr(nBins);
1420 for (
unsigned int i = 0; i < nBins; ++i) {
1421 const double binCenter = pixelTrace.
GetX(i);
1422 const double halfBinWidth = pixelTrace.
GetXErr(i);
1423 const double binStart = binCenter - halfBinWidth;
1424 const double binEnd = binCenter + halfBinWidth;
1426 const double pixelSignal = pixelTrace.
GetY(i);
1427 const double pixelSignalErr = pixelTrace.
GetYErr(i);
1428 assert(isfinite(pixelSignal));
1429 assert(isfinite(pixelSignalErr));
1431 const double apertureSignal = CalcTraceBinContent(apertureTrace, binStart, binEnd) * nRayTracingIterations;
1432 assert(isfinite(apertureSignal));
1435 const double x = binCenter;
1436 if (apertureSignal >= 1.e-9) {
1437 const double y = pixelSignal / apertureSignal;
1438 assert(isfinite(y));
1440 vyerr[i] = pixelSignalErr / apertureSignal;
1448 vxerr[i] = halfBinWidth;
1454 for (
unsigned int i = 0; i < nBins; ++i) {
1455 const double yerr = vyerr[i];
1456 assert(isfinite(vx[i]));
1457 assert(isfinite(vxerr[i]));
1458 assert(isfinite(vy[i]));
1459 assert(isfinite(yerr));
1460 division.
PushBack(vx[i], vxerr[i], vy[i], yerr);
Telescope & GetTelescope(const unsigned int telescopeId, const ComponentSelector::Status status=ComponentSelector::eHasData)
Retrieve Telescope by Id, throw exception if not existent.
unsigned int GetId() const
void WriteDebugInfo(const int eyeId, const int simTelId, const double simTimeOffset, const fevt::FdConstants::LightSource component, const utl::TabulatedFunctionErrors &totalPixelTrace, const utl::TraceD &totalWlTrace, const utl::TabulatedFunctionErrors &realApLightFlux, const utl::TabulatedFunctionErrors &telEff)
unsigned int GetNPoints() const
boost::transform_iterator< LabeledObjectFunctor, typename MultiObjectContainer::iterator, LabeledTabulatedFunctionErrors > Iterator
void SetStop(const SizeType stop)
Set valid data stop bin.
int GetLightSourceSelection()
T & At(const SizeType i)
trace entry with checked address
bool StoreLightComponentsAtPixels()
Returns whether pixel traces are stored for individual light components.
utl::TabulatedFunctionErrors CalcTraceDivision(const utl::TabulatedFunctionErrors &pixelTrace, const utl::TraceD &apertureTrace, const utl::TraceI &nRayTracedTrace, const double nRayTracingIterations)
Description of the electronic channel for the 480 channels of the crate.
unsigned int GetMaxNRayTrace() const
Get the max. no. of photons raytraced per time bin.
void SetMaxNRayTrace(unsigned int nphotons)
Set the max. no. of photons raytraced per time bin.
fevt::EyeHeader & GetHeader()
Header for this Eye Event.
fwk::VModule::ResultFlag Init()
unsigned int GetTimeOffset() const
Time offset of this Telescope compared to fevt::Header::GetTime [ns].
bool HasPhotonTrace(const fevt::FdConstants::LightSource source, const int wl) const
Check that light trace for source /par source is present for the given wavelength bin...
Fluorescence Detector Eye Event.
Simulates the FD telescope.
boost::filter_iterator< ComponentSelector, ConstAllEyeIterator > ConstEyeIterator
bool GetUseOnlyReferenceWavelength() const
Returns whether photons will be generated only at the reference wavelength.
SizeType GetStop() const
Get valid data stop bin.
unsigned int GetFirstPixelId() const
Utility class to do (cached!) conversion from photons at the pixel to photons at aperture.
double GetModelMaxWavelength() const
Class to hold collection (x,y) points and provide interpolation between them.
const utl::TabulatedFunctionErrors & GetMean()
EyeIterator EyesEnd(const ComponentSelector::Status status)
double GetBinning() const
size of one slot
unsigned int GetEyeId() const
double GetMeasuredRelativeEfficiency(const double wl) const
fwk::VModule::ResultFlag DoInitialReconstruction(evt::Event &event, std::map< int, evt::ShowerFRecData * > &dataSets)
Runs the FdProfileReconstructor before the efficiency calculation.
utl::TraceI & GetRayTracedPhotonTrace()
Number of photons that were actually ray-traced (per time bin)
#define INFO(message)
Macro for logging informational messages.
PixelSimData & GetSimData()
void SetPropagateAtmUncertainties(const bool propagate)
Base class for exceptions trying to access non-existing components.
const Eye & GetEye(const unsigned int eyeId) const
Find eye by numerical Id.
Detector description interface for Eye-related data.
boost::filter_iterator< ComponentSelector, AllEyeIterator > EyeIterator
selective Eye iterators
utl::TimeStamp GetPhotonsStartTime() const
Start Time of the photons trace.
void SetLightSourceSelection(const fevt::FdConstants::LightSource source)
Branch GetChild(const std::string &childName) const
Get child of this Branch by child name.
fevt::TelescopeRecData & GetRecData()
Reconstructed data for this telescope.
bool HasPhotonTrace(const FdConstants::LightSource source) const
Check that trace for source /par source is present.
double pow(const double x, const unsigned int i)
void ClearRayTracedPhotonTrace()
Clear the trace of ray traced photons.
Exception for errors encountered when parsing XML.
void PrintTiming(utl::TabularStream &tabStream)
Prints the sub-module timing to the given tabular stream.
Estimate the uncertainty of the light-collection efficiency with the bootstrap method.
Detector description interface for FDetector-related data.
A TimeStamp holds GPS second and nanosecond for some event.
Exception for reporting variable out of valid range.
const Pixel & GetPixel(const unsigned int pixelId) const
Get Pixel by id, throw utl::NonExistentComponentException if n.a.
fwk::VModule::ResultFlag Run(evt::Event &event)
bool GetPropagateGeometryErrors() const
void SetVerbosity(const int verbosity)
bool HasPixel(const unsigned int pixelId, const ComponentSelector::Status status=ComponentSelector::eHasData) const
Check if the pixel is in the event.
fevt::TelescopeSimData & GetSimData()
Description of simulated data for one Telescope.
utl::TabulatedFunctionErrors & GetLightFlux(const FdConstants::LightSource source=fevt::FdConstants::eTotal)
Light flux at diaphragm, photons/m^2 versus time in ns.
Class representing a document branch.
unsigned int GetLastPixelId() const
const double & GetYErr(const unsigned int idx) const
ArrayConstReference XFront() const
read-only reference to front of array of X
LightSource
Possible light sources.
bool HasLongitudinalProfile() const
Fluorescence Detector Pixel event.
const utl::TabulatedFunction & GetQEfficiency() const
Average quantum efficiency as a function of the wavelength.
TelescopeIterator TelescopesEnd()
first available tel of status eHasData (DEPRECATED)
bool HasLightFlux(const FdConstants::LightSource source=FdConstants::eTotal) const
Check that light profile for source /par source is present.
constexpr double nanosecond
bool CalculateEfficiency(const evt::Event &simEvent, evt::Event &realEvent, const int eyeId, const unsigned int nRayTracingIterations, const fevt::FdConstants::LightSource lightSource)
Calculates the light collection efficiency of a sim shower.
const Telescope & GetTelescope(const unsigned int telescopeId) const
Find Telescope by numerical Id.
fwk::VModule::ResultFlag Init()
Initialize: invoked at beginning of run (NOT beginning of event)
bool PrepareEvent(const unsigned int eyeId, const evt::ShowerFRecData &recData, const evt::Event &event, const fevt::Eye &eye)
bool HasFRecShower() const
Check if reconstructed shower info has been allocated.
void SetStart(const SizeType start)
Set valid data start bin.
evt::ShowerFRecData & GetFRecShower()
Reconstructed shower info for this eye.
int GetVerbosity()
Returns the current verbosity level.
EyeIterator EyesBegin(const ComponentSelector::Status status)
int GetFADCTraceLength() const
fwk::VModule::ResultFlag Finish()
Finish: invoked at end of the run (NOT end of the event)
ArrayConstReference YFront() const
read-only reference to front of array of Y
Adaptor class for FdLightCollectionEfficiency's sub-modules for initializing, running, timing them.
Telescope-specific shower reconstruction data.
utl::TabulatedFunctionErrors CalculatePixelTraceSum(const fevt::Telescope &tel, const fevt::FdConstants::LightSource component, const double simTimeOffset, const std::vector< std::vector< unsigned int > > &pixelsInZeta, const utl::TabulatedFunctionErrors &realApLight)
Calculate the sum of pixel traces (simTimeOffset in ns)
utl::MultiTabulatedFunctionErrors & GetLightCollectionEfficiency()
Get the light-collection-efficiency multi tabulated function (for various LightSources) ...
utl::TraceD & GetPhotonWeightSquareTrace(const FdConstants::LightSource source=FdConstants::eTotal)
Trace of the sums of squares of simulated photon weights.
boost::filter_iterator< ComponentSelector, AllTelescopeIterator > TelescopeIterator
selective Telescope iterators
const std::vector< std::vector< unsigned int > > & GetPixelsInZetaOverTime() const
Returns the time-vector of vectors of pixel ids which are within zeta at the given time...
void MakeLightCollectionEfficiency()
Add a light-collection-efficiency multi tabulated function (for various LightSources) ...
void SetExtraRayTraceFactor(double factor)
Set the artificial scaling factor for the number of ray-traced photons.
class to format data in tabular form
A collection of TabulatedFunctionErrors, which provides methods to access different sources...
PhotonTraceIterator PhotonTracesEnd(const fevt::FdConstants::LightSource source)
void PushBack(const double x, const double xErr, const double y, const double yErr)
#define WARNING(message)
Macro for logging warning messages.
unsigned int GetMinNRayTrace() const
Get the min. no. of photons raytraced per time bin.
void GetData(bool &b) const
Overloads of the GetData member template function.
TabulatedFunctionErrors & GetTabulatedFunctionErrors(const int label=0)
Returns the TabulatedFunctionErrors for /par source.
Calculates an aperture light trace based on the ray-traced photons' times.
Top of Fluorescence Detector event hierarchy.
const double & GetXErr(const unsigned int idx) const
Eye-specific shower reconstruction data.
Eye & GetEye(const unsigned int eyeId, const ComponentSelector::Status status=ComponentSelector::eHasData)
return Eye by id
bool HasRayTracedPhotonTrace() const
Check that "ray-traced photon trace" is present.
TelescopeIterator TelescopesBegin()
first available tel of status eHasData (DEPRECATED)
double CalculateAdditionalIterationsToMeetTarget(const fevt::FEvent &theRealFEvent, const fevt::FEvent &theSimFEvent, const fevt::FdConstants::LightSource &lightSource, const double targetRelUncertainty, const double minRelevantEfficiency)
const double & GetY(const unsigned int idx) const
bool HasLightCollectionEfficiency() const
Check that a light-collection-efficiency multi tabulated function exists (for various LightSources) ...
std::pair< fwk::VModule::ResultFlag, unsigned int > RunPhotonGenerationRayTracingLoop(evt::Event &event, evt::Event &realEvent, unsigned int nRayTracingIterations, const fevt::FdConstants::LightSource lightSource)
Runs the ShowerPhotonGenerator and TelescopeSimulator nRayTracingIterations times.
static utl::TabularStream TimingHeader()
Prepares a TabularStream for timing printout.
void UpdateSpotFarFromBorderTimes(const double effThreshold)
double GetReferenceLambda() const
fevt::FEvent & GetFEvent()
Pixel & GetPixel(const unsigned int pixelId, const ComponentSelector::Status status=ComponentSelector::eHasData)
Retrieve Pixel by Id, throw exception if not existent.
bool HasGHParameters() const
double GetModelMinWavelength() const
bool HasEye(const unsigned int eyeId, const ComponentSelector::Status status=ComponentSelector::eHasData) const
void SetBinning(const double binning)
boost::filter_iterator< ComponentSelector, AllPixelIterator > PixelIterator
selective Pixel iterators
Detector description interface for Telescope-related data.
A TimeInterval is used to represent time elapsed between two events.
ResultFlag
Flag returned by module methods to the RunController.
PhotonTraceIterator PhotonTracesBegin(const fevt::FdConstants::LightSource source)
const std::string & GetName() const
const Telescope & GetTelescope(const fevt::Telescope &eventTel) const
Get fdet::Telescope from fevt::Telescope.
double GetFADCBinSize() const
double GetGPSNanoSecond() const
GPS nanosecond.
unsigned int GetId() const
double GetDiaphragmArea() const
Container for a faked event that knows how to claw the necessary information from the sim...
void SetUseOnlyReferenceWavelength(bool onlyRefWl)
Set whether photons should be generated only at the reference wavelength (used by FdLightCollectionEf...
SizeType GetStart() const
Get valid data start bin.
bool HasTelescope(const unsigned int telescopeId, const ComponentSelector::Status status=ComponentSelector::eHasData) const
Check if the telescope is in the event.
utl::TraceD & GetPhotonTrace(const FdConstants::LightSource source=FdConstants::eTotal)
Simulated Photon Trace.
Interface class for access to the Gaisser-Hillas parameters.
Fluorescence emission model.
const double & GetX(const unsigned int idx) const
Interface class to access to Fluorescence reconstruction of a Shower.
fwk::VModule & GetModule()
bool MaxRelUncertaintyBelowThreshold(const double relUncertaintyThreshold, const double absValueThreshold=0.)
bool GetPropagateAtmUncertainties() const
fwk::VModule::ResultFlag ProcessEvent(evt::Event &realEvent)
Main entry point. Run() is just a proxy.
static void FinishTimingPrintout(utl::TabularStream &tabStream)
Finishes the printout and actually dumps it to stdout.
Main configuration utility.
Fluorescence Detector Telescope Event.
fwk::VModule::ResultFlag Run(evt::Event &event)
Run: invoked once per event.
void ResetLightSourceSelection()
Gaisser Hillas with 4 parameters.
void AddTabulatedFunctionErrors(const int label)
double CalculateTargetRelUncertainty(const fevt::FEvent &theRealFEvent, const fevt::FEvent &theSimFEvent, const fevt::FdConstants::LightSource &lightSource, const double minRelevantEfficiency, const double maxUncertaintyChangeFraction)
Recalculates and sets the valid time ranges for profile reconstruction based on the telescope apertur...
bool CalculateTelescopeEfficiency(const fevt::Telescope &simTel, fevt::Telescope &realTel, const fevt::Eye &realEye, const unsigned int nRayTracingIterations, const fevt::FdConstants::LightSource lightSource)
Calculates the light collection efficiency of a telescope.
utl::MultiTraceD::ConstIterator ConstPhotonTraceIterator
void PushBack(const T &value)
Insert a single value at the end.
#define ERROR(message)
Macro for logging error messages.
void SetVerbosity(const int verbosity)
Sets the verbosity level.
void SetMinNRayTrace(unsigned int nphotons)
Set the min. no. of photons raytraced per time bin.
boost::filter_iterator< ComponentSelector, ConstAllTelescopeIterator > ConstTelescopeIterator
Simulate photon injection into FD telescope.
const std::string & GetMessage() const
Retrieve the message from the exception.
bool HasEnergyDeposit() const
bool HasLabel(const int label) const
utl::Branch GetTopBranch(const std::string &id)
Get top branch for moduleConfigLink with given id (XML files)
utl::TraceD CalculateTelescopeTraceSum(const fevt::Telescope &tel, const fevt::FdConstants::LightSource component, const atm::Atmosphere::EmissionMode lightType)
Calculate the wavelength-efficiency weighted sum of light-at-aperture traces.
double GetExtraRayTraceFactor() const
Get the artificial scaling factor for the number of ray-traced photons.
void SetStoreLightComponentsAtPixels(const bool store)
Sets whether pixel traces are stored for individual light components.
Fluorescence Detector Pixel Simulated Data.
void SetPropagateGeometryErrors(const bool propagate)
utl::TimeStamp GetTracesStartTime() const
fwk::VModule::ResultFlag Finish()