CMS 3D CMS Logo

generate2023Geometry.py
Go to the documentation of this file.
1 from __future__ import print_function
2 from optparse import OptionParser
3 import sys, os, operator
4 from pprint import pprint
5 import filecmp
6 
8 
9 # define global
10 detectorVersionDefault = 999
11 
12 def generateGeom(detectorTuple, options):
13  doTest = bool(options.doTest)
14 
15  detectorVersion = "D"+str(options.detectorVersionManual)
16  # reverse dict search if overall D# specified
17  if options.v_detector>0:
18  detectorVersion = "D"+str(options.v_detector)
19  if detectorVersion in detectorVersionDict.values():
20  detectorTuple = detectorVersionDict.keys()[detectorVersionDict.values().index(detectorVersion)]
21  else:
22  print("Unknown detector "+detectorVersion)
23  sys.exit(1)
24  elif detectorTuple in detectorVersionDict.keys():
25  detectorVersion = detectorVersionDict[detectorTuple]
26  else:
27  if not doTest: print("Detector "+str(detectorTuple)+" not found in dictionary, using "+("default" if options.detectorVersionManual==detectorVersionDefault else "provided")+" version number "+str(detectorVersion))
28 
29  # check for deprecation
30  if detectorVersion in deprecatedDets:
31  print("Error: "+detectorVersion+" is deprecated and cannot be used.")
32  sys.exit(1)
33  for subdet in detectorTuple:
34  if subdet in deprecatedSubdets:
35  print("Error: "+subdet+" is deprecated and cannot be used.")
36  sys.exit(1)
37 
38  # create output files
39  xmlName = "cmsExtendedGeometry2023"+detectorVersion+"XML_cfi.py"
40  simName = "GeometryExtended2023"+detectorVersion+"_cff.py"
41  recoName = "GeometryExtended2023"+detectorVersion+"Reco_cff.py"
42 
43  # check directories
44  CMSSWBASE = os.getenv("CMSSW_BASE")
45  CMSSWRELBASE = os.getenv("CMSSW_RELEASE_BASE")
46  if CMSSWBASE is None: CMSSWBASE = ""
47  xmlDir = os.path.join(CMSSWBASE,"src","Geometry","CMSCommonData","python")
48  simrecoDir = os.path.join(CMSSWBASE,"src","Configuration","Geometry","python")
49  if doTest:
50  if not os.path.isdir(xmlDir):
51  xmlDir = os.path.join(CMSSWRELBASE,"src","Geometry","CMSCommonData","python")
52  else:
53  mvCommands = ""
54  if not os.path.isdir(xmlDir):
55  mvCommands += "mv "+xmlName+" "+xmlDir+"/\n"
56  else:
57  xmlName = os.path.join(xmlDir,xmlName)
58  if not os.path.isdir(simrecoDir):
59  mvCommands += "mv "+simName+" "+simrecoDir+"/\n"
60  mvCommands += "mv "+recoName+" "+simrecoDir+"/\n"
61  else:
62  simName = os.path.join(simrecoDir,simName)
63  recoName = os.path.join(simrecoDir,recoName)
64  if len(mvCommands)>0:
65  print("Warning: some geometry packages not checked out.\nOnce they are available, please execute the following commands manually:\n"+mvCommands)
66 
67  # open files
68  xmlFile = open(xmlName,'w')
69  simFile = open(simName,'w')
70  recoFile = open(recoName,'w')
71 
72  # common preamble
73  preamble = "import FWCore.ParameterSet.Config as cms"+"\n"+"\n"
74  preamble += "# This config was generated automatically using generate2023Geometry.py"+"\n"
75  preamble += "# If you notice a mistake, please update the generating script, not just this config"+"\n"+"\n"
76 
77  # create XML config
78  xmlFile.write(preamble)
79  # extra preamble
80  xmlFile.write("XMLIdealGeometryESSource = cms.ESSource(\"XMLIdealGeometryESSource\","+"\n")
81  xmlFile.write(" geomXMLFiles = cms.vstring("+"\n")
82  for section in range(1,maxsections+1):
83  # midamble
84  if section==2:
85  xmlFile.write(" )+"+"\n"+" cms.vstring("+"\n")
86  for iDict,aDict in enumerate(allDicts):
87  if section in aDict[detectorTuple[iDict]].keys():
88  xmlFile.write('\n'.join([ " '"+aLine+"'," for aLine in aDict[detectorTuple[iDict]][section] ])+"\n")
89  # postamble
90  xmlFile.write(" ),"+"\n"+" rootNodeName = cms.string('cms:OCMS')"+"\n"+")"+"\n")
91  xmlFile.close()
92 
93  # create sim config
94  simFile.write(preamble)
95  # always need XML
96  simFile.write("from Geometry.CMSCommonData."+os.path.basename(xmlName).replace(".py","")+" import *"+"\n")
97  for iDict,aDict in enumerate(allDicts):
98  if "sim" in aDict[detectorTuple[iDict]].keys():
99  simFile.write('\n'.join([ aLine for aLine in aDict[detectorTuple[iDict]]["sim"] ])+"\n")
100  simFile.close()
101 
102  # create reco config
103  recoFile.write(preamble)
104  # always need sim
105  recoFile.write("from Configuration.Geometry."+os.path.basename(simName).replace(".py","")+" import *"+"\n\n")
106  for iDict,aDict in enumerate(allDicts):
107  if "reco" in aDict[detectorTuple[iDict]].keys():
108  recoFile.write("# "+aDict["name"]+"\n")
109  recoFile.write('\n'.join([ aLine for aLine in aDict[detectorTuple[iDict]]["reco"] ])+"\n\n")
110  recoFile.close()
111 
112  from Configuration.StandardSequences.GeometryConf import GeometryConf
113  if not doTest: # todo: include these in unit test somehow
114  # specify Era customizations
115  # must be checked manually in:
116  # Configuration/StandardSequences/python/Eras.py
117  # Configuration/Eras/python/
118  # Configuration/PyReleaseValidation/python/upgradeWorkflowComponents.py (workflow definitions)
119  eraLine = ""
120  eraLineItems = []
121  for iDict,aDict in enumerate(allDicts):
122  if "era" in aDict[detectorTuple[iDict]].keys():
123  eraLineItems.append(aDict[detectorTuple[iDict]]["era"])
124  eraLine += ", ".join([ eraLineItem for eraLineItem in eraLineItems ])
125  print("The Era for this detector should contain:")
126  print(eraLine)
127 
128  # specify GeometryConf
129  if not 'Extended2023'+detectorVersion in GeometryConf.keys():
130  print("Please add this line in Configuration/StandardSequences/python/GeometryConf.py:")
131  print(" 'Extended2023"+detectorVersion+"' : 'Extended2023"+detectorVersion+",Extended2023"+detectorVersion+"Reco',")
132 
133  errorList = []
134 
135  if doTest:
136  # tests for Configuration/Geometry
137  if not filecmp.cmp(simName,os.path.join(simrecoDir,simName)):
138  errorList.append(simName+" differs");
139  if not filecmp.cmp(recoName,os.path.join(simrecoDir,recoName)):
140  errorList.append(recoName+" differs");
141  # test for Configuration/StandardSequences
142  if not 'Extended2023'+detectorVersion in GeometryConf.keys():
143  errorList.append('Extended2023'+detectorVersion+" missing from GeometryConf")
144  # test for Geometry/CMSCommonData
145  if not filecmp.cmp(xmlName,os.path.join(xmlDir,xmlName)):
146  errorList.append(xmlName+" differs");
147  return errorList
148 
149 if __name__ == "__main__":
150  # define options
151  parser = OptionParser()
152  for aDict in allDicts:
153  parser.add_option("-"+aDict["abbrev"],"--"+aDict["name"],dest="v_"+aDict["name"],default=aDict["default"],help="version for "+aDict["name"]+" (default = %default)")
154  parser.add_option("-V","--version",dest="detectorVersionManual",default=detectorVersionDefault,help="manual detector version number (default = %default)")
155  parser.add_option("-D","--detector",dest="v_detector",default=0,help="version for whole detector, ignored if 0, overrides subdet versions otherwise (default = %default)")
156  parser.add_option("-l","--list",dest="doList",default=False,action="store_true",help="list known detector versions and exit (default = %default)")
157  parser.add_option("-t","--test",dest="doTest",default=False,action="store_true",help="enable unit test mode (default = %default)")
158  (options, args) = parser.parse_args()
159 
160  # check options
161  if options.doList and not options.doTest:
162  pprint(sorted(detectorVersionDict.items(),key=operator.itemgetter(1)))
163  sys.exit(0)
164  elif options.doTest:
165  # list of errors
166  errorList = []
167  # run all known possibilities
168  for detectorTuple in detectorVersionDict:
169  errorTmp = generateGeom(detectorTuple,options)
170  errorList.extend(errorTmp)
171  if len(errorList)>0:
172  print('\n'.join([anError for anError in errorList]))
173  sys.exit(1)
174  else:
175  sys.exit(0)
176  else:
177  detectorTuple = tuple([aDict["abbrev"]+str(getattr(options,"v_"+aDict["name"])) for aDict in allDicts])
178  generateGeom(detectorTuple,options)
179  sys.exit(0)
180 
def replace(string, replacements)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def generateGeom(detectorTuple, options)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
#define str(s)