Simple confirmation of how to use and optimise TrackInformation, TrackingAction and SteppingAction

Hello all,

I hope you’re fine.

Let’s say I want to keep information about a G4Track, that will be created when the particle (here, a gamma) is created, and updated at the end of each step.

I just want confirmation of how to do that, so that I keep consistent results and that I don’t slow down a lot the simulations. What I do is creating a class derived from G4VUserTrackInformation, that I attach to the G4Track* track in PreUserTrackingAction with :

  if(track->GetDefinition() != G4Gamma::Gamma()) {
    return;
  }
  auto info = dynamic_cast<MyTrackInfo*>(track->GetUserInformation());
  if(!info) {
    auto nonConstTrack = const_cast<G4Track*>(track);

    info = new MyTrackInfo();
    nonConstTrack->SetUserInformation(info);
  }

Then, I update it with a class derived from G4UserSteppingAction, where I write in UserSteppingAction(const G4Step* step) :

  if(!step) return;

  const G4Track* track = step->GetTrack();
  if(!track) return;
  
  auto nonConstTrack = const_cast<G4Track*>(track);
  auto info = dynamic_cast<JumpingTrackInfo*>(nonConstTrack->GetUserInformation());

  if(!info) {
    return;
  }

  // AND THEN, SOME CODE MODIFIYING info ATTRIBUTES

For information :
Geant4 Version: 11.2.2
Operating System: Windows and Linux

Do I do it correctly? Also, is there any optimisation advices you can give me (for this part), as my UserSteppingAction will be executed each step?

Thanks a lot,


It looks to me like you have most of the optimizations right there. You could delay the dynamic_cast<>, but that won’t win you anything: dynamic_cast<>(0) returns 0 with no extra work; it only takes extra work if there’s an actual downcast to be done.

In principle, the null step and null track checks could be skipped, relying on Geant4 do “do the right thing.” But having them in place is much better than letting a segfault tell you there’s a problem.

1 Like