101def 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):
102 global my_MGC_instance
106 my_MGC_instance.setup_path_protection()
111 if 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
112 njobs = int(os.environ[
'ATHENA_CORE_NUMBER'])
113 mglog.info(
'Lucky you - you are running on a full node queue. Will re-configure for '+str(njobs)+
' jobs.')
117 if cluster_type
is not None:
121 mglog.info(
'Running event generation from gridpack (using smarter mode from generate() function)')
122 generate_from_gridpack(runArgs=runArgs,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings)
125 mglog.info(
'Did not identify an input gridpack.')
127 mglog.info(
'The grid_pack flag is set, so I am expecting to create a gridpack in this job')
133 isNLO = my_MGC_instance.isNLO
145 if shutil.which(
'f2py')
is not None:
146 mglog.info(
'Found f2py, will use it for reweighting')
148 raise RuntimeError(
'Could not find f2py, needed for reweighting')
151 global MADGRAPH_COMMAND_STACK
155 mglog.info(
'Started generating gridpack at '+str(time.asctime()))
156 mglog.warning(
' >>>>>> THIS KIND OF JOB SHOULD ONLY BE RUN LOCALLY - NOT IN GRID JOBS <<<<<<')
159 my_settings = {
'nevents':
'1000'}
162 my_settings[
'req_acc']=str(required_accuracy)
165 LO_has_madspin =
False
166 if os.access(f
'{process_dir}/Cards/madspin_card.dat',os.R_OK):
167 MADGRAPH_COMMAND_STACK += [f
'mv {process_dir}/Cards/madspin_card.dat {process_dir}/Cards/madspin_card.tmp.dat']
168 os.rename(f
'{process_dir}/Cards/madspin_card.dat',f
'{process_dir}/Cards/madspin_card.tmp.dat')
169 LO_has_madspin =
True
170 my_settings = {
'gridpack':
'true'}
171 my_MGC_instance.runCardDict.update(my_settings)
174 mglog.info(
'Started generating at '+str(time.asctime()))
176 mglog.info(
'Run '+MADGRAPH_RUN_NAME+
' will be performed in mode '+str(mode)+
' with '+str(njobs)+
' jobs in parallel.')
179 if not os.access(process_dir,os.R_OK):
180 raise RuntimeError(
'No process directory found at '+process_dir)
181 if not os.access(process_dir+
'/bin/generate_events',os.R_OK):
182 raise RuntimeError(
'No generate_events module found in '+process_dir)
184 mglog.info(
'For your information, the libraries available are (should include LHAPDF):')
185 ls_dir(process_dir+
'/lib')
188 if bias_module
is not None:
191 mglog.info(
'Now I will hack the make files a bit. Apologies, but there seems to be no good way around this.')
192 shutil.copyfile(process_dir+
'/Source/make_opts',process_dir+
'/Source/make_opts_old')
193 old_opts = open(process_dir+
'/Source/make_opts_old',
'r')
194 new_opts = open(process_dir+
'/Source/make_opts',
'w')
195 for aline
in old_opts:
197 mglog.info(
'Configuring the fancy gfortran compiler instead of g77 / f77')
198 new_opts.write(
' FC=gfortran\n')
200 new_opts.write(aline)
203 mglog.info(
'Make file hacking complete.')
207 os.chdir(process_dir)
209 MADGRAPH_COMMAND_STACK += [
'cd ${MGaMC_PROCESS_DIR}' ]
212 my_MGC_instance.run_card_consistency_check()
217 original_systematics_program =
None if 'systematics_program' not in my_MGC_instance.runCardDict
else my_MGC_instance.runCardDict[
'systematics_program']
218 my_MGC_instance.runCardDict[
'systematics_program'] =
'None'
219 mglog.info(
'systematics set to NONE')
226 code = check_PMG_updates(process_dir=os.getcwd())
227 if requirePMGSettings
and code!=0:
228 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
232 command = [python,
'bin/generate_events']
234 command += [
'--name='+MADGRAPH_RUN_NAME]
235 mglog.info(
'Removing Cards/shower_card.dat to ensure we get parton level events only')
237 os.unlink(
'Cards/shower_card.dat')
238 except FileNotFoundError:
239 mglog.info(
'Cannot find Cards/shower_card.dat.')
241 command += [MADGRAPH_RUN_NAME]
243 setNCores(process_dir=os.getcwd(), Ncores=njobs)
246 mglog.info(
'Setting up cluster running')
247 my_MGC_instance.configCardDict[
'run_mode'] = 1
249 if cluster_type==
'pbs':
250 mglog.info(
'Modifying bin/internal/cluster.py for PBS cluster running')
251 os.system(
"sed -i \"s:text += prog:text += './'+prog:g\" bin/internal/cluster.py")
253 mglog.info(
'Setting up multi-core running on '+os.environ[
'ATHENA_CORE_NUMBER']+
' cores')
255 mglog.info(
'Setting up serial generation.')
258 my_MGC_instance.write_configCard()
259 my_MGC_instance.write_runCard(runArgs=runArgs)
265 generate =
stack_subprocess(command,stdin=subprocess.PIPE, stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
266 (out,err) = generate.communicate()
267 error_check(err,generate.returncode)
271 MADGRAPH_COMMAND_STACK += [
'cd -' ]
276 energy =
'%1.1f'%(beamEnergy*2./1000.)
277 energy = energy.replace(
'.0',
'').
replace(
'.',
'p')
278 gridpack_name=
'mc_'+energy+
'TeV.'+get_physics_short()+
'.MG'+get_mg5_version().
replace(
'.',
'')+
'.GRID.tar.gz'
279 mglog.info(
'Tidying up gridpack '+gridpack_name)
282 my_MGC_instance.runCardDict.update({
'systematics_program':original_systematics_program})
284 my_MGC_instance.write_runCard(runArgs=runArgs)
289 MADGRAPH_COMMAND_STACK += [f
'mv {process_dir}/Cards/madspin_card.tmp.dat {process_dir}/Cards/madspin_card.dat']
290 os.rename(f
'{process_dir}/Cards/madspin_card.tmp.dat',f
'{process_dir}/Cards/madspin_card.dat')
293 MADGRAPH_COMMAND_STACK += [
'cp '+glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0]+
' '+gridpack_name]
294 shutil.copy(glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0],gridpack_name)
297 MADGRAPH_COMMAND_STACK += [
'mkdir tmp%i/'%os.getpid(),
'cd tmp%i/'%os.getpid()]
298 os.mkdir(
'tmp%i/'%os.getpid())
299 os.chdir(
'tmp%i/'%os.getpid())
300 mglog.info(
'untar gridpack')
303 mglog.info(
'compile and clean up')
304 MADGRAPH_COMMAND_STACK += [
'cd madevent']
305 os.chdir(
'madevent/')
306 compilep =
stack_subprocess([
'./bin/compile'],stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
307 (out,err) = compilep.communicate()
308 error_check(err,compilep.returncode)
309 clean =
stack_subprocess([
'./bin/clean4grid'],stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
310 (out,err) = clean.communicate()
311 error_check(err,clean.returncode)
313 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm ../'+gridpack_name]
315 mglog.info(
'remove old tarball')
316 os.unlink(
'../'+gridpack_name)
317 mglog.info(
'Package up new tarball')
318 tar =
stack_subprocess([
'tar',
'--exclude=SubProcesses/P*/G*/*_results.dat',
'--exclude=SubProcesses/P*/G*/*.log',
'--exclude=SubProcesses/P*/G*/*.txt',
'-cvsf',
'../'+gridpack_name,
'.'])
320 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm -r tmp%i/'%os.getpid()]
322 mglog.info(
'Remove temporary directory')
323 shutil.rmtree(
'tmp%i/'%os.getpid())
324 mglog.info(
'Tidying up complete!')
327 my_MGC_instance.write_runCard(runArgs=runArgs)
329 mglog.info(
'Package up process_dir')
330 MADGRAPH_COMMAND_STACK += [
'mv '+process_dir+
' '+MADGRAPH_GRIDPACK_LOCATION]
331 os.rename(process_dir,MADGRAPH_GRIDPACK_LOCATION)
332 tar =
stack_subprocess([
'tar',
'--exclude=Events/*/*events*gz',
'--exclude=SubProcesses/P*/G*/log*txt',
'--exclude=SubProcesses/P*/G*/events.lhe*',
'--exclude=*/*.o',
'--exclude=*/*/*.o',
'--exclude=*/*/*/*.o',
'--exclude=*/*/*/*/*.o',
'-czf',gridpack_name,MADGRAPH_GRIDPACK_LOCATION])
334 MADGRAPH_COMMAND_STACK += [
'mv '+MADGRAPH_GRIDPACK_LOCATION+
' '+process_dir]
335 os.rename(MADGRAPH_GRIDPACK_LOCATION,process_dir)
337 mglog.info(
'Gridpack sucessfully created, exiting the transform')
338 if hasattr(runArgs,
'outputTXTFile'):
339 mglog.info(
'Touching output TXT (LHE) file for the transform')
340 open(runArgs.outputTXTFile,
'w').close()
341 from AthenaCommon.AppMgr
import theApp
345 mglog.info(
'Finished at '+str(time.asctime()))
350 global my_MGC_instance
356 my_MGC_instance.setup_path_protection()
358 isNLO = my_MGC_instance.isNLO
363 gridpack_run_name =
'GridRun_'+str(random_seed)
366 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',os.R_OK):
367 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat')
376 code = check_PMG_updates(process_dir=MADGRAPH_GRIDPACK_LOCATION)
377 if requirePMGSettings
and code!=0:
378 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
381 settings={
'iseed':str(random_seed)}
383 settings[
'python_seed']=str(random_seed)
384 my_MGC_instance.runCardDict.update(settings)
386 mglog.info(
'Generating events from gridpack')
389 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION):
390 raise RuntimeError(
'Gridpack directory not found at '+MADGRAPH_GRIDPACK_LOCATION)
392 nevents = my_MGC_instance.runCardDict[
'nevents']
393 mglog.info(
'>>>> FOUND GRIDPACK <<<< <- This will be used for generation')
394 mglog.info(
'Generation of '+str(int(nevents))+
' events will be performed using the supplied gridpack with random seed '+str(random_seed))
395 mglog.info(
'Started generating events at '+str(time.asctime()))
398 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py',os.R_OK):
399 os.remove(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py')
404 setNCores(process_dir=MADGRAPH_GRIDPACK_LOCATION)
408 ls_dir(MADGRAPH_GRIDPACK_LOCATION)
411 my_MGC_instance.run_card_consistency_check()
418 systematics_settings=
None
419 if my_MGC_instance.runCardDict.get(
'systematics_program',
None) ==
'systematics':
420 if not my_MGC_instance.runCardDict.get(
'store_rwgt_info',
None):
421 raise RuntimeError(
'Trying to run NLO systematics but reweight info not stored')
422 if 'systematics_arguments' in my_MGC_instance.runCardDict:
423 systematics_settings=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(my_MGC_instance.runCardDict[
'systematics_arguments'])
425 systematics_settings={}
426 mglog.info(
'Turning off systematics for now, running standalone later')
428 my_MGC_instance.runCardDict[
'systematics_program'] =
'none'
431 my_MGC_instance.write_runCard(runArgs=runArgs)
433 global MADGRAPH_COMMAND_STACK
436 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun',os.R_OK):
437 mglog.error(
'/bin/gridrun not found at '+MADGRAPH_GRIDPACK_LOCATION)
438 raise RuntimeError(
'Could not find gridrun executable')
440 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun, starting generation.')
443 mglog.info(
"Now generating {} events with random seed {} and granularity {}".format(int(nevents),int(random_seed),granularity))
445 new_ld_path=
":".join([os.environ[
'LD_LIBRARY_PATH'],os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/madevent/lib',os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/HELAS/lib'])
446 os.environ[
'LD_LIBRARY_PATH']=new_ld_path
447 MADGRAPH_COMMAND_STACK+=[
"export LD_LIBRARY_PATH="+
":".join([
'${LD_LIBRARY_PATH}',new_ld_path])]
448 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)
449 (out,err) = generate.communicate()
450 error_check(err,generate.returncode)
451 gp_events=MADGRAPH_GRIDPACK_LOCATION+
"/Events/GridRun_{}/unweighted_events.lhe.gz".format(int(random_seed))
452 if not os.path.exists(gp_events):
453 mglog.error(
'Error in gp generation, did not find events at '+gp_events)
457 if reweight_card
is not None:
458 pythonpath_backup=os.environ[
'PYTHONPATH']
460 os.environ[
'PYTHONPATH']=
':'.join([p
for p
in pythonpath_backup.split(
':')
if 'madgraph5amc' not in p])
462 os.environ[
'PYTHONPATH']=pythonpath_backup
464 shutil.move(gp_events,
'events.lhe.gz')
468 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events',os.R_OK):
469 raise RuntimeError(
'Could not find generate_events executable at '+MADGRAPH_GRIDPACK_LOCATION)
471 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events, starting generation.')
473 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
474 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name, os.F_OK):
475 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
' directory from gridpack generation')
476 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name]
477 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)
480 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1', os.F_OK):
481 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1 directory from gridpack generation')
482 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1']
483 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1')
485 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
487 if not gridpack_compile:
488 mglog.info(
'Copying make_opts from Template')
489 shutil.copy(os.environ[
'MADPATH']+
'/Template/LO/Source/make_opts',MADGRAPH_GRIDPACK_LOCATION+
'/Source/')
492 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)
493 (out,err) = generate.communicate()
494 error_check(err,generate.returncode)
496 mglog.info(
'Allowing recompilation of gridpack')
497 if os.path.islink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a'):
498 mglog.info(
'Unlinking '+MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
499 os.unlink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
502 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)
503 (out,err) = generate.communicate()
504 error_check(err,generate.returncode)
505 if isNLO
and systematics_settings
is not None:
507 mglog.info(
'Running systematics standalone')
508 systematics_path=MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/systematics.py'
509 events_location=MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz'
510 syst_cmd=[python,systematics_path]+[events_location]*2+[
"--"+k+
"="+systematics_settings[k]
for k
in systematics_settings]
511 mglog.info(
'running: '+
' '.join(syst_cmd))
517 if not os.access(
'events.lhe.gz',os.R_OK):
518 mglog.info(
'Copying generated events to '+currdir)
519 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION+
'Events/'+gridpack_run_name):
520 shutil.copy(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz',
'events.lhe.gz')
522 mglog.info(
'Events were already in place')
526 mglog.info(
'Moving generated events to be in correct format for arrange_output().')
527 mglog.info(
'Unzipping generated events.')
531 mglog.info(
'Moving file over to '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
532 mkdir =
stack_subprocess([
'mkdir',
'-p',(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)])
534 shutil.move(
'events.lhe',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
536 mglog.info(
'Re-zipping into dataset name '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe.gz')
537 rezip =
stack_subprocess([
'gzip',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe'])
545 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat')
546 mglog.info(
'Decaying with MadSpin.')
547 add_madspin(process_dir=MADGRAPH_GRIDPACK_LOCATION)
549 mglog.info(
'Finished at '+str(time.asctime()))
597def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
598 global my_MGC_instance
600 isNLO = my_MGC_instance.isNLO
602 origLHAPATH=os.environ[
'LHAPATH']
603 origLHAPDF_DATA_PATH=os.environ[
'LHAPDF_DATA_PATH']
605 LHAPATH,LHADATAPATH=get_LHAPDF_PATHS()
611 mydict= my_MGC_instance.runCardDict
612 if mydict[
"pdlabel"].
replace(
"'",
"") ==
'lhapdf':
614 mglog.info(
'creating local LHAPDF dir: MGC_LHAPDF/')
615 if os.path.islink(
'MGC_LHAPDF/'):
616 os.unlink(
'MGC_LHAPDF/')
617 elif os.path.isdir(
'MGC_LHAPDF/'):
618 shutil.rmtree(
'MGC_LHAPDF/')
620 newMGCLHA=
'MGC_LHAPDF/'
622 mkdir = subprocess.Popen([
'mkdir',
'-p',newMGCLHA])
625 pdfs_used=[ int(x)
for x
in mydict[
'lhaid'].
replace(
' ',
',').
split(
',') ]
627 if 'sys_pdf' in mydict:
633 pdfs_used.append(idx)
636 if 'systematics_arguments' in mydict:
637 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict[
'systematics_arguments'])
638 if 'pdf' in systematics_arguments:
644 pdfs_used.append(idx)
647 for pdf
in pdfs_used:
648 if isinstance(pdf,str)
and (pdf.lower()==
'errorset' or pdf.lower()==
'central'):
651 pdfid,pdfname=get_lhapdf_id_and_name(pdf)
652 mglog.info(
"Found LHAPDF ID="+str(pdfid)+
", name="+pdfname)
654 if not os.path.exists(newMGCLHA+pdfname)
and not os.path.lexists(newMGCLHA+pdfname):
655 if not os.path.exists(LHADATAPATH+
'/'+pdfname):
656 mglog.warning(
'PDF not installed at '+LHADATAPATH+
'/'+pdfname)
658 mglog.info(
'linking '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
659 os.symlink(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
661 mglog.info(
'copying '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
662 shutil.copytree(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
665 mglog.info(
'linking '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
666 os.symlink(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
668 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
669 mglog.info(
'linking '+atlasLHADATAPATH+
'/lhapdf.conf --> '+newMGCLHA+
'lhapdf.conf')
670 os.symlink(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
672 mglog.info(
'copying '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
673 shutil.copy2(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
675 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
676 mglog.info(
'copying '+atlasLHADATAPATH+
'/lhapdf.conf -->'+newMGCLHA+
'lhapdf.conf')
677 shutil.copy2(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
680 LHADATAPATH=os.getcwd()+
'/MGC_LHAPDF'
683 mglog.info(
'Not using LHAPDF')
684 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
688 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
690 mglog.info(
'Path to LHAPDF install dir: '+LHAPATH)
691 mglog.info(
'Path to LHAPDF data dir: '+LHADATAPATH)
692 if not os.path.isdir(LHADATAPATH):
693 raise RuntimeError(
'LHAPDF data dir not accesible: '+LHADATAPATH)
694 if not os.path.isdir(LHAPATH):
695 raise RuntimeError(
'LHAPDF path dir not accesible: '+LHAPATH)
699 lhapdfconfig=extlhapath
700 if not os.access(lhapdfconfig,os.X_OK):
701 raise RuntimeError(
'Failed to find valid external lhapdf-config at '+lhapdfconfig)
702 LHADATAPATH=subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().
strip()
703 mglog.info(
'Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
704 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
706 getlhaconfig = subprocess.Popen([
'get_files',
'-data',
'lhapdf-config'])
709 if not os.access(os.getcwd()+
'/lhapdf-config',os.X_OK):
710 mglog.error(
'Failed to get lhapdf-config from MadGraphControl')
712 lhapdfconfig = os.getcwd()+
'/lhapdf-config'
714 mglog.info(
'lhapdf-config --version: '+str(subprocess.Popen([lhapdfconfig,
'--version'],stdout = subprocess.PIPE).stdout.read().
strip()))
715 mglog.info(
'lhapdf-config --prefix: '+str(subprocess.Popen([lhapdfconfig,
'--prefix'],stdout = subprocess.PIPE).stdout.read().
strip()))
716 mglog.info(
'lhapdf-config --libdir: '+str(subprocess.Popen([lhapdfconfig,
'--libdir'],stdout = subprocess.PIPE).stdout.read().
strip()))
717 mglog.info(
'lhapdf-config --datadir: '+str(subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().
strip()))
718 mglog.info(
'lhapdf-config --pdfsets-path: '+str(subprocess.Popen([lhapdfconfig,
'--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().
strip()))
721 my_MGC_instance.configCardDict.update({
'lhapdf':lhapdfconfig,
'lhapdf_py3':lhapdfconfig})
723 mglog.info(
'Creating links for LHAPDF')
724 if os.path.islink(process_dir+
'/lib/PDFsets'):
725 os.unlink(process_dir+
'/lib/PDFsets')
726 elif os.path.isdir(process_dir+
'/lib/PDFsets'):
727 shutil.rmtree(process_dir+
'/lib/PDFsets')
729 os.symlink(LHADATAPATH,process_dir+
'/lib/PDFsets')
731 shutil.copytree(LHADATAPATH,process_dir+
'/lib/PDFsets')
732 mglog.info(
'Available PDFs are:')
733 mglog.info( sorted( [ x
for x
in os.listdir(process_dir+
'/lib/PDFsets')
if ".tar.gz" not in x ] ) )
735 global MADGRAPH_COMMAND_STACK
736 MADGRAPH_COMMAND_STACK += [
'# Copy the LHAPDF files locally' ]
737 MADGRAPH_COMMAND_STACK += [
'cp -r '+os.getcwd()+
'/MGC_LHAPDF .' ]
738 MADGRAPH_COMMAND_STACK += [
'cp -r '+process_dir+
'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
740 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
865 """ Run MadSpin on an input LHE file. Takes the process
866 from the LHE file, so you don't need to have a process directory
867 set up in advance. Runs MadSpin and packs the LHE file up appropriately
868 Needs runArgs for the file handling"""
869 if not os.access(input_LHE,os.R_OK):
870 raise RuntimeError(
'Could not find LHE file '+input_LHE)
871 if not os.access(madspin_card,os.R_OK):
872 raise RuntimeError(
'Could not find input MadSpin card '+madspin_card)
874 shutil.copy(input_LHE,input_LHE+
'.original')
875 mglog.info(
'Put backup copy of LHE file at '+input_LHE+
'.original')
877 madspin_exec_card = open(
'madspin_exec_card',
'w')
878 madspin_exec_card.write(
'import '+input_LHE+
'\n')
880 input_madspin_card = open(madspin_card,
'r')
882 for l
in input_madspin_card.readlines():
883 commands = l.split(
'#')[0].
split()
885 if len(commands)>1
and 'import'==commands[0]
and not 'model'==commands[1]:
888 if len(commands)>0
and 'launch' == commands[0]:
890 madspin_exec_card.write(l.strip()+
'\n')
892 madspin_exec_card.write(
'launch\n')
893 madspin_exec_card.close()
894 input_madspin_card.close()
896 madpath=os.environ[
'MADPATH']
897 if not os.access(madpath+
'/MadSpin/madspin',os.R_OK):
898 raise RuntimeError(
'madspin executable not found in '+madpath)
899 mglog.info(
'Starting madspin at '+str(time.asctime()))
900 generate =
stack_subprocess([python,madpath+
'/MadSpin/madspin',
'madspin_exec_card'],stdin=subprocess.PIPE,stderr=subprocess.PIPE
if MADGRAPH_CATCH_ERRORS
else None)
901 (out,err) = generate.communicate()
902 error_check(err,generate.returncode)
903 mglog.info(
'Done with madspin at '+str(time.asctime()))
907 if os.path.exists(os.getcwd()+
'/events.lhe'):
908 os.remove(os.getcwd()+
'/events.lhe')
910 mglog.info(
'Unzipping generated events.')
914 mglog.info(
'Putting a copy in place for the transform.')
915 mod_output = open(os.getcwd()+
'/events.lhe',
'w')
919 with open(input_LHE,
'r')
as fileobject:
920 for line
in fileobject:
922 mod_output.write(line)
927 mglog.info(
'Removed '+str(nEmpty)+
' empty lines from LHEF')
931 raise RuntimeError(
'Must provide runArgs to madspin_on_lhe')
933 outputDS = runArgs.outputTXTFile
if hasattr(runArgs,
'outputTXTFile')
else 'tmp_LHE_events.tar.gz'
935 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
936 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
938 mglog.info(
'Re-zipping into dataset name '+outputDS)
939 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
943 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
944 outputDS = outputDS.split(
'.TXT')[0]
946 if runArgs
is not None:
947 mglog.debug(
'Setting inputGenerator file to '+outputDS)
948 runArgs.inputGeneratorFile=outputDS
951def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,fixEventWeightsForBridgeMode=False):
956 if len(glob.glob(os.path.join(process_dir,
'Events',
'*')))<1:
957 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
958 proc_dir_list = glob.glob(os.path.join(process_dir,
'Events',
'*'))
961 for adir
in proc_dir_list:
962 if 'decayed' in adir:
965 if 'GridRun_' in adir:
968 elif os.path.join(process_dir,
'Events',MADGRAPH_RUN_NAME)
in adir:
970 if not os.access(this_run_name,os.R_OK):
971 raise RuntimeError(
'Unable to locate run directory')
973 hasUnweighted = os.access(this_run_name+
'/unweighted_events.lhe.gz',os.R_OK)
976 madspinDirs=sorted(glob.glob(this_run_name+
'_decayed_*/'))
979 if hasRunMadSpin
and not hasUnweighted:
981 hasUnweighted = os.access(madspinDirs[-1]+
'/unweighted_events.lhe.gz',os.R_OK)
983 global MADGRAPH_COMMAND_STACK
992 if os.path.exists(madspinDirs[-1]+
'/unweighted_events.lhe.gz'):
993 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/unweighted_events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
994 shutil.move(madspinDirs[-1]+
'/unweighted_events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
995 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/unweighted_events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
996 elif os.path.exists(madspinDirs[-1]+
'/events.lhe.gz'):
997 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
998 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
999 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1001 raise RuntimeError(
'MadSpin was run but can\'t find files :(')
1004 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz '+this_run_name+
'/events.lhe.gz']
1005 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/events.lhe.gz')
1006 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/events.lhe.gz')
1009 mglog.error(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1010 raise RuntimeError(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1012 if fixEventWeightsForBridgeMode:
1013 mglog.info(
"Fixing event weights after MadSpin... initial checks.")
1021 eventsfilename=
"unweighted_events"
1023 eventsfilename=
"events"
1024 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/%s.lhe.gz' % eventsfilename])
1027 for line
in open(process_dir+
'/Events/'+MADGRAPH_RUN_NAME+
'/%s.lhe'%eventsfilename):
1028 if "Number of Events" in line:
1030 MGnumevents=int(sline[-1])
1031 elif "Integrated weight (pb)" in line:
1033 MGintweight=float(sline[-1])
1034 elif "set spinmode none" in line:
1036 elif "</header>" in line:
1039 if spinmodenone
and MGnumevents>0
and MGintweight>0:
1040 mglog.info(
"Fixing event weights after MadSpin... modifying LHE file.")
1041 newlhe=open(this_run_name+
'/%s_fixXS.lhe'%eventsfilename,
'w')
1049 event_norm_setting=
"average"
1051 for line
in open(this_run_name+
'/%s.lhe'%eventsfilename):
1054 if "<init>" in line:
1057 elif "</init>" in line:
1059 elif inInit
and initlinecount==0:
1063 if abs(int(sline[-2])) == 3:
1064 event_norm_setting=
"sum"
1065 elif abs(int(sline[-2])) == 4:
1066 event_norm_setting=
"average"
1067 elif inInit
and initlinecount==1:
1070 relunc=float(sline[1])/float(sline[0])
1071 sline[0]=str(MGintweight)
1072 sline[1]=str(float(sline[0])*relunc)
1073 if event_norm_setting==
"sum":
1074 sline[2]=str(MGintweight/MGnumevents)
1075 elif event_norm_setting==
"average":
1076 sline[2]=str(MGintweight)
1077 newline=
' '.join(sline)
1080 elif inInit
and initlinecount>1:
1082 elif "<event>" in line:
1085 elif "</event>" in line:
1087 elif inEvent
and eventlinecount==0:
1090 if event_norm_setting==
"sum":
1091 sline[2]=str(MGintweight/MGnumevents)
1092 elif event_norm_setting==
"average":
1093 sline[2]=str(MGintweight)
1094 newline=
' '.join(sline)
1097 newlhe.write(newline)
1100 mglog.info(
"Fixing event weights after MadSpin... cleaning up.")
1101 shutil.copyfile(this_run_name+
'/%s.lhe' % eventsfilename,
1102 this_run_name+
'/%s_badXS.lhe' % eventsfilename)
1104 shutil.move(this_run_name+
'/%s_fixXS.lhe' % eventsfilename,
1105 this_run_name+
'/%s.lhe' % eventsfilename)
1107 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s.lhe' % eventsfilename])
1110 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s_badXS.lhe' % eventsfilename])
1114 if os.path.exists(os.getcwd()+
'/events.lhe'):
1115 os.remove(os.getcwd()+
'/events.lhe')
1117 mglog.info(
'Unzipping generated events.')
1119 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/unweighted_events.lhe.gz'])
1125 mglog.info(
'Putting a copy in place for the transform.')
1127 orig_input = this_run_name+
'/unweighted_events.lhe'
1128 mod_output = open(os.getcwd()+
'/events.lhe',
'w')
1130 orig_input = this_run_name+
'/events.lhe'
1131 mod_output = open(os.getcwd()+
'/events.lhe',
'w')
1138 with open(orig_input,
'r')
as fileobject:
1139 for line
in fileobject:
1143 if '#' not in newline:
1145 elif '>' not in newline[ newline.find(
'#'): ]:
1148 mglog.info(
'Found bad LHE line with an XML mark in a comment: "'+newline.strip()+
'"')
1149 newline=newline[:newline.find(
'#')]+
'#'+ (newline[newline.find(
'#'):].
replace(
'>',
'-'))
1151 if initrwgt
is False:
1153 elif "</initrwgt>" in newline:
1155 elif "<initrwgt>" in newline:
1157 elif initrwgt
is not None:
1158 newline=newline.replace(
'_DYNSCALE-1',
'')
1159 if '</weight>' in newline:
1160 iend=newline.find(
'</weight>')
1161 istart=newline[:iend].rfind(
'>')
1162 lhe_weights+=[newline[istart+1:iend].
strip()]
1163 mod_output.write(newline)
1167 mglog.info(
'Removed '+str(nEmpty)+
' empty lines from LHEF')
1169 mglog.info(
"The following "+str(len(lhe_weights))+
" weights have been written to the LHE file: "+
",".join(lhe_weights))
1172 mglog.info(
"Checking whether the following expected weights are in LHE file: "+
",".join(expected_weights))
1173 for w
in expected_weights:
1174 if w
not in lhe_weights:
1175 raise RuntimeError(
"Did not find expected weight "+w+
" in lhe file. Did the reweight or systematics module crash?")
1176 mglog.info(
"Found all required weights!")
1179 mod_output2 = open(os.getcwd()+
'/events.lhe',
'r')
1180 test=mod_output2.readline()
1181 if 'version="' in test:
1182 mglog.info(
'Applying LHE version hack')
1183 final_file = open(os.getcwd()+
'/events.lhe.copy',
'w')
1184 final_file.write(
'<LesHouchesEvents version="%i.0">\n'%lhe_version)
1185 shutil.copyfileobj(mod_output2, final_file)
1187 shutil.copy(os.getcwd()+
'/events.lhe.copy',os.getcwd()+
'/events.lhe')
1189 os.remove(os.getcwd()+
'/events.lhe.copy')
1194 raise RuntimeError(
'Must provide runArgs to arrange_output')
1196 if hasattr(runArgs,
'outputTXTFile'):
1197 outputDS = runArgs.outputTXTFile
1199 outputDS =
'tmp_LHE_events.tar.gz'
1200 if hasattr(runArgs,
"avoidExtracting")
and runArgs.avoidExtracting:
1201 outputDS =
'tmp_LHE_events.gz'
1203 outputStem = outputDS
1204 if '.tar.gz' in outputDS:
1205 outputStem = outputDS.split(
'.tar.gz')[0]
1206 elif '.tgz' in outputDS:
1207 outputStem = outputDS.split(
'.tgz')[0]
1208 elif '.gz' in outputDS:
1209 outputStem = outputDS.split(
'.gz')[0]
1211 mglog.warning(f
'Could not figure out what output file type {outputDS} refers to')
1212 outputStem = outputDS.split(
'.')[0]
1213 outputStem +=
'.events'
1215 mglog.info(
'Moving file over to '+outputStem)
1216 shutil.move(os.getcwd()+
'/events.lhe',outputStem)
1218 if '.tar.gz' in outputDS
or '.tgz' in outputDS:
1219 mglog.info(
'Re-zipping + tarring into dataset name '+outputDS)
1222 elif '.gz' in outputDS:
1223 mglog.info(
'Re-zipping into dataset name '+outputDS)
1226 shutil.move(outputStem+
'.gz',outputDS)
1228 mglog.info(f
'Could not understand output type for {outputDS} - will leave uncompressed')
1231 mglog.info(
'Removing the process directory')
1232 shutil.rmtree(process_dir,ignore_errors=
True)
1234 if os.path.isdir(
'MGC_LHAPDF/'):
1235 shutil.rmtree(
'MGC_LHAPDF/',ignore_errors=
True)
1238 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1239 outputDS = outputDS.split(
'.TXT')[0]
1241 if runArgs
is not None:
1242 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1243 runArgs.inputGeneratorFile=outputDS
1245 mglog.info(
'All done with output arranging!')
1283 run_card = process_dir+
'/Cards/run_card.dat'
1284 if isinstance(bias_module,tuple):
1285 mglog.info(
'Using bias module '+bias_module[0])
1286 the_run_card = open(run_card,
'r')
1287 for line
in the_run_card:
1288 if 'bias_module' in line
and not bias_module[0]
in line:
1289 raise RuntimeError(
'You need to add the bias module '+bias_module[0]+
' to the run card to actually run it')
1290 the_run_card.close()
1291 if len(bias_module)!=3:
1292 raise RuntimeError(
'Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1293 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module[0]
1294 os.makedirs(bias_module_newpath)
1295 bias_module_file=open(bias_module_newpath+
'/'+bias_module[0]+
'.f',
'w')
1296 bias_module_file.write(bias_module[1])
1297 bias_module_file.close()
1298 bias_module_make_file=open(bias_module_newpath+
'/Makefile',
'w')
1299 bias_module_make_file.write(bias_module[2])
1300 bias_module_make_file.close()
1302 mglog.info(
'Using bias module '+bias_module)
1303 bias_module_name=bias_module.split(
'/')[-1].
replace(
'.gz',
'')
1304 bias_module_name=bias_module_name.replace(
'.tar',
'')
1305 the_run_card = open(run_card,
'r')
1306 for line
in the_run_card:
1307 if 'bias_module' in line
and bias_module_name
not in line:
1308 raise RuntimeError(
'You need to add the bias module '+bias_module_name+
' to the run card to actually run it')
1309 the_run_card.close()
1311 if os.path.exists(bias_module+
'.tar.gz'):
1312 bias_module_path=bias_module+
'.tar.gz'
1313 elif os.path.exists(bias_module+
'.gz'):
1314 bias_module_path=bias_module+
'.gz'
1315 elif os.path.exists(bias_module):
1316 bias_module_path=bias_module
1318 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')
1320 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module_path.split(
'/')[-1]
1321 mglog.info(
'Copying bias module into place: '+bias_module_newpath)
1322 shutil.copy(bias_module_path,bias_module_newpath)
1323 mglog.info(
'Unpacking bias module')
1324 if bias_module_newpath.endswith(
'.tar.gz'):
1325 untar =
stack_subprocess([
'tar',
'xvzf',bias_module_newpath,
'--directory='+process_dir+
'/Source/BIAS/'])
1327 elif bias_module_path.endswith(
'.gz'):
1374def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1375 """Build a new LHE file from an old one and an updated param card.
1376 The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1377 may have their masses changed.
1378 If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1379 By default, the old LHE file is removed.
1380 If None is provided as a new LHE file name, the new file will replace the old one."""
1382 lhe_file_new_tmp = lhe_file_new
if lhe_file_new
is not None else lhe_file_old+
'.tmp'
1384 if not os.access(lhe_file_old,os.R_OK):
1385 raise RuntimeError(
'Could not access old LHE file at '+str(lhe_file_old)+
'. Please check the file location.')
1387 if param_card_old
is not None:
1388 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_old])
1390 if not os.access(param_card_old,os.R_OK):
1391 raise RuntimeError(
'Could not get param card '+param_card_old)
1393 if os.access(lhe_file_new_tmp,os.R_OK):
1394 raise RuntimeError(
'Old file at'+str(lhe_file_new_tmp)+
' in the current directory. Dont want to clobber it. Please move it first.')
1396 newlhe = open(lhe_file_new_tmp,
'w')
1400 particles_in_events = []
1403 with open(lhe_file_old,
'r')
as fileobject:
1404 for line
in fileobject:
1405 if decayEdit
and '</slha>' not in line:
1407 if decayEdit
and '</slha>' in line:
1409 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1410 and len(line.strip().
split()) > 1:
1411 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1412 blockName = line.strip().
upper().
split()[pos]
1415 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
1416 akey = line.strip().
split()[0]
1417 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
1418 akey = line.strip().
split()[1]
1421 if akey
is not None and blockName ==
'MASS' and akey
in masses:
1422 newlhe.write(
' '+akey+
' '+str(masses[akey])+
' # \n')
1423 mglog.info(
' '+akey+
' '+str(masses[akey])+
' #')
1428 if blockName ==
'DECAY' and param_card_old
is not None:
1430 oldparam = open(param_card_old,
'r')
1432 for old_line
in oldparam.readlines():
1434 if old_line.strip().
upper().startswith(
'DECAY')
and len(old_line.strip().
split()) > 1:
1435 newBlockName = line.strip().
upper().
split()[pos]
1437 newlhe.write(old_line)
1438 elif newBlockName ==
'DECAY':
1440 newlhe.write(old_line)
1448 if not eventRead
and '<event>' in line:
1451 if len(line.split())==11:
1452 aparticle = line.split()[0]
1453 if aparticle
not in particles_in_events:
1454 particles_in_events += [aparticle]
1461 if akey
in particles_in_events:
1462 mglog.error(
'Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1469 if lhe_file_new
is None:
1470 os.remove(lhe_file_old)
1471 shutil.move(lhe_file_new_tmp,lhe_file_old)
1472 lhe_file_new_tmp = lhe_file_old
1474 elif delete_old_lhe:
1475 os.remove(lhe_file_old)
1477 return lhe_file_new_tmp
1545def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
1546 """Build a new run_card.dat from an existing one.
1547 This function can get a fresh runcard from DATAPATH or start from the process directory.
1548 Settings is a dictionary of keys (no spaces needed) and values to replace.
1551 global my_MGC_instance
1553 my_MGC_instance.runCardDict.update(settings)
1558 for s
in list(settings.keys()):
1559 settings_lower[s.lower()] = settings[s]
1562 if run_card_input
is None:
1564 elif run_card_input
is not None and not os.access(run_card_input,os.R_OK):
1565 runcard = subprocess.Popen([
'get_files',
'-data',run_card_input])
1567 if not os.access(run_card_input,os.R_OK):
1568 raise RuntimeError(
'Could not get run card '+run_card_input)
1571 isNLO = my_MGC_instance.isNLO
1573 if not skipBaseFragment:
1577 if runArgs
is not None:
1579 if 'iseed' not in settings_lower:
1580 settings_lower[
'iseed']=rand_seed
1581 if not isNLO
and 'python_seed' not in settings_lower:
1582 settings_lower[
'python_seed']=rand_seed
1583 if 'beamenergy' in settings_lower:
1584 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']))
1585 beamEnergy=settings_lower[
'beamenergy']
1586 settings_lower.pop(
'beamenergy')
1587 if 'ebeam1' not in settings_lower:
1588 settings_lower[
'ebeam1']=beamEnergy
1589 if 'ebeam2' not in settings_lower:
1590 settings_lower[
'ebeam2']=beamEnergy
1592 if 'nevents' in settings_lower:
1593 settings_lower[
'nevents'] = int(settings_lower[
'nevents'])
1596 if 'custom_fcts' in settings_lower
and settings_lower[
'custom_fcts']:
1597 raw_name = str(settings_lower[
'custom_fcts']).
split()[0]
1599 if runArgs
is not None and hasattr(runArgs,
'jobConfig'):
1600 cfgdir = runArgs.jobConfig[0]
if isinstance(runArgs.jobConfig, (list, tuple))
else runArgs.jobConfig
1602 full_path = os.path.join(cfgdir, raw_name)
1603 settings_lower[
'custom_fcts'] = os.path.abspath(full_path)
1604 print(f
"Using custom function(s), specified in custom_fcts with path: {settings_lower['custom_fcts']}")
1607 settings_lower[
'custom_fcts'] = os.path.abspath(raw_name)
1609 mglog.info(
'Modifying run card located at '+run_card_input)
1610 if run_card_backup
is not None:
1611 mglog.info(
'Keeping backup of original run card at '+run_card_backup)
1612 run_card_old = run_card_backup
1614 run_card_old = run_card_input+
'.old_to_be_deleted'
1615 mglog.debug(
'Modifying runcard settings: '+str(settings_lower))
1616 if os.path.isfile(run_card_old):
1617 os.unlink(run_card_old)
1618 os.rename(run_card_input, run_card_old)
1620 oldCard = open(run_card_old,
'r')
1621 newCard = open(process_dir+
'/Cards/run_card.dat',
'w')
1623 for line
in iter(oldCard):
1624 if not line.strip().startswith(
'#'):
1625 command = line.split(
'!', 1)[0]
1626 comment = line.split(
'!', 1)[1]
if '!' in line
else ''
1628 setting = command.split(
'=')[-1]
1629 stripped_setting = setting.strip()
1630 oldValue =
'='.join(command.split(
'=')[:-1])
1631 if stripped_setting.lower()
in settings_lower:
1633 if settings_lower[stripped_setting.lower()]
is None:
1635 mglog.info(
'Removing '+stripped_setting+
'.')
1636 used_settings += [ stripped_setting.lower() ]
1638 if stripped_setting.lower() ==
'custom_fcts':
1640 line =
' '+str(settings_lower[stripped_setting.lower()])+
' = '+setting
1642 line +=
' !'+comment
1644 line = oldValue.replace(oldValue.strip(), str(settings_lower[stripped_setting.lower()]))+
'='+setting
1646 line +=
' !' + comment
1647 mglog.info(
'Setting '+stripped_setting+
' = '+str(settings_lower[stripped_setting.lower()]))
1648 used_settings += [ stripped_setting.lower() ]
1649 newCard.write(line.strip()+
'\n')
1652 if 'mcatnlo_delta' in settings_lower:
1653 if settings_lower[
'mcatnlo_delta'] ==
'True':
1654 modify_config_card(process_dir=process_dir,settings={
'pythia8_path':os.getenv(
"PY8PATH")})
1658 for asetting
in settings_lower:
1659 if asetting
in used_settings:
1661 if settings_lower[asetting]
is None:
1663 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]) )
1664 newCard.write(
' '+str(settings_lower[asetting])+
' = '+str(asetting)+
'\n')
1668 mglog.info(
'Finished modification of run card.')
1669 if run_card_backup
is None:
1670 os.unlink(run_card_old)
1673def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
1674 """Build a new configuration from an existing one.
1675 This function can get a fresh runcard from DATAPATH or start from the process directory.
1676 Settings is a dictionary of keys (no spaces needed) and values to replace.
1678 global my_MGC_instance
1680 my_MGC_instance.configCardDict.update(settings)
1682 config_card = my_MGC_instance.config_path
1685 mglog.info(
'Modifying config card located at '+config_card)
1686 if config_card_backup
is not None:
1687 mglog.info(
'Keeping backup of original config card at '+config_card_backup)
1688 config_card_old = config_card_backup
1690 config_card_old = config_card+
'.old_to_be_deleted'
1691 mglog.debug(
'Modifying config card settings: '+str(settings))
1692 if os.path.isfile(config_card_old):
1693 os.unlink(config_card_old)
1694 os.rename(config_card, config_card_old)
1696 oldCard = open(config_card_old,
'r')
1697 newCard = open(config_card,
'w')
1699 for line
in iter(oldCard):
1700 lmod = line
if set_commented
else line.split(
'#')[0]
1703 for setting
in settings:
1704 if setting
not in lmod:
1707 mglog.info(
'Setting '+setting.strip()+
' to '+str(settings[setting]))
1708 newCard.write(
' '+str(setting.strip())+
' = '+str(settings[setting])+
'\n')
1709 used_settings += [ setting.strip() ]
1717 for asetting
in settings:
1718 if asetting
in used_settings:
1720 if settings[asetting]
is None:
1722 mglog.warning(
'Option '+asetting+
' was not in the default config card. Adding by hand a setting to '+str(settings[asetting]) )
1723 newCard.write(
' '+str(asetting)+
' = '+str(settings[asetting])+
'\n')
1727 mglog.info(
'Finished modification of config card.')
1728 if config_card_backup
is None:
1729 os.unlink(config_card_old)