922def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
923
924
925
926
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
932 for adir in proc_dir_list:
933 if 'decayed' in adir:
934 continue
935 else:
936 if 'GridRun_' in adir:
937 this_run_name=adir
938 break
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
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
959
960
961
962
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
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
1019
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
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
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
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
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
1105
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
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
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
1160 os.remove(os.getcwd()+'/events.lhe.copy')
1161 mod_output2.close()
1162
1163
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
1188 if hasattr(runArgs,'outputTXTFile') and runArgs.outputTXTFile is not None:
1189 outputDS = outputDS.split('.TXT')[0]
1190
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)