test
CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
SherpaHadronizer.cc
Go to the documentation of this file.
1 #include <cassert>
2 #include <iostream>
3 #include <sstream>
4 #include <string>
5 #include <memory>
6 #include <stdint.h>
7 #include <vector>
8 
9 
10 #include "SHERPA/Main/Sherpa.H"
11 #include "ATOOLS/Math/Random.H"
12 
13 #include "ATOOLS/Org/Run_Parameter.H"
14 #include "ATOOLS/Org/MyStrStream.H"
15 
21 
22 #include "CLHEP/Random/RandomEngine.h"
23 
24 
25 //This unnamed namespace is used (instead of static variables) to pass the
26 //randomEngine passed to doSetRandomEngine to the External Random
27 //Number Generator CMS_SHERPA_RNG of sherpa
28 //The advantage of the unnamed namespace over static variables is
29 //that it is only accessible in this file
30 
31 namespace {
32  CLHEP::HepRandomEngine* ExternalEngine=nullptr;
33  CLHEP::HepRandomEngine* GetExternalEngine() { return ExternalEngine; }
34  void SetExternalEngine(CLHEP::HepRandomEngine* v) { ExternalEngine=v; }
35 }
36 
38 public:
39  SherpaHadronizer(const edm::ParameterSet &params);
41 
42  bool readSettings( int ) { return true; }
44  bool declareStableParticles(const std::vector<int> &pdgIds);
45  bool declareSpecialSettings( const std::vector<std::string>& ) { return true; }
46  void statistics();
48  bool decay();
49  bool residualDecay();
50  void finalizeEvent();
51  const char *classname() const { return "SherpaHadronizer"; }
52 
53 
54 private:
55 
56  virtual void doSetRandomEngine(CLHEP::HepRandomEngine* v) override;
57 
65  unsigned int maxEventsToPrint;
66  std::vector<std::string> arguments;
71  std::vector<std::string> weightlist;
72  std::vector<std::string> variationweightlist;
73 };
74 
75 
76 
77 
78 class CMS_SHERPA_RNG: public ATOOLS::External_RNG {
79 public:
80 
82  edm::LogVerbatim("SherpaHadronizer") << "Use stored reference for the external RNG";
83  setRandomEngine(GetExternalEngine());
84  }
85  void setRandomEngine(CLHEP::HepRandomEngine* v) { randomEngine = v; }
86 
87 private:
88  double Get() override;
89  CLHEP::HepRandomEngine* randomEngine;
90 };
91 
92 
93 void SherpaHadronizer::doSetRandomEngine(CLHEP::HepRandomEngine* v) {
94  CMS_SHERPA_RNG* cmsSherpaRng = dynamic_cast<CMS_SHERPA_RNG*>(ATOOLS::ran->GetExternalRng());
95  //~ assert(cmsSherpaRng != nullptr);
96  if (cmsSherpaRng ==nullptr) {
97  //First time call to this function makes the interface store the reference in the unnamed namespace
98  if (!isRNGinitialized){
99  isRNGinitialized=true;
100  edm::LogVerbatim("SherpaHadronizer") << "Store assigned reference of the randomEngine";
101  SetExternalEngine(v);
102  // Throw exception if there is no reference to an external RNG and it is not the first call!
103  } else {
105  << "The Sherpa interface got a randomEngine reference but there is no reference to the external RNG to hand it over to\n";
106  }
107  } else {
108  cmsSherpaRng->setRandomEngine(v);
109  }
110 }
111 
113  BaseHadronizer(params),
114  SherpaParameterSet(params.getParameter<edm::ParameterSet>("SherpaParameters")),
115  isRNGinitialized(false)
116 {
117  if (!params.exists("SherpaProcess")) SherpaProcess="";
118  else SherpaProcess=params.getParameter<std::string>("SherpaProcess");
119  if (!params.exists("SherpaPath")) SherpaPath="";
120  else SherpaPath=params.getParameter<std::string>("SherpaPath");
121  if (!params.exists("SherpaPathPiece")) SherpaPathPiece="";
122  else SherpaPathPiece=params.getParameter<std::string>("SherpaPathPiece");
123  if (!params.exists("SherpaResultDir")) SherpaResultDir="Result";
124  else SherpaResultDir=params.getParameter<std::string>("SherpaResultDir");
125  if (!params.exists("SherpaDefaultWeight")) SherpaDefaultWeight=1.;
126  else SherpaDefaultWeight=params.getParameter<double>("SherpaDefaultWeight");
127  if (!params.exists("maxEventsToPrint")) maxEventsToPrint=0;
128  else maxEventsToPrint=params.getParameter<int>("maxEventsToPrint");
129 // if hepmcextendedweights is used the event weights have to be reordered ( unordered list can be accessed via event->weights().write() )
130 // two lists have to be provided:
131 // 1) SherpaWeights
132 // - containing nominal event weight, combined matrix element and phase space weight, event normalization, and possibly other sherpa weights
133 // 2) SherpaVariationsWeights
134 // - containing weights from scale and PDF variations ( have to be defined in the runcard )
135 // - in case of unweighted events these weights are also divided by the event normalization (see list 1 )
136 // Sherpa Documentation: http://sherpa.hepforge.org/doc/SHERPA-MC-2.2.0.html#Scale-and-PDF-variations
137  if (!params.exists("SherpaWeightsBlock")) {
138  rearrangeWeights=false;
139  } else {
140  rearrangeWeights=true;
141  edm::ParameterSet WeightsBlock = params.getParameter<edm::ParameterSet>("SherpaWeightsBlock");
142  if (WeightsBlock.exists("SherpaWeights"))
143  weightlist=WeightsBlock.getParameter< std::vector<std::string> >("SherpaWeights");
144  else
145  throw cms::Exception("SherpaInterface") <<"SherpaWeights does not exists in SherpaWeightsBlock" << std::endl;
146  if (WeightsBlock.exists("SherpaVariationWeights"))
147  variationweightlist=WeightsBlock.getParameter< std::vector<std::string> >("SherpaVariationWeights");
148  else
149  throw cms::Exception("SherpaInterface") <<"SherpaVariationWeights does not exists in SherpaWeightsBlock" << std::endl;
150  edm::LogVerbatim("SherpaHadronizer") << "SherpaHadronizer will try rearrange the event weights according to SherpaWeights and SherpaVariationWeights";
151  }
152 
153 
154  spf::SherpackFetcher Fetcher(params);
155  int retval=Fetcher.Fetch();
156  if (retval != 0) {
157  throw cms::Exception("SherpaInterface") <<"SherpaHadronizer: Preparation of Sherpack failed ... ";
158  }
159  // The ids (names) of parameter sets to be read (Analysis,Run) to create Analysis.dat, Run.dat
160  //They are given as a vstring.
161  std::vector<std::string> setNames = SherpaParameterSet.getParameter<std::vector<std::string> >("parameterSets");
162  //Loop all set names...
163  for ( unsigned i=0; i<setNames.size(); ++i ) {
164  // ...and read the parameters for each set given in vstrings
165  std::vector<std::string> pars = SherpaParameterSet.getParameter<std::vector<std::string> >(setNames[i]);
166  edm::LogVerbatim("SherpaHadronizer") << "Write Sherpa parameter set " << setNames[i] <<" to "<<setNames[i]<<".dat ";
167  std::string datfile = SherpaPath + "/" + setNames[i] +".dat";
168  std::ofstream os(datfile.c_str());
169  // Loop over all strings and write the according *.dat
170  for(std::vector<std::string>::const_iterator itPar = pars.begin(); itPar != pars.end(); ++itPar ) {
171  os<<(*itPar)<<std::endl;
172  }
173  }
174 
175  //To be conform to the default Sherpa usage create a command line:
176  //name of executable (only for demonstration, could also be empty)
177  std::string shRun = "./Sherpa";
178  //Path where the Sherpa libraries are stored
179  std::string shPath = "PATH=" + SherpaPath;
180  // new for Sherpa 1.3.0, suggested by authors
181  std::string shPathPiece = "PATH_PIECE=" + SherpaPathPiece;
182  //Path where results are stored
183  std::string shRes = "RESULT_DIRECTORY=" + SherpaResultDir; // from Sherpa 1.2.0 on
184  //Name of the external random number class
185  std::string shRng = "EXTERNAL_RNG=CMS_SHERPA_RNG";
186 
187  //create the command line
188  arguments.push_back(shRun.c_str());
189  arguments.push_back(shPath.c_str());
190  arguments.push_back(shPathPiece.c_str());
191  arguments.push_back(shRes.c_str());
192  arguments.push_back(shRng.c_str());
193  isInitialized=false;
194  //initialization of Sherpa moved to initializeForInternalPartons
195 }
196 
198 {
199 }
200 
202 {
203  //initialize Sherpa but only once
204  if (!isInitialized){
205  int argc=arguments.size();
206  char* argv[argc];
207  for (int l=0; l<argc; l++) argv[l]=(char*)arguments[l].c_str();
208  Generator.InitializeTheRun(argc,argv);
209  Generator.InitializeTheEventHandler();
210  isInitialized=true;
211  }
212  return true;
213 }
214 
215 #if 0
216 // naive Sherpa HepMC status fixup //FIXME
217 static int getStatus(const HepMC::GenParticle *p)
218 {
219  return status;
220 }
221 #endif
222 
223 //FIXME
224 bool SherpaHadronizer::declareStableParticles(const std::vector<int> &pdgIds)
225 {
226 #if 0
227  for(std::vector<int>::const_iterator iter = pdgIds.begin();
228  iter != pdgIds.end(); ++iter)
229  if (!markStable(*iter))
230  return false;
231 
232  return true;
233 #else
234  return false;
235 #endif
236 }
237 
238 
240 {
241  //calculate statistics
242  Generator.SummarizeRun();
243 
244  //get the xsec & err
245  double xsec_val = Generator.TotalXS();
246  double xsec_err = Generator.TotalErr();
247 
248  //set the internal cross section in pb in GenRunInfoProduct
249  runInfo().setInternalXSec(GenRunInfoProduct::XSec(xsec_val,xsec_err));
250 
251  if(rearrangeWeights){
252  edm::LogPrint("SherpaHadronizer") << "The order of event weights was changed!" ;
253  for(auto &i: weightlist){
254  edm::LogVerbatim("SherpaHadronizer") << i;
255  }
256  for(auto &i: variationweightlist) {
257  edm::LogVerbatim("SherpaHadronizer") << i;
258  }
259  }
260 
261 }
262 
263 
265 {
266  //get the next event and check if it produced
267  bool rc = false;
268  int itry = 0;
269  bool gen_event = true;
270  while((itry < 3) && gen_event){
271  try{
272  rc = Generator.GenerateOneEvent();
273  gen_event = false;
274  } catch(...){
275  ++itry;
276  std::cerr << "Exception from Generator.GenerateOneEvent() catch. Call # "
277  << itry << " for this event\n";
278  }
279  }
280  if (rc) {
281  //convert it to HepMC2
282  HepMC::GenEvent* evt = new HepMC::GenEvent();
283  Generator.FillHepMCEvent(*evt);
284 
285  // in case of unweighted events sherpa puts the max weight as event weight.
286  // this is not optimal, we want 1 for unweighted events, so we check
287  // whether we are producing unweighted events ("EVENT_GENERATION_MODE" == "1")
288  // the information about the weights to the HepMC weight vector:
289  // [0] event weight
290  // [1] combined matrix element and phase space weight (missing only PDF information, thus directly suitable for PDF reweighting)
291  // [2] event weight normalisation (in case of unweighted events event weights of ~ +/-1 can be obtained by (event weight)/(event weight normalisation))
292  // [3] number of trials.
293  // see also: https://sherpa.hepforge.org/doc/SHERPA-MC-2.1.0.html#Event-output-formats
294  bool unweighted = false;
295  double weight_normalization = -1;
296  if(ATOOLS::ToType<int>(ATOOLS::rpa->gen.Variable("EVENT_GENERATION_MODE")) == 1){
297  if (evt->weights().size()>2) {
298  unweighted = true;
299  weight_normalization = evt->weights()[2];
300  }else{
301  throw cms::Exception("SherpaInterface") <<"Requested unweighted production. Missing normalization weight." << std::endl;
302  }
303  }
304 
305  // vector to fill new weights in correct order
306  std::vector<double> newWeights;
307  if (rearrangeWeights){
308  for ( auto &i : weightlist ) {
309  if (evt->weights().has_key(i)) {
310  newWeights.push_back(evt->weights()[i]);
311  } else {
312  throw cms::Exception("SherpaInterface") <<"Missing weights! Key " << i << " not found, please check the weight definition!" << std::endl;
313  }
314  }
315  for ( auto &i : variationweightlist ) {
316  if (evt->weights().has_key(i)) {
317  if(unweighted){
318  newWeights.push_back(evt->weights()[i]/weight_normalization);
319  }else{
320  newWeights.push_back(evt->weights()[i]);
321  }
322  } else {
323  throw cms::Exception("SherpaInterface") <<"Missing weights! Key " << i << " not found, please check the weight definition!" << std::endl;
324  }
325 
326  }
327  }
328 
329  //Change original weights for reordered ones
330  evt->weights().clear();
331  for (auto& elem: newWeights) {
332  evt->weights().push_back(elem);
333  }
334 
335  if(unweighted){
336  evt->weights()[0]/=weight_normalization;
337  }
338  resetEvent(evt);
339  return true;
340  }
341  else {
342  return false;
343  }
344 }
345 
347 {
348  return true;
349 }
350 
352 {
353  return true;
354 }
355 
357 {
358 #if 0
359  for(HepMC::GenEvent::particle_iterator iter = event->particles_begin();
360  iter != event->particles_end(); iter++)
361  (*iter)->set_status(getStatus(*iter));
362 #endif
363  //******** Verbosity *******
364  if (maxEventsToPrint > 0) {
366  event()->print();
367  }
368 }
369 
370 
371 //GETTER for the external random numbers
372 DECLARE_GETTER(CMS_SHERPA_RNG,"CMS_SHERPA_RNG",ATOOLS::External_RNG,ATOOLS::RNG_Key);
373 
374 ATOOLS::External_RNG *ATOOLS::Getter<ATOOLS::External_RNG,ATOOLS::RNG_Key,CMS_SHERPA_RNG>::operator()(const ATOOLS::RNG_Key &) const
375 { return new CMS_SHERPA_RNG(); }
376 
377 void ATOOLS::Getter<ATOOLS::External_RNG,ATOOLS::RNG_Key,CMS_SHERPA_RNG>::PrintInfo(std::ostream &str,const size_t) const
378 { str<<"CMS_SHERPA_RNG interface"; }
379 
381  if(randomEngine == nullptr) {
383  << "The Sherpa code attempted to a generate random number while\n"
384  << "the engine pointer was null. This might mean that the code\n"
385  << "was modified to generate a random number outside the event and\n"
386  << "beginLuminosityBlock methods, which is not allowed.\n";
387  }
388  return randomEngine->flat();
389 
390 }
391 
393 
T getParameter(std::string const &) const
int i
Definition: DBlmapReader.cc:9
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:17
CLHEP::HepRandomEngine * randomEngine
bool exists(std::string const &parameterName) const
checks if a parameter exists
std::vector< std::string > weightlist
std::string SherpaPathPiece
unsigned int maxEventsToPrint
edm::GeneratorFilter< SherpaHadronizer, gen::ExternalDecayDriver > SherpaGeneratorFilter
#define nullptr
void setInternalXSec(const XSec &xsec)
bool declareStableParticles(const std::vector< int > &pdgIds)
std::auto_ptr< HepMC::GenEvent > & event()
GenRunInfoProduct & runInfo()
edm::ParameterSet SherpaParameterSet
bool initializeForInternalPartons()
SHERPA::Sherpa Generator
std::vector< std::string > variationweightlist
bool generatePartonsAndHadronize()
std::string SherpaPath
bool declareSpecialSettings(const std::vector< std::string > &)
void setRandomEngine(CLHEP::HepRandomEngine *v)
virtual void doSetRandomEngine(CLHEP::HepRandomEngine *v) override
std::string SherpaProcess
tuple argc
Definition: dir2webdir.py:38
std::string SherpaResultDir
std::vector< std::string > arguments
SherpaHadronizer(const edm::ParameterSet &params)
void resetEvent(HepMC::GenEvent *event)
volatile std::atomic< bool > shutdown_flag false
tuple status
Definition: ntuplemaker.py:245
DECLARE_GETTER(CMS_SHERPA_RNG,"CMS_SHERPA_RNG", ATOOLS::External_RNG, ATOOLS::RNG_Key)
const char * classname() const
std::string SherpaChecksum
double Get() override