ATLAS Offline Software
ReadCalibFromCool.py
Go to the documentation of this file.
1 #!/bin/env python
2 
3 # Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
4 #
5 # ReadCalibFromCool.py
6 # Andrei Artamonov 2009-11-03
7 
8 import getopt,sys,os
9 os.environ['TERM'] = 'linux'
10 
11 def usage():
12  print ("Usage: ",sys.argv[0]," [OPTION] ... ")
13  print ("Dumps the TileCal constants from various schemas / folders / tags")
14  print ("")
15  print ("-h, --help shows this help")
16  print ("-f, --folder= specify status folder to use f.i. /TILE/OFL02/CALIB/CIS/LIN ")
17  print ("-t, --tag= specify tag to use, f.i. UPD1 or UPD4 or full suffix like RUN2-HLT-UPD1-00")
18  print ("-r, --run= specify run number, by default uses latest iov")
19  print ("-l, --lumi= specify lumi block number, default is 0")
20  print ("-b, --begin= specify run number of first iov in multi-iov mode, by default uses very first iov")
21  print ("-e, --end= specify run number of last iov in multi-iov mode, by default uses latest iov")
22  print ("-m, --module= specify module to use, default is not set")
23  print ("-N, --chmin= specify minimal channel to use, default is 0")
24  print ("-X, --chmax= specify maximal channel to use, default is 47")
25  print ("-c, --chan= specify channel to use , default is all channels from chmin to chmax")
26  print ("-g, --gain=, -a, --adc= specify adc(gain) to print or number of adcs to print with - sign, default is -2")
27  print ("-n, --nval= specify number of values to output, default is all")
28  print ("-C, --comment print comment for every IOV")
29  print ("-i, --iov print IOVs only for every module")
30  print ("-I, --IOV print IOVs only")
31  print ("-d, --default print also default values stored in AUX01-AUX20")
32  print ("-B, --blob print additional blob info")
33  print ("-H, --hex print frag id instead of module name")
34  print ("-P, --pmt print pmt number in addition to channel number")
35  print ("-p, --prefix= print some prefix on every line ")
36  print ("-k, --keep= field numbers or channel numbers to ignore, e.g. '0,2,3,EBch0,EBch1,EBch12,EBch13,EBspD4ch18,EBspD4ch19,EBspC10ch4,EBspC10ch5' ")
37  print ("-s, --schema= specify schema to use, like 'COOLONL_TILE/CONDBR2' or 'sqlite://;schema=tileSqlite.db;dbname=CONDBR2' or tileSqlite.db")
38  print ("-D, --dbname= specify dbname part of schema if schema only contains file name, default is CONDBR2")
39  print ("-S, --server= specify server - ORACLE or FRONTIER, default is FRONTIER")
40 
41 letters = "hr:l:s:t:f:D:S:n:b:e:m:N:X:c:a:g:p:dBCiIHPk:"
42 keywords = ["help","run=","lumi=","schema=","tag=","folder=","dbname=","server=","module=","begin=","end=","chmin=","chmax=","gain=","adc=","chan=","nval=","prefix=","default","blob","hex","pmt","keep=","comment","iov","IOV"]
43 
44 try:
45  opts, extraparams = getopt.getopt(sys.argv[1:],letters,keywords)
46 except getopt.GetoptError as err:
47  print (str(err))
48  usage()
49  sys.exit(2)
50 
51 # defaults
52 run = 2147483647
53 lumi = 0
54 schema = 'COOLOFL_TILE/CONDBR2'
55 dbname = ''
56 server = ''
57 folderPath = "/TILE/OFL02/CALIB/CIS/LIN"
58 tag = "UPD4"
59 nval = 0
60 nadc = -1
61 rosmin = 1
62 rosmax = 5
63 blob = False
64 hexid = False
65 pmt = False
66 prefix = None
67 modmin = 0
68 modmax = 99999
69 modulename="AUX-1"
70 partname=""
71 one_mod = False
72 mod = -1
73 ros = -1
74 chan_n= -1
75 chanmin = -1
76 chanmax = -1
77 gainmin = -1
78 gainmax = -1
79 begin = -1
80 end = 2147483647
81 iov = False
82 iovonly = False
83 IOVONLY = False
84 comment = False
85 keep=[]
86 
87 for o, a in opts:
88  a = a.strip()
89  if o in ("-f","--folder"):
90  folderPath = a
91  elif o in ("-t","--tag"):
92  tag = a
93  elif o in ("-s","--schema"):
94  schema = a
95  elif o in ("-D","--dbname"):
96  dbname = a
97  elif o in ("-S","--server"):
98  server = a
99  elif o in ("-n","--nval"):
100  nval = int(a)
101  elif o in ("-b","--begin"):
102  begin = int(a)
103  iov = True
104  one_mod = True
105  elif o in ("-e","--end"):
106  end = int(a)
107  iov = True
108  one_mod = True
109  elif o in ("-i","--iov"):
110  iov = True
111  iovonly = True
112  if modulename=='AUX-1':
113  modulename='ALL00'
114  elif o in ("-I","--IOV"):
115  iov = True
116  IOVONLY = True
117  if modulename=='AUX-1':
118  modulename='ALL00'
119  elif o in ("-a","--adc","-g","--gain"):
120  nadc = int(a)
121  elif o in ("-m","--module"):
122  modulename = a
123  one_mod = True
124  elif o in ("-c","--chan"):
125  chan_n = int(a)
126  elif o in ("-N","--chmin"):
127  chanmin = int(a)
128  elif o in ("-X","--chmax"):
129  chanmax = int(a)
130  elif o in ("-C","--comment"):
131  comment = True
132  elif o in ("-r","--run"):
133  run = int(a)
134  elif o in ("-l","--lumi"):
135  lumi = int(a)
136  elif o in ("-d","--default"):
137  rosmin = 0
138  elif o in ("-B","--blob"):
139  blob = True
140  elif o in ("-H","--hex"):
141  hexid = True
142  elif o in ("-P","--pmt"):
143  pmt = True
144  elif o in ("-p","--prefix"):
145  prefix = a
146  elif o in ("-k","--keep"):
147  keep = a.split(",")
148  elif o in ("-h","--help"):
149  usage()
150  sys.exit(2)
151  else:
152  raise RuntimeError("unhandled option")
153 
154 
155 from TileCalibBlobPython import TileCalibTools
156 from TileCalibBlobPython.TileCalibTools import MAXRUN, MAXLBK
157 from TileCalibBlobObjs.Classes import TileCalibUtils, TileCalibType
158 
159 
160 from TileCalibBlobPython.TileCalibLogger import getLogger
161 log = getLogger("ReadCalibFrCool")
162 import logging
163 logLevel=logging.DEBUG
164 log.setLevel(logLevel)
165 log1 = getLogger("TileCalibTools")
166 log1.setLevel(logLevel)
167 
168 
169 #=== check parameters
170 if len(dbname)<7 and run!=2147483647:
171  dbname = 'COMP200' if run<232000 else 'CONDBR2'
172 
173 if 'COOLO' not in schema and ':' not in schema and ';' not in schema:
174  schema='sqlite://;schema='+schema+';dbname='+(dbname if len(dbname) else 'CONDBR2')
175 
176 if schema=='COOLONL_TILE/COMP200':
177  if not (folderPath.startswith('/TILE/ONL01/') or folderPath.startswith('/TILE/OFL01/')):
178  print ("Folder %s doesn't exist in schema %s " % (folderPath,schema))
179  sys.exit(2)
180 
181 if schema=='COOLONL_TILE/CONDBR2':
182  if not folderPath.startswith('/TILE/ONL01/'):
183  print ("Folder %s doesn't exist in schema %s, only /TILE/ONL01 " % (folderPath,schema))
184  sys.exit(2)
185 
186 if schema=='COOLOFL_TILE/COMP200' or schema=='COOLOFL_TILE/CONDBR2':
187  if not folderPath.startswith('/TILE/OFL02/'):
188  print ("Folder %s doesn't exist in schema %s " % (folderPath,schema))
189  sys.exit(2)
190 
191 if iov:
192  run=end
193  lumi=0
194 
195 #=== set database
196 db = TileCalibTools.openDbConn(schema,server)
197 folderTag = TileCalibTools.getFolderTag(schema if 'COMP200' in schema or 'OFLP200' in schema else db, folderPath, tag)
198 log.info("Initializing folder %s with tag %s", folderPath, folderTag)
199 
200 #=== initialize blob reader
201 blobReader = TileCalibTools.TileBlobReader(db,folderPath, folderTag)
202 #blobReader.log().setLevel(logging.DEBUG)
203 
204 #=== get drawer with status at given run
205 log.info("Initializing for run %d, lumiblock %d", run,lumi)
206 flt=None
207 r=5
208 d=0
211 while not flt:
212  d-=1
213  if d<0:
214  r-=1
215  if r<0:
216  break
218  flt = blobReader.getDrawer(r, d, (run,lumi), False, False)
219 if flt:
220  blobT=flt.getObjType()
221  blobV=flt.getObjVersion()
222  mchan=flt.getNChans()
223  mgain=flt.getNGains()
224  mval=flt.getObjSizeUint32()
225  log.info( "Blob type: %d Version: %d Nchannels: %d Ngains: %d Nval: %d", blobT,blobV,mchan,mgain,mval)
226  if nadc<-mgain:
227  nadc=-mgain
228  if nchan<mchan:
229  nchan=mchan
230  if ngain<mgain:
231  ngain=mgain
232 else:
233  mgain=1
234 if nadc==-1:
235  nadc=-ngain
236 
237 log.info("Comment: %s", blobReader.getComment((run,lumi)))
238 
239 #=== check ROS and module numbers
240 if one_mod:
241  partname = modulename[:3]
242  mod = int(modulename[3:]) -1
243 
244 part_dict = {'AUX':0,'LBA':1,'LBC':2,'EBA':3,'EBC':4}
245 if partname in part_dict:
246  ros = part_dict[partname]
247  rosmin = ros
248  rosmax = ros+1
249 else:
250  ros = -1
251 
252 if mod >= 0:
253  modmin = mod
254  modmax = mod+1
255 elif mod < -1:
256  modmax = modmin
257 
258 if chan_n >= 0 and chan_n < nchan:
259  chanmin = chan_n
260  chanmax = chan_n+1
261 else:
262  if chanmin<0:
263  chanmin = 0
264  if chanmax<0:
265  chanmax = nchan
266  else:
267  chanmax += 1
268 
269 if nadc >= 0 and nadc < ngain:
270  gainmin = nadc
271  gainmax = nadc+1
272 else:
273  gainmin = 0
274  if nadc<0:
275  gainmax = -nadc
276  else:
277  gainmax = ngain
278 
279 
280 #=== IOV only option
281 if iovonly or IOVONLY:
282  if iovonly:
283  print("")
284  if begin<0:
285  begin = end
286  lastRun = -1
287  allsince = {}
288  roslist = list(range(rosmin,rosmax))
289  if comment:
290  roslist += [-1]
291  for ros in roslist:
292  if ros==-1:
293  modlist = [1000]
294  modName = "Comment"
295  else:
296  modlist=range(modmin, min(modmax,TileCalibUtils.getMaxDrawer(ros)))
297  for mod in modlist:
298  if mod<1000:
299  if hexid:
300  modName = "0x%x" % ((ros<<8)+mod)
301  else:
302  modName = TileCalibUtils.getDrawerString(ros,mod)
303  iovs = ["None"]
304  dbobjs = blobReader.getDBobjsWithinRange(ros,mod)
305  while dbobjs.goToNext():
306  obj = dbobjs.currentRef()
307  objsince = obj.since()
308  sinceRun = objsince >> 32
309  sinceLum = objsince & 0xFFFFFFFF
310  since = "(%d,%d)" % (sinceRun, sinceLum)
311  if sinceRun>lastRun:
312  lastRun = sinceRun
313  if sinceRun>=begin:
314  if iovs[0]!="None":
315  iovs += [since]
316  else:
317  iovs[0] = since
318  if since in allsince:
319  allsince[since] += [modName]
320  else:
321  allsince[since] = [modName]
322  else:
323  iovs[0] = since
324  if iovonly:
325  print("%s %s" % (modName, " ".join(iovs)) )
326  if IOVONLY:
327  print("")
328  all=[]
329  for since in allsince:
330  if comment and allsince[since][-1]!="Comment":
331  allsince[since] += ["NO_COMMENT"]
332  all+=["%s %s" % (since," ".join(allsince[since]))]
333  if len(all)>0:
334  all.sort()
335  for s in all:
336  print(s)
337  else:
338  print("No new IOVs after run",lastRun)
339  #=== close DB
340  db.closeDatabase()
341  sys.exit(0)
342 
343 
344 #=== Filling the iovList
345 iovList = []
346 if iov:
347  if mod>=0:
348  COOL_part = ros
349  COOL_chan = mod
350  else:
351  COOL_part = -1
352  COOL_chan = 1000
353 
354  try:
355  dbobjs = blobReader.getDBobjsWithinRange(COOL_part,COOL_chan)
356  if (dbobjs is None):
357  raise Exception("No DB objects retrieved when building IOV list!")
358  while dbobjs.goToNext():
359  obj = dbobjs.currentRef()
360  objsince = obj.since()
361  sinceRun = objsince >> 32
362  sinceLum = objsince & 0xFFFFFFFF
363  since = (sinceRun, sinceLum)
364  objuntil = obj.until()
365  untilRun = objuntil >> 32
366  untilLum = objuntil & 0xFFFFFFFF
367  until = (untilRun, untilLum)
368  iovList.append((since, until))
369  except Exception:
370  log.warning( "Warning: can not read IOVs from input DB file" )
371  sys.exit(2)
372 
373  be=iovList[0][0][0]
374  en=iovList[-1][0][0]
375 
376  if begin != be or end != en:
377  ib=0
378  ie=len(iovList)
379  for i,iovs in enumerate(iovList):
380  run = iovs[0][0]
381  lumi = iovs[0][1]
382  if (run<begin and run>be) or (run==begin and lumi==0) :
383  be=run
384  ib=i
385  if run>=end and run<en:
386  en=run
387  ie=i+1
388  log.info( "" )
389  if be != begin:
390  log.info( "Changing begin run from %d to %d (start of IOV)", begin,be)
391  begin=be
392  if en != end:
393  if en>end:
394  log.info( "Changing end run from %d to %d (start of next IOV)", end,en)
395  else:
396  log.info( "Changing end run from %d to %d (start of last IOV)", end,en)
397  end=en
398  iovList=iovList[ib:ie]
399  if COOL_chan == 1000:
400  log.info( "%d IOVs in total for comment field", len(iovList) )
401  else:
402  log.info( "%d IOVs in total for %s", len(iovList),modulename)
403 else:
404  iovList.append(((run,lumi),(MAXRUN, MAXLBK)))
405 
406 log.info( "\n" )
407 
408 
409 
412 dummy = [0]*48
413 barrel = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
414  13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
415  27, 26, 25, 30, 29, 28,-33,-32, 31, 36, 35, 34,
416  39, 38, 37, 42, 41, 40, 45,-44, 43, 48, 47, 46]
417 extbar = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
418  13, 14, 15, 16, 17, 18,-19,-20, 21, 22, 23, 24,
419  -27,-26,-25,-31,-32,-28, 33, 29, 30,-36,-35, 34,
420  44, 38, 37, 43, 42, 41,-45,-39,-40,-48,-47,-46]
421 
422 ch2pmt = [ dummy, barrel, barrel, extbar, extbar ]
423 gname=[]
424 if mgain!=2:
425  for i in range(mgain+1):
426  gname+=[ "g "+str(i) ]
427 else:
428  gname = [ "LG", "HG" ]
429 
430 #=== loop over all partitions,modules,channels
431 pref = ""
432 for iovs in iovList:
433  if iov:
434  pref = "(%i,%i) " % (iovs[0][0],iovs[0][1])
435  if prefix:
436  pref = prefix + " " + pref
437  if comment:
438  log.info( pref + blobReader.getComment(iovs[0]) )
439  if prefix and prefix.startswith("Write"):
440  comm = blobReader.getComment(iovs[0])
441  if ": " in comm:
442  comm = comm[comm.find(": ")+2:]
443  print ('%s --update --folder=%s --tag=%s --run=%i --lumi=%i --comment="%s"' % (prefix,folderPath,folderTag,iovs[0][0],iovs[0][1],comm))
444  miss=0
445  good=0
446  for ros in range(rosmin,rosmax):
447  for mod in range(modmin, min(modmax,TileCalibUtils.getMaxDrawer(ros))):
448  if hexid:
449  modName = "0x%x" % ((ros<<8)+mod)
450  else:
451  modName = TileCalibUtils.getDrawerString(ros,mod)
452  if modName in ['EBA39','EBA40','EBA41','EBA42','EBA55','EBA56','EBA57','EBA58',
453  'EBC39','EBC40','EBC41','EBC42','EBC55','EBC56','EBC57','EBC58' ]:
454  modSpec = 'EBspC10'
455  elif modName in ['EBA15','EBC18']:
456  modSpec = 'EBspD4'
457  elif modName in ['EBC29','EBC32','EBC34','EBC37']:
458  modSpec = 'EBspE4'
459  elif modName in ['EBA07', 'EBA25', 'EBA44', 'EBA53',
460  'EBC07', 'EBC25', 'EBC44', 'EBC53',
461  'EBC28', 'EBC31', 'EBC35', 'EBC38' ]:
462  modSpec = 'EBspE1'
463  elif modName in ['EBA08', 'EBA24', 'EBA43', 'EBA54',
464  'EBC08', 'EBC24', 'EBC43', 'EBC54' ]:
465  modSpec = 'EBMBTS'
466  else:
467  modSpec = modName
468  try:
469  flt = blobReader.getDrawer(ros, mod,iovs[0], False, False)
470  if flt is None or isinstance(flt, (int)):
471  miss+=1
472  print ("%s is missing in DB" % modName)
473  else:
474  good+=1
475  if blob:
476  print ("%s Blob type: %d Version: %d Nchannels: %d Ngains: %d Nval: %d" % (modName, flt.getObjType(), flt.getObjVersion(), flt.getNChans(), flt.getNGains(), flt.getObjSizeUint32()))
477  typeName = TileCalibType.getClassName(flt.getObjType())[-3:]
478  mval0 = 0
479  mval = flt.getObjSizeUint32()
480  if nval<0 and -nval<=mval:
481  mval=-nval
482  mval0=mval-1
483  elif nval!=0 and nval<mval:
484  mval = nval
485  mchan=flt.getNChans()
486  mgain=flt.getNGains()
487  chmin = chanmin if chanmin<mchan else mchan
488  chmax = chanmax if chanmax<mchan else mchan
489  gnmin = gainmin if gainmin<mgain else mgain
490  gnmax = gainmax if gainmax<mgain else mgain
491  for chn in range(chmin,chmax):
492  for adc in range(gnmin,gnmax):
493  if pmt:
494  msg = "%s pm %02i ch %02i %s " % ( modName, abs(ch2pmt[ros][chn]), chn, gname[adc] )
495  else:
496  msg = "%s %2i %1i " % ( modName, chn, adc )
497  for val in range(mval0,mval):
498  if str(val) in keep or modName in keep or modSpec in keep or modName[:3] in keep or modName[:2] in keep \
499  or ("%sch%i"% (modName,chn)) in keep or ("%sch%i"% (modSpec,chn)) in keep or ("%sch%i"% (modName[:3],chn)) in keep or ("%sch%i"% (modName[:2],chn)) in keep \
500  or ("%sch%ig%i"% (modName,chn,adc)) in keep or ("%sch%ig%i"% (modSpec,chn,adc)) in keep or ("%sch%ig%i"% (modName[:3],chn,adc)) in keep or ("%sch%ig%i"% (modName[:2],chn,adc)) in keep:
501  msg += " keep "
502  else:
503  if typeName=='Int':
504  v = flt.getData(chn, adc, val)
505  if v>0xff:
506  msg += " 0x%x" % v
507  else:
508  msg += " %3d" % v
509  elif typeName=='Bch':
510  msg += " %d" % flt.getData(chn, adc, val)
511  else:
512  msg += " %f" % flt.getData(chn, adc, val)
513  print (pref+msg)
514  except Exception as e:
515  print (e)
516  if miss:
517  if iovs[0][0]!=2147483647:
518  print ("%3i drawers are preseint in DB for run %d lb %d" % (good,iovs[0][0],iovs[0][1]))
519  print ("%3i drawers are missing in DB for run %d lb %d" % (miss,iovs[0][0],iovs[0][1]))
520  else:
521  print ("%3i drawers are preseint in DB" % (good))
522  print ("%3i drawers are missing in DB" % (miss))
523  if good==0:
524  print ("Please, check that you are using correct schema and correct tag")
525 
526 #=== close DB
527 db.closeDatabase()
TileCalibUtils::getMaxDrawer
static unsigned int getMaxDrawer(unsigned int ros)
Returns the maximal channel number for a given drawer.
Definition: TileCalibUtils.cxx:136
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
min
constexpr double min()
Definition: ap_fixedTest.cxx:26
TileCalibType::getClassName
static std::string getClassName(TileCalibType::TYPE type)
Returns the class name.
Definition: TileCalibType.cxx:10
TileCalibUtils::max_gain
static unsigned int max_gain()
Python compatibility function.
Definition: TileCalibUtils.h:114
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
print
void print(char *figname, TCanvas *c1)
Definition: TRTCalib_StrawStatusPlots.cxx:25
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
TileCalibUtils::getDrawerString
static std::string getDrawerString(unsigned int ros, unsigned int drawer)
Return the drawer name, e.g.
Definition: TileCalibUtils.cxx:145
ReadCalibFromCool.usage
def usage()
Definition: ReadCalibFromCool.py:11
TileCalibUtils::max_chan
static unsigned int max_chan()
Python compatibility function.
Definition: TileCalibUtils.h:112
str
Definition: BTagTrackIpAccessor.cxx:11
python.CaloCondLogger.getLogger
def getLogger(name="CaloCond")
Definition: CaloCondLogger.py:16