ATLAS Offline Software
Loading...
Searching...
No Matches
Herwig7Control.py
Go to the documentation of this file.
1# Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
2# \file Herwig7Control.py
3# \brief Main python interface for %Herwig7 for preparing the event generation
4# \author Daniel Rauch (daniel.rauch@desy.de)
5# \author Lukas Kretschmann (lukas.kretschmann@cern.ch)
6#
7# This part of the interface provides functionality for running all the tasks
8# necessary to initialize and prepare the event generation.
9# More concretely, it handles the read or alternatively the build/integrate/
10# mergegrids steps in order to produce the Herwig runfile and all other
11# ingredients for a run, possibly also creating a gridpack.
12# The event generation itself starting from reading the runfile is handled
13# in Herwig7_i/Herwig7.h and src/Herwig7.cxx.
14
15import os, shutil, subprocess, sys
16
17from . import Herwig7Utils as hw7Utils
18from . import Herwig7JOChecker as JOChecker
19from . import Herwig7ConfigDecoder as ConfigDecoder
20
21from AthenaCommon import Logging
22athMsgLog = Logging.logging.getLogger('Herwig7Control')
23
24
25# \brief Get path to the `share/Herwig` folder
26#
27# Try to get it from the `InstallArea` first.
28# If this fails fall back to `$HERWIG7_PATH/share/Herwig`
29#
31
32 cmt_paths = os.environ.get("CMAKE_PREFIX_PATH")
33 cmt_config = os.environ.get("BINARY_TAG")
34
35 # trying to get it from the `InstallArea`
36 for path in cmt_paths.split(':'):
37 path = os.path.join(path, "InstallArea", cmt_config, "share")
38 try:
39 filelist = os.listdir(path)
40 except Exception:
41 filelist = []
42 if "HerwigDefaults.rpo" in filelist: return(path)
43
44 # falling back to `$HERWIG7_PATH`
45 path = os.path.join(os.environ['HERWIG7_PATH'], 'share/Herwig')
46 if os.path.isfile(os.path.join(path, 'HerwigDefaults.rpo')):
47 return(path)
48
49 # raise exception if none of the two methods work out
50 raise RuntimeError(hw7Utils.ansi_format_error('Could not find a valid share/Herwig folder'))
51
52
53# proper handling with path set in External/Herwig7/cmt/requirements
54herwig7_path = os.environ['HERWIG7_PATH']
55herwig7_bin_path = os.path.join(herwig7_path, 'bin')
56herwig7_share_path = get_share_path()
57
58herwig7_binary = os.path.join(herwig7_bin_path, 'Herwig')
59
60
61# Do the read/run sequence.
62#
63# This function should provide the read and run step in one go
64def run(gen_config):
65
66 # perform the read step
67 do_read(gen_config)
68
69 # start the event generation
70 do_run(gen_config, cleanup_herwig_scratch=False)
71
72
73# Do the build, integrate, mergegrids and run step in one go
74# without creating a gridpack
75#
76# \param[in] cleanup_herwig_scratch Remove `Herwig-scratch` or 'Herwig-cache' folder after event generation to save disk space
77def matchbox_run(gen_config, integration_jobs, cleanup_herwig_scratch):
78
79 # perform build/integrate/mergegrids sequence
80 do_build_integrate_mergegrids(gen_config, integration_jobs)
81
82 # start the event generation
83 do_run(gen_config, cleanup_herwig_scratch)
84
85
86# Either do the build, integrate and mergegrids steps and create a gridpack
87# or extract it and generate events from it
88#
89# \param[in] cleanup_herwig_scratch Remove `Herwig-scratch` or 'Herwig-cache' folder after event generation to save disk space
90def matchbox_run_gridpack(gen_config, integration_jobs, gridpack_name, cleanup_herwig_scratch, integrate):
91
92 # print start banner including version numbers
93 log(message=start_banner())
94
95 if not gridpack_name or integrate:
96
97 # create infile from jobOption commands
98 write_infile(gen_config)
99
100 # do build/integrate/mergegrids sequence
101 xsec, err = do_build_integrate_mergegrids(gen_config, integration_jobs)
102
103 # compress infile, runfile and process folder to gridpack tarball
104 do_compress_gridpack(gen_config.run_name, gridpack_name)
105
106 # display banner and exit
107 log(message=exit_banner(gridpack_name, xsec, err))
108 sys.exit(0)
109
110 else:
111
112 # unpack the gridpack
113 DSIS_dir = gen_config.runArgs.jobConfig[0]+"/"
114 do_uncompress_gridpack(DSIS_dir+gridpack_name)
115 athMsgLog.info("Finished unpacking the gridpack")
116
117 # start the event generation
118 do_run(gen_config, cleanup_herwig_scratch)
119
120
121
122def do_step(step, command, logfile_name=None):
123
124 athMsgLog.info(hw7Utils.ansi_format_info("Starting Herwig7 '{}' step with command '{}'".format(step, ' '.join(command))))
125
126 logfile = open(logfile_name, 'w') if logfile_name else None
127 do = subprocess.Popen(command, stdout=logfile, stderr=logfile)
128 do.wait()
129 if not do.returncode == 0:
130 raise RuntimeError(hw7Utils.ansi_format_error("Some error occured during the '{}' step.".format(step)))
131
132 if logfile:
133 athMsgLog.info("Content of %s log file '%s':", step, logfile_name)
134 athMsgLog.info("")
135 with open(logfile_name, 'r') as logfile:
136 for line in logfile:
137 athMsgLog.info(' %s', line.rstrip('\n'))
138 athMsgLog.info("")
139
140
142 athMsgLog.info(hw7Utils.ansi_format_info("Doing abort"))
143 sys.exit(0)
144
145
146def render_infile(gen_config):
147 """
148 Render the full Herwig infile as a single string.
149 This is needed to avoid writing a file to disk (old workflow)
150 so that we avoid side effects in the CA fragments.
151 """
152
153 gen_config.default_commands.lock()
154 gen_config.commands.lock()
155
156 commands = \
157 gen_config.global_pre_commands().splitlines() \
158 + gen_config.local_pre_commands().splitlines() \
159 + ["",
160 "## ================",
161 "## Default Commands",
162 "## ================"] \
163 + str(gen_config.default_commands.commands).splitlines() \
164 + ["",
165 "## ========================",
166 "## Commands from jobOptions",
167 "## ========================"] \
168 + str(gen_config.commands.commands).splitlines() \
169 + gen_config.local_post_commands().splitlines()
170
171 return('\n'.join(commands) + '\n')
172
173
175 runfile_name,
176 random_seed=None,
177 me_pdf_name=None,
178 mpi_pdf_name=None,
179 cleanup_herwig_scratch=None,
180 run_settings=None,
181 decode_runfile=False):
182 """Apply the Herwig7 algorithm settings"""
183
184 alg.RunFile = runfile_name
185
186 # Pass CA-supplied run settings to the C++ algorithm. This is materialised
187 # as a Herwig infile only during run time.
188 if run_settings is not None:
189 alg.RunSettings = run_settings
190
191 if decode_runfile:
192 ConfigDecoder.DecodeRunCard(input_file=alg.RunFile)
193
194 # Overwrite athena's seed for the random number generator.
195 if random_seed is None:
196 alg.UseRandomSeedFromGeneratetf = False
197 else:
198 alg.UseRandomSeedFromGeneratetf = True
199 alg.RandomSeedFromGeneratetf = random_seed
200
201 # Set matrix element PDF name in the Herwig7 C++ class.
202 if me_pdf_name is not None:
203 alg.PDFNameME = me_pdf_name
204
205 # Set underlying event PDF name in the Herwig7 C++ class.
206 if mpi_pdf_name is not None:
207 alg.PDFNameMPI = mpi_pdf_name
208
209 # Delete Herwig-scratch folder after finishing the event generation.
210 if cleanup_herwig_scratch is not None:
211 alg.CleanupHerwigScratch = cleanup_herwig_scratch
212
213
214# Configure the legacy Herwig7 algorithm from a gen_config object
216 runfile_name,
217 cleanup_herwig_scratch=None,
218 decode_runfile=False):
219
221 gen_config.genSeq.Herwig7,
222 runfile_name,
223 gen_config.runArgs.randomSeed,
224 gen_config.me_pdf_name,
225 gen_config.mpi_pdf_name,
226 cleanup_herwig_scratch=cleanup_herwig_scratch,
227 decode_runfile=decode_runfile,
228 )
229
230
231# Do the read step
232def do_read(gen_config):
233
234 # print start banner including version numbers
235 log(message=start_banner())
236
237 # create infile from JobOption object
238 write_infile(gen_config)
239
240 # copy HerwigDefaults.rpo to the current working directory
242
243 # call Herwig7 binary to do the read step
244 share_path = get_share_path()
245 do_step('read', [herwig7_binary, 'read', get_infile_name(gen_config.run_name), '-I', share_path])
246
247# Do the read step and re-use an already existing infile
249
250 # print start banner including version numbers
251 log(message=start_banner())
252
253 # copy HerwigDefaults.rpo to the current working directory
255
256 # call Herwig7 binary to do the read step
257 share_path = get_share_path()
258 do_step('read', [herwig7_binary, 'read', gen_config.infile_name, '-I', share_path])
259
260
261# Do the build step
262def do_build(gen_config, integration_jobs):
263
264 # print start banner including version numbers
265 log(message=start_banner())
266
267 # create infile from JobOption object
268 write_infile(gen_config)
269
270 # copy HerwigDefaults.rpo to the current working directory
272
273 # call the Herwig7 binary to do the build step
274 share_path = get_share_path()
275 do_step('build', [herwig7_binary, 'build', get_infile_name(gen_config.run_name), '-I', share_path, '-y '+str(integration_jobs)])
276
277
278# Do the integrate step for one specific integration job
279# \todo provide info about the range
280def do_integrate(run_name, integration_job):
281
282 runfile_name = get_runfile_name(run_name)
283
284 integrate_log = run_name+'.integrate'+str(integration_job)+'.log'
285 integrate_command = [herwig7_binary,'integrate',runfile_name,'--jobid='+str(integration_job)]
286
287 do_step('integrate', integrate_command, integrate_log)
288
289
290# This function provides the mergegrids step
291def do_mergegrids(run_name, integration_jobs):
292
293 runfile_name = get_runfile_name(run_name)
294 mergegrids_command = [herwig7_binary, 'mergegrids', runfile_name]
295
296 do_step('mergegrids', mergegrids_command)
297
298 # calculate the cross section from the integration logfiles and possibly warn about low accuracy
299 xsec, err = hw7Utils.get_cross_section(run_name, integration_jobs)
300
301 return(xsec, err)
302
303
304# Subsequent build, integrate and mergegrid steps
305def do_build_integrate_mergegrids(gen_config, integration_jobs):
306
307 # run build step
308 do_build(gen_config, integration_jobs)
309
310 # run integration jobs in parallel subprocesses
311 runfile_name = get_runfile_name(gen_config.run_name)
312 athMsgLog.info(hw7Utils.ansi_format_info('Starting integration with {} jobs'.format(integration_jobs)))
313
314 integration_procs = []
315 for integration_job in range(integration_jobs):
316 integrate_log = gen_config.run_name+'.integrate'+str(integration_job)+'.log'
317 integrate_command = [herwig7_binary,'integrate',runfile_name,'--jobid='+str(integration_job)]
318 integration_procs.append(hw7Utils.Process(integration_job, integrate_command, integrate_log))
319
320 integration_handler = hw7Utils.ProcessHandler(integration_procs, athMsgLog)
321 if not integration_handler.success():
322 raise RuntimeError(hw7Utils.ansi_format_error('Not all of the integration jobs finished successfully'))
323
324 athMsgLog.info(hw7Utils.ansi_format_ok('All integration jobs finished successfully'))
325
326 # combine the different integration grids
327 xsec, err = do_mergegrids(gen_config.run_name, integration_jobs)
328
329 return(xsec, err)
330
331
332def do_compress_gridpack(run_name, gridpack_name):
333
334 if not (gridpack_name.endswith('.tar.gz') or gridpack_name.endswith('.tgz')): gridpack_name += '.tar.gz'
335 infile_name = get_infile_name(run_name)
336 runfile_name = get_runfile_name(run_name)
337 version = herwig_version()
338 athMsgLog.debug("Scratch area, this is Herwig version '{}'".format(version))
339 if "7.1" in version or "7.0" in version:
340 do_step('compress', ['tar', 'czf', gridpack_name, infile_name, runfile_name, 'Herwig-scratch'])
341 else:
342 do_step('compress', ['tar', 'czf', gridpack_name, infile_name, runfile_name, 'Herwig-cache'])
343
344
345def do_uncompress_gridpack(gridpack_name):
346
347 athMsgLog.info("unpacking gridpack '%s'", gridpack_name)
348 do_step('uncompress', ['tar', 'xzf', gridpack_name])
349
350
351# \param[in] cleanup_herwig_scratch Remove `Herwig-scratch` folder after event generation to save disk space
352def do_run(gen_config, cleanup_herwig_scratch=True):
353
354 # this is necessary to make Herwig aware of the name of the run file
355 runfile_name = get_runfile_name(gen_config.run_name)
356 gen_config.genSeq.Herwig7.RunFile = runfile_name
357
358 # check the options in the .in file
359 JOChecker.check_file()
360
362 gen_config,
363 runfile_name,
364 cleanup_herwig_scratch=cleanup_herwig_scratch,
365 decode_runfile=True,
366 )
367
368 # don't break out here so that the job options can be finished and the C++
369 # part of the interface can take over and generate the events
370 athMsgLog.info(hw7Utils.ansi_format_info("Returning to the job options and starting the event generation afterwards"))
371
372
373# Do the run step and re-use an already existing runfile
375
376 # this is necessary to make Herwig aware of the name of the run file
378 gen_config,
379 gen_config.runfile_name,
380 )
381
382 # don't break out here so that the job options can be finished and the C++
383 # part of the interface can take over and generate the events
384 athMsgLog.info(hw7Utils.ansi_format_info("Returning to the job options and starting the event generation afterwards"))
385
386
387# utility functions -----------------------------------------------------------
388
389
391
392 versions = get_software_versions()
393 return(' '.join(versions[0].split()[1:]))
394
395
397
398 return("H"+herwig_version()+"-Default")
399
400
402
403 versions = get_software_versions()
404 return(' '.join(versions[1].split()[1:]))
405
407
408 herwig_version_number = herwig_version()
409 thepeg_version_number = thepeg_version()
410 herwig_version_space = ' '.join(['' for i in range(14-len(herwig_version_number))])
411 thepeg_version_space = ' '.join(['' for i in range(14-len(thepeg_version_number))])
412
413 banner = ''
414 banner += "#####################################\n"
415 banner += "## {} ##\n".format(hw7Utils.ansi_format_ok("---------------------------"))
416 banner += "## {} ##\n".format(hw7Utils.ansi_format_ok("Starting HERWIG 7 in ATHENA"))
417 banner += "## {} ##\n".format(hw7Utils.ansi_format_ok("---------------------------"))
418 banner += "## ##\n"
419 banner += "## with software versions: ##\n"
420 banner += "## - Herwig7: {}{} ##\n".format(herwig_version_number, herwig_version_space)
421 banner += "## - ThePEG: {}{} ##\n".format(thepeg_version_number, thepeg_version_space)
422 banner += "## ##\n"
423 banner += "#####################################\n"
424 return(banner)
425
426
428
429 return(subprocess.check_output([herwig7_binary,'--version'], text=True).splitlines())
430
431
432def get_infile_name(run_name="Herwig-Matchbox"):
433
434 return('{}.in'.format(run_name))
435
436
437def get_setupfile_name(run_name="Herwig-Matchbox"):
438
439 return('{}.setupfile.in'.format(run_name))
440
441
442def get_runfile_name(run_name="Herwig-Matchbox"):
443
444 return('{}.run'.format(run_name) if not run_name.endswith('.run') else run_name)
445
446
447def write_infile(gen_config, print_infile=True):
448
449 infile_name = get_infile_name(gen_config.run_name)
450 if print_infile: athMsgLog.info("")
451 athMsgLog.info(hw7Utils.ansi_format_info("Writing infile '{}'".format(infile_name)))
452 infile_text = render_infile(gen_config)
453 commands = infile_text.splitlines()
454 try:
455 with open(infile_name, 'w') as infile:
456 for command in commands:
457 infile.write(command+'\n')
458 except Exception:
459 raise RuntimeError('Could not write Herwig/Matchbox infile')
460
461 if print_infile:
462 athMsgLog.info("")
463 for command in commands:
464 athMsgLog.info(' %s', command)
465 athMsgLog.info("")
466
467
468def write_setupfile(run_name, commands, print_setupfile=True):
469
470 setupfile_name = get_setupfile_name(run_name)
471
472 if len(commands) > 0:
473 if print_setupfile: athMsgLog.info("")
474 athMsgLog.info("Writing setupfile '%s'", setupfile_name)
475 try:
476 with open(setupfile_name, 'w') as setupfile:
477 for command in commands: setupfile.write(command+'\n')
478 except Exception:
479 raise RuntimeError('Could not write Herwig/Matchbox setupfile')
480
481 if print_setupfile:
482 athMsgLog.info("")
483 for command in commands: athMsgLog.info(' %s', command)
484 athMsgLog.info("")
485
486 else:
487 athMsgLog.info("No setupfile commands given.")
488
489
490# \brief Copy default repository `HerwigDefaults.rpo` to current working directory
491#
493
494 shutil.copy(os.path.join(get_share_path(), 'HerwigDefaults.rpo'), 'HerwigDefaults.rpo')
495
496
497def log(level='info', message=''):
498
499 if level in ['info', 'warn', 'error']:
500 logger = getattr(athMsgLog, level)
501 for line in message.splitlines(): logger(line)
502 else:
503 raise ValueError("Unknown logging level'{}' specified. Possible values are 'info', 'warn' or 'error'".format(level))
504
505
506def exit_banner(gridpack, cross_section, cross_section_error):
507
508 size = hw7Utils.humanize_bytes(hw7Utils.get_size(gridpack))
509 space_size = hw7Utils.get_repeated_pattern(' ', 31-len(size))
510
511 xsec = '{:f}'.format(cross_section)
512 err = '{:f}'.format(cross_section_error)
513 rel_err = '{:.2f}'.format(cross_section_error / cross_section * 100.0)
514 space_xsec = hw7Utils.get_repeated_pattern(' ', 37-len(xsec)-len(err)-len(rel_err))
515
516 banner = ''
517 space = ' '.join(['' for i in range(70+4+1-len(gridpack))])
518 banner += "##########################################################################################\n"
519 banner += "## ------------------------------------------------------------------------------- ##\n"
520 banner += "## {} (size: {}){} ##\n".format(hw7Utils.ansi_format_ok("HERWIG 7 successfully created the gridpack"), size, space_size)
521 banner += "## ##\n"
522 banner += "## {}{} ##\n".format(hw7Utils.ansi_format_info(gridpack), space)
523 banner += "## ##\n"
524 banner += "## cross section from integration: {} +/- {} ({}%) nb {} ##\n".format(xsec, err, rel_err, space_xsec)
525
526 if cross_section_error / cross_section > hw7Utils.integration_grids_precision_threshold:
527 threshold = '{}%'.format(hw7Utils.integration_grids_precision_threshold*100.0)
528 space_threshold = hw7Utils.get_repeated_pattern(' ', 6-len(threshold))
529 banner += "## ##\n"
530 banner += "## {} ##\n".format(hw7Utils.ansi_format_warning("! WARNING: The integration grids only have a low precision (worse than {}){}!".format(threshold, space_threshold)))
531
532 banner += "## ##\n"
533 banner += "## ------------------------------------------------------------------------------- ##\n"
534 banner += "## ##\n"
535 banner += "## Please ignore the error ##\n"
536 banner += "## ##\n"
537 banner += "## No such file or directory: 'evgen.root' raised while stating file evgen.root ##\n"
538 banner += "## ##\n"
539 banner += "##########################################################################################\n"
540 return(banner)
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:179
static Root::TMsgLogger logger("iLumiCalc")
do_read(gen_config)
matchbox_run(gen_config, integration_jobs, cleanup_herwig_scratch)
do_step(step, command, logfile_name=None)
render_infile(gen_config)
get_setupfile_name(run_name="Herwig-Matchbox")
do_run_existing_runfile(gen_config)
exit_banner(gridpack, cross_section, cross_section_error)
do_integrate(run_name, integration_job)
do_uncompress_gridpack(gridpack_name)
get_infile_name(run_name="Herwig-Matchbox")
run(gen_config)
write_infile(gen_config, print_infile=True)
get_runfile_name(run_name="Herwig-Matchbox")
matchbox_run_gridpack(gen_config, integration_jobs, gridpack_name, cleanup_herwig_scratch, integrate)
do_read_existing_infile(gen_config)
configure_algorithm(alg, runfile_name, random_seed=None, me_pdf_name=None, mpi_pdf_name=None, cleanup_herwig_scratch=None, run_settings=None, decode_runfile=False)
do_compress_gridpack(run_name, gridpack_name)
write_setupfile(run_name, commands, print_setupfile=True)
_configure_run_algorithm(gen_config, runfile_name, cleanup_herwig_scratch=None, decode_runfile=False)
do_mergegrids(run_name, integration_jobs)
do_build_integrate_mergegrids(gen_config, integration_jobs)
do_build(gen_config, integration_jobs)
log(level='info', message='')
do_run(gen_config, cleanup_herwig_scratch=True)