CMS 3D CMS Logo

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  digiCollection_(ps.getParameter<std::string>("digiCollection")),
235  digitizationType_(ps.getParameter<uint32_t>("digitizationType")),
236  premixStage1_(ps.getParameter<bool>("premixStage1")),
237  premixStage1MinCharge_(ps.getParameter<double>("premixStage1MinCharge")),
238  premixStage1MaxCharge_(ps.getParameter<double>("premixStage1MaxCharge")),
239  maxSimHitsAccTime_(ps.getParameter<uint32_t>("maxSimHitsAccTime")),
240  bxTime_(ps.getParameter<double>("bxTime")),
241  hitsProducer_(ps.getParameter<std::string>("hitsProducer")),
242  hitCollection_(ps.getParameter<std::string>("hitCollection")),
243  hitToken_(iC.consumes<std::vector<PCaloHit>>(edm::InputTag(hitsProducer_, hitCollection_))),
244  geomToken_(iC.esConsumes()),
245  verbosity_(ps.getUntrackedParameter<uint32_t>("verbosity", 0)),
246  refSpeed_(0.1 * CLHEP::c_light), //[CLHEP::c_light]=mm/ns convert to cm/ns
247  tofDelay_(ps.getParameter<double>("tofDelay")),
248  averageOccupancies_(occupancyGuesses),
249  nEvents_(1) {
250  //configure from cfg
251 
252  const auto& myCfg_ = ps.getParameter<edm::ParameterSet>("digiCfg");
253 
254  if (myCfg_.existsAs<edm::ParameterSet>("chargeCollectionEfficiencies")) {
255  cce_.clear();
256  const auto& temp = myCfg_.getParameter<edm::ParameterSet>("chargeCollectionEfficiencies")
257  .getParameter<std::vector<double>>("values");
258  for (double cce : temp) {
259  cce_.emplace_back(cce);
260  }
261  } else {
262  std::vector<float>().swap(cce_);
263  }
264 
265  auto const& pluginName = ps.getParameter<std::string>("digitizer");
267 }
268 
269 //
271  if (geomWatcher_.check(es)) {
272  std::unordered_set<DetId>().swap(validIds_);
273 
274  //get geometry
275  CaloGeometry const& geom = es.getData(geomToken_);
276 
277  gHGCal_ =
278  dynamic_cast<const HGCalGeometry*>(geom.getSubdetectorGeometry(theDigitizer_->det(), theDigitizer_->subdet()));
279 
280  int nadded(0);
281  //valid ID lists
282  if (nullptr != gHGCal_) {
283  getValidDetIds(gHGCal_, validIds_);
284  } else {
285  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
286  }
287 
288  if (verbosity_ > 0)
289  edm::LogInfo("HGCDigitizer") << "Added " << nadded << ":" << validIds_.size() << " detIds without "
290  << hitCollection_ << " in first event processed" << std::endl;
291  }
292 
293  // reserve memory for a full detector
294  unsigned idx = getType();
297 }
298 
299 //
300 void HGCDigitizer::finalizeEvent(edm::Event& e, edm::EventSetup const& es, CLHEP::HepRandomEngine* hre) {
301  hitRefs_bx0.clear();
302  PhitRefs_bx0.clear();
303  hitOrder_monitor.clear();
304 
305  const CaloSubdetectorGeometry* theGeom = static_cast<const CaloSubdetectorGeometry*>(gHGCal_);
306 
307  ++nEvents_;
308 
309  unsigned idx = getType();
310  // release memory for unfilled parts of hash table
311  if (validIds_.size() * averageOccupancies_[idx] > simHitAccumulator_->size()) {
312  simHitAccumulator_->reserve(simHitAccumulator_->size());
313  pusimHitAccumulator_->reserve(simHitAccumulator_->size());
314  }
315  //update occupancy guess
316  const double thisOcc = simHitAccumulator_->size() / ((double)validIds_.size());
318 
319  if (premixStage1_) {
320  auto simRecord = std::make_unique<PHGCSimAccumulator>();
321 
322  if (!pusimHitAccumulator_->empty()) {
323  saveSimHitAccumulator_forPreMix(
325  }
326 
327  e.put(std::move(simRecord), digiCollection());
328 
329  } else {
330  auto digiResult = std::make_unique<HGCalDigiCollection>();
331  theDigitizer_->run(digiResult, *simHitAccumulator_, theGeom, validIds_, digitizationType_, hre);
332  edm::LogVerbatim("HGCDigitizer") << "HGCDigitizer:: finalize event - produced " << digiResult->size()
333  << " hits in det/subdet " << theDigitizer_->det() << "/"
334  << theDigitizer_->subdet();
335 #ifdef EDM_ML_DEBUG
336  checkPosition(&(*digiResult));
337 #endif
338  e.put(std::move(digiResult), digiCollection());
339  }
340 
343 }
346  CLHEP::HepRandomEngine* hre) {
347  //get inputs
348 
350  if (!hits.isValid()) {
351  edm::LogError("HGCDigitizer") << " @ accumulate_minbias : can't find " << hitCollection_ << " collection of "
352  << hitsProducer_;
353  return;
354  }
355 
356  //accumulate in-time the main event
357  if (nullptr != gHGCal_) {
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  if (!hits.isValid()) {
369  edm::LogError("HGCDigitizer") << " @ accumulate : can't find " << hitCollection_ << " collection of "
370  << hitsProducer_;
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 //
385  CLHEP::HepRandomEngine* hre) {
388  e.getByLabel(hitTag, hits);
389 
390  if (!hits.isValid()) {
391  edm::LogError("HGCDigitizer") << " @ accumulate : can't find " << hitCollection_ << " collection of "
392  << hitsProducer_;
393  return;
394  }
395 
396  if (nullptr != gHGCal_) {
397  accumulate_forPreMix(hits, e.bunchCrossing(), gHGCal_, hre);
398  } else {
399  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
400  }
401 }
402 
403 //
406  CLHEP::HepRandomEngine* hre) {
407  //get inputs
410  e.getByLabel(hitTag, hits);
411 
412  if (!hits.isValid()) {
413  edm::LogError("HGCDigitizer") << " @ accumulate : can't find " << hitCollection_ << " collection of "
414  << hitsProducer_;
415  return;
416  }
417 
418  //accumulate for the simulated bunch crossing
419  if (nullptr != gHGCal_) {
420  accumulate(hits, e.bunchCrossing(), gHGCal_, hre);
421  } else {
422  throw cms::Exception("BadConfiguration") << "HGCDigitizer is not producing EE, FH, or BH digis!";
423  }
424 }
425 
426 //
428  int bxCrossing,
429  const HGCalGeometry* geom,
430  CLHEP::HepRandomEngine* hre) {
431  if (nullptr == geom)
432  return;
433 
434  auto keV2fC = theDigitizer_->keV2fC();
435  auto tdcForToAOnset = theDigitizer_->tdcForToAOnset();
436 
437  int nchits = (int)hits->size();
438  int count_thisbx = 0;
439  std::vector<HGCCaloHitTuple_t> hitRefs;
440  hitRefs.reserve(nchits);
441  for (int i = 0; i < nchits; ++i) {
442  const auto& the_hit = hits->at(i);
443  DetId id = simToReco(geom, the_hit.id());
444  // to be written the verbosity block
445  if (id.rawId() != 0) {
446  hitRefs.emplace_back(i, id.rawId(), (float)the_hit.time());
447  }
448  }
449  std::sort(hitRefs.begin(), hitRefs.end(), this->orderByDetIdThenTime);
450 
451  nchits = hitRefs.size();
452  for (int i = 0; i < nchits; ++i) {
453  const int hitidx = std::get<0>(hitRefs[i]);
454  const uint32_t id = std::get<1>(hitRefs[i]);
455  if (!validIds_.count(id))
456  continue;
457 
458  if (id == 0)
459  continue;
460 
461  const float toa = std::get<2>(hitRefs[i]);
462  const PCaloHit& hit = hits->at(hitidx);
463  const float charge = hit.energy() * 1e6 * keV2fC; // * getCCE(geom, id, cce_);
464 
465  const float dist2center(getPositionDistance(geom, id));
466  const float tof = toa - dist2center / refSpeed_ + tofDelay_;
467  const int itime = std::floor(tof / bxTime_) + 9;
468 
469  if (itime < 0 || itime > (int)maxBx_)
470  continue;
471 
472  if (itime >= (int)(maxBx_ + 1))
473  continue;
474 
475  int waferThickness = getCellThickness(geom, id);
476  if (itime == (int)thisBx_) {
477  ++count_thisbx;
478  if (PhitRefs_bx0[id].empty()) {
479  PhitRefs_bx0[id].emplace_back(charge, charge, tof);
480  } else if (tof > std::get<2>(PhitRefs_bx0[id].back())) {
481  PhitRefs_bx0[id].emplace_back(charge, charge + std::get<1>(PhitRefs_bx0[id].back()), tof);
482  } else if (tof == std::get<2>(PhitRefs_bx0[id].back())) {
483  std::get<0>(PhitRefs_bx0[id].back()) += charge;
484  std::get<1>(PhitRefs_bx0[id].back()) += charge;
485  } else {
486  //find position to insert new entry preserving time sorting
487  auto findPos = std::upper_bound(PhitRefs_bx0[id].begin(),
488  PhitRefs_bx0[id].end(),
489  hit_timeStamp(charge, 0.f, tof),
490  [](const auto& i, const auto& j) { return std::get<2>(i) <= std::get<2>(j); });
491 
492  auto insertedPos = findPos;
493 
494  if (tof == std::get<2>(*(findPos - 1))) {
495  std::get<0>(*(findPos - 1)) += charge;
496  std::get<1>(*(findPos - 1)) += charge;
497 
498  } else {
499  insertedPos = PhitRefs_bx0[id].insert(findPos,
500  (findPos == PhitRefs_bx0[id].begin())
501  ? hit_timeStamp(charge, charge, tof)
502  : hit_timeStamp(charge, charge + std::get<1>(*(findPos - 1)), tof));
503  }
504  //cumulate the charge of new entry for all elements that follow in the sorted list
505  //and resize list accounting for cases when the inserted element itself crosses the threshold
506 
507  for (auto step = insertedPos; step != PhitRefs_bx0[id].end(); ++step) {
508  if (step != insertedPos)
509  std::get<1>(*(step)) += charge;
510 
511  // resize the list stopping with the first timeStamp with cumulative charge above threshold
512  if (std::get<1>(*step) > tdcForToAOnset[waferThickness - 1] &&
513  std::get<2>(*step) != std::get<2>(PhitRefs_bx0[id].back())) {
514  PhitRefs_bx0[id].resize(
515  std::upper_bound(PhitRefs_bx0[id].begin(),
516  PhitRefs_bx0[id].end(),
517  hit_timeStamp(charge, 0.f, std::get<2>(*step)),
518  [](const auto& i, const auto& j) { return std::get<2>(i) < std::get<2>(j); }) -
519  PhitRefs_bx0[id].begin());
520  for (auto stepEnd = step + 1; stepEnd != PhitRefs_bx0[id].end(); ++stepEnd)
521  std::get<1>(*stepEnd) += charge;
522  break;
523  }
524  }
525  }
526  }
527  }
528 
529  for (const auto& hitCollection : PhitRefs_bx0) {
530  const uint32_t detectorId = hitCollection.first;
531  auto simHitIt = pusimHitAccumulator_->emplace(detectorId, HGCCellHitInfo()).first;
532 
533  for (const auto& hit_timestamp : PhitRefs_bx0[detectorId]) {
534  (simHitIt->second).PUhit_info[1][thisBx_].push_back(std::get<2>(hit_timestamp));
535  (simHitIt->second).PUhit_info[0][thisBx_].push_back(std::get<0>(hit_timestamp));
536  }
537  }
538 
539  if (nchits == 0) {
540  HGCPUSimHitDataAccumulator::iterator simHitIt = pusimHitAccumulator_->emplace(0, HGCCellHitInfo()).first;
541  (simHitIt->second).PUhit_info[1][9].push_back(0.0);
542  (simHitIt->second).PUhit_info[0][9].push_back(0.0);
543  }
544  hitRefs.clear();
545  PhitRefs_bx0.clear();
546 }
547 
548 //
550  int bxCrossing,
551  const HGCalGeometry* geom,
552  CLHEP::HepRandomEngine* hre) {
553  if (nullptr == geom)
554  return;
555 
556  //configuration to apply for the computation of time-of-flight
557  auto weightToAbyEnergy = theDigitizer_->toaModeByEnergy();
558  auto tdcForToAOnset = theDigitizer_->tdcForToAOnset();
559  auto keV2fC = theDigitizer_->keV2fC();
560 
561  //create list of tuples (pos in container, RECO DetId, time) to be sorted first
562  int nchits = (int)hits->size();
563 
564  std::vector<HGCCaloHitTuple_t> hitRefs;
565  hitRefs.reserve(nchits);
566  for (int i = 0; i < nchits; ++i) {
567  const auto& the_hit = hits->at(i);
568  DetId id = simToReco(geom, the_hit.id());
569 
570  if (verbosity_ > 0) {
571  edm::LogVerbatim("HGCDigitizer") << "HGCDigitizer::i/p " << std::hex << the_hit.id() << " o/p " << id.rawId()
572  << std::dec;
573  }
574 
575  if (0 != id.rawId()) {
576  hitRefs.emplace_back(i, id.rawId(), (float)the_hit.time());
577  }
578  }
579 
580  std::sort(hitRefs.begin(), hitRefs.end(), this->orderByDetIdThenTime);
581  //loop over sorted hits
582  nchits = hitRefs.size();
583  for (int i = 0; i < nchits; ++i) {
584  const int hitidx = std::get<0>(hitRefs[i]);
585  const uint32_t id = std::get<1>(hitRefs[i]);
586 
587  //get the data for this cell, if not available then we skip it
588 
589  if (!validIds_.count(id))
590  continue;
591  HGCSimHitDataAccumulator::iterator simHitIt = simHitAccumulator_->emplace(id, HGCCellInfo()).first;
592 
593  if (id == 0)
594  continue; // to be ignored at RECO level
595 
596  const float toa = std::get<2>(hitRefs[i]);
597  const PCaloHit& hit = hits->at(hitidx);
598  const float charge = hit.energy() * 1e6 * keV2fC;
599 
600  //distance to the center of the detector
601  const float dist2center(getPositionDistance(geom, id));
602 
603  //hit time: [time()]=ns [centerDist]=cm [refSpeed_]=cm/ns + delay by 1ns
604  //accumulate in 15 buckets of 25ns (9 pre-samples, 1 in-time, 5 post-samples)
605  const float tof = toa - dist2center / refSpeed_ + tofDelay_;
606  const int itime = std::floor(tof / bxTime_) + 9;
607 
608  //no need to add bx crossing - tof comes already corrected from the mixing module
609  //itime += bxCrossing;
610  //itime += 9;
611 
612  if (itime < 0 || itime > (int)maxBx_)
613  continue;
614 
615  //check if time index is ok and store energy
616  if (itime >= (int)simHitIt->second.hit_info[0].size())
617  continue;
618 
619  (simHitIt->second).hit_info[0][itime] += charge;
620 
621  //for time-of-arrival: save the time-sorted list of timestamps with cumulative charge just above threshold
622  //working version with pileup only for in-time hits
623  int waferThickness = getCellThickness(geom, id);
624  bool orderChanged = false;
625  if (itime == (int)thisBx_) {
626  //if start empty => just add charge and time
627  if (hitRefs_bx0[id].empty()) {
628  hitRefs_bx0[id].emplace_back(charge, tof);
629 
630  } else if (tof <= hitRefs_bx0[id].back().second) {
631  //find position to insert new entry preserving time sorting
632  std::vector<std::pair<float, float>>::iterator findPos =
633  std::upper_bound(hitRefs_bx0[id].begin(),
634  hitRefs_bx0[id].end(),
635  std::pair<float, float>(0.f, tof),
636  [](const auto& i, const auto& j) { return i.second <= j.second; });
637 
638  std::vector<std::pair<float, float>>::iterator insertedPos = findPos;
639  if (findPos->second == tof) {
640  //just merge timestamps with exact timing
641  findPos->first += charge;
642  } else {
643  //insert new element cumulating the charge
644  insertedPos = hitRefs_bx0[id].insert(findPos,
645  (findPos == hitRefs_bx0[id].begin())
646  ? std::pair<float, float>(charge, tof)
647  : std::pair<float, float>((findPos - 1)->first + charge, tof));
648  }
649 
650  //cumulate the charge of new entry for all elements that follow in the sorted list
651  //and resize list accounting for cases when the inserted element itself crosses the threshold
652  for (std::vector<std::pair<float, float>>::iterator step = insertedPos; step != hitRefs_bx0[id].end(); ++step) {
653  if (step != insertedPos)
654  step->first += charge;
655  // resize the list stopping with the first timeStamp with cumulative charge above threshold
656  if (step->first > tdcForToAOnset[waferThickness - 1] && step->second != hitRefs_bx0[id].back().second) {
657  hitRefs_bx0[id].resize(std::upper_bound(hitRefs_bx0[id].begin(),
658  hitRefs_bx0[id].end(),
659  std::pair<float, float>(0.f, step->second),
660  [](const auto& i, const auto& j) { return i.second < j.second; }) -
661  hitRefs_bx0[id].begin());
662  for (auto stepEnd = step + 1; stepEnd != hitRefs_bx0[id].end(); ++stepEnd)
663  stepEnd->first += charge;
664  break;
665  }
666  }
667 
668  orderChanged = true;
669  } else {
670  //add new entry at the end of the list
671  if (hitRefs_bx0[id].back().first <= tdcForToAOnset[waferThickness - 1]) {
672  hitRefs_bx0[id].emplace_back(hitRefs_bx0[id].back().first + charge, tof);
673  }
674  }
675  }
676  float accChargeForToA = hitRefs_bx0[id].empty() ? 0.f : hitRefs_bx0[id].back().first;
677  //now compute the firing ToA through the interpolation of the consecutive time-stamps at threshold
678  if (weightToAbyEnergy)
679  (simHitIt->second).hit_info[1][itime] += charge * tof;
680  else if (accChargeForToA > tdcForToAOnset[waferThickness - 1] &&
681  ((simHitIt->second).hit_info[1][itime] == 0 || orderChanged == true)) {
682  float fireTDC = hitRefs_bx0[id].back().second;
683  if (hitRefs_bx0[id].size() > 1) {
684  float chargeBeforeThr = (hitRefs_bx0[id].end() - 2)->first;
685  float tofchargeBeforeThr = (hitRefs_bx0[id].end() - 2)->second;
686 
687  float deltaQ = accChargeForToA - chargeBeforeThr;
688  float deltaTOF = fireTDC - tofchargeBeforeThr;
689  fireTDC = (tdcForToAOnset[waferThickness - 1] - chargeBeforeThr) * deltaTOF / deltaQ + tofchargeBeforeThr;
690  }
691  (simHitIt->second).hit_info[1][itime] = fireTDC;
692  }
693  }
694  hitRefs.clear();
695 }
696 void HGCDigitizer::accumulate_forPreMix(const PHGCSimAccumulator& simAccumulator, const bool minbiasFlag) {
697  //configuration to apply for the computation of time-of-flight
698  auto weightToAbyEnergy = theDigitizer_->toaModeByEnergy();
699  auto tdcForToAOnset = theDigitizer_->tdcForToAOnset();
700 
701  if (nullptr != gHGCal_) {
702  loadSimHitAccumulator_forPreMix(*simHitAccumulator_,
704  gHGCal_,
705  hitRefs_bx0,
706  simAccumulator,
709  !weightToAbyEnergy,
710  tdcForToAOnset,
711  minbiasFlag,
713  thisBx_);
714  }
715 }
716 
717 //
719  for (HGCSimHitDataAccumulator::iterator it = simHitAccumulator_->begin(); it != simHitAccumulator_->end(); it++) {
720  it->second.hit_info[0].fill(0.);
721  it->second.hit_info[1].fill(0.);
722  }
723 }
724 
725 uint32_t HGCDigitizer::getType() const {
727  switch (theDigitizer_->det()) {
728  case DetId::HGCalEE:
729  idx = 0;
730  break;
731  case DetId::HGCalHSi:
732  idx = 1;
733  break;
734  case DetId::HGCalHSc:
735  idx = 2;
736  break;
737  case DetId::Forward:
738  idx = 3;
739  break;
740  default:
741  break;
742  }
743  return idx;
744 }
745 
747  const double tol(0.5);
748  if (nullptr != gHGCal_) {
749  for (const auto& digi : *(digis)) {
750  const DetId& id = digi.id();
751  const GlobalPoint& global = gHGCal_->getPosition(id);
752  double r = global.perp();
753  double z = std::abs(global.z());
754  std::pair<double, double> zrange = gHGCal_->topology().dddConstants().rangeZ(true);
755  std::pair<double, double> rrange = gHGCal_->topology().dddConstants().rangeR(z, true);
756  bool ok = ((r >= rrange.first) && (r <= rrange.second) && (z >= zrange.first) && (z <= zrange.second));
757  std::string ck = (((r < rrange.first - tol) || (r > rrange.second + tol) || (z < zrange.first - tol) ||
758  (z > zrange.second + tol))
759  ? "***** ERROR *****"
760  : "");
761  bool val = gHGCal_->topology().valid(id);
762  if ((!ok) || (!val)) {
763  if (id.det() == DetId::HGCalEE || id.det() == DetId::HGCalHSi) {
764  edm::LogVerbatim("HGCDigitizer") << "Check " << HGCSiliconDetId(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::HGCalHSc) {
768  edm::LogVerbatim("HGCDigitizer") << "Check " << HGCScintillatorDetId(id) << " " << global << " R " << r << ":"
769  << rrange.first << ":" << rrange.second << " Z " << z << ":" << zrange.first
770  << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
771  } else if ((id.det() == DetId::Forward) && (id.subdetId() == static_cast<int>(HFNose))) {
772  edm::LogVerbatim("HGCDigitizer") << "Check " << HFNoseDetId(id) << " " << global << " R " << r << ":"
773  << rrange.first << ":" << rrange.second << " Z " << z << ":" << zrange.first
774  << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
775  } else {
776  edm::LogVerbatim("HGCDigitizer")
777  << "Check " << std::hex << id.rawId() << std::dec << " " << id.det() << ":" << id.subdetId() << " "
778  << global << " R " << r << ":" << rrange.first << ":" << rrange.second << " Z " << z << ":"
779  << zrange.first << ":" << zrange.second << " Flag " << ok << ":" << val << " " << ck;
780  }
781  }
782  }
783  }
784 }
const std::string hitsProducer_
Definition: HGCDigitizer.h:101
size
Write out results.
Log< level::Info, true > LogVerbatim
uint32_t nEvents_
Definition: HGCDigitizer.h:129
void emplace_back(unsigned int detId, unsigned short sampleIndex, const std::vector< unsigned short > &accCharge, const std::vector< unsigned short > &timing)
const float refSpeed_
Definition: HGCDigitizer.h:122
void checkPosition(const HGCalDigiCollection *digis) const
std::pair< double, double > rangeZ(bool reco) const
ESGetTokenH3DDVariant esConsumes(std::string const &Record, edm::ConsumesCollector &)
Definition: DeDxTools.cc:283
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
std::vector< float > cce_
Definition: HGCDigitizer.h:134
T perp() const
Definition: PV3DBase.h:69
void finalizeEvent(edm::Event &e, edm::EventSetup const &c, CLHEP::HepRandomEngine *hre)
std::unique_ptr< HGCDigitizerBase > theDigitizer_
Definition: HGCDigitizer.h:110
void resetSimHitDataAccumulator()
T z() const
Definition: PV3DBase.h:61
const edm::ESGetToken< CaloGeometry, CaloGeometryRecord > geomToken_
Definition: HGCDigitizer.h:113
bool valid(const DetId &id) const override
Is this a valid cell id.
base
Main Program
Definition: newFWLiteAna.py:92
std::unordered_map< uint32_t, HGCCellInfo > HGCSimHitDataAccumulator
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
const double premixStage1MaxCharge_
Definition: HGCDigitizer.h:95
ForwardSubdetector
const HGCalGeometry * gHGCal_
Definition: HGCDigitizer.h:116
void swap(Association< C > &lhs, Association< C > &rhs)
Definition: Association.h:117
constexpr std::array< uint8_t, layerIndexSize > layer
uint32_t getType() const
U second(std::pair< T, U > const &p)
const double premixStage1MinCharge_
Definition: HGCDigitizer.h:93
static const unsigned int maxBx_
Definition: HGCDigitizer.h:132
edm::ESWatcher< CaloGeometryRecord > geomWatcher_
Definition: HGCDigitizer.h:114
std::unordered_map< uint32_t, std::vector< hit_timeStamp > > hitRec_container
Definition: HGCDigitizer.cc:29
const uint32_t verbosity_
Definition: HGCDigitizer.h:119
static constexpr unsigned sampleOffset
std::unordered_map< uint32_t, std::vector< std::tuple< float, float, float > > > PhitRefs_bx0
Definition: HGCDigitizer.h:136
std::unordered_map< uint32_t, bool > hitOrder_monitor
Definition: HGCDigitizer.h:137
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
std::array< HGCSimDataCollection, nSamples > PUSimHitData
double f[11][100]
std::unordered_set< DetId > validIds_
Definition: HGCDigitizer.h:115
bool getData(T &iHolder) const
Definition: EventSetup.h:122
constexpr size_t nSamples
const HGCalTopology & topology() const
static const unsigned int thisBx_
Definition: HGCDigitizer.h:133
std::unordered_map< uint32_t, std::vector< std::pair< float, float > > > IdHit_Map
Definition: HGCDigitizer.cc:27
std::pair< double, double > rangeR(double z, bool reco) const
Log< level::Info, false > LogInfo
Definition: DetId.h:17
void reserve(size_t size)
const bool premixStage1_
Definition: HGCDigitizer.h:90
bool check(const edm::EventSetup &iSetup)
Definition: ESWatcher.h:57
deadvectors [0] push_back({0.0175431, 0.538005, 6.80997, 13.29})
const edm::EDGetTokenT< std::vector< PCaloHit > > hitToken_
Definition: HGCDigitizer.h:103
GlobalPoint getPosition(const DetId &id, bool debug=false) const
std::array< double, 4 > averageOccupancies_
Definition: HGCDigitizer.h:128
void accumulate(edm::Event const &e, edm::EventSetup const &c, CLHEP::HepRandomEngine *hre)
handle SimHit accumulation
HLT enums.
const float tofDelay_
Definition: HGCDigitizer.h:125
std::unordered_map< uint32_t, std::vector< std::pair< float, float > > > hitRefs_bx0
Definition: HGCDigitizer.h:135
const double bxTime_
Definition: HGCDigitizer.h:99
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:81
static bool orderByDetIdThenTime(const HGCCaloHitTuple_t &a, const HGCCaloHitTuple_t &b)
Definition: HGCDigitizer.h:36
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
std::unique_ptr< hgc::HGCPUSimHitDataAccumulator > pusimHitAccumulator_
Definition: HGCDigitizer.h:82
std::string digiCollection()
Definition: HGCDigitizer.h:76
const HGCalDDDConstants & dddConstants() const
Definition: HGCalTopology.h:98
static void unpackHexagonIndex(const uint32_t &idx, int &subdet, int &z, int &lay, int &wafer, int &celltyp, int &cell)
def move(src, dest)
Definition: eostools.py:511
const int digitizationType_
Definition: HGCDigitizer.h:87
const std::string hitCollection_
Definition: HGCDigitizer.h:102
static constexpr unsigned sampleMask
std::unordered_map< uint32_t, HGCCellHitInfo > HGCPUSimHitDataAccumulator