ATLAS Offline Software
Loading...
Searching...
No Matches
python.MadGraphUtils Namespace Reference

Functions

 stack_subprocess (command, **kwargs)
 generate_prep (process_dir)
 new_process (process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False)
 get_default_runcard (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 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)
 generate_from_gridpack (runArgs=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False)
 setupFastjet (process_dir=None)
 setupLHAPDF (process_dir=None, extlhapath=None, allow_links=True)
 setNCores (process_dir, Ncores=None)
 get_mg5_executable ()
 add_lifetimes (process_dir, threshold=None)
 add_madspin (madspin_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
 madspin_on_lhe (input_LHE, madspin_card, runArgs=None, keep_original=False)
 arrange_output (process_dir=MADGRAPH_GRIDPACK_LOCATION, lhe_version=None, saveProcDir=False, runArgs=None, fixEventWeightsForBridgeMode=False)
 get_expected_reweight_names (reweight_card_loc)
 get_expected_systematic_names (syst_setting)
 setup_bias_module (bias_module, process_dir)
 get_reweight_card (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 check_reweight_card (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 update_lhe_file (lhe_file_old, param_card_old=None, lhe_file_new=None, masses={}, delete_old_lhe=True)
 find_key_and_update (akey, dictionary)
 modify_param_card (param_card_input=None, param_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, params={}, output_location=None)
 print_cards_from_dir (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 print_cards (proc_card='proc_card_mg5.dat', run_card=None, param_card=None, madspin_card=None, reweight_card=None, warn_on_missing=True)
 is_gen_from_gridpack ()
 modify_run_card (run_card_input=None, run_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, runArgs=None, settings={}, skipBaseFragment=False)
 modify_config_card (config_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, settings={}, set_commented=True)
 get_cluster_type (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 run_card_consistency_check (isNLO=False, process_dir='.')
 add_reweighting (run_name, reweight_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
 ls_dir (directory)
 fix_fks_makefile (process_dir)

Variables

 mglog = Logging.logging.getLogger('MadGraphUtils')
 my_MGC_instance = None
str python = 'python'
str MADGRAPH_GRIDPACK_LOCATION = 'madevent'
str MADGRAPH_RUN_NAME = 'run_01'
bool MADGRAPH_CATCH_ERRORS = True
 MADGRAPH_PDFSETTING = None
list MADGRAPH_COMMAND_STACK = []
str patched_shutil_loc = '/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest/shutil_patch'

Function Documentation

◆ add_lifetimes()

python.MadGraphUtils.add_lifetimes ( process_dir,
threshold = None )
 Add lifetimes to the generated LHE file.  Should be
called after generate_events is called.

Definition at line 740 of file MadGraphUtils.py.

740def add_lifetimes(process_dir,threshold=None):
741 """ Add lifetimes to the generated LHE file. Should be
742 called after generate_events is called.
743 """
744
745 me_exec=get_mg5_executable()
746
747 if len(glob.glob(process_dir+'/Events/*'))<1:
748 mglog.error('Process dir '+process_dir+' does not contain events?')
749 run = glob.glob(process_dir+'/Events/*')[0].split('/')[-1]
750
751 # Note : This slightly clunky implementation is needed for the time being
752 # See : https://answers.launchpad.net/mg5amcnlo/+question/267904
753
754 tof_c = open('time_of_flight_exec_card','w')
755 tof_c.write('launch '+process_dir+''' -i
756add_time_of_flight '''+run+((' --threshold='+str(threshold)) if threshold is not None else ''))
757 tof_c.close()
758
759 mglog.info('Started adding time of flight info '+str(time.asctime()))
760
761 generate = stack_subprocess([python,me_exec,'time_of_flight_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
762 (out,err) = generate.communicate()
763 error_check(err,generate.returncode)
764
765 mglog.info('Finished adding time of flight information at '+str(time.asctime()))
766
767 # Re-zip the file if needed
768 lhe_gz = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
769 if not os.access(lhe_gz,os.R_OK):
770 mglog.info('LHE file needs to be zipped')
771 lhe = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
772 rezip = stack_subprocess(['gzip',lhe])
773 rezip.wait()
774 mglog.info('Zipped')
775 else:
776 mglog.info('LHE file zipped by MadGraph automatically. Nothing to do')
777
778 return True
779
780
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177

◆ add_madspin()

python.MadGraphUtils.add_madspin ( madspin_card = None,
process_dir = MADGRAPH_GRIDPACK_LOCATION )
 Run madspin on the generated LHE file.  Should be
run when you have inputGeneratorFile set.
Only requires a simplified process with the same model that you are
interested in (needed to set up a process directory for MG5_aMC)

Definition at line 781 of file MadGraphUtils.py.

781def add_madspin(madspin_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
782 """ Run madspin on the generated LHE file. Should be
783 run when you have inputGeneratorFile set.
784 Only requires a simplified process with the same model that you are
785 interested in (needed to set up a process directory for MG5_aMC)
786 """
787
788 me_exec=get_mg5_executable()
789
790 if madspin_card is not None:
791 shutil.copyfile(madspin_card,process_dir+'/Cards/madspin_card.dat')
792
793 if len(glob.glob(process_dir+'/Events/*'))<1:
794 mglog.error('Process dir '+process_dir+' does not contain events?')
795 proc_dir_list = glob.glob(process_dir+'/Events/*')
796 run=None
797 for adir in proc_dir_list:
798 if 'GridRun_' in adir:
799 run=adir.split('/')[-1]
800 break
801 else:
802 run=proc_dir_list[0].split('/')[-1]
803
804 # Note : This slightly clunky implementation is needed for the time being
805 # See : https://answers.launchpad.net/mg5amcnlo/+question/267904
806
807 ms_c = open('madspin_exec_card','w')
808 ms_c.write('launch '+process_dir+''' -i
809decay_events '''+run)
810 ms_c.close()
811
812 mglog.info('Started running madspin at '+str(time.asctime()))
813
814 generate = stack_subprocess([python,me_exec,'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
815 (out,err) = generate.communicate()
816 error_check(err,generate.returncode)
817 if len(glob.glob(process_dir+'/Events/'+run+'_decayed_*/')) == 0:
818 mglog.error('No '+process_dir+'/Events/'+run+'_decayed_*/ can be found')
819 raise RuntimeError('Problem while running MadSpin')
820
821 mglog.info('Finished running madspin at '+str(time.asctime()))
822
823 # Re-zip the file if needed
824 lhe_gz = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
825 if not os.access(lhe_gz,os.R_OK):
826 mglog.info('LHE file needs to be zipped')
827 lhe = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
828 rezip = stack_subprocess(['gzip',lhe])
829 rezip.wait()
830 mglog.info('Zipped')
831 else:
832 mglog.info('LHE file zipped by MadGraph automatically. Nothing to do')
833
834

◆ add_reweighting()

python.MadGraphUtils.add_reweighting ( run_name,
reweight_card = None,
process_dir = MADGRAPH_GRIDPACK_LOCATION )

Definition at line 1983 of file MadGraphUtils.py.

1983def add_reweighting(run_name,reweight_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
1984 mglog.info('Running reweighting module on existing events')
1985 if reweight_card is not None:
1986 mglog.info('Copying new reweight card from '+reweight_card)
1987 shutil.move(reweight_card,process_dir+'/Cards/reweight_card.dat')
1988 reweight_cmd='{}/bin/madevent reweight {} -f'.format(process_dir,run_name)
1989 reweight = stack_subprocess([python]+reweight_cmd.split(),stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1990 (out,err) = reweight.communicate()
1991 error_check(err,reweight.returncode)
1992 mglog.info('Finished reweighting')
1993
1994
1995
1996

◆ arrange_output()

python.MadGraphUtils.arrange_output ( process_dir = MADGRAPH_GRIDPACK_LOCATION,
lhe_version = None,
saveProcDir = False,
runArgs = None,
fixEventWeightsForBridgeMode = False )

Definition at line 922 of file MadGraphUtils.py.

922def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
923
924 # NLO is not *really* the question here, we need to know if we should look for weighted or
925 # unweighted events in the output directory. MadSpin (above) only seems to give weighted
926 # results for now?
927 if len(glob.glob(os.path.join(process_dir, 'Events','*')))<1:
928 mglog.error('Process dir '+process_dir+' does not contain events?')
929 proc_dir_list = glob.glob(os.path.join(process_dir, 'Events', '*'))
930 this_run_name=None
931 # looping over possible directories to find the right one
932 for adir in proc_dir_list:
933 if 'decayed' in adir:# skipping '*decayed*' directories produced by MadSpin, will be picked later if they exist
934 continue
935 else:
936 if 'GridRun_' in adir:
937 this_run_name=adir
938 break # GridRun_* directories have priority
939 elif os.path.join(process_dir, 'Events',MADGRAPH_RUN_NAME) in adir:
940 this_run_name=adir
941 if not os.access(this_run_name,os.R_OK):
942 raise RuntimeError('Unable to locate run directory')
943
944 hasUnweighted = os.access(this_run_name+'/unweighted_events.lhe.gz',os.R_OK)
945
946 hasRunMadSpin=False
947 madspinDirs=sorted(glob.glob(this_run_name+'_decayed_*/'))
948 if len(madspinDirs):
949 hasRunMadSpin=True
950 if hasRunMadSpin and not hasUnweighted:
951 # check again:
952 hasUnweighted = os.access(madspinDirs[-1]+'/unweighted_events.lhe.gz',os.R_OK)
953
954 global MADGRAPH_COMMAND_STACK
955 if hasRunMadSpin:
956 if len(madspinDirs):
957 if hasUnweighted:
958 # so this is a bit of a mess now...
959 # if madspin is run from an NLO grid pack the correct lhe events are at both
960 # madevent/Events/run_01/unweighted_events.lhe.gz
961 # and madevent/Events/run_01_decayed_1/events.lhe.gz
962 # so there are unweighted events but not in the madspinDir...
963 if os.path.exists(madspinDirs[-1]+'/unweighted_events.lhe.gz'):
964 MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/unweighted_events.lhe.gz'+' '+this_run_name+'/unweighted_events.lhe.gz']
965 shutil.move(madspinDirs[-1]+'/unweighted_events.lhe.gz',this_run_name+'/unweighted_events.lhe.gz')
966 mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/unweighted_events.lhe.gz to '+this_run_name+'/unweighted_events.lhe.gz')
967 elif os.path.exists(madspinDirs[-1]+'/events.lhe.gz'):
968 MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/events.lhe.gz'+' '+this_run_name+'/unweighted_events.lhe.gz']
969 shutil.move(madspinDirs[-1]+'/events.lhe.gz',this_run_name+'/unweighted_events.lhe.gz')
970 mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/events.lhe.gz to '+this_run_name+'/unweighted_events.lhe.gz')
971 else:
972 raise RuntimeError('MadSpin was run but can\'t find files :(')
973
974 else:
975 MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/events.lhe.gz '+this_run_name+'/events.lhe.gz']
976 shutil.move(madspinDirs[-1]+'/events.lhe.gz',this_run_name+'/events.lhe.gz')
977 mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/events.lhe.gz to '+this_run_name+'/events.lhe.gz')
978
979 else:
980 mglog.error('MadSpin was run but can\'t find output folder '+(this_run_name+'_decayed_1/'))
981 raise RuntimeError('MadSpin was run but can\'t find output folder '+(this_run_name+'_decayed_1/'))
982
983 if fixEventWeightsForBridgeMode:
984 mglog.info("Fixing event weights after MadSpin... initial checks.")
985
986 # get the cross section from the undecayed LHE file
987 spinmodenone=False
988 MGnumevents=-1
989 MGintweight=-1
990
991 if hasUnweighted:
992 eventsfilename="unweighted_events"
993 else:
994 eventsfilename="events"
995 unzip = stack_subprocess(['gunzip','-f',this_run_name+'/%s.lhe.gz' % eventsfilename])
996 unzip.wait()
997
998 for line in open(process_dir+'/Events/'+MADGRAPH_RUN_NAME+'/%s.lhe'%eventsfilename):
999 if "Number of Events" in line:
1000 sline=line.split()
1001 MGnumevents=int(sline[-1])
1002 elif "Integrated weight (pb)" in line:
1003 sline=line.split()
1004 MGintweight=float(sline[-1])
1005 elif "set spinmode none" in line:
1006 spinmodenone=True
1007 elif "</header>" in line:
1008 break
1009
1010 if spinmodenone and MGnumevents>0 and MGintweight>0:
1011 mglog.info("Fixing event weights after MadSpin... modifying LHE file.")
1012 newlhe=open(this_run_name+'/%s_fixXS.lhe'%eventsfilename,'w')
1013 initlinecount=0
1014 eventlinecount=0
1015 inInit=False
1016 inEvent=False
1017
1018 # new default for MG 2.6.1+ (https://its.cern.ch/jira/browse/AGENE-1725)
1019 # but verified from LHE below.
1020 event_norm_setting="average"
1021
1022 for line in open(this_run_name+'/%s.lhe'%eventsfilename):
1023
1024 newline=line
1025 if "<init>" in line:
1026 inInit=True
1027 initlinecount=0
1028 elif "</init>" in line:
1029 inInit=False
1030 elif inInit and initlinecount==0:
1031 initlinecount=1
1032 # check event_norm setting in LHE file, deteremines how Pythia interprets event weights
1033 sline=line.split()
1034 if abs(int(sline[-2])) == 3:
1035 event_norm_setting="sum"
1036 elif abs(int(sline[-2])) == 4:
1037 event_norm_setting="average"
1038 elif inInit and initlinecount==1:
1039 sline=line.split()
1040 # update the global XS info
1041 relunc=float(sline[1])/float(sline[0])
1042 sline[0]=str(MGintweight)
1043 sline[1]=str(float(sline[0])*relunc)
1044 if event_norm_setting=="sum":
1045 sline[2]=str(MGintweight/MGnumevents)
1046 elif event_norm_setting=="average":
1047 sline[2]=str(MGintweight)
1048 newline=' '.join(sline)
1049 newline+="\n"
1050 initlinecount+=1
1051 elif inInit and initlinecount>1:
1052 initlinecount+=1
1053 elif "<event>" in line:
1054 inEvent=True
1055 eventlinecount=0
1056 elif "</event>" in line:
1057 inEvent=False
1058 elif inEvent and eventlinecount==0:
1059 sline=line.split()
1060 # next change the per-event weights
1061 if event_norm_setting=="sum":
1062 sline[2]=str(MGintweight/MGnumevents)
1063 elif event_norm_setting=="average":
1064 sline[2]=str(MGintweight)
1065 newline=' '.join(sline)
1066 newline+="\n"
1067 eventlinecount+=1
1068 newlhe.write(newline)
1069 newlhe.close()
1070
1071 mglog.info("Fixing event weights after MadSpin... cleaning up.")
1072 shutil.copyfile(this_run_name+'/%s.lhe' % eventsfilename,
1073 this_run_name+'/%s_badXS.lhe' % eventsfilename)
1074
1075 shutil.move(this_run_name+'/%s_fixXS.lhe' % eventsfilename,
1076 this_run_name+'/%s.lhe' % eventsfilename)
1077
1078 rezip = stack_subprocess(['gzip',this_run_name+'/%s.lhe' % eventsfilename])
1079 rezip.wait()
1080
1081 rezip = stack_subprocess(['gzip',this_run_name+'/%s_badXS.lhe' % eventsfilename])
1082 rezip.wait()
1083
1084 # Clean up in case a link or file was already there
1085 if os.path.exists(os.getcwd()+'/events.lhe'):
1086 os.remove(os.getcwd()+'/events.lhe')
1087
1088 mglog.info('Unzipping generated events.')
1089 if hasUnweighted:
1090 unzip = stack_subprocess(['gunzip','-f',this_run_name+'/unweighted_events.lhe.gz'])
1091 unzip.wait()
1092 else:
1093 unzip = stack_subprocess(['gunzip','-f',this_run_name+'/events.lhe.gz'])
1094 unzip.wait()
1095
1096 mglog.info('Putting a copy in place for the transform.')
1097 if hasUnweighted:
1098 orig_input = this_run_name+'/unweighted_events.lhe'
1099 mod_output = open(os.getcwd()+'/events.lhe','w')
1100 else:
1101 orig_input = this_run_name+'/events.lhe'
1102 mod_output = open(os.getcwd()+'/events.lhe','w')
1103
1104 #Removing empty lines and bad comments in LHE
1105 #and check for existence of weights
1106 initrwgt=None
1107 nEmpty=0
1108 lhe_weights=[]
1109 with open(orig_input,'r') as fileobject:
1110 for line in fileobject:
1111 if line.strip():
1112 # search for bad characters (neccessary until at least MG5 2.8.1)
1113 newline=line
1114 if '#' not in newline:
1115 newline=newline
1116 elif '>' not in newline[ newline.find('#'): ]:
1117 newline=newline
1118 else:
1119 mglog.info('Found bad LHE line with an XML mark in a comment: "'+newline.strip()+'"')
1120 newline=newline[:newline.find('#')]+'#'+ (newline[newline.find('#'):].replace('>','-'))
1121 # check for weightnames that should exist, simplify nominal weight names
1122 if initrwgt is False:
1123 pass
1124 elif "</initrwgt>" in newline:
1125 initrwgt=False
1126 elif "<initrwgt>" in newline:
1127 initrwgt=True
1128 elif initrwgt is not None:
1129 newline=newline.replace('_DYNSCALE-1','')
1130 if '</weight>' in newline:
1131 iend=newline.find('</weight>')
1132 istart=newline[:iend].rfind('>')
1133 lhe_weights+=[newline[istart+1:iend].strip()]
1134 mod_output.write(newline)
1135 else:
1136 nEmpty=nEmpty+1
1137 mod_output.close()
1138 mglog.info('Removed '+str(nEmpty)+' empty lines from LHEF')
1139
1140 mglog.info("The following "+str(len(lhe_weights))+" weights have been written to the LHE file: "+",".join(lhe_weights))
1141 expected_weights=get_expected_reweight_names(get_reweight_card(process_dir))
1142 expected_weights+=get_expected_systematic_names(MADGRAPH_PDFSETTING)
1143 mglog.info("Checking whether the following expected weights are in LHE file: "+",".join(expected_weights))
1144 for w in expected_weights:
1145 if w not in lhe_weights:
1146 raise RuntimeError("Did not find expected weight "+w+" in lhe file. Did the reweight or systematics module crash?")
1147 mglog.info("Found all required weights!")
1148
1149 if lhe_version:
1150 mod_output2 = open(os.getcwd()+'/events.lhe','r')
1151 test=mod_output2.readline()
1152 if 'version="' in test:
1153 mglog.info('Applying LHE version hack')
1154 final_file = open(os.getcwd()+'/events.lhe.copy','w')
1155 final_file.write('<LesHouchesEvents version="%i.0">\n'%lhe_version)
1156 shutil.copyfileobj(mod_output2, final_file)
1157 final_file.close()
1158 shutil.copy(os.getcwd()+'/events.lhe.copy',os.getcwd()+'/events.lhe')
1159 # Clean up after ourselves
1160 os.remove(os.getcwd()+'/events.lhe.copy')
1161 mod_output2.close()
1162
1163 # Actually move over the dataset
1164 if runArgs is None:
1165 raise RuntimeError('Must provide runArgs to arrange_output')
1166
1167 if hasattr(runArgs,'outputTXTFile'):
1168 outputDS = runArgs.outputTXTFile
1169 else:
1170 outputDS = 'tmp_LHE_events.tar.gz'
1171
1172 mglog.info('Moving file over to '+outputDS.split('.tar.gz')[0]+'.events')
1173
1174 shutil.move(os.getcwd()+'/events.lhe',outputDS.split('.tar.gz')[0]+'.events')
1175
1176 mglog.info('Re-zipping into dataset name '+outputDS)
1177 rezip = stack_subprocess(['tar','cvzf',outputDS,outputDS.split('.tar.gz')[0]+'.events'])
1178 rezip.wait()
1179
1180 if not saveProcDir:
1181 mglog.info('Removing the process directory')
1182 shutil.rmtree(process_dir,ignore_errors=True)
1183
1184 if os.path.isdir('MGC_LHAPDF/'):
1185 shutil.rmtree('MGC_LHAPDF/',ignore_errors=True)
1186
1187 # shortening the outputDS in the case of an output TXT file
1188 if hasattr(runArgs,'outputTXTFile') and runArgs.outputTXTFile is not None:
1189 outputDS = outputDS.split('.TXT')[0]
1190 # Do some fixing up for them
1191 if runArgs is not None:
1192 mglog.debug('Setting inputGenerator file to '+outputDS)
1193 runArgs.inputGeneratorFile=outputDS
1194
1195 mglog.info('All done with output arranging!')
1196 return outputDS
1197
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:310

◆ check_reweight_card()

python.MadGraphUtils.check_reweight_card ( process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1288 of file MadGraphUtils.py.

1288def check_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1289 reweight_card=get_reweight_card(process_dir=process_dir)
1290 shutil.move(reweight_card,reweight_card+'.old')
1291 oldcard = open(reweight_card+'.old','r')
1292 newcard = open(reweight_card,'w')
1293 changed = False
1294 info_expression=r'launch.*--rwgt_info\s*=\s*(\S+).*'
1295 name_expression=info_expression.replace('info','name')
1296 goodname_expression=r'^[A-Za-z0-9_\-.]+$'
1297 for line in oldcard:
1298 # we are only interested in the 'launch' line
1299 if not line.strip().startswith('launch') :
1300 newcard.write(line)
1301 else:
1302 rwgt_name_match=re.match(name_expression,line.strip())
1303 rwgt_info_match=re.match(info_expression,line.strip())
1304 if rwgt_name_match is None and rwgt_info_match is None:
1305 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)
1306 for match in [rwgt_info_match,rwgt_name_match]:
1307 if match is None:
1308 continue
1309 if len(match.groups())!=1:
1310 raise RuntimeError('Unexpected format of reweight card in line: '+line)
1311 if not re.match(goodname_expression,match.group(1)):
1312 raise RuntimeError('No special character in reweighting info/name, only allowing '+goodname_expression)
1313 if rwgt_info_match is not None:
1314 newcard.write(line)
1315 elif rwgt_name_match is not None:
1316 newcard.write(line.strip()+' --rwgt_info={0}\n'.format(rwgt_name_match.group(1)))
1317 changed=True
1318 if changed:
1319 mglog.info('Updated reweight_card')
1320 newcard.close()
1321 oldcard.close()
1322
1323

◆ find_key_and_update()

python.MadGraphUtils.find_key_and_update ( akey,
dictionary )
 Helper function when looking at param cards
In some cases it's tricky to match keys - they may differ
only in white space. This tries to sort out when we have
a match, and then uses the one in blockParams afterwards.
In the case of no match, it returns the original key.

Definition at line 1431 of file MadGraphUtils.py.

1431def find_key_and_update(akey,dictionary):
1432 """ Helper function when looking at param cards
1433 In some cases it's tricky to match keys - they may differ
1434 only in white space. This tries to sort out when we have
1435 a match, and then uses the one in blockParams afterwards.
1436 In the case of no match, it returns the original key.
1437 """
1438 test_key = ' '.join(akey.strip().replace('\t',' ').split())
1439 for key in dictionary:
1440 mod_key = ' '.join(key.strip().replace('\t',' ').split())
1441 if mod_key==test_key:
1442 return key
1443 return akey
1444
1445

◆ fix_fks_makefile()

python.MadGraphUtils.fix_fks_makefile ( process_dir)

Definition at line 2005 of file MadGraphUtils.py.

2005def fix_fks_makefile(process_dir):
2006 makefile_fks=process_dir+'/SubProcesses/makefile_fks_dir'
2007 mglog.info('Fixing '+makefile_fks)
2008 shutil.move(makefile_fks,makefile_fks+'_orig')
2009 fin=open(makefile_fks+'_orig')
2010 fout=open(makefile_fks,'w')
2011 edit=False
2012 for line in fin:
2013 if 'FKSParams.mod' in line:
2014 fout.write(line.replace('FKSParams.mod','FKSParams.o'))
2015 edit=True
2016 elif edit and 'driver_mintFO' in line:
2017 fout.write('driver_mintFO.o: weight_lines.o mint_module.o FKSParams.o\n')
2018 elif edit and 'genps_fks.o' in line:
2019 fout.write('genps_fks.o: mint_module.o FKSParams.o\n')
2020 elif edit and 'test_soft_col_limits' in line:
2021 fout.write(line)
2022 fout.write('madfks_plot.o: mint_module.o\n')
2023 fout.write('cluster.o: weight_lines.o\n')
2024 else:
2025 fout.write(line)
2026 fin.close()
2027 fout.close()

◆ generate()

python.MadGraphUtils.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 )

Definition at line 112 of file MadGraphUtils.py.

112def 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):
113 # Just in case
114 setup_path_protection()
115
116 # Set consistent mode and number of jobs
117 mode = 0
118 njobs = 1
119 if 'ATHENA_CORE_NUMBER' in os.environ and int(os.environ['ATHENA_CORE_NUMBER'])>0:
120 njobs = int(os.environ['ATHENA_CORE_NUMBER'])
121 mglog.info('Lucky you - you are running on a full node queue. Will re-configure for '+str(njobs)+' jobs.')
122 mode = 2
123
124 cluster_type = get_cluster_type(process_dir=process_dir)
125 if cluster_type is not None:
126 mode = 1
127
128 if is_gen_from_gridpack():
129 mglog.info('Running event generation from gridpack (using smarter mode from generate() function)')
130 generate_from_gridpack(runArgs=runArgs,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings)
131 return
132 else:
133 mglog.info('Did not identify an input gridpack.')
134 if grid_pack:
135 mglog.info('The grid_pack flag is set, so I am expecting to create a gridpack in this job')
136
137 # Now get a variety of info out of the runArgs
138 beamEnergy,random_seed = get_runArgs_info(runArgs)
139
140 # Check if process is NLO or LO
141 isNLO=is_NLO_run(process_dir=process_dir)
142
143 # temporary fix of makefile, needed for 3.3.1., remove in future
144 if isNLO:
145 fix_fks_makefile(process_dir=process_dir)
146
147 # if f2py not available
148 if get_reweight_card(process_dir=process_dir) is not None:
149 if shutil.which('f2py') is not None:
150 mglog.info('Found f2py, will use it for reweighting')
151 else:
152 raise RuntimeError('Could not find f2py, needed for reweighting')
153 check_reweight_card(process_dir)
154
155 global MADGRAPH_COMMAND_STACK
156
157 if grid_pack:
158 #Running in gridpack mode
159 mglog.info('Started generating gridpack at '+str(time.asctime()))
160 mglog.warning(' >>>>>> THIS KIND OF JOB SHOULD ONLY BE RUN LOCALLY - NOT IN GRID JOBS <<<<<<')
161
162 # Some events required if we specify MadSpin usage!
163 my_settings = {'nevents':'1000'}
164
165 if isNLO:
166 my_settings['req_acc']=str(required_accuracy)
167 else:
168 # At LO, no events are generated. That means we need to move the MS card aside and back.
169 LO_has_madspin = False
170 if os.access(f'{process_dir}/Cards/madspin_card.dat',os.R_OK):
171 MADGRAPH_COMMAND_STACK += [f'mv {process_dir}/Cards/madspin_card.dat {process_dir}/Cards/madspin_card.tmp.dat']
172 os.rename(f'{process_dir}/Cards/madspin_card.dat',f'{process_dir}/Cards/madspin_card.tmp.dat')
173 LO_has_madspin = True
174 my_settings = {'gridpack':'true'}
175 modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=True)
176
177 else:
178 #Running in on-the-fly mode
179 mglog.info('Started generating at '+str(time.asctime()))
180
181 mglog.info('Run '+MADGRAPH_RUN_NAME+' will be performed in mode '+str(mode)+' with '+str(njobs)+' jobs in parallel.')
182
183 # Ensure that things are set up normally
184 if not os.access(process_dir,os.R_OK):
185 raise RuntimeError('No process directory found at '+process_dir)
186 if not os.access(process_dir+'/bin/generate_events',os.R_OK):
187 raise RuntimeError('No generate_events module found in '+process_dir)
188
189 mglog.info('For your information, the libraries available are (should include LHAPDF):')
190 ls_dir(process_dir+'/lib')
191
192 setupFastjet(process_dir=process_dir)
193 if bias_module is not None:
194 setup_bias_module(bias_module,process_dir)
195
196 mglog.info('Now I will hack the make files a bit. Apologies, but there seems to be no good way around this.')
197 shutil.copyfile(process_dir+'/Source/make_opts',process_dir+'/Source/make_opts_old')
198 old_opts = open(process_dir+'/Source/make_opts_old','r')
199 new_opts = open(process_dir+'/Source/make_opts','w')
200 for aline in old_opts:
201 if 'FC=g' in aline:
202 mglog.info('Configuring the fancy gfortran compiler instead of g77 / f77')
203 new_opts.write(' FC=gfortran\n')
204 else:
205 new_opts.write(aline)
206 old_opts.close()
207 new_opts.close()
208 mglog.info('Make file hacking complete.')
209
210 # Change directories
211 currdir=os.getcwd()
212 os.chdir(process_dir)
213 # Record the change
214 MADGRAPH_COMMAND_STACK += [ 'cd ${MGaMC_PROCESS_DIR}' ]
215
216 # Check the run card
217 run_card_consistency_check(isNLO=isNLO)
218
219 # For grid packs we also need to move the systematics program aside
220 if grid_pack:
221 original_systematics_program = None if 'systematics_program' not in my_MGC_instance.runCardDict else my_MGC_instance.runCardDict['systematics_program']
222 modify_run_card(process_dir=process_dir,settings={'systematics_program':'None'},skipBaseFragment=True)
223
224 # Since the consistency check can update some settings, print the cards now
225 print_cards_from_dir(process_dir=os.getcwd())
226
227 # Check the param card
228 code = check_PMG_updates(process_dir=os.getcwd())
229 if requirePMGSettings and code!=0:
230 raise RuntimeError('Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
231
232 # Build up the generate command
233 # Use the new-style way of passing things: just --name, everything else in config
234 command = [python,'bin/generate_events']
235 if isNLO:
236 command += ['--name='+MADGRAPH_RUN_NAME]
237 mglog.info('Removing Cards/shower_card.dat to ensure we get parton level events only')
238 os.unlink('Cards/shower_card.dat')
239 else:
240 command += [MADGRAPH_RUN_NAME]
241 # Set the number of cores to be used
242 setNCores(process_dir=os.getcwd(), Ncores=njobs)
243 # Special handling for mode 1
244 if mode==1:
245 mglog.info('Setting up cluster running')
246 modify_config_card(process_dir=os.getcwd(),settings={'run_mode':1})
247 if cluster_type=='pbs':
248 mglog.info('Modifying bin/internal/cluster.py for PBS cluster running')
249 os.system("sed -i \"s:text += prog:text += './'+prog:g\" bin/internal/cluster.py")
250 elif mode==2:
251 mglog.info('Setting up multi-core running on '+os.environ['ATHENA_CORE_NUMBER']+' cores')
252 elif mode==0:
253 mglog.info('Setting up serial generation.')
254
255 generate_prep(process_dir=os.getcwd())
256 generate = stack_subprocess(command,stdin=subprocess.PIPE, stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
257 (out,err) = generate.communicate()
258 error_check(err,generate.returncode)
259
260 # Get back to where we came from
261 os.chdir(currdir)
262 MADGRAPH_COMMAND_STACK += [ 'cd -' ]
263
264 if grid_pack:
265 # Name dictacted by https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/PmgMcSoftware
266 energy = '%1.1f'%(beamEnergy*2./1000.)
267 energy = energy.replace('.0','').replace('.','p')
268 gridpack_name='mc_'+energy+'TeV.'+get_physics_short()+'.GRID.tar.gz'
269 mglog.info('Tidying up gridpack '+gridpack_name)
270
271 # Return the setting for the systematics_program
272 modify_run_card(process_dir=process_dir,settings={'systematics_program':original_systematics_program})
273
274 if not isNLO:
275 # At LO, no events are generated. That means we need to move the MS card aside and back.
276 if LO_has_madspin:
277 MADGRAPH_COMMAND_STACK += [f'mv {process_dir}/Cards/madspin_card.tmp.dat {process_dir}/Cards/madspin_card.dat']
278 os.rename(f'{process_dir}/Cards/madspin_card.tmp.dat',f'{process_dir}/Cards/madspin_card.dat')
279
280
281 MADGRAPH_COMMAND_STACK += ['cp '+glob.glob(process_dir+'/'+MADGRAPH_RUN_NAME+'_*gridpack.tar.gz')[0]+' '+gridpack_name]
282 shutil.copy(glob.glob(process_dir+'/'+MADGRAPH_RUN_NAME+'_*gridpack.tar.gz')[0],gridpack_name)
283
284 if gridpack_compile:
285 MADGRAPH_COMMAND_STACK += ['mkdir tmp%i/'%os.getpid(),'cd tmp%i/'%os.getpid()]
286 os.mkdir('tmp%i/'%os.getpid())
287 os.chdir('tmp%i/'%os.getpid())
288 mglog.info('untar gridpack')
289 untar = stack_subprocess(['tar','xvzf',('../'+gridpack_name)])
290 untar.wait()
291 mglog.info('compile and clean up')
292 MADGRAPH_COMMAND_STACK += ['cd madevent']
293 os.chdir('madevent/')
294 compilep = stack_subprocess(['./bin/compile'],stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
295 (out,err) = compilep.communicate()
296 error_check(err,compilep.returncode)
297 clean = stack_subprocess(['./bin/clean4grid'],stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
298 (out,err) = clean.communicate()
299 error_check(err,clean.returncode)
300 clean.wait()
301 MADGRAPH_COMMAND_STACK += ['cd ..','rm ../'+gridpack_name]
302 os.chdir('../')
303 mglog.info('remove old tarball')
304 os.unlink('../'+gridpack_name)
305 mglog.info('Package up new tarball')
306 tar = stack_subprocess(['tar','--exclude=SubProcesses/P*/G*/*_results.dat','--exclude=SubProcesses/P*/G*/*.log','--exclude=SubProcesses/P*/G*/*.txt','-cvsf','../'+gridpack_name,'.'])
307 tar.wait()
308 MADGRAPH_COMMAND_STACK += ['cd ..','rm -r tmp%i/'%os.getpid()]
309 os.chdir('../')
310 mglog.info('Remove temporary directory')
311 shutil.rmtree('tmp%i/'%os.getpid())
312 mglog.info('Tidying up complete!')
313
314 else:
315
316
317 mglog.info('Package up process_dir')
318 MADGRAPH_COMMAND_STACK += ['mv '+process_dir+' '+MADGRAPH_GRIDPACK_LOCATION]
319 os.rename(process_dir,MADGRAPH_GRIDPACK_LOCATION)
320 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])
321 tar.wait()
322 MADGRAPH_COMMAND_STACK += ['mv '+MADGRAPH_GRIDPACK_LOCATION+' '+process_dir]
323 os.rename(MADGRAPH_GRIDPACK_LOCATION,process_dir)
324
325 mglog.info('Gridpack sucessfully created, exiting the transform')
326 if hasattr(runArgs,'outputTXTFile'):
327 mglog.info('Touching output TXT (LHE) file for the transform')
328 open(runArgs.outputTXTFile, 'w').close()
329 from AthenaCommon.AppMgr import theApp
330 theApp.finalize()
331 theApp.exit()
332
333 mglog.info('Finished at '+str(time.asctime()))
334 return 0
335
336

◆ generate_from_gridpack()

python.MadGraphUtils.generate_from_gridpack ( runArgs = None,
extlhapath = None,
gridpack_compile = None,
requirePMGSettings = False )

Definition at line 337 of file MadGraphUtils.py.

337def generate_from_gridpack(runArgs=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False):
338 # Get of info out of the runArgs
339 beamEnergy,random_seed = get_runArgs_info(runArgs)
340
341 # Just in case
342 setup_path_protection()
343
344 isNLO=is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION)
345
346 setupFastjet(process_dir=MADGRAPH_GRIDPACK_LOCATION)
347
348 # This is hard-coded as a part of MG5_aMC :'(
349 gridpack_run_name = 'GridRun_'+str(random_seed)
350
351 # Ensure that we only do madspin at the end
352 if os.access(MADGRAPH_GRIDPACK_LOCATION+'/Cards/madspin_card.dat',os.R_OK):
353 os.rename(MADGRAPH_GRIDPACK_LOCATION+'/Cards/madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+'/Cards/backup_madspin_card.dat')
354 do_madspin=True
355 else:
356 do_madspin=False
357
358 if get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION) is not None:
359 check_reweight_card(MADGRAPH_GRIDPACK_LOCATION)
360
361 # Check the param card
362 code = check_PMG_updates(process_dir=MADGRAPH_GRIDPACK_LOCATION)
363 if requirePMGSettings and code!=0:
364 raise RuntimeError('Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
365
366 # Modify run card, then print
367 settings={'iseed':str(random_seed)}
368 if not isNLO:
369 settings['python_seed']=str(random_seed)
370 modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings=settings,skipBaseFragment=True)
371
372 mglog.info('Generating events from gridpack')
373
374 # Ensure that things are set up normally
375 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION):
376 raise RuntimeError('Gridpack directory not found at '+MADGRAPH_GRIDPACK_LOCATION)
377
378 nevents = getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+'/Cards/run_card.dat')['nevents']
379 mglog.info('>>>> FOUND GRIDPACK <<<< <- This will be used for generation')
380 mglog.info('Generation of '+str(int(nevents))+' events will be performed using the supplied gridpack with random seed '+str(random_seed))
381 mglog.info('Started generating events at '+str(time.asctime()))
382
383 #Remove addmasses if it's there
384 if os.access(MADGRAPH_GRIDPACK_LOCATION+'/bin/internal/addmasses.py',os.R_OK):
385 os.remove(MADGRAPH_GRIDPACK_LOCATION+'/bin/internal/addmasses.py')
386
387 currdir=os.getcwd()
388
389 # Make sure we've set the number of processes appropriately
390 setNCores(process_dir=MADGRAPH_GRIDPACK_LOCATION)
391
392 # Run the consistency check, print some useful info
393 ls_dir(currdir)
394 ls_dir(MADGRAPH_GRIDPACK_LOCATION)
395
396 # Update the run card according to consistency checks
397 run_card_consistency_check(isNLO=isNLO,process_dir=MADGRAPH_GRIDPACK_LOCATION)
398
399 # Now all done with updates, so print the cards with the final settings
400 print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION)
401
402 if isNLO:
403 #turn off systematics for gridpack generation and store settings for standalone run
404 run_card_dict=getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+'/Cards/run_card.dat')
405 systematics_settings=None
406 if checkSetting('systematics_program','systematics',run_card_dict):
407 if not checkSettingIsTrue('store_rwgt_info',run_card_dict):
408 raise RuntimeError('Trying to run NLO systematics but reweight info not stored')
409 if checkSettingExists('systematics_arguments',run_card_dict):
410 systematics_settings=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(run_card_dict['systematics_arguments'])
411 else:
412 systematics_settings={}
413 mglog.info('Turning off systematics for now, running standalone later')
414 modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={'systematics_program':'none'},skipBaseFragment=True)
415
416 global MADGRAPH_COMMAND_STACK
417 if not isNLO:
418
419 if not os.access(MADGRAPH_GRIDPACK_LOCATION+'/bin/gridrun',os.R_OK):
420 mglog.error('/bin/gridrun not found at '+MADGRAPH_GRIDPACK_LOCATION)
421 raise RuntimeError('Could not find gridrun executable')
422 else:
423 mglog.info('Found '+MADGRAPH_GRIDPACK_LOCATION+'/bin/gridrun, starting generation.')
424 generate_prep(MADGRAPH_GRIDPACK_LOCATION)
425 granularity=1
426 mglog.info("Now generating {} events with random seed {} and granularity {}".format(int(nevents),int(random_seed),granularity))
427 # not sure whether this is needed but it is done in the old "run.sh" script
428 new_ld_path=":".join([os.environ['LD_LIBRARY_PATH'],os.getcwd()+'/'+MADGRAPH_GRIDPACK_LOCATION+'/madevent/lib',os.getcwd()+'/'+MADGRAPH_GRIDPACK_LOCATION+'/HELAS/lib'])
429 os.environ['LD_LIBRARY_PATH']=new_ld_path
430 MADGRAPH_COMMAND_STACK+=["export LD_LIBRARY_PATH="+":".join(['${LD_LIBRARY_PATH}',new_ld_path])]
431 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)
432 (out,err) = generate.communicate()
433 error_check(err,generate.returncode)
434 gp_events=MADGRAPH_GRIDPACK_LOCATION+"/Events/GridRun_{}/unweighted_events.lhe.gz".format(int(random_seed))
435 if not os.path.exists(gp_events):
436 mglog.error('Error in gp generation, did not find events at '+gp_events)
437
438 # add reweighting, which is not run automatically from LO GPs
439 reweight_card=get_reweight_card(MADGRAPH_GRIDPACK_LOCATION)
440 if reweight_card is not None:
441 pythonpath_backup=os.environ['PYTHONPATH']
442 # workaround as madevent crashes when path to mg in PYTHONPATH
443 os.environ['PYTHONPATH']=':'.join([p for p in pythonpath_backup.split(':') if 'madgraph5amc' not in p])
444 add_reweighting('GridRun_{}'.format(int(random_seed)))
445 os.environ['PYTHONPATH']=pythonpath_backup
446
447 shutil.move(gp_events,'events.lhe.gz')
448
449 else:
450
451 if not os.access(MADGRAPH_GRIDPACK_LOCATION+'/bin/generate_events',os.R_OK):
452 raise RuntimeError('Could not find generate_events executable at '+MADGRAPH_GRIDPACK_LOCATION)
453 else:
454 mglog.info('Found '+MADGRAPH_GRIDPACK_LOCATION+'/bin/generate_events, starting generation.')
455
456 ls_dir(MADGRAPH_GRIDPACK_LOCATION+'/Events/')
457 if os.access(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name, os.F_OK):
458 mglog.info('Removing '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+' directory from gridpack generation')
459 MADGRAPH_COMMAND_STACK += ['rm -rf '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name]
460 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name)
461
462 # Delete events generated when setting up MadSpin during gridpack generation
463 if os.access(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1', os.F_OK):
464 mglog.info('Removing '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1 directory from gridpack generation')
465 MADGRAPH_COMMAND_STACK += ['rm -rf '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1']
466 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1')
467
468 ls_dir(MADGRAPH_GRIDPACK_LOCATION+'/Events/')
469
470 if not gridpack_compile:
471 mglog.info('Copying make_opts from Template')
472 shutil.copy(os.environ['MADPATH']+'/Template/LO/Source/make_opts',MADGRAPH_GRIDPACK_LOCATION+'/Source/')
473
474 generate_prep(MADGRAPH_GRIDPACK_LOCATION)
475 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)
476 (out,err) = generate.communicate()
477 error_check(err,generate.returncode)
478 else:
479 mglog.info('Allowing recompilation of gridpack')
480 if os.path.islink(MADGRAPH_GRIDPACK_LOCATION+'/lib/libLHAPDF.a'):
481 mglog.info('Unlinking '+MADGRAPH_GRIDPACK_LOCATION+'/lib/libLHAPDF.a')
482 os.unlink(MADGRAPH_GRIDPACK_LOCATION+'/lib/libLHAPDF.a')
483
484 generate_prep(MADGRAPH_GRIDPACK_LOCATION)
485 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)
486 (out,err) = generate.communicate()
487 error_check(err,generate.returncode)
488 if isNLO and systematics_settings is not None:
489 # run systematics
490 mglog.info('Running systematics standalone')
491 systematics_path=MADGRAPH_GRIDPACK_LOCATION+'/bin/internal/systematics.py'
492 events_location=MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/events.lhe.gz'
493 syst_cmd=[python,systematics_path]+[events_location]*2+["--"+k+"="+systematics_settings[k] for k in systematics_settings]
494 mglog.info('running: '+' '.join(syst_cmd))
495 systematics = stack_subprocess(syst_cmd)
496 systematics.wait()
497
498
499 # See if MG5 did the job for us already
500 if not os.access('events.lhe.gz',os.R_OK):
501 mglog.info('Copying generated events to '+currdir)
502 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION+'Events/'+gridpack_run_name):
503 shutil.copy(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/events.lhe.gz','events.lhe.gz')
504 else:
505 mglog.info('Events were already in place')
506
507 ls_dir(currdir)
508
509 mglog.info('Moving generated events to be in correct format for arrange_output().')
510 mglog.info('Unzipping generated events.')
511 unzip = stack_subprocess(['gunzip','-f','events.lhe.gz'])
512 unzip.wait()
513
514 mglog.info('Moving file over to '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe')
515 mkdir = stack_subprocess(['mkdir','-p',(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name)])
516 mkdir.wait()
517 shutil.move('events.lhe',MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe')
518
519 mglog.info('Re-zipping into dataset name '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe.gz')
520 rezip = stack_subprocess(['gzip',MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe'])
521 rezip.wait()
522
523 os.chdir(currdir)
524
525 # Now consider MadSpin:
526 if do_madspin:
527 # Move card back
528 os.rename(MADGRAPH_GRIDPACK_LOCATION+'/Cards/backup_madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+'/Cards/madspin_card.dat')
529 mglog.info('Decaying with MadSpin.')
530 add_madspin(process_dir=MADGRAPH_GRIDPACK_LOCATION)
531
532 mglog.info('Finished at '+str(time.asctime()))
533
534 return 0
535
536

◆ generate_prep()

python.MadGraphUtils.generate_prep ( process_dir)

Definition at line 56 of file MadGraphUtils.py.

56def generate_prep(process_dir):
57 global MADGRAPH_COMMAND_STACK
58 if not os.access('Cards_bkup',os.R_OK):
59 shutil.copytree(process_dir+'/Cards','Cards_bkup')
60 shutil.copyfile(process_dir+'/Source/make_opts','Cards_bkup/make_opts_bkup')
61 MADGRAPH_COMMAND_STACK += ['# In case this fails, Cards_bkup should be in your original run directory']
62 MADGRAPH_COMMAND_STACK += ['# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
63 MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup/*dat ${MGaMC_PROCESS_DIR}/Cards/']
64 MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
65 else:
66 mglog.warning('Found Cards_bkup directory existing. Suggests you are either running generation twice (a little funny) or are not using a clean directory.')
67 bkup_v = 1
68 while os.access('Cards_bkup_'+str(bkup_v),os.R_OK) and bkup_v<100:
69 bkup_v += 1
70 if bkup_v<100:
71 shutil.copytree(process_dir+'/Cards','Cards_bkup_'+str(bkup_v))
72 shutil.copyfile(process_dir+'/Source/make_opts','Cards_bkup_'+str(bkup_v)+'/make_opts_bkup')
73 MADGRAPH_COMMAND_STACK += ['# In case this fails, Cards_bkup should be in your original run directory']
74 MADGRAPH_COMMAND_STACK += ['# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
75 MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup_'+str(bkup_v)+'/*dat ${MGaMC_PROCESS_DIR}/Cards/']
76 MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup_'+str(bkup_v)+'/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
77 else:
78 mglog.warning('Way too many Cards_bkup* directories found. Giving up -- standalone script may not work.')
79
80

◆ get_cluster_type()

python.MadGraphUtils.get_cluster_type ( process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1838 of file MadGraphUtils.py.

1838def get_cluster_type(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1839 card_in = open(get_default_config_card(process_dir=process_dir),'r')
1840 for l in card_in.readlines():
1841 if 'cluster_type' not in l.split('#')[0]:
1842 continue
1843 cluster_type = l.split('#')[0].split('=')[1]
1844 mglog.info('Returning cluster type: '+cluster_type)
1845 return cluster_type
1846 return None
1847
1848
1849

◆ get_default_runcard()

python.MadGraphUtils.get_default_runcard ( process_dir = MADGRAPH_GRIDPACK_LOCATION)
 Copy the default runcard from one of several locations
to a local file with name run_card.tmp.dat

Definition at line 91 of file MadGraphUtils.py.

91def get_default_runcard(process_dir=MADGRAPH_GRIDPACK_LOCATION):
92 """ Copy the default runcard from one of several locations
93 to a local file with name run_card.tmp.dat"""
94 output_name = 'run_card.tmp.dat'
95
96 # Get the run card from the installation
97 run_card=process_dir+'/Cards/run_card.dat'
98 if os.access(run_card,os.R_OK):
99 mglog.info('Copying default run_card.dat from '+str(run_card))
100 shutil.copy(run_card,output_name)
101 return output_name
102 else:
103 run_card=process_dir+'/Cards/run_card_default.dat'
104 mglog.info('Fetching default run_card.dat from '+str(run_card))
105 if os.access(run_card,os.R_OK):
106 shutil.copy(run_card,output_name)
107 return output_name
108 else:
109 raise RuntimeError('Cannot find default run_card.dat or run_card_default.dat! I was looking here: %s'%run_card)
110
111

◆ get_expected_reweight_names()

python.MadGraphUtils.get_expected_reweight_names ( reweight_card_loc)

Definition at line 1198 of file MadGraphUtils.py.

1198def get_expected_reweight_names(reweight_card_loc):
1199 if reweight_card_loc is None:
1200 return []
1201 names=[]
1202 f_rw=open(reweight_card_loc)
1203 for line in f_rw:
1204 if 'launch' not in line:
1205 continue
1206 match=re.match(r'launch.*--rwgt_info\s*=\s*(\S+).*',line.strip())
1207 if len(match.groups())!=1:
1208 raise RuntimeError('Unexpected format of reweight card in line'+line)
1209 else:
1210 names+=[match.group(1)]
1211 f_rw.close()
1212 return names
1213

◆ get_expected_systematic_names()

python.MadGraphUtils.get_expected_systematic_names ( syst_setting)

Definition at line 1214 of file MadGraphUtils.py.

1214def get_expected_systematic_names(syst_setting):
1215 names=[]
1216 if syst_setting is None or 'central_pdf' not in syst_setting:
1217 mglog.warning("Systematics have not been defined via base fragment or 'MADGRAPH_PDFSETTING', cannot check for expected weights")
1218 return []
1219 if 'pdf_variations' in syst_setting and isinstance(syst_setting['pdf_variations'],list):
1220 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':syst_setting['central_pdf']}]
1221 for pdf in syst_setting['pdf_variations']:
1222 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':pdf+1}]
1223 if 'alternative_pdfs' in syst_setting and isinstance(syst_setting['alternative_pdfs'],list):
1224 for pdf in syst_setting['alternative_pdfs']:
1225 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':pdf}]
1226 if 'scale_variations' in syst_setting and isinstance(syst_setting['scale_variations'],list):
1227 for mur in syst_setting['scale_variations']:
1228 for muf in syst_setting['scale_variations']:
1229 names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':mur,'muf':muf,'pdf':syst_setting['central_pdf']}]
1230 return names
1231

◆ get_mg5_executable()

python.MadGraphUtils.get_mg5_executable ( )

Definition at line 733 of file MadGraphUtils.py.

733def get_mg5_executable():
734 madpath=os.environ['MADPATH']
735 if not os.access(madpath+'/bin/mg5_aMC',os.R_OK):
736 raise RuntimeError('mg5_aMC executable not found in '+madpath)
737 return madpath+'/bin/mg5_aMC'
738
739

◆ get_reweight_card()

python.MadGraphUtils.get_reweight_card ( process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1282 of file MadGraphUtils.py.

1282def get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1283 if os.access(process_dir+'/Cards/reweight_card.dat',os.R_OK):
1284 return process_dir+'/Cards/reweight_card.dat'
1285 return None
1286
1287

◆ is_gen_from_gridpack()

python.MadGraphUtils.is_gen_from_gridpack ( )
 Simple function for checking if there is a grid pack.
Relies on the specific location of the unpacked gridpack (madevent)
which is here set as a global variable. The gridpack is untarred by
the transform (Gen_tf.py) and no sign is sent to the job itself
that there is a gridpack in use except the file's existence

Definition at line 1646 of file MadGraphUtils.py.

1646def is_gen_from_gridpack():
1647 """ Simple function for checking if there is a grid pack.
1648 Relies on the specific location of the unpacked gridpack (madevent)
1649 which is here set as a global variable. The gridpack is untarred by
1650 the transform (Gen_tf.py) and no sign is sent to the job itself
1651 that there is a gridpack in use except the file's existence"""
1652 if os.access(MADGRAPH_GRIDPACK_LOCATION,os.R_OK):
1653 mglog.info('Located input grid pack area')
1654 return True
1655 return False
1656
1657
1658

◆ ls_dir()

python.MadGraphUtils.ls_dir ( directory)

Definition at line 1997 of file MadGraphUtils.py.

1997def ls_dir(directory):
1998 mglog.info('For your information, ls of '+directory+':')
1999 mglog.info( sorted( os.listdir( directory ) ) )
2000
2001# Final import of some code used in these functions

◆ madspin_on_lhe()

python.MadGraphUtils.madspin_on_lhe ( input_LHE,
madspin_card,
runArgs = None,
keep_original = False )
 Run MadSpin on an input LHE file. Takes the process
from the LHE file, so you don't need to have a process directory
set up in advance. Runs MadSpin and packs the LHE file up appropriately
Needs runArgs for the file handling

Definition at line 835 of file MadGraphUtils.py.

835def madspin_on_lhe(input_LHE,madspin_card,runArgs=None,keep_original=False):
836 """ Run MadSpin on an input LHE file. Takes the process
837 from the LHE file, so you don't need to have a process directory
838 set up in advance. Runs MadSpin and packs the LHE file up appropriately
839 Needs runArgs for the file handling"""
840 if not os.access(input_LHE,os.R_OK):
841 raise RuntimeError('Could not find LHE file '+input_LHE)
842 if not os.access(madspin_card,os.R_OK):
843 raise RuntimeError('Could not find input MadSpin card '+madspin_card)
844 if keep_original:
845 shutil.copy(input_LHE,input_LHE+'.original')
846 mglog.info('Put backup copy of LHE file at '+input_LHE+'.original')
847 # Start writing the card for execution
848 madspin_exec_card = open('madspin_exec_card','w')
849 madspin_exec_card.write('import '+input_LHE+'\n')
850 # Based on the original card
851 input_madspin_card = open(madspin_card,'r')
852 has_launch = False
853 for l in input_madspin_card.readlines():
854 commands = l.split('#')[0].split()
855 # Skip import of a file name that isn't our file
856 if len(commands)>1 and 'import'==commands[0] and not 'model'==commands[1]:
857 continue
858 # Check for a launch command
859 if len(commands)>0 and 'launch' == commands[0]:
860 has_launch = True
861 madspin_exec_card.write(l.strip()+'\n')
862 if not has_launch:
863 madspin_exec_card.write('launch\n')
864 madspin_exec_card.close()
865 input_madspin_card.close()
866 # Now get the madspin executable
867 madpath=os.environ['MADPATH']
868 if not os.access(madpath+'/MadSpin/madspin',os.R_OK):
869 raise RuntimeError('madspin executable not found in '+madpath)
870 mglog.info('Starting madspin at '+str(time.asctime()))
871 generate = stack_subprocess([python,madpath+'/MadSpin/madspin','madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
872 (out,err) = generate.communicate()
873 error_check(err,generate.returncode)
874 mglog.info('Done with madspin at '+str(time.asctime()))
875 # Should now have a re-zipped LHE file
876 # We now have to do a shortened version of arrange_output below
877 # Clean up in case a link or file was already there
878 if os.path.exists(os.getcwd()+'/events.lhe'):
879 os.remove(os.getcwd()+'/events.lhe')
880
881 mglog.info('Unzipping generated events.')
882 unzip = stack_subprocess(['gunzip','-f',input_LHE+'.gz'])
883 unzip.wait()
884
885 mglog.info('Putting a copy in place for the transform.')
886 mod_output = open(os.getcwd()+'/events.lhe','w')
887
888 #Removing empty lines in LHE
889 nEmpty=0
890 with open(input_LHE,'r') as fileobject:
891 for line in fileobject:
892 if line.strip():
893 mod_output.write(line)
894 else:
895 nEmpty=nEmpty+1
896 mod_output.close()
897
898 mglog.info('Removed '+str(nEmpty)+' empty lines from LHEF')
899
900 # Actually move over the dataset - this first part is horrible...
901 if runArgs is None:
902 raise RuntimeError('Must provide runArgs to madspin_on_lhe')
903
904 outputDS = runArgs.outputTXTFile if hasattr(runArgs,'outputTXTFile') else 'tmp_LHE_events.tar.gz'
905
906 mglog.info('Moving file over to '+outputDS.split('.tar.gz')[0]+'.events')
907 shutil.move(os.getcwd()+'/events.lhe',outputDS.split('.tar.gz')[0]+'.events')
908
909 mglog.info('Re-zipping into dataset name '+outputDS)
910 rezip = stack_subprocess(['tar','cvzf',outputDS,outputDS.split('.tar.gz')[0]+'.events'])
911 rezip.wait()
912
913 # shortening the outputDS in the case of an output TXT file
914 if hasattr(runArgs,'outputTXTFile') and runArgs.outputTXTFile is not None:
915 outputDS = outputDS.split('.TXT')[0]
916 # Do some fixing up for them
917 if runArgs is not None:
918 mglog.debug('Setting inputGenerator file to '+outputDS)
919 runArgs.inputGeneratorFile=outputDS
920
921

◆ modify_config_card()

python.MadGraphUtils.modify_config_card ( config_card_backup = None,
process_dir = MADGRAPH_GRIDPACK_LOCATION,
settings = {},
set_commented = True )
Build a new configuration from an existing one.
This function can get a fresh runcard from DATAPATH or start from the process directory.
Settings is a dictionary of keys (no spaces needed) and values to replace.

Definition at line 1781 of file MadGraphUtils.py.

1781def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
1782 """Build a new configuration from an existing one.
1783 This function can get a fresh runcard from DATAPATH or start from the process directory.
1784 Settings is a dictionary of keys (no spaces needed) and values to replace.
1785 """
1786 # Check for the default config card location
1787 config_card=get_default_config_card(process_dir=process_dir)
1788
1789 # The format is similar to the run card, but backwards
1790 mglog.info('Modifying config card located at '+config_card)
1791 if config_card_backup is not None:
1792 mglog.info('Keeping backup of original config card at '+config_card_backup)
1793 config_card_old = config_card_backup
1794 else:
1795 config_card_old = config_card+'.old_to_be_deleted'
1796 mglog.debug('Modifying config card settings: '+str(settings))
1797 if os.path.isfile(config_card_old):
1798 os.unlink(config_card_old) # delete old backup
1799 os.rename(config_card, config_card_old) # change name of original card
1800
1801 oldCard = open(config_card_old, 'r')
1802 newCard = open(config_card, 'w')
1803 used_settings = []
1804 for line in iter(oldCard):
1805 lmod = line if set_commented else line.split('#')[0]
1806 if '=' in lmod:
1807 modified = False
1808 for setting in settings:
1809 if setting not in lmod:
1810 continue
1811 # Assume we hit
1812 mglog.info('Setting '+setting.strip()+' to '+str(settings[setting]))
1813 newCard.write(' '+str(setting.strip())+' = '+str(settings[setting])+'\n')
1814 used_settings += [ setting.strip() ]
1815 modified = True
1816 break
1817 if modified:
1818 continue
1819 newCard.write(line)
1820
1821 # Clean up unused options
1822 for asetting in settings:
1823 if asetting in used_settings:
1824 continue
1825 if settings[asetting] is None:
1826 continue
1827 mglog.warning('Option '+asetting+' was not in the default config card. Adding by hand a setting to '+str(settings[asetting]) )
1828 newCard.write(' '+str(asetting)+' = '+str(settings[asetting])+'\n')
1829 # close files
1830 oldCard.close()
1831 newCard.close()
1832 mglog.info('Finished modification of config card.')
1833 if config_card_backup is None:
1834 os.unlink(config_card_old)
1835
1836
1837

◆ modify_param_card()

python.MadGraphUtils.modify_param_card ( param_card_input = None,
param_card_backup = None,
process_dir = MADGRAPH_GRIDPACK_LOCATION,
params = {},
output_location = None )
Build a new param_card.dat from an existing one.
Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
Keys can include MASS (for masses) and DECAY X (for decays of particle X)

Definition at line 1446 of file MadGraphUtils.py.

1446def modify_param_card(param_card_input=None,param_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,params={},output_location=None):
1447 """Build a new param_card.dat from an existing one.
1448 Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
1449 Keys can include MASS (for masses) and DECAY X (for decays of particle X)"""
1450 # Grab the old param card and move it into place
1451
1452 # Check for the default run card location
1453 if param_card_input is None:
1454 param_card_input=process_dir+'/Cards/param_card.dat'
1455 elif param_card_input is not None and not os.access(param_card_input,os.R_OK):
1456 paramcard = subprocess.Popen(['get_files','-data',param_card_input])
1457 paramcard.wait()
1458 if not os.access(param_card_input,os.R_OK):
1459 raise RuntimeError('Could not get param card '+param_card_input)
1460 mglog.info('Using input param card at '+param_card_input)
1461
1462 #ensure all blocknames and paramnames are upper case
1463 paramsUpper = {}
1464 for blockName in list(params.keys()):
1465 paramsUpper[blockName.upper()] = {}
1466 for paramName in list(params[blockName].keys()):
1467 paramsUpper[blockName.upper()][paramName.upper()] = params[blockName][paramName]
1468
1469 if param_card_backup is not None:
1470 mglog.info('Keeping backup of original param card at '+param_card_backup)
1471 param_card_old = param_card_backup
1472 else:
1473 param_card_old = param_card_input+'.old_to_be_deleted'
1474 if os.path.isfile(param_card_old):
1475 os.unlink(param_card_old) # delete old backup
1476 os.rename(param_card_input, param_card_old) # change name of original card
1477
1478 oldcard = open(param_card_old,'r')
1479 param_card_location= process_dir+'/Cards/param_card.dat' if output_location is None else output_location
1480 newcard = open(param_card_location,'w')
1481 decayEdit = False #only becomes true in a DECAY block when specifying the BR
1482 blockName = ""
1483 doneParams = {} #tracks which params have been done
1484 for linewithcomment in oldcard:
1485 line=linewithcomment.split('#')[0]
1486 if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
1487 and len(line.strip().split()) > 1:
1488 if decayEdit and blockName == 'DECAY':
1489 decayEdit = False # Start a new DECAY block
1490 pos = 0 if line.strip().startswith('DECAY') else 1
1491 if blockName=='MASS' and 'MASS' in paramsUpper:
1492 # Any residual masses to set?
1493 if "MASS" in doneParams:
1494 leftOvers = [ x for x in paramsUpper['MASS'] if x not in doneParams['MASS'] ]
1495 else:
1496 leftOvers = [ x for x in paramsUpper['MASS'] ]
1497
1498 for pdg_id in leftOvers:
1499 mglog.warning('Adding mass line for '+str(pdg_id)+' = '+str(paramsUpper['MASS'][pdg_id])+' which was not in original param card')
1500 newcard.write(' '+str(pdg_id)+' '+str(paramsUpper['MASS'][pdg_id])+'\n')
1501 doneParams['MASS'][pdg_id]=True
1502 if blockName=='DECAY' and 'DECAY' not in line.strip().upper() and 'DECAY' in paramsUpper:
1503 # Any residual decays to include?
1504 leftOvers = [ x for x in paramsUpper['DECAY'] if x not in doneParams['DECAY'] ]
1505 for pdg_id in leftOvers:
1506 mglog.warning('Adding decay for pdg id '+str(pdg_id)+' which was not in the original param card')
1507 newcard.write( paramsUpper['DECAY'][pdg_id].strip()+'\n' )
1508 doneParams['DECAY'][pdg_id]=True
1509 blockName = line.strip().upper().split()[pos]
1510 if decayEdit:
1511 continue #skipping these lines because we are in an edit of the DECAY BR
1512
1513 akey = None
1514 if blockName != 'DECAY' and len(line.strip().split()) > 0:
1515 # The line is already without the comment.
1516 # In the case of mixing matrices this is a bit tricky
1517 if len(line.split())==2:
1518 akey = line.upper().strip().split()[0]
1519 else:
1520 # Take everything but the last word
1521 akey = line.upper().strip()[:line.strip().rfind(' ')].strip()
1522 elif blockName == 'DECAY' and len(line.strip().split()) > 1:
1523 akey = line.strip().split()[1]
1524 if akey is None:
1525 newcard.write(linewithcomment)
1526 continue
1527
1528 #check if we have params for this block
1529 if blockName not in paramsUpper:
1530 newcard.write(linewithcomment)
1531 continue
1532 blockParams = paramsUpper[blockName]
1533 # Check the spacing in the key
1534 akey = find_key_and_update(akey,blockParams)
1535
1536 # look for a string key, which would follow a #
1537 stringkey = None
1538 if '#' in linewithcomment: #ignores comment lines
1539 stringkey = linewithcomment[linewithcomment.find('#')+1:].strip()
1540 if len(stringkey.split()) > 0:
1541 stringkey = stringkey.split()[0].upper()
1542
1543 if akey not in blockParams and not (stringkey is not None and stringkey in blockParams):
1544 newcard.write(linewithcomment)
1545 continue
1546
1547 if akey in blockParams and (stringkey is not None and stringkey in blockParams):
1548 raise RuntimeError('Conflicting use of numeric and string keys '+akey+' and '+stringkey)
1549
1550 theParam = blockParams.get(akey,blockParams[stringkey] if stringkey in blockParams else None)
1551 if blockName not in doneParams:
1552 doneParams[blockName] = {}
1553 if akey in blockParams:
1554 doneParams[blockName][akey]=True
1555 elif stringkey is not None and stringkey in blockParams:
1556 doneParams[blockName][stringkey]=True
1557
1558 #do special case of DECAY block
1559 if blockName=="DECAY":
1560 if theParam.splitlines()[0].split()[0].upper()=="DECAY":
1561 #specifying the full decay block
1562 for newline in theParam.splitlines():
1563 newcard.write(newline+'\n')
1564 mglog.info(newline)
1565 decayEdit = True
1566 else: #just updating the total width
1567 newcard.write('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
1568 mglog.info('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
1569 # second special case of QNUMBERS
1570 elif blockName=='QNUMBERS':
1571 #specifying the full QNUMBERS block
1572 for newline in theParam.splitlines():
1573 newcard.write(newline+'\n')
1574 mglog.info(newline)
1575 decayEdit = True
1576 else: #just updating the parameter
1577 newcard.write(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
1578 mglog.info(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
1579 # Done editing the line!
1580
1581 #check that all specified parameters have been updated (helps to catch typos)
1582 for blockName in paramsUpper:
1583 if blockName not in doneParams and len(paramsUpper[blockName].keys())>0:
1584 raise RuntimeError('Did not find any of the parameters for block '+blockName+' in param_card')
1585 for paramName in paramsUpper[blockName]:
1586 if paramName not in doneParams[blockName]:
1587 raise RuntimeError('Was not able to replace parameter '+paramName+' in param_card')
1588
1589 # Close up and return
1590 oldcard.close()
1591 newcard.close()
1592
1593
1594
int upper(int c)

◆ modify_run_card()

python.MadGraphUtils.modify_run_card ( run_card_input = None,
run_card_backup = None,
process_dir = MADGRAPH_GRIDPACK_LOCATION,
runArgs = None,
settings = {},
skipBaseFragment = False )
Build a new run_card.dat from an existing one.
This function can get a fresh runcard from DATAPATH or start from the process directory.
Settings is a dictionary of keys (no spaces needed) and values to replace.

Definition at line 1659 of file MadGraphUtils.py.

1659def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
1660 """Build a new run_card.dat from an existing one.
1661 This function can get a fresh runcard from DATAPATH or start from the process directory.
1662 Settings is a dictionary of keys (no spaces needed) and values to replace.
1663 """
1664
1665 # Operate on lower case settings, and choose the capitalization MG5 has as the default (or all lower case)
1666 settings_lower = {}
1667 for s in list(settings.keys()):
1668 settings_lower[s.lower()] = settings[s]
1669
1670 # Check for the default run card location
1671 if run_card_input is None:
1672 run_card_input=get_default_runcard(process_dir)
1673 elif run_card_input is not None and not os.access(run_card_input,os.R_OK):
1674 runcard = subprocess.Popen(['get_files','-data',run_card_input])
1675 runcard.wait()
1676 if not os.access(run_card_input,os.R_OK):
1677 raise RuntimeError('Could not get run card '+run_card_input)
1678
1679 # guess NLO
1680 isNLO=is_NLO_run(process_dir=process_dir)
1681 # add gobal PDF and scale uncertainty config to extras, except PDF or weights for syscal config are explictly set
1682 if not skipBaseFragment:
1683 MadGraphControl.MadGraphSystematicsUtils.setup_pdf_and_systematic_weights(MADGRAPH_PDFSETTING,settings_lower,isNLO)
1684
1685 # Get some info out of the runArgs
1686 if runArgs is not None:
1687 beamEnergy,rand_seed = get_runArgs_info(runArgs)
1688 if 'iseed' not in settings_lower:
1689 settings_lower['iseed']=rand_seed
1690 if not isNLO and 'python_seed' not in settings_lower:
1691 settings_lower['python_seed']=rand_seed
1692 if 'beamenergy' in settings_lower:
1693 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']))
1694 beamEnergy=settings_lower['beamenergy']
1695 settings_lower.pop('beamenergy')
1696 if 'ebeam1' not in settings_lower:
1697 settings_lower['ebeam1']=beamEnergy
1698 if 'ebeam2' not in settings_lower:
1699 settings_lower['ebeam2']=beamEnergy
1700 # Make sure nevents is an integer
1701 if 'nevents' in settings_lower:
1702 settings_lower['nevents'] = int(settings_lower['nevents'])
1703
1704 # Normalise custom_fcts early so the rewritten run_card uses the full path
1705 if 'custom_fcts' in settings_lower and settings_lower['custom_fcts']:
1706 raw_name = str(settings_lower['custom_fcts']).split()[0]
1707 # Determine jobConfig directory
1708 if runArgs is not None and hasattr(runArgs, 'jobConfig'):
1709 cfgdir = runArgs.jobConfig[0] if isinstance(runArgs.jobConfig, (list, tuple)) else runArgs.jobConfig
1710 # Build full path and make absolute
1711 full_path = os.path.join(cfgdir, raw_name)
1712 settings_lower['custom_fcts'] = os.path.abspath(full_path)
1713 print(f"Using custom function(s), specified in custom_fcts with path: {settings_lower['custom_fcts']}")
1714 else:
1715 # For internal tests, where jobConfig is not set
1716 settings_lower['custom_fcts'] = os.path.abspath(raw_name)
1717
1718 mglog.info('Modifying run card located at '+run_card_input)
1719 if run_card_backup is not None:
1720 mglog.info('Keeping backup of original run card at '+run_card_backup)
1721 run_card_old = run_card_backup
1722 else:
1723 run_card_old = run_card_input+'.old_to_be_deleted'
1724 mglog.debug('Modifying runcard settings: '+str(settings_lower))
1725 if os.path.isfile(run_card_old):
1726 os.unlink(run_card_old) # delete old backup
1727 os.rename(run_card_input, run_card_old) # change name of original card
1728
1729 oldCard = open(run_card_old, 'r')
1730 newCard = open(process_dir+'/Cards/run_card.dat', 'w')
1731 used_settings = []
1732 for line in iter(oldCard):
1733 if not line.strip().startswith('#'): # line commented out
1734 command = line.split('!', 1)[0]
1735 comment = line.split('!', 1)[1] if '!' in line else ''
1736 if '=' in command:
1737 setting = command.split('=')[-1] #.strip()
1738 stripped_setting = setting.strip()
1739 oldValue = '='.join(command.split('=')[:-1])
1740 if stripped_setting.lower() in settings_lower:
1741 # if setting set to 'None' it will be removed from run_card
1742 if settings_lower[stripped_setting.lower()] is None:
1743 line=''
1744 mglog.info('Removing '+stripped_setting+'.')
1745 used_settings += [ stripped_setting.lower() ]
1746 else:
1747 if stripped_setting.lower() == 'custom_fcts':
1748 # Overwrite completely to avoid duplicating in custom_fcts, else MadGraph will crash
1749 line = ' '+str(settings_lower[stripped_setting.lower()])+' = '+setting
1750 if comment != '':
1751 line += ' !'+comment
1752 else:
1753 line = oldValue.replace(oldValue.strip(), str(settings_lower[stripped_setting.lower()]))+'='+setting
1754 if comment != '':
1755 line += ' !' + comment
1756 mglog.info('Setting '+stripped_setting+' = '+str(settings_lower[stripped_setting.lower()]))
1757 used_settings += [ stripped_setting.lower() ]
1758 newCard.write(line.strip()+'\n')
1759
1760 # Check whether mcatnlo_delta is applied to setup pythia8 path
1761 if 'mcatnlo_delta' in settings_lower:
1762 if settings_lower['mcatnlo_delta'] == 'True':
1763 modify_config_card(process_dir=process_dir,settings={'pythia8_path':os.getenv("PY8PATH")})
1764
1765 # Clean up unused options
1766 for asetting in settings_lower:
1767 if asetting in used_settings:
1768 continue
1769 if settings_lower[asetting] is None:
1770 continue
1771 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]) )
1772 newCard.write( ' '+str(settings_lower[asetting])+' = '+str(asetting)+'\n')
1773 # close files
1774 oldCard.close()
1775 newCard.close()
1776 mglog.info('Finished modification of run card.')
1777 if run_card_backup is None:
1778 os.unlink(run_card_old)
1779
1780
void print(char *figname, TCanvas *c1)

◆ new_process()

python.MadGraphUtils.new_process ( process = 'generate p p > t t~\noutput -f',
plugin = None,
keepJpegs = False,
usePMGSettings = False )

Definition at line 81 of file MadGraphUtils.py.

81def new_process(process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False):
82 global my_MGC_instance
83 print(process,plugin,keepJpegs,usePMGSettings)
84 my_MGC_instance = MGControl(process, plugin, keepJpegs, usePMGSettings)
85 # Sync options as an intermediate solution until the full migration is done
86 modify_run_card(process_dir=my_MGC_instance.process_dir,settings=my_MGC_instance.runCardDict,skipBaseFragment=True)
87 # This should be enabled ASAP, but isn't yet ready
88 #modify_config_card(process_dir=my_MGC_instance.process_dir,settings=my_MGC_instance.configCardDict)
89 return my_MGC_instance.process_dir
90

◆ print_cards()

python.MadGraphUtils.print_cards ( proc_card = 'proc_card_mg5.dat',
run_card = None,
param_card = None,
madspin_card = None,
reweight_card = None,
warn_on_missing = True )

Definition at line 1601 of file MadGraphUtils.py.

1601def print_cards(proc_card='proc_card_mg5.dat',run_card=None,param_card=None,madspin_card=None,reweight_card=None,warn_on_missing=True):
1602 if os.access(proc_card,os.R_OK):
1603 mglog.info("proc_card:")
1604 procCard = subprocess.Popen(['cat',proc_card])
1605 procCard.wait()
1606 elif warn_on_missing:
1607 mglog.warning('No proc_card: '+proc_card+' found')
1608
1609 if run_card is not None and os.access(run_card,os.R_OK):
1610 mglog.info("run_card:")
1611 runCard = subprocess.Popen(['cat',run_card])
1612 runCard.wait()
1613 elif run_card is not None and warn_on_missing:
1614 mglog.warning('No run_card: '+run_card+' found')
1615 else:
1616 mglog.info('Default run card in use')
1617
1618 if param_card is not None and os.access(param_card,os.R_OK):
1619 mglog.info("param_card:")
1620 paramCard = subprocess.Popen(['cat',param_card])
1621 paramCard.wait()
1622 elif param_card is not None and warn_on_missing:
1623 mglog.warning('No param_card: '+param_card+' found')
1624 else:
1625 mglog.info('Default param card in use')
1626
1627 if madspin_card is not None and os.access(madspin_card,os.R_OK):
1628 mglog.info("madspin_card:")
1629 madspinCard = subprocess.Popen(['cat',madspin_card])
1630 madspinCard.wait()
1631 elif madspin_card is not None and warn_on_missing:
1632 mglog.warning('No madspin_card: '+madspin_card+' found')
1633 else:
1634 mglog.info('No madspin card in use')
1635
1636 if reweight_card is not None and os.access(reweight_card,os.R_OK):
1637 mglog.info("reweight_card:")
1638 madspinCard = subprocess.Popen(['cat',reweight_card])
1639 madspinCard.wait()
1640 elif reweight_card is not None and warn_on_missing:
1641 mglog.warning('No reweight_card: '+reweight_card+' found')
1642 else:
1643 mglog.info('No reweight card in use')
1644
1645

◆ print_cards_from_dir()

python.MadGraphUtils.print_cards_from_dir ( process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1595 of file MadGraphUtils.py.

1595def print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1596 card_dir=process_dir+'/Cards/'
1597 print_cards(proc_card=card_dir+'proc_card_mg5.dat',run_card=card_dir+'run_card.dat',param_card=card_dir+'param_card.dat',\
1598 madspin_card=card_dir+'madspin_card.dat',reweight_card=card_dir+'reweight_card.dat',warn_on_missing=False)
1599
1600

◆ run_card_consistency_check()

python.MadGraphUtils.run_card_consistency_check ( isNLO = False,
process_dir = '.' )

Definition at line 1850 of file MadGraphUtils.py.

1850def run_card_consistency_check(isNLO=False,process_dir='.'):
1851 cardpath=process_dir+'/Cards/run_card.dat'
1852 mydict=getDictFromCard(cardpath)
1853 # We should always use event_norm = average [AGENE-1725] otherwise Pythia cross sections are wrong
1854 # Modification: average or bias is ok; sum is incorrect. Change the test to set sum to average
1855 if checkSetting('event_norm','sum',mydict):
1856 modify_run_card(process_dir=process_dir,settings={'event_norm':'average'},skipBaseFragment=True)
1857 mglog.warning("setting event_norm to average, there is basically no use case where event_norm=sum is a good idea")
1858
1859 if not isNLO:
1860 #Check CKKW-L setting
1861 if 'ktdurham' in mydict and float(mydict['ktdurham']) > 0 and int(mydict['ickkw']) != 0:
1862 log='Bad combination of settings for CKKW-L merging! ktdurham=%s and ickkw=%s.'%(mydict['ktdurham'],mydict['ickkw'])
1863 mglog.error(log)
1864 raise RuntimeError(log)
1865
1866 # Check if user is trying to use deprecated syscalc arguments with the other systematics script
1867 if 'systematics_program' not in mydict or mydict['systematics_program']=='systematics':
1868 syscalc_settings=['sys_pdf', 'sys_scalefact', 'sys_alpsfact', 'sys_matchscale']
1869 found_syscalc_setting=False
1870 for s in syscalc_settings:
1871 if s in mydict:
1872 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)')
1873 found_syscalc_setting=True
1874 if found_syscalc_setting:
1875 syst_arguments=MadGraphControl.MadGraphSystematicsUtils.convertSysCalcArguments(mydict)
1876 mglog.info('Converted syscalc arguments to systematics arguments: '+syst_arguments)
1877 syst_settings_update={'systematics_arguments':syst_arguments}
1878 for s in syscalc_settings:
1879 syst_settings_update[s]=None
1880 modify_run_card(process_dir=process_dir,settings=syst_settings_update,skipBaseFragment=True)
1881
1882
1883 # usually the pdf and systematics should be set during modify_run_card
1884 # but check again in case the user did not call the function or provides a different card here
1885 mglog.info('Checking PDF and systematics settings')
1886 if not MadGraphControl.MadGraphSystematicsUtils.base_fragment_setup_check(MADGRAPH_PDFSETTING,mydict,isNLO):
1887 # still need to set pdf and systematics
1888 syst_settings=MadGraphControl.MadGraphSystematicsUtils.get_pdf_and_systematic_settings(MADGRAPH_PDFSETTING,isNLO)
1889 modify_run_card(process_dir=process_dir,settings=syst_settings,skipBaseFragment=True)
1890
1891 mydict_new=getDictFromCard(cardpath)
1892 if 'systematics_arguments' in mydict_new:
1893 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict_new['systematics_arguments'])
1894 if 'weight_info' not in systematics_arguments:
1895 mglog.info('Enforcing systematic weight name convention')
1896 dyn = None
1897 if '--dyn' in systematics_arguments or ' dyn' in systematics_arguments:
1898 if '--dyn' in systematics_arguments:
1899 dyn = systematics_arguments.split('--dyn')[1]
1900 if ' dyn' in systematics_arguments:
1901 dyn = systematics_arguments.split(' dyn')[1]
1902 dyn = dyn.replace('\'',' ').replace('=',' ').split()[0]
1903 if dyn is not None and len(dyn.split(','))>1:
1904 systematics_arguments['weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO_ALTDYNSCALES
1905 else:
1906 systematics_arguments['weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO
1907 modify_run_card(process_dir=process_dir,settings={'systematics_arguments':MadGraphControl.MadGraphSystematicsUtils.write_systematics_arguments(systematics_arguments)},skipBaseFragment=True)
1908
1909 if not isNLO:
1910 if 'python_seed' not in mydict:
1911 mglog.warning('No python seed set in run_card -- adding one with same value as iseed')
1912 modify_run_card(process_dir=process_dir,settings={'python_seed':mydict['iseed']},skipBaseFragment=True)
1913
1914 # consistency check of 4/5 flavour shceme settings
1915 FS_updates={}
1916 proton_5flav = False
1917 jet_5flav = False
1918 with open(process_dir+'/Cards/proc_card_mg5.dat', 'r') as file:
1919 content = file.readlines()
1920 for rawline in content:
1921 line = rawline.split('#')[0]
1922 if line.startswith("define p"):
1923 if ('b' in line.split() and 'b~' in line.split()) or ('5' in line.split() and '-5' in line.split()):
1924 proton_5flav = True
1925 if 'j' in line.split() and jet_5flav:
1926 proton_5flav = True
1927 if line.startswith("define j"):
1928 if ('b' in line.split() and 'b~' in line.split()) or ('5' in line.split() and '-5' in line.split()):
1929 jet_5flav = True
1930 if 'p' in line.split() and proton_5flav:
1931 jet_5flav = True
1932 if proton_5flav or jet_5flav:
1933 FS_updates['asrwgtflavor'] = 5
1934 if not proton_5flav:
1935 mglog.warning('Found 5-flavour jets but 4-flavour proton. This is inconsistent - please pick one.')
1936 mglog.warning('Will proceed assuming 5-flavour scheme.')
1937 if not jet_5flav:
1938 mglog.warning('Found 5-flavour protons but 4-flavour jets. This is inconsistent - please pick one.')
1939 mglog.warning('Will proceed assuming 5-flavour scheme.')
1940 else:
1941 FS_updates['asrwgtflavor'] = 4
1942
1943 if len(FS_updates)==0:
1944 mglog.warning(f'Could not identify 4- or 5-flavor scheme from process card {process_dir}/Cards/proc_card_mg5.dat')
1945
1946 if 'asrwgtflavor' in mydict or 'maxjetflavor' in mydict or 'pdgs_for_merging_cut' in mydict:
1947 if FS_updates['asrwgtflavor'] == 5:
1948 # Process card says we are in the five-flavor scheme
1949 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']):
1950 # Inconsistent setting detected; warn the users and correct the settings
1951 mglog.warning('b and b~ included in p and j for 5-flavor scheme but run card settings are inconsistent; adjusting run card')
1952 run_card_updates = {'asrwgtflavor': 5, 'maxjetflavor': 5, 'pdgs_for_merging_cut': '1, 2, 3, 4, 5, 21'}
1953 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
1954 modify_param_card(process_dir=process_dir, params={'MASS': {'5': '0.000000e+00'}})
1955 else:
1956 mglog.debug('Consistent 5-flavor scheme setup detected.')
1957 if FS_updates['asrwgtflavor'] == 4:
1958 # Process card says we are in the four-flavor scheme
1959 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']):
1960 # Inconsistent setting detected; warn the users and correct the settings
1961 mglog.warning('b and b~ not included in p and j (4-flavor scheme) but run card settings are inconsistent; adjusting run card')
1962 run_card_updates = {'asrwgtflavor': 4, 'maxjetflavor': 4, 'pdgs_for_merging_cut': '1, 2, 3, 4, 21'}
1963 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
1964 modify_param_card(process_dir=process_dir, params={'MASS': {'5': '4.700000e+00'}})
1965 else:
1966 mglog.debug('Consistent 4-flavor scheme setup detected.')
1967 else:
1968 # Flavor scheme setup is missing, adding by hand
1969 if FS_updates['asrwgtflavor'] == 4:
1970 # Warn the users and add the settings according to process card
1971 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.')
1972 run_card_updates = {'asrwgtflavor': 4, 'maxjetflavor': 4, 'pdgs_for_merging_cut': '1, 2, 3, 4, 21'}
1973 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
1974 modify_param_card(process_dir=process_dir, params={'MASS': {'5': '4.700000e+00'}})
1975 elif FS_updates['asrwgtflavor'] == 5:
1976 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.')
1977 run_card_updates = {'asrwgtflavor': 5, 'maxjetflavor': 5, 'pdgs_for_merging_cut': '1, 2, 3, 4, 5, 21'}
1978 modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
1979 modify_param_card(process_dir=process_dir, params={'MASS': {'5': '0.000000e+00'}})
1980
1981 mglog.info('Finished checking run card - All OK!')
1982

◆ setNCores()

python.MadGraphUtils.setNCores ( process_dir,
Ncores = None )

Definition at line 715 of file MadGraphUtils.py.

715def setNCores(process_dir, Ncores=None):
716 my_Ncores = Ncores
717 my_runMode = 2 if 'ATHENA_CORE_NUMBER' in os.environ else 0
718 if Ncores is None and 'ATHENA_CORE_NUMBER' in os.environ and int(os.environ['ATHENA_CORE_NUMBER'])>0:
719 my_Ncores = int(os.environ['ATHENA_CORE_NUMBER'])
720 my_runMode = 2
721 if my_Ncores is None:
722 mglog.info('Setting up for serial run')
723 my_Ncores = 1
724
725 modify_config_card(process_dir=process_dir,settings={'nb_core':my_Ncores,'run_mode':my_runMode,'automatic_html_opening':'False'})
726
727
728
729
730
731
732

◆ setup_bias_module()

python.MadGraphUtils.setup_bias_module ( bias_module,
process_dir )

Definition at line 1232 of file MadGraphUtils.py.

1232def setup_bias_module(bias_module,process_dir):
1233 run_card = process_dir+'/Cards/run_card.dat'
1234 if isinstance(bias_module,tuple):
1235 mglog.info('Using bias module '+bias_module[0])
1236 the_run_card = open(run_card,'r')
1237 for line in the_run_card:
1238 if 'bias_module' in line and not bias_module[0] in line:
1239 raise RuntimeError('You need to add the bias module '+bias_module[0]+' to the run card to actually run it')
1240 the_run_card.close()
1241 if len(bias_module)!=3:
1242 raise RuntimeError('Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1243 bias_module_newpath=process_dir+'/Source/BIAS/'+bias_module[0]
1244 os.makedirs(bias_module_newpath)
1245 bias_module_file=open(bias_module_newpath+'/'+bias_module[0]+'.f','w')
1246 bias_module_file.write(bias_module[1])
1247 bias_module_file.close()
1248 bias_module_make_file=open(bias_module_newpath+'/Makefile','w')
1249 bias_module_make_file.write(bias_module[2])
1250 bias_module_make_file.close()
1251 else:
1252 mglog.info('Using bias module '+bias_module)
1253 bias_module_name=bias_module.split('/')[-1].replace('.gz','')
1254 bias_module_name=bias_module_name.replace('.tar','')
1255 the_run_card = open(run_card,'r')
1256 for line in the_run_card:
1257 if 'bias_module' in line and bias_module_name not in line:
1258 raise RuntimeError('You need to add the bias module '+bias_module_name+' to the run card to actually run it')
1259 the_run_card.close()
1260
1261 if os.path.exists(bias_module+'.tar.gz'):
1262 bias_module_path=bias_module+'.tar.gz'
1263 elif os.path.exists(bias_module+'.gz'):
1264 bias_module_path=bias_module+'.gz'
1265 elif os.path.exists(bias_module):
1266 bias_module_path=bias_module
1267 else:
1268 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')
1269 return 1
1270 bias_module_newpath=process_dir+'/Source/BIAS/'+bias_module_path.split('/')[-1]
1271 mglog.info('Copying bias module into place: '+bias_module_newpath)
1272 shutil.copy(bias_module_path,bias_module_newpath)
1273 mglog.info('Unpacking bias module')
1274 if bias_module_newpath.endswith('.tar.gz'):
1275 untar = stack_subprocess(['tar','xvzf',bias_module_newpath,'--directory='+process_dir+'/Source/BIAS/'])
1276 untar.wait()
1277 elif bias_module_path.endswith('.gz'):
1278 gunzip = stack_subprocess(['gunzip',bias_module_newpath])
1279 gunzip.wait()
1280
1281

◆ setupFastjet()

python.MadGraphUtils.setupFastjet ( process_dir = None)

Definition at line 537 of file MadGraphUtils.py.

537def setupFastjet(process_dir=None):
538
539 isNLO=is_NLO_run(process_dir=process_dir)
540
541 mglog.info('Path to fastjet install dir: '+os.environ['FASTJETPATH'])
542 fastjetconfig = os.environ['FASTJETPATH']+'/bin/fastjet-config'
543
544 mglog.info('fastjet-config --version: '+str(subprocess.Popen([fastjetconfig, '--version'],stdout = subprocess.PIPE).stdout.read().strip()))
545 mglog.info('fastjet-config --prefix: '+str(subprocess.Popen([fastjetconfig, '--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
546
547 if not isNLO:
548 config_card=process_dir+'/Cards/me5_configuration.txt'
549 else:
550 config_card=process_dir+'/Cards/amcatnlo_configuration.txt'
551
552 oldcard = open(config_card,'r')
553 newcard = open(config_card+'.tmp','w')
554
555 for line in oldcard:
556 if 'fastjet = ' in line:
557 newcard.write('fastjet = '+fastjetconfig+'\n')
558 mglog.info('Setting fastjet = '+fastjetconfig+' in '+config_card)
559 else:
560 newcard.write(line)
561 oldcard.close()
562 newcard.close()
563 shutil.move(config_card+'.tmp',config_card)
564
565 return
566
567
568

◆ setupLHAPDF()

python.MadGraphUtils.setupLHAPDF ( process_dir = None,
extlhapath = None,
allow_links = True )

Definition at line 569 of file MadGraphUtils.py.

569def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
570 isNLO=is_NLO_run(process_dir=process_dir)
571
572 origLHAPATH=os.environ['LHAPATH']
573 origLHAPDF_DATA_PATH=os.environ['LHAPDF_DATA_PATH']
574
575 LHAPATH,LHADATAPATH=get_LHAPDF_PATHS()
576
577 pdfname=''
578 pdfid=-999
579
580
581 run_card=process_dir+'/Cards/run_card.dat'
582 mydict=getDictFromCard(run_card)
583
584 if mydict["pdlabel"].replace("'","") == 'lhapdf':
585 #Make local LHAPDF dir
586 mglog.info('creating local LHAPDF dir: MGC_LHAPDF/')
587 if os.path.islink('MGC_LHAPDF/'):
588 os.unlink('MGC_LHAPDF/')
589 elif os.path.isdir('MGC_LHAPDF/'):
590 shutil.rmtree('MGC_LHAPDF/')
591
592 newMGCLHA='MGC_LHAPDF/'
593
594 mkdir = subprocess.Popen(['mkdir','-p',newMGCLHA])
595 mkdir.wait()
596
597 pdfs_used=[ int(x) for x in mydict['lhaid'].replace(' ',',').split(',') ]
598 # included systematics pdfs here
599 if 'sys_pdf' in mydict:
600 sys_pdf=mydict['sys_pdf'].replace('&&',' ').split()
601 for s in sys_pdf:
602 if s.isdigit():
603 idx=int(s)
604 if idx>1000: # the sys_pdf syntax is such that small numbers are used to specify the subpdf index
605 pdfs_used.append(idx)
606 else:
607 pdfs_used.append(s)
608 if 'systematics_arguments' in mydict:
609 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict['systematics_arguments'])
610 if 'pdf' in systematics_arguments:
611 sys_pdf=systematics_arguments['pdf'].replace(',',' ').replace('@',' ').split()
612 for s in sys_pdf:
613 if s.isdigit():
614 idx=int(s)
615 if idx>1000: # the sys_pdf syntax is such that small numbers are used to specify the subpdf index
616 pdfs_used.append(idx)
617 else:
618 pdfs_used.append(s)
619 for pdf in pdfs_used:
620 if isinstance(pdf,str) and (pdf.lower()=='errorset' or pdf.lower()=='central'):
621 continue
622 # new function to get both lhapdf id and name
623 pdfid,pdfname=get_lhapdf_id_and_name(pdf)
624 mglog.info("Found LHAPDF ID="+str(pdfid)+", name="+pdfname)
625
626 if not os.path.exists(newMGCLHA+pdfname) and not os.path.lexists(newMGCLHA+pdfname):
627 if not os.path.exists(LHADATAPATH+'/'+pdfname):
628 mglog.warning('PDF not installed at '+LHADATAPATH+'/'+pdfname)
629 if allow_links:
630 mglog.info('linking '+LHADATAPATH+'/'+pdfname+' --> '+newMGCLHA+pdfname)
631 os.symlink(LHADATAPATH+'/'+pdfname,newMGCLHA+pdfname)
632 else:
633 mglog.info('copying '+LHADATAPATH+'/'+pdfname+' --> '+newMGCLHA+pdfname)
634 shutil.copytree(LHADATAPATH+'/'+pdfname,newMGCLHA+pdfname)
635
636 if allow_links:
637 mglog.info('linking '+LHADATAPATH+'/pdfsets.index --> '+newMGCLHA+'pdfsets.index')
638 os.symlink(LHADATAPATH+'/pdfsets.index',newMGCLHA+'pdfsets.index')
639
640 atlasLHADATAPATH=LHADATAPATH.replace('sft.cern.ch/lcg/external/lhapdfsets/current','atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
641 mglog.info('linking '+atlasLHADATAPATH+'/lhapdf.conf --> '+newMGCLHA+'lhapdf.conf')
642 os.symlink(atlasLHADATAPATH+'/lhapdf.conf',newMGCLHA+'lhapdf.conf')
643 else:
644 mglog.info('copying '+LHADATAPATH+'/pdfsets.index --> '+newMGCLHA+'pdfsets.index')
645 shutil.copy2(LHADATAPATH+'/pdfsets.index',newMGCLHA+'pdfsets.index')
646
647 atlasLHADATAPATH=LHADATAPATH.replace('sft.cern.ch/lcg/external/lhapdfsets/current','atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
648 mglog.info('copying '+atlasLHADATAPATH+'/lhapdf.conf -->'+newMGCLHA+'lhapdf.conf')
649 shutil.copy2(atlasLHADATAPATH+'/lhapdf.conf',newMGCLHA+'lhapdf.conf')
650
651
652 LHADATAPATH=os.getcwd()+'/MGC_LHAPDF'
653
654 else:
655 mglog.info('Not using LHAPDF')
656 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
657
658
659 if isNLO:
660 os.environ['LHAPDF_DATA_PATH']=LHADATAPATH
661
662 mglog.info('Path to LHAPDF install dir: '+LHAPATH)
663 mglog.info('Path to LHAPDF data dir: '+LHADATAPATH)
664 if not os.path.isdir(LHADATAPATH):
665 raise RuntimeError('LHAPDF data dir not accesible: '+LHADATAPATH)
666 if not os.path.isdir(LHAPATH):
667 raise RuntimeError('LHAPDF path dir not accesible: '+LHAPATH)
668
669 # Dealing with LHAPDF
670 if extlhapath:
671 lhapdfconfig=extlhapath
672 if not os.access(lhapdfconfig,os.X_OK):
673 raise RuntimeError('Failed to find valid external lhapdf-config at '+lhapdfconfig)
674 LHADATAPATH=subprocess.Popen([lhapdfconfig, '--datadir'],stdout = subprocess.PIPE).stdout.read().strip()
675 mglog.info('Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
676 os.environ['LHAPDF_DATA_PATH']=LHADATAPATH
677 else:
678 getlhaconfig = subprocess.Popen(['get_files','-data','lhapdf-config'])
679 getlhaconfig.wait()
680 #Get custom lhapdf-config
681 if not os.access(os.getcwd()+'/lhapdf-config',os.X_OK):
682 mglog.error('Failed to get lhapdf-config from MadGraphControl')
683 return 1
684 lhapdfconfig = os.getcwd()+'/lhapdf-config'
685
686 mglog.info('lhapdf-config --version: '+str(subprocess.Popen([lhapdfconfig, '--version'],stdout = subprocess.PIPE).stdout.read().strip()))
687 mglog.info('lhapdf-config --prefix: '+str(subprocess.Popen([lhapdfconfig, '--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
688 mglog.info('lhapdf-config --libdir: '+str(subprocess.Popen([lhapdfconfig, '--libdir'],stdout = subprocess.PIPE).stdout.read().strip()))
689 mglog.info('lhapdf-config --datadir: '+str(subprocess.Popen([lhapdfconfig, '--datadir'],stdout = subprocess.PIPE).stdout.read().strip()))
690 mglog.info('lhapdf-config --pdfsets-path: '+str(subprocess.Popen([lhapdfconfig, '--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().strip()))
691
692 modify_config_card(process_dir=process_dir,settings={'lhapdf':lhapdfconfig,'lhapdf_py3':lhapdfconfig})
693
694 mglog.info('Creating links for LHAPDF')
695 if os.path.islink(process_dir+'/lib/PDFsets'):
696 os.unlink(process_dir+'/lib/PDFsets')
697 elif os.path.isdir(process_dir+'/lib/PDFsets'):
698 shutil.rmtree(process_dir+'/lib/PDFsets')
699 if allow_links:
700 os.symlink(LHADATAPATH,process_dir+'/lib/PDFsets')
701 else:
702 shutil.copytree(LHADATAPATH,process_dir+'/lib/PDFsets')
703 mglog.info('Available PDFs are:')
704 mglog.info( sorted( [ x for x in os.listdir(process_dir+'/lib/PDFsets') if ".tar.gz" not in x ] ) )
705
706 global MADGRAPH_COMMAND_STACK
707 MADGRAPH_COMMAND_STACK += [ '# Copy the LHAPDF files locally' ]
708 MADGRAPH_COMMAND_STACK += [ 'cp -r '+os.getcwd()+'/MGC_LHAPDF .' ]
709 MADGRAPH_COMMAND_STACK += [ 'cp -r '+process_dir+'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
710
711 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
712
713
714# Function to set the number of cores and the running mode in the run card

◆ stack_subprocess()

python.MadGraphUtils.stack_subprocess ( command,
** kwargs )

Definition at line 47 of file MadGraphUtils.py.

47def stack_subprocess(command,**kwargs):
48 global MADGRAPH_COMMAND_STACK
49 MADGRAPH_COMMAND_STACK += [' '.join(command)]
50 return subprocess.Popen(command,**kwargs)
51
52
53
54
55

◆ update_lhe_file()

python.MadGraphUtils.update_lhe_file ( lhe_file_old,
param_card_old = None,
lhe_file_new = None,
masses = {},
delete_old_lhe = True )
Build a new LHE file from an old one and an updated param card.
The masses of some particles can be changed via the masses dictionary.  No particles that appear in the events
may have their masses changed.
If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
By default, the old LHE file is removed.
If None is provided as a new LHE file name, the new file will replace the old one.

Definition at line 1324 of file MadGraphUtils.py.

1324def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1325 """Build a new LHE file from an old one and an updated param card.
1326 The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1327 may have their masses changed.
1328 If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1329 By default, the old LHE file is removed.
1330 If None is provided as a new LHE file name, the new file will replace the old one."""
1331 # If we want to just use a temp file, then put in a little temp holder
1332 lhe_file_new_tmp = lhe_file_new if lhe_file_new is not None else lhe_file_old+'.tmp'
1333 # Make sure the LHE file is there
1334 if not os.access(lhe_file_old,os.R_OK):
1335 raise RuntimeError('Could not access old LHE file at '+str(lhe_file_old)+'. Please check the file location.')
1336 # Grab the old param card
1337 if param_card_old is not None:
1338 paramcard = subprocess.Popen(['get_files','-data',param_card_old])
1339 paramcard.wait()
1340 if not os.access(param_card_old,os.R_OK):
1341 raise RuntimeError('Could not get param card '+param_card_old)
1342 # Don't overwrite old param cards
1343 if os.access(lhe_file_new_tmp,os.R_OK):
1344 raise RuntimeError('Old file at'+str(lhe_file_new_tmp)+' in the current directory. Dont want to clobber it. Please move it first.')
1345
1346 newlhe = open(lhe_file_new_tmp,'w')
1347 blockName = None
1348 decayEdit = False
1349 eventRead = False
1350 particles_in_events = []
1351 # Decay block ends with </slha>
1352
1353 with open(lhe_file_old,'r') as fileobject:
1354 for line in fileobject:
1355 if decayEdit and '</slha>' not in line:
1356 continue
1357 if decayEdit and '</slha>' in line:
1358 decayEdit = False
1359 if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
1360 and len(line.strip().split()) > 1:
1361 pos = 0 if line.strip().startswith('DECAY') else 1
1362 blockName = line.strip().upper().split()[pos]
1363
1364 akey = None
1365 if blockName != 'DECAY' and len(line.strip().split()) > 0:
1366 akey = line.strip().split()[0]
1367 elif blockName == 'DECAY' and len(line.strip().split()) > 1:
1368 akey = line.strip().split()[1]
1369
1370 # Replace the masses with those in the dictionary
1371 if akey is not None and blockName == 'MASS' and akey in masses:
1372 newlhe.write(' '+akey+' '+str(masses[akey])+' # \n')
1373 mglog.info(' '+akey+' '+str(masses[akey])+' #')
1374 decayEdit = False
1375 continue
1376
1377 # Replace the entire decay section of the LHE file with the one from the param card
1378 if blockName == 'DECAY' and param_card_old is not None:
1379 # We are now reading the decay blocks! Take them from the param card
1380 oldparam = open(param_card_old,'r')
1381 newDecays = False
1382 for old_line in oldparam.readlines():
1383 newBlockName = None
1384 if old_line.strip().upper().startswith('DECAY') and len(old_line.strip().split()) > 1:
1385 newBlockName = line.strip().upper().split()[pos]
1386 if newDecays:
1387 newlhe.write(old_line)
1388 elif newBlockName == 'DECAY':
1389 newDecays = True
1390 newlhe.write(old_line)
1391 oldparam.close()
1392 # Done adding the decays
1393 decayEdit = True
1394 blockName = None
1395 continue
1396
1397 # Keep a record of the particles that are in the events
1398 if not eventRead and '<event>' in line:
1399 eventRead = True
1400 if eventRead:
1401 if len(line.split())==11:
1402 aparticle = line.split()[0]
1403 if aparticle not in particles_in_events:
1404 particles_in_events += [aparticle]
1405
1406 # Otherwise write the line again
1407 newlhe.write(line)
1408
1409 # Check that none of the particles that we were setting the masses of appear in the LHE events
1410 for akey in masses:
1411 if akey in particles_in_events:
1412 mglog.error('Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1413 return -1
1414
1415 # Close up and return
1416 newlhe.close()
1417
1418 # Move the new file to the old file location
1419 if lhe_file_new is None:
1420 os.remove(lhe_file_old)
1421 shutil.move(lhe_file_new_tmp,lhe_file_old)
1422 lhe_file_new_tmp = lhe_file_old
1423 # Delete the old file if requested
1424 elif delete_old_lhe:
1425 os.remove(lhe_file_old)
1426
1427 return lhe_file_new_tmp
1428
1429
1430

Variable Documentation

◆ MADGRAPH_CATCH_ERRORS

bool python.MadGraphUtils.MADGRAPH_CATCH_ERRORS = True

Definition at line 26 of file MadGraphUtils.py.

◆ MADGRAPH_COMMAND_STACK

list python.MadGraphUtils.MADGRAPH_COMMAND_STACK = []

Definition at line 29 of file MadGraphUtils.py.

◆ MADGRAPH_GRIDPACK_LOCATION

str python.MadGraphUtils.MADGRAPH_GRIDPACK_LOCATION = 'madevent'

Definition at line 22 of file MadGraphUtils.py.

◆ MADGRAPH_PDFSETTING

python.MadGraphUtils.MADGRAPH_PDFSETTING = None

Definition at line 28 of file MadGraphUtils.py.

◆ MADGRAPH_RUN_NAME

str python.MadGraphUtils.MADGRAPH_RUN_NAME = 'run_01'

Definition at line 24 of file MadGraphUtils.py.

◆ mglog

python.MadGraphUtils.mglog = Logging.logging.getLogger('MadGraphUtils')

Definition at line 16 of file MadGraphUtils.py.

◆ my_MGC_instance

python.MadGraphUtils.my_MGC_instance = None

Definition at line 17 of file MadGraphUtils.py.

◆ patched_shutil_loc

str python.MadGraphUtils.patched_shutil_loc = '/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest/shutil_patch'

Definition at line 31 of file MadGraphUtils.py.

◆ python

str python.MadGraphUtils.python = 'python'

Definition at line 20 of file MadGraphUtils.py.