DD4hep  1.35.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  // Volume is never null since track is always within the world volume
154  G4VSensitiveDetector* g4 = vol->GetSensitiveDetector();
155  Geant4ActionSD* sd = dynamic_cast<Geant4ActionSD*>(g4);
156  if( sd ) {
157  std::string typ = sd->sensitiveType();
158  if ( typ == "calorimeter" )
160  else if ( typ == "tracker" )
161  mask.set( G4PARTICLE_CREATED_TRACKER_HIT );
162  else // Assume by default "tracker"
163  mask.set( G4PARTICLE_CREATED_TRACKER_HIT );
164  }
165  if( !this->m_userHandlers.empty() ) {
166  for( auto* h : this->m_userHandlers )
167  h->mark_track( track, &m_currTrack );
168  }
169 }
170 
172 void Geant4ParticleHandler::operator()(G4Event* event) {
173  typedef Geant4MonteCarloTruth _MC;
174  debug("+++ Event:%d Add EVENT extension of type Geant4ParticleHandler.....",event->GetEventID());
175  context()->event().addExtension((_MC*)this, false);
176  clear();
178  for( auto* h : this->m_userHandlers )
179  h->generate(event, this);
180 }
181 
183 void Geant4ParticleHandler::step(const G4Step* step_value, G4SteppingManager* mgr) {
184  typedef std::vector<const G4Track*> _Sec;
185  ++m_currTrack.steps;
187  //
188  // Tracks below the energy threshold are NOT stored.
189  // If these tracks produce hits or are selected due to another signature,
190  // this criterium will anyhow take precedence.
191  //
192  const _Sec* sec=step_value->GetSecondaryInCurrentStep();
193  if ( not sec->empty() ) {
195  }
196  }
198  for( auto* h : this->m_userHandlers )
199  h->step(step_value, mgr, m_currTrack);
200 }
201 
203 void Geant4ParticleHandler::begin(const G4Track* track) {
204  Geant4TrackHandler h(track);
205  double kine = h.kineticEnergy();
206  G4ThreeVector mom = h.momentum();
207  const G4ThreeVector& v = h.vertex();
208  int reason = (kine > m_kinEnergyCut) ? G4PARTICLE_ABOVE_ENERGY_THRESHOLD : 0;
209  const G4PrimaryParticle* prim = h.primary();
210  Particle* prim_part = 0;
211 
212  // if particles are not tracked to the end, we pick up where we stopped previously
213  if ( m_haveSuspended ) {
214  //primary particles are already in the particle map, we don't have to store them in another map
215  auto existingParticle = m_particleMap.find(h.id());
216  if ( existingParticle != m_particleMap.end() ) {
217  m_currTrack.get_data(*(existingParticle->second));
218  return;
219  }
220  //other particles might not be in the particleMap yet, so we take them from here
221  existingParticle = m_suspendedPM.find(h.id());
222  if ( existingParticle != m_suspendedPM.end() ) {
223  m_currTrack.get_data(*(existingParticle->second));
224  // make sure we delete a suspended particle in the map, fill it back later...
225  delete (*existingParticle).second;
226  m_suspendedPM.erase(existingParticle);
227  return;
228  }
229  }
230 
231  if ( prim ) {
232  prim_part = m_primaryMap->get(prim);
233  if ( !prim_part ) {
234  except("+++ Tracking preaction: Primary particle without generator particle!");
235  }
237  m_particleMap[h.id()] = prim_part->addRef();
238  }
239 
240  if ( prim_part ) {
241  m_currTrack.id = prim_part->id;
242  m_currTrack.reason = prim_part->reason|reason;
243  m_currTrack.mask = prim_part->mask;
244  m_currTrack.status = prim_part->status;
245  m_currTrack.genStatus = prim_part->genStatus;
246  m_currTrack.spin[0] = prim_part->spin[0];
247  m_currTrack.spin[1] = prim_part->spin[1];
248  m_currTrack.spin[2] = prim_part->spin[2];
249  m_currTrack.colorFlow[0] = prim_part->colorFlow[0];
250  m_currTrack.colorFlow[1] = prim_part->colorFlow[1];
251  m_currTrack.parents = prim_part->parents;
252  m_currTrack.daughters = prim_part->daughters;
253  m_currTrack.pdgID = prim_part->pdgID;
254  m_currTrack.mass = prim_part->mass;
255  m_currTrack.charge = int(3.0 * h.charge());
256  }
257  else {
259  m_currTrack.reason = reason;
260  m_currTrack.mask = 0;
263  m_currTrack.spin[0] = 0;
264  m_currTrack.spin[1] = 0;
265  m_currTrack.spin[2] = 0;
266  m_currTrack.colorFlow[0] = 0;
267  m_currTrack.colorFlow[1] = 0;
268  m_currTrack.parents.clear();
269  m_currTrack.daughters.clear();
270  m_currTrack.pdgID = h.pdgID();
271  m_currTrack.mass = h.mass();
272  m_currTrack.charge = int(3.0 * h.charge());
274  }
275  m_currTrack.steps = 0;
277  m_currTrack.g4Parent = h.parent();
278  m_currTrack.originalG4ID= h.id();
279  m_currTrack.process = h.creatorProcess();
280  m_currTrack.time = h.globalTime();
281  m_currTrack.vsx = v.x();
282  m_currTrack.vsy = v.y();
283  m_currTrack.vsz = v.z();
284  m_currTrack.vex = 0.0;
285  m_currTrack.vey = 0.0;
286  m_currTrack.vez = 0.0;
287  m_currTrack.psx = mom.x();
288  m_currTrack.psy = mom.y();
289  m_currTrack.psz = mom.z();
290  m_currTrack.pex = 0.0;
291  m_currTrack.pey = 0.0;
292  m_currTrack.pez = 0.0;
293  // If the creator process of the track is in the list of process products to be kept, set the proper flag
294  if ( m_currTrack.process ) {
295  Processes::iterator i=find(m_processNames.begin(),m_processNames.end(),m_currTrack.process->GetProcessName());
296  if ( i != m_processNames.end() ) {
298  }
299  }
300  if ( m_keepAll ) {
302  }
303 
305  for( auto* handler : this->m_userHandlers )
306  handler->begin(track, m_currTrack);
307 }
308 
310 void Geant4ParticleHandler::end(const G4Track* track) {
311  Geant4TrackHandler h(track);
313  const int g4_id = h.id();
314 
315  int track_reason = m_currTrack.reason;
317  // Update vertex end point and final momentum
318  G4ThreeVector mom = track->GetMomentum();
319  const G4ThreeVector& pos = track->GetPosition();
320  ph->pex = mom.x();
321  ph->pey = mom.y();
322  ph->pez = mom.z();
323  ph->vex = pos.x();
324  ph->vey = pos.y();
325  ph->vez = pos.z();
326 
327  // Set the simulator status bits
328  PropertyMask simStatus(m_currTrack.status);
329 
330  // check if the last step ended on the worldVolume boundary
331  const G4Step* theLastStep = track->GetStep();
332  G4StepPoint* theLastPostStepPoint = NULL;
333  if(theLastStep) theLastPostStepPoint = theLastStep->GetPostStepPoint();
334  if( theLastPostStepPoint &&
335  ( theLastPostStepPoint->GetStepStatus() == fWorldBoundary //particle left world volume
336  //|| theLastPostStepPoint->GetStepStatus() == fGeomBoundary
337  )
338  ) {
339  simStatus.set(G4PARTICLE_SIM_LEFT_DETECTOR);
340  }
341 
342  if(track->GetKineticEnergy() <= 0.) {
343  simStatus.set(G4PARTICLE_SIM_STOPPED);
344  }
345 
347  for( auto* handler : this->m_userHandlers )
348  handler->end(track, m_currTrack);
349 
350  // These are candidate tracks with a probability to be stored due to their properties:
351  // - primary particle
352  // - hits created
353  // - secondaries
354  // - above energy threshold
355  // - to be kept due to creator process
356  // - to be kept due to user information of type 'Geant4ParticleInformation' stored in the G4Track
357  //
358  Geant4ParticleInformation* track_info =
359  dynamic_cast<Geant4ParticleInformation*>(track->GetUserInformation());
360  if ( !mask.isNull() || track_info ) {
361  m_equivalentTracks[g4_id] = g4_id;
362  ParticleMap::iterator ip = m_particleMap.find(g4_id);
363  if ( mask.isSet(G4PARTICLE_PRIMARY) ) {
364  ph.dump2(outputLevel()-1,name(),"Add Primary",h.id(),ip!=m_particleMap.end());
365  }
366  // Create a new MC particle from the current track information saved in the pre-tracking action
367  Particle* part = 0;
368  if ( ip==m_particleMap.end() ) part = m_particleMap[g4_id] = new Particle();
369  else part = (*ip).second;
370  if ( track_info ) {
371  mask.set(G4PARTICLE_KEEP_USER);
372  part->extension.reset(track_info->release());
373  }
374  part->get_data(m_currTrack);
375  }
376  else {
377  // These are tracks without any special properties.
378  //
379  // We will not store them on the record, but have to memorise the
380  // track identifier in order to restore the history for the created hits.
381  int pid = m_currTrack.g4Parent;
382  m_equivalentTracks[g4_id] = pid;
383  // Need to find the last stored particle and OR this particle's mask
384  // with the mask of the last stored particle
385  auto iend = m_equivalentTracks.end(), iequiv=m_equivalentTracks.end();
386  ParticleMap::iterator ip;
387  for(ip=m_particleMap.find(pid); ip == m_particleMap.end(); ip=m_particleMap.find(pid)) {
388  if (iequiv=m_equivalentTracks.find(pid); iequiv == iend) break; // ERROR
389  pid = (*iequiv).second;
390  }
391  if ( ip != m_particleMap.end() )
392  (*ip).second->reason |= track_reason;
393  else
394  ph.dumpWithVertex(outputLevel()+3,name(),"FATAL: No real particle parent present");
395  }
396 
397  if(track->GetTrackStatus() == fSuspend) {
398  m_haveSuspended = true;
399  //track is already in particle map, we pick it up from there in begin again
400  if(m_particleMap.find(g4_id) != m_particleMap.end()) return;
401  //track is not already stored, keep it in special map
402  auto iPart = m_suspendedPM.emplace(g4_id, new Particle());
403  (iPart.first->second)->get_data(m_currTrack);
404  return; // we trust that we eventually return to this function with another status and go on then
405  }
406 
407 }
408 
410 void Geant4ParticleHandler::beginEvent(const G4Event* event) {
412  info("+++ Event %d Begin event action. Access event related information.",event->GetEventID());
414  m_globalParticleID = interaction->nextPID();
415  m_particleMap.clear();
416  m_equivalentTracks.clear();
418  for( auto* h : this->m_userHandlers )
419  h->begin(event);
420 }
421 
423 void Geant4ParticleHandler::dumpMap(const char* tag) const {
424  const std::string& n = name();
425  Geant4ParticleHandle::header4(INFO,n,tag);
426  for(ParticleMap::const_iterator iend=m_particleMap.end(), i=m_particleMap.begin(); i!=iend; ++i) {
427  Geant4ParticleHandle((*i).second).dump4(INFO,n,tag);
428  }
429 }
430 
432 void Geant4ParticleHandler::endEvent(const G4Event* event) {
433  int count = 0;
434  int level = outputLevel();
435  do {
436  if ( level <= VERBOSE ) dumpMap("Particle ");
437  debug("+++ Iteration:%d Tracks:%d Equivalents:%d",++count,m_particleMap.size(),m_equivalentTracks.size());
438  } while( recombineParents() > 0 );
439 
440  if ( level <= VERBOSE ) dumpMap( "Recombined");
441  // Rebase the simulated tracks, so that they fit to the generator particles
443  if ( level <= VERBOSE ) dumpMap( "Rebased ");
444  // Consistency check....
447  for( auto* h : this->m_userHandlers )
448  h->end(event);
450 
451  // Now export the data to the final record.
454  m_primaryMap = 0;
455  clear();
456 }
457 
461  TrackEquivalents equivalents, orgParticles;
462  ParticleMap finalParticles;
463  ParticleMap::const_iterator ipar, iend, i;
464  int count;
465 
467  ParticleMap& pm = interaction->particles;
468 
469  // (1.0) Copy the pre-defined particle mapping for the simulated tracks
470  // It is assumed the mapping is ZERO based without holes.
471  for(count = 0, iend=pm.end(), i=pm.begin(); i!=iend; ++i) {
472  Particle* p = (*i).second;
473  orgParticles[p->id] = p->id;
474  finalParticles[p->id] = p;
475  if ( p->id > count ) count = p->id;
476  if ( (p->reason&G4PARTICLE_PRIMARY) != G4PARTICLE_PRIMARY ) {
477  p->addRef();
478  }
479  }
480  // (1.1) Define the new particle mapping for the simulated tracks
481  for(++count, iend=m_particleMap.end(), i=m_particleMap.begin(); i!=iend; ++i) {
482  Particle* p = (*i).second;
483  if ( (p->reason&G4PARTICLE_PRIMARY) != G4PARTICLE_PRIMARY ) {
484  //if ( orgParticles.find(p->id) == orgParticles.end() ) {
485  orgParticles[p->id] = count;
486  finalParticles[count] = p;
487  p->id = count;
488  ++count;
489  }
490  }
491  // (2) Re-evaluate the corresponding geant4 track equivalents using the new mapping
492  for(TrackEquivalents::iterator ie=m_equivalentTracks.begin(),ie_end=m_equivalentTracks.end(); ie!=ie_end; ++ie) {
493  int g4_equiv = (*ie).first;
494  while( (ipar=m_particleMap.find(g4_equiv)) == m_particleMap.end() ) {
495  TrackEquivalents::const_iterator iequiv = m_equivalentTracks.find(g4_equiv);
496  if ( iequiv == ie_end ) {
497  break; // ERROR !! Will be handled by printout below because ipar==end()
498  }
499  g4_equiv = (*iequiv).second;
500  }
501  TrackEquivalents::mapped_type equiv = (*ie).second;
502  if ( ipar != m_particleMap.end() ) {
503  Geant4ParticleHandle p = (*ipar).second;
504  equivalents[(*ie).first] = p->id; // requires (1) to be filled properly!
505  const G4ParticleDefinition* def = p.definition();
506  int pdg = int(std::abs(def->GetPDGEncoding())+0.1);
507  if ( pdg != 0 && pdg<36 && !(pdg > 10 && pdg < 17) && pdg != 22 ) {
508  error("+++ ERROR: Geant4 particle for track:%d last known is:%d -- is gluon or quark!",equiv,g4_equiv);
509  }
510  pdg = int(std::abs(p->pdgID)+0.1);
511  if ( pdg != 0 && pdg<36 && !(pdg > 10 && pdg < 17) && pdg != 22 ) {
512  error("+++ ERROR(2): Geant4 particle for track:%d last known is:%d -- is gluon or quark!",equiv,g4_equiv);
513  }
514  }
515  else {
516  error("+++ No Equivalent particle for track:%d last known is:%d",equiv,g4_equiv);
517  }
518  }
519 
520  // (3) Compute the particle's parents and daughters.
521  // Replace the original Geant4 track with the
522  // equivalent particle still present in the record.
523  // Note:
524  // We rely here on the ordering of the particles accoding to their
525  // Processing by Geant4 to establish mother daughter relationships.
526  // == > use finalParticles map and NOT m_particleMap.
527  int equiv_id = -1;
528  for( auto& part : finalParticles ) {
529  auto& p = part.second;
530  if ( p->g4Parent > 0 ) {
531  TrackEquivalents::iterator iequ = equivalents.find(p->g4Parent);
532  if ( iequ != equivalents.end() ) {
533  equiv_id = (*iequ).second;//equivalents[p->g4Parent];
534  if ( (ipar=finalParticles.find(equiv_id)) != finalParticles.end() ) {
535  Particle* q = (*ipar).second;
536  bool prim = (p->reason&G4PARTICLE_PRIMARY) == G4PARTICLE_PRIMARY;
537  // We assume that the mother daughter relationship
538  // is filled by the event readers!
539  if ( !prim ) {
540  p->parents.insert(q->id);
541  }
542  if ( !p->parents.empty() ) {
543  int parent_id = (*p->parents.begin());
544  if ( parent_id == q->id )
545  q->daughters.insert(p->id);
546  else if ( !prim )
547  error("+++ Inconsistency in equivalent record! Parent: %d Daughter:%d",q->id, p->id);
548  }
549  else {
550  error("+++ Inconsistency in parent relashionship: %d NO parent!", p->id);
551  }
552  continue;
553  }
554  }
555  error("+++ Inconsistency in particle record: Geant4 parent %d "
556  "of particle %d not in record of final particles!",
557  p->g4Parent,p->id);
558  }
559  }
560 #if 0
561  for(iend=finalParticles.end(), i=finalParticles.begin(); i!=iend; ++i) {
562  Particle* p = (*i).second;
563  if ( p->g4Parent > 0 ) {
564  int parent_id = (*p->parents.begin());
565  if ( (ipar=finalParticles.find(parent_id)) != finalParticles.end() ) {
566  Particle* q = (*ipar).second;
567  // Generator particles have a proper history.
568  // We only deal with particles, which are not of MC origin.
569  //p->parents.insert(q->id);
570  if ( parent_id == q->id )
571  q->daughters.insert(p->id);
572  else
573  error("+++ Inconsistency in equivalent record! Parent: %d Daughter:%d",q->id, p->id);
574  continue;
575  }
576  error("+++ Inconsistency in particle record: Geant4 parent %d "
577  "of particle %d not in record of final particles!",
578  p->g4Parent,p->id);
579  }
580  }
581 #endif
582  m_equivalentTracks = std::move(equivalents);
583  m_particleMap = std::move(finalParticles);
584 }
585 
587 bool Geant4ParticleHandler::defaultKeepParticle(Particle& particle) {
588  PropertyMask mask(particle.reason);
589  bool secondaries = mask.isSet(G4PARTICLE_HAS_SECONDARIES);
590  bool tracker_track = mask.isSet(G4PARTICLE_CREATED_TRACKER_HIT);
591  bool calo_track = mask.isSet(G4PARTICLE_CREATED_CALORIMETER_HIT);
592  bool hits_produced = mask.isSet(G4PARTICLE_CREATED_HIT);
593  bool low_energy = !mask.isSet(G4PARTICLE_ABOVE_ENERGY_THRESHOLD);
594 
596  if ( mask.isNull() || (secondaries && low_energy && !hits_produced) ) {
597  return true;
598  }
600  else if ( !hits_produced && low_energy ) {
601  return true;
602  }
604  else if ( !tracker_track && calo_track && low_energy ) {
605  return true;
606  }
607  else {
608  //printout(INFO,name(),"+++ Track: %d should be kept for no obvious reason....",id);
609  }
610  return false;
611 }
612 
616  std::set<int> remove;
617 
619  for(ParticleMap::reverse_iterator i=m_particleMap.rbegin(); i!=m_particleMap.rend(); ++i) {
620  Particle* p = (*i).second;
621  PropertyMask mask(p->reason);
622  // Allow the user to force the particle handling either by
623  // or the reason mask with G4PARTICLE_KEEP_USER or
624  // to set the reason mask to NULL in order to drop it.
625  //
626  // If the mask entry is set to G4PARTICLE_FORCE_KILL
627  // or is set to NULL, the particle is ALWAYS removed
628  //
629  // Note: This may override all other decisions!
630  bool remove_me = false;
631  if ( !this->m_userHandlers.empty() ) {
632  for( auto* h : this->m_userHandlers )
633  remove_me |= h->keepParticle(*p);
634  } else {
635  remove_me = defaultKeepParticle(*p);
636  }
637 
638  // Now look at the property mask of the particle
639  if ( mask.isNull() || mask.isSet(G4PARTICLE_FORCE_KILL) ) {
640  remove_me = true;
641  }
642  else if ( mask.isSet(G4PARTICLE_KEEP_USER) ) {
644  mask.set(G4PARTICLE_KEEP_USER);
645  continue;
646  }
647  else if ( mask.isSet(G4PARTICLE_PRIMARY) ) {
649  continue;
650  }
651  else if ( mask.isSet(G4PARTICLE_KEEP_ALWAYS) ) {
652  continue;
653  }
654  else if ( mask.isSet(G4PARTICLE_KEEP_PARENT) ) {
655  //continue;
656  }
657  else if ( mask.isSet(G4PARTICLE_KEEP_PROCESS) ) {
658  if(ParticleMap::iterator ip = m_particleMap.find(p->g4Parent); ip != m_particleMap.end() ) {
659  Particle* parent_part = (*ip).second;
660  PropertyMask parent_mask(parent_part->reason);
661  if ( parent_mask.isSet(G4PARTICLE_ABOVE_ENERGY_THRESHOLD) ) {
662  parent_mask.set(G4PARTICLE_KEEP_PARENT);
663  continue;
664  }
665  }
666  // Low energy stuff. Remove it. Reassign to parent.
667  //remove_me = true;
668  }
669 
671  if ( remove_me ) {
672  int g4_id = (*i).first;
673  remove.insert(g4_id);
674  m_equivalentTracks[g4_id] = p->g4Parent;
675  if(ParticleMap::iterator ip = m_particleMap.find(p->g4Parent); ip != m_particleMap.end() ) {
676  Particle* parent_part = (*ip).second;
677  PropertyMask(parent_part->reason).set(mask.value());
678  parent_part->steps += p->steps;
679  parent_part->secondaries += p->secondaries;
681  for( auto* h : this->m_userHandlers )
682  h->combine(*p, *parent_part);
683  }
684  }
685  }
686  for( int r : remove ) {
687  if( auto ir = m_particleMap.find(r); ir != m_particleMap.end() ) {
688  (*ir).second->release();
689  m_particleMap.erase(ir);
690  }
691  }
692  return int(remove.size());
693 }
694 
697  int num_errors = 0;
698 
700  for(const auto& part : m_particleMap ) {
701  Geant4Particle* particle = part.second;
702  Geant4ParticleHandle p(particle);
703  PropertyMask mask(p->reason);
704  PropertyMask status(p->status);
705  std::set<int>& daughters = p->daughters;
706  ParticleMap::const_iterator j;
707  // For all particles, the set of daughters must be contained in the record.
708  for( int id_dau : daughters ) {
709  if ( j=m_particleMap.find(id_dau); j == m_particleMap.end() ) {
710  ++num_errors;
711  error("+++ Particle:%d Daughter %d is not in particle map!",p->id,id_dau);
712  }
713  }
714  // We assume that particles from the generator have consistent parents
715  // For all other particles except the primaries, the parent must be contained in the record.
716  if ( !mask.isSet(G4PARTICLE_PRIMARY) && !status.anySet(G4PARTICLE_GEN_STATUS) ) {
717  bool in_map = false, in_parent_list = false;
718  int parent_id = -1;
719  if( auto eq_it=m_equivalentTracks.find(p->g4Parent); eq_it != m_equivalentTracks.end() ) {
720  parent_id = (*eq_it).second;
721  in_map = (j=m_particleMap.find(parent_id)) != m_particleMap.end();
722  in_parent_list = p->parents.find(parent_id) != p->parents.end();
723  }
724  if ( !in_map || !in_parent_list ) {
725  char parent_list[1024];
726  parent_list[0] = 0;
727  ++num_errors;
728  p.dumpWithMomentum(ERROR,name(),"INCONSISTENCY");
729  for( int ip : p->parents )
730  ::snprintf(parent_list+strlen(parent_list),sizeof(parent_list)-strlen(parent_list),"%d ",ip);
731  error("+++ Particle:%d Parent %d (G4id:%d) In record:%s In parent list:%s [%s]",
732  p->id,parent_id,p->g4Parent,yes_no(in_map),yes_no(in_parent_list),parent_list);
733  }
734  }
735  }
736 
737  if ( num_errors > 0 ) {
738  except("+++ Consistency check failed. Found %d problems.",num_errors);
739  }
740 }
741 
743  for( auto& part : m_particleMap ) {
744  auto* p = part.second;
745  if( !p->parents.empty() ) {
746  PropertyMask mask(p->status);
747  //if the particle did not go to geant4 none of these flags is set
748  // we shouldn't set the vertex bit in this case.
749  if(not mask.anySet(G4PARTICLE_SIM_CREATED
755  continue;
756  }
757  Geant4Particle *parent(m_particleMap[ *p->parents.begin() ]);
758  const double X( parent->vex - p->vsx );
759  const double Y( parent->vey - p->vsy );
760  const double Z( parent->vez - p->vsz );
761  if( sqrt(X*X + Y*Y + Z*Z) > m_minDistToParentVertex ){
763  }
764  }
765  }
766 }
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