9 import os,time,subprocess,glob,re,sys
11 from MCJobOptionUtils.JOsupport
import check_reset_proc_number
12 from MCJobOptionUtils.LHAPDFsupport
import get_LHAPDF_DATA_PATH
13 from MCJobOptionUtils.LHEsupport
import remap_lhe_pdgids
14 from MCJobOptionUtils.LHAPDFsupport
import get_lhapdf_id_and_name
15 from MCJobOptionUtils.LHAPDFsupport
import get_LHAPDF_PATHS
16 from AthenaCommon
import Logging
17 mglog = Logging.logging.getLogger(
'MadGraphUtils')
22 MADGRAPH_GRIDPACK_LOCATION=
'madevent'
24 MADGRAPH_RUN_NAME=
'run_01'
26 MADGRAPH_CATCH_ERRORS=
True
28 MADGRAPH_PDFSETTING=
None
29 MADGRAPH_COMMAND_STACK = []
31 patched_shutil_loc=
'/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest/shutil_patch'
32 if 'PYTHONPATH' in os.environ
and patched_shutil_loc
not in os.environ[
'PYTHONPATH']:
35 os.environ[
'PYTHONPATH'] = patched_shutil_loc+
':'+os.environ[
'PYTHONPATH']
36 MADGRAPH_COMMAND_STACK += [
'export PYTHONPATH='+patched_shutil_loc+
':${PYTHONPATH}']
38 if 'shutil' in sys.modules:
39 sys.modules.pop(
'shutil')
41 sys.path.insert(0,patched_shutil_loc)
44 from MadGraphControl.MadGraphUtilsHelpers
import checkSettingExists,checkSetting,checkSettingIsTrue,getDictFromCard,get_runArgs_info,get_physics_short,is_version_or_newer
45 from MadGraphControl.MadGraphParamHelpers
import do_PMG_updates,check_PMG_updates
48 global MADGRAPH_COMMAND_STACK
49 MADGRAPH_COMMAND_STACK += [
' '.
join(command)]
50 return subprocess.Popen(command,**kwargs)
55 global MADGRAPH_COMMAND_STACK
56 if 'PYTHONPATH' in os.environ:
57 if not any( [(
'Generators/madgraph/models' in x
and 'shutil_patch' not in x)
for x
in os.environ[
'PYTHONPATH'].
split(
':') ]):
58 os.environ[
'PYTHONPATH'] +=
':/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest'
59 MADGRAPH_COMMAND_STACK += [
'export PYTHONPATH=${PYTHONPATH}:/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest']
61 if 'GFORTRAN_TMPDIR' in os.environ:
63 if 'TMPDIR' in os.environ:
64 os.environ[
'GFORTRAN_TMPDIR']=os.environ[
'TMPDIR']
65 MADGRAPH_COMMAND_STACK += [
'export GFORTRAN_TMPDIR=${TMPDIR}']
67 if 'TMP' in os.environ:
68 os.environ[
'GFORTRAN_TMPDIR']=os.environ[
'TMP']
69 MADGRAPH_COMMAND_STACK += [
'export GFORTRAN_TMPDIR=${TMP}']
74 global MADGRAPH_COMMAND_STACK
75 if not os.access(
'Cards_bkup',os.R_OK):
76 shutil.copytree(process_dir+
'/Cards',
'Cards_bkup')
77 shutil.copyfile(process_dir+
'/Source/make_opts',
'Cards_bkup/make_opts_bkup')
78 MADGRAPH_COMMAND_STACK += [
'# In case this fails, Cards_bkup should be in your original run directory']
79 MADGRAPH_COMMAND_STACK += [
'# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
80 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup/*dat ${MGaMC_PROCESS_DIR}/Cards/']
81 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
83 mglog.warning(
'Found Cards_bkup directory existing. Suggests you are either running generation twice (a little funny) or are not using a clean directory.')
85 while os.access(
'Cards_bkup_'+
str(bkup_v),os.R_OK)
and bkup_v<100:
88 shutil.copytree(process_dir+
'/Cards',
'Cards_bkup_'+
str(bkup_v))
89 shutil.copyfile(process_dir+
'/Source/make_opts',
'Cards_bkup_'+
str(bkup_v)+
'/make_opts_bkup')
90 MADGRAPH_COMMAND_STACK += [
'# In case this fails, Cards_bkup should be in your original run directory']
91 MADGRAPH_COMMAND_STACK += [
'# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
92 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup_'+
str(bkup_v)+
'/*dat ${MGaMC_PROCESS_DIR}/Cards/']
93 MADGRAPH_COMMAND_STACK += [
'cp '+os.getcwd()+
'/Cards_bkup_'+
str(bkup_v)+
'/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
95 mglog.warning(
'Way too many Cards_bkup* directories found. Giving up -- standalone script may not work.')
99 global MADGRAPH_CATCH_ERRORS
100 if not MADGRAPH_CATCH_ERRORS:
102 unmasked_error =
False
107 if type(errors)==bytes:
108 errors = errors.decode(
'utf-8')
110 mglog.info(
'Some errors detected by MadGraphControl - checking for serious errors')
111 for err
in errors.split(
'\n'):
112 if len(err.strip())==0:
115 if 'Inappropriate ioctl for device' in err:
118 if 'stty: standard input: Invalid argument' in err:
122 if 'PDF already installed' in err:
125 if 'Read-only file system' in err:
132 if 'impossible to set default multiparticles' in err:
136 if 'More information is found in' in err:
137 my_debug_file = err.split(
"'")[1]
138 if err.startswith(
'tar'):
141 if 'python2 support will be removed' in err:
145 if 'required by /lib64/libfontconfig.so' in err
or\
146 'required by /lib64/libgs.so' in err:
149 if 'Error: Symbol' in err
and 'has no IMPLICIT type' in err:
150 bad_variables += [ err.split(
'Symbol ')[1].
split(
' at ')[0] ]
156 unmasked_error =
True
158 if my_debug_file
is None:
159 debug_files = glob.glob(
'*debug.log')+glob.glob(
'*/*debug.log')
160 for debug_file
in debug_files:
162 has_subproc = os.access(os.path.join(os.path.dirname(debug_file),
'SubProcesses'),os.R_OK)
164 my_debug_file = debug_file
167 if my_debug_file
is not None:
168 if not unmasked_error:
169 mglog.warning(
'Found a debug file at '+my_debug_file+
' but no apparent error. Will terminate.')
170 mglog.error(
'MadGraph5_aMC@NLO appears to have crashed. Debug file output follows.')
171 with open(my_debug_file,
'r')
as error_output:
172 for l
in error_output:
173 mglog.error(l.replace(
'\n',
''))
174 mglog.error(
'End of debug file output')
177 mglog.warning(
'Appeared to detect variables in your run card that MadGraph did not understand:')
178 mglog.warning(
' Check your run card / JO settings for %s',bad_variables)
182 mglog.error(f
'Detected a bad return code: {return_code}')
183 unmasked_error =
True
186 if unmasked_error
or my_debug_file
is not None:
188 raise RuntimeError(
'Error detected in MadGraphControl process')
194 mglog.info(
'Will write a stand-alone debugging script.')
195 mglog.info(
'This is an attempt to provide you commands that you can use')
196 mglog.info(
'to reproduce the error locally. If you make additional')
197 mglog.info(
'modifications by hand (not using MadGraphControl) in your JO,')
198 mglog.info(
'make sure that you check and modify the script as needed.\n\n')
199 global MADGRAPH_COMMAND_STACK
200 mglog.info(
'# Script start; trim off columns left of the "#"')
202 with open(
'standalone_script.sh',
'w')
as standalone_script:
203 for command
in MADGRAPH_COMMAND_STACK:
204 for line
in command.split(
'\n'):
206 standalone_script.write(line+
'\n')
207 mglog.info(
'# Script end')
208 mglog.info(
'Script also written to %s/standalone_script.sh',os.getcwd())
211 def new_process(process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False):
212 """ Generate a new process in madgraph.
213 Pass a process string.
214 Optionally request JPEGs to be kept and request for PMG settings to be used in the param card
215 Return the name of the process directory.
220 return MADGRAPH_GRIDPACK_LOCATION
223 card_loc=
'proc_card_mg5.dat'
224 mglog.info(
'Writing process card to '+card_loc)
225 a_card =
open( card_loc ,
'w' )
226 for l
in process.split(
'\n'):
227 if 'output' not in l:
229 elif '-nojpeg' in l
or keepJpegs:
232 a_card.write(l.split(
'#')[0]+
' -nojpeg #'+l.split(
'#')[1]+
'\n')
234 a_card.write(l+
' -nojpeg\n')
237 madpath=os.environ[
'MADPATH']
243 for l
in process.split(
'\n'):
245 if 'output' not in l.split(
'#')[0].
split():
248 tmplist = l.split(
'#')[0].
split(
' -')[0]
250 if len(tmplist.split())==2:
251 process_dir = tmplist.split()[1]
253 elif len(tmplist.split())==3:
254 process_dir = tmplist.split()[2]
257 mglog.info(
'Saw that you asked for a special output directory: '+
str(process_dir))
260 mglog.info(
'Started process generation at '+
str(time.asctime()))
262 plugin_cmd =
'--mode='+plugin
if plugin
is not None else ''
265 global MADGRAPH_COMMAND_STACK
266 MADGRAPH_COMMAND_STACK += [
'# All jobs should start in a clean directory']
267 MADGRAPH_COMMAND_STACK += [
'mkdir standalone_test; cd standalone_test']
268 MADGRAPH_COMMAND_STACK += [
' '.
join([python,madpath+
'/bin/mg5_aMC '+plugin_cmd+
' << EOF\n'+process+
'\nEOF\n'])]
269 global MADGRAPH_CATCH_ERRORS
270 generate = subprocess.Popen([python,madpath+
'/bin/mg5_aMC',plugin_cmd,card_loc],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
271 (out,err) = generate.communicate()
274 mglog.info(
'Finished process generation at '+
str(time.asctime()))
277 if process_dir ==
'':
278 for adir
in sorted(glob.glob( os.getcwd()+
'/*PROC*' ),reverse=
True):
279 if os.access(
'%s/SubProcesses/subproc.mg'%adir,os.R_OK):
283 mglog.warning(
'Additional possible process directory, '+adir+
' found. Had '+process_dir)
284 mglog.warning(
'Likely this is because you did not run from a clean directory, and this may cause errors later.')
286 if not os.access(
'%s/SubProcesses/subproc.mg'%process_dir,os.R_OK):
287 raise RuntimeError(
'No diagrams for this process in user-define dir='+
str(process_dir))
289 raise RuntimeError(
'No diagrams for this process from list: '+
str(
sorted(glob.glob(os.getcwd()+
'/*PROC*'),reverse=
True)))
292 needed_options = [
'ninja',
'collier',
'fastjet',
'lhapdf',
'syscalc_path']
293 in_config =
open(os.environ[
'MADPATH']+
'/input/mg5_configuration.txt',
'r')
295 for l
in in_config.readlines():
296 for o
in needed_options:
297 if o+
' =' in l.split(
'#')[0]
and 'MCGenerators' in l.split(
'#')[0]:
298 old_path = l.split(
'#')[0].
split(
'=')[1].strip().
split(
'MCGenerators')[1]
299 old_path = old_path[ old_path.find(
'/') : ]
300 if o ==
'lhapdf' and 'LHAPATH' in os.environ:
302 version = os.environ[
'LHAPATH'].
split(
'lhapdf/')[1].
split(
'/')[0]
303 old_version = old_path.split(
'lhapdf/')[1].
split(
'/')[0]
304 old_path = old_path.replace(old_version,version)
307 old_path.replace(
'gosam_contrib',
'gosam-contrib')
308 option_paths[o] = os.environ[
'MADPATH'].
split(
'madgraph5amc')[0]+old_path
310 if o+
' =' in l
and o+
' =' not in l.split(
'#')[0]:
311 mglog.info(
'Option '+o+
' appears commented out in the config file')
314 for o
in needed_options:
315 if o
not in option_paths:
316 mglog.info(
'Path for option '+o+
' not found in original config')
318 mglog.info(
'Modifying config paths to avoid use of afs:')
319 mglog.info(option_paths)
331 mglog.info(
'Setting default sde_strategy to old default (1)')
332 my_settings = {
'sde_strategy':1}
333 modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=
True)
336 MADGRAPH_COMMAND_STACK += [
'export MGaMC_PROCESS_DIR='+os.path.basename(process_dir)]
342 """ Copy the default runcard from one of several locations
343 to a local file with name run_card.tmp.dat"""
344 output_name =
'run_card.tmp.dat'
347 run_card=process_dir+
'/Cards/run_card.dat'
348 if os.access(run_card,os.R_OK):
349 mglog.info(
'Copying default run_card.dat from '+
str(run_card))
350 shutil.copy(run_card,output_name)
353 run_card=process_dir+
'/Cards/run_card_default.dat'
354 mglog.info(
'Fetching default run_card.dat from '+
str(run_card))
355 if os.access(run_card,os.R_OK):
356 shutil.copy(run_card,output_name)
359 raise RuntimeError(
'Cannot find default run_card.dat or run_card_default.dat! I was looking here: %s'%run_card)
362 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):
370 if 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
371 njobs =
int(os.environ[
'ATHENA_CORE_NUMBER'])
372 mglog.info(
'Lucky you - you are running on a full node queue. Will re-configure for '+
str(njobs)+
' jobs.')
376 if cluster_type
is not None:
380 mglog.info(
'Running event generation from gridpack (using smarter mode from generate() function)')
381 generate_from_gridpack(runArgs=runArgs,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings)
384 mglog.info(
'Did not identify an input gridpack.')
386 mglog.info(
'The grid_pack flag is set, so I am expecting to create a gridpack in this job')
400 from distutils.spawn
import find_executable
401 if find_executable(
'f2py')
is not None:
402 mglog.info(
'Found f2py, will use it for reweighting')
404 raise RuntimeError(
'Could not find f2py, needed for reweighting')
407 global MADGRAPH_COMMAND_STACK
411 mglog.info(
'Started generating gridpack at '+
str(time.asctime()))
412 mglog.warning(
' >>>>>> THIS KIND OF JOB SHOULD ONLY BE RUN LOCALLY - NOT IN GRID JOBS <<<<<<')
415 my_settings = {
'nevents':
'1000'}
417 my_settings[
'req_acc']=
str(required_accuracy)
420 LO_has_madspin =
False
421 if os.access(f
'{process_dir}/Cards/madspin_card.dat',os.R_OK):
422 MADGRAPH_COMMAND_STACK += [f
'mv {process_dir}/Cards/madspin_card.dat {process_dir}/Cards/madspin_card.tmp.dat']
423 os.rename(f
'{process_dir}/Cards/madspin_card.dat',f
'{process_dir}/Cards/madspin_card.tmp.dat')
424 LO_has_madspin =
True
425 my_settings = {
'gridpack':
'true'}
426 modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=
True)
430 mglog.info(
'Started generating at '+
str(time.asctime()))
432 mglog.info(
'Run '+MADGRAPH_RUN_NAME+
' will be performed in mode '+
str(mode)+
' with '+
str(njobs)+
' jobs in parallel.')
435 if not os.access(process_dir,os.R_OK):
436 raise RuntimeError(
'No process directory found at '+process_dir)
437 if not os.access(process_dir+
'/bin/generate_events',os.R_OK):
438 raise RuntimeError(
'No generate_events module found in '+process_dir)
440 mglog.info(
'For your information, the libraries available are (should include LHAPDF):')
441 ls_dir(process_dir+
'/lib')
444 if bias_module
is not None:
447 mglog.info(
'Now I will hack the make files a bit. Apologies, but there seems to be no good way around this.')
448 shutil.copyfile(process_dir+
'/Source/make_opts',process_dir+
'/Source/make_opts_old')
449 old_opts =
open(process_dir+
'/Source/make_opts_old',
'r')
450 new_opts =
open(process_dir+
'/Source/make_opts',
'w')
451 for aline
in old_opts:
453 mglog.info(
'Configuring the fancy gfortran compiler instead of g77 / f77')
454 new_opts.write(
' FC=gfortran\n')
456 new_opts.write(aline)
459 mglog.info(
'Make file hacking complete.')
463 os.chdir(process_dir)
465 MADGRAPH_COMMAND_STACK += [
'cd ${MGaMC_PROCESS_DIR}' ]
475 if requirePMGSettings
and code!=0:
476 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
480 command = [python,
'bin/generate_events']
482 command += [
'--name='+MADGRAPH_RUN_NAME]
483 mglog.info(
'Removing Cards/shower_card.dat to ensure we get parton level events only')
484 os.unlink(
'Cards/shower_card.dat')
486 command += [MADGRAPH_RUN_NAME]
488 setNCores(process_dir=os.getcwd(), Ncores=njobs)
491 mglog.info(
'Setting up cluster running')
493 if cluster_type==
'pbs':
494 mglog.info(
'Modifying bin/internal/cluster.py for PBS cluster running')
495 os.system(
"sed -i \"s:text += prog:text += './'+prog:g\" bin/internal/cluster.py")
497 mglog.info(
'Setting up multi-core running on '+os.environ[
'ATHENA_CORE_NUMBER']+
' cores')
499 mglog.info(
'Setting up serial generation.')
502 global MADGRAPH_CATCH_ERRORS
503 generate =
stack_subprocess(command,stdin=subprocess.PIPE, stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
504 (out,err) = generate.communicate()
509 MADGRAPH_COMMAND_STACK += [
'cd -' ]
513 energy =
'%1.1f'%(beamEnergy*2./1000.)
514 energy = energy.replace(
'.0',
'').
replace(
'.',
'p')
516 mglog.info(
'Tidying up gridpack '+gridpack_name)
521 MADGRAPH_COMMAND_STACK += [f
'mv {process_dir}/Cards/madspin_card.tmp.dat {process_dir}/Cards/madspin_card.dat']
522 os.rename(f
'{process_dir}/Cards/madspin_card.tmp.dat',f
'{process_dir}/Cards/madspin_card.dat')
525 MADGRAPH_COMMAND_STACK += [
'cp '+glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0]+
' '+gridpack_name]
526 shutil.copy(glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0],gridpack_name)
529 MADGRAPH_COMMAND_STACK += [
'mkdir tmp%i/'%os.getpid(),
'cd tmp%i/'%os.getpid()]
530 os.mkdir(
'tmp%i/'%os.getpid())
531 os.chdir(
'tmp%i/'%os.getpid())
532 mglog.info(
'untar gridpack')
535 mglog.info(
'compile and clean up')
536 MADGRAPH_COMMAND_STACK += [
'cd madevent']
537 os.chdir(
'madevent/')
538 compilep =
stack_subprocess([
'./bin/compile'],stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
539 (out,err) = compilep.communicate()
541 clean =
stack_subprocess([
'./bin/clean4grid'],stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
542 (out,err) = clean.communicate()
545 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm ../'+gridpack_name]
547 mglog.info(
'remove old tarball')
548 os.unlink(
'../'+gridpack_name)
549 mglog.info(
'Package up new tarball')
550 tar =
stack_subprocess([
'tar',
'--exclude=SubProcesses/P*/G*/*_results.dat',
'--exclude=SubProcesses/P*/G*/*.log',
'--exclude=SubProcesses/P*/G*/*.txt',
'-cvsf',
'../'+gridpack_name,
'.'])
552 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm -r tmp%i/'%os.getpid()]
554 mglog.info(
'Remove temporary directory')
555 shutil.rmtree(
'tmp%i/'%os.getpid())
556 mglog.info(
'Tidying up complete!')
561 mglog.info(
'Package up process_dir')
562 MADGRAPH_COMMAND_STACK += [
'mv '+process_dir+
' '+MADGRAPH_GRIDPACK_LOCATION]
563 os.rename(process_dir,MADGRAPH_GRIDPACK_LOCATION)
564 tar =
stack_subprocess([
'tar',
'--exclude=Events/*/*events*gz',
'--exclude=SubProcesses/P*/G*/log*txt',
'--exclude=SubProcesses/P*/G*/events.lhe*',
'--exclude=*/*.o',
'--exclude=*/*/*.o',
'--exclude=*/*/*/*.o',
'--exclude=*/*/*/*/*.o',
'-czf',gridpack_name,MADGRAPH_GRIDPACK_LOCATION])
566 MADGRAPH_COMMAND_STACK += [
'mv '+MADGRAPH_GRIDPACK_LOCATION+
' '+process_dir]
567 os.rename(MADGRAPH_GRIDPACK_LOCATION,process_dir)
569 mglog.info(
'Gridpack sucessfully created, exiting the transform')
570 if hasattr(runArgs,
'outputTXTFile'):
571 mglog.info(
'Touching output TXT (LHE) file for the transform')
572 open(runArgs.outputTXTFile,
'w').close()
573 from AthenaCommon.AppMgr
import theApp
577 mglog.info(
'Finished at '+
str(time.asctime()))
589 isNLO=
is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION)
594 gridpack_run_name =
'GridRun_'+
str(random_seed)
597 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',os.R_OK):
598 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat')
608 if requirePMGSettings
and code!=0:
609 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
612 settings={
'iseed':
str(random_seed)}
614 settings[
'python_seed']=
str(random_seed)
615 modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings=settings,skipBaseFragment=
True)
617 mglog.info(
'Generating events from gridpack')
620 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION):
621 raise RuntimeError(
'Gridpack directory not found at '+MADGRAPH_GRIDPACK_LOCATION)
623 nevents =
getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/run_card.dat')[
'nevents']
624 mglog.info(
'>>>> FOUND GRIDPACK <<<< <- This will be used for generation')
625 mglog.info(
'Generation of '+
str(
int(nevents))+
' events will be performed using the supplied gridpack with random seed '+
str(random_seed))
626 mglog.info(
'Started generating events at '+
str(time.asctime()))
629 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py',os.R_OK):
630 os.remove(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py')
635 setNCores(process_dir=MADGRAPH_GRIDPACK_LOCATION)
636 global MADGRAPH_CATCH_ERRORS
640 ls_dir(MADGRAPH_GRIDPACK_LOCATION)
650 run_card_dict=
getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/run_card.dat')
651 systematics_settings=
None
652 if checkSetting(
'systematics_program',
'systematics',run_card_dict):
654 raise RuntimeError(
'Trying to run NLO systematics but reweight info not stored')
656 systematics_settings=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(run_card_dict[
'systematics_arguments'])
658 systematics_settings={}
659 mglog.info(
'Turning off systematics for now, running standalone later')
660 modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={
'systematics_program':
'none'},skipBaseFragment=
True)
662 global MADGRAPH_COMMAND_STACK
665 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun',os.R_OK):
666 mglog.error(
'/bin/gridrun not found at '+MADGRAPH_GRIDPACK_LOCATION)
667 raise RuntimeError(
'Could not find gridrun executable')
669 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun, starting generation.')
672 mglog.info(
"Now generating {} events with random seed {} and granularity {}".
format(
int(nevents),
int(random_seed),granularity))
674 new_ld_path=
":".
join([os.environ[
'LD_LIBRARY_PATH'],os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/madevent/lib',os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/HELAS/lib'])
675 os.environ[
'LD_LIBRARY_PATH']=new_ld_path
676 MADGRAPH_COMMAND_STACK+=[
"export LD_LIBRARY_PATH="+
":".
join([
'${LD_LIBRARY_PATH}',new_ld_path])]
677 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)
678 (out,err) = generate.communicate()
680 gp_events=MADGRAPH_GRIDPACK_LOCATION+
"/Events/GridRun_{}/unweighted_events.lhe.gz".
format(
int(random_seed))
681 if not os.path.exists(gp_events):
682 mglog.error(
'Error in gp generation, did not find events at '+gp_events)
686 if reweight_card
is not None:
687 pythonpath_backup=os.environ[
'PYTHONPATH']
689 os.environ[
'PYTHONPATH']=
':'.
join([p
for p
in pythonpath_backup.split(
':')
if 'madgraph5amc' not in p])
691 os.environ[
'PYTHONPATH']=pythonpath_backup
693 shutil.move(gp_events,
'events.lhe.gz')
697 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events',os.R_OK):
698 raise RuntimeError(
'Could not find generate_events executable at '+MADGRAPH_GRIDPACK_LOCATION)
700 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events, starting generation.')
702 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
703 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name, os.F_OK):
704 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
' directory from gridpack generation')
705 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name]
706 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)
709 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1', os.F_OK):
710 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1 directory from gridpack generation')
711 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1']
712 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1')
714 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
716 if not gridpack_compile:
717 mglog.info(
'Copying make_opts from Template')
718 shutil.copy(os.environ[
'MADPATH']+
'/Template/LO/Source/make_opts',MADGRAPH_GRIDPACK_LOCATION+
'/Source/')
721 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)
722 (out,err) = generate.communicate()
725 mglog.info(
'Allowing recompilation of gridpack')
726 if os.path.islink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a'):
727 mglog.info(
'Unlinking '+MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
728 os.unlink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
731 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)
732 (out,err) = generate.communicate()
734 if isNLO
and systematics_settings
is not None:
736 mglog.info(
'Running systematics standalone')
737 systematics_path=MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/systematics.py'
738 events_location=MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz'
739 syst_cmd=[python,systematics_path]+[events_location]*2+[
"--"+k+
"="+systematics_settings[k]
for k
in systematics_settings]
740 mglog.info(
'running: '+
' '.
join(syst_cmd))
746 if not os.access(
'events.lhe.gz',os.R_OK):
747 mglog.info(
'Copying generated events to '+currdir)
748 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION+
'Events/'+gridpack_run_name):
749 shutil.copy(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz',
'events.lhe.gz')
751 mglog.info(
'Events were already in place')
755 mglog.info(
'Moving generated events to be in correct format for arrange_output().')
756 mglog.info(
'Unzipping generated events.')
760 mglog.info(
'Moving file over to '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
761 mkdir =
stack_subprocess([
'mkdir',
'-p',(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)])
763 shutil.move(
'events.lhe',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
765 mglog.info(
'Re-zipping into dataset name '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe.gz')
766 rezip =
stack_subprocess([
'gzip',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe'])
774 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat')
775 mglog.info(
'Decaying with MadSpin.')
776 add_madspin(process_dir=MADGRAPH_GRIDPACK_LOCATION)
778 mglog.info(
'Finished at '+
str(time.asctime()))
787 mglog.info(
'Path to fastjet install dir: '+os.environ[
'FASTJETPATH'])
788 fastjetconfig = os.environ[
'FASTJETPATH']+
'/bin/fastjet-config'
790 mglog.info(
'fastjet-config --version: '+
str(subprocess.Popen([fastjetconfig,
'--version'],stdout = subprocess.PIPE).stdout.read().strip()))
791 mglog.info(
'fastjet-config --prefix: '+
str(subprocess.Popen([fastjetconfig,
'--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
794 config_card=process_dir+
'/Cards/me5_configuration.txt'
796 config_card=process_dir+
'/Cards/amcatnlo_configuration.txt'
798 oldcard =
open(config_card,
'r')
799 newcard =
open(config_card+
'.tmp',
'w')
802 if 'fastjet = ' in line:
803 newcard.write(
'fastjet = '+fastjetconfig+
'\n')
804 mglog.info(
'Setting fastjet = '+fastjetconfig+
' in '+config_card)
809 shutil.move(config_card+
'.tmp',config_card)
815 def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
819 origLHAPATH=os.environ[
'LHAPATH']
820 origLHAPDF_DATA_PATH=os.environ[
'LHAPDF_DATA_PATH']
828 run_card=process_dir+
'/Cards/run_card.dat'
831 if mydict[
"pdlabel"].
replace(
"'",
"") ==
'lhapdf':
833 mglog.info(
'creating local LHAPDF dir: MGC_LHAPDF/')
834 if os.path.islink(
'MGC_LHAPDF/'):
835 os.unlink(
'MGC_LHAPDF/')
836 elif os.path.isdir(
'MGC_LHAPDF/'):
837 shutil.rmtree(
'MGC_LHAPDF/')
839 newMGCLHA=
'MGC_LHAPDF/'
841 mkdir = subprocess.Popen([
'mkdir',
'-p',newMGCLHA])
844 pdfs_used=[
int(x)
for x
in mydict[
'lhaid'].
replace(
' ',
',').
split(
',') ]
846 if 'sys_pdf' in mydict:
852 pdfs_used.append(idx)
855 if 'systematics_arguments' in mydict:
856 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict[
'systematics_arguments'])
857 if 'pdf' in systematics_arguments:
863 pdfs_used.append(idx)
866 for pdf
in pdfs_used:
867 if isinstance(pdf,str)
and (pdf.lower()==
'errorset' or pdf.lower()==
'central'):
871 mglog.info(
"Found LHAPDF ID="+
str(pdfid)+
", name="+pdfname)
873 if not os.path.exists(newMGCLHA+pdfname)
and not os.path.lexists(newMGCLHA+pdfname):
874 if not os.path.exists(LHADATAPATH+
'/'+pdfname):
875 mglog.warning(
'PDF not installed at '+LHADATAPATH+
'/'+pdfname)
877 mglog.info(
'linking '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
878 os.symlink(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
880 mglog.info(
'copying '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
881 shutil.copytree(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
884 mglog.info(
'linking '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
885 os.symlink(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
887 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
888 mglog.info(
'linking '+atlasLHADATAPATH+
'/lhapdf.conf --> '+newMGCLHA+
'lhapdf.conf')
889 os.symlink(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
891 mglog.info(
'copying '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
892 shutil.copy2(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
894 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
895 mglog.info(
'copying '+atlasLHADATAPATH+
'/lhapdf.conf -->'+newMGCLHA+
'lhapdf.conf')
896 shutil.copy2(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
899 LHADATAPATH=os.getcwd()+
'/MGC_LHAPDF'
902 mglog.info(
'Not using LHAPDF')
903 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
907 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
909 mglog.info(
'Path to LHAPDF install dir: '+LHAPATH)
910 mglog.info(
'Path to LHAPDF data dir: '+LHADATAPATH)
911 if not os.path.isdir(LHADATAPATH):
912 raise RuntimeError(
'LHAPDF data dir not accesible: '+LHADATAPATH)
913 if not os.path.isdir(LHAPATH):
914 raise RuntimeError(
'LHAPDF path dir not accesible: '+LHAPATH)
918 lhapdfconfig=extlhapath
919 if not os.access(lhapdfconfig,os.X_OK):
920 raise RuntimeError(
'Failed to find valid external lhapdf-config at '+lhapdfconfig)
921 LHADATAPATH=subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().strip()
922 mglog.info(
'Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
923 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
925 getlhaconfig = subprocess.Popen([
'get_files',
'-data',
'lhapdf-config'])
928 if not os.access(os.getcwd()+
'/lhapdf-config',os.X_OK):
929 mglog.error(
'Failed to get lhapdf-config from MadGraphControl')
931 lhapdfconfig = os.getcwd()+
'/lhapdf-config'
933 mglog.info(
'lhapdf-config --version: '+
str(subprocess.Popen([lhapdfconfig,
'--version'],stdout = subprocess.PIPE).stdout.read().strip()))
934 mglog.info(
'lhapdf-config --prefix: '+
str(subprocess.Popen([lhapdfconfig,
'--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
935 mglog.info(
'lhapdf-config --libdir: '+
str(subprocess.Popen([lhapdfconfig,
'--libdir'],stdout = subprocess.PIPE).stdout.read().strip()))
936 mglog.info(
'lhapdf-config --datadir: '+
str(subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().strip()))
937 mglog.info(
'lhapdf-config --pdfsets-path: '+
str(subprocess.Popen([lhapdfconfig,
'--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().strip()))
939 modify_config_card(process_dir=process_dir,settings={
'lhapdf':lhapdfconfig,
'lhapdf_py3':lhapdfconfig})
941 mglog.info(
'Creating links for LHAPDF')
942 if os.path.islink(process_dir+
'/lib/PDFsets'):
943 os.unlink(process_dir+
'/lib/PDFsets')
944 elif os.path.isdir(process_dir+
'/lib/PDFsets'):
945 shutil.rmtree(process_dir+
'/lib/PDFsets')
947 os.symlink(LHADATAPATH,process_dir+
'/lib/PDFsets')
949 shutil.copytree(LHADATAPATH,process_dir+
'/lib/PDFsets')
950 mglog.info(
'Available PDFs are:')
951 mglog.info(
sorted( [ x
for x
in os.listdir(process_dir+
'/lib/PDFsets')
if ".tar.gz" not in x ] ) )
953 global MADGRAPH_COMMAND_STACK
954 MADGRAPH_COMMAND_STACK += [
'# Copy the LHAPDF files locally' ]
955 MADGRAPH_COMMAND_STACK += [
'cp -r '+os.getcwd()+
'/MGC_LHAPDF .' ]
956 MADGRAPH_COMMAND_STACK += [
'cp -r '+process_dir+
'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
958 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
964 my_runMode = 2
if 'ATHENA_CORE_NUMBER' in os.environ
else 0
965 if Ncores
is None and 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
966 my_Ncores =
int(os.environ[
'ATHENA_CORE_NUMBER'])
968 if my_Ncores
is None:
969 mglog.info(
'Setting up for serial run')
972 modify_config_card(process_dir=process_dir,settings={
'nb_core':my_Ncores,
'run_mode':my_runMode,
'automatic_html_opening':
'False'})
981 madpath=os.environ[
'MADPATH']
982 if not os.access(madpath+
'/bin/mg5_aMC',os.R_OK):
983 raise RuntimeError(
'mg5_aMC executable not found in '+madpath)
984 return madpath+
'/bin/mg5_aMC'
988 """ Add lifetimes to the generated LHE file. Should be
989 called after generate_events is called.
994 if len(glob.glob(process_dir+
'/Events/*'))<1:
995 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
996 run = glob.glob(process_dir+
'/Events/*')[0].
split(
'/')[-1]
1001 tof_c =
open(
'time_of_flight_exec_card',
'w')
1002 tof_c.write(
'launch '+process_dir+
''' -i
1003 add_time_of_flight '''+run+((
' --threshold='+
str(threshold))
if threshold
is not None else ''))
1006 mglog.info(
'Started adding time of flight info '+
str(time.asctime()))
1008 global MADGRAPH_CATCH_ERRORS
1009 generate =
stack_subprocess([python,me_exec,
'time_of_flight_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
1010 (out,err) = generate.communicate()
1013 mglog.info(
'Finished adding time of flight information at '+
str(time.asctime()))
1016 lhe_gz = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1017 if not os.access(lhe_gz,os.R_OK):
1018 mglog.info(
'LHE file needs to be zipped')
1019 lhe = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1022 mglog.info(
'Zipped')
1024 mglog.info(
'LHE file zipped by MadGraph automatically. Nothing to do')
1029 def add_madspin(madspin_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
1030 """ Run madspin on the generated LHE file. Should be
1031 run when you have inputGeneratorFile set.
1032 Only requires a simplified process with the same model that you are
1033 interested in (needed to set up a process directory for MG5_aMC)
1038 if madspin_card
is not None:
1039 shutil.copyfile(madspin_card,process_dir+
'/Cards/madspin_card.dat')
1041 if len(glob.glob(process_dir+
'/Events/*'))<1:
1042 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
1043 proc_dir_list = glob.glob(process_dir+
'/Events/*')
1045 for adir
in proc_dir_list:
1046 if 'GridRun_' in adir:
1047 run=adir.split(
'/')[-1]
1050 run=proc_dir_list[0].
split(
'/')[-1]
1055 ms_c =
open(
'madspin_exec_card',
'w')
1056 ms_c.write(
'launch '+process_dir+
''' -i
1057 decay_events '''+run)
1060 mglog.info(
'Started running madspin at '+
str(time.asctime()))
1062 global MADGRAPH_CATCH_ERRORS
1063 generate =
stack_subprocess([python,me_exec,
'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
1064 (out,err) = generate.communicate()
1066 if len(glob.glob(process_dir+
'/Events/'+run+
'_decayed_*/')) == 0:
1067 mglog.error(
'No '+process_dir+
'/Events/'+run+
'_decayed_*/ can be found')
1068 raise RuntimeError(
'Problem while running MadSpin')
1070 mglog.info(
'Finished running madspin at '+
str(time.asctime()))
1073 lhe_gz = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1074 if not os.access(lhe_gz,os.R_OK):
1075 mglog.info(
'LHE file needs to be zipped')
1076 lhe = glob.glob(process_dir+
'/Events/*/*lhe.gz')[0]
1079 mglog.info(
'Zipped')
1081 mglog.info(
'LHE file zipped by MadGraph automatically. Nothing to do')
1085 """ Run MadSpin on an input LHE file. Takes the process
1086 from the LHE file, so you don't need to have a process directory
1087 set up in advance. Runs MadSpin and packs the LHE file up appropriately
1088 Needs runArgs for the file handling"""
1089 if not os.access(input_LHE,os.R_OK):
1090 raise RuntimeError(
'Could not find LHE file '+input_LHE)
1091 if not os.access(madspin_card,os.R_OK):
1092 raise RuntimeError(
'Could not find input MadSpin card '+madspin_card)
1094 shutil.copy(input_LHE,input_LHE+
'.original')
1095 mglog.info(
'Put backup copy of LHE file at '+input_LHE+
'.original')
1097 madspin_exec_card =
open(
'madspin_exec_card',
'w')
1098 madspin_exec_card.write(
'import '+input_LHE+
'\n')
1100 input_madspin_card =
open(madspin_card,
'r')
1102 for l
in input_madspin_card.readlines():
1103 commands = l.split(
'#')[0].
split()
1105 if len(commands)>1
and 'import'==commands[0]
and not 'model'==commands[1]:
1108 if len(commands)>0
and 'launch' == commands[0]:
1110 madspin_exec_card.write(l.strip()+
'\n')
1112 madspin_exec_card.write(
'launch\n')
1113 madspin_exec_card.close()
1114 input_madspin_card.close()
1116 madpath=os.environ[
'MADPATH']
1117 if not os.access(madpath+
'/MadSpin/madspin',os.R_OK):
1118 raise RuntimeError(
'madspin executable not found in '+madpath)
1119 mglog.info(
'Starting madspin at '+
str(time.asctime()))
1120 global MADGRAPH_CATCH_ERRORS
1121 generate =
stack_subprocess([python,madpath+
'/MadSpin/madspin',
'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
1122 (out,err) = generate.communicate()
1124 mglog.info(
'Done with madspin at '+
str(time.asctime()))
1128 if os.path.exists(os.getcwd()+
'/events.lhe'):
1129 os.remove(os.getcwd()+
'/events.lhe')
1131 mglog.info(
'Unzipping generated events.')
1135 mglog.info(
'Putting a copy in place for the transform.')
1136 mod_output =
open(os.getcwd()+
'/events.lhe',
'w')
1140 with open(input_LHE,
'r')
as fileobject:
1141 for line
in fileobject:
1143 mod_output.write(line)
1148 mglog.info(
'Removed '+
str(nEmpty)+
' empty lines from LHEF')
1152 raise RuntimeError(
'Must provide runArgs to madspin_on_lhe')
1154 outputDS = runArgs.outputTXTFile
if hasattr(runArgs,
'outputTXTFile')
else 'tmp_LHE_events.tar.gz'
1156 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
1157 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
1159 mglog.info(
'Re-zipping into dataset name '+outputDS)
1160 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
1164 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1165 outputDS = outputDS.split(
'.TXT')[0]
1167 if runArgs
is not None:
1168 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1169 runArgs.inputGeneratorFile=outputDS
1172 def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
1177 if len(glob.glob(os.path.join(process_dir,
'Events',
'*')))<1:
1178 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
1179 proc_dir_list = glob.glob(os.path.join(process_dir,
'Events',
'*'))
1182 for adir
in proc_dir_list:
1183 if 'decayed' in adir:
1186 if 'GridRun_' in adir:
1189 elif os.path.join(process_dir,
'Events',MADGRAPH_RUN_NAME)
in adir:
1191 if not os.access(this_run_name,os.R_OK):
1192 raise RuntimeError(
'Unable to locate run directory')
1194 hasUnweighted = os.access(this_run_name+
'/unweighted_events.lhe.gz',os.R_OK)
1197 madspinDirs=
sorted(glob.glob(this_run_name+
'_decayed_*/'))
1198 if len(madspinDirs):
1200 if hasRunMadSpin
and not hasUnweighted:
1202 hasUnweighted = os.access(madspinDirs[-1]+
'/unweighted_events.lhe.gz',os.R_OK)
1204 global MADGRAPH_COMMAND_STACK
1206 if len(madspinDirs):
1213 if os.path.exists(madspinDirs[-1]+
'/unweighted_events.lhe.gz'):
1214 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/unweighted_events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
1215 shutil.move(madspinDirs[-1]+
'/unweighted_events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
1216 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/unweighted_events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1217 elif os.path.exists(madspinDirs[-1]+
'/events.lhe.gz'):
1218 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
1219 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
1220 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1222 raise RuntimeError(
'MadSpin was run but can\'t find files :(')
1225 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz '+this_run_name+
'/events.lhe.gz']
1226 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/events.lhe.gz')
1227 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/events.lhe.gz')
1230 mglog.error(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1231 raise RuntimeError(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1233 if fixEventWeightsForBridgeMode:
1234 mglog.info(
"Fixing event weights after MadSpin... initial checks.")
1242 eventsfilename=
"unweighted_events"
1244 eventsfilename=
"events"
1245 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/%s.lhe.gz' % eventsfilename])
1248 for line
in open(process_dir+
'/Events/'+MADGRAPH_RUN_NAME+
'/%s.lhe'%eventsfilename):
1249 if "Number of Events" in line:
1251 MGnumevents=
int(sline[-1])
1252 elif "Integrated weight (pb)" in line:
1254 MGintweight=
float(sline[-1])
1255 elif "set spinmode none" in line:
1257 elif "</header>" in line:
1260 if spinmodenone
and MGnumevents>0
and MGintweight>0:
1261 mglog.info(
"Fixing event weights after MadSpin... modifying LHE file.")
1262 newlhe=
open(this_run_name+
'/%s_fixXS.lhe'%eventsfilename,
'w')
1270 event_norm_setting=
"average"
1272 for line
in open(this_run_name+
'/%s.lhe'%eventsfilename):
1275 if "<init>" in line:
1278 elif "</init>" in line:
1280 elif inInit
and initlinecount==0:
1284 if abs(
int(sline[-2])) == 3:
1285 event_norm_setting=
"sum"
1286 elif abs(
int(sline[-2])) == 4:
1287 event_norm_setting=
"average"
1288 elif inInit
and initlinecount==1:
1292 sline[0]=
str(MGintweight)
1293 sline[1]=
str(
float(sline[0])*relunc)
1294 if event_norm_setting==
"sum":
1295 sline[2]=
str(MGintweight/MGnumevents)
1296 elif event_norm_setting==
"average":
1297 sline[2]=
str(MGintweight)
1298 newline=
' '.
join(sline)
1301 elif inInit
and initlinecount>1:
1303 elif "<event>" in line:
1306 elif "</event>" in line:
1308 elif inEvent
and eventlinecount==0:
1311 if event_norm_setting==
"sum":
1312 sline[2]=
str(MGintweight/MGnumevents)
1313 elif event_norm_setting==
"average":
1314 sline[2]=
str(MGintweight)
1315 newline=
' '.
join(sline)
1318 newlhe.write(newline)
1321 mglog.info(
"Fixing event weights after MadSpin... cleaning up.")
1322 shutil.copyfile(this_run_name+
'/%s.lhe' % eventsfilename,
1323 this_run_name+
'/%s_badXS.lhe' % eventsfilename)
1325 shutil.move(this_run_name+
'/%s_fixXS.lhe' % eventsfilename,
1326 this_run_name+
'/%s.lhe' % eventsfilename)
1328 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s.lhe' % eventsfilename])
1331 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s_badXS.lhe' % eventsfilename])
1335 if os.path.exists(os.getcwd()+
'/events.lhe'):
1336 os.remove(os.getcwd()+
'/events.lhe')
1338 mglog.info(
'Unzipping generated events.')
1340 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/unweighted_events.lhe.gz'])
1346 mglog.info(
'Putting a copy in place for the transform.')
1348 orig_input = this_run_name+
'/unweighted_events.lhe'
1349 mod_output =
open(os.getcwd()+
'/events.lhe',
'w')
1351 orig_input = this_run_name+
'/events.lhe'
1352 mod_output =
open(os.getcwd()+
'/events.lhe',
'w')
1359 with open(orig_input,
'r')
as fileobject:
1360 for line
in fileobject:
1364 if '#' not in newline:
1366 elif '>' not in newline[ newline.find(
'#'): ]:
1369 mglog.info(
'Found bad LHE line with an XML mark in a comment: "'+newline.strip()+
'"')
1370 newline=newline[:newline.find(
'#')]+
'#'+ (newline[newline.find(
'#'):].
replace(
'>',
'-'))
1372 if initrwgt
is False:
1374 elif "</initrwgt>" in newline:
1376 elif "<initrwgt>" in newline:
1378 elif initrwgt
is not None:
1379 newline=newline.replace(
'_DYNSCALE-1',
'')
1380 if '</weight>' in newline:
1381 iend=newline.find(
'</weight>')
1382 istart=newline[:iend].rfind(
'>')
1383 lhe_weights+=[newline[istart+1:iend].strip()]
1384 mod_output.write(newline)
1388 mglog.info(
'Removed '+
str(nEmpty)+
' empty lines from LHEF')
1390 mglog.info(
"The following "+
str(len(lhe_weights))+
" weights have been written to the LHE file: "+
",".
join(lhe_weights))
1393 mglog.info(
"Checking whether the following expected weights are in LHE file: "+
",".
join(expected_weights))
1394 for w
in expected_weights:
1395 if w
not in lhe_weights:
1396 raise RuntimeError(
"Did not find expected weight "+w+
" in lhe file. Did the reweight or systematics module crash?")
1397 mglog.info(
"Found all required weights!")
1400 mod_output2 =
open(os.getcwd()+
'/events.lhe',
'r')
1401 test=mod_output2.readline()
1402 if 'version="' in test:
1403 mglog.info(
'Applying LHE version hack')
1404 final_file =
open(os.getcwd()+
'/events.lhe.copy',
'w')
1405 final_file.write(
'<LesHouchesEvents version="%i.0">\n'%lhe_version)
1406 shutil.copyfileobj(mod_output2, final_file)
1408 shutil.copy(os.getcwd()+
'/events.lhe.copy',os.getcwd()+
'/events.lhe')
1410 os.remove(os.getcwd()+
'/events.lhe.copy')
1415 raise RuntimeError(
'Must provide runArgs to arrange_output')
1417 if hasattr(runArgs,
'outputTXTFile'):
1418 outputDS = runArgs.outputTXTFile
1420 outputDS =
'tmp_LHE_events.tar.gz'
1422 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
1424 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
1426 mglog.info(
'Re-zipping into dataset name '+outputDS)
1427 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
1431 mglog.info(
'Removing the process directory')
1432 shutil.rmtree(process_dir,ignore_errors=
True)
1434 if os.path.isdir(
'MGC_LHAPDF/'):
1435 shutil.rmtree(
'MGC_LHAPDF/',ignore_errors=
True)
1438 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1439 outputDS = outputDS.split(
'.TXT')[0]
1441 if runArgs
is not None:
1442 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1443 runArgs.inputGeneratorFile=outputDS
1445 mglog.info(
'All done with output arranging!')
1449 if reweight_card_loc
is None:
1452 f_rw=
open(reweight_card_loc)
1454 if 'launch' not in line:
1456 match=re.match(
r'launch.*--rwgt_info\s*=\s*(\S+).*',line.strip())
1457 if len(match.groups())!=1:
1458 raise RuntimeError(
'Unexpected format of reweight card in line'+line)
1460 names+=[match.group(1)]
1466 if syst_setting
is None or 'central_pdf' not in syst_setting:
1467 mglog.warning(
"Systematics have not been defined via base fragment or 'MADGRAPH_PDFSETTING', cannot check for expected weights")
1469 if 'pdf_variations' in syst_setting
and isinstance(syst_setting[
'pdf_variations'],list):
1470 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':1.0,
'muf':1.0,
'pdf':syst_setting[
'central_pdf']}]
1471 for pdf
in syst_setting[
'pdf_variations']:
1472 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':1.0,
'muf':1.0,
'pdf':pdf+1}]
1473 if 'alternative_pdfs' in syst_setting
and isinstance(syst_setting[
'alternative_pdfs'],list):
1474 for pdf
in syst_setting[
'alternative_pdfs']:
1475 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':1.0,
'muf':1.0,
'pdf':pdf}]
1476 if 'scale_variations' in syst_setting
and isinstance(syst_setting[
'scale_variations'],list):
1477 for mur
in syst_setting[
'scale_variations']:
1478 for muf
in syst_setting[
'scale_variations']:
1479 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{
'mur':mur,
'muf':muf,
'pdf':syst_setting[
'central_pdf']}]
1483 run_card = process_dir+
'/Cards/run_card.dat'
1484 if isinstance(bias_module,tuple):
1485 mglog.info(
'Using bias module '+bias_module[0])
1486 the_run_card =
open(run_card,
'r')
1487 for line
in the_run_card:
1488 if 'bias_module' in line
and not bias_module[0]
in line:
1489 raise RuntimeError(
'You need to add the bias module '+bias_module[0]+
' to the run card to actually run it')
1490 the_run_card.close()
1491 if len(bias_module)!=3:
1492 raise RuntimeError(
'Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1493 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module[0]
1494 os.makedirs(bias_module_newpath)
1495 bias_module_file=
open(bias_module_newpath+
'/'+bias_module[0]+
'.f',
'w')
1496 bias_module_file.write(bias_module[1])
1497 bias_module_file.close()
1498 bias_module_make_file=
open(bias_module_newpath+
'/Makefile',
'w')
1499 bias_module_make_file.write(bias_module[2])
1500 bias_module_make_file.close()
1502 mglog.info(
'Using bias module '+bias_module)
1503 bias_module_name=bias_module.split(
'/')[-1].
replace(
'.gz',
'')
1504 bias_module_name=bias_module_name.replace(
'.tar',
'')
1505 the_run_card =
open(run_card,
'r')
1506 for line
in the_run_card:
1507 if 'bias_module' in line
and bias_module_name
not in line:
1508 raise RuntimeError(
'You need to add the bias module '+bias_module_name+
' to the run card to actually run it')
1509 the_run_card.close()
1511 if os.path.exists(bias_module+
'.tar.gz'):
1512 bias_module_path=bias_module+
'.tar.gz'
1513 elif os.path.exists(bias_module+
'.gz'):
1514 bias_module_path=bias_module+
'.gz'
1515 elif os.path.exists(bias_module):
1516 bias_module_path=bias_module
1518 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')
1520 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module_path.split(
'/')[-1]
1521 mglog.info(
'Copying bias module into place: '+bias_module_newpath)
1522 shutil.copy(bias_module_path,bias_module_newpath)
1523 mglog.info(
'Unpacking bias module')
1524 if bias_module_newpath.endswith(
'.tar.gz'):
1525 untar =
stack_subprocess([
'tar',
'xvzf',bias_module_newpath,
'--directory='+process_dir+
'/Source/BIAS/'])
1527 elif bias_module_path.endswith(
'.gz'):
1533 if os.access(process_dir+
'/Cards/reweight_card.dat',os.R_OK):
1534 return process_dir+
'/Cards/reweight_card.dat'
1540 shutil.move(reweight_card,reweight_card+
'.old')
1541 oldcard =
open(reweight_card+
'.old',
'r')
1542 newcard =
open(reweight_card,
'w')
1544 info_expression=
r'launch.*--rwgt_info\s*=\s*(\S+).*'
1545 name_expression=info_expression.replace(
'info',
'name')
1546 goodname_expression=
r'^[A-Za-z0-9_\-.]+$'
1547 for line
in oldcard:
1549 if not line.strip().startswith(
'launch') :
1552 rwgt_name_match=re.match(name_expression,line.strip())
1553 rwgt_info_match=re.match(info_expression,line.strip())
1554 if rwgt_name_match
is None and rwgt_info_match
is None:
1555 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)
1556 for match
in [rwgt_info_match,rwgt_name_match]:
1559 if len(match.groups())!=1:
1560 raise RuntimeError(
'Unexpected format of reweight card in line: '+line)
1561 if not re.match(goodname_expression,match.group(1)):
1562 raise RuntimeError(
'No special character in reweighting info/name, only allowing '+goodname_expression)
1563 if rwgt_info_match
is not None:
1565 elif rwgt_name_match
is not None:
1566 newcard.write(line.strip()+
' --rwgt_info={0}\n'.
format(rwgt_name_match.group(1)))
1569 mglog.info(
'Updated reweight_card')
1576 # Define multiparticle labels
1577 define p = g u c d s u~ c~ d~ s~
1578 define j = g u c d s u~ c~ d~ s~
1579 define pb = g u c d s b u~ c~ d~ s~ b~
1580 define jb = g u c d s b u~ c~ d~ s~ b~
1583 define vl = ve vm vt
1584 define vl~ = ve~ vm~ vt~
1585 define fu = u c e+ mu+ ta+
1586 define fu~ = u~ c~ e- mu- ta-
1587 define fd = d s ve~ vm~ vt~
1588 define fd~ = d~ s~ ve vm vt
1589 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~
1590 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~
1591 define susylq = ul ur dl dr cl cr sl sr
1592 define susylq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~
1593 define susysq = ul ur dl dr cl cr sl sr t1 t2 b1 b2
1594 define susysq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~ t1~ t2~ b1~ b2~
1595 define susysl = el- el+ er- er+ mul- mul+ mur- mur+ ta1- ta1+ ta2- ta2+
1596 define susyv = sve svm svt
1597 define susyv~ = sve~ svm~ svt~
1603 if ktdurham
is None:
1605 if process
is not None:
1606 id_map = {
'go':
'1000021',
'dl':
'1000001',
'ul':
'1000002',
'sl':
'1000003',
'cl':
'1000004',
'b1':
'1000005',
't1':
'1000006',
1607 'dr':
'2000001',
'ur':
'2000002',
'sr':
'2000003',
'cr':
'2000004',
'b2':
'2000005',
't2':
'2000006',
1608 'n1':
'1000022',
'n2':
'1000023',
'x1':
'1000024',
'x2':
'1000037',
'n3':
'1000025',
'n4':
'1000035',
1609 'el':
'1000011',
'mul':
'1000013',
'ta1':
'1000015',
'sve':
'1000012',
'svm':
'1000014',
'svt':
'1000016',
1610 'er':
'2000011',
'mur':
'2000013',
'ta2':
'2000015'}
1612 if 'generate' in l
or 'add process' in l:
1614 for particle
in clean_proc.split():
1615 if particle
not in id_map:
1616 mglog.info(f
'Particle {particle} not found in PDG ID map - skipping')
1618 prod_particles += id_map[particle]
1622 if len(prod_particles)>0:
1623 for x
in prod_particles:
1625 my_mass =
min(my_mass,abs(
float(masses[x])))
1627 mglog.info(f
'Seem to ask for production of PDG ID {x}, but {x} not in mass dictionary?')
1629 strong_ids = [
'1000001',
'1000002',
'1000003',
'1000004',
'1000005',
'1000006',
'2000001',
'2000002',
'2000003',
'2000004',
'2000005',
'2000006',
'1000021']
1630 weak_ids = [
'1000023',
'1000024',
'1000025',
'1000011',
'1000013',
'1000015',
'2000011',
'2000013',
'2000015',
'1000012',
'1000014',
'1000016']
1632 my_mass =
min([abs(
float(masses[x]))
for x
in strong_ids
if x
in masses])
1636 my_mass =
max([abs(
float(masses[x]))
for x
in weak_ids
if x
in masses
and float(masses[x])<10000.])
1638 if my_mass>10000.
and '1000022' in masses:
1639 my_mass = masses[
'1000022']
1641 raise RuntimeError(
'Could not understand which mass to use for matching cut in '+
str(masses))
1644 ktdurham =
min(my_mass*0.25,500)
1646 ktdurham =
max(ktdurham,15)
1647 if syst_mod
is not None and 'qup' in syst_mod.lower():
1648 ktdurham = ktdurham*2.
1649 elif syst_mod
is not None and 'qdown' in syst_mod.lower():
1650 ktdurham = ktdurham*0.5
1652 mglog.info(
'For matching, will use ktdurham of '+
str(ktdurham))
1656 if syst_mod
is not None and 'alpsfactup' in syst_mod.lower():
1658 elif syst_mod
is not None and 'alpsfactdown' in syst_mod.lower():
1661 if syst_mod
is not None and 'scalefactup' in syst_mod.lower():
1663 elif syst_mod
is not None and 'scalefactdown' in syst_mod.lower():
1666 return abs(ktdurham) , alpsfact , scalefact
1671 if 'import model' in process:
1672 mglog.info(
'Assuming that you have specified the model in your process string already')
1674 for l
in process.split(
'\n'):
1675 if 'import model' in l:
1679 if 'MSSM_SLHA2' in full_proc:
1681 for l
in process.split(
'\n'):
1682 if 'import model' not in l:
1685 # Output processes to MadEvent directory
1690 # Specify process(es) to run
1693 # Output processes to MadEvent directory
1700 syst_mod=None, keepOutput=False, param_card=None, writeGridpack=False,\
1701 madspin_card=None, run_settings={}, params={}, fixEventWeightsForBridgeMode=False, add_lifetimes_lhe=False, usePMGSettings=True):
1705 usePMGSettings (bool): See :py:func:`new_process`. Will set SM parameters to the appropriate values. Default: True.
1707 ktdurham = run_settings[
'ktdurham']
if 'ktdurham' in run_settings
else None
1708 ktdurham , alpsfact , scalefact =
get_SUSY_variations( process, params[
'MASS'] , syst_mod , ktdurham=ktdurham )
1710 process_dir = MADGRAPH_GRIDPACK_LOCATION
1713 process_dir =
new_process(full_proc, plugin=plugin, usePMGSettings=usePMGSettings)
1714 mglog.info(
'Using process directory '+
str(process_dir))
1717 modify_param_card(param_card_input=param_card,process_dir=process_dir,params=params)
1720 settings = {
'ktdurham':ktdurham,
'scalefact':scalefact,
'alpsfact':alpsfact}
1721 settings.update(run_settings)
1724 modify_run_card(process_dir=process_dir,runArgs=runArgs,settings=settings)
1727 if madspin_card
is not None:
1728 if not os.access(madspin_card,os.R_OK):
1729 raise RuntimeError(
'Could not locate madspin card at '+
str(madspin_card))
1730 shutil.copy(madspin_card,process_dir+
'/Cards/madspin_card.dat')
1737 generate(runArgs=runArgs,process_dir=process_dir,grid_pack=writeGridpack)
1740 if add_lifetimes_lhe :
1741 mglog.info(
'Requested addition of lifetimes to LHE files: doing so now.')
1748 arrange_output(process_dir=process_dir,saveProcDir=keepOutput,runArgs=runArgs,fixEventWeightsForBridgeMode=fixEventWeightsForBridgeMode)
1750 mglog.info(
'All done generating events!!')
1751 return settings[
'ktdurham']
1754 def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1755 """Build a new LHE file from an old one and an updated param card.
1756 The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1757 may have their masses changed.
1758 If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1759 By default, the old LHE file is removed.
1760 If None is provided as a new LHE file name, the new file will replace the old one."""
1762 lhe_file_new_tmp = lhe_file_new
if lhe_file_new
is not None else lhe_file_old+
'.tmp'
1764 if not os.access(lhe_file_old,os.R_OK):
1765 raise RuntimeError(
'Could not access old LHE file at '+
str(lhe_file_old)+
'. Please check the file location.')
1767 if param_card_old
is not None:
1768 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_old])
1770 if not os.access(param_card_old,os.R_OK):
1771 raise RuntimeError(
'Could not get param card '+param_card_old)
1773 if os.access(lhe_file_new_tmp,os.R_OK):
1774 raise RuntimeError(
'Old file at'+
str(lhe_file_new_tmp)+
' in the current directory. Dont want to clobber it. Please move it first.')
1776 newlhe =
open(lhe_file_new_tmp,
'w')
1780 particles_in_events = []
1783 with open(lhe_file_old,
'r')
as fileobject:
1784 for line
in fileobject:
1785 if decayEdit
and '</slha>' not in line:
1787 if decayEdit
and '</slha>' in line:
1789 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1790 and len(line.strip().
split()) > 1:
1791 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1792 blockName = line.strip().
upper().
split()[pos]
1795 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
1796 akey = line.strip().
split()[0]
1797 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
1798 akey = line.strip().
split()[1]
1801 if akey
is not None and blockName ==
'MASS' and akey
in masses:
1802 newlhe.write(
' '+akey+
' '+
str(masses[akey])+
' # \n')
1803 mglog.info(
' '+akey+
' '+
str(masses[akey])+
' #')
1808 if blockName ==
'DECAY' and param_card_old
is not None:
1810 oldparam =
open(param_card_old,
'r')
1812 for old_line
in oldparam.readlines():
1814 if old_line.strip().
upper().startswith(
'DECAY')
and len(old_line.strip().
split()) > 1:
1815 newBlockName = line.strip().
upper().
split()[pos]
1817 newlhe.write(old_line)
1818 elif newBlockName ==
'DECAY':
1820 newlhe.write(old_line)
1828 if not eventRead
and '<event>' in line:
1831 if len(line.split())==11:
1832 aparticle = line.split()[0]
1833 if aparticle
not in particles_in_events:
1834 particles_in_events += [aparticle]
1841 if akey
in particles_in_events:
1842 mglog.error(
'Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1849 if lhe_file_new
is None:
1850 os.remove(lhe_file_old)
1851 shutil.move(lhe_file_new_tmp,lhe_file_old)
1852 lhe_file_new_tmp = lhe_file_old
1854 elif delete_old_lhe:
1855 os.remove(lhe_file_old)
1857 return lhe_file_new_tmp
1862 """ Helper function when looking at param cards
1863 In some cases it's tricky to match keys - they may differ
1864 only in white space. This tries to sort out when we have
1865 a match, and then uses the one in blockParams afterwards.
1866 In the case of no match, it returns the original key.
1869 for key
in dictionary:
1871 if mod_key==test_key:
1876 def modify_param_card(param_card_input=None,param_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,params={},output_location=None):
1877 """Build a new param_card.dat from an existing one.
1878 Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
1879 Keys can include MASS (for masses) and DECAY X (for decays of particle X)"""
1883 if param_card_input
is None:
1884 param_card_input=process_dir+
'/Cards/param_card.dat'
1885 elif param_card_input
is not None and not os.access(param_card_input,os.R_OK):
1886 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_input])
1888 if not os.access(param_card_input,os.R_OK):
1889 raise RuntimeError(
'Could not get param card '+param_card_input)
1890 mglog.info(
'Using input param card at '+param_card_input)
1894 for blockName
in list(params.keys()):
1895 paramsUpper[blockName.upper()] = {}
1896 for paramName
in list(params[blockName].
keys()):
1897 paramsUpper[blockName.upper()][paramName.upper()] = params[blockName][paramName]
1899 if param_card_backup
is not None:
1900 mglog.info(
'Keeping backup of original param card at '+param_card_backup)
1901 param_card_old = param_card_backup
1903 param_card_old = param_card_input+
'.old_to_be_deleted'
1904 if os.path.isfile(param_card_old):
1905 os.unlink(param_card_old)
1906 os.rename(param_card_input, param_card_old)
1908 oldcard =
open(param_card_old,
'r')
1909 param_card_location= process_dir+
'/Cards/param_card.dat' if output_location
is None else output_location
1910 newcard =
open(param_card_location,
'w')
1914 for linewithcomment
in oldcard:
1915 line=linewithcomment.split(
'#')[0]
1916 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1917 and len(line.strip().
split()) > 1:
1918 if decayEdit
and blockName ==
'DECAY':
1920 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1921 if blockName==
'MASS' and 'MASS' in paramsUpper:
1923 if "MASS" in doneParams:
1924 leftOvers = [ x
for x
in paramsUpper[
'MASS']
if x
not in doneParams[
'MASS'] ]
1926 leftOvers = [ x
for x
in paramsUpper[
'MASS'] ]
1928 for pdg_id
in leftOvers:
1929 mglog.warning(
'Adding mass line for '+
str(pdg_id)+
' = '+
str(paramsUpper[
'MASS'][pdg_id])+
' which was not in original param card')
1930 newcard.write(
' '+
str(pdg_id)+
' '+
str(paramsUpper[
'MASS'][pdg_id])+
'\n')
1931 doneParams[
'MASS'][pdg_id]=
True
1932 if blockName==
'DECAY' and 'DECAY' not in line.strip().
upper()
and 'DECAY' in paramsUpper:
1934 leftOvers = [ x
for x
in paramsUpper[
'DECAY']
if x
not in doneParams[
'DECAY'] ]
1935 for pdg_id
in leftOvers:
1936 mglog.warning(
'Adding decay for pdg id '+
str(pdg_id)+
' which was not in the original param card')
1937 newcard.write( paramsUpper[
'DECAY'][pdg_id].strip()+
'\n' )
1938 doneParams[
'DECAY'][pdg_id]=
True
1939 blockName = line.strip().
upper().
split()[pos]
1944 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
1947 if len(line.split())==2:
1948 akey = line.upper().strip().
split()[0]
1951 akey = line.upper().strip()[:line.strip().rfind(
' ')].strip()
1952 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
1953 akey = line.strip().
split()[1]
1955 newcard.write(linewithcomment)
1959 if blockName
not in paramsUpper:
1960 newcard.write(linewithcomment)
1962 blockParams = paramsUpper[blockName]
1968 if '#' in linewithcomment:
1969 stringkey = linewithcomment[linewithcomment.find(
'#')+1:].strip()
1970 if len(stringkey.split()) > 0:
1971 stringkey = stringkey.split()[0].
upper()
1973 if akey
not in blockParams
and not (stringkey
is not None and stringkey
in blockParams):
1974 newcard.write(linewithcomment)
1977 if akey
in blockParams
and (stringkey
is not None and stringkey
in blockParams):
1978 raise RuntimeError(
'Conflicting use of numeric and string keys '+akey+
' and '+stringkey)
1980 theParam = blockParams.get(akey,blockParams[stringkey]
if stringkey
in blockParams
else None)
1981 if blockName
not in doneParams:
1982 doneParams[blockName] = {}
1983 if akey
in blockParams:
1984 doneParams[blockName][akey]=
True
1985 elif stringkey
is not None and stringkey
in blockParams:
1986 doneParams[blockName][stringkey]=
True
1989 if blockName==
"DECAY":
1990 if theParam.splitlines()[0].
split()[0].
upper()==
"DECAY":
1992 for newline
in theParam.splitlines():
1993 newcard.write(newline+
'\n')
1997 newcard.write(
'DECAY '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
1998 mglog.info(
'DECAY '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2000 elif blockName==
'QNUMBERS':
2002 for newline
in theParam.splitlines():
2003 newcard.write(newline+
'\n')
2007 newcard.write(
' '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2008 mglog.info(
' '+akey+
' '+
str(theParam)+
' # '+(linewithcomment[linewithcomment.find(
'#')+1:].strip()
if linewithcomment.find(
'#')>0
else "")+
'\n')
2012 for blockName
in paramsUpper:
2013 if blockName
not in doneParams
and len(paramsUpper[blockName].
keys())>0:
2014 raise RuntimeError(
'Did not find any of the parameters for block '+blockName+
' in param_card')
2015 for paramName
in paramsUpper[blockName]:
2016 if paramName
not in doneParams[blockName]:
2017 raise RuntimeError(
'Was not able to replace parameter '+paramName+
' in param_card')
2024 def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
2025 """Build a new run_card.dat from an existing one.
2026 This function can get a fresh runcard from DATAPATH or start from the process directory.
2027 Settings is a dictionary of keys (no spaces needed) and values to replace.
2032 for s
in list(settings.keys()):
2033 settings_lower[s.lower()] = settings[s]
2036 if run_card_input
is None:
2038 elif run_card_input
is not None and not os.access(run_card_input,os.R_OK):
2039 runcard = subprocess.Popen([
'get_files',
'-data',run_card_input])
2041 if not os.access(run_card_input,os.R_OK):
2042 raise RuntimeError(
'Could not get run card '+run_card_input)
2047 if not skipBaseFragment:
2048 MadGraphControl.MadGraphSystematicsUtils.setup_pdf_and_systematic_weights(MADGRAPH_PDFSETTING,settings_lower,isNLO)
2051 if runArgs
is not None:
2053 if 'iseed' not in settings_lower:
2054 settings_lower[
'iseed']=rand_seed
2055 if not isNLO
and 'python_seed' not in settings_lower:
2056 settings_lower[
'python_seed']=rand_seed
2057 if 'beamenergy' in settings_lower:
2058 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']))
2059 beamEnergy=settings_lower[
'beamenergy']
2060 settings_lower.pop(
'beamenergy')
2061 if 'ebeam1' not in settings_lower:
2062 settings_lower[
'ebeam1']=beamEnergy
2063 if 'ebeam2' not in settings_lower:
2064 settings_lower[
'ebeam2']=beamEnergy
2066 if 'nevents' in settings_lower:
2067 settings_lower[
'nevents'] =
int(settings_lower[
'nevents'])
2069 mglog.info(
'Modifying run card located at '+run_card_input)
2070 if run_card_backup
is not None:
2071 mglog.info(
'Keeping backup of original run card at '+run_card_backup)
2072 run_card_old = run_card_backup
2074 run_card_old = run_card_input+
'.old_to_be_deleted'
2075 mglog.debug(
'Modifying runcard settings: '+
str(settings_lower))
2076 if os.path.isfile(run_card_old):
2077 os.unlink(run_card_old)
2078 os.rename(run_card_input, run_card_old)
2080 oldCard =
open(run_card_old,
'r')
2081 newCard =
open(process_dir+
'/Cards/run_card.dat',
'w')
2083 for line
in iter(oldCard):
2084 if not line.strip().startswith(
'#'):
2085 command = line.split(
'!', 1)[0]
2086 comment = line.split(
'!', 1)[1]
if '!' in line
else ''
2088 setting = command.split(
'=')[-1]
2089 stripped_setting = setting.strip()
2090 oldValue =
'='.
join(command.split(
'=')[:-1])
2091 if stripped_setting.lower()
in settings_lower:
2093 if settings_lower[stripped_setting.lower()]
is None:
2095 mglog.info(
'Removing '+stripped_setting+
'.')
2096 used_settings += [ stripped_setting.lower() ]
2098 line = oldValue.replace(oldValue.strip(),
str(settings_lower[stripped_setting.lower()]))+
'='+setting
2100 line +=
' !' + comment
2101 mglog.info(
'Setting '+stripped_setting+
' = '+
str(settings_lower[stripped_setting.lower()]))
2102 used_settings += [ stripped_setting.lower() ]
2103 newCard.write(line.strip()+
'\n')
2106 if 'mcatnlo_delta' in settings_lower:
2107 if settings_lower[
'mcatnlo_delta'] ==
'True':
2108 modify_config_card(process_dir=process_dir,settings={
'pythia8_path':os.getenv(
"PY8PATH")})
2111 for asetting
in settings_lower:
2112 if asetting
in used_settings:
2114 if settings_lower[asetting]
is None:
2116 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]) )
2117 newCard.write(
' '+
str(settings_lower[asetting])+
' = '+
str(asetting)+
'\n')
2121 mglog.info(
'Finished modification of run card.')
2122 if run_card_backup
is None:
2123 os.unlink(run_card_old)
2126 def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
2127 """Build a new configuration from an existing one.
2128 This function can get a fresh runcard from DATAPATH or start from the process directory.
2129 Settings is a dictionary of keys (no spaces needed) and values to replace.
2135 mglog.info(
'Modifying config card located at '+config_card)
2136 if config_card_backup
is not None:
2137 mglog.info(
'Keeping backup of original config card at '+config_card_backup)
2138 config_card_old = config_card_backup
2140 config_card_old = config_card+
'.old_to_be_deleted'
2141 mglog.debug(
'Modifying config card settings: '+
str(settings))
2142 if os.path.isfile(config_card_old):
2143 os.unlink(config_card_old)
2144 os.rename(config_card, config_card_old)
2146 oldCard =
open(config_card_old,
'r')
2147 newCard =
open(config_card,
'w')
2149 for line
in iter(oldCard):
2150 lmod = line
if set_commented
else line.split(
'#')[0]
2153 for setting
in settings:
2154 if setting
not in lmod:
2157 mglog.info(
'Setting '+setting.strip()+
' to '+
str(settings[setting]))
2158 newCard.write(
' '+
str(setting.strip())+
' = '+
str(settings[setting])+
'\n')
2159 used_settings += [ setting.strip() ]
2167 for asetting
in settings:
2168 if asetting
in used_settings:
2170 if settings[asetting]
is None:
2172 mglog.warning(
'Option '+asetting+
' was not in the default config card. Adding by hand a setting to '+
str(settings[asetting]) )
2173 newCard.write(
' '+
str(asetting)+
' = '+
str(settings[asetting])+
'\n')
2177 mglog.info(
'Finished modification of config card.')
2178 if config_card_backup
is None:
2179 os.unlink(config_card_old)
2183 card_dir=process_dir+
'/Cards/'
2184 print_cards(proc_card=card_dir+
'proc_card_mg5.dat',run_card=card_dir+
'run_card.dat',param_card=card_dir+
'param_card.dat',\
2185 madspin_card=card_dir+
'madspin_card.dat',reweight_card=card_dir+
'reweight_card.dat',warn_on_missing=
False)
2188 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):
2189 if os.access(proc_card,os.R_OK):
2190 mglog.info(
"proc_card:")
2191 procCard = subprocess.Popen([
'cat',proc_card])
2193 elif warn_on_missing:
2194 mglog.warning(
'No proc_card: '+proc_card+
' found')
2196 if run_card
is not None and os.access(run_card,os.R_OK):
2197 mglog.info(
"run_card:")
2198 runCard = subprocess.Popen([
'cat',run_card])
2200 elif run_card
is not None and warn_on_missing:
2201 mglog.warning(
'No run_card: '+run_card+
' found')
2203 mglog.info(
'Default run card in use')
2205 if param_card
is not None and os.access(param_card,os.R_OK):
2206 mglog.info(
"param_card:")
2207 paramCard = subprocess.Popen([
'cat',param_card])
2209 elif param_card
is not None and warn_on_missing:
2210 mglog.warning(
'No param_card: '+param_card+
' found')
2212 mglog.info(
'Default param card in use')
2214 if madspin_card
is not None and os.access(madspin_card,os.R_OK):
2215 mglog.info(
"madspin_card:")
2216 madspinCard = subprocess.Popen([
'cat',madspin_card])
2218 elif madspin_card
is not None and warn_on_missing:
2219 mglog.warning(
'No madspin_card: '+madspin_card+
' found')
2221 mglog.info(
'No madspin card in use')
2223 if reweight_card
is not None and os.access(reweight_card,os.R_OK):
2224 mglog.info(
"reweight_card:")
2225 madspinCard = subprocess.Popen([
'cat',reweight_card])
2227 elif reweight_card
is not None and warn_on_missing:
2228 mglog.warning(
'No reweight_card: '+reweight_card+
' found')
2230 mglog.info(
'No reweight card in use')
2234 """ Simple function for checking if there is a grid pack.
2235 Relies on the specific location of the unpacked gridpack (madevent)
2236 which is here set as a global variable. The gridpack is untarred by
2237 the transform (Gen_tf.py) and no sign is sent to the job itself
2238 that there is a gridpack in use except the file's existence"""
2239 if os.access(MADGRAPH_GRIDPACK_LOCATION,os.R_OK):
2240 mglog.info(
'Located input grid pack area')
2247 lo_config_card=process_dir+
'/Cards/me5_configuration.txt'
2248 nlo_config_card=process_dir+
'/Cards/amcatnlo_configuration.txt'
2250 if os.access(lo_config_card,os.R_OK)
and not os.access(nlo_config_card,os.R_OK):
2251 return lo_config_card
2252 elif os.access(nlo_config_card,os.R_OK)
and not os.access(lo_config_card,os.R_OK):
2253 return nlo_config_card
2254 elif os.access(nlo_config_card,os.R_OK)
and os.access(lo_config_card,os.R_OK):
2255 mglog.error(
'Found both types of config card in '+process_dir)
2257 mglog.error(
'No config card in '+process_dir)
2258 raise RuntimeError(
'Unable to locate configuration card')
2263 for l
in card_in.readlines():
2264 if 'cluster_type' not in l.split(
'#')[0]:
2266 cluster_type = l.split(
'#')[0].
split(
'=')[1]
2267 mglog.info(
'Returning cluster type: '+cluster_type)
2278 cardpath=process_dir+
'/Cards/run_card.dat'
2284 modify_run_card(process_dir=process_dir,settings={
'event_norm':
'average'},skipBaseFragment=
True)
2285 mglog.warning(
"setting event_norm to average, there is basically no use case where event_norm=sum is a good idea")
2289 if 'ktdurham' in mydict
and float(mydict[
'ktdurham']) > 0
and int(mydict[
'ickkw']) != 0:
2290 log=
'Bad combination of settings for CKKW-L merging! ktdurham=%s and ickkw=%s.'%(mydict[
'ktdurham'],mydict[
'ickkw'])
2292 raise RuntimeError(log)
2295 if 'systematics_program' not in mydict
or mydict[
'systematics_program']==
'systematics':
2296 syscalc_settings=[
'sys_pdf',
'sys_scalefact',
'sys_alpsfact',
'sys_matchscale']
2297 found_syscalc_setting=
False
2298 for s
in syscalc_settings:
2300 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)')
2301 found_syscalc_setting=
True
2302 if found_syscalc_setting:
2303 syst_arguments=MadGraphControl.MadGraphSystematicsUtils.convertSysCalcArguments(mydict)
2304 mglog.info(
'Converted syscalc arguments to systematics arguments: '+syst_arguments)
2305 syst_settings_update={
'systematics_arguments':syst_arguments}
2306 for s
in syscalc_settings:
2307 syst_settings_update[s]=
None
2308 modify_run_card(process_dir=process_dir,settings=syst_settings_update,skipBaseFragment=
True)
2313 mglog.info(
'Checking PDF and systematics settings')
2314 if not MadGraphControl.MadGraphSystematicsUtils.base_fragment_setup_check(MADGRAPH_PDFSETTING,mydict,isNLO):
2316 syst_settings=MadGraphControl.MadGraphSystematicsUtils.get_pdf_and_systematic_settings(MADGRAPH_PDFSETTING,isNLO)
2317 modify_run_card(process_dir=process_dir,settings=syst_settings,skipBaseFragment=
True)
2320 if 'systematics_arguments' in mydict_new:
2321 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict_new[
'systematics_arguments'])
2322 if 'weight_info' not in systematics_arguments:
2323 mglog.info(
'Enforcing systematic weight name convention')
2325 if '--dyn' in systematics_arguments
or ' dyn' in systematics_arguments:
2326 if '--dyn' in systematics_arguments:
2327 dyn = systematics_arguments.split(
'--dyn')[1]
2328 if ' dyn' in systematics_arguments:
2329 dyn = systematics_arguments.split(
' dyn')[1]
2330 dyn = dyn.replace(
'\'',
' ').
replace(
'=',
' ').
split()[0]
2331 if dyn
is not None and len(dyn.split(
','))>1:
2332 systematics_arguments[
'weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO_ALTDYNSCALES
2334 systematics_arguments[
'weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO
2335 modify_run_card(process_dir=process_dir,settings={
'systematics_arguments':MadGraphControl.MadGraphSystematicsUtils.write_systematics_arguments(systematics_arguments)},skipBaseFragment=
True)
2338 if 'python_seed' not in mydict:
2339 mglog.warning(
'No python seed set in run_card -- adding one with same value as iseed')
2340 modify_run_card(process_dir=process_dir,settings={
'python_seed':mydict[
'iseed']},skipBaseFragment=
True)
2344 proton_5flav =
False
2346 with open(process_dir+
'/Cards/proc_card_mg5.dat',
'r')
as file:
2347 content = file.readlines()
2348 for rawline
in content:
2349 line = rawline.split(
'#')[0]
2350 if line.startswith(
"define p"):
2351 if 'b' in line.split()
and 'b~' in line.split():
2353 if 'j' in line.split()
and jet_5flav:
2355 if line.startswith(
"define j"):
2356 if 'b' in line.split()
and 'b~' in line.split():
2358 if 'p' in line.split()
and proton_5flav:
2360 if proton_5flav
or jet_5flav:
2361 FS_updates[
'asrwgtflavor'] = 5
2362 if not proton_5flav:
2363 mglog.warning(
'Found 5-flavour jets but 4-flavour proton. This is inconsistent - please pick one.')
2364 mglog.warning(
'Will proceed assuming 5-flavour scheme.')
2366 mglog.warning(
'Found 5-flavour protons but 4-flavour jets. This is inconsistent - please pick one.')
2367 mglog.warning(
'Will proceed assuming 5-flavour scheme.')
2369 FS_updates[
'asrwgtflavor'] = 4
2371 if len(FS_updates)==0:
2372 mglog.warning(f
'Could not identify 4- or 5-flavor scheme from process card {process_dir}/Cards/proc_card_mg5.dat')
2374 if 'asrwgtflavor' in mydict
or 'maxjetflavor' in mydict
or 'pdgs_for_merging_cut' in mydict:
2375 if FS_updates[
'asrwgtflavor'] == 5:
2377 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']):
2379 mglog.warning(
'b and b~ included in p and j for 5-flavor scheme but run card settings are inconsistent; adjusting run card')
2380 run_card_updates = {
'asrwgtflavor': 5,
'maxjetflavor': 5,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 5, 21'}
2381 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2382 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'0.000000e+00'}})
2384 mglog.debug(
'Consistent 5-flavor scheme setup detected.')
2385 if FS_updates[
'asrwgtflavor'] == 4:
2387 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']):
2389 mglog.warning(
'b and b~ not included in p and j (4-flavor scheme) but run card settings are inconsistent; adjusting run card')
2390 run_card_updates = {
'asrwgtflavor': 4,
'maxjetflavor': 4,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 21'}
2391 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2392 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'4.700000e+00'}})
2394 mglog.debug(
'Consistent 4-flavor scheme setup detected.')
2397 if FS_updates[
'asrwgtflavor'] == 4:
2399 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.')
2400 run_card_updates = {
'asrwgtflavor': 4,
'maxjetflavor': 4,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 21'}
2401 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2402 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'4.700000e+00'}})
2403 elif FS_updates[
'asrwgtflavor'] == 5:
2404 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.')
2405 run_card_updates = {
'asrwgtflavor': 5,
'maxjetflavor': 5,
'pdgs_for_merging_cut':
'1, 2, 3, 4, 5, 21'}
2406 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=
True)
2407 modify_param_card(process_dir=process_dir, params={
'MASS': {
'5':
'0.000000e+00'}})
2409 mglog.info(
'Finished checking run card - All OK!')
2412 mglog.info(
'Running reweighting module on existing events')
2413 if reweight_card
is not None:
2414 mglog.info(
'Copying new reweight card from '+reweight_card)
2415 shutil.move(reweight_card,process_dir+
'/Cards/reweight_card.dat')
2416 reweight_cmd=
'{}/bin/madevent reweight {} -f'.
format(process_dir,run_name)
2417 global MADGRAPH_CATCH_ERRORS
2418 reweight =
stack_subprocess([python]+reweight_cmd.split(),stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
2419 (out,err) = reweight.communicate()
2421 mglog.info(
'Finished reweighting')
2427 mglog.info(
'For your information, ls of '+directory+
':')
2428 mglog.info(
sorted( os.listdir( directory ) ) )
2431 import MadGraphControl.MadGraphSystematicsUtils
2435 makefile_fks=process_dir+
'/SubProcesses/makefile_fks_dir'
2436 mglog.info(
'Fixing '+makefile_fks)
2437 shutil.move(makefile_fks,makefile_fks+
'_orig')
2438 fin=
open(makefile_fks+
'_orig')
2439 fout=
open(makefile_fks,
'w')
2442 if 'FKSParams.mod' in line:
2443 fout.write(line.replace(
'FKSParams.mod',
'FKSParams.o'))
2445 elif edit
and 'driver_mintFO' in line:
2446 fout.write(
'driver_mintFO.o: weight_lines.o mint_module.o FKSParams.o\n')
2447 elif edit
and 'genps_fks.o' in line:
2448 fout.write(
'genps_fks.o: mint_module.o FKSParams.o\n')
2449 elif edit
and 'test_soft_col_limits' in line:
2451 fout.write(
'madfks_plot.o: mint_module.o\n')
2452 fout.write(
'cluster.o: weight_lines.o\n')