ATLAS Offline Software
Loading...
Searching...
No Matches
Herwig7.cxx
Go to the documentation of this file.
1// -*- C++ -*-
2/*
3 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
4*/
5
6
11
12#include "Herwig7_i/Herwig7.h"
13
14#include "ThePEG/Repository/EventGenerator.h"
15#include "ThePEG/Repository/Repository.h"
16#include "ThePEG/Persistency/PersistentIStream.h"
17#include "ThePEG/Utilities/DynamicLoader.h"
18#include "ThePEG/Utilities/Debug.h"
19#include "ThePEG/EventRecord/Event.h"
20#include "ThePEG/EventRecord/SubProcess.h"
21#include "ThePEG/Handlers/XComb.h"
22#include "ThePEG/Handlers/EventHandler.h"
23#include "ThePEG/PDF/PartonExtractor.h"
24#include "ThePEG/PDF/PDF.h"
25
26#include "Herwig/API/HerwigAPI.h"
27#include "Herwig/Utilities/HerwigStrategy.h"
28
30
31#include <fstream>
32#include <thread>
33#include <chrono>
34#include <filesystem>
35#include <ranges>
36
37void convert_to_HepMC(const ThePEG::Event & m_event, HepMC::GenEvent & evt, bool nocopies,ThePEG::Energy eunit, ThePEG::Length lunit);
38
39
40// Constructor
41Herwig7::Herwig7(const std::string& name, ISvcLocator* pSvcLocator) :
42 GenModule(name, pSvcLocator),
45 m_pdfname_me("UNKNOWN"), m_pdfname_mpi("UNKNOWN") // m_pdfname_ps("UNKONWN"),
46{
47 declareProperty("RunFile", m_runfile="Herwig7");
48 declareProperty("RunSettings", m_runSettings="");
49 declareProperty("SetupFile", m_setupfile="");
50
51 declareProperty("UseRandomSeedFromGeneratetf", m_use_seed_from_generatetf);
52 declareProperty("RandomSeedFromGeneratetf", m_seed_from_generatetf);
53
54 declareProperty("PDFNameME", m_pdfname_me);
55 // declareProperty("PDFNamePS", m_pdfname_ps);
56 declareProperty("PDFNameMPI", m_pdfname_mpi);
57
58 declareProperty("CrossSectionScaleFactor", m_xsscale=1.0);
59
60 declareProperty("CleanupHerwigScratch", m_cleanup_herwig_scratch);
61
62 declareProperty("Dsid", m_dsid);
63}
64
71 ATH_MSG_INFO("Herwig7 initialising...");
72
73 ATH_CHECK(m_evtInfoKey.initialize());
74
75 // Get random number seeds from Atlas RNG service, and pass them as Hw7 RNG
76 // default seeds (they can be overridden with an explicit Hw7 set command in the JO)
77 CLHEP::HepRandomEngine* engine = this->getRandomEngineDuringInitialize("Herwig7", m_randomSeed); // conditionsRun=1, lbn=1
78 const long* seeds = engine->getSeeds();
79 // The RNG service supplies two seeds, but Hw7 only uses one. To avoid the situation
80 // where varying one seed has no effect (this already stung us in pre-production
81 // job transform tests), we multiply the two seeds and let them wrap around the long
82 // type MAX_SIZE:
83 int32_t combined_seed = std::abs(seeds[0] * seeds[1]);
84 // Represent the combined seed as a string, so the config system can parse it back to a long ;)
85 std::ostringstream ss_seed;
86 ss_seed << combined_seed;
87 // Configure the API and print the seed to the log
89 ATH_MSG_INFO("Using the random number seed " + std::to_string(m_seed_from_generatetf) + " provided via Generate_tf.py");
91 } else {
92 ATH_MSG_INFO("Using the random number seed " + ss_seed.str() + " provided by athena");
93 m_api.seed(combined_seed);
94 }
95
96 // Change repo log level and make sure that config errors result in a program exit
97 //ThePEG::Debug::level = 10000;
98 ThePEG::Repository::exitOnError() = 1;
99
100 // Use everything from $DATAPATH and $LD_LIBRARY_PATH:
101 const char* datapath = getenv( "DATAPATH" );
102 std::vector<std::string> datapaths;
103 if (datapath) {
104 std::string datapath_str(datapath);
105 for (auto part : std::views::split(datapath_str, ':')) {
106 datapaths.emplace_back(part.begin(), part.end());
107 }
108 }
109 for( const std::string& p : datapaths ) {
110 ThePEG::Repository::appendReadDir( p );
111 }
112 const char* ldpath = getenv( "LD_LIBRARY_PATH" );
113 std::vector<std::string> ldpaths;
114 if (ldpath) {
115 std::string ldpath_str(ldpath);
116 for (auto part : ldpath_str | std::views::split(':')) {
117 ldpaths.emplace_back(std::string(part.begin(), part.end()));
118 }
119 }
120 for( const std::string& p : ldpaths ) {
121 ThePEG::DynamicLoader::appendPath( p );
122 }
123
124 ATH_MSG_DEBUG("Num of library search paths = " << ThePEG::DynamicLoader::allPaths().size());
125
126 // Use PathResolver to find default Hw7 ThePEG repository file.
127 const std::string repopath = PathResolver::find_file_from_list("HerwigDefaults.rpo", datapath);
128 ATH_MSG_DEBUG("Loading Herwig default repo from " << repopath);
129 ThePEG::Repository::load(repopath);
130 ATH_MSG_DEBUG("Successfully loaded Herwig default repository");
131
132 const std::string share_path = std::filesystem::path(std::move(repopath)).parent_path().string();
133
134 if (!m_runSettings.empty()) {
135 ATH_CHECK(writeRunFileFromText(share_path));
136 }
137
138 ATH_MSG_INFO("Setting runfile name '"+m_runfile+"'");
139 m_api.inputfile(m_runfile);
140
141 ATH_MSG_INFO("starting to prepare the run from runfile '"+m_runfile+"'...");
142
143 m_runinfo = std::make_shared<HepMC3::GenRunInfo>();
145 struct HepMC3::GenRunInfo::ToolInfo generator={std::string("Herwig7"), Herwig::HerwigStrategy::version, std::string("Used generator")};
146 m_runinfo->tools().push_back(std::move(generator));
147 // read in a Herwig runfile and obtain the event generator
148 m_gen = Herwig::API::prepareRun(m_api);
149 ATH_MSG_DEBUG("preparing the run...");
150
151 return StatusCode::SUCCESS;
152}
153
154
155StatusCode Herwig7::writeRunFileFromText(const std::string& share_path) {
156 if (m_runSettings.empty()) {
157 return StatusCode::SUCCESS;
158 }
159
160 std::string inputfile_name = m_runfile;
161 const std::string runfile_suffix = ".run";
162 const auto suffix_pos = inputfile_name.rfind(runfile_suffix);
163 if (suffix_pos != std::string::npos) {
164 inputfile_name.replace(suffix_pos, runfile_suffix.size(), ".in");
165 } else {
166 std::filesystem::path inputfile_path(m_runfile);
167 inputfile_path.replace_extension(".in");
168 inputfile_name = inputfile_path.string();
169 }
170
171 ATH_MSG_INFO("Writing CA infile text to '"+inputfile_name+"'");
172 std::ofstream infile_stream(inputfile_name);
173 infile_stream << m_runSettings;
174 if (!infile_stream) {
175 ATH_MSG_ERROR("Failed to write CA infile text to '"+inputfile_name+"'");
176 return StatusCode::FAILURE;
177 }
178
179 if (share_path.empty()) {
180 ATH_MSG_ERROR("Could not determine the Herwig share path for CA infile materialisation");
181 return StatusCode::FAILURE;
182 }
183
184 ATH_MSG_INFO("Preparing Herwig runfile from CA infile '"+inputfile_name+"'");
185 m_api.prependReadDirectory(share_path);
186 m_api.inputfile(inputfile_name);
187 Herwig::API::read(m_api);
188 ATH_MSG_INFO("Finished materialising runfile '"+m_runfile+"'");
189 return StatusCode::SUCCESS;
190}
191
192
193
198 ATH_MSG_DEBUG("Herwig7 generating an event");
199 assert(m_gen);
200 m_event = m_gen->shoot();
201 return StatusCode::SUCCESS;
202}
203
204
205
213 // Convert the Herwig event into the HepMC GenEvent
214 ATH_MSG_DEBUG("Converting ThePEG::Event to HepMC::GenEvent");
215 if (!evt->run_info()) evt->set_run_info(m_runinfo);
216 evt->set_units(HepMC3::Units::MEV, HepMC3::Units::MM);
217 convert_to_HepMC(*m_event, *evt, false, ThePEG::MeV, ThePEG::millimeter);
218 ATH_MSG_DEBUG("Converted ThePEG::Event to HepMC::GenEvent");
219
220 // Fill the event number into HepMC event record
222 evt->set_event_number(evtInfo->eventNumber());
223
224 // Fill event with random seeds from Atlas RNG service
225 const EventContext& ctx = Gaudi::Hive::currentContext();
226 const long* s = this->getRandomEngine("Herwig7", ctx)->getSeeds();
227 std::vector<long> seeds(s, s+2);
228 ATH_MSG_DEBUG("Random seeds: " << seeds[0] << ", " << seeds[1]);
229 HepMC::set_random_states(evt,seeds);
230
231 // Add a unit entry to the event weight vector if it's currently empty
232 if (evt->weights().empty()) {
233 evt->weights().push_back(m_event->weight());
234 }
235
236 // Add PDF info manually (for now, until natively supported in the ThePEG converter)
237 ATH_MSG_DEBUG("Adding PDF info to HepMC");
238 // IDs of the partons going into the primary sub process
239 ThePEG::tSubProPtr sub = m_event->primarySubProcess();
240 int id1 = sub->incoming().first ->id();
241 int id2 = sub->incoming().second->id();
242 // Get the event handler
243 ThePEG::tcEHPtr eh = ThePEG::dynamic_ptr_cast<ThePEG::tcEHPtr>(m_event->handler());
244 // Get the values of x
245 double x1 = eh->lastX1();
246 double x2 = eh->lastX2();
247 // Get the pdfs
248 std::pair<ThePEG::PDF,ThePEG::PDF> pdfs;
249 pdfs.first = eh->pdf<ThePEG::PDF>(sub->incoming().first);
250 pdfs.second = eh->pdf<ThePEG::PDF>(sub->incoming().second);
251 // Get the scale
252 ThePEG::Energy2 scale = eh->lastScale();
253 double Q = std::sqrt(scale/ThePEG::GeV2);
254 // Get the values of the pdfs
255 double pdf1 = pdfs.first.xfx(sub->incoming().first ->dataPtr(), scale, x1);
256 double pdf2 = pdfs.first.xfx(sub->incoming().second->dataPtr(), scale, x2);
257 // Create the PDFinfo object
258 HepMC3::GenPdfInfoPtr pdfi = std::make_shared<HepMC3::GenPdfInfo>();
259 pdfi->set(id1, id2, x1, x2, Q, pdf1, pdf2);
260 evt->set_pdf_info(std::move(pdfi));
261 ATH_MSG_DEBUG("Added PDF info to HepMC");
262
263//uncomment to list HepMC events
264// std::cout << " print::listing Herwig7 " << std::endl;
265// HepMC3::Print::listing(std::cout, *evt);
266
267 return StatusCode::SUCCESS;
268}
269
270
271
276 ATH_MSG_INFO("Herwig7 finalizing.");
277 assert(m_gen);
278 ATH_MSG_INFO( "MetaData: generator = Herwig7 " << HWVERSION );
279 ATH_MSG_INFO( std::scientific << std::setprecision(5) << "MetaData: cross-section (nb) = " << m_gen->eventHandler()->integratedXSec()*m_xsscale/ThePEG::nanobarn);
280 // ATH_MSG_INFO( "MetaData: PDF = " << m_pdfname_me << " (ME); " << m_pdfname_ps << " (shower); " << m_pdfname_mpi << " (MPI)" );
281 ATH_MSG_INFO("MetaData: PDF = " << m_pdfname_me << " (ME); " << m_pdfname_mpi << " (shower/MPI)");
282 m_gen->finalize();
283 ThePEG::Repository::cleanup();
284
285 // possibly tidy up working directory
286 if (m_cleanup_herwig_scratch && (std::filesystem::is_directory("Herwig-scratch") || std::filesystem::is_directory("Herwig-cache"))){
287
288 ATH_MSG_INFO("removing Herwig-scratch/Herwig-cache folder from "+std::filesystem::current_path().string());
289
290 // sleep for some time to allow all access to terminate
291 std::this_thread::sleep_for(std::chrono::seconds(5));
292
293 // in case the folder can't be deleted continue with warning
294 try {
295 (std::filesystem::remove_all("Herwig-scratch") || std::filesystem::remove_all("Herwig-cache"));
296 }
297 catch (const std::exception& e) {
298 ATH_MSG_WARNING("Failed to delete the folder 'Herwig-scratch': "+std::string(e.what()));
299 }
300
301 }
302
303 return StatusCode::SUCCESS;
304}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
void convert_to_HepMC(const ThePEG::Event &m_event, HepMC::GenEvent &evt, bool nocopies, ThePEG::Energy eunit, ThePEG::Length lunit)
Athena interface for the Herwig7 generator.
size_t size() const
Number of registered mappings.
Gaudi::Details::PropertyBase & declareProperty(Gaudi::Property< T, V, H > &t)
GenModule(const std::string &name, ISvcLocator *pSvcLocator)
Constructor.
Definition GenModule.cxx:14
CLHEP::HepRandomEngine * getRandomEngine(const std::string &streamName, const EventContext &ctx) const
Definition GenModule.cxx:34
CLHEP::HepRandomEngine * getRandomEngineDuringInitialize(const std::string &streamName, unsigned long int randomSeedOffset, unsigned int conditionsRun=1, unsigned int lbn=1) const
Definition GenModule.cxx:53
IntegerProperty m_randomSeed
Seed for random number engine.
Definition GenModule.h:84
std::shared_ptr< HepMC3::GenRunInfo > m_runinfo
The run info for HepMC3.
Definition GenModule.h:90
std::string m_pdfname_mpi
PS PDF name, stored for AMI capture at finalize.
Definition Herwig7.h:195
StatusCode callGenerator()
Run the generator for one event.
Definition Herwig7.cxx:197
SG::ReadHandleKey< xAOD::EventInfo > m_evtInfoKey
Definition Herwig7.h:206
StatusCode genFinalize()
Close down the generator.
Definition Herwig7.cxx:275
ThePEG::EventPtr m_event
ThePEG event object.
Definition Herwig7.h:162
int m_seed_from_generatetf
Random number seed from Generate_tf.py.
Definition Herwig7.h:186
StatusCode writeRunFileFromText(const std::string &share_path)
Write the CA input text into a real Herwig runfile.
Definition Herwig7.cxx:155
std::string m_pdfname_me
ME PDF name, stored for AMI capture at finalize.
Definition Herwig7.h:189
bool m_cleanup_herwig_scratch
Possibly remove Herwig-scratch folder after finishing the event generation.
Definition Herwig7.h:198
Herwig7(const std::string &name, ISvcLocator *pSvcLocator)
Constructor.
Definition Herwig7.cxx:41
double m_xsscale
Scale integrated cross section by a factor for MetaData output.
Definition Herwig7.h:201
std::string m_runSettings
In-memory run settings provided by CA fragments.
Definition Herwig7.h:176
StatusCode fillEvt(HepMC::GenEvent *evt)
Convert the generated event into the HepMC format.
Definition Herwig7.cxx:212
int m_dsid
Gen_tf.py run args needed in interface.
Definition Herwig7.h:204
ThePEG::EGPtr m_gen
ThePEG generator object.
Definition Herwig7.h:159
std::string m_runfile
Name of run file.
Definition Herwig7.h:172
StatusCode genInitialize()
Initialize the generator.
Definition Herwig7.cxx:70
Herwig7API m_api
Herwig7 API object.
Definition Herwig7.h:156
std::string m_setupfile
Name of setup file.
Definition Herwig7.h:179
bool m_use_seed_from_generatetf
Ignore random number seed provided by athena and use the one from Generate_tf.py instead.
Definition Herwig7.h:183
static std::string find_file_from_list(const std::string &logical_file_name, const std::string &search_list)
void set_random_states(GenEvent *e, std::vector< long int > &a)
Definition GenEvent.h:588
HepMC3::GenEvent GenEvent
Definition GenEvent.h:39