15import os, shutil, subprocess, sys
17from .
import Herwig7Utils
as hw7Utils
18from .
import Herwig7JOChecker
as JOChecker
19from .
import Herwig7ConfigDecoder
as ConfigDecoder
21from AthenaCommon
import Logging
22athMsgLog = Logging.logging.getLogger(
'Herwig7Control')
32 cmt_paths = os.environ.get(
"CMAKE_PREFIX_PATH")
33 cmt_config = os.environ.get(
"BINARY_TAG")
36 for path
in cmt_paths.split(
':'):
37 path = os.path.join(path,
"InstallArea", cmt_config,
"share")
39 filelist = os.listdir(path)
42 if "HerwigDefaults.rpo" in filelist: return(path)
45 path = os.path.join(os.environ[
'HERWIG7_PATH'],
'share/Herwig')
46 if os.path.isfile(os.path.join(path,
'HerwigDefaults.rpo')):
50 raise RuntimeError(hw7Utils.ansi_format_error(
'Could not find a valid share/Herwig folder'))
54herwig7_path = os.environ[
'HERWIG7_PATH']
55herwig7_bin_path = os.path.join(herwig7_path,
'bin')
58herwig7_binary = os.path.join(herwig7_bin_path,
'Herwig')
70 do_run(gen_config, cleanup_herwig_scratch=
False)
77def matchbox_run(gen_config, integration_jobs, cleanup_herwig_scratch):
83 do_run(gen_config, cleanup_herwig_scratch)
95 if not gridpack_name
or integrate:
113 DSIS_dir = gen_config.runArgs.jobConfig[0]+
"/"
115 athMsgLog.info(
"Finished unpacking the gridpack")
118 do_run(gen_config, cleanup_herwig_scratch)
124 athMsgLog.info(hw7Utils.ansi_format_info(
"Starting Herwig7 '{}' step with command '{}'".format(step,
' '.join(command))))
126 logfile = open(logfile_name,
'w')
if logfile_name
else None
127 do = subprocess.Popen(command, stdout=logfile, stderr=logfile)
129 if not do.returncode == 0:
130 raise RuntimeError(hw7Utils.ansi_format_error(
"Some error occured during the '{}' step.".format(step)))
133 athMsgLog.info(
"Content of %s log file '%s':", step, logfile_name)
135 with open(logfile_name,
'r')
as logfile:
137 athMsgLog.info(
' %s', line.rstrip(
'\n'))
142 athMsgLog.info(hw7Utils.ansi_format_info(
"Doing abort"))
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.
153 gen_config.default_commands.lock()
154 gen_config.commands.lock()
157 gen_config.global_pre_commands().splitlines() \
158 + gen_config.local_pre_commands().splitlines() \
160 "## ================",
161 "## Default Commands",
162 "## ================"] \
163 + str(gen_config.default_commands.commands).splitlines() \
165 "## ========================",
166 "## Commands from jobOptions",
167 "## ========================"] \
168 + str(gen_config.commands.commands).splitlines() \
169 + gen_config.local_post_commands().splitlines()
171 return(
'\n'.join(commands) +
'\n')
179 cleanup_herwig_scratch=None,
181 decode_runfile=False):
182 """Apply the Herwig7 algorithm settings"""
184 alg.RunFile = runfile_name
188 if run_settings
is not None:
189 alg.RunSettings = run_settings
190 alg.Repository = os.path.join(herwig7_share_path,
'HerwigDefaults.rpo')
193 ConfigDecoder.DecodeRunCard(input_file=alg.RunFile)
196 if random_seed
is None:
197 alg.UseRandomSeedFromGeneratetf =
False
199 alg.UseRandomSeedFromGeneratetf =
True
200 alg.RandomSeedFromGeneratetf = random_seed
203 if me_pdf_name
is not None:
204 alg.PDFNameME = me_pdf_name
207 if mpi_pdf_name
is not None:
208 alg.PDFNameMPI = mpi_pdf_name
211 if cleanup_herwig_scratch
is not None:
212 alg.CleanupHerwigScratch = cleanup_herwig_scratch
218 cleanup_herwig_scratch=None,
219 decode_runfile=False):
222 gen_config.genSeq.Herwig7,
224 gen_config.runArgs.randomSeed,
225 gen_config.me_pdf_name,
226 gen_config.mpi_pdf_name,
227 cleanup_herwig_scratch=cleanup_herwig_scratch,
228 decode_runfile=decode_runfile,
259 do_step(
'read', [herwig7_binary,
'read', gen_config.infile_name,
'-I', share_path])
276 do_step(
'build', [herwig7_binary,
'build',
get_infile_name(gen_config.run_name),
'-I', share_path,
'-y '+str(integration_jobs)])
285 integrate_log = run_name+
'.integrate'+str(integration_job)+
'.log'
286 integrate_command = [herwig7_binary,
'integrate',runfile_name,
'--jobid='+str(integration_job)]
288 do_step(
'integrate', integrate_command, integrate_log)
295 mergegrids_command = [herwig7_binary,
'mergegrids', runfile_name]
297 do_step(
'mergegrids', mergegrids_command)
300 xsec, err = hw7Utils.get_cross_section(run_name, integration_jobs)
309 do_build(gen_config, integration_jobs)
313 athMsgLog.info(hw7Utils.ansi_format_info(
'Starting integration with {} jobs'.format(integration_jobs)))
315 integration_procs = []
316 for integration_job
in range(integration_jobs):
317 integrate_log = gen_config.run_name+
'.integrate'+str(integration_job)+
'.log'
318 integrate_command = [herwig7_binary,
'integrate',runfile_name,
'--jobid='+str(integration_job)]
319 integration_procs.append(hw7Utils.Process(integration_job, integrate_command, integrate_log))
321 integration_handler = hw7Utils.ProcessHandler(integration_procs, athMsgLog)
322 if not integration_handler.success():
323 raise RuntimeError(hw7Utils.ansi_format_error(
'Not all of the integration jobs finished successfully'))
325 athMsgLog.info(hw7Utils.ansi_format_ok(
'All integration jobs finished successfully'))
328 xsec, err =
do_mergegrids(gen_config.run_name, integration_jobs)
335 if not (gridpack_name.endswith(
'.tar.gz')
or gridpack_name.endswith(
'.tgz')): gridpack_name +=
'.tar.gz'
339 athMsgLog.debug(
"Scratch area, this is Herwig version '{}'".format(version))
340 if "7.1" in version
or "7.0" in version:
341 do_step(
'compress', [
'tar',
'czf', gridpack_name, infile_name, runfile_name,
'Herwig-scratch'])
343 do_step(
'compress', [
'tar',
'czf', gridpack_name, infile_name, runfile_name,
'Herwig-cache'])
348 athMsgLog.info(
"unpacking gridpack '%s'", gridpack_name)
349 do_step(
'uncompress', [
'tar',
'xzf', gridpack_name])
353def do_run(gen_config, cleanup_herwig_scratch=True):
357 gen_config.genSeq.Herwig7.RunFile = runfile_name
360 JOChecker.check_file()
365 cleanup_herwig_scratch=cleanup_herwig_scratch,
371 athMsgLog.info(hw7Utils.ansi_format_info(
"Returning to the job options and starting the event generation afterwards"))
380 gen_config.runfile_name,
385 athMsgLog.info(hw7Utils.ansi_format_info(
"Returning to the job options and starting the event generation afterwards"))
394 return(
' '.join(versions[0].
split()[1:]))
405 return(
' '.join(versions[1].
split()[1:]))
411 herwig_version_space =
' '.join([
'' for i
in range(14-len(herwig_version_number))])
412 thepeg_version_space =
' '.join([
'' for i
in range(14-len(thepeg_version_number))])
415 banner +=
"#####################################\n"
416 banner +=
"## {} ##\n".format(hw7Utils.ansi_format_ok(
"---------------------------"))
417 banner +=
"## {} ##\n".format(hw7Utils.ansi_format_ok(
"Starting HERWIG 7 in ATHENA"))
418 banner +=
"## {} ##\n".format(hw7Utils.ansi_format_ok(
"---------------------------"))
420 banner +=
"## with software versions: ##\n"
421 banner +=
"## - Herwig7: {}{} ##\n".format(herwig_version_number, herwig_version_space)
422 banner +=
"## - ThePEG: {}{} ##\n".format(thepeg_version_number, thepeg_version_space)
424 banner +=
"#####################################\n"
430 return(subprocess.check_output([herwig7_binary,
'--version'], text=
True).splitlines())
435 return(
'{}.in'.format(run_name))
440 return(
'{}.setupfile.in'.format(run_name))
445 return(
'{}.run'.format(run_name)
if not run_name.endswith(
'.run')
else run_name)
451 if print_infile: athMsgLog.info(
"")
452 athMsgLog.info(hw7Utils.ansi_format_info(
"Writing infile '{}'".format(infile_name)))
454 commands = infile_text.splitlines()
456 with open(infile_name,
'w')
as infile:
457 for command
in commands:
458 infile.write(command+
'\n')
460 raise RuntimeError(
'Could not write Herwig/Matchbox infile')
464 for command
in commands:
465 athMsgLog.info(
' %s', command)
473 if len(commands) > 0:
474 if print_setupfile: athMsgLog.info(
"")
475 athMsgLog.info(
"Writing setupfile '%s'", setupfile_name)
477 with open(setupfile_name,
'w')
as setupfile:
478 for command
in commands: setupfile.write(command+
'\n')
480 raise RuntimeError(
'Could not write Herwig/Matchbox setupfile')
484 for command
in commands: athMsgLog.info(
' %s', command)
488 athMsgLog.info(
"No setupfile commands given.")
495 shutil.copy(os.path.join(
get_share_path(),
'HerwigDefaults.rpo'),
'HerwigDefaults.rpo')
498def log(level='info', message=''):
500 if level
in [
'info',
'warn',
'error']:
501 logger = getattr(athMsgLog, level)
502 for line
in message.splitlines():
logger(line)
504 raise ValueError(
"Unknown logging level'{}' specified. Possible values are 'info', 'warn' or 'error'".format(level))
509 size = hw7Utils.humanize_bytes(hw7Utils.get_size(gridpack))
510 space_size = hw7Utils.get_repeated_pattern(
' ', 31-len(size))
512 xsec =
'{:f}'.format(cross_section)
513 err =
'{:f}'.format(cross_section_error)
514 rel_err =
'{:.2f}'.format(cross_section_error / cross_section * 100.0)
515 space_xsec = hw7Utils.get_repeated_pattern(
' ', 37-len(xsec)-len(err)-len(rel_err))
518 space =
' '.join([
'' for i
in range(70+4+1-len(gridpack))])
519 banner +=
"##########################################################################################\n"
520 banner +=
"## ------------------------------------------------------------------------------- ##\n"
521 banner +=
"## {} (size: {}){} ##\n".format(hw7Utils.ansi_format_ok(
"HERWIG 7 successfully created the gridpack"), size, space_size)
523 banner +=
"## {}{} ##\n".format(hw7Utils.ansi_format_info(gridpack), space)
525 banner +=
"## cross section from integration: {} +/- {} ({}%) nb {} ##\n".format(xsec, err, rel_err, space_xsec)
527 if cross_section_error / cross_section > hw7Utils.integration_grids_precision_threshold:
528 threshold =
'{}%'.format(hw7Utils.integration_grids_precision_threshold*100.0)
529 space_threshold = hw7Utils.get_repeated_pattern(
' ', 6-len(threshold))
531 banner +=
"## {} ##\n".format(hw7Utils.ansi_format_warning(
"! WARNING: The integration grids only have a low precision (worse than {}){}!".format(threshold, space_threshold)))
534 banner +=
"## ------------------------------------------------------------------------------- ##\n"
536 banner +=
"## Please ignore the error ##\n"
538 banner +=
"## No such file or directory: 'evgen.root' raised while stating file evgen.root ##\n"
540 banner +=
"##########################################################################################\n"
std::vector< std::string > split(const std::string &s, const std::string &t=":")
static Root::TMsgLogger logger("iLumiCalc")
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_mergegrids(run_name, integration_jobs)
get_infile_name(run_name="Herwig-Matchbox")
do_read_existing_infile(gen_config)
exit_banner(gridpack, cross_section, cross_section_error)
do_uncompress_gridpack(gridpack_name)
do_build(gen_config, integration_jobs)
get_setupfile_name(run_name="Herwig-Matchbox")
do_compress_gridpack(run_name, gridpack_name)
log(level='info', message='')
do_step(step, command, logfile_name=None)
do_integrate(run_name, integration_job)
do_build_integrate_mergegrids(gen_config, integration_jobs)
matchbox_run_gridpack(gen_config, integration_jobs, gridpack_name, cleanup_herwig_scratch, integrate)
matchbox_run(gen_config, integration_jobs, cleanup_herwig_scratch)
render_infile(gen_config)
write_infile(gen_config, print_infile=True)
_configure_run_algorithm(gen_config, runfile_name, cleanup_herwig_scratch=None, decode_runfile=False)
get_runfile_name(run_name="Herwig-Matchbox")
do_run_existing_runfile(gen_config)
do_run(gen_config, cleanup_herwig_scratch=True)
write_setupfile(run_name, commands, print_setupfile=True)