MdMuonEstimator.cc
Go to the documentation of this file.
1 // $Id: MdMuonEstimator.cc 34060 2021-03-11 16:43:53Z sanchez $
2 #include "MdMuonEstimator.h"
3 
4 #include "OneBinStrategy.h"
5 #include "NBinStrategy.h"
6 #include "NBinCenteredStrategy.h"
8 
9 #include <fwk/CentralConfig.h>
10 #include <det/VManager.h>
11 #include <mdet/MDetector.h>
12 #include <sdet/SDetector.h>
13 #include <evt/ShowerRecData.h>
14 #include <evt/ShowerSRecData.h>
15 #include <sevt/SEvent.h>
16 #include <mevt/Module.h>
17 
18 #include <utl/ConsecutiveEnumFactory.h>
19 #include <utl/Trace.h>
20 #include <utl/AugerUnits.h>
21 #include <utl/Branch.h>
22 #include <utl/RandomEngine.h>
23 #include <utl/ConfigUtils.h>
24 #include <utl/TimeStamp.h>
25 #include <utl/PhysicalConstants.h>
26 #include <utl/TimeInterval.h>
27 
28 #include <utl/ErrorLogger.h>
29 #include <utl/Verbosity.h>
30 
31 #include <sstream>
32 //#include <cassert>
33 
34 #include <TH1I.h>
35 
36 using namespace fwk;
37 using std::cout;
38 using std::endl;
39 
40 
41 namespace MdMuonEstimatorAG {
42 
43  const char* const MdMuonEstimator::kCountingStrategyTags[] = { "OneBin", "NBin", "NBinCentered", "InfiniteWindow" };
44 
45 
47  MdMuonEstimator::Init() //evt::Event& event
48  {
49  DEBUGLOG("Initiating Muon Estimator");
50 
51  // Configuration reading.
52  utl::Branch config = fwk::CentralConfig::GetInstance()->GetTopBranch("MdMuonEstimator");
53  fUnits.SetTimeDefault(utl::ns, "ns");
54  fUnits.Configure(config);
55  fLog.Configure(config);
56  std::string tag;
57  LoadConfig(config, "countingStrategy", tag, kCountingStrategyTags[0]);
58  LoadConfig(config, "nBinWindowSize", fNBinWindowSize, 12);
59 
61 
62  //cout << kCountingStrategyTags[ fCountingStrategy ] << endl;
63  //cout << "Muon Estimator Initiated" << endl;
64  return eSuccess;
65  }
66 
67 
69  MdMuonEstimator::Run(evt::Event& event)
70  {
71  if (!event.HasMEvent()) {
72  WARNING("\n+++++++++\nEvent without MEvent: nothing to be done. Skipping to next event.\n++++++++++\n");
73  return eContinueLoop;
74  }
75 
76  // Initiate counting strategy
77  unsigned int traceLength = GetTraceLength(event);
78  double samplingTimeTrace = GetSamplingTime(event);
79 
80  switch (fCountingStrategy) {
81  case eOneBin:
82  fEstimator.reset(new OneBinStrategy(traceLength, samplingTimeTrace));
83  fLog("Strategy")(kCountingStrategyTags[ fCountingStrategy ])(".");
84  fCountingWindowSize = 1;
85  break;
86  case eNBin:
87  fEstimator.reset(new NBinStrategy(fNBinWindowSize, traceLength));
88  fLog("#NBin Window size", 1)
89  (fNBinWindowSize)("-")
90  ("Strategy")(kCountingStrategyTags[ fCountingStrategy ])(".");
91  fCountingWindowSize = fNBinWindowSize;
92  break;
93  case eNBinCentered:
94  fEstimator.reset(new NBinCenteredStrategy(fNBinWindowSize, traceLength));
95  fLog("#NBin Window size", 1)
96  (fNBinWindowSize)("-")
97  ("Strategy")(kCountingStrategyTags[ fCountingStrategy ])(".");
98  fCountingWindowSize = fNBinWindowSize;
99  break;
100  case eInfiniteWindow:
101  fEstimator.reset(new InfiniteWindowStrategy(traceLength));
102  fLog("Strategy")(kCountingStrategyTags[ fCountingStrategy ])(".");
103  fCountingWindowSize = traceLength; // Set to length of the trace
104  break;
105  default:
106  ERROR("Invalid muon estimation strategy!");
107  break;
108  } //end switch
109 
110  mevt::MEvent& me = event.GetMEvent();
111  const mdet::MDetector& theMdDetector = det::Detector::GetInstance().GetMDetector();
112 
113  std::ostringstream os;
114  for (mevt::MEvent::CounterIterator ic = me.CountersBegin(); ic != me.CountersEnd(); ++ic) {
115 
116  mevt::Counter& counter = *ic;
117  const int counterId = counter.GetId();
118 
119  if (counter.IsRejected()) {
120  os.str("");
121  os << "Skipping the rejected counter " << counterId;
122  INFO(os);
123  continue;
124  }
125 
126  os.str("");
127  os << "Processing counter " << counterId;
128  INFO(os);
129 
130  const mdet::Counter& mdetCounter = theMdDetector.GetCounter(counterId);
131  //int stationId = mdetCounter.GetAssociatedTankId();
132 
133  for (mevt::Counter::ModuleIterator im = counter.ModulesBegin(), em = counter.ModulesEnd(); im != em; ++im) {
134 
135  DEBUGLOG("Starting module loop");
136  mevt::Module& module = *im;
137  const int moduleId = module.GetId();
138  //const int moduleGlobalId = counterId*100 + moduleId;
139 
140  os.str("");
141  os << "Processing module " << moduleId;
142  DEBUGLOG(os);
143 
144  const mdet::Module& mdetModule = mdetCounter.GetModule(moduleId);
145 
146  // Check if module was flagged as rejected (by a selector) or, in the case of real data, if T1 from SD was not matched
147  // this should imply empty module traces (all "0s")
148  if (module.IsRejected()) {
149  os.str("");
150  os << "Module " << module.GetId() << " of counter " << counterId;
151  os << " discarded because flagged as: " << module.GetRejectionReason();
152  WARNING(os);
153  continue;
154  }
155 
156  if (!module.HasRecData()) {
157  module.MakeRecData();
158  }
159  DEBUGLOG("After making mRecData");
160 
161  // Get a vector with the channel ids and bin numbers of the pattern matches
162  const std::vector<std::pair<unsigned int, unsigned int>> vModulePatternMatches = GetModulePatternMatches(module);
163  DEBUGLOG("After getting vModulePatternMatches");
164 
165  // Fill the channelsOn histogram
166  FillChannelsOn(module, vModulePatternMatches, mdetModule);
167  DEBUGLOG("After filling channelsOn");
168 
169  // The pattern matches of the channels are already filled into
170  // the ChannelRecData by MdPatternFinder
171  // Fill that information into the ModuleRecData
172  LoadPatternMatchesInModuleRecData(module, vModulePatternMatches, mdetModule);
173  DEBUGLOG("After loading pattern matches in the module reconstructed data");
174 
175  SetSegmentationAndArea(module, mdetModule); //Before EstimateNumberOfMuons!
176  DEBUGLOG("After setting the segmentation and area");
177 
178  EstimateNumberOfMuons(module, vModulePatternMatches);
179  DEBUGLOG("After estimating number of muons");
180  } // end module loop
181  } // end counter loop
182 
183  return eSuccess;
184  }
185 
186 
188  MdMuonEstimator::Finish()
189  {
190  return eSuccess;
191  }
192 
193 
194  unsigned int
195  MdMuonEstimator::GetTraceLength(evt::Event& event)
196  const
197  {
198  unsigned int nTraceSamples = 0;
199 
200  mevt::MEvent& me = event.GetMEvent();
201  for (mevt::MEvent::CounterIterator ic = me.CountersBegin(); ic != me.CountersEnd(); ++ic) {
202  mevt::Counter& counter = *ic;
203  if (counter.IsRejected()) {
204  continue;
205  }
206  const int counterId = counter.GetId();
207  for (mevt::Counter::ModuleIterator im = counter.ModulesBegin(), em = counter.ModulesEnd(); im != em; ++im) {
208  mevt::Module& module = *im;
209  if (module.IsRejected()) {
210  continue;
211  }
212  const int moduleId = module.GetId();
213 
214  const mdet::MDetector& theMdDetector = det::Detector::GetInstance().GetMDetector();
215  const mdet::Counter& mdetCounter = theMdDetector.GetCounter(counterId);
216  const mdet::Module& mdetModule = mdetCounter.GetModule(moduleId);
217 
218  nTraceSamples = mdetModule.IsSiPM() ?
219  mdetModule.GetFrontEndSiPM().GetBufferLength() :
220  mdetModule.GetFrontEnd().GetBufferLength();
221 
222  //cout << "nTraceSamples " << nTraceSamples << endl;
223  if (!nTraceSamples) {
224  break;
225  }
226  }
227  if (!nTraceSamples) {
228  break;
229  }
230  }
231 
232  return nTraceSamples;
233  }
234 
235 
236 double
237  MdMuonEstimator::GetSamplingTime(evt::Event& event)
238  const
239  {
240  double samplingTime = 0;
241 
242  mevt::MEvent& me = event.GetMEvent();
243  for (mevt::MEvent::CounterIterator ic = me.CountersBegin(); ic != me.CountersEnd(); ++ic) {
244  mevt::Counter& counter = *ic;
245  if (counter.IsRejected()) {
246  continue;
247  }
248  const int counterId = counter.GetId();
249  for (mevt::Counter::ModuleIterator im = counter.ModulesBegin(), em = counter.ModulesEnd(); im != em; ++im) {
250  mevt::Module& module = *im;
251  if (module.IsRejected()) {
252  continue;
253  }
254  const int moduleId = module.GetId();
255 
256  const mdet::MDetector& theMdDetector = det::Detector::GetInstance().GetMDetector();
257  const mdet::Counter& mdetCounter = theMdDetector.GetCounter(counterId);
258  const mdet::Module& mdetModule = mdetCounter.GetModule(moduleId);
259 
260  samplingTime = mdetModule.IsSiPM() ?
262  mdetModule.GetFrontEnd().GetMeanSampleRatePeriod();
263 
264  //cout << "samplingTime " << samplingTime << endl;
265  if (!samplingTime) {
266  break;
267  }
268  }
269  if (!samplingTime) {
270  break;
271  }
272  }
273 
274  return samplingTime;
275  }
276 
277 
278  std::vector<std::pair<unsigned int, unsigned int>>
279  MdMuonEstimator::GetModulePatternMatches(mevt::Module& module)
280  const
281  {
282  // Get pattern match bins
283  std::vector<std::pair<unsigned int, unsigned int>> vMatchBins;
284  for (mevt::Module::ChannelIterator channel = module.ChannelsBegin(), ech = module.ChannelsEnd();
285  channel != ech; ++channel) {
286 
287  if (channel->HasRecData() && !channel->IsMasked()) { // Use unmasked channels only
288  for (mevt::ChannelRecData::PatternMatchBinIterator mut = channel->GetRecData().PatternMatchBinsBegin(),
289  end = channel->GetRecData().PatternMatchBinsEnd(); mut != end; ++mut) {
290  vMatchBins.push_back(std::make_pair(channel->GetId(),*mut));
291  }
292  }
293  }
294 
295  return vMatchBins;
296  }
297 
298 
299  void
300  MdMuonEstimator::FillChannelsOn(mevt::Module& module, const std::vector<std::pair<unsigned int, unsigned int>>& vModulePatternMatches, const mdet::Module& mdetModule)
301  const
302  {
303  mevt::ModuleRecData& mRecData = module.GetRecData();
304 
305  // ChannelsOnTrace: Module-level trace that adds a 1 in every time-bin where a pattern match starts
306  if ( !mRecData.HasChannelsOn())
307  mRecData.MakeChannelsOn();
308 
309  utl::TraceUI& channelsOnTrace = mRecData.GetChannelsOn();
310 
311  // ChannelsInhibitedTrace: Module-level trace that adds a 1 in every time-bin of a pattern match except the first bin
312  if ( !mRecData.HasChannelsInhibited() )
313  mRecData.MakeChannelsInhibited();
314 
315  utl::TraceUI& channelsInhibitedTrace = mRecData.GetChannelsInhibited();
316 
317  // Get the size and binning of the module (they are the same for all channels)
318  const unsigned int traceSize = mdetModule.IsSiPM() ?
319  mdetModule.GetFrontEndSiPM().GetBufferLength() :
320  mdetModule.GetFrontEnd().GetBufferLength();
321 
322  // Fill auxiliary vectors to fill later the channelsOn and channelsInhibited traces
323  std::vector<unsigned int> channelsOnVector(traceSize,0);
324  std::vector<unsigned int> channelsInhibitedVector(traceSize,0);
325  for (std::vector<std::pair<unsigned int, unsigned int>>::const_iterator it = vModulePatternMatches.begin(); it != vModulePatternMatches.end(); ++it) {
326  const unsigned int bin = it->second;
327  ++channelsOnVector[bin];
328  for (unsigned int i = 1; i < (unsigned int) mRecData.GetWindowSize(); ++i){
329  ++channelsInhibitedVector[bin+i];
330  }
331  }
332  // Fill the ChannelsOnTrace
333  for (std::vector<unsigned int>::const_iterator it = channelsOnVector.begin(); it != channelsOnVector.end(); ++it){
334  channelsOnTrace.PushBack(*it);
335  }
336  // Fill the ChannelsInhibitedTrace
337  for (std::vector<unsigned int>::const_iterator it = channelsInhibitedVector.begin(); it != channelsInhibitedVector.end(); ++it){
338  channelsInhibitedTrace.PushBack(*it);
339  }
340 
341  // Set the ChannelsOn binning
342  const double samplingTime = mdetModule.IsSiPM() ?
344  mdetModule.GetFrontEnd().GetMeanSampleRatePeriod();
345  const double channelsOnBinning = samplingTime * fCountingWindowSize;
346  channelsOnTrace.SetBinning(channelsOnBinning);
347 
348  std::ostringstream info;
349  info << "Counting channels on\n"
350  "Number of bins = " << traceSize << "\n"
351  "Binning (ns) = " << channelsOnBinning;
352  DEBUGLOG(info);
353  }
354 
355  void
356  MdMuonEstimator::LoadPatternMatchesInModuleRecData(mevt::Module& module, const std::vector<std::pair<unsigned int, unsigned int>>& vModulePatternMatches, const mdet::Module& mdetModule)
357  const
358  {
359  DEBUGLOG("Starting LoadPatternMatchesInModuleRecData");
360  mevt::ModuleRecData& mRecData = module.GetRecData();
361 
362  // Fill the pattern match times vector
363  const double samplingTime = mdetModule.IsSiPM() ?
365  mdetModule.GetFrontEnd().GetMeanSampleRatePeriod();
366 
367  for (std::vector<std::pair<unsigned int, unsigned int>>::const_iterator it = vModulePatternMatches.begin();
368  it != vModulePatternMatches.end(); ++it) {
369  const double matchTime = it->second * samplingTime;
370  mRecData.AddPatternMatchTime(matchTime);
371  //std::cout << "Recontructed matched times in counter " << cId << ", Module " << module.GetId() << " " << matchTime << std::endl;
372  }
373  DEBUGLOG("After filling the pattern match times vector");
374  }
375 
376 void
377  MdMuonEstimator::SetSegmentationAndArea(mevt::Module& module, const mdet::Module& mdetModule)
378  const
379  {
380  mevt::ModuleRecData& mRecData = module.GetRecData();
381 
382  const size_t segmentation = module.GetNumberOfActiveChannels();
383  mRecData.SetSegmentation(segmentation);
384  DEBUGLOG("After setting the segmentation");
385 
386  const mdet::Scintillator& scintillator = *(mdetModule.ScintillatorsBegin());
387  const double scintillatorArea = scintillator.GetArea();
388  const double moduleArea = scintillatorArea * segmentation;
389  mRecData.SetActiveArea(moduleArea);
390  DEBUGLOG("After setting the active area");
391  }
392 
393 void
394  MdMuonEstimator::EstimateNumberOfMuons(mevt::Module& module, std::vector<std::pair<unsigned int, unsigned int>> vModulePatternMatches)
395  const
396  {
397  // TODO: Add error estimation
398  mevt::ModuleRecData& mRecData = module.GetRecData();
399  std::ostringstream os;
400 
401  // Set the number of estimated muons
402  const double numberOfMuons = (*fEstimator)(vModulePatternMatches, mRecData);
403  mRecData.SetNumberOfEstimatedMuons(numberOfMuons);
404  DEBUGLOG("After setting the number of muons");
405 
406  // Calculate errors with the likelihood at a later step in the reconstruction, using the profile likelihood
407  mRecData.SetNumberOfMuonsErrorHigh(0);
408  mRecData.SetNumberOfMuonsErrorLow(0);
409 
410  if (!mRecData.IsSaturated()) {
411  os.str("");
412  os << "module " << module.GetId() << ", "
413  << std::fixed << std::setprecision(1)
414  << "area = " << mRecData.GetActiveArea() << " m2, "
415  << "bars = " << mRecData.GetSegmentation() << ", "
416  << "muons = " << numberOfMuons; // << " +" << errorHigh << " -" << errorLow;
417  INFO(os);
418  } else {
419  os.str("");
420  os << "module " << module.GetId() << " is saturated";
421  INFO(os);
422  }
423  // Set the lower limit to the number of muons for both saturated and unsaturated modules
424  mRecData.SetNumberOfMuonsLowLimit(0);
425 
426  DEBUGLOG("Finishing EstimateNumberOfMuons");
427  }
428 
429 }
Module level reconstruction data. This class contains all data required by the muon reconstruction...
Definition: ModuleRecData.h:29
bool HasChannelsInhibited() const
const Module & GetModule(const int mId) const
Retrieve by id a constant module.
CounterConstIterator CountersBegin() const
Definition: MEvent.h:49
bool HasMEvent() const
static EnumType Create(const int k)
int version of the overloaded creation method.
**void SetActiveArea(const double area)
Counter level event data.
void SetNumberOfMuonsLowLimit(const double e)
The lower limit to the number of muons in a module.
std::string GetRejectionReason() const
PatternMatchBinContainer::const_iterator PatternMatchBinIterator
double GetActiveArea() const
void AddPatternMatchTime(const double t)
#define INFO(message)
Macro for logging informational messages.
Definition: ErrorLogger.h:161
ScintillatorConstIterator ScintillatorsBegin() const
Begin iterator over the contained scitillators.
void Init()
Initialise the registry.
bool IsRejected() const
Check if the counter is rejected.
int GetId() const
Detector associated to muon detector hierarchy.
Definition: MDetector.h:32
Actual muon-sensitive objects.
utl::TraceUI & GetChannelsInhibited()
Class representing a document branch.
Definition: Branch.h:107
Module level event data.
Definition: MEvent/Module.h:41
utl::TraceUI & GetChannelsOn()
Number of windows with a signal in a module.
Definition: ModuleRecData.cc:9
bool HasChannelsOn() const
#define DEBUGLOG(message)
Macro for logging debugging messages.
Definition: ErrorLogger.h:157
double GetMeanSampleRatePeriod() const
Mean electronic sample rate period.
Definition: FrontEnd.cc:43
ChannelConstIterator ChannelsBegin() const
void SetNumberOfMuonsErrorHigh(const double e)
Array of Scintillator.
double GetMeanSampleRatePeriod() const
Mean electronic sample rate period.
Definition: FrontEndSiPM.cc:53
void SetNumberOfEstimatedMuons(const double m)
Number of estimated muons in a module.
#define WARNING(message)
Macro for logging warning messages.
Definition: ErrorLogger.h:163
double GetArea() const
Compute Scintillator&#39;s total area in square metres.
unsigned int GetBufferLength() const
Number of bins of the buffer.
Definition: FrontEnd.h:130
const FrontEnd & GetFrontEnd() const
InternalModuleCollection::ComponentIterator ModuleIterator
void SetSegmentation(const size_t nm)
ModuleConstIterator ModulesBegin() const
Root detector of the muon detector hierarchy.
Functor implementing a muon counting strategy bin-wise.
void SetBinning(const double binning)
Definition: Trace.h:139
ChannelConstIterator ChannelsEnd() const
ResultFlag
Flag returned by module methods to the RunController.
Definition: VModule.h:60
int GetId() const
The id of the counter.
Functor implementing a muon counting strategy bin-wise.
unsigned int GetWindowSize() const
ModuleConstIterator ModulesEnd() const
InternalCounterCollection::ComponentIterator CounterIterator
Definition: MEvent.h:31
static CentralConfig * GetInstance()
Use this the first time you get an instance of central configuration.
Template class for a FADC data or calibrated data container. Use the typedefs (TraceD, TraceI, etc.) defined in Trace-fwd.h.
Definition: Trace-fwd.h:19
ModuleRecData & GetRecData()
const FrontEndSiPM & GetFrontEndSiPM() const
bool IsRejected() const
void LoadConfig(const utl::Branch &b, const std::string &tag, T1 &var, const T2 &defaultValue)
Helper method to load a particular configuration parameter.
Definition: ConfigUtils.h:35
size_t GetSegmentation() const
CounterConstIterator CountersEnd() const
Definition: MEvent.h:52
constexpr double ns
Definition: AugerUnits.h:162
bool IsSiPM() const
const Counter & GetCounter(int id) const
Retrieve Counter by id.
Definition: MDetector.h:68
bool HasRecData() const
void PushBack(const T &value)
Insert a single value at the end.
Definition: Trace.h:119
#define ERROR(message)
Macro for logging error messages.
Definition: ErrorLogger.h:165
Root of the Muon event hierarchy.
Definition: MEvent.h:25
size_t GetNumberOfActiveChannels() const
void SetNumberOfMuonsErrorLow(const double e)
utl::Branch GetTopBranch(const std::string &id)
Get top branch for moduleConfigLink with given id (XML files)
bool IsSaturated() const
Definition: ModuleRecData.h:85
Functor implementing a muon counting strategy bin-wise.
Definition: NBinStrategy.h:19
void MakeRecData()
InternalChannelCollection::ComponentIterator ChannelIterator
Definition: MEvent/Module.h:68
Functor implementing a muon counting strategy bin-wise.
unsigned int GetBufferLength() const
Number of bins of the buffer.
Definition: FrontEndSiPM.h:120

, generated on Tue Sep 26 2023.