3 """Functionality core of the Gen_tf transform"""
13 import os, re, string, subprocess
14 import AthenaCommon.AlgSequence
as acas
15 import AthenaCommon.AppMgr
as acam
16 from AthenaCommon.AthenaCommonFlags
import jobproperties
18 from xAODEventInfoCnv.xAODEventInfoCnvConf
import xAODMaker__EventInfoCnvAlg
19 acam.athMasterSeq += xAODMaker__EventInfoCnvAlg(xAODKey=
"TMPEvtInfo")
22 acam.athMasterSeq += acas.AlgSequence(
"EvgenGenSeq")
23 genSeq = acam.athMasterSeq.EvgenGenSeq
24 acam.athMasterSeq += acas.AlgSequence(
"EvgenFixSeq")
25 fixSeq = acam.athMasterSeq.EvgenFixSeq
26 acam.athMasterSeq += acas.AlgSequence(
"EvgenPreFilterSeq")
27 prefiltSeq = acam.athMasterSeq.EvgenPreFilterSeq
28 acam.athMasterSeq += acas.AlgSequence(
"EvgenTestSeq")
29 testSeq = acam.athMasterSeq.EvgenTestSeq
31 from EvgenProdTools.LogicalExpressionFilter
import LogicalExpressionFilter
33 filtSeq = acam.athMasterSeq.EvgenFilterSeq
34 topSeq = acas.AlgSequence()
36 topSeq += acas.AlgSequence(
"EvgenPostSeq")
37 postSeq = topSeq.EvgenPostSeq
46 import AthenaCommon.AtlasUnixGeneratorJob
47 include(
"PartPropSvc/PartPropSvc.py")
50 from PerfMonComps.PerfMonFlags
import jobproperties
as perfmonjp
51 perfmonjp.PerfMonFlags.doFastMonMT =
True
54 from RngComps.RngCompsConf
import AthRNGSvc
58 jobproperties.AthenaCommonFlags.AllowIgnoreConfigError =
False
61 from AthenaCommon.Logging
import logging
62 evgenLog = logging.getLogger(
'Gen_tf')
69 evgenLog.debug(
"****************** CHECKING EVENT GENERATION ARGS *****************")
70 evgenLog.debug(
str(runArgs))
72 if hasattr(runArgs,
"inputGeneratorFile"):
73 evgenLog.info(
"inputGeneratorFile = " + runArgs.inputGeneratorFile)
75 if hasattr(runArgs,
"outputYODAFile"):
76 evgenLog.info(
"specified outputYODAFile = " + runArgs.outputYODAFile)
80 if not hasattr(runArgs,
"outputEVNTFile")
and not hasattr(runArgs,
"outputEVNT_PreFile"):
81 if hasattr(runArgs,
"outputYODAFile"):
82 evgenLog.info(
"No outputEVNTFile specified but outputYODAFile is used")
83 evgenLog.info(
"Will run GENtoEVGEN without saving the output EVNT file, asuming a valid outputYODAFile will be produced")
85 raise RuntimeError(
"No output evgen EVNT or EVNT_Pre file provided.")
88 if not hasattr(runArgs,
"ecmEnergy"):
89 raise RuntimeError(
"No center of mass energy provided.")
91 evgenLog.info(
' ecmEnergy = ' +
str(runArgs.ecmEnergy) )
92 if not hasattr(runArgs,
"randomSeed"):
93 raise RuntimeError(
"No random seed provided.")
95 if not hasattr(runArgs,
"firstEvent"):
96 raise RuntimeError(
"No first number provided.")
97 if ( runArgs.firstEvent <= 0):
98 evgenLog.warning(
"Run argument firstEvent should be > 0")
105 evgenLog.debug(
"****************** CONFIGURING EVENT GENERATION *****************")
109 from EvgenJobTransforms.EvgenConfig
import evgenConfig
110 from GeneratorConfig.GenConfigHelpers
import gens_known, gen_lhef, gens_lhef, gen_sortkey, gens_testhepmc, gens_notune, gen_require_steering
113 from EvgenProdTools.EvgenProdToolsConf
import FixHepMC
114 if not hasattr(fixSeq,
"FixHepMC"):
118 from EvgenProdTools.EvgenProdToolsConf
import TestHepMC
119 testSeq += TestHepMC(CmEnergy=runArgs.ecmEnergy*Units.GeV)
121 if not hasattr(svcMgr,
'THistSvc'):
122 from GaudiSvc.GaudiSvcConf
import THistSvc
124 svcMgr.THistSvc.Output = [
"TestHepMCname DATAFILE='TestHepMC.root' OPT='RECREATE'"]
128 from EvgenProdTools.EvgenProdToolsConf
import CopyEventWeight
129 if not hasattr(postSeq,
"CopyEventWeight"):
130 postSeq += CopyEventWeight(mcEventWeightsKey=
"TMPEvtInfo.mcEventWeights")
132 from EvgenProdTools.EvgenProdToolsConf
import FillFilterValues
133 if not hasattr(postSeq,
"FillFilterValues"):
134 postSeq += FillFilterValues(mcFilterHTKey=
"TMPEvtInfo.mcFilterHT")
138 from EvgenProdTools.EvgenProdToolsConf
import CountHepMC
139 svcMgr.EventSelector.FirstEvent = runArgs.firstEvent
145 if not hasattr(postSeq,
"CountHepMC"):
146 postSeq += CountHepMC(InputEventInfo=
"TMPEvtInfo",
147 OutputEventInfo=
"EventInfo",
148 mcEventWeightsKey=
"TMPEvtInfo.mcEventWeights")
151 postSeq.CountHepMC.FirstEvent = runArgs.firstEvent
152 postSeq.CountHepMC.CorrectHepMC =
True
153 postSeq.CountHepMC.CorrectEventID =
True
157 if hasattr(runArgs,
"printEvts")
and runArgs.printEvts > 0:
158 from TruthIO.TruthIOConf
import PrintMC
160 postSeq.PrintMC.McEventKey =
"GEN_EVENT"
161 postSeq.PrintMC.VerboseOutput =
True
162 postSeq.PrintMC.PrintStyle =
"Barcode"
163 postSeq.PrintMC.FirstEvent = 1
164 postSeq.PrintMC.LastEvent = runArgs.printEvts
167 from EvgenProdTools.EvgenProdToolsConf
import SimTimeEstimate
168 if not hasattr(postSeq,
"SimTimeEstimate"):
169 postSeq += SimTimeEstimate()
173 if hasattr(runArgs,
"rivetAnas"):
174 from Rivet_i.Rivet_iConf
import Rivet_i
176 anaSeq.Rivet_i.Analyses = runArgs.rivetAnas
177 anaSeq.Rivet_i.AnalysisPath = os.environ[
'PWD']
178 if hasattr(runArgs,
"outputYODAFile"):
179 anaSeq.Rivet_i.HistoFile = runArgs.outputYODAFile
182 rel = os.popen(
"echo $AtlasVersion").
read()
184 if not rel
or int(rel[:2]) > 22:
185 from AthenaCommon.AppMgr
import ServiceMgr
186 ServiceMgr.EventSelector.EventsPerRun =
int(2**63 - 1)
193 evgenLog.debug(
"****************** LOADING PRE-INCLUDES AND JOB CONFIG *****************")
196 if hasattr(runArgs,
"preInclude"):
197 for fragment
in runArgs.preInclude:
201 if hasattr(runArgs,
"preExec"):
202 evgenLog.info(
"Transform pre-exec")
203 for cmd
in runArgs.preExec:
208 return [name
for name
in os.listdir(a_dir)
209 if os.path.isdir(os.path.join(a_dir, name))]
214 if hasattr(runArgs,
"outputTXTFile"): outputTXTFile=runArgs.outputTXTFile
218 if len(runArgs.jobConfig) != 1:
219 evgenLog.info(
"runArgs.jobConfig = %s" % runArgs.jobConfig)
220 evgenLog.error(
"You must supply one and only one jobConfig file argument")
223 evgenLog.info(
"Using JOBOPTSEARCHPATH (as seen in skeleton) = '%s'" % os.environ[
"JOBOPTSEARCHPATH"])
224 FIRST_DIR = (os.environ[
'JOBOPTSEARCHPATH']).
split(
":")[0]
226 jofiles = [f
for f
in os.listdir(FIRST_DIR)
if (f.startswith(
'mc')
and f.endswith(
'.py'))]
228 evgenLog.error(
"You must supply one and only one jobOption file in DSID directory")
232 joparts = (os.path.basename(jofile)).
split(
".")
235 if joparts[0].startswith(
"mc")
and all(c
in string.digits
for c
in joparts[0][2:]):
238 if len(joparts) != 3:
239 evgenLog.error(jofile +
" name format is wrong: must be of the form mc.<physicsShort>.py: please rename.")
242 jo_physshortpart = joparts[1]
243 max_jo_physshort_length = 50
244 if len(jo_physshortpart) > max_jo_physshort_length:
245 evgenLog.error(f
"{jofile} contains a physicsShort field of more than {max_jo_physshort_length} characters: please rename.")
248 jo_physshortparts = jo_physshortpart.split(
"_")
249 if len(jo_physshortparts) < 2:
250 evgenLog.error(jofile +
" has too few physicsShort fields separated by '_': should contain <generators>(_<tune+PDF_if_available>)_<process>. Please rename.")
253 check_jofiles=
"/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/scripts/check_jo_consistency.py"
254 if os.path.exists(check_jofiles):
256 check_naming(os.path.basename(jofile))
258 evgenLog.waring(
"check_jo_consistency.py not found, will proceed without JOs check.")
269 evgenLog.debug(
"****************** CHECKING EVGEN CONFIGURATION *****************")
271 if hasattr(runArgs,
'inputGeneratorFile')
and int(evgenConfig.inputFilesPerJob) == 0 :
272 evgenConfig.inputFilesPerJob = 1
275 for opt
in str(evgenConfig).
split(os.linesep):
277 evgenLog.info(
".transform = Gen_tf")
280 evgenLog.info(
".platform = "+
str(os.environ[
'BINARY_TAG']))
285 if evgenConfig.obsolete:
286 evgenLog.error(
"JOs or icludes are obsolete, please check them")
289 if not evgenConfig.generators:
290 evgenLog.error(
"No entries in evgenConfig.generators: invalid configuration, please check your JO")
293 if len(evgenConfig.generators) > len(
set(evgenConfig.generators)):
294 evgenLog.error(
"Duplicate entries in evgenConfig.generators: invalid configuration, please check your JO")
297 gennames =
sorted(evgenConfig.generators, key=gen_sortkey)
299 if joparts[0].startswith(
"MC"):
300 genpart = jo_physshortparts[0]
301 expectedgenpart =
''.
join(gennames)
303 expectedgenpart = expectedgenpart.replace(
"HerwigJimmy",
"Herwig")
308 return s.replace(
"Py",
"Pythia").
replace(
"MG",
"MadGraph").
replace(
"Ph",
"Powheg").
replace(
"Hpp",
"Herwigpp").
replace(
"H7",
"Herwig7").
replace(
"Sh",
"Sherpa").
replace(
"Ag",
"Alpgen").
replace(
"EG",
"EvtGen").
replace(
"PG",
"ParticleGun").
replace(
"Gva",
"Geneva")
311 return s.replace(
"Pythia",
"Py").
replace(
"MadGraph",
"MG").
replace(
"Powheg",
"Ph").
replace(
"Herwigpp",
"Hpp").
replace(
"Herwig7",
"H7").
replace(
"Sherpa",
"Sh").
replace(
"Alpgen",
"Ag").
replace(
"EvtGen",
"EG").
replace(
"PG",
"ParticleGun").
replace(
"Geneva",
"Gva")
313 if genpart !=
_norm(expectedgenpart)
and _norm2(genpart) !=
_norm(expectedgenpart):
314 evgenLog.error(
"Expected first part of JO name to be '%s' or '%s', but found '%s'" % (
_norm(expectedgenpart),
_norm(
_short2(expectedgenpart)), genpart))
315 evgenLog.error(
"gennames '%s' " %(expectedgenpart))
320 if not gens_notune(gennames)
and len(jo_physshortparts) < 3:
321 evgenLog.error(jofile +
" with generators " + expectedgenpart +
322 " has too few physicsShort fields separated by '_'." +
323 " It should contain <generators>_<tune+PDF_<process>. Please rename.")
329 if hasattr(runArgs,
"outputEVNTFile")
and not hasattr(runArgs,
"outputEVNT_PreFile"):
330 raise RuntimeError(
"'EvtGen' found in job options name, please set '--steering=afterburn'")
336 if hasattr(runArgs,
'inputGeneratorFile')
and ',' in runArgs.inputGeneratorFile: multiInput = runArgs.inputGeneratorFile.count(
',')+1
341 if not evgenConfig.nEventsPerJob:
342 evgenLog.info(
'#############################################################')
343 evgenLog.info(
' !!!! no nEventsPerJob set !!! The default 10000 used. !!! ')
344 evgenLog.info(
'#############################################################')
346 evgenLog.info(
' nEventsPerJob = ' +
str(evgenConfig.nEventsPerJob) )
348 if evgenConfig.minevents > 0 :
349 raise RuntimeError(
"evgenConfig.minevents is obsolete and should be removed from the JOs")
350 if evgenConfig.nEventsPerJob < 1:
351 raise RuntimeError(
"evgenConfig.nEventsPerJob must be at least 1")
352 elif evgenConfig.nEventsPerJob > 100000:
353 raise RuntimeError(
"evgenConfig.nEventsPerJob can be max. 100000")
355 allowed_nEventsPerJob_lt1000 = [1, 2, 5, 10, 20, 25, 50, 100, 200, 500, 1000]
356 msg =
"evgenConfig.nEventsPerJob = %d: " % evgenConfig.nEventsPerJob
358 if evgenConfig.nEventsPerJob >= 1000
and evgenConfig.nEventsPerJob <=10000
and (evgenConfig.nEventsPerJob % 1000 != 0
or 10000 % evgenConfig.nEventsPerJob != 0):
359 msg +=
"nEventsPerJob in range [1K, 10K] must be a multiple of 1K and a divisor of 10K"
360 raise RuntimeError(msg)
361 elif evgenConfig.nEventsPerJob > 10000
and evgenConfig.nEventsPerJob % 10000 != 0:
362 msg +=
"nEventsPerJob >10K must be a multiple of 10K"
363 raise RuntimeError(msg)
364 elif evgenConfig.nEventsPerJob < 1000
and evgenConfig.nEventsPerJob
not in allowed_nEventsPerJob_lt1000:
365 msg +=
"nEventsPerJob in range <= 1000 must be one of %s" % allowed_nEventsPerJob_lt1000
366 raise RuntimeError(msg)
367 postSeq.CountHepMC.RequestedOutput = evgenConfig.nEventsPerJob
if runArgs.maxEvents == -1
else runArgs.maxEvents
368 evgenLog.info(
'Requested output events = '+
str(postSeq.CountHepMC.RequestedOutput))
371 if evgenConfig.keywords:
372 from GeneratorConfig.GenConfigHelpers
import checkKeywords
376 if evgenConfig.categories:
379 lkwfile =
"CategoryList.txt"
381 for p
in os.environ[
"DATAPATH"].
split(
":"):
382 lkwpath = os.path.join(p, lkwfile)
383 if os.path.exists(lkwpath):
389 with open(lkwpath,
'r')
as catlist:
391 allowed_list = ast.literal_eval(line)
392 allowed_cat.append(allowed_list)
396 it = iter(evgenConfig.categories)
400 if "L1:" in l2
and "L2:" in l1:
402 print (
"first",l1,
"second",l2)
403 bad_cat.extend([l1, l2])
404 for a1,a2
in allowed_cat:
405 if l1.strip().lower()==a1.strip().lower()
and l2.strip().lower()==a2.strip().lower():
408 msg =
"evgenConfig.categories contains non-standard category: %s. " %
", ".
join(bad_cat)
409 msg +=
"Please check the allowed categories list and fix."
414 evgenLog.warning(
"Could not find CategoryList.txt file %s in $DATAPATH" % lkwfile)
416 if hasattr( runArgs,
"outputEVNTFile")
or hasattr( runArgs,
"outputEVNT_PreFile"):
418 from AthenaPoolCnvSvc.WriteAthenaPool
import AthenaPoolOutputStream
419 from AthenaPoolCnvSvc.AthenaPoolCnvSvcConf
import AthenaPoolCnvSvc
420 if hasattr(runArgs,
"outputEVNTFile"):
421 poolFile = runArgs.outputEVNTFile
422 elif hasattr(runArgs,
"outputEVNT_PreFile"):
423 poolFile = runArgs.outputEVNT_PreFile
425 raise RuntimeError(
"Output pool file, either EVNT or EVNT_Pre, is not known.")
430 svcMgr.AthenaPoolCnvSvc.PoolAttributes += [ f
"DatabaseName = '{poolFile}'; FILEFORWARD_COMPATIBILITY = '1'" ]
431 svcMgr.AthenaPoolCnvSvc.OneDataHeaderForm =
False
435 StreamEVGEN.ForceRead =
True
436 StreamEVGEN.ItemList += [
"EventInfo#*",
"xAOD::EventInfo#EventInfo*",
"xAOD::EventAuxInfo#EventInfoAux.*",
"McEventCollection#*"]
437 StreamEVGEN.RequireAlgs += [
"EvgenFilterSeq"]
439 if evgenConfig.saveJets:
440 StreamEVGEN.ItemList += [
"xAOD::JetContainer#AntiKt4TruthJets",
"xAOD::AuxContainerBase!#AntiKt4TruthJetsAux.-PseudoJet.-constituentLinks.-constituentWeights"]
441 StreamEVGEN.ItemList += [
"xAOD::JetContainer#AntiKt6TruthJets",
"xAOD::AuxContainerBase!#AntiKt6TruthJetsAux.-PseudoJet.-constituentLinks.-constituentWeights"]
442 if evgenConfig.savePileupTruthParticles:
443 StreamEVGEN.ItemList += [
"xAOD::TruthParticleContainer#TruthPileupParticles*"]
444 StreamEVGEN.ItemList += [
"xAOD::TruthParticleAuxContainer#TruthPileupParticlesAux.*"]
447 for removeItem
in evgenConfig.doNotSaveItems: StreamEVGEN.ItemList.remove( removeItem )
450 for addItem
in evgenConfig.extraSaveItems: StreamEVGEN.ItemList += [ addItem ]
453 dsid = os.path.basename(runArgs.jobConfig[0])
454 if not dsid.isdigit():
456 svcMgr.EventSelector.RunNumber =
int(dsid)
459 from GeneratorConfig.Versioning
import generatorsGetInitialVersionedDictionary, generatorsVersionedStringList
463 import EventInfoMgt.EventInfoMgtInit
464 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"hepmc_version":
"HepMC" +
str(os.environ[
'HEPMCVER'])})
465 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"mc_channel_number":
str(dsid)})
466 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"lhefGenerator":
'+'.
join(
filter( gen_lhef, gennames ) ) })
467 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"generators":
'+'.
join(gennamesvers)})
468 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"evgenProcess": evgenConfig.process})
469 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"evgenTune": evgenConfig.tune})
470 if hasattr( evgenConfig,
"hardPDF" ) : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"hardPDF": evgenConfig.hardPDF})
471 if hasattr( evgenConfig,
"softPDF" ) : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"softPDF": evgenConfig.softPDF})
472 if hasattr( runArgs,
"randomSeed") : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"randomSeed":
str(runArgs.randomSeed)})
473 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"keywords":
", ".
join(evgenConfig.keywords).lower()})
476 evgenLog.info(
"HepMC version " +
str(os.environ[
'HEPMCVER']))
479 from PyUtils
import AMITagHelper
480 AMITagHelper.SetAMITag(runArgs=runArgs)
483 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"beam_energy":
str(
int(runArgs.ecmEnergy*Units.GeV/2.0))})
484 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"beam_type":
'collisions'})
488 include(
"EvgenJobTransforms/Generate_ecmenergies.py")
490 if 'ParticleGun' in evgenConfig.generators:
492 from RngComps.RngCompsConf
import AtRndmGenSvc
494 include(
"EvgenJobTransforms/Generate_randomseeds.py")
497 include(
"EvgenJobTransforms/Generate_dsid_ranseed.py")
500 if (hasattr( runArgs,
"VERBOSE")
and runArgs.VERBOSE )
or (hasattr( runArgs,
"loglevel")
and runArgs.loglevel ==
"DEBUG")
or (hasattr( runArgs,
"loglevel")
and runArgs.loglevel ==
"VERBOSE"):
501 include(
"EvgenJobTransforms/Generate_debug_level.py")
504 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"specialConfiguration": evgenConfig.specialConfig })
508 if hasattr(testSeq,
"TestHepMC")
and not gens_testhepmc(evgenConfig.generators):
509 evgenLog.info(
"Removing TestHepMC sanity checker")
510 del testSeq.TestHepMC
518 with open(
'/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common/BlackList_caches.txt')
as bfile:
519 for line
in bfile.readlines():
523 badRelFlav=line.split(
',')[0].strip()
525 badCache=line.split(
',')[1].strip()
527 badGens=line.split(
',')[2].strip()
529 used_gens =
','.
join(generatorName)
531 if relFlavour==badRelFlav
and cache==badCache
and re.search(badGens,used_gens)
is not None:
532 if badGens==
"": badGens=
"all generators"
533 isError=relFlavour+
","+cache+
" is blacklisted for " + badGens
539 with open(
'/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common/PurpleList_generators.txt')
as bfile:
540 for line
in bfile.readlines():
544 purpleRelFlav=line.split(
',')[0].strip()
546 purpleCache=line.split(
',')[1].strip()
548 purpleGens=line.split(
',')[2].strip()
550 purpleProcess=line.split(
',')[3].strip()
552 used_gens =
','.
join(generatorName)
554 if relFlavour==purpleRelFlav
and cache==purpleCache
and re.search(purpleGens,used_gens)
is not None:
555 isError=relFlavour+
","+cache+
" is blacklisted for " + purpleGens +
" if it uses " + purpleProcess
560 evgenLog.debug(
"****************** CHECKING RELEASE IS NOT BLACKLISTED *****************")
561 if os.path.exists(
'/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common'):
564 if (hasattr( runArgs,
"ignoreBlackList")
and runArgs.ignoreBlackList):
565 evgenLog.warning(
"This run is blacklisted for this generator, please use a different one for production !! "+ errorBL )
567 raise RuntimeError(
"This run is blacklisted for this generator, please use a different one !! "+ errorBL)
571 evgenLog.warning(
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
572 evgenLog.warning(
"!!! WARNING !!! "+ errorPL )
573 evgenLog.warning(
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
576 msg.waring(
"No access to cvmfs, so blacklisted runs will not be checked")
581 if hasattr(runArgs,
"postInclude"):
582 for fragment
in runArgs.postInclude:
585 if hasattr(runArgs,
"postExec"):
586 evgenLog.info(
"Transform post-exec")
587 for cmd
in runArgs.postExec:
595 acas.dumpMasterSequence()
603 evgenLog.debug(
"****************** HANDLING EVGEN INPUT FILES *****************")
607 if "McAtNlo" in evgenConfig.generators
and "Herwig" in evgenConfig.generators:
608 datFile =
"inparmMcAtNlo.dat"
609 elif "Alpgen" in evgenConfig.generators:
610 datFile =
"inparmAlpGen.dat"
611 elif "Protos" in evgenConfig.generators:
612 datFile =
"protos.dat"
613 elif "ProtosLHEF" in evgenConfig.generators:
614 datFile =
"protoslhef.dat"
615 elif "AcerMC" in evgenConfig.generators:
616 datFile =
"inparmAcerMC.dat"
617 elif "CompHep" in evgenConfig.generators:
618 datFile =
"inparmCompHep.dat"
622 if "Alpgen" in evgenConfig.generators:
623 eventsFile =
"alpgen.unw_events"
624 elif "Protos" in evgenConfig.generators:
625 eventsFile =
"protos.events"
626 elif "ProtosLHEF" in evgenConfig.generators:
627 eventsFile =
"protoslhef.events"
628 elif "BeamHaloGenerator" in evgenConfig.generators:
629 eventsFile =
"beamhalogen.events"
630 elif "HepMCAscii" in evgenConfig.generators:
631 eventsFile =
"events.hepmc"
632 elif "ReadMcAscii" in evgenConfig.generators:
633 eventsFile =
"events.hepmc"
635 eventsFile =
"events.lhe"
640 "Return a matching file, provided it is unique"
642 files = glob.glob(pattern)
645 raise RuntimeError(
"No '%s' file found" % pattern)
647 raise RuntimeError(
"More than one '%s' file found" % pattern)
653 if(os.path.exists(outputFile)):
654 print (
"outputFile ",outputFile,
" already exists. Will rename to ",outputFile,
".OLD")
655 os.rename(outputFile,outputFile+
".OLD")
656 output =
open(outputFile,
'w')
659 for file
in listOfFiles:
660 cmd =
"grep /event "+file+
" | wc -l"
661 nevents+=
int(subprocess.check_output(cmd,stderr=subprocess.STDOUT,shell=
True))
663 for file
in listOfFiles:
666 print (
"*** Starting file ",file)
667 for line
in open(file,
"r"):
673 if(
"<event" in line
and inHeader):
675 if(len(holdHeader)<1):
681 elif(
not inHeader
and not (
"</LesHouchesEvents>" in line)):
685 if(
"nevents" in line):
687 tmp = line.split(
"=")
688 line = line.replace(tmp[0],
str(nevents))
689 elif(
"numevts" in line):
691 tmp = line.split(
" ")
693 line = line.replace(tmp[1],nnn)
695 output.write(
"</LesHouchesEvents>\n")
700 "Make a symlink safely"
702 if os.path.exists(dstfile)
and not os.path.samefile(dstfile, srcfile):
704 if not os.path.exists(dstfile):
705 evgenLog.info(
"Symlinking %s to %s" % (srcfile, dstfile))
706 print (
"Symlinking %s to %s" % (srcfile, dstfile))
707 os.symlink(srcfile, dstfile)
709 evgenLog.debug(
"Symlinking: %s is already the same as %s" % (dstfile, srcfile))
712 if eventsFile
or datFile:
713 if not hasattr(runArgs,
"inputGeneratorFile")
or runArgs.inputGeneratorFile ==
"NONE":
714 raise RuntimeError(
"%s needs input file (argument inputGeneratorFile)" % runArgs.jobConfig)
715 if evgenConfig.inputfilecheck
and not re.search(evgenConfig.inputfilecheck, runArgs.inputGeneratorFile):
716 raise RuntimeError(
"inputGeneratorFile=%s is incompatible with inputfilecheck '%s' in %s" %
717 (runArgs.inputGeneratorFile, evgenConfig.inputfilecheck, runArgs.jobConfig))
719 if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
720 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tar.")[0]
722 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
"._")[0]
727 myinputfiles = runArgs.inputGeneratorFile
728 genInputFiles = myinputfiles.split(
',')
729 numberOfFiles = len(genInputFiles)
732 if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
733 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tar.")[0]
735 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
"._")[0]
737 if "events" in inputroot :
738 inputroot = inputroot.replace(
".events",
"")
743 for file
in genInputFiles:
746 if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
747 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tar.")[0]
749 input0 = os.path.basename(file).
split(
"._")[0]
750 input1 = (os.path.basename(file).
split(
"._")[1]).
split(
".")[0]
751 inputroot = input0+
"._"+input1
752 evgenLog.info(
"inputroot = ",inputroot)
755 with open(realEventsFile,
'r')
as f:
756 first_line = f.readline()
757 if(
not (
"LesHouche" in first_line)):
758 raise RuntimeError(
"%s is NOT a LesHouche file" % realEventsFile)
759 allFiles.append(realEventsFile)
763 if hasattr(runArgs,
"inputGeneratorFile")
and runArgs.inputGeneratorFile !=
"NONE":
764 raise RuntimeError(
"inputGeneratorFile arg specified for %s, but generators %s do not require an input file" %
765 (runArgs.jobConfig,
str(gennames)))
766 if evgenConfig.inputfilecheck:
767 raise RuntimeError(
"evgenConfig.inputfilecheck specified in %s, but generators %s do not require an input file" %
768 (runArgs.jobConfig,
str(gennames)))
771 if evgenConfig.auxfiles:
773 get_files(evgenConfig.auxfiles, keepDir=
False, errorIfNotFound=
True)
781 if not hasattr(evgenConfig, attr)
or not getattr(evgenConfig, attr):
782 msg =
"evgenConfig attribute '%s' not found." % attr
784 raise RuntimeError(
"Required " + msg)
788 if hasattr(runArgs,
"outputTXTFile"):
791 with open(eventsFile)
as f:
793 count_ev += line.count(
'/event')
795 print(
"MetaData: %s = %s" % (
"Number of produced LHE events ", count_ev))
796 elif hasattr(runArgs,
"inputGeneratorFile"):
799 with open(eventsFile)
as f:
801 count_ev += line.count(
'/event')
803 print(
"MetaData: %s = %s" % (
"Number of input LHE events ", count_ev))
807 msg = evgenConfig.description
809 msg +=
" " + evgenConfig.notes
810 print (
"MetaData: %s = %s" % (
"physicsComment", msg))
813 print (
"MetaData: %s = %s" % (
"generatorName",
"+".
join(gennamesvers)))
815 print (
"MetaData: %s = %s" % (
"physicsProcess", evgenConfig.process))
817 print (
"MetaData: %s = %s" % (
"generatorTune", evgenConfig.tune))
819 print (
"MetaData: %s = %s" % (
"hardPDF", evgenConfig.hardPDF))
821 print (
"MetaData: %s = %s" % (
"softPDF", evgenConfig.softPDF))
823 print (
"MetaData: %s = %s" % (
"nEventsPerJob", evgenConfig.nEventsPerJob))
825 print (
"MetaData: %s = %s" % (
"keywords",
", ".
join(evgenConfig.keywords).lower()))
827 print (
"MetaData: %s = %s" % (
"categories",
", ".
join(evgenConfig.categories)))
829 print (
"MetaData: %s = %s" % (
"specialConfig", evgenConfig.specialConfig))
832 print (
"MetaData: %s = %s" % (
"contactPhysicist",
", ".
join(evgenConfig.contact)))
833 print (
"MetaData: %s = %s" % (
"randomSeed",
str(runArgs.randomSeed)))
836 filterNames = [alg.getType()
for alg
in acas.iter_algseq(filtSeq)]
837 excludedNames = [
'AthSequencer',
'PyAthena::Alg',
'TestHepMC']
838 filterNames =
list(
set(filterNames) -
set(excludedNames))
839 print (
"MetaData: %s = %s" % (
"genFilterNames",
", ".
join(filterNames)))
846 from PyJobTransformsCore.runargs
import RunArguments
847 runPars = RunArguments()
848 runPars.nEventsPerJob = evgenConfig.nEventsPerJob
849 runPars.maxeventsstrategy = evgenConfig.maxeventsstrategy
850 with open(
"config.pickle",
"wb")
as f:
852 pickle.dump(runPars, f)
858 evgenLog.info(
"****************** STARTING EVENT GENERATION *****************")