CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
HGCDigitizer.cc
Go to the documentation of this file.
19 #include <algorithm>
20 #include <boost/foreach.hpp>
22 
23 //#define EDM_ML_DEBUG
24 using namespace std;
25 using namespace hgc_digi;
26 
27 typedef std::unordered_map<uint32_t, std::vector<std::pair<float, float>>> IdHit_Map;
28 typedef std::tuple<float, float, float> hit_timeStamp;
29 typedef std::unordered_map<uint32_t, std::vector<hit_timeStamp>> hitRec_container;
30 
31 namespace {
32 
33  constexpr std::array<double, 4> occupancyGuesses = {{0.5, 0.2, 0.2, 0.8}};
34 
35  float getPositionDistance(const HGCalGeometry* geom, const DetId& id) { return geom->getPosition(id).mag(); }
36 
37  int getCellThickness(const HGCalGeometry* geom, const DetId& detid) {
38  const auto& dddConst = geom->topology().dddConstants();
39  return (1 + dddConst.waferType(detid));
40  }
41 
42  void getValidDetIds(const HGCalGeometry* geom, std::unordered_set<DetId>& valid) {
43  const std::vector<DetId>& ids = geom->getValidDetIds();
44  valid.reserve(ids.size());
45  valid.insert(ids.begin(), ids.end());
46  }
47 
48  DetId simToReco(const HGCalGeometry* geom, unsigned simId) {
49  DetId result(0);
50  const auto& topo = geom->topology();
51  const auto& dddConst = topo.dddConstants();
52 
53  if (dddConst.waferHexagon8() || dddConst.tileTrapezoid()) {
54  result = DetId(simId);
55  } else {
56  int subdet(DetId(simId).subdetId()), layer, cell, sec, subsec, zp;
57  HGCalTestNumbering::unpackHexagonIndex(simId, subdet, zp, layer, sec, subsec, cell);
58  //sec is wafer and subsec is celltyp
59  //skip this hit if after ganging it is not valid
60  auto recoLayerCell = dddConst.simToReco(cell, layer, sec, topo.detectorType());
61  cell = recoLayerCell.first;
62  layer = recoLayerCell.second;
63  if (layer < 0 || cell < 0) {
64  return result;
65  } else {
66  //assign the RECO DetId
67  result = HGCalDetId((ForwardSubdetector)subdet, zp, layer, subsec, sec, cell);
68  }
69  }
70  return result;
71  }
72 
73  void saveSimHitAccumulator_forPreMix(PHGCSimAccumulator& simResult,
74  const hgc::HGCPUSimHitDataAccumulator& simData,
75  const std::unordered_set<DetId>& validIds,
76  const float minCharge,
77  const float maxCharge) {
78  constexpr auto nEnergies = std::tuple_size<decltype(hgc_digi::HGCCellHitInfo().PUhit_info)>::value;
79  static_assert(nEnergies <= PHGCSimAccumulator::SimHitCollection::energyMask + 1,
80  "PHGCSimAccumulator bit pattern needs to updated");
82  "PHGCSimAccumulator bit pattern needs to updated");
83  const float minPackChargeLog = minCharge > 0.f ? std::log(minCharge) : -2;
84  const float maxPackChargeLog = std::log(maxCharge);
86 
87  simResult.reserve(simData.size());
88 
89  for (const auto& id : validIds) {
90  auto found = simData.find(id);
91  if (found == simData.end())
92  continue;
93 
94  const hgc_digi::PUSimHitData& accCharge_across_bxs = found->second.PUhit_info[0];
95  const hgc_digi::PUSimHitData& timing_across_bxs = found->second.PUhit_info[1];
96  for (size_t iSample = 0; iSample < hgc_digi::nSamples; ++iSample) {
97  const std::vector<float>& accCharge_inthis_bx = accCharge_across_bxs[iSample];
98  const std::vector<float>& timing_inthis_bx = timing_across_bxs[iSample];
99  std::vector<unsigned short> vc, vt;
100  size_t nhits = accCharge_inthis_bx.size();
101 
102  for (size_t ihit = 0; ihit < nhits; ++ihit) {
103  if (accCharge_inthis_bx[ihit] > minCharge) {
104  unsigned short c =
105  logintpack::pack16log(accCharge_inthis_bx[ihit], minPackChargeLog, maxPackChargeLog, base);
106  unsigned short t = logintpack::pack16log(timing_inthis_bx[ihit], minPackChargeLog, maxPackChargeLog, base);
107  vc.emplace_back(c);
108  vt.emplace_back(t);
109  }
110  }
111  simResult.emplace_back(id.rawId(), iSample, vc, vt);
112  }
113  }
114  simResult.shrink_to_fit();
115  }
116 
117  void loadSimHitAccumulator_forPreMix(hgc::HGCSimHitDataAccumulator& simData,
119  const HGCalGeometry* geom,
120  IdHit_Map& hitRefs_bx0,
121  const PHGCSimAccumulator& simAccumulator,
122  const float minCharge,
123  const float maxCharge,
124  bool setIfZero,
125  const std::array<float, 3>& tdcForToAOnset,
126  const bool minbiasFlag,
127  std::unordered_map<uint32_t, bool>& hitOrder_monitor,
128  const unsigned int thisBx) {
129  const float minPackChargeLog = minCharge > 0.f ? std::log(minCharge) : -2;
130  const float maxPackChargeLog = std::log(maxCharge);
132  for (const auto& detIdIndexHitInfo : simAccumulator) {
133  unsigned int detId = detIdIndexHitInfo.detId();
134 
135  auto simIt = simData.emplace(detId, HGCCellInfo()).first;
136  size_t nhits = detIdIndexHitInfo.nhits();
137 
138  hitOrder_monitor[detId] = false;
139  if (nhits > 0) {
140  unsigned short iSample = detIdIndexHitInfo.sampleIndex();
141 
142  const auto& unsigned_charge_array = detIdIndexHitInfo.chargeArray();
143  const auto& unsigned_time_array = detIdIndexHitInfo.timeArray();
144 
145  float p_charge, p_time;
146  unsigned short unsigned_charge, unsigned_time;
147 
148  for (size_t ihit = 0; ihit < nhits; ++ihit) {
149  unsigned_charge = (unsigned_charge_array[ihit] & PHGCSimAccumulator::SimHitCollection::dataMask);
150  unsigned_time = (unsigned_time_array[ihit] & PHGCSimAccumulator::SimHitCollection::dataMask);
151  p_time = logintpack::unpack16log(unsigned_time, minPackChargeLog, maxPackChargeLog, base);
152  p_charge = logintpack::unpack16log(unsigned_charge, minPackChargeLog, maxPackChargeLog, base);
153 
154  (simIt->second).hit_info[0][iSample] += p_charge;
155  if (iSample == (unsigned short)thisBx) {
156  if (hitRefs_bx0[detId].empty()) {
157  hitRefs_bx0[detId].emplace_back(p_charge, p_time);
158  } else {
159  if (p_time < hitRefs_bx0[detId].back().second) {
160  auto findPos = std::upper_bound(hitRefs_bx0[detId].begin(),
161  hitRefs_bx0[detId].end(),
162  std::make_pair(0.f, p_time),
163  [](const auto& i, const auto& j) { return i.second < j.second; });
164 
165  auto insertedPos = findPos;
166  if (findPos == hitRefs_bx0[detId].begin()) {
167  insertedPos = hitRefs_bx0[detId].emplace(insertedPos, p_charge, p_time);
168  } else {
169  auto prevPos = findPos - 1;
170  if (prevPos->second == p_time) {
171  prevPos->first = prevPos->first + p_charge;
172  insertedPos = prevPos;
173  } else if (prevPos->second < p_time) {
174  insertedPos = hitRefs_bx0[detId].emplace(findPos, (prevPos)->first + p_charge, p_time);
175  }
176  }
177 
178  for (auto step = insertedPos; step != hitRefs_bx0[detId].end(); ++step) {
179  if (step != insertedPos)
180  step->first += p_charge;
181  }
182 
183  hitOrder_monitor[detId] = true;
184 
185  } else if (p_time == hitRefs_bx0[detId].back().second) {
186  hitRefs_bx0[detId].back().first += p_charge;
187  } else if (p_time > hitRefs_bx0[detId].back().second) {
188  hitRefs_bx0[detId].emplace_back(hitRefs_bx0[detId].back().first + p_charge, p_time);
189  }
190  }
191  }
192  }
193  }
194  }
195 
196  if (minbiasFlag) {
197  for (const auto& hitmapIterator : hitRefs_bx0) {
198  unsigned int detectorId = hitmapIterator.first;
199  auto simIt = simData.emplace(detectorId, HGCCellInfo()).first;
200  const bool orderChanged = hitOrder_monitor[detectorId];
201  int waferThickness = getCellThickness(geom, detectorId);
202  float cell_threshold = tdcForToAOnset[waferThickness - 1];
203  const auto& hitRec = hitmapIterator.second;
204  float accChargeForToA(0.f), fireTDC(0.f);
205  const auto aboveThrPos = std::upper_bound(
206  hitRec.begin(), hitRec.end(), std::make_pair(cell_threshold, 0.f), [](const auto& i, const auto& j) {
207  return i.first < j.first;
208  });
209 
210  if (aboveThrPos == hitRec.end()) {
211  accChargeForToA = hitRec.back().first;
212  fireTDC = 0.f;
213  } else if (hitRec.end() - aboveThrPos > 0 || orderChanged) {
214  accChargeForToA = aboveThrPos->first;
215  fireTDC = aboveThrPos->second;
216  if (aboveThrPos - hitRec.begin() >= 1) {
217  const auto& belowThrPos = aboveThrPos - 1;
218  float chargeBeforeThr = belowThrPos->first;
219  float timeBeforeThr = belowThrPos->second;
220  float deltaQ = accChargeForToA - chargeBeforeThr;
221  float deltaTOF = fireTDC - timeBeforeThr;
222  fireTDC = (cell_threshold - chargeBeforeThr) * deltaTOF / deltaQ + timeBeforeThr;
223  }
224  }
225  (simIt->second).hit_info[1][9] = fireTDC;
226  }
227  }
228  }
229 } //namespace
230 
232  : simHitAccumulator_(new HGCSimHitDataAccumulator()),
233  pusimHitAccumulator_(new HGCPUSimHitDataAccumulator()),
234  geomToken_(iC.esConsumes()),
235  refSpeed_(0.1 * CLHEP::c_light), //[CLHEP::c_light]=mm/ns convert to cm/ns
236  averageOccupancies_(occupancyGuesses),
237  nEvents_(1) {
238  //configure from cfg
239 
240  hitCollection_ = ps.getParameter<std::string>("hitCollection");
241  digiCollection_ = ps.getParameter<std::string>("digiCollection");
242  maxSimHitsAccTime_ = ps.getParameter<uint32_t>("maxSimHitsAccTime");
243  bxTime_ = ps.getParameter<double>("bxTime");
244  digitizationType_ = ps.getParameter<uint32_t>("digitizationType");
245  verbosity_ = ps.getUntrackedParameter<uint32_t>("verbosity", 0);
246  tofDelay_ = ps.getParameter<double>("tofDelay");
247  premixStage1_ = ps.getParameter<bool>("premixStage1");
248  premixStage1MinCharge_ = ps.getParameter<double>("premixStage1MinCharge");
249  premixStage1MaxCharge_ = ps.getParameter<double>("premixStage1MaxCharge");
250  iC.consumes<std::vector<PCaloHit>>(edm::InputTag("g4SimHits", hitCollection_));
251  const auto& myCfg_ = ps.getParameter<edm::ParameterSet>("digiCfg");
252 
253  if (myCfg_.existsAs<edm::ParameterSet>("chargeCollectionEfficiencies")) {
254  cce_.clear();
255  const auto& temp = myCfg_.getParameter<edm::ParameterSet>("chargeCollectionEfficiencies")
256  .getParameter<std::vector<double>>("values");
257  for (double cce : temp) {
258  cce_.emplace_back(cce);
259  }
260  } else {
261  std::vector<float>().swap(cce_);
262  }
263 
264  auto const& pluginName = ps.getParameter<std::string>("digitizer");
265  theDigitizer_ = HGCDigitizerPluginFactory::get()->create(pluginName, ps);
266 }
267 
268 //
270  if (geomWatcher_.check(es)) {
271  std::unordered_set<DetId>().swap(validIds_);
272 
273  //get geometry
274  CaloGeometry const& geom = es.getData(geomToken_);
275 
276  gHGCal_ =
277  dynamic_cast<const HGCalGeometry*>(geom.getSubdetectorGeometry(theDigitizer_->det(), theDigitizer_->subdet()));
278 
279  int nadded(0);
280  //valid ID lists
281  if (nullptr != gHGCal_) {
282  getValidDetIds(gHGCal_, validIds_);
283  } else {
284  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
285  }
286 
287  if (verbosity_ > 0)
288  edm::LogInfo("HGCDigitizer") << "Added " << nadded << ":" << validIds_.size() << " detIds without "
289  << hitCollection_ << " in first event processed" << std::endl;
290  }
291 
292  // reserve memory for a full detector
293  unsigned idx = getType();
294  simHitAccumulator_->reserve(averageOccupancies_[idx] * validIds_.size());
295  pusimHitAccumulator_->reserve(averageOccupancies_[idx] * validIds_.size());
296 }
297 
298 //
299 void HGCDigitizer::finalizeEvent(edm::Event& e, edm::EventSetup const& es, CLHEP::HepRandomEngine* hre) {
300  hitRefs_bx0.clear();
301  PhitRefs_bx0.clear();
302  hitOrder_monitor.clear();
303 
304  const CaloSubdetectorGeometry* theGeom = static_cast<const CaloSubdetectorGeometry*>(gHGCal_);
305 
306  ++nEvents_;
307 
308  unsigned idx = getType();
309  // release memory for unfilled parts of hash table
310  if (validIds_.size() * averageOccupancies_[idx] > simHitAccumulator_->size()) {
311  simHitAccumulator_->reserve(simHitAccumulator_->size());
312  pusimHitAccumulator_->reserve(simHitAccumulator_->size());
313  }
314  //update occupancy guess
315  const double thisOcc = simHitAccumulator_->size() / ((double)validIds_.size());
316  averageOccupancies_[idx] = (averageOccupancies_[idx] * (nEvents_ - 1) + thisOcc) / nEvents_;
317 
318  if (premixStage1_) {
319  auto simRecord = std::make_unique<PHGCSimAccumulator>();
320 
321  if (!pusimHitAccumulator_->empty()) {
322  saveSimHitAccumulator_forPreMix(
324  }
325 
326  e.put(std::move(simRecord), digiCollection());
327 
328  } else {
329  auto digiResult = std::make_unique<HGCalDigiCollection>();
330  theDigitizer_->run(digiResult, *simHitAccumulator_, theGeom, validIds_, digitizationType_, hre);
331  edm::LogVerbatim("HGCDigitizer") << "HGCDigitizer:: finalize event - produced " << digiResult->size()
332  << " hits in det/subdet " << theDigitizer_->det() << "/"
333  << theDigitizer_->subdet();
334 #ifdef EDM_ML_DEBUG
335  checkPosition(&(*digiResult));
336 #endif
337  e.put(std::move(digiResult), digiCollection());
338  }
339 
342 }
344  edm::EventSetup const& eventSetup,
345  CLHEP::HepRandomEngine* hre) {
346  //get inputs
347 
349  e.getByLabel(edm::InputTag("g4SimHits", hitCollection_), hits);
350  if (!hits.isValid()) {
351  edm::LogError("HGCDigitizer") << " @ accumulate_minbias : can't find " << hitCollection_
352  << " collection of g4SimHits";
353  return;
354  }
355 
356  //accumulate in-time the main event
357  if (nullptr != gHGCal_) {
358  accumulate_forPreMix(hits, 0, gHGCal_, hre);
359  } else {
360  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
361  }
362 }
363 
364 //
365 void HGCDigitizer::accumulate(edm::Event const& e, edm::EventSetup const& eventSetup, CLHEP::HepRandomEngine* hre) {
366  //get inputs
368  e.getByLabel(edm::InputTag("g4SimHits", hitCollection_), hits);
369  if (!hits.isValid()) {
370  edm::LogError("HGCDigitizer") << " @ accumulate : can't find " << hitCollection_ << " collection of g4SimHits";
371  return;
372  }
373 
374  //accumulate in-time the main event
375  if (nullptr != gHGCal_) {
376  accumulate(hits, 0, gHGCal_, hre);
377  } else {
378  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
379  }
380 }
381 
382 //
384  edm::EventSetup const& eventSetup,
385  CLHEP::HepRandomEngine* hre) {
387  e.getByLabel(edm::InputTag("g4SimHits", hitCollection_), hits);
388 
389  if (!hits.isValid()) {
390  edm::LogError("HGCDigitizer") << " @ accumulate : can't find " << hitCollection_ << " collection of g4SimHits";
391  return;
392  }
393 
394  if (nullptr != gHGCal_) {
395  accumulate_forPreMix(hits, e.bunchCrossing(), gHGCal_, hre);
396  } else {
397  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
398  }
399 }
400 
401 //
403  edm::EventSetup const& eventSetup,
404  CLHEP::HepRandomEngine* hre) {
405  //get inputs
407  e.getByLabel(edm::InputTag("g4SimHits", hitCollection_), hits);
408 
409  if (!hits.isValid()) {
410  edm::LogError("HGCDigitizer") << " @ accumulate : can't find " << hitCollection_ << " collection of g4SimHits";
411  return;
412  }
413 
414  //accumulate for the simulated bunch crossing
415  if (nullptr != gHGCal_) {
416  accumulate(hits, e.bunchCrossing(), gHGCal_, hre);
417  } else {
418  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
419  }
420 }
421 
422 //
424  int bxCrossing,
425  const HGCalGeometry* geom,
426  CLHEP::HepRandomEngine* hre) {
427  if (nullptr == geom)
428  return;
429 
430  auto keV2fC = theDigitizer_->keV2fC();
431  auto tdcForToAOnset = theDigitizer_->tdcForToAOnset();
432 
433  int nchits = (int)hits->size();
434  int count_thisbx = 0;
435  std::vector<HGCCaloHitTuple_t> hitRefs;
436  hitRefs.reserve(nchits);
437  for (int i = 0; i < nchits; ++i) {
438  const auto& the_hit = hits->at(i);
439  DetId id = simToReco(geom, the_hit.id());
440  // to be written the verbosity block
441  if (id.rawId() != 0) {
442  hitRefs.emplace_back(i, id.rawId(), (float)the_hit.time());
443  }
444  }
445  std::sort(hitRefs.begin(), hitRefs.end(), this->orderByDetIdThenTime);
446 
447  nchits = hitRefs.size();
448  for (int i = 0; i < nchits; ++i) {
449  const int hitidx = std::get<0>(hitRefs[i]);
450  const uint32_t id = std::get<1>(hitRefs[i]);
451  if (!validIds_.count(id))
452  continue;
453 
454  if (id == 0)
455  continue;
456 
457  const float toa = std::get<2>(hitRefs[i]);
458  const PCaloHit& hit = hits->at(hitidx);
459  const float charge = hit.energy() * 1e6 * keV2fC; // * getCCE(geom, id, cce_);
460 
461  const float dist2center(getPositionDistance(geom, id));
462  const float tof = toa - dist2center / refSpeed_ + tofDelay_;
463  const int itime = std::floor(tof / bxTime_) + 9;
464 
465  if (itime < 0 || itime > (int)maxBx_)
466  continue;
467 
468  if (itime >= (int)(maxBx_ + 1))
469  continue;
470 
471  int waferThickness = getCellThickness(geom, id);
472  if (itime == (int)thisBx_) {
473  ++count_thisbx;
474  if (PhitRefs_bx0[id].empty()) {
475  PhitRefs_bx0[id].emplace_back(charge, charge, tof);
476  } else if (tof > std::get<2>(PhitRefs_bx0[id].back())) {
477  PhitRefs_bx0[id].emplace_back(charge, charge + std::get<1>(PhitRefs_bx0[id].back()), tof);
478  } else if (tof == std::get<2>(PhitRefs_bx0[id].back())) {
479  std::get<0>(PhitRefs_bx0[id].back()) += charge;
480  std::get<1>(PhitRefs_bx0[id].back()) += charge;
481  } else {
482  //find position to insert new entry preserving time sorting
483  auto findPos = std::upper_bound(PhitRefs_bx0[id].begin(),
484  PhitRefs_bx0[id].end(),
485  hit_timeStamp(charge, 0.f, tof),
486  [](const auto& i, const auto& j) { return std::get<2>(i) <= std::get<2>(j); });
487 
488  auto insertedPos = findPos;
489 
490  if (tof == std::get<2>(*(findPos - 1))) {
491  std::get<0>(*(findPos - 1)) += charge;
492  std::get<1>(*(findPos - 1)) += charge;
493 
494  } else {
495  insertedPos = PhitRefs_bx0[id].insert(findPos,
496  (findPos == PhitRefs_bx0[id].begin())
497  ? hit_timeStamp(charge, charge, tof)
498  : hit_timeStamp(charge, charge + std::get<1>(*(findPos - 1)), tof));
499  }
500  //cumulate the charge of new entry for all elements that follow in the sorted list
501  //and resize list accounting for cases when the inserted element itself crosses the threshold
502 
503  for (auto step = insertedPos; step != PhitRefs_bx0[id].end(); ++step) {
504  if (step != insertedPos)
505  std::get<1>(*(step)) += charge;
506 
507  // resize the list stopping with the first timeStamp with cumulative charge above threshold
508  if (std::get<1>(*step) > tdcForToAOnset[waferThickness - 1] &&
509  std::get<2>(*step) != std::get<2>(PhitRefs_bx0[id].back())) {
510  PhitRefs_bx0[id].resize(
512  PhitRefs_bx0[id].end(),
513  hit_timeStamp(charge, 0.f, std::get<2>(*step)),
514  [](const auto& i, const auto& j) { return std::get<2>(i) < std::get<2>(j); }) -
515  PhitRefs_bx0[id].begin());
516  for (auto stepEnd = step + 1; stepEnd != PhitRefs_bx0[id].end(); ++stepEnd)
517  std::get<1>(*stepEnd) += charge;
518  break;
519  }
520  }
521  }
522  }
523  }
524 
525  for (const auto& hitCollection : PhitRefs_bx0) {
526  const uint32_t detectorId = hitCollection.first;
527  auto simHitIt = pusimHitAccumulator_->emplace(detectorId, HGCCellHitInfo()).first;
528 
529  for (const auto& hit_timestamp : PhitRefs_bx0[detectorId]) {
530  (simHitIt->second).PUhit_info[1][thisBx_].push_back(std::get<2>(hit_timestamp));
531  (simHitIt->second).PUhit_info[0][thisBx_].push_back(std::get<0>(hit_timestamp));
532  }
533  }
534 
535  if (nchits == 0) {
536  HGCPUSimHitDataAccumulator::iterator simHitIt = pusimHitAccumulator_->emplace(0, HGCCellHitInfo()).first;
537  (simHitIt->second).PUhit_info[1][9].push_back(0.0);
538  (simHitIt->second).PUhit_info[0][9].push_back(0.0);
539  }
540  hitRefs.clear();
541  PhitRefs_bx0.clear();
542 }
543 
544 //
546  int bxCrossing,
547  const HGCalGeometry* geom,
548  CLHEP::HepRandomEngine* hre) {
549  if (nullptr == geom)
550  return;
551 
552  //configuration to apply for the computation of time-of-flight
553  auto weightToAbyEnergy = theDigitizer_->toaModeByEnergy();
554  auto tdcForToAOnset = theDigitizer_->tdcForToAOnset();
555  auto keV2fC = theDigitizer_->keV2fC();
556 
557  //create list of tuples (pos in container, RECO DetId, time) to be sorted first
558  int nchits = (int)hits->size();
559 
560  std::vector<HGCCaloHitTuple_t> hitRefs;
561  hitRefs.reserve(nchits);
562  for (int i = 0; i < nchits; ++i) {
563  const auto& the_hit = hits->at(i);
564  DetId id = simToReco(geom, the_hit.id());
565 
566  if (verbosity_ > 0) {
567  edm::LogVerbatim("HGCDigitizer") << "HGCDigitizer::i/p " << std::hex << the_hit.id() << " o/p " << id.rawId()
568  << std::dec;
569  }
570 
571  if (0 != id.rawId()) {
572  hitRefs.emplace_back(i, id.rawId(), (float)the_hit.time());
573  }
574  }
575 
576  std::sort(hitRefs.begin(), hitRefs.end(), this->orderByDetIdThenTime);
577  //loop over sorted hits
578  nchits = hitRefs.size();
579  for (int i = 0; i < nchits; ++i) {
580  const int hitidx = std::get<0>(hitRefs[i]);
581  const uint32_t id = std::get<1>(hitRefs[i]);
582 
583  //get the data for this cell, if not available then we skip it
584 
585  if (!validIds_.count(id))
586  continue;
587  HGCSimHitDataAccumulator::iterator simHitIt = simHitAccumulator_->emplace(id, HGCCellInfo()).first;
588 
589  if (id == 0)
590  continue; // to be ignored at RECO level
591 
592  const float toa = std::get<2>(hitRefs[i]);
593  const PCaloHit& hit = hits->at(hitidx);
594  const float charge = hit.energy() * 1e6 * keV2fC;
595 
596  //distance to the center of the detector
597  const float dist2center(getPositionDistance(geom, id));
598 
599  //hit time: [time()]=ns [centerDist]=cm [refSpeed_]=cm/ns + delay by 1ns
600  //accumulate in 15 buckets of 25ns (9 pre-samples, 1 in-time, 5 post-samples)
601  const float tof = toa - dist2center / refSpeed_ + tofDelay_;
602  const int itime = std::floor(tof / bxTime_) + 9;
603 
604  //no need to add bx crossing - tof comes already corrected from the mixing module
605  //itime += bxCrossing;
606  //itime += 9;
607 
608  if (itime < 0 || itime > (int)maxBx_)
609  continue;
610 
611  //check if time index is ok and store energy
612  if (itime >= (int)simHitIt->second.hit_info[0].size())
613  continue;
614 
615  (simHitIt->second).hit_info[0][itime] += charge;
616 
617  //for time-of-arrival: save the time-sorted list of timestamps with cumulative charge just above threshold
618  //working version with pileup only for in-time hits
619  int waferThickness = getCellThickness(geom, id);
620  bool orderChanged = false;
621  if (itime == (int)thisBx_) {
622  //if start empty => just add charge and time
623  if (hitRefs_bx0[id].empty()) {
624  hitRefs_bx0[id].emplace_back(charge, tof);
625 
626  } else if (tof <= hitRefs_bx0[id].back().second) {
627  //find position to insert new entry preserving time sorting
628  std::vector<std::pair<float, float>>::iterator findPos =
630  hitRefs_bx0[id].end(),
631  std::pair<float, float>(0.f, tof),
632  [](const auto& i, const auto& j) { return i.second <= j.second; });
633 
634  std::vector<std::pair<float, float>>::iterator insertedPos = findPos;
635  if (findPos->second == tof) {
636  //just merge timestamps with exact timing
637  findPos->first += charge;
638  } else {
639  //insert new element cumulating the charge
640  insertedPos = hitRefs_bx0[id].insert(findPos,
641  (findPos == hitRefs_bx0[id].begin())
642  ? std::pair<float, float>(charge, tof)
643  : std::pair<float, float>((findPos - 1)->first + charge, tof));
644  }
645 
646  //cumulate the charge of new entry for all elements that follow in the sorted list
647  //and resize list accounting for cases when the inserted element itself crosses the threshold
648  for (std::vector<std::pair<float, float>>::iterator step = insertedPos; step != hitRefs_bx0[id].end(); ++step) {
649  if (step != insertedPos)
650  step->first += charge;
651  // resize the list stopping with the first timeStamp with cumulative charge above threshold
652  if (step->first > tdcForToAOnset[waferThickness - 1] && step->second != hitRefs_bx0[id].back().second) {
654  hitRefs_bx0[id].end(),
655  std::pair<float, float>(0.f, step->second),
656  [](const auto& i, const auto& j) { return i.second < j.second; }) -
657  hitRefs_bx0[id].begin());
658  for (auto stepEnd = step + 1; stepEnd != hitRefs_bx0[id].end(); ++stepEnd)
659  stepEnd->first += charge;
660  break;
661  }
662  }
663 
664  orderChanged = true;
665  } else {
666  //add new entry at the end of the list
667  if (hitRefs_bx0[id].back().first <= tdcForToAOnset[waferThickness - 1]) {
668  hitRefs_bx0[id].emplace_back(hitRefs_bx0[id].back().first + charge, tof);
669  }
670  }
671  }
672  float accChargeForToA = hitRefs_bx0[id].empty() ? 0.f : hitRefs_bx0[id].back().first;
673  //now compute the firing ToA through the interpolation of the consecutive time-stamps at threshold
674  if (weightToAbyEnergy)
675  (simHitIt->second).hit_info[1][itime] += charge * tof;
676  else if (accChargeForToA > tdcForToAOnset[waferThickness - 1] &&
677  ((simHitIt->second).hit_info[1][itime] == 0 || orderChanged == true)) {
678  float fireTDC = hitRefs_bx0[id].back().second;
679  if (hitRefs_bx0[id].size() > 1) {
680  float chargeBeforeThr = (hitRefs_bx0[id].end() - 2)->first;
681  float tofchargeBeforeThr = (hitRefs_bx0[id].end() - 2)->second;
682 
683  float deltaQ = accChargeForToA - chargeBeforeThr;
684  float deltaTOF = fireTDC - tofchargeBeforeThr;
685  fireTDC = (tdcForToAOnset[waferThickness - 1] - chargeBeforeThr) * deltaTOF / deltaQ + tofchargeBeforeThr;
686  }
687  (simHitIt->second).hit_info[1][itime] = fireTDC;
688  }
689  }
690  hitRefs.clear();
691 }
692 void HGCDigitizer::accumulate_forPreMix(const PHGCSimAccumulator& simAccumulator, const bool minbiasFlag) {
693  //configuration to apply for the computation of time-of-flight
694  auto weightToAbyEnergy = theDigitizer_->toaModeByEnergy();
695  auto tdcForToAOnset = theDigitizer_->tdcForToAOnset();
696 
697  if (nullptr != gHGCal_) {
698  loadSimHitAccumulator_forPreMix(*simHitAccumulator_,
700  gHGCal_,
701  hitRefs_bx0,
702  simAccumulator,
705  !weightToAbyEnergy,
706  tdcForToAOnset,
707  minbiasFlag,
709  thisBx_);
710  }
711 }
712 
713 //
715  for (HGCSimHitDataAccumulator::iterator it = simHitAccumulator_->begin(); it != simHitAccumulator_->end(); it++) {
716  it->second.hit_info[0].fill(0.);
717  it->second.hit_info[1].fill(0.);
718  }
719 }
720 
721 uint32_t HGCDigitizer::getType() const {
722  uint32_t idx = std::numeric_limits<unsigned>::max();
723  switch (theDigitizer_->det()) {
724  case DetId::HGCalEE:
725  idx = 0;
726  break;
727  case DetId::HGCalHSi:
728  idx = 1;
729  break;
730  case DetId::HGCalHSc:
731  idx = 2;
732  break;
733  case DetId::Forward:
734  idx = 3;
735  break;
736  default:
737  break;
738  }
739  return idx;
740 }
741 
743  const double tol(0.5);
744  if (nullptr != gHGCal_) {
745  for (const auto& digi : *(digis)) {
746  const DetId& id = digi.id();
747  const GlobalPoint& global = gHGCal_->getPosition(id);
748  double r = global.perp();
749  double z = std::abs(global.z());
750  std::pair<double, double> zrange = gHGCal_->topology().dddConstants().rangeZ(true);
751  std::pair<double, double> rrange = gHGCal_->topology().dddConstants().rangeR(z, true);
752  bool ok = ((r >= rrange.first) && (r <= rrange.second) && (z >= zrange.first) && (z <= zrange.second));
753  std::string ck = (((r < rrange.first - tol) || (r > rrange.second + tol) || (z < zrange.first - tol) ||
754  (z > zrange.second + tol))
755  ? "***** ERROR *****"
756  : "");
757  bool val = gHGCal_->topology().valid(id);
758  if ((!ok) || (!val)) {
759  if (id.det() == DetId::HGCalEE || id.det() == DetId::HGCalHSi) {
760  edm::LogVerbatim("HGCDigitizer") << "Check " << HGCSiliconDetId(id) << " " << global << " R " << r << ":"
761  << rrange.first << ":" << rrange.second << " Z " << z << ":" << zrange.first
762  << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
763  } else if (id.det() == DetId::HGCalHSc) {
764  edm::LogVerbatim("HGCDigitizer") << "Check " << HGCScintillatorDetId(id) << " " << global << " R " << r << ":"
765  << rrange.first << ":" << rrange.second << " Z " << z << ":" << zrange.first
766  << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
767  } else if ((id.det() == DetId::Forward) && (id.subdetId() == static_cast<int>(HFNose))) {
768  edm::LogVerbatim("HGCDigitizer") << "Check " << HFNoseDetId(id) << " " << global << " R " << r << ":"
769  << rrange.first << ":" << rrange.second << " Z " << z << ":" << zrange.first
770  << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
771  } else {
772  edm::LogVerbatim("HGCDigitizer")
773  << "Check " << std::hex << id.rawId() << std::dec << " " << id.det() << ":" << id.subdetId() << " "
774  << global << " R " << r << ":" << rrange.first << ":" << rrange.second << " Z " << z << ":"
775  << zrange.first << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
776  }
777  }
778  }
779  }
780 }
tuple base
Main Program
Definition: newFWLiteAna.py:92
EDGetTokenT< ProductType > consumes(edm::InputTag const &tag)
Log< level::Info, true > LogVerbatim
uint32_t nEvents_
Definition: HGCDigitizer.h:123
const CaloSubdetectorGeometry * getSubdetectorGeometry(const DetId &id) const
access the subdetector geometry for the given subdetector directly
Definition: CaloGeometry.cc:34
void emplace_back(unsigned int detId, unsigned short sampleIndex, const std::vector< unsigned short > &accCharge, const std::vector< unsigned short > &timing)
T getUntrackedParameter(std::string const &, T const &) const
bool premixStage1_
Definition: HGCDigitizer.h:86
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:133
static std::vector< std::string > checklist log
std::vector< float > cce_
Definition: HGCDigitizer.h:128
const edm::EventSetup & c
void finalizeEvent(edm::Event &e, edm::EventSetup const &c, CLHEP::HepRandomEngine *hre)
T perp() const
Definition: PV3DBase.h:69
int digitizationType_
Definition: HGCDigitizer.h:83
std::string hitCollection_
Definition: HGCDigitizer.h:80
std::unique_ptr< HGCDigitizerBase > theDigitizer_
Definition: HGCDigitizer.h:104
uint16_t *__restrict__ id
void resetSimHitDataAccumulator()
const edm::ESGetToken< CaloGeometry, CaloGeometryRecord > geomToken_
Definition: HGCDigitizer.h:107
bool valid(const DetId &id) const override
Is this a valid cell id.
std::unordered_map< uint32_t, HGCCellInfo > HGCSimHitDataAccumulator
__host__ __device__ constexpr RandomIt upper_bound(RandomIt first, RandomIt last, const T &value, Compare comp={})
void initializeEvent(edm::Event const &e, edm::EventSetup const &c)
actions at the start/end of event
static constexpr unsigned dataMask
double unpack16log(int16_t i, double lmin, double lmax, uint16_t base=32768)
Definition: liblogintpack.h:62
Log< level::Error, false > LogError
ForwardSubdetector
const HGCalGeometry * gHGCal_
Definition: HGCDigitizer.h:110
void swap(Association< C > &lhs, Association< C > &rhs)
Definition: Association.h:117
constexpr std::array< uint8_t, layerIndexSize > layer
std::string digiCollection_
Definition: HGCDigitizer.h:80
tuple result
Definition: mps_fire.py:311
bool getData(T &iHolder) const
Definition: EventSetup.h:122
U second(std::pair< T, U > const &p)
std::pair< double, double > rangeR(double z, bool reco) const
static const unsigned int maxBx_
Definition: HGCDigitizer.h:126
edm::ESWatcher< CaloGeometryRecord > geomWatcher_
Definition: HGCDigitizer.h:108
std::unordered_map< uint32_t, std::vector< hit_timeStamp > > hitRec_container
Definition: HGCDigitizer.cc:29
static constexpr unsigned sampleOffset
std::pair< double, double > rangeZ(bool reco) const
T mag() const
Definition: PV3DBase.h:64
std::unordered_map< uint32_t, std::vector< std::tuple< float, float, float > > > PhitRefs_bx0
Definition: HGCDigitizer.h:130
T z() const
Definition: PV3DBase.h:61
const HGCalTopology & topology() const
std::unordered_map< uint32_t, bool > hitOrder_monitor
Definition: HGCDigitizer.h:131
def move
Definition: eostools.py:511
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
std::array< HGCSimDataCollection, nSamples > PUSimHitData
std::unordered_set< DetId > validIds_
Definition: HGCDigitizer.h:109
bool isValid() const
Definition: HandleBase.h:70
constexpr size_t nSamples
static const unsigned int thisBx_
Definition: HGCDigitizer.h:127
bool getByLabel(InputTag const &tag, Handle< PROD > &result) const
Definition: Event.h:500
std::unordered_map< uint32_t, std::vector< std::pair< float, float > > > IdHit_Map
Definition: HGCDigitizer.cc:27
Log< level::Info, false > LogInfo
uint32_t getType() const
Definition: DetId.h:17
void reserve(size_t size)
double premixStage1MinCharge_
Definition: HGCDigitizer.h:89
void checkPosition(const HGCalDigiCollection *digis) const
const HGCalDDDConstants & dddConstants() const
Definition: HGCalTopology.h:98
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
const std::vector< DetId > & getValidDetIds(DetId::Detector det=DetId::Detector(0), int subdet=0) const override
Get a list of valid detector ids (for the given subdetector)
Definition: HGCalGeometry.h:89
int maxSimHitsAccTime_
Definition: HGCDigitizer.h:94
bool check(const edm::EventSetup &iSetup)
Definition: ESWatcher.h:57
deadvectors[0] push_back({0.0175431, 0.538005, 6.80997, 13.29})
std::array< double, 4 > averageOccupancies_
Definition: HGCDigitizer.h:122
void accumulate(edm::Event const &e, edm::EventSetup const &c, CLHEP::HepRandomEngine *hre)
handle SimHit accumulation
GlobalPoint getPosition(const DetId &id, bool debug=false) const
bool getByLabel(edm::InputTag const &tag, edm::Handle< T > &result) const
std::unordered_map< uint32_t, std::vector< std::pair< float, float > > > hitRefs_bx0
Definition: HGCDigitizer.h:129
string end
Definition: dataset.py:937
HGCDigitizer(const edm::ParameterSet &ps, edm::ConsumesCollector &iC)
std::tuple< float, float, float > hit_timeStamp
Definition: HGCDigitizer.cc:28
step
Definition: StallMonitor.cc:98
#define get
std::unique_ptr< hgc::HGCSimHitDataAccumulator > simHitAccumulator_
Definition: HGCDigitizer.h:96
static bool orderByDetIdThenTime(const HGCCaloHitTuple_t &a, const HGCCaloHitTuple_t &b)
Definition: HGCDigitizer.h:36
double bxTime_
Definition: HGCDigitizer.h:95
void accumulate_forPreMix(edm::Event const &e, edm::EventSetup const &c, CLHEP::HepRandomEngine *hre)
static constexpr unsigned energyMask
int16_t pack16log(double x, double lmin, double lmax, uint16_t base=32768)
Definition: liblogintpack.h:27
double premixStage1MaxCharge_
Definition: HGCDigitizer.h:91
std::unique_ptr< hgc::HGCPUSimHitDataAccumulator > pusimHitAccumulator_
Definition: HGCDigitizer.h:97
std::string digiCollection()
Definition: HGCDigitizer.h:76
ESGetTokenH3DDVariant esConsumes(std::string const &Reccord, edm::ConsumesCollector &)
Definition: DeDxTools.cc:283
tuple size
Write out results.
static void unpackHexagonIndex(const uint32_t &idx, int &subdet, int &z, int &lay, int &wafer, int &celltyp, int &cell)
uint32_t verbosity_
Definition: HGCDigitizer.h:113
static constexpr unsigned sampleMask
std::unordered_map< uint32_t, HGCCellHitInfo > HGCPUSimHitDataAccumulator