Public Member Functions | Private Types | Private Member Functions | Private Attributes | List of all members
testing::SeedTestPolicy Class Reference

Test module for NuRandomService. More...

Inheritance diagram for testing::SeedTestPolicy:
art::EDAnalyzer art::detail::Analyzer art::detail::LegacyModule art::Observer art::ModuleBase

Public Member Functions

 SeedTestPolicy (fhicl::ParameterSet const &pset)
 
virtual void analyze (art::Event const &event) override
 
virtual void endJob () override
 
- Public Member Functions inherited from art::EDAnalyzer
 EDAnalyzer (fhicl::ParameterSet const &pset)
 
template<typename Config >
 EDAnalyzer (Table< Config > const &config)
 
std::string workerType () const
 
- Public Member Functions inherited from art::detail::Analyzer
virtual ~Analyzer () noexcept
 
 Analyzer (fhicl::ParameterSet const &pset)
 
template<typename Config >
 Analyzer (Table< Config > const &config)
 
void doBeginJob ()
 
void doEndJob ()
 
void doRespondToOpenInputFile (FileBlock const &fb)
 
void doRespondToCloseInputFile (FileBlock const &fb)
 
void doRespondToOpenOutputFiles (FileBlock const &fb)
 
void doRespondToCloseOutputFiles (FileBlock const &fb)
 
bool doBeginRun (RunPrincipal &rp, ModuleContext const &mc)
 
bool doEndRun (RunPrincipal &rp, ModuleContext const &mc)
 
bool doBeginSubRun (SubRunPrincipal &srp, ModuleContext const &mc)
 
bool doEndSubRun (SubRunPrincipal &srp, ModuleContext const &mc)
 
bool doEvent (EventPrincipal &ep, ModuleContext const &mc, std::atomic< std::size_t > &counts_run, std::atomic< std::size_t > &counts_passed, std::atomic< std::size_t > &counts_failed)
 
- Public Member Functions inherited from art::Observer
 ~Observer () noexcept
 
 Observer (Observer const &)=delete
 
 Observer (Observer &&)=delete
 
Observeroperator= (Observer const &)=delete
 
Observeroperator= (Observer &&)=delete
 
void registerProducts (ProductDescriptions &, ModuleDescription const &)
 
void fillDescriptions (ModuleDescription const &)
 
std::string const & processName () const
 
bool wantAllEvents () const
 
bool wantEvent (Event const &e)
 
fhicl::ParameterSetID selectorConfig () const
 
Handle< TriggerResultsgetTriggerResults (Event const &e) const
 
- Public Member Functions inherited from art::ModuleBase
virtual ~ModuleBase () noexcept
 
 ModuleBase ()
 
ModuleDescription const & moduleDescription () const
 
void setModuleDescription (ModuleDescription const &)
 
std::array< std::vector< ProductInfo >, NumBranchTypes > const & getConsumables () const
 
void sortConsumables (std::string const &current_process_name)
 
template<typename T , BranchType BT>
ViewToken< T > consumesView (InputTag const &tag)
 
template<typename T , BranchType BT>
ViewToken< T > mayConsumeView (InputTag const &tag)
 

Private Types

using seed_t = testing::NuRandomService::seed_t
 

Private Member Functions

bool isLocalEngine (size_t iEngine) const
 Returns whether the engine associated with the specified index is local. More...
 
seed_t verifySeed (CLHEP::HepRandomEngine &, std::string const &instanceName)
 
seed_t obtainSeed (std::string instanceName="")
 
bool handleSeedServiceException (art::Exception &e)
 Returns whether e is an exception we can handle (and, if so, it handles) More...
 

Private Attributes

std::vector< std::stringinstanceNames
 
std::map< std::string, seed_tstartSeeds
 seeds after the constructor More...
 
unsigned int nExpectedErrors
 number of expected errors More...
 
bool useGenerators
 instanciate and use random number generators More...
 
