CMS 3D CMS Logo

CaloSD.cc
Go to the documentation of this file.
1 // File: CaloSD.cc
3 // Description: Sensitive Detector class for calorimeters
5 
14 
15 #include "G4EventManager.hh"
16 #include "G4LogicalVolumeStore.hh"
17 #include "G4LogicalVolume.hh"
18 #include "G4SDManager.hh"
19 #include "G4Step.hh"
20 #include "G4Track.hh"
21 #include "G4VProcess.hh"
22 #include "G4GFlashSpot.hh"
23 #include "G4ParticleTable.hh"
24 #include "G4PhysicalConstants.hh"
25 
26 #include <CLHEP/Units/SystemOfUnits.h>
27 
28 #include <fstream>
29 #include <memory>
30 #include <sstream>
31 
32 //#define EDM_ML_DEBUG
33 
35  const SensitiveDetectorCatalog& clg,
36  edm::ParameterSet const& p,
37  const SimTrackManager* manager,
38  float timeSliceUnit,
39  bool ignoreTkID,
40  const std::string& newcollName)
41  : SensitiveCaloDetector(name, clg, newcollName),
42  G4VGFlashSensitiveDetector(),
43  eminHit(0.),
44  m_trackManager(manager),
45  ignoreTrackID(ignoreTkID),
46  timeSlice(timeSliceUnit),
47  eminHitD(0.) {
48  //Parameters
49  nHC_ = (newcollName.empty()) ? 1 : 2;
50  for (int k = 0; k < 2; ++k) {
51  currentHit[k] = nullptr;
52  theHC[k] = nullptr;
53  hcID[k] = -1;
54  }
55  bool dd4hep = p.getParameter<bool>("g4GeometryDD4hepSource");
56  int addlevel = dd4hep ? 1 : 0;
57  edm::ParameterSet m_CaloSD = p.getParameter<edm::ParameterSet>("CaloSD");
58  energyCut = m_CaloSD.getParameter<double>("EminTrack") * CLHEP::GeV;
59  tmaxHit = m_CaloSD.getParameter<double>("TmaxHit") * CLHEP::ns;
60  std::vector<double> eminHits = m_CaloSD.getParameter<std::vector<double>>("EminHits");
61  std::vector<double> tmaxHits = m_CaloSD.getParameter<std::vector<double>>("TmaxHits");
62  hcn_ = m_CaloSD.getParameter<std::vector<std::string>>("HCNames");
63  useResMap_ = m_CaloSD.getParameter<std::vector<int>>("UseResponseTables");
64  std::vector<double> eminHitX = m_CaloSD.getParameter<std::vector<double>>("EminHitsDepth");
65  suppressHeavy = m_CaloSD.getParameter<bool>("SuppressHeavy");
66  kmaxIon = m_CaloSD.getParameter<double>("IonThreshold") * CLHEP::MeV;
67  kmaxProton = m_CaloSD.getParameter<double>("ProtonThreshold") * CLHEP::MeV;
68  kmaxNeutron = m_CaloSD.getParameter<double>("NeutronThreshold") * CLHEP::MeV;
69  nCheckedHits[0] = m_CaloSD.getUntrackedParameter<int>("CheckHits", 25);
70  nCheckedHits[1] = nCheckedHits[0];
71  useMap = m_CaloSD.getUntrackedParameter<bool>("UseMap", true);
72  int verbn = m_CaloSD.getUntrackedParameter<int>("Verbosity", 0);
73  corrTOFBeam = m_CaloSD.getParameter<bool>("CorrectTOFBeam");
74  double beamZ = m_CaloSD.getParameter<double>("BeamPosition") * CLHEP::cm;
75  correctT = beamZ / CLHEP::c_light / CLHEP::nanosecond;
76  doFineCalo_ = m_CaloSD.getParameter<bool>("DoFineCalo");
77  eMinFine_ = m_CaloSD.getParameter<double>("EminFineTrack") * CLHEP::MeV;
78  std::vector<std::string> fineNames = m_CaloSD.getParameter<std::vector<std::string>>("FineCaloNames");
79  std::vector<int> fineLevels = m_CaloSD.getParameter<std::vector<int>>("FineCaloLevels");
80  std::vector<int> useFines = m_CaloSD.getParameter<std::vector<int>>("UseFineCalo");
81  for (auto& level : fineLevels)
82  level += addlevel;
83 
84  SetVerboseLevel(verbn);
85  for (int k = 0; k < 2; ++k)
86  meanResponse[k].reset(nullptr);
87  for (unsigned int k = 0; k < hcn_.size(); ++k) {
88  if (name == hcn_[k]) {
89  if (k < eminHits.size())
90  eminHit = eminHits[k] * CLHEP::MeV;
91  if (k < eminHitX.size())
92  eminHitD = eminHitX[k] * CLHEP::MeV;
93  if (k < tmaxHits.size())
94  tmaxHit = tmaxHits[k] * CLHEP::ns;
95  if (k < useResMap_.size() && useResMap_[k] > 0) {
96  meanResponse[0] = std::make_unique<CaloMeanResponse>(p);
97  break;
98  }
99  }
100  }
101  detName_ = name;
102  collName_[0] = name;
103  collName_[1] = newcollName;
104  slave[0] = std::make_unique<CaloSlaveSD>(name);
105  slave[1].reset(nullptr);
106 
107  for (int k = 0; k < 2; ++k) {
110  }
111  isParameterized = false;
112 
113  entrancePoint.set(0., 0., 0.);
114  entranceLocal.set(0., 0., 0.);
115  posGlobal.set(0., 0., 0.);
117 
118  primAncestor = 0;
119  forceSave = false;
120  for (int k = 0; k < 2; ++k) {
121  cleanIndex[k] = primIDSaved[k] = totalHits[k] = 0;
122  }
123 
124  edm::LogVerbatim("CaloSim") << "CaloSD: Minimum energy of track for saving it " << energyCut / CLHEP::GeV
125  << " GeV\n Use of HitID Map " << useMap << "\n Check last "
126  << nCheckedHits[0] << " before saving the hit\n Correct TOF globally by "
127  << correctT << " ns (Flag =" << corrTOFBeam << ")\n Save hits recorded before "
128  << tmaxHit << " ns and if energy is above " << eminHit / CLHEP::MeV
129  << " MeV (for depth 0) or " << eminHitD / CLHEP::MeV
130  << " MeV (for nonzero depths);\n Time Slice Unit " << timeSlice
131  << "\nIgnore TrackID Flag " << ignoreTrackID << " doFineCalo flag " << doFineCalo_
132  << "\nBeam Position " << beamZ / CLHEP::cm << " cm";
133  if (doFineCalo_)
134  edm::LogVerbatim("DoFineCalo") << "Using finecalo v2";
135 
136  // Treat fine calorimeters
137  edm::LogVerbatim("CaloSim") << "CaloSD: Have a possibility of " << fineNames.size() << " fine calorimeters of which "
138  << useFines.size() << " are selected";
139  for (unsigned int k = 0; k < fineNames.size(); ++k)
140  edm::LogVerbatim("CaloSim") << "[" << k << "] " << fineNames[k] << " at " << fineLevels[k];
141  std::ostringstream st1;
142  for (unsigned int k = 0; k < useFines.size(); ++k)
143  st1 << " [" << k << "] " << useFines[k] << ":" << fineNames[useFines[k]];
144  edm::LogVerbatim("CaloSim") << "CaloSD used calorimeters" << st1.str();
145  const G4LogicalVolumeStore* lvs = G4LogicalVolumeStore::GetInstance();
146  std::vector<G4LogicalVolume*>::const_iterator lvcite;
147  for (unsigned int i = 0; i < useFines.size(); i++) {
148  G4LogicalVolume* lv = nullptr;
149  G4String name = static_cast<G4String>(fineNames[useFines[i]]);
150  for (lvcite = lvs->begin(); lvcite != lvs->end(); lvcite++) {
151  G4String namx(static_cast<G4String>(DD4hep2DDDName::nameMatterLV((*lvcite)->GetName(), dd4hep)));
152  if (namx == name) {
153  lv = (*lvcite);
154  break;
155  }
156  }
157  if (lv != nullptr) {
159  detector.name = name;
160  detector.lv = lv;
161  detector.level = fineLevels[useFines[i]];
162  fineDetectors_.emplace_back(detector);
163  }
164  }
165 #ifdef EDM_ML_DEBUG
166  edm::LogVerbatim("CaloSim") << "CaloSD::Loads information for " << fineDetectors_.size() << " fine detectors";
167  unsigned int k(0);
168  for (const auto& detector : fineDetectors_) {
169  edm::LogVerbatim("CaloSim") << "Detector[" << k << "] " << detector.name << " at level " << detector.level
170  << " pointer to LV: " << detector.lv;
171  }
172 #endif
173 }
174 
176 
178  for (unsigned int k = 0; k < hcn_.size(); ++k) {
179  if (name == hcn_[k]) {
180  if (k < useResMap_.size() && useResMap_[k] > 0) {
181  meanResponse[1] = std::make_unique<CaloMeanResponse>(p);
182  break;
183  }
184  }
185  }
186  slave[1] = std::make_unique<CaloSlaveSD>(name);
187 #ifdef EDM_ML_DEBUG
188  edm::LogVerbatim("CaloSim") << "CaloSD:: Initialise a second collection for " << name;
189  for (int k = 0; k < nHC_; ++k)
190  edm::LogVerbatim("CaloSim") << "Detector[" << k << "]" << detName_ << " collection " << collName_[k];
191 
192 #endif
193 }
194 
195 G4bool CaloSD::ProcessHits(G4Step* aStep, G4TouchableHistory*) {
196  NaNTrap(aStep);
197  ignoreReject = false;
198 
199 #ifdef EDM_ML_DEBUG
200  edm::LogVerbatim("CaloSim") << "CaloSD::" << GetName() << " ID= " << aStep->GetTrack()->GetTrackID()
201  << " prID= " << aStep->GetTrack()->GetParentID()
202  << " Eprestep= " << aStep->GetPreStepPoint()->GetKineticEnergy()
203  << " step= " << aStep->GetStepLength() << " Edep= " << aStep->GetTotalEnergyDeposit();
204 #endif
205 
206  // Class variable to determine whether finecalo rules should apply for this step
207  doFineCaloThisStep_ = (doFineCalo_ && isItFineCalo(aStep->GetPreStepPoint()->GetTouchable()));
208 
209  // apply shower library or parameterisation
210  // independent on energy deposition at a step
211  if (isParameterized) {
212  if (getFromLibrary(aStep)) {
213  // for parameterized showers the primary track should be killed
214  // secondary tracks should be killed if they are in the same volume
215  (aStep->GetTrack())->SetTrackStatus(fStopAndKill);
216  if (0 < aStep->GetNumberOfSecondariesInCurrentStep()) {
217  auto tv = aStep->GetSecondaryInCurrentStep();
218  auto vol = aStep->GetPreStepPoint()->GetPhysicalVolume();
219  for (auto& tk : *tv) {
220  if (tk->GetVolume() == vol) {
221  const_cast<G4Track*>(tk)->SetTrackStatus(fStopAndKill);
222  }
223  }
224  }
225  return true;
226  }
227  }
228 
229  // ignore steps without energy deposit
230  edepositEM = edepositHAD = 0.f;
231  if (aStep->GetTotalEnergyDeposit() <= 0.0) {
232  return false;
233  }
234 
235  // check unitID
236  unsigned int unitID = setDetUnitId(aStep);
237  auto const theTrack = aStep->GetTrack();
238  uint16_t depth = getDepth(aStep);
239 
240  double time = theTrack->GetGlobalTime() / CLHEP::nanosecond;
241  int primaryID = getTrackID(theTrack);
242  if (unitID > 0) {
243  currentID[0].setID(unitID, time, primaryID, depth);
244  } else {
245  if (!ignoreReject) {
246  const G4TouchableHistory* touch = static_cast<const G4TouchableHistory*>(theTrack->GetTouchable());
247  edm::LogVerbatim("CaloSim") << "CaloSD::ProcessHits: unitID= " << unitID
248  << " currUnit= " << currentID[0].unitID() << " Detector: " << GetName()
249  << " trackID= " << theTrack->GetTrackID() << " "
250  << theTrack->GetDefinition()->GetParticleName()
251  << "\n Edep= " << aStep->GetTotalEnergyDeposit()
252  << " PV: " << touch->GetVolume(0)->GetName()
253  << " PVid= " << touch->GetReplicaNumber(0) << " MVid= " << touch->GetReplicaNumber(1);
254  }
255  return false;
256  }
257  double energy = getEnergyDeposit(aStep);
258  if (energy <= 0.0) {
259  return false;
260  }
261 
262  if (doFineCaloThisStep_) {
263  currentID[0].setID(unitID, time, findBoundaryCrossingParent(theTrack), depth);
265  }
266 
268  edepositEM = energy;
269  } else {
271  }
272 #ifdef EDM_ML_DEBUG
273  const G4TouchableHistory* touch = static_cast<const G4TouchableHistory*>(theTrack->GetTouchable());
274  edm::LogVerbatim("CaloSim") << "CaloSD::" << GetName() << " PV:" << touch->GetVolume(0)->GetName()
275  << " PVid=" << touch->GetReplicaNumber(0) << " MVid=" << touch->GetReplicaNumber(1)
276  << " Unit:" << std::hex << unitID << std::dec << " Edep=" << edepositEM << " "
277  << edepositHAD << " ID=" << theTrack->GetTrackID() << " pID=" << theTrack->GetParentID()
278  << " E=" << theTrack->GetKineticEnergy() << " S=" << aStep->GetStepLength() << "\n "
279  << theTrack->GetDefinition()->GetParticleName() << " primaryID= " << primaryID
280  << " currentID= (" << currentID[0] << ") previousID= (" << previousID[0] << ")";
281 #endif
282  if (!hitExists(aStep, 0)) {
283  currentHit[0] = createNewHit(aStep, theTrack, 0);
284  } else {
285 #ifdef EDM_ML_DEBUG
286  edm::LogVerbatim("DoFineCalo") << "Not creating new hit, only updating " << shortreprID(currentHit[0]);
287 #endif
288  }
289 
290  processSecondHit(aStep, theTrack);
291 
292  return true;
293 }
294 
295 bool CaloSD::ProcessHits(G4GFlashSpot* aSpot, G4TouchableHistory*) {
296  edepositEM = edepositHAD = 0.f;
297  const G4Track* track = aSpot->GetOriginatorTrack()->GetPrimaryTrack();
298 
299  double edep = aSpot->GetEnergySpot()->GetEnergy();
300  if (edep <= 0.0) {
301  return false;
302  }
303 
304  G4Step fFakeStep;
305  G4StepPoint* fFakePreStepPoint = fFakeStep.GetPreStepPoint();
306  G4StepPoint* fFakePostStepPoint = fFakeStep.GetPostStepPoint();
307  fFakePreStepPoint->SetPosition(aSpot->GetPosition());
308  fFakePostStepPoint->SetPosition(aSpot->GetPosition());
309 
310  G4TouchableHandle fTouchableHandle = aSpot->GetTouchableHandle();
311  fFakePreStepPoint->SetTouchableHandle(fTouchableHandle);
312  fFakeStep.SetTotalEnergyDeposit(edep);
313  edep = EnergyCorrected(fFakeStep, track);
314 
315  // zero edep means hit outside the calorimeter
316  if (edep <= 0.0) {
317  return false;
318  }
319 
321  edepositEM = edep;
322  } else {
323  edepositHAD = edep;
324  }
325 
326  unsigned int unitID = setDetUnitId(&fFakeStep);
327 
328  if (unitID > 0) {
329  // time of initial track
330  double time = track->GetGlobalTime() / CLHEP::nanosecond;
331  int primaryID = getTrackID(track);
332  uint16_t depth = getDepth(&fFakeStep);
333  currentID[0].setID(unitID, time, primaryID, depth);
334 #ifdef EDM_ML_DEBUG
335  edm::LogVerbatim("CaloSim") << "CaloSD:: GetSpotInfo for Unit 0x" << std::hex << currentID[0].unitID() << std::dec
336  << " Edeposit = " << edepositEM << " " << edepositHAD;
337 #endif
338  // Update if in the same detector, time-slice and for same track
339  if (currentID[0] == previousID[0]) {
340  updateHit(currentHit[0], 0);
341  } else {
342  posGlobal = aSpot->GetEnergySpot()->GetPosition();
343  // Reset entry point for new primary
344  if (currentID[0].trackID() != previousID[0].trackID()) {
345  entrancePoint = aSpot->GetPosition();
346  entranceLocal = aSpot->GetTouchableHandle()->GetHistory()->GetTopTransform().TransformPoint(entrancePoint);
347  incidentEnergy = track->GetKineticEnergy();
348 #ifdef EDM_ML_DEBUG
349  edm::LogVerbatim("CaloSim") << "CaloSD: Incident energy " << incidentEnergy / CLHEP::GeV << " GeV and"
350  << " entrance point " << entrancePoint << " (Global) " << entranceLocal
351  << " (Local)";
352 #endif
353  }
354  if (!checkHit()) {
355  currentHit[0] = createNewHit(&fFakeStep, track, 0);
356  }
357  }
358  return true;
359  }
360  return false;
361 }
362 
363 double CaloSD::getEnergyDeposit(const G4Step* aStep) { return aStep->GetTotalEnergyDeposit(); }
364 
365 double CaloSD::EnergyCorrected(const G4Step& aStep, const G4Track*) { return aStep.GetTotalEnergyDeposit(); }
366 
367 bool CaloSD::getFromLibrary(const G4Step*) { return false; }
368 
369 bool CaloSD::isItFineCalo(const G4VTouchable* touch) {
370  bool ok(false);
371  int level = ((touch->GetHistoryDepth()) + 1);
372  for (const auto& detector : fineDetectors_) {
373  if (level > 0 && level >= detector.level) {
374  int ii = level - detector.level;
375  G4LogicalVolume* lv = touch->GetVolume(ii)->GetLogicalVolume();
376  ok = (lv == detector.lv);
377 #ifdef EDM_ML_DEBUG
378  std::string name1 = (lv == nullptr) ? "Unknown" : lv->GetName();
379  edm::LogVerbatim("CaloSim") << "CaloSD: volume " << name1 << ":" << detector.name << " at Level "
380  << detector.level << " Flag " << ok;
381 #endif
382  if (ok)
383  break;
384  }
385  }
386  return ok;
387 }
388 
389 void CaloSD::Initialize(G4HCofThisEvent* HCE) {
390 #ifdef EDM_ML_DEBUG
391  edm::LogVerbatim("CaloSim") << "CaloSD : Initialize called for " << detName_;
392 #endif
393 
394  for (int k = 0; k < nHC_; ++k) {
395  totalHits[k] = 0;
396 
397  //This initialization is performed at the beginning of an event
398  //------------------------------------------------------------
400 
401  if (hcID[k] < 0) {
402  hcID[k] = G4SDManager::GetSDMpointer()->GetCollectionID(collName_[k]);
403  }
404  //theHC ownership is transfered here to HCE
405  HCE->AddHitsCollection(hcID[k], theHC[k]);
406 #ifdef EDM_ML_DEBUG
407  edm::LogVerbatim("CaloSim") << "CaloSD : Add hits collection for " << hcID[k] << " for " << k << ":" << detName_
408  << ":" << collName_[k];
409 #endif
410  }
411 }
412 
413 void CaloSD::EndOfEvent(G4HCofThisEvent*) {
414  // clean the hits for the last tracks
415 
417 
418 #ifdef EDM_ML_DEBUG
419  for (int k = 0; k < nHC_; ++k) {
420  if (theHC[k] == nullptr)
421  edm::LogVerbatim("CaloSim") << "CaloSD: EndofEvent entered for container " << k << " with no entries";
422  else
423  edm::LogVerbatim("CaloSim") << "CaloSD: EndofEvent entered for container " << k << " with " << theHC[k]->entries()
424  << " entries";
425  }
426 #endif
427 }
428 
429 void CaloSD::clear() {}
430 
432 
434  for (int k = 0; k < nHC_; ++k) {
435 #ifdef EDM_ML_DEBUG
436  edm::LogVerbatim("CaloSim") << "CaloSD: Collection " << theHC[k]->GetName();
437 #endif
438  theHC[k]->PrintAllHits();
439  }
440 }
441 
443  for (int k = 0; k < nHC_; ++k) {
444 #ifdef EDM_ML_DEBUG
445  edm::LogVerbatim("CaloSim") << "CaloSD: Tries to transfer " << slave[k].get()->hits().size() << " hits for "
446  << slave[k].get()->name() << " " << hname;
447 #endif
448  if (slave[k].get()->name() == hname) {
449  cc = slave[k].get()->hits();
450  slave[k].get()->Clean();
451  }
452  }
453 }
454 
455 G4ThreeVector CaloSD::setToLocal(const G4ThreeVector& global, const G4VTouchable* touch) const {
456  return touch->GetHistory()->GetTopTransform().TransformPoint(global);
457 }
458 
459 G4ThreeVector CaloSD::setToGlobal(const G4ThreeVector& local, const G4VTouchable* touch) const {
460  return touch->GetHistory()->GetTopTransform().Inverse().TransformPoint(local);
461 }
462 
463 bool CaloSD::hitExists(const G4Step* aStep, int k) {
464 #ifdef EDM_ML_DEBUG
465  edm::LogVerbatim("CaloSim") << "CaloSD: hitExists for " << k;
466 #endif
467  // Update if in the same detector, time-slice and for same track
468  if (currentID[k] == previousID[k]) {
469  updateHit(currentHit[k], k);
470  return true;
471  }
472 
473  // Note T. Klijnsma:
474  // This is a rather strange place to set these class variables.
475  // The code would be much more readable if all logic for determining
476  // whether to update a hit or create a new hit is done in one place,
477  // and only then perform the actual updating or creating of the hit.
478 
479  // Reset entry point for new primary (only for the primary hit)
480  if (k == 0) {
481  posGlobal = aStep->GetPreStepPoint()->GetPosition();
482  if (currentID[k].trackID() != previousID[k].trackID()) {
483  resetForNewPrimary(aStep);
484  }
485  }
486  return checkHit(k);
487 }
488 
489 bool CaloSD::checkHit(int k) {
490 #ifdef EDM_ML_DEBUG
491  edm::LogVerbatim("CaloSim") << "CaloSD: checkHit for " << k << " for map " << useMap << ":" << &hitMap[k] << " Nhits "
492  << nCheckedHits[k] << " HC " << theHC[k] << " ID " << currentID[k];
493 #endif
494  //look in the HitContainer whether a hit with the same ID already exists:
495  bool found = false;
496  if (useMap) {
497  std::map<CaloHitID, CaloG4Hit*>::const_iterator it = hitMap[k].find(currentID[k]);
498  if (it != hitMap[k].end()) {
499  currentHit[k] = it->second;
500  found = true;
501  }
502  } else if (nCheckedHits[k] > 0) {
503  int nhits = theHC[k]->entries();
504  int minhit = std::max(nhits - nCheckedHits[k], 0);
505  int maxhit = nhits - 1;
506 
507  for (int j = maxhit; j > minhit; --j) {
508  if ((*theHC[k])[j]->getID() == currentID[k]) {
509  currentHit[k] = (*theHC[k])[j];
510  found = true;
511  break;
512  }
513  }
514  }
515 
516  if (found) {
517  updateHit(currentHit[k], k);
518  }
519  return found;
520 }
521 
522 int CaloSD::getNumberOfHits(int k) { return theHC[k]->entries(); }
523 
524 /*
525 Takes a vector of ints (representing trackIDs), and returns a formatted string
526 for debugging purposes
527 */
528 std::string CaloSD::printableDecayChain(const std::vector<unsigned int>& decayChain) {
529  std::stringstream ss;
530  for (long unsigned int i = 0; i < decayChain.size(); i++) {
531  if (i > 0)
532  ss << " <- ";
533  ss << decayChain[i];
534  }
535  return ss.str();
536 }
537 
538 /* Very short representation of a CaloHitID */
540  std::stringstream ss;
541  ss << GetName() << "/" << ID.unitID() << "/trk" << ID.trackID() << "/d" << ID.depth() << "/time" << ID.timeSliceID();
542  if (ID.isFinecaloTrackID())
543  ss << "/FC";
544  return ss.str();
545 }
546 
547 /* As above, but with a hit as input */
549 
550 /*
551 Finds the boundary-crossing parent of a track, and stores it in the CaloSD's map
552 */
553 unsigned int CaloSD::findBoundaryCrossingParent(const G4Track* track, bool markAsSaveable) {
555  unsigned int id = track->GetTrackID();
556  // First see if this track is already in the map
557  auto it = boundaryCrossingParentMap_.find(id);
558  if (it != boundaryCrossingParentMap_.end()) {
559 #ifdef EDM_ML_DEBUG
560  edm::LogVerbatim("DoFineCalo") << "Track " << id << " parent already cached: " << it->second;
561 #endif
562  return it->second;
563  }
564  // Then see if the track itself crosses the boundary
565  else if (trkInfo->crossedBoundary()) {
566 #ifdef EDM_ML_DEBUG
567  edm::LogVerbatim("DoFineCalo") << "Track " << id << " crosses boundary itself";
568 #endif
570  trkInfo->setStoreTrack();
571  return id;
572  }
573  // Else, traverse the history of the track
574  std::vector<unsigned int> decayChain{id};
575 #ifdef EDM_ML_DEBUG
576  edm::LogVerbatim("DoFineCalo") << "Track " << id << ": Traversing history to find boundary-crossing parent";
577 #endif
578  unsigned int parentID = track->GetParentID();
579  while (true) {
580  if (parentID == 0)
581  throw cms::Exception("Unknown", "CaloSD")
582  << "Hit end of parentage for track " << id << " without finding a boundary-crossing parent";
583  // First check if this ancestor is already in the map
584  auto it = boundaryCrossingParentMap_.find(parentID);
585  if (it != boundaryCrossingParentMap_.end()) {
586 #ifdef EDM_ML_DEBUG
587  edm::LogVerbatim("DoFineCalo") << " Track " << parentID
588  << " boundary-crossing parent already cached: " << it->second;
589 #endif
590  // Store this parent also for the rest of the traversed decay chain
591  for (auto ancestorID : decayChain)
592  boundaryCrossingParentMap_[ancestorID] = it->second;
593 #ifdef EDM_ML_DEBUG
594  // In debug mode, still build the rest of the decay chain for debugging
595  decayChain.push_back(parentID);
596  while (parentID != it->second) {
597  parentID = m_trackManager->getTrackByID(parentID, true)->parentID();
598  decayChain.push_back(parentID);
599  }
600  edm::LogVerbatim("DoFineCalo") << " Full decay chain: " << printableDecayChain(decayChain);
601 #endif
602  return it->second;
603  }
604  // If not, get this parent from the track manager (expensive)
606  if (parentTrack->crossedBoundary()) {
607  if (markAsSaveable)
608  parentTrack->setToBeSaved();
609  decayChain.push_back(parentID);
610  // Record this boundary crossing parent for all traversed ancestors
611  for (auto ancestorID : decayChain)
612  boundaryCrossingParentMap_[ancestorID] = parentID;
613 #ifdef EDM_ML_DEBUG
614  edm::LogVerbatim("DoFineCalo") << " Found boundary-crossing ancestor " << parentID << " for track " << id
615  << "; decay chain: " << printableDecayChain(decayChain);
616 #endif
617  return parentID;
618  }
619  // Next iteration
620  decayChain.push_back(parentID);
621  parentID = parentTrack->parentID();
622  }
623 }
624 
625 CaloG4Hit* CaloSD::createNewHit(const G4Step* aStep, const G4Track* theTrack, int k) {
626 #ifdef EDM_ML_DEBUG
627  edm::LogVerbatim("CaloSim") << "CaloSD::CreateNewHit " << getNumberOfHits() << " for " << GetName()
628  << " Unit:" << currentID[k].unitID() << " " << currentID[k].depth()
629  << " Edep= " << edepositEM << " " << edepositHAD
630  << " primaryID= " << currentID[k].trackID()
631  << " timeSlice= " << currentID[k].timeSliceID() << " ID= " << theTrack->GetTrackID()
632  << " " << theTrack->GetDefinition()->GetParticleName()
633  << " E(GeV)= " << theTrack->GetKineticEnergy() / CLHEP::GeV
634  << " parentID= " << theTrack->GetParentID() << "\n Ein= " << incidentEnergy
635  << " entranceGlobal: " << entrancePoint << " entranceLocal: " << entranceLocal
636  << " posGlobal: " << posGlobal;
637 #endif
638 
639  CaloG4Hit* aHit;
640  if (!reusehit[k].empty()) {
641  aHit = reusehit[k].back().release();
642  aHit->setEM(0.f);
643  aHit->setHadr(0.f);
644  reusehit[k].pop_back();
645  } else {
646  aHit = new CaloG4Hit;
647  }
648 
649  aHit->setID(currentID[k]);
650  aHit->setEntry(entrancePoint.x(), entrancePoint.y(), entrancePoint.z());
652  aHit->setPosition(posGlobal.x(), posGlobal.y(), posGlobal.z());
654  updateHit(aHit, k);
655 
656  storeHit(aHit, k);
657  TrackInformation* trkInfo = cmsTrackInformation(theTrack);
658 
659 #ifdef EDM_ML_DEBUG
661  edm::LogVerbatim("DoFineCalo") << "New hit " << shortreprID(aHit) << " using finecalo;"
662  << " isItFineCalo(post)=" << isItFineCalo(aStep->GetPostStepPoint()->GetTouchable())
663  << " isItFineCalo(pre)=" << isItFineCalo(aStep->GetPreStepPoint()->GetTouchable());
664 #endif
665 
666  // 'Traditional', non-fine history bookkeeping
667  if (!doFineCaloThisStep_) {
668  double etrack = 0;
669  if (currentID[k].trackID() == primIDSaved[k]) { // The track is saved; nothing to be done
670  } else if (currentID[k].trackID() == theTrack->GetTrackID()) {
671  etrack = theTrack->GetKineticEnergy();
672 #ifdef EDM_ML_DEBUG
673  edm::LogVerbatim("CaloSim") << "CaloSD: set save the track " << currentID[k].trackID() << " etrack " << etrack
674  << " eCut " << energyCut << " force: " << forceSave
675  << " save: " << (etrack >= energyCut || forceSave);
676 #endif
677  if (etrack >= energyCut || forceSave) {
678  trkInfo->setStoreTrack();
679  }
680  } else {
682 #ifdef EDM_ML_DEBUG
683  edm::LogVerbatim("CaloSim") << "CaloSD : TrackWithHistory pointer for " << currentID[k].trackID() << " is "
684  << trkh;
685 #endif
686  if (trkh != nullptr) {
687  etrack = sqrt(trkh->momentum().Mag2());
688  if (etrack >= energyCut) {
689  trkh->setToBeSaved();
690 #ifdef EDM_ML_DEBUG
691  edm::LogVerbatim("CaloSim") << "CaloSD: set save the track " << currentID[k].trackID() << " with Hit";
692 #endif
693  }
694  }
695  }
697  }
698 
699  if (useMap)
700  ++totalHits[k];
701  return aHit;
702 }
703 
704 void CaloSD::updateHit(CaloG4Hit* aHit, int k) {
706 #ifdef EDM_ML_DEBUG
707  edm::LogVerbatim("CaloSim") << "CaloSD:" << GetName() << " Add energy deposit in " << currentID[k]
708  << " Edep_em(MeV)= " << edepositEM << " Edep_had(MeV)= " << edepositHAD;
709 #endif
710 
711  // buffer for next steps:
712  previousID[k] = currentID[k];
713 }
714 
715 void CaloSD::resetForNewPrimary(const G4Step* aStep) {
716  auto const preStepPoint = aStep->GetPreStepPoint();
717  entrancePoint = preStepPoint->GetPosition();
718  entranceLocal = setToLocal(entrancePoint, preStepPoint->GetTouchable());
719  incidentEnergy = preStepPoint->GetKineticEnergy();
720 #ifdef EDM_ML_DEBUG
721  edm::LogVerbatim("CaloSim") << "CaloSD::resetForNewPrimary for " << GetName()
722  << " ID= " << aStep->GetTrack()->GetTrackID() << " Ein= " << incidentEnergy / CLHEP::GeV
723  << " GeV and"
724  << " entrance point global: " << entrancePoint << " local: " << entranceLocal;
725 #endif
726 }
727 
728 double CaloSD::getAttenuation(const G4Step* aStep, double birk1, double birk2, double birk3) const {
729  double weight = 1.;
730  double charge = aStep->GetPreStepPoint()->GetCharge();
731  double length = aStep->GetStepLength();
732 
733  if (charge != 0. && length > 0.) {
734  double density = aStep->GetPreStepPoint()->GetMaterial()->GetDensity();
735  double dedx = aStep->GetTotalEnergyDeposit() / length;
736  double rkb = birk1 / density;
737  double c = birk2 * rkb * rkb;
738  if (std::abs(charge) >= 2.)
739  rkb /= birk3; // based on alpha particle data
740  weight = 1. / (1. + rkb * dedx + c * dedx * dedx);
741 #ifdef EDM_ML_DEBUG
742  edm::LogVerbatim("CaloSim") << "CaloSD::getAttenuation in " << aStep->GetPreStepPoint()->GetMaterial()->GetName()
743  << " Charge " << charge << " dE/dx " << dedx << " Birk Const " << rkb << ", " << c
744  << " Weight = " << weight << " dE " << aStep->GetTotalEnergyDeposit();
745 #endif
746  }
747  return weight;
748 }
749 
750 void CaloSD::update(const BeginOfRun*) { initRun(); }
751 
752 void CaloSD::update(const BeginOfEvent* g4Event) {
753 #ifdef EDM_ML_DEBUG
754  edm::LogVerbatim("CaloSim") << "CaloSD: Dispatched BeginOfEvent for " << GetName() << " !";
755 #endif
756  clearHits();
757  initEvent(g4Event);
758 }
759 
760 void CaloSD::update(const EndOfTrack* trk) {
761  int id = (*trk)()->GetTrackID();
762  TrackInformation* trkI = cmsTrackInformation((*trk)());
763  int lastTrackID = -1;
764  if (trkI)
765  lastTrackID = trkI->getIDonCaloSurface();
766  if (id == lastTrackID) {
767  auto trksForThisEvent = m_trackManager->trackContainer();
768  if (!trksForThisEvent->empty()) {
769  TrackWithHistory* trkH = trksForThisEvent->back();
770  if (trkH->trackID() == id) {
771  tkMap[id] = trkH;
772 #ifdef EDM_ML_DEBUG
773  edm::LogVerbatim("CaloSim") << "CaloSD: get track " << id << " from Container of size "
774  << trksForThisEvent->size() << " with ID " << trkH->trackID();
775 #endif
776  }
777  }
778  }
779 }
780 
781 void CaloSD::update(const ::EndOfEvent*) {
782  endEvent();
783  for (int k = 0; k < nHC_; ++k) {
784  slave[k].get()->ReserveMemory(theHC[k]->entries());
785 
786  int count(0);
787  double eEM(0.0);
788  double eHAD(0.0);
789  double eEM2(0.0);
790  double eHAD2(0.0);
791 #ifdef EDM_ML_DEBUG
792  int wrong(0);
793  double tt(0.0);
794  double zloc(0.0);
795  double zglob(0.0);
796  double ee(0.0);
797 #endif
798  int hc_entries = theHC[k]->entries();
799  for (int i = 0; i < hc_entries; ++i) {
800 #ifdef EDM_ML_DEBUG
801  if (!saveHit((*theHC[k])[i], k)) {
802  ++wrong;
803  }
804 #else
805  saveHit((*theHC[k])[i], k);
806 #endif
807 
808  ++count;
809  double x = (*theHC[k])[i]->getEM();
810  eEM += x;
811  eEM2 += x * x;
812  x = (*theHC[k])[i]->getHadr();
813  eHAD += x;
814  eHAD2 += x * x;
815 #ifdef EDM_ML_DEBUG
816  tt += (*theHC[k])[i]->getTimeSlice();
817  ee += (*theHC[k])[i]->getIncidentEnergy();
818  zglob += std::abs((*theHC[k])[i]->getEntry().z());
819  zloc += std::abs((*theHC[k])[i]->getEntryLocal().z());
820 #endif
821  }
822 
823  double norm = (count > 0) ? 1.0 / count : 0.0;
824  eEM *= norm;
825  eEM2 *= norm;
826  eHAD *= norm;
827  eHAD2 *= norm;
828  eEM2 = std::sqrt(eEM2 - eEM * eEM);
829  eHAD2 = std::sqrt(eHAD2 - eHAD * eHAD);
830 #ifdef EDM_ML_DEBUG
831  tt *= norm;
832  ee *= norm;
833  zglob *= norm;
834  zloc *= norm;
835  edm::LogVerbatim("CaloSim") << "CaloSD: " << GetName() << " store " << count << " hits; " << wrong
836  << " track IDs not given properly and " << totalHits - count
837  << " hits not passing cuts\n EmeanEM= " << eEM << " ErmsEM= " << eEM2
838  << "\n EmeanHAD= " << eHAD << " ErmsHAD= " << eHAD2 << " TimeMean= " << tt
839  << " E0mean= " << ee << " Zglob= " << zglob << " Zloc= " << zloc << " ";
840 #endif
841  std::vector<std::unique_ptr<CaloG4Hit>>().swap(reusehit[k]);
842  if (useMap)
843  hitMap[k].erase(hitMap[k].begin(), hitMap[k].end());
844  }
845  tkMap.erase(tkMap.begin(), tkMap.end());
847 }
848 
850  for (int k = 0; k < nHC_; ++k) {
851  previousID[k].reset();
852  primIDSaved[k] = -99;
853  cleanIndex[k] = 0;
854 #ifdef EDM_ML_DEBUG
855  edm::LogVerbatim("CaloSim") << "CaloSD: Clears hit vector for " << GetName()
856  << " and initialise slave: " << slave[k].get()->name();
857 #endif
858  slave[k].get()->Initialize();
859  }
860 }
861 
863  if (fpCaloG4HitAllocator) {
864  fpCaloG4HitAllocator->ResetStorage();
865  }
866 }
867 
869 
871 
873 
874 int CaloSD::getTrackID(const G4Track* aTrack) {
875  int primaryID = 0;
876  TrackInformation* trkInfo = cmsTrackInformation(aTrack);
877  if (trkInfo) {
878  primaryID = trkInfo->getIDonCaloSurface();
879 #ifdef EDM_ML_DEBUG
880  edm::LogVerbatim("CaloSim") << "Track ID: " << trkInfo->getIDonCaloSurface() << ":" << aTrack->GetTrackID() << ":"
881  << primaryID;
882 #endif
883  } else {
884  primaryID = aTrack->GetTrackID();
885 #ifdef EDM_ML_DEBUG
886  edm::LogWarning("CaloSim") << "CaloSD: Problem with primaryID **** set by force to TkID **** " << primaryID;
887 #endif
888  }
889  return primaryID;
890 }
891 
892 int CaloSD::setTrackID(const G4Step* aStep) {
893  auto const theTrack = aStep->GetTrack();
894  TrackInformation* trkInfo = cmsTrackInformation(theTrack);
895  int primaryID = trkInfo->getIDonCaloSurface();
896  if (primaryID <= 0) {
897  primaryID = theTrack->GetTrackID();
898  }
899 #ifdef EDM_ML_DEBUG
900  edm::LogVerbatim("CaloSim") << "Track ID: " << trkInfo->getIDonCaloSurface() << ":" << theTrack->GetTrackID() << ":"
901  << primaryID;
902 #endif
903 
904  if (primaryID != previousID[0].trackID()) {
905  resetForNewPrimary(aStep);
906  }
907 #ifdef EDM_ML_DEBUG
908  edm::LogVerbatim("CaloSim") << "CaloSD::setTrackID for " << GetName()
909  << " trackID= " << aStep->GetTrack()->GetTrackID() << " primaryID= " << primaryID;
910 #endif
911  return primaryID;
912 }
913 
914 uint16_t CaloSD::getDepth(const G4Step*) { return 0; }
915 
916 void CaloSD::processSecondHit(const G4Step*, const G4Track*) {}
917 
919  double emin(eminHit);
920  if (hit->getDepth() > 0)
921  emin = eminHitD;
922 #ifdef EDM_ML_DEBUG
923  edm::LogVerbatim("CaloSim") << "CaloSD::filterHit(..) Depth " << hit->getDepth() << " Emin = " << emin << " ("
924  << eminHit << ", " << eminHitD << ")";
925 #endif
926  return ((time <= tmaxHit) && (hit->getEnergyDeposit() > emin));
927 }
928 
929 double CaloSD::getResponseWt(const G4Track* aTrack, int k) {
930  double wt = 1.0;
931  if (meanResponse[k].get()) {
932  TrackInformation* trkInfo = cmsTrackInformation(aTrack);
933  wt = meanResponse[k].get()->getWeight(trkInfo->genParticlePID(), trkInfo->genParticleP());
934  }
935  return wt;
936 }
937 
939  if (hit == nullptr || previousID[k].trackID() < 0) {
940  edm::LogWarning("CaloSim") << "CaloSD: hit to be stored is nullptr !!"
941  << " previousID.trackID()= " << previousID[k].trackID();
942  return;
943  }
944 
945  theHC[k]->insert(hit);
946  if (useMap)
947  hitMap[k].insert(std::pair<CaloHitID, CaloG4Hit*>(previousID[k], hit));
948 }
949 
950 bool CaloSD::saveHit(CaloG4Hit* aHit, int k) {
951  int tkID;
952  bool ok = true;
953 
954  double time = aHit->getTimeSlice();
955  if (corrTOFBeam)
956  time += correctT;
957 
958  // More strict bookkeeping for finecalo
959  if (doFineCalo_ && aHit->isFinecaloTrackID()) {
960 #ifdef EDM_ML_DEBUG
961  edm::LogVerbatim("DoFineCalo") << "Saving hit " << shortreprID(aHit);
962 #endif
963  if (!m_trackManager)
964  throw cms::Exception("Unknown", "CaloSD") << "m_trackManager not set, needed for finecalo!";
965  if (!m_trackManager->trackExists(aHit->getTrackID()))
966  throw cms::Exception("Unknown", "CaloSD")
967  << "Error on hit " << shortreprID(aHit) << ": Parent track not in track manager";
968  slave[k].get()->processHits(aHit->getUnitID(),
969  aHit->getEM() / CLHEP::GeV,
970  aHit->getHadr() / CLHEP::GeV,
971  time,
972  aHit->getTrackID(),
973  aHit->getDepth());
974  }
975  // Regular, not-fine way:
976  else {
977  if (m_trackManager) {
978  tkID = m_trackManager->giveMotherNeeded(aHit->getTrackID());
979  if (tkID == 0) {
980  if (m_trackManager->trackExists(aHit->getTrackID()))
981  tkID = (aHit->getTrackID());
982  else {
983  ok = false;
984  }
985  }
986  } else {
987  tkID = aHit->getTrackID();
988  ok = false;
989  }
990 #ifdef EDM_ML_DEBUG
991  edm::LogVerbatim("DoFineCalo") << "Saving hit " << shortreprID(aHit) << " with trackID=" << tkID;
992 #endif
993 
994  slave[k].get()->processHits(
995  aHit->getUnitID(), aHit->getEM() / CLHEP::GeV, aHit->getHadr() / CLHEP::GeV, time, tkID, aHit->getDepth());
996  }
997 
998 #ifdef EDM_ML_DEBUG
999  if (!ok)
1000  edm::LogWarning("CaloSim") << "CaloSD:Cannot find track ID for " << aHit->getTrackID();
1001  edm::LogVerbatim("CaloSim") << "CalosD: Track ID " << aHit->getTrackID() << " changed to " << tkID
1002  << " by SimTrackManager Status " << ok;
1003 #endif
1004 
1005 #ifdef EDM_ML_DEBUG
1006  edm::LogVerbatim("CaloSim") << "CaloSD: Store Hit at " << std::hex << aHit->getUnitID() << std::dec << " "
1007  << aHit->getDepth() << " due to " << tkID << " in time " << time << " of energy "
1008  << aHit->getEM() / CLHEP::GeV << " GeV (EM) and " << aHit->getHadr() / CLHEP::GeV
1009  << " GeV (Hadr)";
1010 #endif
1011  return ok;
1012 }
1013 
1014 void CaloSD::update(const BeginOfTrack* trk) {
1015  int primary = -1;
1016  TrackInformation* trkInfo = cmsTrackInformation((*trk)());
1017  if (trkInfo->isPrimary())
1018  primary = (*trk)()->GetTrackID();
1019 
1020 #ifdef EDM_ML_DEBUG
1021  edm::LogVerbatim("CaloSim") << "New track: isPrimary " << trkInfo->isPrimary() << " primary ID = " << primary
1022  << " primary ancestor ID " << primAncestor;
1023 #endif
1024 
1025  // update the information if a different primary track ID
1026 
1027  if (primary > 0 && primary != primAncestor) {
1028  primAncestor = primary;
1029 
1030  // clean the hits information
1031 
1032  bool clean(false);
1033  for (int k = 0; k < nHC_; ++k)
1034  if (theHC[k]->entries() > 0)
1035  clean = true;
1036  if (clean)
1038  }
1039 }
1040 
1042  for (int k = 0; k < nHC_; ++k) {
1043  std::vector<CaloG4Hit*>* theCollection = theHC[k]->GetVector();
1044 
1045 #ifdef EDM_ML_DEBUG
1046  edm::LogVerbatim("CaloSim") << "CaloSD: collection before merging, size = " << theHC[k]->entries();
1047 #endif
1048  if (reusehit[k].empty())
1049  reusehit[k].reserve(theHC[k]->entries() - cleanIndex[k]);
1050 
1051  // if no map used, merge before hits to have the save situation as a map
1052  if (!useMap) {
1053  std::vector<CaloG4Hit*> hitvec;
1054 
1055  hitvec.swap(*theCollection);
1056  sort((hitvec.begin() + cleanIndex[k]), hitvec.end(), CaloG4HitLess());
1057 #ifdef EDM_ML_DEBUG
1058  edm::LogVerbatim("CaloSim") << "CaloSD::cleanHitCollection: sort hits in buffer starting from "
1059  << "element = " << cleanIndex[k];
1060  for (unsigned int i = 0; i < hitvec.size(); ++i) {
1061  if (hitvec[i] == nullptr)
1062  edm::LogVerbatim("CaloSim") << i << " has a null pointer";
1063  else
1064  edm::LogVerbatim("CaloSim") << i << " " << *hitvec[i];
1065  }
1066 #endif
1068  for (unsigned int i = cleanIndex[k]; i < hitvec.size(); ++i) {
1069  int jump = 0;
1070  for (unsigned int j = i + 1; j < hitvec.size() && equal(hitvec[i], hitvec[j]); ++j) {
1071  ++jump;
1072  // merge j to i
1073  (*hitvec[i]).addEnergyDeposit(*hitvec[j]);
1074  (*hitvec[j]).setEM(0.);
1075  (*hitvec[j]).setHadr(0.);
1076  reusehit[k].emplace_back(hitvec[j]);
1077  hitvec[j] = nullptr;
1078  }
1079  i += jump;
1080  }
1081 #ifdef EDM_ML_DEBUG
1082  edm::LogVerbatim("CaloSim") << "CaloSD: cleanHitCollection merge the hits in buffer ";
1083  for (unsigned int i = 0; i < hitvec.size(); ++i) {
1084  if (hitvec[i] == nullptr)
1085  edm::LogVerbatim("CaloSim") << i << " has a null pointer";
1086  else
1087  edm::LogVerbatim("CaloSim") << i << " " << *hitvec[i];
1088  }
1089 #endif
1090  //move all nullptr to end of list and then remove them
1091  hitvec.erase(std::stable_partition(
1092  hitvec.begin() + cleanIndex[k], hitvec.end(), [](CaloG4Hit* p) { return p != nullptr; }),
1093  hitvec.end());
1094 #ifdef EDM_ML_DEBUG
1095  edm::LogVerbatim("CaloSim") << "CaloSD::cleanHitCollection: remove the merged hits in buffer, new size = "
1096  << hitvec.size();
1097 #endif
1098  hitvec.swap(*theCollection);
1099  totalHits[k] = theHC[k]->entries();
1100  }
1101 
1102 #ifdef EDM_ML_DEBUG
1103  edm::LogVerbatim("CaloSim") << "CaloSD: collection after merging, size= " << theHC[k]->entries()
1104  << " Size of reusehit= " << reusehit[k].size()
1105  << "\n starting hit selection from index = " << cleanIndex[k];
1106 #endif
1107 
1108  int addhit = 0;
1109  for (unsigned int i = cleanIndex[k]; i < theCollection->size(); ++i) {
1110  CaloG4Hit* aHit((*theCollection)[i]);
1111 
1112  // selection
1113 
1114  double time = aHit->getTimeSlice();
1115  if (corrTOFBeam)
1116  time += correctT;
1117  if (!filterHit(aHit, time)) {
1118 #ifdef EDM_ML_DEBUG
1119  edm::LogVerbatim("CaloSim") << "CaloSD: dropped CaloG4Hit "
1120  << " " << *aHit;
1121 #endif
1122 
1123  // create the list of hits to be reused
1124 
1125  reusehit[k].emplace_back((*theCollection)[i]);
1126  (*theCollection)[i] = nullptr;
1127  ++addhit;
1128  }
1129  }
1130 
1131 #ifdef EDM_ML_DEBUG
1132  edm::LogVerbatim("CaloSim") << "CaloSD: Size of reusehit after selection = " << reusehit[k].size()
1133  << " Number of added hit = " << addhit;
1134 #endif
1135  if (useMap) {
1136  if (addhit > 0) {
1137  int offset = reusehit[k].size() - addhit;
1138  for (int ii = addhit - 1; ii >= 0; --ii) {
1139  CaloHitID theID = reusehit[k][offset + ii]->getID();
1140  hitMap[k].erase(theID);
1141  }
1142  }
1143  }
1144 
1145  //move all nullptr to end of list and then remove them
1146  theCollection->erase(
1147  std::stable_partition(
1148  theCollection->begin() + cleanIndex[k], theCollection->end(), [](CaloG4Hit* p) { return p != nullptr; }),
1149  theCollection->end());
1150 #ifdef EDM_ML_DEBUG
1151  edm::LogVerbatim("CaloSim") << "CaloSD: hit collection after selection, size = " << theHC[k]->entries();
1152  theHC[k]->PrintAllHits();
1153 #endif
1154 
1155  cleanIndex[k] = theHC[k]->entries();
1156  }
1157 }
1158 
1159 void CaloSD::printDetectorLevels(const G4VTouchable* touch) const {
1160  //Print name and copy numbers
1161  int level = ((touch->GetHistoryDepth()) + 1);
1162  std::ostringstream st1;
1163  st1 << level << " Levels:";
1164  if (level > 0) {
1165  for (int ii = 0; ii < level; ii++) {
1166  int i = level - ii - 1;
1167  G4VPhysicalVolume* pv = touch->GetVolume(i);
1168  std::string name = (pv != nullptr) ? pv->GetName() : "Unknown";
1169  st1 << " " << name << ":" << touch->GetReplicaNumber(i);
1170  }
1171  }
1172  edm::LogVerbatim("CaloSim") << st1.str();
1173 }
CaloG4Hit * currentHit[2]
Definition: CaloSD.h:152
float edepositEM
Definition: CaloSD.h:144
virtual void processSecondHit(const G4Step *, const G4Track *)
Definition: CaloSD.cc:916
int getNumberOfHits(int k=0)
Definition: CaloSD.cc:522
double genParticleP() const
Int_t getEntry(TBranch *branch, EntryNumber entryNumber)
Definition: RootTree.cc:527
double energyCut
Definition: CaloSD.h:148
Log< level::Info, true > LogVerbatim
int getTrackID() const
Definition: CaloG4Hit.h:64
bool isPrimary() const
bool ignoreReject
Definition: CaloSD.h:178
void setStoreTrack()
can only be set to true, cannot be reset to false!
bool crossedBoundary() const
T getParameter(std::string const &) const
Definition: ParameterSet.h:307
virtual bool getFromLibrary(const G4Step *step)
Definition: CaloSD.cc:367
std::vector< PCaloHit > PCaloHitContainer
double kmaxNeutron
Definition: CaloSD.h:155
bool doFineCaloThisStep_
Definition: CaloSD.h:200
G4ThreadLocal G4Allocator< CaloG4Hit > * fpCaloG4HitAllocator
Definition: CaloG4Hit.cc:11
std::map< CaloHitID, CaloG4Hit * > hitMap[2]
Definition: CaloSD.h:195
virtual uint16_t getDepth(const G4Step *)
Definition: CaloSD.cc:914
virtual double getEnergyDeposit(const G4Step *step)
Definition: CaloSD.cc:363
virtual double EnergyCorrected(const G4Step &step, const G4Track *)
Definition: CaloSD.cc:365
int parentID() const
unsigned int findBoundaryCrossingParent(const G4Track *track, bool markParentAsSaveable=true)
Definition: CaloSD.cc:553
double eMinFine_
Definition: CaloSD.h:193
bool corrTOFBeam
Definition: CaloSD.h:180
double getEM() const
Definition: CaloG4Hit.h:55
TrackWithHistory * getTrackByID(int trackID, bool strict=false) const
void setIncidentEnergy(double e)
Definition: CaloG4Hit.h:62
const math::XYZVectorD & momentum() const
uint32_t cc[maxCellsPerHit]
Definition: gpuFishbone.h:49
void setEntryLocal(double x, double y, double z)
Definition: CaloG4Hit.h:50
void DrawAll() override
Definition: CaloSD.cc:431
uint32_t ID
Definition: Definitions.h:24
void clear() override
Definition: CaloSD.cc:429
uint32_t setDetUnitId(const G4Step *step) override=0
bool useMap
Definition: CaloSD.h:179
void newCollection(const std::string &name, edm::ParameterSet const &p)
Definition: CaloSD.cc:177
double eminHitD
Definition: CaloSD.h:190
uint16_t getDepth() const
Definition: CaloG4Hit.h:69
G4ThreeVector setToLocal(const G4ThreeVector &, const G4VTouchable *) const
Definition: CaloSD.cc:455
Definition: weight.py:1
int nCheckedHits[2]
Definition: CaloSD.h:187
G4ThreeVector posGlobal
Definition: CaloSD.h:142
virtual int getTrackID(const G4Track *)
Definition: CaloSD.cc:874
CaloG4HitCollection * theHC[2]
Definition: CaloSD.h:174
void Initialize(G4HCofThisEvent *HCE) override
Definition: CaloSD.cc:389
int primAncestor
Definition: CaloSD.h:183
int cleanIndex[2]
Definition: CaloSD.h:184
std::vector< int > useResMap_
Definition: CaloSD.h:150
void reset() override
Definition: CaloSD.cc:862
double kmaxProton
Definition: CaloSD.h:155
void fillHits(edm::PCaloHitContainer &, const std::string &) override
Definition: CaloSD.cc:442
std::vector< Detector > fineDetectors_
Definition: CaloSD.h:199
double eminHit
Definition: CaloSD.h:148
void swap(Association< C > &lhs, Association< C > &rhs)
Definition: Association.h:112
bool saveHit(CaloG4Hit *, int k=0)
Definition: CaloSD.cc:950
double getHadr() const
Definition: CaloG4Hit.h:58
bool checkHit(int k=0)
Definition: CaloSD.cc:489
bool equal(const T &first, const T &second)
Definition: Equal.h:32
virtual void initEvent(const BeginOfEvent *)
Definition: CaloSD.cc:870
std::unordered_map< unsigned int, unsigned int > boundaryCrossingParentMap_
Definition: CaloSD.h:197
void cleanHitCollection()
Definition: CaloSD.cc:1041
void reset()
Definition: CaloHitID.cc:49
static void clean(char *s)
T getUntrackedParameter(std::string const &, T const &) const
int primIDSaved[2]
Definition: CaloSD.h:186
bool forceSave
Definition: CaloSD.h:157
int nHC_
Definition: CaloSD.h:158
int timeSliceID() const
Definition: CaloHitID.h:21
bool isItFineCalo(const G4VTouchable *touch)
Definition: CaloSD.cc:369
void addEnergyDeposit(double em, double hd)
Definition: CaloG4Hit.cc:45
float timeSlice
Definition: CaloSD.h:189
Definition: TTTypes.h:54
double getResponseWt(const G4Track *, int k=0)
Definition: CaloSD.cc:929
bool isFinecaloTrackID() const
Definition: CaloG4Hit.h:70
void updateHit(CaloG4Hit *, int k)
Definition: CaloSD.cc:704
CaloG4Hit * createNewHit(const G4Step *, const G4Track *, int k)
Definition: CaloSD.cc:625
static std::string printableDecayChain(const std::vector< unsigned int > &decayChain)
Definition: CaloSD.cc:528
double kmaxIon
Definition: CaloSD.h:155
bool suppressHeavy
Definition: CaloSD.h:154
float edepositHAD
Definition: CaloSD.h:144
T sqrt(T t)
Definition: SSEVec.h:23
void resetForNewPrimary(const G4Step *)
Definition: CaloSD.cc:715
void setEM(double e)
Definition: CaloG4Hit.h:56
bool doFineCalo_
Definition: CaloSD.h:192
void setID(uint32_t i, double d, int j, uint16_t k=0)
Definition: CaloG4Hit.h:73
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
G4bool ProcessHits(G4Step *step, G4TouchableHistory *) override
Definition: CaloSD.cc:195
std::vector< std::string > hcn_
Definition: CaloSD.h:149
double f[11][100]
~CaloSD() override
Definition: CaloSD.cc:175
std::vector< std::unique_ptr< CaloG4Hit > > reusehit[2]
Definition: CaloSD.h:198
uint32_t unitID() const
Definition: CaloHitID.h:20
G4ThreeVector setToGlobal(const G4ThreeVector &, const G4VTouchable *) const
Definition: CaloSD.cc:459
int totalHits[2]
Definition: CaloSD.h:185
TrackInformation * cmsTrackInformation(const G4Track *aTrack)
virtual bool filterHit(CaloG4Hit *, double)
Definition: CaloSD.cc:918
int getIDonCaloSurface() const
ii
Definition: cuy.py:589
CaloHitID previousID[2]
Definition: CaloSD.h:146
double tmaxHit
Definition: CaloSD.h:148
void setID(uint32_t unitID, double timeSlice, int trackID, uint16_t depth=0)
Definition: CaloHitID.cc:41
int genParticlePID() const
CaloSD(const std::string &aSDname, const SensitiveDetectorCatalog &clg, edm::ParameterSet const &p, const SimTrackManager *, float timeSlice=1., bool ignoreTkID=false, const std::string &newcolname="")
Definition: CaloSD.cc:34
virtual void initRun()
Definition: CaloSD.cc:868
double correctT
Definition: CaloSD.h:191
double getAttenuation(const G4Step *aStep, double birk1, double birk2, double birk3) const
Definition: CaloSD.cc:728
void EndOfEvent(G4HCofThisEvent *eventHC) override
Definition: CaloSD.cc:413
CSCCFEBTimeSlice const *const timeSlice(T const &data, int nCFEB, int nSample)
void storeHit(CaloG4Hit *, int k=0)
Definition: CaloSD.cc:938
uint32_t getUnitID() const
Definition: CaloG4Hit.h:66
const std::vector< TrackWithHistory * > * trackContainer() const
bool hitExists(const G4Step *, int k)
Definition: CaloSD.cc:463
virtual void endEvent()
Definition: CaloSD.cc:872
bool trackExists(int i) const
void printDetectorLevels(const G4VTouchable *) const
Definition: CaloSD.cc:1159
void setHadr(double e)
Definition: CaloG4Hit.h:59
float incidentEnergy
Definition: CaloSD.h:143
virtual int setTrackID(const G4Step *)
Definition: CaloSD.cc:892
void markAsFinecaloTrackID(bool flag=true)
Definition: CaloHitID.h:29
void setPosition(double x, double y, double z)
Definition: CaloG4Hit.h:53
void setEntry(double x, double y, double z)
Definition: CaloG4Hit.h:47
G4THitsCollection< CaloG4Hit > CaloG4HitCollection
int trackID() const
static bool isGammaElectronPositron(int pdgCode)
bool isParameterized
Definition: CaloSD.h:177
double getTimeSlice() const
Definition: CaloG4Hit.h:67
std::string detName_
Definition: CaloSD.h:159
CaloHitID currentID[2]
Definition: CaloSD.h:146
std::string collName_[2]
Definition: CaloSD.h:159
std::map< int, TrackWithHistory * > tkMap
Definition: CaloSD.h:196
int giveMotherNeeded(int i) const
std::unique_ptr< CaloMeanResponse > meanResponse[2]
Definition: CaloSD.h:172
const SimTrackManager * m_trackManager
Definition: CaloSD.h:169
std::string shortreprID(const CaloHitID &ID)
Definition: CaloSD.cc:539
Log< level::Warning, false > LogWarning
void clearHits() override
Definition: CaloSD.cc:849
std::string nameMatterLV(const std::string &name, bool dd4hep)
int hcID[2]
Definition: CaloSD.h:182
int trackID() const
Definition: CaloHitID.h:23
std::unique_ptr< CaloSlaveSD > slave[2]
Definition: CaloSD.h:171
void PrintAll() override
Definition: CaloSD.cc:433
void NaNTrap(const G4Step *step) const
G4ThreeVector entrancePoint
Definition: CaloSD.h:140
G4ThreeVector entranceLocal
Definition: CaloSD.h:141
void update(const BeginOfRun *) override
This routine will be called when the appropriate signal arrives.
Definition: CaloSD.cc:750
bool ignoreTrackID
Definition: CaloSD.h:176
uint16_t depth() const
Definition: CaloHitID.h:24