ATLAS Offline Software
Loading...
Searching...
No Matches
python.MadGraphUtilsHelpers Namespace Reference

Functions

 settingIsTrue (setting)
 get_mg5_version ()
 is_version_or_newer (args)
 isNLO_from_run_card (run_card)
 error_check (errors_a, return_code)
 write_test_script ()
 modify_param_card (param_card_input=None, param_card_backup=None, process_dir=MADGRAPH_GRIDPACK_LOCATION, params={}, output_location=None)
 find_key_and_update (akey, dictionary)

Variables

 mglog = Logging.logging.getLogger('MadGraphUtils')
str MADGRAPH_GRIDPACK_LOCATION = 'madevent'
bool MADGRAPH_CATCH_ERRORS = True
list MADGRAPH_COMMAND_STACK = []

Function Documentation

◆ error_check()

python.MadGraphUtilsHelpers.error_check ( errors_a,
return_code )

Definition at line 72 of file MadGraphUtilsHelpers.py.

72def error_check(errors_a, return_code):
73 if not MADGRAPH_CATCH_ERRORS:
74 return
75 unmasked_error = False
76 my_debug_file = None
77 bad_variables = []
78 # Make sure we are getting a string and not a byte string (python3 ftw)
79 errors = errors_a
80 if type(errors)==bytes:
81 errors = errors.decode('utf-8')
82 if len(errors):
83 mglog.info('Some errors detected by MadGraphControl - checking for serious errors')
84 for err in errors.split('\n'):
85 if len(err.strip())==0:
86 continue
87 # Errors to do with I/O... not clear on their origin yet
88 if 'Inappropriate ioctl for device' in err:
89 mglog.info(err)
90 continue
91 if 'stty: standard input: Invalid argument' in err:
92 mglog.info(err)
93 continue
94 # Errors for PDF sets that should be fixed in MG5_aMC 2.7
95 if 'PDF already installed' in err:
96 mglog.info(err)
97 continue
98 if 'Read-only file system' in err:
99 mglog.info(err)
100 continue
101 if 'HTML' in err:
102 # https://bugs.launchpad.net/mg5amcnlo/+bug/1870217
103 mglog.info(err)
104 continue
105 if 'impossible to set default multiparticles' in err:
106 # https://answers.launchpad.net/mg5amcnlo/+question/690004
107 mglog.info(err)
108 continue
109 if 'More information is found in' in err:
110 my_debug_file = err.split("'")[1]
111 if err.startswith('tar'):
112 mglog.info(err)
113 continue
114 if 'python2 support will be removed' in err:
115 mglog.info(err)
116 continue
117 if 'python3.12 support is still experimental' in err:
118 mglog.info(err)
119 continue
120 # Another new python 3.12 message in MG5_aMC 3.6
121 if 'python3.12+ support: For reweighting feature, please use 3.6.X release.' in err:
122 mglog.info(err)
123 continue
124 # silly ghostscript issue in 21.6.46 nightly
125 if 'required by /lib64/libfontconfig.so' in err or\
126 'required by /lib64/libgs.so' in err:
127 mglog.info(err)
128 continue
129 if 'Error: Symbol' in err and 'has no IMPLICIT type' in err:
130 bad_variables += [ err.split('Symbol ')[1].split(' at ')[0] ]
131 # error output from tqdm (progress bar)
132 if 'it/s' in err:
133 mglog.info(err)
134 continue
135 mglog.error(err)
136 unmasked_error = True
137 # This is a bit clunky, but needed because we could be several places when we get here
138 if my_debug_file is None:
139 debug_files = glob.glob('*debug.log')+glob.glob('*/*debug.log')
140 for debug_file in debug_files:
141 # This protects against somebody piping their output to my_debug.log and it being caught here
142 has_subproc = os.access(os.path.join(os.path.dirname(debug_file),'SubProcesses'),os.R_OK)
143 if has_subproc:
144 my_debug_file = debug_file
145 break
146
147 if my_debug_file is not None:
148 if not unmasked_error:
149 mglog.warning('Found a debug file at '+my_debug_file+' but no apparent error. Will terminate.')
150 mglog.error('MadGraph5_aMC@NLO appears to have crashed. Debug file output follows.')
151 with open(my_debug_file,'r') as error_output:
152 for l in error_output:
153 mglog.error(l.replace('\n',''))
154 mglog.error('End of debug file output')
155
156 if bad_variables:
157 mglog.warning('Appeared to detect variables in your run card that MadGraph did not understand:')
158 mglog.warning(' Check your run card / JO settings for %s',bad_variables)
159
160 # Check the return code
161 if return_code!=0:
162 mglog.error(f'Detected a bad return code: {return_code}')
163 unmasked_error = True
164
165 # Now raise an error if we were in either of the error states
166 if unmasked_error or my_debug_file is not None:
167 write_test_script()
168 raise RuntimeError('Error detected in MadGraphControl process')
169 return
170
171
172# Write a short test script for standalone debugging
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177