bool perEventSeeds
 whether we expect different seeds on each event More...
 
std::string const moduleLabel
 configured module label More...
 
unsigned int nErrors = 0
 Number of errors detected so far. More...
 
std::unique_ptr< CLHEP::HepRandomEngine > localEngine
 self-managed More...
 
std::map< std::string, CLHEP::HepRandomEngine * > engines
 

Additional Inherited Members

- Public Types inherited from art::EDAnalyzer
using WorkerType = WorkerT< EDAnalyzer >
 
using ModuleType = EDAnalyzer
 
- Protected Member Functions inherited from art::Observer
 Observer (fhicl::ParameterSet const &config)
 
 Observer (std::vector< std::string > const &paths, fhicl::ParameterSet const &config)
 
detail::ProcessAndEventSelectorsprocessAndEventSelectors ()
 
- Protected Member Functions inherited from art::ModuleBase
ConsumesCollectorconsumesCollector ()
 
template<typename T , BranchType = InEvent>
ProductToken< T > consumes (InputTag const &)
 
template<typename Element , BranchType = InEvent>
ViewToken< Element > consumesView (InputTag const &)
 
template<typename T , BranchType = InEvent>
void consumesMany ()
 
template<typename T , BranchType = InEvent>
ProductToken< T > mayConsume (InputTag const &)
 
template<typename Element , BranchType = InEvent>
ViewToken< Element > mayConsumeView (InputTag const &)
 
template<typename T , BranchType = InEvent>
void mayConsumeMany ()
 

Detailed Description

Test module for NuRandomService.

The test writes on screen the random seeds it gets.

Note that the test does not actually get any random number, unless the useGenerators option is turned on.

Configuration parameters:

Definition at line 65 of file SeedTestPolicy_module.cc.

Member Typedef Documentation

Definition at line 76 of file SeedTestPolicy_module.cc.

Constructor & Destructor Documentation

testing::SeedTestPolicy::SeedTestPolicy ( fhicl::ParameterSet const &  pset)
explicit

Definition at line 110 of file SeedTestPolicy_module.cc.

