Plot primary energy spectrum

In your UserEventAction, you can get the information about the generated primary in each event via G4Event::GetPrimaryVertex(G4int i) (use G4Event::GetNumberOfPrimaryVertex() to get the count and loop). From each vertex, you can get the individual primary particles from G4PrimaryVertex::GetPrmary(G4int i) and G4PrimaryVertex::GetNumberOfParticle().

If you used GPS to throw a single particle per event, you could skip the looping and just get index 0 in each case, but then you’d have to modify your code if you decided later to throw multiple primaries.

You could also make use of your SteppingAction or TrackingAction to look for tracks with ParentID==0, and get the initial energy that way. The method above has the advantage that it works any time during your event; tracks are deleted as soon as they finish tracking, so you can’t get back to them later.

1 Like