◆ find_key_and_update()

python.MadGraphUtilsHelpers.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 336 of file MadGraphUtilsHelpers.py.

336def find_key_and_update(akey,dictionary):
337 """ Helper function when looking at param cards
338 In some cases it's tricky to match keys - they may differ
339 only in white space. This tries to sort out when we have
340 a match, and then uses the one in blockParams afterwards.
341 In the case of no match, it returns the original key.
342 """
343 test_key = ' '.join(akey.strip().replace('\t',' ').split())
344 for key in dictionary:
345 mod_key = ' '.join(key.strip().replace('\t',' ').split())
346 if mod_key==test_key:
347 return key
348 return akey
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:310

◆ get_mg5_version()

python.MadGraphUtilsHelpers.get_mg5_version ( )
Return MadGraph version string (e.g. '3.5.1')

Used to include MG version in gridpack names for better traceability.
Reads version from $MADPATH/VERSION file.

Definition at line 21 of file MadGraphUtilsHelpers.py.

21def get_mg5_version():
22 """Return MadGraph version string (e.g. '3.5.1')
23
24 Used to include MG version in gridpack names for better traceability.
25 Reads version from $MADPATH/VERSION file.
26 """
27 with open(os.environ['MADPATH']+'/VERSION','r') as version_file:
28 for line in version_file:
29 if 'version' in line:
30 return line.split('=')[1].strip()
31 raise RuntimeError('Failed to find MadGraph/MadGraph5_aMC@NLO version')
32

◆ is_version_or_newer()

python.MadGraphUtilsHelpers.is_version_or_newer ( args)

Definition at line 33 of file MadGraphUtilsHelpers.py.

33def is_version_or_newer(args):
34 # also need to find out the version (copied from generate)
35 import os
36 version=None
37 version_file = open(os.environ['MADPATH']+'/VERSION','r')
38
39 for line in version_file:
40 if 'version' in line:
41 version=line.split('=')[1].strip()
42 version_file.close()
43
44 if not version:
45 raise RuntimeError('Failed to find MadGraph/MadGraph5_aMC@NLO version in '+version_file)
46
47 vs=[int(v) for v in version.split('.')]
48
49 # this is lazy, let's hope there wont be a subversion > 100...
50 y=int(100**max(len(vs),len(args)))
51 testnumber=0
52 for x in args:
53 testnumber+=x*y
54 y/=100
55
56 y=int(100**max(len(vs),len(args)))
57 versionnumber=0
58 for x in vs:
59 versionnumber+=x*y
60 y/=100
61 return versionnumber>=testnumber
62
#define max(a, b)
Definition cfImp.cxx:41

◆ isNLO_from_run_card()

python.MadGraphUtilsHelpers.isNLO_from_run_card ( run_card)

Definition at line 63 of file MadGraphUtilsHelpers.py.

63def isNLO_from_run_card(run_card):
64 f = open(run_card,'r')
65 if "parton_shower" in f.read().lower():
66 f.close()
67 return True
68 else:
69 f.close()
70 return False
71

◆ modify_param_card()

python.MadGraphUtilsHelpers.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 189 of file MadGraphUtilsHelpers.py.