111  : art::EDAnalyzer(pset)
112  , instanceNames (pset.get<std::vector<std::string>>("instanceNames", {}))
113  , nExpectedErrors(pset.get<unsigned int> ("expectedErrors", 0U))
114  , useGenerators (pset.get<bool> ("useGenerators", true))
115  , perEventSeeds (pset.get<bool> ("perEventSeeds", false))
116  , moduleLabel (pset.get<std::string> ("module_label"))
117 {
118 
119  //
120  // print some configuration information
121  //
122  { // anonymous block
123  mf::LogInfo log("SeedTestPolicy");
124  log << "Construct SeedTestPolicy with "
125  << instanceNames.size() << " engine instances:";
126  for (auto const& instanceName: instanceNames)
127  log << " " << instanceName;
128 
129  } // anonymous block
130 
131  auto* Seeds = &*(art::ServiceHandle<rndm::NuRandomService>());
132 
133  // by default, have at least one, default engine instance
134  if (instanceNames.empty()) instanceNames.push_back("");
135 
136  mf::LogInfo log("SeedTestPolicy"); // cumulative log
137 
138  //
139  // register all the engines, and store their seeds
140  //
141  for (std::string const& instanceName: instanceNames) {
142  seed_t const seed = obtainSeed(instanceName);
143  log << "\nSeed for '" << instanceName << "' is: " << seed;
144  startSeeds.emplace(instanceName, seed);
145  } // for first loop (declaration)
146 
147 
148  //
149  // verify the seed of each instance
150  //
151  for (size_t iEngine = 0; iEngine < instanceNames.size(); ++iEngine) {
152  std::string const& instanceName = instanceNames[iEngine];
153 
154  // This involved condition tree ensures that SeedMaster is queried
155  // for a seed exactly once per instance, no matter what.
156  // This is relevant for the error count.
157  // Out of it, a seed is returned.
159  if (isLocalEngine(iEngine)) {
160  if (useGenerators) {
161  localEngine = std::make_unique<CLHEP::HepJamesRandom>();
162  engines.emplace(instanceName, localEngine.get());
163  try {
164  seed = Seeds->defineEngine(*localEngine, instanceName);
165  }
166  catch(art::Exception& e) {
167  if (!handleSeedServiceException(e)) throw;
168  }
169  mf::LogInfo("SeedTestConstruct")
170  << "Engine instance '" << instanceName
171  << "' will be owned by the test module.";
172  } // if use generators
173  else seed = obtainSeed(instanceName);
174  } // if local
175  else { // if managed by art
176  seed = obtainSeed(instanceName);
177  if (useGenerators) {
178  auto& engine = createEngine(seed, "HepJamesRandom", instanceName);
179  // registration still matters for per-event policies
180  Seeds->defineEngine(engine, instanceName);
181  verifySeed(engine, instanceName);
182  engines.emplace(instanceName, &engine);
183  }
184  } // if ... else
185 
186  // check that the seed returned by the service is still the same
187  seed_t const expectedSeed = startSeeds.at(instanceName);
188  if (seed != expectedSeed) {
190  << "NuRandomService returned different seed values for engine instance '"
191  << instanceName << "': first " << expectedSeed << ", now " << seed
192  << "\n";
193  } // if unexpected seed
194  } // for second loop
195 
196  //
197  // An engine with the following label has already been registered
198  // (it's the one managed by RandomGeneratorService).
199  // Registering another should raise an exception
200  // (incidentally, if useGenerators is false we are trying to register nullptr)
201  //
202  bool bBug = false;
203  try {
204  Seeds->declareEngine(instanceNames.front());
205  bBug = true;
206  }
207  catch(std::exception const& e) {
209  }
210  if (bBug) {
212  << "Registration of local engine with duplicate label"
213  " did not throw an exception";
214  }
215 
216 } // testing::SeedTestPolicy::SeedTestPolicy()
base_engine_t & createEngine(seed_t seed)
std::string string
Definition: nybbler.cc:12
MaybeLogger_< ELseverityLevel::ELsev_info, false > LogInfo
std::string const moduleLabel
configured module label
bool handleSeedServiceException(art::Exception &e)
Returns whether e is an exception we can handle (and, if so, it handles)
unsigned long seed_t
std::vector< std::string > instanceNames
seed_t verifySeed(CLHEP::HepRandomEngine &, std::string const &instanceName)
const double e
bool perEventSeeds
whether we expect different seeds on each event
std::unique_ptr< CLHEP::HepRandomEngine > localEngine
self-managed
static constexpr seed_t InvalidSeed
An invalid seed.
seed_t obtainSeed(std::string instanceName="")
unsigned int nExpectedErrors
number of expected errors
std::map< std::string, seed_t > startSeeds
seeds after the constructor
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
std::map< std::string, CLHEP::HepRandomEngine * > engines
bool isSeedServiceException(std::exception const &e)
Returns whether the exception looks to be from NuRandomService.
bool isLocalEngine(size_t iEngine) const
Returns whether the engine associated with the specified index is local.
bool useGenerators
instanciate and use random number generators
cet::coded_exception< error, detail::translate > exception
Definition: exception.h:33

Member Function Documentation

void testing::SeedTestPolicy::analyze ( art::Event const &  event)
overridevirtual

Implements art::EDAnalyzer.

Definition at line 220 of file SeedTestPolicy_module.cc.

