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