189def modify_param_card(param_card_input=None,param_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,params={},output_location=None):
190 """Build a new param_card.dat from an existing one.
191 Params should be a dictionary of dictionaries. The first key is the block name, and the second in the param name.
192 Keys can include MASS (for masses) and DECAY X (for decays of particle X)"""
193 # Grab the old param card and move it into place
194
195 # Check for the default run card location
196 if param_card_input is None:
197 param_card_input=process_dir+'/Cards/param_card.dat'
198 elif param_card_input is not None and not os.access(param_card_input,os.R_OK):
199 paramcard = subprocess.Popen(['get_files','-data',param_card_input])
200 paramcard.wait()
201 if not os.access(param_card_input,os.R_OK):
202 raise RuntimeError('Could not get param card '+param_card_input)
203 mglog.info('Using input param card at '+param_card_input)
204
205 #ensure all blocknames and paramnames are upper case
206 paramsUpper = {}
207 for blockName in list(params.keys()):
208 paramsUpper[blockName.upper()] = {}
209 for paramName in list(params[blockName].keys()):
210 paramsUpper[blockName.upper()][paramName.upper()] = params[blockName][paramName]
211
212 if param_card_backup is not None:
213 mglog.info('Keeping backup of original param card at '+param_card_backup)
214 param_card_old = param_card_backup
215 else:
216 param_card_old = param_card_input+'.old_to_be_deleted'
217 if os.path.isfile(param_card_old):
218 os.unlink(param_card_old) # delete old backup
219 os.rename(param_card_input, param_card_old) # change name of original card
220
221 oldcard = open(param_card_old,'r')
222 param_card_location= process_dir+'/Cards/param_card.dat' if output_location is None else output_location
223 newcard = open(param_card_location,'w')
224 decayEdit = False #only becomes true in a DECAY block when specifying the BR
225 blockName = ""
226 doneParams = {} #tracks which params have been done
227 for linewithcomment in oldcard:
228 line=linewithcomment.split('#')[0]
229 if line.strip().upper().startswith('BLOCK') or line.strip().upper().startswith('DECAY')\
230 and len(line.strip().split()) > 1:
231 if decayEdit and blockName == 'DECAY':
232 decayEdit = False # Start a new DECAY block
233 pos = 0 if line.strip().startswith('DECAY') else 1
234 if blockName=='MASS' and 'MASS' in paramsUpper:
235 # Any residual masses to set?
236 if "MASS" in doneParams:
237 leftOvers = [ x for x in paramsUpper['MASS'] if x not in doneParams['MASS'] ]
238 else:
239 leftOvers = [ x for x in paramsUpper['MASS'] ]
240
241 for pdg_id in leftOvers:
242 mglog.warning('Adding mass line for '+str(pdg_id)+' = '+str(paramsUpper['MASS'][pdg_id])+' which was not in original param card')
243 newcard.write(' '+str(pdg_id)+' '+str(paramsUpper['MASS'][pdg_id])+'\n')
244 doneParams['MASS'][pdg_id]=True
245 if blockName=='DECAY' and 'DECAY' not in line.strip().upper() and 'DECAY' in paramsUpper:
246 # Any residual decays to include?
247 leftOvers = [ x for x in paramsUpper['DECAY'] if x not in doneParams['DECAY'] ]
248 for pdg_id in leftOvers:
249 mglog.warning('Adding decay for pdg id '+str(pdg_id)+' which was not in the original param card')
250 newcard.write( paramsUpper['DECAY'][pdg_id].strip()+'\n' )
251 doneParams['DECAY'][pdg_id]=True
252 blockName = line.strip().upper().split()[pos]
253 if decayEdit:
254 continue #skipping these lines because we are in an edit of the DECAY BR
255
256 akey = None
257 if blockName != 'DECAY' and len(line.strip().split()) > 0:
258 # The line is already without the comment.
259 # In the case of mixing matrices this is a bit tricky
260 if len(line.split())==2:
261 akey = line.upper().strip().split()[0]
262 else:
263 # Take everything but the last word
264 akey = line.upper().strip()[:line.strip().rfind(' ')].strip()
265 elif blockName == 'DECAY' and len(line.strip().split()) > 1:
266 akey = line.strip().split()[1]
267 if akey is None:
268 newcard.write(linewithcomment)
269 continue
270
271 #check if we have params for this block
272 if blockName not in paramsUpper:
273 newcard.write(linewithcomment)
274 continue
275 blockParams = paramsUpper[blockName]
276 # Check the spacing in the key
277 akey = find_key_and_update(akey,blockParams)
278
279 # look for a string key, which would follow a #
280 stringkey = None
281 if '#' in linewithcomment: #ignores comment lines
282 stringkey = linewithcomment[linewithcomment.find('#')+1:].strip()
283 if len(stringkey.split()) > 0:
284 stringkey = stringkey.split()[0].upper()
285
286 if akey not in blockParams and not (stringkey is not None and stringkey in blockParams):
287 newcard.write(linewithcomment)
288 continue
289
290 if akey in blockParams and (stringkey is not None and stringkey in blockParams):
291 raise RuntimeError('Conflicting use of numeric and string keys '+akey+' and '+stringkey)
292
293 theParam = blockParams.get(akey,blockParams[stringkey] if stringkey in blockParams else None)
294 if blockName not in doneParams:
295 doneParams[blockName] = {}
296 if akey in blockParams:
297 doneParams[blockName][akey]=True
298 elif stringkey is not None and stringkey in blockParams:
299 doneParams[blockName][stringkey]=True
300
301 #do special case of DECAY block
302 if blockName=="DECAY":
303 if theParam.splitlines()[0].split()[0].upper()=="DECAY":
304 #specifying the full decay block
305 for newline in theParam.splitlines():
306 newcard.write(newline+'\n')
307 mglog.info(newline)
308 decayEdit = True
309 else: #just updating the total width
310 newcard.write('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
311 mglog.info('DECAY '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
312 # second special case of QNUMBERS
313 elif blockName=='QNUMBERS':
314 #specifying the full QNUMBERS block
315 for newline in theParam.splitlines():
316 newcard.write(newline+'\n')
317 mglog.info(newline)
318 decayEdit = True
319 else: #just updating the parameter
320 newcard.write(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
321 mglog.info(' '+akey+' '+str(theParam)+' # '+(linewithcomment[linewithcomment.find('#')+1:].strip() if linewithcomment.find('#')>0 else "")+'\n')
322 # Done editing the line!
323
324 #check that all specified parameters have been updated (helps to catch typos)
325 for blockName in paramsUpper:
326 if blockName not in doneParams and len(paramsUpper[blockName].keys())>0:
327 raise RuntimeError('Did not find any of the parameters for block '+blockName+' in param_card')
328 for paramName in paramsUpper[blockName]:
329 if paramName not in doneParams[blockName]:
330 raise RuntimeError('Was not able to replace parameter '+paramName+' in param_card')
331
332 # Close up and return
333 oldcard.close()
334 newcard.close()
335
int upper(int c)

◆ settingIsTrue()

python.MadGraphUtilsHelpers.settingIsTrue ( setting)

Definition at line 16 of file MadGraphUtilsHelpers.py.

16def settingIsTrue(setting):
17 if setting.replace("'",'').replace('"','').replace('.','').lower() in ['t','true']:
18 return True
19 return False
20

◆ write_test_script()

python.MadGraphUtilsHelpers.write_test_script ( )

Definition at line 173 of file MadGraphUtilsHelpers.py.

173def write_test_script():
174 mglog.info('Will write a stand-alone debugging script.')
175 mglog.info('This is an attempt to provide you commands that you can use')
176 mglog.info('to reproduce the error locally. If you make additional')
177 mglog.info('modifications by hand (not using MadGraphControl) in your JO,')
178 mglog.info('make sure that you check and modify the script as needed.\n\n')
179 mglog.info('# Script start; trim off columns left of the "#"')
180 # Write offline stand-alone reproduction script
181 with open('standalone_script.sh','w') as standalone_script:
182 for command in MADGRAPH_COMMAND_STACK:
183 for line in command.split('\n'):
184 mglog.info(line)
185 standalone_script.write(line+'\n')
186 mglog.info('# Script end')
187 mglog.info('Script also written to %s/standalone_script.sh',os.getcwd())
188

Variable Documentation

◆ MADGRAPH_CATCH_ERRORS

bool python.MadGraphUtilsHelpers.MADGRAPH_CATCH_ERRORS = True

Definition at line 11 of file MadGraphUtilsHelpers.py.

◆ MADGRAPH_COMMAND_STACK

list python.MadGraphUtilsHelpers.MADGRAPH_COMMAND_STACK = []

Definition at line 12 of file MadGraphUtilsHelpers.py.

◆ MADGRAPH_GRIDPACK_LOCATION

str python.MadGraphUtilsHelpers.MADGRAPH_GRIDPACK_LOCATION = 'madevent'

Definition at line 9 of file MadGraphUtilsHelpers.py.

◆ mglog

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

Definition at line 6 of file MadGraphUtilsHelpers.py.