220  {
221 
222  mf::LogVerbatim("SeedTestPolicy")
223  << "SeedTestPolicy::analyze() " << event.id() << " with "
224  << instanceNames.size() << " random engines";
225 
226  if (useGenerators) {
227  for (auto const& instanceName : instanceNames) {
228  //
229  // collect information and resources
230  //
231  seed_t const startSeed = startSeeds.at(instanceName);
232  CLHEP::HepRandomEngine& engine = *engines.at(instanceName);
233 
234  //
235  // check seed (if per event, it should be the opposite)
236  //
237  seed_t const actualSeed = testing::NuRandomService::readSeed(engine);
238  if (perEventSeeds) {
239  if (actualSeed == startSeed) {
240  // this has a ridiculously low chance of begin fortuitous
242  << "per event seed " << actualSeed << " of engine '" << instanceName
243  << "' is the same as at beginning!\n";
244  }
245  }
246  else {
247  if (actualSeed != startSeed) {
249  << "expected seed " << startSeed << " for engine '" << instanceName
250  << "', got " << actualSeed << " instead!\n";
251  }
252  }
253 
254  //
255  // print character statistics
256  //
257  mf::LogVerbatim("SeedTestPolicy")
258  << std::setw(12) << (instanceName.empty()? "<default>": instanceName)
260  << " (seed: " << actualSeed << ")";
261 
262  } // for
263  } // if use generators
264 
265 } // testing::SeedTestPolicy::analyze()
MaybeLogger_< ELseverityLevel::ELsev_info, true > LogVerbatim
unsigned long seed_t
std::vector< std::string > instanceNames
std::string CreateCharacter(CLHEP::HepRandomEngine &engine)
Creates a "character statistics" using the specified random engine.
bool perEventSeeds
whether we expect different seeds on each event
std::map< std::string, seed_t > startSeeds
seeds after the constructor
Q_EXPORT QTSManip setw(int w)
Definition: qtextstream.h:331
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
seed_t readSeed(CLHEP::HepRandomEngine const &engine)
Returns the seed of the specified engine (CLHEP overload)
std::map< std::string, CLHEP::HepRandomEngine * > engines
bool useGenerators
instanciate and use random number generators
void testing::SeedTestPolicy::endJob ( )
overridevirtual

Reimplemented from art::EDAnalyzer.

Definition at line 270 of file SeedTestPolicy_module.cc.

271 {
272  // if we have an unexpected amount of errors, bail out
273  if (nExpectedErrors != nErrors) {
275  e << "SeedTestPolicy: detected " << nErrors << " errors";
276  if (nExpectedErrors) e << ", " << nExpectedErrors << " expected";
277  throw e << "!\n";
278  }
279 } // testing::SeedTestPolicy::endJob()
unsigned int nErrors
Number of errors detected so far.
const double e
unsigned int nExpectedErrors
number of expected errors
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
bool testing::SeedTestPolicy::handleSeedServiceException ( art::Exception e)
private

Returns whether e is an exception we can handle (and, if so, it handles)

Definition at line 310 of file SeedTestPolicy_module.cc.

311 {
313 
314  ++nErrors;
315  mf::LogError log("SeedTest01");
316  log << "Detected";
317  if (nErrors > nExpectedErrors) log << " UNEXPECTED";
318  log << " error #" << nErrors << ":\n" << e << "\n";
319  return true;
320 } // testing::SeedTestPolicy::handleSeedServiceException()
unsigned int nErrors
Number of errors detected so far.
const double e
unsigned int nExpectedErrors
number of expected errors
bool isSeedServiceException(std::exception const &e)
Returns whether the exception looks to be from NuRandomService.
bool testing::SeedTestPolicy::isLocalEngine ( size_t  iEngine) const
private

Returns whether the engine associated with the specified index is local.

Definition at line 323 of file SeedTestPolicy_module.cc.

323  {
324  return (i == 0) && (instanceNames.size() != 1);
325 } // testing::SeedTestPolicy::isLocalEngine()
std::vector< std::string > instanceNames
testing::SeedTestPolicy::seed_t testing::SeedTestPolicy::obtainSeed ( std::string  instanceName = "")
private

Definition at line 285 of file SeedTestPolicy_module.cc.

