Counting number of particles in SD

Hello Dear Experts,
In my simulation i have ion beam bumping target. I want to count number of some product particles. i.e. neutrons. To do so in my SD class i check if i look at neutron steps and check trackId. If trackid differs from previous i add +1 to particle number in event. Is it correct to do so?

That’s a good, efficient way to do what you want, for neutrons.

It’s not completely safe in general, because it is possible for a track to be “paused”, other tracks to be processed, and then the original “paused” track to be picked up again. This is how the Cherenkov radiation process works – it avoids putting a large number of photon tracks on the stack.

To deal with that situation, you would need to keep a record of all the track ID’s you’ve seen in the event (std::set<G4int> is an easy way to do this), then at the end of the event clear the list and start over.

Thank you. I will take this in consideration to avoid mistakes in future!

Thinking about it, you could use the std::set<G4int> option under all conditions all conditions for simple track counting.

In your SD, look at the input G4Step and see if it meets your criteria (whatever they are). If it does, do insert(step->GetTrack()->GetTrackID()) on your std::set<> object. If that action has already been done, it’ll just fall through.

At the end of the event, std::set<>::size() tells you how many tracks you saw. Put that into your N-tuple or histogram or whatever, and clear the object for the next event.