9 import os,time,subprocess,glob,re,sys
10 from AthenaCommon
import Logging
11 mglog = Logging.logging.getLogger(
'MadGraphUtils')
16 MADGRAPH_GRIDPACK_LOCATION=
'madevent'
18 MADGRAPH_RUN_NAME=
'run_01'
20 MADGRAPH_CATCH_ERRORS=
True
22 MADGRAPH_PDFSETTING=
None
23 MADGRAPH_COMMAND_STACK = []
25 patched_shutil_loc=
'/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest/shutil_patch'
26 if 'PYTHONPATH' in os.environ
and patched_shutil_loc
not in os.environ[
'PYTHONPATH']:
29 os.environ[
'PYTHONPATH'] = patched_shutil_loc+
':'+os.environ[
'PYTHONPATH']
30 MADGRAPH_COMMAND_STACK += [
'export PYTHONPATH='+patched_shutil_loc+
':${PYTHONPATH}']
32 if 'shutil' in sys.modules:
33 sys.modules.pop(
'shutil')
35 sys.path.insert(0,patched_shutil_loc)
38 from MadGraphControl.MadGraphUtilsHelpers
import checkSettingExists,checkSetting,checkSettingIsTrue,getDictFromCard,get_runArgs_info,get_physics_short,is_version_or_newer
39 from MadGraphControl.MadGraphParamHelpers
import do_PMG_updates,check_PMG_updates
42 global MADGRAPH_COMMAND_STACK
43 MADGRAPH_COMMAND_STACK += [
' '.
join(command)]
44 return subprocess.Popen(command,**kwargs)
49 global MADGRAPH_COMMAND_STACK
50 if 'PYTHONPATH' in os.environ:
51 if not any( [(
'Generators/madgraph/models' in x
and 'shutil_patch' not in x)
for x
in os.environ[
'PYTHONPATH'].
split(
':') ]):
52 os.environ[
'PYTHONPATH'] +=
':/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest'
53 MADGRAPH_COMMAND_STACK += [
'export PYTHONPATH=${PYTHONPATH}:/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest']
55 if 'GFORTRAN_TMPDIR' in os.environ:
57 if 'TMPDIR' in os.environ:
58 os.environ[
'GFORTRAN_TMPDIR']=os.environ[
'TMPDIR']
59 MADGRAPH_COMMAND_STACK += [
'export GFORTRAN_TMPDIR=${TMPDIR}']
61 if 'TMP' in os.environ:
62 os.environ[
'GFORTRAN_TMPDIR']=os.environ[
'TMP']
63 MADGRAPH_COMMAND_STACK += [
'export GFORTRAN_TMPDIR=${TMP}']
69 from __main__
import opts
71 mglog.info(
'Athena running on config only mode: not executing MadGraph')
79 global MADGRAPH_COMMAND_STACK
80 if not os.access(
'Cards_bkup',os.R_OK):
81 shutil.copytree(process_dir+
'/Cards',
'Cards_bkup')
82 shutil.copyfile(process_dir+
'/Source/make_opts',
'Cards_bkup/make_opts_bkup')
83 MADGRAPH_COMMAND_STACK += [
'# In case this fails, Cards_bkup should be in your original run directory']
84 MADGRAPH_COMMAND_STACK += [
'# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
85 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup/*dat ${MGaMC_PROCESS_DIR}/Cards/']
86 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
88 mglog.warning(
'Found Cards_bkup directory existing. Suggests you are either running generation twice (a little funny) or are not using a clean directory.')
90 while os.access(
'Cards_bkup_'+
str(bkup_v),os.R_OK)
and bkup_v<100:
93 shutil.copytree(process_dir+
'/Cards',
'Cards_bkup_'+
str(bkup_v))
94 shutil.copyfile(process_dir+
'/Source/make_opts',
'Cards_bkup_'+
str(bkup_v)+
'/make_opts_bkup')
95 MADGRAPH_COMMAND_STACK += [
'# In case this fails, Cards_bkup should be in your original run directory']
96 MADGRAPH_COMMAND_STACK += [
'# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
97 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup_'+
str(bkup_v)+
'/*dat ${MGaMC_PROCESS_DIR}/Cards/']
98 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup_'+
str(bkup_v)+
'/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
100 mglog.warning(
'Way too many Cards_bkup* directories found. Giving up -- standalone script may not work.')
104 global MADGRAPH_CATCH_ERRORS
105 if not MADGRAPH_CATCH_ERRORS:
107 unmasked_error =
False
112 if type(errors)==bytes:
113 errors = errors.decode(
'utf-8')
115 mglog.info(
'Some errors detected by MadGraphControl - checking for serious errors')
116 for err
in errors.split(
'\n'):
117 if len(err.strip())==0:
120 if 'Inappropriate ioctl for device' in err:
123 if 'stty: standard input: Invalid argument' in err:
127 if 'PDF already installed' in err:
130 if 'Read-only file system' in err:
137 if 'impossible to set default multiparticles' in err:
141 if 'More information is found in' in err:
142 my_debug_file = err.split(
"'")[1]
143 if err.startswith(
'tar'):
146 if 'python2 support will be removed' in err:
150 if 'required by /lib64/libfontconfig.so' in err
or\
151 'required by /lib64/libgs.so' in err:
154 if 'Error: Symbol' in err
and 'has no IMPLICIT type' in err:
155 bad_variables += [ err.split(
'Symbol ')[1].
split(
' at ')[0] ]
161 unmasked_error =
True
163 if my_debug_file
is None:
164 debug_files = glob.glob(
'*debug.log')+glob.glob(
'*/*debug.log')
165 for debug_file
in debug_files:
167 has_subproc = os.access(os.path.join(os.path.dirname(debug_file),
'SubProcesses'),os.R_OK)
169 my_debug_file = debug_file
172 if my_debug_file
is not None:
173 if not unmasked_error:
174 mglog.warning(
'Found a debug file at '+my_debug_file+
' but no apparent error. Will terminate.')
175 mglog.error(
'MadGraph5_aMC@NLO appears to have crashed. Debug file output follows.')
176 with open(my_debug_file,
'r')
as error_output:
177 for l
in error_output:
178 mglog.error(l.replace(
'\n',
''))
179 mglog.error(
'End of debug file output')
182 mglog.warning(
'Appeared to detect variables in your run card that MadGraph did not understand:')
183 mglog.warning(
' Check your run card / JO settings for %s',bad_variables)
187 mglog.error(f
'Detected a bad return code: {return_code}')
188 unmasked_error =
True
191 if unmasked_error
or my_debug_file
is not None:
193 raise RuntimeError(
'Error detected in MadGraphControl process')
199 mglog.info(
'Will write a stand-alone debugging script.')
200 mglog.info(
'This is an attempt to provide you commands that you can use')
201 mglog.info(
'to reproduce the error locally. If you make additional')
202 mglog.info(
'modifications by hand (not using MadGraphControl) in your JO,')
203 mglog.info(
'make sure that you check and modify the script as needed.\n\n')
204 global MADGRAPH_COMMAND_STACK
205 mglog.info(
'# Script start; trim off columns left of the "#"')
207 with open(
'standalone_script.sh',
'w')
as standalone_script:
208 for command
in MADGRAPH_COMMAND_STACK:
209 for line
in command.split(
'\n'):
211 standalone_script.write(line+
'\n')
212 mglog.info(
'# Script end')
213 mglog.info(
'Script also written to %s/standalone_script.sh',os.getcwd())
216 def new_process(process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False):
217 """ Generate a new process in madgraph.
218 Pass a process string.
219 Optionally request JPEGs to be kept and request for PMG settings to be used in the param card
220 Return the name of the process directory.
225 os.makedirs(
'dummy_proc/Cards')
232 return MADGRAPH_GRIDPACK_LOCATION
235 card_loc=
'proc_card_mg5.dat'
236 mglog.info(
'Writing process card to '+card_loc)
237 a_card =
open( card_loc ,
'w' )
238 for l
in process.split(
'\n'):
239 if 'output' not in l:
241 elif '-nojpeg' in l
or keepJpegs:
244 a_card.write(l.split(
'#')[0]+
' -nojpeg #'+l.split(
'#')[1]+
'\n')
246 a_card.write(l+
' -nojpeg\n')
249 madpath=os.environ[
'MADPATH']
255 for l
in process.split(
'\n'):
257 if 'output' not in l.split(
'#')[0].
split():
260 tmplist = l.split(
'#')[0].
split(
' -')[0]
262 if len(tmplist.split())==2:
263 process_dir = tmplist.split()[1]
265 elif len(tmplist.split())==3:
266 process_dir = tmplist.split()[2]
269 mglog.info(
'Saw that you asked for a special output directory: '+
str(process_dir))
272 mglog.info(
'Started process generation at '+
str(time.asctime()))
274 plugin_cmd =
'--mode='+plugin
if plugin
is not None else ''
277 global MADGRAPH_COMMAND_STACK
278 MADGRAPH_COMMAND_STACK += [
'# All jobs should start in a clean directory']
279 MADGRAPH_COMMAND_STACK += [
'mkdir standalone_test; cd standalone_test']
280 MADGRAPH_COMMAND_STACK += [
' '.
join([python,madpath+
'/bin/mg5_aMC '+plugin_cmd+
' << EOF\n'+process+
'\nEOF\n'])]
281 global MADGRAPH_CATCH_ERRORS
282 generate = subprocess.Popen([python,madpath+
'/bin/mg5_aMC',plugin_cmd,card_loc],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
283 (out,err) = generate.communicate()
286 mglog.info(
'Finished process generation at '+
str(time.asctime()))
289 if process_dir ==
'':
290 for adir
in sorted(glob.glob( os.getcwd()+
'/*PROC*' ),reverse=
True):
291 if os.access(
'%s/SubProcesses/subproc.mg'%adir,os.R_OK):
295 mglog.warning(
'Additional possible process directory, '+adir+
' found. Had '+process_dir)
296 mglog.warning(
'Likely this is because you did not run from a clean directory, and this may cause errors later.')
298 if not os.access(
'%s/SubProcesses/subproc.mg'%process_dir,os.R_OK):
299 raise RuntimeError(
'No diagrams for this process in user-define dir='+
str(process_dir))
301 raise RuntimeError(
'No diagrams for this process from list: '+
str(
sorted(glob.glob(os.getcwd()+
'/*PROC*'),reverse=
True)))
304 needed_options = [
'ninja',
'collier',
'fastjet',
'lhapdf',
'syscalc_path']
305 in_config =
open(os.environ[
'MADPATH']+
'/input/mg5_configuration.txt',
'r')
307 for l
in in_config.readlines():
308 for o
in needed_options:
309 if o+
' =' in l.split(
'#')[0]
and 'MCGenerators' in l.split(
'#')[0]:
310 old_path = l.split(
'#')[0].
split(
'=')[1].strip().
split(
'MCGenerators')[1]
311 old_path = old_path[ old_path.find(
'/') : ]
312 if o ==
'lhapdf' and 'LHAPATH' in os.environ:
314 version = os.environ[
'LHAPATH'].
split(
'lhapdf/')[1].
split(
'/')[0]
315 old_version = old_path.split(
'lhapdf/')[1].
split(
'/')[0]
316 old_path = old_path.replace(old_version,version)
319 old_path.replace(
'gosam_contrib',
'gosam-contrib')
320 option_paths[o] = os.environ[
'MADPATH'].
split(
'madgraph5amc')[0]+old_path
322 if o+
' =' in l
and o+
' =' not in l.split(
'#')[0]:
323 mglog.info(
'Option '+o+
' appears commented out in the config file')
326 for o
in needed_options:
327 if o
not in option_paths:
328 mglog.info(
'Path for option '+o+
' not found in original config')
330 mglog.info(
'Modifying config paths to avoid use of afs:')
331 mglog.info(option_paths)
343 mglog.info(
'Setting default sde_strategy to old default (1)')
344 my_settings = {
'sde_strategy':1}
345 modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=
True)
348 MADGRAPH_COMMAND_STACK += [
'export MGaMC_PROCESS_DIR='+os.path.basename(process_dir)]
354 """ Copy the default runcard from one of several locations
355 to a local file with name run_card.tmp.dat"""
356 output_name =
'run_card.tmp.dat'
358 mglog.info(
'Athena running on config only mode: grabbing run card the old way, as there will be no proc dir')
359 mglog.info(
'Fetching default LO run_card.dat')
360 if os.access(os.environ[
'MADPATH']+
'/Template/LO/Cards/run_card.dat',os.R_OK):
361 shutil.copy(os.environ[
'MADPATH']+
'/Template/LO/Cards/run_card.dat',output_name)
362 return 'run_card.dat'
363 elif os.access(os.environ[
'MADPATH']+
'/Template/Cards/run_card.dat',os.R_OK):
364 shutil.copy(os.environ[
'MADPATH']+
'/Template/Cards/run_card.dat',output_name)
367 raise RuntimeError(
'Cannot find default LO run_card.dat!')
370 run_card=process_dir+
'/Cards/run_card.dat'
371 if os.access(run_card,os.R_OK):
372 mglog.info(
'Copying default run_card.dat from '+
str(run_card))
373 shutil.copy(run_card,output_name)
376 run_card=process_dir+
'/Cards/run_card_default.dat'
377 mglog.info(
'Fetching default run_card.dat from '+
str(run_card))
378 if os.access(run_card,os.R_OK):
379 shutil.copy(run_card,output_name)
382 raise RuntimeError(
'Cannot find default run_card.dat or run_card_default.dat! I was looking here: %s'%run_card)
385 def generate(process_dir='PROC_mssm_0', grid_pack=False, gridpack_compile=False, extlhapath=None, required_accuracy=0.01, runArgs=None, bias_module=None, requirePMGSettings=False):
395 if 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
396 njobs =
int(os.environ[
'ATHENA_CORE_NUMBER'])
397 mglog.info(
'Lucky you - you are running on a full node queue. Will re-configure for '+
str(njobs)+
' jobs.')
401 if cluster_type
is not None:
405 mglog.info(
'Running event generation from gridpack (using smarter mode from generate() function)')
406 generate_from_gridpack(runArgs=runArgs,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings)
409 mglog.info(
'Did not identify an input gridpack.')
411 mglog.info(
'The grid_pack flag is set, so I am expecting to create a gridpack in this job')
425 from distutils.spawn
import find_executable
426 if find_executable(
'f2py')
is not None:
427 mglog.info(
'Found f2py, will use it for reweighting')
429 raise RuntimeError(
'Could not find f2py, needed for reweighting')
434 mglog.info(
'Started generating gridpack at '+
str(time.asctime()))
435 mglog.warning(
' >>>>>> THIS KIND OF JOB SHOULD ONLY BE RUN LOCALLY - NOT IN GRID JOBS <<<<<<')
438 my_settings = {
'nevents':
'1000'}
440 my_settings[
'req_acc']=
str(required_accuracy)
442 my_settings = {
'gridpack':
'true'}
443 modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=
True)
447 mglog.info(
'Started generating at '+
str(time.asctime()))
449 mglog.info(
'Run '+MADGRAPH_RUN_NAME+
' will be performed in mode '+
str(mode)+
' with '+
str(njobs)+
' jobs in parallel.')
452 if not os.access(process_dir,os.R_OK):
453 raise RuntimeError(
'No process directory found at '+process_dir)
454 if not os.access(process_dir+
'/bin/generate_events',os.R_OK):
455 raise RuntimeError(
'No generate_events module found in '+process_dir)
457 mglog.info(
'For your information, the libraries available are (should include LHAPDF):')
458 ls_dir(process_dir+
'/lib')
461 if bias_module
is not None:
464 mglog.info(
'Now I will hack the make files a bit. Apologies, but there seems to be no good way around this.')
465 shutil.copyfile(process_dir+
'/Source/make_opts',process_dir+
'/Source/make_opts_old')
466 old_opts =
open(process_dir+
'/Source/make_opts_old',
'r')
467 new_opts =
open(process_dir+
'/Source/make_opts',
'w')
468 for aline
in old_opts:
470 mglog.info(
'Configuring the fancy gfortran compiler instead of g77 / f77')
471 new_opts.write(
' FC=gfortran\n')
473 new_opts.write(aline)
476 mglog.info(
'Make file hacking complete.')
480 os.chdir(process_dir)
482 global MADGRAPH_COMMAND_STACK
483 MADGRAPH_COMMAND_STACK += [
'cd ${MGaMC_PROCESS_DIR}' ]
494 if requirePMGSettings
and code!=0:
495 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
499 command = [python,
'bin/generate_events']
501 command += [
'--name='+MADGRAPH_RUN_NAME]
502 mglog.info(
'Removing Cards/shower_card.dat to ensure we get parton level events only')
503 os.unlink(
'Cards/shower_card.dat')
505 command += [MADGRAPH_RUN_NAME]
507 setNCores(process_dir=os.getcwd(), Ncores=njobs)
510 mglog.info(
'Setting up cluster running')
512 if cluster_type==
'pbs':
513 mglog.info(
'Modifying bin/internal/cluster.py for PBS cluster running')
514 os.system(
"sed -i \"s:text += prog:text += './'+prog:g\" bin/internal/cluster.py")
516 mglog.info(
'Setting up multi-core running on '+os.environ[
'ATHENA_CORE_NUMBER']+
' cores')
518 mglog.info(
'Setting up serial generation.')
521 global MADGRAPH_CATCH_ERRORS
522 generate =
stack_subprocess(command,stdin=subprocess.PIPE, stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
523 (out,err) = generate.communicate()
528 MADGRAPH_COMMAND_STACK += [
'cd -' ]
532 energy =
'%1.1f'%(beamEnergy*2./1000.)
533 energy = energy.replace(
'.0',
'').
replace(
'.',
'p')
535 mglog.info(
'Tidying up gridpack '+gridpack_name)
539 MADGRAPH_COMMAND_STACK += [
'cp '+glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0]+
' '+gridpack_name]
540 shutil.copy(glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0],gridpack_name)
543 MADGRAPH_COMMAND_STACK += [
'mkdir tmp%i/'%os.getpid(),
'cd tmp%i/'%os.getpid()]
544 os.mkdir(
'tmp%i/'%os.getpid())
545 os.chdir(
'tmp%i/'%os.getpid())
546 mglog.info(
'untar gridpack')
549 mglog.info(
'compile and clean up')
550 MADGRAPH_COMMAND_STACK += [
'cd madevent']
551 os.chdir(
'madevent/')
552 compilep =
stack_subprocess([
'./bin/compile'],stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
553 (out,err) = compilep.communicate()
555 clean =
stack_subprocess([
'./bin/clean4grid'],stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
556 (out,err) = clean.communicate()
559 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm ../'+gridpack_name]
561 mglog.info(
'remove old tarball')
562 os.unlink(
'../'+gridpack_name)
563 mglog.info(
'Package up new tarball')
564 tar =
stack_subprocess([
'tar',
'cvzf',
'../'+gridpack_name,
'--exclude=SubProcesses/P*/G*/*_results.dat',
'--exclude=SubProcesses/P*/G*/*.log',
'--exclude=SubProcesses/P*/G*/*.txt',
'.'])
566 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm -r tmp%i/'%os.getpid()]
568 mglog.info(
'Remove temporary directory')
569 shutil.rmtree(
'tmp%i/'%os.getpid())
570 mglog.info(
'Tidying up complete!')
575 mglog.info(
'Package up process_dir')
576 MADGRAPH_COMMAND_STACK += [
'mv '+process_dir+
' '+MADGRAPH_GRIDPACK_LOCATION]
577 os.rename(process_dir,MADGRAPH_GRIDPACK_LOCATION)
578 tar =
stack_subprocess([
'tar',
'czf',gridpack_name,MADGRAPH_GRIDPACK_LOCATION,
'--exclude=Events/*/*events*gz',
'--exclude=SubProcesses/P*/G*/log*txt',
'--exclude=SubProcesses/P*/G*/events.lhe*',
'--exclude=*/*.o',
'--exclude=*/*/*.o',
'--exclude=*/*/*/*.o',
'--exclude=*/*/*/*/*.o'])
580 MADGRAPH_COMMAND_STACK += [
'mv '+MADGRAPH_GRIDPACK_LOCATION+
' '+process_dir]
581 os.rename(MADGRAPH_GRIDPACK_LOCATION,process_dir)
583 mglog.info(
'Gridpack sucessfully created, exiting the transform')
584 if hasattr(runArgs,
'outputTXTFile'):
585 mglog.info(
'Touching output TXT (LHE) file for the transform')
586 open(runArgs.outputTXTFile,
'w').close()
587 from AthenaCommon.AppMgr
import theApp
591 mglog.info(
'Finished at '+
str(time.asctime()))
603 isNLO=
is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION)
608 gridpack_run_name =
'GridRun_'+
str(random_seed)
611 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',os.R_OK):
612 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat')
622 if requirePMGSettings
and code!=0:
623 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
626 settings={
'iseed':
str(random_seed)}
628 settings[
'python_seed']=
str(random_seed)
629 modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings=settings,skipBaseFragment=
True)
631 mglog.info(
'Generating events from gridpack')
634 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION):
635 raise RuntimeError(
'Gridpack directory not found at '+MADGRAPH_GRIDPACK_LOCATION)
637 nevents =
getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/run_card.dat')[
'nevents']
638 mglog.info(
'>>>> FOUND GRIDPACK <<<< <- This will be used for generation')
639 mglog.info(
'Generation of '+
str(
int(nevents))+
' events will be performed using the supplied gridpack with random seed '+
str(random_seed))
640 mglog.info(
'Started generating events at '+
str(time.asctime()))
643 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py',os.R_OK):
644 os.remove(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py')
649 setNCores(process_dir=MADGRAPH_GRIDPACK_LOCATION)
650 global MADGRAPH_CATCH_ERRORS
654 ls_dir(MADGRAPH_GRIDPACK_LOCATION)
664 run_card_dict=
getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/run_card.dat')
665 systematics_settings=
None
666 if checkSetting(
'systematics_program',
'systematics',run_card_dict):
668 raise RuntimeError(
'Trying to run NLO systematics but reweight info not stored')
670 systematics_settings=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(run_card_dict[
'systematics_arguments'])
672 systematics_settings={}
673 mglog.info(
'Turning off systematics for now, running standalone later')
674 modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={
'systematics_program':
'none'},skipBaseFragment=
True)
676 global MADGRAPH_COMMAND_STACK
679 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun',os.R_OK):
680 mglog.error(
'/bin/gridrun not found at '+MADGRAPH_GRIDPACK_LOCATION)
681 raise RuntimeError(
'Could not find gridrun executable')
683 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun, starting generation.')
686 mglog.info(
"Now generating {} events with random seed {} and granularity {}".
format(
int(nevents),
int(random_seed),granularity))
688 new_ld_path=
":".
join([os.environ[
'LD_LIBRARY_PATH'],os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/madevent/lib',os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/HELAS/lib'])
689 os.environ[
'LD_LIBRARY_PATH']=new_ld_path
690 MADGRAPH_COMMAND_STACK+=[
"export LD_LIBRARY_PATH="+
":".
join([
'${LD_LIBRARY_PATH}',new_ld_path])]
691 generate =
stack_subprocess([python,MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun',
str(
int(nevents)),
str(
int(random_seed)),
str(granularity)],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
692 (out,err) = generate.communicate()
694 gp_events=MADGRAPH_GRIDPACK_LOCATION+
"/Events/GridRun_{}/unweighted_events.lhe.gz".
format(
int(random_seed))
695 if not os.path.exists(gp_events):
696 mglog.error(
'Error in gp generation, did not find events at '+gp_events)
700 if reweight_card
is not None:
701 pythonpath_backup=os.environ[
'PYTHONPATH']
703 os.environ[
'PYTHONPATH']=
':'.
join([p
for p
in pythonpath_backup.split(
':')
if 'madgraph5amc' not in p])
705 os.environ[
'PYTHONPATH']=pythonpath_backup
707 shutil.move(gp_events,
'events.lhe.gz')
711 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events',os.R_OK):
712 raise RuntimeError(
'Could not find generate_events executable at '+MADGRAPH_GRIDPACK_LOCATION)
714 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events, starting generation.')
716 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
717 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name, os.F_OK):
718 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
' directory from gridpack generation')
719 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name]
720 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)
723 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1', os.F_OK):
724 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1 directory from gridpack generation')
725 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1']
726 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1')
728 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
730 if not gridpack_compile:
731 mglog.info(
'Copying make_opts from Template')
732 shutil.copy(os.environ[
'MADPATH']+
'/Template/LO/Source/make_opts',MADGRAPH_GRIDPACK_LOCATION+
'/Source/')
735 generate =
stack_subprocess([python,MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events',
'--parton',
'--nocompile',
'--only_generation',
'-f',
'--name='+gridpack_run_name],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
736 (out,err) = generate.communicate()
739 mglog.info(
'Allowing recompilation of gridpack')
740 if os.path.islink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a'):
741 mglog.info(
'Unlinking '+MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
742 os.unlink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
745 generate =
stack_subprocess([python,MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events',
'--parton',
'--only_generation',
'-f',
'--name='+gridpack_run_name],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
746 (out,err) = generate.communicate()
748 if isNLO
and systematics_settings
is not None:
750 mglog.info(
'Running systematics standalone')
751 systematics_path=MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/systematics.py'
752 events_location=MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz'
753 syst_cmd=[python,systematics_path]+[events_location]*2+[
"--"+k+
"="+systematics_settings[k]
for k
in systematics_settings]
754 mglog.info(
'running: '+
' '.
join(syst_cmd))
760 if not os.access(
'events.lhe.gz',os.R_OK):
761 mglog.info(
'Copying generated events to '+currdir)
762 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION+
'Events/'+gridpack_run_name):
763 shutil.copy(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz',
'events.lhe.gz')
765 mglog.info(
'Events were already in place')
769 mglog.info(
'Moving generated events to be in correct format for arrange_output().')
770 mglog.info(
'Unzipping generated events.')
774 mglog.info(
'Moving file over to '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
775 mkdir =
stack_subprocess([
'mkdir',
'-p',(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)])
777 shutil.move(
'events.lhe',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
779 mglog.info(
'Re-zipping into dataset name '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe.gz')
780 rezip =
stack_subprocess([
'gzip',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe'])
788 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat')
789 mglog.info(
'Decaying with MadSpin.')
790 add_madspin(process_dir=MADGRAPH_GRIDPACK_LOCATION)
792 mglog.info(
'Finished at '+
str(time.asctime()))
801 mglog.info(
'Path to fastjet install dir: '+os.environ[
'FASTJETPATH'])
802 fastjetconfig = os.environ[
'FASTJETPATH']+
'/bin/fastjet-config'
804 mglog.info(
'fastjet-config --version: '+
str(subprocess.Popen([fastjetconfig,
'--version'],stdout = subprocess.PIPE).stdout.read().strip()))
805 mglog.info(
'fastjet-config --prefix: '+
str(subprocess.Popen([fastjetconfig,
'--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
808 config_card=process_dir+
'/Cards/me5_configuration.txt'
810 config_card=process_dir+
'/Cards/amcatnlo_configuration.txt'
812 oldcard =
open(config_card,
'r')
813 newcard =
open(config_card+
'.tmp',
'w')
816 if 'fastjet = ' in line:
817 newcard.write(
'fastjet = '+fastjetconfig+
'\n')
818 mglog.info(
'Setting fastjet = '+fastjetconfig+
' in '+config_card)
823 shutil.move(config_card+
'.tmp',config_card)
835 for p
in os.environ[
'LHAPATH'].
split(
':')+os.environ[
'LHAPDF_DATA_PATH'].
split(
':'):
836 if os.path.exists(p+
"/../../lib/")
and LHAPATH
is None:
838 for p
in os.environ[
'LHAPDF_DATA_PATH'].
split(
':')+os.environ[
'LHAPATH'].
split(
':'):
839 if os.path.exists(p)
and LHADATAPATH
is None and p!=LHAPATH:
841 if LHADATAPATH
is None:
844 mglog.error(
'Could not find path to LHAPDF installation')
845 return LHAPATH,LHADATAPATH
853 pdflist =
open(LHADATAPATH+
'/pdfsets.index',
'r')
854 if isinstance(pdf,int)
or pdf.isdigit():
858 splitline=line.split()
859 if int(splitline[0]) == pdfid:
865 splitline=line.split()
866 if splitline[1] == pdfname:
867 pdfid=
int(splitline[0])
872 err=
'Couldn\'t find PDF name associated to ID %i in %s.'%(pdfid,LHADATAPATH+
'/pdfsets.index')
874 raise RuntimeError(err)
876 err=
'Couldn\'t find PDF ID associated to name %s in %s.'%(pdfname,LHADATAPATH+
'/pdfsets.index')
878 raise RuntimeError(err)
883 def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
887 origLHAPATH=os.environ[
'LHAPATH']
888 origLHAPDF_DATA_PATH=os.environ[
'LHAPDF_DATA_PATH']
896 run_card=process_dir+
'/Cards/run_card.dat'
899 if mydict[
"pdlabel"].
replace(
"'",
"") ==
'lhapdf':
901 mglog.info(
'creating local LHAPDF dir: MGC_LHAPDF/')
902 if os.path.islink(
'MGC_LHAPDF/'):
903 os.unlink(
'MGC_LHAPDF/')
904 elif os.path.isdir(
'MGC_LHAPDF/'):
905 shutil.rmtree(
'MGC_LHAPDF/')
907 newMGCLHA=
'MGC_LHAPDF/'
909 mkdir = subprocess.Popen([
'mkdir',
'-p',newMGCLHA])
912 pdfs_used=[
int(x)
for x
in mydict[
'lhaid'].
replace(
' ',
',').
split(
',') ]
914 if 'sys_pdf' in mydict:
920 pdfs_used.append(idx)
923 if 'systematics_arguments' in mydict:
924 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict[
'systematics_arguments'])
925 if 'pdf' in systematics_arguments:
931 pdfs_used.append(idx)
934 for pdf
in pdfs_used:
935 if isinstance(pdf,str)
and (pdf.lower()==
'errorset' or pdf.lower()==
'central'):
939 mglog.info(
"Found LHAPDF ID="+
str(pdfid)+
", name="+pdfname)
941 if not os.path.exists(newMGCLHA+pdfname)
and not os.path.lexists(newMGCLHA+pdfname):
942 if not os.path.exists(LHADATAPATH+
'/'+pdfname):
943 mglog.warning(
'PDF not installed at '+LHADATAPATH+
'/'+pdfname)
945 mglog.info(
'linking '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
946 os.symlink(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
948 mglog.info(
'copying '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
949 shutil.copytree(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
952 mglog.info(
'linking '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
953 os.symlink(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
955 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
956 mglog.info(
'linking '+atlasLHADATAPATH+
'/lhapdf.conf --> '+newMGCLHA+
'lhapdf.conf')
957 os.symlink(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
959 mglog.info(
'copying '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
960 shutil.copy2(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
962 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
963 mglog.info(
'copying '+atlasLHADATAPATH+
'/lhapdf.conf -->'+newMGCLHA+
'lhapdf.conf')
964 shutil.copy2(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
967 LHADATAPATH=os.getcwd()+
'/MGC_LHAPDF'
970 mglog.info(
'Not using LHAPDF')
971 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
975 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
977 mglog.info(
'Path to LHAPDF install dir: '+LHAPATH)
978 mglog.info(
'Path to LHAPDF data dir: '+LHADATAPATH)
979 if not os.path.isdir(LHADATAPATH):
980 raise RuntimeError(
'LHAPDF data dir not accesible: '+LHADATAPATH)
981 if not os.path.isdir(LHAPATH):
982 raise RuntimeError(
'LHAPDF path dir not accesible: '+LHAPATH)
986 lhapdfconfig=extlhapath
987 if not os.access(lhapdfconfig,os.X_OK):
988 raise RuntimeError(
'Failed to find valid external lhapdf-config at '+lhapdfconfig)
989 LHADATAPATH=subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().strip()
990 mglog.info(
'Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
991 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
993 getlhaconfig = subprocess.Popen([
'get_files',
'-data',
'lhapdf-config'])
996 if not os.access(os.getcwd()+
'/lhapdf-config',os.X_OK):
997 mglog.error(
'Failed to get lhapdf-config from MadGraphControl')
999 lhapdfconfig = os.getcwd()+
'/lhapdf-config'
1001 mglog.info(
'lhapdf-config --version: '+
str(subprocess.Popen([lhapdfconfig,
'--version'],stdout = subprocess.PIPE).stdout.read().strip()))
1002 mglog.info(
'lhapdf-config --prefix: '+
str(subprocess.Popen([lhapdfconfig,
'--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
1003 mglog.info(
'lhapdf-config --libdir: '+
str(subprocess.Popen([lhapdfconfig,
'--libdir'],stdout = subprocess.PIPE).stdout.read().strip()))
1004 mglog.info(
'lhapdf-config --datadir: '+
str(subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().strip()))
1005 mglog.info(
'lhapdf-config --pdfsets-path: '+
str(subprocess.Popen([lhapdfconfig,
'--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().strip()))
1007 modify_config_card(process_dir=process_dir,settings={
'lhapdf':lhapdfconfig,
'lhapdf_py3':lhapdfconfig})
1009 mglog.info(
'Creating links for LHAPDF')
1010 if os.path.islink(process_dir+
'/lib/PDFsets'):
1011 os.unlink(process_dir+
'/lib/PDFsets')
1012 elif os.path.isdir(process_dir+
'/lib/PDFsets'):
1013 shutil.rmtree(process_dir+
'/lib/PDFsets')
1015 os.symlink(LHADATAPATH,process_dir+
'/lib/PDFsets')
1017 shutil.copytree(LHADATAPATH,process_dir+
'/lib/PDFsets')
1018 mglog.info(
'Available PDFs are:')
1019 mglog.info(
sorted( [ x
for x
in os.listdir(process_dir+
'/lib/PDFsets')
if ".tar.gz" not in x ] ) )
1021 global MADGRAPH_COMMAND_STACK
1022 MADGRAPH_COMMAND_STACK += [
'# Copy the LHAPDF files locally' ]
1023 MADGRAPH_COMMAND_STACK += [
'cp -r '+os.getcwd()+
'/MGC_LHAPDF .' ]
1024 MADGRAPH_COMMAND_STACK += [
'cp -r '+process_dir+
'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
1026 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
1032 my_runMode = 2
if 'ATHENA_CORE_NUMBER' in os.environ
else 0
1033 if Ncores
is None and 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
1034 my_Ncores =
int(os.environ[
'ATHENA_CORE_NUMBER'])
1036 if my_Ncores
is None:
1037 mglog.info(
'Setting up for serial run')
1040 modify_config_card(process_dir=process_dir,settings={
'nb_core':my_Ncores,
'run_mode':my_runMode,
'automatic_html_opening':
'False'})
1044 mglog.info(
'Restoring original LHAPDF env variables:')
1045 os.environ[
'LHAPATH']=origLHAPATH
1046 os.environ[
'LHAPDF_DATA_PATH']=origLHAPDF_DATA_PATH
1047 mglog.info(
'LHAPATH='+os.environ[
'LHAPATH'])
1048 mglog.info(
'LHAPDF_DATA_PATH='+os.environ[
'LHAPDF_DATA_PATH'])
1052 madpath=os.environ[
'MADPATH']
1053 if not os.access(madpath+
'/bin/mg5_aMC',os.R_OK):
1054 raise RuntimeError(
'mg5_aMC executable not found in '+madpath)
1055 return madpath+
'/bin/mg5_aMC'
1059 """ Add lifetimes to the generated LHE file. Should be
1060 called after generate_events is called.
1067 if len(glob.glob(process_dir+
'/Events/*'))<1:
1068 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
1069 run = glob.glob(process_dir+
'/Events/*')[0].
split(
'/')[-1]
1074 tof_c =
open(
'time_of_flight_exec_card',
'w')
1075 tof_c.write(
'launch '+process_dir+
''' -i
1076 add_time_of_flight '''+run+((
' --threshold='+
str(threshold))
if threshold
is not None else ''))
1079 mglog.info(
'Started adding time of flight info '+
str(time.asctime()))
1081 global MADGRAPH_CATCH_ERRORS
1082 generate =
stack_subprocess([python,me_exec,
'time_of_flight_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
1083 (out,err) = generate.communicate()
1086 mglog.info(
'Finished adding time of flight information at '+
str(time.asctime()))
1089 lhe_gz = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1090 if not os.access(lhe_gz,os.R_OK):
1091 mglog.info(
'LHE file needs to be zipped')
1092 lhe = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1095 mglog.info(
'Zipped')
1097 mglog.info(
'LHE file zipped by MadGraph automatically. Nothing to do')
1102 def add_madspin(madspin_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
1103 """ Run madspin on the generated LHE file. Should be
1104 run when you have inputGeneratorFile set.
1105 Only requires a simplified process with the same model that you are
1106 interested in (needed to set up a process directory for MG5_aMC)
1113 if madspin_card
is not None:
1114 shutil.copyfile(madspin_card,process_dir+
'/Cards/madspin_card.dat')
1116 if len(glob.glob(process_dir+
'/Events/*'))<1:
1117 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
1118 proc_dir_list = glob.glob(process_dir+
'/Events/*')
1120 for adir
in proc_dir_list:
1121 if 'GridRun_' in adir:
1122 run=adir.split(
'/')[-1]
1125 run=proc_dir_list[0].
split(
'/')[-1]
1130 ms_c =
open(
'madspin_exec_card',
'w')
1131 ms_c.write(
'launch '+process_dir+
''' -i
1132 decay_events '''+run)
1135 mglog.info(
'Started running madspin at '+
str(time.asctime()))
1137 global MADGRAPH_CATCH_ERRORS
1138 generate =
stack_subprocess([python,me_exec,
'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
1139 (out,err) = generate.communicate()
1141 if len(glob.glob(process_dir+
'/Events/'+run+
'_decayed_*/')) == 0:
1142 mglog.error(
'No '+process_dir+
'/Events/'+run+
'_decayed_*/ can be found')
1143 raise RuntimeError(
'Problem while running MadSpin')
1145 mglog.info(
'Finished running madspin at '+
str(time.asctime()))
1148 lhe_gz = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1149 if not os.access(lhe_gz,os.R_OK):
1150 mglog.info(
'LHE file needs to be zipped')
1151 lhe = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1154 mglog.info(
'Zipped')
1156 mglog.info(
'LHE file zipped by MadGraph automatically. Nothing to do')
1160 """ Run MadSpin on an input LHE file. Takes the process
1161 from the LHE file, so you don't need to have a process directory
1162 set up in advance. Runs MadSpin and packs the LHE file up appropriately
1163 Needs runArgs for the file handling"""
1164 if not os.access(input_LHE,os.R_OK):
1165 raise RuntimeError(
'Could not find LHE file '+input_LHE)
1166 if not os.access(madspin_card,os.R_OK):
1167 raise RuntimeError(
'Could not find input MadSpin card '+madspin_card)
1169 shutil.copy(input_LHE,input_LHE+
'.original')
1170 mglog.info(
'Put backup copy of LHE file at '+input_LHE+
'.original')
1172 madspin_exec_card =
open(
'madspin_exec_card',
'w')
1173 madspin_exec_card.write(
'import '+input_LHE+
'\n')
1175 input_madspin_card =
open(madspin_card,
'r')
1177 for l
in input_madspin_card.readlines():
1178 commands = l.split(
'#')[0].
split()
1180 if len(commands)>1
and 'import'==commands[0]
and not 'model'==commands[1]:
1183 if len(commands)>0
and 'launch' == commands[0]:
1185 madspin_exec_card.write(l.strip()+
'\n')
1187 madspin_exec_card.write(
'launch\n')
1188 madspin_exec_card.close()
1189 input_madspin_card.close()
1191 madpath=os.environ[
'MADPATH']
1192 if not os.access(madpath+
'/MadSpin/madspin',os.R_OK):
1193 raise RuntimeError(
'madspin executable not found in '+madpath)
1194 mglog.info(
'Starting madspin at '+
str(time.asctime()))
1195 global MADGRAPH_CATCH_ERRORS
1196 generate =
stack_subprocess([python,madpath+
'/MadSpin/madspin',
'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
1197 (out,err) = generate.communicate()
1199 mglog.info(
'Done with madspin at '+
str(time.asctime()))
1203 if os.path.exists(os.getcwd()+
'/events.lhe'):
1204 os.remove(os.getcwd()+
'/events.lhe')
1206 mglog.info(
'Unzipping generated events.')
1210 mglog.info(
'Putting a copy in place for the transform.')
1211 mod_output =
open(os.getcwd()+
'/events.lhe',
'w')
1215 with open(input_LHE,
'r')
as fileobject:
1216 for line
in fileobject:
1218 mod_output.write(line)
1223 mglog.info(
'Removed '+
str(nEmpty)+
' empty lines from LHEF')
1227 raise RuntimeError(
'Must provide runArgs to madspin_on_lhe')
1229 outputDS = runArgs.outputTXTFile
if hasattr(runArgs,
'outputTXTFile')
else 'tmp_LHE_events'
1231 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
1232 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
1234 mglog.info(
'Re-zipping into dataset name '+outputDS)
1235 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
1239 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1240 outputDS = outputDS.split(
'.TXT')[0]
1242 if runArgs
is not None:
1243 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1244 runArgs.inputGeneratorFile=outputDS
1247 def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
1254 if len(glob.glob(os.path.join(process_dir,
'Events',
'*')))<1:
1255 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
1256 proc_dir_list = glob.glob(os.path.join(process_dir,
'Events',
'*'))
1259 for adir
in proc_dir_list:
1260 if 'decayed' in adir:
1263 if 'GridRun_' in adir:
1266 elif os.path.join(process_dir,
'Events',MADGRAPH_RUN_NAME)
in adir:
1268 if not os.access(this_run_name,os.R_OK):
1269 raise RuntimeError(
'Unable to locate run directory')
1271 hasUnweighted = os.access(this_run_name+
'/unweighted_events.lhe.gz',os.R_OK)
1274 madspinDirs=
sorted(glob.glob(this_run_name+
'_decayed_*/'))
1275 if len(madspinDirs):
1277 if hasRunMadSpin
and not hasUnweighted:
1279 hasUnweighted = os.access(madspinDirs[-1]+
'/unweighted_events.lhe.gz',os.R_OK)
1281 global MADGRAPH_COMMAND_STACK
1283 if len(madspinDirs):
1290 if os.path.exists(madspinDirs[-1]+
'/unweighted_events.lhe.gz'):
1291 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/unweighted_events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
1292 shutil.move(madspinDirs[-1]+
'/unweighted_events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
1293 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/unweighted_events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1294 elif os.path.exists(madspinDirs[-1]+
'/events.lhe.gz'):
1295 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
1296 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
1297 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1299 raise RuntimeError(
'MadSpin was run but can\'t find files :(')
1302 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz '+this_run_name+
'/events.lhe.gz']
1303 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/events.lhe.gz')
1304 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/events.lhe.gz')
1307 mglog.error(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1308 raise RuntimeError(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1310 if fixEventWeightsForBridgeMode:
1311 mglog.info(
"Fixing event weights after MadSpin... initial checks.")
1319 eventsfilename=
"unweighted_events"
1321 eventsfilename=
"events"
1322 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/%s.lhe.gz' % eventsfilename])
1325 for line
in open(process_dir+
'/Events/'+MADGRAPH_RUN_NAME+
'/%s.lhe'%eventsfilename):
1326 if "Number of Events" in line:
1328 MGnumevents=
int(sline[-1])
1329 elif "Integrated weight (pb)" in line:
1331 MGintweight=
float(sline[-1])
1332 elif "set spinmode none" in line:
1334 elif "</header>" in line:
1337 if spinmodenone
and MGnumevents>0
and MGintweight>0:
1338 mglog.info(
"Fixing event weights after MadSpin... modifying LHE file.")
1339 newlhe=
open(this_run_name+
'/%s_fixXS.lhe'%eventsfilename,
'w')
1347 event_norm_setting=
"average"
1349 for line
in open(this_run_name+
'/%s.lhe'%eventsfilename):
1352 if "<init>" in line:
1355 elif "</init>" in line:
1357 elif inInit
and initlinecount==0:
1361 if abs(
int(sline[-2])) == 3:
1362 event_norm_setting=
"sum"
1363 elif abs(
int(sline[-2])) == 4:
1364 event_norm_setting=
"average"
1365 elif inInit
and initlinecount==1:
1369 sline[0]=
str(MGintweight)
1370 sline[1]=
str(
float(sline[0])*relunc)
1371 if event_norm_setting==
"sum":
1372 sline[2]=
str(MGintweight/MGnumevents)
1373 elif event_norm_setting==
"average":
1374 sline[2]=
str(MGintweight)
1375 newline=
' '.
join(sline)
1378 elif inInit
and initlinecount>1:
1380 elif "<event>" in line:
1383 elif "</event>" in line:
1385 elif inEvent
and eventlinecount==0:
1388 if event_norm_setting==
"sum":
1389 sline[2]=
str(MGintweight/MGnumevents)
1390 elif event_norm_setting==
"average":
1391 sline[2]=
str(MGintweight)
1392 newline=
' '.
join(sline)
1395 newlhe.write(newline)
1398 mglog.info(
"Fixing event weights after MadSpin... cleaning up.")
1399 shutil.copyfile(this_run_name+
'/%s.lhe' % eventsfilename,
1400 this_run_name+
'/%s_badXS.lhe' % eventsfilename)
1402 shutil.move(this_run_name+
'/%s_fixXS.lhe' % eventsfilename,
1403 this_run_name+
'/%s.lhe' % eventsfilename)
1405 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s.lhe' % eventsfilename])
1408 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s_badXS.lhe' % eventsfilename])
1412 if os.path.exists(os.getcwd()+
'/events.lhe'):
1413 os.remove(os.getcwd()+
'/events.lhe')
1415 mglog.info(
'Unzipping generated events.')
1417 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/unweighted_events.lhe.gz'])
1423 mglog.info(
'Putting a copy in place for the transform.')
1425 orig_input = this_run_name+
'/unweighted_events.lhe'
1426 mod_output =
open(os.getcwd()+
'/events.lhe',
'w')
1428 orig_input = this_run_name+
'/events.lhe'
1429 mod_output =
open(os.getcwd()+
'/events.lhe',
'w')
1436 with open(orig_input,
'r')
as fileobject:
1437 for line
in fileobject:
1441 if '#' not in newline:
1443 elif '>' not in newline[ newline.find(
'#'): ]:
1446 mglog.warning(
'Found bad LHE line with an XML mark in a comment: "'+newline.strip()+
'"')
1447 newline=newline[:newline.find(
'#')]+
'#'+ (newline[newline.find(
'#'):].
replace(
'>',
'-'))
1449 if initrwgt
is False:
1451 elif "</initrwgt>" in newline:
1453 elif "<initrwgt>" in newline:
1455 elif initrwgt
is not None:
1456 newline=newline.replace(
'_DYNSCALE-1',
'')
1457 if '</weight>' in newline:
1458 iend=newline.find(
'</weight>')
1459 istart=newline[:iend].rfind(
'>')
1460 lhe_weights+=[newline[istart+1:iend].strip()]
1461 mod_output.write(newline)
1465 mglog.info(
'Removed '+
str(nEmpty)+
' empty lines from LHEF')
1467 mglog.info(
"The following "+
str(len(lhe_weights))+
" weights have been written to the LHE file: "+
",".
join(lhe_weights))
1470 mglog.info(
"Checking whether the following expected weights are in LHE file: "+
",".
join(expected_weights))
1471 for w
in expected_weights:
1472 if w
not in lhe_weights:
1473 raise RuntimeError(
"Did not find expected weight "+w+
" in lhe file. Did the reweight or systematics module crash?")
1474 mglog.info(
"Found all required weights!")
1477 mod_output2 =
open(os.getcwd()+
'/events.lhe',
'r')
1478 test=mod_output2.readline()
1479 if 'version="' in test:
1480 mglog.info(
'Applying LHE version hack')
1481 final_file =
open(os.getcwd()+
'/events.lhe.copy',
'w')
1482 final_file.write(
'<LesHouchesEvents version="%i.0">\n'%lhe_version)
1483 shutil.copyfileobj(mod_output2, final_file)
1485 shutil.copy(os.getcwd()+
'/events.lhe.copy',os.getcwd()+
'/events.lhe')
1487 os.remove(os.getcwd()+
'/events.lhe.copy')
1492 raise RuntimeError(
'Must provide runArgs to arrange_output')
1494 if hasattr(runArgs,
'outputTXTFile'):
1495 outputDS = runArgs.outputTXTFile
1497 outputDS =
'tmp_LHE_events'
1499 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
1501 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
1503 mglog.info(
'Re-zipping into dataset name '+outputDS)
1504 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
1508 mglog.info(
'Removing the process directory')
1509 shutil.rmtree(process_dir,ignore_errors=
True)
1511 if os.path.isdir(
'MGC_LHAPDF/'):
1512 shutil.rmtree(
'MGC_LHAPDF/',ignore_errors=
True)
1515 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1516 outputDS = outputDS.split(
'.TXT')[0]
1518 if runArgs
is not None:
1519 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1520 runArgs.inputGeneratorFile=outputDS
1522 mglog.info(
'All done with output arranging!')
1526 if reweight_card_loc
is None:
1529 f_rw=
open(reweight_card_loc)
1531 if 'launch' not in line:
1533 match=re.match(
r'launch.*--rwgt_info\s*=\s*(\S+).*',line.strip())
1534 if len(match.groups())!=1:
1535 raise RuntimeError(
'Unexpected format of reweight card in line'+line)
1537 names+=[match.group(1)]
1543 if syst_setting
is None or 'central_pdf' not in syst_setting:
1544 mglog.warning(
"Systematics have not been defined via base fragment or 'MADGRAPH_PDFSETTING', cannot check for expected weights")
1546 if 'pdf_variations' in syst_setting
and isinstance(syst_setting[
'pdf_variations'],list):
1547 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':1.0,
'muf':1.0,
'pdf':syst_setting[
'central_pdf']}]
1548 for pdf
in syst_setting[
'pdf_variations']:
1549 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':1.0,
'muf':1.0,
'pdf':pdf+1}]
1550 if 'alternative_pdfs' in syst_setting
and isinstance(syst_setting[
'alternative_pdfs'],list):
1551 for pdf
in syst_setting[
'alternative_pdfs']:
1552 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':1.0,
'muf':1.0,
'pdf':pdf}]
1553 if 'scale_variations' in syst_setting
and isinstance(syst_setting[
'scale_variations'],list):
1554 for mur
in syst_setting[
'scale_variations']:
1555 for muf
in syst_setting[
'scale_variations']:
1556 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':mur,
'muf':muf,
'pdf':syst_setting[
'central_pdf']}]
1560 run_card = process_dir+
'/Cards/run_card.dat'
1561 if isinstance(bias_module,tuple):
1562 mglog.info(
'Using bias module '+bias_module[0])
1563 the_run_card =
open(run_card,
'r')
1564 for line
in the_run_card:
1565 if 'bias_module' in line
and not bias_module[0]
in line:
1566 raise RuntimeError(
'You need to add the bias module '+bias_module[0]+
' to the run card to actually run it')
1567 the_run_card.close()
1568 if len(bias_module)!=3:
1569 raise RuntimeError(
'Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1570 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module[0]
1571 os.makedirs(bias_module_newpath)
1572 bias_module_file=
open(bias_module_newpath+
'/'+bias_module[0]+
'.f',
'w')
1573 bias_module_file.write(bias_module[1])
1574 bias_module_file.close()
1575 bias_module_make_file=
open(bias_module_newpath+
'/Makefile',
'w')
1576 bias_module_make_file.write(bias_module[2])
1577 bias_module_make_file.close()
1579 mglog.info(
'Using bias module '+bias_module)
1580 bias_module_name=bias_module.split(
'/')[-1].
replace(
'.gz',
'')
1581 bias_module_name=bias_module_name.replace(
'.tar',
'')
1582 the_run_card =
open(run_card,
'r')
1583 for line
in the_run_card:
1584 if 'bias_module' in line
and bias_module_name
not in line:
1585 raise RuntimeError(
'You need to add the bias module '+bias_module_name+
' to the run card to actually run it')
1586 the_run_card.close()
1588 if os.path.exists(bias_module+
'.tar.gz'):
1589 bias_module_path=bias_module+
'.tar.gz'
1590 elif os.path.exists(bias_module+
'.gz'):
1591 bias_module_path=bias_module+
'.gz'
1592 elif os.path.exists(bias_module):
1593 bias_module_path=bias_module
1595 mglog.error(
'Did not find bias module '+bias_module+
' , this path should point to folder or tarball. Alternatively give a tuple of strings containing module name, module, and makefile')
1597 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module_path.split(
'/')[-1]
1598 mglog.info(
'Copying bias module into place: '+bias_module_newpath)
1599 shutil.copy(bias_module_path,bias_module_newpath)
1600 mglog.info(
'Unpacking bias module')
1601 if bias_module_newpath.endswith(
'.tar.gz'):
1602 untar =
stack_subprocess([
'tar',
'xvzf',bias_module_newpath,
'--directory='+process_dir+
'/Source/BIAS/'])
1604 elif bias_module_path.endswith(
'.gz'):
1610 if os.access(process_dir+
'/Cards/reweight_card.dat',os.R_OK):
1611 return process_dir+
'/Cards/reweight_card.dat'
1617 shutil.move(reweight_card,reweight_card+
'.old')
1618 oldcard =
open(reweight_card+
'.old',
'r')
1619 newcard =
open(reweight_card,
'w')
1621 info_expression=
r'launch.*--rwgt_info\s*=\s*(\S+).*'
1622 name_expression=info_expression.replace(
'info',
'name')
1623 goodname_expression=
r'^[A-Za-z0-9_\-.]+$'
1624 for line
in oldcard:
1626 if not line.strip().startswith(
'launch') :
1629 rwgt_name_match=re.match(name_expression,line.strip())
1630 rwgt_info_match=re.match(info_expression,line.strip())
1631 if rwgt_name_match
is None and rwgt_info_match
is None:
1632 raise RuntimeError(
'Every reweighting should have a --rwgt_info (see https://cp3.irmp.ucl.ac.be/projects/madgraph/wiki/Reweight), please update your reweight_card accordingly. Line to fix: '+line)
1633 for match
in [rwgt_info_match,rwgt_name_match]:
1636 if len(match.groups())!=1:
1637 raise RuntimeError(
'Unexpected format of reweight card in line: '+line)
1638 if not re.match(goodname_expression,match.group(1)):
1639 raise RuntimeError(
'No special character in reweighting info/name, only allowing '+goodname_expression)
1640 if rwgt_info_match
is not None:
1642 elif rwgt_name_match
is not None:
1643 newcard.write(line.strip()+
' --rwgt_info={0}\n'.
format(rwgt_name_match.group(1)))
1646 mglog.info(
'Updated reweight_card')
1653 # Define multiparticle labels
1654 define p = g u c d s u~ c~ d~ s~
1655 define j = g u c d s u~ c~ d~ s~
1656 define pb = g u c d s b u~ c~ d~ s~ b~
1657 define jb = g u c d s b u~ c~ d~ s~ b~
1660 define vl = ve vm vt
1661 define vl~ = ve~ vm~ vt~
1662 define fu = u c e+ mu+ ta+
1663 define fu~ = u~ c~ e- mu- ta-
1664 define fd = d s ve~ vm~ vt~
1665 define fd~ = d~ s~ ve vm vt
1666 define susystrong = go ul ur dl dr cl cr sl sr t1 t2 b1 b2 ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~ t1~ t2~ b1~ b2~
1667 define susyweak = el- el+ er- er+ mul- mul+ mur- mur+ ta1- ta1+ ta2- ta2+ n1 n2 n3 n4 x1- x1+ x2- x2+ sve sve~ svm svm~ svt svt~
1668 define susylq = ul ur dl dr cl cr sl sr
1669 define susylq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~
1670 define susysq = ul ur dl dr cl cr sl sr t1 t2 b1 b2
1671 define susysq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~ t1~ t2~ b1~ b2~
1672 define susysl = el- el+ er- er+ mul- mul+ mur- mur+ ta1- ta1+ ta2- ta2+
1673 define susyv = sve svm svt
1674 define susyv~ = sve~ svm~ svt~
1680 if ktdurham
is None:
1682 if process
is not None:
1683 id_map = {
'go':
'1000021',
'dl':
'1000001',
'ul':
'1000002',
'sl':
'1000003',
'cl':
'1000004',
'b1':
'1000005',
't1':
'1000006',
1684 'dr':
'2000001',
'ur':
'2000002',
'sr':
'2000003',
'cr':
'2000004',
'b2':
'2000005',
't2':
'2000006',
1685 'n1':
'1000022',
'n2':
'1000023',
'x1':
'1000024',
'x2':
'1000037',
'n3':
'1000025',
'n4':
'1000035',
1686 'el':
'1000011',
'mul':
'1000013',
'ta1':
'1000015',
'sve':
'1000012',
'svm':
'1000014',
'svt':
'1000016',
1687 'er':
'2000011',
'mur':
'2000013',
'ta2':
'2000015'}
1689 if 'generate' in l
or 'add process' in l:
1691 for particle
in clean_proc.split():
1692 if particle
not in id_map:
1693 mglog.info(f
'Particle {particle} not found in PDG ID map - skipping')
1695 prod_particles += id_map[particle]
1699 if len(prod_particles)>0:
1700 for x
in prod_particles:
1702 my_mass =
min(my_mass,abs(
float(masses[x])))
1704 mglog.info(f
'Seem to ask for production of PDG ID {x}, but {x} not in mass dictionary?')
1706 strong_ids = [
'1000001',
'1000002',
'1000003',
'1000004',
'1000005',
'1000006',
'2000001',
'2000002',
'2000003',
'2000004',
'2000005',
'2000006',
'1000021']
1707 weak_ids = [
'1000023',
'1000024',
'1000025',
'1000011',
'1000013',
'1000015',
'2000011',
'2000013',
'2000015',
'1000012',
'1000014',
'1000016']
1709 my_mass =
min([abs(
float(masses[x]))
for x
in strong_ids
if x
in masses])
1713 my_mass =
max([abs(
float(masses[x]))
for x
in weak_ids
if x
in masses
and float(masses[x])<10000.])
1715 if my_mass>10000.
and '1000022' in masses:
1716 my_mass = masses[
'1000022']
1718 raise RuntimeError(
'Could not understand which mass to use for matching cut in '+
str(masses))
1721 ktdurham =
min(my_mass*0.25,500)
1723 ktdurham =
max(ktdurham,15)
1724 if syst_mod
is not None and 'qup' in syst_mod.lower():
1725 ktdurham = ktdurham*2.
1726 elif syst_mod
is not None and 'qdown' in syst_mod.lower():
1727 ktdurham = ktdurham*0.5
1729 mglog.info(
'For matching, will use ktdurham of '+
str(ktdurham))
1733 if syst_mod
is not None and 'alpsfactup' in syst_mod.lower():
1735 elif syst_mod
is not None and 'alpsfactdown' in syst_mod.lower():
1738 if syst_mod
is not None and 'scalefactup' in syst_mod.lower():
1740 elif syst_mod
is not None and 'scalefactdown' in syst_mod.lower():
1743 return abs(ktdurham) , alpsfact , scalefact
1748 if 'import model' in process:
1749 mglog.info(
'Assuming that you have specified the model in your process string already')
1751 for l
in process.split(
'\n'):
1752 if 'import model' in l:
1756 if 'MSSM_SLHA2' in full_proc:
1758 for l
in process.split(
'\n'):
1759 if 'import model' not in l:
1762 # Output processes to MadEvent directory
1767 # Specify process(es) to run
1770 # Output processes to MadEvent directory
1777 syst_mod=None, keepOutput=False, param_card=None, writeGridpack=False,\
1778 madspin_card=None, run_settings={}, params={}, fixEventWeightsForBridgeMode=False, add_lifetimes_lhe=False, usePMGSettings=True):
1782 usePMGSettings (bool): See :py:func:`new_process`. Will set SM parameters to the appropriate values. Default: True.
1784 ktdurham = run_settings[
'ktdurham']
if 'ktdurham' in run_settings
else None
1785 ktdurham , alpsfact , scalefact =
get_SUSY_variations( process, params[
'MASS'] , syst_mod , ktdurham=ktdurham )
1787 process_dir = MADGRAPH_GRIDPACK_LOCATION
1790 process_dir =
new_process(full_proc, plugin=plugin, usePMGSettings=usePMGSettings)
1791 mglog.info(
'Using process directory '+
str(process_dir))
1794 modify_param_card(param_card_input=param_card,process_dir=process_dir,params=params)
1797 settings = {
'ktdurham':ktdurham,
'scalefact':scalefact,
'alpsfact':alpsfact}
1798 settings.update(run_settings)
1801 modify_run_card(process_dir=process_dir,runArgs=runArgs,settings=settings)
1804 if madspin_card
is not None:
1805 if not os.access(madspin_card,os.R_OK):
1806 raise RuntimeError(
'Could not locate madspin card at '+
str(madspin_card))
1807 shutil.copy(madspin_card,process_dir+
'/Cards/madspin_card.dat')
1814 generate(runArgs=runArgs,process_dir=process_dir,grid_pack=writeGridpack)
1817 if add_lifetimes_lhe :
1818 mglog.info(
'Requested addition of lifetimes to LHE files: doing so now.')
1825 arrange_output(process_dir=process_dir,saveProcDir=keepOutput,runArgs=runArgs,fixEventWeightsForBridgeMode=fixEventWeightsForBridgeMode)
1827 mglog.info(
'All done generating events!!')
1828 return settings[
'ktdurham']
1831 def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1832 """Build a new LHE file from an old one and an updated param card.
1833 The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1834 may have their masses changed.
1835 If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1836 By default, the old LHE file is removed.
1837 If None is provided as a new LHE file name, the new file will replace the old one."""
1839 lhe_file_new_tmp = lhe_file_new
if lhe_file_new
is not None else lhe_file_old+
'.tmp'
1841 if not os.access(lhe_file_old,os.R_OK):
1842 raise RuntimeError(
'Could not access old LHE file at '+
str(lhe_file_old)+
'. Please check the file location.')
1844 if param_card_old
is not None:
1845 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_old])
1847 if not os.access(param_card_old,os.R_OK):
1848 raise RuntimeError(
'Could not get param card '+param_card_old)
1850 if os.access(lhe_file_new_tmp,os.R_OK):
1851 raise RuntimeError(
'Old file at'+
str(lhe_file_new_tmp)+
' in the current directory. Dont want to clobber it. Please move it first.')
1853 newlhe =
open(lhe_file_new_tmp,
'w')
1857 particles_in_events = []
1860 with open(lhe_file_old,
'r')
as fileobject:
1861 for line
in fileobject:
1862 if decayEdit
and '</slha>' not in line:
1864 if decayEdit
and '</slha>' in line:
1866 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1867 and len(line.strip().
split()) > 1:
1868 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1869 blockName = line.strip().
upper().
split()[pos]
1872 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
1873 akey = line.strip().
split()[0]
1874 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
1875 akey = line.strip().
split()[1]
1878 if akey
is not None and blockName ==
'MASS' and akey
in masses:
1879 newlhe.write(
' '+akey+
' '+
str(masses[akey])+
' # \n')
1880 mglog.info(
' '+akey+
' '+
str(masses[akey])+
' #')
1885 if blockName ==
'DECAY' and param_card_old
is not None:
1887 oldparam =
open(param_card_old,
'r')
1889 for old_line
in oldparam.readlines():
1891 if old_line.strip().
upper().startswith(
'DECAY')
and len(old_line.strip().
split()) > 1:
1892 newBlockName = line.strip().
upper().
split()[pos]
1894 newlhe.write(old_line)
1895 elif newBlockName ==
'DECAY':
1897 newlhe.write(old_line)
1905 if not eventRead
and '<event>' in line:
1908 if len(line.split())==11:
1909 aparticle = line.split()[0]
1910 if aparticle
not in particles_in_events:
1911 particles_in_events += [aparticle]
1918 if akey
in particles_in_events:
1919 mglog.error(
'Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1926 if lhe_file_new
is None:
1927 os.remove(lhe_file_old)
1928 shutil.move(lhe_file_new_tmp,lhe_file_old)
1929 lhe_file_new_tmp = lhe_file_old
1931 elif delete_old_lhe:
1932 os.remove(lhe_file_old)
1934 return lhe_file_new_tmp
1938 """Update the PDG IDs used in an LHE file. This is a bit finicky, as we have to
1939 both touch the LHE file metadata _and_ modify the events themselves. But since this
1940 is "just" a remapping, it should be safe assuming Pythia8 is told the correct thing
1941 afterwards and can get the showering right."""
1943 lhe_file_new_tmp = lhe_file_new
if lhe_file_new
is not None else lhe_file_old+
'.tmp'
1945 if not os.access(lhe_file_old,os.R_OK):
1946 raise RuntimeError(
'Could not access old LHE file at '+
str(lhe_file_old)+
'. Please check the file location.')
1949 pdgid_map_str = {
str(x) :
str(pdgid_map[x])
for x
in pdgid_map }
1951 pdgid_map_str.update( {
'-'+
str(x) :
'-'+
str(pdgid_map[x])
for x
in pdgid_map
if '-'+
str(x)
not in pdgid_map } )
1953 newlhe =
open(lhe_file_new_tmp,
'w')
1956 with open(lhe_file_old,
'r')
as fileobject:
1957 for line
in fileobject:
1959 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1960 and len(line.strip().
split()) > 1:
1961 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1962 blockName = line.strip().
upper().
split()[pos]
1963 elif '</slha>' in line:
1966 if len(line.split(
'#')[0].strip())==0:
1968 for pdgid
in pdgid_map_str:
1969 if pdgid
in line_mod.split():
1970 line_mod = line_mod.replace( pdgid , pdgid_map_str[pdgid] )
1971 newlhe.write(line_mod)
1974 if blockName==
'MASS' and line.split()[0]
in pdgid_map_str:
1975 newlhe.write( line.replace( line.split()[0] , pdgid_map_str[ line.split()[0] ] , 1 ) )
1977 if blockName==
'DECAY' and line.split()[1]
in pdgid_map_str:
1978 newlhe.write( line.replace( line.split()[1] , pdgid_map_str[ line.split()[1] ] , 1 ) )
1980 if blockName==
'QNUMBERS' and line.split()[2]
in pdgid_map_str:
1981 newlhe.write( line.replace( line.split()[2] , pdgid_map_str[ line.split()[2] ] , 1 ) )
1983 if '<event>' in line:
1985 if eventRead
and len(line.split())==13
and line.split()[0]
in pdgid_map_str:
1986 newlhe.write( line.replace( line.split()[0] , pdgid_map_str[ line.split()[0] ] , 1 ) )
1993 if lhe_file_new
is None:
1994 os.remove(lhe_file_old)
1995 shutil.move(lhe_file_new_tmp,lhe_file_old)
1996 lhe_file_new_tmp = lhe_file_old
1998 elif delete_old_lhe:
1999 os.remove(lhe_file_old)
2001 return lhe_file_new_tmp
2005 """ Helper function when looking at param cards
2006 In some cases it's tricky to match keys - they may differ
2007 only in white space. This tries to sort out when we have
2008 a match, and then uses the one in blockParams afterwards.
2009 In the case of no match, it returns the original key.
2012 for key
in dictionary:
2014 if mod_key==test_key:
2019 def modify_param_card(param_card_input=None,param_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,params={},output_location=None):
2020 """Build a new param_card.dat from an existing one.
2021 Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
2022 Keys can include MASS (for masses) and DECAY X (for decays of particle X)"""
2026 if param_card_input
is None:
2027 param_card_input=process_dir+
'/Cards/param_card.dat'
2028 elif param_card_input
is not None and not os.access(param_card_input,os.R_OK):
2029 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_input])
2031 if not os.access(param_card_input,os.R_OK):
2032 raise RuntimeError(
'Could not get param card '+param_card_input)
2033 mglog.info(
'Using input param card at '+param_card_input)
2037 for blockName
in list(params.keys()):
2038 paramsUpper[blockName.upper()] = {}
2039 for paramName
in list(params[blockName].
keys()):
2040 paramsUpper[blockName.upper()][paramName.upper()] = params[blockName][paramName]
2042 if param_card_backup
is not None:
2043 mglog.info(
'Keeping backup of original param card at '+param_card_backup)
2044 param_card_old = param_card_backup
2046 param_card_old = param_card_input+
'.old_to_be_deleted'
2047 if os.path.isfile(param_card_old):
2048 os.unlink(param_card_old)
2049 os.rename(param_card_input, param_card_old)
2051 oldcard =
open(param_card_old,
'r')
2052 param_card_location= process_dir+
'/Cards/param_card.dat' if output_location
is None else output_location
2053 newcard =
open(param_card_location,
'w')
2057 for linewithcomment
in oldcard:
2058 line=linewithcomment.split(
'#')[0]
2059 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
2060 and len(line.strip().
split()) > 1:
2061 if decayEdit
and blockName ==
'DECAY':
2063 pos = 0
if line.strip().startswith(
'DECAY')
else 1
2064 if blockName==
'MASS' and 'MASS' in paramsUpper:
2066 if "MASS" in doneParams:
2067 leftOvers = [ x
for x
in paramsUpper[
'MASS']
if x
not in doneParams[
'MASS'] ]
2069 leftOvers = [ x
for x
in paramsUpper[
'MASS'] ]
2071 for pdg_id
in leftOvers:
2072 mglog.warning(
'Adding mass line for '+
str(pdg_id)+
' = '+
str(paramsUpper[
'MASS'][pdg_id])+
' which was not in original param card')
2073 newcard.write(
' '+
str(pdg_id)+
' '+
str(paramsUpper[
'MASS'][pdg_id])+
'\n')
2074 doneParams[
'MASS'][pdg_id]=
True
2075 if blockName==
'DECAY' and 'DECAY' not in line.strip().
upper()
and 'DECAY' in paramsUpper:
2077 leftOvers = [ x
for x
in paramsUpper[
'DECAY']
if x
not in doneParams[
'DECAY'] ]
2078 for pdg_id
in leftOvers:
2079 mglog.warning(
'Adding decay for pdg id '+
str(pdg_id)+
' which was not in the original param card')
2080 newcard.write( paramsUpper[
'DECAY'][pdg_id].strip()+
'\n' )
2081 doneParams[
'DECAY'][pdg_id]=
True
2082 blockName = line.strip().
upper().
split()[pos]
2087 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
2090 if len(line.split())==2:
2091 akey = line.upper().strip().
split()[0]
2094 akey = line.upper().strip()[:line.strip().rfind(
' ')].strip()
2095 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
2096 akey = line.strip().
split()[1]
2098 newcard.write(linewithcomment)
2102 if blockName
not in paramsUpper:
2103 newcard.write(linewithcomment)
2105 blockParams = paramsUpper[blockName]
2111 if '#' in linewithcomment:
2112 stringkey = linewithcomment[linewithcomment.find(
'#')+1:].strip()
2113 if len(stringkey.split()) > 0:
2114 stringkey = stringkey.split()[0].
upper()
2116 if akey
not in blockParams
and not (stringkey
is not None and stringkey
in blockParams):
2117 newcard.write(linewithcomment)
2120 if akey
in blockParams
and (stringkey
is not None and stringkey
in blockParams):
2121 raise RuntimeError(
'Conflicting use of numeric and string keys '+akey+
' and '+stringkey)
2123 theParam = blockParams.get(akey,blockParams[stringkey]
if stringkey
in blockParams
else None)
2124 if blockName
not in doneParams:
2125 doneParams[blockName] = {}
2126 if akey
in blockParams:
2127 doneParams[blockName][akey]=
True
2128 elif stringkey
is not None and stringkey
in blockParams:
2129 doneParams[blockName][stringkey]=
True
2132 if blockName==
"DECAY":
2133 if theParam.splitlines()[0].
split()[0].
upper()==
"DECAY":
2135 for newline
in theParam.splitlines():
2136 newcard.write(newline+
'\n')
2140 newcard.write(
'DECAY '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2141 mglog.info(
'DECAY '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2143 elif blockName==
'QNUMBERS':
2145 for newline
in theParam.splitlines():
2146 newcard.write(newline+
'\n')
2150 newcard.write(
' '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2151 mglog.info(
' '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2155 for blockName
in paramsUpper:
2156 if blockName
not in doneParams
and len(paramsUpper[blockName].
keys())>0:
2157 raise RuntimeError(
'Did not find any of the parameters for block '+blockName+
' in param_card')
2158 for paramName
in paramsUpper[blockName]:
2159 if paramName
not in doneParams[blockName]:
2160 raise RuntimeError(
'Was not able to replace parameter '+paramName+
' in param_card')
2167 def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
2168 """Build a new run_card.dat from an existing one.
2169 This function can get a fresh runcard from DATAPATH or start from the process directory.
2170 Settings is a dictionary of keys (no spaces needed) and values to replace.
2173 mglog.info(
'Running config-only. No proc card, so not operating on the run card.')
2178 for s
in list(settings.keys()):
2179 settings_lower[s.lower()] = settings[s]
2182 if run_card_input
is None:
2184 elif run_card_input
is not None and not os.access(run_card_input,os.R_OK):
2185 runcard = subprocess.Popen([
'get_files',
'-data',run_card_input])
2187 if not os.access(run_card_input,os.R_OK):
2188 raise RuntimeError(
'Could not get run card '+run_card_input)
2193 if not skipBaseFragment:
2194 MadGraphControl.MadGraphSystematicsUtils.setup_pdf_and_systematic_weights(MADGRAPH_PDFSETTING,settings_lower,isNLO)
2197 if runArgs
is not None:
2199 if 'iseed' not in settings_lower:
2200 settings_lower[
'iseed']=rand_seed
2201 if not isNLO
and 'python_seed' not in settings_lower:
2202 settings_lower[
'python_seed']=rand_seed
2203 if 'beamenergy' in settings_lower:
2204 mglog.warning(
'Do not set beam energy in MG settings. The variables are ebeam1 and ebeam2. Will use your setting of '+
str(settings_lower[
'beamenergy']))
2205 beamEnergy=settings_lower[
'beamenergy']
2206 settings_lower.pop(
'beamenergy')
2207 if 'ebeam1' not in settings_lower:
2208 settings_lower[
'ebeam1']=beamEnergy
2209 if 'ebeam2' not in settings_lower:
2210 settings_lower[
'ebeam2']=beamEnergy
2212 if 'nevents' in settings_lower:
2213 settings_lower[
'nevents'] =
int(settings_lower[
'nevents'])
2215 mglog.info(
'Modifying run card located at '+run_card_input)
2216 if run_card_backup
is not None:
2217 mglog.info(
'Keeping backup of original run card at '+run_card_backup)
2218 run_card_old = run_card_backup
2220 run_card_old = run_card_input+
'.old_to_be_deleted'
2221 mglog.debug(
'Modifying runcard settings: '+
str(settings_lower))
2222 if os.path.isfile(run_card_old):
2223 os.unlink(run_card_old)
2224 os.rename(run_card_input, run_card_old)
2226 oldCard =
open(run_card_old,
'r')
2227 newCard =
open(process_dir+
'/Cards/run_card.dat',
'w')
2229 for line
in iter(oldCard):
2230 if not line.strip().startswith(
'#'):
2231 command = line.split(
'!', 1)[0]
2232 comment = line.split(
'!', 1)[1]
if '!' in line
else ''
2234 setting = command.split(
'=')[-1]
2235 stripped_setting = setting.strip()
2236 oldValue =
'='.
join(command.split(
'=')[:-1])
2237 if stripped_setting.lower()
in settings_lower:
2239 if settings_lower[stripped_setting.lower()]
is None:
2241 mglog.info(
'Removing '+stripped_setting+
'.')
2242 used_settings += [ stripped_setting.lower() ]
2244 line = oldValue.replace(oldValue.strip(),
str(settings_lower[stripped_setting.lower()]))+
'='+setting
2246 line +=
' !' + comment
2247 mglog.info(
'Setting '+stripped_setting+
' = '+
str(settings_lower[stripped_setting.lower()]))
2248 used_settings += [ stripped_setting.lower() ]
2249 newCard.write(line.strip()+
'\n')
2252 if 'mcatnlo_delta' in settings_lower:
2253 if settings_lower[
'mcatnlo_delta'] ==
'True':
2254 modify_config_card(process_dir=process_dir,settings={
'pythia8_path':os.getenv(
"PY8PATH")})
2257 for asetting
in settings_lower:
2258 if asetting
in used_settings:
2260 if settings_lower[asetting]
is None:
2262 mglog.info(
'Option '+asetting+
' was not in the default run_card (normal for hidden options). Adding by hand a setting to '+
str(settings_lower[asetting]) )
2263 newCard.write(
' '+
str(settings_lower[asetting])+
' = '+
str(asetting)+
'\n')
2267 mglog.info(
'Finished modification of run card.')
2268 if run_card_backup
is None:
2269 os.unlink(run_card_old)
2272 def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
2273 """Build a new configuration from an existing one.
2274 This function can get a fresh runcard from DATAPATH or start from the process directory.
2275 Settings is a dictionary of keys (no spaces needed) and values to replace.
2281 mglog.info(
'Modifying config card located at '+config_card)
2282 if config_card_backup
is not None:
2283 mglog.info(
'Keeping backup of original config card at '+config_card_backup)
2284 config_card_old = config_card_backup
2286 config_card_old = config_card+
'.old_to_be_deleted'
2287 mglog.debug(
'Modifying config card settings: '+
str(settings))
2288 if os.path.isfile(config_card_old):
2289 os.unlink(config_card_old)
2290 os.rename(config_card, config_card_old)
2292 oldCard =
open(config_card_old,
'r')
2293 newCard =
open(config_card,
'w')
2295 for line
in iter(oldCard):
2296 lmod = line
if set_commented
else line.split(
'#')[0]
2299 for setting
in settings:
2300 if setting
not in lmod:
2303 mglog.info(
'Setting '+setting.strip()+
' to '+
str(settings[setting]))
2304 newCard.write(
' '+
str(setting.strip())+
' = '+
str(settings[setting])+
'\n')
2305 used_settings += [ setting.strip() ]
2313 for asetting
in settings:
2314 if asetting
in used_settings:
2316 if settings[asetting]
is None:
2318 mglog.warning(
'Option '+asetting+
' was not in the default config card. Adding by hand a setting to '+
str(settings[asetting]) )
2319 newCard.write(
' '+
str(asetting)+
' = '+
str(settings[asetting])+
'\n')
2323 mglog.info(
'Finished modification of config card.')
2324 if config_card_backup
is None:
2325 os.unlink(config_card_old)
2329 card_dir=process_dir+
'/Cards/'
2330 print_cards(proc_card=card_dir+
'proc_card_mg5.dat',run_card=card_dir+
'run_card.dat',param_card=card_dir+
'param_card.dat',\
2331 madspin_card=card_dir+
'madspin_card.dat',reweight_card=card_dir+
'reweight_card.dat',warn_on_missing=
False)
2334 def print_cards(proc_card='proc_card_mg5.dat',run_card=None,param_card=None,madspin_card=None,reweight_card=None,warn_on_missing=True):
2335 if os.access(proc_card,os.R_OK):
2336 mglog.info(
"proc_card:")
2337 procCard = subprocess.Popen([
'cat',proc_card])
2339 elif warn_on_missing:
2340 mglog.warning(
'No proc_card: '+proc_card+
' found')
2342 if run_card
is not None and os.access(run_card,os.R_OK):
2343 mglog.info(
"run_card:")
2344 runCard = subprocess.Popen([
'cat',run_card])
2346 elif run_card
is not None and warn_on_missing:
2347 mglog.warning(
'No run_card: '+run_card+
' found')
2349 mglog.info(
'Default run card in use')
2351 if param_card
is not None and os.access(param_card,os.R_OK):
2352 mglog.info(
"param_card:")
2353 paramCard = subprocess.Popen([
'cat',param_card])
2355 elif param_card
is not None and warn_on_missing:
2356 mglog.warning(
'No param_card: '+param_card+
' found')
2358 mglog.info(
'Default param card in use')
2360 if madspin_card
is not None and os.access(madspin_card,os.R_OK):
2361 mglog.info(
"madspin_card:")
2362 madspinCard = subprocess.Popen([
'cat',madspin_card])
2364 elif madspin_card
is not None and warn_on_missing:
2365 mglog.warning(
'No madspin_card: '+madspin_card+
' found')
2367 mglog.info(
'No madspin card in use')
2369 if reweight_card
is not None and os.access(reweight_card,os.R_OK):
2370 mglog.info(
"reweight_card:")
2371 madspinCard = subprocess.Popen([
'cat',reweight_card])
2373 elif reweight_card
is not None and warn_on_missing:
2374 mglog.warning(
'No reweight_card: '+reweight_card+
' found')
2376 mglog.info(
'No reweight card in use')
2380 """ Simple function for checking if there is a grid pack.
2381 Relies on the specific location of the unpacked gridpack (madevent)
2382 which is here set as a global variable. The gridpack is untarred by
2383 the transform (Gen_tf.py) and no sign is sent to the job itself
2384 that there is a gridpack in use except the file's existence"""
2385 if os.access(MADGRAPH_GRIDPACK_LOCATION,os.R_OK):
2386 mglog.info(
'Located input grid pack area')
2393 mglog.info(
'Athena running on config only mode: grabbing config card the old way, as there will be no proc dir')
2394 if os.access(os.environ[
'MADPATH']+
'/input/mg5_configuration.txt',os.R_OK):
2395 shutil.copy(os.environ[
'MADPATH']+
'/input/mg5_configuration.txt',
'local_mg5_configuration.txt')
2396 return 'local_mg5_configuration.txt'
2398 lo_config_card=process_dir+
'/Cards/me5_configuration.txt'
2399 nlo_config_card=process_dir+
'/Cards/amcatnlo_configuration.txt'
2401 if os.access(lo_config_card,os.R_OK)
and not os.access(nlo_config_card,os.R_OK):
2402 return lo_config_card
2403 elif os.access(nlo_config_card,os.R_OK)
and not os.access(lo_config_card,os.R_OK):
2404 return nlo_config_card
2405 elif os.access(nlo_config_card,os.R_OK)
and os.access(lo_config_card,os.R_OK):
2406 mglog.error(
'Found both types of config card in '+process_dir)
2408 mglog.error(
'No config card in '+process_dir)
2409 raise RuntimeError(
'Unable to locate configuration card')
2414 for l
in card_in.readlines():
2415 if 'cluster_type' not in l.split(
'#')[0]:
2417 cluster_type = l.split(
'#')[0].
split(
'=')[1]
2418 mglog.info(
'Returning cluster type: '+cluster_type)
2431 cardpath=process_dir+
'/Cards/run_card.dat'
2437 modify_run_card(process_dir=process_dir,settings={
'event_norm':
'average'},skipBaseFragment=
True)
2438 mglog.warning(
"setting event_norm to average, there is basically no use case where event_norm=sum is a good idea")
2442 if 'ktdurham' in mydict
and float(mydict[
'ktdurham']) > 0
and int(mydict[
'ickkw']) != 0:
2443 log=
'Bad combination of settings for CKKW-L merging! ktdurham=%s and ickkw=%s.'%(mydict[
'ktdurham'],mydict[
'ickkw'])
2445 raise RuntimeError(log)
2448 if 'systematics_program' not in mydict
or mydict[
'systematics_program']==
'systematics':
2449 syscalc_settings=[
'sys_pdf',
'sys_scalefact',
'sys_alpsfact',
'sys_matchscale']
2450 found_syscalc_setting=
False
2451 for s
in syscalc_settings:
2453 mglog.warning(
'Using syscalc setting '+s+
' with new systematics script. Systematics script is default from 2.6.2 and steered differently (https://cp3.irmp.ucl.ac.be/projects/madgraph/wiki/Systematics#Systematicspythonmodule)')
2454 found_syscalc_setting=
True
2455 if found_syscalc_setting:
2456 syst_arguments=MadGraphControl.MadGraphSystematicsUtils.convertSysCalcArguments(mydict)
2457 mglog.info(
'Converted syscalc arguments to systematics arguments: '+syst_arguments)
2458 syst_settings_update={
'systematics_arguments':syst_arguments}
2459 for s
in syscalc_settings:
2460 syst_settings_update[s]=
None
2461 modify_run_card(process_dir=process_dir,settings=syst_settings_update,skipBaseFragment=
True)
2466 mglog.info(
'Checking PDF and systematics settings')
2467 if not MadGraphControl.MadGraphSystematicsUtils.base_fragment_setup_check(MADGRAPH_PDFSETTING,mydict,isNLO):
2469 syst_settings=MadGraphControl.MadGraphSystematicsUtils.get_pdf_and_systematic_settings(MADGRAPH_PDFSETTING,isNLO)
2470 modify_run_card(process_dir=process_dir,settings=syst_settings,skipBaseFragment=
True)
2473 if 'systematics_arguments' in mydict_new:
2474 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict_new[
'systematics_arguments'])
2475 if 'weight_info' not in systematics_arguments:
2476 mglog.info(
'Enforcing systematic weight name convention')
2478 if '--dyn' in systematics_arguments
or ' dyn' in systematics_arguments:
2479 if '--dyn' in systematics_arguments:
2480 dyn = systematics_arguments.split(
'--dyn')[1]
2481 if ' dyn' in systematics_arguments:
2482 dyn = systematics_arguments.split(
' dyn')[1]
2483 dyn = dyn.replace(
'\'',
' ').
replace(
'=',
' ').
split()[0]
2484 if dyn
is not None and len(dyn.split(
','))>1:
2485 systematics_arguments[
'weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO_ALTDYNSCALES
2487 systematics_arguments[
'weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO
2488 modify_run_card(process_dir=process_dir,settings={
'systematics_arguments':MadGraphControl.MadGraphSystematicsUtils.write_systematics_arguments(systematics_arguments)},skipBaseFragment=
True)
2491 if 'python_seed' not in mydict:
2492 mglog.warning(
'No python seed set in run_card -- adding one with same value as iseed')
2493 modify_run_card(process_dir=process_dir,settings={
'python_seed':mydict[
'iseed']},skipBaseFragment=
True)
2498 proton_5flav =
False
2500 with open(process_dir+
'/Cards/proc_card_mg5.dat',
'r')
as file:
2501 content = file.readlines()
2502 for rawline
in content:
2503 line = rawline.split(
'#')[0]
2504 if line.startswith(
"define p"):
2505 if 'b' in line.split()
and 'b~' in line.split():
2507 if 'j' in line.split()
and jet_5flav:
2509 if line.startswith(
"define j"):
2510 if 'b' in line.split()
and 'b~' in line.split():
2512 if 'p' in line.split()
and proton_5flav:
2514 if proton_5flav
or jet_5flav:
2515 FS_updates[
'asrwgtflavor'] = 5
2516 if not proton_5flav:
2517 mglog.warning(
'Found 5-flavour jets but 4-flavour proton. This is inconsistent - please pick one.')
2518 mglog.warning(
'Will proceed assuming 5-flavour scheme.')
2520 mglog.warning(
'Found 5-flavour protons but 4-flavour jets. This is inconsistent - please pick one.')
2521 mglog.warning(
'Will proceed assuming 5-flavour scheme.')
2523 FS_updates[
'asrwgtflavor'] = 4
2525 if len(FS_updates)==0:
2526 mglog.warning(f
'Could not identify 4- or 5-flavor scheme from process card {process_dir}/Cards/proc_card_mg5.dat')
2528 if 'asrwgtflavor' in mydict
or 'maxjetflavor' in mydict
or 'pdgs_for_merging_cut' in mydict:
2529 if FS_updates[
'asrwgtflavor'] == 5:
2531 if (
'asrwgtflavor' in mydict
and int(mydict[
'asrwgtflavor']) != 5)
or (
'maxjetflavor' in mydict
and int(mydict[
'maxjetflavor']) != 5)
or (
'pdgs_for_merging_cut' in mydict
and '5' not in mydict[
'pdgs_for_merging_cut']):
2533 mglog.warning(
'b and b~ included in p and j for 5-flavor scheme but run card settings are inconsistent; adjusting run card')
2534 run_card_updates = {
'asrwgtflavor': 5,
'maxjetflavor': 5,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 5, 21'}
2535 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2536 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'0.000000e+00'}})
2538 mglog.debug(
'Consistent 5-flavor scheme setup detected.')
2539 if FS_updates[
'asrwgtflavor'] == 4:
2541 if (
'asrwgtflavor' in mydict
and int(mydict[
'asrwgtflavor']) != 4)
or (
'maxjetflavor' in mydict
and int(mydict[
'maxjetflavor']) != 4)
or (
'pdgs_for_merging_cut' in mydict
and '5' in mydict[
'pdgs_for_merging_cut']):
2543 mglog.warning(
'b and b~ not included in p and j (4-flavor scheme) but run card settings are inconsistent; adjusting run card')
2544 run_card_updates = {
'asrwgtflavor': 4,
'maxjetflavor': 4,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 21'}
2545 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2546 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'4.700000e+00'}})
2548 mglog.debug(
'Consistent 4-flavor scheme setup detected.')
2551 if FS_updates[
'asrwgtflavor'] == 4:
2553 mglog.warning(
'Flavor scheme setup is missing, adding by hand according to process card - b and b~ not included in p and j, 4-flavor scheme setup will be used; adjusting run card.')
2554 run_card_updates = {
'asrwgtflavor': 4,
'maxjetflavor': 4,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 21'}
2555 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2556 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'4.700000e+00'}})
2557 elif FS_updates[
'asrwgtflavor'] == 5:
2558 mglog.warning(
'Flavor scheme setup is missing, adding by hand according to process card - b and b~ included in p and j, 5-flavor scheme setup will be used; adjusting run card.')
2559 run_card_updates = {
'asrwgtflavor': 5,
'maxjetflavor': 5,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 5, 21'}
2560 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2561 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'0.000000e+00'}})
2563 mglog.info(
'Finished checking run card - All OK!')
2566 mglog.info(
'Running reweighting module on existing events')
2567 if reweight_card
is not None:
2568 mglog.info(
'Copying new reweight card from '+reweight_card)
2569 shutil.move(reweight_card,process_dir+
'/Cards/reweight_card.dat')
2570 reweight_cmd=
'{}/bin/madevent reweight {} -f'.
format(process_dir,run_name)
2571 global MADGRAPH_CATCH_ERRORS
2572 reweight =
stack_subprocess([python]+reweight_cmd.split(),stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
2573 (out,err) = reweight.communicate()
2575 mglog.info(
'Finished reweighting')
2578 if 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
2579 mglog.info(
'Noticed that you have run with an athena MT-like whole-node setup. Will re-configure now to make sure that the remainder of the job runs serially.')
2581 if not hasattr(opts,
'nprocs'):
2582 mglog.warning(
'Did not see option!')
2585 mglog.debug(
str(opts))
2589 mglog.info(
'For your information, ls of '+directory+
':')
2590 mglog.info(
sorted( os.listdir( directory ) ) )
2593 import MadGraphControl.MadGraphSystematicsUtils
2597 makefile_fks=process_dir+
'/SubProcesses/makefile_fks_dir'
2598 mglog.info(
'Fixing '+makefile_fks)
2599 shutil.move(makefile_fks,makefile_fks+
'_orig')
2600 fin=
open(makefile_fks+
'_orig')
2601 fout=
open(makefile_fks,
'w')
2604 if 'FKSParams.mod' in line:
2605 fout.write(line.replace(
'FKSParams.mod',
'FKSParams.o'))
2607 elif edit
and 'driver_mintFO' in line:
2608 fout.write(
'driver_mintFO.o: weight_lines.o mint_module.o FKSParams.o\n')
2609 elif edit
and 'genps_fks.o' in line:
2610 fout.write(
'genps_fks.o: mint_module.o FKSParams.o\n')
2611 elif edit
and 'test_soft_col_limits' in line:
2613 fout.write(
'madfks_plot.o: mint_module.o\n')
2614 fout.write(
'cluster.o: weight_lines.o\n')