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-2025 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:8080/api-v5.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 if 'UPD1' in globalTag or 'UPD4' in globalTag or 'COND' not in globalTag:
151 if prefix != '':
152 if globalTag.startswith(prefix) or globalTag.startswith(prefix.upper()):
153 tag=globalTag
154 else:
155 tag=prefix+'-'+globalTag
156 self.log().info("Resolved localTag \'%s\' to folderTag \'%s\'", globalTag,tag)
157 elif folder!='' and not (globalTag.upper().startswith('TILE') or globalTag.upper().startswith('CALO')):
158 tag = TileCalibUtils.getFullTag(folder, globalTag)
159 if tag.startswith('Calo') and 'NoiseCell' not in tag:
160 tag='CALO'+tag[4:]
161 self.log().info("Resolved localTag \'%s\' to folderTag \'%s\'", globalTag,tag)
162 else:
163 tag=globalTag
164 self.log().info("Use localTag \'%s\' as is", tag)
165 else:
166 tag=None
167 if api:
168 tags=api.find_global_tag_map(globalTag)
169 else:
170 tags=self.__api_instance.find_global_tag_map(globalTag)
171 if tags.size==0:
172 raise Exception( "globalTag %s not found" % (globalTag) )
173 else:
174 for i in range(tags.size):
175 t=tags.resources[i].tag_name
176 l=tags.resources[i].label
177 if (prefix!='' and t.startswith(prefix)) or l==folder:
178 tag=t
179 self.log().info("Resolved globalTag \'%s\' to folderTag \'%s\'", globalTag,tag)
180 #taginfo = self.__api_instance.find_tag(name=tag)
181 #print(taginfo)
182 return tag
183
184 #____________________________________________________________________
185 def getIovs(self,since=(MINRUN,MINLBK),until=(MAXRUN,MAXLBK)):
186 if self.__api_instance is None:
187 return [self.__iovList[0][0]]
188 else:
189 run_lumi1=str((since[0]<<32)+since[1]+1)
190 run_lumi2=str((until[0]<<32)+until[1]+1)
191 MAXRUNLUMI1=str(MAXRUNLUMI+1)
192 iovs1=self.__api_instance.select_iovs(self.__tag,"0",run_lumi1,sort='id.since:DESC,id.insertionTime:DESC',size=1,snapshot=0)
193 iovs2=self.__api_instance.select_iovs(self.__tag,run_lumi2,MAXRUNLUMI1,sort='id.since:ASC,id.insertionTime:DESC',size=1,snapshot=0)
194 since1=0 if iovs1.size==0 else iovs1.resources[0].since
195 until1=MAXRUNLUMI if iovs2.size==0 else iovs2.resources[0].since
196 iovs=self.__api_instance.select_iovs(self.__tag,str(since1),str(until1),sort='id.since:ASC,id.insertionTime:DESC',size=999999,snapshot=0)
197 iovList=[]
198 if iovs.size==0:
199 raise Exception( "IOV for tag %s IOV [%s,%s] - (%s,%s) not found" % (self.__tag,since[0],since[1],until[0],until[1]) )
200 else:
201 for i in range(iovs.size):
202 iov=iovs.resources[i]
203 since=int(iov.since)
204 runS=since>>32
205 lumiS=since&0xFFFFFFFF
206 if (runS,lumiS) not in iovList:
207 iovList.append((runS,lumiS))
208 return iovList
209
210 #____________________________________________________________________
211 def getIov(self, option=0):
212 if option!=0:
213 return self.__iov
214 else:
215 return self.__iovList[-1]
216
217 #____________________________________________________________________
218 def __getIov(self,runlumi,dbg=False):
219 if self.__api_instance is None:
220 pass
221 else:
222 run_lumi1=str((runlumi[0]<<32)+runlumi[1]+1)
223 MAXRUNLUMI1=str(MAXRUNLUMI+1)
224 iovs1=self.__api_instance.select_iovs(self.__tag,"0",run_lumi1,sort='id.since:DESC,id.insertionTime:DESC',size=1,snapshot=0)
225 iovs2=self.__api_instance.select_iovs(self.__tag,run_lumi1,MAXRUNLUMI1,sort='id.since:ASC,id.insertionTime:DESC',size=1,snapshot=0)
226 if iovs1.size==0:
227 raise Exception( "IOV for tag %s run,lumi (%s,%s) not found" % (self.__tag,runlumi[0],runlumi[1]) )
228 else:
229 iov=iovs1.resources[0]
230 since=int(iov.since)
231 runS=since>>32
232 lumiS=since&0xFFFFFFFF
233 until=MAXRUNLUMI if iovs2.size==0 else iovs2.resources[0].since
234 runU=until>>32
235 lumiU=until&0xFFFFFFFF
236 hash=iov.payload_hash
237 if dbg:
238 #self.log().info('Run,Lumi (%d,%d)' , runlumi)
239 self.log().info('IOV [%d,%d] - (%d,%d)' , runS,lumiS,runU,lumiU)
240 self.log().info('Insertion time %s' , iov.insertion_time)
241 self.log().info('Hash %s' , hash)
242 payload = self.__api_instance.get_payload(hash=hash).decode('utf-8')
243 jdata=json.loads(payload)
244 #with open("payload.json", 'w') as the_file:
245 # the_file.write(payload)
246 # the_file.write('\n')
247 self.__iovList.append(((runS,lumiS),(runU, lumiU)))
248 self.__iov = self.__runlumi2iov(self.__iovList[-1])
249 if self.__copyBlob:
250 self.payload = jdata
251 return
252 for chan in range(self.__modmin,self.__modmax):
253 try:
254 blob=jdata[str(chan)][0]
255 except Exception:
256 blob=None
257 self.__create_drawer(blob,chan)
258 try:
259 blob=jdata['1000'][0]
260 except Exception:
261 blob=None
262 self.__create_comment(blob)
263 return
264
265 #____________________________________________________________________
266 def __runlumi2iov(self,runlumi):
267 since = (runlumi[0][0]<<32) + runlumi[0][1]
268 until = (runlumi[1][0]<<32) + runlumi[1][1]
269 return (since,until)
270
271 #____________________________________________________________________
272 def __checkIov(self,runlumi):
273 point = (runlumi[0]<<32) + runlumi[1]
274 inrange = point>=self.__iov[0] and point<self.__iov[1]
275 return inrange
276
277 #____________________________________________________________________
278 def __make_blob(self,string):
279 b = Blob()
280 b.write(string)
281 b.seek(0)
282 return b
283
284 #____________________________________________________________________
285 def __create_comment(self,b64string):
286 if b64string is None or len(b64string)==0:
287 if b64string is None:
288 self.__commentBlob = None
289 else:
290 self.__commentBlob = 0
291 self.__comment = None
292 else:
293 blob1 = base64.decodebytes(bytes(b64string,'ascii'))
294 self.__commentBlob = self.__make_blob(blob1)
296 return
297
298 #____________________________________________________________________
299 def __create_drawer(self,b64string,chan):
300 if b64string is None or isinstance(b64string, (int, float)) or len(b64string)==0:
301 if b64string is None:
302 self.__drawerBlob[chan] = None
303 else:
304 self.__drawerBlob[chan] = 0
305 self.__drawer[chan] = None
306 return
307 blob1 = base64.decodebytes(bytes(b64string,'ascii'))
308 self.__drawerBlob[chan] = self.__make_blob(blob1)
310 typeName = TileCalibType.getClassName(cmt.getObjType())
311 del cmt
312 #=== create calibDrawer depending on type
313 if typeName=='TileCalibDrawerFlt':
315 self.log().debug( "typeName = Flt " )
316 elif typeName=='TileCalibDrawerInt':
318 self.log().debug( "typeName = Int " )
319 elif typeName=='TileCalibDrawerBch':
321 self.log().debug( "typeName = Bch " )
322 elif typeName=='TileCalibDrawerOfc':
324 self.log().debug( "typeName = Ofc " )
325 elif typeName=='TileCalibDrawerCmt':
326 self.__drawer[chan] = cppyy.gbl.CaloCondBlobFlt.getInstance(self.__drawerBlob[chan])
327 self.log().debug( "typeName = CaloFlt " )
328 else:
329 self.__drawer[chan] = None
330 self.log().warn("Unknown blob type for chan %d - ignoring", chan)
331 return
332
333 #____________________________________________________________________
334 def getPayload(self, runlumi=None, dbg=False):
335
336 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
337 self.__getIov(runlumi,dbg)
338
339 return self.payload
340
341 #____________________________________________________________________
342 def getBlob(self,ros, mod, runlumi=None, dbg=False):
343
344 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
345 self.__getIov(runlumi,dbg)
346
347 chanNum = getDrawerIdx(ros,mod)
348
349 if (chanNum>=0 and chanNum<len(self.__drawer)):
350 return self.__drawerBlob[chanNum]
351 else:
352 raise Exception( "Invalid drawer requested: %s %s" % (ros,mod) )
353
354 #____________________________________________________________________
355 def getDrawer(self,ros, mod, runlumi=None, dbg=False, useDefault=True):
356
357 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
358 self.__getIov(runlumi,dbg)
359
360 chanNum = getDrawerIdx(ros,mod)
361
362 if (chanNum>=0 and chanNum<len(self.__drawer)):
363 drawer=self.__drawer[chanNum]
364 if not useDefault and drawer is None:
365 if self.__drawerBlob[chanNum] is None:
366 return None
367 else:
368 return 0
369 while drawer is None:
370 #=== no default at all?
371 if ros==0 and drawer==0:
372 raise Exception('No default available')
373 #=== follow default policy
374 ros,mod = self.getDefault(ros,mod)
375 chanNum = getDrawerIdx(ros,mod)
376 drawer=self.__drawer[chanNum]
377 return drawer
378 elif (chanNum == 1000):
379 return self.__comment
380 else:
381 raise Exception( "Invalid drawer requested: %s %s" % (ros,mod) )
382
383 #____________________________________________________________________
384 def getComment(self,runlumi=None,split=False):
385
386 if self.__remote and runlumi is not None and not self.__checkIov(runlumi):
387 self.__getIov(runlumi)
388 if self.__comment is not None:
389 if split:
390 return (self.__comment.getAuthor(),self.__comment.getComment(),self.__comment.getDate())
391 else:
392 return self.__comment.getFullComment()
393 else:
394 return "<no comment found>"
395
396 #____________________________________________________________________
397 def getDefault(self, ros, drawer):
398 """
399 Returns a default drawer number (among first 20 COOL channels) for any drawer in any partition
400 """
401 if ros==0:
402 if drawer<=4 or drawer==12 or drawer>=20:
403 drawer1=0
404 elif drawer<12:
405 drawer1=4
406 else:
407 drawer1=12
408 elif ros==1 or ros==2:
409 drawer1=4
410 elif ros==3:
411 OffsetEBA = [ 0, 0, 0, 0, 0, 0, 3, 2, #// Merged E+1: EBA07; Outer MBTS: EBA08
412 0, 0, 0, 0, 7, 6, 5, 7, #// D+4: EBA13, EBA16; Special D+4: EBA14; Special D+40: EBA15
413 7, 6, 6, 7, 0, 0, 0, 2, #// D+4: EBA17, EBA20; Special D+4: EBA18, EBA19; Outer MBTS: EBA24
414 3, 0, 0, 0, 0, 0, 0, 0, #// Merged E+1: EBA25
415 0, 0, 0, 0, 0, 0, 1, 1, #// Inner MBTS + special C+10: EBA39, EBA40
416 1, 1, 2, 3, 0, 0, 0, 0, #// Inner MBTS + special C+10: EBA41, EBA42; Outer MBTS: EBA43; Merged E+1: EBA44
417 0, 0, 0, 0, 3, 2, 1, 1, #// Merged E+1: EBA53; Outer MBTS: EBA54; Inner MBTS + special C+10: EBA55, EBA56
418 1, 1, 0, 0, 0, 0, 0, 0] #// Inner MBTS + special C+10: EBA57, EBA58
419 drawer1 = 12 + OffsetEBA[drawer]
420 elif ros==4:
421 OffsetEBC = [ 0, 0, 0, 0, 0, 0, 3, 2, #// Merged E-1: EBC07; Outer MBTS: EBC08
422 0, 0, 0, 0, 7, 6, 6, 7, # // D-4: EBC13, EBC16; Special D-4: EBC14, EBC15;
423 7, 5, 6, 7, 0, 0, 0, 2, #// D-4: EBC17, EBC20; Special D-40 EBC18; Special D-4: EBC19; Outer MBTS: EBC24
424 3, 0, 0, 3, 4, 0, 3, 4, #// Merged E-1: EBC25, EBC28, EBC31; E-4': EBC29, EBC32
425 0, 4, 3, 0, 4, 3, 1, 1, #// E-4': EBC34, EBC37; Merged E-1: EBC35, EBC38; Inner MBTS + special C-10: EBC39, EBC40
426 1, 1, 2, 3, 0, 0, 0, 0, #// Inner MBTS + special C-10: EBC41, EBC42; Outer MBTS: EBC43; Merged E-1: EBC44
427 0, 0, 0, 0, 3, 2, 1, 1, #// Merged E-1: EBC53; Outer MBTS: EBC54; Inner MBTS + special C-10: EBC55, EBC56
428 1, 1, 0, 0, 0, 0, 0, 0] #// Inner MBTS + special C-10: EBC57, EBC58
429 drawer1 = 12 + OffsetEBC[drawer]
430 else:
431 drawer1=0
432
433 return (0,drawer1)
434
435 #____________________________________________________________________
436 def dumpIovs(self, iovList, rosmin, rosmax, drawermin, drawermax, option=1, comment=False, usenames=True):
437 """
438 Dumps statistics - how many non-empty modules exists in different IOVs
439 """
440
441 if len(iovList)>0:
442 alliovs={}
443 allmods={}
444 zeroiovs={}
445 nmod=0
446 rosrange=list(range(rosmin,rosmax))
447 if comment:
448 rosrange+=[9999]
449 for since in iovList:
450 iov="(%s,%s)" % since
451 allmod=""
452 missmod=""
453 zeromod=""
454 zero=0
455 miss=0
456 for ros in rosrange:
457 if ros<0:
458 (dmin,dmax) = (drawermin,drawermax)
459 elif ros>4:
461 else:
462 (dmin,dmax) = (drawermin,min(drawermax,TileCalibUtils.getMaxDrawer(ros)))
463 for drawer in range(dmin,dmax):
464 flt = self.getDrawer(ros, drawer, since, False, False)
465 if ros<0 or ros>4:
467 mod = "Comment"
468 else:
469 mod = "CH_"+str(getDrawerIdx(ros,drawer))
470 elif usenames:
471 mod = TileCalibUtils.getDrawerString(ros,drawer)
472 else:
473 mod = str(getDrawerIdx(ros,drawer))
474 if mod not in allmods:
475 allmods[mod] = ""
476 nmod += 1
477 if flt is not None:
478 if flt==0:
479 zero += 1
480 zeromod += " " + mod
481 allmod += " " + mod + "_zero"
482 allmods[mod] += " " + iov + "_zero"
483 else:
484 allmod += " " + mod
485 allmods[mod] += " " + iov
486 else:
487 miss+=1
488 missmod += " " + mod
489 word = 'module' if usenames else 'COOL channel'
490 if miss==0 and nmod>1:
491 alliovs[iov] = " All %s" % plural(nmod,word)
492 elif miss>0 and miss<10:
493 alliovs[iov] = " %s present, %s missing:%s" % (plural(nmod-miss,word),plural(miss,word),missmod)
494 else:
495 alliovs[iov] = "%s ; %s present, %s missing" % (allmod,plural(nmod-miss,word),plural(miss,word))
496 zeroiovs[iov] = (zero,zeromod)
497
498 if (option&1)==1:
499 print("")
500 for key,value in allmods.items():
501 if value=="":
502 value=" None"
503 print("%s\t%s" % (key,value))
504 if (option&2)==2:
505 print("")
506 for key,value in alliovs.items():
507 if value=="":
508 value=" None"
509 if zeroiovs[key] and zeroiovs[key][0]>0:
510 if "_zero" not in value:
511 print("%s\t%s ; zero-sized blobs for %d modules:%s" % (key,value,zeroiovs[key][0],zeroiovs[key][1]))
512 else:
513 print("%s\t%s ; zero-sized blobs for %d modules" % (key,value,zeroiovs[key][0]))
514 else:
515 print("%s\t%s" % (key,value))
516 else:
517 print("\nNo IOVs found")
518
519
520class TileBlobWriterCrest(TileCalibLogger):
521 """
522 TileBlobWriterCrest is a helper class, managing the details of
523 CREST interactions for the user of TileCalibBlobs.
524 """
525
526 #____________________________________________________________________
527 def __init__(self, db, folderPath, calibDrawerType, payload=None):
528 """
529 Input:
530 - db : db should be a database connection
531 - folderPath: full folder path to create or update
532 """
533
534 #=== initialize base class
535 TileCalibLogger.__init__(self, "TileBlobWriter")
536
537 #=== store db
538 self.__db = db
539 self.__folderPath = folderPath
540 self.__payload = payload
541 if payload is not None:
542 return
543
544 #=== create default vectors based on calibDrawerType
545 self.__calibDrawerType = calibDrawerType
546 if calibDrawerType in ['TileCalibDrawerFlt', 'Flt']:
547 self.__TileCalibDrawer = TileCalibDrawerFlt
548 self.__defVec = cppyy.gbl.std.vector('std::vector<float>')()
549 elif calibDrawerType in ['TileCalibDrawerBch', 'Bch']:
550 self.__TileCalibDrawer = TileCalibDrawerBch
551 self.__defVec = cppyy.gbl.std.vector('std::vector<unsigned int>')()
552 elif calibDrawerType in ['TileCalibDrawerInt', 'Int']:
553 self.__TileCalibDrawer = TileCalibDrawerInt
554 self.__defVec = cppyy.gbl.std.vector('std::vector<unsigned int>')()
555 elif calibDrawerType in ['CaloCondBlobFlt', 'CaloFlt']:
556 self.__TileCalibDrawer = cppyy.gbl.CaloCondBlobFlt
557 self.__defVec = cppyy.gbl.std.vector('std::vector<float>')()
558 else:
559 raise Exception("Unknown calibDrawerType: %s" % calibDrawerType)
560
561 # Always all drawers should be written
562 self.__drawerBlob = {drawerIdx:Blob() for drawerIdx in range(0, TileCalibUtils.max_draweridx())}
563 self.__drawer = {}
564 #____________________________________________________________________
565 def register(self, since=(MINRUN,MINLBK), tag="", chan=-1, payload=None):
566 """
567 Registers the folder in the database.
568 - since: lower limit of IOV
569 - tag : The tag to write to
570 - chan : COOL channel to write, if negative - all COOL channels are written
571 Comment channel is always written
572
573 The interpretation of the 'since' inputs depends on their type:
574 - tuple(int,int) : run and lbk number
575 """
576
577 if self.__payload is None and payload is None:
578 jdata = {}
579 for drawerIdx,blob in self.__drawerBlob.items():
580 if chan<0 or drawerIdx==chan or drawerIdx==1000:
581 if blob is None or blob==0:
582 b64string = ''
583 else:
584 blob.seek(0)
585 b64string = str(base64.b64encode(blob.read()), 'ascii')
586 jdata[drawerIdx] = [b64string]
587 else:
588 if payload is not None:
589 self.__payload = payload
590 jdata = self.__payload
591
592 (sinceRun, sinceLumi) = since
593
594 if not self.__db or (self.__db and self.__db.endswith('.json')):
595 # Writting into the json file
596 fullTag = tag
597 if self.__folderPath and not (tag.upper().startswith('TILE') or tag.upper().startswith('CALO')):
598 fullTag = TileCalibUtils.getFullTag(self.__folderPath, tag)
599 fileName = f"{fullTag}.{sinceRun}.{sinceLumi}.json"
600 if self.__db:
601 fileName = f'{self.__db[:-5]}.{fileName}'
602
603 with open(fileName, 'w') as the_file:
604 json.dump(jdata, the_file)
605 the_file.write('\n')
606
607 #=== print info
608 self.log().info( 'Writting tag "%s"', fullTag)
609 self.log().info( '... since : [%s,%s]' , sinceRun, sinceLumi)
610 if self.__payload is None:
611 self.log().info( '... with comment field: "%s"', self.getComment())
612 self.log().info( '... into file : %s' , fileName)
613
614 #____________________________________________________________________
615 def setComment(self, author, comment=None):
616 """
617 Sets a general comment in the comment channel.
618 """
620 commentBlob = self.__drawerBlob.get(drawerIdx, None)
621 if commentBlob:
622 commentBlob.resize(0)
623 else:
624 commentBlob = Blob()
625 self.__drawerBlob[drawerIdx] = commentBlob
626
627 if isinstance(author, tuple) and len(author) == 3:
628 tm = time.mktime(datetime.datetime.strptime(author[2], "%a %b %d %H:%M:%S %Y").timetuple())
629 self.__drawer[drawerIdx] = TileCalibDrawerCmt.getInstance(commentBlob, author[0], author[1], int(tm))
630 else:
631 self.__drawer[drawerIdx] = TileCalibDrawerCmt.getInstance(commentBlob, author, comment)
632
633 #____________________________________________________________________
634 def getComment(self, split=False):
635 """
636 Returns the general comment (default if none is set)
637 """
639 comment = self.__drawer.get(drawerIdx, None)
640 if comment:
641 if split:
642 return (comment.getAuthor(), self.__comment.getComment(), self.__comment.getDate())
643 else:
644 return comment.getFullComment()
645 else:
646 return "<no comment found>"
647
648 #____________________________________________________________________
649 def getDrawer(self, ros, drawer, calibDrawerTemplate=None):
650 """
651 Returns a TileCalibDrawer object of requested type
652 for the given ROS and drawer.
653 """
654
655 try:
656 drawerIdx = getDrawerIdx(ros, drawer)
657 calibDrawer = self.__drawer.get(drawerIdx, None)
658
659 if not calibDrawer:
660 if self.__calibDrawerType in ['CaloCondBlobFlt', 'CaloFlt']:
661 calibDrawer = self.__TileCalibDrawer.getInstance(self.__drawerBlob[drawerIdx])
662 else:
663 calibDrawer = self.__TileCalibDrawer.getInstance(self.__drawerBlob[drawerIdx], self.__defVec,0,0)
664 self.__drawer[drawerIdx] = calibDrawer
665
666 #=== clone if requested
667 if calibDrawerTemplate:
668 calibDrawer.clone(calibDrawerTemplate)
669
670 return calibDrawer
671
672 except Exception as e:
673 self.log().critical( e )
674 return None
675
676 #____________________________________________________________________
677 def zeroBlob(self, ros, drawer):
678 """
679 Resets blob size to zero
680 """
681 try:
682 drawerIdx = getDrawerIdx(ros, drawer)
683 blob = self.__drawerBlob[drawerIdx]
684 blob.resize(0)
685 except Exception as e:
686 self.log().critical( e )
687 return None
688
689
690#____________________________________________________________________
691def getDrawerIdx(ros, drawer):
692 """
693 Calculates TileCalibDrawer index
694 from ros number and drawer number
695 """
696
697 if ros<0 or ros>4:
698 drawerIdx = drawer
699 else:
700 drawerIdx = TileCalibUtils.getDrawerIdx(ros, drawer)
701
702 return drawerIdx
703
704#____________________________________________________________________
705def plural(n, txt):
706 """
707 merges integer number and text
708 and adds 's' at the end of text
709 if n is not equal 1
710 """
711
712 text = f'{n} {txt}'
713 if n!=1:
714 text += 's'
715 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)
setComment(self, author, comment=None)
__init__(self, db, folderPath, calibDrawerType, payload=None)
#define register
Definition dictionary.h:21
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