ATLAS Offline Software
Loading...
Searching...
No Matches
TileCalibCrest.py
Go to the documentation of this file.
1#!/bin/env python
2
3# Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
4# TileCalibCrest.py
5# Sanya Solodkov <Sanya.Solodkov@cern.ch>, 2025-02-04
6# Laura Sargsyan <Laura.Sargsyan@cern.ch>, 2025-09-16
7# Siarhei Harkusha <Siarhei.Harkusha@cern.ch>, 2025-05-19
8
9"""
10Python helper module for managing CREST DB connections and TileCalibBlobs.
11"""
12
13import os, re, cppyy, base64, json, time, datetime
14
15from PyCool import cool # noqa: F401
16Blob = cppyy.gbl.coral.Blob
17
18from pycrest.api.crest_api import CrestApi
19
20from TileCalibBlobObjs.Classes import TileCalibUtils, TileCalibDrawerCmt, \
21 TileCalibDrawerInt, TileCalibDrawerOfc, TileCalibDrawerBch, \
22 TileCalibDrawerFlt, TileCalibType
23from TileCalibBlobPython import TileCalibTools
24
25#=== get a logger
26from TileCalibBlobPython.TileCalibLogger import TileCalibLogger, getLogger
27log = getLogger("TileCalibCrest")
28
29
30#======================================================================
31#===
32#=== Global helper functions
33#===
34#======================================================================
35
36#
37#______________________________________________________________________
38#=== useful constants
39MINRUN = 0
40MINLBK = 0
41MAXRUN = (1<<31)-1
42MAXLBK = (1<<32)-1
43MAXRUNLUMI = (MAXRUN<<32)+MAXLBK
44# empty Tile channel for storing laser partition variation. DO NOT CHANGE.
45LASPARTCHAN = 43
46
47
48class TileBlobReaderCrest(TileCalibLogger):
49 """
50 TileCalibBlobReader is a helper class, managing the details of CREST interactions for
51 the user of TileCalibBlobs.
52 """
53
54 #____________________________________________________________________
55 def __init__(self, db, folder='', tag='', run=None, lumi=0, modmin=0, modmax=275, copyBlob=False):
56 """
57 Input:
58 - db : server connection string or file name
59 - folder: full folder path
60 - tag : The folder tag, e.g. \"UPD4-24\" or full tag
61 - run : Run number (if known)
62 - lumi : Lumi block number
63 - modmin: Minimal module (COOL channel number)
64 - modmax: Maximal module (COOL channel number)
65 - copyBlob: save payload from CREST (Default:False, True to copy payload to json file)
66 """
67 #=== initialize base class
68 TileCalibLogger.__init__(self,"TileBlobReader")
69 self.payload = {}
70 self.__db = db
71 self.__folder = folder
72 self.__tag = tag
73 self.__copyBlob = copyBlob
74
75 self.__iovList = []
76 self.__iov = (-1,0)
77 self.__commentBlob = None
78 self.__drawerBlob = [None]*276
79 self.__comment = None
80 self.__drawer = [None]*276
81 self.__modmin = modmin
82 self.__modmax = modmax+1
83
84 #=== try to open db
85 self.__remote = (("http://" in db) or ("https://" in db) or ("CREST" in db))
86 if self.__remote:
87 if 'http' not in self.__db:
88 self.__db = os.getenv(db,os.getenv('CREST_HOST',os.getenv('CREST_SERVER_PATH','http://crest-j23.cern.ch:8081/api-v6.0')))
89 self.log().info('Host %s' , (self.__db))
90 self.__api_instance = CrestApi(host=self.__db)
91 socks = os.getenv('CREST_SOCKS', 'False')
92 if socks == 'True': self.__api_instance.socks()
93 self.__tag = self.getFolderTag(folder,None,tag)
94 if run is not None and lumi is not None:
95 log.info("Initializing for run %d, lumiblock %d", run,lumi)
96 self.__getIov((run,lumi),True)
97 else:
98 self.log().info('File %s' , (self.__db))
99 self.__api_instance = None
100 self.__tag = 'unknown'
101 self.__iovList.append(((MINRUN,MINLBK),(MAXRUN, MAXLBK)))
102 self.__iov = self.__runlumi2iov(self.__iovList[-1])
103 with open(self.__db, 'r') as the_file:
104 jdata = json.load(the_file)
105 if self.__copyBlob:
106 self.payload = jdata
107 return
108 for chan in range(self.__modmin,self.__modmax):
109 try:
110 blob=jdata[str(chan)][0]
111 except Exception:
112 blob=None
113 self.__create_drawer(blob,chan)
114 try:
115 blob=jdata['1000'][0]
116 except Exception:
117 blob=None
118 self.__create_comment(blob)
119
120 #____________________________________________________________________
121 def getTag(self):
122 return self.__tag
123
124 #____________________________________________________________________
125 def getFolderTag(self, folder, prefix, globalTag, api=None):
126 if globalTag=='CURRENT' or globalTag=='UPD4' or globalTag=='' or globalTag=='HEAD':
127 globalTag=TileCalibTools.getAliasFromFile('Current')
128 log.info("Resolved CURRENT globalTag to \'%s\'", globalTag)
129 elif globalTag=='CURRENTES' or globalTag=='UPD1':
130 globalTag=TileCalibTools.getAliasFromFile('CurrentES')
131 log.info("Resolved CURRENT ES globalTag to \'%s\'", globalTag)
132 elif globalTag=='NEXT':
133 globalTag=TileCalibTools.getAliasFromFile('Next')
134 log.info("Resolved NEXT globalTag to \'%s\'", globalTag)
135 elif globalTag=='NEXTES':
136 globalTag=TileCalibTools.getAliasFromFile('NextES')
137 log.info("Resolved NEXT ES globalTag to \'%s\'", globalTag)
138 globalTag=globalTag.replace('*','')
139 if prefix is None:
140 prefix = ''
141 for f in folder.split('/'):
142 if re.findall('[a-z]+',f) != [] and f!='CellNoise':
143 prefix+=f
144 else:
145 prefix+=f.capitalize()
146 else:
147 prefix=prefix.strip('-').split('-')[0]
148 if prefix.startswith('Calo') and 'NoiseCell' not in prefix:
149 prefix='CALO'+prefix[4:]
150 prefix=prefix.replace('Pileupnoiselumi','PileUpNoiseLumi')
151 if 'UPD1' in globalTag or 'UPD4' in globalTag or ('COND' not in globalTag and 'CREST' not in globalTag):
152 if prefix != '':
153 if prefix in globalTag or prefix.upper() in globalTag:
154 tag=globalTag
155 else:
156 tag=prefix+'-'+globalTag
157 self.log().info("Resolved localTag \'%s\' to folderTag \'%s\'", globalTag,tag)
158 elif folder!='' and not (globalTag.upper().startswith('TILE') or globalTag.upper().startswith('CALO')):
159 tag = TileCalibUtils.getFullTag(folder, globalTag)
160 if tag.startswith('Calo') and 'NoiseCell' not in tag:
161 tag='CALO'+tag[4:]
162 tag=tag.replace('Pileupnoiselumi','PileUpNoiseLumi')
163 self.log().info("Resolved localTag \'%s\' to folderTag \'%s\'", globalTag,tag)
164 else:
165 tag=globalTag
166 self.log().info("Use localTag \'%s\' as is", tag)
167 else:
168 tag=None
169 if api:
170 tags=api.find_global_tag_map(globalTag)
171 else:
172 tags=self.__api_instance.find_global_tag_map(globalTag)
173 if tags.size==0:
174 raise Exception( "globalTag %s not found" % (globalTag) )
175 else:
176 for i in range(tags.size):
177 t=tags.resources[i].tag_name
178 l=tags.resources[i].label
179 if (prefix!='' and t.startswith(prefix)) or l==folder:
180 tag=t
181 self.log().info("Resolved globalTag \'%s\' to folderTag \'%s\'", globalTag,tag)
182 #taginfo = self.__api_instance.find_tag(name=tag)
183 #print(taginfo)
184 return tag
185
186 #____________________________________________________________________
187 def getIovs(self,since=(MINRUN,MINLBK),until=(MAXRUN,MAXLBK)):
188 if self.__api_instance is None:
189 return [self.__iovList[0][0]]
190 else:
191 run_lumi1=str((since[0]<<32)+since[1]+1)
192 run_lumi2=str((until[0]<<32)+until[1]+1)
193 MAXRUNLUMI1=str(MAXRUNLUMI+1)
194 iovs1=self.__api_instance.select_iovs(self.__tag,"0",run_lumi1,sort='id.since:DESC,id.insertionTime:DESC',size=1,snapshot=0)
195 iovs2=self.__api_instance.select_iovs(self.__tag,run_lumi2,MAXRUNLUMI1,sort='id.since:ASC,id.insertionTime:DESC',size=1,snapshot=0)
196 since1=0 if iovs1.size==0 else iovs1.resources[0].since
197 until1=MAXRUNLUMI if iovs2.size==0 else iovs2.resources[0].since
198 iovs=self.__api_instance.select_iovs(self.__tag,str(since1),str(until1),sort='id.since:ASC,id.insertionTime:DESC',size=999999,snapshot=0)
199 iovList=[]
200 if iovs.size==0:
201 raise Exception( "IOV for tag %s IOV [%s,%s] - (%s,%s) not found" % (self.__tag,since[0],since[1],until[0],until[1]) )
202 else:
203 for i in range(iovs.size):
204 iov=iovs.resources[i]
205 since=int(iov.since)
206 runS=since>>32
207 lumiS=since&0xFFFFFFFF
208 if (runS,lumiS) not in iovList:
209 iovList.append((runS,lumiS))
210 return iovList
211
212 #____________________________________________________________________
213 def getIov(self, option=0):
214 if option!=0:
215 return self.__iov
216 else:
217 return self.__iovList[-1]
218
219 #____________________________________________________________________
220 def __getIov(self,runlumi,dbg=False):
221 if self.__api_instance is None:
222 pass
223 else:
224 run_lumi1=str((runlumi[0]<<32)+runlumi[1]+1)
225 MAXRUNLUMI1=str(MAXRUNLUMI+1)
226 iovs1=self.__api_instance.select_iovs(self.__tag,"0",run_lumi1,sort='id.since:DESC,id.insertionTime:DESC',size=1,snapshot=0)
227 iovs2=self.__api_instance.select_iovs(self.__tag,run_lumi1,MAXRUNLUMI1,sort='id.since:ASC,id.insertionTime:DESC',size=1,snapshot=0)
228 if iovs1.size==0:
229 raise Exception( "IOV for tag %s run,lumi (%s,%s) not found" % (self.__tag,runlumi[0],runlumi[1]) )
230 else:
231 iov=iovs1.resources[0]
232 since=int(iov.since)
233 runS=since>>32
234 lumiS=since&0xFFFFFFFF
235 until=MAXRUNLUMI if iovs2.size==0 else iovs2.resources[0].since
236 runU=until>>32
237 lumiU=until&0xFFFFFFFF
238 hash=iov.payload_hash
239 if dbg:
240 #self.log().info('Run,Lumi (%d,%d)' , runlumi)
241 self.log().info('IOV [%d,%d] - (%d,%d)' , runS,lumiS,runU,lumiU)
242 self.log().info('Insertion time %s' , iov.insertion_time)
243 self.log().info('Hash %s' , hash)
244 payload = self.__api_instance.get_payload(hash=hash).decode('utf-8')
245 jdata=json.loads(payload)
246 #with open("payload.json", 'w') as the_file:
247 # the_file.write(payload)
248 # the_file.write('\n')
249 self.__iovList.append(((runS,lumiS),(runU, lumiU)))
250 self.__iov = self.__runlumi2iov(self.__iovList[-1])
251 if self.__copyBlob:
252 self.payload = jdata
253 return
254 for chan in range(self.__modmin,self.__modmax):
255 try:
256 blob=jdata[str(chan)][0]
257 except Exception:
258 blob=None
259 self.__create_drawer(blob,chan)
260 try:
261 blob=jdata['1000'][0]
262 except Exception:
263 blob=None
264 self.__create_comment(blob)
265 return
266
267 #____________________________________________________________________
268 def __runlumi2iov(self,runlumi):
269 since = (runlumi[0][0]<<32) + runlumi[0][1]
270 until = (runlumi[1][0]<<32) + runlumi[1][1]
271 return (since,until)
272
273 #____________________________________________________________________
274 def __checkIov(self,runlumi):
275 point = (runlumi[0]<<32) + runlumi[1]
276 inrange = point>=self.__iov[0] and point<self.__iov[1]
277 return inrange
278
279 #____________________________________________________________________
280 def __make_blob(self,string):
281 b = Blob()
282 b.write(string)
283 b.seek(0)
284 return b
285
286 #____________________________________________________________________
287 def __create_comment(self,b64string):
288 if b64string is None or len(b64string)==0:
289 if b64string is None:
290 self.__commentBlob = None
291 else:
292 self.__commentBlob = 0
293 self.__comment = None
294 else:
295 blob1 = base64.decodebytes(bytes(b64string,'ascii'))
296 self.__commentBlob = self.__make_blob(blob1)
298 return
299
300 #____________________________________________________________________
301 def __create_drawer(self,b64string,chan):
302 if b64string is None or isinstance(b64string, (int, float)) or len(b64string)==0:
303 if b64string is None:
304 self.__drawerBlob[chan] = None
305 else:
306 self.__drawerBlob[chan] = 0
307 self.__drawer[chan] = None
308 return
309 blob1 = base64.decodebytes(bytes(b64string,'ascii'))
310 self.__drawerBlob[chan] = self.__make_blob(blob1)
312 typeName = TileCalibType.getClassName(cmt.getObjType())
313 del cmt
314 #=== create calibDrawer depending on type
315 if typeName=='TileCalibDrawerFlt':
317 self.log().debug( "typeName = Flt " )
318 elif typeName=='TileCalibDrawerInt':
320 self.log().debug( "typeName = Int " )
321 elif typeName=='TileCalibDrawerBch':
323 self.log().debug( "typeName = Bch " )
324 elif typeName=='TileCalibDrawerOfc':
326 self.log().debug( "typeName = Ofc " )
327 elif typeName=='TileCalibDrawerCmt':
328 self.__drawer[chan] = cppyy.gbl.CaloCondBlobFlt.getInstance(self.__drawerBlob[chan])
329 self.log().debug( "typeName = CaloFlt " )
330 else:
331 self.__drawer[chan] = None
332 self.log().warn("Unknown blob type for chan %d - ignoring", chan)
333 return
334
335 #____________________________________________________________________
336 def getPayload(self, runlumi=None, dbg=False):
337
338 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
339 self.__getIov(runlumi,dbg)
340
341 return self.payload
342
343 #____________________________________________________________________
344 def getBlob(self,ros, mod, runlumi=None, dbg=False):
345
346 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
347 self.__getIov(runlumi,dbg)
348
349 chanNum = getDrawerIdx(ros,mod)
350
351 if (chanNum>=0 and chanNum<len(self.__drawer)):
352 return self.__drawerBlob[chanNum]
353 else:
354 raise Exception( "Invalid drawer requested: %s %s" % (ros,mod) )
355
356 #____________________________________________________________________
357 def getDrawer(self,ros, mod, runlumi=None, dbg=False, useDefault=True):
358
359 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
360 self.__getIov(runlumi,dbg)
361
362 chanNum = getDrawerIdx(ros,mod)
363
364 if (chanNum>=0 and chanNum<len(self.__drawer)):
365 drawer=self.__drawer[chanNum]
366 if not useDefault and drawer is None:
367 if self.__drawerBlob[chanNum] is None:
368 return None
369 else:
370 return 0
371 while drawer is None:
372 #=== no default at all?
373 if ros==0 and drawer==0:
374 raise Exception('No default available')
375 #=== follow default policy
376 ros,mod = self.getDefault(ros,mod)
377 chanNum = getDrawerIdx(ros,mod)
378 drawer=self.__drawer[chanNum]
379 return drawer
380 elif (chanNum == 1000):
381 return self.__comment
382 else:
383 raise Exception( "Invalid drawer requested: %s %s" % (ros,mod) )
384
385 #____________________________________________________________________
386 def getComment(self,runlumi=None,split=False):
387
388 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
389 self.__getIov(runlumi)
390 if self.__comment is not None:
391 if split:
392 return (self.__comment.getAuthor(),self.__comment.getComment(),self.__comment.getDate())
393 else:
394 return self.__comment.getFullComment()
395 else:
396 return "<no comment found>"
397
398 #____________________________________________________________________
399 def getDefault(self, ros, drawer):
400 """
401 Returns a default drawer number (among first 20 COOL channels) for any drawer in any partition
402 """
403 if ros==0:
404 if drawer<=4 or drawer==12 or drawer>=20:
405 drawer1=0
406 elif drawer<12:
407 drawer1=4
408 else:
409 drawer1=12
410 elif ros==1 or ros==2:
411 drawer1=4
412 elif ros==3:
413 OffsetEBA = [ 0, 0, 0, 0, 0, 0, 3, 2, #// Merged E+1: EBA07; Outer MBTS: EBA08
414 0, 0, 0, 0, 7, 6, 5, 7, #// D+4: EBA13, EBA16; Special D+4: EBA14; Special D+40: EBA15
415 7, 6, 6, 7, 0, 0, 0, 2, #// D+4: EBA17, EBA20; Special D+4: EBA18, EBA19; Outer MBTS: EBA24
416 3, 0, 0, 0, 0, 0, 0, 0, #// Merged E+1: EBA25
417 0, 0, 0, 0, 0, 0, 1, 1, #// Inner MBTS + special C+10: EBA39, EBA40
418 1, 1, 2, 3, 0, 0, 0, 0, #// Inner MBTS + special C+10: EBA41, EBA42; Outer MBTS: EBA43; Merged E+1: EBA44
419 0, 0, 0, 0, 3, 2, 1, 1, #// Merged E+1: EBA53; Outer MBTS: EBA54; Inner MBTS + special C+10: EBA55, EBA56
420 1, 1, 0, 0, 0, 0, 0, 0] #// Inner MBTS + special C+10: EBA57, EBA58
421 drawer1 = 12 + OffsetEBA[drawer]
422 elif ros==4:
423 OffsetEBC = [ 0, 0, 0, 0, 0, 0, 3, 2, #// Merged E-1: EBC07; Outer MBTS: EBC08
424 0, 0, 0, 0, 7, 6, 6, 7, # // D-4: EBC13, EBC16; Special D-4: EBC14, EBC15;
425 7, 5, 6, 7, 0, 0, 0, 2, #// D-4: EBC17, EBC20; Special D-40 EBC18; Special D-4: EBC19; Outer MBTS: EBC24
426 3, 0, 0, 3, 4, 0, 3, 4, #// Merged E-1: EBC25, EBC28, EBC31; E-4': EBC29, EBC32
427 0, 4, 3, 0, 4, 3, 1, 1, #// E-4': EBC34, EBC37; Merged E-1: EBC35, EBC38; Inner MBTS + special C-10: EBC39, EBC40
428 1, 1, 2, 3, 0, 0, 0, 0, #// Inner MBTS + special C-10: EBC41, EBC42; Outer MBTS: EBC43; Merged E-1: EBC44
429 0, 0, 0, 0, 3, 2, 1, 1, #// Merged E-1: EBC53; Outer MBTS: EBC54; Inner MBTS + special C-10: EBC55, EBC56
430 1, 1, 0, 0, 0, 0, 0, 0] #// Inner MBTS + special C-10: EBC57, EBC58
431 drawer1 = 12 + OffsetEBC[drawer]
432 else:
433 drawer1=0
434
435 return (0,drawer1)
436
437 #____________________________________________________________________
438 def dumpIovs(self, iovList, rosmin, rosmax, drawermin, drawermax, option=1, comment=False, usenames=True):
439 """
440 Dumps statistics - how many non-empty modules exists in different IOVs
441 """
442
443 if len(iovList)>0:
444 alliovs={}
445 allmods={}
446 zeroiovs={}
447 nmod=0
448 rosrange=list(range(rosmin,rosmax))
449 if comment:
450 rosrange+=[9999]
451 for since in iovList:
452 iov="(%s,%s)" % since
453 allmod=""
454 missmod=""
455 zeromod=""
456 zero=0
457 miss=0
458 for ros in rosrange:
459 if ros<0:
460 (dmin,dmax) = (drawermin,drawermax)
461 elif ros>4:
463 else:
464 (dmin,dmax) = (drawermin,min(drawermax,TileCalibUtils.getMaxDrawer(ros)))
465 for drawer in range(dmin,dmax):
466 flt = self.getDrawer(ros, drawer, since, False, False)
467 if ros<0 or ros>4:
469 mod = "Comment"
470 else:
471 mod = "CH_"+str(getDrawerIdx(ros,drawer))
472 elif usenames:
473 mod = TileCalibUtils.getDrawerString(ros,drawer)
474 else:
475 mod = str(getDrawerIdx(ros,drawer))
476 if mod not in allmods:
477 allmods[mod] = ""
478 nmod += 1
479 if flt is not None:
480 if flt==0:
481 zero += 1
482 zeromod += " " + mod
483 allmod += " " + mod + "_zero"
484 allmods[mod] += " " + iov + "_zero"
485 else:
486 allmod += " " + mod
487 allmods[mod] += " " + iov
488 else:
489 miss+=1
490 missmod += " " + mod
491 word = 'module' if usenames else 'COOL channel'
492 if miss==0 and nmod>1:
493 alliovs[iov] = " All %s" % plural(nmod,word)
494 elif miss>0 and miss<10:
495 alliovs[iov] = " %s present, %s missing:%s" % (plural(nmod-miss,word),plural(miss,word),missmod)
496 else:
497 alliovs[iov] = "%s ; %s present, %s missing" % (allmod,plural(nmod-miss,word),plural(miss,word))
498 zeroiovs[iov] = (zero,zeromod)
499
500 if (option&1)==1:
501 print("")
502 for key,value in allmods.items():
503 if value=="":
504 value=" None"
505 print("%s\t%s" % (key,value))
506 if (option&2)==2:
507 print("")
508 for key,value in alliovs.items():
509 if value=="":
510 value=" None"
511 if zeroiovs[key] and zeroiovs[key][0]>0:
512 if "_zero" not in value:
513 print("%s\t%s ; zero-sized blobs for %d modules:%s" % (key,value,zeroiovs[key][0],zeroiovs[key][1]))
514 else:
515 print("%s\t%s ; zero-sized blobs for %d modules" % (key,value,zeroiovs[key][0]))
516 else:
517 print("%s\t%s" % (key,value))
518 else:
519 print("\nNo IOVs found")
520
521
522class TileBlobWriterCrest(TileCalibLogger):
523 """
524 TileBlobWriterCrest is a helper class, managing the details of
525 CREST interactions for the user of TileCalibBlobs.
526 """
527
528 #____________________________________________________________________
529 def __init__(self, db, folderPath, calibDrawerType, payload=None):
530 """
531 Input:
532 - db : db should be a database connection
533 - folderPath: full folder path to create or update
534 """
535
536 #=== initialize base class
537 TileCalibLogger.__init__(self, "TileBlobWriter")
538
539 #=== store db
540 self.__db = db
541 self.__folderPath = folderPath
542 self.__payload = payload
543 if payload is not None:
544 return
545
546 #=== create default vectors based on calibDrawerType
547 self.__calibDrawerType = calibDrawerType
548 if calibDrawerType in ['TileCalibDrawerFlt', 'Flt']:
549 self.__TileCalibDrawer = TileCalibDrawerFlt
550 self.__defVec = cppyy.gbl.std.vector('std::vector<float>')()
551 elif calibDrawerType in ['TileCalibDrawerBch', 'Bch']:
552 self.__TileCalibDrawer = TileCalibDrawerBch
553 self.__defVec = cppyy.gbl.std.vector('std::vector<unsigned int>')()
554 elif calibDrawerType in ['TileCalibDrawerInt', 'Int']:
555 self.__TileCalibDrawer = TileCalibDrawerInt
556 self.__defVec = cppyy.gbl.std.vector('std::vector<unsigned int>')()
557 elif calibDrawerType in ['CaloCondBlobFlt', 'CaloFlt']:
558 self.__TileCalibDrawer = cppyy.gbl.CaloCondBlobFlt
559 self.__defVec = cppyy.gbl.std.vector('std::vector<float>')()
560 else:
561 raise Exception("Unknown calibDrawerType: %s" % calibDrawerType)
562
563 # Always all drawers should be written
564 self.__drawerBlob = {drawerIdx:Blob() for drawerIdx in range(0, TileCalibUtils.max_draweridx())}
565 self.__drawer = {}
566 #____________________________________________________________________
567 def register(self, since=(MINRUN,MINLBK), tag="", chan=-1, payload=None):
568 """
569 Registers the folder in the database.
570 - since: lower limit of IOV
571 - tag : The tag to write to
572 - chan : COOL channel to write, if negative - all COOL channels are written
573 Comment channel is always written
574
575 The interpretation of the 'since' inputs depends on their type:
576 - tuple(int,int) : run and lbk number
577 """
578
579 if self.__payload is None and payload is None:
580 jdata = {}
581 for drawerIdx,blob in self.__drawerBlob.items():
582 if chan<0 or drawerIdx==chan or drawerIdx==1000:
583 if blob is None or blob==0:
584 b64string = ''
585 else:
586 blob.seek(0)
587 b64string = str(base64.b64encode(blob.read()), 'ascii')
588 jdata[drawerIdx] = [b64string]
589 else:
590 if payload is not None:
591 self.__payload = payload
592 jdata = self.__payload
593
594 (sinceRun, sinceLumi) = since
595
596 if not self.__db or (self.__db and self.__db.endswith('.json')):
597 # Writting into the json file
598 fullTag = tag
599 if self.__folderPath and not (tag.upper().startswith('TILE') or tag.upper().startswith('CALO')):
600 fullTag = TileCalibUtils.getFullTag(self.__folderPath, tag)
601 fileName = f"{fullTag}.{sinceRun}.{sinceLumi}.json"
602 if self.__db:
603 fileName = f'{self.__db[:-5]}.{fileName}'
604
605 with open(fileName, 'w') as the_file:
606 json.dump(jdata, the_file)
607 the_file.write('\n')
608
609 #=== print info
610 self.log().info( 'Writting tag "%s"', fullTag)
611 self.log().info( '... since : [%s,%s]' , sinceRun, sinceLumi)
612 if self.__payload is None:
613 self.log().info( '... with comment field: "%s"', self.getComment())
614 self.log().info( '... into file : %s' , fileName)
615
616 #____________________________________________________________________
617 def setComment(self, author, comment=None):
618 """
619 Sets a general comment in the comment channel.
620 """
622 commentBlob = self.__drawerBlob.get(drawerIdx, None)
623 if commentBlob:
624 commentBlob.resize(0)
625 else:
626 commentBlob = Blob()
627 self.__drawerBlob[drawerIdx] = commentBlob
628
629 if isinstance(author, tuple) and len(author) == 3:
630 tm = time.mktime(datetime.datetime.strptime(author[2], "%a %b %d %H:%M:%S %Y").timetuple())
631 self.__drawer[drawerIdx] = TileCalibDrawerCmt.getInstance(commentBlob, author[0], author[1], int(tm))
632 else:
633 self.__drawer[drawerIdx] = TileCalibDrawerCmt.getInstance(commentBlob, author, comment)
634
635 #____________________________________________________________________
636 def getComment(self, split=False):
637 """
638 Returns the general comment (default if none is set)
639 """
641 comment = self.__drawer.get(drawerIdx, None)
642 if comment:
643 if split:
644 return (comment.getAuthor(), self.__comment.getComment(), self.__comment.getDate())
645 else:
646 return comment.getFullComment()
647 else:
648 return "<no comment found>"
649
650 #____________________________________________________________________
651 def getDrawer(self, ros, drawer, calibDrawerTemplate=None):
652 """
653 Returns a TileCalibDrawer object of requested type
654 for the given ROS and drawer.
655 """
656
657 try:
658 drawerIdx = getDrawerIdx(ros, drawer)
659 calibDrawer = self.__drawer.get(drawerIdx, None)
660
661 if not calibDrawer:
662 if self.__calibDrawerType in ['CaloCondBlobFlt', 'CaloFlt']:
663 calibDrawer = self.__TileCalibDrawer.getInstance(self.__drawerBlob[drawerIdx])
664 else:
665 calibDrawer = self.__TileCalibDrawer.getInstance(self.__drawerBlob[drawerIdx], self.__defVec,0,0)
666 self.__drawer[drawerIdx] = calibDrawer
667
668 #=== clone if requested
669 if calibDrawerTemplate:
670 calibDrawer.clone(calibDrawerTemplate)
671
672 return calibDrawer
673
674 except Exception as e:
675 self.log().critical( e )
676 return None
677
678 #____________________________________________________________________
679 def zeroBlob(self, ros, drawer):
680 """
681 Resets blob size to zero
682 """
683 try:
684 drawerIdx = getDrawerIdx(ros, drawer)
685 blob = self.__drawerBlob[drawerIdx]
686 blob.resize(0)
687 except Exception as e:
688 self.log().critical( e )
689 return None
690
691
692#____________________________________________________________________
693def getDrawerIdx(ros, drawer):
694 """
695 Calculates TileCalibDrawer index
696 from ros number and drawer number
697 """
698
699 if ros<0 or ros>4:
700 drawerIdx = drawer
701 else:
702 drawerIdx = TileCalibUtils.getDrawerIdx(ros, drawer)
703
704 return drawerIdx
705
706#____________________________________________________________________
707def plural(n, txt):
708 """
709 merges integer number and text
710 and adds 's' at the end of text
711 if n is not equal 1
712 """
713
714 text = f'{n} {txt}'
715 if n!=1:
716 text += 's'
717 return text
const bool debug
void print(char *figname, TCanvas *c1)
#define min(a, b)
Definition cfImp.cxx:40
static const TileCalibDrawerBch * getInstance(const coral::Blob &blob)
Returns a pointer to a const TileCalibDrawerBch.
static const TileCalibDrawerCmt * getInstance(const coral::Blob &blob)
Returns a pointer to a const TileCalibDrawerCmt.
static const TileCalibDrawerFlt * getInstance(const coral::Blob &blob)
Returns a pointer to a const TileCalibDrawerFlt.
static const TileCalibDrawerInt * getInstance(const coral::Blob &blob)
Returns a pointer to a const TileCalibDrawerBch.
static TileCalibDrawerOfc * getInstance(coral::Blob &blob, uint16_t objVersion, uint32_t nSamples, int32_t nPhases, uint16_t nChans, uint16_t nGains, const std::string &author="", const std::string &comment="", uint64_t timeStamp=0)
Returns a pointer to a non-const TileCalibDrawerOfc.
static std::string getClassName(TileCalibType::TYPE type)
Returns the class name.
static std::string getDrawerString(unsigned int ros, unsigned int drawer)
Return the drawer name, e.g.
static unsigned int max_draweridx()
Python compatibility function.
static unsigned int getDrawerIdx(unsigned int ros, unsigned int drawer)
Returns a drawer hash.
static unsigned int getMaxDrawer(unsigned int ros)
Returns the maximal channel number for a given drawer.
static std::string getFullTag(const std::string &folder, const std::string &tag)
Returns the full tag string, composed of camelized folder name and tag part.
static unsigned int getCommentChannel()
Returns the COOL channel number for the comment channel.
getIovs(self, since=(MINRUN, MINLBK), until=(MAXRUN, MAXLBK))
getFolderTag(self, folder, prefix, globalTag, api=None)
getPayload(self, runlumi=None, dbg=False)
__init__(self, db, folder='', tag='', run=None, lumi=0, modmin=0, modmax=275, copyBlob=False)
getDrawer(self, ros, mod, runlumi=None, dbg=False, useDefault=True)
dumpIovs(self, iovList, rosmin, rosmax, drawermin, drawermax, option=1, comment=False, usenames=True)
getComment(self, runlumi=None, split=False)
getBlob(self, ros, mod, runlumi=None, dbg=False)
getDrawer(self, ros, drawer, calibDrawerTemplate=None)
register(self, since=(MINRUN, MINLBK), tag="", chan=-1, payload=None)
setComment(self, author, comment=None)
__init__(self, db, folderPath, calibDrawerType, payload=None)
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition hcg.cxx:130
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177