15 import os, shutil, subprocess, sys
17 from .
import Herwig7Utils
as hw7Utils
18 from .
import Herwig7JOChecker
as JOChecker
19 from .
import Herwig7ConfigDecoder
as ConfigDecoder
21 from AthenaCommon
import Logging
22 athMsgLog = 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'))
54 herwig7_path = os.environ[
'HERWIG7_PATH']
55 herwig7_bin_path = os.path.join(herwig7_path,
'bin')
58 herwig7_binary = os.path.join(herwig7_bin_path,
'Herwig')
70 do_run(gen_config, cleanup_herwig_scratch=
False)
77 def 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)
122 def do_step(step, command, logfile_name=None):
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"))
173 do_step(
'read', [herwig7_binary,
'read', gen_config.infile_name,
'-I', share_path])
190 do_step(
'build', [herwig7_binary,
'build',
get_infile_name(gen_config.run_name),
'-I', share_path,
'-y '+
str(integration_jobs)])
199 integrate_log = run_name+
'.integrate'+
str(integration_job)+
'.log'
200 integrate_command = [herwig7_binary,
'integrate',runfile_name,
'--jobid='+
str(integration_job)]
202 do_step(
'integrate', integrate_command, integrate_log)
209 mergegrids_command = [herwig7_binary,
'mergegrids', runfile_name]
211 do_step(
'mergegrids', mergegrids_command)
214 xsec, err = hw7Utils.get_cross_section(run_name, integration_jobs)
223 do_build(gen_config, integration_jobs)
227 athMsgLog.info(hw7Utils.ansi_format_info(
'Starting integration with {} jobs'.
format(integration_jobs)))
229 integration_procs = []
230 for integration_job
in range(integration_jobs):
231 integrate_log = gen_config.run_name+
'.integrate'+
str(integration_job)+
'.log'
232 integrate_command = [herwig7_binary,
'integrate',runfile_name,
'--jobid='+
str(integration_job)]
233 integration_procs.append(hw7Utils.Process(integration_job, integrate_command, integrate_log))
235 integration_handler = hw7Utils.ProcessHandler(integration_procs, athMsgLog)
236 if not integration_handler.success():
237 raise RuntimeError(hw7Utils.ansi_format_error(
'Not all of the integration jobs finished successfully'))
239 athMsgLog.info(hw7Utils.ansi_format_ok(
'All integration jobs finished successfully'))
242 xsec, err =
do_mergegrids(gen_config.run_name, integration_jobs)
249 if not (gridpack_name.endswith(
'.tar.gz')
or gridpack_name.endswith(
'.tgz')): gridpack_name +=
'.tar.gz'
253 athMsgLog.debug(
"Scratch area, this is Herwig version '{}'".
format(version))
254 if "7.1" in version
or "7.0" in version:
255 do_step(
'compress', [
'tar',
'czf', gridpack_name, infile_name, runfile_name,
'Herwig-scratch'])
257 do_step(
'compress', [
'tar',
'czf', gridpack_name, infile_name, runfile_name,
'Herwig-cache'])
262 athMsgLog.info(
"unpacking gridpack '%s'", gridpack_name)
263 do_step(
'uncompress', [
'tar',
'xzf', gridpack_name])
267 def do_run(gen_config, cleanup_herwig_scratch=True):
273 JOChecker.check_file()
276 ConfigDecoder.DecodeRunCard(input_file = gen_config.genSeq.Herwig7.RunFile)
279 if gen_config.runArgs.randomSeed
is None:
280 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
False
282 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
True
283 gen_config.genSeq.Herwig7.RandomSeedFromGeneratetf = gen_config.runArgs.randomSeed
286 gen_config.genSeq.Herwig7.PDFNameME = gen_config.me_pdf_name
289 gen_config.genSeq.Herwig7.PDFNameMPI = gen_config.mpi_pdf_name
292 gen_config.genSeq.Herwig7.CleanupHerwigScratch = cleanup_herwig_scratch
296 athMsgLog.info(hw7Utils.ansi_format_info(
"Returning to the job options and starting the event generation afterwards"))
303 gen_config.genSeq.Herwig7.RunFile = gen_config.runfile_name
306 if gen_config.runArgs.randomSeed
is None:
307 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
False
309 gen_config.genSeq.Herwig7.UseRandomSeedFromGeneratetf =
True
310 gen_config.genSeq.Herwig7.RandomSeedFromGeneratetf = gen_config.runArgs.randomSeed
314 athMsgLog.info(hw7Utils.ansi_format_info(
"Returning to the job options and starting the event generation afterwards"))
323 return(
' '.
join(versions[0].
split()[1:]))
328 return(
' '.
join(versions[1].
split()[1:]))
334 herwig_version_space =
' '.
join([
'' for i
in range(14-len(herwig_version_number))])
335 thepeg_version_space =
' '.
join([
'' for i
in range(14-len(thepeg_version_number))])
338 banner +=
"#####################################\n"
339 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_ok(
"---------------------------"))
340 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_ok(
"Starting HERWIG 7 in ATHENA"))
341 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_ok(
"---------------------------"))
343 banner +=
"## with software versions: ##\n"
344 banner +=
"## - Herwig7: {}{} ##\n".
format(herwig_version_number, herwig_version_space)
345 banner +=
"## - ThePEG: {}{} ##\n".
format(thepeg_version_number, thepeg_version_space)
347 banner +=
"#####################################\n"
353 return(subprocess.check_output([herwig7_binary,
'--version'], text=
True).splitlines())
358 return(
'{}.in'.
format(run_name))
363 return(
'{}.setupfile.in'.
format(run_name))
368 return(
'{}.run'.
format(run_name)
if not run_name.endswith(
'.run')
else run_name)
374 gen_config.default_commands.lock()
375 gen_config.commands.lock()
378 if print_infile: athMsgLog.info(
"")
379 athMsgLog.info(hw7Utils.ansi_format_info(
"Writing infile '{}'".
format(infile_name)))
381 gen_config.global_pre_commands().splitlines() \
382 + gen_config.local_pre_commands().splitlines() \
384 "## ================",
385 "## Default Commands",
386 "## ================"] \
387 +
str(gen_config.default_commands.commands).splitlines() \
389 "## ========================",
390 "## Commands from jobOptions",
391 "## ========================"] \
392 +
str(gen_config.commands.commands).splitlines() \
393 + gen_config.local_post_commands().splitlines()
395 with open(infile_name,
'w')
as infile:
396 for command
in commands:
397 infile.write(command+
'\n')
399 raise RuntimeError(
'Could not write Herwig/Matchbox infile')
403 for command
in commands:
404 athMsgLog.info(
' %s', command)
412 if len(commands) > 0:
413 if print_setupfile: athMsgLog.info(
"")
414 athMsgLog.info(
"Writing setupfile '%s'", setupfile_name)
416 with open(setupfile_name,
'w')
as setupfile:
417 for command
in commands: setupfile.write(command+
'\n')
419 raise RuntimeError(
'Could not write Herwig/Matchbox setupfile')
423 for command
in commands: athMsgLog.info(
' %s', command)
427 athMsgLog.info(
"No setupfile commands given.")
434 shutil.copy(os.path.join(
get_share_path(),
'HerwigDefaults.rpo'),
'HerwigDefaults.rpo')
437 def log(level='info', message=''):
439 if level
in [
'info',
'warn',
'error']:
440 logger = getattr(athMsgLog, level)
441 for line
in message.splitlines():
logger(line)
443 raise ValueError(
"Unknown logging level'{}' specified. Possible values are 'info', 'warn' or 'error'".
format(level))
448 size = hw7Utils.humanize_bytes(hw7Utils.get_size(gridpack))
449 space_size = hw7Utils.get_repeated_pattern(
' ', 31-len(size))
451 xsec =
'{:f}'.
format(cross_section)
452 err =
'{:f}'.
format(cross_section_error)
453 rel_err =
'{:.2f}'.
format(cross_section_error / cross_section * 100.0)
454 space_xsec = hw7Utils.get_repeated_pattern(
' ', 37-len(xsec)-len(err)-len(rel_err))
457 space =
' '.
join([
'' for i
in range(70+4+1-len(gridpack))])
458 banner +=
"##########################################################################################\n"
459 banner +=
"## ------------------------------------------------------------------------------- ##\n"
460 banner +=
"## {} (size: {}){} ##\n".
format(hw7Utils.ansi_format_ok(
"HERWIG 7 successfully created the gridpack"), size, space_size)
462 banner +=
"## {}{} ##\n".
format(hw7Utils.ansi_format_info(gridpack), space)
464 banner +=
"## cross section from integration: {} +/- {} ({}%) nb {} ##\n".
format(xsec, err, rel_err, space_xsec)
466 if cross_section_error / cross_section > hw7Utils.integration_grids_precision_threshold:
467 threshold =
'{}%'.
format(hw7Utils.integration_grids_precision_threshold*100.0)
468 space_threshold = hw7Utils.get_repeated_pattern(
' ', 6-len(threshold))
470 banner +=
"## {} ##\n".
format(hw7Utils.ansi_format_warning(
"! WARNING: The integration grids only have a low precision (worse than {}){}!".
format(threshold, space_threshold)))
473 banner +=
"## ------------------------------------------------------------------------------- ##\n"
475 banner +=
"## Please ignore the error ##\n"
477 banner +=
"## No such file or directory: 'evgen.root' raised while stating file evgen.root ##\n"
479 banner +=
"##########################################################################################\n"