CMS 3D CMS Logo

Public Member Functions | Static Public Member Functions | Private Types | Private Member Functions | Private Attributes | Static Private Attributes

edm::service::RandomNumberGeneratorService Class Reference

#include <RandomNumberGeneratorService.h>

Inheritance diagram for edm::service::RandomNumberGeneratorService:
edm::RandomNumberGenerator

List of all members.

Public Member Functions

virtual CLHEP::HepRandomEngine & getEngine () const
 Use this to get the random number engine, this is the only function most users should call.
virtual std::vector
< RandomEngineState > const & 
getEventCache () const
virtual std::vector
< RandomEngineState > const & 
getLumiCache () const
virtual uint32_t mySeed () const
 Exists for backward compatibility.
void postBeginLumi (LuminosityBlock const &lumi, EventSetup const &es)
virtual void postEventRead (Event const &event)
void postForkReacquireResources (unsigned childIndex, unsigned kMaxChildren)
void postModule (ModuleDescription const &description)
void postModuleBeginJob (ModuleDescription const &description)
void postModuleBeginLumi (ModuleDescription const &description)
void postModuleBeginRun (ModuleDescription const &description)
void postModuleConstruction (ModuleDescription const &description)
void postModuleEndJob (ModuleDescription const &description)
void postModuleEndLumi (ModuleDescription const &description)
void postModuleEndRun (ModuleDescription const &description)
virtual void preBeginLumi (LuminosityBlock const &lumi)
void preModule (ModuleDescription const &description)
void preModuleBeginJob (ModuleDescription const &description)
void preModuleBeginLumi (ModuleDescription const &description)
void preModuleBeginRun (ModuleDescription const &description)
void preModuleConstruction (ModuleDescription const &description)
void preModuleEndJob (ModuleDescription const &description)
void preModuleEndLumi (ModuleDescription const &description)
void preModuleEndRun (ModuleDescription const &description)
virtual void print ()
 For debugging purposes only.
 RandomNumberGeneratorService (ParameterSet const &pset, ActivityRegistry &activityRegistry)
virtual ~RandomNumberGeneratorService ()

Static Public Member Functions

static void fillDescriptions (ConfigurationDescriptions &descriptions)

Private Types

typedef std::map< std::string,
boost::shared_ptr
< CLHEP::HepRandomEngine > > 
EngineMap
typedef std::vector< std::string > VString
typedef std::vector< uint32_t > VUint32

Private Member Functions

bool backwardCompatibilityRead (Event const &event)
void checkEngineType (std::string const &typeFromConfig, std::string const &typeFromEvent, std::string const &engineLabel)
std::string constructSaveFileName ()
void oldStyleConfig (ParameterSet const &pset)
RandomNumberGeneratorService
const & 
operator= (RandomNumberGeneratorService const &)
void pop ()
void push (std::string const &iLabel)
 RandomNumberGeneratorService (RandomNumberGeneratorService const &)
bool readEngineState (std::istream &is, std::vector< RandomEngineState > &cache, std::string const &whichStates, bool &saveToCache)
void readEventStatesFromTextFile (std::string const &fileName)
void readFromEvent (Event const &event)
void readFromLuminosityBlock (LuminosityBlock const &lumi)
void readLumiStatesFromTextFile (std::string const &fileName)
void readStatesFromFile (std::string const &fileName, std::vector< RandomEngineState > &cache, std::string const &whichStates)
void readVector (std::istream &is, unsigned numItems, std::vector< uint32_t > &v)
void restoreFromCache (std::vector< RandomEngineState > const &cache)
void saveStatesToFile (std::string const &fileName)
void snapShot (std::vector< RandomEngineState > &cache)
void startNewSequencesForEvents ()
void writeStates (std::vector< RandomEngineState > const &v, std::ofstream &outFile)
void writeVector (VUint32 const &v, std::ofstream &outFile)

Private Attributes

unsigned childIndex_
EngineMap::const_iterator currentEngine_
std::string currentLabel_
bool enableChecking_
EngineMap engineMap_
std::map< std::string,
std::string > 
engineNameMap_
std::vector
< EngineMap::const_iterator > 
engineStack_
std::vector< std::vector
< unsigned long > > 
engineStateStack_
std::vector< RandomEngineStateeventCache_
uint32_t eventSeedOffset_
bool failedToFindStatesInLumi_
bool firstLumi_
VString labelStack_
std::vector< RandomEngineStatelumiCache_
std::string restoreFileName_
std::string restoreStateLabel_
std::string saveFileName_
bool saveFileNameRecorded_
std::map< std::string, VUint32seedMap_

Static Private Attributes

static uint32_t maxSeedHepJames = 900000000U
static uint32_t maxSeedRanecu = 2147483647U
static uint32_t maxSeedTRandom3 = 4294967295U

Detailed Description

Description: Manages random number engines for modules

Usage: See comments in base class, FWCore/Utilities/RandomNumberGenerator.h

Author:
Chris Jones and W. David Dagenhart, created March 7, 2006 (originally in FWCore/Services)

Definition at line 40 of file RandomNumberGeneratorService.h.


Member Typedef Documentation

typedef std::map<std::string, boost::shared_ptr<CLHEP::HepRandomEngine> > edm::service::RandomNumberGeneratorService::EngineMap [private]

Definition at line 153 of file RandomNumberGeneratorService.h.

typedef std::vector<std::string> edm::service::RandomNumberGeneratorService::VString [private]

Definition at line 103 of file RandomNumberGeneratorService.h.

typedef std::vector<uint32_t> edm::service::RandomNumberGeneratorService::VUint32 [private]

Definition at line 104 of file RandomNumberGeneratorService.h.


Constructor & Destructor Documentation

edm::service::RandomNumberGeneratorService::RandomNumberGeneratorService ( ParameterSet const &  pset,
ActivityRegistry activityRegistry 
)

