15 import os, shutil, subprocess, sys
18 from .
import Herwig7Utils
as hw7Utils
19 from .
import Herwig7JOChecker
as JOChecker
22 from AthenaCommon
import Logging
23 athMsgLog = Logging.logging.getLogger(
'Herwig7Control')
33 cmt_paths = os.environ.get(
"CMAKE_PREFIX_PATH")
34 cmt_config = os.environ.get(
"BINARY_TAG")
37 for path
in cmt_paths.split(
':'):
38 path = os.path.join(path,
"InstallArea", cmt_config,
"share")
40 filelist = os.listdir(path)
43 if "HerwigDefaults.rpo" in filelist: return(path)
46 path = os.path.join(os.environ[
'HERWIG7_PATH'],
'share/Herwig')
47 if os.path.isfile(os.path.join(path,
'HerwigDefaults.rpo')):
51 raise RuntimeError(hw7Utils.ansi_format_error(
'Could not find a valid share/Herwig folder'))
55 herwig7_path = os.environ[
'HERWIG7_PATH']
56 herwig7_bin_path = os.path.join(herwig7_path,
'bin')
59 herwig7_binary = os.path.join(herwig7_bin_path,
'Herwig')
71 do_run(gen_config, cleanup_herwig_scratch=
False)
78 def matchbox_run(gen_config, integration_jobs, cleanup_herwig_scratch):
84 do_run(gen_config, cleanup_herwig_scratch)
96 if not gridpack_name
or integrate:
114 DSIS_dir = gen_config.runArgs.jobConfig[0]+
"/"
116 athMsgLog.info(
"Finished unpacking the gridpack")
119 do_run(gen_config, cleanup_herwig_scratch)
123 def do_step(step, command, logfile_name=None):
125 athMsgLog.info(hw7Utils.ansi_format_info(
"Starting Herwig7 '{}' step with command '{}'".
format(step,
' '.
join(command))))
127 logfile =
open(logfile_name,
'w')
if logfile_name
else None
128 do = subprocess.Popen(command, stdout=logfile, stderr=logfile)
130 if not do.returncode == 0:
131 raise RuntimeError(hw7Utils.ansi_format_error(
"Some error occured during the '{}' step.".
format(step)))
134 athMsgLog.info(
"Content of %s log file '%s':", step, logfile_name)
136 with open(logfile_name,
'r')
as logfile:
138 athMsgLog.info(
' %s', line.rstrip(
'\n'))
143 athMsgLog.info(hw7Utils.ansi_format_info(
"Doing abort"))
174 do_step(
'read', [herwig7_binary,
'read', gen_config.infile_name,
'-I', share_path])
191 do_step(
'build', [herwig7_binary,
'build',
get_infile_name(gen_config.run_name),
'-I', share_path,
'-y '+
str(integration_jobs)])
201 integrate_log = run_name+
'.integrate'+
str(integration_job)+
'.log'
202 integrate_command = [herwig7_binary,
'integrate',runfile_name,
'--jobid='+
str(integration_job)]
205 do_step(
'integrate', integrate_command, integrate_log)
212 mergegrids_command = [herwig7_binary,
'mergegrids', runfile_name]
215 do_step(
'mergegrids', mergegrids_command)
218 xsec, err = hw7Utils.get_cross_section(run_name, integration_jobs)
227 do_build(gen_config, integration_jobs)
232 athMsgLog.info(hw7Utils.ansi_format_info(
'Starting integration with {} jobs'.
format(integration_jobs)))
234 integration_procs = []
235 for integration_job
in range(integration_jobs):
236 integrate_log = gen_config.run_name+
'.integrate'+
str(integration_job)+
'.log'
237 integrate_command = [herwig7_binary,
'integrate',runfile_name,
'--jobid='+
str(integration_job)]
239 integration_procs.append(hw7Utils.Process(integration_job, integrate_command, integrate_log))
241 integration_handler = hw7Utils.ProcessHandler(integration_procs, athMsgLog)
242 if not integration_handler.success():
243 raise RuntimeError(hw7Utils.ansi_format_error(
'Not all of the integration jobs finished successfully'))
245 athMsgLog.info(hw7Utils.ansi_format_ok(
'All integration jobs finished successfully'))
248 xsec, err =
do_mergegrids(gen_config.run_name, integration_jobs)
255 if not (gridpack_name.endswith(
'.tar.gz')
or gridpack_name.endswith(
'.tgz')): gridpack_name +=
'.tar.gz'
259 athMsgLog.debug(
"Scratch area, this is Herwig version '{}'".
format(version))
260 if "7.1" in version
or "7.0" in version:
261 do_step(
'compress', [
'tar',
'czf', gridpack_name, infile_name, runfile_name,
'Herwig-scratch'])
263 do_step(
'compress', [
'tar',
'czf', gridpack_name, infile_name, runfile_name,
'Herwig-cache'])
268 athMsgLog.info(
"unpacking gridpack '%s'", gridpack_name)
269 do_step(
'uncompress', [
'tar',
'xzf', gridpack_name])
273 def do_run(gen_config, cleanup_herwig_scratch=True):
279 JOChecker.check_file()
282 if gen_config.runArgs.randomSeed
is None:
283 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
False
285 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
True
286 gen_config.genSeq.Herwig7.RandomSeedFromGeneratetf = gen_config.runArgs.randomSeed
289 gen_config.genSeq.Herwig7.PDFNameME = gen_config.me_pdf_name
292 gen_config.genSeq.Herwig7.PDFNameMPI = gen_config.mpi_pdf_name
295 gen_config.genSeq.Herwig7.CleanupHerwigScratch = cleanup_herwig_scratch
299 athMsgLog.info(hw7Utils.ansi_format_info(
"Returning to the job options and starting the event generation afterwards"))
306 gen_config.genSeq.Herwig7.RunFile = gen_config.runfile_name
309 if gen_config.runArgs.randomSeed
is None:
310 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
False
312 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
True
313 gen_config.genSeq.Herwig7.RandomSeedFromGeneratetf = gen_config.runArgs.randomSeed
317 athMsgLog.info(hw7Utils.ansi_format_info(
"Returning to the job options and starting the event generation afterwards"))
326 return(
' '.
join(versions[0].
split()[1:]))
331 return(
' '.
join(versions[1].
split()[1:]))
337 herwig_version_space =
' '.
join([
'' for i
in range(14-len(herwig_version_number))])
338 thepeg_version_space =
' '.
join([
'' for i
in range(14-len(thepeg_version_number))])
341 banner +=
"#####################################\n"
342 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_ok(
"---------------------------"))
343 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_ok(
"Starting HERWIG 7 in ATHENA"))
344 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_ok(
"---------------------------"))
346 banner +=
"## with software versions: ##\n"
347 banner +=
"## - Herwig7: {}{} ##\n".
format(herwig_version_number, herwig_version_space)
348 banner +=
"## - ThePEG: {}{} ##\n".
format(thepeg_version_number, thepeg_version_space)
360 banner +=
"#####################################\n"
366 return(six.ensure_str(subprocess.check_output([herwig7_binary,
'--version'])).splitlines())
371 return(
'{}.in'.
format(run_name))
376 return(
'{}.setupfile.in'.
format(run_name))
381 return(
'{}.run'.
format(run_name)
if not run_name.endswith(
'.run')
else run_name)
387 gen_config.default_commands.lock()
388 gen_config.commands.lock()
391 if print_infile: athMsgLog.info(
"")
392 athMsgLog.info(hw7Utils.ansi_format_info(
"Writing infile '{}'".
format(infile_name)))
394 gen_config.global_pre_commands().splitlines() \
395 + gen_config.local_pre_commands().splitlines() \
397 "## ================",
398 "## Default Commands",
399 "## ================"] \
400 +
str(gen_config.default_commands.commands).splitlines() \
402 "## ========================",
403 "## Commands from jobOptions",
404 "## ========================"] \
405 +
str(gen_config.commands.commands).splitlines() \
406 + gen_config.local_post_commands().splitlines()
408 with open(infile_name,
'w')
as infile:
409 for command
in commands:
410 infile.write(command+
'\n')
412 raise RuntimeError(
'Could not write Herwig/Matchbox infile')
416 for command
in commands:
417 athMsgLog.info(
' %s', command)
425 if len(commands) > 0:
426 if print_setupfile: athMsgLog.info(
"")
427 athMsgLog.info(
"Writing setupfile '%s'", setupfile_name)
429 with open(setupfile_name,
'w')
as setupfile:
430 for command
in commands: setupfile.write(command+
'\n')
432 raise RuntimeError(
'Could not write Herwig/Matchbox setupfile')
436 for command
in commands: athMsgLog.info(
' %s', command)
440 athMsgLog.info(
"No setupfile commands given.")
447 shutil.copy(os.path.join(
get_share_path(),
'HerwigDefaults.rpo'),
'HerwigDefaults.rpo')
450 def log(level='info', message=''):
452 if level
in [
'info',
'warn',
'error']:
453 logger = getattr(athMsgLog, level)
454 for line
in message.splitlines():
logger(line)
456 raise ValueError(
"Unknown logging level'{}' specified. Possible values are 'info', 'warn' or 'error'".
format(level))
461 size = hw7Utils.humanize_bytes(hw7Utils.get_size(gridpack))
462 space_size = hw7Utils.get_repeated_pattern(
' ', 31-len(size))
464 xsec =
'{:f}'.
format(cross_section)
465 err =
'{:f}'.
format(cross_section_error)
466 rel_err =
'{:.2f}'.
format(cross_section_error / cross_section * 100.0)
467 space_xsec = hw7Utils.get_repeated_pattern(
' ', 37-len(xsec)-len(err)-len(rel_err))
470 space =
' '.
join([
'' for i
in range(70+4+1-len(gridpack))])
471 banner +=
"##########################################################################################\n"
472 banner +=
"## ------------------------------------------------------------------------------- ##\n"
473 banner +=
"## {} (size: {}){} ##\n".
format(hw7Utils.ansi_format_ok(
"HERWIG 7 successfully created the gridpack"), size, space_size)
475 banner +=
"## {}{} ##\n".
format(hw7Utils.ansi_format_info(gridpack), space)
477 banner +=
"## cross section from integration: {} +/- {} ({}%) nb {} ##\n".
format(xsec, err, rel_err, space_xsec)
479 if cross_section_error / cross_section > hw7Utils.integration_grids_precision_threshold:
480 threshold =
'{}%'.
format(hw7Utils.integration_grids_precision_threshold*100.0)
481 space_threshold = hw7Utils.get_repeated_pattern(
' ', 6-len(threshold))
483 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_warning(
"! WARNING: The integration grids only have a low precision (worse than {}){}!".
format(threshold, space_threshold)))
486 banner +=
"## ------------------------------------------------------------------------------- ##\n"
488 banner +=
"## Please ignore the error ##\n"
490 banner +=
"## No such file or directory: 'evgen.root' raised while stating file evgen.root ##\n"
492 banner +=
"##########################################################################################\n"