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