Tracking particles only within a certain volume

I’m trying to write a program tracking particles only within a certain volume (no further tracking once the particles leave the volume). I assumed I could modify the G4UserStackingAction::ClassifyNewTrack(const G4Track* track) function, so that it returns fUrgent only when the volume is correct (returns fKill otherwise). However, somehow the program is shut down upon the execution of /run/beamOn 1 (no error at the compilation or program launching), when I use the following functions:

  1. G4LogicalVolume* volume = track->GetVolume()->GetLogicalVolume();

  2. G4LogicalVolume* volume
    = track->GetStep()->GetPreStepPoint()->GetTouchableHandle()

Q1. Are there any problems with using these functions in G4UserStackingAction::ClassifyNewTrack()?

Q2. Any suggestion for tracking particles only within a certain volume (other than modifying the

For the primary particles, track->GetVolume() will return a nullptr, resulting in a segmentation fault if you try to retrieve the logical volume. So you’d need to filter out the primaries.

However, I’m not sure if stacking action is what you seek. It will be invoked for each new track (new primary, created secondaries), so you could kill secondaries created outside your volume of interest, but it won’t kill the particles (tracks) that are already being simulated, and are escaping your volume. For that you need the granularity of the stepping action.

Thank you so much for the explanation and suggestion.

@anna I was trying to implement what I thought you meant. Somehow I cannot kill the optical photons in the stepping action. Can you please take a look at the following code snippet I inserted to the UserSteppingAction() function?

G4Track* track = step->GetTrack();
G4ParticleDefinition* particleType = track->GetDefinition();

if (particleType == G4OpticalPhoton::OpticalPhotonDefinition()) track->SetTrackStatus(fStopAndKill);

How do you know they are not killed?
I copied your code to extended/optical/OpNovice example, and using /tracking/verbose 1 I can see that all optical photons are killed after the first step.

1 Like

@anna I just looked at the visualization result. Seeing a lot of photons, I assumed they were not killed. However, using the command (/tracking/verbose 1), I can see they are indeed killed after the first step. Thank you so much!

Where do I see the options for SetTrackStatus, e.g. fStopAndKill?

these particle are gamma ,not opticle photon