130def generate(process_dir='PROC_mssm_0', grid_pack=False, gridpack_compile=False, extlhapath=None, required_accuracy=0.01, runArgs=None, flags=None, bias_module=None, requirePMGSettings=False, pdf_setting=None):
131 global my_MGC_instance
135 my_MGC_instance.setup_path_protection()
140 if 'ATHENA_CORE_NUMBER' in os.environ
and int(os.environ[
'ATHENA_CORE_NUMBER'])>0:
141 njobs = int(os.environ[
'ATHENA_CORE_NUMBER'])
142 mglog.info(
'Lucky you - you are running on a full node queue. Will re-configure for '+str(njobs)+
' jobs.')
146 if cluster_type
is not None:
150 mglog.info(
'Running event generation from gridpack (using smarter mode from generate() function)')
151 if flags
is not None:
152 generate_from_gridpack(flags=flags,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings,pdf_setting=pdf_setting)
154 generate_from_gridpack(runArgs=runArgs,extlhapath=extlhapath,gridpack_compile=gridpack_compile,requirePMGSettings=requirePMGSettings,pdf_setting=pdf_setting)
157 mglog.info(
'Did not identify an input gridpack.')
159 mglog.info(
'The grid_pack flag is set, so I am expecting to create a gridpack in this job')
165 isNLO = my_MGC_instance.isNLO
176 if shutil.which(
'f2py')
is not None:
177 mglog.info(
'Found f2py, will use it for reweighting')
179 raise RuntimeError(
'Could not find f2py, needed for reweighting')
182 global MADGRAPH_COMMAND_STACK
186 mglog.info(
'Started generating gridpack at '+str(time.asctime()))
187 mglog.warning(
' >>>>>> THIS KIND OF JOB SHOULD ONLY BE RUN LOCALLY - NOT IN GRID JOBS <<<<<<')
190 my_settings = {
'nevents':
'1000'}
193 my_settings[
'req_acc']=str(required_accuracy)
196 LO_has_madspin =
False
197 if os.access(f
'{process_dir}/Cards/madspin_card.dat',os.R_OK):
198 MADGRAPH_COMMAND_STACK += [f
'mv {process_dir}/Cards/madspin_card.dat {process_dir}/Cards/madspin_card.tmp.dat']
199 os.rename(f
'{process_dir}/Cards/madspin_card.dat',f
'{process_dir}/Cards/madspin_card.tmp.dat')
200 LO_has_madspin =
True
201 my_settings = {
'gridpack':
'true'}
202 my_MGC_instance.runCardDict.update(my_settings)
205 mglog.info(
'Started generating at '+str(time.asctime()))
207 mglog.info(
'Run '+MADGRAPH_RUN_NAME+
' will be performed in mode '+str(mode)+
' with '+str(njobs)+
' jobs in parallel.')
210 if not os.access(process_dir,os.R_OK):
211 raise RuntimeError(
'No process directory found at '+process_dir)
212 if not os.access(process_dir+
'/bin/generate_events',os.R_OK):
213 raise RuntimeError(
'No generate_events module found in '+process_dir)
215 mglog.info(
'For your information, the libraries available are (should include LHAPDF):')
216 ls_dir(process_dir+
'/lib')
219 if bias_module
is not None:
222 mglog.info(
'Now I will hack the make files a bit. Apologies, but there seems to be no good way around this.')
223 shutil.copyfile(process_dir+
'/Source/make_opts',process_dir+
'/Source/make_opts_old')
224 old_opts = open(process_dir+
'/Source/make_opts_old',
'r')
225 new_opts = open(process_dir+
'/Source/make_opts',
'w')
226 for aline
in old_opts:
228 mglog.info(
'Configuring the fancy gfortran compiler instead of g77 / f77')
229 new_opts.write(
' FC=gfortran\n')
231 new_opts.write(aline)
234 mglog.info(
'Make file hacking complete.')
238 os.chdir(process_dir)
240 MADGRAPH_COMMAND_STACK += [
'cd ${MGaMC_PROCESS_DIR}' ]
243 my_MGC_instance.run_card_consistency_check()
247 code = check_PMG_updates(my_MGC_instance.paramCard)
248 if requirePMGSettings
and code!=0:
249 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
253 command = [python,
'bin/generate_events']
255 command += [
'--name='+MADGRAPH_RUN_NAME]
256 mglog.info(
'Removing Cards/shower_card.dat to ensure we get parton level events only')
258 os.unlink(
'Cards/shower_card.dat')
259 except FileNotFoundError:
260 mglog.info(
'Cannot find Cards/shower_card.dat.')
262 command += [MADGRAPH_RUN_NAME]
264 setNCores(process_dir=os.getcwd(), Ncores=njobs)
267 mglog.info(
'Setting up cluster running')
268 my_MGC_instance.configCardDict[
'run_mode'] = 1
270 if cluster_type==
'pbs':
271 mglog.info(
'Modifying bin/internal/cluster.py for PBS cluster running')
272 os.system(
"sed -i \"s:text += prog:text += './'+prog:g\" bin/internal/cluster.py")
274 mglog.info(
'Setting up multi-core running on '+os.environ[
'ATHENA_CORE_NUMBER']+
' cores')
276 mglog.info(
'Setting up serial generation.')
279 my_MGC_instance.write_configCard()
281 my_MGC_instance.paramCard.write_paramCard()
289 (out,err) = generate.communicate()
290 error_check(err,generate.returncode)
294 MADGRAPH_COMMAND_STACK += [
'cd -' ]
299 energy =
'%1.1f'%(beamEnergy*2./1000.)
300 energy = energy.replace(
'.0',
'').
replace(
'.',
'p')
301 gridpack_name=
'mc_'+energy+
'TeV.'+get_physics_short()+
'.MG'+get_mg5_version().
replace(
'.',
'')+
'.GRID.tar.gz'
302 mglog.info(
'Tidying up gridpack '+gridpack_name)
307 MADGRAPH_COMMAND_STACK += [f
'mv {process_dir}/Cards/madspin_card.tmp.dat {process_dir}/Cards/madspin_card.dat']
308 os.rename(f
'{process_dir}/Cards/madspin_card.tmp.dat',f
'{process_dir}/Cards/madspin_card.dat')
311 MADGRAPH_COMMAND_STACK += [
'cp '+glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0]+
' '+gridpack_name]
312 shutil.copy(glob.glob(process_dir+
'/'+MADGRAPH_RUN_NAME+
'_*gridpack.tar.gz')[0],gridpack_name)
315 MADGRAPH_COMMAND_STACK += [
'mkdir tmp%i/'%os.getpid(),
'cd tmp%i/'%os.getpid()]
316 os.mkdir(
'tmp%i/'%os.getpid())
317 os.chdir(
'tmp%i/'%os.getpid())
318 mglog.info(
'untar gridpack')
321 mglog.info(
'compile and clean up')
322 MADGRAPH_COMMAND_STACK += [
'cd madevent']
323 os.chdir(
'madevent/')
325 (out,err) = compilep.communicate()
326 error_check(err,compilep.returncode)
328 (out,err) = clean.communicate()
329 error_check(err,clean.returncode)
331 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm ../'+gridpack_name]
333 mglog.info(
'remove old tarball')
334 os.unlink(
'../'+gridpack_name)
335 mglog.info(
'Package up new tarball')
336 tar =
stack_subprocess([
'tar',
'--exclude=SubProcesses/P*/G*/*_results.dat',
'--exclude=SubProcesses/P*/G*/*.log',
'--exclude=SubProcesses/P*/G*/*.txt',
'-cvsf',
'../'+gridpack_name,
'.'])
338 MADGRAPH_COMMAND_STACK += [
'cd ..',
'rm -r tmp%i/'%os.getpid()]
340 mglog.info(
'Remove temporary directory')
341 shutil.rmtree(
'tmp%i/'%os.getpid())
342 mglog.info(
'Tidying up complete!')
347 mglog.info(
'Package up process_dir')
348 MADGRAPH_COMMAND_STACK += [
'mv '+process_dir+
' '+MADGRAPH_GRIDPACK_LOCATION]
349 os.rename(process_dir,MADGRAPH_GRIDPACK_LOCATION)
350 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])
352 MADGRAPH_COMMAND_STACK += [
'mv '+MADGRAPH_GRIDPACK_LOCATION+
' '+process_dir]
353 os.rename(MADGRAPH_GRIDPACK_LOCATION,process_dir)
355 mglog.info(
'Gridpack sucessfully created, exiting the transform')
358 mglog.info(
'Touching output TXT (LHE) file for the transform')
359 open(output_txt_file,
'w').close()
360 from AthenaCommon.AppMgr
import theApp
364 mglog.info(
'Finished at '+str(time.asctime()))
368def generate_from_gridpack(runArgs=None, flags=None, extlhapath=None, gridpack_compile=None, requirePMGSettings=False, pdf_setting=None):
369 global my_MGC_instance
375 my_MGC_instance.setup_path_protection()
377 isNLO = my_MGC_instance.isNLO
382 gridpack_run_name =
'GridRun_'+str(random_seed)
385 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',os.R_OK):
386 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat')
395 code = check_PMG_updates(my_MGC_instance.paramCard)
396 if requirePMGSettings
and code!=0:
397 raise RuntimeError(
'Settings are not compliant with PMG defaults! Please use do_PMG_updates function to get PMG default params.')
400 settings={
'iseed':str(random_seed)}
402 settings[
'python_seed']=str(random_seed)
403 my_MGC_instance.runCardDict.update(settings)
405 mglog.info(
'Generating events from gridpack')
408 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION):
409 raise RuntimeError(
'Gridpack directory not found at '+MADGRAPH_GRIDPACK_LOCATION)
411 nevents = my_MGC_instance.runCardDict[
'nevents']
412 mglog.info(
'>>>> FOUND GRIDPACK <<<< <- This will be used for generation')
413 mglog.info(
'Generation of '+str(int(nevents))+
' events will be performed using the supplied gridpack with random seed '+str(random_seed))
414 mglog.info(
'Started generating events at '+str(time.asctime()))
417 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py',os.R_OK):
418 os.remove(MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/addmasses.py')
423 setNCores(process_dir=MADGRAPH_GRIDPACK_LOCATION)
427 ls_dir(MADGRAPH_GRIDPACK_LOCATION)
430 my_MGC_instance.run_card_consistency_check()
437 systematics_settings=
None
438 if my_MGC_instance.runCardDict.get(
'systematics_program',
None) ==
'systematics':
439 if not my_MGC_instance.runCardDict.get(
'store_rwgt_info',
None):
440 raise RuntimeError(
'Trying to run NLO systematics but reweight info not stored')
441 if 'systematics_arguments' in my_MGC_instance.runCardDict:
442 systematics_settings=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(my_MGC_instance.runCardDict[
'systematics_arguments'])
444 systematics_settings={}
445 mglog.info(
'Turning off systematics for now, running standalone later')
449 my_MGC_instance.write_configCard()
450 my_MGC_instance.paramCard.write_paramCard()
452 global MADGRAPH_COMMAND_STACK
455 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun',os.R_OK):
456 mglog.error(
'/bin/gridrun not found at '+MADGRAPH_GRIDPACK_LOCATION)
457 raise RuntimeError(
'Could not find gridrun executable')
459 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/gridrun, starting generation.')
462 mglog.info(
"Now generating {} events with random seed {} and granularity {}".format(int(nevents),int(random_seed),granularity))
464 new_ld_path=
":".join([os.environ[
'LD_LIBRARY_PATH'],os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/madevent/lib',os.getcwd()+
'/'+MADGRAPH_GRIDPACK_LOCATION+
'/HELAS/lib'])
465 os.environ[
'LD_LIBRARY_PATH']=new_ld_path
466 MADGRAPH_COMMAND_STACK+=[
"export LD_LIBRARY_PATH="+
":".join([
'${LD_LIBRARY_PATH}',new_ld_path])]
467 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 _should_catch_errors()
else None)
468 (out,err) = generate.communicate()
469 error_check(err,generate.returncode)
470 gp_events=MADGRAPH_GRIDPACK_LOCATION+
"/Events/GridRun_{}/unweighted_events.lhe.gz".format(int(random_seed))
471 if not os.path.exists(gp_events):
472 mglog.error(
'Error in gp generation, did not find events at '+gp_events)
476 if reweight_card
is not None:
477 pythonpath_backup=os.environ[
'PYTHONPATH']
479 os.environ[
'PYTHONPATH']=
':'.join([p
for p
in pythonpath_backup.split(
':')
if 'madgraph5amc' not in p])
481 os.environ[
'PYTHONPATH']=pythonpath_backup
483 shutil.move(gp_events,
'events.lhe.gz')
487 if not os.access(MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events',os.R_OK):
488 raise RuntimeError(
'Could not find generate_events executable at '+MADGRAPH_GRIDPACK_LOCATION)
490 mglog.info(
'Found '+MADGRAPH_GRIDPACK_LOCATION+
'/bin/generate_events, starting generation.')
492 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
493 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name, os.F_OK):
494 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
' directory from gridpack generation')
495 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name]
496 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)
499 if os.access(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1', os.F_OK):
500 mglog.info(
'Removing '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1 directory from gridpack generation')
501 MADGRAPH_COMMAND_STACK += [
'rm -rf '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1']
502 shutil.rmtree(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'_decayed_1')
504 ls_dir(MADGRAPH_GRIDPACK_LOCATION+
'/Events/')
506 if not gridpack_compile:
507 mglog.info(
'Copying make_opts from Template')
508 shutil.copy(os.environ[
'MADPATH']+
'/Template/LO/Source/make_opts',MADGRAPH_GRIDPACK_LOCATION+
'/Source/')
511 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 _should_catch_errors()
else None)
512 (out,err) = generate.communicate()
513 error_check(err,generate.returncode)
515 mglog.info(
'Allowing recompilation of gridpack')
516 if os.path.islink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a'):
517 mglog.info(
'Unlinking '+MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
518 os.unlink(MADGRAPH_GRIDPACK_LOCATION+
'/lib/libLHAPDF.a')
521 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 _should_catch_errors()
else None)
522 (out,err) = generate.communicate()
523 error_check(err,generate.returncode)
524 if isNLO
and systematics_settings
is not None:
526 mglog.info(
'Running systematics standalone')
527 systematics_path=MADGRAPH_GRIDPACK_LOCATION+
'/bin/internal/systematics.py'
528 events_location=MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz'
530 syst_cmd=[python,systematics_path]+[events_location]*2+[
"--"+k+
"="+systematics_settings[k]
for k
in systematics_settings]
531 mglog.info(
'running: '+
' '.join(syst_cmd))
536 if not os.access(
'events.lhe.gz',os.R_OK):
537 mglog.info(
'Copying generated events to '+currdir)
538 if not os.path.exists(MADGRAPH_GRIDPACK_LOCATION+
'Events/'+gridpack_run_name):
539 shutil.copy(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/events.lhe.gz',
'events.lhe.gz')
541 mglog.info(
'Events were already in place')
545 mglog.info(
'Moving generated events to be in correct format for arrange_output().')
546 mglog.info(
'Unzipping generated events.')
550 mglog.info(
'Moving file over to '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
551 mkdir =
stack_subprocess([
'mkdir',
'-p',(MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name)])
553 shutil.move(
'events.lhe',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe')
555 mglog.info(
'Re-zipping into dataset name '+MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe.gz')
556 rezip =
stack_subprocess([
'gzip',MADGRAPH_GRIDPACK_LOCATION+
'/Events/'+gridpack_run_name+
'/unweighted_events.lhe'])
564 os.rename(MADGRAPH_GRIDPACK_LOCATION+
'/Cards/backup_madspin_card.dat',MADGRAPH_GRIDPACK_LOCATION+
'/Cards/madspin_card.dat')
565 mglog.info(
'Decaying with MadSpin.')
568 mglog.info(
'Finished at '+str(time.asctime()))
634def setupLHAPDF(process_dir=None, extlhapath=None, allow_links=True):
635 global my_MGC_instance
637 isNLO = my_MGC_instance.isNLO
639 origLHAPATH=os.environ[
'LHAPATH']
640 origLHAPDF_DATA_PATH=os.environ[
'LHAPDF_DATA_PATH']
642 LHAPATH,LHADATAPATH=get_LHAPDF_PATHS()
648 mydict= my_MGC_instance.runCardDict
649 if mydict[
"pdlabel"].
replace(
"'",
"") ==
'lhapdf':
651 mglog.info(
'creating local LHAPDF dir: MGC_LHAPDF/')
652 if os.path.islink(
'MGC_LHAPDF/'):
653 os.unlink(
'MGC_LHAPDF/')
654 elif os.path.isdir(
'MGC_LHAPDF/'):
655 shutil.rmtree(
'MGC_LHAPDF/')
657 newMGCLHA=
'MGC_LHAPDF/'
659 mkdir = subprocess.Popen([
'mkdir',
'-p',newMGCLHA])
662 pdfs_used=[ int(x)
for x
in mydict[
'lhaid'].
replace(
' ',
',').
split(
',') ]
664 if 'sys_pdf' in mydict:
670 pdfs_used.append(idx)
673 if 'systematics_arguments' in mydict:
674 systematics_arguments=MadGraphControl.MadGraphSystematicsUtils.parse_systematics_arguments(mydict[
'systematics_arguments'])
675 if 'pdf' in systematics_arguments:
681 pdfs_used.append(idx)
684 for pdf
in pdfs_used:
685 if isinstance(pdf,str)
and (pdf.lower()==
'errorset' or pdf.lower()==
'central'):
688 pdfid,pdfname=get_lhapdf_id_and_name(pdf)
689 mglog.info(
"Found LHAPDF ID="+str(pdfid)+
", name="+pdfname)
691 if not os.path.exists(newMGCLHA+pdfname)
and not os.path.lexists(newMGCLHA+pdfname):
692 if not os.path.exists(LHADATAPATH+
'/'+pdfname):
693 mglog.warning(
'PDF not installed at '+LHADATAPATH+
'/'+pdfname)
695 mglog.info(
'linking '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
696 os.symlink(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
698 mglog.info(
'copying '+LHADATAPATH+
'/'+pdfname+
' --> '+newMGCLHA+pdfname)
699 shutil.copytree(LHADATAPATH+
'/'+pdfname,newMGCLHA+pdfname)
702 mglog.info(
'linking '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
703 os.symlink(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
705 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
706 mglog.info(
'linking '+atlasLHADATAPATH+
'/lhapdf.conf --> '+newMGCLHA+
'lhapdf.conf')
707 os.symlink(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
709 mglog.info(
'copying '+LHADATAPATH+
'/pdfsets.index --> '+newMGCLHA+
'pdfsets.index')
710 shutil.copy2(LHADATAPATH+
'/pdfsets.index',newMGCLHA+
'pdfsets.index')
712 atlasLHADATAPATH=LHADATAPATH.replace(
'sft.cern.ch/lcg/external/lhapdfsets/current',
'atlas.cern.ch/repo/sw/Generators/lhapdfsets/current')
713 mglog.info(
'copying '+atlasLHADATAPATH+
'/lhapdf.conf -->'+newMGCLHA+
'lhapdf.conf')
714 shutil.copy2(atlasLHADATAPATH+
'/lhapdf.conf',newMGCLHA+
'lhapdf.conf')
717 LHADATAPATH=os.getcwd()+
'/MGC_LHAPDF'
720 mglog.info(
'Not using LHAPDF')
721 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
725 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
727 mglog.info(
'Path to LHAPDF install dir: '+LHAPATH)
728 mglog.info(
'Path to LHAPDF data dir: '+LHADATAPATH)
729 if not os.path.isdir(LHADATAPATH):
730 raise RuntimeError(
'LHAPDF data dir not accesible: '+LHADATAPATH)
731 if not os.path.isdir(LHAPATH):
732 raise RuntimeError(
'LHAPDF path dir not accesible: '+LHAPATH)
736 lhapdfconfig=extlhapath
737 if not os.access(lhapdfconfig,os.X_OK):
738 raise RuntimeError(
'Failed to find valid external lhapdf-config at '+lhapdfconfig)
739 LHADATAPATH=subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().
strip()
740 mglog.info(
'Changing LHAPDF_DATA_PATH to '+LHADATAPATH)
741 os.environ[
'LHAPDF_DATA_PATH']=LHADATAPATH
743 getlhaconfig = subprocess.Popen([
'get_files',
'-data',
'lhapdf-config'])
746 if not os.access(os.getcwd()+
'/lhapdf-config',os.X_OK):
747 mglog.error(
'Failed to get lhapdf-config from MadGraphControl')
749 lhapdfconfig = os.getcwd()+
'/lhapdf-config'
751 mglog.info(
'lhapdf-config --version: '+str(subprocess.Popen([lhapdfconfig,
'--version'],stdout = subprocess.PIPE).stdout.read().
strip()))
752 mglog.info(
'lhapdf-config --prefix: '+str(subprocess.Popen([lhapdfconfig,
'--prefix'],stdout = subprocess.PIPE).stdout.read().
strip()))
753 mglog.info(
'lhapdf-config --libdir: '+str(subprocess.Popen([lhapdfconfig,
'--libdir'],stdout = subprocess.PIPE).stdout.read().
strip()))
754 mglog.info(
'lhapdf-config --datadir: '+str(subprocess.Popen([lhapdfconfig,
'--datadir'],stdout = subprocess.PIPE).stdout.read().
strip()))
755 mglog.info(
'lhapdf-config --pdfsets-path: '+str(subprocess.Popen([lhapdfconfig,
'--pdfsets-path'],stdout = subprocess.PIPE).stdout.read().
strip()))
758 my_MGC_instance.configCardDict.update({
'lhapdf':lhapdfconfig,
'lhapdf_py3':lhapdfconfig})
760 mglog.info(
'Creating links for LHAPDF')
761 if os.path.islink(process_dir+
'/lib/PDFsets'):
762 os.unlink(process_dir+
'/lib/PDFsets')
763 elif os.path.isdir(process_dir+
'/lib/PDFsets'):
764 shutil.rmtree(process_dir+
'/lib/PDFsets')
766 os.symlink(LHADATAPATH,process_dir+
'/lib/PDFsets')
768 shutil.copytree(LHADATAPATH,process_dir+
'/lib/PDFsets')
769 mglog.info(
'Available PDFs are:')
770 mglog.info( sorted( [ x
for x
in os.listdir(process_dir+
'/lib/PDFsets')
if ".tar.gz" not in x ] ) )
772 global MADGRAPH_COMMAND_STACK
773 MADGRAPH_COMMAND_STACK += [
'# Copy the LHAPDF files locally' ]
774 MADGRAPH_COMMAND_STACK += [
'cp -r '+os.getcwd()+
'/MGC_LHAPDF .' ]
775 MADGRAPH_COMMAND_STACK += [
'cp -r '+process_dir+
'/lib/PDFsets ${MGaMC_PROCESS_DIR}/lib/' ]
777 return (LHAPATH,origLHAPATH,origLHAPDF_DATA_PATH)
903 """ Run MadSpin on an input LHE file. Takes the process
904 from the LHE file, so you don't need to have a process directory
905 set up in advance. Runs MadSpin and packs the LHE file up appropriately
906 Needs runArgs for the file handling"""
907 if not os.access(input_LHE,os.R_OK):
908 raise RuntimeError(
'Could not find LHE file '+input_LHE)
909 if not os.access(madspin_card,os.R_OK):
910 raise RuntimeError(
'Could not find input MadSpin card '+madspin_card)
912 shutil.copy(input_LHE,input_LHE+
'.original')
913 mglog.info(
'Put backup copy of LHE file at '+input_LHE+
'.original')
915 madspin_exec_card = open(
'madspin_exec_card',
'w')
916 madspin_exec_card.write(
'import '+input_LHE+
'\n')
918 input_madspin_card = open(madspin_card,
'r')
920 for l
in input_madspin_card.readlines():
921 commands = l.split(
'#')[0].
split()
923 if len(commands)>1
and 'import'==commands[0]
and not 'model'==commands[1]:
926 if len(commands)>0
and 'launch' == commands[0]:
928 madspin_exec_card.write(l.strip()+
'\n')
930 madspin_exec_card.write(
'launch\n')
931 madspin_exec_card.close()
932 input_madspin_card.close()
934 madpath=os.environ[
'MADPATH']
935 if not os.access(madpath+
'/MadSpin/madspin',os.R_OK):
936 raise RuntimeError(
'madspin executable not found in '+madpath)
937 mglog.info(
'Starting madspin at '+str(time.asctime()))
939 (out,err) = generate.communicate()
940 error_check(err,generate.returncode)
941 mglog.info(
'Done with madspin at '+str(time.asctime()))
945 if os.path.exists(os.getcwd()+
'/events.lhe'):
946 os.remove(os.getcwd()+
'/events.lhe')
948 mglog.info(
'Unzipping generated events.')
952 mglog.info(
'Putting a copy in place for the transform.')
953 mod_output = open(os.getcwd()+
'/events.lhe',
'w')
957 with open(input_LHE,
'r')
as fileobject:
958 for line
in fileobject:
960 mod_output.write(line)
965 mglog.info(
'Removed '+str(nEmpty)+
' empty lines from LHEF')
969 raise RuntimeError(
'Must provide runArgs to madspin_on_lhe')
971 outputDS = runArgs.outputTXTFile
if hasattr(runArgs,
'outputTXTFile')
else 'tmp_LHE_events.tar.gz'
973 mglog.info(
'Moving file over to '+outputDS.split(
'.tar.gz')[0]+
'.events')
974 shutil.move(os.getcwd()+
'/events.lhe',outputDS.split(
'.tar.gz')[0]+
'.events')
976 mglog.info(
'Re-zipping into dataset name '+outputDS)
977 rezip =
stack_subprocess([
'tar',
'cvzf',outputDS,outputDS.split(
'.tar.gz')[0]+
'.events'])
981 if hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
982 outputDS = outputDS.split(
'.TXT')[0]
984 if runArgs
is not None:
985 mglog.debug(
'Setting inputGenerator file to '+outputDS)
986 runArgs.inputGeneratorFile=outputDS
989def arrange_output(process_dir=MADGRAPH_GRIDPACK_LOCATION,lhe_version=None,saveProcDir=False,runArgs=None,flags=None,fixEventWeightsForBridgeMode=False,pdf_setting=None):
994 if len(glob.glob(os.path.join(process_dir,
'Events',
'*')))<1:
995 mglog.error(
'Process dir '+process_dir+
' does not contain events?')
996 proc_dir_list = glob.glob(os.path.join(process_dir,
'Events',
'*'))
999 for adir
in proc_dir_list:
1000 if 'decayed' in adir:
1003 if 'GridRun_' in adir:
1006 elif os.path.join(process_dir,
'Events',MADGRAPH_RUN_NAME)
in adir:
1008 if not os.access(this_run_name,os.R_OK):
1009 raise RuntimeError(
'Unable to locate run directory')
1011 hasUnweighted = os.access(this_run_name+
'/unweighted_events.lhe.gz',os.R_OK)
1014 madspinDirs=sorted(glob.glob(this_run_name+
'_decayed_*/'))
1015 if len(madspinDirs):
1017 if hasRunMadSpin
and not hasUnweighted:
1019 hasUnweighted = os.access(madspinDirs[-1]+
'/unweighted_events.lhe.gz',os.R_OK)
1021 global MADGRAPH_COMMAND_STACK
1023 if len(madspinDirs):
1030 if os.path.exists(madspinDirs[-1]+
'/unweighted_events.lhe.gz'):
1031 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/unweighted_events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
1032 shutil.move(madspinDirs[-1]+
'/unweighted_events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
1033 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/unweighted_events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1034 elif os.path.exists(madspinDirs[-1]+
'/events.lhe.gz'):
1035 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz'+
' '+this_run_name+
'/unweighted_events.lhe.gz']
1036 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/unweighted_events.lhe.gz')
1037 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/unweighted_events.lhe.gz')
1039 raise RuntimeError(
'MadSpin was run but can\'t find files :(')
1042 MADGRAPH_COMMAND_STACK += [
'mv '+madspinDirs[-1]+
'/events.lhe.gz '+this_run_name+
'/events.lhe.gz']
1043 shutil.move(madspinDirs[-1]+
'/events.lhe.gz',this_run_name+
'/events.lhe.gz')
1044 mglog.info(
'Moving MadSpin events from '+madspinDirs[-1]+
'/events.lhe.gz to '+this_run_name+
'/events.lhe.gz')
1047 mglog.error(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1048 raise RuntimeError(
'MadSpin was run but can\'t find output folder '+(this_run_name+
'_decayed_1/'))
1050 if fixEventWeightsForBridgeMode:
1051 mglog.info(
"Fixing event weights after MadSpin... initial checks.")
1059 eventsfilename=
"unweighted_events"
1061 eventsfilename=
"events"
1062 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/%s.lhe.gz' % eventsfilename])
1065 for line
in open(process_dir+
'/Events/'+MADGRAPH_RUN_NAME+
'/%s.lhe'%eventsfilename):
1066 if "Number of Events" in line:
1068 MGnumevents=int(sline[-1])
1069 elif "Integrated weight (pb)" in line:
1071 MGintweight=float(sline[-1])
1072 elif "set spinmode none" in line:
1074 elif "</header>" in line:
1077 if spinmodenone
and MGnumevents>0
and MGintweight>0:
1078 mglog.info(
"Fixing event weights after MadSpin... modifying LHE file.")
1079 newlhe=open(this_run_name+
'/%s_fixXS.lhe'%eventsfilename,
'w')
1087 event_norm_setting=
"average"
1089 for line
in open(this_run_name+
'/%s.lhe'%eventsfilename):
1092 if "<init>" in line:
1095 elif "</init>" in line:
1097 elif inInit
and initlinecount==0:
1101 if abs(int(sline[-2])) == 3:
1102 event_norm_setting=
"sum"
1103 elif abs(int(sline[-2])) == 4:
1104 event_norm_setting=
"average"
1105 elif inInit
and initlinecount==1:
1108 relunc=float(sline[1])/float(sline[0])
1109 sline[0]=str(MGintweight)
1110 sline[1]=str(float(sline[0])*relunc)
1111 if event_norm_setting==
"sum":
1112 sline[2]=str(MGintweight/MGnumevents)
1113 elif event_norm_setting==
"average":
1114 sline[2]=str(MGintweight)
1115 newline=
' '.join(sline)
1118 elif inInit
and initlinecount>1:
1120 elif "<event>" in line:
1123 elif "</event>" in line:
1125 elif inEvent
and eventlinecount==0:
1128 if event_norm_setting==
"sum":
1129 sline[2]=str(MGintweight/MGnumevents)
1130 elif event_norm_setting==
"average":
1131 sline[2]=str(MGintweight)
1132 newline=
' '.join(sline)
1135 newlhe.write(newline)
1138 mglog.info(
"Fixing event weights after MadSpin... cleaning up.")
1139 shutil.copyfile(this_run_name+
'/%s.lhe' % eventsfilename,
1140 this_run_name+
'/%s_badXS.lhe' % eventsfilename)
1142 shutil.move(this_run_name+
'/%s_fixXS.lhe' % eventsfilename,
1143 this_run_name+
'/%s.lhe' % eventsfilename)
1145 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s.lhe' % eventsfilename])
1148 rezip =
stack_subprocess([
'gzip',this_run_name+
'/%s_badXS.lhe' % eventsfilename])
1152 if os.path.exists(os.getcwd()+
'/events.lhe'):
1153 os.remove(os.getcwd()+
'/events.lhe')
1155 mglog.info(
'Unzipping generated events.')
1157 unzip =
stack_subprocess([
'gunzip',
'-f',this_run_name+
'/unweighted_events.lhe.gz'])
1163 mglog.info(
'Putting a copy in place for the transform.')
1165 orig_input = this_run_name+
'/unweighted_events.lhe'
1166 mod_output = open(os.getcwd()+
'/events.lhe',
'w')
1168 orig_input = this_run_name+
'/events.lhe'
1169 mod_output = open(os.getcwd()+
'/events.lhe',
'w')
1176 with open(orig_input,
'r')
as fileobject:
1177 for line
in fileobject:
1181 if '#' not in newline:
1183 elif '>' not in newline[ newline.find(
'#'): ]:
1186 mglog.info(
'Found bad LHE line with an XML mark in a comment: "'+newline.strip()+
'"')
1187 newline=newline[:newline.find(
'#')]+
'#'+ (newline[newline.find(
'#'):].
replace(
'>',
'-'))
1189 if initrwgt
is False:
1191 elif "</initrwgt>" in newline:
1193 elif "<initrwgt>" in newline:
1195 elif initrwgt
is not None:
1196 newline=newline.replace(
'_DYNSCALE-1',
'')
1197 if '</weight>' in newline:
1198 iend=newline.find(
'</weight>')
1199 istart=newline[:iend].rfind(
'>')
1200 lhe_weights+=[newline[istart+1:iend].
strip()]
1201 mod_output.write(newline)
1205 mglog.info(
'Removed '+str(nEmpty)+
' empty lines from LHEF')
1207 mglog.info(
"The following "+str(len(lhe_weights))+
" weights have been written to the LHE file: "+
",".join(lhe_weights))
1210 mglog.info(
"Checking whether the following expected weights are in LHE file: "+
",".join(expected_weights))
1211 for w
in expected_weights:
1212 if w
not in lhe_weights:
1213 raise RuntimeError(
"Did not find expected weight "+w+
" in lhe file. Did the reweight or systematics module crash?")
1214 mglog.info(
"Found all required weights!")
1217 mod_output2 = open(os.getcwd()+
'/events.lhe',
'r')
1218 test=mod_output2.readline()
1219 if 'version="' in test:
1220 mglog.info(
'Applying LHE version hack')
1221 final_file = open(os.getcwd()+
'/events.lhe.copy',
'w')
1222 final_file.write(
'<LesHouchesEvents version="%i.0">\n'%lhe_version)
1223 shutil.copyfileobj(mod_output2, final_file)
1225 shutil.copy(os.getcwd()+
'/events.lhe.copy',os.getcwd()+
'/events.lhe')
1227 os.remove(os.getcwd()+
'/events.lhe.copy')
1232 if outputDS
is None:
1233 outputDS =
'tmp_LHE_events.tar.gz'
1234 if flags
is not None and hasattr(flags,
'Generator')
and hasattr(flags.Generator,
'avoidExtracting')
and flags.Generator.avoidExtracting:
1235 outputDS =
'tmp_LHE_events.gz'
1236 elif runArgs
is not None and hasattr(runArgs,
'avoidExtracting')
and runArgs.avoidExtracting:
1237 outputDS =
'tmp_LHE_events.gz'
1239 outputStem = outputDS
1240 if '.tar.gz' in outputDS:
1241 outputStem = outputDS.split(
'.tar.gz')[0]
1242 elif '.tgz' in outputDS:
1243 outputStem = outputDS.split(
'.tgz')[0]
1244 elif '.gz' in outputDS:
1245 outputStem = outputDS.split(
'.gz')[0]
1247 mglog.warning(f
'Could not figure out what output file type {outputDS} refers to')
1248 outputStem = outputDS.split(
'.')[0]
1249 outputStem +=
'.events'
1251 mglog.info(
'Moving file over to '+outputStem)
1252 shutil.move(os.getcwd()+
'/events.lhe',outputStem)
1254 if '.tar.gz' in outputDS
or '.tgz' in outputDS:
1255 mglog.info(
'Re-zipping + tarring into dataset name '+outputDS)
1258 elif '.gz' in outputDS:
1259 mglog.info(
'Re-zipping into dataset name '+outputDS)
1262 shutil.move(outputStem+
'.gz',outputDS)
1264 mglog.info(f
'Could not understand output type for {outputDS} - will leave uncompressed')
1267 mglog.info(
'Removing the process directory')
1268 shutil.rmtree(process_dir,ignore_errors=
True)
1270 if os.path.isdir(
'MGC_LHAPDF/'):
1271 shutil.rmtree(
'MGC_LHAPDF/',ignore_errors=
True)
1274 if runArgs
is not None and hasattr(runArgs,
'outputTXTFile')
and runArgs.outputTXTFile
is not None:
1275 outputDS = outputDS.split(
'.TXT')[0]
1277 if runArgs
is not None:
1278 mglog.debug(
'Setting inputGenerator file to '+outputDS)
1279 runArgs.inputGeneratorFile=outputDS
1281 mglog.info(
'All done with output arranging!')
1319 run_card = process_dir+
'/Cards/run_card.dat'
1320 if isinstance(bias_module,tuple):
1321 mglog.info(
'Using bias module '+bias_module[0])
1322 the_run_card = open(run_card,
'r')
1323 for line
in the_run_card:
1324 if 'bias_module' in line
and not bias_module[0]
in line:
1325 raise RuntimeError(
'You need to add the bias module '+bias_module[0]+
' to the run card to actually run it')
1326 the_run_card.close()
1327 if len(bias_module)!=3:
1328 raise RuntimeError(
'Please give a 3-tuple of strings containing bias module name, bias module, and makefile. Alternatively, give path to bias module tarball.')
1329 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module[0]
1330 os.makedirs(bias_module_newpath)
1331 bias_module_file=open(bias_module_newpath+
'/'+bias_module[0]+
'.f',
'w')
1332 bias_module_file.write(bias_module[1])
1333 bias_module_file.close()
1334 bias_module_make_file=open(bias_module_newpath+
'/Makefile',
'w')
1335 bias_module_make_file.write(bias_module[2])
1336 bias_module_make_file.close()
1338 mglog.info(
'Using bias module '+bias_module)
1339 bias_module_name=bias_module.split(
'/')[-1].
replace(
'.gz',
'')
1340 bias_module_name=bias_module_name.replace(
'.tar',
'')
1341 the_run_card = open(run_card,
'r')
1342 for line
in the_run_card:
1343 if 'bias_module' in line
and bias_module_name
not in line:
1344 raise RuntimeError(
'You need to add the bias module '+bias_module_name+
' to the run card to actually run it')
1345 the_run_card.close()
1347 if os.path.exists(bias_module+
'.tar.gz'):
1348 bias_module_path=bias_module+
'.tar.gz'
1349 elif os.path.exists(bias_module+
'.gz'):
1350 bias_module_path=bias_module+
'.gz'
1351 elif os.path.exists(bias_module):
1352 bias_module_path=bias_module
1354 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')
1356 bias_module_newpath=process_dir+
'/Source/BIAS/'+bias_module_path.split(
'/')[-1]
1357 mglog.info(
'Copying bias module into place: '+bias_module_newpath)
1358 shutil.copy(bias_module_path,bias_module_newpath)
1359 mglog.info(
'Unpacking bias module')
1360 if bias_module_newpath.endswith(
'.tar.gz'):
1361 untar =
stack_subprocess([
'tar',
'xvzf',bias_module_newpath,
'--directory='+process_dir+
'/Source/BIAS/'])
1363 elif bias_module_path.endswith(
'.gz'):
1410def update_lhe_file(lhe_file_old,param_card_old=None,lhe_file_new=None,masses={},delete_old_lhe=True):
1411 """Build a new LHE file from an old one and an updated param card.
1412 The masses of some particles can be changed via the masses dictionary. No particles that appear in the events
1413 may have their masses changed.
1414 If the param card is provided, the decay block in the LHE file will be replaced with the one in the param card.
1415 By default, the old LHE file is removed.
1416 If None is provided as a new LHE file name, the new file will replace the old one."""
1418 lhe_file_new_tmp = lhe_file_new
if lhe_file_new
is not None else lhe_file_old+
'.tmp'
1420 if not os.access(lhe_file_old,os.R_OK):
1421 raise RuntimeError(
'Could not access old LHE file at '+str(lhe_file_old)+
'. Please check the file location.')
1423 if param_card_old
is not None:
1424 paramcard = subprocess.Popen([
'get_files',
'-data',param_card_old])
1426 if not os.access(param_card_old,os.R_OK):
1427 raise RuntimeError(
'Could not get param card '+param_card_old)
1429 if os.access(lhe_file_new_tmp,os.R_OK):
1430 raise RuntimeError(
'Old file at'+str(lhe_file_new_tmp)+
' in the current directory. Dont want to clobber it. Please move it first.')
1432 newlhe = open(lhe_file_new_tmp,
'w')
1436 particles_in_events = []
1439 with open(lhe_file_old,
'r')
as fileobject:
1440 for line
in fileobject:
1441 if decayEdit
and '</slha>' not in line:
1443 if decayEdit
and '</slha>' in line:
1445 if line.strip().
upper().startswith(
'BLOCK')
or line.strip().
upper().startswith(
'DECAY')\
1446 and len(line.strip().
split()) > 1:
1447 pos = 0
if line.strip().startswith(
'DECAY')
else 1
1448 blockName = line.strip().
upper().
split()[pos]
1451 if blockName !=
'DECAY' and len(line.strip().
split()) > 0:
1452 akey = line.strip().
split()[0]
1453 elif blockName ==
'DECAY' and len(line.strip().
split()) > 1:
1454 akey = line.strip().
split()[1]
1457 if akey
is not None and blockName ==
'MASS' and akey
in masses:
1458 newlhe.write(
' '+akey+
' '+str(masses[akey])+
' # \n')
1459 mglog.info(
' '+akey+
' '+str(masses[akey])+
' #')
1464 if blockName ==
'DECAY' and param_card_old
is not None:
1466 oldparam = open(param_card_old,
'r')
1468 for old_line
in oldparam.readlines():
1470 if old_line.strip().
upper().startswith(
'DECAY')
and len(old_line.strip().
split()) > 1:
1471 newBlockName = line.strip().
upper().
split()[pos]
1473 newlhe.write(old_line)
1474 elif newBlockName ==
'DECAY':
1476 newlhe.write(old_line)
1484 if not eventRead
and '<event>' in line:
1487 if len(line.split())==11:
1488 aparticle = line.split()[0]
1489 if aparticle
not in particles_in_events:
1490 particles_in_events += [aparticle]
1497 if akey
in particles_in_events:
1498 mglog.error(
'Attempted to change mass of a particle that was in an LHE event! This is not allowed!')
1505 if lhe_file_new
is None:
1506 os.remove(lhe_file_old)
1507 shutil.move(lhe_file_new_tmp,lhe_file_old)
1508 lhe_file_new_tmp = lhe_file_old
1510 elif delete_old_lhe:
1511 os.remove(lhe_file_old)
1513 return lhe_file_new_tmp