How can I count all optical photons generated in an event?


G4UserStackingAction can be utilized not only for stack management but also for counting particles in an event. Here is an example. In your StackingAction, you will see all primaries and secondaries at your ClassifyNewTrack method. Here you can examine whether the new track is optical photon, thus you can count all of them in the current event. You will be informed whenever the "urgent" stack becomes empty via your NewStage method. If you do not use "waiting" stack, it means the "end of event". Don't forget to reset your counter at PrepareNewEvent method.

A sample implementation of G4UserStackingAction is the following.

Header file (T01StackingAction.hh)


#ifndef T01StackingAction_H
#define T01StackingAction_H 1

#include "G4UserStackingAction.hh"

class T01StackingAction : public G4UserStackingAction
{
  public:
    T01StackingAction();
    virtual ~T01StackingAction();

  public:
    virtual G4ClassificationOfNewTrack ClassifyNewTrack(const G4Track* aTrack);
    virtual void NewStage();
    virtual void PrepareNewEvent();

  private:
    G4int gammaCounter;
};

#endif


Source file (T01StackingAction.cc)

#include "T01StackingAction.hh"
#include "G4ios.hh"
#include "G4ParticleDefinition.hh"
#include "G4ParticleTypes.hh"
#include "G4Track.hh"

T01StackingAction::T01StackingAction()
: gammaCounter(0)
{;}

T01StackingAction::~T01StackingAction()
{;}

G4ClassificationOfNewTrack
T01StackingAction::ClassifyNewTrack(const G4Track * aTrack)
{
  if(aTrack->GetDefinition()==G4OpticalPhoton::OpticalPhotonDefinition())
  { // particle is optical photon
    if(aTrack->GetParentID()>0)
    { // particle is secondary
      gammaCounter++;
    }
  }

  return fUrgent;
}

void T01StackingAction::NewStage()
{
  G4cout << "Number of gamma produces in this event : "
         << gammaCounter << G4endl;
}

void T01StackingAction::PrepareNewEvent()
{ gammaCounter = 0; }

    

Once you create above, you have to instanciate this class object in your main() and set it to your RunManager.


Makoto Asai