Re-run the same event by controlling the seeds

Hello,

After storing information from each event of a simulation in a ROOT file, I would be interested in finding an event I am interested in and resimulating it in exactly the same way, in order to store more information (or inspect it graphically).

Let’s say event 63 in my simulation catches my eye.

The following lines:

CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine());
CLHEP::HepRandom::setTheSeed(124);

allow me to control the seed at the beginning of the run.

However if I check the engine at each event, with:

CLHEP::HepRandom::showEngineStatus();

eventually, event 63 (for example) will show:

--------- Ranecu engine status ---------
Initial seed (index) = 124
Current couple of seeds = 277819502, 115827135


How can I use the couple of seeds to run a simulation with only one event that is identical to event 63? I would imagine going to the BeginOfEventAction, and settings the couple of seeds, but I don’t understand how to do that.

Many thanks

There are two useful commands CLHEP::HepRandom::getTheEngine()->saveStatus() and CLHEP::HepRandom::getTheEngine()->restoreStatus().

I used this code some time ago to ensure I rerun the same events. It’s already in the primary generator action, not the event action, as it involved random numbers.

#include <filesystem>

void PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)
{
  std::string fileName = "random/event_"+std::to_string(anEvent->GetEventID())+".rndm.stat";
  if (std::filesystem::exists(fileName)) {
    CLHEP::HepRandom::getTheEngine()->restoreStatus (fileName.c_str());
  } else {
    CLHEP::HepRandom::getTheEngine()->saveStatus (fileName.c_str());
  }
[...]
}
1 Like

you may have a look to example TestEm4. See README and rndmSeed.mac

1 Like

Thanks for all the answers! I also managed to solve it by storing

fEventSeedIndex = CLHEP::HepRandom::getTheSeed();
fEventSeed1 = CLHEP::HepRandom::getTheSeeds()[0];
fEventSeed2 = CLHEP::HepRandom::getTheSeeds()[1];

At the BeginOfEventAction, the first time I run the script.

When I later want to run the very same event, I do:

std::vector< G4int > fEventSeeds{fEventSeed1, fEventSeed2};
setTheSeeds(fEventSeeds,fEventSeedIndex);

In BeginOfEventAction, in the same code block (before the random seed gets called).

As far as I know this works only if you have set the RanecuEngine at the beginning of your script:

CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine());

Thanks, this is also useful. I ended up using the getTheSeeds method instead because I was interested in storing this information in a compact way as a series of ints in a root ntuple, but your suggestion will be also useful for other applications I was working on!