Definition at line 47 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, currentEngine_, currentLabel_, engineMap_, engineNameMap_, engineStack_, Exception, edm::ParameterSet::exists(), edm::ParameterSet::getParameterNamesForType(), edm::ParameterSet::getParameterSet(), edm::ParameterSet::getUntrackedParameter(), labelStack_, maxSeedHepJames, maxSeedRanecu, oldStyleConfig(), postBeginLumi(), postForkReacquireResources(), postModule(), postModuleBeginJob(), postModuleBeginLumi(), postModuleBeginRun(), postModuleConstruction(), postModuleEndJob(), postModuleEndLumi(), postModuleEndRun(), preModule(), preModuleBeginJob(), preModuleBeginLumi(), preModuleBeginRun(), preModuleConstruction(), preModuleEndJob(), preModuleEndLumi(), preModuleEndRun(), restoreFileName_, restoreStateLabel_, saveFileName_, seedMap_, edm::ActivityRegistry::watchPostBeginLumi(), edm::ActivityRegistry::watchPostForkReacquireResources(), edm::ActivityRegistry::watchPostModule(), edm::ActivityRegistry::watchPostModuleBeginJob(), edm::ActivityRegistry::watchPostModuleBeginLumi(), edm::ActivityRegistry::watchPostModuleBeginRun(), edm::ActivityRegistry::watchPostModuleConstruction(), edm::ActivityRegistry::watchPostModuleEndJob(), edm::ActivityRegistry::watchPostModuleEndLumi(), edm::ActivityRegistry::watchPostModuleEndRun(), edm::ActivityRegistry::watchPreModule(), edm::ActivityRegistry::watchPreModuleBeginJob(), edm::ActivityRegistry::watchPreModuleBeginLumi(), edm::ActivityRegistry::watchPreModuleBeginRun(), edm::ActivityRegistry::watchPreModuleConstruction(), edm::ActivityRegistry::watchPreModuleEndJob(), edm::ActivityRegistry::watchPreModuleEndLumi(), and edm::ActivityRegistry::watchPreModuleEndRun().

                                                                                                  :
      restoreStateLabel_(pset.getUntrackedParameter<std::string>("restoreStateLabel")),
      saveFileName_(pset.getUntrackedParameter<std::string>("saveFileName")),
      saveFileNameRecorded_(false),
      restoreFileName_(pset.getUntrackedParameter<std::string>("restoreFileName")),
      enableChecking_(pset.getUntrackedParameter<bool>("enableChecking")),
      firstLumi_(true),
      childIndex_(0U),
      eventSeedOffset_(pset.getUntrackedParameter<unsigned>("eventSeedOffset")),
      failedToFindStatesInLumi_(false) {

      if (!restoreFileName_.empty() && !restoreStateLabel_.empty()) {
        throw edm::Exception(edm::errors::Configuration)
          << "In the configuration for the RandomNumberGeneratorService both\n"
          << "restoreFileName and restoreStateLabel were set to nonempty values\n"
          << "which is illegal.  It is impossible to restore the random engine\n"
          << "states two different ways in the same process.\n";
      }

      // The saveFileName and must correspond to a file name without any path specification.
      // Throw if that is not true.
      if (!saveFileName_.empty() && (saveFileName_.find("/") != std::string::npos)) {
        throw edm::Exception(edm::errors::Configuration)
          << "The saveFileName parameter must be a simple file name with no path\n"
          << "specification. In the configuration, it was given the value \""
          << saveFileName_ << "\"\n";
      }

      // Check if the configuration file is still expressed in the old style.
      // We do this by looking for a PSet named moduleSeeds.  This parameter
      // is unique to an old style cfg file.
      if (pset.exists("moduleSeeds")) {
        oldStyleConfig(pset);
      }
      else {

        uint32_t initialSeed;
        VUint32 initialSeedSet;
        std::string engineName;

        VString pSets = pset.getParameterNamesForType<ParameterSet>();
        for (VString::const_iterator it = pSets.begin(), itEnd = pSets.end(); it != itEnd; ++it) {

          ParameterSet const& modulePSet = pset.getParameterSet(*it);
          engineName = modulePSet.getUntrackedParameter<std::string>("engineName", std::string("HepJamesRandom"));

          bool initialSeedExists = modulePSet.exists("initialSeed");
          bool initialSeedSetExists = modulePSet.exists("initialSeedSet");

          if (initialSeedExists && initialSeedSetExists) {
            throw edm::Exception(edm::errors::Configuration)
              << "For the module with the label \"" << *it << "\",\n"
              << "both the parameters \"initialSeed\" and \"initialSeedSet\"\n"
              << "have been set in the configuration. You must set one or\n"
              << "the other.  It is illegal to set both.\n";
          }
          else if (!initialSeedExists && !initialSeedSetExists) {
            throw edm::Exception(edm::errors::Configuration)
              << "For the module with the label \"" << *it << "\",\n"
              << "neither the parameter \"initialSeed\" nor \"initialSeedSet\"\n"
              << "has been set in the configuration. You must set one or\n"
              << "the other.\n";
          }
          else if (initialSeedExists) {
            initialSeed = modulePSet.getUntrackedParameter<uint32_t>("initialSeed");
            initialSeedSet.clear();
            initialSeedSet.push_back(initialSeed);
          }
          else if (initialSeedSetExists) {
            initialSeedSet = modulePSet.getUntrackedParameter<VUint32>("initialSeedSet");
          }
          seedMap_[*it] = initialSeedSet;
          engineNameMap_[*it] = engineName;

          // For the CLHEP::RanecuEngine case, require a seed set containing exactly two seeds.

          if (engineName == std::string("RanecuEngine")) {
            if (initialSeedSet.size() != 2U) {
              throw edm::Exception(edm::errors::Configuration)
                << "Random engines of type \"RanecuEngine\" require 2 seeds\n"
                << "be specified with the parameter named \"initialSeedSet\".\n"
                << "Either \"initialSeedSet\" was not in the configuration\n"
                << "or its size was not 2 for the module with label \"" << *it << "\".\n" ;
            }
            boost::shared_ptr<CLHEP::HepRandomEngine> engine(new CLHEP::RanecuEngine());
            engineMap_[*it] = engine;

            if (initialSeedSet[0] > maxSeedRanecu ||
                initialSeedSet[1] > maxSeedRanecu) {  // They need to fit in a 31 bit integer
              throw edm::Exception(edm::errors::Configuration)
                << "The RanecuEngine seeds should be in the range 0 to 2147483647.\n"
                << "The seeds passed to the RandomNumberGenerationService from the\n"
                   "configuration file were " << initialSeedSet[0] << " and " << initialSeedSet[1]
                << "\nThis was for the module with label \"" << *it << "\".\n";
            }
            long int seedL[2];
            seedL[0] = static_cast<long int>(initialSeedSet[0]);
            seedL[1] = static_cast<long int>(initialSeedSet[1]);
            engine->setSeeds(seedL,0);
          }
          // For the other engines, one seed is required
          else {
            if (initialSeedSet.size() != 1U) {
              throw edm::Exception(edm::errors::Configuration)
                << "Random engines of type \"HepJamesRandom\" and \"TRandom3\n"
                << "require exactly 1 seed be specified in the configuration.\n"
                << "There were " << initialSeedSet.size() << " seeds set for the\n"
                << "module with label \"" << *it << "\".\n" ;
            }
            long int seedL = static_cast<long int>(initialSeedSet[0]);

            if (engineName == "HepJamesRandom") {
              if (initialSeedSet[0] > maxSeedHepJames) {
                throw edm::Exception(edm::errors::Configuration)
                  << "The CLHEP::HepJamesRandom engine seed should be in the range 0 to 900000000.\n"
                  << "The seed passed to the RandomNumberGenerationService from the\n"
                     "configuration file was " << initialSeedSet[0] << ".  This was for \n"
                  << "the module with label " << *it << ".\n";
              }
              boost::shared_ptr<CLHEP::HepRandomEngine> engine(new CLHEP::HepJamesRandom(seedL));
              engineMap_[*it] = engine;
            }
            else if(engineName == "TRandom3") {

              // There is a dangerous conversion from uint32_t to long
              // that occurs above. In the next 2 lines we check the
              // behavior is what we need for the service to work
              // properly.  This conversion is forced on us by the
              // CLHEP and ROOT interfaces. If the assert ever starts
              // to fail we will have to come up with a way to deal
              // with this.
              uint32_t seedu32 = static_cast<uint32_t>(seedL);
              assert(initialSeedSet[0] == seedu32);

              boost::shared_ptr<CLHEP::HepRandomEngine> engine(new TRandomAdaptor(seedL));
              engineMap_[*it] = engine;
            }
            else {
              throw edm::Exception(edm::errors::Configuration)
                << "The random engine name, \"" << engineName
                << "\", does not correspond to a supported engine.\n"
                << "This engine was configured for the module with label \"" << *it << "\"";
            }
          }
        }
      }

      activityRegistry.watchPostBeginLumi(this,&RandomNumberGeneratorService::postBeginLumi);

      activityRegistry.watchPreModuleConstruction(this,&RandomNumberGeneratorService::preModuleConstruction);
      activityRegistry.watchPostModuleConstruction(this,&RandomNumberGeneratorService::postModuleConstruction);

      activityRegistry.watchPreModuleBeginJob(this,&RandomNumberGeneratorService::preModuleBeginJob);
      activityRegistry.watchPostModuleBeginJob(this,&RandomNumberGeneratorService::postModuleBeginJob);

      activityRegistry.watchPreModuleBeginRun(this,&RandomNumberGeneratorService::preModuleBeginRun);
      activityRegistry.watchPostModuleBeginRun(this,&RandomNumberGeneratorService::postModuleBeginRun);

      activityRegistry.watchPreModuleBeginLumi(this,&RandomNumberGeneratorService::preModuleBeginLumi);
      activityRegistry.watchPostModuleBeginLumi(this,&RandomNumberGeneratorService::postModuleBeginLumi);

      activityRegistry.watchPreModule(this,&RandomNumberGeneratorService::preModule);
      activityRegistry.watchPostModule(this,&RandomNumberGeneratorService::postModule);

      activityRegistry.watchPreModuleEndLumi(this,&RandomNumberGeneratorService::preModuleEndLumi);
      activityRegistry.watchPostModuleEndLumi(this,&RandomNumberGeneratorService::postModuleEndLumi);

      activityRegistry.watchPreModuleEndRun(this,&RandomNumberGeneratorService::preModuleEndRun);
      activityRegistry.watchPostModuleEndRun(this,&RandomNumberGeneratorService::postModuleEndRun);

      activityRegistry.watchPreModuleEndJob(this,&RandomNumberGeneratorService::preModuleEndJob);
      activityRegistry.watchPostModuleEndJob(this,&RandomNumberGeneratorService::postModuleEndJob);

      activityRegistry.watchPostForkReacquireResources(this,&RandomNumberGeneratorService::postForkReacquireResources);

      // the default for the stack is to point to the 'end' of our map which is used to define not set
      engineStack_.push_back(engineMap_.end());
      currentEngine_ = engineMap_.end();

      labelStack_.push_back(std::string());
      currentLabel_ = std::string();
    }
