ATLAS Offline Software
Loading...
Searching...
No Matches
python.GENtoEVGEN_Skeleton Namespace Reference

Functions

 setupSample (runArgs, flags)
 checkBlackList (cache, generatorName, checkType)
 fromRunArgs (runArgs)

Variables

 jobPropertiesDisallowed
 evgenLog = logging.getLogger("Gen_tf")

Detailed Description

Functionality core of the Gen_tf transform

Function Documentation

◆ checkBlackList()

python.GENtoEVGEN_Skeleton.checkBlackList ( cache,
generatorName,
checkType )

Definition at line 120 of file GENtoEVGEN_Skeleton.py.

120def checkBlackList(cache, generatorName, checkType) :
121 isError = None
122 fileName = "BlackList_caches.txt" if checkType == "black" else "PurpleList_generators.txt"
123 with open(f"/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common/{fileName}") as bfile:
124 for line in bfile.readlines():
125 if not line.strip():
126 continue
127 # Bad caches
128 badCache=line.split(',')[1].strip()
129 # Bad generators
130 badGens=line.split(',')[2].strip()
131
132 used_gens = ','.join(generatorName)
133 # Match Generator and release cache
134 if cache==badCache and re.search(badGens,used_gens) is not None:
135 if badGens=="": badGens="all generators"
136 isError=f"{cache} is {checkType}-listed for {badGens}"
137 return isError
138 return isError
139
140
141# Main function

◆ fromRunArgs()

python.GENtoEVGEN_Skeleton.fromRunArgs ( runArgs)

Definition at line 142 of file GENtoEVGEN_Skeleton.py.

