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

Functions

 setupSample (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()

checkBlackList ( cache,
generatorName,
checkType )

Definition at line 130 of file GEN_Skeleton.py.

130def checkBlackList(cache, generatorName, checkType) :
131 isError = None
132 fileName = "BlackList_caches.txt" if checkType == "black" else "PurpleList_generators.txt"
133 with open(f"/cvmfs/atlas.cern.ch/repo/sw/Generators/MCJobOptions/common/{fileName}") as bfile:
134 for line in bfile.readlines():
135 if not line.strip():
136 continue
137 # Bad caches
138 badCache=line.split(',')[1].strip()
139 # Bad generators
140 badGens=line.split(',')[2].strip()
141
142 used_gens = ','.join(generatorName)
143 # Match Generator and release cache
144 if cache==badCache and re.search(badGens,used_gens) is not None:
145 if badGens=="": badGens="all generators"
146 isError=f"{cache} is {checkType}-listed for {badGens}"
147 return isError
148 return isError
149
150
151# Main function

◆ fromRunArgs()

fromRunArgs ( runArgs)

Definition at line 152 of file GEN_Skeleton.py.

152def fromRunArgs(runArgs):
153 # print release information
154 d = release_metadata()
155 evgenLog.info("using release [%(project name)s-%(release)s] [%(platform)s] [%(nightly name)s/%(nightly release)s] -- built on [%(date)s]", d)
156 athenaRel = d["release"]
157
158 evgenLog.info("****************** STARTING EVENT GENERATION *****************")
159
160 evgenLog.info("**** Transformation run arguments")
161 evgenLog.info(runArgs)
162
163 evgenLog.info("**** Setting-up configuration flags")
164
165 from AthenaConfiguration.AllConfigFlags import initConfigFlags
166 flags = initConfigFlags()
167
168 from AthenaConfiguration.Enums import ProductionStep
169 flags.Common.ProductionStep = ProductionStep.Generation
170
171 # Convert run arguments to global athena flags
172 from PyJobTransforms.CommonRunArgsToFlags import commonRunArgsToFlags
173 commonRunArgsToFlags(runArgs, flags)
174
175 # Convert generator-specific run arguments to global athena flags
176 from GeneratorConfig.GeneratorConfigFlags import generatorRunArgsToFlags
177 generatorRunArgsToFlags(runArgs, flags)
178
179 # convert arguments to flags
180 flags.fillFromArgs()
181
182 # Create an instance of the Sample(EvgenCAConfig) and update global flags accordingly
183 sample = setupSample(flags)
184
185 # Determine output file name and type.
186 output_pool_file = (
187 flags.Output.EVNTFileName
188 or getattr(runArgs, "outputEVNTFile", None)
189 or getattr(runArgs, "outputEVNT_PreFile", None)
190 )
191 flags.Output.EVNTFileName = output_pool_file or ""
192 output_txt_file = (
193 flags.Output.TXTFileName
194 or getattr(runArgs, "outputTXTFile", None)
195 )
196 flags.Output.TXTFileName = output_txt_file or ""
197
198 # If no EVNT output is specified, we check if it's a TXT-only run (i.e. standalone LHE output production).
199 # In that case, we don't require an EVNT output file.
200 txt_only_mode = _is_txt_only_run(flags)
201 if not output_pool_file and not (flags.Generator.outputYODAFile or txt_only_mode):
202 raise RuntimeError("No output evgen EVNT or EVNT_Pre file provided.")
203
204 # Setup the main flags
205 flags.Exec.FirstEvent = flags.Generator.firstEvent
206
207 # We are always doing MC
208 flags.Input.isMC = True
209
210 # If no inputEVNT_PreFile was provided clear transform placeholder input files
211 # and set RunNumber/TimeStamp based on DSID.
212 if hasattr(runArgs, "inputEVNT_PreFile") and runArgs.inputEVNT_PreFile:
213 flags.Input.Files = runArgs.inputEVNT_PreFile
214 else:
215 flags.Input.Files = []
216
217 if not flags.Input.Files:
218 flags.Input.Files = []
219 flags.Input.RunNumbers = [flags.Generator.DSID]
220 flags.Input.TimeStamps = [0]
221
222 flags.PerfMon.doFastMonMT = True
223 flags.PerfMon.doFullMonMT = True
224
225 # Process pre-include
226 processPreInclude(runArgs, flags)
227
228 # Process pre-exec
229 processPreExec(runArgs, flags)
230
231 # Lock flags
232 flags.lock()
233
234 evgenLog.info("**** Configuration flags")
235 if runArgs.VERBOSE:
236 flags.dump()
237 else:
238 flags.dump("Generator.*")
239
240 # Print various stuff
241 evgenLog.info(".transform = Gen_tf")
242 evgenLog.info(".platform = " + str(os.environ["BINARY_TAG"]))
243
244 # Announce start of job configuration
245 evgenLog.info("**** Configuring event generation")
246
247 # Main object
248 from AthenaConfiguration.MainServicesConfig import MainEvgenServicesCfg
249 cfg = MainEvgenServicesCfg(flags, withSequences=True)
250 # We need to tell athena to continuously generate events until the
251 # number of requested output events is reached. This is not necessarily
252 # equal to EvtMax (maxEvents) because of filters.
253 cfg.setAppProperty("EvtMax", -1, overwrite=True)
254
255 # Input file handling (if needed)
256 if flags.Input.Files and not txt_only_mode:
257 from AthenaPoolCnvSvc.PoolReadConfig import PoolReadCfg
258 cfg.merge(PoolReadCfg(flags))
259
260 # EventInfoCnvAlg
261 from xAODEventInfoCnv.xAODEventInfoCnvConfig import EventInfoCnvAlgCfg
262 cfg.merge(EventInfoCnvAlgCfg(flags, disableBeamSpot=True, xAODKey="TMPEvtInfo"),
263 sequenceName=EvgenSequence.Generator.value)
264
265 # Set up the process
266 cfg.merge(sample.setupProcess(flags))
267
268 # Sort the list of generator names into standard form
269 from GeneratorConfig.GenConfigHelpers import gen_sortkey
270 from GeneratorConfig.Versioning import generatorsGetInitialVersionedDictionary, generatorsVersionedStringList
271 if not flags.Input.Files:
272 generators = sorted(cfg.getService("GeneratorInfoSvc").Generators, key=gen_sortkey)
273 gendict = generatorsGetInitialVersionedDictionary(generators)
274 generatorsWithVersion = generatorsVersionedStringList(gendict)
275 else:
276 # TODO: read from metadata
277 generators = []
278 generatorsWithVersion = []
279
280 # Check if the setup requires steering
281 from GeneratorConfig.GenConfigHelpers import gen_require_steering
282 if gen_require_steering(generators):
283 if hasattr(runArgs, "outputEVNTFile") and not hasattr(runArgs, "outputEVNT_PreFile"):
284 raise RuntimeError("'EvtGen' found in job options name, please set '--steering=afterburn'")
285
286 # LHE input handling
287 nEventsLHE = None
288 if flags.Generator.inputFilesPerJob > 0:
289 if not flags.Generator.inputGeneratorFile:
290 raise RuntimeError(f"Sample sets inputFilesPerJob = {flags.Generator.inputFilesPerJob} but Gen_tf run without inputGeneratorFile")
291 else:
292 nEventsLHE = _handle_input_files(generators, flags)
293
294 # Check black-list and purple-list
295 blError = checkBlackList(athenaRel, generators, "black")
296 plError = checkBlackList(athenaRel, generators, "purple")
297 if blError is not None:
298 raise RuntimeError(blError)
299 if plError is not None:
300 evgenLog.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
301 evgenLog.warning(f"!!! WARNING {plError} !!!")
302 evgenLog.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
303
304 # Fix non-standard event features
305 if not txt_only_mode and not flags.Input.Files:
306 from EvgenProdTools.EvgenProdToolsConfig import FixHepMCCfg
307 from GeneratorConfig.GenConfigHelpers import gens_purgenoendvtx
308 generatorsList = generators.copy()
309 if "Pythia8" in generatorsList:
310 pythia8Alg = cfg.getEventAlgo("Pythia8_i")
311 if pythia8Alg.Beam1 != "PROTON" or pythia8Alg.Beam2 != "PROTON":
312 # generator name is still "Pythia8", even when colliding nuclei
313 generatorsList.append("Pythia8-Angantyr")
314 cfg.merge(FixHepMCCfg(flags,
315 PurgeUnstableWithoutEndVtx=gens_purgenoendvtx(generatorsList)))
316
317 # Merge GenWeightDeclarationCfg to declare the number
318 # of generator weights to the CutFlowSvc
319 if output_pool_file and not flags.Input.Files:
320 from EvgenProdTools.EvgenProdToolsConfig import GenWeightDeclarationCfg
321 cfg.merge(GenWeightDeclarationCfg(flags))
322
323 # Sanity check the event record (not appropriate for all generators)
324 from GeneratorConfig.GenConfigHelpers import gens_testhepmc
325 if not txt_only_mode and gens_testhepmc(generators):
326 from EvgenProdTools.EvgenProdToolsConfig import TestHepMCCfg
327 cfg.merge(TestHepMCCfg(flags))
328
329 # Copying event-level HepMC decorations is EVNT-oriented and not needed for
330 # standalone LHE output production.
331 if not txt_only_mode:
332 from EvgenProdTools.EvgenProdToolsConfig import CopyEventWeightCfg
333 cfg.merge(CopyEventWeightCfg(flags))
334
335 from EvgenProdTools.EvgenProdToolsConfig import FillFilterValuesCfg
336 cfg.merge(FillFilterValuesCfg(flags))
337
338 # Configure the event counting (AFTER all filters)
339 from EvgenProdTools.EvgenProdToolsConfig import CountHepMCCfg
340 requested_output = (
341 1 if txt_only_mode else
342 (sample.nEventsPerJob if flags.Exec.MaxEvents == -1 else flags.Exec.MaxEvents)
343 )
344 count_kwargs = {"RequestedOutput": requested_output}
345 if txt_only_mode:
346 # In TXT-only mode there is no GEN_EVENT in StoreGate. Disabling
347 # HepMC/EventInfo corrections avoids dereferencing missing event data.
348 count_kwargs["CorrectHepMC"] = False
349 count_kwargs["CorrectEventID"] = False
350 count_kwargs["CorrectRunNumber"] = False
351 count_kwargs["CopyRunNumber"] = False
352 count_kwargs["InputEventInfo"] = ""
353 count_kwargs["OutputEventInfo"] = ""
354 count_kwargs["mcEventWeightsKey"] = ""
355 cfg.merge(CountHepMCCfg(flags, **count_kwargs))
356 evgenLog.info(f"Requested output events = {cfg.getEventAlgo('CountHepMC').RequestedOutput}")
357
358 # Print out the contents of the first 5 events (after filtering)
359 if not txt_only_mode and flags.Generator.printEvts > 0:
360 from TruthIO.TruthIOConfig import PrintMCCfg
361 cfg.merge(PrintMCCfg(flags,
362 LastEvent=flags.Generator.printEvts))
363
364 # PerfMon
365 from PerfMonComps.PerfMonCompsConfig import PerfMonMTSvcCfg
366 cfg.merge(PerfMonMTSvcCfg(flags), sequenceName=EvgenSequence.Post.value)
367
368 # Estimate time needed for Simulation
369 if not txt_only_mode:
370 from EvgenProdTools.EvgenProdToolsConfig import SimTimeEstimateCfg
371 cfg.merge(SimTimeEstimateCfg(flags))
372
373 # TODO: Rivet
374
375 # Extra metadata
376 from EventInfoMgt.TagInfoMgrConfig import TagInfoMgrCfg
377 from GeneratorConfig.GenConfigHelpers import gen_lhef
378 metadata = {
379 "project_name": "IS_SIMULATION",
380 f"AtlasRelease_{runArgs.trfSubstepName}": flags.Input.Release or "n/a",
381 "beam_energy": str(int(flags.Beam.Energy)),
382 "beam_type": flags.Beam.Type.value,
383 "hepmc_version": f"HepMC{os.environ['HEPMCVER']}",
384 "keywords": ", ".join(sample.keywords).lower(),
385 "lhefGenerator": '+'.join(filter(gen_lhef, generators)),
386 "mc_channel_number": str(flags.Generator.DSID),
387 }
388 if not flags.Input.Files:
389 metadata.update({
390 "generators": '+'.join(generatorsWithVersion),
391 "tune": cfg.getService("GeneratorInfoSvc").Tune
392 })
393 if hasattr(sample, "process"): metadata.update({"evgenProcess": sample.process})
394 if hasattr(sample, "tune"): metadata.update({"evgenTune": sample.tune})
395 if hasattr(sample, "hadronizationModel"): metadata.update({"hadronizationModel": sample.hadronizationModel})
396 if hasattr(sample, "partonShowerModel"): metadata.update({"partonShowerModel": sample.partonShowerModel})
397 if hasattr(sample, "specialConfig"): metadata.update({"specialConfiguration": sample.specialConfig})
398 if hasattr(sample, "hardPDF"): metadata.update({"hardPDF": sample.hardPDF})
399 if hasattr(sample, "softPDF"): metadata.update({"softPDF": sample.softPDF})
400 if hasattr(sample, "randomSeed"): metadata.update({"randomSeed": str(flags.Random.SeedOffset)})
401 cfg.merge(TagInfoMgrCfg(flags, tagValuePairs=metadata))
402
403 # Print metadata in the log
404 evgenLog.info(f"HepMC version {os.environ['HEPMCVER']}")
405 if not flags.Input.Files:
406 evgenLog.info(f"MetaData: generatorTune = {cfg.getService('GeneratorInfoSvc').Tune}")
407 evgenLog.info("MetaData: generatorName = {}".format(generatorsWithVersion))
408 if nEventsLHE is not None:
409 print(f"MetaData: Number of input LHE events = {nEventsLHE}")
410 elif txt_only_mode:
411 produced_lhe = None
412 for candidate in (flags.Output.TXTFileName, "events.lhe"):
413 if candidate and os.path.exists(candidate):
414 produced_lhe = candidate
415 break
416 if produced_lhe:
417 nEventsTXT = _count_lhe_events(produced_lhe)
418 print(f"MetaData: Number of produced LHE events = {nEventsTXT}")
419
420 if output_pool_file:
421 # Count all events that are written
422 from EventBookkeeperTools.EventBookkeeperToolsConfig import AllWrittenEventsCounterAlgCfg
423 cfg.merge(AllWrittenEventsCounterAlgCfg(flags))
424
425 # Configure output stream
426 from OutputStreamAthenaPool.OutputStreamConfig import OutputStreamCfg
427 cfg.merge(OutputStreamCfg(flags, "EVNT", ["McEventCollection#*"],
428 MetadataItemList=["IOVMetaDataContainer#*"]))
429
430 # Add in-file MetaData
431 from AthenaConfiguration.Enums import MetadataCategory
432 from xAODMetaDataCnv.InfileMetaDataConfig import SetupMetaDataForStreamCfg
433 cfg.merge(SetupMetaDataForStreamCfg(flags, "EVNT",
434 createMetadata=[MetadataCategory.CutFlowMetaData,
435 MetadataCategory.TruthMetaData]))
436
437 # Post-include
438 processPostInclude(runArgs, flags, cfg)
439
440 # Post-exec
441 processPostExec(runArgs, flags, cfg)
442
443 # Write AMI tag into in-file MetaData
444 from PyUtils.AMITagHelperConfig import AMITagCfg
445 cfg.merge(AMITagCfg(flags, runArgs))
446
447 # Hack the main sequence to not ignore filters
448 # TODO: figure out if we can do it in a more elegant way without another nested sequence
449 cfg.getSequence("AthAlgSeq").IgnoreFilterPassed = False
450
451 # Print ComponentAccumulator components
452 cfg.printConfig(prefix="Gen_tf", printSequenceTreeOnly=not runArgs.VERBOSE)
453
454 # Run final ComponentAccumulator
455 sys.exit(not cfg.run().isSuccess())
void print(char *figname, TCanvas *c1)

◆ setupSample()

setupSample ( flags)

Definition at line 37 of file GEN_Skeleton.py.

37def setupSample(flags):
38 # Only permit one jobConfig argument for evgen
39 job_config = flags.Generator.jobConfig
40 if isinstance(job_config, str):
41 job_config = [job_config]
42 if len(job_config) != 1:
43 raise RuntimeError("You must supply one and only one jobConfig file argument")
44
45 evgenLog.info("Using JOBOPTSEARCHPATH (as seen in skeleton) = {}".format(os.environ["JOBOPTSEARCHPATH"]))
46
47 FIRST_DIR = (os.environ["JOBOPTSEARCHPATH"]).split(":")[0]
48
49 # Find jO file
50 jofiles = [f for f in os.listdir(FIRST_DIR) if (f.startswith("mc") and f.endswith(".py"))]
51 if len(jofiles) !=1:
52 raise RuntimeError("You must supply one and only one jobOption file in DSID directory")
53 jofile = jofiles[0]
54
55 # Perform consistency checks on the jO
56 from GeneratorConfig.GenConfigHelpers import (
57 checkNaming,
58 checkNEventsPerJob,
59 checkKeywords,
60 checkCategories
61 )
62 checkNaming(jofile)
63
64 # Import the jO as a module
65 # We cannot do import BLAH directly since
66 # 1. the filenames are not python compatible (mc.GEN_blah.py)
67 # 2. the filenames are different for every jO
68 import importlib.util
69 spec = importlib.util.spec_from_file_location(
70 name="sample",
71 location=os.path.join(FIRST_DIR,jofile),
72 )
73 jo = importlib.util.module_from_spec(spec)
74
75 spec.loader.exec_module(jo)
76 evgenLog.info(f"including file {jofile}")
77
78 # Create instance of Sample(EvgenCAConfig)
79 sample = jo.Sample(flags)
80
81 # Set up the sample properties
82 sample.setupFlags(flags)
83
84 # Set the random number seed
85 # Need to use logic in EvgenJobTransforms.Generate_dsid_ranseed
86
87 # Get DSID
88 dsid = os.path.basename(job_config[0])
89 if dsid.startswith("Test"):
90 dsid = dsid.split("Test")[-1]
91
92 # Update the global flags
93 if dsid.isdigit():
94 flags.Generator.DSID = int(dsid)
95
96 # Set nEventsPerJob
97 if not sample.nEventsPerJob:
98 evgenLog.info("#############################################################")
99 evgenLog.info(" !!!! no sample.nEventsPerJob set !!!")
100 evgenLog.info("#############################################################")
101 # We don't need to set the global flag because its default is 10000
102 else:
103 checkNEventsPerJob(sample)
104 evgenLog.info(" nEventsPerJob = " + str(sample.nEventsPerJob))
105 flags.Generator.nEventsPerJob = sample.nEventsPerJob
106
107 # Validate all required/conditional sample metadata with explicit rules.
108 _validate_sample_properties(sample)
109
110 # Propagate optional sample values to global flags.
111 flags.Generator.inputFilesPerJob = sample.inputFilesPerJob
112 flags.Generator.MEgenerator = sample.MEgenerator or ""
113
114 # Print sample metadata in the log.
115 for var, value in vars(sample).items():
116 evgenLog.info("MetaData: {} = {}".format(var, value))
117
118 # Keywords check
119 if hasattr(sample, "keywords"):
120 checkKeywords(sample, evgenLog)
121
122 # L1, L2 categories check
123 if hasattr(sample, "categories"):
124 checkCategories(sample, evgenLog)
125
126 return sample
127
128
129# Function to check black-listed releases
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:179

Variable Documentation

◆ evgenLog

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

Definition at line 11 of file GEN_Skeleton.py.

◆ jobPropertiesDisallowed

python.GEN_Skeleton.jobPropertiesDisallowed

Definition at line 7 of file GEN_Skeleton.py.