edm::service::RandomNumberGeneratorService::~RandomNumberGeneratorService ( ) [virtual]

Definition at line 231 of file RandomNumberGeneratorService.cc.

                                                                {
    }
edm::service::RandomNumberGeneratorService::RandomNumberGeneratorService ( RandomNumberGeneratorService const &  ) [private]

Member Function Documentation

bool edm::service::RandomNumberGeneratorService::backwardCompatibilityRead ( Event const &  event) [private]

Definition at line 752 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, eventCache_, Exception, edm::HandleBase::isValid(), restoreStateLabel_, and evf::utils::state.

Referenced by readFromEvent().

                                                                              {

      Handle<std::vector<RandomEngineState> > states;

      event.getByLabel(restoreStateLabel_, states);
      if (!states.isValid()) {
        return false;
      }
      for (std::vector<RandomEngineState>::const_iterator state = states->begin(),
                                                          iEnd = states->end();
           state != iEnd; ++state) {

        std::vector<RandomEngineState>::iterator cachedState = 
          std::lower_bound(eventCache_.begin(), eventCache_.end(), *state);


        if (cachedState != eventCache_.end() && cachedState->getLabel() == state->getLabel()) {
          if (cachedState->getSeed().size() != state->getSeed().size() ||
              cachedState->getState().size() != state->getState().size()) {
            throw edm::Exception(edm::errors::Configuration)
              << "In function RandomNumberGeneratorService::backwardCompatibilityRead.\n"
              << "When attempting to replay processing with the RandomNumberGeneratorService,\n"
              << "the engine type for each module must be the same in the replay configuration\n"
              << "and the original configuration.  If this is not the problem, then the data\n"
              << "is somehow corrupted or there is a bug because the vector in the data containing\n"
              << "the seeds or engine state is the incorrect size for the type of random engine.\n";
          }
          cachedState->setSeed(state->getSeed());
          cachedState->setState(state->getState());
        }
      }
      return true;
    }
void edm::service::RandomNumberGeneratorService::checkEngineType ( std::string const &  typeFromConfig,
std::string const &  typeFromEvent,
std::string const &  engineLabel 
) [private]

Definition at line 894 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, and Exception.

Referenced by restoreFromCache().

    {
      if (typeFromConfig != typeFromEvent) {
        throw edm::Exception(edm::errors::Configuration)
          << "The RandomNumberGeneratorService is trying to restore\n"
          << "the state of the random engine for the module \"" 
          << engineLabel << "\".  An\n"
          << "error was detected because the type of the engine in the\n"
          << "input file and the configuration file do not match.\n"
          << "In the configuration file the type is \"" << typeFromConfig
          << "\".\nIn the input file the type is \"" << typeFromEvent << "\".  If\n"
          << "you are not generating any random numbers in this module, then\n"
          << "remove the line in the configuration file that gives it\n"
          << "a seed and the error will go away.  Otherwise, you must give\n"
          << "this module the same engine type in the configuration file or\n"
          << "stop trying to restore the random engine state.\n";
      }
    }
std::string edm::service::RandomNumberGeneratorService::constructSaveFileName ( ) [private]

Definition at line 977 of file RandomNumberGeneratorService.cc.

References createBeamHaloJobs::directory, newFWLiteAna::fullName, and saveFileName_.

Referenced by postEventRead().

    {
      char directory[1500];
      std::string fullName(getcwd(directory, sizeof(directory)) ? directory : "/PathIsTooBig");
      fullName += "/" + saveFileName_;
      return fullName;
    }
void edm::service::RandomNumberGeneratorService::fillDescriptions ( ConfigurationDescriptions descriptions) [static]

Definition at line 302 of file RandomNumberGeneratorService.cc.

References edm::ConfigurationDescriptions::add(), edm::ParameterSetDescription::addNode(), edm::ParameterSetDescription::addOptionalUntracked(), edm::ParameterSetDescription::addUntracked(), edm::ParameterSetDescription::addWildcardUntracked(), edm::friendlyname::emptyString(), edm::RequireZeroOrMore, and edm::ParameterDescriptionNode::setComment().

                                                                                           {
      ParameterSetDescription desc;

      std::string emptyString;
      desc.addUntracked<std::string>("restoreStateLabel", emptyString);
      desc.addUntracked<std::string>("saveFileName", emptyString);
      desc.addUntracked<std::string>("restoreFileName", emptyString);
      desc.addUntracked<bool>("enableChecking", false);
      desc.addUntracked<unsigned>("eventSeedOffset", 0U);

      ParameterSetDescription val;
      // When the migration away from the deprecated interface is complete it would be better
      // to change the next line to a declaration of a single parameter named initialSeed instead
      // of being a wildcard.  Also the next two lines might also be combined with an "exclusive or"
      // operator.
      val.addWildcardUntracked<uint32_t>("*")->setComment("In the new interface, this wildcard will "
        "match either nothing or one parameter named initialSeed.  Either initialSeed will exist or "
        "initialSeedSet will exist but not both.  In the old deprecated interface, this will match "
        "parameters with the names being the module labels and the values being the seeds");
      val.addOptionalUntracked<std::vector<uint32_t> >("initialSeedSet")->setComment("New interface only");
      val.addOptionalUntracked<std::string>("engineName",std::string("HepJamesRandom"))->setComment("New interface only");

      ParameterWildcard<ParameterSetDescription> wnode("*", edm::RequireZeroOrMore, true, val);
      wnode.setComment("In the new interface, the name of each ParameterSet will be the associated module label. "
                       "In the old deprecated interface there will be one ParameterSet named moduleSeeds");
      desc.addNode(wnode);

      // This only exists for backward compatibility reasons
      // This should be removed if all the configurations are
      // ever upgraded properly.
      desc.addOptionalUntracked<uint32_t>("sourceSeed")->
        setComment("This parameter is deprecated, has no effect and will likely be completely removed someday");

      descriptions.add("RandomNumberGeneratorService", desc);
    }
CLHEP::HepRandomEngine & edm::service::RandomNumberGeneratorService::getEngine ( ) const [virtual]

Use this to get the random number engine, this is the only function most users should call.

Implements edm::RandomNumberGenerator.

Definition at line 235 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, currentEngine_, currentLabel_, engineMap_, Exception, and edm::errors::Unknown.

                                                  {

      if (currentEngine_ == engineMap_.end()) {
        if (currentLabel_ != std::string() ) {
          throw edm::Exception(edm::errors::Configuration)
            << "The module with label \""
            << currentLabel_
            << "\" requested a random number engine from the \n"
               "RandomNumberGeneratorService, but that module was not configured\n"
               "for random numbers.  An engine is created only if a seed(s) is provided\n"
               "in the configuration file.  Please add the following PSet to the\n"
               "configuration file for the RandomNumberGeneratorService:\n\n"
               "  " << currentLabel_ << " = cms.PSet(\n"
               "    initialSeed = cms.untracked.uint32(your_seed),\n"
               "    engineName = cms.untracked.string('TRandom3')\n"
               "  )\n"
               "where you replace \"your_seed\" with a number and add a comma if necessary\n"
              "The \"engineName\" parameter is optional. If absent the default is \"HepJamesRandom\".\n";
        }
        else {
          throw edm::Exception(edm::errors::Unknown)
             << "Requested a random number engine from the RandomNumberGeneratorService\n"
                "when no module was active.  This is not supposed to be possible.\n"
                "Please inform the edm developers about this. It would be helpful to\n"
                "know the stack. If a source was requesting a random engine this could\n"
                "happen. Sources are not supposed to be doing that anymore.\n";
        }
      }
      return *(currentEngine_->second); 
    }
