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