ATLAS Offline Software
StripDefectsEmulatorConfig.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
3 """
4  Emulating strip defects by dropping elements from the RDO input container
5 """
6 from AthenaConfiguration.AllConfigFlags import initConfigFlags
7 from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
8 from AthenaConfiguration.ComponentFactory import CompFactory
9 
10 from AthenaCommon.Constants import INFO
11 
12 def ordered_pairs(a_list) :
13  """
14  Return True if every two elements in a_list form a pair whose two elements are
15  in ascending order. The element pairs themselves may have an arbitrary order.
16  """
17  for i in range(0,len(a_list),2) :
18  if a_list[i]>a_list[i+1] :
19  return False
20  return True
21 
22 def makeCornerDefectParam(probability=1e-1,
23  min_rx=0.,
24  max_rx=4e-3,
25  min_ry=0.,
26  max_ry=4e-3,
27  min_sagitta=0.,
28  max_sagitta=2e-3) :
29  """
30  Convenience method to create a parameter set for module corner defects.
31  The corner defects have a circular shape and intersect the sensor edges at certain
32  points in x and y direction. The line between these two intersection points forms
33  a sagitta of the circle.
34  probability: Probability of a module to have one or more corner defects.
35  min_rx: minimum position from the corner in local x-direction of possible intersection points.
36  max_rx: maximum position from the corner in local x-direction of possible intersection points.
37  min_ry: minimum position from the corner in local y-direction of possible intersection points.
38  max_ry: maximum position from the corner in local x-direction of possible intersection points.
39  min_sagitta: minimum size of the sagitta (upper limit of circle radius)
40  max_sagitta: maximum size of the sagitta (lower limit of circle radius)
41  """
42  assert min_rx<max_rx
43  assert min_ry<max_ry
44  assert min_sagitta<max_sagitta
45  return [probability,
46  min_rx, max_rx-min_rx,
47  min_ry, max_ry-min_ry,
48  min_sagitta, max_sagitta-min_sagitta]
49 
50 def moduleDefect(bec=[-2,2],
51  layer=[0,8],
52  eta_range=[-99,99],
53  phi_range=[-99,99],
54  columns_or_strips=[0,2000],
55  column_or_strip_length=[0,1000000],
56  side_range=[0,1],
57  all_rows=True,
58  probability=[1e-2],
59  fractionsOfNDefects=[],
60  noiseProbability=None,
61  noiseShape=[],
62  cornerDefectParam=None,
63  cornerDefectNCornerFractions=None,
64  ) :
65  '''
66  Convenience function to create parameters for strip or pixel defects emulation conditions data
67  bec: range to select the bec identifier part (range is inclusive)
68  layer: range to select the layer/disc identifier part (range is inclusive)
69  eta_range: range to select the eta index identifier part (range is inclusive)
70  phi_range: range to select the phi index identifier part (range is inclusive)
71  columns_or_strips: match only modules with number of columns or strips in this range (range is inclusive)
72  column_or_strip_length: match the strip lengths in microns (range is inclusive)
73  side_range: to select both sides of a sensor [0,1], to select either side [0,0,1,1]
74  all_rows: to select individal modules (0), or all modules associated to the same physical sensor (1)
75  probabilities: module-defect, strip/pixel defect (for pixel additionally group defect probabilities:
76  at least one core-column defect, at least one defect circuit)
77  fractions: per group defect, fractions to have exactly 1..n group defects under the condition that there is
78  at least one such group defect.
79  noiseProbability: None or probability of a strip (or pixel) to produce a spurious hit.
80  noiseShape: empty list or binned pdf used to compute one random number per spurious hit (time bin for strips, tot for pixel).
81  cornerDefectParam: None or parameters e.g. created with makeCornerDefectParam to create defects at module corners.
82  cornerDefectNCornerFractions: if cornerDefectParam is not None the fractions of 1 to 4 corners to have a defect if the module
83  has such defects.
84  '''
85  # test that the ranges have coorect number of elements and that ranges are ordered
86  assert len(bec)%2==0 and len(bec) >= 2 and ordered_pairs(bec)
87  assert len(layer)%2==0 and len(layer) >= 2 and ordered_pairs(layer)
88  assert len(eta_range)%2==0 and len(eta_range) >= 2 and ordered_pairs(eta_range)
89  assert len(phi_range)%2==0 and len(phi_range) >= 2 and ordered_pairs(phi_range)
90  assert len(side_range)%2==0 and len(side_range) >= 2 and ordered_pairs(side_range)
91  assert len(columns_or_strips)%2==0 and len(columns_or_strips) >= 2 and ordered_pairs(columns_or_strips)
92  assert len(column_or_strip_length)%2==0 and len(column_or_strip_length) >= 2 and ordered_pairs(column_or_strip_length)
93  assert len(fractionsOfNDefects)==0 or len(fractionsOfNDefects)+2==len(probability)
94 
95  assert cornerDefectParam is not None or cornerDefectNCornerFractions is None
96  assert cornerDefectParam is None or cornerDefectNCornerFractions is not None
97 
98  length=[ l for l in set([len(bec),len(layer),len(eta_range),len(phi_range),len(side_range),len(columns_or_strips)]) ]
99  # every range must contain a multiple of the number of elements of every other range
100  for i in range(1,len(length)) :
101  for j in range(0,i) :
102  assert max(length[i],length[j])%min(length[i],length[j])==0
103 
104  module_pattern=[]
105  prob=[]
106  fractions=[]
107  noiseProbList=[]
108  noiseShapeList=[]
109  cornerDefectList=[]
110  cornerDefectCornerFractionList=[]
111  if noiseProbability is not None and noiseProbability>0. :
112  # ensure that the the noise shape integral is 1.
113  shape_sum = sum(noiseShape)
114  noiseShape = [ elm/shape_sum for elm in noiseShape ]
115  else :
116  noiseProbability=None
117 
118  for i in range(0,max(length),2) :
119  module_pattern+=[ [bec[i%len(bec)], bec[(i+1)%len(bec)],
120  layer[i%len(layer)], layer[(i+1)%len(layer)],
121  eta_range[i%len(eta_range)], eta_range[(i+1)%len(eta_range)],
122  phi_range[i%len(phi_range)], phi_range[(i+1)%len(phi_range)],
123  columns_or_strips[i%len(columns_or_strips)], columns_or_strips[(i+1)%len(columns_or_strips)],
124  column_or_strip_length[i%len(column_or_strip_length)], column_or_strip_length[(i+1)%len(column_or_strip_length)],
125  side_range[i%len(side_range)], side_range[(i+1)%len(side_range)],
126  1 if all_rows else 0] ]
127  prob += [ probability ]
128  fractions += [ [fraction for per_pattern in fractionsOfNDefects for fraction in per_pattern + [-1] ] ]
129  if noiseProbability is not None:
130  noiseProbList+=[noiseProbability]
131  noiseShapeList+=[noiseShape]
132  if cornerDefectParam is not None:
133  cornerDefectList+=[ cornerDefectParam ]
134  cornerDefectCornerFractionList+=[ cornerDefectNCornerFractions ]
135 
136  return module_pattern, prob, fractions, noiseProbList, noiseShapeList, cornerDefectList, cornerDefectCornerFractionList
137 
138 def combineModuleDefects( defects ) :
139  '''
140  Convenience function to combine a list of outputs of calls of moduleDefect, to produce lists to
141  set the ModulePatterns, DefectProbabilities, and NDefectFractionsPerPattern etc. properties of the
142  pixel or strip DefectsEmulatorCondAlg.
143  '''
144  result=[]
145  for i in range(0,len(defects[0])) :
146  result.append( [ elm for sublist in defects for elm in sublist[i] ] )
147  return result
148 
149 def StripRDORemappingCfg(flags, InputKey="StripRDOs") :
150  """
151  Remapping service to rename the input strip RDO collection
152  """
153  acc = ComponentAccumulator()
154 
155  from SGComps.AddressRemappingConfig import AddressRemappingCfg
156  renames = [ '%s#%s->%s' % ('SCT_RDO_Container', InputKey, f"{InputKey}_ORIG") ]
157  acc.merge(AddressRemappingCfg( renameMaps = renames ))
158  return acc
159 
161  """
162  Remapping service to rename the input ITk strip RDO collection
163  """
164  return StripRDORemappingCfg(flags,"ITkStripRDOs")
165 
166 def DefectsHistSvcCfg(flags, HistogramGroup: str="StripDefects", FileName: str='strip_defects.root') -> ComponentAccumulator:
167  """
168  THistSvc to histogram some properties of emulated defects.
169  """
170  acc = ComponentAccumulator()
171  if HistogramGroup is not None and len(HistogramGroup) > 0 and FileName is not None and len(FileName) > 0 :
172  histSvc = CompFactory.THistSvc(Output = [f"{HistogramGroup} DATAFILE='{FileName}', OPT='RECREATE'"] )
173  acc.addService(histSvc)
174  return acc
175 
176 def ITkDefectsHistSvcCfg(flags, HistogramGroup="ITkStripDefects") -> ComponentAccumulator:
177  return DefectsHistSvcCfg(flags,HistogramGroup)
178 
179 
181  name: str = "StripDefectsEmulatorCondAlg",
182  **kwargs: dict) -> ComponentAccumulator:
183  """
184  Schedule conditions algorithm to create emulated strip defect conditions data
185  """
186  acc = ComponentAccumulator()
187  kwargs.setdefault("ModulePatterns", [[-2,2,0,99,-99,99,-99,99,0,9999,0,1,0]]) # ranges: barrel/ec, all layers, all eta, all phi, all column counts,
188  # all sides, don't auto-match connected rows
189  kwargs.setdefault("DefectProbabilities", [[0.,1.e-4]]) # only strip defects
190  kwargs.setdefault("DetEleCollKey", "StripDetectorElementCollection")
191  kwargs.setdefault("WriteKey", "StripEmulatedDefects")
192  kwargs.setdefault("IDName","SCT_ID")
193  kwargs.setdefault("HistogramGroupName","") # disable histogramming; enable: e.g. /StripDefects/EmulatedDefects/
194 
195  kwargs.setdefault("RngPerDefectType",False) # If True use one RNG per defect type (module, chip-defects, core-column, pixel-defects, corner-defects)
196  kwargs.setdefault("DefectsInputFiles",[]) # If not empty read defects from input files and merge defects (root RNTuple/json; extension: .root .json")
197  kwargs.setdefault("DefectsOutputFile","") # If not empty write defects to a output file (root RNTuple/json; (extension: .root .json")
198  if "DefectsOutputFile" in kwargs and kwargs["DefectsOutputFile"] is None :
199  kwargs["DefectsOutputFile"]=""
200 
201  acc.addCondAlgo(CompFactory.InDet.StripDefectsEmulatorCondAlg(name,**kwargs))
202  return acc
203 
205  name: str = "ITkStripDefectsEmulatorCondAlg",
206  **kwargs: dict) -> ComponentAccumulator:
207  """
208  Schedule conditions algorithm to create emulated ITk strip defect conditions data
209  """
210  kwargs.setdefault("ModulePatterns", [[-2,2,0,99,-99,99,-99,99,0,9999,0,1,0]]) # ranges: barrel/ec, all layers, all eta, all phi,
211  # all sides, don't auto-match connected rows
212  kwargs.setdefault("DefectProbabilities", [[0.,1.e-4]]) # only strip defects
213  kwargs.setdefault("DetEleCollKey", "ITkStripDetectorElementCollection")
214  kwargs.setdefault("IDName","SCT_ID")
215  kwargs.setdefault("WriteKey", "ITkStripEmulatedDefects")
216 
217  kwargs.setdefault("RngPerDefectType",False) # If True use one RNG per defect type (module, chip-defects, core-column, pixel-defects, corner-defects)
218  kwargs.setdefault("DefectsInputFiles",[]) # If not empty read defects from input files and merge defects (root RNTuple/json; extension: .root .json")
219  kwargs.setdefault("DefectsOutputFile","") # If not empty write defects to a output file (root RNTuple/json; (extension: .root .json")
220  if "DefectsOutputFile" in kwargs and kwargs["DefectsOutputFile"] is None :
221  kwargs["DefectsOutputFile"]=""
222 
223  return StripDefectsEmulatorCondAlgCfg(flags,name,**kwargs)
224 
225 
227  name: str = "ITkStripDefectsEmulatorAlg",
228  **kwargs: dict) -> ComponentAccumulator:
229  """
230  Schedule algorithm to emulate strip defects by dropping RDOs overlapping with emulated
231  defects conditions data.
232  """
233  acc = ComponentAccumulator()
234 
235  if "InputKey" not in kwargs :
236  # rename original RDO collection
237  acc.merge(StripRDORemappingCfg(flags))
238  kwargs.setdefault("InputKey","StripRDOs_ORIG")
239 
240  if "EmulatedDefectsKey" not in kwargs :
241  # create defects conditions data
242  acc.merge( ITkStripDefectsEmulatorCondAlgCfg(flags))
243  kwargs.setdefault("EmulatedDefectsKey", "StripEmulatedDefects")
244  kwargs.setdefault("OutputKey","StripRDOs")
245  kwargs.setdefault("HistogramGroupName","") # disable histogramming, enable e.g. /StripDefects/RejectedRDOs/
246 
247  acc.addEventAlgo(CompFactory.InDet.StripDefectsEmulatorAlg(name,**kwargs))
248  return acc
249 
251  name: str = "ITkStripDefectsEmulatorAlg",
252  **kwargs: dict) -> ComponentAccumulator:
253  """
254  Schedule algorithm to emulate ITk strip defects by dropping RDOs overlapping with emulated
255  defects conditions data.
256  """
257  acc = ComponentAccumulator()
258  if "InputKey" not in kwargs :
259  # rename original RDO collection
260  acc.merge(ITkStripRDORemappingCfg(flags))
261  kwargs.setdefault("InputKey","ITkStripRDOs_ORIG")
262 
263  if "EmulatedDefectsKey" not in kwargs :
264  # create defects conditions data
265  acc.merge( ITkStripDefectsEmulatorCondAlgCfg(flags))
266  kwargs.setdefault("EmulatedDefectsKey", "ITkStripEmulatedDefects")
267  kwargs.setdefault("OutputKey","ITkStripRDOs")
268 
269  kwargs.setdefault("HistogramGroupName","") # disable histogramming, enable e.g. /StripDefects/RejectedRDOs/
270 
271  acc.addEventAlgo(CompFactory.InDet.StripDefectsEmulatorAlg(name,**kwargs))
272  return acc
273 
275  name: str = "ITkStripDefectsEmulatorToDetectorElementStatusCondAlgCfg",
276  **kwargs: dict) -> ComponentAccumulator:
277  acc = ComponentAccumulator()
278  kwargs.setdefault("EmulatedDefectsKey","ITkStripEmulatedDefects")
279  kwargs.setdefault("WriteKey","ITkStripDetectorElementStatusFromEmulatedDefects")
280  acc.addCondAlgo(CompFactory.InDet.StripEmulatedDefectsToDetectorElementStatusCondAlg(name,**kwargs))
281  return acc
282 
283 
284 if __name__ == "__main__":
285  #
286  # Test ITk strip defect emulation
287  #
288  flags = initConfigFlags()
289 
290  from AthenaConfiguration.Enums import ProductionStep
291  flags.Common.ProductionStep = ProductionStep.Simulation
292  from AthenaConfiguration.TestDefaults import defaultGeometryTags, defaultConditionsTags
293  flags.GeoModel.AtlasVersion = defaultGeometryTags.RUN4
294  flags.IOVDb.GlobalTag = defaultConditionsTags.RUN4_MC
295  flags.GeoModel.Align.Dynamic = False
296  flags.Input.Files = ['/cvmfs/atlas-nightlies.cern.ch/repo/data/data-art/PhaseIIUpgrade/RDO/ATLAS-P2-RUN4-03-00-00/mc21_14TeV.601229.PhPy8EG_A14_ttbar_hdamp258p75_SingleLep.recon.RDO.e8481_s4149_r14700/RDO.33629020._000047.pool.root.1']
297 
298  flags.Detector.GeometryITkStrip = True
299  flags.Detector.GeometryITkStrip = True
300  flags.Detector.GeometryBpipe = True
301  flags.Detector.GeometryCalo = False
302 
303  flags.Concurrency.NumThreads = 8
304  flags.Concurrency.NumConcurrentEvents = 8
305 
306  flags.Exec.MaxEvents = 10
307 
308  flags.lock()
309  flags.dump()
310 
311  from AthenaConfiguration.MainServicesConfig import MainServicesCfg
312  acc = MainServicesCfg( flags )
313  from AthenaPoolCnvSvc.PoolReadConfig import PoolReadCfg
314  acc.merge(PoolReadCfg(flags))
315 
316  # Need geometry
317  from ActsConfig.ActsGeometryConfig import ActsTrackingGeometrySvcCfg
318  acc.merge( ActsTrackingGeometrySvcCfg(flags,
319  OutputLevel=INFO,
320  RunConsistencyChecks=False,
321  ObjDebugOutput=False))
322 
323  from SCT_ConditionsAlgorithms.ITkStripConditionsAlgorithmsConfig import ITkStripDetectorElementStatusCondAlgNoByteStreamErrorsCfg
325 
326  # ITk strip defect configuration defined in post include
327  from StripDefectsEmulatorPostInclude import emulateITkStripDefects
328  emulateITkStripDefects(flags,acc)
329 
330  acc.printConfig(withDetails=True, summariseProps=True,printDefaults=True)
331  sc = acc.run()
332 
333  if sc.isFailure():
334  import sys
335  sys.exit(1)
StripDefectsEmulatorConfig.moduleDefect
def moduleDefect(bec=[-2, 2], layer=[0, 8], eta_range=[-99, 99], phi_range=[-99, 99], columns_or_strips=[0, 2000], column_or_strip_length=[0, 1000000], side_range=[0, 1], all_rows=True, probability=[1e-2], fractionsOfNDefects=[], noiseProbability=None, noiseShape=[], cornerDefectParam=None, cornerDefectNCornerFractions=None)
Definition: StripDefectsEmulatorConfig.py:50
ActsGeometryConfig.ActsTrackingGeometrySvcCfg
ComponentAccumulator ActsTrackingGeometrySvcCfg(flags, str name="ActsTrackingGeometrySvc", **kwargs)
Definition: ActsGeometryConfig.py:6
AddressRemappingConfig.AddressRemappingCfg
def AddressRemappingCfg(renameMaps=[], overwriteMaps=[])
Definition: AddressRemappingConfig.py:10
StripDefectsEmulatorConfig.StripDefectsEmulatorCondAlgCfg
ComponentAccumulator StripDefectsEmulatorCondAlgCfg(flags, str name="StripDefectsEmulatorCondAlg", **dict kwargs)
Definition: StripDefectsEmulatorConfig.py:180
StripDefectsEmulatorConfig.DefectsHistSvcCfg
ComponentAccumulator DefectsHistSvcCfg(flags, str HistogramGroup="StripDefects", str FileName='strip_defects.root')
Definition: StripDefectsEmulatorConfig.py:166
python.JetAnalysisCommon.ComponentAccumulator
ComponentAccumulator
Definition: JetAnalysisCommon.py:302
max
constexpr double max()
Definition: ap_fixedTest.cxx:33
min
constexpr double min()
Definition: ap_fixedTest.cxx:26
StripDefectsEmulatorConfig.ITkStripRDORemappingCfg
def ITkStripRDORemappingCfg(flags)
Definition: StripDefectsEmulatorConfig.py:160
StripDefectsEmulatorConfig.makeCornerDefectParam
def makeCornerDefectParam(probability=1e-1, min_rx=0., max_rx=4e-3, min_ry=0., max_ry=4e-3, min_sagitta=0., max_sagitta=2e-3)
Definition: StripDefectsEmulatorConfig.py:22
StripDefectsEmulatorConfig.ITkDefectsHistSvcCfg
ComponentAccumulator ITkDefectsHistSvcCfg(flags, HistogramGroup="ITkStripDefects")
Definition: StripDefectsEmulatorConfig.py:176
convertTimingResiduals.sum
sum
Definition: convertTimingResiduals.py:55
StripDefectsEmulatorConfig.StripDefectsEmulatorAlgCfg
ComponentAccumulator StripDefectsEmulatorAlgCfg(flags, str name="ITkStripDefectsEmulatorAlg", **dict kwargs)
Definition: StripDefectsEmulatorConfig.py:226
StripDefectsEmulatorConfig.combineModuleDefects
def combineModuleDefects(defects)
Definition: StripDefectsEmulatorConfig.py:138
StripDefectsEmulatorConfig.ITkStripDefectsEmulatorCondAlgCfg
ComponentAccumulator ITkStripDefectsEmulatorCondAlgCfg(flags, str name="ITkStripDefectsEmulatorCondAlg", **dict kwargs)
Definition: StripDefectsEmulatorConfig.py:204
python.MainServicesConfig.MainServicesCfg
def MainServicesCfg(flags, LoopMgr='AthenaEventLoopMgr')
Definition: MainServicesConfig.py:312
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:194
Constants
some useful constants -------------------------------------------------—
StripDefectsEmulatorConfig.ITkStripDefectsEmulatorToDetectorElementStatusCondAlgCfg
ComponentAccumulator ITkStripDefectsEmulatorToDetectorElementStatusCondAlgCfg(flags, str name="ITkStripDefectsEmulatorToDetectorElementStatusCondAlgCfg", **dict kwargs)
Definition: StripDefectsEmulatorConfig.py:274
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
StripDefectsEmulatorPostInclude.emulateITkStripDefects
def emulateITkStripDefects(flags, cfg, float StripDefectProb=1e-2, float ModuleDefectProb=1e-2, float NoiseProb=0., int MaxRandomPositionAttempts=10, RngPerDefectType=False, DefectsInputFiles=[], DefectsOutputFile=None, bool FillHistogramsPerPattern=True, bool FillEtaPhiHistogramsPerPattern=True, str HistogramGroupName="ITkStripDefects", str HistogramFileName=None, PropagateDefectsToStatus=True)
Definition: StripDefectsEmulatorPostInclude.py:32
StripDefectsEmulatorConfig.StripRDORemappingCfg
def StripRDORemappingCfg(flags, InputKey="StripRDOs")
Definition: StripDefectsEmulatorConfig.py:149
python.AllConfigFlags.initConfigFlags
def initConfigFlags()
Definition: AllConfigFlags.py:19
python.ITkStripConditionsAlgorithmsConfig.ITkStripDetectorElementStatusCondAlgNoByteStreamErrorsCfg
def ITkStripDetectorElementStatusCondAlgNoByteStreamErrorsCfg(flags, name="ITkStripDetectorElementStatusCondAlgNoByteStreamErrors", **kwargs)
Definition: ITkStripConditionsAlgorithmsConfig.py:78
python.PoolReadConfig.PoolReadCfg
def PoolReadCfg(flags)
Definition: PoolReadConfig.py:71
StripDefectsEmulatorConfig.ITkStripDefectsEmulatorAlgCfg
ComponentAccumulator ITkStripDefectsEmulatorAlgCfg(flags, str name="ITkStripDefectsEmulatorAlg", **dict kwargs)
Definition: StripDefectsEmulatorConfig.py:250
StripDefectsEmulatorConfig.ordered_pairs
def ordered_pairs(a_list)
Definition: StripDefectsEmulatorConfig.py:12