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