ATLAS Offline Software
skel.GENtoTXT.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
2 #
3 """Functionality core of the Generate_tf transform"""
4 
5 
8 
9 
11 
12 import ast
13 import os, re, string, subprocess
14 import AthenaCommon.AlgSequence as acas
15 import AthenaCommon.AppMgr as acam
16 from AthenaCommon.AthenaCommonFlags import jobproperties
17 from AthenaCommon.AthenaCommonFlags import athenaCommonFlags
18 from AthenaCommon.AthenaCommonFlags import jobproperties
19 
20 from xAODEventInfoCnv.xAODEventInfoCnvConf import xAODMaker__EventInfoCnvAlg
21 acam.athMasterSeq += xAODMaker__EventInfoCnvAlg(xAODKey="TMPEvtInfo")
22 
23 theApp = acam.theApp
24 acam.athMasterSeq += acas.AlgSequence("EvgenGenSeq")
25 genSeq = acam.athMasterSeq.EvgenGenSeq
26 acam.athMasterSeq += acas.AlgSequence("EvgenFixSeq")
27 fixSeq = acam.athMasterSeq.EvgenFixSeq
28 acam.athMasterSeq += acas.AlgSequence("EvgenPreFilterSeq")
29 prefiltSeq = acam.athMasterSeq.EvgenPreFilterSeq
30 acam.athMasterSeq += acas.AlgSequence("EvgenTestSeq")
31 testSeq = acam.athMasterSeq.EvgenTestSeq
32 
33 from EvgenProdTools.LogicalExpressionFilter import LogicalExpressionFilter
34 acam.athMasterSeq += LogicalExpressionFilter("EvgenFilterSeq")
35 filtSeq = acam.athMasterSeq.EvgenFilterSeq
36 topSeq = acas.AlgSequence()
37 anaSeq = topSeq
38 topSeq += acas.AlgSequence("EvgenPostSeq")
39 postSeq = topSeq.EvgenPostSeq
40 
43 
44 
45 import AthenaCommon.AtlasUnixGeneratorJob
46 include("PartPropSvc/PartPropSvc.py")
47 
48 
49 from PerfMonComps.PerfMonFlags import jobproperties as perfmonjp
50 perfmonjp.PerfMonFlags.doFastMonMT = True
51 
52 from RngComps.RngCompsConf import AthRNGSvc
53 svcMgr += AthRNGSvc()
54 
55 
56 jobproperties.AthenaCommonFlags.AllowIgnoreConfigError = False
57 
58 
59 from AthenaCommon.Logging import logging
60 evgenLog = logging.getLogger('Gen_tf')
61 
62 
65 
66 
67 evgenLog.debug("****************** CHECKING EVENT GENERATION ARGS *****************")
68 evgenLog.debug(str(runArgs))
69 evgenLog.info ("****************** CHECKING EVENT GENERATION ARGS *****************")
70 
71 # TODO: Allow generation without writing an output file (if outputEVNTFile is None)?
72 if not hasattr(runArgs, "ecmEnergy"):
73  raise RuntimeError("No center of mass energy provided.")
74 else:
75  evgenLog.info(' ecmEnergy = ' + str(runArgs.ecmEnergy) )
76 
79 
80 
81 evgenLog.debug("****************** CONFIGURING MATRIX ELEMENT GENERATION *****************")
82 evgenLog.info("****************** CONFIGURING MATRIX ELEMENT GENERATION *****************")
83 
84 
86 from EvgenJobTransforms.EvgenConfig import evgenConfig
87 from GeneratorConfig.GenConfigHelpers import gens_known, gen_lhef, gens_lhef, gen_sortkey, gens_testhepmc, gens_notune, gen_require_steering
88 
89 
91 from EvgenProdTools.EvgenProdToolsConf import CountHepMC
92 if (runArgs.firstEvent <= 0):
93  evgenLog.warning("Run argument firstEvent should be > 0")
94 
95 svcMgr.EventSelector.FirstEvent = runArgs.firstEvent
96 theApp.EvtMax = -1
97 
98 #evgenConfig.nEventsPerJob = 1
99 if not hasattr(postSeq, "CountHepMC"):
100  postSeq += CountHepMC(InputEventInfo="TMPEvtInfo",
101  OutputEventInfo="EventInfo",
102  mcEventWeightsKey="")
103 
104 postSeq.CountHepMC.FirstEvent = runArgs.firstEvent
105 postSeq.CountHepMC.CorrectHepMC = True
106 postSeq.CountHepMC.CorrectEventID = True
107 
108 
109 
112 
113 
114 evgenLog.debug("****************** LOADING PRE-INCLUDES AND JOB CONFIG *****************")
115 evgenLog.info("****************** LOADING PRE-INCLUDES AND JOB CONFIG *****************")
116 
117 
118 if hasattr(runArgs, "preInclude"):
119  for fragment in runArgs.preInclude:
120  include(fragment)
121 
122 
123 if hasattr(runArgs, "preExec"):
124  evgenLog.info("Transform pre-exec")
125  for cmd in runArgs.preExec:
126  evgenLog.info(cmd)
127  exec(cmd)
128 
130  return [name for name in os.listdir(a_dir)
131  if os.path.isdir(os.path.join(a_dir, name))]
132 
133 
134 # TODO: Explain!!!
135 def OutputTXTFile():
136  outputTXTFile = None
137  if hasattr(runArgs,"outputTXTFile"): outputTXTFile=runArgs.outputTXTFile
138  return outputTXTFile
139 
140 
142 
143 if len(runArgs.jobConfig) != 1:
144  evgenLog.info("runArgs.jobConfig = " + runArgs.jobConfig)
145  evgenLog.error("You must supply one and only one jobConfig file argument. It has to start from mc. and end with .py")
146  sys.exit(1)
147 
148 print ("Using JOBOPTSEARCHPATH (as seen in skeleton) = '%s'" % (os.environ["JOBOPTSEARCHPATH"]))
149 FIRST_DIR = (os.environ['JOBOPTSEARCHPATH']).split(":")[0]
150 
151 dsid_param = runArgs.jobConfig[0]
152 evgenLog.info("dsid_param = " + dsid_param)
153 dsid = os.path.basename(dsid_param)
154 evgenLog.info("dsid = " + dsid)
155 jofiles = [f for f in os.listdir(FIRST_DIR) if (f.startswith('mc') and f.endswith('.py'))]
156 
157 if len(jofiles) !=1:
158  evgenLog.info("runArgs.jobConfig wrong " + runArgs.jobConfig)
159  evgenLog.error("You must supply one and only one jobOption file in DSID directory. It has to start with mc. and end with .py")
160  sys.exit(1)
161 jofile = jofiles[0]
162 joparts = (os.path.basename(jofile)).split(".")
163 
164 officialJO = False
165 if joparts[0].startswith("mc") and all(c in string.digits for c in joparts[0][2:]):
166  officialJO = True
167 
168  if len(joparts) != 3:
169  evgenLog.error(jofile + " name format is wrong: must be of the form MC<xx>.<physicsShort>.py: please rename.")
170  sys.exit(1)
171 
172 
173  jo_physshortpart = joparts[1]
174  max_jo_physshort_length = 50
175  if len(jo_physshortpart) > max_jo_physshort_length:
176  evgenLog.error(f"{jofile} contains a physicsShort field of more than {max_jo_physshort_length} characters: please rename.")
177  sys.exit(1)
178 
179  jo_physshortparts = jo_physshortpart.split("_")
180  if len(jo_physshortparts) < 2:
181  evgenLog.error(jofile + " has too few physicsShort fields separated by '_': should contain <generators>(_<tune+PDF_if_available>)_<process>. Please rename.")
182  sys.exit(1)
183 
184  check_jofiles="/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/scripts/check_jo_consistency.py"
185  if os.path.exists(check_jofiles):
186  evgenLog.info("Checking offical JO file name consistency")
187  include(check_jofiles)
188  check_naming(os.path.basename(jofile))
189  else:
190  evgenLog.warning("check_jo_consistency.py not found, will proceed without JOs consistency check")
191 # sys.exit(1)
192 
193 include(jofile)
194 include("EvgenJobTransforms/LHEonly.py")
195 
196 
199 
200 
201 evgenLog.debug("****************** CHECKING EVGEN CONFIGURATION *****************")
202 evgenLog.info("****************** CHECKING EVGEN CONFIGURATION *****************")
203 
204 
205 for opt in str(evgenConfig).split(os.linesep):
206  evgenLog.info(opt)
207 evgenLog.info(".transform = Gen_tf")
208 
209 
212 if evgenConfig.obsolete:
213  evgenLog.error("JOs or icludes are obsolete, please check them")
214  sys.exit(1)
215 
216 if not evgenConfig.generators:
217  evgenLog.error("No entries in evgenConfig.generators: invalid configuration, please check your JO")
218  sys.exit(1)
219 
220 if len(evgenConfig.generators) > len(set(evgenConfig.generators)):
221  evgenLog.error("Duplicate entries in evgenConfig.generators: invalid configuration, please check your JO")
222  sys.exit(1)
223 
224 gennames = sorted(evgenConfig.generators, key=gen_sortkey)
225 
226 if joparts[0].startswith("MC"): #< if this is an "official" JO
227  genpart = jo_physshortparts[0]
228  expectedgenpart = ''.join(gennames)
229 
230  expectedgenpart = expectedgenpart.replace("HerwigJimmy", "Herwig")
231  def _norm(s):
232  # TODO: add EvtGen to this normalization for MC14?
233  return s.replace("Photospp", "").replace("Photos", "").replace("TauolaPP", "").replace("Tauolapp", "").replace("Tauola", "")
234  def _norm2(s):
235  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")
236 
237  def _short2(s):
238  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")
239 
240 
241  if genpart != _norm(expectedgenpart) and _norm2(genpart) != _norm(expectedgenpart):
242  evgenLog.error("Expected first part of JO name to be '%s' or '%s', but found '%s'" % (_norm(expectedgenpart), _norm(_short2(expectedgenpart)), genpart))
243  evgenLog.error("gennames '%s' " %(expectedgenpart))
244  sys.exit(1)
245 
246  del _norm
247 
248  if not gens_notune(gennames) and len(jo_physshortparts) < 3:
249  evgenLog.error(jofile + " with generators " + expectedgenpart +
250  " has too few physicsShort fields separated by '_'." +
251  " It should contain <generators>_<tune+PDF_<process>. Please rename.")
252  sys.exit(1)
253 
254 
256 if gen_require_steering(gennames):
257  if hasattr(runArgs, "outputEVNTFile") and not hasattr(runArgs, "outputEVNT_PreFile"):
258  raise RuntimeError("'EvtGen' found in job options name, please set '--steering=afterburn'")
259 
260 
261 
263 rounding = 0
264 if hasattr(runArgs,'inputGeneratorFile') and ',' in runArgs.inputGeneratorFile: multiInput = runArgs.inputGeneratorFile.count(',')+1
265 else:
266  multiInput = 0
267 
268 # check if default nEventsPerJob used
269 if not evgenConfig.nEventsPerJob:
270  evgenLog.info('#############################################################')
271  evgenLog.info(' !!!! no nEventsPerJob set !!! The default 10000 used. !!! ')
272  evgenLog.info('#############################################################')
273 else:
274  evgenLog.info(' nEventsPerJob set to ' + str(evgenConfig.nEventsPerJob) )
275 
276 if evgenConfig.minevents > 0 :
277  raise RuntimeError("evgenConfig.minevents is obsolete and should be removed from the JOs")
278 
279 if evgenConfig.nEventsPerJob < 1:
280  raise RunTimeError("evgenConfig.nEventsPerJob must be at least 1")
281 else:
282  evgenLog.info("evgenConfig.nEventsPerJob = {}, but only {} (dummy) event(s) will be generated by Pythia8 for lhe-only production".format(evgenConfig.nEventsPerJob, postSeq.CountHepMC.RequestedOutput))
283 
284 
285 
286 if not evgenConfig.keywords:
287  evgenLog.warning("No entries in evgenConfig.keywords: invalid configuration, please check your JO !!")
288 
289 
290 if evgenConfig.keywords:
291  from GeneratorConfig.GenConfigHelpers import checkKeywords
292  checkKeywords(evgenConfig, evgenLog, officialJO)
293 
294 
295 if not evgenConfig.categories:
296  evgenLog.warning("No entries in evgenConfig.categories: invalid configuration, please check your JO !!")
297 
298 
299 if evgenConfig.categories:
300 
302  lkwfile = "CategoryList.txt"
303  lkwpath = None
304  for p in os.environ["DATAPATH"].split(":"):
305  lkwpath = os.path.join(p, lkwfile)
306  if os.path.exists(lkwpath):
307  break
308  lkwpath = None
309 
310  allowed_cat = []
311  if lkwpath:
312  with open(lkwpath, 'r') as catlist:
313  for line in catlist:
314  allowed_list = ast.literal_eval(line)
315  allowed_cat.append(allowed_list)
316 
317 
318  bad_cat =[]
319  it = iter(evgenConfig.categories)
320  for x in it:
321  l1 = x
322  l2 = next(it)
323  if "L1:" in l2 and "L2:" in l1:
324  l1, l2 = l2, l1
325  print("first",l1,"second",l2)
326  bad_cat.extend([l1, l2])
327  for a1,a2 in allowed_cat:
328  if l1.strip().lower()==a1.strip().lower() and l2.strip().lower()==a2.strip().lower():
329  bad_cat=[]
330  if bad_cat:
331  msg = "evgenConfig.categories contains non-standard category: %s. " % ", ".join(bad_cat)
332  msg += "Please check the allowed categories list and fix."
333  evgenLog.error(msg)
334  if officialJO:
335  sys.exit(1)
336  else:
337  evgenLog.warning("Could not find CategoryList.txt file %s in DATAPATH" % lkwfile)
338 
339 
340 dsid = os.path.basename(runArgs.jobConfig[0])
341 if not dsid.isdigit():
342  dsid = "999999"
343 svcMgr.EventSelector.RunNumber = int(dsid)
344 
345 
346 from GeneratorConfig.Versioning import generatorsGetInitialVersionedDictionary, generatorsVersionedStringList
347 gendict = generatorsGetInitialVersionedDictionary(gennames)
348 gennamesvers = generatorsVersionedStringList(gendict)
349 
350 import EventInfoMgt.EventInfoMgtInit
351 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"hepmc_version":"HepMC" + str(os.environ['HEPMCVER'])})
352 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"mc_channel_number":str(dsid)})
353 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"lhefGenerator": '+'.join( filter( gen_lhef, gennames ) ) })
354 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"generators": '+'.join(gennamesvers)})
355 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"evgenProcess": evgenConfig.process})
356 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"evgenTune": evgenConfig.tune})
357 if hasattr( evgenConfig, "hardPDF" ) : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"hardPDF": evgenConfig.hardPDF})
358 if hasattr( evgenConfig, "softPDF" ) : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"softPDF": evgenConfig.softPDF})
359 if hasattr( runArgs, "randomSeed") : svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"randomSeed": str(runArgs.randomSeed)})
360 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"keywords": ", ".join(evgenConfig.keywords).lower()})
361 
362 # print version of HepMC to the log
363 evgenLog.info("HepMC version " + str(os.environ['HEPMCVER']))
364 
365 # Set AMITag in in-file metadata
366 from PyUtils import AMITagHelper
367 AMITagHelper.SetAMITag(runArgs=runArgs)
368 
369 
370 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"beam_energy": str(int(runArgs.ecmEnergy*Units.GeV/2.0))})
371 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"beam_type": 'collisions'})
372 
373 
375 include("EvgenJobTransforms/Generate_ecmenergies.py")
376 
377 # Propagate DSID and seed to the generators
378 include("EvgenJobTransforms/Generate_dsid_ranseed.py")
379 
380 
381 if (hasattr( runArgs, "VERBOSE") and runArgs.VERBOSE ) or (hasattr( runArgs, "loglevel") and runArgs.loglevel == "DEBUG") or (hasattr( runArgs, "loglevel") and runArgs.loglevel == "VERBOSE"):
382  include("EvgenJobTransforms/Generate_debug_level.py")
383 
384 
388 def checkBlackList(relFlavour,cache,generatorName) :
389  isError = None
390  with open('/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common/BlackList_caches.txt') as bfile:
391  for line in bfile.readlines():
392  if not line.strip():
393  continue
394  # Blacklisted release flavours
395  badRelFlav=line.split(',')[0].strip()
396  # Blacklisted caches
397  badCache=line.split(',')[1].strip()
398  # Blacklisted generators
399  badGens=line.split(',')[2].strip()
400 
401  used_gens = ','.join(generatorName)
402  #Match Generator and release type e.g. AtlasProduction, MCProd
403  if relFlavour==badRelFlav and cache==badCache and re.search(badGens,used_gens) is not None:
404  if badGens=="": badGens="all generators"
405  isError=relFlavour+","+cache+" is blacklisted for " + badGens
406  return isError
407  return isError
408 
409 def checkPurpleList(relFlavour,cache,generatorName) :
410  isError = None
411  with open('/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common/PurpleList_generators.txt') as bfile:
412  for line in bfile.readlines():
413  if not line.strip():
414  continue
415  # Purple-listed release flavours
416  purpleRelFlav=line.split(',')[0].strip()
417  # Purple-listed caches
418  purpleCache=line.split(',')[1].strip()
419  # Purple-listed generators
420  purpleGens=line.split(',')[2].strip()
421  # Purple-listed process
422  purpleProcess=line.split(',')[3].strip()
423 
424  used_gens = ','.join(generatorName)
425  #Match Generator and release type e.g. AtlasProduction, MCProd
426  if relFlavour==purpleRelFlav and cache==purpleCache and re.search(purpleGens,used_gens) is not None:
427  isError=relFlavour+","+cache+" is blacklisted for " + purpleGens + " if it uses " + purpleProcess
428  return isError
429  return isError
430 
431 
432 evgenLog.debug("****************** CHECKING RELEASE IS NOT BLACKLISTED *****************")
433 rel = os.popen("echo $AtlasVersion").read()
434 rel = rel.strip()
435 if os.path.exists('/cvmfs/atlas.cern.ch/repo/sw/Generators/MC16JobOptions/common'):
436  errorBL = checkBlackList("AthGeneration",rel,gennames)
437  if (errorBL):
438  if (hasattr( runArgs, "ignoreBlackList") and runArgs.ignoreBlackList):
439  evgenLog.warning("This run is blacklisted for this generator, please use a different one for production !! "+ errorBL )
440  else:
441  raise RuntimeError("This run is blacklisted for this generator, please use a different one !! "+ errorBL)
442 
443  errorPL = checkPurpleList("AthGeneration",rel,gennames)
444  if (errorPL):
445  evgenLog.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
446  evgenLog.warning("!!! WARNING !!! "+ errorPL )
447  evgenLog.warning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
448 else:
449  msg.waring("No access to cvmfs, so blacklisted runs will not be checked")
450 
451 
452 
453 svcMgr.TagInfoMgr.ExtraTagValuePairs.update({"specialConfiguration": evgenConfig.specialConfig})
454 
455 
456 
458 
459 
460 
463 
464 if hasattr(runArgs, "postInclude"):
465  for fragment in runArgs.postInclude:
466  include(fragment)
467 
468 if hasattr(runArgs, "postExec"):
469  evgenLog.info("Transform post-exec")
470  for cmd in runArgs.postExec:
471  evgenLog.info(cmd)
472  exec(cmd)
473 
474 
477 acas.dumpMasterSequence()
478 
479 
480 
483 
484 
485 evgenLog.debug("****************** HANDLING EVGEN INPUT FILES *****************")
486 print("****************** HANDLING EVGEN INPUT FILES *****************")
487 
488 datFile = None
489 if "McAtNlo" in evgenConfig.generators and "Herwig" in evgenConfig.generators:
490  datFile = "inparmMcAtNlo.dat"
491 elif "Alpgen" in evgenConfig.generators:
492  datFile = "inparmAlpGen.dat"
493 elif "Protos" in evgenConfig.generators:
494  datFile = "protos.dat"
495 elif "ProtosLHEF" in evgenConfig.generators:
496  datFile = "protoslhef.dat"
497 elif "AcerMC" in evgenConfig.generators:
498  datFile = "inparmAcerMC.dat"
499 elif "CompHep" in evgenConfig.generators:
500  datFile = "inparmCompHep.dat"
501 
502 
503 if "Alpgen" in evgenConfig.generators:
504  eventsFile = "alpgen.unw_events"
505 elif "Protos" in evgenConfig.generators:
506  eventsFile = "protos.events"
507 elif "ProtosLHEF" in evgenConfig.generators:
508  eventsFile = "protoslhef.events"
509 elif "BeamHaloGenerator" in evgenConfig.generators:
510  eventsFile = "beamhalogen.events"
511 elif "HepMCAscii" in evgenConfig.generators:
512  eventsFile = "events.hepmc"
513 elif "ReadMcAscii" in evgenConfig.generators:
514  eventsFile = "events.hepmc"
515 elif gens_lhef(evgenConfig.generators):
516  #eventsFile = outputTXTFile
517  eventsFile = "events.lhe"
518 
519 
520 
521 def find_unique_file(pattern):
522  "Return a matching file, provided it is unique"
523  import glob
524  files = glob.glob(pattern)
525 
526  if not files:
527  raise RuntimeError("No '%s' file found" % pattern)
528  elif len(files) > 1:
529  raise RuntimeError("More than one '%s' file found" % pattern)
530  return files[0]
531 
532 # This function merges a list of input LHE file to make one outputFile. The header is taken from the first
533 # file, but the number of events is updated to equal the total number of events in all the input files
534 def merge_lhe_files(listOfFiles,outputFile):
535  if(os.path.exists(outputFile)):
536  print ("outputFile ",outputFile," already exists. Will rename to ",outputFile,".OLD")
537  os.rename(outputFile,outputFile+".OLD")
538  output = open(outputFile,'w')
539  holdHeader = ""
540  nevents=0
541  for file in listOfFiles:
542  cmd = "grep /event "+file+" | wc -l"
543  nevents+=int(subprocess.check_output(cmd,stderr=subprocess.STDOUT,shell=True))
544 
545  for file in listOfFiles:
546  inHeader = True
547  header = ""
548  print ("*** Starting file ",file)
549  for line in open(file,"r"):
550 
555  if("<event" in line and inHeader):
556  inHeader = False
557  if(len(holdHeader)<1):
558  holdHeader = header
559  output.write(header)
560  output.write(line)
561 
563  elif(not inHeader and not ("</LesHouchesEvents>" in line)):
564  output.write(line)
565  if(inHeader):
566 
567  if("nevents" in line):
568 
569  tmp = line.split("=")
570  line = line.replace(tmp[0],str(nevents))
571  elif("numevts" in line):
572 
573  tmp = line.split(" ")
574  nnn = str(nevents)
575  line = line.replace(tmp[1],nnn)
576  header+=line
577  output.write("</LesHouchesEvents>\n")
578  output.close()
579 
580 def mk_symlink(srcfile, dstfile):
581  "Make a symlink safely"
582  if dstfile:
583  if os.path.exists(dstfile) and not os.path.samefile(dstfile, srcfile):
584  os.remove(dstfile)
585  if not os.path.exists(dstfile):
586  evgenLog.info("Symlinking %s to %s" % (srcfile, dstfile))
587  os.symlink(srcfile, dstfile)
588  else:
589  evgenLog.debug("Symlinking: %s is already the same as %s" % (dstfile, srcfile))
590 
591 
592 if eventsFile or datFile:
593  if not hasattr(runArgs, "inputGeneratorFile") or runArgs.inputGeneratorFile == "NONE":
594  raise RuntimeError("%s needs input file (argument inputGeneratorFile)" % runArgs.jobConfig)
595  if evgenConfig.inputfilecheck and not re.search(evgenConfig.inputfilecheck, runArgs.inputGeneratorFile):
596  raise RuntimeError("inputGeneratorFile=%s is incompatible with inputfilecheck '%s' in %s" %
597  (runArgs.inputGeneratorFile, evgenConfig.inputfilecheck, runArgs.jobConfig))
598  if datFile:
599  if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
600  inputroot = os.path.basename(runArgs.inputGeneratorFile).split(".tar.")[0]
601  else:
602  inputroot = os.path.basename(runArgs.inputGeneratorFile).split("._")[0]
603 
604  realDatFile = find_unique_file('*%s*.dat' % inputroot)
605  mk_symlink(realDatFile, datFile)
606  if eventsFile:
607  myinputfiles = runArgs.inputGeneratorFile
608  genInputFiles = myinputfiles.split(',')
609  numberOfFiles = len(genInputFiles)
610  # if there is a single file, make a symlink. If multiple files, merge them into one output eventsFile
611  if(numberOfFiles<2):
612  if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
613  inputroot = os.path.basename(runArgs.inputGeneratorFile).split(".tar.")[0]
614  else:
615  inputroot = os.path.basename(runArgs.inputGeneratorFile).split("._")[0]
616 
617  if "events" in inputroot :
618  inputroot = inputroot.replace(".events","")
619  realEventsFile = find_unique_file('*%s.*ev*ts' % inputroot)
620  mk_symlink(realEventsFile, eventsFile)
621  else:
622  allFiles = []
623  for file in genInputFiles:
624 # Since we can have multiple files from the same task, inputroot must include more of the filename
625 # to make it unique
626  if ".tar" in os.path.basename(runArgs.inputGeneratorFile):
627  inputroot = os.path.basename(runArgs.inputGeneratorFile).split(".tar.")[0]
628  else:
629  input0 = os.path.basename(file).split("._")[0]
630  input1 = (os.path.basename(file).split("._")[1]).split(".")[0]
631  inputroot = input0+"._"+input1
632  realEventsFile = find_unique_file('*%s.*ev*ts' % inputroot)
633 # The only input format where merging is permitted is LHE
634  with open(realEventsFile, 'r') as f:
635  first_line = f.readline()
636  if(not ("LesHouche" in first_line)):
637  raise RuntimeError("%s is NOT a LesHouche file" % realEventsFile)
638  allFiles.append(realEventsFile)
639  merge_lhe_files(allFiles,eventsFile)
640 
641 else:
642  if hasattr(runArgs, "inputGeneratorFile") and runArgs.inputGeneratorFile != "NONE":
643  raise RuntimeError("inputGeneratorFile arg specified for %s, but generators %s do not require an input file" %
644  (runArgs.jobConfig, str(gennames)))
645 # if evgenConfig.inputfilecheck:
646 # raise RuntimeError("evgenConfig.inputfilecheck specified in %s, but generators %s do not require an input file" %
647 # (runArgs.jobConfig, str(gennames)))
648 
649 
650 if evgenConfig.auxfiles:
651  from PyJobTransformsCore.trfutil import get_files
652  get_files(evgenConfig.auxfiles, keepDir=False, errorIfNotFound=True)
653 
654 
657 
658 def _checkattr(attr, required=False):
659  if not hasattr(evgenConfig, attr) or not getattr(evgenConfig, attr):
660  msg = "evgenConfig attribute '%s' not found." % attr
661  if required:
662  raise RuntimeError("Required " + msg)
663  return False
664  return True
665 # counting the number of events in LHE output
666 count_ev = 0
667 with open(eventsFile) as f:
668  for line in f:
669  count_ev += line.count('/event')
670 
671 evgenLog.info('Requested output events = '+str(count_ev))
672 print("MetaData: %s = %s" % ("Number of produced LHE events ", count_ev))
673 
674 if _checkattr("description", required=True):
675  msg = evgenConfig.description
676  if _checkattr("notes"):
677  msg += " " + evgenConfig.notes
678  print("MetaData: %s = %s" % ("physicsComment", msg))
679 if _checkattr("generators", required=True):
680  print ("MetaData: %s = %s" % ("generatorName", "+".join(gennamesvers)))
681 if _checkattr("process"):
682  print ("MetaData: %s = %s" % ("physicsProcess", evgenConfig.process))
683 if _checkattr("tune"):
684  print ("MetaData: %s = %s" % ("generatorTune", evgenConfig.tune))
685 if _checkattr("hardPDF"):
686  print ("MetaData: %s = %s" % ("hardPDF", evgenConfig.hardPDF))
687 if _checkattr("softPDF"):
688  print ("MetaData: %s = %s" % ("softPDF", evgenConfig.softPDF))
689 if _checkattr("nEventsPerJob"):
690  print ("MetaData: %s = %s" % ("nEventsPerJob", evgenConfig.nEventsPerJob))
691 if _checkattr("keywords"):
692  print ("MetaData: %s = %s" % ("keywords", ", ".join(evgenConfig.keywords).lower() ))
693 if _checkattr("categories"):
694  print ( ", " + ", ".join(evgenConfig.categories))
695 else:
696  print (" ")
697 
698 #if _checkattr("categories"): # will be uncommented when categories included into metadata
699 # print "MetaData: %s = %s" % ("categories", ", ".join(evgenConfig.categories))
700 if _checkattr("specialConfig"):
701  print ("MetaData: %s = %s" % ("specialConfig", evgenConfig.specialConfig))
702 # TODO: Require that a contact / JO author is always set
703 if _checkattr("contact"):
704  print ("MetaData: %s = %s" % ("contactPhysicist", ", ".join(evgenConfig.contact)))
705 #if _checkattr( "randomSeed") : # comment out for the time being
706 print ("MetaData: %s = %s" % ("randomSeed", str(runArgs.randomSeed)))
707 
708 
709 
710 
711 # Output list of generator filters used
712 filterNames = [alg.getType() for alg in acas.iter_algseq(filtSeq)]
713 excludedNames = ['AthSequencer', 'PyAthena::Alg', 'TestHepMC']
714 filterNames = list(set(filterNames) - set(excludedNames))
715 print ("MetaData: %s = %s" % ("genFilterNames", ", ".join(filterNames)))
716 
717 
718 
721 
722 from PyJobTransformsCore.runargs import RunArguments
723 runPars = RunArguments()
724 runPars.nEventsPerJob = evgenConfig.nEventsPerJob
725 runPars.maxeventsstrategy = evgenConfig.maxeventsstrategy
726 with open("config.pickle", "wb") as f:
727  import pickle
728  pickle.dump(runPars, f)
729 
730 
731 
734 
735 evgenLog.debug("****************** STARTING EVENT GENERATION *****************")
736 print ("****************** STARTING EVENT GENERATION *****************")
737 print ("**************************************************************")
738 print ("****************** PLEASE IGNORE THE LOG FROM PYTHIA ************")
739 print ("****************** GENERATION OF ONE PYTHIA EVENT ***************")
740 print ("******************** IS NEEDED TO MAKE *************")
741 print ("****************** THE TRANSFORM WORK ***************************")
742 print ("**************************************************************")
read
IovVectorMap_t read(const Folder &theFolder, const SelectionCriterion &choice, const unsigned int limit=10)
Definition: openCoraCool.cxx:569
replace
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition: hcg.cxx:307
skel.find_unique_file
def find_unique_file(pattern)
Helper functions for input file handling.
Definition: skel.ABtoEVGEN.py:461
vtune_athena.format
format
Definition: vtune_athena.py:14
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
trfutil
skel.merge_lhe_files
def merge_lhe_files(listOfFiles, outputFile)
Check that there is exactly 1 match.
Definition: skel.GENtoEVGEN.py:652
covarianceTool.filter
filter
Definition: covarianceTool.py:514
AthRNGSvc
A service to manage multiple RNG streams in thread-safe way.
Definition: AthRNGSvc.h:34
skel.OutputTXTFile
def OutputTXTFile()
==============================================================
Definition: skel.ABtoEVGEN.py:181
find_unique_file
Definition: find_unique_file.py:1
fillPileUpNoiseLumi.next
next
Definition: fillPileUpNoiseLumi.py:52
skel.checkBlackList
def checkBlackList(relFlavour, cache, generatorName)
Propagate debug output level requirement to generators.
Definition: skel.GENtoEVGEN.py:516
LArG4FSStartPointFilter.exec
exec
Definition: LArG4FSStartPointFilter.py:103
python.GenConfigHelpers.gen_require_steering
def gen_require_steering(gennames)
Definition: GenConfigHelpers.py:49
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
LogicalExpressionFilter
Definition: LogicalExpressionFilter.py:1
python.Versioning.generatorsGetInitialVersionedDictionary
def generatorsGetInitialVersionedDictionary(generators)
Definition: Versioning.py:25
python.GenConfigHelpers.gens_notune
def gens_notune(gennames)
Definition: GenConfigHelpers.py:84
skel._short2
def _short2(s)
Definition: skel.ABtoEVGEN.py:272
python.GenConfigHelpers.gens_lhef
def gens_lhef(gennames)
Definition: GenConfigHelpers.py:68
python.Include.include
include
Definition: Include.py:318
python.GenConfigHelpers.checkKeywords
def checkKeywords(sample, evgenLog, officialJO)
Definition: GenConfigHelpers.py:150
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
merge_lhe_files
Definition: merge_lhe_files.py:1
CxxUtils::set
constexpr std::enable_if_t< is_bitmask_v< E >, E & > set(E &lhs, E rhs)
Convenience function to set bits in a class enum bitmask.
Definition: bitmask.h:232
print
void print(char *figname, TCanvas *c1)
Definition: TRTCalib_StrawStatusPlots.cxx:25
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
skel._norm
def _norm(s)
Definition: skel.ABtoEVGEN.py:266
skel.checkPurpleList
def checkPurpleList(relFlavour, cache, generatorName)
Definition: skel.GENtoEVGEN.py:537
python.Versioning.generatorsVersionedStringList
def generatorsVersionedStringList(generatorsDictionary)
Definition: Versioning.py:44
Cut::all
@ all
Definition: SUSYToolsAlg.cxx:67
skel.get_immediate_subdirectories
def get_immediate_subdirectories(a_dir)
==============================================================
Definition: skel.GENtoEVGEN.py:207
Trk::open
@ open
Definition: BinningType.h:40
skel._checkattr
def _checkattr(attr, required=False)
==============================================================
Definition: skel.ABtoEVGEN.py:494
skel.mk_symlink
def mk_symlink(srcfile, dstfile)
Definition: skel.ABtoEVGEN.py:472
if
if(febId1==febId2)
Definition: LArRodBlockPhysicsV0.cxx:567
skel._norm2
def _norm2(s)
Definition: skel.ABtoEVGEN.py:269
CountHepMC
Count the number of events to pass all algorithms/filters.
Definition: CountHepMC.h:22
str
Definition: BTagTrackIpAccessor.cxx:11
python.trfutil.get_files
def get_files(listOfFiles, fromWhere='data', doCopy='ifNotLocal', errorIfNotFound=True, keepDir=True, depth=0, sep=os.pathsep)
Definition: trfutil.py:40
Trk::split
@ split
Definition: LayerMaterialProperties.h:38