ATLAS Offline Software
Loading...
Searching...
No Matches
Sherpa_i.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
4
7#include "GaudiKernel/MsgStream.h"
10
11#include "Sherpa_i/Sherpa_i.h"
12
13
14#include "ATOOLS/Org/CXXFLAGS_PACKAGES.H"
15#undef USING__HEPMC2
16#include "SHERPA/Main/Sherpa.H"
17#include "SHERPA/Initialization/Initialization_Handler.H"
18#ifdef IS_SHERPA_3
19#include "ATOOLS/Phys/Variations.H"
20#else
21#include "SHERPA/Tools/Variations.H"
22#endif
23#include "ATOOLS/Org/Exception.H"
24#include "ATOOLS/Org/Run_Parameter.H"
25
26#include <utility> //std::ignore
27#include <cstdio>
28#include <cstring>
29#include <mutex>
30#include <signal.h>
31#include <stdlib.h>
32#include <sys/stat.h>
33#include "CLHEP/Random/RandFlat.h"
34
35CLHEP::HepRandomEngine* p_rndEngine{};
36
37Sherpa_i::Sherpa_i(const std::string& name, ISvcLocator* pSvcLocator)
38 : GenModule(name, pSvcLocator)
39{
40 #ifdef IS_SHERPA_3
41 declareProperty("BaseFragment", m_inputfiles["Base.yaml"] = "");
42 declareProperty("RunCard", m_inputfiles["Sherpa.yaml"] = "");
43 #endif
44}
45
46
47
49 if (m_plugincode != "") {
51 #ifndef IS_SHERPA_3
52 m_params.value().push_back("SHERPA_LDADD=Sherpa_iPlugin");
53 #endif
54 }
55
56 ATH_MSG_INFO("Sherpa initialising...");
57
58 #ifdef IS_SHERPA_3
59 for (auto& inputfile : m_inputfiles) {
60 // remove first line and last character containing '"'
61 // TODO fix Python/C++ string passing, to not contain " in first place
62 inputfile.second.erase(0, inputfile.second.find("\n") + 1);
63 inputfile.second.pop_back();
64 }
65 #endif
66
67 ATH_MSG_DEBUG("... compiling plugin code");
68 if (m_plugincode != "") {
70 #ifdef IS_SHERPA_3
71 m_inputfiles["Base.yaml"] += "SHERPA_LDADD: Sherpa_iPlugin \n";
72 #else
73 m_params.value().push_back("SHERPA_LDADD=Sherpa_iPlugin");
74 #endif
75 }
76
77 ATH_MSG_DEBUG("... seeding Athena random number generator");
78 p_rndEngine = getRandomEngineDuringInitialize("SHERPA", m_randomSeed, m_dsid); // NOT THREAD-SAFE
79
80 #ifdef IS_SHERPA_3
81 ATH_MSG_DEBUG("... adapting output level");
82 if( msg().level()==MSG::FATAL || msg().level()==MSG::ERROR || msg().level()==MSG::WARNING ){
83 m_inputfiles["Base.yaml"] += "\nEVT_OUTPUT: 0 \n";
84 }
85 else if(msg().level()==MSG::INFO){
86 m_inputfiles["Base.yaml"] += "\nEVT_OUTPUT: 2 \n";
87 }
88 else if(msg().level()==MSG::DEBUG){
89 m_inputfiles["Base.yaml"] += "\nEVT_OUTPUT: 15 \n";
90 }
91 else{
92 m_inputfiles["Base.yaml"] += "\nEVT_OUTPUT: 15 \n";
93 }
94
95 ATH_MSG_DEBUG("... writing input files to directory");
96 for (auto& inputfile : m_inputfiles) {
97 // write input content to file in working directory
98 FILE *file = fopen(inputfile.first.c_str(),"w");
99 if (!file) {
100 ATH_MSG_ERROR("Cannot open " << inputfile.first);
101 return StatusCode::FAILURE;
102 }
103 fputs(inputfile.second.c_str(),file);
104 fclose(file);
105 ATH_MSG_INFO("Sherpa_i using the following settings in "+inputfile.first);
106 ATH_MSG_INFO("\n"+inputfile.second+"\n");
107 }
108
109 ATH_MSG_DEBUG("... go Sherpa!");
110 int argc = 2;
111 char** argv = new char*[2];
112 argv[0] = new char[7];
113 argv[1] = new char[34];
114 strcpy(argv[0], "Sherpa");
115 strcpy(argv[1], "RUNDATA: [Base.yaml, Sherpa.yaml]");
116 p_sherpa = new SHERPA::Sherpa(argc, argv);
117 delete [] argv;
118 #else
119 p_sherpa = new SHERPA::Sherpa();
120 #endif
121
122
123 #ifdef IS_SHERPA_3
124
125 try {
126 p_sherpa->InitializeTheRun();
127 p_sherpa->InitializeTheEventHandler();
128 }
129 catch (const ATOOLS::normal_exit& exception) {
130 ATH_MSG_ERROR("Normal exit caught, this probably means:");
131 ATH_MSG_ERROR("Have to compile Amegic libraries");
132 ATH_MSG_ERROR("You probably want to run ./makelibs");
133 return StatusCode::FAILURE;
134 }
135 catch (const ATOOLS::Exception& exception) {
136 ATH_MSG_ERROR("Unwanted ATOOLS::exception caught.");
137 ATH_MSG_ERROR(exception);
138 return StatusCode::FAILURE;
139 }
140 #else
141
142 try {
143 int argc;
144 char** argv;
145 getParameters(argc, argv);
146 p_sherpa->InitializeTheRun(argc,(char **)argv);
147 delete [] argv;
148
149 p_sherpa->InitializeTheEventHandler();
150 }
151 catch (const ATOOLS::Exception& exception) {
152 if (exception.Class()=="Matrix_Element_Handler" && exception.Type()==ATOOLS::ex::normal_exit) {
153 ATH_MSG_ERROR("Have to compile Amegic libraries");
154 ATH_MSG_ERROR("You probably want to run ./makelibs");
155 }
156 else {
157 ATH_MSG_ERROR("Unwanted ATOOLS::exception caught.");
158 ATH_MSG_ERROR(exception);
159 }
160 return StatusCode::FAILURE;
161 }
162 #endif
163 catch (const std::exception& exception) {
164 ATH_MSG_ERROR("std::exception caught.");
165 return StatusCode::FAILURE;
166 }
167
168 m_runinfo = std::make_shared<HepMC3::GenRunInfo>();
170 struct HepMC3::GenRunInfo::ToolInfo generator = {
171 std::string("SHERPA"),
172 std::string(SHERPA_VERSION)+ "." + std::string(SHERPA_SUBVERSION),
173 std::string("Used generator")
174 };
175 m_runinfo->tools().push_back(std::move(generator));
176 return StatusCode::SUCCESS;
177}
178
179
181 ATH_MSG_DEBUG("Sherpa_i in callGenerator()");
182 //Re-seed the random number stream
183 long seeds[7];
184 const EventContext& ctx = Gaudi::Hive::currentContext();
185 ATHRNG::calculateSeedsMC21(seeds, "SHERPA", ctx.eventID().event_number(), m_dsid, m_randomSeed);
186 p_rndEngine->setSeeds(seeds, 0); // NOT THREAD-SAFE
187
188 do {
189 ATH_MSG_DEBUG("Trying to generate event with Sherpa");
190 } while (p_sherpa->GenerateOneEvent()==false);
191
192 const size_t genEvents = ATOOLS::rpa->gen.NumberOfGeneratedEvents();
193 if (genEvents%1000==0) {
194 ATH_MSG_INFO("Passed "<<genEvents<<" events.");
195 }
196
197 return StatusCode::SUCCESS;
198}
199
201 ATH_MSG_DEBUG( "Sherpa_i Filling event");
202 if (!event->run_info()) event->set_run_info(m_runinfo);
203 p_sherpa->FillHepMCEvent(*event);
204
205
206//Weight, MEWeight, WeightNormalisation, NTrials
207 if (event->weights().size()>2) {
208 double nominal = event->weight("Weight");
209 for (const auto& name: event->weight_names()) {
210 if (name == "WeightNormalisation") continue;
211 if (name == "NTrials") continue;
212 if (name == "Weight") continue;
213 if (std::abs(event->weight(name)) > m_variation_weight_cap*std::abs(nominal)) {
214 ATH_MSG_INFO("Capping variation" << name << " = " << event->weight(name)/nominal << "*nominal");
215 event->weight(name) *= m_variation_weight_cap*std::abs(nominal)/std::abs(event->weight(name));
216 }
217 ATH_MSG_DEBUG("Sherpa WEIGHT " << name << " value="<< event->weight(name));
218 }
219 }
220
221 event->set_units(HepMC3::Units::MEV, HepMC3::Units::MM);
222
223
224 return StatusCode::SUCCESS;
225}
226
228
229 ATH_MSG_INFO("Sherpa_i finalize()");
230
231 std::cout << "MetaData: generator = Sherpa" << SHERPA_VERSION << "." << SHERPA_SUBVERSION << std::endl;
232 std::cout << "MetaData: cross-section (nb)= " << p_sherpa->TotalXS()/1000.0*m_xsscale << std::endl;
233
234 std::cout << "MetaData: PDF = " << p_sherpa->PDFInfo() << std::endl;
235
236 std::cout << "Named variations initialised by Sherpa:" << std::endl;
237 std::cout << *p_sherpa->GetInitHandler()->GetVariations() << std::endl;
238
239 p_sherpa->SummarizeRun();
240
241 if (m_cleanup) {
242 ATH_MSG_INFO("Deleting left-over files from working directory.");
243 system("rm -rf Results.db Process MIG_*.db MPI_*.dat libSherpa*.so libProc*.so");
244 }
245
246 return StatusCode::SUCCESS;
247}
248
249
250#ifndef IS_SHERPA_3
251void Sherpa_i::getParameters(int &argc, char** &argv) {
252 std::vector<std::string> params;
253
254 // set some ATLAS specific default values as a starting point
255 params.push_back("EXTERNAL_RNG=Atlas_RNG");
256
257 /***
258 Adopt Atlas Debug Level Scheme
259 ***/
260
261 std::string verbose_arg;
262 MsgStream log(msgSvc(), name());
263 if( log.level()==MSG::FATAL || log.level()==MSG::ERROR || log.level()==MSG::WARNING ){
264 params.push_back("OUTPUT=0");
265 }
266 else if(log.level()==MSG::INFO){
267 params.push_back("OUTPUT=2");
268 }
269 else if(log.level()==MSG::DEBUG){
270 params.push_back("OUTPUT=3");
271 }
272 else{
273 params.push_back("OUTPUT=15");
274 }
275
276 // disregard manual RUNDATA setting if run card given in JO
277 if (m_runcard != "") m_params.value().push_back("RUNDATA=Run.dat");
278
279 // allow to overwrite all parameters from JO file
280 params.insert(params.begin()+params.size(), m_params.begin(), m_params.end());
281
282 // create Run.dat file if runcard explicitely given
283 if (m_runcard != "") {
284 FILE *file = fopen("Run.dat","w");
285 if (!file) {
286 ATH_MSG_ERROR("Cannot open Run.dat");
287 }
288 else {
289 fputs(m_runcard.value().c_str(),file);
290 fclose(file);
291 }
292 }
293
294 /***
295 Convert into Sherpas argc/argv arguments
296 ***/
297 argc = 1+params.size();
298 argv = new char * [ 1+params.size() ];
299 argv[0] = new char[7];
300 strcpy(argv[0], "Sherpa");
301
302 ATH_MSG_INFO("Sherpa_i using the following Arguments");
304 for(size_t i=0; i<params.size(); i++) {
305 ATH_MSG_INFO(" [ " << params[i] << " ] ");
306 argv[i+1] = new char[params[i].size()+1];
307 strcpy(argv[i+1], params[i].c_str());
308 }
309 ATH_MSG_INFO("End Sherpa_i Argument List");
310 ATH_MSG_INFO("Further Sherpa initialisation output will be redirected to the LOG_FILE specified above.");
311
312}
313#endif
314
315void Sherpa_i::compilePlugin(const std::string& pluginCode) {
316 // TODO: not very pretty, should we eventually do this in Python instead (base fragment)
317 FILE *file = fopen("Sherpa_iPlugin.C","w");
318 if (!file) {
319 ATH_MSG_ERROR("Cannot open Sherpa_iPlugin.C");
320 }
321 else {
322 fputs(pluginCode.c_str(),file);
323 fclose(file);
324 }
325 std::string command;
326 // Python -> C++ string conversion seems to add quote character as first
327 // and last line if the string contains quotes (like always in a plugin)
328 // thus removing them here
329 command += "tail -n +2 Sherpa_iPlugin.C | head -n -1 > Sherpa_iPlugin.C.tmp; mv Sherpa_iPlugin.C.tmp Sherpa_iPlugin.C; ";
330 command += "g++ -shared -std=c++0x -g ";
331 command += "-I`Sherpa-config --incdir` ";
332 command += "`Sherpa-config --ldflags` ";
333 command += "-I$FASTJETPATH/include ";
334 command += "-fPIC -o libSherpa_iPlugin.so Sherpa_iPlugin.C";
335 ATH_MSG_INFO("Now compiling plugin library using: "+command);
336 if (system(command.c_str())!=0) {
337 ATH_MSG_ERROR("Error compiling plugin library.");
338 }
339}
340
344using namespace ATOOLS;
345
346Atlas_RNG::Atlas_RNG(CLHEP::HepRandomEngine* engine) :
347 External_RNG(), p_engine(engine), m_filename("Config.conf")
348{
349}
350
351Atlas_RNG::~Atlas_RNG() { std::ignore = std::remove(m_filename.c_str()); }
352
354
355 return CLHEP::RandFlat::shoot(p_engine);
356
357}
358
359const std::string Atlas_RNG::GenerateUID() const {
360 std::string result{""};
361 const int nMax = 26;
362 char alphabet[nMax] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',
363 'h', 'i', 'j', 'k', 'l', 'm', 'n',
364 'o', 'p', 'q', 'r', 's', 't', 'u',
365 'v', 'w', 'x', 'y', 'z' };
366 for (size_t i = 0; i < 6; ++i) {
367 //insecure random number generator, but not being used for crypto
368 //coverity[dont_call]
369 result += alphabet[rand() % nMax];
370 }
371 return result;
372}
373
375 // We set the file name first time the worker calls SaveStatus
376 std::call_once(m_once_flag_atlas_rng, [&](){
377 struct stat info;
378 if ( !stat("/dev/shm", &info)) {
379 m_filename = "/dev/shm/Config.conf.";
380 }
382 std::cout << "RNG state being saved to: " << m_filename << std::endl;
383 });
384 p_engine->saveStatus(m_filename.c_str());
385}
386
387void Atlas_RNG::RestoreStatus() { p_engine->restoreStatus(m_filename.c_str()); }
388
389// some getter magic to make this random number generator available to sherpa
390// DECLARE_GETTER doesn't compile with c++20 in Sherpa versions before 3.
391#ifdef IS_SHERPA_3
392DECLARE_GETTER(Atlas_RNG,"Atlas_RNG",External_RNG,RNG_Key);
393#else
394namespace ATOOLS {
395template <> class Getter<External_RNG,RNG_Key,Atlas_RNG,std::less<std::string>>:
396 public Getter_Function<External_RNG,RNG_Key,std::less<std::string>> {
397private:
399protected:
400 void PrintInfo(std::ostream &str,const size_t width) const;
401 Object_Type *operator()(const Parameter_Type &parameters) const;
402public:
403 Getter(const bool &d=true):
404 Getter_Function<External_RNG,RNG_Key,std::less<std::string>>("Atlas_RNG")
405 { SetDisplay(d); }
406};
407}
408ATOOLS::Getter<External_RNG,RNG_Key,Atlas_RNG>
409ATOOLS::Getter<External_RNG,RNG_Key,Atlas_RNG>::s_initializer(true);
410#endif
411
412External_RNG *ATOOLS::Getter<External_RNG,RNG_Key,Atlas_RNG>::operator()(const RNG_Key &) const
413{ return new Atlas_RNG(p_rndEngine); }
414
415void ATOOLS::Getter<External_RNG,RNG_Key,Atlas_RNG>::PrintInfo(std::ostream &str,const size_t) const
416{ str<<"Atlas RNG interface"; }
#define ATH_MSG_ERROR(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_DEBUG(x)
ATLAS-specific HepMC functions.
CLHEP::HepRandomEngine * p_rndEngine
Definition Sherpa_i.cxx:35
const double width
Object_Type * operator()(const Parameter_Type &parameters) const
void PrintInfo(std::ostream &str, const size_t width) const
static Getter< External_RNG, RNG_Key, Atlas_RNG, std::less< std::string > > s_initializer
Definition Sherpa_i.cxx:398
Gaudi::Details::PropertyBase & declareProperty(Gaudi::Property< T, V, H > &t)
Atlas_RNG(CLHEP::HepRandomEngine *)
Definition Sherpa_i.cxx:346
void SaveStatus()
Definition Sherpa_i.cxx:374
CLHEP::HepRandomEngine * p_engine
Definition Sherpa_i.h:78
double Get()
Definition Sherpa_i.cxx:353
void RestoreStatus()
Definition Sherpa_i.cxx:387
std::string m_filename
Definition Sherpa_i.h:79
std::once_flag m_once_flag_atlas_rng
Definition Sherpa_i.h:80
const std::string GenerateUID() const
Definition Sherpa_i.cxx:359
GenModule(const std::string &name, ISvcLocator *pSvcLocator)
Constructor.
Definition GenModule.cxx:14
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
StatusCode genFinalize()
For finalising the generator, if required.
Definition Sherpa_i.cxx:227
StringProperty m_runcard
FIXME unused?
Definition Sherpa_i.h:42
StatusCode genInitialize()
For initializing the generator, if required.
Definition Sherpa_i.cxx:48
SHERPA::Sherpa * p_sherpa
Definition Sherpa_i.h:32
StringProperty m_plugincode
Optional code for plugin library to compile and load at run time.
Definition Sherpa_i.h:61
StringArrayProperty m_params
List of additional Sherpa parameters beyond run card snippet (from JO file).
Definition Sherpa_i.h:45
BooleanProperty m_cleanup
Definition Sherpa_i.h:67
IntegerProperty m_dsid
Definition Sherpa_i.h:70
void compilePlugin(const std::string &)
Definition Sherpa_i.cxx:315
Sherpa_i(const std::string &name, ISvcLocator *pSvcLocator)
Definition Sherpa_i.cxx:37
StatusCode callGenerator()
For calling the generator on each iteration of the event loop.
Definition Sherpa_i.cxx:180
DoubleProperty m_variation_weight_cap
Variation weight cap factor.
Definition Sherpa_i.h:64
DoubleProperty m_xsscale
Definition Sherpa_i.h:66
StatusCode fillEvt(HepMC::GenEvent *evt)
For filling the HepMC event object.
Definition Sherpa_i.cxx:200
void getParameters(int &argc, char **&argv)
Definition Sherpa_i.cxx:251
STL class.
void calculateSeedsMC21(long *seeds, const std::string &algName, uint64_t ev, uint64_t run, uint64_t offset=0)
Set the random seed using a string (e.g.
HepMC3::GenEvent GenEvent
Definition GenEvent.h:39
STL namespace.
DataModel_detail::iterator< DVL > remove(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end, const T &value)
Specialization of remove for DataVector/List.
MsgStream & msg
Definition testRead.cxx:32
TFile * file