ATLAS Offline Software
AtDSFMTGenSvc.cxx
Go to the documentation of this file.
1 /*
2  Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration
3 */
4 
5 #include "GaudiKernel/ISvcLocator.h"
6 #include "GaudiKernel/IIncidentSvc.h"
7 #include "GaudiKernel/Incident.h"
8 #include "GaudiKernel/DataIncident.h"
9 #include "GaudiKernel/ServiceHandle.h"
10 
11 #include "interpretSeeds.h"
12 #include "AtDSFMTGenSvc.h"
13 #include "crc_combine.h"
14 
16 #include "CLHEP/Random/RandGauss.h"
17 
18 #include <cassert>
19 #include <iostream>
20 
21 /*FIXME temporarily needed for old seeding scheme*/
23 
24 using namespace std;
25 
27 AtDSFMTGenSvc::AtDSFMTGenSvc(const std::string& name,ISvcLocator* svc)
28  : base_class(name,svc),
29  m_reseedingOffsets(),
30  m_engines(), m_engines_copy() {
31  // Set Default values
32  m_default_seed1 = 3591;
33  m_default_seed2 = 2309736;
34  m_PYTHIA_default_seed1 = 93453591;
35  m_PYTHIA_default_seed2 = 73436;
36  m_HERWIG_default_seed1 = 355391;
37  m_HERWIG_default_seed2 = 97336;
38 }
39 
40 
43 {
44  engineIter i(m_engines.begin()), e(m_engines.end());
45  while (i != e) delete (i++)->second;
46 }
47 
49 {
51  ("Initializing " << name() << "\n INITIALISING RANDOM NUMBER STREAMS. ");
52 
54  ServiceHandle<IIncidentSvc> pIncSvc("IncidentSvc", name());
55 
56  // set up the incident service:
57  ATH_CHECK( pIncSvc.retrieve() );
58 
59  //start listening to "EndEvent"
60  static const int PRIORITY = 100;
61  pIncSvc->addListener(this, "EndEvent", PRIORITY);
62  pIncSvc->addListener(this, "AfterReseedIncident", PRIORITY);
63 
64  //and to BeginEvent if we are reseeding
65  if (m_eventReseed) {
66  ATH_MSG_INFO ("will be reseeded for every event");
67  pIncSvc->addListener(this, "BeginEvent", PRIORITY);
68  pIncSvc->addListener(this, "ReseedIncident", PRIORITY);
69  }
70  pIncSvc.release().ignore();
71 
72  if (m_read_from_file) {
73  // Read from a file
74  ifstream infile( m_file_to_read.value().c_str() );
75  if ( !infile ) {
76  ATH_MSG_ERROR (" Unable to open: " << m_file_to_read.value());
77  return StatusCode::FAILURE;
78  } else {
79  std::string buffer;
80  while (std::getline(infile, buffer)) {
81  string stream;
82  std::vector<uint32_t> seeds;
83  //split the space-separated string in 3 words:
84  if (interpretSeeds(buffer, stream, seeds)) {
85  msg (MSG::DEBUG)
86  << " INITIALISING " << stream << " stream with seeds ";
87  for (std::vector<uint32_t>::const_iterator i = seeds.begin(); i != seeds.end(); ++i){
88  // The state returned is a set of 32-bit numbers.
89  // On 64-bit platforms, though, the vector holds 64-bit ints.
90  // For the first word, one gets garbage in the high 32 bits.
91  // (This is because the crc32 routine used in clhep
92  // to hash the engine names doesn't mask down to 32 bits.)
93  // So mask off the garbage so that we get consistent results
94  // across platforms.
95  msg() << ((*i) & 0xffffffffu) << " ";
96  }
97  msg() << " read from file " << m_file_to_read.value() << endmsg;
98  if (CreateStream(seeds, stream)) {
100  << stream << " stream initialized succesfully" <<endmsg;
101  } else {
102  msg(MSG::ERROR)
103  << stream << " stream FAILED to initialize" <<endmsg;
104  return StatusCode::FAILURE;
105  }
106  } else {
107  msg(MSG::ERROR)
108  << "bad line\n" << buffer
109  << "\n in input file " << m_file_to_read.value() << endmsg;
110  return StatusCode::FAILURE;
111  }
112  }
113 
114  }
115  }
116  // Create the various streams according to user's request
117  for (const auto& i : m_streams_seeds.value()) {
118  string stream;
119  uint32_t seed1, seed2, offset(0);
120  //parse the stream property string
122  ATH_MSG_VERBOSE("Seeds property: stream " << stream
123  << " seeds " << seed1 << ' ' << seed2
124  << ", reseeding offset " << offset);
125  } else {
126  ATH_MSG_ERROR("bad Seeds property\n" << i);
127  return StatusCode::FAILURE;
128  }
129 
130  // Check if stream already generated (e.g. from reading a file)
131  bool not_found(true);
132  if ( number_of_streams() != 0 ) {
134  while (sf != end() && (not_found=((*sf).first != stream))) ++sf;
135  }
136 
137  if (not_found) {
139  (" INITIALISING " << stream << " stream with seeds "
140  << seed1 << " " << seed2);
141  CreateStream(seed1, seed2, stream);
142  if (m_eventReseed) {
143  m_reseedingOffsets.insert(std::make_pair(stream, offset));
144  // apply the offset we just inserted
145  ATH_MSG_DEBUG("Applying reseeding offset " << offset <<
146  " to stream " << stream);
147  this->setOnDefinedSeeds(seed1, seed2, stream);
148  }
149  }
150 
151  }
152  return StatusCode::SUCCESS;
153 }
154 
155 void AtDSFMTGenSvc::handle(const Incident &inc) {
156  ATH_MSG_DEBUG (" Handle EndEvent ");
157 
158  if ( inc.type() == "EndEvent" ||
159  inc.type() == "AfterReseedIncident" )
160  {
161  m_engines_copy.clear();
162  engineConstIter iE(begin()), eE(end());
163  while(iE != eE) {
164  CLHEP::HepRandomEngine* engine = GetEngine(iE->first);
165  std::vector<unsigned long> v = engine->put();
166  std::vector<uint32_t> tseeds(v.size());
167  for (size_t i=0; i<v.size(); ++i) {
168  // The state returned is a set of 32-bit numbers.
169  // On 64-bit platforms, though, the vector holds 64-bit ints.
170  // For the first word, one gets garbage in the high 32 bits.
171  // (This is because the crc32 routine used in clhep
172  // to hash the engine names doesn't mask down to 32 bits.)
173  // Mask off the garbage to get consistent results
174  // across platforms.
175  tseeds[i] = (v[i] & 0xffffffffu);
176  }
177  m_engines_copy.insert(std::make_pair(iE->first, tseeds));
178  ++iE;
179  }
180 
181  print();
182  } else if (inc.type() == "BeginEvent") {
183  ATH_MSG_DEBUG (" Handle BeginEvent ");
184  EventContext context = inc.context();
185  const EventIDBase& ei = context.eventID();
186  //clear static RandGauss cache (generates two numbers per call to shoot()
188  //loop over generator streams, combining the stream name to the hash
189  vector<string>::const_iterator i(m_reseedStreamNames.begin());
190  vector<string>::const_iterator e(m_reseedStreamNames.end());
191  //by default (when no streams are specified in streamNames, seed all
192  //streams
193  if (i == e) {
194  if (!(this->setAllOnDefinedSeeds(ei.event_number(),
195  ei.run_number())))
196  throw GaudiException("can not reseed all streams ", name(), StatusCode::FAILURE);
197  } else {
198  while (i != e) {
199  const string& strName(*i++);
200  if (0 == this->setOnDefinedSeeds(ei.event_number(),
201  ei.run_number(),
202  strName)) {
203  throw GaudiException(string("can not reseed stream ") + strName,
204  name(), StatusCode::FAILURE);
205  } else {
206  msg() << MSG::VERBOSE << "Reseeded stream " << strName
207  << " for random service " << endmsg;
208  }
209  }
210  }
211  }
212  else if (inc.type() == "ReseedIncident") {
213  typedef ContextIncident<std::pair<unsigned,unsigned> > Ctxt;
214  const Ctxt* incident = dynamic_cast<const Ctxt*>(&inc);
215  const std::pair<unsigned,unsigned>& data = incident->tag();
216  //clear static RandGauss cache (generates two numbers per call to shoot()
218  //loop over generator streams, combining the stream name to the hash
219  vector<string>::const_iterator i(m_reseedStreamNames.begin());
220  vector<string>::const_iterator e(m_reseedStreamNames.end());
221  //by default (when no streams are specified in streamNames, seed all
222  //streams
223  if (i == e) {
224  if (!(this->setAllOnDefinedSeeds(data.first,
225  data.second)))
226  throw GaudiException("can not reseed all streams ", name(), StatusCode::FAILURE);
227  } else {
228  while (i != e) {
229  const string& strName(*i++);
230  if (0 == this->setOnDefinedSeeds(data.first,
231  data.second,
232  strName)) {
233  throw GaudiException(string("can not reseed stream ") + strName,
234  name(), StatusCode::FAILURE);
235  } else {
236  msg() << MSG::VERBOSE << "Reseeded stream " << strName
237  << " for random service " << endmsg;
238  }
239  }
240  }
241  }
242 }
243 
245 {
246  ATH_MSG_INFO (" FINALISING ");
247 
248  if (m_save_to_file) {
249  // Write the status of the Service to file
250  std::ofstream outfile( m_file_to_write.value().c_str() );
251  if ( !outfile ) {
252  ATH_MSG_ERROR ("error: unable to open: " << m_file_to_write.value());
253  } else {
254  for (std::map<std::string, std::vector<uint32_t> >::const_iterator i = m_engines_copy.begin();
255  i != m_engines_copy.end();
256  ++i) {
257  outfile << (*i).first << " ";
258  for (std::vector<uint32_t>::const_iterator j = (*i).second.begin(); j !=(*i).second.end(); ++j){
259  outfile << (*j) << " ";
260  }
261  outfile << endl;
262  }
263  ATH_MSG_DEBUG (" wrote seeds to " << m_file_to_write.value() );
264  }
265  }
266  return StatusCode::SUCCESS;
267 }
268 
269 CLHEP::HepRandomEngine* AtDSFMTGenSvc::GetEngine ( const std::string& streamName )
270 {
271  engineConstIter citer = m_engines.find(streamName);
272  if ( citer == m_engines.end() )
273  {
274  m_engines.insert( engineValType( streamName, new CLHEP::dSFMTEngine() ) );
275  SetStreamSeeds( streamName );
276  }
277 
278  engineIter iter = m_engines.find(streamName);
279  return (CLHEP::HepRandomEngine*)(*iter).second;
280 }
281 
283 {
284  long seeds[3] = { (long)seed1, (long)seed2, 0 };
285  const long* s = seeds;
286  engineConstIter citer = m_engines.find(streamName);
287  if ( citer == m_engines.end() )
288  m_engines.insert(engineValType(streamName, new CLHEP::dSFMTEngine(s)));
289  engineIter iter = m_engines.find(streamName);
290  ((*iter).second)->setSeeds(s, 0);
291 }
292 
293 bool AtDSFMTGenSvc::CreateStream(const std::vector<uint32_t>& seeds, const std::string& streamName)
294 {
295  engineConstIter citer = m_engines.find(streamName);
296  if ( citer == m_engines.end() ) m_engines.insert(engineValType(streamName, new CLHEP::dSFMTEngine() ) );
297  engineIter iter = m_engines.find(streamName);
298  std::vector<unsigned long> longSeeds(seeds.size());
299  for (size_t i=0; i<seeds.size(); ++i) longSeeds[i]=seeds[i];
300  return (((*iter).second)->getState( longSeeds ));
301 }
302 
303 void AtDSFMTGenSvc::SetStreamSeeds( const std::string& StreamName )
304 {
305  uint32_t seed1;
306  uint32_t seed2;
307  if (StreamName == "PYTHIA")
308  {
309  seed1 = m_PYTHIA_default_seed1;
310  seed2 = m_PYTHIA_default_seed2;
311  }
312  else if (StreamName == "HERWIG")
313  {
314  seed1 = m_HERWIG_default_seed1;
315  seed2 = m_HERWIG_default_seed2;
316  }
317  else
318  {
319  seed1 = m_default_seed1;
320  seed2 = m_default_seed2;
321  }
323  (" INITIALISING " << StreamName << " stream with DEFAULT seeds "
324  << seed1 << " " << seed2);
325 
326  long seeds[3] = { (long)seed1, (long)seed2, 0 };
327  const long* s = seeds;
328  engineIter iter = m_engines.find(StreamName);
329  ((*iter).second)->setSeeds(s,0);
330 }
331 
332 void AtDSFMTGenSvc::print(const std::string& StreamName )
333 {
334  engineConstIter citer = m_engines.find(StreamName);
335  if ( citer == m_engines.end() ) {
336  ATH_MSG_WARNING (" Stream = " << StreamName << " NOT FOUND");
337  } else {
338  std::vector<unsigned long> v = ((*citer).second)->put();
339  msg(MSG::DEBUG) << " Stream = " << StreamName << " ";
340  for (std::vector<unsigned long>::const_iterator i = v.begin(); i != v.end(); ++i){
341  // The state returned is a set of 32-bit numbers.
342  // On 64-bit platforms, though, the vector holds 64-bit ints.
343  // For the first word, one gets garbage in the high 32 bits.
344  // (This is because the crc32 routine used in clhep
345  // to hash the engine names doesn't mask down to 32 bits.)
346  // So mask off the garbage so that we get consistent results
347  // across platforms.
348  msg() << ((*i) & 0xffffffffu) << " ";
349  }
350  msg() << endmsg;
351  }
352 }
353 
354 void AtDSFMTGenSvc::print ( void )
355 {
356  for (engineConstIter i = m_engines.begin(); i != m_engines.end(); ++i)
357  print( (*i).first );
358 }
359 
361  const std::string& streamName)
362 {
363  uint32_t theHash(eventNumber);
364  map<string, uint32_t>::const_iterator citer(m_reseedingOffsets.find(streamName));
365  bool hasOffset(citer != m_reseedingOffsets.end() && 0 != citer->second);
366  if (hasOffset) theHash=crc_combine(theHash, citer->second);
367 
368  theHash=crc_combine(theHash, runNumber);
369  ATH_MSG_VERBOSE( "Reseeding stream " << streamName
370  << " with eventNumber " << eventNumber
371  << " runNumber " << runNumber);
372  if (hasOffset) ATH_MSG_VERBOSE("Applied offset " << citer->second);
373  return this->setOnDefinedSeeds(theHash, streamName);
374 }
375 
376 CLHEP::HepRandomEngine* AtDSFMTGenSvc::setOnDefinedSeeds(uint32_t theSeed,
377  const std::string& streamName){
378  engineConstIter citer = m_engines.find(streamName);
380  if ( citer == m_engines.end() )
381  m_engines.insert(engineValType(streamName, new CLHEP::dSFMTEngine() ) );
382 
383  engineIter iter = m_engines.find(streamName);
384  theSeed=crc_combine(theSeed, streamName);
385  ATH_MSG_DEBUG("Reseeding stream " << streamName << " with " << theSeed);
386  CLHEP::HepRandomEngine* eng = (*iter).second;
387  eng->setSeed( theSeed, 0 );
388  return (CLHEP::HepRandomEngine*)eng;
389 }
390 
391 bool
393 {
394  bool allOK(true);
395  engineIter i(m_engines.begin()), e(m_engines.end());
396  while (i!=e &&
397  (allOK=(0 != this->setOnDefinedSeeds(eventNumber,
398  runNumber,
399  (*i++).first)))) {
400  /*empty*/
401  }
402 
403  return allOK;
404 }
405 
406 bool
408  bool allOK(true);
409  engineIter i(m_engines.begin()), e(m_engines.end());
410  while (i!=e &&
411  (allOK=(0 != this->setOnDefinedSeeds(theSeed, (*i++).first)))) {
412  /*empty*/
413  }
414  return allOK;
415 }
python.SystemOfUnits.second
int second
Definition: SystemOfUnits.py:120
dSFMTEngine.h
AtDSFMTGenSvc::AtDSFMTGenSvc
AtDSFMTGenSvc(const std::string &name, ISvcLocator *svc)
Standard Constructor.
Definition: AtDSFMTGenSvc.cxx:27
data
char data[hepevt_bytes_allocation_ATLAS]
Definition: HepEvt.cxx:11
CLHEP::dSFMTEngine
Definition: dSFMTEngine.h:31
AtDSFMTGenSvc::engineIter
engineMap::iterator engineIter
Definition: AtDSFMTGenSvc.h:63
AtDSFMTGenSvc::m_PYTHIA_default_seed2
long m_PYTHIA_default_seed2
Definition: AtDSFMTGenSvc.h:131
python.SystemOfUnits.s
int s
Definition: SystemOfUnits.py:131
AtDSFMTGenSvc::handle
virtual void handle(const Incident &) override
IIncidentListener implementation. Handles EndEvent incident.
Definition: AtDSFMTGenSvc.cxx:155
run.infile
string infile
Definition: run.py:13
AtDSFMTGenSvc::engineConstIter
engineMap::const_iterator engineConstIter
Definition: AtDSFMTGenSvc.h:64
ATH_MSG_INFO
#define ATH_MSG_INFO(x)
Definition: AthMsgStreamMacros.h:31
xAOD::uint32_t
setEventNumber uint32_t
Definition: EventInfo_v1.cxx:127
hash_functions.h
AtDSFMTGenSvc::m_default_seed1
long m_default_seed1
Definition: AtDSFMTGenSvc.h:128
PlotCalibFromCool.begin
begin
Definition: PlotCalibFromCool.py:94
AtDSFMTGenSvc::setOnDefinedSeeds
virtual CLHEP::HepRandomEngine * setOnDefinedSeeds(uint32_t theSeed, const std::string &streamName) override
crc_combine.h
ATH_MSG_VERBOSE
#define ATH_MSG_VERBOSE(x)
Definition: AthMsgStreamMacros.h:28
AtDSFMTGenSvc::GetEngine
virtual CLHEP::HepRandomEngine * GetEngine(const std::string &streamName) override
Definition: AtDSFMTGenSvc.cxx:269
AtDSFMTGenSvc::finalize
virtual StatusCode finalize() override
Definition: AtDSFMTGenSvc.cxx:244
AthenaPoolTestWrite.stream
string stream
Definition: AthenaPoolTestWrite.py:12
Trk::u
@ u
Enums for curvilinear frames.
Definition: ParamDefs.h:83
AtDSFMTGenSvc::SetStreamSeeds
void SetStreamSeeds(const std::string &StreamName)
Definition: AtDSFMTGenSvc.cxx:303
genPbPbJobOpt.seed2
seed2
Definition: genPbPbJobOpt.py:57
mergePhysValFiles.end
end
Definition: DataQuality/DataQualityUtils/scripts/mergePhysValFiles.py:93
AtDSFMTGenSvc::m_PYTHIA_default_seed1
long m_PYTHIA_default_seed1
Definition: AtDSFMTGenSvc.h:130
AtDSFMTGenSvc::initialize
virtual StatusCode initialize() override
Definition: AtDSFMTGenSvc.cxx:48
crc_combine
uint32_t crc_combine(uint32_t seed, uint32_t v)
using crc32 for architecture independence in combining the seeds
Definition: AthenaKernel/src/crc_combine.h:11
AtDSFMTGenSvc::print
virtual void print(void) override
createCoolChannelIdFile.buffer
buffer
Definition: createCoolChannelIdFile.py:12
ATH_MSG_ERROR
#define ATH_MSG_ERROR(x)
Definition: AthMsgStreamMacros.h:33
EventInfoWrite.StreamName
string StreamName
Definition: EventInfoWrite.py:28
lumiFormat.i
int i
Definition: lumiFormat.py:92
endmsg
#define endmsg
Definition: AnalysisConfig_Ntuple.cxx:63
EL::StatusCode
::StatusCode StatusCode
StatusCode definition for legacy code.
Definition: PhysicsAnalysis/D3PDTools/EventLoop/EventLoop/StatusCode.h:22
ATH_MSG_DEBUG
#define ATH_MSG_DEBUG(x)
Definition: AthMsgStreamMacros.h:29
AtDSFMTGenSvc::m_HERWIG_default_seed1
long m_HERWIG_default_seed1
Definition: AtDSFMTGenSvc.h:132
ATH_CHECK
#define ATH_CHECK
Definition: AthCheckMacros.h:40
interpretSeeds
bool interpretSeeds(const std::string &buffer, std::string &stream, uint32_t &seed1, uint32_t &seed2, short &luxury, uint32_t &offset)
Definition: interpretSeeds.cxx:28
xAOD::eventNumber
eventNumber
Definition: EventInfo_v1.cxx:124
interpretSeeds.h
Handler::svc
AthROOTErrorHandlerSvc * svc
Definition: AthROOTErrorHandlerSvc.cxx:10
HLT::setFlag
void setFlag(TrigPassFlags *flags, const T *obj, const CONTAINER *container, const std::vector< bool > &flag)
Set the flag at index position.
Definition: TrigPassFlags.h:121
AtDSFMTGenSvc::setAllOnDefinedSeeds
virtual bool setAllOnDefinedSeeds(uint32_t theSeed) override
seed all streams we manage, combining theSeed and the stream names
name
std::string name
Definition: Control/AthContainers/Root/debug.cxx:192
python.PyAthena.v
v
Definition: PyAthena.py:157
DeMoAtlasDataLoss.runNumber
string runNumber
Definition: DeMoAtlasDataLoss.py:64
AthenaPoolExample_Copy.streamName
string streamName
Definition: AthenaPoolExample_Copy.py:39
DiTauMassTools::MaxHistStrategyV2::e
e
Definition: PhysicsAnalysis/TauID/DiTauMassTools/DiTauMassTools/HelperFunctions.h:26
AtDSFMTGenSvc::CreateStream
virtual void CreateStream(uint32_t seed1, uint32_t seed2, const std::string &streamName) override
mapkey::sf
@ sf
Definition: TElectronEfficiencyCorrectionTool.cxx:38
ATH_MSG_WARNING
#define ATH_MSG_WARNING(x)
Definition: AthMsgStreamMacros.h:32
DeMoScan.first
bool first
Definition: DeMoScan.py:534
DEBUG
#define DEBUG
Definition: page_access.h:11
AtDSFMTGenSvc.h
A random number engine manager, based on dSFMT. http://www.math.sci.hiroshima-u.ac....
Muon::print
std::string print(const MuPatSegment &)
Definition: MuonTrackSteering.cxx:28
genPbPbJobOpt.seed1
seed1
Definition: genPbPbJobOpt.py:56
convertTimingResiduals.offset
offset
Definition: convertTimingResiduals.py:71
AtDSFMTGenSvc::~AtDSFMTGenSvc
virtual ~AtDSFMTGenSvc()
Standard Destructor.
Definition: AtDSFMTGenSvc.cxx:42
AtDSFMTGenSvc::m_default_seed2
long m_default_seed2
Definition: AtDSFMTGenSvc.h:129
python.Constants.VERBOSE
int VERBOSE
Definition: Control/AthenaCommon/python/Constants.py:14
PrepareReferenceFile.outfile
outfile
Definition: PrepareReferenceFile.py:42
AtDSFMTGenSvc::engineValType
engineMap::value_type engineValType
Definition: AtDSFMTGenSvc.h:65
python.AutoConfigFlags.msg
msg
Definition: AutoConfigFlags.py:7
AtDSFMTGenSvc::m_HERWIG_default_seed2
long m_HERWIG_default_seed2
Definition: AtDSFMTGenSvc.h:133
ServiceHandle< IIncidentSvc >