ATLAS Offline Software
DumpGeoConfig.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
2 
3 #----------------------------------------------------------------
4 # Author: Riccardo Maria BIANCHI <riccardo.maria.bianchi@cern.ch>
5 # Initial version: Feb 2024
6 #----------------------------------------------------------------
7 
8 from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
9 from AthenaConfiguration.ComponentFactory import CompFactory
10 #from AthenaConfiguration.Enums import Format
11 
12 
13 def configureGeometry(flags, cfg):
14 
15  # Beam pipe
16  if flags.Detector.GeometryBpipe:
17  from BeamPipeGeoModel.BeamPipeGMConfig import BeamPipeGeometryCfg
18  cfg.merge(BeamPipeGeometryCfg(flags))
19 
20  # Inner Detectors
21  if flags.Detector.GeometryPixel:
22  from PixelGeoModel.PixelGeoModelConfig import PixelReadoutGeometryCfg
23  cfg.merge(PixelReadoutGeometryCfg(flags))
24  # TODO: do we need to set this separately?
25  # if flags.Detector.GeometryBCM:
26 
27  if flags.Detector.GeometrySCT:
28  from SCT_GeoModel.SCT_GeoModelConfig import SCT_ReadoutGeometryCfg
29  cfg.merge(SCT_ReadoutGeometryCfg(flags))
30 
31  if flags.Detector.GeometryTRT:
32  from TRT_GeoModel.TRT_GeoModelConfig import TRT_ReadoutGeometryCfg
33  cfg.merge(TRT_ReadoutGeometryCfg(flags))
34 
35  # InDetServMat
36  # Trigger the build of the InDetServMat geometry
37  # if any ID subsystems have been enabled
38  if flags.Detector.GeometryID:
39  from InDetServMatGeoModel.InDetServMatGeoModelConfig import (
40  InDetServiceMaterialCfg)
41  cfg.merge(InDetServiceMaterialCfg(flags))
42 
43  # Calorimeters
44  if flags.Detector.GeometryLAr:
45  from LArGeoAlgsNV.LArGMConfig import LArGMCfg
46  cfg.merge(LArGMCfg(flags))
47 
48  if flags.Detector.GeometryTile:
49  from TileGeoModel.TileGMConfig import TileGMCfg
50  #flags.Tile.forceFullGeometry = True
51  cfg.merge(TileGMCfg(flags))
52  # We must set the "FULL" geometry explicitely, otherwise the "RECO" version will be used by default,
53  # which is almost 'empty' (just the first level of child volumes is created for the "RECO" geo).
54  cfg.getService("GeoModelSvc").DetectorTools["TileDetectorTool"].GeometryConfig="FULL"
55  # TODO: do we need to set this separately?
56  # if flags.Detector.GeometryMBTS:
57 
58  # Muon spectrometer
59  if flags.Detector.GeometryMuon:
60  from MuonConfig.MuonGeometryConfig import MuonGeoModelCfg
61  cfg.merge(MuonGeoModelCfg(flags))
62 
63  # HGTD (defined only for Run4 geometry tags)
64  if flags.Detector.GeometryHGTD:
65  #set up geometry
66  if flags.HGTD.Geometry.useGeoModelXml:
67  from HGTD_GeoModelXml.HGTD_GeoModelConfig import HGTD_SimulationGeometryCfg
68  else:
69  from HGTD_GeoModel.HGTD_GeoModelConfig import HGTD_SimulationGeometryCfg
70  cfg.merge(HGTD_SimulationGeometryCfg(flags))
71 
72  # ITk (defined only for Run4 geometry tags)
73  if flags.Detector.GeometryITkPixel:
74  from PixelGeoModelXml.ITkPixelGeoModelConfig import ITkPixelReadoutGeometryCfg
75  cfg.merge(ITkPixelReadoutGeometryCfg(flags))
76  if flags.Detector.GeometryITkStrip:
77  from StripGeoModelXml.ITkStripGeoModelConfig import ITkStripReadoutGeometryCfg
78  cfg.merge(ITkStripReadoutGeometryCfg(flags))
79  # TODO: do we need to set those separately?
80  # if flags.Detector.GeometryBCMPrime:
81  # if flags.Detector.GeometryPLR:
82 
83  # Cavern (disabled by default)
84  if flags.Detector.GeometryCavern:
85  from AtlasGeoModel.CavernGMConfig import CavernGeometryCfg
86  cfg.merge(CavernGeometryCfg(flags))
87 
88  # Forward detectors (disabled by default)
89  if flags.Detector.GeometryLucid or flags.Detector.GeometryALFA or flags.Detector.GeometryAFP or flags.Detector.GeometryFwdRegion :
90  from AtlasGeoModel.ForDetGeoModelConfig import ForDetGeometryCfg
91  cfg.merge(ForDetGeometryCfg(flags))
92  if flags.Detector.GeometryZDC:
93  from ZDC_GeoM.ZdcGeoModelConfig import ZDC_DetToolCfg
94  cfg.merge(ZDC_DetToolCfg(flags))
95 
96  # Temporary 'hack':
97  # Replace EllipticTube with Box,
98  # to bypass a crash due to lack of support
99  # for EllipticTube in GeoModelIO
100  # See: https://its.cern.ch/jira/browse/ATLASSIM-7263
101  if "ForwardRegionGeoModelTool" in cfg.getService("GeoModelSvc").DetectorTools:
102  cfg.getService("GeoModelSvc").DetectorTools["ForwardRegionGeoModelTool"].vp1Compatibility=True
103 
104 
106  import os
107 
108  if "AtlasVersion" in os.environ:
109  return os.environ["AtlasVersion"]
110  if "AtlasBaseVersion" in os.environ:
111  return os.environ["AtlasBaseVersion"]
112  return "Unknown"
113 
114 def DumpGeoCfg(flags, name="DumpGeoCA", outFileName="", **kwargs):
115  # This is based on a few old-style configuation files:
116  # JiveXML_RecEx_config.py
117  # JiveXML_jobOptionBase.py
118  result = ComponentAccumulator()
119 
120  #print(dir("args: ", args)) # debug
121 
122 
123  # set diitional Alg's properties
124  # Note: at this point, the user-defined Geo TAG args.detDescr,
125  # if set, has already replaced the default GeoModel.AtlasVersion in 'flags';
126  # so, we can use the latter, directy.
127  _logger.verbose("Using ATLAS/Athena version: %s", getATLASVersion())
128  _logger.verbose("Using GeoModel ATLAS version: %s", flags.GeoModel.AtlasVersion)
129  kwargs.setdefault("AtlasRelease", getATLASVersion())
130  kwargs.setdefault("AtlasVersion", flags.GeoModel.AtlasVersion)
131  kwargs.setdefault("OutSQLiteFileName", outFileName)
132  if args.filterDetManagers:
133  kwargs.setdefault("UserFilterDetManager", args.filterDetManagers.split(","))
134  if args.showTreetopContent:
135  kwargs.setdefault("ShowTreetopContent", True)
136 
137  the_alg = CompFactory.DumpGeo(name="DumpGeoAlg", **kwargs)
138  result.addEventAlgo(the_alg, primary=True)
139  return result
140 
141 
142 if __name__=="__main__":
143  import os, sys
144  # Run with e.g. python -m DumpGeo.DumpGeoConfig --detDescr=<ATLAS-geometry-tag> --filter=[<list of tree tops>]
145 
146  # from AthenaConfiguration.Enums import Format
147  from AthenaCommon.Logging import logging
148  from AthenaCommon.Constants import VERBOSE
149 
150  from AthenaConfiguration.TestDefaults import defaultGeometryTags
151 
152  # ++++ Firstly we setup flags ++++
153  _logger = logging.getLogger('DumpGeo')
154  _logger.setLevel(VERBOSE)
155 
156  from AthenaConfiguration.AllConfigFlags import initConfigFlags
157  flags = initConfigFlags()
158  flags.Exec.MaxEvents = 0
159  # ^ We do not need any events to get the GeoModel tree from the GeoModelSvc.
160  # So, we don't need to run on any events,
161  # and we don't need to trigger any execute() Athena methods either.
162  # So, we set 'EvtMax' to 0 and Athena will skip the 'execute' phase;
163  # only the 'finalize' step will be run after the 'init'.
164  # -- Note:
165  # Also, if we run on events (even on 1 event) and we dump the Pixel
166  # as part of the DetectorManager filter, then we get a crash because
167  # the PixelDetectorManager complains during the 'execute' phase,
168  # because we 'stole' a handle on its TreeTop,
169  # which contains a FullPhysVol and cannot be shared.
170  flags.Concurrency.NumThreads = 0
171  # ^ VP1 will not work with the scheduler, since its condition/data dependencies are not known in advance
172  # More in details: the scheduler needs to know BEFORE the event, what the dependencies of each Alg are.
173  # So for VP1, no dependencies are declared, which means the conditions data is not there.
174  # So when I load tracks, the geometry is missing and it crashes.
175  # Turning off the scheduler (with NumThreads=0) fixes this.
176 
177  parser = flags.getArgumentParser()
178  parser.prog = 'dump-geo'
179  # here we extend the parser with CLI options specific to DumpGeo
180  parser.add_argument("--detDescr", default=defaultGeometryTags.RUN3,
181  help="The ATLAS geometry tag you want to dump (a convenience alias for the Athena flag 'GeoModel.AtlasVersion=TAG')", metavar="TAG")
182  # parser.add_argument("--filterTreeTops", help="Only output the GeoModel Tree Tops specified in the FILTER list; input is a comma-separated list")
183  parser.add_argument("--filterDetManagers", help="Only output the GeoModel Detector Managers specified in the FILTER list; input is a comma-separated list")
184  parser.add_argument("-f", "--forceOverwrite",
185  help="Force to overwrite an existing SQLite output file with the same name, if any", action = 'store_true')
186  parser.add_argument("--showTreetopContent",
187  help="Show the content of the Treetops --- (by default, only the list of Treetops is shown)", action = 'store_true')
188  parser.add_argument("--debugCA", help="Debug the CA configuration: print flags, tools, ... --- mainly, for DumpGeo developers. '1' prints a subset of the CA flags, '2' prints all of them.")
189 
190  args = flags.fillFromArgs(parser=parser)
191 
192  if args.help:
193  # No point doing more here, since we just want to print the help.
194  sys.exit()
195 
196  _logger.verbose("+ About to set flags related to the input")
197 
198  # Empty input is not normal for Athena, so we will need to check
199  # this repeatedly below (the same as with VP1)
200  dumpgeo_empty_input = False
201  # This covers the use case where we launch DumpGeo
202  # without input files; e.g., to check the detector description
203  if (flags.Input.Files == [] or
204  flags.Input.Files == ['_ATHENA_GENERIC_INPUTFILE_NAME_']):
205  from Campaigns.Utils import Campaign
206  from AthenaConfiguration.TestDefaults import defaultGeometryTags
207 
208  dumpgeo_empty_input = True
209  # NB Must set e.g. ConfigFlags.Input.Runparse_args() Number and
210  # ConfigFlags.Input.TimeStamp before calling the
211  # MainServicesCfg to avoid it attempting auto-configuration
212  # from an input file, which is empty in this use case.
213  # If you don't have it, it (and/or other Cfg routines) complains and crashes.
214  # See also:
215  # https://acode-browser1.usatlas.bnl.gov/lxr/source/athena/InnerDetector/InDetConditions/SCT_ConditionsAlgorithms/python/SCT_DCSConditionsTestAlgConfig.py#0023
216  flags.Input.ProjectName = "mc20_13TeV"
217  flags.Input.RunNumbers = [330000]
218  flags.Input.TimeStamps = [1]
219  flags.Input.TypedCollections = []
220 
221  # set default CondDB and Geometry version
222  flags.IOVDb.GlobalTag = "OFLCOND-MC23-SDR-RUN3-02"
223  flags.Input.isMC = True
224  flags.Input.MCCampaign = Campaign.Unknown
225  flags.GeoModel.AtlasVersion = defaultGeometryTags.RUN3
226  _logger.verbose("+ ... Done")
227  _logger.verbose("+ empty input: '%s'" % dumpgeo_empty_input)
228 
229  _logger.verbose("+ detDescr flag: '%s'" % args.detDescr)
230 
231 
232  _logger.verbose("+ About to set the detector flags")
233  # So we can now set up the geometry flags from the input
234  from AthenaConfiguration.DetectorConfigFlags import setupDetectorFlags
235  setupDetectorFlags(flags, None, use_metadata=not dumpgeo_empty_input,
236  toggle_geometry=True, keep_beampipe=True)
237  _logger.verbose("+ ... Done")
238 
239  if args.detDescr:
240  _logger.verbose("+ About to set this detector description tag: '%s'" % args.detDescr)
241  flags.GeoModel.AtlasVersion = args.detDescr
242  _logger.verbose("+ ... Done")
243 
244 
245  # finalize setting flags: lock them.
246  flags.lock()
247 
248 
249 
250  # Handle the user's inputs and create a file name
251  # for the output SQLite, accordingly
252  outFileName = "geometry"
253  filterDetManagers = []
254  # - Put Geometry TAG into the file name
255  # NOTE: at this point, the user-defined Geo TAG args.detDescr,
256  # if set, has already replaced the default TAG in 'flags';
257  # so, we can use the latter, directy.
258  geoTAG = flags.GeoModel.AtlasVersion
259  print("+ DumpGeo -- INFO -- This is the Detector Description geometry TAG you are dumping: '%s'" % geoTAG)
260  outFileName = outFileName + "-" + geoTAG
261  # - Put DetectorManagers' names into the file name,
262  # if the filter has been used by the user
263  if args.filterDetManagers:
264  print("+ DumpGeo -- NOTE -- Your 'GeoModel Detector Manager' filter set: '%s'" % args.filterDetManagers)
265  filterDetManagers = args.filterDetManagers.split(",")
266  outFileName = outFileName + "-" + "-".join(filterDetManagers)
267  # - Add the final extension to the name of the output SQLite file
268  outFileName = outFileName + ".db"
269 
270  # Overwrite the output SQLite file, if existing
271  if os.path.exists(outFileName):
272  if args.forceOverwrite is True:
273  print("+ DumpGeo -- NOTE -- You chose to overwrite an existing geometry dump file with the same name, if present.")
274  # os.environ["DUMPGEOFORCEOVERWRITE"] = "1" # save to an env var, for later use in GeoModelStandalone/GeoExporter
275  # Check if the file exists before attempting to delete it
276  if os.path.exists(outFileName):
277  os.remove(outFileName)
278  print(f"The file {outFileName} has been deleted.")
279  else:
280  print(f"The file {outFileName} does not exist. So, it was not needed to 'force-delete' it. Continuing...")
281  else:
282  print(f"\nDumpGeo -- ERROR! The ouput file '{outFileName}' exists already!\nPlease move or remove it, or use the 'force' option: '-f' or '--forceOverWrite'.\n\n")
283  sys.exit()
284  #raise ValueError("The output file exists already!")
285 
286 
287 
288  # ++++ Now we setup the actual configuration ++++
289  _logger.verbose("+ Setup main services")
290  from AthenaConfiguration.MainServicesConfig import MainServicesCfg
291  cfg = MainServicesCfg(flags)
292  _logger.verbose("+ ...Done")
293 
294  _logger.verbose("+ About to setup geometry")
295  configureGeometry(flags,cfg)
296  _logger.verbose("+ ...Done")
297 
298  # debug messages
299  if args.debugCA:
300  debugCAlevel = int(args.debugCA)
301  if debugCAlevel >= 1:
302  _logger.verbose("Debug --- printing flags...")
303  print("\nflags:", flags)
304  for fl in flags:
305  print("fl:", fl)
306  print("\nflags.Tile:", flags.Tile)
307  for fl in flags.Tile:
308  print("fl.Tile:", fl)
309  print(dir(cfg))
310  print("cfg._privateTools: ", cfg._privateTools)
311  print("cfg._publicTools: ", cfg._publicTools)
312  if debugCAlevel >= 2:
313  flags.dump()
314  flags._loadDynaFlags('GeoModel')
315  flags._loadDynaFlags('Detector')
316  flags.dump('Detector.(Geometry|Enable)', True)
317  if debugCAlevel >= 1:
318  _logger.verbose("We're in a debugCA session, flags have been printed out, now exiting...")
319  sys.exit()
320 
321 
322  # configure DumpGeo
323  cfg.merge(DumpGeoCfg(flags, args, outFileName=outFileName))
324  cfg.run()
325 
python.JetAnalysisCommon.ComponentAccumulator
ComponentAccumulator
Definition: JetAnalysisCommon.py:302
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
BeamPipeGMConfig.BeamPipeGeometryCfg
def BeamPipeGeometryCfg(flags)
Definition: BeamPipeGMConfig.py:5
TRT_GeoModelConfig.TRT_ReadoutGeometryCfg
def TRT_ReadoutGeometryCfg(flags)
Definition: TRT_GeoModelConfig.py:59
python.InDetServMatGeoModelConfig.InDetServiceMaterialCfg
def InDetServiceMaterialCfg(flags)
Definition: InDetServMatGeoModelConfig.py:8
ITkStripGeoModelConfig.ITkStripReadoutGeometryCfg
def ITkStripReadoutGeometryCfg(flags)
Definition: ITkStripGeoModelConfig.py:39
python.ForDetGeoModelConfig.ForDetGeometryCfg
def ForDetGeometryCfg(flags)
Definition: ForDetGeoModelConfig.py:33
ITkPixelGeoModelConfig.ITkPixelReadoutGeometryCfg
def ITkPixelReadoutGeometryCfg(flags)
Definition: ITkPixelGeoModelConfig.py:39
DumpGeoConfig.configureGeometry
def configureGeometry(flags, cfg)
Definition: DumpGeoConfig.py:13
ZdcGeoModelConfig.ZDC_DetToolCfg
def ZDC_DetToolCfg(flags)
Definition: ZdcGeoModelConfig.py:4
SCT_GeoModelConfig.SCT_ReadoutGeometryCfg
def SCT_ReadoutGeometryCfg(flags)
Definition: SCT_GeoModelConfig.py:51
python.MainServicesConfig.MainServicesCfg
def MainServicesCfg(flags, LoopMgr='AthenaEventLoopMgr')
Definition: MainServicesConfig.py:260
Constants
some useful constants -------------------------------------------------—
LArGMConfig.LArGMCfg
def LArGMCfg(flags)
Definition: LArGMConfig.py:8
beamspotman.dir
string dir
Definition: beamspotman.py:623
print
void print(char *figname, TCanvas *c1)
Definition: TRTCalib_StrawStatusPlots.cxx:25
PixelGeoModelConfig.PixelReadoutGeometryCfg
def PixelReadoutGeometryCfg(flags)
Definition: PixelGeoModelConfig.py:52
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.DetectorConfigFlags.setupDetectorFlags
def setupDetectorFlags(flags, custom_list=None, use_metadata=False, toggle_geometry=False, validate_only=False, keep_beampipe=False)
Definition: DetectorConfigFlags.py:289
DumpGeoConfig.getATLASVersion
def getATLASVersion()
Definition: DumpGeoConfig.py:105
python.CavernGMConfig.CavernGeometryCfg
def CavernGeometryCfg(flags)
Definition: CavernGMConfig.py:6
python.MuonGeometryConfig.MuonGeoModelCfg
def MuonGeoModelCfg(flags)
Definition: MuonGeometryConfig.py:28
python.AllConfigFlags.initConfigFlags
def initConfigFlags()
Definition: AllConfigFlags.py:19
DumpGeoConfig.DumpGeoCfg
def DumpGeoCfg(flags, name="DumpGeoCA", outFileName="", **kwargs)
Definition: DumpGeoConfig.py:114
HGTD_GeoModelConfig.HGTD_SimulationGeometryCfg
def HGTD_SimulationGeometryCfg(flags)
Definition: python/HGTD_GeoModelConfig.py:17
TileGMConfig.TileGMCfg
def TileGMCfg(flags)
Definition: TileGMConfig.py:7