3"""Functionality core of the Gen_tf transform"""
13import os, re, string, subprocess
14import AthenaCommon.AlgSequence
as acas
15import AthenaCommon.AppMgr
as acam
16from AthenaCommon.AthenaCommonFlags
import jobproperties
18from xAODEventInfoCnv.xAODEventInfoCnvConf
import xAODMaker__EventInfoCnvAlg
19acam.athMasterSeq += xAODMaker__EventInfoCnvAlg(xAODKey=
"TMPEvtInfo")
22acam.athMasterSeq += acas.AlgSequence(
"EvgenGenSeq")
23genSeq = acam.athMasterSeq.EvgenGenSeq
24acam.athMasterSeq += acas.AlgSequence(
"EvgenFixSeq")
25fixSeq = acam.athMasterSeq.EvgenFixSeq
26acam.athMasterSeq += acas.AlgSequence(
"EvgenPreFilterSeq")
27prefiltSeq = acam.athMasterSeq.EvgenPreFilterSeq
28acam.athMasterSeq += acas.AlgSequence(
"EvgenTestSeq")
29testSeq = acam.athMasterSeq.EvgenTestSeq
31from EvgenProdTools.LogicalExpressionFilter
import LogicalExpressionFilter
33filtSeq = acam.athMasterSeq.EvgenFilterSeq
34topSeq = acas.AlgSequence()
36topSeq += acas.AlgSequence(
"EvgenPostSeq")
37postSeq = topSeq.EvgenPostSeq
46import AthenaCommon.AtlasUnixGeneratorJob
47include(
"PartPropSvc/PartPropSvc.py")
50from PerfMonComps.PerfMonFlags
import jobproperties
as perfmonjp
51perfmonjp.PerfMonFlags.doFastMonMT =
True
54from RngComps.RngCompsConf
import AthRNGSvc
58jobproperties.AthenaCommonFlags.AllowIgnoreConfigError =
False
61from AthenaCommon.Logging
import logging
62evgenLog = logging.getLogger(
'Gen_tf')
69evgenLog.debug(
"****************** CHECKING EVENT GENERATION ARGS *****************")
70evgenLog.debug(
str(runArgs))
72if hasattr(runArgs,
"inputGeneratorFile"):
73 evgenLog.info(
"inputGeneratorFile = " + runArgs.inputGeneratorFile)
75if hasattr(runArgs,
"outputYODAFile"):
76 evgenLog.info(
"specified outputYODAFile = " + runArgs.outputYODAFile)
80if 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.")
88if not hasattr(runArgs,
"ecmEnergy"):
89 raise RuntimeError(
"No center of mass energy provided.")
91 evgenLog.info(
'ecmEnergy = ' +
str(runArgs.ecmEnergy) )
92if not hasattr(runArgs,
"randomSeed"):
93 raise RuntimeError(
"No random seed provided.")
95if not hasattr(runArgs,
"firstEvent"):
96 raise RuntimeError(
"No first number provided.")
97if ( runArgs.firstEvent <= 0):
98 evgenLog.warning(
"Run argument firstEvent should be > 0")
105evgenLog.debug(
"****************** CONFIGURING EVENT GENERATION *****************")
109from EvgenJobTransforms.EvgenConfig
import evgenConfig
110from GeneratorConfig.GenConfigHelpers
import gens_known, gen_lhef, gens_lhef, gen_sortkey, gens_testhepmc, gens_notune, gen_require_steering, gens_purgenoendvtx
113from EvgenProdTools.EvgenProdToolsConf
import FixHepMC
114if not hasattr(fixSeq,
"FixHepMC"):
118from EvgenProdTools.EvgenProdToolsConf
import TestHepMC
119testSeq +=
TestHepMC(CmEnergy=runArgs.ecmEnergy*Units.GeV)
121if not hasattr(svcMgr,
'THistSvc'):
122 from GaudiSvc.GaudiSvcConf
import THistSvc
124svcMgr.THistSvc.Output = [
"TestHepMCname DATAFILE='TestHepMC.root' OPT='RECREATE'"]
128from EvgenProdTools.EvgenProdToolsConf
import CopyEventWeight
129if not hasattr(postSeq,
"CopyEventWeight"):
130 postSeq +=
CopyEventWeight(mcEventWeightsKey=
"TMPEvtInfo.mcEventWeights")
132from EvgenProdTools.EvgenProdToolsConf
import FillFilterValues
133if not hasattr(postSeq,
"FillFilterValues"):
138from EvgenProdTools.EvgenProdToolsConf
import CountHepMC
139svcMgr.EventSelector.FirstEvent = runArgs.firstEvent
145if not hasattr(postSeq,
"CountHepMC"):
146 postSeq +=
CountHepMC(InputEventInfo=
"TMPEvtInfo",
147 OutputEventInfo=
"EventInfo",
148 mcEventWeightsKey=
"mcEventWeights")
151postSeq.CountHepMC.FirstEvent = runArgs.firstEvent
152postSeq.CountHepMC.CorrectHepMC =
True
153postSeq.CountHepMC.CorrectEventID =
True
157if 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
167from EvgenProdTools.EvgenProdToolsConf
import SimTimeEstimate
168if not hasattr(postSeq,
"SimTimeEstimate"):
173if 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
182rel = os.popen(
"echo $AtlasVersion").
read()
184if not rel
or int(rel[:2]) > 22:
185 from AthenaCommon.AppMgr
import ServiceMgr
186 ServiceMgr.EventSelector.EventsPerRun = int(2**63 - 1)
193evgenLog.debug(
"****************** LOADING PRE-INCLUDES AND JOB CONFIG *****************")
196if hasattr(runArgs,
"preInclude"):
197 for fragment
in runArgs.preInclude:
201if 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
218if 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")
223evgenLog.info(
"Using JOBOPTSEARCHPATH (as seen in skeleton) = '%s'" % os.environ[
"JOBOPTSEARCHPATH"])
224FIRST_DIR = (os.environ[
'JOBOPTSEARCHPATH']).
split(
":")[0]
226jofiles = [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")
232joparts = (os.path.basename(jofile)).
split(
".")
234if joparts[0].startswith(
"mc")
and all(c
in string.digits
for c
in joparts[0][2:]):
236 if len(joparts) != 3:
237 evgenLog.error(jofile +
" name format is wrong: must be of the form mc.<physicsShort>.py: please rename.")
240 jo_physshortpart = joparts[1]
241 max_jo_physshort_length = 50
242 if len(jo_physshortpart) > max_jo_physshort_length:
243 evgenLog.error(f
"{jofile} contains a physicsShort field of more than {max_jo_physshort_length} characters: please rename.")
246 jo_physshortparts = jo_physshortpart.split(
"_")
247 if len(jo_physshortparts) < 2:
248 evgenLog.error(jofile +
" has too few physicsShort fields separated by '_': should contain <generators>(_<tune+PDF_if_available>)_<process>. Please rename.")
251 check_jofiles=
"/cvmfs/atlas.cern.ch/repo/sw/Generators/MCJobOptions/scripts/check_jo_consistency.py"
252 if os.path.exists(check_jofiles):
253 include(check_jofiles)
254 check_naming(os.path.basename(jofile))
256 evgenLog.waring(
"check_jo_consistency.py not found, will proceed without JOs check.")
269evgenLog.debug(
"****************** CHECKING EVGEN CONFIGURATION *****************")
271if hasattr(runArgs,
'inputGeneratorFile')
and int(evgenConfig.inputFilesPerJob) == 0 :
272 evgenConfig.inputFilesPerJob = 1
275for opt
in str(evgenConfig).
split(os.linesep):
277evgenLog.info(
".transform = Gen_tf")
280evgenLog.info(
".platform = "+
str(os.environ[
'BINARY_TAG']))
285if evgenConfig.obsolete:
286 evgenLog.error(
"JOs or icludes are obsolete, please check them")
289if not evgenConfig.generators:
290 evgenLog.error(
"No entries in evgenConfig.generators: invalid configuration, please check your JO")
293if len(evgenConfig.generators) > len(
set(evgenConfig.generators)):
294 evgenLog.error(
"Duplicate entries in evgenConfig.generators: invalid configuration, please check your JO")
297gennames = sorted(evgenConfig.generators, key=gen_sortkey)
299if joparts[0].startswith(
"Mc"):
300 genpart = jo_physshortparts[0]
301 expectedgenpart =
''.join(gennames)
303 expectedgenpart = expectedgenpart.replace(
"HerwigJimmy",
"Herwig")
318 if genpart !=
_norm(expectedgenpart)
and _norm2(genpart) !=
_norm(expectedgenpart):
319 evgenLog.error(
"Expected first part of JO name to be '%s' or '%s', but found '%s'" % (
_norm(expectedgenpart),
_norm(
_short2(expectedgenpart)), genpart))
320 evgenLog.error(
"gennames '%s' " %(expectedgenpart))
325 if not gens_notune(gennames)
and len(jo_physshortparts) < 3:
326 evgenLog.error(jofile +
" with generators " + expectedgenpart +
327 " has too few physicsShort fields separated by '_'." +
328 " It should contain <generators>_<tune+PDF_<process>. Please rename.")
333if gen_require_steering(gennames):
334 if hasattr(runArgs,
"outputEVNTFile")
and not hasattr(runArgs,
"outputEVNT_PreFile"):
335 raise RuntimeError(
"'EvtGen' found in job options name, please set '--steering=afterburn'")
341if hasattr(runArgs,
'inputGeneratorFile')
and ',' in runArgs.inputGeneratorFile: multiInput = runArgs.inputGeneratorFile.count(
',')+1
346if not evgenConfig.nEventsPerJob:
347 evgenLog.info(
'#############################################################')
348 evgenLog.info(
' !!!! no nEventsPerJob set !!! The default 10000 used. !!! ')
349 evgenLog.info(
'#############################################################')
351 evgenLog.info(
' nEventsPerJob = ' +
str(evgenConfig.nEventsPerJob) )
353if evgenConfig.minevents > 0 :
354 raise RuntimeError(
"evgenConfig.minevents is obsolete and should be removed from the JOs")
355if evgenConfig.nEventsPerJob < 1:
356 raise RuntimeError(
"evgenConfig.nEventsPerJob must be at least 1")
357elif evgenConfig.nEventsPerJob > 100000:
358 raise RuntimeError(
"evgenConfig.nEventsPerJob can be max. 100000")
360 allowed_nEventsPerJob_lt1000 = [1, 2, 5, 10, 20, 25, 50, 100, 200, 500, 1000]
361 msg =
"evgenConfig.nEventsPerJob = %d: " % evgenConfig.nEventsPerJob
363 if evgenConfig.nEventsPerJob >= 1000
and evgenConfig.nEventsPerJob <=10000
and (evgenConfig.nEventsPerJob % 1000 != 0
or 10000 % evgenConfig.nEventsPerJob != 0):
364 msg +=
"nEventsPerJob in range [1K, 10K] must be a multiple of 1K and a divisor of 10K"
365 raise RuntimeError(msg)
366 elif evgenConfig.nEventsPerJob > 10000
and evgenConfig.nEventsPerJob % 10000 != 0:
367 msg +=
"nEventsPerJob >10K must be a multiple of 10K"
368 raise RuntimeError(msg)
369 elif evgenConfig.nEventsPerJob < 1000
and evgenConfig.nEventsPerJob
not in allowed_nEventsPerJob_lt1000:
370 msg +=
"nEventsPerJob in range <= 1000 must be one of %s" % allowed_nEventsPerJob_lt1000
371 raise RuntimeError(msg)
372 postSeq.CountHepMC.RequestedOutput = evgenConfig.nEventsPerJob
if runArgs.maxEvents == -1
else runArgs.maxEvents
373 evgenLog.info(
'Requested output events = '+
str(postSeq.CountHepMC.RequestedOutput))
378 if hasattr(testSeq,
"TestHepMC")
and postSeq.CountHepMC.RequestedOutput<100:
379 testSeq.TestHepMC.EffFailThreshold = postSeq.CountHepMC.RequestedOutput/(postSeq.CountHepMC.RequestedOutput+1) - 0.01
382if evgenConfig.keywords:
383 from GeneratorConfig.GenConfigHelpers
import checkKeywords
384 checkKeywords(evgenConfig, evgenLog)
387if evgenConfig.categories:
390 lkwfile =
"CategoryList.txt"
392 for p
in os.environ[
"DATAPATH"].
split(
":"):
393 lkwpath = os.path.join(p, lkwfile)
394 if os.path.exists(lkwpath):
400 with open(lkwpath,
'r')
as catlist:
402 allowed_list = ast.literal_eval(line)
403 allowed_cat.append(allowed_list)
407 it = iter(evgenConfig.categories)
411 if "L1:" in l2
and "L2:" in l1:
413 print (
"first",l1,
"second",l2)
414 bad_cat.extend([l1, l2])
415 for a1,a2
in allowed_cat:
416 if l1.strip().lower()==a1.strip().lower()
and l2.strip().lower()==a2.strip().lower():
419 msg =
"evgenConfig.categories contains non-standard category: %s. " %
", ".join(bad_cat)
420 msg +=
"Please check the allowed categories list and fix."
424 evgenLog.warning(
"Could not find CategoryList.txt file %s in $DATAPATH" % lkwfile)
426if hasattr( runArgs,
"outputEVNTFile")
or hasattr( runArgs,
"outputEVNT_PreFile"):
428 from AthenaPoolCnvSvc.WriteAthenaPool
import AthenaPoolOutputStream
429 from AthenaPoolCnvSvc.AthenaPoolCnvSvcConf
import AthenaPoolCnvSvc
430 if hasattr(runArgs,
"outputEVNTFile"):
431 poolFile = runArgs.outputEVNTFile
432 elif hasattr(runArgs,
"outputEVNT_PreFile"):
433 poolFile = runArgs.outputEVNT_PreFile
435 raise RuntimeError(
"Output pool file, either EVNT or EVNT_Pre, is not known.")
440 svcMgr.AthenaPoolCnvSvc.PoolAttributes += [ f
"DatabaseName = '{poolFile}'; FILEFORWARD_COMPATIBILITY = '1'" ]
441 svcMgr.AthenaPoolCnvSvc.OneDataHeaderForm =
False
443 StreamEVGEN = AthenaPoolOutputStream(
"StreamEVGEN", poolFile, noTag=
True, eventInfoKey=
"EventInfo")
445 StreamEVGEN.ForceRead =
True
446 StreamEVGEN.ItemList += [
"EventInfo#*",
"xAOD::EventInfo#EventInfo*",
"xAOD::EventAuxInfo#EventInfoAux.*",
"McEventCollection#*"]
447 StreamEVGEN.RequireAlgs += [
"EvgenFilterSeq"]
449 if evgenConfig.saveJets:
450 StreamEVGEN.ItemList += [
"xAOD::JetContainer#AntiKt4TruthJets",
"xAOD::AuxContainerBase!#AntiKt4TruthJetsAux.-PseudoJet.-constituentLinks.-constituentWeights"]
451 StreamEVGEN.ItemList += [
"xAOD::JetContainer#AntiKt6TruthJets",
"xAOD::AuxContainerBase!#AntiKt6TruthJetsAux.-PseudoJet.-constituentLinks.-constituentWeights"]
452 if evgenConfig.savePileupTruthParticles:
453 StreamEVGEN.ItemList += [
"xAOD::TruthParticleContainer#TruthPileupParticles*"]
454 StreamEVGEN.ItemList += [
"xAOD::TruthParticleAuxContainer#TruthPileupParticlesAux.*"]
457 for removeItem
in evgenConfig.doNotSaveItems: StreamEVGEN.ItemList.remove( removeItem )
460 for addItem
in evgenConfig.extraSaveItems: StreamEVGEN.ItemList += [ addItem ]
463dsid = os.path.basename(runArgs.jobConfig[0])
464if not dsid.isdigit():
466svcMgr.EventSelector.RunNumber = int(dsid)
469from GeneratorConfig.Versioning
import generatorsGetInitialVersionedDictionary, generatorsVersionedStringList
470gendict = generatorsGetInitialVersionedDictionary(gennames)
471gennamesvers = generatorsVersionedStringList(gendict)
473import EventInfoMgt.EventInfoMgtInit
474svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"hepmc_version":
"HepMC" +
str(os.environ[
'HEPMCVER'])})
475svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"mc_channel_number":
str(dsid)})
476svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"lhefGenerator":
'+'.join( filter( gen_lhef, gennames ) ) })
477svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"generators":
'+'.join(gennamesvers)})
478svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"evgenProcess": evgenConfig.process})
479svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"evgenTune": evgenConfig.tune})
480if hasattr( evgenConfig,
"hardPDF" ) : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"hardPDF": evgenConfig.hardPDF})
481if hasattr( evgenConfig,
"softPDF" ) : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"softPDF": evgenConfig.softPDF})
482if hasattr( runArgs,
"randomSeed") : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"randomSeed":
str(runArgs.randomSeed)})
483svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"keywords":
", ".join(evgenConfig.keywords).lower()})
486evgenLog.info(
"HepMC version " +
str(os.environ[
'HEPMCVER']))
489from PyUtils
import AMITagHelper
490AMITagHelper.SetAMITag(runArgs=runArgs)
493svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"beam_energy":
str(int(runArgs.ecmEnergy*Units.GeV/2.0))})
494svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"beam_type":
'collisions'})
497from OutputStreamAthenaPool.OutputStreamAthenaPoolConf
import CopyEventStreamInfo
499ToolSvc += streamInfoTool
500svcMgr.MetaDataSvc.MetaDataTools += [ streamInfoTool ]
504include(
"EvgenJobTransforms/Generate_ecmenergies.py")
506if 'ParticleGun' in evgenConfig.generators:
508 from RngComps.RngCompsConf
import AtRndmGenSvc
510 include(
"EvgenJobTransforms/Generate_randomseeds.py")
513 include(
"EvgenJobTransforms/Generate_dsid_ranseed.py")
516generatorsList = evgenConfig.generators.copy()
517if hasattr(genSeq,
"Pythia8"):
518 if (hasattr(genSeq.Pythia8,
"Beam1")
and genSeq.Pythia8.Beam1 !=
"PROTON" )
or \
519 (hasattr(genSeq.Pythia8,
"Beam2")
and genSeq.Pythia8.Beam2 !=
"PROTON" ):
521 generatorsList.append(
"Pythia8-Angantyr")
522if gens_purgenoendvtx(generatorsList):
523 fixSeq.FixHepMC.PurgeUnstableWithoutEndVtx =
True
526if 'Sherpa' in evgenConfig.generators:
527 fixSeq.FixHepMC.IgnoreSemiDisconnected =
True
530if (hasattr( runArgs,
"VERBOSE")
and runArgs.VERBOSE )
or (hasattr( runArgs,
"loglevel")
and runArgs.loglevel ==
"DEBUG")
or (hasattr( runArgs,
"loglevel")
and runArgs.loglevel ==
"VERBOSE"):
531 include(
"EvgenJobTransforms/Generate_debug_level.py")
534svcMgr.TagInfoMgr.ExtraTagValuePairs.update({
"specialConfiguration": evgenConfig.specialConfig })
538if hasattr(testSeq,
"TestHepMC")
and not gens_testhepmc(evgenConfig.generators):
539 evgenLog.info(
"Removing TestHepMC sanity checker")
540 del testSeq.TestHepMC
548 with open(
'/cvmfs/atlas.cern.ch/repo/sw/Generators/MCJobOptions/common/BlackList_caches.txt')
as bfile:
549 for line
in bfile.readlines():
553 badRelFlav=line.split(
',')[0].
strip()
555 badCache=line.split(
',')[1].
strip()
557 badGens=line.split(
',')[2].
strip()
559 used_gens =
','.join(generatorName)
561 if relFlavour==badRelFlav
and cache==badCache
and re.search(badGens,used_gens)
is not None:
562 if badGens==
"": badGens=
"all generators"
563 isError=relFlavour+
","+cache+
" is blocklisted for " + badGens
569 with open(
'/cvmfs/atlas.cern.ch/repo/sw/Generators/MCJobOptions/common/PurpleList_generators.txt')
as bfile:
570 for line
in bfile.readlines():
574 purpleRelFlav=line.split(
',')[0].
strip()
576 purpleCache=line.split(
',')[1].
strip()
578 purpleGens=line.split(
',')[2].
strip()
580 purpleProcess=line.split(
',')[3].
strip()
582 used_gens =
','.join(generatorName)
584 if relFlavour==purpleRelFlav
and cache==purpleCache
and re.search(purpleGens,used_gens)
is not None:
585 isError=relFlavour+
","+cache+
" is blocklisted for " + purpleGens +
" if it uses " + purpleProcess
590evgenLog.debug(
"****************** CHECKING RELEASE IS NOT BLACKLISTED *****************")
591if os.path.exists(
'/cvmfs/atlas.cern.ch/repo/sw/Generators/MCJobOptions/common'):
594 if (hasattr( runArgs,
"ignoreBlackList")
and runArgs.ignoreBlackList):
595 evgenLog.warning(
"This run is blocklisted for this generator, please use a different one for production !! "+ errorBL )
597 raise RuntimeError(
"This run is blocklisted for this generator, please use a different one !! "+ errorBL)
601 evgenLog.warning(
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
602 evgenLog.warning(
"!!! WARNING !!! "+ errorPL )
603 evgenLog.warning(
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
606 msg.waring(
"No access to cvmfs, so blocklisted runs will not be checked")
611if hasattr(runArgs,
"postInclude"):
612 for fragment
in runArgs.postInclude:
615if hasattr(runArgs,
"postExec"):
616 evgenLog.info(
"Transform post-exec")
617 for cmd
in runArgs.postExec:
625acas.dumpMasterSequence()
633evgenLog.debug(
"****************** HANDLING EVGEN INPUT FILES *****************")
637if "McAtNlo" in evgenConfig.generators
and "Herwig" in evgenConfig.generators:
638 datFile =
"inparmMcAtNlo.dat"
639elif "Alpgen" in evgenConfig.generators:
640 datFile =
"inparmAlpGen.dat"
641elif "Protos" in evgenConfig.generators:
642 datFile =
"protos.dat"
643elif "ProtosLHEF" in evgenConfig.generators:
644 datFile =
"protoslhef.dat"
645elif "AcerMC" in evgenConfig.generators:
646 datFile =
"inparmAcerMC.dat"
647elif "CompHep" in evgenConfig.generators:
648 datFile =
"inparmCompHep.dat"
652if "Alpgen" in evgenConfig.generators:
653 eventsFile =
"alpgen.unw_events"
654elif "Protos" in evgenConfig.generators:
655 eventsFile =
"protos.events"
656elif "ProtosLHEF" in evgenConfig.generators:
657 eventsFile =
"protoslhef.events"
658elif "BeamHaloGenerator" in evgenConfig.generators:
659 eventsFile =
"beamhalogen.events"
660elif "HepMCAscii" in evgenConfig.generators:
661 eventsFile =
"events.hepmc"
662elif "ReadMcAscii" in evgenConfig.generators:
663 eventsFile =
"events.hepmc"
664elif gens_lhef(evgenConfig.generators):
665 eventsFile =
"events.lhe"
670 "Return a matching file, provided it is unique"
672 files = glob.glob(pattern)
675 raise RuntimeError(
"No '%s' file found" % pattern)
677 raise RuntimeError(
"More than one '%s' file found" % pattern)
683 if(os.path.exists(outputFile)):
684 print (
"outputFile ",outputFile,
" already exists. Will rename to ",outputFile,
".OLD")
685 os.rename(outputFile,outputFile+
".OLD")
686 output = open(outputFile,
'w')
689 for file
in listOfFiles:
690 cmd =
"grep /event "+file+
" | wc -l"
691 nevents+=int(subprocess.check_output(cmd,stderr=subprocess.STDOUT,shell=
True))
693 for file
in listOfFiles:
696 print (
"*** Starting file ",file)
697 for line
in open(file,
"r"):
703 if(
"<event" in line
and inHeader):
705 if(len(holdHeader)<1):
711 elif(
not inHeader
and not (
"</LesHouchesEvents>" in line)):
715 if(
"nevents" in line):
717 tmp = line.split(
"=")
718 line = line.replace(tmp[0],
str(nevents))
719 elif(
"numevts" in line):
721 tmp = line.split(
" ")
723 line = line.replace(tmp[1],nnn)
725 output.write(
"</LesHouchesEvents>\n")
730 "Make a symlink safely"
732 if os.path.exists(dstfile)
and not os.path.samefile(dstfile, srcfile):
734 if not os.path.exists(dstfile):
735 evgenLog.info(
"Symlinking %s to %s" % (srcfile, dstfile))
736 print (
"Symlinking %s to %s" % (srcfile, dstfile))
737 os.symlink(srcfile, dstfile)
739 evgenLog.debug(
"Symlinking: %s is already the same as %s" % (dstfile, srcfile))
742if eventsFile
or datFile:
743 if not hasattr(runArgs,
"inputGeneratorFile")
or runArgs.inputGeneratorFile ==
"NONE":
744 raise RuntimeError(
"%s needs input file (argument inputGeneratorFile)" % runArgs.jobConfig)
745 if evgenConfig.inputfilecheck
and not re.search(evgenConfig.inputfilecheck, runArgs.inputGeneratorFile):
746 raise RuntimeError(
"inputGeneratorFile=%s is incompatible with inputfilecheck '%s' in %s" %
747 (runArgs.inputGeneratorFile, evgenConfig.inputfilecheck, runArgs.jobConfig))
749 if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
750 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tar.")[0]
751 elif ".tgz" in os.path.basename(runArgs.inputGeneratorFile):
752 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tgz")[0]
753 elif ".gz" in os.path.basename(runArgs.inputGeneratorFile):
754 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".gz")[0]
756 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
"._")[0]
761 myinputfiles = runArgs.inputGeneratorFile
762 genInputFiles = myinputfiles.split(
',')
763 numberOfFiles = len(genInputFiles)
766 if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
767 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tar.")[0]
768 elif ".tgz" in os.path.basename(runArgs.inputGeneratorFile):
769 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tgz")[0]
770 elif ".gz" in os.path.basename(runArgs.inputGeneratorFile):
771 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".gz")[0]
773 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
"._")[0]
775 if "events" in inputroot :
776 inputroot = inputroot.replace(
".events",
"")
781 for file
in genInputFiles:
784 if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
785 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tar.")[0]
786 elif ".tgz" in os.path.basename(runArgs.inputGeneratorFile):
787 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".tgz")[0]
788 elif ".gz" in os.path.basename(runArgs.inputGeneratorFile):
789 inputroot = os.path.basename(runArgs.inputGeneratorFile).
split(
".gz")[0]
791 input0 = os.path.basename(file).
split(
"._")[0]
792 input1 = (os.path.basename(file).
split(
"._")[1]).
split(
".")[0]
793 inputroot = input0+
"._"+input1
794 evgenLog.info(
"inputroot = %s",inputroot)
797 with open(realEventsFile,
'r')
as f:
798 first_line = f.readline()
799 if(
not (
"LesHouche" in first_line)):
800 raise RuntimeError(
"%s is NOT a LesHouche file" % realEventsFile)
801 allFiles.append(realEventsFile)
805 if hasattr(runArgs,
"inputGeneratorFile")
and runArgs.inputGeneratorFile !=
"NONE":
806 raise RuntimeError(
"inputGeneratorFile arg specified for %s, but generators %s do not require an input file" %
807 (runArgs.jobConfig,
str(gennames)))
808 if evgenConfig.inputfilecheck:
809 raise RuntimeError(
"evgenConfig.inputfilecheck specified in %s, but generators %s do not require an input file" %
810 (runArgs.jobConfig,
str(gennames)))
813if evgenConfig.auxfiles:
815 get_files(evgenConfig.auxfiles, keepDir=
False, errorIfNotFound=
True)
823 if not hasattr(evgenConfig, attr)
or not getattr(evgenConfig, attr):
824 msg =
"evgenConfig attribute '%s' not found." % attr
826 raise RuntimeError(
"Required " + msg)
830if hasattr(runArgs,
"outputTXTFile"):
833 with open(eventsFile)
as f:
835 count_ev += line.count(
'/event')
837 print(
"MetaData: %s = %s" % (
"Number of produced LHE events ", count_ev))
838elif hasattr(runArgs,
"inputGeneratorFile"):
841 with open(eventsFile)
as f:
843 count_ev += line.count(
'/event')
845 print(
"MetaData: %s = %s" % (
"Number of input LHE events ", count_ev))
849 msg = evgenConfig.description
851 msg +=
" " + evgenConfig.notes
852 print (
"MetaData: %s = %s" % (
"physicsComment", msg))
855 print (
"MetaData: %s = %s" % (
"generatorName",
"+".join(gennamesvers)))
857 print (
"MetaData: %s = %s" % (
"physicsProcess", evgenConfig.process))
859 print (
"MetaData: %s = %s" % (
"generatorTune", evgenConfig.tune))
861 print (
"MetaData: %s = %s" % (
"hardPDF", evgenConfig.hardPDF))
863 print (
"MetaData: %s = %s" % (
"softPDF", evgenConfig.softPDF))
865 print (
"MetaData: %s = %s" % (
"nEventsPerJob", evgenConfig.nEventsPerJob))
867 print (
"MetaData: %s = %s" % (
"keywords",
", ".join(evgenConfig.keywords).lower()))
869 print (
"MetaData: %s = %s" % (
"categories",
", ".join(evgenConfig.categories)))
871 print (
"MetaData: %s = %s" % (
"specialConfig", evgenConfig.specialConfig))
874 print (
"MetaData: %s = %s" % (
"contactPhysicist",
", ".join(evgenConfig.contact)))
875print (
"MetaData: %s = %s" % (
"randomSeed",
str(runArgs.randomSeed)))
878filterNames = [alg.getType()
for alg
in acas.iter_algseq(filtSeq)]
879excludedNames = [
'AthSequencer',
'PyAthena::Alg',
'TestHepMC']
880filterNames = list(
set(filterNames) -
set(excludedNames))
881print (
"MetaData: %s = %s" % (
"genFilterNames",
", ".join(filterNames)))
883if (hasattr( runArgs,
"allowOldFilter")
and runArgs.allowOldFilter):
884 for alg
in acas.iter_algseq(filtSeq):
885 filtName = alg.getType()
886 exceptName =[
'xAOD',
'Jet']
887 if filtName
not in excludedNames:
888 if not any(ex
in filtName
for ex
in exceptName):
889 alg.AllowOldFilter=
True
895from PyJobTransformsCore.runargs
import RunArguments
896runPars = RunArguments()
897runPars.nEventsPerJob = evgenConfig.nEventsPerJob
898runPars.maxeventsstrategy = evgenConfig.maxeventsstrategy
899with open(
"config.pickle",
"wb")
as f:
901 pickle.dump(runPars, f)
907evgenLog.info(
"****************** STARTING EVENT GENERATION *****************")
void print(char *figname, TCanvas *c1)
A random number engine manager, based on Ranecu.
A service to manage multiple RNG streams in thread-safe way.
This class provides an algorithm to make the EventStreamInfo object and update it.
Copy MC truth event weights into the event info store.
Count the number of events to pass all algorithms/filters.
Copy MC gen values we filter on into the event info store.
A "fix-up" algorithm to correct weird event records.
Print MC event details for a range of event numbers.
Interface to the Rivet analysis package.
Algorithm to estimate the amount of CPU time that simulation will take.
Filtering algorithm to sanity check HepMC event features.
std::string replace(std::string s, const std::string &s2, const std::string &s3)
std::vector< std::string > split(const std::string &s, const std::string &t=":")
get_immediate_subdirectories(a_dir)
==============================================================
checkBlockList(relFlavour, cache, generatorName)
Add special config option (extended model info for BSM scenarios).
_checkattr(attr, required=False)
==============================================================
mk_symlink(srcfile, dstfile)
OutputTXTFile()
==============================================================
checkPurpleList(relFlavour, cache, generatorName)
IovVectorMap_t read(const Folder &theFolder, const SelectionCriterion &choice, const unsigned int limit=10)