142def fromRunArgs(runArgs):
143 # print release information
144 d = release_metadata()
145 evgenLog.info("using release [%(project name)s-%(release)s] [%(platform)s] [%(nightly name)s/%(nightly release)s] -- built on [%(date)s]", d)
146 athenaRel = d["release"]
147
148 evgenLog.info("****************** STARTING EVENT GENERATION *****************")
149
150 evgenLog.info("**** Transformation run arguments")
151 evgenLog.info(runArgs)
152
153 evgenLog.info("**** Setting-up configuration flags")
154
155 from AthenaConfiguration.AllConfigFlags import initConfigFlags
156 flags = initConfigFlags()
157
158 from AthenaConfiguration.Enums import ProductionStep
159 flags.Common.ProductionStep = ProductionStep.Generation
160
161 # Convert run arguments to global athena flags
162 from PyJobTransforms.CommonRunArgsToFlags import commonRunArgsToFlags
163 commonRunArgsToFlags(runArgs, flags)
164
165 # Convert generator-specific run arguments to global athena flags
166 from GeneratorConfig.GeneratorConfigFlags import generatorRunArgsToFlags
167 generatorRunArgsToFlags(runArgs, flags)
168
169 # convert arguments to flags
170 flags.fillFromArgs()
171
172 # Create an instance of the Sample(EvgenCAConfig) and update global flags accordingly
173 sample = setupSample(runArgs, flags)
174
175 # Sort the list of generator names into standard form
176 from GeneratorConfig.GenConfigHelpers import gen_sortkey, gen_lhef
177 generatorNames = sorted(sample.generators, key=gen_sortkey)
178
179 # Check black-list and purple-list
180 blError = checkBlackList(athenaRel,generatorNames, "black")
181 plError = checkBlackList(athenaRel,generatorNames, "purple")
182 if blError is not None:
183 raise RuntimeError(blError)
184 if plError is not None:
185 evgenLog.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
186 evgenLog.warning(f"!!! WARNING {plError} !!!")
187 evgenLog.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
188
189 # Setup the main flags
190 flags.Exec.FirstEvent = runArgs.firstEvent
191 # Max events should be not set, job stopping is handled by CountHepMC
192 # using the RequestedOutput property
193 flags.Exec.MaxEvents = -1
194
195 if hasattr(runArgs, "inputEVNT_PreFile"):
196 flags.Input.Files = runArgs.inputEVNT_PreFile
197 else:
198 flags.Input.Files = []
199 flags.Input.RunNumbers = [flags.Generator.DSID]
200 flags.Input.TimeStamps = [0]
201
202 flags.Output.EVNTFileName = runArgs.outputEVNTFile
203
204 flags.Beam.Energy = runArgs.ecmEnergy / 2 * GeV
205
206 flags.PerfMon.doFastMonMT = True
207 flags.PerfMon.doFullMonMT = True
208
209 # Process pre-include
210 processPreInclude(runArgs, flags)
211
212 # Process pre-exec
213 processPreExec(runArgs, flags)
214
215 # Lock flags
216 flags.lock()
217
218 evgenLog.info("**** Configuration flags")
219 if runArgs.VERBOSE:
220 flags.dump()
221 else:
222 flags.dump("Generator.*")
223
224 # Print various stuff
225 evgenLog.info(".transform = Gen_tf")
226 evgenLog.info(".platform = " + str(os.environ["BINARY_TAG"]))
227
228 # Announce start of job configuration
229 evgenLog.info("**** Configuring event generation")
230
231 # Main object
232 from AthenaConfiguration.MainServicesConfig import MainEvgenServicesCfg
233 cfg = MainEvgenServicesCfg(flags, withSequences=True)
234
235 # Input file handling (if needed)
236 if flags.Input.Files:
237 from AthenaPoolCnvSvc.PoolReadConfig import PoolReadCfg
238 cfg.merge(PoolReadCfg(flags))
239
240 # EventInfoCnvAlg
241 from xAODEventInfoCnv.xAODEventInfoCnvConfig import EventInfoCnvAlgCfg
242 cfg.merge(EventInfoCnvAlgCfg(flags, disableBeamSpot=True, xAODKey="TMPEvtInfo"),
243 sequenceName=EvgenSequence.Generator.value)
244
245 # Set up the process
246 cfg.merge(sample.setupProcess(flags))
247
248 # Fix non-standard event features
249 if not flags.Input.Files:
250 from EvgenProdTools.EvgenProdToolsConfig import FixHepMCCfg
251 from GeneratorConfig.GenConfigHelpers import gens_purgenoendvtx
252 generatorsList = sample.generators.copy()
253 if "Pythia8" in generatorsList:
254 pythia8Alg = cfg.getEventAlgo("Pythia8_i")
255 if pythia8Alg.Beam1 != "PROTON" or pythia8Alg.Beam2 != "PROTON":
256 # generator name is still "Pythia8", even when colliding nuclei
257 generatorsList.append("Pythia8-Angantyr")
258 cfg.merge(FixHepMCCfg(flags,
259 PurgeUnstableWithoutEndVtx=gens_purgenoendvtx(generatorsList)))
260
261
262 from GeneratorConfig.GenConfigHelpers import gens_testhepmc
263 if gens_testhepmc(sample.generators):
264 from EvgenProdTools.EvgenProdToolsConfig import TestHepMCCfg
265 cfg.merge(TestHepMCCfg(flags))
266
267 # Copy the event weight from HepMC to the Athena EventInfo class
268 from EvgenProdTools.EvgenProdToolsConfig import CopyEventWeightCfg
269 cfg.merge(CopyEventWeightCfg(flags))
270
271 from EvgenProdTools.EvgenProdToolsConfig import FillFilterValuesCfg
272 cfg.merge(FillFilterValuesCfg(flags))
273
274 # Configure the event counting (AFTER all filters)
275 from EvgenProdTools.EvgenProdToolsConfig import CountHepMCCfg
276 cfg.merge(CountHepMCCfg(flags,
277 RequestedOutput=sample.nEventsPerJob if runArgs.maxEvents == -1
278 else runArgs.maxEvents))
279 evgenLog.info("Requested output events = %d", cfg.getEventAlgo("CountHepMC").RequestedOutput)
280
281 # Print out the contents of the first 5 events (after filtering)
282 if hasattr(runArgs, "printEvts") and runArgs.printEvts > 0:
283 from TruthIO.TruthIOConfig import PrintMCCfg
284 cfg.merge(PrintMCCfg(flags,
285 LastEvent=runArgs.printEvts))
286
287 # PerfMon
288 from PerfMonComps.PerfMonCompsConfig import PerfMonMTSvcCfg
289 cfg.merge(PerfMonMTSvcCfg(flags), sequenceName=EvgenSequence.Post.value)
290
291 # Estimate time needed for Simulation
292 from EvgenProdTools.EvgenProdToolsConfig import SimTimeEstimateCfg
293 cfg.merge(SimTimeEstimateCfg(flags))
294
295 # TODO: Rivet
296
297 # Include information about generators in metadata
298 from GeneratorConfig.Versioning import generatorsGetInitialVersionedDictionary, generatorsVersionedStringList
299 generatorDictionary = generatorsGetInitialVersionedDictionary(generatorNames)
300 generatorList = generatorsVersionedStringList(generatorDictionary)
301
302 # Extra metadata
303 # TODO: to be optimised
304 from EventInfoMgt.TagInfoMgrConfig import TagInfoMgrCfg
305 metadata = {
306 "project_name": "IS_SIMULATION",
307 f"AtlasRelease_{runArgs.trfSubstepName}": flags.Input.Release or "n/a",
308 "beam_energy": str(int(flags.Beam.Energy)),
309 "beam_type": flags.Beam.Type.value,
310 "generators": '+'.join(generatorList),
311 "hepmc_version": f"HepMC{os.environ['HEPMCVER']}",
312 "keywords": ", ".join(sample.keywords).lower(),
313 "lhefGenerator": '+'.join(filter(gen_lhef, generatorNames)),
314 "mc_channel_number": str(flags.Generator.DSID),
315 }
316 if hasattr(sample, "process"): metadata.update({"evgenProcess": sample.process})
317 if hasattr(sample, "tune"): metadata.update({"evgenTune": sample.tune})
318 if hasattr(sample, "specialConfig"): metadata.update({"specialConfiguration": sample.specialConfig})
319 if hasattr(sample, "hardPDF"): metadata.update({"hardPDF": sample.hardPDF})
320 if hasattr(sample, "softPDF"): metadata.update({"softPDF": sample.softPDF})
321 if hasattr(sample, "randomSeed"): metadata.update({"randomSeed": str(runArgs.randomSeed)})
322 cfg.merge(TagInfoMgrCfg(flags, tagValuePairs=metadata))
323
324 # Print version of HepMC to the log
325 evgenLog.info("HepMC version %s", os.environ["HEPMCVER"])
326
327 # Configure output stream
328 from OutputStreamAthenaPool.OutputStreamConfig import OutputStreamCfg
329 cfg.merge(OutputStreamCfg(flags, "EVNT", ["McEventCollection#*"]))
330
331 # Add in-file MetaData
332 from xAODMetaDataCnv.InfileMetaDataConfig import SetupMetaDataForStreamCfg
333 cfg.merge(SetupMetaDataForStreamCfg(flags, "EVNT"))
334
335 # Post-include
336 processPostInclude(runArgs, flags, cfg)
337
338 # Post-exec
339 processPostExec(runArgs, flags, cfg)
340
341 # Write AMI tag into in-file MetaData
342 from PyUtils.AMITagHelperConfig import AMITagCfg
343 cfg.merge(AMITagCfg(flags, runArgs))
344
345 # Print ComponentAccumulator components
346 cfg.printConfig(prefix="Gen_tf", printSequenceTreeOnly=not runArgs.VERBOSE)
347
348 # Run final ComponentAccumulator
349 sys.exit(not cfg.run().isSuccess())