std::vector< RandomEngineState > const & edm::service::RandomNumberGeneratorService::getEventCache ( ) const [virtual]

Implements edm::RandomNumberGenerator.

Definition at line 603 of file RandomNumberGeneratorService.cc.

References eventCache_.

                                                      {
      return eventCache_;
    }
std::vector< RandomEngineState > const & edm::service::RandomNumberGeneratorService::getLumiCache ( ) const [virtual]

Implements edm::RandomNumberGenerator.

Definition at line 598 of file RandomNumberGeneratorService.cc.

References lumiCache_.

                                                     {
      return lumiCache_;
    }
uint32_t edm::service::RandomNumberGeneratorService::mySeed ( ) const [virtual]

Exists for backward compatibility.

Implements edm::RandomNumberGenerator.

Definition at line 267 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, currentLabel_, Exception, seedMap_, and edm::errors::Unknown.

                                               {

      std::map<std::string, VUint32>::const_iterator iter;
      iter = seedMap_.find(currentLabel_);

      if (iter == seedMap_.end()) {
        if (currentLabel_ != std::string() ) {
          throw edm::Exception(edm::errors::Configuration)
            << "The module with label \""
            << currentLabel_
            << "\" requested a random number seed from the \n"
               "RandomNumberGeneratorService, but that module was not configured\n"
               "for random numbers.  An engine is created only if a seed(s) is provided\n"
               "in the configuration file.  Please add the following PSet to the\n"
               "configuration file for the RandomNumberGeneratorService:\n\n"
               "  " << currentLabel_ << " = cms.PSet(\n"
               "    initialSeed = cms.untracked.uint32(your_seed),\n"
               "    engineName = cms.untracked.string('TRandom3')\n"
               "  )\n"
               "where you replace \"your_seed\" with a number and add a comma if necessary\n"
              "The \"engineName\" parameter is optional. If absent the default is \"HepJamesRandom\".\n";
        }
        else {
          throw edm::Exception(edm::errors::Unknown)
             << "Requested a random number seed from the RandomNumberGeneratorService\n"
                "when no module was active.  This is not supposed to be possible.\n"
                "Please inform the edm developers about this. It would be helpful to\n"
                "know the stack. If a source was requesting a random engine this could\n"
                "happen. Sources are not supposed to be doing that anymore.\n";
        }
      }
      return iter->second[0];
    }
void edm::service::RandomNumberGeneratorService::oldStyleConfig ( ParameterSet const &  pset) [private]

Definition at line 1254 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, engineMap_, engineNameMap_, Exception, edm::ParameterSet::getParameterNames(), edm::ParameterSet::getParameterNamesForType(), edm::ParameterSet::getParameterSet(), edm::ParameterSet::getUntrackedParameter(), maxSeedHepJames, RecoTau_DiTaus_pt_20-420_cfg::moduleSeeds, h::names, and seedMap_.

Referenced by RandomNumberGeneratorService().

                                                                         {
      VString pSets = pset.getParameterNamesForType<ParameterSet>();
      for (VString::const_iterator it = pSets.begin(), itEnd = pSets.end(); it != itEnd; ++it) {
        if (*it != std::string("moduleSeeds")) {
          throw Exception(errors::Configuration)
            << "RandomNumberGeneratorService supports two configuration interfaces.\n" 
            << "One is old and deprecated, but still supported for backward compatibility\n"
            << "reasons. It is illegal to mix parameters using both the old and new service\n"
            << "interface in the same configuration. It is assumed the old interface is being\n"
            << "used if the parameter set named \"moduleSeeds\" exists.  In that case it is\n"
            << "illegal to have any other nested ParameterSets. This exception was thrown\n"
            << "because that happened.\n";
        }
      }

      ParameterSet const& moduleSeeds = pset.getParameterSet("moduleSeeds");

      std::vector<uint32_t> seeds;

      VString names = moduleSeeds.getParameterNames();
      for (VString::const_iterator itName = names.begin(), itNameEnd = names.end();
           itName != itNameEnd; ++itName) {

        uint32_t seed = moduleSeeds.getUntrackedParameter<uint32_t>(*itName);

        seeds.clear();
        seeds.push_back(seed);
        seedMap_[*itName] = seeds;
        engineNameMap_[*itName] = std::string("HepJamesRandom");

        if (seed > maxSeedHepJames) {
          throw edm::Exception(edm::errors::Configuration)
            << "The CLHEP::HepJamesRandom engine seed should be in the range 0 to 900000000.\n"
            << "The seed passed to the RandomNumberGenerationService from the\n"
               "configuration file was " << seed << ". This was for the module\n"
            << "with label \"" << *itName << "\".";
        }
        long seedL = static_cast<long>(seed);
        engineMap_[*itName] = boost::shared_ptr<CLHEP::HepRandomEngine>(new CLHEP::HepJamesRandom(seedL));
      }
    }
RandomNumberGeneratorService const& edm::service::RandomNumberGeneratorService::operator= ( RandomNumberGeneratorService const &  ) [private]
void edm::service::RandomNumberGeneratorService::pop ( ) [private]

Definition at line 692 of file RandomNumberGeneratorService.cc.

References currentEngine_, currentLabel_, engineStack_, and labelStack_.

Referenced by postModule(), postModuleBeginJob(), postModuleBeginLumi(), postModuleBeginRun(), postModuleConstruction(), postModuleEndJob(), postModuleEndLumi(), and postModuleEndRun().

    {
      engineStack_.pop_back();
      //NOTE: algorithm is such that we always have at least one item in the stacks
      currentEngine_ = engineStack_.back();
      labelStack_.pop_back();
      currentLabel_ = labelStack_.back();
    }
void edm::service::RandomNumberGeneratorService::postBeginLumi ( LuminosityBlock const &  lumi,
EventSetup const &  es 
)

Definition at line 383 of file RandomNumberGeneratorService.cc.

References eventCache_, firstLumi_, readEventStatesFromTextFile(), restoreFileName_, restoreFromCache(), snapShot(), and startNewSequencesForEvents().

Referenced by RandomNumberGeneratorService().

                                                                                                 {

      if (firstLumi_) {
        // reset state with new seeds based on child index
        startNewSequencesForEvents();
        if (!restoreFileName_.empty()) {
          snapShot(eventCache_);
          // copy state from text file to event cache
          readEventStatesFromTextFile(restoreFileName_);
        }
      }
      if (!firstLumi_ || !restoreFileName_.empty()) {
        // copy state from event cache to engines
        restoreFromCache(eventCache_);
      }
      firstLumi_ = false;
    }
void edm::service::RandomNumberGeneratorService::postEventRead ( Event const &  event) [virtual]

Implements edm::RandomNumberGenerator.

Definition at line 402 of file RandomNumberGeneratorService.cc.

References constructSaveFileName(), eventCache_, newFWLiteAna::fullName, readFromEvent(), restoreFromCache(), restoreStateLabel_, saveFileName_, saveFileNameRecorded_, saveStatesToFile(), and snapShot().

                                                                  {
      // copy from Event to event cache
      if (!restoreStateLabel_.empty()) {
        snapShot(eventCache_);
        readFromEvent(event);

        // copy from event cache to engines
        restoreFromCache(eventCache_);
      }
      else {
        // copy from engines to event cache
        snapShot(eventCache_);
      }
      // if requested write text file from both caches
      if (!saveFileName_.empty())  {
        saveStatesToFile(saveFileName_);
        if (!saveFileNameRecorded_) {
          std::string fullName = constructSaveFileName();
          Service<JobReport> reportSvc;
          reportSvc->reportRandomStateFile(fullName);
          saveFileNameRecorded_ = true;
        }
      }
    }
void edm::service::RandomNumberGeneratorService::postForkReacquireResources ( unsigned  childIndex,
unsigned  kMaxChildren 
)

Definition at line 339 of file RandomNumberGeneratorService.cc.

References childIndex_, saveFileName_, and createPayload::suffix.

Referenced by RandomNumberGeneratorService().

                                                                                                       {
      childIndex_ = childIndex;

      std::ostringstream suffix;
      suffix << "_" << childIndex;
      saveFileName_ += suffix.str();
    }
void edm::service::RandomNumberGeneratorService::postModule ( ModuleDescription const &  description)

Definition at line 521 of file RandomNumberGeneratorService.cc.

