ATLAS Offline Software
CSV_InDetImporter.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
2 
3 from AthenaPython.PyAthenaComps import Alg,StatusCode
4 import csv
5 import ROOT
6 import os
7 import math
8 from InDetMeasurementUtilities.CSV_DictFormats import CSV_DictFormats
9 
10 def getCSVFilename(outputDir, container, eventNumber):
11  return f"{outputDir}/{container}_event_{eventNumber}.csv"
12 
14  """
15  Algorithm to load InDet tracks data from CSV files to xAOD collections
16  Conventions in files naming:
17  - the files should reside in one dir and alg needs to be pointed to it through indir property, the naming convention: container_event_XYZ.csv should be used
18  - files CSV format needs to be identical to the one used in export
19  - if a given file is missing the data is not loaded, just reporting in the log about it
20  - If need to modify this behavior, hey, go for it, it is python
21  """
22  def __init__(self, name):
23  Alg.__init__ (self, name)
24  self.indir = None
25  self.trackParticleName = None
26  return
27 
28  def initialize(self):
29  if self.indir is None:
30  self.msg.error("Input directory not configured")
31  return StatusCode.Failure
32  if not os.path.exists(self.indir):
33  self.msg.error("Missing input directory %s", self.indir)
34  return StatusCode.Failure
35 
36  return StatusCode.Success
37 
38  def execute(self):
39  if self.trackParticleName:
40  if not self.readTrackParticle():
41  return StatusCode.Failure
42 
43  return StatusCode.Success
44 
45  def getEventNumber(self):
46  ei = self.evtStore.retrieve("xAOD::EventInfo", "EventInfo")
47  return ei.eventNumber()
48 
49  def readTrackParticle(self):
50  inputFileName = getCSVFilename(self.indir, self.trackParticleName, self.getEventNumber())
51  if not os.path.exists(inputFileName):
52  self.msg.warning("Missing file %s, this will result in missing collections in certain events which is not allowed by POOL &ROOT ", inputFileName)
53  return StatusCode.Recoverable
54 
55 
56  c = ROOT.xAOD.TrackParticleContainer()
57  aux = ROOT.xAOD.TrackParticleAuxContainer()
58  c.setStore (aux)
59  ROOT.SetOwnership (c,False)
60  ROOT.SetOwnership (aux,False)
61 
62  # data reading
63  with open(inputFileName, "r") as f:
64  reader = csv.DictReader(f)
65  for k in reader.fieldnames:
66  if k not in CSV_DictFormats["InDetTrackParticles"].keys():
67  self.msg.error("A key: %s found in data that does not seem to be known", k)
68  return StatusCode.Failure
69 
70  for data in reader:
71  tp = ROOT.xAOD.TrackParticle()
72  c.push_back(tp)
73  ROOT.SetOwnership (tp, False)
74  covm = ROOT.xAOD.ParametersCovMatrix_t()
75  covm.setZero()
76  theta = 2.0 * math.atan( math.exp(-float(data['eta'])))
77  tp.setDefiningParameters(float(data['d0']), float(data['z0']), float(data['phi']),
78  theta,
79  float(data['charge']) * math.sin(theta)/float(data['pt']))
80  tp.setDefiningParametersCovMatrix(covm)
81  pass
82 
83  if not self.evtStore.record (c, self.trackParticleName, False):
84  return StatusCode.Failure
85  if not self.evtStore.record (aux, f'{self.trackParticleName}Aux.', False):
86  return StatusCode.Failure
87 
88  return StatusCode.Success
89 
90 
91 def CSV_InDetImporterCfg(flags, indir, trackParticleName):
92  from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
93  from OutputStreamAthenaPool.OutputStreamConfig import addToESD, addToAOD
94 
96 
97  algo = CSV_InDetImporterAlg("CSV_InDetImporter")
98  algo.indir = indir
99  if trackParticleName:
100  algo.trackParticleName = trackParticleName
101  output = [f'xAOD::TrackParticleContainer#{trackParticleName}', f'xAOD::TrackParticleAuxContainer#{trackParticleName}Aux.']
102  algo.ExtraOutput = output[:1]
103  ca.merge(addToESD(flags, output))
104  ca.merge(addToAOD(flags, output))
105 
106  ca.addEventAlgo(algo)
107  return ca
108 
109 
110 if __name__ == '__main__':
111  from AthenaConfiguration.AllConfigFlags import initConfigFlags
112  from AthenaConfiguration.MainServicesConfig import MainServicesCfg
113  flags = initConfigFlags()
114  flags.addFlag('CSVInputDir','testdir')
115  flags.addFlag("TrackParticlesName",'NewTP')
116  flags.Exec.MaxEvents=2
117  flags.fillFromArgs()
118  flags.Output.AODFileName="outAOD.pool.root"
119  flags.lock()
120 
121  acc=MainServicesCfg(flags)
122  # if need to read POOL file
123  from AthenaPoolCnvSvc.PoolReadConfig import PoolReadCfg
124  acc.merge(PoolReadCfg(flags))
125 
126  acc.merge(CSV_InDetImporterCfg(flags, indir=flags.CSVInputDir, trackParticleName=flags.TrackParticlesName))
127 
128  acc.printConfig(withDetails=True)
129  # either
130  status = acc.run()
131  if status.isFailure():
132  import sys
133  sys.exit(-1)
python.PyKernel.retrieve
def retrieve(aClass, aKey=None)
Definition: PyKernel.py:110
python.JetAnalysisCommon.ComponentAccumulator
ComponentAccumulator
Definition: JetAnalysisCommon.py:302
CSV_InDetImporter.getCSVFilename
def getCSVFilename(outputDir, container, eventNumber)
Definition: CSV_InDetImporter.py:10
CSV_InDetImporter.CSV_InDetImporterAlg
Definition: CSV_InDetImporter.py:13
CSV_InDetImporter.CSV_InDetImporterAlg.execute
def execute(self)
Definition: CSV_InDetImporter.py:38
python.MainServicesConfig.MainServicesCfg
def MainServicesCfg(flags, LoopMgr='AthenaEventLoopMgr')
Definition: MainServicesConfig.py:260
CSV_InDetImporter.CSV_InDetImporterAlg.readTrackParticle
def readTrackParticle(self)
Definition: CSV_InDetImporter.py:49
python.OutputStreamConfig.addToESD
def addToESD(flags, itemOrList, **kwargs)
Definition: OutputStreamConfig.py:127
CSV_InDetImporter.CSV_InDetImporterAlg.initialize
def initialize(self)
Definition: CSV_InDetImporter.py:28
CSV_InDetImporter.CSV_InDetImporterCfg
def CSV_InDetImporterCfg(flags, indir, trackParticleName)
Definition: CSV_InDetImporter.py:91
CSV_InDetImporter.CSV_InDetImporterAlg.__init__
def __init__(self, name)
Definition: CSV_InDetImporter.py:22
Trk::open
@ open
Definition: BinningType.h:40
python.AllConfigFlags.initConfigFlags
def initConfigFlags()
Definition: AllConfigFlags.py:19
python.OutputStreamConfig.addToAOD
def addToAOD(flags, itemOrList, **kwargs)
Definition: OutputStreamConfig.py:142
CSV_InDetImporter.CSV_InDetImporterAlg.getEventNumber
def getEventNumber(self)
Definition: CSV_InDetImporter.py:45
CSV_InDetImporter.CSV_InDetImporterAlg.indir
indir
Definition: CSV_InDetImporter.py:24
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:798
python.PoolReadConfig.PoolReadCfg
def PoolReadCfg(flags)
Definition: PoolReadConfig.py:69
error
Definition: IImpactPoint3dEstimator.h:70
readCCLHist.float
float
Definition: readCCLHist.py:83
CSV_InDetImporter.CSV_InDetImporterAlg.trackParticleName
trackParticleName
Definition: CSV_InDetImporter.py:25