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 get_LHAPDF_DATA_PATH ()
 
def get_LHAPDF_PATHS ()
 
def get_lhapdf_id_and_name (pdf)
 
def setupLHAPDF (process_dir=None, extlhapath=None, allow_links=True)
 
def setNCores (process_dir, Ncores=None)
 
def resetLHAPDF (origLHAPATH='', origLHAPDF_DATA_PATH='')
 
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 remap_lhe_pdgids (lhe_file_old, lhe_file_new=None, pdgid_map={}, 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 check_reset_proc_number (opts)
 
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 1058 of file MadGraphUtils.py.

1058 def add_lifetimes(process_dir,threshold=None):
1059  """ Add lifetimes to the generated LHE file. Should be
1060  called after generate_events is called.
1061  """
1062  if config_only_check():
1063  return
1064 
1065  me_exec=get_mg5_executable()
1066 
1067  if len(glob.glob(process_dir+'/Events/*'))<1:
1068  mglog.error('Process dir '+process_dir+' does not contain events?')
1069  run = glob.glob(process_dir+'/Events/*')[0].split('/')[-1]
1070 
1071  # Note : This slightly clunky implementation is needed for the time being
1072  # See : https://answers.launchpad.net/mg5amcnlo/+question/267904
1073 
1074  tof_c = open('time_of_flight_exec_card','w')
1075  tof_c.write('launch '+process_dir+''' -i
1076 add_time_of_flight '''+run+((' --threshold='+str(threshold)) if threshold is not None else ''))
1077  tof_c.close()
1078 
1079  mglog.info('Started adding time of flight info '+str(time.asctime()))
1080 
1081  global MADGRAPH_CATCH_ERRORS
1082  generate = stack_subprocess([python,me_exec,'time_of_flight_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1083  (out,err) = generate.communicate()
1084  error_check(err,generate.returncode)
1085 
1086  mglog.info('Finished adding time of flight information at '+str(time.asctime()))
1087 
1088  # Re-zip the file if needed
1089  lhe_gz = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1090  if not os.access(lhe_gz,os.R_OK):
1091  mglog.info('LHE file needs to be zipped')
1092  lhe = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1093  rezip = stack_subprocess(['gzip',lhe])
1094  rezip.wait()
1095  mglog.info('Zipped')
1096  else:
1097  mglog.info('LHE file zipped by MadGraph automatically. Nothing to do')
1098 
1099  return True
1100 
1101 

◆ 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 1102 of file MadGraphUtils.py.

1102 def add_madspin(madspin_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
1103  """ Run madspin on the generated LHE file. Should be
1104  run when you have inputGeneratorFile set.
1105  Only requires a simplified process with the same model that you are
1106  interested in (needed to set up a process directory for MG5_aMC)
1107  """
1108  if config_only_check():
1109  return
1110 
1111  me_exec=get_mg5_executable()
1112 
1113  if madspin_card is not None:
1114  shutil.copyfile(madspin_card,process_dir+'/Cards/madspin_card.dat')
1115 
1116  if len(glob.glob(process_dir+'/Events/*'))<1:
1117  mglog.error('Process dir '+process_dir+' does not contain events?')
1118  proc_dir_list = glob.glob(process_dir+'/Events/*')
1119  run=None
1120  for adir in proc_dir_list:
1121  if 'GridRun_' in adir:
1122  run=adir.split('/')[-1]
1123  break
1124  else:
1125  run=proc_dir_list[0].split('/')[-1]
1126 
1127  # Note : This slightly clunky implementation is needed for the time being
1128  # See : https://answers.launchpad.net/mg5amcnlo/+question/267904
1129 
1130  ms_c = open('madspin_exec_card','w')
1131  ms_c.write('launch '+process_dir+''' -i
1132 decay_events '''+run)
1133  ms_c.close()
1134 
1135  mglog.info('Started running madspin at '+str(time.asctime()))
1136 
1137  global MADGRAPH_CATCH_ERRORS
1138  generate = stack_subprocess([python,me_exec,'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1139  (out,err) = generate.communicate()
1140  error_check(err,generate.returncode)
1141  if len(glob.glob(process_dir+'/Events/'+run+'_decayed_*/')) == 0:
1142  mglog.error('No '+process_dir+'/Events/'+run+'_decayed_*/ can be found')
1143  raise RuntimeError('Problem while running MadSpin')
1144 
1145  mglog.info('Finished running madspin at '+str(time.asctime()))
1146 
1147  # Re-zip the file if needed
1148  lhe_gz = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1149  if not os.access(lhe_gz,os.R_OK):
1150  mglog.info('LHE file needs to be zipped')
1151  lhe = glob.glob(process_dir+'/Events/*/*lhe.gz')[0]
1152  rezip = stack_subprocess(['gzip',lhe])
1153  rezip.wait()
1154  mglog.info('Zipped')
1155  else:
1156  mglog.info('LHE file zipped by MadGraph automatically. Nothing to do')
1157 
1158 

◆ add_reweighting()

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

Definition at line 2565 of file MadGraphUtils.py.

2565 def add_reweighting(run_name,reweight_card=None,process_dir=MADGRAPH_GRIDPACK_LOCATION):
2566  mglog.info('Running reweighting module on existing events')
2567  if reweight_card is not None:
2568  mglog.info('Copying new reweight card from '+reweight_card)
2569  shutil.move(reweight_card,process_dir+'/Cards/reweight_card.dat')
2570  reweight_cmd='{}/bin/madevent reweight {} -f'.format(process_dir,run_name)
2571  global MADGRAPH_CATCH_ERRORS
2572  reweight = stack_subprocess([python]+reweight_cmd.split(),stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
2573  (out,err) = reweight.communicate()
2574  error_check(err,reweight.returncode)
2575  mglog.info('Finished reweighting')
2576 

◆ arrange_output()

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

Definition at line 1247 of file MadGraphUtils.py.

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

◆ check_reset_proc_number()

def python.MadGraphUtils.check_reset_proc_number (   opts)

Definition at line 2577 of file MadGraphUtils.py.

2577 def check_reset_proc_number(opts):
2578  if 'ATHENA_CORE_NUMBER' in os.environ and int(os.environ['ATHENA_CORE_NUMBER'])>0:
2579  mglog.info('Noticed that you have run with an athena MT-like whole-node setup. Will re-configure now to make sure that the remainder of the job runs serially.')
2580  # Try to modify the opts underfoot
2581  if not hasattr(opts,'nprocs'):
2582  mglog.warning('Did not see option!')
2583  else:
2584  opts.nprocs = 0
2585  mglog.debug(str(opts))
2586 
2587 

◆ check_reweight_card()

def python.MadGraphUtils.check_reweight_card (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1615 of file MadGraphUtils.py.

1615 def check_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1616  reweight_card=get_reweight_card(process_dir=process_dir)
1617  shutil.move(reweight_card,reweight_card+'.old')
1618  oldcard = open(reweight_card+'.old','r')
1619  newcard = open(reweight_card,'w')
1620  changed = False
1621  info_expression=r'launch.*--rwgt_info\s*=\s*(\S+).*'
1622  name_expression=info_expression.replace('info','name')
1623  goodname_expression=r'^[A-Za-z0-9_\-.]+$'
1624  for line in oldcard:
1625  # we are only interested in the 'launch' line
1626  if not line.strip().startswith('launch') :
1627  newcard.write(line)
1628  else:
1629  rwgt_name_match=re.match(name_expression,line.strip())
1630  rwgt_info_match=re.match(info_expression,line.strip())
1631  if rwgt_name_match is None and rwgt_info_match is None:
1632  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)
1633  for match in [rwgt_info_match,rwgt_name_match]:
1634  if match is None:
1635  continue
1636  if len(match.groups())!=1:
1637  raise RuntimeError('Unexpected format of reweight card in line: '+line)
1638  if not re.match(goodname_expression,match.group(1)):
1639  raise RuntimeError('No special character in reweighting info/name, only allowing '+goodname_expression)
1640  if rwgt_info_match is not None:
1641  newcard.write(line)
1642  elif rwgt_name_match is not None:
1643  newcard.write(line.strip()+' --rwgt_info={0}\n'.format(rwgt_name_match.group(1)))
1644  changed=True
1645  if changed:
1646  mglog.info('Updated reweight_card')
1647  newcard.close()
1648  oldcard.close()
1649 
1650 

◆ config_only_check()

def python.MadGraphUtils.config_only_check ( )

Definition at line 67 of file MadGraphUtils.py.

67 def config_only_check():
68  try:
69  from __main__ import opts
70  if opts.config_only:
71  mglog.info('Athena running on config only mode: not executing MadGraph')
72  return True
73  except ImportError:
74  pass
75  return False
76 
77 

◆ error_check()

def python.MadGraphUtils.error_check (   errors_a,
  return_code 
)

Definition at line 103 of file MadGraphUtils.py.

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

2004 def find_key_and_update(akey,dictionary):
2005  """ Helper function when looking at param cards
2006  In some cases it's tricky to match keys - they may differ
2007  only in white space. This tries to sort out when we have
2008  a match, and then uses the one in blockParams afterwards.
2009  In the case of no match, it returns the original key.
2010  """
2011  test_key = ' '.join(akey.strip().replace('\t',' ').split())
2012  for key in dictionary:
2013  mod_key = ' '.join(key.strip().replace('\t',' ').split())
2014  if mod_key==test_key:
2015  return key
2016  return akey
2017 
2018 

◆ fix_fks_makefile()

def python.MadGraphUtils.fix_fks_makefile (   process_dir)

Definition at line 2596 of file MadGraphUtils.py.

2596 def fix_fks_makefile(process_dir):
2597  makefile_fks=process_dir+'/SubProcesses/makefile_fks_dir'
2598  mglog.info('Fixing '+makefile_fks)
2599  shutil.move(makefile_fks,makefile_fks+'_orig')
2600  fin=open(makefile_fks+'_orig')
2601  fout=open(makefile_fks,'w')
2602  edit=False
2603  for line in fin:
2604  if 'FKSParams.mod' in line:
2605  fout.write(line.replace('FKSParams.mod','FKSParams.o'))
2606  edit=True
2607  elif edit and 'driver_mintFO' in line:
2608  fout.write('driver_mintFO.o: weight_lines.o mint_module.o FKSParams.o\n')
2609  elif edit and 'genps_fks.o' in line:
2610  fout.write('genps_fks.o: mint_module.o FKSParams.o\n')
2611  elif edit and 'test_soft_col_limits' in line:
2612  fout.write(line)
2613  fout.write('madfks_plot.o: mint_module.o\n')
2614  fout.write('cluster.o: weight_lines.o\n')
2615  else:
2616  fout.write(line)
2617  fin.close()
2618  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 385 of file MadGraphUtils.py.

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

◆ generate_from_gridpack()

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

Definition at line 595 of file MadGraphUtils.py.

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

◆ generate_prep()

def python.MadGraphUtils.generate_prep (   process_dir)

Definition at line 78 of file MadGraphUtils.py.

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

◆ get_cluster_type()

def python.MadGraphUtils.get_cluster_type (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2412 of file MadGraphUtils.py.

2412 def get_cluster_type(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2413  card_in = open(get_default_config_card(process_dir=process_dir),'r')
2414  for l in card_in.readlines():
2415  if 'cluster_type' not in l.split('#')[0]:
2416  continue
2417  cluster_type = l.split('#')[0].split('=')[1]
2418  mglog.info('Returning cluster type: '+cluster_type)
2419  return cluster_type
2420  return None
2421 
2422 

◆ get_default_config_card()

def python.MadGraphUtils.get_default_config_card (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2391 of file MadGraphUtils.py.

2391 def get_default_config_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2392  if config_only_check():
2393  mglog.info('Athena running on config only mode: grabbing config card the old way, as there will be no proc dir')
2394  if os.access(os.environ['MADPATH']+'/input/mg5_configuration.txt',os.R_OK):
2395  shutil.copy(os.environ['MADPATH']+'/input/mg5_configuration.txt','local_mg5_configuration.txt')
2396  return 'local_mg5_configuration.txt'
2397 
2398  lo_config_card=process_dir+'/Cards/me5_configuration.txt'
2399  nlo_config_card=process_dir+'/Cards/amcatnlo_configuration.txt'
2400 
2401  if os.access(lo_config_card,os.R_OK) and not os.access(nlo_config_card,os.R_OK):
2402  return lo_config_card
2403  elif os.access(nlo_config_card,os.R_OK) and not os.access(lo_config_card,os.R_OK):
2404  return nlo_config_card
2405  elif os.access(nlo_config_card,os.R_OK) and os.access(lo_config_card,os.R_OK):
2406  mglog.error('Found both types of config card in '+process_dir)
2407  else:
2408  mglog.error('No config card in '+process_dir)
2409  raise RuntimeError('Unable to locate configuration card')
2410 
2411 

◆ 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 353 of file MadGraphUtils.py.

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

◆ get_expected_reweight_names()

def python.MadGraphUtils.get_expected_reweight_names (   reweight_card_loc)

Definition at line 1525 of file MadGraphUtils.py.

1525 def get_expected_reweight_names(reweight_card_loc):
1526  if reweight_card_loc is None:
1527  return []
1528  names=[]
1529  f_rw=open(reweight_card_loc)
1530  for line in f_rw:
1531  if 'launch' not in line:
1532  continue
1533  match=re.match(r'launch.*--rwgt_info\s*=\s*(\S+).*',line.strip())
1534  if len(match.groups())!=1:
1535  raise RuntimeError('Unexpected format of reweight card in line'+line)
1536  else:
1537  names+=[match.group(1)]
1538  f_rw.close()
1539  return names
1540 

◆ get_expected_systematic_names()

def python.MadGraphUtils.get_expected_systematic_names (   syst_setting)

Definition at line 1541 of file MadGraphUtils.py.

1541 def get_expected_systematic_names(syst_setting):
1542  names=[]
1543  if syst_setting is None or 'central_pdf' not in syst_setting:
1544  mglog.warning("Systematics have not been defined via base fragment or 'MADGRAPH_PDFSETTING', cannot check for expected weights")
1545  return []
1546  if 'pdf_variations' in syst_setting and isinstance(syst_setting['pdf_variations'],list):
1547  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':syst_setting['central_pdf']}]
1548  for pdf in syst_setting['pdf_variations']:
1549  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':pdf+1}]
1550  if 'alternative_pdfs' in syst_setting and isinstance(syst_setting['alternative_pdfs'],list):
1551  for pdf in syst_setting['alternative_pdfs']:
1552  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':1.0,'muf':1.0,'pdf':pdf}]
1553  if 'scale_variations' in syst_setting and isinstance(syst_setting['scale_variations'],list):
1554  for mur in syst_setting['scale_variations']:
1555  for muf in syst_setting['scale_variations']:
1556  names+=[MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO%{'mur':mur,'muf':muf,'pdf':syst_setting['central_pdf']}]
1557  return names
1558 

◆ get_LHAPDF_DATA_PATH()

def python.MadGraphUtils.get_LHAPDF_DATA_PATH ( )

Definition at line 828 of file MadGraphUtils.py.

829  return get_LHAPDF_PATHS()[1]
830 
831 

◆ get_lhapdf_id_and_name()

def python.MadGraphUtils.get_lhapdf_id_and_name (   pdf)

Definition at line 849 of file MadGraphUtils.py.

849 def get_lhapdf_id_and_name(pdf):
850  pdfname=''
851  pdfid=-999
852  LHADATAPATH=get_LHAPDF_DATA_PATH()
853  pdflist = open(LHADATAPATH+'/pdfsets.index','r')
854  if isinstance(pdf,int) or pdf.isdigit():
855  pdf=int(pdf)
856  pdfid=pdf
857  for line in pdflist:
858  splitline=line.split()
859  if int(splitline[0]) == pdfid:
860  pdfname=splitline[1]
861  break
862  else:
863  pdfname=pdf
864  for line in pdflist:
865  splitline=line.split()
866  if splitline[1] == pdfname:
867  pdfid=int(splitline[0])
868  break
869  pdflist.close()
870 
871  if pdfname=='':
872  err='Couldn\'t find PDF name associated to ID %i in %s.'%(pdfid,LHADATAPATH+'/pdfsets.index')
873  mglog.error(err)
874  raise RuntimeError(err)
875  if pdfid<0:
876  err='Couldn\'t find PDF ID associated to name %s in %s.'%(pdfname,LHADATAPATH+'/pdfsets.index')
877  mglog.error(err)
878  raise RuntimeError(err)
879 
880  return pdfid,pdfname
881 
882 

◆ get_LHAPDF_PATHS()

def python.MadGraphUtils.get_LHAPDF_PATHS ( )

Definition at line 832 of file MadGraphUtils.py.

832 def get_LHAPDF_PATHS():
833  LHADATAPATH=None
834  LHAPATH=None
835  for p in os.environ['LHAPATH'].split(':')+os.environ['LHAPDF_DATA_PATH'].split(':'):
836  if os.path.exists(p+"/../../lib/") and LHAPATH is None:
837  LHAPATH=p
838  for p in os.environ['LHAPDF_DATA_PATH'].split(':')+os.environ['LHAPATH'].split(':'):
839  if os.path.exists(p) and LHADATAPATH is None and p!=LHAPATH:
840  LHADATAPATH=p
841  if LHADATAPATH is None:
842  LHADATAPATH=LHAPATH
843  if LHAPATH is None:
844  mglog.error('Could not find path to LHAPDF installation')
845  return LHAPATH,LHADATAPATH
846 
847 
848 # function to get lhapdf id and name from either id or name

◆ get_mg5_executable()

def python.MadGraphUtils.get_mg5_executable ( )

Definition at line 1051 of file MadGraphUtils.py.

1051 def get_mg5_executable():
1052  madpath=os.environ['MADPATH']
1053  if not os.access(madpath+'/bin/mg5_aMC',os.R_OK):
1054  raise RuntimeError('mg5_aMC executable not found in '+madpath)
1055  return madpath+'/bin/mg5_aMC'
1056 
1057 

◆ get_reweight_card()

def python.MadGraphUtils.get_reweight_card (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 1609 of file MadGraphUtils.py.

1609 def get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION):
1610  if os.access(process_dir+'/Cards/reweight_card.dat',os.R_OK):
1611  return process_dir+'/Cards/reweight_card.dat'
1612  return None
1613 
1614 

◆ get_SUSY_variations()

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

Definition at line 1678 of file MadGraphUtils.py.

1678 def get_SUSY_variations( process , masses , syst_mod , ktdurham = None ):
1679  # Don't override an explicit setting from the run card!
1680  if ktdurham is None:
1681  prod_particles = []
1682  if process is not None:
1683  id_map = {'go':'1000021','dl':'1000001','ul':'1000002','sl':'1000003','cl':'1000004','b1':'1000005','t1':'1000006',
1684  'dr':'2000001','ur':'2000002','sr':'2000003','cr':'2000004','b2':'2000005','t2':'2000006',
1685  'n1':'1000022','n2':'1000023','x1':'1000024','x2':'1000037','n3':'1000025','n4':'1000035',
1686  'el':'1000011','mul':'1000013','ta1':'1000015','sve':'1000012','svm':'1000014','svt':'1000016',
1687  'er':'2000011','mur':'2000013','ta2':'2000015'}
1688  for l in process:
1689  if 'generate' in l or 'add process' in l:
1690  clean_proc = l.replace('generate','').replace('+','').replace('-','').replace('~','').replace('add process','').split('>')[1].split(',')[0]
1691  for particle in clean_proc.split():
1692  if particle not in id_map:
1693  mglog.info(f'Particle {particle} not found in PDG ID map - skipping')
1694  else:
1695  prod_particles += id_map[particle]
1696  # If we don't specify a process, then all we can do is guess based on available masses
1697  # Same if we failed to identify the right particles
1698  my_mass = 10000.
1699  if len(prod_particles)>0:
1700  for x in prod_particles:
1701  if x in masses:
1702  my_mass = min(my_mass,abs(float(masses[x])))
1703  else:
1704  mglog.info(f'Seem to ask for production of PDG ID {x}, but {x} not in mass dictionary?')
1705  if my_mass>9999.:
1706  strong_ids = ['1000001','1000002','1000003','1000004','1000005','1000006','2000001','2000002','2000003','2000004','2000005','2000006','1000021']
1707  weak_ids = ['1000023','1000024','1000025','1000011','1000013','1000015','2000011','2000013','2000015','1000012','1000014','1000016']
1708  # First check the lightest of the heavy sparticles - all squarks and gluino
1709  my_mass = min([abs(float(masses[x])) for x in strong_ids if x in masses])
1710  # Now check if strong production was not the key mode
1711  if my_mass>10000.:
1712  # This is a little tricky, but: we want the heaviest non-decoupled mass
1713  my_mass = max([abs(float(masses[x])) for x in weak_ids if x in masses and float(masses[x])<10000.])
1714  # Final check for N1N1 with everything else decoupled
1715  if my_mass>10000. and '1000022' in masses:
1716  my_mass = masses['1000022']
1717  if my_mass>10000.:
1718  raise RuntimeError('Could not understand which mass to use for matching cut in '+str(masses))
1719 
1720  # Now set the matching scale accordingly
1721  ktdurham = min(my_mass*0.25,500)
1722  # Should not be weirdly low - can't imagine a situation where you'd really want the scale below 15 GeV
1723  ktdurham = max(ktdurham,15)
1724  if syst_mod is not None and 'qup' in syst_mod.lower():
1725  ktdurham = ktdurham*2.
1726  elif syst_mod is not None and 'qdown' in syst_mod.lower():
1727  ktdurham = ktdurham*0.5
1728 
1729  mglog.info('For matching, will use ktdurham of '+str(ktdurham))
1730 
1731  alpsfact = 1.0
1732  scalefact = 1.0
1733  if syst_mod is not None and 'alpsfactup' in syst_mod.lower():
1734  alpsfact = 2.0
1735  elif syst_mod is not None and 'alpsfactdown' in syst_mod.lower():
1736  alpsfact = 0.5
1737 
1738  if syst_mod is not None and 'scalefactup' in syst_mod.lower():
1739  scalefact = 2.0
1740  elif syst_mod is not None and 'scalefactdown' in syst_mod.lower():
1741  scalefact = 0.5
1742 
1743  return abs(ktdurham) , alpsfact , scalefact
1744 
1745 

◆ helpful_SUSY_definitions()

def python.MadGraphUtils.helpful_SUSY_definitions ( )

Definition at line 1651 of file MadGraphUtils.py.

1652  return """
1653 # Define multiparticle labels
1654 define p = g u c d s u~ c~ d~ s~
1655 define j = g u c d s u~ c~ d~ s~
1656 define pb = g u c d s b u~ c~ d~ s~ b~
1657 define jb = g u c d s b u~ c~ d~ s~ b~
1658 define l+ = e+ mu+
1659 define l- = e- mu-
1660 define vl = ve vm vt
1661 define vl~ = ve~ vm~ vt~
1662 define fu = u c e+ mu+ ta+
1663 define fu~ = u~ c~ e- mu- ta-
1664 define fd = d s ve~ vm~ vt~
1665 define fd~ = d~ s~ ve vm vt
1666 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~
1667 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~
1668 define susylq = ul ur dl dr cl cr sl sr
1669 define susylq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~
1670 define susysq = ul ur dl dr cl cr sl sr t1 t2 b1 b2
1671 define susysq~ = ul~ ur~ dl~ dr~ cl~ cr~ sl~ sr~ t1~ t2~ b1~ b2~
1672 define susysl = el- el+ er- er+ mul- mul+ mur- mur+ ta1- ta1+ ta2- ta2+
1673 define susyv = sve svm svt
1674 define susyv~ = sve~ svm~ svt~
1675 """
1676 
1677 

◆ 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 2379 of file MadGraphUtils.py.

2379 def is_gen_from_gridpack():
2380  """ Simple function for checking if there is a grid pack.
2381  Relies on the specific location of the unpacked gridpack (madevent)
2382  which is here set as a global variable. The gridpack is untarred by
2383  the transform (Gen_tf.py) and no sign is sent to the job itself
2384  that there is a gridpack in use except the file's existence"""
2385  if os.access(MADGRAPH_GRIDPACK_LOCATION,os.R_OK):
2386  mglog.info('Located input grid pack area')
2387  return True
2388  return False
2389 
2390 

◆ is_NLO_run()

def python.MadGraphUtils.is_NLO_run (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2423 of file MadGraphUtils.py.

2423 def is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2424  # Very simple check based on the above config card grabbing
2425  if config_only_check():
2426  return False
2427  return get_default_config_card(process_dir=process_dir)==process_dir+'/Cards/amcatnlo_configuration.txt'
2428 
2429 

◆ ls_dir()

def python.MadGraphUtils.ls_dir (   directory)

Definition at line 2588 of file MadGraphUtils.py.

2588 def ls_dir(directory):
2589  mglog.info('For your information, ls of '+directory+':')
2590  mglog.info( sorted( os.listdir( directory ) ) )
2591 
2592 # 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 1159 of file MadGraphUtils.py.

1159 def madspin_on_lhe(input_LHE,madspin_card,runArgs=None,keep_original=False):
1160  """ Run MadSpin on an input LHE file. Takes the process
1161  from the LHE file, so you don't need to have a process directory
1162  set up in advance. Runs MadSpin and packs the LHE file up appropriately
1163  Needs runArgs for the file handling"""
1164  if not os.access(input_LHE,os.R_OK):
1165  raise RuntimeError('Could not find LHE file '+input_LHE)
1166  if not os.access(madspin_card,os.R_OK):
1167  raise RuntimeError('Could not find input MadSpin card '+madspin_card)
1168  if keep_original:
1169  shutil.copy(input_LHE,input_LHE+'.original')
1170  mglog.info('Put backup copy of LHE file at '+input_LHE+'.original')
1171  # Start writing the card for execution
1172  madspin_exec_card = open('madspin_exec_card','w')
1173  madspin_exec_card.write('import '+input_LHE+'\n')
1174  # Based on the original card
1175  input_madspin_card = open(madspin_card,'r')
1176  has_launch = False
1177  for l in input_madspin_card.readlines():
1178  commands = l.split('#')[0].split()
1179  # Skip import of a file name that isn't our file
1180  if len(commands)>1 and 'import'==commands[0] and not 'model'==commands[1]:
1181  continue
1182  # Check for a launch command
1183  if len(commands)>0 and 'launch' == commands[0]:
1184  has_launch = True
1185  madspin_exec_card.write(l.strip()+'\n')
1186  if not has_launch:
1187  madspin_exec_card.write('launch\n')
1188  madspin_exec_card.close()
1189  input_madspin_card.close()
1190  # Now get the madspin executable
1191  madpath=os.environ['MADPATH']
1192  if not os.access(madpath+'/MadSpin/madspin',os.R_OK):
1193  raise RuntimeError('madspin executable not found in '+madpath)
1194  mglog.info('Starting madspin at '+str(time.asctime()))
1195  global MADGRAPH_CATCH_ERRORS
1196  generate = stack_subprocess([python,madpath+'/MadSpin/madspin','madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE if MADGRAPH_CATCH_ERRORS else None)
1197  (out,err) = generate.communicate()
1198  error_check(err,generate.returncode)
1199  mglog.info('Done with madspin at '+str(time.asctime()))
1200  # Should now have a re-zipped LHE file
1201  # We now have to do a shortened version of arrange_output below
1202  # Clean up in case a link or file was already there
1203  if os.path.exists(os.getcwd()+'/events.lhe'):
1204  os.remove(os.getcwd()+'/events.lhe')
1205 
1206  mglog.info('Unzipping generated events.')
1207  unzip = stack_subprocess(['gunzip','-f',input_LHE+'.gz'])
1208  unzip.wait()
1209 
1210  mglog.info('Putting a copy in place for the transform.')
1211  mod_output = open(os.getcwd()+'/events.lhe','w')
1212 
1213  #Removing empty lines in LHE
1214  nEmpty=0
1215  with open(input_LHE,'r') as fileobject:
1216  for line in fileobject:
1217  if line.strip():
1218  mod_output.write(line)
1219  else:
1220  nEmpty=nEmpty+1
1221  mod_output.close()
1222 
1223  mglog.info('Removed '+str(nEmpty)+' empty lines from LHEF')
1224 
1225  # Actually move over the dataset - this first part is horrible...
1226  if runArgs is None:
1227  raise RuntimeError('Must provide runArgs to madspin_on_lhe')
1228 
1229  outputDS = runArgs.outputTXTFile if hasattr(runArgs,'outputTXTFile') else 'tmp_LHE_events'
1230 
1231  mglog.info('Moving file over to '+outputDS.split('.tar.gz')[0]+'.events')
1232  shutil.move(os.getcwd()+'/events.lhe',outputDS.split('.tar.gz')[0]+'.events')
1233 
1234  mglog.info('Re-zipping into dataset name '+outputDS)
1235  rezip = stack_subprocess(['tar','cvzf',outputDS,outputDS.split('.tar.gz')[0]+'.events'])
1236  rezip.wait()
1237 
1238  # shortening the outputDS in the case of an output TXT file
1239  if hasattr(runArgs,'outputTXTFile') and runArgs.outputTXTFile is not None:
1240  outputDS = outputDS.split('.TXT')[0]
1241  # Do some fixing up for them
1242  if runArgs is not None:
1243  mglog.debug('Setting inputGenerator file to '+outputDS)
1244  runArgs.inputGeneratorFile=outputDS
1245 
1246 

◆ 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 2272 of file MadGraphUtils.py.

2272 def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
2273  """Build a new configuration from an existing one.
2274  This function can get a fresh runcard from DATAPATH or start from the process directory.
2275  Settings is a dictionary of keys (no spaces needed) and values to replace.
2276  """
2277  # Check for the default config card location
2278  config_card=get_default_config_card(process_dir=process_dir)
2279 
2280  # The format is similar to the run card, but backwards
2281  mglog.info('Modifying config card located at '+config_card)
2282  if config_card_backup is not None:
2283  mglog.info('Keeping backup of original config card at '+config_card_backup)
2284  config_card_old = config_card_backup
2285  else:
2286  config_card_old = config_card+'.old_to_be_deleted'
2287  mglog.debug('Modifying config card settings: '+str(settings))
2288  if os.path.isfile(config_card_old):
2289  os.unlink(config_card_old) # delete old backup
2290  os.rename(config_card, config_card_old) # change name of original card
2291 
2292  oldCard = open(config_card_old, 'r')
2293  newCard = open(config_card, 'w')
2294  used_settings = []
2295  for line in iter(oldCard):
2296  lmod = line if set_commented else line.split('#')[0]
2297  if '=' in lmod:
2298  modified = False
2299  for setting in settings:
2300  if setting not in lmod:
2301  continue
2302  # Assume we hit
2303  mglog.info('Setting '+setting.strip()+' to '+str(settings[setting]))
2304  newCard.write(' '+str(setting.strip())+' = '+str(settings[setting])+'\n')
2305  used_settings += [ setting.strip() ]
2306  modified = True
2307  break
2308  if modified:
2309  continue
2310  newCard.write(line)
2311 
2312  # Clean up unused options
2313  for asetting in settings:
2314  if asetting in used_settings:
2315  continue
2316  if settings[asetting] is None:
2317  continue
2318  mglog.warning('Option '+asetting+' was not in the default config card. Adding by hand a setting to '+str(settings[asetting]) )
2319  newCard.write(' '+str(asetting)+' = '+str(settings[asetting])+'\n')
2320  # close files
2321  oldCard.close()
2322  newCard.close()
2323  mglog.info('Finished modification of config card.')
2324  if config_card_backup is None:
2325  os.unlink(config_card_old)
2326 
2327 

◆ 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 2019 of file MadGraphUtils.py.

2019 def modify_param_card(param_card_input=None,param_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,params={},output_location=None):
2020  """Build a new param_card.dat from an existing one.
2021  Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
2022  Keys can include MASS (for masses) and DECAY X (for decays of particle X)"""
2023  # Grab the old param card and move it into place
2024 
2025  # Check for the default run card location
2026  if param_card_input is None:
2027  param_card_input=process_dir+'/Cards/param_card.dat'
2028  elif param_card_input is not None and not os.access(param_card_input,os.R_OK):
2029  paramcard = subprocess.Popen(['get_files','-data',param_card_input])
2030  paramcard.wait()
2031  if not os.access(param_card_input,os.R_OK):
2032  raise RuntimeError('Could not get param card '+param_card_input)
2033  mglog.info('Using input param card at '+param_card_input)
2034 
2035  #ensure all blocknames and paramnames are upper case
2036  paramsUpper = {}
2037  for blockName in list(params.keys()):
2038  paramsUpper[blockName.upper()] = {}
2039  for paramName in list(params[blockName].keys()):
2040  paramsUpper[blockName.upper()][paramName.upper()] = params[blockName][paramName]
2041 
2042  if param_card_backup is not None:
2043  mglog.info('Keeping backup of original param card at '+param_card_backup)
2044  param_card_old = param_card_backup
2045  else:
2046  param_card_old = param_card_input+'.old_to_be_deleted'
2047  if os.path.isfile(param_card_old):
2048  os.unlink(param_card_old) # delete old backup
2049  os.rename(param_card_input, param_card_old) # change name of original card
2050 
2051  oldcard = open(param_card_old,'r')
2052  param_card_location= process_dir+'/Cards/param_card.dat' if output_location is None else output_location
2053  newcard = open(param_card_location,'w')
2054  decayEdit = False #only becomes true in a DECAY block when specifying the BR
2055  blockName = ""
2056  doneParams = {} #tracks which params have been done
2057  for linewithcomment in oldcard:
2058  line=linewithcomment.split('#')[0]
2059  if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
2060  and len(line.strip().split()) > 1:
2061  if decayEdit and blockName == 'DECAY':
2062  decayEdit = False # Start a new DECAY block
2063  pos = 0 if line.strip().startswith('DECAY') else 1
2064  if blockName=='MASS' and 'MASS' in paramsUpper:
2065  # Any residual masses to set?
2066  if "MASS" in doneParams:
2067  leftOvers = [ x for x in paramsUpper['MASS'] if x not in doneParams['MASS'] ]
2068  else:
2069  leftOvers = [ x for x in paramsUpper['MASS'] ]
2070 
2071  for pdg_id in leftOvers:
2072  mglog.warning('Adding mass line for '+str(pdg_id)+' = '+str(paramsUpper['MASS'][pdg_id])+' which was not in original param card')
2073  newcard.write(' '+str(pdg_id)+' '+str(paramsUpper['MASS'][pdg_id])+'\n')
2074  doneParams['MASS'][pdg_id]=True
2075  if blockName=='DECAY' and 'DECAY' not in line.strip().upper() and 'DECAY' in paramsUpper:
2076  # Any residual decays to include?
2077  leftOvers = [ x for x in paramsUpper['DECAY'] if x not in doneParams['DECAY'] ]
2078  for pdg_id in leftOvers:
2079  mglog.warning('Adding decay for pdg id '+str(pdg_id)+' which was not in the original param card')
2080  newcard.write( paramsUpper['DECAY'][pdg_id].strip()+'\n' )
2081  doneParams['DECAY'][pdg_id]=True
2082  blockName = line.strip().upper().split()[pos]
2083  if decayEdit:
2084  continue #skipping these lines because we are in an edit of the DECAY BR
2085 
2086  akey = None
2087  if blockName != 'DECAY' and len(line.strip().split()) > 0:
2088  # The line is already without the comment.
2089  # In the case of mixing matrices this is a bit tricky
2090  if len(line.split())==2:
2091  akey = line.upper().strip().split()[0]
2092  else:
2093  # Take everything but the last word
2094  akey = line.upper().strip()[:line.strip().rfind(' ')].strip()
2095  elif blockName == 'DECAY' and len(line.strip().split()) > 1:
2096  akey = line.strip().split()[1]
2097  if akey is None:
2098  newcard.write(linewithcomment)
2099  continue
2100 
2101  #check if we have params for this block
2102  if blockName not in paramsUpper:
2103  newcard.write(linewithcomment)
2104  continue
2105  blockParams = paramsUpper[blockName]
2106  # Check the spacing in the key
2107  akey = find_key_and_update(akey,blockParams)
2108 
2109  # look for a string key, which would follow a #
2110  stringkey = None
2111  if '#' in linewithcomment: #ignores comment lines
2112  stringkey = linewithcomment[linewithcomment.find('#')+1:].strip()
2113  if len(stringkey.split()) > 0:
2114  stringkey = stringkey.split()[0].upper()
2115 
2116  if akey not in blockParams and not (stringkey is not None and stringkey in blockParams):
2117  newcard.write(linewithcomment)
2118  continue
2119 
2120  if akey in blockParams and (stringkey is not None and stringkey in blockParams):
2121  raise RuntimeError('Conflicting use of numeric and string keys '+akey+' and '+stringkey)
2122 
2123  theParam = blockParams.get(akey,blockParams[stringkey] if stringkey in blockParams else None)
2124  if blockName not in doneParams:
2125  doneParams[blockName] = {}
2126  if akey in blockParams:
2127  doneParams[blockName][akey]=True
2128  elif stringkey is not None and stringkey in blockParams:
2129  doneParams[blockName][stringkey]=True
2130 
2131  #do special case of DECAY block
2132  if blockName=="DECAY":
2133  if theParam.splitlines()[0].split()[0].upper()=="DECAY":
2134  #specifying the full decay block
2135  for newline in theParam.splitlines():
2136  newcard.write(newline+'\n')
2137  mglog.info(newline)
2138  decayEdit = True
2139  else: #just updating the total width
2140  newcard.write('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2141  mglog.info('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2142  # second special case of QNUMBERS
2143  elif blockName=='QNUMBERS':
2144  #specifying the full QNUMBERS block
2145  for newline in theParam.splitlines():
2146  newcard.write(newline+'\n')
2147  mglog.info(newline)
2148  decayEdit = True
2149  else: #just updating the parameter
2150  newcard.write(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2151  mglog.info(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
2152  # Done editing the line!
2153 
2154  #check that all specified parameters have been updated (helps to catch typos)
2155  for blockName in paramsUpper:
2156  if blockName not in doneParams and len(paramsUpper[blockName].keys())>0:
2157  raise RuntimeError('Did not find any of the parameters for block '+blockName+' in param_card')
2158  for paramName in paramsUpper[blockName]:
2159  if paramName not in doneParams[blockName]:
2160  raise RuntimeError('Was not able to replace parameter '+paramName+' in param_card')
2161 
2162  # Close up and return
2163  oldcard.close()
2164  newcard.close()
2165 
2166 

◆ 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 2167 of file MadGraphUtils.py.

2167 def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
2168  """Build a new run_card.dat from an existing one.
2169  This function can get a fresh runcard from DATAPATH or start from the process directory.
2170  Settings is a dictionary of keys (no spaces needed) and values to replace.
2171  """
2172  if config_only_check():
2173  mglog.info('Running config-only. No proc card, so not operating on the run card.')
2174  return
2175 
2176  # Operate on lower case settings, and choose the capitalization MG5 has as the default (or all lower case)
2177  settings_lower = {}
2178  for s in list(settings.keys()):
2179  settings_lower[s.lower()] = settings[s]
2180 
2181  # Check for the default run card location
2182  if run_card_input is None:
2183  run_card_input=get_default_runcard(process_dir)
2184  elif run_card_input is not None and not os.access(run_card_input,os.R_OK):
2185  runcard = subprocess.Popen(['get_files','-data',run_card_input])
2186  runcard.wait()
2187  if not os.access(run_card_input,os.R_OK):
2188  raise RuntimeError('Could not get run card '+run_card_input)
2189 
2190  # guess NLO
2191  isNLO=is_NLO_run(process_dir=process_dir)
2192  # add gobal PDF and scale uncertainty config to extras, except PDF or weights for syscal config are explictly set
2193  if not skipBaseFragment:
2194  MadGraphControl.MadGraphSystematicsUtils.setup_pdf_and_systematic_weights(MADGRAPH_PDFSETTING,settings_lower,isNLO)
2195 
2196  # Get some info out of the runArgs
2197  if runArgs is not None:
2198  beamEnergy,rand_seed = get_runArgs_info(runArgs)
2199  if 'iseed' not in settings_lower:
2200  settings_lower['iseed']=rand_seed
2201  if not isNLO and 'python_seed' not in settings_lower:
2202  settings_lower['python_seed']=rand_seed
2203  if 'beamenergy' in settings_lower:
2204  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']))
2205  beamEnergy=settings_lower['beamenergy']
2206  settings_lower.pop('beamenergy')
2207  if 'ebeam1' not in settings_lower:
2208  settings_lower['ebeam1']=beamEnergy
2209  if 'ebeam2' not in settings_lower:
2210  settings_lower['ebeam2']=beamEnergy
2211  # Make sure nevents is an integer
2212  if 'nevents' in settings_lower:
2213  settings_lower['nevents'] = int(settings_lower['nevents'])
2214 
2215  mglog.info('Modifying run card located at '+run_card_input)
2216  if run_card_backup is not None:
2217  mglog.info('Keeping backup of original run card at '+run_card_backup)
2218  run_card_old = run_card_backup
2219  else:
2220  run_card_old = run_card_input+'.old_to_be_deleted'
2221  mglog.debug('Modifying runcard settings: '+str(settings_lower))
2222  if os.path.isfile(run_card_old):
2223  os.unlink(run_card_old) # delete old backup
2224  os.rename(run_card_input, run_card_old) # change name of original card
2225 
2226  oldCard = open(run_card_old, 'r')
2227  newCard = open(process_dir+'/Cards/run_card.dat', 'w')
2228  used_settings = []
2229  for line in iter(oldCard):
2230  if not line.strip().startswith('#'): # line commented out
2231  command = line.split('!', 1)[0]
2232  comment = line.split('!', 1)[1] if '!' in line else ''
2233  if '=' in command:
2234  setting = command.split('=')[-1] #.strip()
2235  stripped_setting = setting.strip()
2236  oldValue = '='.join(command.split('=')[:-1])
2237  if stripped_setting.lower() in settings_lower:
2238  # if setting set to 'None' it will be removed from run_card
2239  if settings_lower[stripped_setting.lower()] is None:
2240  line=''
2241  mglog.info('Removing '+stripped_setting+'.')
2242  used_settings += [ stripped_setting.lower() ]
2243  else:
2244  line = oldValue.replace(oldValue.strip(), str(settings_lower[stripped_setting.lower()]))+'='+setting
2245  if comment != '':
2246  line += ' !' + comment
2247  mglog.info('Setting '+stripped_setting+' = '+str(settings_lower[stripped_setting.lower()]))
2248  used_settings += [ stripped_setting.lower() ]
2249  newCard.write(line.strip()+'\n')
2250 
2251  # Check whether mcatnlo_delta is applied to setup pythia8 path
2252  if 'mcatnlo_delta' in settings_lower:
2253  if settings_lower['mcatnlo_delta'] == 'True':
2254  modify_config_card(process_dir=process_dir,settings={'pythia8_path':os.getenv("PY8PATH")})
2255 
2256  # Clean up unused options
2257  for asetting in settings_lower:
2258  if asetting in used_settings:
2259  continue
2260  if settings_lower[asetting] is None:
2261  continue
2262  mglog.info('Option '+asetting+' was not in the default run_card (normal for hidden options). Adding by hand a setting to '+str(settings_lower[asetting]) )
2263  newCard.write( ' '+str(settings_lower[asetting])+' = '+str(asetting)+'\n')
2264  # close files
2265  oldCard.close()
2266  newCard.close()
2267  mglog.info('Finished modification of run card.')
2268  if run_card_backup is None:
2269  os.unlink(run_card_old)
2270 
2271 

◆ 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 216 of file MadGraphUtils.py.

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

◆ 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 2334 of file MadGraphUtils.py.

2334 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):
2335  if os.access(proc_card,os.R_OK):
2336  mglog.info("proc_card:")
2337  procCard = subprocess.Popen(['cat',proc_card])
2338  procCard.wait()
2339  elif warn_on_missing:
2340  mglog.warning('No proc_card: '+proc_card+' found')
2341 
2342  if run_card is not None and os.access(run_card,os.R_OK):
2343  mglog.info("run_card:")
2344  runCard = subprocess.Popen(['cat',run_card])
2345  runCard.wait()
2346  elif run_card is not None and warn_on_missing:
2347  mglog.warning('No run_card: '+run_card+' found')
2348  else:
2349  mglog.info('Default run card in use')
2350 
2351  if param_card is not None and os.access(param_card,os.R_OK):
2352  mglog.info("param_card:")
2353  paramCard = subprocess.Popen(['cat',param_card])
2354  paramCard.wait()
2355  elif param_card is not None and warn_on_missing:
2356  mglog.warning('No param_card: '+param_card+' found')
2357  else:
2358  mglog.info('Default param card in use')
2359 
2360  if madspin_card is not None and os.access(madspin_card,os.R_OK):
2361  mglog.info("madspin_card:")
2362  madspinCard = subprocess.Popen(['cat',madspin_card])
2363  madspinCard.wait()
2364  elif madspin_card is not None and warn_on_missing:
2365  mglog.warning('No madspin_card: '+madspin_card+' found')
2366  else:
2367  mglog.info('No madspin card in use')
2368 
2369  if reweight_card is not None and os.access(reweight_card,os.R_OK):
2370  mglog.info("reweight_card:")
2371  madspinCard = subprocess.Popen(['cat',reweight_card])
2372  madspinCard.wait()
2373  elif reweight_card is not None and warn_on_missing:
2374  mglog.warning('No reweight_card: '+reweight_card+' found')
2375  else:
2376  mglog.info('No reweight card in use')
2377 
2378 

◆ print_cards_from_dir()

def python.MadGraphUtils.print_cards_from_dir (   process_dir = MADGRAPH_GRIDPACK_LOCATION)

Definition at line 2328 of file MadGraphUtils.py.

2328 def print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION):
2329  card_dir=process_dir+'/Cards/'
2330  print_cards(proc_card=card_dir+'proc_card_mg5.dat',run_card=card_dir+'run_card.dat',param_card=card_dir+'param_card.dat',\
2331  madspin_card=card_dir+'madspin_card.dat',reweight_card=card_dir+'reweight_card.dat',warn_on_missing=False)
2332 
2333 

◆ remap_lhe_pdgids()

def python.MadGraphUtils.remap_lhe_pdgids (   lhe_file_old,
  lhe_file_new = None,
  pdgid_map = {},
  delete_old_lhe = True 
)
Update the PDG IDs used in an LHE file. This is a bit finicky, as we have to
both touch the LHE file metadata _and_ modify the events themselves. But since this
is "just" a remapping, it should be safe assuming Pythia8 is told the correct thing
afterwards and can get the showering right.

Definition at line 1937 of file MadGraphUtils.py.

1937 def remap_lhe_pdgids(lhe_file_old,lhe_file_new=None,pdgid_map={},delete_old_lhe=True):
1938  """Update the PDG IDs used in an LHE file. This is a bit finicky, as we have to
1939  both touch the LHE file metadata _and_ modify the events themselves. But since this
1940  is "just" a remapping, it should be safe assuming Pythia8 is told the correct thing
1941  afterwards and can get the showering right."""
1942  # If we want to just use a temp file, then put in a little temp holder
1943  lhe_file_new_tmp = lhe_file_new if lhe_file_new is not None else lhe_file_old+'.tmp'
1944  # Make sure the LHE file is there
1945  if not os.access(lhe_file_old,os.R_OK):
1946  raise RuntimeError('Could not access old LHE file at '+str(lhe_file_old)+'. Please check the file location.')
1947 
1948  # Convert the map into a str:str map, no matter what we started with
1949  pdgid_map_str = { str(x) : str(pdgid_map[x]) for x in pdgid_map }
1950  # Add anti-particles if they aren't already there
1951  pdgid_map_str.update( { '-'+str(x) : '-'+str(pdgid_map[x]) for x in pdgid_map if '-'+str(x) not in pdgid_map } )
1952 
1953  newlhe = open(lhe_file_new_tmp,'w')
1954  blockName = None
1955  eventRead = False
1956  with open(lhe_file_old,'r') as fileobject:
1957  for line in fileobject:
1958  # In case we're reading the param section and we have a block, read the block name
1959  if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
1960  and len(line.strip().split()) > 1:
1961  pos = 0 if line.strip().startswith('DECAY') else 1
1962  blockName = line.strip().upper().split()[pos]
1963  elif '</slha>' in line:
1964  blockName = None
1965  # Check for comments - just write those and move on
1966  if len(line.split('#')[0].strip())==0:
1967  line_mod = line
1968  for pdgid in pdgid_map_str:
1969  if pdgid in line_mod.split():
1970  line_mod = line_mod.replace( pdgid , pdgid_map_str[pdgid] )
1971  newlhe.write(line_mod)
1972  continue
1973  # Replace the PDG ID in the mass block
1974  if blockName=='MASS' and line.split()[0] in pdgid_map_str:
1975  newlhe.write( line.replace( line.split()[0] , pdgid_map_str[ line.split()[0] ] , 1 ) )
1976  continue
1977  if blockName=='DECAY' and line.split()[1] in pdgid_map_str:
1978  newlhe.write( line.replace( line.split()[1] , pdgid_map_str[ line.split()[1] ] , 1 ) )
1979  continue
1980  if blockName=='QNUMBERS' and line.split()[2] in pdgid_map_str:
1981  newlhe.write( line.replace( line.split()[2] , pdgid_map_str[ line.split()[2] ] , 1 ) )
1982  continue
1983  if '<event>' in line:
1984  eventRead = True
1985  if eventRead and len(line.split())==13 and line.split()[0] in pdgid_map_str:
1986  newlhe.write( line.replace( line.split()[0] , pdgid_map_str[ line.split()[0] ] , 1 ) )
1987  continue
1988 
1989  # Otherwise write the line again
1990  newlhe.write(line)
1991 
1992  # Move the new file to the old file location
1993  if lhe_file_new is None:
1994  os.remove(lhe_file_old)
1995  shutil.move(lhe_file_new_tmp,lhe_file_old)
1996  lhe_file_new_tmp = lhe_file_old
1997  # Delete the old file if requested
1998  elif delete_old_lhe:
1999  os.remove(lhe_file_old)
2000 
2001  return lhe_file_new_tmp
2002 
2003 

◆ resetLHAPDF()

def python.MadGraphUtils.resetLHAPDF (   origLHAPATH = '',
  origLHAPDF_DATA_PATH = '' 
)

Definition at line 1043 of file MadGraphUtils.py.

1043 def resetLHAPDF(origLHAPATH='',origLHAPDF_DATA_PATH=''):
1044  mglog.info('Restoring original LHAPDF env variables:')
1045  os.environ['LHAPATH']=origLHAPATH
1046  os.environ['LHAPDF_DATA_PATH']=origLHAPDF_DATA_PATH
1047  mglog.info('LHAPATH='+os.environ['LHAPATH'])
1048  mglog.info('LHAPDF_DATA_PATH='+os.environ['LHAPDF_DATA_PATH'])
1049 
1050 

◆ run_card_consistency_check()

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

Definition at line 2430 of file MadGraphUtils.py.

2430 def run_card_consistency_check(isNLO=False,process_dir='.'):
2431  cardpath=process_dir+'/Cards/run_card.dat'
2432  mydict=getDictFromCard(cardpath)
2433 
2434  # We should always use event_norm = average [AGENE-1725] otherwise Pythia cross sections are wrong
2435  # Modification: average or bias is ok; sum is incorrect. Change the test to set sum to average
2436  if checkSetting('event_norm','sum',mydict):
2437  modify_run_card(process_dir=process_dir,settings={'event_norm':'average'},skipBaseFragment=True)
2438  mglog.warning("setting event_norm to average, there is basically no use case where event_norm=sum is a good idea")
2439 
2440  if not isNLO:
2441  #Check CKKW-L setting
2442  if 'ktdurham' in mydict and float(mydict['ktdurham']) > 0 and int(mydict['ickkw']) != 0:
2443  log='Bad combination of settings for CKKW-L merging! ktdurham=%s and ickkw=%s.'%(mydict['ktdurham'],mydict['ickkw'])
2444  mglog.error(log)
2445  raise RuntimeError(log)
2446 
2447  # Check if user is trying to use deprecated syscalc arguments with the other systematics script
2448  if 'systematics_program' not in mydict or mydict['systematics_program']=='systematics':
2449  syscalc_settings=['sys_pdf', 'sys_scalefact', 'sys_alpsfact', 'sys_matchscale']
2450  found_syscalc_setting=False
2451  for s in syscalc_settings:
2452  if s in mydict:
2453  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)')
2454  found_syscalc_setting=True
2455  if found_syscalc_setting:
2456  syst_arguments=MadGraphControl.MadGraphSystematicsUtils.convertSysCalcArguments(mydict)
2457  mglog.info('Converted syscalc arguments to systematics arguments: '+syst_arguments)
2458  syst_settings_update={'systematics_arguments':syst_arguments}
2459  for s in syscalc_settings:
2460  syst_settings_update[s]=None
2461  modify_run_card(process_dir=process_dir,settings=syst_settings_update,skipBaseFragment=True)
2462 
2463 
2464  # usually the pdf and systematics should be set during modify_run_card
2465  # but check again in case the user did not call the function or provides a different card here
2466  mglog.info('Checking PDF and systematics settings')
2467  if not MadGraphControl.MadGraphSystematicsUtils.base_fragment_setup_check(MADGRAPH_PDFSETTING,mydict,isNLO):
2468  # still need to set pdf and systematics
2469  syst_settings=MadGraphControl.MadGraphSystematicsUtils.get_pdf_and_systematic_settings(MADGRAPH_PDFSETTING,isNLO)
2470  modify_run_card(process_dir=process_dir,settings=syst_settings,skipBaseFragment=True)
2471 
2472  mydict_new=getDictFromCard(cardpath)
2473  if 'systematics_arguments' in mydict_new:
2474  systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict_new['systematics_arguments'])
2475  if 'weight_info' not in systematics_arguments:
2476  mglog.info('Enforcing systematic weight name convention')
2477  dyn = None
2478  if '--dyn' in systematics_arguments or ' dyn' in systematics_arguments:
2479  if '--dyn' in systematics_arguments:
2480  dyn = systematics_arguments.split('--dyn')[1]
2481  if ' dyn' in systematics_arguments:
2482  dyn = systematics_arguments.split(' dyn')[1]
2483  dyn = dyn.replace('\'',' ').replace('=',' ').split()[0]
2484  if dyn is not None and len(dyn.split(','))>1:
2485  systematics_arguments['weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO_ALTDYNSCALES
2486  else:
2487  systematics_arguments['weight_info']=MadGraphControl.MadGraphSystematicsUtils.SYSTEMATICS_WEIGHT_INFO
2488  modify_run_card(process_dir=process_dir,settings={'systematics_arguments':MadGraphControl.MadGraphSystematicsUtils.write_systematics_arguments(systematics_arguments)},skipBaseFragment=True)
2489 
2490  if not isNLO:
2491  if 'python_seed' not in mydict:
2492  mglog.warning('No python seed set in run_card -- adding one with same value as iseed')
2493  modify_run_card(process_dir=process_dir,settings={'python_seed':mydict['iseed']},skipBaseFragment=True)
2494 
2495  # consistency check of 4/5 flavour shceme settings
2496  # Note MG5_aMC default is 4-flavour scheme
2497  FS_updates={}
2498  proton_5flav = False
2499  jet_5flav = False
2500  with open(process_dir+'/Cards/proc_card_mg5.dat', 'r') as file:
2501  content = file.readlines()
2502  for rawline in content:
2503  line = rawline.split('#')[0]
2504  if line.startswith("define p"):
2505  if 'b' in line.split() and 'b~' in line.split():
2506  proton_5flav = True
2507  if 'j' in line.split() and jet_5flav:
2508  proton_5flav = True
2509  if line.startswith("define j"):
2510  if 'b' in line.split() and 'b~' in line.split():
2511  jet_5flav = True
2512  if 'p' in line.split() and proton_5flav:
2513  jet_5flav = True
2514  if proton_5flav or jet_5flav:
2515  FS_updates['asrwgtflavor'] = 5
2516  if not proton_5flav:
2517  mglog.warning('Found 5-flavour jets but 4-flavour proton. This is inconsistent - please pick one.')
2518  mglog.warning('Will proceed assuming 5-flavour scheme.')
2519  if not jet_5flav:
2520  mglog.warning('Found 5-flavour protons but 4-flavour jets. This is inconsistent - please pick one.')
2521  mglog.warning('Will proceed assuming 5-flavour scheme.')
2522  else:
2523  FS_updates['asrwgtflavor'] = 4
2524 
2525  if len(FS_updates)==0:
2526  mglog.warning(f'Could not identify 4- or 5-flavor scheme from process card {process_dir}/Cards/proc_card_mg5.dat')
2527 
2528  if 'asrwgtflavor' in mydict or 'maxjetflavor' in mydict or 'pdgs_for_merging_cut' in mydict:
2529  if FS_updates['asrwgtflavor'] == 5:
2530  # Process card says we are in the five-flavor scheme
2531  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']):
2532  # Inconsistent setting detected; warn the users and correct the settings
2533  mglog.warning('b and b~ included in p and j for 5-flavor scheme but run card settings are inconsistent; adjusting run card')
2534  run_card_updates = {'asrwgtflavor': 5, 'maxjetflavor': 5, 'pdgs_for_merging_cut': '1, 2, 3, 4, 5, 21'}
2535  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2536  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '0.000000e+00'}})
2537  else:
2538  mglog.debug('Consistent 5-flavor scheme setup detected.')
2539  if FS_updates['asrwgtflavor'] == 4:
2540  # Process card says we are in the four-flavor scheme
2541  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']):
2542  # Inconsistent setting detected; warn the users and correct the settings
2543  mglog.warning('b and b~ not included in p and j (4-flavor scheme) but run card settings are inconsistent; adjusting run card')
2544  run_card_updates = {'asrwgtflavor': 4, 'maxjetflavor': 4, 'pdgs_for_merging_cut': '1, 2, 3, 4, 21'}
2545  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2546  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '4.700000e+00'}})
2547  else:
2548  mglog.debug('Consistent 4-flavor scheme setup detected.')
2549  else:
2550  # Flavor scheme setup is missing, adding by hand
2551  if FS_updates['asrwgtflavor'] == 4:
2552  # Warn the users and add the settings according to process card
2553  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.')
2554  run_card_updates = {'asrwgtflavor': 4, 'maxjetflavor': 4, 'pdgs_for_merging_cut': '1, 2, 3, 4, 21'}
2555  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2556  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '4.700000e+00'}})
2557  elif FS_updates['asrwgtflavor'] == 5:
2558  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.')
2559  run_card_updates = {'asrwgtflavor': 5, 'maxjetflavor': 5, 'pdgs_for_merging_cut': '1, 2, 3, 4, 5, 21'}
2560  modify_run_card(process_dir=process_dir,settings=run_card_updates,skipBaseFragment=True)
2561  modify_param_card(process_dir=process_dir, params={'MASS': {'5': '0.000000e+00'}})
2562 
2563  mglog.info('Finished checking run card - All OK!')
2564 

◆ setNCores()

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

Definition at line 1030 of file MadGraphUtils.py.

1030 def setNCores(process_dir, Ncores=None):
1031  my_Ncores = Ncores
1032  my_runMode = 2 if 'ATHENA_CORE_NUMBER' in os.environ else 0
1033  if Ncores is None and 'ATHENA_CORE_NUMBER' in os.environ and int(os.environ['ATHENA_CORE_NUMBER'])>0:
1034  my_Ncores = int(os.environ['ATHENA_CORE_NUMBER'])
1035  my_runMode = 2
1036  if my_Ncores is None:
1037  mglog.info('Setting up for serial run')
1038  my_Ncores = 1
1039 
1040  modify_config_card(process_dir=process_dir,settings={'nb_core':my_Ncores,'run_mode':my_runMode,'automatic_html_opening':'False'})
1041 
1042 

◆ setup_bias_module()

def python.MadGraphUtils.setup_bias_module (   bias_module,
  process_dir 
)

Definition at line 1559 of file MadGraphUtils.py.

1559 def setup_bias_module(bias_module,process_dir):
1560  run_card = process_dir+'/Cards/run_card.dat'
1561  if isinstance(bias_module,tuple):
1562  mglog.info('Using bias module '+bias_module[0])
1563  the_run_card = open(run_card,'r')
1564  for line in the_run_card:
1565  if 'bias_module' in line and not bias_module[0] in line:
1566  raise RuntimeError('You need to add the bias module '+bias_module[0]+' to the run card to actually run it')
1567  the_run_card.close()
1568  if len(bias_module)!=3:
1569  raise RuntimeError('Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1570  bias_module_newpath=process_dir+'/Source/BIAS/'+bias_module[0]
1571  os.makedirs(bias_module_newpath)
1572  bias_module_file=open(bias_module_newpath+'/'+bias_module[0]+'.f','w')
1573  bias_module_file.write(bias_module[1])
1574  bias_module_file.close()
1575  bias_module_make_file=open(bias_module_newpath+'/Makefile','w')
1576  bias_module_make_file.write(bias_module[2])
1577  bias_module_make_file.close()
1578  else:
1579  mglog.info('Using bias module '+bias_module)
1580  bias_module_name=bias_module.split('/')[-1].replace('.gz','')
1581  bias_module_name=bias_module_name.replace('.tar','')
1582  the_run_card = open(run_card,'r')
1583  for line in the_run_card:
1584  if 'bias_module' in line and bias_module_name not in line:
1585  raise RuntimeError('You need to add the bias module '+bias_module_name+' to the run card to actually run it')
1586  the_run_card.close()
1587 
1588  if os.path.exists(bias_module+'.tar.gz'):
1589  bias_module_path=bias_module+'.tar.gz'
1590  elif os.path.exists(bias_module+'.gz'):
1591  bias_module_path=bias_module+'.gz'
1592  elif os.path.exists(bias_module):
1593  bias_module_path=bias_module
1594  else:
1595  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')
1596  return 1
1597  bias_module_newpath=process_dir+'/Source/BIAS/'+bias_module_path.split('/')[-1]
1598  mglog.info('Copying bias module into place: '+bias_module_newpath)
1599  shutil.copy(bias_module_path,bias_module_newpath)
1600  mglog.info('Unpacking bias module')
1601  if bias_module_newpath.endswith('.tar.gz'):
1602  untar = stack_subprocess(['tar','xvzf',bias_module_newpath,'--directory='+process_dir+'/Source/BIAS/'])
1603  untar.wait()
1604  elif bias_module_path.endswith('.gz'):
1605  gunzip = stack_subprocess(['gunzip',bias_module_newpath])
1606  gunzip.wait()
1607 
1608 

◆ setup_path_protection()

def python.MadGraphUtils.setup_path_protection ( )

Definition at line 47 of file MadGraphUtils.py.

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

◆ setupFastjet()

def python.MadGraphUtils.setupFastjet (   process_dir = None)

Definition at line 797 of file MadGraphUtils.py.

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

◆ setupLHAPDF()

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

Definition at line 883 of file MadGraphUtils.py.

883 def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
884 
885  isNLO=is_NLO_run(process_dir=process_dir)
886 
887  origLHAPATH=os.environ['LHAPATH']
888  origLHAPDF_DATA_PATH=os.environ['LHAPDF_DATA_PATH']
889 
890  LHAPATH,LHADATAPATH=get_LHAPDF_PATHS()
891 
892  pdfname=''
893  pdfid=-999
894 
895 
896  run_card=process_dir+'/Cards/run_card.dat'
897  mydict=getDictFromCard(run_card)
898 
899  if mydict["pdlabel"].replace("'","") == 'lhapdf':
900  #Make local LHAPDF dir
901  mglog.info('creating local LHAPDF dir: MGC_LHAPDF/')
902  if os.path.islink('MGC_LHAPDF/'):
903  os.unlink('MGC_LHAPDF/')
904  elif os.path.isdir('MGC_LHAPDF/'):
905  shutil.rmtree('MGC_LHAPDF/')
906 
907  newMGCLHA='MGC_LHAPDF/'
908 
909  mkdir = subprocess.Popen(['mkdir','-p',newMGCLHA])
910  mkdir.wait()
911 
912  pdfs_used=[ int(x) for x in mydict['lhaid'].replace(' ',',').split(',') ]
913  # included systematics pdfs here
914  if 'sys_pdf' in mydict:
915  sys_pdf=mydict['sys_pdf'].replace('&&',' ').split()
916  for s in sys_pdf:
917  if s.isdigit():
918  idx=int(s)
919  if idx>1000: # the sys_pdf syntax is such that small numbers are used to specify the subpdf index
920  pdfs_used.append(idx)
921  else:
922  pdfs_used.append(s)
923  if 'systematics_arguments' in mydict:
924  systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict['systematics_arguments'])
925  if 'pdf' in systematics_arguments:
926  sys_pdf=systematics_arguments['pdf'].replace(',',' ').replace('@',' ').split()
927  for s in sys_pdf:
928  if s.isdigit():
929  idx=int(s)
930  if idx>1000: # the sys_pdf syntax is such that small numbers are used to specify the subpdf index
931  pdfs_used.append(idx)
932  else:
933  pdfs_used.append(s)
934  for pdf in pdfs_used:
935  if isinstance(pdf,str) and (pdf.lower()=='errorset' or pdf.lower()=='central'):
936  continue
937  # new function to get both lhapdf id and name
938  pdfid,pdfname=get_lhapdf_id_and_name(pdf)
939  mglog.info("Found LHAPDF ID="+str(pdfid)+", name="+pdfname)
940 
941  if not os.path.exists(newMGCLHA+pdfname) and not os.path.lexists(newMGCLHA+pdfname):
942  if not os.path.exists(LHADATAPATH+'/'+pdfname):
943  mglog.warning('PDF not installed at '+LHADATAPATH+'/'+pdfname)
944  if allow_links:
945  mglog.info('linking '+LHADATAPATH+'/'+pdfname+' --> '+newMGCLHA+pdfname)
946  os.symlink(LHADATAPATH+'/'+pdfname,newMGCLHA+pdfname)
947  else:
948  mglog.info('copying '+LHADATAPATH+'/'+pdfname+' --> '+newMGCLHA+pdfname)
949  shutil.copytree(LHADATAPATH+'/'+pdfname,newMGCLHA+pdfname)
950 
951  if allow_links:
952  mglog.info('linking '+LHADATAPATH+'/pdfsets.index --> '+newMGCLHA+'pdfsets.index')
953  os.symlink(LHADATAPATH+'/pdfsets.index',newMGCLHA+'pdfsets.index')
954 
955  atlasLHADATAPATH=LHADATAPATH.replace('sft.cern.ch/lcg/external/lhapdfsets/current','atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
956  mglog.info('linking '+atlasLHADATAPATH+'/lhapdf.conf --> '+newMGCLHA+'lhapdf.conf')
957  os.symlink(atlasLHADATAPATH+'/lhapdf.conf',newMGCLHA+'lhapdf.conf')
958  else:
959  mglog.info('copying '+LHADATAPATH+'/pdfsets.index --> '+newMGCLHA+'pdfsets.index')
960  shutil.copy2(LHADATAPATH+'/pdfsets.index',newMGCLHA+'pdfsets.index')
961 
962  atlasLHADATAPATH=LHADATAPATH.replace('sft.cern.ch/lcg/external/lhapdfsets/current','atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
963  mglog.info('copying '+atlasLHADATAPATH+'/lhapdf.conf -->'+newMGCLHA+'lhapdf.conf')
964  shutil.copy2(atlasLHADATAPATH+'/lhapdf.conf',newMGCLHA+'lhapdf.conf')
965 
966 
967  LHADATAPATH=os.getcwd()+'/MGC_LHAPDF'
968 
969  else:
970  mglog.info('Not using LHAPDF')
971  return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
972 
973 
974  if isNLO:
975  os.environ['LHAPDF_DATA_PATH']=LHADATAPATH
976 
977  mglog.info('Path to LHAPDF install dir: '+LHAPATH)
978  mglog.info('Path to LHAPDF data dir: '+LHADATAPATH)
979  if not os.path.isdir(LHADATAPATH):
980  raise RuntimeError('LHAPDF data dir not accesible: '+LHADATAPATH)
981  if not os.path.isdir(LHAPATH):
982  raise RuntimeError('LHAPDF path dir not accesible: '+LHAPATH)
983 
984  # Dealing with LHAPDF
985  if extlhapath:
986  lhapdfconfig=extlhapath
987  if not os.access(lhapdfconfig,os.X_OK):
988  raise RuntimeError('Failed to find valid external lhapdf-config at '+lhapdfconfig)
989  LHADATAPATH=subprocess.Popen([lhapdfconfig, '--datadir'],stdout = subprocess.PIPE).stdout.read().strip()
990  mglog.info('Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
991  os.environ['LHAPDF_DATA_PATH']=LHADATAPATH
992  else:
993  getlhaconfig = subprocess.Popen(['get_files','-data','lhapdf-config'])
994  getlhaconfig.wait()
995  #Get custom lhapdf-config
996  if not os.access(os.getcwd()+'/lhapdf-config',os.X_OK):
997  mglog.error('Failed to get lhapdf-config from MadGraphControl')
998  return 1
999  lhapdfconfig = os.getcwd()+'/lhapdf-config'
1000 
1001  mglog.info('lhapdf-config --version: '+str(subprocess.Popen([lhapdfconfig, '--version'],stdout = subprocess.PIPE).stdout.read().strip()))
1002  mglog.info('lhapdf-config --prefix: '+str(subprocess.Popen([lhapdfconfig, '--prefix'],stdout = subprocess.PIPE).stdout.read().strip()))
1003  mglog.info('lhapdf-config --libdir: '+str(subprocess.Popen([lhapdfconfig, '--libdir'],stdout = subprocess.PIPE).stdout.read().strip()))
1004  mglog.info('lhapdf-config --datadir: '+str(subprocess.Popen([lhapdfconfig, '--datadir'],stdout = subprocess.PIPE).stdout.read().strip()))
1005  mglog.info('lhapdf-config --pdfsets-path: '+str(subprocess.Popen([lhapdfconfig, '--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().strip()))
1006 
1007  modify_config_card(process_dir=process_dir,settings={'lhapdf':lhapdfconfig,'lhapdf_py3':lhapdfconfig})
1008 
1009  mglog.info('Creating links for LHAPDF')
1010  if os.path.islink(process_dir+'/lib/PDFsets'):
1011  os.unlink(process_dir+'/lib/PDFsets')
1012  elif os.path.isdir(process_dir+'/lib/PDFsets'):
1013  shutil.rmtree(process_dir+'/lib/PDFsets')
1014  if allow_links:
1015  os.symlink(LHADATAPATH,process_dir+'/lib/PDFsets')
1016  else:
1017  shutil.copytree(LHADATAPATH,process_dir+'/lib/PDFsets')
1018  mglog.info('Available PDFs are:')
1019  mglog.info( sorted( [ x for x in os.listdir(process_dir+'/lib/PDFsets') if ".tar.gz" not in x ] ) )
1020 
1021  global MADGRAPH_COMMAND_STACK
1022  MADGRAPH_COMMAND_STACK += [ '# Copy the LHAPDF files locally' ]
1023  MADGRAPH_COMMAND_STACK += [ 'cp -r '+os.getcwd()+'/MGC_LHAPDF .' ]
1024  MADGRAPH_COMMAND_STACK += [ 'cp -r '+process_dir+'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
1025 
1026  return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
1027 
1028 
1029 # 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 41 of file MadGraphUtils.py.

41 def stack_subprocess(command,**kwargs):
42  global MADGRAPH_COMMAND_STACK
43  MADGRAPH_COMMAND_STACK += [' '.join(command)]
44  return subprocess.Popen(command,**kwargs)
45 
46 

◆ 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 1776 of file MadGraphUtils.py.

1776 def SUSY_Generation(runArgs = None, process=None, plugin=None,\
1777  syst_mod=None, keepOutput=False, param_card=None, writeGridpack=False,\
1778  madspin_card=None, run_settings={}, params={}, fixEventWeightsForBridgeMode=False, add_lifetimes_lhe=False, usePMGSettings=True):
1779 
1780  """
1781  Keyword Arguments:
1782  usePMGSettings (bool): See :py:func:`new_process`. Will set SM parameters to the appropriate values. Default: True.
1783  """
1784  ktdurham = run_settings['ktdurham'] if 'ktdurham' in run_settings else None
1785  ktdurham , alpsfact , scalefact = get_SUSY_variations( process, params['MASS'] , syst_mod , ktdurham=ktdurham )
1786 
1787  process_dir = MADGRAPH_GRIDPACK_LOCATION
1788  if not is_gen_from_gridpack():
1789  full_proc = SUSY_process(process)
1790  process_dir = new_process(full_proc, plugin=plugin, usePMGSettings=usePMGSettings)
1791  mglog.info('Using process directory '+str(process_dir))
1792 
1793  # Grab the param card and move the new masses into place
1794  modify_param_card(param_card_input=param_card,process_dir=process_dir,params=params)
1795 
1796  # Set up the extras dictionary
1797  settings = {'ktdurham':ktdurham,'scalefact':scalefact,'alpsfact':alpsfact}
1798  settings.update(run_settings) # This allows explicit settings in the input to override these settings
1799 
1800  # Set up the run card
1801  modify_run_card(process_dir=process_dir,runArgs=runArgs,settings=settings)
1802 
1803  # Set up madspin if needed
1804  if madspin_card is not None:
1805  if not os.access(madspin_card,os.R_OK):
1806  raise RuntimeError('Could not locate madspin card at '+str(madspin_card))
1807  shutil.copy(madspin_card,process_dir+'/Cards/madspin_card.dat')
1808 
1809  # Generate events!
1810  if is_gen_from_gridpack():
1811  generate_from_gridpack(runArgs=runArgs)
1812  else:
1813  # Grab the run card and move it into place
1814  generate(runArgs=runArgs,process_dir=process_dir,grid_pack=writeGridpack)
1815 
1816  # Add lifetimes to LHE before arranging output if requested
1817  if add_lifetimes_lhe :
1818  mglog.info('Requested addition of lifetimes to LHE files: doing so now.')
1819  if is_gen_from_gridpack():
1820  add_lifetimes()
1821  else:
1822  add_lifetimes(process_dir=process_dir)
1823 
1824  # Move output files into the appropriate place, with the appropriate name
1825  arrange_output(process_dir=process_dir,saveProcDir=keepOutput,runArgs=runArgs,fixEventWeightsForBridgeMode=fixEventWeightsForBridgeMode)
1826 
1827  mglog.info('All done generating events!!')
1828  return settings['ktdurham']
1829 
1830 

◆ SUSY_process()

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

Definition at line 1746 of file MadGraphUtils.py.

1746 def SUSY_process(process=''):
1747  # Generate the new process!
1748  if 'import model' in process:
1749  mglog.info('Assuming that you have specified the model in your process string already')
1750  full_proc = ''
1751  for l in process.split('\n'):
1752  if 'import model' in l:
1753  full_proc += l+'\n'
1754  break
1755  # Only magically add helpful definitions if we are in the right model
1756  if 'MSSM_SLHA2' in full_proc:
1757  full_proc+=helpful_SUSY_definitions()
1758  for l in process.split('\n'):
1759  if 'import model' not in l:
1760  full_proc += l+'\n'
1761  full_proc+="""
1762 # Output processes to MadEvent directory
1763 output -f
1764 """
1765  else:
1766  full_proc = "import model MSSM_SLHA2\n"+helpful_SUSY_definitions()+"""
1767 # Specify process(es) to run
1768 
1769 """+process+"""
1770 # Output processes to MadEvent directory
1771 output -f
1772 """
1773  return full_proc
1774 
1775 

◆ 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 1831 of file MadGraphUtils.py.

1831 def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1832  """Build a new LHE file from an old one and an updated param card.
1833  The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1834  may have their masses changed.
1835  If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1836  By default, the old LHE file is removed.
1837  If None is provided as a new LHE file name, the new file will replace the old one."""
1838  # If we want to just use a temp file, then put in a little temp holder
1839  lhe_file_new_tmp = lhe_file_new if lhe_file_new is not None else lhe_file_old+'.tmp'
1840  # Make sure the LHE file is there
1841  if not os.access(lhe_file_old,os.R_OK):
1842  raise RuntimeError('Could not access old LHE file at '+str(lhe_file_old)+'. Please check the file location.')
1843  # Grab the old param card
1844  if param_card_old is not None:
1845  paramcard = subprocess.Popen(['get_files','-data',param_card_old])
1846  paramcard.wait()
1847  if not os.access(param_card_old,os.R_OK):
1848  raise RuntimeError('Could not get param card '+param_card_old)
1849  # Don't overwrite old param cards
1850  if os.access(lhe_file_new_tmp,os.R_OK):
1851  raise RuntimeError('Old file at'+str(lhe_file_new_tmp)+' in the current directory. Dont want to clobber it. Please move it first.')
1852 
1853  newlhe = open(lhe_file_new_tmp,'w')
1854  blockName = None
1855  decayEdit = False
1856  eventRead = False
1857  particles_in_events = []
1858  # Decay block ends with </slha>
1859 
1860  with open(lhe_file_old,'r') as fileobject:
1861  for line in fileobject:
1862  if decayEdit and '</slha>' not in line:
1863  continue
1864  if decayEdit and '</slha>' in line:
1865  decayEdit = False
1866  if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
1867  and len(line.strip().split()) > 1:
1868  pos = 0 if line.strip().startswith('DECAY') else 1
1869  blockName = line.strip().upper().split()[pos]
1870 
1871  akey = None
1872  if blockName != 'DECAY' and len(line.strip().split()) > 0:
1873  akey = line.strip().split()[0]
1874  elif blockName == 'DECAY' and len(line.strip().split()) > 1:
1875  akey = line.strip().split()[1]
1876 
1877  # Replace the masses with those in the dictionary
1878  if akey is not None and blockName == 'MASS' and akey in masses:
1879  newlhe.write(' '+akey+' '+str(masses[akey])+' # \n')
1880  mglog.info(' '+akey+' '+str(masses[akey])+' #')
1881  decayEdit = False
1882  continue
1883 
1884  # Replace the entire decay section of the LHE file with the one from the param card
1885  if blockName == 'DECAY' and param_card_old is not None:
1886  # We are now reading the decay blocks! Take them from the param card
1887  oldparam = open(param_card_old,'r')
1888  newDecays = False
1889  for old_line in oldparam.readlines():
1890  newBlockName = None
1891  if old_line.strip().upper().startswith('DECAY') and len(old_line.strip().split()) > 1:
1892  newBlockName = line.strip().upper().split()[pos]
1893  if newDecays:
1894  newlhe.write(old_line)
1895  elif newBlockName == 'DECAY':
1896  newDecays = True
1897  newlhe.write(old_line)
1898  oldparam.close()
1899  # Done adding the decays
1900  decayEdit = True
1901  blockName = None
1902  continue
1903 
1904  # Keep a record of the particles that are in the events
1905  if not eventRead and '<event>' in line:
1906  eventRead = True
1907  if eventRead:
1908  if len(line.split())==11:
1909  aparticle = line.split()[0]
1910  if aparticle not in particles_in_events:
1911  particles_in_events += [aparticle]
1912 
1913  # Otherwise write the line again
1914  newlhe.write(line)
1915 
1916  # Check that none of the particles that we were setting the masses of appear in the LHE events
1917  for akey in masses:
1918  if akey in particles_in_events:
1919  mglog.error('Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1920  return -1
1921 
1922  # Close up and return
1923  newlhe.close()
1924 
1925  # Move the new file to the old file location
1926  if lhe_file_new is None:
1927  os.remove(lhe_file_old)
1928  shutil.move(lhe_file_new_tmp,lhe_file_old)
1929  lhe_file_new_tmp = lhe_file_old
1930  # Delete the old file if requested
1931  elif delete_old_lhe:
1932  os.remove(lhe_file_old)
1933 
1934  return lhe_file_new_tmp
1935 
1936 

◆ write_test_script()

def python.MadGraphUtils.write_test_script ( )

Definition at line 198 of file MadGraphUtils.py.

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

Variable Documentation

◆ MADGRAPH_CATCH_ERRORS

bool python.MadGraphUtils.MADGRAPH_CATCH_ERRORS = True

Definition at line 20 of file MadGraphUtils.py.

◆ MADGRAPH_COMMAND_STACK

list python.MadGraphUtils.MADGRAPH_COMMAND_STACK = []

Definition at line 23 of file MadGraphUtils.py.

◆ MADGRAPH_GRIDPACK_LOCATION

string python.MadGraphUtils.MADGRAPH_GRIDPACK_LOCATION = 'madevent'

Definition at line 16 of file MadGraphUtils.py.

◆ MADGRAPH_PDFSETTING

python.MadGraphUtils.MADGRAPH_PDFSETTING = None

Definition at line 22 of file MadGraphUtils.py.

◆ MADGRAPH_RUN_NAME

string python.MadGraphUtils.MADGRAPH_RUN_NAME = 'run_01'

Definition at line 18 of file MadGraphUtils.py.

◆ mglog

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

Definition at line 11 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 25 of file MadGraphUtils.py.

◆ python

string python.MadGraphUtils.python = 'python'

Definition at line 14 of file MadGraphUtils.py.

python.MadGraphUtils.check_reset_proc_number
def check_reset_proc_number(opts)
Definition: MadGraphUtils.py:2577
replace
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition: hcg.cxx:307
python.MadGraphUtils.is_NLO_run
def is_NLO_run(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2423
max
#define max(a, b)
Definition: cfImp.cxx:41
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:41
python.MadGraphParamHelpers.do_PMG_updates
def do_PMG_updates(process_dir)
Definition: MadGraphParamHelpers.py:144
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:2019
python.MadGraphUtils.arrange_output
def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION, lhe_version=None, saveProcDir=False, runArgs=None, fixEventWeightsForBridgeMode=False)
Definition: MadGraphUtils.py:1247
python.MadGraphUtilsHelpers.get_runArgs_info
def get_runArgs_info(runArgs)
Definition: MadGraphUtilsHelpers.py:94
python.MadGraphUtils.setupLHAPDF
def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True)
Definition: MadGraphUtils.py:883
python.MadGraphUtils.get_LHAPDF_PATHS
def get_LHAPDF_PATHS()
Definition: MadGraphUtils.py:832
python.MadGraphUtils.ls_dir
def ls_dir(directory)
Definition: MadGraphUtils.py:2588
python.MadGraphUtils.remap_lhe_pdgids
def remap_lhe_pdgids(lhe_file_old, lhe_file_new=None, pdgid_map={}, delete_old_lhe=True)
Definition: MadGraphUtils.py:1937
python.MadGraphUtilsHelpers.checkSetting
def checkSetting(key_, value_, mydict_)
Definition: MadGraphUtilsHelpers.py:33
python.MadGraphUtils.resetLHAPDF
def resetLHAPDF(origLHAPATH='', origLHAPDF_DATA_PATH='')
Definition: MadGraphUtils.py:1043
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:1831
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:2391
python.MadGraphUtils.new_process
def new_process(process='generate p p > t t~\noutput -f', plugin=None, keepJpegs=False, usePMGSettings=False)
Definition: MadGraphUtils.py:216
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:2272
python.MadGraphUtils.setup_path_protection
def setup_path_protection()
Definition: MadGraphUtils.py:47
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:1776
python.MadGraphUtils.check_reweight_card
def check_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:1615
python.MadGraphUtils.config_only_check
def config_only_check()
Definition: MadGraphUtils.py:67
python.MadGraphUtils.get_default_runcard
def get_default_runcard(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:353
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
python.MadGraphUtils.write_test_script
def write_test_script()
Definition: MadGraphUtils.py:198
python.MadGraphUtils.error_check
def error_check(errors_a, return_code)
Definition: MadGraphUtils.py:103
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:385
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:2334
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:2379
python.MadGraphUtils.get_lhapdf_id_and_name
def get_lhapdf_id_and_name(pdf)
Definition: MadGraphUtils.py:849
min
#define min(a, b)
Definition: cfImp.cxx:40
python.MadGraphUtils.get_expected_systematic_names
def get_expected_systematic_names(syst_setting)
Definition: MadGraphUtils.py:1541
python.MadGraphUtils.add_madspin
def add_madspin(madspin_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:1102
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:78
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:2167
python.MadGraphUtils.setup_bias_module
def setup_bias_module(bias_module, process_dir)
Definition: MadGraphUtils.py:1559
python.MadGraphUtils.run_card_consistency_check
def run_card_consistency_check(isNLO=False, process_dir='.')
Definition: MadGraphUtils.py:2430
python.MadGraphUtils.setupFastjet
def setupFastjet(process_dir=None)
Definition: MadGraphUtils.py:797
generate
Definition: generate.cxx:28
python.MadGraphUtilsHelpers.checkSettingExists
def checkSettingExists(key_, mydict_)
Definition: MadGraphUtilsHelpers.py:48
Trk::open
@ open
Definition: BinningType.h:40
python.MadGraphUtils.fix_fks_makefile
def fix_fks_makefile(process_dir)
Definition: MadGraphUtils.py:2596
python.MadGraphUtils.setNCores
def setNCores(process_dir, Ncores=None)
Definition: MadGraphUtils.py:1030
python.MadGraphUtils.generate_from_gridpack
def generate_from_gridpack(runArgs=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False)
Definition: MadGraphUtils.py:595
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.MadGraphUtils.get_expected_reweight_names
def get_expected_reweight_names(reweight_card_loc)
Definition: MadGraphUtils.py:1525
python.MadGraphUtils.get_mg5_executable
def get_mg5_executable()
Definition: MadGraphUtils.py:1051
python.MadGraphUtils.get_cluster_type
def get_cluster_type(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2412
str
Definition: BTagTrackIpAccessor.cxx:11
python.MadGraphUtils.get_reweight_card
def get_reweight_card(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:1609
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:1159
python.MadGraphUtils.get_SUSY_variations
def get_SUSY_variations(process, masses, syst_mod, ktdurham=None)
Definition: MadGraphUtils.py:1678
python.MadGraphUtils.print_cards_from_dir
def print_cards_from_dir(process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2328
python.MadGraphUtils.add_reweighting
def add_reweighting(run_name, reweight_card=None, process_dir=MADGRAPH_GRIDPACK_LOCATION)
Definition: MadGraphUtils.py:2565
python.MadGraphUtils.stack_subprocess
def stack_subprocess(command, **kwargs)
Definition: MadGraphUtils.py:41
python.MadGraphUtils.add_lifetimes
def add_lifetimes(process_dir, threshold=None)
Definition: MadGraphUtils.py:1058
python.MadGraphUtils.find_key_and_update
def find_key_and_update(akey, dictionary)
Definition: MadGraphUtils.py:2004
python.MadGraphUtils.SUSY_process
def SUSY_process(process='')
Definition: MadGraphUtils.py:1746
readCCLHist.float
float
Definition: readCCLHist.py:83
Trk::split
@ split
Definition: LayerMaterialProperties.h:38
python.MadGraphUtilsHelpers.get_physics_short
def get_physics_short()
Definition: MadGraphUtilsHelpers.py:107
python.MadGraphUtilsHelpers.getDictFromCard
def getDictFromCard(card_loc, lowercase=False)
Definition: MadGraphUtilsHelpers.py:3
python.MadGraphUtilsHelpers.is_version_or_newer
def is_version_or_newer(args)
Definition: MadGraphUtilsHelpers.py:55
python.MadGraphUtils.get_LHAPDF_DATA_PATH
def get_LHAPDF_DATA_PATH()
Definition: MadGraphUtils.py:828
python.MadGraphUtils.helpful_SUSY_definitions
def helpful_SUSY_definitions()
Definition: MadGraphUtils.py:1651