References pop().

Referenced by RandomNumberGeneratorService().

                                                                                 {
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleBeginJob ( ModuleDescription const &  description)

Definition at line 466 of file RandomNumberGeneratorService.cc.

References currentEngine_, enableChecking_, engineMap_, engineStateStack_, Exception, edm::errors::LogicError, edm::ModuleDescription::moduleLabel(), edm::ModuleDescription::moduleName(), and pop().

Referenced by RandomNumberGeneratorService().

                                                                                         {
      if (enableChecking_ && currentEngine_ != engineMap_.end()) {
        if (engineStateStack_.back() != currentEngine_->second->put()) {
          throw edm::Exception(edm::errors::LogicError)
            << "It is illegal to generate random numbers during beginJob because \n"
               "that makes it very difficult to reproduce the processing of individual\n"
               "events.  Random numbers were generated during beginJob for the module with\n"
               "class name \"" << description.moduleName() << "\"\n"
               "and module label \"" << description.moduleLabel() << "\"\n";
        }
        engineStateStack_.pop_back();
      }
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleBeginLumi ( ModuleDescription const &  description)

Definition at line 511 of file RandomNumberGeneratorService.cc.

References pop().

Referenced by RandomNumberGeneratorService().

                                                                                          {
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleBeginRun ( ModuleDescription const &  description)

Definition at line 490 of file RandomNumberGeneratorService.cc.

References currentEngine_, enableChecking_, engineMap_, engineStateStack_, Exception, edm::errors::LogicError, edm::ModuleDescription::moduleLabel(), edm::ModuleDescription::moduleName(), and pop().

Referenced by RandomNumberGeneratorService().

                                                                                         {
      if (enableChecking_ && currentEngine_ != engineMap_.end()) {
        if (engineStateStack_.back() != currentEngine_->second->put()) {
          throw edm::Exception(edm::errors::LogicError)
            << "It is illegal to generate random numbers during beginRun because \n"
               "that makes it very difficult to reproduce the processing of individual\n"
               "events.  Random numbers were generated during beginRun for the module with\n"
               "class name \"" << description.moduleName() << "\"\n"
               "and module label \"" << description.moduleLabel() << "\"\n";
        }
        engineStateStack_.pop_back();
      }
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleConstruction ( ModuleDescription const &  description)

Definition at line 441 of file RandomNumberGeneratorService.cc.

References currentEngine_, enableChecking_, engineMap_, engineStateStack_, Exception, edm::errors::LogicError, edm::ModuleDescription::moduleLabel(), edm::ModuleDescription::moduleName(), and pop().

Referenced by RandomNumberGeneratorService().

    {
      if (enableChecking_ && currentEngine_ != engineMap_.end()) {
        if (engineStateStack_.back() != currentEngine_->second->put()) {
          throw edm::Exception(edm::errors::LogicError)
            << "It is illegal to generate random numbers during module construction because \n"
               "that makes it very difficult to reproduce the processing of individual\n"
               "events.  Random numbers were generated during module construction for the module with\n"
               "class name \"" << description.moduleName() << "\"\n"
               "and module label \"" << description.moduleLabel() << "\"\n";
        }
        engineStateStack_.pop_back();
      }
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleEndJob ( ModuleDescription const &  description)

Definition at line 582 of file RandomNumberGeneratorService.cc.

References currentEngine_, enableChecking_, engineMap_, engineStateStack_, Exception, edm::errors::LogicError, edm::ModuleDescription::moduleLabel(), edm::ModuleDescription::moduleName(), and pop().

Referenced by RandomNumberGeneratorService().

                                                                                       {
      if (enableChecking_ && currentEngine_ != engineMap_.end()) {
        if (engineStateStack_.back() != currentEngine_->second->put()) {
          throw edm::Exception(edm::errors::LogicError)
            << "It is illegal to generate random numbers during endJob because \n"
               "that makes it very difficult to reproduce the processing of individual\n"
               "events.  Random numbers were generated during endJob for the module with\n"
               "class name \"" << description.moduleName() << "\"\n"
               "and module label \"" << description.moduleLabel() << "\"\n";
        }
        engineStateStack_.pop_back();
      }
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleEndLumi ( ModuleDescription const &  description)

Definition at line 534 of file RandomNumberGeneratorService.cc.

References currentEngine_, enableChecking_, engineMap_, engineStateStack_, Exception, edm::errors::LogicError, edm::ModuleDescription::moduleLabel(), edm::ModuleDescription::moduleName(), and pop().

Referenced by RandomNumberGeneratorService().

                                                                                        {
      if (enableChecking_ && currentEngine_ != engineMap_.end()) {
        if (engineStateStack_.back() != currentEngine_->second->put()) {
          throw edm::Exception(edm::errors::LogicError)
            << "It is illegal to generate random numbers during endLumi because \n"
               "that makes it very difficult to reproduce the processing of individual\n"
               "events.  Random numbers were generated during endLumi for the module with\n"
               "class name \"" << description.moduleName() << "\"\n"
               "and module label \"" << description.moduleLabel() << "\"\n";
        }
        engineStateStack_.pop_back();
      }
      pop();
    }
void edm::service::RandomNumberGeneratorService::postModuleEndRun ( ModuleDescription const &  description)

Definition at line 558 of file RandomNumberGeneratorService.cc.

References currentEngine_, enableChecking_, engineMap_, engineStateStack_, Exception, edm::errors::LogicError, edm::ModuleDescription::moduleLabel(), edm::ModuleDescription::moduleName(), and pop().

Referenced by RandomNumberGeneratorService().

                                                                                       {
      if (enableChecking_ && currentEngine_ != engineMap_.end()) {
        if (engineStateStack_.back() != currentEngine_->second->put()) {
          throw edm::Exception(edm::errors::LogicError)
            << "It is illegal to generate random numbers during endRun because \n"
               "that makes it very difficult to reproduce the processing of individual\n"
               "events.  Random numbers were generated during endRun for the module with\n"
               "class name \"" << description.moduleName() << "\"\n"
               "and module label \"" << description.moduleLabel() << "\"\n";
        }
        engineStateStack_.pop_back();
      }
      pop();
    }
void edm::service::RandomNumberGeneratorService::preBeginLumi ( LuminosityBlock const &  lumi) [virtual]

Implements edm::RandomNumberGenerator.

Definition at line 352 of file RandomNumberGeneratorService.cc.

References eventCache_, firstLumi_, lumiCache_, readFromLuminosityBlock(), readLumiStatesFromTextFile(), restoreFileName_, restoreFromCache(), restoreStateLabel_, and snapShot().

                                                                          {

      if (firstLumi_) {
        // copy state from engines to lumi cache
        snapShot(lumiCache_);

        if (!restoreFileName_.empty()) {
          // copy state from text file to lumi cache
          readLumiStatesFromTextFile(restoreFileName_);
        }
      }
      else {
        snapShot(eventCache_);
      }

      // copy state from LuminosityBlock to lumi cache
      if (!restoreStateLabel_.empty()) {
        readFromLuminosityBlock(lumi);
      }

      if (!firstLumi_ || !restoreFileName_.empty() || !restoreStateLabel_.empty()) {
        // copy state from lumi cache to engines
        restoreFromCache(lumiCache_);
      }
    }
void edm::service::RandomNumberGeneratorService::preModule ( ModuleDescription const &  description)

Definition at line 516 of file RandomNumberGeneratorService.cc.

References edm::ModuleDescription::moduleLabel(), and push().

Referenced by RandomNumberGeneratorService().

                                                                                {
      push(description.moduleLabel());
    }
void edm::service::RandomNumberGeneratorService::preModuleBeginJob ( ModuleDescription const &  description)
void edm::service::RandomNumberGeneratorService::preModuleBeginLumi ( ModuleDescription const &  description)

Definition at line 506 of file RandomNumberGeneratorService.cc.

References edm::ModuleDescription::moduleLabel(), and push().

Referenced by RandomNumberGeneratorService().

                                                                                         {
      push(description.moduleLabel());
    }
void edm::service::RandomNumberGeneratorService::preModuleBeginRun ( ModuleDescription const &  description)
void edm::service::RandomNumberGeneratorService::preModuleConstruction ( ModuleDescription const &  description)
void edm::service::RandomNumberGeneratorService::preModuleEndJob ( ModuleDescription const &  description)
void edm::service::RandomNumberGeneratorService::preModuleEndLumi ( ModuleDescription const &  description)
void edm::service::RandomNumberGeneratorService::preModuleEndRun ( ModuleDescription const &  description)
void edm::service::RandomNumberGeneratorService::print ( void  ) [virtual]

For debugging purposes only.

Implements edm::RandomNumberGenerator.

Definition at line 608 of file RandomNumberGeneratorService.cc.

References gather_cfg::cout, currentEngine_, currentLabel_, engineMap_, engineNameMap_, engineStack_, i, labelStack_, python::multivaluedict::map(), restoreFileName_, restoreStateLabel_, saveFileName_, and seedMap_.

                                        {
      std::cout << "\n\nRandomNumberGeneratorService dump\n\n";

      std::cout << "    Contents of seedMap\n";
      for (std::map<std::string, std::vector<uint32_t> >::const_iterator iter = seedMap_.begin();
           iter != seedMap_.end();
           ++iter) {
        std::cout << "        " << iter->first;
        std::vector<uint32_t> seeds = iter->second;
        for (std::vector<uint32_t>::const_iterator vIter = seeds.begin();
             vIter != seeds.end();
             ++vIter) {
          std::cout << "   "  << *vIter;
        }
        std::cout << "\n";
      }
      std::cout << "\n    Contents of engineNameMap\n";
      for (std::map<std::string, std::string>::const_iterator iter = engineNameMap_.begin();
           iter != engineNameMap_.end();
           ++iter) {
        std::cout << "        " << iter->first << "   " << iter->second << "\n";
      }
      std::cout << "\n    Contents of engineMap\n";
      for (EngineMap::const_iterator iter = engineMap_.begin();
           iter != engineMap_.end();
           ++iter) {
        std::cout << "        " << iter->first
                  << "   " << iter->second->name() << "   ";
        if (iter->second->name() == std::string("HepJamesRandom")) {
          std::cout << iter->second->getSeed();
        }
        else {
          std::cout << "Engine does not know original seed";
        }
        std::cout << "\n";
      }
      std::cout << "\n";
      std::cout << "    currentLabel_ = " << currentLabel_ << "\n";
      std::cout << "    labelStack_ size = " << labelStack_.size() << "\n";
      int i = 0;
      for (VString::const_iterator iter = labelStack_.begin();
           iter != labelStack_.end();
           ++iter, ++i) {
        std::cout << "                 " << i << "  " << *iter << "\n";    
      }
      if (currentEngine_ == engineMap_.end()) {
        std::cout << "    currentEngine points to end\n";
      }
      else {
        std::cout << "    currentEngine_ = " << currentEngine_->first
                  << "  " << currentEngine_->second->name()
                  << "  " << currentEngine_->second->getSeed() << "\n";
      }

      std::cout << "    engineStack_ size = " << engineStack_.size() << "\n";
      i = 0;
      for (std::vector<EngineMap::const_iterator>::const_iterator iter = engineStack_.begin();
           iter != engineStack_.end();
           ++iter, ++i) {
        if (*iter == engineMap_.end()) {
          std::cout << "                 " << i << "  Points to end of engine map\n";    
        }
        else {
          std::cout << "                 " << i << "  " << (*iter)->first 
                    << "  " << (*iter)->second->name() << "  " << (*iter)->second->getSeed() << "\n";    
        }
      }

      std::cout << "    restoreStateLabel_ = " << restoreStateLabel_ << "\n";
      std::cout << "    saveFileName_ = " << saveFileName_ << "\n";
      std::cout << "    restoreFileName_ = " << restoreFileName_ << "\n";
    }
void edm::service::RandomNumberGeneratorService::push ( std::string const &  iLabel) [private]
bool edm::service::RandomNumberGeneratorService::readEngineState ( std::istream &  is,
std::vector< RandomEngineState > &  cache,
std::string const &  whichStates,
bool &  saveToCache 
) [private]

Definition at line 1023 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, Exception, moduleLabel(), readVector(), restoreFileName_, and RandomEngineState::setLabel().

Referenced by readStatesFromFile().

                                                                           {
      std::string leading;
      std::string trailing;
      std::string moduleLabel;
      std::vector<uint32_t>::size_type seedVectorSize;
      std::vector<uint32_t> seedVector;
      std::vector<uint32_t>::size_type stateVectorSize;
      std::vector<uint32_t> stateVector;

      // First we need to look for the special strings
      // that mark the end of the file and beginning and
      // and end of the data for different sections.

      is >> leading;
      if (!is.good()) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read next field and did not hit the end yet.\n";
      }

      // This marks the end of the file. We are done.
      if (leading == std::string("</RandomEngineStates>")) return false;

      // This marks the end of a section of the data
      if (leading == std::string("</Event>") ||
          leading == std::string("</Lumi>")) {
        saveToCache = false;
        return true;
      }

      // This marks the beginning of a section
      if (leading == std::string("<Event>") ||
          leading == std::string("<Lumi>")) {
        saveToCache = (leading == whichStates);
        return true;
      }

      // Process the next engine state

      is >> moduleLabel >> trailing;
      if (!is.good() ||
          leading != std::string("<ModuleLabel>") ||
          trailing != std::string("</ModuleLabel>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read a module label when restoring random engine states.\n";
      }

      is >> leading >> seedVectorSize >> trailing;
      if (!is.good() ||
          leading != std::string("<SeedLength>") ||
          trailing != std::string("</SeedLength>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read seed vector length when restoring random engine states.\n";
      }

      is >> leading;
      if (!is.good() ||
          leading != std::string("<InitialSeeds>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read beginning of InitialSeeds when restoring random engine states.\n";
      }

      readVector(is, seedVectorSize, seedVector);      

      is >> trailing;
      if (!is.good() ||
          trailing != std::string("</InitialSeeds>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read end of InitialSeeds when restoring random engine states.\n";
      }

      is >> leading >> stateVectorSize >> trailing;
      if (!is.good() ||
          leading != std::string("<FullStateLength>") ||
          trailing != std::string("</FullStateLength>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read state vector length when restoring random engine states.\n";
      }

      is >> leading;
      if (!is.good() ||
          leading != std::string("<FullState>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read beginning of FullState when restoring random engine states.\n";
      }

      readVector(is, stateVectorSize, stateVector);      

      is >> trailing;
      if (!is.good() ||
          trailing != std::string("</FullState>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n" 
          << "Cannot read end of FullState when restoring random engine states.\n";
      }

      if (saveToCache) {
        RandomEngineState randomEngineState;
        randomEngineState.setLabel(moduleLabel);
        std::vector<RandomEngineState>::iterator state = 
          std::lower_bound(cache.begin(), cache.end(), randomEngineState);

        if (state != cache.end() && moduleLabel == state->getLabel()) {
          if (seedVector.size() != state->getSeed().size() ||
              stateVector.size() != state->getState().size()) {
            throw edm::Exception(edm::errors::Configuration)
              << "File \"" << restoreFileName_ 
              << "\" is ill-structured or otherwise corrupted.\n" 
              << "Vectors containing engine state are the incorrect size for the type of random engine.\n";
          }
          state->setSeed(seedVector);
          state->setState(stateVector);
        }
      }
      return true;
    }
void edm::service::RandomNumberGeneratorService::readEventStatesFromTextFile ( std::string const &  fileName) [private]

Definition at line 986 of file RandomNumberGeneratorService.cc.

References eventCache_, and readStatesFromFile().

Referenced by postBeginLumi().

                                                                                       {
      std::string whichStates("<Event>");
      readStatesFromFile(fileName, eventCache_, whichStates);
    }
void edm::service::RandomNumberGeneratorService::readFromEvent ( Event const &  event) [private]

Definition at line 717 of file RandomNumberGeneratorService.cc.

References backwardCompatibilityRead(), eventCache_, Exception, failedToFindStatesInLumi_, edm::HandleBase::isValid(), edm::errors::ProductNotFound, and restoreStateLabel_.

Referenced by postEventRead().

                                                                  {

      Handle<edm::RandomEngineStates> states;

      event.getByLabel(restoreStateLabel_, states);

      if (!states.isValid()) {
        if (failedToFindStatesInLumi_ && backwardCompatibilityRead(event)) {
          return;
        }
        else {
          throw edm::Exception(edm::errors::ProductNotFound)
            << "The RandomNumberGeneratorService is trying to restore\n"
            << "the state of the random engines by reading a product from\n"
            << "the Event with label \"" << restoreStateLabel_ << "\".  It\n"
            << "fails to find one.  The label used in the request for the product\n"
            << "is set in the configuration. It is probably set to the wrong value\n"
            << "in the configuration file.  It must match the module label\n"
            << "of the RandomEngineStateProducer that created the product in\n"
            << "a previous process\n";
        }
      }
      if (failedToFindStatesInLumi_) {
        throw edm::Exception(edm::errors::ProductNotFound)
          << "The RandomNumberGeneratorService is trying to restore\n"
          << "the state of the random engines by reading a product from\n"
          << "the Event and LuminosityBlock with label \"" << restoreStateLabel_ << "\".\n"
          << "It found the product in the Event but not the one in the LuminosityBlock.\n"
          << "Either the product in the LuminosityBlock was dropped or\n"
          << "there is a bug somewhere\n";
      }
      states->getRandomEngineStates(eventCache_);
    }
void edm::service::RandomNumberGeneratorService::readFromLuminosityBlock ( LuminosityBlock const &  lumi) [private]

Definition at line 702 of file RandomNumberGeneratorService.cc.

References failedToFindStatesInLumi_, edm::LuminosityBlock::getByLabel(), edm::HandleBase::isValid(), lumiCache_, and restoreStateLabel_.

Referenced by preBeginLumi().

                                                                                     {

      Handle<edm::RandomEngineStates> states;

      lumi.getByLabel(restoreStateLabel_, "beginLumi", states);

      if (!states.isValid()) {
        failedToFindStatesInLumi_ = true;
        return;
      }
      failedToFindStatesInLumi_ = false;
      states->getRandomEngineStates(lumiCache_);
    }
void edm::service::RandomNumberGeneratorService::readLumiStatesFromTextFile ( std::string const &  fileName) [private]

Definition at line 992 of file RandomNumberGeneratorService.cc.

References lumiCache_, and readStatesFromFile().

Referenced by preBeginLumi().

                                                                                      {
      std::string whichStates("<Lumi>");
      readStatesFromFile(fileName, lumiCache_, whichStates);
    }
void edm::service::RandomNumberGeneratorService::readStatesFromFile ( std::string const &  fileName,
std::vector< RandomEngineState > &  cache,
std::string const &  whichStates 
) [private]

Definition at line 999 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, Exception, recoMuon::in, readEngineState(), restoreFileName_, and runonSM::text.

Referenced by readEventStatesFromTextFile(), and readLumiStatesFromTextFile().

                                                                                   {
      std::ifstream inFile;
      inFile.open(fileName.c_str(), std::ifstream::in);
      if (!inFile) {
        throw edm::Exception(edm::errors::Configuration)
          << "Unable to open the file \""
          << fileName << "\" to restore the random engine states.\n";
      }

      std::string text;
      inFile >> text;
      if (!inFile.good() || text != std::string("<RandomEngineStates>")) {
        throw edm::Exception(edm::errors::Configuration)
          << "Attempting to read file with random number engine states.\n"
          << "File \"" << restoreFileName_ 
          << "\" is ill-structured or otherwise corrupted.\n"
          << "Cannot read the file header word.\n";
      }
      bool saveToCache = false;
      while (readEngineState(inFile, cache, whichStates, saveToCache)) { }
    }
void edm::service::RandomNumberGeneratorService::readVector ( std::istream &  is,
unsigned  numItems,
std::vector< uint32_t > &  v 
) [private]

Definition at line 1158 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, runTheMatrix::data, Exception, i, and restoreFileName_.

Referenced by readEngineState().

                                                                                                       {
      v.clear();
      v.reserve(numItems);
      uint32_t data;
      for (unsigned i = 0; i < numItems; ++i) {
        is >> data;
        if (!is.good()) {
          throw edm::Exception(edm::errors::Configuration)
            << "File \"" << restoreFileName_ 
            << "\" is ill-structured or otherwise corrupted.\n" 
            << "Cannot read vector when restoring random engine states.\n";
        }
        v.push_back(data);
      }
    }
void edm::service::RandomNumberGeneratorService::restoreFromCache ( std::vector< RandomEngineState > const &  cache) [private]

Definition at line 811 of file RandomNumberGeneratorService.cc.

References checkEngineType(), engineMap_, Exception, seedMap_, and edm::errors::Unknown.

Referenced by postBeginLumi(), postEventRead(), and preBeginLumi().

                                                                                            {
      for (std::vector<RandomEngineState>::const_iterator iter = cache.begin(),
                                                          iEnd = cache.end();
           iter != iEnd; ++iter) {

        std::string const& engineLabel = iter->getLabel();

        std::vector<uint32_t> const& engineState = iter->getState();
        std::vector<unsigned long> engineStateL;
        for (std::vector<uint32_t>::const_iterator iVal = engineState.begin(),
                                                 theEnd = engineState.end();
             iVal != theEnd; ++iVal) {
          engineStateL.push_back(static_cast<unsigned long>(*iVal));
        }

        std::vector<uint32_t> const& engineSeeds = iter->getSeed();
        std::vector<long> engineSeedsL;
        for (std::vector<uint32_t>::const_iterator iVal = engineSeeds.begin(),
                                                 theEnd = engineSeeds.end();
          iVal != theEnd;
          ++iVal) {
          long seedL = static_cast<long>(*iVal);
          engineSeedsL.push_back(seedL);

          // There is a dangerous conversion from uint32_t to long
          // that occurs above. In the next 2 lines we check the
          // behavior is what we need for the service to work
          // properly.  This conversion is forced on us by the
          // CLHEP and ROOT interfaces. If the assert ever starts
          // to fail we will have to come up with a way to deal
          // with this.
          uint32_t seedu32 = static_cast<uint32_t>(seedL);
          assert(*iVal == seedu32);
        }

        EngineMap::iterator engine = engineMap_.find(engineLabel);

        if (engine != engineMap_.end()) {

          seedMap_[engineLabel] = engineSeeds;

          // We need to handle each type of engine differently because each
          // has different requirements on the seed or seeds.
          if (engineStateL[0] == CLHEP::engineIDulong<CLHEP::HepJamesRandom>()) {

            checkEngineType(engine->second->name(), std::string("HepJamesRandom"), engineLabel);

            // These two lines actually restore the seed and engine state.
            engine->second->setSeed(engineSeedsL[0], 0);
            engine->second->get(engineStateL);
          }
          else if (engineStateL[0] == CLHEP::engineIDulong<CLHEP::RanecuEngine>()) {

            checkEngineType(engine->second->name(), std::string("RanecuEngine"), engineLabel);

            // This line actually restores the engine state.
            engine->second->get(engineStateL);
          }
          else if (engineStateL[0] == CLHEP::engineIDulong<TRandomAdaptor>()) {

            checkEngineType(engine->second->name(), std::string("TRandom3"), engineLabel);

            // This line actually restores the engine state.
            engine->second->setSeed(engineSeedsL[0], 0);
            engine->second->get(engineStateL);
          }
          // This should not be possible because this code should be able to restore
          // any kind of engine whose state can be saved.
          else {
            throw edm::Exception(edm::errors::Unknown)
              << "The RandomNumberGeneratorService is trying to restore the state\n"
                 "of the random engines.  The state in the event indicates an engine\n"
                 "of an unknown type.  This should not be possible unless you are\n"
                 "running with an old code release on a new file that was created\n"
                 "with a newer release which had new engine types added.  In this case\n"
                 "the only solution is to use a newer release.  In any other case, notify\n"
                 "the EDM developers because this should not be possible\n";
          }
        }
      }
    }
void edm::service::RandomNumberGeneratorService::saveStatesToFile ( std::string const &  fileName) [private]

Definition at line 916 of file RandomNumberGeneratorService.cc.

References edm::errors::Configuration, eventCache_, Exception, lumiCache_, dbtoconf::out, and writeStates().

Referenced by postEventRead().

    {
      std::ofstream outFile;
      outFile.open(fileName.c_str(), std::ofstream::out | std::ofstream::trunc);
      if (!outFile) {
        throw edm::Exception(edm::errors::Configuration)
          << "Unable to open the file \""
          << fileName << "\" to save the state of the random engines.\n";
      }
      outFile << "<RandomEngineStates>\n";

      outFile << "<Event>\n";
      writeStates(eventCache_, outFile);
      outFile << "</Event>\n" ;

      outFile << "<Lumi>\n";
      writeStates(lumiCache_, outFile);
      outFile << "</Lumi>\n" ;

      outFile << "</RandomEngineStates>\n" ;
    }
void edm::service::RandomNumberGeneratorService::snapShot ( std::vector< RandomEngineState > &  cache) [private]

Definition at line 787 of file RandomNumberGeneratorService.cc.

References engineMap_, seedMap_, and evf::utils::state.

Referenced by postBeginLumi(), postEventRead(), and preBeginLumi().

    {
      cache.resize(engineMap_.size());
      std::vector<RandomEngineState>::iterator state = cache.begin();

      for (EngineMap::const_iterator iter = engineMap_.begin();
           iter != engineMap_.end();
           ++iter, ++state) {

        state->setLabel(iter->first);
        state->setSeed(seedMap_[iter->first]);

        std::vector<unsigned long> stateL = iter->second->put();
        state->clearStateVector();
        state->reserveStateVector(stateL.size());
        for (std::vector<unsigned long>::const_iterator vIter = stateL.begin();
             vIter != stateL.end();
             ++vIter) {
          state->push_back_stateVector(static_cast<uint32_t>(*vIter));
        }
      }
    }
void edm::service::RandomNumberGeneratorService::startNewSequencesForEvents ( ) [private]

Definition at line 1175 of file RandomNumberGeneratorService.cc.

References childIndex_, engineMap_, engineNameMap_, eventSeedOffset_, maxSeedHepJames, maxSeedRanecu, maxSeedTRandom3, mod(), moduleLabel(), and seedMap_.

Referenced by postBeginLumi().

                                                             {

      if (childIndex_ == 0U && eventSeedOffset_ == 0U) return;

      for (EngineMap::const_iterator iter = engineMap_.begin();
           iter != engineMap_.end();
           ++iter) {

        uint32_t offset1 = childIndex_;
        uint32_t offset2 = eventSeedOffset_;

        std::string const& moduleLabel = iter->first;
        std::string const& engineName = engineNameMap_[moduleLabel];
        VUint32 & seeds = seedMap_[moduleLabel];

       if (engineName == std::string("RanecuEngine")) {
          assert(seeds.size() == 2U);
          // Wrap around if the offsets push the seed over the maximum allowed value
          uint32_t mod = maxSeedRanecu + 1U;
          offset1 = offset1 % mod;
          offset2 = offset2 % mod;
          seeds[0] = (seeds[0] + offset1) % mod;
          seeds[0] = (seeds[0] + offset2) % mod;
          long int seedL[2];
          seedL[0] = static_cast<long int>(seeds[0]);
          seedL[1] = static_cast<long int>(seeds[1]);
          iter->second->setSeeds(seedL,0);
        }
        else {
          assert(seeds.size() == 1U);

          if (engineName == "HepJamesRandom") {
            // Wrap around if the offsets push the seed over the maximum allowed value
            uint32_t mod = maxSeedHepJames + 1U;
            offset1 = offset1 % mod;
            offset2 = offset2 % mod;
            seeds[0] = (seeds[0] + offset1) % mod;
            seeds[0] = (seeds[0] + offset2) % mod;

            long int seedL = static_cast<long int>(seeds[0]);
            iter->second->setSeed(seedL, 0);
          }
          else {
            assert(engineName == "TRandom3");
            // Wrap around if the offsets push the seed over the maximum allowed value
            // We have to be extra careful with this one because it may also go beyond
            // the values 32 bits can hold
            uint32_t max32 = maxSeedTRandom3;
            if ((max32 - seeds[0]) >= offset1) {
              seeds[0] = seeds[0] + offset1;
            }
            else {
              seeds[0] = offset1 - (max32 - seeds[0]) - 1U;
            }
            if ((max32 - seeds[0]) >= offset2) {
              seeds[0] = seeds[0] + offset2;
            }
            else {
              seeds[0] = offset2 - (max32 - seeds[0]) - 1U;
            }
            long seedL = static_cast<long>(seeds[0]);

            // There is a dangerous conversion from uint32_t to long
            // that occurs above. In the next 2 lines we check the
            // behavior is what we need for the service to work
            // properly.  This conversion is forced on us by the
            // CLHEP and ROOT interfaces. If the assert ever starts
            // to fail we will have to come up with a way to deal
            // with this.
            uint32_t seedu32 = static_cast<uint32_t>(seedL);
            assert(seeds[0] == seedu32);

            iter->second->setSeed(seedL, 0);
          }
        }
      }
    }
void edm::service::RandomNumberGeneratorService::writeStates ( std::vector< RandomEngineState > const &  v,
std::ofstream &  outFile 
) [private]

Definition at line 939 of file RandomNumberGeneratorService.cc.

References writeVector().

Referenced by saveStatesToFile().

                                                                     {
      for (std::vector<RandomEngineState>::const_iterator iter = v.begin(),
                                                          iEnd = v.end();
        iter != iEnd; ++iter) {

        std::vector<uint32_t> const& seedVector = iter->getSeed();
        std::vector<uint32_t>::size_type seedVectorLength = seedVector.size();

        std::vector<uint32_t> const& stateVector = iter->getState();
        std::vector<uint32_t>::size_type stateVectorLength = stateVector.size();

        outFile << "<ModuleLabel>\n" << iter->getLabel() << "\n</ModuleLabel>\n";

        outFile << "<SeedLength>\n" << seedVectorLength << "\n</SeedLength>\n" ;
        outFile << "<InitialSeeds>\n";
        writeVector(seedVector, outFile);
        outFile << "</InitialSeeds>\n";
        outFile << "<FullStateLength>\n" << stateVectorLength << "\n</FullStateLength>\n";
        outFile << "<FullState>\n";
        writeVector(stateVector, outFile);
        outFile   << "</FullState>\n";
      }
    }
void edm::service::RandomNumberGeneratorService::writeVector ( VUint32 const &  v,
std::ofstream &  outFile 
) [private]

Definition at line 965 of file RandomNumberGeneratorService.cc.

References i.

Referenced by writeStates().

    {
      if (v.empty()) return;
      size_t numItems = v.size();
      for (size_t i = 0; i < numItems; ++i)  {
        if (i != 0 && i % 10 == 0) outFile << "\n";
        outFile << std::setw(13) << v[i];
      }
      outFile << "\n";
    }

Member Data Documentation

std::map<std::string, std::string> edm::service::RandomNumberGeneratorService::engineNameMap_ [private]
std::vector<EngineMap::const_iterator> edm::service::RandomNumberGeneratorService::engineStack_ [private]

Definition at line 159 of file RandomNumberGeneratorService.h.

Referenced by pop(), print(), push(), and RandomNumberGeneratorService().

std::vector<std::vector<unsigned long> > edm::service::RandomNumberGeneratorService::engineStateStack_ [private]

Definition at line 208 of file RandomNumberGeneratorService.h.

Referenced by startNewSequencesForEvents().

Definition at line 210 of file RandomNumberGeneratorService.h.

Referenced by readFromEvent(), and readFromLuminosityBlock().

Definition at line 202 of file RandomNumberGeneratorService.h.

Referenced by postBeginLumi(), and preBeginLumi().

Definition at line 162 of file RandomNumberGeneratorService.h.

Referenced by pop(), print(), push(), and RandomNumberGeneratorService().

uint32_t edm::service::RandomNumberGeneratorService::maxSeedHepJames = 900000000U [static, private]
uint32_t edm::service::RandomNumberGeneratorService::maxSeedRanecu = 2147483647U [static, private]
uint32_t edm::service::RandomNumberGeneratorService::maxSeedTRandom3 = 4294967295U [static, private]

Definition at line 214 of file RandomNumberGeneratorService.h.

Referenced by startNewSequencesForEvents().

Definition at line 189 of file RandomNumberGeneratorService.h.

Referenced by postEventRead().