CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
PileUp.cc
Go to the documentation of this file.
16 
19 
25 
26 #include "CLHEP/Random/RandPoissonQ.h"
27 #include "CLHEP/Random/RandPoisson.h"
28 
29 #include <algorithm>
30 #include <memory>
31 
32 namespace edm {
33  PileUp::PileUp(ParameterSet const& pset, std::string sourcename, double averageNumber, TH1F * const histo, const bool playback) :
34  type_(pset.getParameter<std::string>("type")),
35  Source_type_(sourcename),
36  averageNumber_(averageNumber),
37  intAverage_(static_cast<int>(averageNumber)),
38  histo_(histo),
39  histoDistribution_(type_ == "histo"),
40  probFunctionDistribution_(type_ == "probFunction"),
41  poisson_(type_ == "poisson"),
42  fixed_(type_ == "fixed"),
43  none_(type_ == "none"),
44  fileNameHash_(0U),
45  productRegistry_(new SignallingProductRegistry),
46  input_(VectorInputSourceFactory::get()->makeVectorInputSource(pset, InputSourceDescription(
48  *productRegistry_,
49  std::make_shared<BranchIDListHelper>(),
50  std::make_shared<ThinnedAssociationsHelper>(),
51  std::make_shared<ActivityRegistry>(),
52  -1, -1, -1,
54  )).release()),
55  processConfiguration_(new ProcessConfiguration(std::string("@MIXING"), getReleaseVersion(), getPassID())),
56  eventPrincipal_(),
57  lumiPrincipal_(),
58  runPrincipal_(),
59  provider_(),
60  vPoissonDistribution_(),
61  vPoissonDistr_OOT_(),
62  randomEngines_(),
63  playback_(playback),
64  sequential_(pset.getUntrackedParameter<bool>("sequential", false)),
65  samelumi_(pset.getUntrackedParameter<bool>("sameLumiBlock", false)),
66  seed_(0) {
67 
68  // Use the empty parameter set for the parameter set ID of our "@MIXING" process.
70 
71  if(pset.existsAs<std::vector<ParameterSet> >("producers", true)) {
72  std::vector<ParameterSet> producers = pset.getParameter<std::vector<ParameterSet> >("producers");
74  }
75 
76  productRegistry_->setFrozen();
77 
78  // A modified HistoryAppender must be used for unscheduled processing.
79  eventPrincipal_.reset(new EventPrincipal(input_->productRegistry(),
80  input_->branchIDListHelper(),
81  input_->thinnedAssociationsHelper(),
83  nullptr));
84 
85  if (pset.exists("nbPileupEvents")) {
86  seed_=pset.getParameter<edm::ParameterSet>("nbPileupEvents").getUntrackedParameter<int>("seed",0);
87  }
88 
89  bool DB=type_=="readDB";
90 
92  if (!rng.isAvailable()) {
93  throw cms::Exception("Configuration")
94  << "PileUp requires the RandomNumberGeneratorService\n"
95  "which is not present in the configuration file. You must add the service\n"
96  "in the configuration file or remove the modules that require it.";
97  }
98 
99  // Get seed for the case when using user histogram or probability function
100  // RANDOM_NUMBER_ERROR
101  // Random number should be generated by the engines from the
102  // RandomNumberGeneratorService. This appears to use the global
103  // engine in ROOT. This is not thread safe unless the module using
104  // it is a one module and declares a shared resource and all
105  // other modules using it also declare the same shared resource.
106  // This also breaks replay.
108  if(seed_ !=0) {
109  gRandom->SetSeed(seed_);
110  LogInfo("MixingModule") << " Change seed for " << type_ << " mode. The seed is set to " << seed_;
111  }
112  else {
113  gRandom->SetSeed(rng->mySeed());
114  }
115  }
116 
118  throw cms::Exception("Illegal parameter value","PileUp::PileUp(ParameterSet const& pset)")
119  << "'type' parameter (a string) has a value of '" << type_ << "'.\n"
120  << "Legal values are 'poisson', 'fixed', or 'none'\n";
121  }
122 
123  if (!DB){
124  manage_OOT_ = pset.getUntrackedParameter<bool>("manage_OOT", false);
125 
126  // Check for string describing special processing. Add these here for individual cases
127 
128  PU_Study_ = false;
129  Study_type_ = "";
130 
131  Study_type_ = pset.getUntrackedParameter<std::string>("Special_Pileup_Studies", "");
132 
133  if(Study_type_ == "Fixed_ITPU_Vary_OOTPU") {
134 
135  PU_Study_ = true;
136  intFixed_ITPU_ = pset.getUntrackedParameter<int>("intFixed_ITPU", 0);
137 
138  }
139 
140  if(manage_OOT_) { // figure out what the parameters are
141 
142  // if (playback_) throw cms::Exception("Illegal parameter clash","PileUp::PileUp(ParameterSet const& pset)")
143  // << " manage_OOT option not allowed with playback ";
144 
145  std::string OOT_type = pset.getUntrackedParameter<std::string>("OOT_type");
146 
147  if(OOT_type == "Poisson" || OOT_type == "poisson") {
148  poisson_OOT_ = true;
149  }
150  else if(OOT_type == "Fixed" || OOT_type == "fixed") {
151  fixed_OOT_ = true;
152  // read back the fixed number requested out-of-time
153  intFixed_OOT_ = pset.getUntrackedParameter<int>("intFixed_OOT", -1);
154  if(intFixed_OOT_ < 0) {
155  throw cms::Exception("Illegal parameter value","PileUp::PileUp(ParameterSet const& pset)")
156  << " Fixed out-of-time pileup requested, but no fixed value given ";
157  }
158  }
159  else {
160  throw cms::Exception("Illegal parameter value","PileUp::PileUp(ParameterSet const& pset)")
161  << "'OOT_type' parameter (a string) has a value of '" << OOT_type << "'.\n"
162  << "Legal values are 'poisson' or 'fixed'\n";
163  }
164  edm::LogInfo("MixingModule") <<" Out-of-time pileup will be generated with a " << OOT_type << " distribution. " ;
165  }
166  }
167 
168  if(Source_type_ == "cosmics") { // allow for some extra flexibility for mixing
169  minBunch_cosmics_ = pset.getUntrackedParameter<int>("minBunch_cosmics", -1000);
170  maxBunch_cosmics_ = pset.getUntrackedParameter<int>("maxBunch_cosmics", 1000);
171  }
172 
173 
174 
175  } // end of constructor
176 
177 
178 
179 
180 
182  input_->doBeginJob();
183  if (provider_.get() != nullptr) {
184  provider_->beginJob(*productRegistry_);
185  }
186  }
187 
188  void PileUp::endJob () {
189  if (provider_.get() != nullptr) {
190  provider_->endJob();
191  }
192  input_->doEndJob();
193  }
194 
196  if (provider_.get() != nullptr) {
197  auto aux = std::make_shared<RunAuxiliary>(run.runAuxiliary());
199  provider_->beginRun(*runPrincipal_, setup, run.moduleCallingContext());
200  }
201  }
203  if (provider_.get() != nullptr) {
204  auto aux = std::make_shared<LuminosityBlockAuxiliary>(lumi.luminosityBlockAuxiliary());
206  lumiPrincipal_->setRunPrincipal(runPrincipal_);
207  provider_->beginLuminosityBlock(*lumiPrincipal_, setup, lumi.moduleCallingContext());
208  }
209  }
210 
212  if (provider_.get() != nullptr) {
213  provider_->endRun(*runPrincipal_, setup, run.moduleCallingContext());
214  }
215  }
217  if (provider_.get() != nullptr) {
218  provider_->endLuminosityBlock(*lumiPrincipal_, setup, lumi.moduleCallingContext());
219  }
220  }
221 
223  if (provider_.get() != nullptr) {
224  // note: run and lumi numbers must be modified to match lumiPrincipal_
225  eventPrincipal_->setLuminosityBlockPrincipal(lumiPrincipal_);
226  eventPrincipal_->setRunAndLumiNumber(lumiPrincipal_->run(), lumiPrincipal_->luminosityBlock());
227  provider_->setupPileUpEvent(*eventPrincipal_, setup);
228  }
229  }
230 
232  //get the required parameters from DB.
234  setup.get<MixingRcd>().get(configM);
235 
236  const MixingInputConfig & config=configM->config(inputType_);
237 
238  //get the type
239  type_=config.type();
240  //set booleans
241  histoDistribution_=type_ == "histo";
242  probFunctionDistribution_=type_ == "probFunction";
243  poisson_=type_ == "poisson";
244  fixed_=type_ == "fixed";
245  none_=type_ == "none";
246 
247  if (histoDistribution_) edm::LogError("MisConfiguration")<<"type histo cannot be reloaded from DB, yet";
248 
249  if (fixed_){
251  }
252  else if (poisson_)
253  {
254  averageNumber_=config.averageNumber();
255  for(auto & distribution : vPoissonDistribution_) {
256  if(distribution) {
257  distribution.reset(new CLHEP::RandPoissonQ(distribution->engine(), averageNumber_));
258  }
259  }
260  }
261  else if (probFunctionDistribution_)
262  {
263  //need to reload the histogram from DB
264  const std::vector<int> & dataProbFunctionVar = config.probFunctionVariable();
265  std::vector<double> dataProb = config.probValue();
266 
267  int varSize = (int) dataProbFunctionVar.size();
268  int probSize = (int) dataProb.size();
269 
270  if ((dataProbFunctionVar[0] != 0) || (dataProbFunctionVar[varSize - 1] != (varSize - 1)))
271  throw cms::Exception("BadProbFunction") << "Please, check the variables of the probability function! The first variable should be 0 and the difference between two variables should be 1." << std::endl;
272 
273  // Complete the vector containing the probability function data
274  // with the values "0"
275  if (probSize < varSize){
276  edm::LogWarning("MixingModule") << " The probability function data will be completed with " <<(varSize - probSize) <<" values 0.";
277 
278  for (int i=0; i<(varSize - probSize); i++) dataProb.push_back(0);
279 
280  probSize = dataProb.size();
281  edm::LogInfo("MixingModule") << " The number of the P(x) data set after adding the values 0 is " << probSize;
282  }
283 
284  // Create an histogram with the data from the probability function provided by the user
285  int xmin = (int) dataProbFunctionVar[0];
286  int xmax = (int) dataProbFunctionVar[varSize-1]+1; // need upper edge to be one beyond last value
287  int numBins = varSize;
288 
289  edm::LogInfo("MixingModule") << "An histogram will be created with " << numBins << " bins in the range ("<< xmin << "," << xmax << ")." << std::endl;
290 
291  if (histo_) delete histo_;
292  histo_ = new TH1F("h","Histo from the user's probability function",numBins,xmin,xmax);
293 
294  LogDebug("MixingModule") << "Filling histogram with the following data:" << std::endl;
295 
296  for (int j=0; j < numBins ; j++){
297  LogDebug("MixingModule") << " x = " << dataProbFunctionVar[j ]<< " P(x) = " << dataProb[j];
298  histo_->Fill(dataProbFunctionVar[j]+0.5,dataProb[j]); // assuming integer values for the bins, fill bin centers, not edges
299  }
300 
301  // Check if the histogram is normalized
302  if ( ((histo_->Integral() - 1) > 1.0e-02) && ((histo_->Integral() - 1) < -1.0e-02)){
303  throw cms::Exception("BadProbFunction") << "The probability function should be normalized!!! " << std::endl;
304  }
305  averageNumber_=histo_->GetMean();
306  }
307 
308  int oot=config.outOfTime();
309  manage_OOT_=false;
310  if (oot==1)
311  {
312  manage_OOT_=true;
313  poisson_OOT_ = false;
314  fixed_OOT_ = true;
315  intFixed_OOT_=config.fixedOutOfTime();
316  }
317  else if (oot==2)
318  {
319  manage_OOT_=true;
320  poisson_OOT_ = true;
321  fixed_OOT_ = false;
322  }
323 
324 
325  }
327  }
328 
329  std::unique_ptr<CLHEP::RandPoissonQ> const& PileUp::poissonDistribution(StreamID const& streamID) {
330  unsigned int index = streamID.value();
331  if(index >= vPoissonDistribution_.size()) {
332  // This resizing is not thread safe and only works because
333  // this is used by a "one" type module
334  vPoissonDistribution_.resize(index + 1);
335  }
336  std::unique_ptr<CLHEP::RandPoissonQ>& ptr = vPoissonDistribution_[index];
337  if(!ptr) {
338  CLHEP::HepRandomEngine& engine = *randomEngine(streamID);
339  ptr.reset(new CLHEP::RandPoissonQ(engine, averageNumber_));
340  }
341  return ptr;
342  }
343 
344  std::unique_ptr<CLHEP::RandPoisson> const& PileUp::poissonDistr_OOT(StreamID const& streamID) {
345  unsigned int index = streamID.value();
346  if(index >= vPoissonDistr_OOT_.size()) {
347  // This resizing is not thread safe and only works because
348  // this is used by a "one" type module
349  vPoissonDistr_OOT_.resize(index + 1);
350  }
351  std::unique_ptr<CLHEP::RandPoisson>& ptr = vPoissonDistr_OOT_[index];
352  if(!ptr) {
353  CLHEP::HepRandomEngine& engine = *randomEngine(streamID);
354  ptr.reset(new CLHEP::RandPoisson(engine));
355  }
356  return ptr;
357  }
358 
359  CLHEP::HepRandomEngine* PileUp::randomEngine(StreamID const& streamID) {
360  unsigned int index = streamID.value();
361  if(index >= randomEngines_.size()) {
362  // This resizing is not thread safe and only works because
363  // this is used by a "one" type module
364  randomEngines_.resize(index + 1, nullptr);
365  }
366  CLHEP::HepRandomEngine* ptr = randomEngines_[index];
367  if(!ptr) {
369  ptr = &rng->getEngine(streamID);
370  randomEngines_[index] = ptr;
371  }
372  return ptr;
373  }
374 
375  void PileUp::CalculatePileup(int MinBunch, int MaxBunch, std::vector<int>& PileupSelection, std::vector<float>& TrueNumInteractions, StreamID const& streamID) {
376 
377  // if we are managing the distribution of out-of-time pileup separately, select the distribution for bunch
378  // crossing zero first, save it for later.
379 
380  int nzero_crossing = -1;
381  double Fnzero_crossing = -1;
382 
383  if(manage_OOT_) {
384  if (none_){
385  nzero_crossing = 0;
386  }else if (poisson_){
387  nzero_crossing = poissonDistribution(streamID)->fire() ;
388  }else if (fixed_){
389  nzero_crossing = intAverage_ ;
391  // RANDOM_NUMBER_ERROR
392  // Random number should be generated by the engines from the
393  // RandomNumberGeneratorService. This appears to use the global
394  // engine in ROOT. This is not thread safe unless the module using
395  // it is a one module and declares a shared resource and all
396  // other modules using it also declare the same shared resource.
397  // This also breaks replay.
398  double d = histo_->GetRandom();
399  //n = (int) floor(d + 0.5); // incorrect for bins with integer edges
400  Fnzero_crossing = d;
401  nzero_crossing = int(d);
402  }
403 
404  }
405 
406  for(int bx = MinBunch; bx < MaxBunch+1; ++bx) {
407 
408  if(manage_OOT_) {
409  if(bx==0 && !poisson_OOT_) {
410  PileupSelection.push_back(nzero_crossing) ;
411  TrueNumInteractions.push_back( nzero_crossing );
412  }
413  else{
414  if(poisson_OOT_) {
415  if(PU_Study_ && (Study_type_ == "Fixed_ITPU_Vary_OOTPU" ) && bx==0 ) {
416  PileupSelection.push_back(intFixed_ITPU_) ;
417  }
418  else{
419  PileupSelection.push_back(poissonDistr_OOT(streamID)->fire(Fnzero_crossing)) ;
420  }
421  TrueNumInteractions.push_back( Fnzero_crossing );
422  }
423  else {
424  PileupSelection.push_back(intFixed_OOT_) ;
425  TrueNumInteractions.push_back( intFixed_OOT_ );
426  }
427  }
428  }
429  else {
430  if (none_){
431  PileupSelection.push_back(0);
432  TrueNumInteractions.push_back( 0. );
433  }else if (poisson_){
434  PileupSelection.push_back(poissonDistribution(streamID)->fire());
435  TrueNumInteractions.push_back( averageNumber_ );
436  }else if (fixed_){
437  PileupSelection.push_back(intAverage_);
438  TrueNumInteractions.push_back( intAverage_ );
440  // RANDOM_NUMBER_ERROR
441  // Random number should be generated by the engines from the
442  // RandomNumberGeneratorService. This appears to use the global
443  // engine in ROOT. This is not thread safe unless the module using
444  // it is a one module and declares a shared resource and all
445  // other modules using it also declare the same shared resource.
446  // This also breaks replay.
447  double d = histo_->GetRandom();
448  PileupSelection.push_back(int(d));
449  TrueNumInteractions.push_back( d );
450  }
451  }
452 
453  }
454  }
455 
456 
457 } //namespace edm
#define LogDebug(id)
bool manage_OOT_
Definition: PileUp.h:96
T getParameter(std::string const &) const
T getUntrackedParameter(std::string const &, T const &) const
std::string getPassID()
Definition: GetPassID.h:8
int i
Definition: DBlmapReader.cc:9
std::unique_ptr< SecondaryEventProvider > provider_
Definition: PileUp.h:117
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:185
std::shared_ptr< ProcessConfiguration > processConfiguration_
Definition: PileUp.h:113
unsigned int inputType_
Definition: PileUp.h:85
const int fixedOutOfTime() const
tuple lumi
Definition: fjr2json.py:35
bool exists(std::string const &parameterName) const
checks if a parameter exists
void endJob()
Definition: PileUp.cc:188
TH1F * histo_
Definition: PileUp.h:90
bool fixed_
Definition: PileUp.h:94
const std::vector< double > & probValue() const
PileUp(ParameterSet const &pset, std::string sourcename, double averageNumber, TH1F *const histo, const bool playback)
Definition: PileUp.cc:33
const double averageNumber() const
ModuleCallingContext const * moduleCallingContext() const
std::vector< CLHEP::HepRandomEngine * > randomEngines_
Definition: PileUp.h:120
int const intAverage_
Definition: PileUp.h:89
bool probFunctionDistribution_
Definition: PileUp.h:92
int maxBunch_cosmics_
Definition: PileUp.h:108
std::string Study_type_
Definition: PileUp.h:101
tuple d
Definition: ztail.py:151
bool histoDistribution_
Definition: PileUp.h:91
bool poisson_
Definition: PileUp.h:93
void endLuminosityBlock(const edm::LuminosityBlock &lumi, const edm::EventSetup &setup)
Definition: PileUp.cc:216
double averageNumber() const
Definition: PileUp.h:44
const int outOfTime() const
virtual std::uint32_t mySeed() const =0
std::vector< std::unique_ptr< CLHEP::RandPoissonQ > > vPoissonDistribution_
Definition: PileUp.h:118
std::unique_ptr< VectorInputSource > const input_
Definition: PileUp.h:112
bool poisson_OOT_
Definition: PileUp.h:97
void beginJob()
Definition: PileUp.cc:181
tuple averageNumber
set the number of pileup
bool isAvailable() const
Definition: Service.h:46
int j
Definition: DBlmapReader.cc:9
int intFixed_ITPU_
Definition: PileUp.h:105
void beginRun(const edm::Run &run, const edm::EventSetup &setup)
Definition: PileUp.cc:195
std::unique_ptr< CLHEP::RandPoissonQ > const & poissonDistribution(StreamID const &streamID)
Definition: PileUp.cc:329
void CalculatePileup(int MinBunch, int MaxBunch, std::vector< int > &PileupSelection, std::vector< float > &TrueNumInteractions, StreamID const &)
Definition: PileUp.cc:375
bool PU_Study_
Definition: PileUp.h:100
void beginLuminosityBlock(const edm::LuminosityBlock &lumi, const edm::EventSetup &setup)
Definition: PileUp.cc:202
bool fixed_OOT_
Definition: PileUp.h:98
int minBunch_cosmics_
Definition: PileUp.h:107
std::string getReleaseVersion()
void setupPileUpEvent(const edm::EventSetup &setup)
Definition: PileUp.cc:222
unsigned int value() const
Definition: StreamID.h:46
std::shared_ptr< LuminosityBlockPrincipal > lumiPrincipal_
Definition: PileUp.h:115
std::string type_
Definition: PileUp.h:86
LuminosityBlockAuxiliary const & luminosityBlockAuxiliary() const
const T & get() const
Definition: EventSetup.h:55
void endRun(const edm::Run &run, const edm::EventSetup &setup)
Definition: PileUp.cc:211
const std::vector< int > & probFunctionVariable() const
RunAuxiliary const & runAuxiliary() const
Definition: Run.h:55
std::shared_ptr< ProductRegistry > productRegistry_
Definition: PileUp.h:111
std::string Source_type_
Definition: PileUp.h:87
std::unique_ptr< CLHEP::RandPoisson > const & poissonDistr_OOT(StreamID const &streamID)
Definition: PileUp.cc:344
void reload(const edm::EventSetup &setup)
Definition: PileUp.cc:231
int seed_
Definition: PileUp.h:136
ModuleCallingContext const * moduleCallingContext() const
Definition: Run.h:143
bool none_
Definition: PileUp.h:95
CLHEP::HepRandomEngine * randomEngine(StreamID const &streamID)
Definition: PileUp.cc:359
std::vector< std::unique_ptr< CLHEP::RandPoisson > > vPoissonDistr_OOT_
Definition: PileUp.h:119
int intFixed_OOT_
Definition: PileUp.h:104
volatile std::atomic< bool > shutdown_flag false
std::unique_ptr< EventPrincipal > eventPrincipal_
Definition: PileUp.h:114
std::string type() const
std::shared_ptr< RunPrincipal > runPrincipal_
Definition: PileUp.h:116
static ParameterSetID emptyParameterSetID()
void setup(std::vector< TH2F > &depth, std::string name, std::string units="")
T get(const Candidate &c)
Definition: component.h:55
double averageNumber_
Definition: PileUp.h:88
Definition: Run.h:41