CMS 3D CMS Logo

Herwig7Interface.cc
Go to the documentation of this file.
1 
7 #include <iostream>
8 #include <fstream>
9 #include <sstream>
10 #include <cstdlib>
11 #include <memory>
12 #include <cmath>
13 #include <cstdlib>
14 
15 #include <algorithm>
16 
17 #include <boost/shared_ptr.hpp>
18 #include <boost/filesystem.hpp>
19 
20 #include <HepMC/GenEvent.h>
21 #include <HepMC/PdfInfo.h>
22 #include <HepMC/IO_GenEvent.h>
23 
24 #include <Herwig/API/HerwigAPI.h>
25 
26 #include <ThePEG/Utilities/DynamicLoader.h>
27 #include <ThePEG/Repository/Repository.h>
28 #include <ThePEG/Handlers/EventHandler.h>
29 #include <ThePEG/Handlers/XComb.h>
30 #include <ThePEG/EventRecord/Event.h>
31 #include <ThePEG/EventRecord/Particle.h>
32 #include <ThePEG/EventRecord/Collision.h>
33 #include <ThePEG/EventRecord/TmpTransform.h>
34 #include <ThePEG/Config/ThePEG.h>
35 #include <ThePEG/PDF/PartonExtractor.h>
36 #include <ThePEG/PDF/PDFBase.h>
37 #include <ThePEG/Utilities/UtilityBase.h>
38 #include <ThePEG/Vectors/HepMCConverter.h>
39 
40 
42 
44 
48 
49 using namespace std;
50 using namespace gen;
51 
53  randomEngineGlueProxy_(ThePEG::RandomEngineGlue::Proxy::create()),
54  dataLocation_(ParameterCollector::resolve(pset.getParameter<string>("dataLocation"))),
55  generator_(pset.getParameter<string>("generatorModule")),
56  run_(pset.getParameter<string>("run")),
57  dumpConfig_(pset.getUntrackedParameter<string>("dumpConfig", "HerwigConfig.in")),
58  skipEvents_(pset.getUntrackedParameter<unsigned int>("skipEvents", 0))
59 {
60  // Write events in hepmc ascii format for debugging purposes
61  string dumpEvents = pset.getUntrackedParameter<string>("dumpEvents", "");
62  if (!dumpEvents.empty()) {
63  iobc_.reset(new HepMC::IO_GenEvent(dumpEvents.c_str(), ios::out));
64  edm::LogInfo("ThePEGSource") << "Event logging switched on (=> " << dumpEvents << ")";
65  }
66  // Clear dumpConfig target
67  if (!dumpConfig_.empty())
68  ofstream cfgDump(dumpConfig_.c_str(), ios_base::trunc);
69 }
70 
72 {
73  if (eg_)
74  eg_->finalize();
75  edm::LogInfo("Herwig7Interface") << "Event generator finalized";
76 }
77 
78 void Herwig7Interface::setPEGRandomEngine(CLHEP::HepRandomEngine* v) {
79  randomEngineGlueProxy_->setRandomEngine(v);
81  if(rnd) {
82  rnd->setRandomEngine(v);
83  }
84 }
85 
86 
88 {
89  std::string runModeTemp = pset.getUntrackedParameter<string>("runModeList","read,run");
90 
91  // To Lower
92  std::transform(runModeTemp.begin(), runModeTemp.end(), runModeTemp.begin(), ::tolower);
93 
94 
95 
96  while(!runModeTemp.empty())
97  {
98  // Split first part of List
99  std::string choice;
100  size_t pos = runModeTemp.find(",");
101  if (std::string::npos == pos)
102  choice=runModeTemp;
103  else
104  choice = runModeTemp.substr(0, pos);
105 
106  if (pos == std::string::npos)
107  runModeTemp.erase();
108  else
109  runModeTemp.erase(0, pos+1);
110 
111  // construct HerwigUIProvider object and return it as global object
112  HwUI_ = new Herwig::HerwigUIProvider(pset, dumpConfig_, Herwig::RunMode::READ);
113  edm::LogInfo("Herwig7Interface") << "HerwigUIProvider object with run mode " << HwUI_->runMode() << " created.\n";
114 
115 
116  // Chose run mode
117  if ( choice == "read" )
118  {
119  createInputFile(pset);
120  HwUI_->setRunMode(Herwig::RunMode::READ, pset, dumpConfig_);
121  edm::LogInfo("Herwig7Interface") << "Input file " << dumpConfig_ << " will be passed to Herwig for the read step.\n";
123  }
124  else if ( choice == "build" )
125  {
126  createInputFile(pset);
127  HwUI_->setRunMode(Herwig::RunMode::BUILD, pset, dumpConfig_);
128  edm::LogInfo("Herwig7Interface") << "Input file " << dumpConfig_ << " will be passed to Herwig for the build step.\n";
130 
131  }
132  else if ( choice == "integrate" )
133  {
134  std::string runFileName = run_ + ".run";
135  edm::LogInfo("Herwig7Interface") << "Run file " << runFileName << " will be passed to Herwig for the integrate step.\n";
136  HwUI_->setRunMode(Herwig::RunMode::INTEGRATE, pset, runFileName);
138 
139  }
140  else if ( choice == "run" )
141  {
142  std::string runFileName = run_ + ".run";
143  edm::LogInfo("Herwig7Interface") << "Run file " << runFileName << " will be passed to Herwig for the run step.\n";
144  HwUI_->setRunMode(Herwig::RunMode::RUN, pset, runFileName);
145  }
146  else
147  {
148  edm::LogInfo("Herwig7Interface") << "Cannot recognize \"" << choice << "\".\n"
149  << "Trying to skip step.\n";
150  continue;
151  }
152 
153  }
154 
155 }
156 
158 {
159  try {
160 
161  edm::LogInfo("Herwig7Interface") << "callHerwigGenerator function invoked with run mode " << HwUI_->runMode() << ".\n";
162 
163  // Call program switches according to runMode
164  switch ( HwUI_->runMode() ) {
165  case Herwig::RunMode::INIT: Herwig::API::init(*HwUI_); break;
166  case Herwig::RunMode::READ: Herwig::API::read(*HwUI_); break;
167  case Herwig::RunMode::BUILD: Herwig::API::build(*HwUI_); break;
168  case Herwig::RunMode::INTEGRATE: Herwig::API::integrate(*HwUI_); break;
169  case Herwig::RunMode::MERGEGRIDS: Herwig::API::mergegrids(*HwUI_); break;
170  case Herwig::RunMode::RUN: eg_ = Herwig::API::prepareRun(*HwUI_); break;
172  edm::LogError("Herwig7Interface") << "Error during read in of command line parameters.\n"
173  << "Program execution will stop now.";
174  return;
175  default:
176  HwUI_->quitWithHelp();
177  }
178 
179  return;
180 
181  }
182  catch ( ThePEG::Exception & e ) {
183  edm::LogError("Herwig7Interface") << ": ThePEG::Exception caught.\n"
184  << e.what() << '\n'
185  << "See logfile for details.\n";
186  return;
187  }
188  catch ( std::exception & e ) {
189  edm::LogError("Herwig7Interface") << ": " << e.what() << '\n';
190  return;
191  }
192  catch ( const char* what ) {
193  edm::LogError("Herwig7Interface") << ": caught exception: "
194  << what << "\n";
195  return;
196  }
197 
198 }
199 
200 
202 {
203  if ( HwUI_->runMode() == Herwig::RunMode::RUN) {
204  edm::LogInfo("Herwig7Interface") << "Starting EventGenerator initialization";
206  edm::LogInfo("Herwig7Interface") << "EventGenerator initialized";
207 
208  // Skip events
209  for (unsigned int i = 0; i < skipEvents_; i++) {
211  eg_->shoot();
212  edm::LogInfo("Herwig7Interface") << "Event discarded";
213  }
214 
215  return true;
216 
217  } else {
218  edm::LogInfo("Herwig7Interface") << "Stopped EventGenerator due to missing run mode.";
219  return false;
220 /*
221  throw cms::Exception("Herwig7Interface")
222  << "EventGenerator could not be initialized due to wrong run mode!" << endl;
223 */
224  }
225 
226 }
227 
229 {
230  /*ThePEG::RandomEngineGlue *rnd = randomEngineGlueProxy_->getInstance();
231 
232  if (!rnd)
233  edm::LogWarning("ProxyMissing")
234  << "ThePEG not initialised with RandomEngineGlue.";
235  else
236  rnd->flush();
237  */
238 }
239 
240 auto_ptr<HepMC::GenEvent> Herwig7Interface::convert(
241  const ThePEG::EventPtr &event)
242 {
243  return std::auto_ptr<HepMC::GenEvent>(
245 }
246 
247 
248 
249 
250 double Herwig7Interface::pthat(const ThePEG::EventPtr &event)
251 {
252  using namespace ThePEG;
253 
254  if (!event->primaryCollision())
255  return -1.0;
256 
257  tSubProPtr sub = event->primaryCollision()->primarySubProcess();
258  TmpTransform<tSubProPtr> tmp(sub, Utilities::getBoostToCM(
259  sub->incoming()));
260 
261  double pthat = (*sub->outgoing().begin())->momentum().perp() / ThePEG::GeV;
262  for(PVector::const_iterator it = sub->outgoing().begin();
263  it != sub->outgoing().end(); ++it)
264  pthat = std::min<double>(pthat, (*it)->momentum().perp() / ThePEG::GeV);
265 
266  return pthat;
267 }
268 
269 
270 
271 
273 {
274  /* Initialize the input config for Herwig from
275  * 1. the Herwig7 config files
276  * 2. the CMSSW config blocks
277  * Writes them to an output file which is read by Herwig
278  */
279 
280  stringstream logstream;
281 
282 
283  // Contains input config passed to Herwig
284  stringstream herwiginputconfig;
285 
286  // Define output file to which input config is written, too, if dumpConfig parameter is set.
287  // Otherwise use default file HerwigConfig.in which is read in by Herwig
288  ofstream cfgDump;
289  cfgDump.open(dumpConfig_.c_str(), ios_base::app);
290 
291 
292 
293  // Read Herwig config files as input
294  vector<string> configFiles = pset.getParameter<vector<string> >("configFiles");
295  // Loop over the config files
296  for ( const auto & iter : configFiles ) {
297  // Open external config file
298  ifstream externalConfigFile (iter);
299  if (externalConfigFile.is_open()) {
300  edm::LogInfo("Herwig7Interface") << "Reading config file (" << iter << ")" << endl;
301  stringstream configFileStream;
302  configFileStream << externalConfigFile.rdbuf();
303  string configFileContent = configFileStream.str();
304 
305  // Comment out occurence of saverun in config file since it is set later considering run and generator option
306  string searchKeyword("saverun");
307  if(configFileContent.find(searchKeyword) !=std::string::npos) {
308  edm::LogInfo("Herwig7Interface") << "Commented out saverun command in external input config file(" << iter << ")" << endl;
309  configFileContent.insert(configFileContent.find(searchKeyword),"#");
310  }
311  herwiginputconfig << "# Begin Config file input" << endl << configFileContent << endl << "# End Config file input";
312  edm::LogInfo("Herwig7Interface") << "Finished reading config file (" << iter << ")" << endl;
313  }
314  else {
315  edm::LogWarning("Herwig7Interface") << "Could not read config file (" << iter << ")" << endl;
316  }
317  }
318 
319  edm::LogInfo("Herwig7Interface") << "Start with processing CMSSW config" << endl;
320  // Read CMSSW config file parameter sets starting from "parameterSets"
321  ParameterCollector collector(pset);
323  iter = collector.begin();
324  herwiginputconfig << endl << "# Begin Parameter set input\n" << endl;
325  for(; iter != collector.end(); ++iter) {
326  herwiginputconfig << *iter << endl;
327  }
328 
329  // Add some additional necessary lines to the Herwig input config
330  herwiginputconfig << "saverun " << run_ << " " << generator_ << endl;
331  // write the ProxyID for the RandomEngineGlue to fill its pointer in
332  ostringstream ss;
333  ss << randomEngineGlueProxy_->getID();
334  //herwiginputconfig << "set " << generator_ << ":RandomNumberGenerator:ProxyID " << ss.str() << endl;
335 
336 
337  // Dump Herwig input config to file, so that it can be read by Herwig
338  cfgDump << herwiginputconfig.str() << endl;
339  cfgDump.close();
340 }
341 
T getParameter(std::string const &) const
T getUntrackedParameter(std::string const &, T const &) const
static double pthat(const ThePEG::EventPtr &event)
const double GeV
Definition: MathUtil.h:16
void initRepository(const edm::ParameterSet &params)
void createInputFile(const edm::ParameterSet &params)
def create(alignables, pedeDump, additionalData, outputFile, config)
void setPEGRandomEngine(CLHEP::HepRandomEngine *)
std::auto_ptr< HepMC::IO_BaseClass > iobc_
int init
Definition: HydjetWrapper.h:67
#define noexcept
std::string dumpConfig_
ThePEG::EGPtr eg_
void setRunMode(RunMode::Mode runMode, const edm::ParameterSet &pset, std::string inputFile="")
const std::string run_
static std::auto_ptr< HepMC::GenEvent > convert(const ThePEG::EventPtr &event)
def convert(infile, ofile)
Herwig7Interface(const edm::ParameterSet &params)
const std::string generator_
const unsigned int skipEvents_
std::vector< std::vector< double > > tmp
Definition: MVATrainer.cc:100
const_iterator end() const
boost::shared_ptr< ThePEG::RandomEngineGlue::Proxy > randomEngineGlueProxy_
const_iterator begin() const
void flushRandomNumberGenerator()
void setRandomEngine(CLHEP::HepRandomEngine *v)
RunMode::Mode runMode() const
Requested Herwig run mode.
Herwig::HerwigUIProvider * HwUI_
Definition: event.py:1
static const int ERROR