286 {
287  // Returns the seed for the specified engine instance, or 0 in case of
288  // configuration error (in which case, an error counter is increased)
290  try {
292  // currently (v0_00_03), the two calls are actually equivalent
293  seed
294  = instanceName.empty()? seeds->getSeed(): seeds->getSeed(instanceName);
295  }
296  catch(art::Exception& e) {
298 
299  ++nErrors;
300  mf::LogError log("SeedTestPolicy");
301  log << "Detected";
302  if (nErrors > nExpectedErrors) log << " UNEXPECTED";
303  log << " error #" << nErrors << ":\n" << e;
304  }
305  return seed;
306 } // testing::SeedTestPolicy::obtainSeed()
unsigned int nErrors
Number of errors detected so far.
seed_t getSeed(std::string instanceName)
Returns a seed for the engine with specified instance name.
unsigned long seed_t
const double e
static constexpr seed_t InvalidSeed
An invalid seed.
unsigned int nExpectedErrors
number of expected errors
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
std::vector< TrajPoint > seeds
Definition: DataStructs.cxx:13
bool isSeedServiceException(std::exception const &e)
Returns whether the exception looks to be from NuRandomService.
testing::SeedTestPolicy::seed_t testing::SeedTestPolicy::verifySeed ( CLHEP::HepRandomEngine &  engine,
std::string const &  instanceName 
)
private

Definition at line 329 of file SeedTestPolicy_module.cc.

331 {
332  seed_t const actualSeed = testing::NuRandomService::readSeed(engine);
333  seed_t const expectedSeed = startSeeds.at(instanceName);
334  // if the expected seed is invalid, we are not even sure it was ever set;
335  // the engine is in an invalid state and that's it
336  if (!rndm::NuRandomService::isSeedValid(expectedSeed)) return actualSeed;
337 
338  if (actualSeed != expectedSeed) {
340  << "expected seed " << expectedSeed << " for engine '" << instanceName
341  << "', got " << actualSeed << " instead!";
342  }
343  return actualSeed;
344 } // testing::SeedTestPolicy::verifySeed()
unsigned long seed_t
static constexpr bool isSeedValid(seed_t seed)
Returns whether the specified seed is valid.
std::map< std::string, seed_t > startSeeds
seeds after the constructor
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
seed_t readSeed(CLHEP::HepRandomEngine const &engine)
Returns the seed of the specified engine (CLHEP overload)

Member Data Documentation

std::map<std::string, CLHEP::HepRandomEngine*> testing::SeedTestPolicy::engines
private

Definition at line 88 of file SeedTestPolicy_module.cc.

std::vector<std::string> testing::SeedTestPolicy::instanceNames
private

Definition at line 78 of file SeedTestPolicy_module.cc.

std::unique_ptr<CLHEP::HepRandomEngine> testing::SeedTestPolicy::localEngine
private

self-managed

Definition at line 87 of file SeedTestPolicy_module.cc.

std::string const testing::SeedTestPolicy::moduleLabel
private

configured module label

Definition at line 83 of file SeedTestPolicy_module.cc.

unsigned int testing::SeedTestPolicy::nErrors = 0
private

Number of errors detected so far.

Definition at line 85 of file SeedTestPolicy_module.cc.

unsigned int testing::SeedTestPolicy::nExpectedErrors
private

number of expected errors

Definition at line 80 of file SeedTestPolicy_module.cc.

bool testing::SeedTestPolicy::perEventSeeds
private

whether we expect different seeds on each event

Definition at line 82 of file SeedTestPolicy_module.cc.

std::map<std::string, seed_t> testing::SeedTestPolicy::startSeeds
private

seeds after the constructor

Definition at line 79 of file SeedTestPolicy_module.cc.

bool testing::SeedTestPolicy::useGenerators
private

instanciate and use random number generators

Definition at line 81 of file SeedTestPolicy_module.cc.


The documentation for this class was generated from the following file: