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.c_str(), 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  if(HwUI_) delete HwUI_;
117  HwUI_ = new Herwig::HerwigUIProvider(pset, dumpConfig_, Herwig::RunMode::READ);
118  edm::LogInfo("Herwig7Interface") << "HerwigUIProvider object with run mode " << HwUI_->runMode() << " created.\n";
119 
120 
121  // Chose run mode
122  if ( choice == "read" )
123  {
124  createInputFile(pset);
125  HwUI_->setRunMode(Herwig::RunMode::READ, pset, dumpConfig_);
126  edm::LogInfo("Herwig7Interface") << "Input file " << dumpConfig_ << " will be passed to Herwig for the read step.\n";
128  }
129  else if ( choice == "build" )
130  {
131  createInputFile(pset);
132  HwUI_->setRunMode(Herwig::RunMode::BUILD, pset, dumpConfig_);
133  edm::LogInfo("Herwig7Interface") << "Input file " << dumpConfig_ << " will be passed to Herwig for the build step.\n";
135 
136  }
137  else if ( choice == "integrate" )
138  {
139  std::string runFileName = run_ + ".run";
140  edm::LogInfo("Herwig7Interface") << "Run file " << runFileName << " will be passed to Herwig for the integrate step.\n";
141  HwUI_->setRunMode(Herwig::RunMode::INTEGRATE, pset, runFileName);
143 
144  }
145  else if ( choice == "run" )
146  {
147  std::string runFileName = run_ + ".run";
148  edm::LogInfo("Herwig7Interface") << "Run file " << runFileName << " will be passed to Herwig for the run step.\n";
149  HwUI_->setRunMode(Herwig::RunMode::RUN, pset, runFileName);
150  }
151  else
152  {
153  edm::LogInfo("Herwig7Interface") << "Cannot recognize \"" << choice << "\".\n"
154  << "Trying to skip step.\n";
155  continue;
156  }
157 
158  }
159 
160 }
161 
163 {
164  try {
165 
166  edm::LogInfo("Herwig7Interface") << "callHerwigGenerator function invoked with run mode " << HwUI_->runMode() << ".\n";
167 
168  // Call program switches according to runMode
169  switch ( HwUI_->runMode() ) {
170  case Herwig::RunMode::INIT: Herwig::API::init(*HwUI_); break;
171  case Herwig::RunMode::READ: Herwig::API::read(*HwUI_); break;
172  case Herwig::RunMode::BUILD: Herwig::API::build(*HwUI_); break;
173  case Herwig::RunMode::INTEGRATE: Herwig::API::integrate(*HwUI_); break;
174  case Herwig::RunMode::MERGEGRIDS: Herwig::API::mergegrids(*HwUI_); break;
175  case Herwig::RunMode::RUN: {
176  HwUI_->setSeed(randomEngine->getSeed());
177  eg_ = Herwig::API::prepareRun(*HwUI_); break;}
179  edm::LogError("Herwig7Interface") << "Error during read in of command line parameters.\n"
180  << "Program execution will stop now.";
181  return;
182  default:
183  HwUI_->quitWithHelp();
184  }
185 
186  return;
187 
188  }
189  catch ( ThePEG::Exception & e ) {
190  edm::LogError("Herwig7Interface") << ": ThePEG::Exception caught.\n"
191  << e.what() << '\n'
192  << "See logfile for details.\n";
193  return;
194  }
195  catch ( std::exception & e ) {
196  edm::LogError("Herwig7Interface") << ": " << e.what() << '\n';
197  return;
198  }
199  catch ( const char* what ) {
200  edm::LogError("Herwig7Interface") << ": caught exception: "
201  << what << "\n";
202  return;
203  }
204 
205 }
206 
207 
209 {
210  if ( HwUI_->runMode() == Herwig::RunMode::RUN) {
211  edm::LogInfo("Herwig7Interface") << "Starting EventGenerator initialization";
213  edm::LogInfo("Herwig7Interface") << "EventGenerator initialized";
214 
215  // Skip events
216  for (unsigned int i = 0; i < skipEvents_; i++) {
218  eg_->shoot();
219  edm::LogInfo("Herwig7Interface") << "Event discarded";
220  }
221 
222  return true;
223 
224  } else {
225  edm::LogInfo("Herwig7Interface") << "Stopped EventGenerator due to missing run mode.";
226  return false;
227 /*
228  throw cms::Exception("Herwig7Interface")
229  << "EventGenerator could not be initialized due to wrong run mode!" << endl;
230 */
231  }
232 
233 }
234 
236 {
237  /*ThePEG::RandomEngineGlue *rnd = randomEngineGlueProxy_->getInstance();
238 
239  if (!rnd)
240  edm::LogWarning("ProxyMissing")
241  << "ThePEG not initialised with RandomEngineGlue.";
242  else
243  rnd->flush();
244  */
245 }
246 
247 auto_ptr<HepMC::GenEvent> Herwig7Interface::convert(
248  const ThePEG::EventPtr &event)
249 {
250  return std::auto_ptr<HepMC::GenEvent>(
252 }
253 
254 
255 
256 
257 double Herwig7Interface::pthat(const ThePEG::EventPtr &event)
258 {
259  using namespace ThePEG;
260 
261  if (!event->primaryCollision())
262  return -1.0;
263 
264  tSubProPtr sub = event->primaryCollision()->primarySubProcess();
265  TmpTransform<tSubProPtr> tmp(sub, Utilities::getBoostToCM(
266  sub->incoming()));
267 
268  double pthat = (*sub->outgoing().begin())->momentum().perp() / ThePEG::GeV;
269  for(PVector::const_iterator it = sub->outgoing().begin();
270  it != sub->outgoing().end(); ++it)
271  pthat = std::min<double>(pthat, (*it)->momentum().perp() / ThePEG::GeV);
272 
273  return pthat;
274 }
275 
276 
277 
278 
280 {
281  /* Initialize the input config for Herwig from
282  * 1. the Herwig7 config files
283  * 2. the CMSSW config blocks
284  * Writes them to an output file which is read by Herwig
285  */
286 
287  stringstream logstream;
288 
289 
290  // Contains input config passed to Herwig
291  stringstream herwiginputconfig;
292 
293  // Define output file to which input config is written, too, if dumpConfig parameter is set.
294  // Otherwise use default file HerwigConfig.in which is read in by Herwig
295  ofstream cfgDump;
296  cfgDump.open(dumpConfig_.c_str(), ios_base::app);
297 
298 
299 
300  // Read Herwig config files as input
301  vector<string> configFiles = pset.getParameter<vector<string> >("configFiles");
302  // Loop over the config files
303  for ( const auto & iter : configFiles ) {
304  // Open external config file
305  ifstream externalConfigFile (iter);
306  if (externalConfigFile.is_open()) {
307  edm::LogInfo("Herwig7Interface") << "Reading config file (" << iter << ")" << endl;
308  stringstream configFileStream;
309  configFileStream << externalConfigFile.rdbuf();
310  string configFileContent = configFileStream.str();
311 
312  // Comment out occurence of saverun in config file since it is set later considering run and generator option
313  string searchKeyword("saverun");
314  if(configFileContent.find(searchKeyword) !=std::string::npos) {
315  edm::LogInfo("Herwig7Interface") << "Commented out saverun command in external input config file(" << iter << ")" << endl;
316  configFileContent.insert(configFileContent.find(searchKeyword),"#");
317  }
318  herwiginputconfig << "# Begin Config file input" << endl << configFileContent << endl << "# End Config file input";
319  edm::LogInfo("Herwig7Interface") << "Finished reading config file (" << iter << ")" << endl;
320  }
321  else {
322  edm::LogWarning("Herwig7Interface") << "Could not read config file (" << iter << ")" << endl;
323  }
324  }
325 
326  edm::LogInfo("Herwig7Interface") << "Start with processing CMSSW config" << endl;
327  // Read CMSSW config file parameter sets starting from "parameterSets"
328  ParameterCollector collector(pset);
330  iter = collector.begin();
331  herwiginputconfig << endl << "# Begin Parameter set input\n" << endl;
332  for(; iter != collector.end(); ++iter) {
333  herwiginputconfig << *iter << endl;
334  }
335 
336  // Add some additional necessary lines to the Herwig input config
337  herwiginputconfig << "saverun " << run_ << " " << generator_ << endl;
338  // write the ProxyID for the RandomEngineGlue to fill its pointer in
339  ostringstream ss;
340  ss << randomEngineGlueProxy_->getID();
341  //herwiginputconfig << "set " << generator_ << ":RandomNumberGenerator:ProxyID " << ss.str() << endl;
342 
343 
344  // Dump Herwig input config to file, so that it can be read by Herwig
345  cfgDump << herwiginputconfig.str() << endl;
346  cfgDump.close();
347 }
348 
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
CLHEP::HepRandomEngine * randomEngine
~Herwig7Interface() 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)
Herwig::HerwigUIProvider * HwUI_
void quitWithHelp() const override
Definition: event.py:1
static const int ERROR
RunMode::Mode runMode() const override
Requested Herwig run mode.