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'
1201 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
1203 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
1205 mglog.info(
'Re-zipping into dataset name '+outputDS)
1206 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
1210 mglog.info(
'Removing the process directory')
1211 shutil.rmtree(process_dir,ignore_errors=
True)
1213 if os.path.isdir(
'MGC_LHAPDF/'):
1214 shutil.rmtree(
'MGC_LHAPDF/',ignore_errors=
True)
1217 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1218 outputDS = outputDS.split(
'.TXT')[0]
1220 if runArgs
is not None:
1221 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1222 runArgs.inputGeneratorFile=outputDS
1224 mglog.info(
'All done with output arranging!')
1262 run_card = process_dir+
'/Cards/run_card.dat'
1263 if isinstance(bias_module,tuple):
1264 mglog.info(
'Using bias module '+bias_module[0])
1265 the_run_card = open(run_card,
'r')
1266 for line
in the_run_card:
1267 if 'bias_module' in line
and not bias_module[0]
in line:
1268 raise RuntimeError(
'You need to add the bias module '+bias_module[0]+
' to the run card to actually run it')
1269 the_run_card.close()
1270 if len(bias_module)!=3:
1271 raise RuntimeError(
'Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1272 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module[0]
1273 os.makedirs(bias_module_newpath)
1274 bias_module_file=open(bias_module_newpath+
'/'+bias_module[0]+
'.f',
'w')
1275 bias_module_file.write(bias_module[1])
1276 bias_module_file.close()
1277 bias_module_make_file=open(bias_module_newpath+
'/Makefile',
'w')
1278 bias_module_make_file.write(bias_module[2])
1279 bias_module_make_file.close()
1281 mglog.info(
'Using bias module '+bias_module)
1282 bias_module_name=bias_module.split(
'/')[-1].
replace(
'.gz',
'')
1283 bias_module_name=bias_module_name.replace(
'.tar',
'')
1284 the_run_card = open(run_card,
'r')
1285 for line
in the_run_card:
1286 if 'bias_module' in line
and bias_module_name
not in line:
1287 raise RuntimeError(
'You need to add the bias module '+bias_module_name+
' to the run card to actually run it')
1288 the_run_card.close()
1290 if os.path.exists(bias_module+
'.tar.gz'):
1291 bias_module_path=bias_module+
'.tar.gz'
1292 elif os.path.exists(bias_module+
'.gz'):
1293 bias_module_path=bias_module+
'.gz'
1294 elif os.path.exists(bias_module):
1295 bias_module_path=bias_module
1297 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')
1299 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module_path.split(
'/')[-1]
1300 mglog.info(
'Copying bias module into place: '+bias_module_newpath)
1301 shutil.copy(bias_module_path,bias_module_newpath)
1302 mglog.info(
'Unpacking bias module')
1303 if bias_module_newpath.endswith(
'.tar.gz'):
1304 untar =
stack_subprocess([
'tar',
'xvzf',bias_module_newpath,
'--directory='+process_dir+
'/Source/BIAS/'])
1306 elif bias_module_path.endswith(
'.gz'):
1353def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1354 """Build a new LHE file from an old one and an updated param card.
1355 The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1356 may have their masses changed.
1357 If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1358 By default, the old LHE file is removed.
1359 If None is provided as a new LHE file name, the new file will replace the old one."""
1361 lhe_file_new_tmp = lhe_file_new
if lhe_file_new
is not None else lhe_file_old+
'.tmp'
1363 if not os.access(lhe_file_old,os.R_OK):
1364 raise RuntimeError(
'Could not access old LHE file at '+str(lhe_file_old)+
'. Please check the file location.')
1366 if param_card_old
is not None:
1367 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_old])
1369 if not os.access(param_card_old,os.R_OK):
1370 raise RuntimeError(
'Could not get param card '+param_card_old)
1372 if os.access(lhe_file_new_tmp,os.R_OK):
1373 raise RuntimeError(
'Old file at'+str(lhe_file_new_tmp)+
' in the current directory. Dont want to clobber it. Please move it first.')
1375 newlhe = open(lhe_file_new_tmp,
'w')
1379 particles_in_events = []
1382 with open(lhe_file_old,
'r')
as fileobject:
1383 for line
in fileobject:
1384 if decayEdit
and '</slha>' not in line:
1386 if decayEdit
and '</slha>' in line:
1388 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1389 and len(line.strip().
split()) > 1:
1390 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1391 blockName = line.strip().
upper().
split()[pos]
1394 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
1395 akey = line.strip().
split()[0]
1396 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
1397 akey = line.strip().
split()[1]
1400 if akey
is not None and blockName ==
'MASS' and akey
in masses:
1401 newlhe.write(
' '+akey+
' '+str(masses[akey])+
' # \n')
1402 mglog.info(
' '+akey+
' '+str(masses[akey])+
' #')
1407 if blockName ==
'DECAY' and param_card_old
is not None:
1409 oldparam = open(param_card_old,
'r')
1411 for old_line
in oldparam.readlines():
1413 if old_line.strip().
upper().startswith(
'DECAY')
and len(old_line.strip().
split()) > 1:
1414 newBlockName = line.strip().
upper().
split()[pos]
1416 newlhe.write(old_line)
1417 elif newBlockName ==
'DECAY':
1419 newlhe.write(old_line)
1427 if not eventRead
and '<event>' in line:
1430 if len(line.split())==11:
1431 aparticle = line.split()[0]
1432 if aparticle
not in particles_in_events:
1433 particles_in_events += [aparticle]
1440 if akey
in particles_in_events:
1441 mglog.error(
'Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1448 if lhe_file_new
is None:
1449 os.remove(lhe_file_old)
1450 shutil.move(lhe_file_new_tmp,lhe_file_old)
1451 lhe_file_new_tmp = lhe_file_old
1453 elif delete_old_lhe:
1454 os.remove(lhe_file_old)
1456 return lhe_file_new_tmp
1524def modify_run_card(run_card_input=None,run_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,runArgs=None,settings={},skipBaseFragment=False):
1525 """Build a new run_card.dat from an existing one.
1526 This function can get a fresh runcard from DATAPATH or start from the process directory.
1527 Settings is a dictionary of keys (no spaces needed) and values to replace.
1530 global my_MGC_instance
1532 my_MGC_instance.runCardDict.update(settings)
1537 for s
in list(settings.keys()):
1538 settings_lower[s.lower()] = settings[s]
1541 if run_card_input
is None:
1543 elif run_card_input
is not None and not os.access(run_card_input,os.R_OK):
1544 runcard = subprocess.Popen([
'get_files',
'-data',run_card_input])
1546 if not os.access(run_card_input,os.R_OK):
1547 raise RuntimeError(
'Could not get run card '+run_card_input)
1550 isNLO = my_MGC_instance.isNLO
1552 if not skipBaseFragment:
1556 if runArgs
is not None:
1558 if 'iseed' not in settings_lower:
1559 settings_lower[
'iseed']=rand_seed
1560 if not isNLO
and 'python_seed' not in settings_lower:
1561 settings_lower[
'python_seed']=rand_seed
1562 if 'beamenergy' in settings_lower:
1563 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']))
1564 beamEnergy=settings_lower[
'beamenergy']
1565 settings_lower.pop(
'beamenergy')
1566 if 'ebeam1' not in settings_lower:
1567 settings_lower[
'ebeam1']=beamEnergy
1568 if 'ebeam2' not in settings_lower:
1569 settings_lower[
'ebeam2']=beamEnergy
1571 if 'nevents' in settings_lower:
1572 settings_lower[
'nevents'] = int(settings_lower[
'nevents'])
1575 if 'custom_fcts' in settings_lower
and settings_lower[
'custom_fcts']:
1576 raw_name = str(settings_lower[
'custom_fcts']).
split()[0]
1578 if runArgs
is not None and hasattr(runArgs,
'jobConfig'):
1579 cfgdir = runArgs.jobConfig[0]
if isinstance(runArgs.jobConfig, (list, tuple))
else runArgs.jobConfig
1581 full_path = os.path.join(cfgdir, raw_name)
1582 settings_lower[
'custom_fcts'] = os.path.abspath(full_path)
1583 print(f
"Using custom function(s), specified in custom_fcts with path: {settings_lower['custom_fcts']}")
1586 settings_lower[
'custom_fcts'] = os.path.abspath(raw_name)
1588 mglog.info(
'Modifying run card located at '+run_card_input)
1589 if run_card_backup
is not None:
1590 mglog.info(
'Keeping backup of original run card at '+run_card_backup)
1591 run_card_old = run_card_backup
1593 run_card_old = run_card_input+
'.old_to_be_deleted'
1594 mglog.debug(
'Modifying runcard settings: '+str(settings_lower))
1595 if os.path.isfile(run_card_old):
1596 os.unlink(run_card_old)
1597 os.rename(run_card_input, run_card_old)
1599 oldCard = open(run_card_old,
'r')
1600 newCard = open(process_dir+
'/Cards/run_card.dat',
'w')
1602 for line
in iter(oldCard):
1603 if not line.strip().startswith(
'#'):
1604 command = line.split(
'!', 1)[0]
1605 comment = line.split(
'!', 1)[1]
if '!' in line
else ''
1607 setting = command.split(
'=')[-1]
1608 stripped_setting = setting.strip()
1609 oldValue =
'='.join(command.split(
'=')[:-1])
1610 if stripped_setting.lower()
in settings_lower:
1612 if settings_lower[stripped_setting.lower()]
is None:
1614 mglog.info(
'Removing '+stripped_setting+
'.')
1615 used_settings += [ stripped_setting.lower() ]
1617 if stripped_setting.lower() ==
'custom_fcts':
1619 line =
' '+str(settings_lower[stripped_setting.lower()])+
' = '+setting
1621 line +=
' !'+comment
1623 line = oldValue.replace(oldValue.strip(), str(settings_lower[stripped_setting.lower()]))+
'='+setting
1625 line +=
' !' + comment
1626 mglog.info(
'Setting '+stripped_setting+
' = '+str(settings_lower[stripped_setting.lower()]))
1627 used_settings += [ stripped_setting.lower() ]
1628 newCard.write(line.strip()+
'\n')
1631 if 'mcatnlo_delta' in settings_lower:
1632 if settings_lower[
'mcatnlo_delta'] ==
'True':
1633 modify_config_card(process_dir=process_dir,settings={
'pythia8_path':os.getenv(
"PY8PATH")})
1637 for asetting
in settings_lower:
1638 if asetting
in used_settings:
1640 if settings_lower[asetting]
is None:
1642 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]) )
1643 newCard.write(
' '+str(settings_lower[asetting])+
' = '+str(asetting)+
'\n')
1647 mglog.info(
'Finished modification of run card.')
1648 if run_card_backup
is None:
1649 os.unlink(run_card_old)
1652def modify_config_card(config_card_backup=None,process_dir=MADGRAPH_GRIDPACK_LOCATION,settings={},set_commented=True):
1653 """Build a new configuration from an existing one.
1654 This function can get a fresh runcard from DATAPATH or start from the process directory.
1655 Settings is a dictionary of keys (no spaces needed) and values to replace.
1657 global my_MGC_instance
1659 my_MGC_instance.configCardDict.update(settings)
1661 config_card = my_MGC_instance.config_path
1664 mglog.info(
'Modifying config card located at '+config_card)
1665 if config_card_backup
is not None:
1666 mglog.info(
'Keeping backup of original config card at '+config_card_backup)
1667 config_card_old = config_card_backup
1669 config_card_old = config_card+
'.old_to_be_deleted'
1670 mglog.debug(
'Modifying config card settings: '+str(settings))
1671 if os.path.isfile(config_card_old):
1672 os.unlink(config_card_old)
1673 os.rename(config_card, config_card_old)
1675 oldCard = open(config_card_old,
'r')
1676 newCard = open(config_card,
'w')
1678 for line
in iter(oldCard):
1679 lmod = line
if set_commented
else line.split(
'#')[0]
1682 for setting
in settings:
1683 if setting
not in lmod:
1686 mglog.info(
'Setting '+setting.strip()+
' to '+str(settings[setting]))
1687 newCard.write(
' '+str(setting.strip())+
' = '+str(settings[setting])+
'\n')
1688 used_settings += [ setting.strip() ]
1696 for asetting
in settings:
1697 if asetting
in used_settings:
1699 if settings[asetting]
is None:
1701 mglog.warning(
'Option '+asetting+
' was not in the default config card. Adding by hand a setting to '+str(settings[asetting]) )
1702 newCard.write(
' '+str(asetting)+
' = '+str(settings[asetting])+
'\n')
1706 mglog.info(
'Finished modification of config card.')
1707 if config_card_backup
is None:
1708 os.unlink(config_card_old)