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