ATLAS Offline Software
TRTCalib_calib_Skeleton.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
2 
3 import sys, tarfile, glob, random, subprocess
4 
5 from PyJobTransforms.CommonRunArgsToFlags import commonRunArgsToFlags
6 from PyJobTransforms.TransformUtils import processPreExec, processPreInclude, processPostExec, processPostInclude
7 from TRT_CalibAlgs.TRTCalibrationMgrConfig import CalibConfig, TRT_CalibrationMgrCfg, TRT_StrawStatusCfg
8 from AthenaConfiguration.MainServicesConfig import MainServicesCfg
9 
10 def nextstep(text):
11  print("\n"+"#"*100)
12  print("#")
13  print("# %s" % (text))
14  print("#")
15  print("#"*100,"\n")
16 
17 def tryError(command, error):
18  try:
19  print(" Running: %s\n" % (command))
20  stdout, stderr = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
21  print("OUTPUT: \n%s" % (stdout.decode('ascii')))
22  print("ERRORS: %s" % ("NONE" if stderr.decode('ascii')=='' else "\n"+stderr.decode('ascii')))
23  if stderr:
24  exit(1)
25  except OSError as e:
26  print(error,e)
27  sys.exit(e.errno)
28 
29 def fromRunArgs(runArgs):
30 
31  outputFile = runArgs.outputTAR_CALIBFile
32 
33 
34  nextstep("UNTAR input file")
35 
36 
37  print("Uncompressing files:")
38  try:
39  for file in runArgs.inputTARFile:
40  print("\t-",file)
41  tarfile.open(file).extractall(".")
42  except OSError as e:
43  print("ERROR: Failed uncompressing TAR file\n",e)
44  sys.exit(e.errno)
45 
46 
47  nextstep("Renaming *straw.txt and *tracktuple.root files for the final output")
48 
49 
50  listOfStrawFiles = glob.glob("*.merged.straw.txt")
51  listOfTrackFiles = glob.glob("*.tracktuple.root")
52 
53  if not listOfStrawFiles or (not listOfTrackFiles and runArgs.piecetoken != "all"):
54  print("ERROR: Empty array of \"*.merged.straw.txt\" (size %d) or \"*.tracktuple.root\" (size %d) files" % (len(listOfStrawFiles), len(listOfTrackFiles)))
55  exit(1)
56 
57  command = "mv -v %s %s.merged.straw.txt; " % (listOfStrawFiles[0],outputFile)
58 
59  if(runArgs.piecetoken == "all"):
60  print("INFO: piecetoken equal to \"all\". Saving *tracktuple.root file")
61  command += "mv -v %s %s.tracktuple.root; " % (listOfTrackFiles[0],outputFile)
62  else:
63  print("INFO: piecetoken different than \"all\". Not need to rename *tracktuple.root file")
64 
65  tryError(command, "Renaming *straw.txt and *tracktuple.root files\n")
66 
67 
68  nextstep("Calculating constants ATHENA")
69 
70 
71  myFile = []
72  # generating the RAW file path
73  if runArgs.rawfile:
74  myFile.append(runArgs.rawfile)
75 
76  else:
77  if not runArgs.project and not runArgs.runnr and not runArgs.stream:
78  try:
79  splitInput = runArgs.inputTARFile[0].split('.')
80  project="----"
81  runnr ="----"
82  stream ="----"
83  if splitInput:
84  runArgs.project = splitInput[0]
85  runArgs.runnr = splitInput[1]
86  runArgs.stream = splitInput[2]
87  print("INFO: No input arguments are given to name the RAW file. Obtained from \"lsn\"...")
88  else:
89  print("ERROR: not able to find project=\"%s\" or runNumber=\"%s\" or stream=\"%s\" from \"lsn\" " % (project, runnr, stream))
90  exit(1)
91 
92  except OSError as e:
93  print("ERROR: Failed trying to build RAW file name for Athena.\n",e)
94  sys.exit(e.errno)
95 
96  if (not runArgs.project or not runArgs.runnr or not runArgs.stream):
97  print("ERROR: Raw file not provided, project=\"%s\" or runNumber=\"%s\" or stream=\"%s\" missing..." % (runArgs.project, runArgs.runnr, runArgs.stream))
98  print("Provide them!")
99  sys.exit(1)
100  else:
101  rawpath = "/eos/atlas/atlastier0/rucio/%s/%s/%s/%s.%s.%s.merge.RAW/" % (runArgs.project,runArgs.stream,runArgs.runnr.zfill(8),runArgs.project,runArgs.runnr.zfill(8),runArgs.stream)
102  globedFiles = glob.glob(rawpath+"*")
103  if not globedFiles:
104  print("ERROR: Not able to find any file under %s. Please check that the path is correct or files exists" % (rawpath))
105  sys.exit(1)
106 
107  myFile.append(random.choice(globedFiles))
108  print("RAW file selected for testing:",myFile)
109  if not myFile:
110  print("ERROR: provide a valid project=\"%s\" or runNumber=\"%s\" or stream=\"%s\"" % (runArgs.project, runArgs.runnr, runArgs.stream))
111  sys.exit(1)
112 
113  from AthenaConfiguration.AllConfigFlags import initConfigFlags
114  flags=initConfigFlags()
115 
116  commonRunArgsToFlags(runArgs, flags)
117 
118  processPreInclude(runArgs, flags)
119  processPreExec(runArgs, flags)
120 
121  # Change this to a the hardcoded data file
122  flags.Input.Files=myFile
123  flags.Output.HISTFileName="DontUse.remove"
124 
125  # Only one event must be run
126  flags.Exec.MaxEvents=1
127 
128  # Importing flags - Switching off detector parts and monitoring
129  CalibConfig(flags)
130 
131  # To respect --athenaopts
132  flags.fillFromArgs()
133 
134  # Reason why we need to clone and replace: https://gitlab.cern.ch/atlas/athena/-/merge_requests/68616#note_7614858
135  flags = flags.cloneAndReplace(
136  "Tracking.ActiveConfig",
137  f"Tracking.{flags.Tracking.PrimaryPassConfig.value}Pass",
138  # Keep original flags as some of the subsequent passes use
139  # lambda functions relying on them
140  keepOriginal=True)
141 
142  flags.lock()
143  flags.dump()
144 
145  cfg=MainServicesCfg(flags)
146 
147  from ByteStreamCnvSvc.ByteStreamConfig import ByteStreamReadCfg
148  cfg.merge(ByteStreamReadCfg(flags))
149 
150  from InDetConfig.TrackRecoConfig import InDetTrackRecoCfg
151  cfg.merge(InDetTrackRecoCfg(flags))
152 
153  cfg.merge(TRT_CalibrationMgrCfg(flags,DoCalibrate=True, Hittuple=glob.glob("*.basic.root")[0], caltag=runArgs.piecetoken))
154  cfg.merge(TRT_StrawStatusCfg(flags))
155 
156  processPostInclude(runArgs, flags, cfg)
157  processPostExec(runArgs, flags, cfg)
158 
159  with open("ConfigTRTCalib_calib.pkl", "wb") as f:
160  cfg.store(f)
161 
162  sc = cfg.run()
163  if not sc.isSuccess():
164  sys.exit(not sc.isSuccess())
165 
166 
167  nextstep("Renaming outputs from Calibrator")
168 
169 
170  command = "mv -v calibout.root %s.calibout.root ; " % (outputFile)
171  command += "mv -v calibout_rt.txt %s.calibout_rt.txt; " % (outputFile)
172  command += "mv -v calibout_t0.txt %s.calibout_t0.txt; " % (outputFile)
173  command += "mv -v calib_constants_out.txt %s.calib_constants_out.txt; " % (outputFile)
174 
175  tryError(command, "ERROR: Failed renaming files in TRT calib step\n")
176 
177 
178  nextstep("TAR'ing files")
179 
180  try:
181  # Getting list of files to be compressed
182  files_list=glob.glob(outputFile+".*")
183  # Compressing
184  tar = tarfile.open(outputFile, "w:gz")
185  print("Compressing files in %s output file:" % outputFile)
186  for file in files_list:
187  print("\t-",file)
188  tar.add(file)
189  tar.close()
190  except OSError as e:
191  print("ERROR: Failed compressing the output files\n",e)
192  sys.exit(e.errno)
193 
194  # Prints all types of txt files present in a Path
195  print("\nListing files:")
196  for file in sorted(glob.glob("./*", recursive=True)):
197  print("\t-",file)
python.TransformUtils.processPreExec
def processPreExec(runArgs, flags)
Definition: Tools/PyJobTransforms/python/TransformUtils.py:41
python.TransformUtils.processPostExec
def processPostExec(runArgs, flags, cfg)
Definition: Tools/PyJobTransforms/python/TransformUtils.py:50
TRTCalib_calib_Skeleton.nextstep
def nextstep(text)
Definition: TRTCalib_calib_Skeleton.py:10
TRTCalib_calib_Skeleton.tryError
def tryError(command, error)
Definition: TRTCalib_calib_Skeleton.py:17
python.TransformUtils.processPostInclude
def processPostInclude(runArgs, flags, cfg)
Definition: Tools/PyJobTransforms/python/TransformUtils.py:69
python.ByteStreamConfig.ByteStreamReadCfg
def ByteStreamReadCfg(flags, type_names=None)
Definition: Event/ByteStreamCnvSvc/python/ByteStreamConfig.py:25
python.TransformUtils.processPreInclude
def processPreInclude(runArgs, flags)
Definition: Tools/PyJobTransforms/python/TransformUtils.py:62
TRTCalib_calib_Skeleton.fromRunArgs
def fromRunArgs(runArgs)
Definition: TRTCalib_calib_Skeleton.py:29
TRTCalibrationMgrConfig.TRT_StrawStatusCfg
def TRT_StrawStatusCfg(flags, name='InDet_TRT_StrawStatus', **kwargs)
Definition: TRTCalibrationMgrConfig.py:57
python.MainServicesConfig.MainServicesCfg
def MainServicesCfg(flags, LoopMgr='AthenaEventLoopMgr')
Definition: MainServicesConfig.py:260
python.CommonRunArgsToFlags.commonRunArgsToFlags
def commonRunArgsToFlags(runArgs, configFlags)
Definition: CommonRunArgsToFlags.py:12
calibdata.exit
exit
Definition: calibdata.py:236
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.
TRTCalibrationMgrConfig.TRT_CalibrationMgrCfg
def TRT_CalibrationMgrCfg(flags, name='TRT_CalibrationMgr', calibconstants='', Hittuple='', caltag='', **kwargs)
Definition: TRTCalibrationMgrConfig.py:9
python.TrackRecoConfig.InDetTrackRecoCfg
def InDetTrackRecoCfg(flags)
Main ID tracking config #####################.
Definition: TrackRecoConfig.py:791
TRTCalibrationMgrConfig.CalibConfig
def CalibConfig(flags)
Definition: TRTCalibrationMgrConfig.py:74
Trk::open
@ open
Definition: BinningType.h:40
python.AllConfigFlags.initConfigFlags
def initConfigFlags()
Definition: AllConfigFlags.py:19
if
if(febId1==febId2)
Definition: LArRodBlockPhysicsV0.cxx:567
dbg::print
void print(std::FILE *stream, std::format_string< Args... > fmt, Args &&... args)
Definition: SGImplSvc.cxx:70
Trk::split
@ split
Definition: LayerMaterialProperties.h:38