◆ setupSample()

python.GENtoEVGEN_Skeleton.setupSample ( runArgs,
flags )

Definition at line 25 of file GENtoEVGEN_Skeleton.py.

25def setupSample(runArgs, flags):
26 # Only permit one jobConfig argument for evgen
27 if len(runArgs.jobConfig) != 1:
28 raise RuntimeError("You must supply one and only one jobConfig file argument")
29
30 evgenLog.info("Using JOBOPTSEARCHPATH (as seen in skeleton) = {}".format(os.environ["JOBOPTSEARCHPATH"]))
31
32 FIRST_DIR = (os.environ["JOBOPTSEARCHPATH"]).split(":")[0]
33
34 # Find jO file
35 jofiles = [f for f in os.listdir(FIRST_DIR) if (f.startswith("mc") and f.endswith(".py"))]
36 if len(jofiles) !=1:
37 raise RuntimeError("You must supply one and only one jobOption file in DSID directory")
38 jofile = jofiles[0]
39
40 # Perform consistency checks on the jO
41 from GeneratorConfig.GenConfigHelpers import checkJOConsistency, checkNEventsPerJob, checkKeywords, checkCategories
42 officialJO = checkJOConsistency(jofile)
43
44 # Import the jO as a module
45 # We cannot do import BLAH directly since
46 # 1. the filenames are not python compatible (mc.GEN_blah.py)
47 # 2. the filenames are different for every jO
48 import importlib.util
49 spec = importlib.util.spec_from_file_location(
50 name="sample",
51 location=os.path.join(FIRST_DIR,jofile),
52 )
53 jo = importlib.util.module_from_spec(spec)
54 spec.loader.exec_module(jo)
55 evgenLog.info("including file %s", jofile)
56
57 # Create instance of Sample(EvgenCAConfig)
58 sample = jo.Sample(flags)
59
60 # Set up the sample properties
61 sample.setupFlags(flags)
62
63 # Set the random number seed
64 # Need to use logic in EvgenJobTransforms.Generate_dsid_ranseed
65
66 # Get DSID
67 dsid = os.path.basename(runArgs.jobConfig[0])
68 if dsid.startswith("Test"):
69 dsid = dsid.split("Test")[-1]
70
71 # Update the global flags
72 if dsid.isdigit():
73 flags.Generator.DSID = int(dsid)
74
75 # Set nEventsPerJob
76 if not sample.nEventsPerJob:
77 evgenLog.info("#############################################################")
78 evgenLog.info(" !!!! no sample.nEventsPerJob set !!! The default 10000 used. !!! ")
79 evgenLog.info("#############################################################")
80 else:
81 checkNEventsPerJob(sample)
82 evgenLog.info(" nEventsPerJob = " + str(sample.nEventsPerJob))
83 flags.Generator.nEventsPerJob = sample.nEventsPerJob
84
85 # Check if sample attributes have been properly set
86 for var, value in vars(sample).items():
87 if not value:
88 raise RuntimeError("self.{} should be set in Sample(EvgenConfig)".format(var))
89 else:
90 if var == "generators":
91 from GeneratorConfig.Versioning import generatorsGetInitialVersionedDictionary, generatorsVersionedStringList
92 from GeneratorConfig.GenConfigHelpers import gen_sortkey
93 gennames = sorted(sample.generators, key=gen_sortkey)
94 gendict = generatorsGetInitialVersionedDictionary(gennames)
95 gennamesvers = generatorsVersionedStringList(gendict)
96 evgenLog.info("MetaData: generatorName = {}".format(gennamesvers))
97 else:
98 evgenLog.info("MetaData: {} = {}".format(var, value))
99
100 # Check for other inconsistencies in jO
101 if len(sample.generators) > len(set(sample.generators)):
102 raise RuntimeError("Duplicate entries in generators: invalid configuration, please check your JO")
103 from GeneratorConfig.GenConfigHelpers import gen_require_steering
104 if gen_require_steering(sample.generators):
105 if hasattr(runArgs, "outputEVNTFile") and not hasattr(runArgs, "outputEVNT_PreFile"):
106 raise RuntimeError("'EvtGen' found in job options name, please set '--steering=afterburn'")
107
108 # Keywords check
109 if hasattr(sample, "keywords"):
110 checkKeywords(sample, evgenLog, officialJO)
111
112 # L1, L2 categories check
113 if hasattr(sample, "categories"):
114 checkCategories(sample, evgenLog, officialJO)
115
116 return sample
117
118
119# Function to check black-listed releases
STL class.
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177

Variable Documentation

◆ evgenLog

python.GENtoEVGEN_Skeleton.evgenLog = logging.getLogger("Gen_tf")

Definition at line 11 of file GENtoEVGEN_Skeleton.py.

◆ jobPropertiesDisallowed

python.GENtoEVGEN_Skeleton.jobPropertiesDisallowed

Definition at line 7 of file GENtoEVGEN_Skeleton.py.