DD4hep  1.34.0
Detector Description Toolkit for High Energy Physics
Geant4ParticleHandler.cpp
Go to the documentation of this file.
1 //==========================================================================
2 // AIDA Detector description implementation
3 //--------------------------------------------------------------------------
4 // Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
5 // All rights reserved.
6 //
7 // For the licensing terms see $DD4hepINSTALL/LICENSE.
8 // For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
9 //
10 // Author : M.Frank
11 //
12 //==========================================================================
13 
14 // Framework include files
15 #include <DD4hep/Primitives.h>
16 #include <DD4hep/InstanceCount.h>
17 #include <DDG4/Geant4StepHandler.h>
19 #include <DDG4/Geant4EventAction.h>
26 
27 // Geant4 include files
28 #include <G4Step.hh>
29 #include <G4Track.hh>
30 #include <G4Event.hh>
31 #include <G4TrackStatus.hh>
32 #include <G4PrimaryVertex.hh>
33 #include <G4PrimaryParticle.hh>
34 #include <G4TrackingManager.hh>
35 #include <G4ParticleDefinition.hh>
36 #include <CLHEP/Units/SystemOfUnits.h>
37 
38 // C/C++ include files
39 #include <set>
40 #include <algorithm>
41 
42 using namespace dd4hep::sim;
43 using PropertyMask = dd4hep::detail::ReferenceBitMask<int>;
44 
48 {
49  InstanceCount::increment(this);
50  //generatorAction().adopt(this);
51  eventAction().callAtBegin(this, &Geant4ParticleHandler::beginEvent);
52  eventAction().callAtEnd(this, &Geant4ParticleHandler::endEvent);
53  trackingAction().callAtFinal(this, &Geant4ParticleHandler::end,CallbackSequence::FRONT);
54  trackingAction().callUpFront(this, &Geant4ParticleHandler::begin,CallbackSequence::FRONT);
55  steppingAction().call(this, &Geant4ParticleHandler::step);
56  m_globalParticleID = 0;
57  declareProperty("PrintEndTracking", m_printEndTracking = false);
58  declareProperty("PrintStartTracking", m_printStartTracking = false);
59  declareProperty("KeepAllParticles", m_keepAll = false);
60  declareProperty("SaveProcesses", m_processNames);
61  declareProperty("MinimalKineticEnergy", m_kinEnergyCut = 100e0*CLHEP::MeV);
62  declareProperty("MinDistToParentVertex", m_minDistToParentVertex = 2.2e-14*CLHEP::mm);//default tolerance for g4ThreeVector isNear
63  m_needsControl = true;
64 }
65 
67 Geant4ParticleHandler::Geant4ParticleHandler()
69 {
70  m_globalParticleID = 0;
71  declareProperty("PrintEndTracking", m_printEndTracking = false);
72  declareProperty("PrintStartTracking", m_printStartTracking = false);
73  declareProperty("KeepAllParticles", m_keepAll = false);
74  declareProperty("SaveProcesses", m_processNames);
75  declareProperty("MinimalKineticEnergy", m_kinEnergyCut = 100e0*CLHEP::MeV);
76  declareProperty("MinDistToParentVertex", m_minDistToParentVertex = 2.2e-14*CLHEP::mm);//default tolerance for g4ThreeVector isNear
77  m_needsControl = true;
78 }
79 
81 Geant4ParticleHandler::~Geant4ParticleHandler() {
82  clear();
83  for( auto* h : this->m_userHandlers )
84  detail::releasePtr(h);
85  this->m_userHandlers.clear();
87 }
88 
91  return *this;
92 }
93 
96  if ( action ) {
97  if ( Geant4UserParticleHandler* h = dynamic_cast<Geant4UserParticleHandler*>(action) ) {
98  this->m_userHandlers.push_back(h);
99  h->addRef();
100  return true;
101  }
102  except("Cannot add an user particle handler object [Object-exists].");
103  }
104  except("Cannot add an invalid user particle handler object [NULL-object].");
105  return false;
106 }
107 
110  detail::releaseObjects(m_particleMap);
111  m_particleMap.clear();
112  // m_suspendedPM should already be empty and cleared...
113  assert(m_suspendedPM.empty() && "There was something wrong with the particle record treatment, please open a bug report!");
114  m_equivalentTracks.clear();
115 }
116 
118 void Geant4ParticleHandler::mark(const G4Track* track, int reason) {
119  if ( track ) {
120  if ( reason != 0 ) {
121  PropertyMask(m_currTrack.reason).set(reason);
122  return;
123  }
124  }
125  except("Cannot mark the G4Track if the pointer is invalid!");
126 }
127 
129 void Geant4ParticleHandler::mark(const G4Step* step_value, int reason) {
130  if ( step_value ) {
131  mark(step_value->GetTrack(),reason);
132  return;
133  }
134  except("Cannot mark the G4Track if the step-pointer is invalid!");
135 }
136 
138 void Geant4ParticleHandler::mark(const G4Step* step_value) {
139  if ( step_value ) {
140  this->mark(step_value->GetTrack());
141  return;
142  }
143  except("Cannot mark the G4Track if the step-pointer is invalid!");
144 }
145 
147 void Geant4ParticleHandler::mark(const G4Track* track) {
149  mask.set(G4PARTICLE_CREATED_HIT);
151  // If yes, flag it, because it is a candidate for removal.
152  G4LogicalVolume* vol = track->GetVolume()->GetLogicalVolume();
153  G4VSensitiveDetector* g4 = vol->GetSensitiveDetector();
154  Geant4ActionSD* sd = dynamic_cast<Geant4ActionSD*>(g4);
155  std::string typ = sd ? sd->sensitiveType() : std::string();
156  if ( typ == "calorimeter" )
158  else if ( typ == "tracker" )
160  else // Assume by default "tracker"
162 
163  if ( !this->m_userHandlers.empty() ) {
164  for( auto* h : this->m_userHandlers )
165  h->mark_track(track, &m_currTrack, sd->sequence());
166  }
167 }
168 
170 void Geant4ParticleHandler::operator()(G4Event* event) {
171  typedef Geant4MonteCarloTruth _MC;
172  debug("+++ Event:%d Add EVENT extension of type Geant4ParticleHandler.....",event->GetEventID());
173  context()->event().addExtension((_MC*)this, false);
174  clear();
176  for( auto* h : this->m_userHandlers )
177  h->generate(event, this);
178 }
179 
181 void Geant4ParticleHandler::step(const G4Step* step_value, G4SteppingManager* mgr) {
182  typedef std::vector<const G4Track*> _Sec;
183  ++m_currTrack.steps;
185  //
186  // Tracks below the energy threshold are NOT stored.
187  // If these tracks produce hits or are selected due to another signature,
188  // this criterium will anyhow take precedence.
189  //
190  const _Sec* sec=step_value->GetSecondaryInCurrentStep();
191  if ( not sec->empty() ) {
193  }
194  }
196  for( auto* h : this->m_userHandlers )
197  h->step(step_value, mgr, m_currTrack);
198 }
199 
201 void Geant4ParticleHandler::begin(const G4Track* track) {
202  Geant4TrackHandler h(track);
203  double kine = h.kineticEnergy();
204  G4ThreeVector mom = h.momentum();
205  const G4ThreeVector& v = h.vertex();
206  int reason = (kine > m_kinEnergyCut) ? G4PARTICLE_ABOVE_ENERGY_THRESHOLD : 0;
207  const G4PrimaryParticle* prim = h.primary();
208  Particle* prim_part = 0;
209 
210  // if particles are not tracked to the end, we pick up where we stopped previously
211  if ( m_haveSuspended ) {
212  //primary particles are already in the particle map, we don't have to store them in another map
213  auto existingParticle = m_particleMap.find(h.id());
214  if ( existingParticle != m_particleMap.end() ) {
215  m_currTrack.get_data(*(existingParticle->second));
216  return;
217  }
218  //other particles might not be in the particleMap yet, so we take them from here
219  existingParticle = m_suspendedPM.find(h.id());
220  if ( existingParticle != m_suspendedPM.end() ) {
221  m_currTrack.get_data(*(existingParticle->second));
222  // make sure we delete a suspended particle in the map, fill it back later...
223  delete (*existingParticle).second;
224  m_suspendedPM.erase(existingParticle);
225  return;
226  }
227  }
228 
229  if ( prim ) {
230  prim_part = m_primaryMap->get(prim);
231  if ( !prim_part ) {
232  except("+++ Tracking preaction: Primary particle without generator particle!");
233  }
235  m_particleMap[h.id()] = prim_part->addRef();
236  }
237 
238  if ( prim_part ) {
239  m_currTrack.id = prim_part->id;
240  m_currTrack.reason = prim_part->reason|reason;
241  m_currTrack.mask = prim_part->mask;
242  m_currTrack.status = prim_part->status;
243  m_currTrack.genStatus = prim_part->genStatus;
244  m_currTrack.spin[0] = prim_part->spin[0];
245  m_currTrack.spin[1] = prim_part->spin[1];
246  m_currTrack.spin[2] = prim_part->spin[2];
247  m_currTrack.colorFlow[0] = prim_part->colorFlow[0];
248  m_currTrack.colorFlow[1] = prim_part->colorFlow[1];
249  m_currTrack.parents = prim_part->parents;
250  m_currTrack.daughters = prim_part->daughters;
251  m_currTrack.pdgID = prim_part->pdgID;
252  m_currTrack.mass = prim_part->mass;
253  m_currTrack.charge = int(3.0 * h.charge());
254  }
255  else {
257  m_currTrack.reason = reason;
258  m_currTrack.mask = 0;
261  m_currTrack.spin[0] = 0;
262  m_currTrack.spin[1] = 0;
263  m_currTrack.spin[2] = 0;
264  m_currTrack.colorFlow[0] = 0;
265  m_currTrack.colorFlow[1] = 0;
266  m_currTrack.parents.clear();
267  m_currTrack.daughters.clear();
268  m_currTrack.pdgID = h.pdgID();
269  m_currTrack.mass = h.mass();
270  m_currTrack.charge = int(3.0 * h.charge());
272  }
273  m_currTrack.steps = 0;
275  m_currTrack.g4Parent = h.parent();
276  m_currTrack.originalG4ID= h.id();
277  m_currTrack.process = h.creatorProcess();
278  m_currTrack.time = h.globalTime();
279  m_currTrack.vsx = v.x();
280  m_currTrack.vsy = v.y();
281  m_currTrack.vsz = v.z();
282  m_currTrack.vex = 0.0;
283  m_currTrack.vey = 0.0;
284  m_currTrack.vez = 0.0;
285  m_currTrack.psx = mom.x();
286  m_currTrack.psy = mom.y();
287  m_currTrack.psz = mom.z();
288  m_currTrack.pex = 0.0;
289  m_currTrack.pey = 0.0;
290  m_currTrack.pez = 0.0;
291  // If the creator process of the track is in the list of process products to be kept, set the proper flag
292  if ( m_currTrack.process ) {
293  Processes::iterator i=find(m_processNames.begin(),m_processNames.end(),m_currTrack.process->GetProcessName());
294  if ( i != m_processNames.end() ) {
296  }
297  }
298  if ( m_keepAll ) {
300  }
301 
303  for( auto* handler : this->m_userHandlers )
304  handler->begin(track, m_currTrack);
305 }
306 
308 void Geant4ParticleHandler::end(const G4Track* track) {
309  Geant4TrackHandler h(track);
311  const int g4_id = h.id();
312 
313  int track_reason = m_currTrack.reason;
315  // Update vertex end point and final momentum
316  G4ThreeVector mom = track->GetMomentum();
317  const G4ThreeVector& pos = track->GetPosition();
318  ph->pex = mom.x();
319  ph->pey = mom.y();
320  ph->pez = mom.z();
321  ph->vex = pos.x();
322  ph->vey = pos.y();
323  ph->vez = pos.z();
324 
325  // Set the simulator status bits
326  PropertyMask simStatus(m_currTrack.status);
327 
328  // check if the last step ended on the worldVolume boundary
329  const G4Step* theLastStep = track->GetStep();
330  G4StepPoint* theLastPostStepPoint = NULL;
331  if(theLastStep) theLastPostStepPoint = theLastStep->GetPostStepPoint();
332  if( theLastPostStepPoint &&
333  ( theLastPostStepPoint->GetStepStatus() == fWorldBoundary //particle left world volume
334  //|| theLastPostStepPoint->GetStepStatus() == fGeomBoundary
335  )
336  ) {
337  simStatus.set(G4PARTICLE_SIM_LEFT_DETECTOR);
338  }
339 
340  if(track->GetKineticEnergy() <= 0.) {
341  simStatus.set(G4PARTICLE_SIM_STOPPED);
342  }
343 
345  for( auto* handler : this->m_userHandlers )
346  handler->end(track, m_currTrack);
347 
348  // These are candidate tracks with a probability to be stored due to their properties:
349  // - primary particle
350  // - hits created
351  // - secondaries
352  // - above energy threshold
353  // - to be kept due to creator process
354  // - to be kept due to user information of type 'Geant4ParticleInformation' stored in the G4Track
355  //
356  Geant4ParticleInformation* track_info =
357  dynamic_cast<Geant4ParticleInformation*>(track->GetUserInformation());
358  if ( !mask.isNull() || track_info ) {
359  m_equivalentTracks[g4_id] = g4_id;
360  ParticleMap::iterator ip = m_particleMap.find(g4_id);
361  if ( mask.isSet(G4PARTICLE_PRIMARY) ) {
362  ph.dump2(outputLevel()-1,name(),"Add Primary",h.id(),ip!=m_particleMap.end());
363  }
364  // Create a new MC particle from the current track information saved in the pre-tracking action
365  Particle* part = 0;
366  if ( ip==m_particleMap.end() ) part = m_particleMap[g4_id] = new Particle();
367  else part = (*ip).second;
368  if ( track_info ) {
369  mask.set(G4PARTICLE_KEEP_USER);
370  part->extension.reset(track_info->release());
371  }
372  part->get_data(m_currTrack);
373  }
374  else {
375  // These are tracks without any special properties.
376  //
377  // We will not store them on the record, but have to memorise the
378  // track identifier in order to restore the history for the created hits.
379  int pid = m_currTrack.g4Parent;
380  m_equivalentTracks[g4_id] = pid;
381  // Need to find the last stored particle and OR this particle's mask
382  // with the mask of the last stored particle
383  auto iend = m_equivalentTracks.end(), iequiv=m_equivalentTracks.end();
384  ParticleMap::iterator ip;
385  for(ip=m_particleMap.find(pid); ip == m_particleMap.end(); ip=m_particleMap.find(pid)) {
386  if (iequiv=m_equivalentTracks.find(pid); iequiv == iend) break; // ERROR
387  pid = (*iequiv).second;
388  }
389  if ( ip != m_particleMap.end() )
390  (*ip).second->reason |= track_reason;
391  else
392  ph.dumpWithVertex(outputLevel()+3,name(),"FATAL: No real particle parent present");
393  }
394 
395  if(track->GetTrackStatus() == fSuspend) {
396  m_haveSuspended = true;
397  //track is already in particle map, we pick it up from there in begin again
398  if(m_particleMap.find(g4_id) != m_particleMap.end()) return;
399  //track is not already stored, keep it in special map
400  auto iPart = m_suspendedPM.emplace(g4_id, new Particle());
401  (iPart.first->second)->get_data(m_currTrack);
402  return; // we trust that we eventually return to this function with another status and go on then
403  }
404 
405 }
406 
408 void Geant4ParticleHandler::beginEvent(const G4Event* event) {
410  info("+++ Event %d Begin event action. Access event related information.",event->GetEventID());
412  m_globalParticleID = interaction->nextPID();
413  m_particleMap.clear();
414  m_equivalentTracks.clear();
416  for( auto* h : this->m_userHandlers )
417  h->begin(event);
418 }
419 
421 void Geant4ParticleHandler::dumpMap(const char* tag) const {
422  const std::string& n = name();
423  Geant4ParticleHandle::header4(INFO,n,tag);
424  for(ParticleMap::const_iterator iend=m_particleMap.end(), i=m_particleMap.begin(); i!=iend; ++i) {
425  Geant4ParticleHandle((*i).second).dump4(INFO,n,tag);
426  }
427 }
428 
430 void Geant4ParticleHandler::endEvent(const G4Event* event) {
431  int count = 0;
432  int level = outputLevel();
433  do {
434  if ( level <= VERBOSE ) dumpMap("Particle ");
435  debug("+++ Iteration:%d Tracks:%d Equivalents:%d",++count,m_particleMap.size(),m_equivalentTracks.size());
436  } while( recombineParents() > 0 );
437 
438  if ( level <= VERBOSE ) dumpMap( "Recombined");
439  // Rebase the simulated tracks, so that they fit to the generator particles
441  if ( level <= VERBOSE ) dumpMap( "Rebased ");
442  // Consistency check....
445  for( auto* h : this->m_userHandlers )
446  h->end(event);
448 
449  // Now export the data to the final record.
452  m_primaryMap = 0;
453  clear();
454 }
455 
459  TrackEquivalents equivalents, orgParticles;
460  ParticleMap finalParticles;
461  ParticleMap::const_iterator ipar, iend, i;
462  int count;
463 
465  ParticleMap& pm = interaction->particles;
466 
467  // (1.0) Copy the pre-defined particle mapping for the simulated tracks
468  // It is assumed the mapping is ZERO based without holes.
469  for(count = 0, iend=pm.end(), i=pm.begin(); i!=iend; ++i) {
470  Particle* p = (*i).second;
471  orgParticles[p->id] = p->id;
472  finalParticles[p->id] = p;
473  if ( p->id > count ) count = p->id;
474  if ( (p->reason&G4PARTICLE_PRIMARY) != G4PARTICLE_PRIMARY ) {
475  p->addRef();
476  }
477  }
478  // (1.1) Define the new particle mapping for the simulated tracks
479  for(++count, iend=m_particleMap.end(), i=m_particleMap.begin(); i!=iend; ++i) {
480  Particle* p = (*i).second;
481  if ( (p->reason&G4PARTICLE_PRIMARY) != G4PARTICLE_PRIMARY ) {
482  //if ( orgParticles.find(p->id) == orgParticles.end() ) {
483  orgParticles[p->id] = count;
484  finalParticles[count] = p;
485  p->id = count;
486  ++count;
487  }
488  }
489  // (2) Re-evaluate the corresponding geant4 track equivalents using the new mapping
490  for(TrackEquivalents::iterator ie=m_equivalentTracks.begin(),ie_end=m_equivalentTracks.end(); ie!=ie_end; ++ie) {
491  int g4_equiv = (*ie).first;
492  while( (ipar=m_particleMap.find(g4_equiv)) == m_particleMap.end() ) {
493  TrackEquivalents::const_iterator iequiv = m_equivalentTracks.find(g4_equiv);
494  if ( iequiv == ie_end ) {
495  break; // ERROR !! Will be handled by printout below because ipar==end()
496  }
497  g4_equiv = (*iequiv).second;
498  }
499  TrackEquivalents::mapped_type equiv = (*ie).second;
500  if ( ipar != m_particleMap.end() ) {
501  Geant4ParticleHandle p = (*ipar).second;
502  equivalents[(*ie).first] = p->id; // requires (1) to be filled properly!
503  const G4ParticleDefinition* def = p.definition();
504  int pdg = int(std::abs(def->GetPDGEncoding())+0.1);
505  if ( pdg != 0 && pdg<36 && !(pdg > 10 && pdg < 17) && pdg != 22 ) {
506  error("+++ ERROR: Geant4 particle for track:%d last known is:%d -- is gluon or quark!",equiv,g4_equiv);
507  }
508  pdg = int(std::abs(p->pdgID)+0.1);
509  if ( pdg != 0 && pdg<36 && !(pdg > 10 && pdg < 17) && pdg != 22 ) {
510  error("+++ ERROR(2): Geant4 particle for track:%d last known is:%d -- is gluon or quark!",equiv,g4_equiv);
511  }
512  }
513  else {
514  error("+++ No Equivalent particle for track:%d last known is:%d",equiv,g4_equiv);
515  }
516  }
517 
518  // (3) Compute the particle's parents and daughters.
519  // Replace the original Geant4 track with the
520  // equivalent particle still present in the record.
521  // Note:
522  // We rely here on the ordering of the particles accoding to their
523  // Processing by Geant4 to establish mother daughter relationships.
524  // == > use finalParticles map and NOT m_particleMap.
525  int equiv_id = -1;
526  for( auto& part : finalParticles ) {
527  auto& p = part.second;
528  if ( p->g4Parent > 0 ) {
529  TrackEquivalents::iterator iequ = equivalents.find(p->g4Parent);
530  if ( iequ != equivalents.end() ) {
531  equiv_id = (*iequ).second;//equivalents[p->g4Parent];
532  if ( (ipar=finalParticles.find(equiv_id)) != finalParticles.end() ) {
533  Particle* q = (*ipar).second;
534  bool prim = (p->reason&G4PARTICLE_PRIMARY) == G4PARTICLE_PRIMARY;
535  // We assume that the mother daughter relationship
536  // is filled by the event readers!
537  if ( !prim ) {
538  p->parents.insert(q->id);
539  }
540  if ( !p->parents.empty() ) {
541  int parent_id = (*p->parents.begin());
542  if ( parent_id == q->id )
543  q->daughters.insert(p->id);
544  else if ( !prim )
545  error("+++ Inconsistency in equivalent record! Parent: %d Daughter:%d",q->id, p->id);
546  }
547  else {
548  error("+++ Inconsistency in parent relashionship: %d NO parent!", p->id);
549  }
550  continue;
551  }
552  }
553  error("+++ Inconsistency in particle record: Geant4 parent %d "
554  "of particle %d not in record of final particles!",
555  p->g4Parent,p->id);
556  }
557  }
558 #if 0
559  for(iend=finalParticles.end(), i=finalParticles.begin(); i!=iend; ++i) {
560  Particle* p = (*i).second;
561  if ( p->g4Parent > 0 ) {
562  int parent_id = (*p->parents.begin());
563  if ( (ipar=finalParticles.find(parent_id)) != finalParticles.end() ) {
564  Particle* q = (*ipar).second;
565  // Generator particles have a proper history.
566  // We only deal with particles, which are not of MC origin.
567  //p->parents.insert(q->id);
568  if ( parent_id == q->id )
569  q->daughters.insert(p->id);
570  else
571  error("+++ Inconsistency in equivalent record! Parent: %d Daughter:%d",q->id, p->id);
572  continue;
573  }
574  error("+++ Inconsistency in particle record: Geant4 parent %d "
575  "of particle %d not in record of final particles!",
576  p->g4Parent,p->id);
577  }
578  }
579 #endif
580  m_equivalentTracks = std::move(equivalents);
581  m_particleMap = std::move(finalParticles);
582 }
583 
585 bool Geant4ParticleHandler::defaultKeepParticle(Particle& particle) {
586  PropertyMask mask(particle.reason);
587  bool secondaries = mask.isSet(G4PARTICLE_HAS_SECONDARIES);
588  bool tracker_track = mask.isSet(G4PARTICLE_CREATED_TRACKER_HIT);
589  bool calo_track = mask.isSet(G4PARTICLE_CREATED_CALORIMETER_HIT);
590  bool hits_produced = mask.isSet(G4PARTICLE_CREATED_HIT);
591  bool low_energy = !mask.isSet(G4PARTICLE_ABOVE_ENERGY_THRESHOLD);
592 
594  if ( mask.isNull() || (secondaries && low_energy && !hits_produced) ) {
595  return true;
596  }
598  else if ( !hits_produced && low_energy ) {
599  return true;
600  }
602  else if ( !tracker_track && calo_track && low_energy ) {
603  return true;
604  }
605  else {
606  //printout(INFO,name(),"+++ Track: %d should be kept for no obvious reason....",id);
607  }
608  return false;
609 }
610 
614  std::set<int> remove;
615 
617  for(ParticleMap::reverse_iterator i=m_particleMap.rbegin(); i!=m_particleMap.rend(); ++i) {
618  Particle* p = (*i).second;
619  PropertyMask mask(p->reason);
620  // Allow the user to force the particle handling either by
621  // or the reason mask with G4PARTICLE_KEEP_USER or
622  // to set the reason mask to NULL in order to drop it.
623  //
624  // If the mask entry is set to G4PARTICLE_FORCE_KILL
625  // or is set to NULL, the particle is ALWAYS removed
626  //
627  // Note: This may override all other decisions!
628  bool remove_me = defaultKeepParticle(*p);
629  if ( !this->m_userHandlers.empty() ) {
630  remove_me = true;
631  for( auto* h : this->m_userHandlers )
632  remove_me |= h->keepParticle(*p);
633  }
634 
635  // Now look at the property mask of the particle
636  if ( mask.isNull() || mask.isSet(G4PARTICLE_FORCE_KILL) ) {
637  remove_me = true;
638  }
639  else if ( mask.isSet(G4PARTICLE_KEEP_USER) ) {
641  mask.set(G4PARTICLE_KEEP_USER);
642  continue;
643  }
644  else if ( mask.isSet(G4PARTICLE_PRIMARY) ) {
646  continue;
647  }
648  else if ( mask.isSet(G4PARTICLE_KEEP_ALWAYS) ) {
649  continue;
650  }
651  else if ( mask.isSet(G4PARTICLE_KEEP_PARENT) ) {
652  //continue;
653  }
654  else if ( mask.isSet(G4PARTICLE_KEEP_PROCESS) ) {
655  if(ParticleMap::iterator ip = m_particleMap.find(p->g4Parent); ip != m_particleMap.end() ) {
656  Particle* parent_part = (*ip).second;
657  PropertyMask parent_mask(parent_part->reason);
658  if ( parent_mask.isSet(G4PARTICLE_ABOVE_ENERGY_THRESHOLD) ) {
659  parent_mask.set(G4PARTICLE_KEEP_PARENT);
660  continue;
661  }
662  }
663  // Low energy stuff. Remove it. Reassign to parent.
664  //remove_me = true;
665  }
666 
668  if ( remove_me ) {
669  int g4_id = (*i).first;
670  remove.insert(g4_id);
671  m_equivalentTracks[g4_id] = p->g4Parent;
672  if(ParticleMap::iterator ip = m_particleMap.find(p->g4Parent); ip != m_particleMap.end() ) {
673  Particle* parent_part = (*ip).second;
674  PropertyMask(parent_part->reason).set(mask.value());
675  parent_part->steps += p->steps;
676  parent_part->secondaries += p->secondaries;
678  for( auto* h : this->m_userHandlers )
679  h->combine(*p, *parent_part);
680  }
681  }
682  }
683  for( int r : remove ) {
684  if( auto ir = m_particleMap.find(r); ir != m_particleMap.end() ) {
685  (*ir).second->release();
686  m_particleMap.erase(ir);
687  }
688  }
689  return int(remove.size());
690 }
691 
694  int num_errors = 0;
695 
697  for(const auto& part : m_particleMap ) {
698  Geant4Particle* particle = part.second;
699  Geant4ParticleHandle p(particle);
700  PropertyMask mask(p->reason);
701  PropertyMask status(p->status);
702  std::set<int>& daughters = p->daughters;
703  ParticleMap::const_iterator j;
704  // For all particles, the set of daughters must be contained in the record.
705  for( int id_dau : daughters ) {
706  if ( j=m_particleMap.find(id_dau); j == m_particleMap.end() ) {
707  ++num_errors;
708  error("+++ Particle:%d Daughter %d is not in particle map!",p->id,id_dau);
709  }
710  }
711  // We assume that particles from the generator have consistent parents
712  // For all other particles except the primaries, the parent must be contained in the record.
713  if ( !mask.isSet(G4PARTICLE_PRIMARY) && !status.anySet(G4PARTICLE_GEN_STATUS) ) {
714  bool in_map = false, in_parent_list = false;
715  int parent_id = -1;
716  if( auto eq_it=m_equivalentTracks.find(p->g4Parent); eq_it != m_equivalentTracks.end() ) {
717  parent_id = (*eq_it).second;
718  in_map = (j=m_particleMap.find(parent_id)) != m_particleMap.end();
719  in_parent_list = p->parents.find(parent_id) != p->parents.end();
720  }
721  if ( !in_map || !in_parent_list ) {
722  char parent_list[1024];
723  parent_list[0] = 0;
724  ++num_errors;
725  p.dumpWithMomentum(ERROR,name(),"INCONSISTENCY");
726  for( int ip : p->parents )
727  ::snprintf(parent_list+strlen(parent_list),sizeof(parent_list)-strlen(parent_list),"%d ",ip);
728  error("+++ Particle:%d Parent %d (G4id:%d) In record:%s In parent list:%s [%s]",
729  p->id,parent_id,p->g4Parent,yes_no(in_map),yes_no(in_parent_list),parent_list);
730  }
731  }
732  }
733 
734  if ( num_errors > 0 ) {
735  except("+++ Consistency check failed. Found %d problems.",num_errors);
736  }
737 }
738 
740  for( auto& part : m_particleMap ) {
741  auto* p = part.second;
742  if( !p->parents.empty() ) {
743  PropertyMask mask(p->status);
744  //if the particle did not go to geant4 none of these flags is set
745  // we shouldn't set the vertex bit in this case.
746  if(not mask.anySet(G4PARTICLE_SIM_CREATED
752  continue;
753  }
754  Geant4Particle *parent(m_particleMap[ *p->parents.begin() ]);
755  const double X( parent->vex - p->vsx );
756  const double Y( parent->vey - p->vsy );
757  const double Z( parent->vez - p->vsz );
758  if( sqrt(X*X + Y*Y + Z*Z) > m_minDistToParentVertex ){
760  }
761  }
762  }
763 }
dd4hep::sim::G4PARTICLE_SIM_CREATED
@ G4PARTICLE_SIM_CREATED
Definition: Geant4Particle.h:85
dd4hep::sim::G4PARTICLE_CREATED_TRACKER_HIT
@ G4PARTICLE_CREATED_TRACKER_HIT
Definition: Geant4Particle.h:64
dd4hep::sim::Geant4ParticleHandler::endEvent
virtual void endEvent(const G4Event *event)
Post-event action callback.
dd4hep::sim::Geant4ParticleHandler::m_keepAll
bool m_keepAll
Property: Flag to keep all particles generated.
Definition: Geant4ParticleHandler.h:99
dd4hep::sim::Geant4ParticleHandler::Geant4ParticleHandler
Geant4ParticleHandler()
No default constructor.
Geant4TrackHandler.h
dd4hep::sim::Geant4PrimaryMap
Data structure to map primaries to particles.
Definition: Geant4Primary.h:64
dd4hep::sim::Geant4PrimaryInteraction::nextPID
int nextPID()
Access a new particle identifier within the interaction.
Definition: Geant4Primary.cpp:65
dd4hep::sim::Geant4ParticleHandler::Particle
Geant4ParticleMap::Particle Particle
Definition: Geant4ParticleHandler.h:74
dd4hep::sim::G4PARTICLE_ABOVE_ENERGY_THRESHOLD
@ G4PARTICLE_ABOVE_ENERGY_THRESHOLD
Definition: Geant4Particle.h:60
dd4hep::sim::Geant4Particle::vsz
double vsz
Definition: Geant4Particle.h:124
dd4hep::sim::G4PARTICLE_KEEP_PARENT
@ G4PARTICLE_KEEP_PARENT
Definition: Geant4Particle.h:62
dd4hep::sim::Geant4Particle::reason
int reason
Definition: Geant4Particle.h:111
Geant4ParticleHandler
Geant4Action to collect the MC particle information.
dd4hep::sim::G4PARTICLE_SIM_PARENT_RADIATED
@ G4PARTICLE_SIM_PARENT_RADIATED
Definition: Geant4Particle.h:91
v
View * v
Definition: MultiView.cpp:28
dd4hep::sim::Geant4Particle::mass
double mass
Particle mass.
Definition: Geant4Particle.h:132
dd4hep::sim::Geant4ParticleHandler::recombineParents
int recombineParents()
Recombine particles and associate the to parents with cleanup.
dd4hep::sim::Geant4Particle::vey
double vey
Definition: Geant4Particle.h:126
dd4hep::sim::Geant4Particle::pez
double pez
Definition: Geant4Particle.h:130
dd4hep::sim::Geant4ParticleHandler::m_primaryMap
Geant4PrimaryMap * m_primaryMap
Primary map.
Definition: Geant4ParticleHandler.h:117
dd4hep::sim::Geant4ParticleInformation::release
ParticleExtension * release()
Definition: Geant4ParticleInformation.h:86
dd4hep::sim::G4PARTICLE_KEEP_USER
@ G4PARTICLE_KEEP_USER
Definition: Geant4Particle.h:65
dd4hep::sim::Geant4PrimaryInteraction
Class modelling a single interaction with multiple primary vertices and particles.
Definition: Geant4Primary.h:95
dd4hep::sim::G4PARTICLE_KEEP_PROCESS
@ G4PARTICLE_KEEP_PROCESS
Definition: Geant4Particle.h:61
dd4hep::sim::Geant4ParticleHandler::m_processNames
Processes m_processNames
Property: All the processes of which the decay products will be explicitly stored.
Definition: Geant4ParticleHandler.h:107
dd4hep::sim::Geant4Particle::id
int id
not persistent
Definition: Geant4Particle.h:108
dd4hep::sim::Geant4ParticleHandler::operator=
Geant4ParticleHandler & operator=(const Geant4ParticleHandler &c)
No assignment operator.
Geant4SensDetAction.h
Geant4TrackingAction.h
dd4hep::sim::Geant4ParticleMap::adopt
void adopt(ParticleMap &pm, TrackEquivalents &equiv)
Adopt particle maps.
Definition: Geant4Particle.cpp:522
Geant4EventAction.h
dd4hep::sim::Geant4ParticleHandler::checkConsistency
void checkConsistency() const
Check the record consistency.
dd4hep::sim::Geant4ParticleHandler::begin
virtual void begin(const G4Track *track)
Pre-track action callback.
dd4hep::sim::Geant4Particle::pdgID
int pdgID
Definition: Geant4Particle.h:115
dd4hep::sim::Geant4Particle::g4Parent
int g4Parent
not persistent
Definition: Geant4Particle.h:110
dd4hep::sim::Geant4Particle::psz
double psz
Definition: Geant4Particle.h:128
dd4hep::sim::G4PARTICLE_CREATED_HIT
@ G4PARTICLE_CREATED_HIT
Definition: Geant4Particle.h:57
dd4hep::sim::Geant4PrimaryInteraction::particles
ParticleMap particles
The map of particles participating in this primary interaction.
Definition: Geant4Primary.h:112
dd4hep::sim::Geant4ParticleHandler::step
virtual void step(const G4Step *step, G4SteppingManager *mgr)
User stepping callback.
dd4hep::sim::Geant4Context::event
Geant4Event & event() const
Access the geant4 event – valid only between BeginEvent() and EndEvent()!
Definition: Geant4Context.cpp:84
Geant4StepHandler.h
dd4hep::sim::Geant4Particle::secondaries
int secondaries
Definition: Geant4Particle.h:114
Geant4UserParticleHandler.h
dd4hep::sim::G4PARTICLE_SIM_BACKSCATTER
@ G4PARTICLE_SIM_BACKSCATTER
Definition: Geant4Particle.h:86
Geant4SteppingAction.h
dd4hep::sim::Geant4ParticleHandler::m_equivalentTracks
TrackEquivalents m_equivalentTracks
Map associating the G4Track identifiers with identifiers of existing MCParticles.
Definition: Geant4ParticleHandler.h:126
dd4hep::sim::Geant4ParticleHandler::m_suspendedPM
ParticleMap m_suspendedPM
Map with stored MC Particles that were suspended by the stepping action.
Definition: Geant4ParticleHandler.h:123
dd4hep::sim::Geant4Particle::extension
std::unique_ptr< ParticleExtension > extension
User data extension if required.
Definition: Geant4Particle.h:143
PropertyMask
dd4hep::detail::ReferenceBitMask< int > PropertyMask
Definition: Geant4ParticleHandler.cpp:43
dd4hep::sim::Geant4Particle::get_data
Geant4Particle & get_data(Geant4Particle &c)
Assignment operator.
Definition: Geant4Particle.cpp:67
dd4hep::sim::Geant4ParticleMap
Data structure to map particles produced during the generation and the simulation.
Definition: Geant4Particle.h:337
dd4hep::sim::Geant4Action::info
void info(const char *fmt,...) const
Support of info messages.
Definition: Geant4Action.cpp:215
dd4hep::sim::Geant4Event::extension
T * extension(bool alert=true)
Access to type safe extension object. Exception is thrown if the object is invalid.
Definition: Geant4Context.h:151
dd4hep::sim::Geant4Action::except
void except(const char *fmt,...) const
Support of exceptions: Print fatal message and throw runtime_error.
Definition: Geant4Action.cpp:256
dd4hep::sim::Geant4ParticleHandler::m_userHandlers
std::vector< Geant4UserParticleHandler * > m_userHandlers
User action pointer.
Definition: Geant4ParticleHandler.h:111
dd4hep::sim::G4PARTICLE_SIM_STOPPED
@ G4PARTICLE_SIM_STOPPED
Definition: Geant4Particle.h:89
dd4hep::sim::Geant4ParticleHandler::dumpMap
void dumpMap(const char *tag) const
Debugging: Dump Geant4 particle map.
Geant4UserParticleHandler
Geant4ParticleHandler user extension action called by the particle handler.
dd4hep::sim::Geant4Action::error
void error(const char *fmt,...) const
Support of error messages.
Definition: Geant4Action.cpp:231
Geant4ParticleInformation.h
dd4hep::sim::Geant4Particle::vez
double vez
Definition: Geant4Particle.h:126
Geant4ParticleHandler.h
dd4hep::sim::G4PARTICLE_SIM_DECAY_CALO
@ G4PARTICLE_SIM_DECAY_CALO
Definition: Geant4Particle.h:87
dd4hep::sim::Geant4ParticleHandler::rebaseSimulatedTracks
void rebaseSimulatedTracks(int base)
Rebase the simulated tracks, so that they fit to the generator particles.
dd4hep::sim::Geant4ParticleHandler::TrackEquivalents
Geant4ParticleMap::TrackEquivalents TrackEquivalents
Definition: Geant4ParticleHandler.h:76
G4VSensitiveDetector
Class of the Geant4 toolkit. See http://www-geant4.kek.jp/Reference.
Definition: Geant4Classes.h:59
dd4hep::sim::G4PARTICLE_KEEP_ALWAYS
@ G4PARTICLE_KEEP_ALWAYS
Definition: Geant4Particle.h:66
dd4hep::sim::Geant4Particle::colorFlow
int colorFlow[2]
Definition: Geant4Particle.h:117
dd4hep::sim::Geant4Particle::spin
float spin[3]
Definition: Geant4Particle.h:121
dd4hep::sim::G4PARTICLE_GEN_STATUS
@ G4PARTICLE_GEN_STATUS
Definition: Geant4Particle.h:82
dd4hep::InstanceCount::decrement
static void decrement(T *)
Decrement count according to type information.
Definition: InstanceCount.h:102
dd4hep::sim::Geant4MonteCarloTruth
Default Interface class to handle monte carlo truth records.
Definition: Geant4MonteCarloTruth.h:43
dd4hep::sim::Geant4Particle::genStatus
unsigned short genStatus
Definition: Geant4Particle.h:118
dd4hep::sim::Geant4GeneratorAction
Concrete implementation of the Geant4 generator action base class.
Definition: Geant4GeneratorAction.h:47
dd4hep::sim::Geant4ParticleHandler::m_minDistToParentVertex
double m_minDistToParentVertex
Property: Minimal distance after which the vertexIsNotEndpointOfParent flag is set.
Definition: Geant4ParticleHandler.h:105
dd4hep::sim::Geant4ParticleHandler::adopt
bool adopt(Geant4Action *action)
Adopt the user particle handler.
dd4hep::sim::Geant4Particle::status
int status
Definition: Geant4Particle.h:116
dd4hep::sim::Geant4TrackHandler
Helper class to ease the extraction of information from a G4Track object.
Definition: Geant4TrackHandler.h:53
dd4hep::sim::Geant4Particle::originalG4ID
int originalG4ID
Definition: Geant4Particle.h:109
dd4hep::sim::Geant4ActionSD::sensitiveType
virtual const std::string & sensitiveType() const =0
Access to the sensitive type of the detector.
dd4hep::sim::Geant4ParticleHandle::dump4
void dump4(int level, const std::string &src, const char *tag) const
Definition: Geant4Particle.cpp:382
dd4hep::sim::Geant4Particle::daughters
Particles daughters
The list of daughters of this MC particle.
Definition: Geant4Particle.h:140
dd4hep::sim::G4PARTICLE_SIM_DECAY_TRACKER
@ G4PARTICLE_SIM_DECAY_TRACKER
Definition: Geant4Particle.h:88
dd4hep::sim::Geant4Action
Default base class for all Geant 4 actions and derivates thereof.
Definition: Geant4Action.h:113
dd4hep::sim::Geant4ParticleHandler::defaultKeepParticle
static bool defaultKeepParticle(Particle &particle)
Default callback to be answered if the particle should be kept if NO user handler is installed.
dd4hep::sim::Geant4Action::name
const std::string & name() const
Access name of the action.
Definition: Geant4Action.h:280
dd4hep::sim::Geant4Particle::mask
int mask
Definition: Geant4Particle.h:112
dd4hep::sim::Geant4Particle::time
double time
Particle creation time.
Definition: Geant4Particle.h:134
dd4hep::sim::Geant4Particle::steps
int steps
Definition: Geant4Particle.h:113
dd4hep::sim::Geant4Particle::process
const G4VProcess * process
Reference to the G4VProcess, which created this track.
Definition: Geant4Particle.h:145
dd4hep::sim::Geant4Particle::pex
double pex
The track momentum at the end vertex.
Definition: Geant4Particle.h:130
dd4hep::sim::Geant4ActionSD
Interface class to access properties of the underlying Geant4 sensitive detector structure.
Definition: Geant4SensDetAction.h:61
dd4hep::sim::Geant4Action::outputLevel
PrintLevel outputLevel() const
Access the output level.
Definition: Geant4Action.h:296
dd4hep::sim::G4PARTICLE_HAS_SECONDARIES
@ G4PARTICLE_HAS_SECONDARIES
Definition: Geant4Particle.h:59
dd4hep::sim::Geant4Particle::vex
double vex
The end vertex.
Definition: Geant4Particle.h:126
dd4hep::sim::Geant4ParticleHandler::m_globalParticleID
int m_globalParticleID
Global particle identifier. Obtained at the begin of the event.
Definition: Geant4ParticleHandler.h:115
dd4hep::sim::Geant4ParticleHandler::m_particleMap
ParticleMap m_particleMap
Map with stored MC Particles.
Definition: Geant4ParticleHandler.h:121
dd4hep::sim::Geant4ParticleHandler::m_haveSuspended
bool m_haveSuspended
Definition: Geant4ParticleHandler.h:124
dd4hep::sim::Geant4Particle::vsx
double vsx
The starting vertex.
Definition: Geant4Particle.h:124
dd4hep::sim::Geant4ParticleHandler::operator()
virtual void operator()(G4Event *event) override
Event generation action callback.
dd4hep::sim::Geant4Particle::psx
double psx
The track momentum at the start vertex.
Definition: Geant4Particle.h:128
dd4hep::sim::Geant4ParticleHandle::definition
const G4ParticleDefinition * definition() const
Access the Geant4 particle definition object (expensive!)
Definition: Geant4Particle.cpp:112
dd4hep::sim::Geant4ParticleHandler::setVertexEndpointBit
void setVertexEndpointBit()
set the endpointIsNotVertexOfParentFlag at the end of the event
dd4hep::sim::Geant4Particle::pey
double pey
Definition: Geant4Particle.h:130
dd4hep::sim::Geant4ParticleHandler::mark
virtual void mark(const G4Track *track) override
Mark a Geant4 track to be kept for later MC truth analysis. Default flag: CREATED_HIT.
dd4hep::sim::G4PARTICLE_FORCE_KILL
@ G4PARTICLE_FORCE_KILL
Definition: Geant4Particle.h:67
dd4hep::sim::Geant4Event::addExtension
void * addExtension(unsigned long long int k, ExtensionEntry *e)
Add an extension object to the detector element.
Definition: Geant4Context.h:140
Primitives.h
dd4hep::sim::G4PARTICLE_SIM_LEFT_DETECTOR
@ G4PARTICLE_SIM_LEFT_DETECTOR
Definition: Geant4Particle.h:90
dd4hep::sim
Namespace for the Geant4 based simulation part of the AIDA detector description toolkit.
Definition: EDM4hepFileReader.cpp:46
dd4hep::sim::Geant4ParticleHandler::clear
void clear()
Clear particle maps.
dd4hep::sim::Geant4ParticleHandle
Data structure to access derived MC particle information.
Definition: Geant4Particle.h:181
dd4hep::sim::Geant4ParticleHandler::m_currTrack
Particle m_currTrack
Local buffer about the 'current' G4Track.
Definition: Geant4ParticleHandler.h:119
dd4hep::sim::Geant4ParticleInformation
Wrapper to store user information in a G4Track.
Definition: Geant4ParticleInformation.h:48
dd4hep::sim::Geant4Particle::parents
Particles parents
The list of parents of this MC particle.
Definition: Geant4Particle.h:138
dd4hep::sim::Geant4Particle::vsy
double vsy
Definition: Geant4Particle.h:124
dd4hep::sim::G4PARTICLE_CREATED_CALORIMETER_HIT
@ G4PARTICLE_CREATED_CALORIMETER_HIT
Definition: Geant4Particle.h:63
dd4hep::sim::Geant4Action::debug
void debug(const char *fmt,...) const
Support of debug messages.
Definition: Geant4Action.cpp:207
dd4hep::sim::Geant4ParticleHandler::m_kinEnergyCut
double m_kinEnergyCut
Property: Flag if the handler is executed in standalone mode and hence must manage particles.
Definition: Geant4ParticleHandler.h:103
dd4hep::sim::Geant4ParticleHandler::end
virtual void end(const G4Track *track)
Post-track action callback.
dd4hep::sim::G4PARTICLE_PRIMARY
@ G4PARTICLE_PRIMARY
Definition: Geant4Particle.h:58
dd4hep::sim::Geant4Particle
Data structure to store the MC particle information.
Definition: Geant4Particle.h:103
dd4hep::sim::Geant4Particle::charge
char charge
Definition: Geant4Particle.h:119
PropertyMask
dd4hep::detail::ReferenceBitMask< int > PropertyMask
Definition: EDM4hepFileReader.cpp:43
InstanceCount.h
dd4hep::sim::Geant4PrimaryMap::get
Geant4Particle * get(const G4PrimaryParticle *particle)
Access DDG4 particle by G4 primary particle.
Definition: Geant4Primary.cpp:44
dd4hep::sim::Geant4Particle::psy
double psy
Definition: Geant4Particle.h:128
dd4hep::sim::Geant4ParticleHandler::ParticleMap
Geant4ParticleMap::ParticleMap ParticleMap
Definition: Geant4ParticleHandler.h:75
dd4hep::sim::Geant4ParticleHandler::beginEvent
virtual void beginEvent(const G4Event *event)
Pre-event action callback.
dd4hep::sim::Geant4ParticleHandle::header4
static void header4(int level, const std::string &src, const char *tag)
Definition: Geant4Particle.cpp:371
dd4hep::sim::Geant4Context
Generic context to extend user, run and event information.
Definition: Geant4Context.h:201
dd4hep::sim::Geant4Action::context
Geant4Context * context() const
Access the context.
Definition: Geant4Action.h:270
dd4hep::sim::Geant4ActionSD::sequence
virtual Geant4SensDetActionSequence * sequence() const =0
Access the DDG4 action sequence.