From ff6717fea501aec40a853e4c37bf262b055ce062 Mon Sep 17 00:00:00 2001
From: Florian Uhlig <f.uhlig@gsi.de>
Date: Wed, 31 Mar 2021 10:28:01 +0200
Subject: [PATCH] Set random seed when running a simulation

Up to now the ROOT random number generator was always initialised with the
same default value. In some cases this gives strange results when doing
large scale simulations with several jobs.
To solve the problem TRandom is now initialised with the value 0 which uses a
seed value based on the system time with a granularity of 100ns.
This granularity should be good enough to have different seed values even if
several jobs start a similar times on the batch farm.
A setter was added to allow to set the seed value explicitly from a macro,
refs #1395, #2066
---
 sim/transport/steer/CbmTransport.cxx |  4 ++++
 sim/transport/steer/CbmTransport.h   | 14 +++++++++++++-
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/sim/transport/steer/CbmTransport.cxx b/sim/transport/steer/CbmTransport.cxx
index c79d77955a..b16713eb3d 100644
--- a/sim/transport/steer/CbmTransport.cxx
+++ b/sim/transport/steer/CbmTransport.cxx
@@ -33,6 +33,7 @@
 #include "TGeant4.h"
 #include "TGeoManager.h"
 #include "TPythia6Decayer.h"
+#include "TRandom.h"
 #include "TROOT.h"
 #include "TStopwatch.h"
 #include "TString.h"
@@ -469,6 +470,9 @@ void CbmTransport::Run(Int_t nEvents) {
   // --- Timer
   TStopwatch timer;
 
+  // --- Set the global random seed
+  gRandom->SetSeed(fRandomSeed);
+
   // --- Check presence of required requisites
   if (fOutFileName.IsNull())
     LOG(fatal) << GetName() << ": No output file specified!";
diff --git a/sim/transport/steer/CbmTransport.h b/sim/transport/steer/CbmTransport.h
index 5e927912d9..8ed7564a35 100644
--- a/sim/transport/steer/CbmTransport.h
+++ b/sim/transport/steer/CbmTransport.h
@@ -304,6 +304,16 @@ public:
                            Double_t phiMax = 2. * TMath::Pi());
 
 
+    /** @brief Set global random seed value
+     ** @param seedValue
+     **
+     ** This function allows to set the global seed value used
+     ** by ROOTs random number generator TRandom
+     **/
+  void SetRandomSeed(const ULong_t seedValue) {
+    fRandomSeed = seedValue;
+  }
+
   /** @brief Enable smearing of event vertex in x and y.
      ** @param choice  If kTRUE(default), smearing is enabled.
      **
@@ -381,6 +391,8 @@ private:
   CbmGeant3Settings* fGeant3Settings {nullptr};  //!
   CbmGeant4Settings* fGeant4Settings {nullptr};  //!
 
+  ULong_t fRandomSeed {0};
+
   /** @brief Event generator initialisation **/
   void InitEventGenerator();
 
@@ -403,7 +415,7 @@ private:
   /** @brief Create and register the setup modules **/
   void RegisterSetup();
 
-  ClassDef(CbmTransport, 3);
+  ClassDef(CbmTransport, 4);
 };
 
 #endif /* CBMTRANSPORT_H */
-- 
GitLab