From 3650114b2126c5c4fec2fa6282a61f2faa610cf2 Mon Sep 17 00:00:00 2001 From: Jan Kieseler Date: Tue, 27 Aug 2024 09:36:30 +0200 Subject: [PATCH] better seeding --- bind/G4Calo.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/bind/G4Calo.py b/bind/G4Calo.py index 68a90ec..7f5a7a0 100644 --- a/bind/G4Calo.py +++ b/bind/G4Calo.py @@ -154,7 +154,6 @@ def _run_mini_batch( seed = int(batch_seed + counter) print(f"Running mini batch with seed {seed}") - G4System.init(cw, seed) #counter gives random seed offset df = G4System.run_batch(nEvents, particleSpec, minEnergy_GeV, maxEnergy_GeV,"") @@ -189,15 +188,21 @@ def run_batch( nevents = [nEventsPerCore if i < nCores - 1 else nEventsLastCore for i in range(nCores)] - batch_seed = int(time.time()) #this is seconds - # make sure that the seed is different for next run. This is not perfect but should be good enough - # given the course takes a week this should be sufficient (10^7 seconds ~ 4 months) - time.sleep(1) - batch_seed = batch_seed % 10000000 - print(f"Batch seed: {batch_seed}") + #the used seeds are stored in the home directory in a file called .seeds.txt + # check if file exists, if so, read last seed. If not create it + if os.path.exists(os.path.expanduser("~/.g4calo_seeds.txt")): + with open(os.path.expanduser("~/.g4calo_seeds.txt"), "r") as f: + seed = int(f.read()) + else: + seed = 0 + with open(os.path.expanduser("~/.g4calo_seeds.txt"), "w") as f: + f.write(str(seed + nCores)) + + seed += 1 + print(f"Batch seed: {seed}") #use a multiprocessing pool to run the mini batches in parallel with multiprocessing.Pool(nCores) as pool: - dfs = pool.starmap(_run_mini_batch_silent, [(gd, nevents[i], particleSpec, minEnergy_GeV, maxEnergy_GeV, batch_seed, i) for i in range(nCores)]) + dfs = pool.starmap(_run_mini_batch_silent, [(gd, nevents[i], particleSpec, minEnergy_GeV, maxEnergy_GeV, seed, i) for i in range(nCores)]) alldf = pd.concat(dfs) alldf.reset_index(drop=True, inplace=True) @@ -212,18 +217,19 @@ def run_batch( def _fill_event(gd : GeometryDescriptor, particleSpec: str, - energy: float): + energy: float, + seed: int = -1): from G4Calo import __G4System G4System = __G4System() - G4System.init(gd, -1) + G4System.init(gd, seed) G4System.run_batch(1, particleSpec, energy, energy,"") return gd def display_event(gd : GeometryDescriptor, particleSpec: str, energy: float, - logE = False, renderer=None): + logE = False, renderer=None, seed = -1): #run _fill_event in forked mode using 1-core multiprocessing to avoid G4 singletons to interfere with multiprocessing.Pool(1) as pool: