942def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
943
944
945
946
947 if len(glob.glob(os.path.join(process_dir, 'Events','*')))<1:
948 mglog.error('Process dir '+process_dir+' does not contain events?')
949 proc_dir_list = glob.glob(os.path.join(process_dir, 'Events', '*'))
950 this_run_name=None
951
952 for adir in proc_dir_list:
953 if 'decayed' in adir:
954 continue
955 else:
956 if 'GridRun_' in adir:
957 this_run_name=adir
958 break
959 elif os.path.join(process_dir, 'Events',MADGRAPH_RUN_NAME) in adir:
960 this_run_name=adir
961 if not os.access(this_run_name,os.R_OK):
962 raise RuntimeError('Unable to locate run directory')
963
964 hasUnweighted = os.access(this_run_name+'/unweighted_events.lhe.gz',os.R_OK)
965
966 hasRunMadSpin=False
967 madspinDirs=sorted(glob.glob(this_run_name+'_decayed_*/'))
968 if len(madspinDirs):
969 hasRunMadSpin=True
970 if hasRunMadSpin and not hasUnweighted:
971
972 hasUnweighted = os.access(madspinDirs[-1]+'/unweighted_events.lhe.gz',os.R_OK)
973
974 global MADGRAPH_COMMAND_STACK
975 if hasRunMadSpin:
976 if len(madspinDirs):
977 if hasUnweighted:
978
979
980
981
982
983 if os.path.exists(madspinDirs[-1]+'/unweighted_events.lhe.gz'):
984 MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/unweighted_events.lhe.gz'+' '+this_run_name+'/unweighted_events.lhe.gz']
985 shutil.move(madspinDirs[-1]+'/unweighted_events.lhe.gz',this_run_name+'/unweighted_events.lhe.gz')
986 mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/unweighted_events.lhe.gz to '+this_run_name+'/unweighted_events.lhe.gz')
987 elif os.path.exists(madspinDirs[-1]+'/events.lhe.gz'):
988 MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/events.lhe.gz'+' '+this_run_name+'/unweighted_events.lhe.gz']
989 shutil.move(madspinDirs[-1]+'/events.lhe.gz',this_run_name+'/unweighted_events.lhe.gz')
990 mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/events.lhe.gz to '+this_run_name+'/unweighted_events.lhe.gz')
991 else:
992 raise RuntimeError('MadSpin was run but can\'t find files :(')
993
994 else:
995 MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/events.lhe.gz '+this_run_name+'/events.lhe.gz']
996 shutil.move(madspinDirs[-1]+'/events.lhe.gz',this_run_name+'/events.lhe.gz')
997 mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/events.lhe.gz to '+this_run_name+'/events.lhe.gz')
998
999 else:
1000 mglog.error('MadSpin was run but can\'t find output folder '+(this_run_name+'_decayed_1/'))
1001 raise RuntimeError('MadSpin was run but can\'t find output folder '+(this_run_name+'_decayed_1/'))
1002
1003 if fixEventWeightsForBridgeMode:
1004 mglog.info("Fixing event weights after MadSpin... initial checks.")
1005
1006
1007 spinmodenone=False
1008 MGnumevents=-1
1009 MGintweight=-1
1010
1011 if hasUnweighted:
1012 eventsfilename="unweighted_events"
1013 else:
1014 eventsfilename="events"
1015 unzip = stack_subprocess(['gunzip','-f',this_run_name+'/%s.lhe.gz' % eventsfilename])
1016 unzip.wait()
1017
1018 for line in open(process_dir+'/Events/'+MADGRAPH_RUN_NAME+'/%s.lhe'%eventsfilename):
1019 if "Number of Events" in line:
1020 sline=line.split()
1021 MGnumevents=int(sline[-1])
1022 elif "Integrated weight (pb)" in line:
1023 sline=line.split()
1024 MGintweight=float(sline[-1])
1025 elif "set spinmode none" in line:
1026 spinmodenone=True
1027 elif "</header>" in line:
1028 break
1029
1030 if spinmodenone and MGnumevents>0 and MGintweight>0:
1031 mglog.info("Fixing event weights after MadSpin... modifying LHE file.")
1032 newlhe=open(this_run_name+'/%s_fixXS.lhe'%eventsfilename,'w')
1033 initlinecount=0
1034 eventlinecount=0
1035 inInit=False
1036 inEvent=False
1037
1038
1039
1040 event_norm_setting="average"
1041
1042 for line in open(this_run_name+'/%s.lhe'%eventsfilename):
1043
1044 newline=line
1045 if "<init>" in line:
1046 inInit=True
1047 initlinecount=0
1048 elif "</init>" in line:
1049 inInit=False
1050 elif inInit and initlinecount==0:
1051 initlinecount=1
1052
1053 sline=line.split()
1054 if abs(int(sline[-2])) == 3:
1055 event_norm_setting="sum"
1056 elif abs(int(sline[-2])) == 4:
1057 event_norm_setting="average"
1058 elif inInit and initlinecount==1:
1059 sline=line.split()
1060
1061 relunc=float(sline[1])/float(sline[0])
1062 sline[0]=str(MGintweight)
1063 sline[1]=str(float(sline[0])*relunc)
1064 if event_norm_setting=="sum":
1065 sline[2]=str(MGintweight/MGnumevents)
1066 elif event_norm_setting=="average":
1067 sline[2]=str(MGintweight)
1068 newline=' '.join(sline)
1069 newline+="\n"
1070 initlinecount+=1
1071 elif inInit and initlinecount>1:
1072 initlinecount+=1
1073 elif "<event>" in line:
1074 inEvent=True
1075 eventlinecount=0
1076 elif "</event>" in line:
1077 inEvent=False
1078 elif inEvent and eventlinecount==0:
1079 sline=line.split()
1080
1081 if event_norm_setting=="sum":
1082 sline[2]=str(MGintweight/MGnumevents)
1083 elif event_norm_setting=="average":
1084 sline[2]=str(MGintweight)
1085 newline=' '.join(sline)
1086 newline+="\n"
1087 eventlinecount+=1
1088 newlhe.write(newline)
1089 newlhe.close()
1090
1091 mglog.info("Fixing event weights after MadSpin... cleaning up.")
1092 shutil.copyfile(this_run_name+'/%s.lhe' % eventsfilename,
1093 this_run_name+'/%s_badXS.lhe' % eventsfilename)
1094
1095 shutil.move(this_run_name+'/%s_fixXS.lhe' % eventsfilename,
1096 this_run_name+'/%s.lhe' % eventsfilename)
1097
1098 rezip = stack_subprocess(['gzip',this_run_name+'/%s.lhe' % eventsfilename])
1099 rezip.wait()
1100
1101 rezip = stack_subprocess(['gzip',this_run_name+'/%s_badXS.lhe' % eventsfilename])
1102 rezip.wait()
1103
1104
1105 if os.path.exists(os.getcwd()+'/events.lhe'):
1106 os.remove(os.getcwd()+'/events.lhe')
1107
1108 mglog.info('Unzipping generated events.')
1109 if hasUnweighted:
1110 unzip = stack_subprocess(['gunzip','-f',this_run_name+'/unweighted_events.lhe.gz'])
1111 unzip.wait()
1112 else:
1113 unzip = stack_subprocess(['gunzip','-f',this_run_name+'/events.lhe.gz'])
1114 unzip.wait()
1115
1116 mglog.info('Putting a copy in place for the transform.')
1117 if hasUnweighted:
1118 orig_input = this_run_name+'/unweighted_events.lhe'
1119 mod_output = open(os.getcwd()+'/events.lhe','w')
1120 else:
1121 orig_input = this_run_name+'/events.lhe'
1122 mod_output = open(os.getcwd()+'/events.lhe','w')
1123
1124
1125
1126 initrwgt=None
1127 nEmpty=0
1128 lhe_weights=[]
1129 with open(orig_input,'r') as fileobject:
1130 for line in fileobject:
1131 if line.strip():
1132
1133 newline=line
1134 if '#' not in newline:
1135 newline=newline
1136 elif '>' not in newline[ newline.find('#'): ]:
1137 newline=newline
1138 else:
1139 mglog.info('Found bad LHE line with an XML mark in a comment: "'+newline.strip()+'"')
1140 newline=newline[:newline.find(
'#')]+
'#'+ (newline[newline.find(
'#'):].
replace(
'>',
'-'))
1141
1142 if initrwgt is False:
1143 pass
1144 elif "</initrwgt>" in newline:
1145 initrwgt=False
1146 elif "<initrwgt>" in newline:
1147 initrwgt=True
1148 elif initrwgt is not None:
1149 newline=newline.replace('_DYNSCALE-1','')
1150 if '</weight>' in newline:
1151 iend=newline.find('</weight>')
1152 istart=newline[:iend].rfind('>')
1153 lhe_weights+=[newline[istart+1:iend].
strip()]
1154 mod_output.write(newline)
1155 else:
1156 nEmpty=nEmpty+1
1157 mod_output.close()
1158 mglog.info('Removed '+str(nEmpty)+' empty lines from LHEF')
1159
1160 mglog.info("The following "+str(len(lhe_weights))+" weights have been written to the LHE file: "+",".join(lhe_weights))
1161 expected_weights=get_expected_reweight_names(get_reweight_card(process_dir))
1162 expected_weights+=get_expected_systematic_names(MADGRAPH_PDFSETTING)
1163 mglog.info("Checking whether the following expected weights are in LHE file: "+",".join(expected_weights))
1164 for w in expected_weights:
1165 if w not in lhe_weights:
1166 raise RuntimeError("Did not find expected weight "+w+" in lhe file. Did the reweight or systematics module crash?")
1167 mglog.info("Found all required weights!")
1168
1169 if lhe_version:
1170 mod_output2 = open(os.getcwd()+'/events.lhe','r')
1171 test=mod_output2.readline()
1172 if 'version="' in test:
1173 mglog.info('Applying LHE version hack')
1174 final_file = open(os.getcwd()+'/events.lhe.copy','w')
1175 final_file.write('<LesHouchesEvents version="%i.0">\n'%lhe_version)
1176 shutil.copyfileobj(mod_output2, final_file)
1177 final_file.close()
1178 shutil.copy(os.getcwd()+'/events.lhe.copy',os.getcwd()+'/events.lhe')
1179
1180 os.remove(os.getcwd()+'/events.lhe.copy')
1181 mod_output2.close()
1182
1183
1184 if runArgs is None:
1185 raise RuntimeError('Must provide runArgs to arrange_output')
1186
1187 if hasattr(runArgs,'outputTXTFile'):
1188 outputDS = runArgs.outputTXTFile
1189 else:
1190 outputDS = 'tmp_LHE_events.tar.gz'
1191
1192 mglog.info('Moving file over to '+outputDS.split('.tar.gz')[0]+'.events')
1193
1194 shutil.move(os.getcwd()+'/events.lhe',outputDS.split('.tar.gz')[0]+'.events')
1195
1196 mglog.info('Re-zipping into dataset name '+outputDS)
1197 rezip = stack_subprocess(['tar','cvzf',outputDS,outputDS.split('.tar.gz')[0]+'.events'])
1198 rezip.wait()
1199
1200 if not saveProcDir:
1201 mglog.info('Removing the process directory')
1202 shutil.rmtree(process_dir,ignore_errors=True)
1203
1204 if os.path.isdir('MGC_LHAPDF/'):
1205 shutil.rmtree('MGC_LHAPDF/',ignore_errors=True)
1206
1207
1208 if hasattr(runArgs,'outputTXTFile') and runArgs.outputTXTFile is not None:
1209 outputDS = outputDS.split('.TXT')[0]
1210
1211 if runArgs is not None:
1212 mglog.debug('Setting inputGenerator file to '+outputDS)
1213 runArgs.inputGeneratorFile=outputDS
1214
1215 mglog.info('All done with output arranging!')
1216 return outputDS
1217
std::string replace(std::string s, const std::string &s2, const std::string &s3)