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