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;
70 };
71 
72 
73 
74 
75 class CMS_SHERPA_RNG: public ATOOLS::External_RNG {
76 public:
77 
79  std::cout << "Use stored reference for the external RNG" << std::endl;
80  setRandomEngine(GetExternalEngine());
81  }
82  void setRandomEngine(CLHEP::HepRandomEngine* v) { randomEngine = v; }
83 
84 private:
85  double Get() override;
86  CLHEP::HepRandomEngine* randomEngine;
87 };
88 
89 
90 void SherpaHadronizer::doSetRandomEngine(CLHEP::HepRandomEngine* v) {
91  CMS_SHERPA_RNG* cmsSherpaRng = dynamic_cast<CMS_SHERPA_RNG*>(ATOOLS::ran->GetExternalRng());
92  //~ assert(cmsSherpaRng != nullptr);
93  if (cmsSherpaRng ==nullptr) {
94  //First time call to this function makes the interface store the reference in the unnamed namespace
95  if (!isRNGinitialized){
96  isRNGinitialized=true;
97  std::cout << "Store assigned reference of the randomEngine" << std::endl;
98  SetExternalEngine(v);
99  // Throw exception if there is no reference to an external RNG and it is not the first call!
100  } else {
102  << "The Sherpa interface got a randomEngine reference but there is no reference to the external RNG to hand it over to\n";
103  }
104  } else {
105  cmsSherpaRng->setRandomEngine(v);
106  }
107 }
108 
110  BaseHadronizer(params),
111  SherpaParameterSet(params.getParameter<edm::ParameterSet>("SherpaParameters")),
112  isRNGinitialized(false)
113 {
114  if (!params.exists("SherpaProcess")) SherpaProcess="";
115  else SherpaProcess=params.getParameter<std::string>("SherpaProcess");
116  if (!params.exists("SherpaPath")) SherpaPath="";
117  else SherpaPath=params.getParameter<std::string>("SherpaPath");
118  if (!params.exists("SherpaPathPiece")) SherpaPathPiece="";
119  else SherpaPathPiece=params.getParameter<std::string>("SherpaPathPiece");
120  if (!params.exists("SherpaResultDir")) SherpaResultDir="Result";
121  else SherpaResultDir=params.getParameter<std::string>("SherpaResultDir");
122  if (!params.exists("SherpaDefaultWeight")) SherpaDefaultWeight=1.;
123  else SherpaDefaultWeight=params.getParameter<double>("SherpaDefaultWeight");
124  if (!params.exists("maxEventsToPrint")) maxEventsToPrint=0;
125  else maxEventsToPrint=params.getParameter<int>("maxEventsToPrint");
126 
127 
128  spf::SherpackFetcher Fetcher(params);
129  int retval=Fetcher.Fetch();
130  if (retval != 0) {
131  std::cout << "SherpaHadronizer: Preparation of Sherpack failed ... " << std::endl;
132  std::cout << "SherpaHadronizer: Error code: " << retval << std::endl;
133  std::terminate();
134 
135  }
136  // The ids (names) of parameter sets to be read (Analysis,Run) to create Analysis.dat, Run.dat
137  //They are given as a vstring.
138  std::vector<std::string> setNames = SherpaParameterSet.getParameter<std::vector<std::string> >("parameterSets");
139  //Loop all set names...
140  for ( unsigned i=0; i<setNames.size(); ++i ) {
141  // ...and read the parameters for each set given in vstrings
142  std::vector<std::string> pars = SherpaParameterSet.getParameter<std::vector<std::string> >(setNames[i]);
143  std::cout << "Write Sherpa parameter set " << setNames[i] <<" to "<<setNames[i]<<".dat "<<std::endl;
144  std::string datfile = SherpaPath + "/" + setNames[i] +".dat";
145  std::ofstream os(datfile.c_str());
146  // Loop over all strings and write the according *.dat
147  for(std::vector<std::string>::const_iterator itPar = pars.begin(); itPar != pars.end(); ++itPar ) {
148  os<<(*itPar)<<std::endl;
149  }
150  }
151 
152  //To be conform to the default Sherpa usage create a command line:
153  //name of executable (only for demonstration, could also be empty)
154  std::string shRun = "./Sherpa";
155  //Path where the Sherpa libraries are stored
156  std::string shPath = "PATH=" + SherpaPath;
157  // new for Sherpa 1.3.0, suggested by authors
158  std::string shPathPiece = "PATH_PIECE=" + SherpaPathPiece;
159  //Path where results are stored
160  std::string shRes = "RESULT_DIRECTORY=" + SherpaResultDir; // from Sherpa 1.2.0 on
161  //Name of the external random number class
162  std::string shRng = "EXTERNAL_RNG=CMS_SHERPA_RNG";
163 
164  //create the command line
165  arguments.push_back(shRun.c_str());
166  arguments.push_back(shPath.c_str());
167  arguments.push_back(shPathPiece.c_str());
168  arguments.push_back(shRes.c_str());
169  arguments.push_back(shRng.c_str());
170  isInitialized=false;
171  //initialization of Sherpa moved to initializeForInternalPartons
172 }
173 
175 {
176 }
177 
179 {
180  //initialize Sherpa but only once
181  if (!isInitialized){
182  int argc=arguments.size();
183  char* argv[argc];
184  for (int l=0; l<argc; l++) argv[l]=(char*)arguments[l].c_str();
185  Generator.InitializeTheRun(argc,argv);
186  Generator.InitializeTheEventHandler();
187  isInitialized=true;
188  }
189  return true;
190 }
191 
192 #if 0
193 // naive Sherpa HepMC status fixup //FIXME
194 static int getStatus(const HepMC::GenParticle *p)
195 {
196  return status;
197 }
198 #endif
199 
200 //FIXME
201 bool SherpaHadronizer::declareStableParticles(const std::vector<int> &pdgIds)
202 {
203 #if 0
204  for(std::vector<int>::const_iterator iter = pdgIds.begin();
205  iter != pdgIds.end(); ++iter)
206  if (!markStable(*iter))
207  return false;
208 
209  return true;
210 #else
211  return false;
212 #endif
213 }
214 
215 
217 {
218  //calculate statistics
219  Generator.SummarizeRun();
220 
221  //get the xsec & err
222  double xsec_val = Generator.TotalXS();
223  double xsec_err = Generator.TotalErr();
224 
225  //set the internal cross section in pb in GenRunInfoProduct
226  runInfo().setInternalXSec(GenRunInfoProduct::XSec(xsec_val,xsec_err));
227 
228 }
229 
230 
232 {
233  //get the next event and check if it produced
234  bool rc = false;
235  int itry = 0;
236  bool gen_event = true;
237  while((itry < 3) && gen_event){
238  try{
239  rc = Generator.GenerateOneEvent();
240  gen_event = false;
241  } catch(...){
242  ++itry;
243  std::cerr << "Exception from Generator.GenerateOneEvent() catch. Call # "
244  << itry << " for this event\n";
245  }
246  }
247  if (rc) {
248  //convert it to HepMC2
249  HepMC::GenEvent* evt = new HepMC::GenEvent();
250  Generator.FillHepMCEvent(*evt);
251 
252  // in case of unweighted events sherpa puts the max weight as event weight.
253  // this is not optimal, we want 1 for unweighted events, so we check
254  // whether we are producing unweighted events ("EVENT_GENERATION_MODE" == "1")
255  // the information about the weights to the HepMC weight vector:
256  // [0] event weight
257  // [1] combined matrix element and phase space weight (missing only PDF information, thus directly suitable for PDF reweighting)
258  // [2] event weight normalisation (in case of unweighted events event weights of ~ +/-1 can be obtained by (event weight)/(event weight normalisation))
259  // [3] number of trials.
260  // see also: https://sherpa.hepforge.org/doc/SHERPA-MC-2.1.0.html#Event-output-formats
261  if(ATOOLS::ToType<int>(ATOOLS::rpa->gen.Variable("EVENT_GENERATION_MODE")) == 1){
262  if (evt->weights().size()>2) {
263  evt->weights()[0]/=evt->weights()[2];
264  }
265  }
266  resetEvent(evt);
267  return true;
268  }
269  else {
270  return false;
271  }
272 }
273 
275 {
276  return true;
277 }
278 
280 {
281  return true;
282 }
283 
285 {
286 #if 0
287  for(HepMC::GenEvent::particle_iterator iter = event->particles_begin();
288  iter != event->particles_end(); iter++)
289  (*iter)->set_status(getStatus(*iter));
290 #endif
291  //******** Verbosity *******
292  if (maxEventsToPrint > 0) {
294  event()->print();
295  }
296 }
297 
298 
299 //GETTER for the external random numbers
300 DECLARE_GETTER(CMS_SHERPA_RNG,"CMS_SHERPA_RNG",ATOOLS::External_RNG,ATOOLS::RNG_Key);
301 
302 ATOOLS::External_RNG *ATOOLS::Getter<ATOOLS::External_RNG,ATOOLS::RNG_Key,CMS_SHERPA_RNG>::operator()(const ATOOLS::RNG_Key &) const
303 { return new CMS_SHERPA_RNG(); }
304 
305 void ATOOLS::Getter<ATOOLS::External_RNG,ATOOLS::RNG_Key,CMS_SHERPA_RNG>::PrintInfo(std::ostream &str,const size_t) const
306 { str<<"CMS_SHERPA_RNG interface"; }
307 
309  if(randomEngine == nullptr) {
311  << "The Sherpa code attempted to a generate random number while\n"
312  << "the engine pointer was null. This might mean that the code\n"
313  << "was modified to generate a random number outside the event and\n"
314  << "beginLuminosityBlock methods, which is not allowed.\n";
315  }
316  return randomEngine->flat();
317 
318 }
319 
321 
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::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
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)
tuple cout
Definition: gather_cfg.py:145
void resetEvent(HepMC::GenEvent *event)
volatile std::atomic< bool > shutdown_flag false
DECLARE_GETTER(CMS_SHERPA_RNG,"CMS_SHERPA_RNG", ATOOLS::External_RNG, ATOOLS::RNG_Key)
const char * classname() const
std::string SherpaChecksum
tuple status
Definition: mps_update.py:57
double Get() override