Change (not randomly) the energy of the primary particles for each event

Hello,

I would like to change (not randomly) the energy of the primary particles for each event. To do this I have tried to get the event ID at the PrimaryGeneratorAction and use if-else statements. The code compiles and starts successfully; however, it crashes as soon as I generate the first event. Below, I paste part of the code I am using (for brevity, I present only two energies):

void B4PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)
{

int eID = 0;
const G4Event* evt = G4RunManager::GetRunManager()->GetCurrentEvent();
eID = evt->GetEventID();

if(eID = 1){
fParticleGun->SetParticleEnergy(1MeV);
G4ParticleDefinition
particleDefinition
= G4ParticleTable::GetParticleTable()->FindParticle(“gamma”);
fParticleGun->SetParticleDefinition(particleDefinition);
}
else{
fParticleGun->SetParticleEnergy(1GeV);
G4ParticleDefinition
particleDefinition
= G4ParticleTable::GetParticleTable()->FindParticle(“gamma”);
fParticleGun->SetParticleDefinition(particleDefinition);
}

fParticleGun->SetParticleMomentumDirection(G4ThreeVector(xD,yD,zD));

fParticleGun->SetParticlePosition(G4ThreeVector(xR, yR, z0));

fParticleGun->GeneratePrimaryVertex(anEvent);
}

Possibly, my approach is not the most efficient but I have a MATLAB code to automatically write all the if-else statements with the appropriate energies.

Hope my question and problem is understandable.

Thanks in advance,

Ivan Munoz

1 Like

I have a similar issue. Would like to access the eventID in the PrimaryGenerator.

void MyPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)
{
const G4Event* evt = G4RunManager::GetRunManager()->GetCurrentEvent();
eID = evt->GetEventID();
}

but the above generates a segfault on the very first event… I suspect this may have to do with the first call to PrimaryGenerator, i.e. prior to RunAction but I have no way to prove/understand that.
I have limited C++ skills. Thank you!

Current event is set only after being generated:

void G4RunManager::ProcessOneEvent(G4int i_event) {
  currentEvent = GenerateEvent(i_event);
}

But you can get the event ID directly from the input argument (it is set by the run manager before passing it to your implementation of G4VUserPrimaryGeneratorAction):

void MyPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) {
   int eID = anEvent->GetEventID();
}