CMS 3D CMS Logo

alignment.py
Go to the documentation of this file.
1 import collections
2 import os
3 import re
4 
5 import configTemplates
6 from helperFunctions import replaceByMap, parsecolor, parsestyle
7 from TkAlExceptions import AllInOneError
8 
10  condShorts = {
11  "TrackerAlignmentErrorExtendedRcd": {
12  "zeroAPE_phase0": {
13  "connectString":("frontier://FrontierProd"
14  "/CMS_CONDITIONS"),
15  "tagName": "TrackerIdealGeometryErrorsExtended210_mc",
16  "labelName": ""
17  },
18  "zeroAPE_phase1": {
19  "connectString":("frontier://FrontierProd"
20  "/CMS_CONDITIONS"),
21  "tagName": "TrackerAlignmentErrorsExtended_Upgrade2017_design_v0",
22  "labelName": ""
23  },
24  },
25  "TrackerSurfaceDeformationRcd": {
26  "zeroDeformations": {
27  "connectString":("frontier://FrontierProd"
28  "/CMS_CONDITIONS"),
29  "tagName": "TrackerSurfaceDeformations_zero",
30  "labelName": ""
31  },
32  },
33  }
34  def __init__(self, name, config, runGeomComp = "1"):
35  section = "alignment:%s"%name
36  if not config.has_section( section ):
37  raise AllInOneError("section %s not found. Please define the "
38  "alignment!"%section)
39  config.checkInput(section,
40  knownSimpleOptions = ['globaltag', 'style', 'color', 'title', 'mp', 'mp_alignments', 'mp_deformations', 'hp', 'sm'],
41  knownKeywords = ['condition'])
42  self.name = name
43  if config.exists(section,"title"):
44  self.title = config.get(section,"title")
45  else:
46  self.title = self.name
47  if (int(runGeomComp) != 1):
48  self.name += "_run" + runGeomComp
49  self.title += " run " + runGeomComp
50  if "|" in self.title or "," in self.title or '"' in self.title:
51  msg = "The characters '|', '\"', and ',' cannot be used in the alignment title!"
52  raise AllInOneError(msg)
53  self.runGeomComp = runGeomComp
54  self.globaltag = config.get( section, "globaltag" )
55  self.conditions = self.__getConditions( config, section )
56 
57  self.color = config.get(section,"color")
58  self.style = config.get(section,"style")
59 
60  self.color = str(parsecolor(self.color))
61  self.style = str(parsestyle(self.style))
62 
63  def __shorthandExists(self, theRcdName, theShorthand):
64  """Method which checks, if `theShorthand` is a valid shorthand for the
65  given `theRcdName`.
66 
67  Arguments:
68  - `theRcdName`: String which specifies the database record.
69  - `theShorthand`: String which specifies the shorthand to check.
70  """
71 
72  if (theRcdName in self.condShorts) and \
73  (theShorthand in self.condShorts[theRcdName]):
74  return True
75  else:
76  return False
77 
78  def __getConditions( self, theConfig, theSection ):
79  conditions = []
80  for option in theConfig.options( theSection ):
81  if option in ("mp", "mp_alignments", "mp_deformations"):
82  condPars = theConfig.get(theSection, option).split(",")
83  condPars = [_.strip() for _ in condPars]
84  if len(condPars) == 1:
85  number, = condPars
86  jobm = None
87  elif len(condPars) == 2:
88  number, jobm = condPars
89  else:
90  raise AllInOneError("Up to 2 arguments accepted for {} (job number, and optionally jobm index)".format(option))
91 
92  if option == "mp":
93  alignments = True
94  deformations = True
95  elif option == "mp_alignments":
96  alignments = True
97  deformations = False
98  option = "mp"
99  elif option == "mp_deformations":
100  alignments = False
101  deformations = True
102  option = "mp"
103  else:
104  assert False
105 
106  folder = "/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN/MP/MPproduction/{}{}/".format(option, number)
107  if not os.path.exists(folder):
108  raise AllInOneError(folder+" does not exist.")
109  folder = os.path.join(folder, "jobData")
110  jobmfolders = set()
111  if jobm is None:
112  for filename in os.listdir(folder):
113  if re.match("jobm([0-9]*)", filename) and os.path.isdir(os.path.join(folder, filename)):
114  jobmfolders.add(filename)
115  if len(jobmfolders) == 0:
116  raise AllInOneError("No jobm or jobm(number) folder in {}".format(folder))
117  elif len(jobmfolders) == 1:
118  folder = os.path.join(folder, jobmfolders.pop())
119  else:
120  raise AllInOneError(
121  "Multiple jobm or jobm(number) folders in {}\n".format(folder)
122  + ", ".join(jobmfolders) + "\n"
123  + "Please specify 0 for jobm, or a number for one of the others."
124  )
125  elif jobm == "0":
126  folder = os.path.join(folder, "jobm")
127  if os.path.exists(folder + "0"):
128  raise AllInOneError("Not set up to handle a folder named jobm0")
129  else:
130  folder = os.path.join(folder, "jobm{}".format(jobm))
131 
132  dbfile = os.path.join(folder, "alignments_MP.db")
133  if not os.path.exists(dbfile):
134  raise AllInOneError("No file {}. Maybe your alignment folder is corrupted, or maybe you specified the wrong jobm?".format(dbfile))
135 
136  if alignments:
137  conditions.append({"rcdName": "TrackerAlignmentRcd",
138  "connectString": "sqlite_file:"+dbfile,
139  "tagName": "Alignments",
140  "labelName": ""})
141  if deformations:
142  conditions.append({"rcdName": "TrackerSurfaceDeformationRcd",
143  "connectString": "sqlite_file:"+dbfile,
144  "tagName": "Deformations",
145  "labelName": ""})
146 
147  elif option in ("hp", "sm"):
148  condPars = theConfig.get(theSection, option).split(",")
149  condPars = [_.strip() for _ in condPars]
150  if len(condPars) == 1:
151  number, = condPars
152  iteration = None
153  elif len(condPars) == 2:
154  number, iteration = condPars
155  else:
156  raise AllInOneError("Up to 2 arguments accepted for {} (job number, and optionally iteration)".format(option))
157  folder = "/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN2/HipPy/alignments/{}{}".format(option, number)
158  if not os.path.exists(folder):
159  raise AllInOneError(folder+" does not exist.")
160  if iteration is None:
161  for filename in os.listdir(folder):
162  match = re.match("alignments_iter([0-9]*).db", filename)
163  if match:
164  if iteration is None or int(match.group(1)) > iteration:
165  iteration = int(match.group(1))
166  if iteration is None:
167  raise AllInOneError("No alignments in {}".format(folder))
168  dbfile = os.path.join(folder, "alignments_iter{}.db".format(iteration))
169  if not os.path.exists(dbfile):
170  raise AllInOneError("No file {}.".format(dbfile))
171  conditions.append({"rcdName": "TrackerAlignmentRcd",
172  "connectString": "sqlite_file:"+dbfile,
173  "tagName": "Alignments",
174  "labelName": ""})
175 
176  elif option.startswith( "condition " ):
177  rcdName = option.split( "condition " )[1]
178  condPars = theConfig.get( theSection, option ).split( "," )
179  if len(condPars) == 1:
180  if len(condPars[0])==0:
181  msg = ("In section [%s]: '%s' is used with too few "
182  "arguments. A connect_string and a tag are "
183  "required!"%(theSection, option))
184  raise AllInOneError(msg)
185  elif self.__shorthandExists(rcdName, condPars[0]):
186  shorthand = condPars[0]
187  condPars = [
188  self.condShorts[rcdName][shorthand]["connectString"],
189  self.condShorts[rcdName][shorthand]["tagName"],
190  self.condShorts[rcdName][shorthand]["labelName"]]
191  elif rcdName == "TrackerAlignmentErrorExtendedRcd" and condPars[0] == "zeroAPE":
192  raise AllInOneError("Please specify either zeroAPE_phase0 or zeroAPE_phase1")
193  #can probably make zeroAPE an alias of zeroAPE_phase1 at some point,
194  #but not sure if now is the time
195  else:
196  msg = ("In section [%s]: '%s' is used with '%s', "
197  "which is an unknown shorthand for '%s'. Either "
198  "provide at least a connect_string and a tag or "
199  "use a known shorthand.\n"
200  %(theSection, option, condPars[0], rcdName))
201  if rcdName in self.condShorts:
202  msg += "Known shorthands for '%s':\n"%(rcdName)
203  theShorts = self.condShorts[rcdName]
204  knownShorts = [("\t"+key+": "
205  +theShorts[key]["connectString"]+","
206  +theShorts[key]["tagName"]+","
207  +theShorts[key]["labelName"]) \
208  for key in theShorts]
209  msg+="\n".join(knownShorts)
210  else:
211  msg += ("There are no known shorthands for '%s'."
212  %(rcdName))
213  raise AllInOneError(msg)
214  if len( condPars ) == 2:
215  condPars.append( "" )
216  if len(condPars) > 3:
217  msg = ("In section [%s]: '%s' is used with too many "
218  "arguments. A maximum of 3 arguments is allowed."
219  %(theSection, option))
220  raise AllInOneError(msg)
221  conditions.append({"rcdName": rcdName.strip(),
222  "connectString": condPars[0].strip(),
223  "tagName": condPars[1].strip(),
224  "labelName": condPars[2].strip()})
225 
226  rcdnames = collections.Counter(condition["rcdName"] for condition in conditions)
227  if rcdnames and max(rcdnames.values()) >= 2:
228  raise AllInOneError("Some conditions are specified multiple times (possibly through mp or hp options)!\n"
229  + ", ".join(rcdname for rcdname, count in rcdnames.iteritems() if count >= 2))
230 
231 
232  return conditions
233 
234  def __testDbExist(self, dbpath):
235  #FIXME delete return to end train debuging
236  return
237  if not dbpath.startswith("sqlite_file:"):
238  print "WARNING: could not check existence for",dbpath
239  else:
240  if not os.path.exists( dbpath.split("sqlite_file:")[1] ):
241  raise "could not find file: '%s'"%dbpath.split("sqlite_file:")[1]
242 
243  def restrictTo( self, restriction ):
244  result = []
245  if not restriction == None:
246  for mode in self.mode:
247  if mode in restriction:
248  result.append( mode )
249  self.mode = result
250 
251  def getRepMap( self ):
252  result = {
253  "name": self.name,
254  "title": self.title,
255  "color": self.color,
256  "style": self.style,
257  "runGeomComp": self.runGeomComp,
258  "GlobalTag": self.globaltag
259  }
260  return result
261 
262  def getConditions(self):
263  """This function creates the configuration snippet to override
264  global tag conditions.
265  """
266  if len( self.conditions ):
267  loadCond = ("\nimport CalibTracker.Configuration."
268  "Common.PoolDBESSource_cfi\n")
269  for cond in self.conditions:
270  if not cond["labelName"] == "":
271  temp = configTemplates.conditionsTemplate.replace(
272  "tag = cms.string('.oO[tagName]Oo.')",
273  ("tag = cms.string('.oO[tagName]Oo.'),"
274  "\nlabel = cms.untracked.string('.oO[labelName]Oo.')"))
275  else:
276  temp = configTemplates.conditionsTemplate
277  loadCond += replaceByMap( temp, cond )
278  else:
279  loadCond = ""
280  return loadCond
dictionary condShorts
Definition: alignment.py:10
def __getConditions(self, theConfig, theSection)
Definition: alignment.py:78
def parsestyle(style)
def restrictTo(self, restriction)
Definition: alignment.py:243
def __testDbExist(self, dbpath)
Definition: alignment.py:234
def __shorthandExists(self, theRcdName, theShorthand)
Definition: alignment.py:63
def replaceByMap(target, the_map)
— Helpers —############################
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def parsecolor(color)
def getRepMap(self)
Definition: alignment.py:251
double split
Definition: MVATrainer.cc:139
def __init__(self, name, config, runGeomComp="1")
Definition: alignment.py:34
def getConditions(self)
Definition: alignment.py:262