15import getopt,sys,os,re,bisect
16os.environ[
'TERM'] =
'linux'
19 print (
"Usage: ",sys.argv[0],
" [OPTION] ... ")
20 print (
"Updates Cell Noise database using new values from ASCII file")
22 print (
"-h, --help shows this help")
23 print (
"-i, --inschema= specify name of input JSON file or CREST_SERVER_PATH")
24 print (
"-o, --outschema= specify name of output JSON file, default is CaloNoise.json")
25 print (
"-t, --tag= specify the input tag")
26 print (
"-T, --outtag= specify the output tag if different from input tag")
27 print (
"-f, --folder= specify status folder to use e.g. /TILE/OFL02/NOISE/CELL")
28 print (
"-x, --txtfile= specify the text file with the new noise constants")
29 print (
"-r, --run= specify run number for start of IOV")
30 print (
"-l, --lumi= specify lumiblock number for start of IOV, default is 0")
31 print (
"-b, --begin= specify run number of first iov in multi-iov mode, by default uses very first iov")
32 print (
"-e, --end= specify run number of last iov in multi-iov mode, by default uses latest iov")
33 print (
"-L, --endlumi= specify lumi block number for last iov in multi-iov mode, default is 0")
34 print (
"-A, --adjust in multi-iov mode adjust iov boundaries to nearest iov available in DB, default is False")
35 print (
"-c, --comment= specify comment which should be written to DB, in multi-iov mode it is appended to old comment")
36 print (
"-C, --Comment= specify comment which should be written to DB, in mutli-iov mode it overwrites old comment")
37 print (
"-U, --user= specify username for comment")
38 print (
"-n, --channel= specify COOL channel to use (48 by defalt)")
39 print (
"-s, --scale= specify scale factor for all the fields except ratio field")
40 print (
"--scaleElec= specify separate scale factor for all electronic noise fields except ratio field")
41 print (
"if run number and lumiblock number are omitted - all IOVs from input file are updated")
43letters =
"hi:o:t:T:f:x:r:l:b:e:L:A:c:C:U:n:s:"
44keywords = [
"help",
"inschema=",
"outschema=",
"tag=",
"outtag=",
"folder=",
"txtfile=",
"run=",
"lumi=",
"begin=",
"end=",
"endlumi=",
"adjust",
45 "channel=",
"scale=",
"scaleA=",
"scaleB=",
"scaleD=",
"scaleE=",
"scaleD4=",
"scaleC10=",
"scaleD4sp=",
"scaleC10sp=",
"scaleElec=",
46 "comment=",
"Comment=",
"user=",
"intag=",
"infile=",
"outfile="]
49 opts, extraparams = getopt.getopt(sys.argv[1:],letters,keywords)
50except getopt.GetoptError
as err:
57outSchema =
'CaloNoise.json'
60folderPath =
'/TILE/OFL02/NOISE/CELL'
91 if o
in (
"-i",
"--inschema",
"--infile"):
93 elif o
in (
"-o",
"--outschema",
"--outfile"):
95 elif o
in (
"-t",
"--tag",
"--intag"):
97 elif o
in (
"-T",
"--outtag"):
99 elif o
in (
"-f",
"--folder"):
101 elif o
in (
"-r",
"--run"):
105 elif o
in (
"-l",
"--lumi"):
107 elif o
in (
"-b",
"--begin"):
110 elif o
in (
"-e",
"--end"):
112 elif o
in (
"-L",
"--endlumi"):
114 elif o
in (
"-A",
"--adjust"):
116 elif o
in (
"-u",
"--update"):
118 elif o
in (
"-n",
"--channel"):
120 elif o
in (
"-s",
"--scale"):
122 elif o
in (
"-s",
"--scaleA"):
124 elif o
in (
"-s",
"--scaleB"):
126 elif o
in (
"-s",
"--scaleD"):
128 elif o
in (
"-s",
"--scaleE"):
130 elif o
in (
"-s",
"--scaleD4"):
132 elif o
in (
"-s",
"--scaleC10"):
134 elif o
in (
"-s",
"--scaleD4sp"):
136 elif o
in (
"-s",
"--scaleC10sp"):
137 scaleC10sp = float(a)
138 elif o
in (
"-s",
"--scaleElec"):
140 elif o
in (
"-x",
"--txtfile"):
142 elif o
in (
"-c",
"--comment"):
144 elif o
in (
"-C",
"--Comment"):
147 elif o
in (
"-U",
"--user"):
149 elif o
in (
"-h",
"--help"):
193 scaleC10sp = scaleC10
199inputIsFile = os.path.isfile(inSchema)
200inTagIsFullTag = (inTag.upper().startswith(
'TILE')
or inTag.upper().startswith(
'CALO')
or inTag.upper().startswith(
"LAR"))
203outTagIsFullTag = (outTag.upper().startswith(
'TILE')
or outTag.upper().startswith(
'CALO')
or outTag.upper().startswith(
"LAR"))
205 print(
"Please, provide inschema (e.g. --inschema=CaloNoise.json or --inschema=CREST)")
208 print(
"Please, provide outschema (e.g. --outschema=CaloNoise.json)")
211 if len(folderPath)<1
and not inTagIsFullTag:
212 print(
"Please, provide folder (e.g. --folder=/TILE/OFL02/NOISE/CELL)")
215 print(
"Please, provide tag (e.g. --tag=RUN2-UPD4-34 or --tag=TileOfl02NoiseCell-RUN2-UPD4-34)")
218 print(
"Please, provide outtag (e.g. --tag=RUN2-UPD4-35 --outtag=TileOfl02NoiseCell-RUN2-UPD4-35)")
220if not outTagIsFullTag:
222 print(
"Please, provide full outtag (e.g. --outtag=TileOfl02NoiseCell-RUN2-UPD4-35)")
224 elif len(folderPath)<1:
225 print(
"Please, provide folder (e.g. --folder=/TILE/OFL02/NOISE/CELL)")
230from TileCalibBlobPython
import TileCalibLogger
231from TileCalibBlobPython
import TileCalibCrest
232from TileCalibBlobPython
import TileCellTools
235log = TileCalibLogger.getLogger(
"WriteCellNoise")
238 log.setLevel(logging.INFO)
240 log.setLevel(logging.DEBUG)
264hashMgrDef=TileCellTools.TileCellHashMgr(cabling=cabling)
265hashMgrA=TileCellTools.TileCellHashMgr(
"UpgradeA")
266hashMgrBC=TileCellTools.TileCellHashMgr(
"UpgradeBC")
267hashMgrABC=TileCellTools.TileCellHashMgr(
"UpgradeABC")
271until = (TileCalibCrest.MAXRUN,TileCalibCrest.MAXLBK)
272if end >= TileCalibCrest.MAXRUN:
273 end = TileCalibCrest.MAXRUN
274 endlumi = TileCalibCrest.MAXLBK
281 log.info(
"Initializing folder %s with tag %s", inFolder, inTag)
282reader = TileCalibCrest.TileBlobReaderCrest(inSchema,inFolder,inTag)
283blob = reader.getBlob(-1,chan,(end,endlumi),
False)
285 log.critical(
"Could not locate a data blob in CREST payload for COOL channel %s", chan)
288if not outTagIsFullTag
and not inputIsFile :
290 outTag = reader.getTag()
292 outTag = reader.getFolderTag(folderPath,
None,outTag)
295 iovList = reader.getIovs()
301 ib=bisect.bisect(iovList,since)-1
304 if iovList[ib] != since:
307 log.info(
"Moving beginning of first IOV with new cell noise from (%d,%d) to (%d,%d)" , beg,lumi,since[0],since[1])
310 log.info(
"Creating new IOV starting from (%d,%d) with new cell noise" , beg,lumi)
317 log.info(
"Next IOV with old cell noise starts from (%d,%d)" , until[0],until[1])
320 ie=bisect.bisect_left(iovList,until)
324 if iovList[ie] != until:
327 log.info(
"Moving end of last IOV from (%d,%d) to (%d,%d)" , end,endlumi,until[0],until[1])
329 log.info(
"Keeping end of last IOV at (%d,%d) - new IOV is shorter than IOV in input DB" , end,endlumi)
332 iovList = iovList[ib:ie]
333 iovUntil = iovList[1:] + [until]
336 log.info(
"IOVs: %s" , str(iovList))
337 log.info(
"%d IOVs in total, end of last IOV is %s" , ie-ib,str(until))
339 if Comment
is None and len(comment)>0:
344 print(
"Please, provide run number at command line")
347 log.info(
"Creating single IOV starting from run,lumi %d,%d" , run,lumi)
349 until = (end, endlumi)
365 with open(txtFile,
"r")
as f:
366 cellDataText = f.readlines()
368 print(
"\nCan not read input file %s" % (txtFile))
371 for line
in cellDataText:
376 if fields[0].startswith(
"#"):
379 if fields[0][:1].isalpha():
381 if useNames
is not None and not useNames:
382 print(
"Mixture of formats in inpyt file %s - useNames" % (txtFile))
385 if fields[0]==
'Cell':
386 if useModuleNames
is not None and useModuleNames:
387 print(
"Mixture of formats in inpyt file %s - useModuleNames" % (txtFile))
393 if useModuleNames
is not None and not useModuleNames:
394 print(
"Mixture of formats in inpyt file %s - useModuleNames" % (txtFile))
399 if fields[2].isdigit():
400 if useGain
is not None and not useGain:
401 print(
"Mixture of formats in inpyt file %s - useGain" % (txtFile))
411 if useGain
is not None and useGain:
412 print(
"Mixture of formats in inpyt file %s - useGain" % (txtFile))
415 print(
"Too many fields in input file %s" % (txtFile))
419 noise = [-1]+fields[2:]
423 if cellName.startswith(
'BC'):
424 cellName=
'B'+cellName[2:]
425 if not (
'+' in cellName
or '-' in cellName
or '*' in cellName):
426 p = re.search(
"\\d", cellName).start()
427 cellPos = modName+cellName[:p] +
'+' + cellName[p:]
428 cellNeg = modName+cellName[:p] +
'-' + cellName[p:]
429 dictKey = (cellPos,gain)
430 cellData[dictKey] = noise
431 dictKey = (cellNeg,gain)
432 cellData[dictKey] = noise
433 if (cellName==
'spE1'):
434 for cellNm
in [
'mbE+1',
'mbE-1',
'e4E+1',
'e4E-1']:
435 cellN = modName+cellNm
436 dictKey = (cellN,gain)
437 if dictKey
not in cellData:
438 cellData[dictKey] = noise
440 cellN = modName+cellName
441 dictKey = (cellN,gain)
442 cellData[dictKey] = noise
443 if (cellName==
'spE+1'):
444 for cellNm
in [
'mbE+1',
'e4E+1']:
445 cellN = modName+cellNm
446 dictKey = (cellN,gain)
447 if dictKey
not in cellData:
448 cellData[dictKey] = noise
449 if (cellName==
'spE-1'):
450 for cellNm
in [
'mbE-1',
'e4E-1']:
451 cellN = modName+cellNm
452 dictKey = (cellN,gain)
453 if dictKey
not in cellData:
454 cellData[dictKey] = noise
457 if useNames
is not None and useNames:
458 print(
"Mixture of formats in input file %s - useNames" % (txtFile))
461 cellHash = int(fields[0])
462 cellGain = int(fields[1])
464 dictKey = (cellHash,cellGain)
465 cellData[dictKey] = noise
466 if icell[gain]<cellHash:
478 log.info(
"No input txt file provided, making copy from input DB to output DB")
485 modName=
"LAr %2d" % chan
490for io,since
in enumerate(iovList):
500 log.info(
"Updating IOV [%d,%d] - [%d,%d)" , sinceRun, sinceLum, untilRun, untilLum)
502 blobR = reader.getDrawer(-1,chan,(sinceRun,sinceLum),
False,
False)
505 mcell=blobR.getNChans()
506 mgain=blobR.getNGains()
507 mval=blobR.getObjSizeUint32()
509 log.info(
"input file: ncell: %d ngain %d nval %d" ,
max(icell), igain, ival)
510 log.info(
"input db: ncell: %d ngain %d nval %d" , mcell, mgain, mval)
518 log.info(
"output db: ncell: %d ngain %d nval %d" , ncell, ngain, nval)
520 if ncell>hashMgrA.getHashMax():
522 elif ncell>hashMgrBC.getHashMax():
524 elif ncell>hashMgrDef.getHashMax():
528 log.info(
"Using %s CellMgr with hashMax %d" , hashMgr.getGeometry(),hashMgr.getHashMax())
530 GainDefVec = cppyy.gbl.std.vector(
'float')()
531 for val
in range(nval):
532 GainDefVec.push_back(0.0)
533 defVec = cppyy.gbl.std.vector(
'std::vector<float>')()
534 for gain
in range(ngain):
535 defVec.push_back(GainDefVec)
538 writer = TileCalibCrest.TileBlobWriterCrest(outSchema,folderPath,
'CaloFlt')
539 blobW = writer.getDrawer(-1,chan)
540 blobW.init(defVec,ncell,1)
542 src = [
'Default',
'DB',
'File',
'Scale']
551 for cell
in range(ncell):
552 exist0 = (cell<mcell)
554 (modName,cellName)=hashMgr.getNames(cell)
555 fullName=
"%s %6s" % (modName,cellName)
556 for gain
in range(ngain):
557 exist1 = (exist0
and (gain<mgain))
564 dictKey = (modName+cellName,gn)
566 dictKey = (cellName,gn)
568 dictKey = (cell, gain)
569 noise = cellData.get(dictKey,[])
571 for field
in range(nval):
572 exist = (exist1
and (field<mval))
573 value = GainDefVec[field]
575 strval=str(noise[field])
576 if strval.startswith(
"*"):
577 coef=float(strval[1:])
578 value = blobR.getData(cell,gain,field)*coef
579 elif strval.startswith(
"++")
or strval.startswith(
"+-") :
580 coef=float(strval[1:])
581 value = blobR.getData(cell,gain,field)+coef
582 elif strval==
"keep" or strval==
"None":
585 value = float(strval)
586 if (value
is None or value<0)
and exist:
587 value = blobR.getData(cell,gain,field)
591 value = blobR.getData(cell,gain,field)
593 if field==1
or field>4:
594 if 'spC' in cellName:
596 elif 'spD' in cellName:
598 elif 'C' in cellName
and '10' in cellName:
600 elif 'D' in cellName
and '4' in cellName:
602 elif 'E' in cellName:
604 elif 'D' in cellName:
606 elif 'B' in cellName:
608 elif 'A' in cellName:
615 src[exist] =
"ScalePileUp %s" % str(sc)
616 elif field<4
and scaleElec>0.0:
619 src[exist] =
"ScaleElec %s" % str(scaleElec)
621 blobW.setData( cell, gain, field, value )
622 if rescale
or exist>1:
623 print (
"%s hash %4d gain %d field %d value %f Source %s" % (fullName, cell, gain, field, value, src[exist]))
624 except Exception
as e:
625 log.warning(
"Exception on IOV [%d,%d]-[%d,%d)" , sinceRun, sinceLum, untilRun, untilLum)
626 print (FullName,
"Cell",cell,
"gain",gain,
"field",field,
"value",strval,
"noise vector",noise)
630 author =
"<no comment found>"
634 elif comment ==
"keep":
635 author = reader.getComment(since,
True)
637 if author ==
"<no comment found>":
639 if comment
and comment!=
"keep":
643 comm =
"Update for run,lumi %i,%i from file %s" % (sinceRun,sinceLum,txtFile)
645 comm =
"Update for run %i from file %s" % (sinceRun,txtFile)
646 comm1 = reader.getComment(since)
647 if comm1
and comm1 !=
"<no comment found>" and iov:
648 comm +=
" // " + comm1
649 writer.setComment(author,comm)
650 writer.register((sinceRun,sinceLum), outTag, chan)
652log.info(
"Using %s CellMgr with hashMax %d" , hashMgr.getGeometry(),hashMgr.getHashMax())
void print(char *figname, TCanvas *c1)
std::vector< std::string > split(const std::string &s, const std::string &t=":")