CMS 3D CMS Logo

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