DD4hep  1.30.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  m_ownsParticles(false), m_userHandler(0), m_primaryMap(0)
49 {
50  InstanceCount::increment(this);
51  //generatorAction().adopt(this);
52  eventAction().callAtBegin(this, &Geant4ParticleHandler::beginEvent);
53  eventAction().callAtEnd(this, &Geant4ParticleHandler::endEvent);
54  trackingAction().callAtFinal(this, &Geant4ParticleHandler::end,CallbackSequence::FRONT);
55  trackingAction().callUpFront(this, &Geant4ParticleHandler::begin,CallbackSequence::FRONT);
56  steppingAction().call(this, &Geant4ParticleHandler::step);
57  m_globalParticleID = 0;
58  declareProperty("PrintEndTracking", m_printEndTracking = false);
59  declareProperty("PrintStartTracking", m_printStartTracking = false);
60  declareProperty("KeepAllParticles", m_keepAll = false);
61  declareProperty("SaveProcesses", m_processNames);
62  declareProperty("MinimalKineticEnergy", m_kinEnergyCut = 100e0*CLHEP::MeV);
63  declareProperty("MinDistToParentVertex", m_minDistToParentVertex = 2.2e-14*CLHEP::mm);//default tolerance for g4ThreeVector isNear
64  m_needsControl = true;
65 }
66 
68 Geant4ParticleHandler::Geant4ParticleHandler()
70  m_ownsParticles(false), m_userHandler(0), m_primaryMap(0)
71 {
72  m_globalParticleID = 0;
73  declareProperty("PrintEndTracking", m_printEndTracking = false);
74  declareProperty("PrintStartTracking", m_printStartTracking = false);
75  declareProperty("KeepAllParticles", m_keepAll = false);
76  declareProperty("SaveProcesses", m_processNames);
77  declareProperty("MinimalKineticEnergy", m_kinEnergyCut = 100e0*CLHEP::MeV);
78  declareProperty("MinDistToParentVertex", m_minDistToParentVertex = 2.2e-14*CLHEP::mm);//default tolerance for g4ThreeVector isNear
79  m_needsControl = true;
80 }
81 
83 Geant4ParticleHandler::~Geant4ParticleHandler() {
84  clear();
85  detail::releasePtr(m_userHandler);
87 }
88 
91  return *this;
92 }
93 
96  if ( action ) {
97  if ( !m_userHandler ) {
98  if ( Geant4UserParticleHandler* h = dynamic_cast<Geant4UserParticleHandler*>(action) ) {
99  m_userHandler = h;
101  return true;
102  }
103  except("Cannot add an invalid user particle handler object [Invalid-object-type].");
104  }
105  except("Cannot add an user particle handler object [Object-exists].");
106  }
107  except("Cannot add an invalid user particle handler object [NULL-object].");
108  return false;
109 }
110 
113  detail::releaseObjects(m_particleMap);
114  m_particleMap.clear();
115  // m_suspendedPM should already be empty and cleared...
116  assert(m_suspendedPM.empty() && "There was something wrong with the particle record treatment, please open a bug report!");
117  m_equivalentTracks.clear();
118 }
119 
121 void Geant4ParticleHandler::mark(const G4Track* track, int reason) {
122  if ( track ) {
123  if ( reason != 0 ) {
124  PropertyMask(m_currTrack.reason).set(reason);
125  return;
126  }
127  }
128  except("Cannot mark the G4Track if the pointer is invalid!");
129 }
130 
132 void Geant4ParticleHandler::mark(const G4Step* step_value, int reason) {
133  if ( step_value ) {
134  mark(step_value->GetTrack(),reason);
135  return;
136  }
137  except("Cannot mark the G4Track if the step-pointer is invalid!");
138 }
139 
141 void Geant4ParticleHandler::mark(const G4Step* step_value) {
142  if ( step_value ) {
143  mark(step_value->GetTrack());
144  return;
145  }
146  except("Cannot mark the G4Track if the step-pointer is invalid!");
147 }
148 
150 void Geant4ParticleHandler::mark(const G4Track* track) {
152  mask.set(G4PARTICLE_CREATED_HIT);
154  // If yes, flag it, because it is a candidate for removal.
155  G4LogicalVolume* vol = track->GetVolume()->GetLogicalVolume();
156  G4VSensitiveDetector* g4 = vol->GetSensitiveDetector();
157  Geant4ActionSD* sd = dynamic_cast<Geant4ActionSD*>(g4);
158  std::string typ = sd ? sd->sensitiveType() : std::string();
159  if ( typ == "calorimeter" )
161  else if ( typ == "tracker" )
163  else // Assume by default "tracker"
165 
166  //Geant4ParticleHandle(&m_currTrack).dump4(outputLevel(),vol->GetName(),"hit created by particle");
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  if ( m_userHandler ) {
177  m_userHandler->generate(event, this);
178  }
179 }
180 
182 void Geant4ParticleHandler::step(const G4Step* step_value, G4SteppingManager* mgr) {
183  typedef std::vector<const G4Track*> _Sec;
184  ++m_currTrack.steps;
186  //
187  // Tracks below the energy threshold are NOT stored.
188  // If these tracks produce hits or are selected due to another signature,
189  // this criterium will anyhow take precedence.
190  //
191  const _Sec* sec=step_value->GetSecondaryInCurrentStep();
192  if ( not sec->empty() ) {
194  }
195  }
197  if ( m_userHandler ) {
198  m_userHandler->step(step_value, mgr, m_currTrack);
199  }
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  if ( m_userHandler ) {
307  }
308 }
309 
311 void Geant4ParticleHandler::end(const G4Track* track) {
312  Geant4TrackHandler h(track);
314  const int g4_id = h.id();
315 
316  int track_reason = m_currTrack.reason;
318  // Update vertex end point and final momentum
319  G4ThreeVector mom = track->GetMomentum();
320  const G4ThreeVector& pos = track->GetPosition();
321  ph->pex = mom.x();
322  ph->pey = mom.y();
323  ph->pez = mom.z();
324  ph->vex = pos.x();
325  ph->vey = pos.y();
326  ph->vez = pos.z();
327 
328  // Set the simulator status bits
329  PropertyMask simStatus(m_currTrack.status);
330 
331  // check if the last step ended on the worldVolume boundary
332  const G4Step* theLastStep = track->GetStep();
333  G4StepPoint* theLastPostStepPoint = NULL;
334  if(theLastStep) theLastPostStepPoint = theLastStep->GetPostStepPoint();
335  if( theLastPostStepPoint &&
336  ( theLastPostStepPoint->GetStepStatus() == fWorldBoundary //particle left world volume
337  //|| theLastPostStepPoint->GetStepStatus() == fGeomBoundary
338  )
339  ) {
340  simStatus.set(G4PARTICLE_SIM_LEFT_DETECTOR);
341  }
342 
343  if(track->GetKineticEnergy() <= 0.) {
344  simStatus.set(G4PARTICLE_SIM_STOPPED);
345  }
346 
348  if ( m_userHandler ) {
349  m_userHandler->end(track, m_currTrack);
350  }
351 
352  // These are candidate tracks with a probability to be stored due to their properties:
353  // - primary particle
354  // - hits created
355  // - secondaries
356  // - above energy threshold
357  // - to be kept due to creator process
358  // - to be kept due to user information of type 'Geant4ParticleInformation' stored in the G4Track
359  //
360  Geant4ParticleInformation* track_info =
361  dynamic_cast<Geant4ParticleInformation*>(track->GetUserInformation());
362  if ( !mask.isNull() || track_info ) {
363  m_equivalentTracks[g4_id] = g4_id;
364  ParticleMap::iterator ip = m_particleMap.find(g4_id);
365  if ( mask.isSet(G4PARTICLE_PRIMARY) ) {
366  ph.dump2(outputLevel()-1,name(),"Add Primary",h.id(),ip!=m_particleMap.end());
367  }
368  // Create a new MC particle from the current track information saved in the pre-tracking action
369  Particle* part = 0;
370  if ( ip==m_particleMap.end() ) part = m_particleMap[g4_id] = new Particle();
371  else part = (*ip).second;
372  if ( track_info ) {
373  mask.set(G4PARTICLE_KEEP_USER);
374  part->extension.reset(track_info->release());
375  }
376  part->get_data(m_currTrack);
377  }
378  else {
379  // These are tracks without any special properties.
380  //
381  // We will not store them on the record, but have to memorise the
382  // track identifier in order to restore the history for the created hits.
383  int pid = m_currTrack.g4Parent;
384  m_equivalentTracks[g4_id] = pid;
385  // Need to find the last stored particle and OR this particle's mask
386  // with the mask of the last stored particle
387  auto iend = m_equivalentTracks.end(), iequiv=m_equivalentTracks.end();
388  ParticleMap::iterator ip;
389  for(ip=m_particleMap.find(pid); ip == m_particleMap.end(); ip=m_particleMap.find(pid)) {
390  if (iequiv=m_equivalentTracks.find(pid); iequiv == iend) break; // ERROR
391  pid = (*iequiv).second;
392  }
393  if ( ip != m_particleMap.end() )
394  (*ip).second->reason |= track_reason;
395  else
396  ph.dumpWithVertex(outputLevel()+3,name(),"FATAL: No real particle parent present");
397  }
398 
399  if(track->GetTrackStatus() == fSuspend) {
400  m_haveSuspended = true;
401  //track is already in particle map, we pick it up from there in begin again
402  if(m_particleMap.find(g4_id) != m_particleMap.end()) return;
403  //track is not already stored, keep it in special map
404  auto iPart = m_suspendedPM.emplace(g4_id, new Particle());
405  (iPart.first->second)->get_data(m_currTrack);
406  return; // we trust that we eventually return to this function with another status and go on then
407  }
408 
409 }
410 
412 void Geant4ParticleHandler::beginEvent(const G4Event* event) {
414  info("+++ Event %d Begin event action. Access event related information.",event->GetEventID());
416  m_globalParticleID = interaction->nextPID();
417  m_particleMap.clear();
418  m_equivalentTracks.clear();
420  if ( m_userHandler ) {
421  m_userHandler->begin(event);
422  }
423 }
424 
426 void Geant4ParticleHandler::dumpMap(const char* tag) const {
427  const std::string& n = name();
428  Geant4ParticleHandle::header4(INFO,n,tag);
429  for(ParticleMap::const_iterator iend=m_particleMap.end(), i=m_particleMap.begin(); i!=iend; ++i) {
430  Geant4ParticleHandle((*i).second).dump4(INFO,n,tag);
431  }
432 }
433 
435 void Geant4ParticleHandler::endEvent(const G4Event* event) {
436  int count = 0;
437  int level = outputLevel();
438  do {
439  if ( level <= VERBOSE ) dumpMap("Particle ");
440  debug("+++ Iteration:%d Tracks:%d Equivalents:%d",++count,m_particleMap.size(),m_equivalentTracks.size());
441  } while( recombineParents() > 0 );
442 
443  if ( level <= VERBOSE ) dumpMap( "Recombined");
444  // Rebase the simulated tracks, so that they fit to the generator particles
446  if ( level <= VERBOSE ) dumpMap( "Rebased ");
447  // Consistency check....
450  if ( m_userHandler ) {
451  m_userHandler->end(event);
452  }
454 
455  // Now export the data to the final record.
458  m_primaryMap = 0;
459  clear();
460 }
461 
465  TrackEquivalents equivalents, orgParticles;
466  ParticleMap finalParticles;
467  ParticleMap::const_iterator ipar, iend, i;
468  int count;
469 
471  ParticleMap& pm = interaction->particles;
472 
473  // (1.0) Copy the pre-defined particle mapping for the simulated tracks
474  // It is assumed the mapping is ZERO based without holes.
475  for(count = 0, iend=pm.end(), i=pm.begin(); i!=iend; ++i) {
476  Particle* p = (*i).second;
477  orgParticles[p->id] = p->id;
478  finalParticles[p->id] = p;
479  if ( p->id > count ) count = p->id;
480  if ( (p->reason&G4PARTICLE_PRIMARY) != G4PARTICLE_PRIMARY ) {
481  p->addRef();
482  }
483  }
484  // (1.1) Define the new particle mapping for the simulated tracks
485  for(++count, iend=m_particleMap.end(), i=m_particleMap.begin(); i!=iend; ++i) {
486  Particle* p = (*i).second;
487  if ( (p->reason&G4PARTICLE_PRIMARY) != G4PARTICLE_PRIMARY ) {
488  //if ( orgParticles.find(p->id) == orgParticles.end() ) {
489  orgParticles[p->id] = count;
490  finalParticles[count] = p;
491  p->id = count;
492  ++count;
493  }
494  }
495  // (2) Re-evaluate the corresponding geant4 track equivalents using the new mapping
496  for(TrackEquivalents::iterator ie=m_equivalentTracks.begin(),ie_end=m_equivalentTracks.end(); ie!=ie_end; ++ie) {
497  int g4_equiv = (*ie).first;
498  while( (ipar=m_particleMap.find(g4_equiv)) == m_particleMap.end() ) {
499  TrackEquivalents::const_iterator iequiv = m_equivalentTracks.find(g4_equiv);
500  if ( iequiv == ie_end ) {
501  break; // ERROR !! Will be handled by printout below because ipar==end()
502  }
503  g4_equiv = (*iequiv).second;
504  }
505  TrackEquivalents::mapped_type equiv = (*ie).second;
506  if ( ipar != m_particleMap.end() ) {
507  Geant4ParticleHandle p = (*ipar).second;
508  equivalents[(*ie).first] = p->id; // requires (1) to be filled properly!
509  const G4ParticleDefinition* def = p.definition();
510  int pdg = int(std::abs(def->GetPDGEncoding())+0.1);
511  if ( pdg != 0 && pdg<36 && !(pdg > 10 && pdg < 17) && pdg != 22 ) {
512  error("+++ ERROR: Geant4 particle for track:%d last known is:%d -- is gluon or quark!",equiv,g4_equiv);
513  }
514  pdg = int(std::abs(p->pdgID)+0.1);
515  if ( pdg != 0 && pdg<36 && !(pdg > 10 && pdg < 17) && pdg != 22 ) {
516  error("+++ ERROR(2): Geant4 particle for track:%d last known is:%d -- is gluon or quark!",equiv,g4_equiv);
517  }
518  }
519  else {
520  error("+++ No Equivalent particle for track:%d last known is:%d",equiv,g4_equiv);
521  }
522  }
523 
524  // (3) Compute the particle's parents and daughters.
525  // Replace the original Geant4 track with the
526  // equivalent particle still present in the record.
527  // Note:
528  // We rely here on the ordering of the particles accoding to their
529  // Processing by Geant4 to establish mother daughter relationships.
530  // == > use finalParticles map and NOT m_particleMap.
531  int equiv_id = -1;
532  for( auto& part : finalParticles ) {
533  auto& p = part.second;
534  if ( p->g4Parent > 0 ) {
535  TrackEquivalents::iterator iequ = equivalents.find(p->g4Parent);
536  if ( iequ != equivalents.end() ) {
537  equiv_id = (*iequ).second;//equivalents[p->g4Parent];
538  if ( (ipar=finalParticles.find(equiv_id)) != finalParticles.end() ) {
539  Particle* q = (*ipar).second;
540  bool prim = (p->reason&G4PARTICLE_PRIMARY) == G4PARTICLE_PRIMARY;
541  // We assume that the mother daughter relationship
542  // is filled by the event readers!
543  if ( !prim ) {
544  p->parents.insert(q->id);
545  }
546  if ( !p->parents.empty() ) {
547  int parent_id = (*p->parents.begin());
548  if ( parent_id == q->id )
549  q->daughters.insert(p->id);
550  else if ( !prim )
551  error("+++ Inconsistency in equivalent record! Parent: %d Daughter:%d",q->id, p->id);
552  }
553  else {
554  error("+++ Inconsistency in parent relashionship: %d NO parent!", p->id);
555  }
556  continue;
557  }
558  }
559  error("+++ Inconsistency in particle record: Geant4 parent %d "
560  "of particle %d not in record of final particles!",
561  p->g4Parent,p->id);
562  }
563  }
564 #if 0
565  for(iend=finalParticles.end(), i=finalParticles.begin(); i!=iend; ++i) {
566  Particle* p = (*i).second;
567  if ( p->g4Parent > 0 ) {
568  int parent_id = (*p->parents.begin());
569  if ( (ipar=finalParticles.find(parent_id)) != finalParticles.end() ) {
570  Particle* q = (*ipar).second;
571  // Generator particles have a proper history.
572  // We only deal with particles, which are not of MC origin.
573  //p->parents.insert(q->id);
574  if ( parent_id == q->id )
575  q->daughters.insert(p->id);
576  else
577  error("+++ Inconsistency in equivalent record! Parent: %d Daughter:%d",q->id, p->id);
578  continue;
579  }
580  error("+++ Inconsistency in particle record: Geant4 parent %d "
581  "of particle %d not in record of final particles!",
582  p->g4Parent,p->id);
583  }
584  }
585 #endif
586  m_equivalentTracks = std::move(equivalents);
587  m_particleMap = std::move(finalParticles);
588 }
589 
591 bool Geant4ParticleHandler::defaultKeepParticle(Particle& particle) {
592  PropertyMask mask(particle.reason);
593  bool secondaries = mask.isSet(G4PARTICLE_HAS_SECONDARIES);
594  bool tracker_track = mask.isSet(G4PARTICLE_CREATED_TRACKER_HIT);
595  bool calo_track = mask.isSet(G4PARTICLE_CREATED_CALORIMETER_HIT);
596  bool hits_produced = mask.isSet(G4PARTICLE_CREATED_HIT);
597  bool low_energy = !mask.isSet(G4PARTICLE_ABOVE_ENERGY_THRESHOLD);
598 
600  if ( mask.isNull() || (secondaries && low_energy && !hits_produced) ) {
601  return true;
602  }
604  else if ( !hits_produced && low_energy ) {
605  return true;
606  }
608  else if ( !tracker_track && calo_track && low_energy ) {
609  return true;
610  }
611  else {
612  //printout(INFO,name(),"+++ Track: %d should be kept for no obvious reason....",id);
613  }
614  return false;
615 }
616 
620  std::set<int> remove;
621 
623  for(ParticleMap::reverse_iterator i=m_particleMap.rbegin(); i!=m_particleMap.rend(); ++i) {
624  Particle* p = (*i).second;
625  PropertyMask mask(p->reason);
626  // Allow the user to force the particle handling either by
627  // or the reason mask with G4PARTICLE_KEEP_USER or
628  // to set the reason mask to NULL in order to drop it.
629  //
630  // If the mask entry is set to G4PARTICLE_FORCE_KILL
631  // or is set to NULL, the particle is ALWAYS removed
632  //
633  // Note: This may override all other decisions!
634  bool remove_me = m_userHandler ? m_userHandler->keepParticle(*p) : defaultKeepParticle(*p);
635 
636  // Now look at the property mask of the particle
637  if ( mask.isNull() || mask.isSet(G4PARTICLE_FORCE_KILL) ) {
638  remove_me = true;
639  }
640  else if ( mask.isSet(G4PARTICLE_KEEP_USER) ) {
642  mask.set(G4PARTICLE_KEEP_USER);
643  continue;
644  }
645  else if ( mask.isSet(G4PARTICLE_PRIMARY) ) {
647  continue;
648  }
649  else if ( mask.isSet(G4PARTICLE_KEEP_ALWAYS) ) {
650  continue;
651  }
652  else if ( mask.isSet(G4PARTICLE_KEEP_PARENT) ) {
653  //continue;
654  }
655  else if ( mask.isSet(G4PARTICLE_KEEP_PROCESS) ) {
656  if(ParticleMap::iterator ip = m_particleMap.find(p->g4Parent); ip != m_particleMap.end() ) {
657  Particle* parent_part = (*ip).second;
658  PropertyMask parent_mask(parent_part->reason);
659  if ( parent_mask.isSet(G4PARTICLE_ABOVE_ENERGY_THRESHOLD) ) {
660  parent_mask.set(G4PARTICLE_KEEP_PARENT);
661  continue;
662  }
663  }
664  // Low energy stuff. Remove it. Reassign to parent.
665  //remove_me = true;
666  }
667 
669  if ( remove_me ) {
670  int g4_id = (*i).first;
671  remove.insert(g4_id);
672  m_equivalentTracks[g4_id] = p->g4Parent;
673  if(ParticleMap::iterator ip = m_particleMap.find(p->g4Parent); ip != m_particleMap.end() ) {
674  Particle* parent_part = (*ip).second;
675  PropertyMask(parent_part->reason).set(mask.value());
676  parent_part->steps += p->steps;
677  parent_part->secondaries += p->secondaries;
679  if ( m_userHandler ) {
680  m_userHandler->combine(*p, *parent_part);
681  }
682  }
683  }
684  }
685  for( int r : remove ) {
686  if( auto ir = m_particleMap.find(r); ir != m_particleMap.end() ) {
687  (*ir).second->release();
688  m_particleMap.erase(ir);
689  }
690  }
691  return int(remove.size());
692 }
693 
696  int num_errors = 0;
697 
699  for(const auto& part : m_particleMap ) {
700  Geant4Particle* particle = part.second;
701  Geant4ParticleHandle p(particle);
702  PropertyMask mask(p->reason);
703  PropertyMask status(p->status);
704  std::set<int>& daughters = p->daughters;
705  ParticleMap::const_iterator j;
706  // For all particles, the set of daughters must be contained in the record.
707  for( int id_dau : daughters ) {
708  if ( j=m_particleMap.find(id_dau); j == m_particleMap.end() ) {
709  ++num_errors;
710  error("+++ Particle:%d Daughter %d is not in particle map!",p->id,id_dau);
711  }
712  }
713  // We assume that particles from the generator have consistent parents
714  // For all other particles except the primaries, the parent must be contained in the record.
715  if ( !mask.isSet(G4PARTICLE_PRIMARY) && !status.anySet(G4PARTICLE_GEN_STATUS) ) {
716  bool in_map = false, in_parent_list = false;
717  int parent_id = -1;
718  if( auto eq_it=m_equivalentTracks.find(p->g4Parent); eq_it != m_equivalentTracks.end() ) {
719  parent_id = (*eq_it).second;
720  in_map = (j=m_particleMap.find(parent_id)) != m_particleMap.end();
721  in_parent_list = p->parents.find(parent_id) != p->parents.end();
722  }
723  if ( !in_map || !in_parent_list ) {
724  char parent_list[1024];
725  parent_list[0] = 0;
726  ++num_errors;
727  p.dumpWithMomentum(ERROR,name(),"INCONSISTENCY");
728  for( int ip : p->parents )
729  ::snprintf(parent_list+strlen(parent_list),sizeof(parent_list)-strlen(parent_list),"%d ",ip);
730  error("+++ Particle:%d Parent %d (G4id:%d) In record:%s In parent list:%s [%s]",
731  p->id,parent_id,p->g4Parent,yes_no(in_map),yes_no(in_parent_list),parent_list);
732  }
733  }
734  }
735 
736  if ( num_errors > 0 ) {
737  except("+++ Consistency check failed. Found %d problems.",num_errors);
738  }
739 }
740 
742  for( auto& part : m_particleMap ) {
743  auto* p = part.second;
744  if( !p->parents.empty() ) {
745  Geant4Particle *parent(m_particleMap[ *p->parents.begin() ]);
746  const double X( parent->vex - p->vsx );
747  const double Y( parent->vey - p->vsy );
748  const double Z( parent->vez - p->vsz );
749  if( sqrt(X*X + Y*Y + Z*Z) > m_minDistToParentVertex ){
751  }
752  }
753  }
754 }
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::Geant4UserParticleHandler::keepParticle
virtual bool keepParticle(Particle &particle)
Callback to be answered if the particle MUST be kept during recombination step.
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::Geant4UserParticleHandler::generate
virtual void generate(G4Event *event, Geant4ParticleHandler *handler)
Event generation action callback.
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:526
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
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::Geant4UserParticleHandler::step
virtual void step(const G4Step *step, G4SteppingManager *mgr, Particle &particle)
User stepping callback.
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::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::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
dd4hep::sim::Geant4UserParticleHandler::combine
virtual void combine(Particle &to_be_deleted, Particle &remaining_parent)
Callback when parent should be combined.
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::Geant4UserParticleHandler::end
virtual void end(const G4Event *event)
Post-event action callback.
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:386
dd4hep::sim::Geant4Particle::daughters
Particles daughters
The list of daughters of this MC particle.
Definition: Geant4Particle.h:140
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:116
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::m_userHandler
Geant4UserParticleHandler * m_userHandler
User action pointer.
Definition: Geant4ParticleHandler.h:111
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::Geant4Action::addRef
long addRef()
Increase reference count.
Definition: Geant4Action.cpp:71
dd4hep::sim
Namespace for the Geant4 based simulation part of the AIDA detector description toolkit.
Definition: Geant4Output2EDM4hep.cpp:49
PropertyMask
dd4hep::detail::ReferenceBitMask< int > PropertyMask
Definition: HepMC3EventReader.cpp:37
dd4hep::sim::Geant4UserParticleHandler::begin
virtual void begin(const G4Event *event)
Pre-event action callback.
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: Energy cut below which particles are not collected, but assigned to the parent.
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
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:375
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