ATLAS Offline Software
Functions | Variables
python.MadGraphUtils Namespace Reference

Functions

def stack_subprocess (command, **kwargs)
 
def setup_path_protection ()
 
def config_only_check ()
 
def generate_prep (process_dir)
 
def error_check (errors_a, return_code)
 
def write_test_script ()
 
def new_process (process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False)
 
def get_default_runcard (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def generate (process_dir='PROC_mssm_0', grid_pack=False, gridpack_compile=False, extlhapath=None, required_accuracy=0.01, runArgs=None, bias_module=None, requirePMGSettings=False)
 
def generate_from_gridpack (runArgs=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False)
 
def setupFastjet (process_dir=None)
 
def setupLHAPDF (process_dir=None, extlhapath=None, allow_links=True)
 
def setNCores (process_dir, Ncores=None)
 
def get_mg5_executable ()
 
def add_lifetimes (process_dir, threshold=None)
 
def add_madspin (madspin_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def madspin_on_lhe (input_LHE, madspin_card, runArgs=None, keep_original=False)
 
def arrange_output (process_dir=MADGRAPH_GRIDPACK_LOCATION, lhe_version=None, saveProcDir=False, runArgs=None, fixEventWeightsForBridgeMode=False)
 
def get_expected_reweight_names (reweight_card_loc)
 
def get_expected_systematic_names (syst_setting)
 
def setup_bias_module (bias_module, process_dir)
 
def get_reweight_card (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def check_reweight_card (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def helpful_SUSY_definitions ()
 
def get_SUSY_variations (process, masses, syst_mod, ktdurham=None)
 
def SUSY_process (process='')
 
def SUSY_Generation (runArgs=None, process=None, plugin=None, syst_mod=None, keepOutput=False, param_card=None, writeGridpack=False, madspin_card=None, run_settings={}, params={}, fixEventWeightsForBridgeMode=False, add_lifetimes_lhe=False, usePMGSettings=True)
 
def update_lhe_file (lhe_file_old, param_card_old=None, lhe_file_new=None, masses={}, delete_old_lhe=True)
 
def find_key_and_update (akey, dictionary)
 
def modify_param_card (param_card_input=None, param_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, params={}, output_location=None)
 
def modify_run_card (run_card_input=None, run_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, runArgs=None, settings={}, skipBaseFragment=False)
 
def modify_config_card (config_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, settings={}, set_commented=True)
 
def print_cards_from_dir (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def print_cards (proc_card='proc_card_mg5.dat', run_card=None, param_card=None, madspin_card=None, reweight_card=None, warn_on_missing=True)
 
def is_gen_from_gridpack ()
 
def get_default_config_card (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def get_cluster_type (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def is_NLO_run (process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def run_card_consistency_check (isNLO=False, process_dir='.')
 
def add_reweighting (run_name, reweight_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
 
def ls_dir (directory)
 
def fix_fks_makefile (process_dir)
 

Variables

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

Function Documentation

◆ add_lifetimes()

def 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 1007 of file MadGraphUtils.py.

1007 def add_lifetimes(process_dir,threshold=None):
1008  """ Add lifetimes to the generated LHE file. Should be
1009  called after generate_events is called.
1010  """
1011  if config_only_check():
1012  return
1013 
1014  me_exec=get_mg5_executable()
1015 
1016  if len(glob.glob(process_dir+'/Events/*'))<1:
1017  mglog.error('Process dir '+process_dir+' does not contain events?')
1018  run = glob.glob(process_dir+'/Events/*')[0].split('/')[-1]
1019 
1020  # Note : This slightly clunky implementation is needed for the time being
1021  # See : https://answers.launchpad.net/mg5amcnlo/+question/267904
1022 
1023  tof_c = open('time_of_flight_exec_card','w')
1024  tof_c.write('launch '+process_dir+''' -i
1025 add_time_of_flight '''+run+((' --threshold='+str(threshold)) if threshold is not None else ''))
1026  tof_c.close()
1027 
1028  mglog.info('Started adding time of flight info '+str(time.asctime()))
1029 
1030  global MADGRAPH_CATCH_ERRORS
1031  generate = stack_subprocess([python,me_exec,'time_of_flight_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1032  (out,err) = generate.communicate()
1033  error_check(err,generate.returncode)
1034 
1035  mglog.info('Finished adding time of flight information at '+str(time.asctime()))
1036 
1037  # Re-zip the file if needed
1038  lhe_gz = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1039  if not os.access(lhe_gz,os.R_OK):
1040  mglog.info('LHE file needs to be zipped')
1041  lhe = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1042  rezip = stack_subprocess(['gzip',lhe])
1043  rezip.wait()
1044  mglog.info('Zipped')
1045  else:
1046  mglog.info('LHE file zipped by MadGraph automatically. Nothing to do')
1047 
1048  return True
1049 
1050 

◆ add_madspin()

def 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 1051 of file MadGraphUtils.py.

1051 def add_madspin(madspin_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
1052  """ Run madspin on the generated LHE file. Should be
1053  run when you have inputGeneratorFile set.
1054  Only requires a simplified process with the same model that you are
1055  interested in (needed to set up a process directory for MG5_aMC)
1056  """
1057  if config_only_check():
1058  return
1059 
1060  me_exec=get_mg5_executable()
1061 
1062  if madspin_card is not None:
1063  shutil.copyfile(madspin_card,process_dir+'/Cards/madspin_card.dat')
1064 
1065  if len(glob.glob(process_dir+'/Events/*'))<1:
1066  mglog.error('Process dir '+process_dir+' does not contain events?')
1067  proc_dir_list = glob.glob(process_dir+'/Events/*')
1068  run=None
1069  for adir in proc_dir_list:
1070  if 'GridRun_' in adir:
1071  run=adir.split('/')[-1]
1072  break
1073  else:
1074  run=proc_dir_list[0].split('/')[-1]
1075 
1076  # Note : This slightly clunky implementation is needed for the time being
1077  # See : https://answers.launchpad.net/mg5amcnlo/+question/267904
1078 
1079  ms_c = open('madspin_exec_card','w')
1080  ms_c.write('launch '+process_dir+''' -i
1081 decay_events '''+run)
1082  ms_c.close()
1083 
1084  mglog.info('Started running madspin at '+str(time.asctime()))
1085 
1086  global MADGRAPH_CATCH_ERRORS
1087  generate = stack_subprocess([python,me_exec,'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1088  (out,err) = generate.communicate()
1089  error_check(err,generate.returncode)
1090  if len(glob.glob(process_dir+'/Events/'+run+'_decayed_*/')) == 0:
1091  mglog.error('No '+process_dir+'/Events/'+run+'_decayed_*/ can be found')
1092  raise RuntimeError('Problem while running MadSpin')
1093 
1094  mglog.info('Finished running madspin at '+str(time.asctime()))
1095 
1096  # Re-zip the file if needed
1097  lhe_gz = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1098  if not os.access(lhe_gz,os.R_OK):
1099  mglog.info('LHE file needs to be zipped')
1100  lhe = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1101  rezip = stack_subprocess(['gzip',lhe])
1102  rezip.wait()
1103  mglog.info('Zipped')
1104  else:
1105  mglog.info('LHE file zipped by MadGraph automatically. Nothing to do')
1106 
1107 

◆ add_reweighting()

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

Definition at line 2428 of file MadGraphUtils.py.

2428 def add_reweighting(run_name,reweight_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
2429  mglog.info('Running reweighting module on existing events')
2430  if reweight_card is not None:
2431  mglog.info('Copying new reweight card from '+reweight_card)
2432  shutil.move(reweight_card,process_dir+'/Cards/reweight_card.dat')
2433  reweight_cmd='{}/bin/madevent reweight {} -f'.format(process_dir,run_name)
2434  global MADGRAPH_CATCH_ERRORS
2435  reweight = stack_subprocess([python]+reweight_cmd.split(),stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
2436  (out,err) = reweight.communicate()
2437  error_check(err,reweight.returncode)
2438  mglog.info('Finished reweighting')
2439 
2440 
2441 
2442 

◆ arrange_output()

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

Definition at line 1196 of file MadGraphUtils.py.

1196 def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
1197  if config_only_check():
1198  return
1199 
1200  # NLO is not *really* the question here, we need to know if we should look for weighted or
1201  # unweighted events in the output directory. MadSpin (above) only seems to give weighted
1202  # results for now?
1203  if len(glob.glob(os.path.join(process_dir, 'Events','*')))<1:
1204  mglog.error('Process dir '+process_dir+' does not contain events?')
1205  proc_dir_list = glob.glob(os.path.join(process_dir, 'Events', '*'))
1206  this_run_name=None
1207  # looping over possible directories to find the right one
1208  for adir in proc_dir_list:
1209  if 'decayed' in adir:# skipping '*decayed*' directories produced by MadSpin, will be picked later if they exist
1210  continue
1211  else:
1212  if 'GridRun_' in adir:
1213  this_run_name=adir
1214  break # GridRun_* directories have priority
1215  elif os.path.join(process_dir, 'Events',MADGRAPH_RUN_NAME) in adir:
1216  this_run_name=adir
1217  if not os.access(this_run_name,os.R_OK):
1218  raise RuntimeError('Unable to locate run directory')
1219 
1220  hasUnweighted = os.access(this_run_name+'/unweighted_events.lhe.gz',os.R_OK)
1221 
1222  hasRunMadSpin=False
1223  madspinDirs=sorted(glob.glob(this_run_name+'_decayed_*/'))
1224  if len(madspinDirs):
1225  hasRunMadSpin=True
1226  if hasRunMadSpin and not hasUnweighted:
1227  # check again:
1228  hasUnweighted = os.access(madspinDirs[-1]+'/unweighted_events.lhe.gz',os.R_OK)
1229 
1230  global MADGRAPH_COMMAND_STACK
1231  if hasRunMadSpin:
1232  if len(madspinDirs):
1233  if hasUnweighted:
1234  # so this is a bit of a mess now...
1235  # if madspin is run from an NLO grid pack the correct lhe events are at both
1236  # madevent/Events/run_01/unweighted_events.lhe.gz
1237  # and madevent/Events/run_01_decayed_1/events.lhe.gz
1238  # so there are unweighted events but not in the madspinDir...
1239  if os.path.exists(madspinDirs[-1]+'/unweighted_events.lhe.gz'):
1240  MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/unweighted_events.lhe.gz'+' '+this_run_name+'/unweighted_events.lhe.gz']
1241  shutil.move(madspinDirs[-1]+'/unweighted_events.lhe.gz',this_run_name+'/unweighted_events.lhe.gz')
1242  mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/unweighted_events.lhe.gz to '+this_run_name+'/unweighted_events.lhe.gz')
1243  elif os.path.exists(madspinDirs[-1]+'/events.lhe.gz'):
1244  MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/events.lhe.gz'+' '+this_run_name+'/unweighted_events.lhe.gz']
1245  shutil.move(madspinDirs[-1]+'/events.lhe.gz',this_run_name+'/unweighted_events.lhe.gz')
1246  mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/events.lhe.gz to '+this_run_name+'/unweighted_events.lhe.gz')
1247  else:
1248  raise RuntimeError('MadSpin was run but can\'t find files :(')
1249 
1250  else:
1251  MADGRAPH_COMMAND_STACK += ['mv '+madspinDirs[-1]+'/events.lhe.gz '+this_run_name+'/events.lhe.gz']
1252  shutil.move(madspinDirs[-1]+'/events.lhe.gz',this_run_name+'/events.lhe.gz')
1253  mglog.info('Moving MadSpin events from '+madspinDirs[-1]+'/events.lhe.gz to '+this_run_name+'/events.lhe.gz')
1254 
1255  else:
1256  mglog.error('MadSpin was run but can\'t find output folder '+(this_run_name+'_decayed_1/'))
1257  raise RuntimeError('MadSpin was run but can\'t find output folder '+(this_run_name+'_decayed_1/'))
1258 
1259  if fixEventWeightsForBridgeMode:
1260  mglog.info("Fixing event weights after MadSpin... initial checks.")
1261 
1262  # get the cross section from the undecayed LHE file
1263  spinmodenone=False
1264  MGnumevents=-1
1265  MGintweight=-1
1266 
1267  if hasUnweighted:
1268  eventsfilename="unweighted_events"
1269  else:
1270  eventsfilename="events"
1271  unzip = stack_subprocess(['gunzip','-f',this_run_name+'/%s.lhe.gz' % eventsfilename])
1272  unzip.wait()
1273 
1274  for line in open(process_dir+'/Events/'+MADGRAPH_RUN_NAME+'/%s.lhe'%eventsfilename):
1275  if "Number of Events" in line:
1276  sline=line.split()
1277  MGnumevents=int(sline[-1])
1278  elif "Integrated weight (pb)" in line:
1279  sline=line.split()
1280  MGintweight=float(sline[-1])
1281  elif "set spinmode none" in line:
1282  spinmodenone=True
1283  elif "</header>" in line:
1284  break
1285 
1286  if spinmodenone and MGnumevents>0 and MGintweight>0:
1287  mglog.info("Fixing event weights after MadSpin... modifying LHE file.")
1288  newlhe=open(this_run_name+'/%s_fixXS.lhe'%eventsfilename,'w')
1289  initlinecount=0
1290  eventlinecount=0
1291  inInit=False
1292  inEvent=False
1293 
1294  # new default for MG 2.6.1+ (https://its.cern.ch/jira/browse/AGENE-1725)
1295  # but verified from LHE below.
1296  event_norm_setting="average"
1297 
1298  for line in open(this_run_name+'/%s.lhe'%eventsfilename):
1299 
1300  newline=line
1301  if "<init>" in line:
1302  inInit=True
1303  initlinecount=0
1304  elif "</init>" in line:
1305  inInit=False
1306  elif inInit and initlinecount==0:
1307  initlinecount=1
1308  # check event_norm setting in LHE file, deteremines how Pythia interprets event weights
1309  sline=line.split()
1310  if abs(int(sline[-2])) == 3:
1311  event_norm_setting="sum"
1312  elif abs(int(sline[-2])) == 4:
1313  event_norm_setting="average"
1314  elif inInit and initlinecount==1:
1315  sline=line.split()
1316  # update the global XS info
1317  relunc=float(sline[1])/float(sline[0])
1318  sline[0]=str(MGintweight)
1319  sline[1]=str(float(sline[0])*relunc)
1320  if event_norm_setting=="sum":
1321  sline[2]=str(MGintweight/MGnumevents)
1322  elif event_norm_setting=="average":
1323  sline[2]=str(MGintweight)
1324  newline=' '.join(sline)
1325  newline+="\n"
1326  initlinecount+=1
1327  elif inInit and initlinecount>1:
1328  initlinecount+=1
1329  elif "<event>" in line:
1330  inEvent=True
1331  eventlinecount=0
1332  elif "</event>" in line:
1333  inEvent=False
1334  elif inEvent and eventlinecount==0:
1335  sline=line.split()
1336  # next change the per-event weights
1337  if event_norm_setting=="sum":
1338  sline[2]=str(MGintweight/MGnumevents)
1339  elif event_norm_setting=="average":
1340  sline[2]=str(MGintweight)
1341  newline=' '.join(sline)
1342  newline+="\n"
1343  eventlinecount+=1
1344  newlhe.write(newline)
1345  newlhe.close()
1346 
1347  mglog.info("Fixing event weights after MadSpin... cleaning up.")
1348  shutil.copyfile(this_run_name+'/%s.lhe' % eventsfilename,
1349  this_run_name+'/%s_badXS.lhe' % eventsfilename)
1350 
1351  shutil.move(this_run_name+'/%s_fixXS.lhe' % eventsfilename,
1352  this_run_name+'/%s.lhe' % eventsfilename)
1353 
1354  rezip = stack_subprocess(['gzip',this_run_name+'/%s.lhe' % eventsfilename])
1355  rezip.wait()
1356 
1357  rezip = stack_subprocess(['gzip',this_run_name+'/%s_badXS.lhe' % eventsfilename])
1358  rezip.wait()
1359 
1360  # Clean up in case a link or file was already there
1361  if os.path.exists(os.getcwd()+'/events.lhe'):
1362  os.remove(os.getcwd()+'/events.lhe')
1363 
1364  mglog.info('Unzipping generated events.')
1365  if hasUnweighted:
1366  unzip = stack_subprocess(['gunzip','-f',this_run_name+'/unweighted_events.lhe.gz'])
1367  unzip.wait()
1368  else:
1369  unzip = stack_subprocess(['gunzip','-f',this_run_name+'/events.lhe.gz'])
1370  unzip.wait()
1371 
1372  mglog.info('Putting a copy in place for the transform.')
1373  if hasUnweighted:
1374  orig_input = this_run_name+'/unweighted_events.lhe'
1375  mod_output = open(os.getcwd()+'/events.lhe','w')
1376  else:
1377  orig_input = this_run_name+'/events.lhe'
1378  mod_output = open(os.getcwd()+'/events.lhe','w')
1379 
1380  #Removing empty lines and bad comments in LHE
1381  #and check for existence of weights
1382  initrwgt=None
1383  nEmpty=0
1384  lhe_weights=[]
1385  with open(orig_input,'r') as fileobject:
1386  for line in fileobject:
1387  if line.strip():
1388  # search for bad characters (neccessary until at least MG5 2.8.1)
1389  newline=line
1390  if '#' not in newline:
1391  newline=newline
1392  elif '>' not in newline[ newline.find('#'): ]:
1393  newline=newline
1394  else:
1395  mglog.warning('Found bad LHE line with an XML mark in a comment: "'+newline.strip()+'"')
1396  newline=newline[:newline.find('#')]+'#'+ (newline[newline.find('#'):].replace('>','-'))
1397  # check for weightnames that should exist, simplify nominal weight names
1398  if initrwgt is False:
1399  pass
1400  elif "</initrwgt>" in newline:
1401  initrwgt=False
1402  elif "<initrwgt>" in newline:
1403  initrwgt=True
1404  elif initrwgt is not None:
1405  newline=newline.replace('_DYNSCALE-1','')
1406  if '</weight>' in newline:
1407  iend=newline.find('</weight>')
1408  istart=newline[:iend].rfind('>')
1409  lhe_weights+=[newline[istart+1:iend].strip()]
1410  mod_output.write(newline)
1411  else:
1412  nEmpty=nEmpty+1
1413  mod_output.close()
1414  mglog.info('Removed '+str(nEmpty)+' empty lines from LHEF')
1415 
1416  mglog.info("The following "+str(len(lhe_weights))+" weights have been written to the LHE file: "+",".join(lhe_weights))
1417  expected_weights=get_expected_reweight_names(get_reweight_card(process_dir))
1418  expected_weights+=get_expected_systematic_names(MADGRAPH_PDFSETTING)
1419  mglog.info("Checking whether the following expected weights are in LHE file: "+",".join(expected_weights))
1420  for w in expected_weights:
1421  if w not in lhe_weights:
1422  raise RuntimeError("Did not find expected weight "+w+" in lhe file. Did the reweight or systematics module crash?")
1423  mglog.info("Found all required weights!")
1424 
1425  if lhe_version:
1426  mod_output2 = open(os.getcwd()+'/events.lhe','r')
1427  test=mod_output2.readline()
1428  if 'version="' in test:
1429  mglog.info('Applying LHE version hack')
1430  final_file = open(os.getcwd()+'/events.lhe.copy','w')
1431  final_file.write('<LesHouchesEvents version="%i.0">\n'%lhe_version)
1432  shutil.copyfileobj(mod_output2, final_file)
1433  final_file.close()
1434  shutil.copy(os.getcwd()+'/events.lhe.copy',os.getcwd()+'/events.lhe')
1435  # Clean up after ourselves
1436  os.remove(os.getcwd()+'/events.lhe.copy')
1437  mod_output2.close()
1438 
1439  # Actually move over the dataset
1440  if runArgs is None:
1441  raise RuntimeError('Must provide runArgs to arrange_output')
1442 
1443  if hasattr(runArgs,'outputTXTFile'):
1444  outputDS = runArgs.outputTXTFile
1445  else:
1446  outputDS = 'tmp_LHE_events'
1447 
1448  mglog.info('Moving file over to '+outputDS.split('.tar.gz')[0]+'.events')
1449 
1450  shutil.move(os.getcwd()+'/events.lhe',outputDS.split('.tar.gz')[0]+'.events')
1451 
1452  mglog.info('Re-zipping into dataset name '+outputDS)
1453  rezip = stack_subprocess(['tar','cvzf',outputDS,outputDS.split('.tar.gz')[0]+'.events'])
1454  rezip.wait()
1455 
1456  if not saveProcDir:
1457  mglog.info('Removing the process directory')
1458  shutil.rmtree(process_dir,ignore_errors=True)
1459 
1460  if os.path.isdir('MGC_LHAPDF/'):
1461  shutil.rmtree('MGC_LHAPDF/',ignore_errors=True)
1462 
1463  # shortening the outputDS in the case of an output TXT file
1464  if hasattr(runArgs,'outputTXTFile') and runArgs.outputTXTFile is not None:
1465  outputDS = outputDS.split('.TXT')[0]
1466  # Do some fixing up for them
1467  if runArgs is not None:
1468  mglog.debug('Setting inputGenerator file to '+outputDS)
1469  runArgs.inputGeneratorFile=outputDS
1470 
1471  mglog.info('All done with output arranging!')
1472  return outputDS
1473 

◆ check_reweight_card()

def python.MadGraphUtils.check_reweight_card (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1564 of file MadGraphUtils.py.

1564 def check_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1565  reweight_card=get_reweight_card(process_dir=process_dir)
1566  shutil.move(reweight_card,reweight_card+'.old')
1567  oldcard = open(reweight_card+'.old','r')
1568  newcard = open(reweight_card,'w')
1569  changed = False
1570  info_expression=r'launch.*--rwgt_info\s*=\s*(\S+).*'
1571  name_expression=info_expression.replace('info','name')
1572  goodname_expression=r'^[A-Za-z0-9_\-.]+$'
1573  for line in oldcard:
1574  # we are only interested in the 'launch' line
1575  if not line.strip().startswith('launch') :
1576  newcard.write(line)
1577  else:
1578  rwgt_name_match=re.match(name_expression,line.strip())
1579  rwgt_info_match=re.match(info_expression,line.strip())
1580  if rwgt_name_match is None and rwgt_info_match is None:
1581  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)
1582  for match in [rwgt_info_match,rwgt_name_match]:
1583  if match is None:
1584  continue
1585  if len(match.groups())!=1:
1586  raise RuntimeError('Unexpected format of reweight card in line: '+line)
1587  if not re.match(goodname_expression,match.group(1)):
1588  raise RuntimeError('No special character in reweighting info/name, only allowing '+goodname_expression)
1589  if rwgt_info_match is not None:
1590  newcard.write(line)
1591  elif rwgt_name_match is not None:
1592  newcard.write(line.strip()+' --rwgt_info={0}\n'.format(rwgt_name_match.group(1)))
1593  changed=True
1594  if changed:
1595  mglog.info('Updated reweight_card')
1596  newcard.close()
1597  oldcard.close()
1598 
1599 

◆ config_only_check()

def python.MadGraphUtils.config_only_check ( )

Definition at line 73 of file MadGraphUtils.py.

73 def config_only_check():
74  try:
75  from __main__ import opts
76  if opts.config_only:
77  mglog.info('Athena running on config only mode: not executing MadGraph')
78  return True
79  except ImportError:
80  pass
81  return False
82 
83 

◆ error_check()

def python.MadGraphUtils.error_check (   errors_a,
  return_code 
)

Definition at line 109 of file MadGraphUtils.py.

109 def error_check(errors_a, return_code):
110  global MADGRAPH_CATCH_ERRORS
111  if not MADGRAPH_CATCH_ERRORS:
112  return
113  unmasked_error = False
114  my_debug_file = None
115  bad_variables = []
116  # Make sure we are getting a string and not a byte string (python3 ftw)
117  errors = errors_a
118  if type(errors)==bytes:
119  errors = errors.decode('utf-8')
120  if len(errors):
121  mglog.info('Some errors detected by MadGraphControl - checking for serious errors')
122  for err in errors.split('\n'):
123  if len(err.strip())==0:
124  continue
125  # Errors to do with I/O... not clear on their origin yet
126  if 'Inappropriate ioctl for device' in err:
127  mglog.info(err)
128  continue
129  if 'stty: standard input: Invalid argument' in err:
130  mglog.info(err)
131  continue
132  # Errors for PDF sets that should be fixed in MG5_aMC 2.7
133  if 'PDF already installed' in err:
134  mglog.info(err)
135  continue
136  if 'Read-only file system' in err:
137  mglog.info(err)
138  continue
139  if 'HTML' in err:
140  # https://bugs.launchpad.net/mg5amcnlo/+bug/1870217
141  mglog.info(err)
142  continue
143  if 'impossible to set default multiparticles' in err:
144  # https://answers.launchpad.net/mg5amcnlo/+question/690004
145  mglog.info(err)
146  continue
147  if 'More information is found in' in err:
148  my_debug_file = err.split("'")[1]
149  if err.startswith('tar'):
150  mglog.info(err)
151  continue
152  if 'python2 support will be removed' in err:
153  mglog.info(err)
154  continue
155  # silly ghostscript issue in 21.6.46 nightly
156  if 'required by /lib64/libfontconfig.so' in err or\
157  'required by /lib64/libgs.so' in err:
158  mglog.info(err)
159  continue
160  if 'Error: Symbol' in err and 'has no IMPLICIT type' in err:
161  bad_variables += [ err.split('Symbol ')[1].split(' at ')[0] ]
162  # error output from tqdm (progress bar)
163  if 'it/s' in err:
164  mglog.info(err)
165  continue
166  mglog.error(err)
167  unmasked_error = True
168  # This is a bit clunky, but needed because we could be several places when we get here
169  if my_debug_file is None:
170  debug_files = glob.glob('*debug.log')+glob.glob('*/*debug.log')
171  for debug_file in debug_files:
172  # This protects against somebody piping their output to my_debug.log and it being caught here
173  has_subproc = os.access(os.path.join(os.path.dirname(debug_file),'SubProcesses'),os.R_OK)
174  if has_subproc:
175  my_debug_file = debug_file
176  break
177 
178  if my_debug_file is not None:
179  if not unmasked_error:
180  mglog.warning('Found a debug file at '+my_debug_file+' but no apparent error. Will terminate.')
181  mglog.error('MadGraph5_aMC@NLO appears to have crashed. Debug file output follows.')
182  with open(my_debug_file,'r') as error_output:
183  for l in error_output:
184  mglog.error(l.replace('\n',''))
185  mglog.error('End of debug file output')
186 
187  if bad_variables:
188  mglog.warning('Appeared to detect variables in your run card that MadGraph did not understand:')
189  mglog.warning(' Check your run card / JO settings for %s',bad_variables)
190 
191  # Check the return code
192  if return_code!=0:
193  mglog.error(f'Detected a bad return code: {return_code}')
194  unmasked_error = True
195 
196  # Now raise an error if we were in either of the error states
197  if unmasked_error or my_debug_file is not None:
199  raise RuntimeError('Error detected in MadGraphControl process')
200  return
201 
202 
203 # Write a short test script for standalone debugging

◆ find_key_and_update()

def 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 1887 of file MadGraphUtils.py.

1887 def find_key_and_update(akey,dictionary):
1888  """ Helper function when looking at param cards
1889  In some cases it's tricky to match keys - they may differ
1890  only in white space. This tries to sort out when we have
1891  a match, and then uses the one in blockParams afterwards.
1892  In the case of no match, it returns the original key.
1893  """
1894  test_key = ' '.join(akey.strip().replace('\t',' ').split())
1895  for key in dictionary:
1896  mod_key = ' '.join(key.strip().replace('\t',' ').split())
1897  if mod_key==test_key:
1898  return key
1899  return akey
1900 
1901 

◆ fix_fks_makefile()

def python.MadGraphUtils.fix_fks_makefile (   process_dir)

Definition at line 2451 of file MadGraphUtils.py.

2451 def fix_fks_makefile(process_dir):
2452  makefile_fks=process_dir+'/SubProcesses/makefile_fks_dir'
2453  mglog.info('Fixing '+makefile_fks)
2454  shutil.move(makefile_fks,makefile_fks+'_orig')
2455  fin=open(makefile_fks+'_orig')
2456  fout=open(makefile_fks,'w')
2457  edit=False
2458  for line in fin:
2459  if 'FKSParams.mod' in line:
2460  fout.write(line.replace('FKSParams.mod','FKSParams.o'))
2461  edit=True
2462  elif edit and 'driver_mintFO' in line:
2463  fout.write('driver_mintFO.o: weight_lines.o mint_module.o FKSParams.o\n')
2464  elif edit and 'genps_fks.o' in line:
2465  fout.write('genps_fks.o: mint_module.o FKSParams.o\n')
2466  elif edit and 'test_soft_col_limits' in line:
2467  fout.write(line)
2468  fout.write('madfks_plot.o: mint_module.o\n')
2469  fout.write('cluster.o: weight_lines.o\n')
2470  else:
2471  fout.write(line)
2472  fin.close()
2473  fout.close()

◆ generate()

def 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 391 of file MadGraphUtils.py.

391 def generate(process_dir='PROC_mssm_0', grid_pack=False, gridpack_compile=False, extlhapath=None, required_accuracy=0.01, runArgs=None, bias_module=None, requirePMGSettings=False):
392  if config_only_check():
393  return
394 
395  # Just in case
397 
398  # Set consistent mode and number of jobs
399  mode = 0
400  njobs = 1
401  if 'ATHENA_CORE_NUMBER' in os.environ and int(os.environ['ATHENA_CORE_NUMBER'])>0:
402  njobs = int(os.environ['ATHENA_CORE_NUMBER'])
403  mglog.info('Lucky you - you are running on a full node queue. Will re-configure for '+str(njobs)+' jobs.')
404  mode = 2
405 
406  cluster_type = get_cluster_type(process_dir=process_dir)
407  if cluster_type is not None:
408  mode = 1
409 
411  mglog.info('Running event generation from gridpack (using smarter mode from generate() function)')
412  generate_from_gridpack(runArgs=runArgs,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings)
413  return
414  else:
415  mglog.info('Did not identify an input gridpack.')
416  if grid_pack:
417  mglog.info('The grid_pack flag is set, so I am expecting to create a gridpack in this job')
418 
419  # Now get a variety of info out of the runArgs
420  beamEnergy,random_seed = get_runArgs_info(runArgs)
421 
422  # Check if process is NLO or LO
423  isNLO=is_NLO_run(process_dir=process_dir)
424 
425  # temporary fix of makefile, needed for 3.3.1., remove in future
426  if isNLO:
427  fix_fks_makefile(process_dir=process_dir)
428 
429  # if f2py not available
430  if get_reweight_card(process_dir=process_dir) is not None:
431  from distutils.spawn import find_executable
432  if find_executable('f2py') is not None:
433  mglog.info('Found f2py, will use it for reweighting')
434  else:
435  raise RuntimeError('Could not find f2py, needed for reweighting')
436  check_reweight_card(process_dir)
437 
438  if grid_pack:
439  #Running in gridpack mode
440  mglog.info('Started generating gridpack at '+str(time.asctime()))
441  mglog.warning(' >>>>>> THIS KIND OF JOB SHOULD ONLY BE RUN LOCALLY - NOT IN GRID JOBS <<<<<<')
442 
443  # Some events required if we specify MadSpin usage!
444  my_settings = {'nevents':'1000'}
445  if isNLO:
446  my_settings['req_acc']=str(required_accuracy)
447  else:
448  my_settings = {'gridpack':'true'}
449  modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=True)
450 
451  else:
452  #Running in on-the-fly mode
453  mglog.info('Started generating at '+str(time.asctime()))
454 
455  mglog.info('Run '+MADGRAPH_RUN_NAME+' will be performed in mode '+str(mode)+' with '+str(njobs)+' jobs in parallel.')
456 
457  # Ensure that things are set up normally
458  if not os.access(process_dir,os.R_OK):
459  raise RuntimeError('No process directory found at '+process_dir)
460  if not os.access(process_dir+'/bin/generate_events',os.R_OK):
461  raise RuntimeError('No generate_events module found in '+process_dir)
462 
463  mglog.info('For your information, the libraries available are (should include LHAPDF):')
464  ls_dir(process_dir+'/lib')
465 
466  setupFastjet(process_dir=process_dir)
467  if bias_module is not None:
468  setup_bias_module(bias_module,process_dir)
469 
470  mglog.info('Now I will hack the make files a bit. Apologies, but there seems to be no good way around this.')
471  shutil.copyfile(process_dir+'/Source/make_opts',process_dir+'/Source/make_opts_old')
472  old_opts = open(process_dir+'/Source/make_opts_old','r')
473  new_opts = open(process_dir+'/Source/make_opts','w')
474  for aline in old_opts:
475  if 'FC=g' in aline:
476  mglog.info('Configuring the fancy gfortran compiler instead of g77 / f77')
477  new_opts.write(' FC=gfortran\n')
478  else:
479  new_opts.write(aline)
480  old_opts.close()
481  new_opts.close()
482  mglog.info('Make file hacking complete.')
483 
484  # Change directories
485  currdir=os.getcwd()
486  os.chdir(process_dir)
487  # Record the change
488  global MADGRAPH_COMMAND_STACK
489  MADGRAPH_COMMAND_STACK += [ 'cd ${MGaMC_PROCESS_DIR}' ]
490 
491 
492  # Check the run card
493  run_card_consistency_check(isNLO=isNLO)
494 
495  # Since the consistency check can update some settings, print the cards now
496  print_cards_from_dir(process_dir=os.getcwd())
497 
498  # Check the param card
499  code = check_PMG_updates(process_dir=os.getcwd())
500  if requirePMGSettings and code!=0:
501  raise RuntimeError('Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
502 
503  # Build up the generate command
504  # Use the new-style way of passing things: just --name, everything else in config
505  command = [python,'bin/generate_events']
506  if isNLO:
507  command += ['--name='+MADGRAPH_RUN_NAME]
508  mglog.info('Removing Cards/shower_card.dat to ensure we get parton level events only')
509  os.unlink('Cards/shower_card.dat')
510  else:
511  command += [MADGRAPH_RUN_NAME]
512  # Set the number of cores to be used
513  setNCores(process_dir=os.getcwd(), Ncores=njobs)
514  # Special handling for mode 1
515  if mode==1:
516  mglog.info('Setting up cluster running')
517  modify_config_card(process_dir=os.getcwd(),settings={'run_mode':1})
518  if cluster_type=='pbs':
519  mglog.info('Modifying bin/internal/cluster.py for PBS cluster running')
520  os.system("sed -i \"s:text += prog:text += './'+prog:g\" bin/internal/cluster.py")
521  elif mode==2:
522  mglog.info('Setting up multi-core running on '+os.environ['ATHENA_CORE_NUMBER']+' cores')
523  elif mode==0:
524  mglog.info('Setting up serial generation.')
525 
526  generate_prep(process_dir=os.getcwd())
527  global MADGRAPH_CATCH_ERRORS
528  generate = stack_subprocess(command,stdin=subprocess.PIPE, stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
529  (out,err) = generate.communicate()
530  error_check(err,generate.returncode)
531 
532  # Get back to where we came from
533  os.chdir(currdir)
534  MADGRAPH_COMMAND_STACK += [ 'cd -' ]
535 
536  if grid_pack:
537  # Name dictacted by https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/PmgMcSoftware
538  energy = '%1.1f'%(beamEnergy*2./1000.)
539  energy = energy.replace('.0','').replace('.','p')
540  gridpack_name='mc_'+energy+'TeV.'+get_physics_short()+'.GRID.tar.gz'
541  mglog.info('Tidying up gridpack '+gridpack_name)
542 
543  if not isNLO:
544 
545  MADGRAPH_COMMAND_STACK += ['cp '+glob.glob(process_dir+'/'+MADGRAPH_RUN_NAME+'_*gridpack.tar.gz')[0]+' '+gridpack_name]
546  shutil.copy(glob.glob(process_dir+'/'+MADGRAPH_RUN_NAME+'_*gridpack.tar.gz')[0],gridpack_name)
547 
548  if gridpack_compile:
549  MADGRAPH_COMMAND_STACK += ['mkdir tmp%i/'%os.getpid(),'cd tmp%i/'%os.getpid()]
550  os.mkdir('tmp%i/'%os.getpid())
551  os.chdir('tmp%i/'%os.getpid())
552  mglog.info('untar gridpack')
553  untar = stack_subprocess(['tar','xvzf',('../'+gridpack_name)])
554  untar.wait()
555  mglog.info('compile and clean up')
556  MADGRAPH_COMMAND_STACK += ['cd madevent']
557  os.chdir('madevent/')
558  compilep = stack_subprocess(['./bin/compile'],stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
559  (out,err) = compilep.communicate()
560  error_check(err,compilep.returncode)
561  clean = stack_subprocess(['./bin/clean4grid'],stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
562  (out,err) = clean.communicate()
563  error_check(err,clean.returncode)
564  clean.wait()
565  MADGRAPH_COMMAND_STACK += ['cd ..','rm ../'+gridpack_name]
566  os.chdir('../')
567  mglog.info('remove old tarball')
568  os.unlink('../'+gridpack_name)
569  mglog.info('Package up new tarball')
570  tar = stack_subprocess(['tar','cvzf','../'+gridpack_name,'--exclude=SubProcesses/P*/G*/*_results.dat','--exclude=SubProcesses/P*/G*/*.log','--exclude=SubProcesses/P*/G*/*.txt','.'])
571  tar.wait()
572  MADGRAPH_COMMAND_STACK += ['cd ..','rm -r tmp%i/'%os.getpid()]
573  os.chdir('../')
574  mglog.info('Remove temporary directory')
575  shutil.rmtree('tmp%i/'%os.getpid())
576  mglog.info('Tidying up complete!')
577 
578  else:
579 
580 
581  mglog.info('Package up process_dir')
582  MADGRAPH_COMMAND_STACK += ['mv '+process_dir+' '+MADGRAPH_GRIDPACK_LOCATION]
583  os.rename(process_dir,MADGRAPH_GRIDPACK_LOCATION)
584  tar = stack_subprocess(['tar','czf',gridpack_name,MADGRAPH_GRIDPACK_LOCATION,'--exclude=Events/*/*events*gz','--exclude=SubProcesses/P*/G*/log*txt','--exclude=SubProcesses/P*/G*/events.lhe*','--exclude=*/*.o','--exclude=*/*/*.o','--exclude=*/*/*/*.o','--exclude=*/*/*/*/*.o'])
585  tar.wait()
586  MADGRAPH_COMMAND_STACK += ['mv '+MADGRAPH_GRIDPACK_LOCATION+' '+process_dir]
587  os.rename(MADGRAPH_GRIDPACK_LOCATION,process_dir)
588 
589  mglog.info('Gridpack sucessfully created, exiting the transform')
590  if hasattr(runArgs,'outputTXTFile'):
591  mglog.info('Touching output TXT (LHE) file for the transform')
592  open(runArgs.outputTXTFile, 'w').close()
593  from AthenaCommon.AppMgr import theApp
594  theApp.finalize()
595  theApp.exit()
596 
597  mglog.info('Finished at '+str(time.asctime()))
598  return 0
599 
600 

◆ generate_from_gridpack()

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

Definition at line 601 of file MadGraphUtils.py.

601 def generate_from_gridpack(runArgs=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False):
602 
603  # Get of info out of the runArgs
604  beamEnergy,random_seed = get_runArgs_info(runArgs)
605 
606  # Just in case
608 
609  isNLO=is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION)
610 
611  setupFastjet(process_dir=MADGRAPH_GRIDPACK_LOCATION)
612 
613  # This is hard-coded as a part of MG5_aMC :'(
614  gridpack_run_name = 'GridRun_'+str(random_seed)
615 
616  # Ensure that we only do madspin at the end
617  if os.access(MADGRAPH_GRIDPACK_LOCATION+'/Cards/madspin_card.dat',os.R_OK):
618  os.rename(MADGRAPH_GRIDPACK_LOCATION+'/Cards/madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+'/Cards/backup_madspin_card.dat')
619  do_madspin=True
620  else:
621  do_madspin=False
622 
623  if get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION) is not None:
624  check_reweight_card(MADGRAPH_GRIDPACK_LOCATION)
625 
626  # Check the param card
627  code = check_PMG_updates(process_dir=MADGRAPH_GRIDPACK_LOCATION)
628  if requirePMGSettings and code!=0:
629  raise RuntimeError('Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
630 
631  # Modify run card, then print
632  settings={'iseed':str(random_seed)}
633  if not isNLO:
634  settings['python_seed']=str(random_seed)
635  modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings=settings,skipBaseFragment=True)
636 
637  mglog.info('Generating events from gridpack')
638 
639  # Ensure that things are set up normally
640  if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION):
641  raise RuntimeError('Gridpack directory not found at '+MADGRAPH_GRIDPACK_LOCATION)
642 
643  nevents = getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+'/Cards/run_card.dat')['nevents']
644  mglog.info('>>>> FOUND GRIDPACK <<<< <- This will be used for generation')
645  mglog.info('Generation of '+str(int(nevents))+' events will be performed using the supplied gridpack with random seed '+str(random_seed))
646  mglog.info('Started generating events at '+str(time.asctime()))
647 
648  #Remove addmasses if it's there
649  if os.access(MADGRAPH_GRIDPACK_LOCATION+'/bin/internal/addmasses.py',os.R_OK):
650  os.remove(MADGRAPH_GRIDPACK_LOCATION+'/bin/internal/addmasses.py')
651 
652  currdir=os.getcwd()
653 
654  # Make sure we've set the number of processes appropriately
655  setNCores(process_dir=MADGRAPH_GRIDPACK_LOCATION)
656  global MADGRAPH_CATCH_ERRORS
657 
658  # Run the consistency check, print some useful info
659  ls_dir(currdir)
660  ls_dir(MADGRAPH_GRIDPACK_LOCATION)
661 
662  # Update the run card according to consistency checks
663  run_card_consistency_check(isNLO=isNLO,process_dir=MADGRAPH_GRIDPACK_LOCATION)
664 
665  # Now all done with updates, so print the cards with the final settings
666  print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION)
667 
668  if isNLO:
669  #turn off systematics for gridpack generation and store settings for standalone run
670  run_card_dict=getDictFromCard(MADGRAPH_GRIDPACK_LOCATION+'/Cards/run_card.dat')
671  systematics_settings=None
672  if checkSetting('systematics_program','systematics',run_card_dict):
673  if not checkSettingIsTrue('store_rwgt_info',run_card_dict):
674  raise RuntimeError('Trying to run NLO systematics but reweight info not stored')
675  if checkSettingExists('systematics_arguments',run_card_dict):
676  systematics_settings=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(run_card_dict['systematics_arguments'])
677  else:
678  systematics_settings={}
679  mglog.info('Turning off systematics for now, running standalone later')
680  modify_run_card(process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={'systematics_program':'none'},skipBaseFragment=True)
681 
682  global MADGRAPH_COMMAND_STACK
683  if not isNLO:
684 
685  if not os.access(MADGRAPH_GRIDPACK_LOCATION+'/bin/gridrun',os.R_OK):
686  mglog.error('/bin/gridrun not found at '+MADGRAPH_GRIDPACK_LOCATION)
687  raise RuntimeError('Could not find gridrun executable')
688  else:
689  mglog.info('Found '+MADGRAPH_GRIDPACK_LOCATION+'/bin/gridrun, starting generation.')
690  generate_prep(MADGRAPH_GRIDPACK_LOCATION)
691  granularity=1
692  mglog.info("Now generating {} events with random seed {} and granularity {}".format(int(nevents),int(random_seed),granularity))
693  # not sure whether this is needed but it is done in the old "run.sh" script
694  new_ld_path=":".join([os.environ['LD_LIBRARY_PATH'],os.getcwd()+'/'+MADGRAPH_GRIDPACK_LOCATION+'/madevent/lib',os.getcwd()+'/'+MADGRAPH_GRIDPACK_LOCATION+'/HELAS/lib'])
695  os.environ['LD_LIBRARY_PATH']=new_ld_path
696  MADGRAPH_COMMAND_STACK+=["export LD_LIBRARY_PATH="+":".join(['${LD_LIBRARY_PATH}',new_ld_path])]
697  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)
698  (out,err) = generate.communicate()
699  error_check(err,generate.returncode)
700  gp_events=MADGRAPH_GRIDPACK_LOCATION+"/Events/GridRun_{}/unweighted_events.lhe.gz".format(int(random_seed))
701  if not os.path.exists(gp_events):
702  mglog.error('Error in gp generation, did not find events at '+gp_events)
703 
704  # add reweighting, which is not run automatically from LO GPs
705  reweight_card=get_reweight_card(MADGRAPH_GRIDPACK_LOCATION)
706  if reweight_card is not None:
707  pythonpath_backup=os.environ['PYTHONPATH']
708  # workaround as madevent crashes when path to mg in PYTHONPATH
709  os.environ['PYTHONPATH']=':'.join([p for p in pythonpath_backup.split(':') if 'madgraph5amc' not in p])
710  add_reweighting('GridRun_{}'.format(int(random_seed)))
711  os.environ['PYTHONPATH']=pythonpath_backup
712 
713  shutil.move(gp_events,'events.lhe.gz')
714 
715  else:
716 
717  if not os.access(MADGRAPH_GRIDPACK_LOCATION+'/bin/generate_events',os.R_OK):
718  raise RuntimeError('Could not find generate_events executable at '+MADGRAPH_GRIDPACK_LOCATION)
719  else:
720  mglog.info('Found '+MADGRAPH_GRIDPACK_LOCATION+'/bin/generate_events, starting generation.')
721 
722  ls_dir(MADGRAPH_GRIDPACK_LOCATION+'/Events/')
723  if os.access(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name, os.F_OK):
724  mglog.info('Removing '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+' directory from gridpack generation')
725  MADGRAPH_COMMAND_STACK += ['rm -rf '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name]
726  shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name)
727 
728  # Delete events generated when setting up MadSpin during gridpack generation
729  if os.access(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1', os.F_OK):
730  mglog.info('Removing '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1 directory from gridpack generation')
731  MADGRAPH_COMMAND_STACK += ['rm -rf '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1']
732  shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'_decayed_1')
733 
734  ls_dir(MADGRAPH_GRIDPACK_LOCATION+'/Events/')
735 
736  if not gridpack_compile:
737  mglog.info('Copying make_opts from Template')
738  shutil.copy(os.environ['MADPATH']+'/Template/LO/Source/make_opts',MADGRAPH_GRIDPACK_LOCATION+'/Source/')
739 
740  generate_prep(MADGRAPH_GRIDPACK_LOCATION)
741  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)
742  (out,err) = generate.communicate()
743  error_check(err,generate.returncode)
744  else:
745  mglog.info('Allowing recompilation of gridpack')
746  if os.path.islink(MADGRAPH_GRIDPACK_LOCATION+'/lib/libLHAPDF.a'):
747  mglog.info('Unlinking '+MADGRAPH_GRIDPACK_LOCATION+'/lib/libLHAPDF.a')
748  os.unlink(MADGRAPH_GRIDPACK_LOCATION+'/lib/libLHAPDF.a')
749 
750  generate_prep(MADGRAPH_GRIDPACK_LOCATION)
751  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)
752  (out,err) = generate.communicate()
753  error_check(err,generate.returncode)
754  if isNLO and systematics_settings is not None:
755  # run systematics
756  mglog.info('Running systematics standalone')
757  systematics_path=MADGRAPH_GRIDPACK_LOCATION+'/bin/internal/systematics.py'
758  events_location=MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/events.lhe.gz'
759  syst_cmd=[python,systematics_path]+[events_location]*2+["--"+k+"="+systematics_settings[k] for k in systematics_settings]
760  mglog.info('running: '+' '.join(syst_cmd))
761  systematics = stack_subprocess(syst_cmd)
762  systematics.wait()
763 
764 
765  # See if MG5 did the job for us already
766  if not os.access('events.lhe.gz',os.R_OK):
767  mglog.info('Copying generated events to '+currdir)
768  if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION+'Events/'+gridpack_run_name):
769  shutil.copy(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/events.lhe.gz','events.lhe.gz')
770  else:
771  mglog.info('Events were already in place')
772 
773  ls_dir(currdir)
774 
775  mglog.info('Moving generated events to be in correct format for arrange_output().')
776  mglog.info('Unzipping generated events.')
777  unzip = stack_subprocess(['gunzip','-f','events.lhe.gz'])
778  unzip.wait()
779 
780  mglog.info('Moving file over to '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe')
781  mkdir = stack_subprocess(['mkdir','-p',(MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name)])
782  mkdir.wait()
783  shutil.move('events.lhe',MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe')
784 
785  mglog.info('Re-zipping into dataset name '+MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe.gz')
786  rezip = stack_subprocess(['gzip',MADGRAPH_GRIDPACK_LOCATION+'/Events/'+gridpack_run_name+'/unweighted_events.lhe'])
787  rezip.wait()
788 
789  os.chdir(currdir)
790 
791  # Now consider MadSpin:
792  if do_madspin:
793  # Move card back
794  os.rename(MADGRAPH_GRIDPACK_LOCATION+'/Cards/backup_madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+'/Cards/madspin_card.dat')
795  mglog.info('Decaying with MadSpin.')
796  add_madspin(process_dir=MADGRAPH_GRIDPACK_LOCATION)
797 
798  mglog.info('Finished at '+str(time.asctime()))
799 
800  return 0
801 
802 

◆ generate_prep()

def python.MadGraphUtils.generate_prep (   process_dir)

Definition at line 84 of file MadGraphUtils.py.

84 def generate_prep(process_dir):
85  global MADGRAPH_COMMAND_STACK
86  if not os.access('Cards_bkup',os.R_OK):
87  shutil.copytree(process_dir+'/Cards','Cards_bkup')
88  shutil.copyfile(process_dir+'/Source/make_opts','Cards_bkup/make_opts_bkup')
89  MADGRAPH_COMMAND_STACK += ['# In case this fails, Cards_bkup should be in your original run directory']
90  MADGRAPH_COMMAND_STACK += ['# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
91  MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup/*dat ${MGaMC_PROCESS_DIR}/Cards/']
92  MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
93  else:
94  mglog.warning('Found Cards_bkup directory existing. Suggests you are either running generation twice (a little funny) or are not using a clean directory.')
95  bkup_v = 1
96  while os.access('Cards_bkup_'+str(bkup_v),os.R_OK) and bkup_v<100:
97  bkup_v += 1
98  if bkup_v<100:
99  shutil.copytree(process_dir+'/Cards','Cards_bkup_'+str(bkup_v))
100  shutil.copyfile(process_dir+'/Source/make_opts','Cards_bkup_'+str(bkup_v)+'/make_opts_bkup')
101  MADGRAPH_COMMAND_STACK += ['# In case this fails, Cards_bkup should be in your original run directory']
102  MADGRAPH_COMMAND_STACK += ['# And ${MGaMC_PROCESS_DIR} can be replaced with whatever process directory exists in your stand-alone test']
103  MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup_'+str(bkup_v)+'/*dat ${MGaMC_PROCESS_DIR}/Cards/']
104  MADGRAPH_COMMAND_STACK += ['cp '+os.getcwd()+'/Cards_bkup_'+str(bkup_v)+'/make_opts_bkup ${MGaMC_PROCESS_DIR}/Source/make_opts']
105  else:
106  mglog.warning('Way too many Cards_bkup* directories found. Giving up -- standalone script may not work.')
107 
108 

◆ get_cluster_type()

def python.MadGraphUtils.get_cluster_type (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2295 of file MadGraphUtils.py.

2295 def get_cluster_type(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2296  card_in = open(get_default_config_card(process_dir=process_dir),'r')
2297  for l in card_in.readlines():
2298  if 'cluster_type' not in l.split('#')[0]:
2299  continue
2300  cluster_type = l.split('#')[0].split('=')[1]
2301  mglog.info('Returning cluster type: '+cluster_type)
2302  return cluster_type
2303  return None
2304 
2305 

◆ get_default_config_card()

def python.MadGraphUtils.get_default_config_card (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2274 of file MadGraphUtils.py.

2274 def get_default_config_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2275  if config_only_check():
2276  mglog.info('Athena running on config only mode: grabbing config card the old way, as there will be no proc dir')
2277  if os.access(os.environ['MADPATH']+'/input/mg5_configuration.txt',os.R_OK):
2278  shutil.copy(os.environ['MADPATH']+'/input/mg5_configuration.txt','local_mg5_configuration.txt')
2279  return 'local_mg5_configuration.txt'
2280 
2281  lo_config_card=process_dir+'/Cards/me5_configuration.txt'
2282  nlo_config_card=process_dir+'/Cards/amcatnlo_configuration.txt'
2283 
2284  if os.access(lo_config_card,os.R_OK) and not os.access(nlo_config_card,os.R_OK):
2285  return lo_config_card
2286  elif os.access(nlo_config_card,os.R_OK) and not os.access(lo_config_card,os.R_OK):
2287  return nlo_config_card
2288  elif os.access(nlo_config_card,os.R_OK) and os.access(lo_config_card,os.R_OK):
2289  mglog.error('Found both types of config card in '+process_dir)
2290  else:
2291  mglog.error('No config card in '+process_dir)
2292  raise RuntimeError('Unable to locate configuration card')
2293 
2294 

◆ get_default_runcard()

def 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 359 of file MadGraphUtils.py.

359 def get_default_runcard(process_dir=MADGRAPH_GRIDPACK_LOCATION):
360  """ Copy the default runcard from one of several locations
361  to a local file with name run_card.tmp.dat"""
362  output_name = 'run_card.tmp.dat'
363  if config_only_check():
364  mglog.info('Athena running on config only mode: grabbing run card the old way, as there will be no proc dir')
365  mglog.info('Fetching default LO run_card.dat')
366  if os.access(os.environ['MADPATH']+'/Template/LO/Cards/run_card.dat',os.R_OK):
367  shutil.copy(os.environ['MADPATH']+'/Template/LO/Cards/run_card.dat',output_name)
368  return 'run_card.dat'
369  elif os.access(os.environ['MADPATH']+'/Template/Cards/run_card.dat',os.R_OK):
370  shutil.copy(os.environ['MADPATH']+'/Template/Cards/run_card.dat',output_name)
371  return output_name
372  else:
373  raise RuntimeError('Cannot find default LO run_card.dat!')
374 
375  # Get the run card from the installation
376  run_card=process_dir+'/Cards/run_card.dat'
377  if os.access(run_card,os.R_OK):
378  mglog.info('Copying default run_card.dat from '+str(run_card))
379  shutil.copy(run_card,output_name)
380  return output_name
381  else:
382  run_card=process_dir+'/Cards/run_card_default.dat'
383  mglog.info('Fetching default run_card.dat from '+str(run_card))
384  if os.access(run_card,os.R_OK):
385  shutil.copy(run_card,output_name)
386  return output_name
387  else:
388  raise RuntimeError('Cannot find default run_card.dat or run_card_default.dat! I was looking here: %s'%run_card)
389 
390 

◆ get_expected_reweight_names()

def python.MadGraphUtils.get_expected_reweight_names (   reweight_card_loc)

Definition at line 1474 of file MadGraphUtils.py.

1474 def get_expected_reweight_names(reweight_card_loc):
1475  if reweight_card_loc is None:
1476  return []
1477  names=[]
1478  f_rw=open(reweight_card_loc)
1479  for line in f_rw:
1480  if 'launch' not in line:
1481  continue
1482  match=re.match(r'launch.*--rwgt_info\s*=\s*(\S+).*',line.strip())
1483  if len(match.groups())!=1:
1484  raise RuntimeError('Unexpected format of reweight card in line'+line)
1485  else:
1486  names+=[match.group(1)]
1487  f_rw.close()
1488  return names
1489 

◆ get_expected_systematic_names()

def python.MadGraphUtils.get_expected_systematic_names (   syst_setting)

Definition at line 1490 of file MadGraphUtils.py.

1490 def get_expected_systematic_names(syst_setting):
1491  names=[]
1492  if syst_setting is None or 'central_pdf' not in syst_setting:
1493  mglog.warning("Systematics have not been defined via base fragment or 'MADGRAPH_PDFSETTING', cannot check for expected weights")
1494  return []
1495  if 'pdf_variations' in syst_setting and isinstance(syst_setting['pdf_variations'],list):
1496  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':syst_setting['central_pdf']}]
1497  for pdf in syst_setting['pdf_variations']:
1498  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':pdf+1}]
1499  if 'alternative_pdfs' in syst_setting and isinstance(syst_setting['alternative_pdfs'],list):
1500  for pdf in syst_setting['alternative_pdfs']:
1501  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':pdf}]
1502  if 'scale_variations' in syst_setting and isinstance(syst_setting['scale_variations'],list):
1503  for mur in syst_setting['scale_variations']:
1504  for muf in syst_setting['scale_variations']:
1505  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':mur,'muf':muf,'pdf':syst_setting['central_pdf']}]
1506  return names
1507 

◆ get_mg5_executable()

def python.MadGraphUtils.get_mg5_executable ( )

Definition at line 1000 of file MadGraphUtils.py.

1000 def get_mg5_executable():
1001  madpath=os.environ['MADPATH']
1002  if not os.access(madpath+'/bin/mg5_aMC',os.R_OK):
1003  raise RuntimeError('mg5_aMC executable not found in '+madpath)
1004  return madpath+'/bin/mg5_aMC'
1005 
1006 

◆ get_reweight_card()

def python.MadGraphUtils.get_reweight_card (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1558 of file MadGraphUtils.py.

1558 def get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1559  if os.access(process_dir+'/Cards/reweight_card.dat',os.R_OK):
1560  return process_dir+'/Cards/reweight_card.dat'
1561  return None
1562 
1563 

◆ get_SUSY_variations()

def python.MadGraphUtils.get_SUSY_variations (   process,
  masses,
  syst_mod,
  ktdurham = None 
)

Definition at line 1627 of file MadGraphUtils.py.

1627 def get_SUSY_variations( process , masses , syst_mod , ktdurham = None ):
1628  # Don't override an explicit setting from the run card!
1629  if ktdurham is None:
1630  prod_particles = []
1631  if process is not None:
1632  id_map = {'go':'1000021','dl':'1000001','ul':'1000002','sl':'1000003','cl':'1000004','b1':'1000005','t1':'1000006',
1633  'dr':'2000001','ur':'2000002','sr':'2000003','cr':'2000004','b2':'2000005','t2':'2000006',
1634  'n1':'1000022','n2':'1000023','x1':'1000024','x2':'1000037','n3':'1000025','n4':'1000035',
1635  'el':'1000011','mul':'1000013','ta1':'1000015','sve':'1000012','svm':'1000014','svt':'1000016',
1636  'er':'2000011','mur':'2000013','ta2':'2000015'}
1637  for l in process:
1638  if 'generate' in l or 'add process' in l:
1639  clean_proc = l.replace('generate','').replace('+','').replace('-','').replace('~','').replace('add process','').split('>')[1].split(',')[0]
1640  for particle in clean_proc.split():
1641  if particle not in id_map:
1642  mglog.info(f'Particle {particle} not found in PDG ID map - skipping')
1643  else:
1644  prod_particles += id_map[particle]
1645  # If we don't specify a process, then all we can do is guess based on available masses
1646  # Same if we failed to identify the right particles
1647  my_mass = 10000.
1648  if len(prod_particles)>0:
1649  for x in prod_particles:
1650  if x in masses:
1651  my_mass = min(my_mass,abs(float(masses[x])))
1652  else:
1653  mglog.info(f'Seem to ask for production of PDG ID {x}, but {x} not in mass dictionary?')
1654  if my_mass>9999.:
1655  strong_ids = ['1000001','1000002','1000003','1000004','1000005','1000006','2000001','2000002','2000003','2000004','2000005','2000006','1000021']
1656  weak_ids = ['1000023','1000024','1000025','1000011','1000013','1000015','2000011','2000013','2000015','1000012','1000014','1000016']
1657  # First check the lightest of the heavy sparticles - all squarks and gluino
1658  my_mass = min([abs(float(masses[x])) for x in strong_ids if x in masses])
1659  # Now check if strong production was not the key mode
1660  if my_mass>10000.:
1661  # This is a little tricky, but: we want the heaviest non-decoupled mass
1662  my_mass = max([abs(float(masses[x])) for x in weak_ids if x in masses and float(masses[x])<10000.])
1663  # Final check for N1N1 with everything else decoupled
1664  if my_mass>10000. and '1000022' in masses:
1665  my_mass = masses['1000022']
1666  if my_mass>10000.:
1667  raise RuntimeError('Could not understand which mass to use for matching cut in '+str(masses))
1668 
1669  # Now set the matching scale accordingly
1670  ktdurham = min(my_mass*0.25,500)
1671  # Should not be weirdly low - can't imagine a situation where you'd really want the scale below 15 GeV
1672  ktdurham = max(ktdurham,15)
1673  if syst_mod is not None and 'qup' in syst_mod.lower():
1674  ktdurham = ktdurham*2.
1675  elif syst_mod is not None and 'qdown' in syst_mod.lower():
1676  ktdurham = ktdurham*0.5
1677 
1678  mglog.info('For matching, will use ktdurham of '+str(ktdurham))
1679 
1680  alpsfact = 1.0
1681  scalefact = 1.0
1682  if syst_mod is not None and 'alpsfactup' in syst_mod.lower():
1683  alpsfact = 2.0
1684  elif syst_mod is not None and 'alpsfactdown' in syst_mod.lower():
1685  alpsfact = 0.5
1686 
1687  if syst_mod is not None and 'scalefactup' in syst_mod.lower():
1688  scalefact = 2.0
1689  elif syst_mod is not None and 'scalefactdown' in syst_mod.lower():
1690  scalefact = 0.5
1691 
1692  return abs(ktdurham) , alpsfact , scalefact
1693 
1694 

◆ helpful_SUSY_definitions()

def python.MadGraphUtils.helpful_SUSY_definitions ( )

Definition at line 1600 of file MadGraphUtils.py.

1601  return """
1602 # Define multiparticle labels
1603 define p = g u c d s u~ c~ d~ s~
1604 define j = g u c d s u~ c~ d~ s~
1605 define pb = g u c d s b u~ c~ d~ s~ b~
1606 define jb = g u c d s b u~ c~ d~ s~ b~
1607 define l+ = e+ mu+
1608 define l- = e- mu-
1609 define vl = ve vm vt
1610 define vl~ = ve~ vm~ vt~
1611 define fu = u c e+ mu+ ta+
1612 define fu~ = u~ c~ e- mu- ta-
1613 define fd = d s ve~ vm~ vt~
1614 define fd~ = d~ s~ ve vm vt
1615 define susystrong = go ul ur dl dr cl cr sl sr t1 t2 b1 b2 ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~ t1~ t2~ b1~ b2~
1616 define susyweak = el- el+ er- er+ mul- mul+ mur- mur+ ta1- ta1+ ta2- ta2+ n1 n2 n3 n4 x1- x1+ x2- x2+ sve sve~ svm svm~ svt svt~
1617 define susylq = ul ur dl dr cl cr sl sr
1618 define susylq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~
1619 define susysq = ul ur dl dr cl cr sl sr t1 t2 b1 b2
1620 define susysq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~ t1~ t2~ b1~ b2~
1621 define susysl = el- el+ er- er+ mul- mul+ mur- mur+ ta1- ta1+ ta2- ta2+
1622 define susyv = sve svm svt
1623 define susyv~ = sve~ svm~ svt~
1624 """
1625 
1626 

◆ is_gen_from_gridpack()

def 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 2262 of file MadGraphUtils.py.

2262 def is_gen_from_gridpack():
2263  """ Simple function for checking if there is a grid pack.
2264  Relies on the specific location of the unpacked gridpack (madevent)
2265  which is here set as a global variable. The gridpack is untarred by
2266  the transform (Gen_tf.py) and no sign is sent to the job itself
2267  that there is a gridpack in use except the file's existence"""
2268  if os.access(MADGRAPH_GRIDPACK_LOCATION,os.R_OK):
2269  mglog.info('Located input grid pack area')
2270  return True
2271  return False
2272 
2273 

◆ is_NLO_run()

def python.MadGraphUtils.is_NLO_run (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2306 of file MadGraphUtils.py.

2306 def is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2307  # Very simple check based on the above config card grabbing
2308  if config_only_check():
2309  return False
2310  return get_default_config_card(process_dir=process_dir)==process_dir+'/Cards/amcatnlo_configuration.txt'
2311 
2312 

◆ ls_dir()

def python.MadGraphUtils.ls_dir (   directory)

Definition at line 2443 of file MadGraphUtils.py.

2443 def ls_dir(directory):
2444  mglog.info('For your information, ls of '+directory+':')
2445  mglog.info( sorted( os.listdir( directory ) ) )
2446 
2447 # Final import of some code used in these functions

◆ madspin_on_lhe()

def 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 1108 of file MadGraphUtils.py.

1108 def madspin_on_lhe(input_LHE,madspin_card,runArgs=None,keep_original=False):
1109  """ Run MadSpin on an input LHE file. Takes the process
1110  from the LHE file, so you don't need to have a process directory
1111  set up in advance. Runs MadSpin and packs the LHE file up appropriately
1112  Needs runArgs for the file handling"""
1113  if not os.access(input_LHE,os.R_OK):
1114  raise RuntimeError('Could not find LHE file '+input_LHE)
1115  if not os.access(madspin_card,os.R_OK):
1116  raise RuntimeError('Could not find input MadSpin card '+madspin_card)
1117  if keep_original:
1118  shutil.copy(input_LHE,input_LHE+'.original')
1119  mglog.info('Put backup copy of LHE file at '+input_LHE+'.original')
1120  # Start writing the card for execution
1121  madspin_exec_card = open('madspin_exec_card','w')
1122  madspin_exec_card.write('import '+input_LHE+'\n')
1123  # Based on the original card
1124  input_madspin_card = open(madspin_card,'r')
1125  has_launch = False
1126  for l in input_madspin_card.readlines():
1127  commands = l.split('#')[0].split()
1128  # Skip import of a file name that isn't our file
1129  if len(commands)>1 and 'import'==commands[0] and not 'model'==commands[1]:
1130  continue
1131  # Check for a launch command
1132  if len(commands)>0 and 'launch' == commands[0]:
1133  has_launch = True
1134  madspin_exec_card.write(l.strip()+'\n')
1135  if not has_launch:
1136  madspin_exec_card.write('launch\n')
1137  madspin_exec_card.close()
1138  input_madspin_card.close()
1139  # Now get the madspin executable
1140  madpath=os.environ['MADPATH']
1141  if not os.access(madpath+'/MadSpin/madspin',os.R_OK):
1142  raise RuntimeError('madspin executable not found in '+madpath)
1143  mglog.info('Starting madspin at '+str(time.asctime()))
1144  global MADGRAPH_CATCH_ERRORS
1145  generate = stack_subprocess([python,madpath+'/MadSpin/madspin','madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1146  (out,err) = generate.communicate()
1147  error_check(err,generate.returncode)
1148  mglog.info('Done with madspin at '+str(time.asctime()))
1149  # Should now have a re-zipped LHE file
1150  # We now have to do a shortened version of arrange_output below
1151  # Clean up in case a link or file was already there
1152  if os.path.exists(os.getcwd()+'/events.lhe'):
1153  os.remove(os.getcwd()+'/events.lhe')
1154 
1155  mglog.info('Unzipping generated events.')
1156  unzip = stack_subprocess(['gunzip','-f',input_LHE+'.gz'])
1157  unzip.wait()
1158 
1159  mglog.info('Putting a copy in place for the transform.')
1160  mod_output = open(os.getcwd()+'/events.lhe','w')
1161 
1162  #Removing empty lines in LHE
1163  nEmpty=0
1164  with open(input_LHE,'r') as fileobject:
1165  for line in fileobject:
1166  if line.strip():
1167  mod_output.write(line)
1168  else:
1169  nEmpty=nEmpty+1
1170  mod_output.close()
1171 
1172  mglog.info('Removed '+str(nEmpty)+' empty lines from LHEF')
1173 
1174  # Actually move over the dataset - this first part is horrible...
1175  if runArgs is None:
1176  raise RuntimeError('Must provide runArgs to madspin_on_lhe')
1177 
1178  outputDS = runArgs.outputTXTFile if hasattr(runArgs,'outputTXTFile') else 'tmp_LHE_events'
1179 
1180  mglog.info('Moving file over to '+outputDS.split('.tar.gz')[0]+'.events')
1181  shutil.move(os.getcwd()+'/events.lhe',outputDS.split('.tar.gz')[0]+'.events')
1182 
1183  mglog.info('Re-zipping into dataset name '+outputDS)
1184  rezip = stack_subprocess(['tar','cvzf',outputDS,outputDS.split('.tar.gz')[0]+'.events'])
1185  rezip.wait()
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 

◆ modify_config_card()

def 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 2155 of file MadGraphUtils.py.

2155 def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
2156  """Build a new configuration from an existing one.
2157  This function can get a fresh runcard from DATAPATH or start from the process directory.
2158  Settings is a dictionary of keys (no spaces needed) and values to replace.
2159  """
2160  # Check for the default config card location
2161  config_card=get_default_config_card(process_dir=process_dir)
2162 
2163  # The format is similar to the run card, but backwards
2164  mglog.info('Modifying config card located at '+config_card)
2165  if config_card_backup is not None:
2166  mglog.info('Keeping backup of original config card at '+config_card_backup)
2167  config_card_old = config_card_backup
2168  else:
2169  config_card_old = config_card+'.old_to_be_deleted'
2170  mglog.debug('Modifying config card settings: '+str(settings))
2171  if os.path.isfile(config_card_old):
2172  os.unlink(config_card_old) # delete old backup
2173  os.rename(config_card, config_card_old) # change name of original card
2174 
2175  oldCard = open(config_card_old, 'r')
2176  newCard = open(config_card, 'w')
2177  used_settings = []
2178  for line in iter(oldCard):
2179  lmod = line if set_commented else line.split('#')[0]
2180  if '=' in lmod:
2181  modified = False
2182  for setting in settings:
2183  if setting not in lmod:
2184  continue
2185  # Assume we hit
2186  mglog.info('Setting '+setting.strip()+' to '+str(settings[setting]))
2187  newCard.write(' '+str(setting.strip())+' = '+str(settings[setting])+'\n')
2188  used_settings += [ setting.strip() ]
2189  modified = True
2190  break
2191  if modified:
2192  continue
2193  newCard.write(line)
2194 
2195  # Clean up unused options
2196  for asetting in settings:
2197  if asetting in used_settings:
2198  continue
2199  if settings[asetting] is None:
2200  continue
2201  mglog.warning('Option '+asetting+' was not in the default config card. Adding by hand a setting to '+str(settings[asetting]) )
2202  newCard.write(' '+str(asetting)+' = '+str(settings[asetting])+'\n')
2203  # close files
2204  oldCard.close()
2205  newCard.close()
2206  mglog.info('Finished modification of config card.')
2207  if config_card_backup is None:
2208  os.unlink(config_card_old)
2209 
2210 

◆ modify_param_card()

def 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 1902 of file MadGraphUtils.py.

1902 def modify_param_card(param_card_input=None,param_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,params={},output_location=None):
1903  """Build a new param_card.dat from an existing one.
1904  Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
1905  Keys can include MASS (for masses) and DECAY X (for decays of particle X)"""
1906  # Grab the old param card and move it into place
1907 
1908  # Check for the default run card location
1909  if param_card_input is None:
1910  param_card_input=process_dir+'/Cards/param_card.dat'
1911  elif param_card_input is not None and not os.access(param_card_input,os.R_OK):
1912  paramcard = subprocess.Popen(['get_files','-data',param_card_input])
1913  paramcard.wait()
1914  if not os.access(param_card_input,os.R_OK):
1915  raise RuntimeError('Could not get param card '+param_card_input)
1916  mglog.info('Using input param card at '+param_card_input)
1917 
1918  #ensure all blocknames and paramnames are upper case
1919  paramsUpper = {}
1920  for blockName in list(params.keys()):
1921  paramsUpper[blockName.upper()] = {}
1922  for paramName in list(params[blockName].keys()):
1923  paramsUpper[blockName.upper()][paramName.upper()] = params[blockName][paramName]
1924 
1925  if param_card_backup is not None:
1926  mglog.info('Keeping backup of original param card at '+param_card_backup)
1927  param_card_old = param_card_backup
1928  else:
1929  param_card_old = param_card_input+'.old_to_be_deleted'
1930  if os.path.isfile(param_card_old):
1931  os.unlink(param_card_old) # delete old backup
1932  os.rename(param_card_input, param_card_old) # change name of original card
1933 
1934  oldcard = open(param_card_old,'r')
1935  param_card_location= process_dir+'/Cards/param_card.dat' if output_location is None else output_location
1936  newcard = open(param_card_location,'w')
1937  decayEdit = False #only becomes true in a DECAY block when specifying the BR
1938  blockName = ""
1939  doneParams = {} #tracks which params have been done
1940  for linewithcomment in oldcard:
1941  line=linewithcomment.split('#')[0]
1942  if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
1943  and len(line.strip().split()) > 1:
1944  if decayEdit and blockName == 'DECAY':
1945  decayEdit = False # Start a new DECAY block
1946  pos = 0 if line.strip().startswith('DECAY') else 1
1947  if blockName=='MASS' and 'MASS' in paramsUpper:
1948  # Any residual masses to set?
1949  if "MASS" in doneParams:
1950  leftOvers = [ x for x in paramsUpper['MASS'] if x not in doneParams['MASS'] ]
1951  else:
1952  leftOvers = [ x for x in paramsUpper['MASS'] ]
1953 
1954  for pdg_id in leftOvers:
1955  mglog.warning('Adding mass line for '+str(pdg_id)+' = '+str(paramsUpper['MASS'][pdg_id])+' which was not in original param card')
1956  newcard.write(' '+str(pdg_id)+' '+str(paramsUpper['MASS'][pdg_id])+'\n')
1957  doneParams['MASS'][pdg_id]=True
1958  if blockName=='DECAY' and 'DECAY' not in line.strip().upper() and 'DECAY' in paramsUpper:
1959  # Any residual decays to include?
1960  leftOvers = [ x for x in paramsUpper['DECAY'] if x not in doneParams['DECAY'] ]
1961  for pdg_id in leftOvers:
1962  mglog.warning('Adding decay for pdg id '+str(pdg_id)+' which was not in the original param card')
1963  newcard.write( paramsUpper['DECAY'][pdg_id].strip()+'\n' )
1964  doneParams['DECAY'][pdg_id]=True
1965  blockName = line.strip().upper().split()[pos]
1966  if decayEdit:
1967  continue #skipping these lines because we are in an edit of the DECAY BR
1968 
1969  akey = None
1970  if blockName != 'DECAY' and len(line.strip().split()) > 0:
1971  # The line is already without the comment.
1972  # In the case of mixing matrices this is a bit tricky
1973  if len(line.split())==2:
1974  akey = line.upper().strip().split()[0]
1975  else:
1976  # Take everything but the last word
1977  akey = line.upper().strip()[:line.strip().rfind(' ')].strip()
1978  elif blockName == 'DECAY' and len(line.strip().split()) > 1:
1979  akey = line.strip().split()[1]
1980  if akey is None:
1981  newcard.write(linewithcomment)
1982  continue
1983 
1984  #check if we have params for this block
1985  if blockName not in paramsUpper:
1986  newcard.write(linewithcomment)
1987  continue
1988  blockParams = paramsUpper[blockName]
1989  # Check the spacing in the key
1990  akey = find_key_and_update(akey,blockParams)
1991 
1992  # look for a string key, which would follow a #
1993  stringkey = None
1994  if '#' in linewithcomment: #ignores comment lines
1995  stringkey = linewithcomment[linewithcomment.find('#')+1:].strip()
1996  if len(stringkey.split()) > 0:
1997  stringkey = stringkey.split()[0].upper()
1998 
1999  if akey not in blockParams and not (stringkey is not None and stringkey in blockParams):
2000  newcard.write(linewithcomment)
2001  continue
2002 
2003  if akey in blockParams and (stringkey is not None and stringkey in blockParams):
2004  raise RuntimeError('Conflicting use of numeric and string keys '+akey+' and '+stringkey)
2005 
2006  theParam = blockParams.get(akey,blockParams[stringkey] if stringkey in blockParams else None)
2007  if blockName not in doneParams:
2008  doneParams[blockName] = {}
2009  if akey in blockParams:
2010  doneParams[blockName][akey]=True
2011  elif stringkey is not None and stringkey in blockParams:
2012  doneParams[blockName][stringkey]=True
2013 
2014  #do special case of DECAY block
2015  if blockName=="DECAY":
2016  if theParam.splitlines()[0].split()[0].upper()=="DECAY":
2017  #specifying the full decay block
2018  for newline in theParam.splitlines():
2019  newcard.write(newline+'\n')
2020  mglog.info(newline)
2021  decayEdit = True
2022  else: #just updating the total width
2023  newcard.write('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2024  mglog.info('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2025  # second special case of QNUMBERS
2026  elif blockName=='QNUMBERS':
2027  #specifying the full QNUMBERS block
2028  for newline in theParam.splitlines():
2029  newcard.write(newline+'\n')
2030  mglog.info(newline)
2031  decayEdit = True
2032  else: #just updating the parameter
2033  newcard.write(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2034  mglog.info(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2035  # Done editing the line!
2036 
2037  #check that all specified parameters have been updated (helps to catch typos)
2038  for blockName in paramsUpper:
2039  if blockName not in doneParams and len(paramsUpper[blockName].keys())>0:
2040  raise RuntimeError('Did not find any of the parameters for block '+blockName+' in param_card')
2041  for paramName in paramsUpper[blockName]:
2042  if paramName not in doneParams[blockName]:
2043  raise RuntimeError('Was not able to replace parameter '+paramName+' in param_card')
2044 
2045  # Close up and return
2046  oldcard.close()
2047  newcard.close()
2048 
2049 

◆ modify_run_card()

def 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 2050 of file MadGraphUtils.py.

2050 def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
2051  """Build a new run_card.dat from an existing one.
2052  This function can get a fresh runcard from DATAPATH or start from the process directory.
2053  Settings is a dictionary of keys (no spaces needed) and values to replace.
2054  """
2055  if config_only_check():
2056  mglog.info('Running config-only. No proc card, so not operating on the run card.')
2057  return
2058 
2059  # Operate on lower case settings, and choose the capitalization MG5 has as the default (or all lower case)
2060  settings_lower = {}
2061  for s in list(settings.keys()):
2062  settings_lower[s.lower()] = settings[s]
2063 
2064  # Check for the default run card location
2065  if run_card_input is None:
2066  run_card_input=get_default_runcard(process_dir)
2067  elif run_card_input is not None and not os.access(run_card_input,os.R_OK):
2068  runcard = subprocess.Popen(['get_files','-data',run_card_input])
2069  runcard.wait()
2070  if not os.access(run_card_input,os.R_OK):
2071  raise RuntimeError('Could not get run card '+run_card_input)
2072 
2073  # guess NLO
2074  isNLO=is_NLO_run(process_dir=process_dir)
2075  # add gobal PDF and scale uncertainty config to extras, except PDF or weights for syscal config are explictly set
2076  if not skipBaseFragment:
2077  MadGraphControl.MadGraphSystematicsUtils.setup_pdf_and_systematic_weights(MADGRAPH_PDFSETTING,settings_lower,isNLO)
2078 
2079  # Get some info out of the runArgs
2080  if runArgs is not None:
2081  beamEnergy,rand_seed = get_runArgs_info(runArgs)
2082  if 'iseed' not in settings_lower:
2083  settings_lower['iseed']=rand_seed
2084  if not isNLO and 'python_seed' not in settings_lower:
2085  settings_lower['python_seed']=rand_seed
2086  if 'beamenergy' in settings_lower:
2087  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']))
2088  beamEnergy=settings_lower['beamenergy']
2089  settings_lower.pop('beamenergy')
2090  if 'ebeam1' not in settings_lower:
2091  settings_lower['ebeam1']=beamEnergy
2092  if 'ebeam2' not in settings_lower:
2093  settings_lower['ebeam2']=beamEnergy
2094  # Make sure nevents is an integer
2095  if 'nevents' in settings_lower:
2096  settings_lower['nevents'] = int(settings_lower['nevents'])
2097 
2098  mglog.info('Modifying run card located at '+run_card_input)
2099  if run_card_backup is not None:
2100  mglog.info('Keeping backup of original run card at '+run_card_backup)
2101  run_card_old = run_card_backup
2102  else:
2103  run_card_old = run_card_input+'.old_to_be_deleted'
2104  mglog.debug('Modifying runcard settings: '+str(settings_lower))
2105  if os.path.isfile(run_card_old):
2106  os.unlink(run_card_old) # delete old backup
2107  os.rename(run_card_input, run_card_old) # change name of original card
2108 
2109  oldCard = open(run_card_old, 'r')
2110  newCard = open(process_dir+'/Cards/run_card.dat', 'w')
2111  used_settings = []
2112  for line in iter(oldCard):
2113  if not line.strip().startswith('#'): # line commented out
2114  command = line.split('!', 1)[0]
2115  comment = line.split('!', 1)[1] if '!' in line else ''
2116  if '=' in command:
2117  setting = command.split('=')[-1] #.strip()
2118  stripped_setting = setting.strip()
2119  oldValue = '='.join(command.split('=')[:-1])
2120  if stripped_setting.lower() in settings_lower:
2121  # if setting set to 'None' it will be removed from run_card
2122  if settings_lower[stripped_setting.lower()] is None:
2123  line=''
2124  mglog.info('Removing '+stripped_setting+'.')
2125  used_settings += [ stripped_setting.lower() ]
2126  else:
2127  line = oldValue.replace(oldValue.strip(), str(settings_lower[stripped_setting.lower()]))+'='+setting
2128  if comment != '':
2129  line += ' !' + comment
2130  mglog.info('Setting '+stripped_setting+' = '+str(settings_lower[stripped_setting.lower()]))
2131  used_settings += [ stripped_setting.lower() ]
2132  newCard.write(line.strip()+'\n')
2133 
2134  # Check whether mcatnlo_delta is applied to setup pythia8 path
2135  if 'mcatnlo_delta' in settings_lower:
2136  if settings_lower['mcatnlo_delta'] == 'True':
2137  modify_config_card(process_dir=process_dir,settings={'pythia8_path':os.getenv("PY8PATH")})
2138 
2139  # Clean up unused options
2140  for asetting in settings_lower:
2141  if asetting in used_settings:
2142  continue
2143  if settings_lower[asetting] is None:
2144  continue
2145  mglog.warning('Option '+asetting+' was not in the default run_card. Adding by hand a setting to '+str(settings_lower[asetting]) )
2146  newCard.write( ' '+str(settings_lower[asetting])+' = '+str(asetting)+'\n')
2147  # close files
2148  oldCard.close()
2149  newCard.close()
2150  mglog.info('Finished modification of run card.')
2151  if run_card_backup is None:
2152  os.unlink(run_card_old)
2153 
2154 

◆ new_process()

def python.MadGraphUtils.new_process (   process = 'generate p p > t t~\noutput -f',
  plugin = None,
  keepJpegs = False,
  usePMGSettings = False 
)
Generate a new process in madgraph.
Pass a process string.
Optionally request JPEGs to be kept and request for PMG settings to be used in the param card
Return the name of the process directory.

Definition at line 222 of file MadGraphUtils.py.

222 def new_process(process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False):
223  """ Generate a new process in madgraph.
224  Pass a process string.
225  Optionally request JPEGs to be kept and request for PMG settings to be used in the param card
226  Return the name of the process directory.
227  """
228  if config_only_check():
229  # Give some directories to work on
230  try:
231  os.makedirs('dummy_proc/Cards')
232  except os.error:
233  pass
234  return 'dummy_proc'
235 
236  # Don't run if generating events from gridpack
238  return MADGRAPH_GRIDPACK_LOCATION
239 
240  # Actually just sent the process card contents - let's make a card
241  card_loc='proc_card_mg5.dat'
242  mglog.info('Writing process card to '+card_loc)
243  a_card = open( card_loc , 'w' )
244  for l in process.split('\n'):
245  if 'output' not in l:
246  a_card.write(l+'\n')
247  elif '-nojpeg' in l or keepJpegs:
248  a_card.write(l+'\n')
249  elif '#' in l:
250  a_card.write(l.split('#')[0]+' -nojpeg #'+l.split('#')[1]+'\n')
251  else:
252  a_card.write(l+' -nojpeg\n')
253  a_card.close()
254 
255  madpath=os.environ['MADPATH']
256  # Just in case
258 
259  # Check if we have a special output directory
260  process_dir = ''
261  for l in process.split('\n'):
262  # Look for an output line
263  if 'output' not in l.split('#')[0].split():
264  continue
265  # Check how many things before the options start
266  tmplist = l.split('#')[0].split(' -')[0]
267  # if two things, second is the directory
268  if len(tmplist.split())==2:
269  process_dir = tmplist.split()[1]
270  # if three things, third is the directory (second is the format)
271  elif len(tmplist.split())==3:
272  process_dir = tmplist.split()[2]
273  # See if we got a directory
274  if ''!=process_dir:
275  mglog.info('Saw that you asked for a special output directory: '+str(process_dir))
276  break
277 
278  mglog.info('Started process generation at '+str(time.asctime()))
279 
280  plugin_cmd = '--mode='+plugin if plugin is not None else ''
281 
282  # Note special handling here to explicitly print the process
283  global MADGRAPH_COMMAND_STACK
284  MADGRAPH_COMMAND_STACK += ['# All jobs should start in a clean directory']
285  MADGRAPH_COMMAND_STACK += ['mkdir standalone_test; cd standalone_test']
286  MADGRAPH_COMMAND_STACK += [' '.join([python,madpath+'/bin/mg5_aMC '+plugin_cmd+' << EOF\n'+process+'\nEOF\n'])]
287  global MADGRAPH_CATCH_ERRORS
288  generate = subprocess.Popen([python,madpath+'/bin/mg5_aMC',plugin_cmd,card_loc],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
289  (out,err) = generate.communicate()
290  error_check(err,generate.returncode)
291 
292  mglog.info('Finished process generation at '+str(time.asctime()))
293 
294  # at this point process_dir is for sure defined - it's equal to '' in the worst case
295  if process_dir == '': # no user-defined value, need to find the directory created by MadGraph5
296  for adir in sorted(glob.glob( os.getcwd()+'/*PROC*' ),reverse=True):
297  if os.access('%s/SubProcesses/subproc.mg'%adir,os.R_OK):
298  if process_dir=='':
299  process_dir=adir
300  else:
301  mglog.warning('Additional possible process directory, '+adir+' found. Had '+process_dir)
302  mglog.warning('Likely this is because you did not run from a clean directory, and this may cause errors later.')
303  else: # user-defined directory
304  if not os.access('%s/SubProcesses/subproc.mg'%process_dir,os.R_OK):
305  raise RuntimeError('No diagrams for this process in user-define dir='+str(process_dir))
306  if process_dir=='':
307  raise RuntimeError('No diagrams for this process from list: '+str(sorted(glob.glob(os.getcwd()+'/*PROC*'),reverse=True)))
308 
309  # Special catch related to path setting and using afs
310  needed_options = ['ninja','collier','fastjet','lhapdf','syscalc_path']
311  in_config = open(os.environ['MADPATH']+'/input/mg5_configuration.txt','r')
312  option_paths = {}
313  for l in in_config.readlines():
314  for o in needed_options:
315  if o+' =' in l.split('#')[0] and 'MCGenerators' in l.split('#')[0]:
316  old_path = l.split('#')[0].split('=')[1].strip().split('MCGenerators')[1]
317  old_path = old_path[ old_path.find('/') : ]
318  if o =='lhapdf' and 'LHAPATH' in os.environ:
319  # Patch for LHAPDF version
320  version = os.environ['LHAPATH'].split('lhapdf/')[1].split('/')[0]
321  old_version = old_path.split('lhapdf/')[1].split('/')[0]
322  old_path = old_path.replace(old_version,version)
323  if o=='ninja':
324  # Patch for stupid naming problem
325  old_path.replace('gosam_contrib','gosam-contrib')
326  option_paths[o] = os.environ['MADPATH'].split('madgraph5amc')[0]+old_path
327  # Check to see if the option has been commented out
328  if o+' =' in l and o+' =' not in l.split('#')[0]:
329  mglog.info('Option '+o+' appears commented out in the config file')
330 
331  in_config.close()
332  for o in needed_options:
333  if o not in option_paths:
334  mglog.warning('Path for option '+o+' not found in original config')
335 
336  mglog.info('Modifying config paths to avoid use of afs:')
337  mglog.info(option_paths)
338 
339  # Set the paths appropriately
340  modify_config_card(process_dir=process_dir,settings=option_paths,set_commented=False)
341  # Done modifying paths
342 
343  # If requested, apply PMG default settings
344  if usePMGSettings:
345  do_PMG_updates(process_dir)
346 
347  # After 2.9.3, enforce the standard default sde_strategy, so that this won't randomly change on the user
348  if is_version_or_newer([2,9,3]) and not is_NLO_run(process_dir=process_dir):
349  mglog.info('Setting default sde_strategy to old default (1)')
350  my_settings = {'sde_strategy':1}
351  modify_run_card(process_dir=process_dir,settings=my_settings,skipBaseFragment=True)
352 
353  # Make sure we store the resultant directory
354  MADGRAPH_COMMAND_STACK += ['export MGaMC_PROCESS_DIR='+os.path.basename(process_dir)]
355 
356  return process_dir
357 
358 

◆ print_cards()

def 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 2217 of file MadGraphUtils.py.

2217 def print_cards(proc_card='proc_card_mg5.dat',run_card=None,param_card=None,madspin_card=None,reweight_card=None,warn_on_missing=True):
2218  if os.access(proc_card,os.R_OK):
2219  mglog.info("proc_card:")
2220  procCard = subprocess.Popen(['cat',proc_card])
2221  procCard.wait()
2222  elif warn_on_missing:
2223  mglog.warning('No proc_card: '+proc_card+' found')
2224 
2225  if run_card is not None and os.access(run_card,os.R_OK):
2226  mglog.info("run_card:")
2227  runCard = subprocess.Popen(['cat',run_card])
2228  runCard.wait()
2229  elif run_card is not None and warn_on_missing:
2230  mglog.warning('No run_card: '+run_card+' found')
2231  else:
2232  mglog.info('Default run card in use')
2233 
2234  if param_card is not None and os.access(param_card,os.R_OK):
2235  mglog.info("param_card:")
2236  paramCard = subprocess.Popen(['cat',param_card])
2237  paramCard.wait()
2238  elif param_card is not None and warn_on_missing:
2239  mglog.warning('No param_card: '+param_card+' found')
2240  else:
2241  mglog.info('Default param card in use')
2242 
2243  if madspin_card is not None and os.access(madspin_card,os.R_OK):
2244  mglog.info("madspin_card:")
2245  madspinCard = subprocess.Popen(['cat',madspin_card])
2246  madspinCard.wait()
2247  elif madspin_card is not None and warn_on_missing:
2248  mglog.warning('No madspin_card: '+madspin_card+' found')
2249  else:
2250  mglog.info('No madspin card in use')
2251 
2252  if reweight_card is not None and os.access(reweight_card,os.R_OK):
2253  mglog.info("reweight_card:")
2254  madspinCard = subprocess.Popen(['cat',reweight_card])
2255  madspinCard.wait()
2256  elif reweight_card is not None and warn_on_missing:
2257  mglog.warning('No reweight_card: '+reweight_card+' found')
2258  else:
2259  mglog.info('No reweight card in use')
2260 
2261 

◆ print_cards_from_dir()

def python.MadGraphUtils.print_cards_from_dir (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2211 of file MadGraphUtils.py.

2211 def print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2212  card_dir=process_dir+'/Cards/'
2213  print_cards(proc_card=card_dir+'proc_card_mg5.dat',run_card=card_dir+'run_card.dat',param_card=card_dir+'param_card.dat',\
2214  madspin_card=card_dir+'madspin_card.dat',reweight_card=card_dir+'reweight_card.dat',warn_on_missing=False)
2215 
2216 

◆ run_card_consistency_check()

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

Definition at line 2313 of file MadGraphUtils.py.

2313 def run_card_consistency_check(isNLO=False,process_dir='.'):
2314  cardpath=process_dir+'/Cards/run_card.dat'
2315  mydict=getDictFromCard(cardpath)
2316 
2317  # We should always use event_norm = average [AGENE-1725] otherwise Pythia cross sections are wrong
2318  # Modification: average or bias is ok; sum is incorrect. Change the test to set sum to average
2319  if checkSetting('event_norm','sum',mydict):
2320  modify_run_card(process_dir=process_dir,settings={'event_norm':'average'},skipBaseFragment=True)
2321  mglog.warning("setting event_norm to average, there is basically no use case where event_norm=sum is a good idea")
2322 
2323  if not isNLO:
2324  #Check CKKW-L setting
2325  if 'ktdurham' in mydict and float(mydict['ktdurham']) > 0 and int(mydict['ickkw']) != 0:
2326  log='Bad combination of settings for CKKW-L merging! ktdurham=%s and ickkw=%s.'%(mydict['ktdurham'],mydict['ickkw'])
2327  mglog.error(log)
2328  raise RuntimeError(log)
2329 
2330  # Check if user is trying to use deprecated syscalc arguments with the other systematics script
2331  if 'systematics_program' not in mydict or mydict['systematics_program']=='systematics':
2332  syscalc_settings=['sys_pdf', 'sys_scalefact', 'sys_alpsfact', 'sys_matchscale']
2333  found_syscalc_setting=False
2334  for s in syscalc_settings:
2335  if s in mydict:
2336  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)')
2337  found_syscalc_setting=True
2338  if found_syscalc_setting:
2339  syst_arguments=MadGraphControl.MadGraphSystematicsUtils.convertSysCalcArguments(mydict)
2340  mglog.info('Converted syscalc arguments to systematics arguments: '+syst_arguments)
2341  syst_settings_update={'systematics_arguments':syst_arguments}
2342  for s in syscalc_settings:
2343  syst_settings_update[s]=None
2344  modify_run_card(process_dir=process_dir,settings=syst_settings_update,skipBaseFragment=True)
2345 
2346 
2347  # usually the pdf and systematics should be set during modify_run_card
2348  # but check again in case the user did not call the function or provides a different card here
2349  mglog.info('Checking PDF and systematics settings')
2350  if not MadGraphControl.MadGraphSystematicsUtils.base_fragment_setup_check(MADGRAPH_PDFSETTING,mydict,isNLO):
2351  # still need to set pdf and systematics
2352  syst_settings=MadGraphControl.MadGraphSystematicsUtils.get_pdf_and_systematic_settings(MADGRAPH_PDFSETTING,isNLO)
2353  modify_run_card(process_dir=process_dir,settings=syst_settings,skipBaseFragment=True)
2354 
2355  mydict_new=getDictFromCard(cardpath)
2356  if 'systematics_arguments' in mydict_new:
2357  systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict_new['systematics_arguments'])
2358  if 'weight_info' not in systematics_arguments:
2359  mglog.info('Enforcing systematic weight name convention')
2360  dyn = None
2361  if '--dyn' in systematics_arguments or ' dyn' in systematics_arguments:
2362  if '--dyn' in systematics_arguments:
2363  dyn = systematics_arguments.split('--dyn')[1]
2364  if ' dyn' in systematics_arguments:
2365  dyn = systematics_arguments.split(' dyn')[1]
2366  dyn = dyn.replace('\'',' ').replace('=',' ').split()[0]
2367  if dyn is not None and len(dyn.split(','))>1:
2368  systematics_arguments['weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO_ALTDYNSCALES
2369  else:
2370  systematics_arguments['weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO
2371  modify_run_card(process_dir=process_dir,settings={'systematics_arguments':MadGraphControl.MadGraphSystematicsUtils.write_systematics_arguments(systematics_arguments)},skipBaseFragment=True)
2372 
2373  if not isNLO:
2374  if 'python_seed' not in mydict:
2375  mglog.warning('No python seed set in run_card -- adding one with same value as iseed')
2376  modify_run_card(process_dir=process_dir,settings={'python_seed':mydict['iseed']},skipBaseFragment=True)
2377 
2378  # consistency check of 4/5 flavour shceme settings
2379  FS_updates={}
2380  with open(process_dir+'/Cards/proc_card_mg5.dat', 'r') as file:
2381  content = file.readlines()
2382  for line in content:
2383  if line.startswith("define p") or line.startswith("define j"):
2384  if "b" in line and "b~" in line:
2385  FS_updates['asrwgtflavor'] = 5
2386  else:
2387  FS_updates['asrwgtflavor'] = 4
2388  if len(FS_updates)==0:
2389  mglog.warning(f'Could not identify 4- or 5-flavor scheme from process card {process_dir}/Cards/proc_card_mg5.dat')
2390 
2391  if 'asrwgtflavor' in mydict or 'maxjetflavor' in mydict or 'pdgs_for_merging_cut' in mydict:
2392  if FS_updates['asrwgtflavor'] == 5:
2393  # Process card says we are in the five-flavor scheme
2394  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']):
2395  # Inconsistent setting detected; warn the users and correct the settings
2396  mglog.warning('b and b~ included in p and j for 5-flavor scheme but run card settings are inconsistent; adjusting run card')
2397  run_card_updates = {'asrwgtflavor': 5, 'maxjetflavor': 5, 'pdgs_for_merging_cut': '1, 2, 3, 4, 5, 21'}
2398  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2399  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '0.000000e+00'}})
2400  else:
2401  mglog.debug('Consistent 5-flavor scheme setup detected.')
2402  if FS_updates['asrwgtflavor'] == 4:
2403  # Process card says we are in the four-flavor scheme
2404  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']):
2405  # Inconsistent setting detected; warn the users and correct the settings
2406  mglog.warning('b and b~ not included in p and j (4-flavor scheme) but run card settings are inconsistent; adjusting run card')
2407  run_card_updates = {'asrwgtflavor': 4, 'maxjetflavor': 4, 'pdgs_for_merging_cut': '1, 2, 3, 4, 21'}
2408  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2409  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '4.700000e+00'}})
2410  else:
2411  mglog.debug('Consistent 4-flavor scheme setup detected.')
2412  else:
2413  # Flavor scheme setup is missing, adding by hand
2414  if FS_updates['asrwgtflavor'] == 4:
2415  # Warn the users and add the settings according to process card
2416  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.')
2417  run_card_updates = {'asrwgtflavor': 4, 'maxjetflavor': 4, 'pdgs_for_merging_cut': '1, 2, 3, 4, 21'}
2418  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2419  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '4.700000e+00'}})
2420  elif FS_updates['asrwgtflavor'] == 5:
2421  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.')
2422  run_card_updates = {'asrwgtflavor': 5, 'maxjetflavor': 5, 'pdgs_for_merging_cut': '1, 2, 3, 4, 5, 21'}
2423  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2424  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '0.000000e+00'}})
2425 
2426  mglog.info('Finished checking run card - All OK!')
2427 

◆ setNCores()

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

Definition at line 982 of file MadGraphUtils.py.

982 def setNCores(process_dir, Ncores=None):
983  my_Ncores = Ncores
984  my_runMode = 2 if 'ATHENA_CORE_NUMBER' in os.environ else 0
985  if Ncores is None and 'ATHENA_CORE_NUMBER' in os.environ and int(os.environ['ATHENA_CORE_NUMBER'])>0:
986  my_Ncores = int(os.environ['ATHENA_CORE_NUMBER'])
987  my_runMode = 2
988  if my_Ncores is None:
989  mglog.info('Setting up for serial run')
990  my_Ncores = 1
991 
992  modify_config_card(process_dir=process_dir,settings={'nb_core':my_Ncores,'run_mode':my_runMode,'automatic_html_opening':'False'})
993 
994 
995 
996 
997 
998 
999 

◆ setup_bias_module()

def python.MadGraphUtils.setup_bias_module (   bias_module,
  process_dir 
)

Definition at line 1508 of file MadGraphUtils.py.

1508 def setup_bias_module(bias_module,process_dir):
1509  run_card = process_dir+'/Cards/run_card.dat'
1510  if isinstance(bias_module,tuple):
1511  mglog.info('Using bias module '+bias_module[0])
1512  the_run_card = open(run_card,'r')
1513  for line in the_run_card:
1514  if 'bias_module' in line and not bias_module[0] in line:
1515  raise RuntimeError('You need to add the bias module '+bias_module[0]+' to the run card to actually run it')
1516  the_run_card.close()
1517  if len(bias_module)!=3:
1518  raise RuntimeError('Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1519  bias_module_newpath=process_dir+'/Source/BIAS/'+bias_module[0]
1520  os.makedirs(bias_module_newpath)
1521  bias_module_file=open(bias_module_newpath+'/'+bias_module[0]+'.f','w')
1522  bias_module_file.write(bias_module[1])
1523  bias_module_file.close()
1524  bias_module_make_file=open(bias_module_newpath+'/Makefile','w')
1525  bias_module_make_file.write(bias_module[2])
1526  bias_module_make_file.close()
1527  else:
1528  mglog.info('Using bias module '+bias_module)
1529  bias_module_name=bias_module.split('/')[-1].replace('.gz','')
1530  bias_module_name=bias_module_name.replace('.tar','')
1531  the_run_card = open(run_card,'r')
1532  for line in the_run_card:
1533  if 'bias_module' in line and bias_module_name not in line:
1534  raise RuntimeError('You need to add the bias module '+bias_module_name+' to the run card to actually run it')
1535  the_run_card.close()
1536 
1537  if os.path.exists(bias_module+'.tar.gz'):
1538  bias_module_path=bias_module+'.tar.gz'
1539  elif os.path.exists(bias_module+'.gz'):
1540  bias_module_path=bias_module+'.gz'
1541  elif os.path.exists(bias_module):
1542  bias_module_path=bias_module
1543  else:
1544  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')
1545  return 1
1546  bias_module_newpath=process_dir+'/Source/BIAS/'+bias_module_path.split('/')[-1]
1547  mglog.info('Copying bias module into place: '+bias_module_newpath)
1548  shutil.copy(bias_module_path,bias_module_newpath)
1549  mglog.info('Unpacking bias module')
1550  if bias_module_newpath.endswith('.tar.gz'):
1551  untar = stack_subprocess(['tar','xvzf',bias_module_newpath,'--directory='+process_dir+'/Source/BIAS/'])
1552  untar.wait()
1553  elif bias_module_path.endswith('.gz'):
1554  gunzip = stack_subprocess(['gunzip',bias_module_newpath])
1555  gunzip.wait()
1556 
1557 

◆ setup_path_protection()

def python.MadGraphUtils.setup_path_protection ( )

Definition at line 53 of file MadGraphUtils.py.

54  # Addition for models directory
55  global MADGRAPH_COMMAND_STACK
56  if 'PYTHONPATH' in os.environ:
57  if not any( [('Generators/madgraph/models' in x and 'shutil_patch' not in x) for x in os.environ['PYTHONPATH'].split(':') ]):
58  os.environ['PYTHONPATH'] += ':/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest'
59  MADGRAPH_COMMAND_STACK += ['export PYTHONPATH=${PYTHONPATH}:/cvmfs/atlas.cern.ch/repo/sw/Generators/madgraph/models/latest']
60  # Make sure that gfortran doesn't write to somewhere it shouldn't
61  if 'GFORTRAN_TMPDIR' in os.environ:
62  return
63  if 'TMPDIR' in os.environ:
64  os.environ['GFORTRAN_TMPDIR']=os.environ['TMPDIR']
65  MADGRAPH_COMMAND_STACK += ['export GFORTRAN_TMPDIR=${TMPDIR}']
66  return
67  if 'TMP' in os.environ:
68  os.environ['GFORTRAN_TMPDIR']=os.environ['TMP']
69  MADGRAPH_COMMAND_STACK += ['export GFORTRAN_TMPDIR=${TMP}']
70  return
71 
72 

◆ setupFastjet()

def python.MadGraphUtils.setupFastjet (   process_dir = None)

Definition at line 803 of file MadGraphUtils.py.

803 def setupFastjet(process_dir=None):
804 
805  isNLO=is_NLO_run(process_dir=process_dir)
806 
807  mglog.info('Path to fastjet install dir: '+os.environ['FASTJETPATH'])
808  fastjetconfig = os.environ['FASTJETPATH']+'/bin/fastjet-config'
809 
810  mglog.info('fastjet-config --version: '+str(subprocess.Popen([fastjetconfig, '--version'],stdout = subprocess.PIPE).stdout.read().strip()))
811  mglog.info('fastjet-config --prefix: '+str(subprocess.Popen([fastjetconfig, '--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
812 
813  if not isNLO:
814  config_card=process_dir+'/Cards/me5_configuration.txt'
815  else:
816  config_card=process_dir+'/Cards/amcatnlo_configuration.txt'
817 
818  oldcard = open(config_card,'r')
819  newcard = open(config_card+'.tmp','w')
820 
821  for line in oldcard:
822  if 'fastjet = ' in line:
823  newcard.write('fastjet = '+fastjetconfig+'\n')
824  mglog.info('Setting fastjet = '+fastjetconfig+' in '+config_card)
825  else:
826  newcard.write(line)
827  oldcard.close()
828  newcard.close()
829  shutil.move(config_card+'.tmp',config_card)
830 
831  return
832 
833 
834 

◆ setupLHAPDF()

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

Definition at line 835 of file MadGraphUtils.py.

835 def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
836 
837  isNLO=is_NLO_run(process_dir=process_dir)
838 
839  origLHAPATH=os.environ['LHAPATH']
840  origLHAPDF_DATA_PATH=os.environ['LHAPDF_DATA_PATH']
841 
842  LHAPATH,LHADATAPATH=get_LHAPDF_PATHS()
843 
844  pdfname=''
845  pdfid=-999
846 
847 
848  run_card=process_dir+'/Cards/run_card.dat'
849  mydict=getDictFromCard(run_card)
850 
851  if mydict["pdlabel"].replace("'","") == 'lhapdf':
852  #Make local LHAPDF dir
853  mglog.info('creating local LHAPDF dir: MGC_LHAPDF/')
854  if os.path.islink('MGC_LHAPDF/'):
855  os.unlink('MGC_LHAPDF/')
856  elif os.path.isdir('MGC_LHAPDF/'):
857  shutil.rmtree('MGC_LHAPDF/')
858 
859  newMGCLHA='MGC_LHAPDF/'
860 
861  mkdir = subprocess.Popen(['mkdir','-p',newMGCLHA])
862  mkdir.wait()
863 
864  pdfs_used=[ int(x) for x in mydict['lhaid'].replace(' ',',').split(',') ]
865  # included systematics pdfs here
866  if 'sys_pdf' in mydict:
867  sys_pdf=mydict['sys_pdf'].replace('&&',' ').split()
868  for s in sys_pdf:
869  if s.isdigit():
870  idx=int(s)
871  if idx>1000: # the sys_pdf syntax is such that small numbers are used to specify the subpdf index
872  pdfs_used.append(idx)
873  else:
874  pdfs_used.append(s)
875  if 'systematics_arguments' in mydict:
876  systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict['systematics_arguments'])
877  if 'pdf' in systematics_arguments:
878  sys_pdf=systematics_arguments['pdf'].replace(',',' ').replace('@',' ').split()
879  for s in sys_pdf:
880  if s.isdigit():
881  idx=int(s)
882  if idx>1000: # the sys_pdf syntax is such that small numbers are used to specify the subpdf index
883  pdfs_used.append(idx)
884  else:
885  pdfs_used.append(s)
886  for pdf in pdfs_used:
887  if isinstance(pdf,str) and (pdf.lower()=='errorset' or pdf.lower()=='central'):
888  continue
889  # new function to get both lhapdf id and name
890  pdfid,pdfname=get_lhapdf_id_and_name(pdf)
891  mglog.info("Found LHAPDF ID="+str(pdfid)+", name="+pdfname)
892 
893  if not os.path.exists(newMGCLHA+pdfname) and not os.path.lexists(newMGCLHA+pdfname):
894  if not os.path.exists(LHADATAPATH+'/'+pdfname):
895  mglog.warning('PDF not installed at '+LHADATAPATH+'/'+pdfname)
896  if allow_links:
897  mglog.info('linking '+LHADATAPATH+'/'+pdfname+' --> '+newMGCLHA+pdfname)
898  os.symlink(LHADATAPATH+'/'+pdfname,newMGCLHA+pdfname)
899  else:
900  mglog.info('copying '+LHADATAPATH+'/'+pdfname+' --> '+newMGCLHA+pdfname)
901  shutil.copytree(LHADATAPATH+'/'+pdfname,newMGCLHA+pdfname)
902 
903  if allow_links:
904  mglog.info('linking '+LHADATAPATH+'/pdfsets.index --> '+newMGCLHA+'pdfsets.index')
905  os.symlink(LHADATAPATH+'/pdfsets.index',newMGCLHA+'pdfsets.index')
906 
907  atlasLHADATAPATH=LHADATAPATH.replace('sft.cern.ch/lcg/external/lhapdfsets/current','atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
908  mglog.info('linking '+atlasLHADATAPATH+'/lhapdf.conf --> '+newMGCLHA+'lhapdf.conf')
909  os.symlink(atlasLHADATAPATH+'/lhapdf.conf',newMGCLHA+'lhapdf.conf')
910  else:
911  mglog.info('copying '+LHADATAPATH+'/pdfsets.index --> '+newMGCLHA+'pdfsets.index')
912  shutil.copy2(LHADATAPATH+'/pdfsets.index',newMGCLHA+'pdfsets.index')
913 
914  atlasLHADATAPATH=LHADATAPATH.replace('sft.cern.ch/lcg/external/lhapdfsets/current','atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
915  mglog.info('copying '+atlasLHADATAPATH+'/lhapdf.conf -->'+newMGCLHA+'lhapdf.conf')
916  shutil.copy2(atlasLHADATAPATH+'/lhapdf.conf',newMGCLHA+'lhapdf.conf')
917 
918 
919  LHADATAPATH=os.getcwd()+'/MGC_LHAPDF'
920 
921  else:
922  mglog.info('Not using LHAPDF')
923  return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
924 
925 
926  if isNLO:
927  os.environ['LHAPDF_DATA_PATH']=LHADATAPATH
928 
929  mglog.info('Path to LHAPDF install dir: '+LHAPATH)
930  mglog.info('Path to LHAPDF data dir: '+LHADATAPATH)
931  if not os.path.isdir(LHADATAPATH):
932  raise RuntimeError('LHAPDF data dir not accesible: '+LHADATAPATH)
933  if not os.path.isdir(LHAPATH):
934  raise RuntimeError('LHAPDF path dir not accesible: '+LHAPATH)
935 
936  # Dealing with LHAPDF
937  if extlhapath:
938  lhapdfconfig=extlhapath
939  if not os.access(lhapdfconfig,os.X_OK):
940  raise RuntimeError('Failed to find valid external lhapdf-config at '+lhapdfconfig)
941  LHADATAPATH=subprocess.Popen([lhapdfconfig, '--datadir'],stdout = subprocess.PIPE).stdout.read().strip()
942  mglog.info('Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
943  os.environ['LHAPDF_DATA_PATH']=LHADATAPATH
944  else:
945  getlhaconfig = subprocess.Popen(['get_files','-data','lhapdf-config'])
946  getlhaconfig.wait()
947  #Get custom lhapdf-config
948  if not os.access(os.getcwd()+'/lhapdf-config',os.X_OK):
949  mglog.error('Failed to get lhapdf-config from MadGraphControl')
950  return 1
951  lhapdfconfig = os.getcwd()+'/lhapdf-config'
952 
953  mglog.info('lhapdf-config --version: '+str(subprocess.Popen([lhapdfconfig, '--version'],stdout = subprocess.PIPE).stdout.read().strip()))
954  mglog.info('lhapdf-config --prefix: '+str(subprocess.Popen([lhapdfconfig, '--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
955  mglog.info('lhapdf-config --libdir: '+str(subprocess.Popen([lhapdfconfig, '--libdir'],stdout = subprocess.PIPE).stdout.read().strip()))
956  mglog.info('lhapdf-config --datadir: '+str(subprocess.Popen([lhapdfconfig, '--datadir'],stdout = subprocess.PIPE).stdout.read().strip()))
957  mglog.info('lhapdf-config --pdfsets-path: '+str(subprocess.Popen([lhapdfconfig, '--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().strip()))
958 
959  modify_config_card(process_dir=process_dir,settings={'lhapdf':lhapdfconfig,'lhapdf_py3':lhapdfconfig})
960 
961  mglog.info('Creating links for LHAPDF')
962  if os.path.islink(process_dir+'/lib/PDFsets'):
963  os.unlink(process_dir+'/lib/PDFsets')
964  elif os.path.isdir(process_dir+'/lib/PDFsets'):
965  shutil.rmtree(process_dir+'/lib/PDFsets')
966  if allow_links:
967  os.symlink(LHADATAPATH,process_dir+'/lib/PDFsets')
968  else:
969  shutil.copytree(LHADATAPATH,process_dir+'/lib/PDFsets')
970  mglog.info('Available PDFs are:')
971  mglog.info( sorted( [ x for x in os.listdir(process_dir+'/lib/PDFsets') if ".tar.gz" not in x ] ) )
972 
973  global MADGRAPH_COMMAND_STACK
974  MADGRAPH_COMMAND_STACK += [ '# Copy the LHAPDF files locally' ]
975  MADGRAPH_COMMAND_STACK += [ 'cp -r '+os.getcwd()+'/MGC_LHAPDF .' ]
976  MADGRAPH_COMMAND_STACK += [ 'cp -r '+process_dir+'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
977 
978  return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
979 
980 
981 # Function to set the number of cores and the running mode in the run card

◆ stack_subprocess()

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

Definition at line 47 of file MadGraphUtils.py.

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

◆ SUSY_Generation()

def python.MadGraphUtils.SUSY_Generation (   runArgs = None,
  process = None,
  plugin = None,
  syst_mod = None,
  keepOutput = False,
  param_card = None,
  writeGridpack = False,
  madspin_card = None,
  run_settings = {},
  params = {},
  fixEventWeightsForBridgeMode = False,
  add_lifetimes_lhe = False,
  usePMGSettings = True 
)
Keyword Arguments:
    usePMGSettings (bool): See :py:func:`new_process`. Will set SM parameters to the appropriate values. Default: True.

Definition at line 1725 of file MadGraphUtils.py.

1725 def SUSY_Generation(runArgs = None, process=None, plugin=None,\
1726  syst_mod=None, keepOutput=False, param_card=None, writeGridpack=False,\
1727  madspin_card=None, run_settings={}, params={}, fixEventWeightsForBridgeMode=False, add_lifetimes_lhe=False, usePMGSettings=True):
1728 
1729  """
1730  Keyword Arguments:
1731  usePMGSettings (bool): See :py:func:`new_process`. Will set SM parameters to the appropriate values. Default: True.
1732  """
1733  ktdurham = run_settings['ktdurham'] if 'ktdurham' in run_settings else None
1734  ktdurham , alpsfact , scalefact = get_SUSY_variations( process, params['MASS'] , syst_mod , ktdurham=ktdurham )
1735 
1736  process_dir = MADGRAPH_GRIDPACK_LOCATION
1737  if not is_gen_from_gridpack():
1738  full_proc = SUSY_process(process)
1739  process_dir = new_process(full_proc, plugin=plugin, usePMGSettings=usePMGSettings)
1740  mglog.info('Using process directory '+str(process_dir))
1741 
1742  # Grab the param card and move the new masses into place
1743  modify_param_card(param_card_input=param_card,process_dir=process_dir,params=params)
1744 
1745  # Set up the extras dictionary
1746  settings = {'ktdurham':ktdurham,'scalefact':scalefact,'alpsfact':alpsfact}
1747  settings.update(run_settings) # This allows explicit settings in the input to override these settings
1748 
1749  # Set up the run card
1750  modify_run_card(process_dir=process_dir,runArgs=runArgs,settings=settings)
1751 
1752  # Set up madspin if needed
1753  if madspin_card is not None:
1754  if not os.access(madspin_card,os.R_OK):
1755  raise RuntimeError('Could not locate madspin card at '+str(madspin_card))
1756  shutil.copy(madspin_card,process_dir+'/Cards/madspin_card.dat')
1757 
1758  # Generate events!
1759  if is_gen_from_gridpack():
1760  generate_from_gridpack(runArgs=runArgs)
1761  else:
1762  # Grab the run card and move it into place
1763  generate(runArgs=runArgs,process_dir=process_dir,grid_pack=writeGridpack)
1764 
1765  # Add lifetimes to LHE before arranging output if requested
1766  if add_lifetimes_lhe :
1767  mglog.info('Requested addition of lifetimes to LHE files: doing so now.')
1768  if is_gen_from_gridpack():
1769  add_lifetimes()
1770  else:
1771  add_lifetimes(process_dir=process_dir)
1772 
1773  # Move output files into the appropriate place, with the appropriate name
1774  arrange_output(process_dir=process_dir,saveProcDir=keepOutput,runArgs=runArgs,fixEventWeightsForBridgeMode=fixEventWeightsForBridgeMode)
1775 
1776  mglog.info('All done generating events!!')
1777  return settings['ktdurham']
1778 
1779 

◆ SUSY_process()

def python.MadGraphUtils.SUSY_process (   process = '')

Definition at line 1695 of file MadGraphUtils.py.

1695 def SUSY_process(process=''):
1696  # Generate the new process!
1697  if 'import model' in process:
1698  mglog.info('Assuming that you have specified the model in your process string already')
1699  full_proc = ''
1700  for l in process.split('\n'):
1701  if 'import model' in l:
1702  full_proc += l+'\n'
1703  break
1704  # Only magically add helpful definitions if we are in the right model
1705  if 'MSSM_SLHA2' in full_proc:
1706  full_proc+=helpful_SUSY_definitions()
1707  for l in process.split('\n'):
1708  if 'import model' not in l:
1709  full_proc += l+'\n'
1710  full_proc+="""
1711 # Output processes to MadEvent directory
1712 output -f
1713 """
1714  else:
1715  full_proc = "import model MSSM_SLHA2\n"+helpful_SUSY_definitions()+"""
1716 # Specify process(es) to run
1717 
1718 """+process+"""
1719 # Output processes to MadEvent directory
1720 output -f
1721 """
1722  return full_proc
1723 
1724 

◆ update_lhe_file()

def 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 1780 of file MadGraphUtils.py.

1780 def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1781  """Build a new LHE file from an old one and an updated param card.
1782  The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1783  may have their masses changed.
1784  If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1785  By default, the old LHE file is removed.
1786  If None is provided as a new LHE file name, the new file will replace the old one."""
1787  # If we want to just use a temp file, then put in a little temp holder
1788  lhe_file_new_tmp = lhe_file_new if lhe_file_new is not None else lhe_file_old+'.tmp'
1789  # Make sure the LHE file is there
1790  if not os.access(lhe_file_old,os.R_OK):
1791  raise RuntimeError('Could not access old LHE file at '+str(lhe_file_old)+'. Please check the file location.')
1792  # Grab the old param card
1793  if param_card_old is not None:
1794  paramcard = subprocess.Popen(['get_files','-data',param_card_old])
1795  paramcard.wait()
1796  if not os.access(param_card_old,os.R_OK):
1797  raise RuntimeError('Could not get param card '+param_card_old)
1798  # Don't overwrite old param cards
1799  if os.access(lhe_file_new_tmp,os.R_OK):
1800  raise RuntimeError('Old file at'+str(lhe_file_new_tmp)+' in the current directory. Dont want to clobber it. Please move it first.')
1801 
1802  newlhe = open(lhe_file_new_tmp,'w')
1803  blockName = None
1804  decayEdit = False
1805  eventRead = False
1806  particles_in_events = []
1807  # Decay block ends with </slha>
1808 
1809  with open(lhe_file_old,'r') as fileobject:
1810  for line in fileobject:
1811  if decayEdit and '</slha>' not in line:
1812  continue
1813  if decayEdit and '</slha>' in line:
1814  decayEdit = False
1815  if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
1816  and len(line.strip().split()) > 1:
1817  pos = 0 if line.strip().startswith('DECAY') else 1
1818  blockName = line.strip().upper().split()[pos]
1819 
1820  akey = None
1821  if blockName != 'DECAY' and len(line.strip().split()) > 0:
1822  akey = line.strip().split()[0]
1823  elif blockName == 'DECAY' and len(line.strip().split()) > 1:
1824  akey = line.strip().split()[1]
1825 
1826  # Replace the masses with those in the dictionary
1827  if akey is not None and blockName == 'MASS' and akey in masses:
1828  newlhe.write(' '+akey+' '+str(masses[akey])+' # \n')
1829  mglog.info(' '+akey+' '+str(masses[akey])+' #')
1830  decayEdit = False
1831  continue
1832 
1833  # Replace the entire decay section of the LHE file with the one from the param card
1834  if blockName == 'DECAY' and param_card_old is not None:
1835  # We are now reading the decay blocks! Take them from the param card
1836  oldparam = open(param_card_old,'r')
1837  newDecays = False
1838  for old_line in oldparam.readlines():
1839  newBlockName = None
1840  if old_line.strip().upper().startswith('DECAY') and len(old_line.strip().split()) > 1:
1841  newBlockName = line.strip().upper().split()[pos]
1842  if newDecays:
1843  newlhe.write(old_line)
1844  elif newBlockName == 'DECAY':
1845  newDecays = True
1846  newlhe.write(old_line)
1847  oldparam.close()
1848  # Done adding the decays
1849  decayEdit = True
1850  blockName = None
1851  continue
1852 
1853  # Keep a record of the particles that are in the events
1854  if not eventRead and '<event>' in line:
1855  eventRead = True
1856  if eventRead:
1857  if len(line.split())==11:
1858  aparticle = line.split()[0]
1859  if aparticle not in particles_in_events:
1860  particles_in_events += [aparticle]
1861 
1862  # Otherwise write the line again
1863  newlhe.write(line)
1864 
1865  # Check that none of the particles that we were setting the masses of appear in the LHE events
1866  for akey in masses:
1867  if akey in particles_in_events:
1868  mglog.error('Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1869  return -1
1870 
1871  # Close up and return
1872  newlhe.close()
1873 
1874  # Move the new file to the old file location
1875  if lhe_file_new is None:
1876  os.remove(lhe_file_old)
1877  shutil.move(lhe_file_new_tmp,lhe_file_old)
1878  lhe_file_new_tmp = lhe_file_old
1879  # Delete the old file if requested
1880  elif delete_old_lhe:
1881  os.remove(lhe_file_old)
1882 
1883  return lhe_file_new_tmp
1884 
1885 
1886 

◆ write_test_script()

def python.MadGraphUtils.write_test_script ( )

Definition at line 204 of file MadGraphUtils.py.

204 def write_test_script():
205  mglog.info('Will write a stand-alone debugging script.')
206  mglog.info('This is an attempt to provide you commands that you can use')
207  mglog.info('to reproduce the error locally. If you make additional')
208  mglog.info('modifications by hand (not using MadGraphControl) in your JO,')
209  mglog.info('make sure that you check and modify the script as needed.\n\n')
210  global MADGRAPH_COMMAND_STACK
211  mglog.info('# Script start; trim off columns left of the "#"')
212  # Write offline stand-alone reproduction script
213  with open('standalone_script.sh','w') as standalone_script:
214  for command in MADGRAPH_COMMAND_STACK:
215  for line in command.split('\n'):
216  mglog.info(line)
217  standalone_script.write(line+'\n')
218  mglog.info('# Script end')
219  mglog.info('Script also written to %s/standalone_script.sh',os.getcwd())
220 
221 

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

string 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

string 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 17 of file MadGraphUtils.py.

◆ patched_shutil_loc

string 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

string python.MadGraphUtils.python = 'python'

Definition at line 20 of file MadGraphUtils.py.

replace
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition: hcg.cxx:307
python.LHAPDFsupport.get_LHAPDF_PATHS
def get_LHAPDF_PATHS()
Definition: LHAPDFsupport.py:17
python.MadGraphUtils.is_NLO_run
def is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2306
vtune_athena.format
format
Definition: vtune_athena.py:14
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
python.MadGraphUtilsHelpers.checkSettingIsTrue
def checkSettingIsTrue(key_, mydict_)
Definition: MadGraphUtilsHelpers.py:45
python.MadGraphParamHelpers.do_PMG_updates
def do_PMG_updates(process_dir)
Definition: MadGraphParamHelpers.py:144
max
constexpr double max()
Definition: ap_fixedTest.cxx:33
python.MadGraphUtils.modify_param_card
def modify_param_card(param_card_input=None, param_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, params={}, output_location=None)
Definition: MadGraphUtils.py:1902
min
constexpr double min()
Definition: ap_fixedTest.cxx:26
python.MadGraphUtils.arrange_output
def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION, lhe_version=None, saveProcDir=False, runArgs=None, fixEventWeightsForBridgeMode=False)
Definition: MadGraphUtils.py:1196
python.MadGraphUtilsHelpers.get_runArgs_info
def get_runArgs_info(runArgs)
Definition: MadGraphUtilsHelpers.py:98
python.MadGraphUtils.setupLHAPDF
def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True)
Definition: MadGraphUtils.py:835
python.MadGraphUtils.ls_dir
def ls_dir(directory)
Definition: MadGraphUtils.py:2443
python.MadGraphUtilsHelpers.checkSetting
def checkSetting(key_, value_, mydict_)
Definition: MadGraphUtilsHelpers.py:37
upper
int upper(int c)
Definition: LArBadChannelParser.cxx:49
python.MadGraphUtils.update_lhe_file
def update_lhe_file(lhe_file_old, param_card_old=None, lhe_file_new=None, masses={}, delete_old_lhe=True)
Definition: MadGraphUtils.py:1780
python.MadGraphParamHelpers.check_PMG_updates
def check_PMG_updates(process_dir)
Definition: MadGraphParamHelpers.py:154
python.MadGraphUtils.get_default_config_card
def get_default_config_card(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2274
python.MadGraphUtils.new_process
def new_process(process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False)
Definition: MadGraphUtils.py:222
python.MadGraphUtils.modify_config_card
def modify_config_card(config_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, settings={}, set_commented=True)
Definition: MadGraphUtils.py:2155
python.MadGraphUtils.setup_path_protection
def setup_path_protection()
Definition: MadGraphUtils.py:53
python.MadGraphUtils.SUSY_Generation
def SUSY_Generation(runArgs=None, process=None, plugin=None, syst_mod=None, keepOutput=False, param_card=None, writeGridpack=False, madspin_card=None, run_settings={}, params={}, fixEventWeightsForBridgeMode=False, add_lifetimes_lhe=False, usePMGSettings=True)
Definition: MadGraphUtils.py:1725
python.MadGraphUtils.check_reweight_card
def check_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:1564
python.MadGraphUtils.config_only_check
def config_only_check()
Definition: MadGraphUtils.py:73
python.MadGraphUtils.get_default_runcard
def get_default_runcard(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:359
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
python.MadGraphUtils.write_test_script
def write_test_script()
Definition: MadGraphUtils.py:204
python.MadGraphUtils.error_check
def error_check(errors_a, return_code)
Definition: MadGraphUtils.py:109
python.MadGraphUtils.generate
def generate(process_dir='PROC_mssm_0', grid_pack=False, gridpack_compile=False, extlhapath=None, required_accuracy=0.01, runArgs=None, bias_module=None, requirePMGSettings=False)
Definition: MadGraphUtils.py:391
python.MadGraphUtils.print_cards
def print_cards(proc_card='proc_card_mg5.dat', run_card=None, param_card=None, madspin_card=None, reweight_card=None, warn_on_missing=True)
Definition: MadGraphUtils.py:2217
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
python.MadGraphUtils.is_gen_from_gridpack
def is_gen_from_gridpack()
Definition: MadGraphUtils.py:2262
python.MadGraphUtils.get_expected_systematic_names
def get_expected_systematic_names(syst_setting)
Definition: MadGraphUtils.py:1490
python.MadGraphUtils.add_madspin
def add_madspin(madspin_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:1051
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.MadGraphUtils.generate_prep
def generate_prep(process_dir)
Definition: MadGraphUtils.py:84
python.MadGraphUtils.modify_run_card
def modify_run_card(run_card_input=None, run_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, runArgs=None, settings={}, skipBaseFragment=False)
Definition: MadGraphUtils.py:2050
python.MadGraphUtils.setup_bias_module
def setup_bias_module(bias_module, process_dir)
Definition: MadGraphUtils.py:1508
python.MadGraphUtils.run_card_consistency_check
def run_card_consistency_check(isNLO=False, process_dir='.')
Definition: MadGraphUtils.py:2313
python.MadGraphUtils.setupFastjet
def setupFastjet(process_dir=None)
Definition: MadGraphUtils.py:803
generate
Definition: generate.cxx:28
python.MadGraphUtilsHelpers.checkSettingExists
def checkSettingExists(key_, mydict_)
Definition: MadGraphUtilsHelpers.py:52
Trk::open
@ open
Definition: BinningType.h:40
python.MadGraphUtils.fix_fks_makefile
def fix_fks_makefile(process_dir)
Definition: MadGraphUtils.py:2451
python.MadGraphUtils.setNCores
def setNCores(process_dir, Ncores=None)
Definition: MadGraphUtils.py:982
python.MadGraphUtils.generate_from_gridpack
def generate_from_gridpack(runArgs=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False)
Definition: MadGraphUtils.py:601
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.JOsupport.get_physics_short
def get_physics_short()
Definition: JOsupport.py:12
python.MadGraphUtils.get_expected_reweight_names
def get_expected_reweight_names(reweight_card_loc)
Definition: MadGraphUtils.py:1474
python.MadGraphUtils.get_mg5_executable
def get_mg5_executable()
Definition: MadGraphUtils.py:1000
python.MadGraphUtils.get_cluster_type
def get_cluster_type(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2295
str
Definition: BTagTrackIpAccessor.cxx:11
python.MadGraphUtils.get_reweight_card
def get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:1558
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:798
python.MadGraphUtils.madspin_on_lhe
def madspin_on_lhe(input_LHE, madspin_card, runArgs=None, keep_original=False)
Definition: MadGraphUtils.py:1108
python.MadGraphUtils.get_SUSY_variations
def get_SUSY_variations(process, masses, syst_mod, ktdurham=None)
Definition: MadGraphUtils.py:1627
python.MadGraphUtils.print_cards_from_dir
def print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2211
python.LHAPDFsupport.get_lhapdf_id_and_name
def get_lhapdf_id_and_name(pdf)
Definition: LHAPDFsupport.py:33
python.MadGraphUtils.add_reweighting
def add_reweighting(run_name, reweight_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2428
python.MadGraphUtils.stack_subprocess
def stack_subprocess(command, **kwargs)
Definition: MadGraphUtils.py:47
python.MadGraphUtils.add_lifetimes
def add_lifetimes(process_dir, threshold=None)
Definition: MadGraphUtils.py:1007
python.MadGraphUtils.find_key_and_update
def find_key_and_update(akey, dictionary)
Definition: MadGraphUtils.py:1887
python.MadGraphUtils.SUSY_process
def SUSY_process(process='')
Definition: MadGraphUtils.py:1695
readCCLHist.float
float
Definition: readCCLHist.py:83
Trk::split
@ split
Definition: LayerMaterialProperties.h:38
python.MadGraphUtilsHelpers.getDictFromCard
def getDictFromCard(card_loc, lowercase=False)
Definition: MadGraphUtilsHelpers.py:7
python.MadGraphUtilsHelpers.is_version_or_newer
def is_version_or_newer(args)
Definition: MadGraphUtilsHelpers.py:59
python.MadGraphUtils.helpful_SUSY_definitions
def helpful_SUSY_definitions()
Definition: MadGraphUtils.py:1600