ATLAS Offline Software
Loading...
Searching...
No Matches
doL1CaloHVCorrections.py
Go to the documentation of this file.
1#!/bin/env python
2
3#
4# Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
5#
6
7
8
9#from ROOT import gRandom,TCanvas,TH1F,TH2F
10import ROOT
11import sys
12import time
13import os
14#from ctypes import *
15
16from PyCool import cool
17from optparse import OptionParser
18
19import PlotCalibrationGains
20import PlotCalibrationHV
21
22
24
25 def __init__(self):
26
28 self.UNIX2COOL = 1000000000
29
30 # get database service and open database
31 dbSvc = cool.DatabaseSvcFactory.databaseService()
32
33 dbString = 'oracle://ATLAS_COOLPROD;schema=ATLAS_COOLONL_TRIGGER;dbname=CONDBR2'
34 try:
35 db = dbSvc.openDatabase(dbString, False)
36 except Exception as e:
37 print ('Error: Problem opening database', e)
38 sys.exit(1)
39
40 folder_name = "/TRIGGER/Receivers/Factors/HVCorrections"
41 folder=db.getFolder(folder_name)
42
43 startUtime = int(time.time())
44 endUtime = int(time.time())
45 startValKey = startUtime * self.UNIX2COOL
46 endValKey = endUtime * self.UNIX2COOL
47 chsel = cool.ChannelSelection(0,sys.maxsize)
48
49 try:
50 itr=folder.browseObjects(startValKey, endValKey, chsel)
51 except Exception as e:
52 print (e)
53 sys.exit(1)
54
55 for row in itr:
56 ReceiverId = hex(int(row.channelId()))
57 payload = row.payload()
58 HVCorrection = payload['factor']
59
60 self.correctionsFromCOOL[ReceiverId] = HVCorrection
61
62 # close database
63 db.closeDatabase()
64
65 def getCorrection(self, receiver):
66
67 return self.correctionsFromCOOL[receiver]
68
70
71 def __init__(self, mapping):
72
73 self.geometry_convertor = mapping
74
75 self.layer_weights_em = {} # per eta bin
76 self.layer_weights_had = {} # per eta bin
77
78 file_name = ROOT.PathResolver.find_calib_file("TrigT1Calo/HVcorrPhysicsWeights_v1.txt")
79
80
81
82 try:
83
84 file = open(file_name)
85
86 except IOError:
87
88 print ("\ncould not find file: %s ....exiting\n" % file_name)
89
90 sys.exit()
91
92 for line in file.readlines():
93
94 parts = line.split()
95
96 self.layer_weights_em [int(parts[0])] = [float(parts[1]),float(parts[2]),float(parts[3]),float(parts[4]),float(parts[5])]
97 self.layer_weights_had[int(parts[0])] = [float(parts[6]),float(parts[7]),float(parts[8]),float(parts[9])]
98
99 file.close()
100
101
102 def GetCorrection(self, receiver, layer_corr, layer_names):
103
104 coolid = self.geometry_convertor.getPPMfromReceiver(receiver)
105
106 eta_bin = self.geometry_convertor.getEtaBin(coolid)
107
108 hv_coef = 0. # new hv coefficient
109 normalisation = 0.
110
111
112
113 if self.geometry_convertor.isCoolEm (coolid):
114
115 is_overlap = self.geometry_convertor.isPPMOverlap(coolid)
116
117
118
119 for n in range(len(layer_names)):
120
121 layer = layer_names[n]
122
124
125 hv_coef += layer_corr[n] * self.layer_weights_em [eta_bin][0]
126 normalisation += self.layer_weights_em [eta_bin][0]
127
128 if PlotCalibrationHV.isEmFront(layer,is_overlap):
129
130 hv_coef += layer_corr[n] * self.layer_weights_em [eta_bin][1]
131 normalisation += self.layer_weights_em [eta_bin][1]
132
133 if PlotCalibrationHV.isEmMiddle(layer,is_overlap):
134
135 hv_coef += layer_corr[n] * self.layer_weights_em [eta_bin][2]
136 normalisation += self.layer_weights_em [eta_bin][2]
137
138 if PlotCalibrationHV.isEmBack(layer,is_overlap):
139
140 hv_coef += layer_corr[n] * self.layer_weights_em [eta_bin][3]
141 normalisation += self.layer_weights_em [eta_bin][3]
142
143 if PlotCalibrationHV.isEmOverlapBack(layer,is_overlap):
144
145 hv_coef += layer_corr[n] * self.layer_weights_em [eta_bin][4]
146 normalisation += self.layer_weights_em [eta_bin][4]
147
148
149
150 if self.geometry_convertor.isCoolHad(coolid):
151
152 regions = "EmbFcalHighEta" # (?)
153
154
155
156 for n in range(len(layer_names)):
157
158 layer = layer_names[n]
159
160 if PlotCalibrationHV.isHadFirstLayer(layer,regions):
161
162 hv_coef += layer_corr[n] * self.layer_weights_had[eta_bin][0]
163 normalisation += self.layer_weights_had[eta_bin][0]
164
165 if PlotCalibrationHV.isHadSecondLayer(layer,regions):
166
167 hv_coef += layer_corr[n] * self.layer_weights_had[eta_bin][1]
168 normalisation += self.layer_weights_had[eta_bin][1]
169
170 if PlotCalibrationHV.isHadThirdLayer(layer,regions):
171
172 hv_coef += layer_corr[n] * self.layer_weights_had[eta_bin][2]
173 normalisation += self.layer_weights_had[eta_bin][2]
174
175 if PlotCalibrationHV.isHadFourthLayer(layer,regions):
176
177 hv_coef += layer_corr[n] * self.layer_weights_had[eta_bin][3]
178 normalisation += self.layer_weights_had[eta_bin][3]
179
180 totalCorrection = hv_coef / normalisation # correction is a weighted sum of layer corrections
181
182 return totalCorrection
183
184def writeHVToSqlite(name,input_dict):
185
186 UNIX2COOL = 1000000000
187
188 dbSvc = cool.DatabaseSvcFactory.databaseService()
189 connectString = 'sqlite://;schema='+name+';dbname=L1CALO'
190
191 print ('\nrecreating database file:',name)
192 dbSvc.dropDatabase( connectString )
193 db = dbSvc.createDatabase( connectString )
194
195 spec = cool.RecordSpecification()
196 spec.extend("factor", cool.StorageType.Float)
197 spec.extend("status", cool.StorageType.UInt32 )
198 folderSpec = cool.FolderSpecification(cool.FolderVersioning.SINGLE_VERSION, spec)
199
200 now = int(time.time())
201
202 since = now*UNIX2COOL
203# since = 0
204# until = sys.maxint
205 until = cool.ValidityKeyMax
206 db.createFolderSet('/TRIGGER')
207 db.createFolderSet('/TRIGGER/Receivers')
208 db.createFolderSet('/TRIGGER/Receivers/Factors')
209
210 folder_description = '<timeStamp>time</timeStamp><addrHeader><address_header service_type="71" clid="1238547719"/></addrHeader><typeName>CondAttrListCollection</typeName>'
211 f = db.createFolder( "/TRIGGER/Receivers/Factors/HVCorrections", folderSpec, folder_description)
212
213 print (" Now creating sqlite file for ", len(list(input_dict.keys())), " channels")
214 for i in list(input_dict.keys()):
215 data = cool.Record( spec )
216 data['factor'] = input_dict[i][0]
217 data['status'] = input_dict[i][1]
218 f.storeObject(since,until, data, int(i,16) )
219
220 db.closeDatabase()
221
222
223if __name__ == "__main__":
224
225 print (" Starting script for calculating L1Calo HV corrections")
226
227
228
229 parser = OptionParser(add_help_option=False)
230
231 parser.add_option("-i", "--hv_input", action = "store", type = "string", dest = "hv_input", default = "")
232 parser.add_option("-t", "--hv_corr_diff", action = "store", type = "float", dest = "hv_corr_diff", default = 0.01)
233 parser.add_option("-c", "--channel_list", action = "store", type = "string", dest = "channel_list", default = "")
234 parser.add_option("-o", "--output_files", action = "store", type = "string", dest = "output_files", default = "doL1CaloHVCorrections")
235
236 parser.add_option("--noFCAL", action = "store_true", dest = "noFCAL", default = False)
237 parser.add_option("--noFCAL23",action = "store_true", dest = "noFCAL23", default = False)
238
239 parser.add_option("-h", "--help", action = "store_true")
240
241 (options, args) = parser.parse_args()
242
243 if options.help: # print helpful info
244
245 print ("\nusage: python doL1CaloHVCorrections.py [options]")
246
247 print ("\noptions:\n" )
248
249 print ("-i, --hv_input hv input .sqlite file (default: '') *")
250 print ("-t, --hv_corr_diff minimum abs. change in hv corrections (default: 0.01)")
251 print ("-c, --channel_list file containing an input channel list (default: '')")
252 print ("-o, --output_files name assigned to all the output files (default: doL1CaloHVCorrections)")
253 print ("--noFCAL receiver channels in FCAL not considered")
254 print ("--noFCAL23 receiver channels in hadronic FCAL (FCAL23) not considered")
255
256
257 print ("\n[*] minimal requirements")
258
259 print ("\nexample: python doL1CaloHVCorrections.py -i file_1 ")
260
261 print ("\nnote: if no input channel list is given all the channels will be considered by default")
262
263 print ("\n(see https://twiki.cern.ch/twiki/bin/save/Atlas/LevelOneCaloGainPredictor for more info)\n")
264
265 sys.exit()
266
267 if options.hv_input == "" :
268 print ("\ntoo few input arguments given ....exiting , need at least sqlite file with input HV corrections\n")
269
270 sys.exit()
271
272# root-y stuff
273
274 ROOT.gStyle.SetPalette(1)
275 ROOT.gStyle.SetOptStat(111111)
276 ROOT.gStyle.SetCanvasColor(10)
277
278 c1 = ROOT.TCanvas('c1','Example',200,10,700,500)
279
280 h_corrEmb_em = PlotCalibrationGains.L1CaloMap("Calculated HV corrections for EM (EMB in overlap) ","#eta bin","#phi bin")
281 h_corrFcalLowEta_had = PlotCalibrationGains.L1CaloMap("Calculated HV corrections for HAD (FCAL low #eta)","#eta bin","#phi bin")
282
283 h_corrEmec_em = PlotCalibrationGains.L1CaloMap("Calculated HV corrections for EM overlap (EMEC)","#eta bin","#phi bin")
284 h_corrFcalHighEta_had = PlotCalibrationGains.L1CaloMap("Calculated HV corrections for HAD FCAL (high #eta)","#eta bin","#phi bin")
285#
286 h_RefcorrEmb_em = PlotCalibrationGains.L1CaloMap("Reference HV corrections for EM (EMB in overlap) ","#eta bin","#phi bin")
287 h_RefcorrFcalLowEta_had = PlotCalibrationGains.L1CaloMap("Reference HV corrections for HAD (FCAL low #eta)","#eta bin","#phi bin")
288
289 h_RefcorrEmec_em = PlotCalibrationGains.L1CaloMap("Reference HV corrections for EM overlap (EMEC)","#eta bin","#phi bin")
290 h_RefcorrFcalHighEta_had = PlotCalibrationGains.L1CaloMap("Reference HV corrections for HAD FCAL (high #eta)","#eta bin","#phi bin")
291#
292 h_DiffcorrEmb_em = PlotCalibrationGains.L1CaloMap("(calculated-reference) HV corrections for EM (EMB in overlap) ","#eta bin","#phi bin")
293 h_DiffcorrFcalLowEta_had = PlotCalibrationGains.L1CaloMap("(calculated-reference) HV corrections for HAD (FCAL low #eta)","#eta bin","#phi bin")
294
295 h_DiffcorrEmec_em = PlotCalibrationGains.L1CaloMap("(calculated-reference) HV corrections for EM overlap (EMEC)","#eta bin","#phi bin")
296 h_DiffcorrFcalHighEta_had = PlotCalibrationGains.L1CaloMap("(calculated-reference) HV corrections for HAD FCAL (high #eta)","#eta bin","#phi bin")
297#
298
299 hv_input = PlotCalibrationHV.L1CaloHVReader(options.hv_input)
300
301 referenceCorrectionReader = HVCorrectionCOOLReader()
302
304 geometry_convertor.LoadReceiverPPMMap()
305
306 correctionCalculator = HVCorrectionCalculator(geometry_convertor)
307
308
309
310 print ("Creating output file", options.output_files+".txt")
311 output_text = open(options.output_files+".txt","w")
312
313
314 # now loop over receivers, either those in the list, or all of them
315
316 if options.channel_list != "": # from .txt file
317
318 try:
319
320 channel_list = open(options.channel_list)
321
322 except IOError:
323
324 print ("\ncould not find file: %s ....exiting\n" % options.channel_list)
325
326 sys.exit()
327
328 print ("\nreading input channel list from:", options.channel_list)
329
330 receiver_list = []
331
332 for channel in channel_list.readlines():
333
334 parts = channel.split()
335 receiver_list.append(parts[0])
336
337 channel_list.close()
338
339 else: # from oracle database
340
341 print ("\nreading input channel list from oracle database")
342
343 receiver_list = list(geometry_convertor.receiver_to_ppm_map.keys())
344
345
346
347 if not receiver_list:
348
349 print ("\ninput channel list is empty ....exiting\n")
350
351 sys.exit()
352
353 print ("\nsearching %s channels for hv correction changes, at least one layer > %s" % (len(receiver_list), options.hv_corr_diff))
354
355
356
357 calculatedCorrections = {}
358
359 for receiver in receiver_list:
360
361 if receiver not in list(hv_input.GetNLayers().keys()):
362
363 continue # skip this receiver (it's non-LAr)
364
365
366 coolid = geometry_convertor.getPPMfromReceiver(receiver)
367
368 eta_bin = geometry_convertor.getEtaBin(coolid)
369 phi_bin = geometry_convertor.getPhiBin(coolid)
370
371 if options.noFCAL and geometry_convertor.isPPMFCAL(coolid):
372 continue # skip this receiver (it's non-LAr)
373
374 if options.noFCAL23 and geometry_convertor.isPPMFCAL(coolid) and geometry_convertor.isCoolHad(coolid):
375 continue # skip this receiver (it's non-LAr)
376
377
378
379 num_layers = (hv_input.GetNLayers())[receiver]
380
381 layer_names = [-1,-1,-1,-1] # default layer names (see... Calorimeter/CaloIdentifier/CaloIdentifier/CaloCell_ID.h)
382
383 if num_layers > 0:
384 layer_names[0] = (hv_input.GetName1()[receiver])
385 if num_layers > 1:
386 layer_names[1] = (hv_input.GetName2()[receiver])
387 if num_layers > 2:
388 layer_names[2] = (hv_input.GetName3()[receiver])
389 if num_layers > 3:
390 layer_names[3] = (hv_input.GetName4()[receiver])
391
392
393
394 layer_corr = [1.,1.,1.,1.] # default hv corrections
395
396 if receiver in list(hv_input.GetMeanCorections().keys()): # if mean hv correction > 1
397
398 if num_layers > 0:
399 layer_corr[0] = (hv_input.GetCorLayer1()[receiver])
400 if num_layers > 1:
401 layer_corr[1] = (hv_input.GetCorLayer2()[receiver])
402 if num_layers > 2:
403 layer_corr[2] = (hv_input.GetCorLayer3()[receiver])
404 if num_layers > 3:
405 layer_corr[3] = (hv_input.GetCorLayer4()[receiver])
406
407
408
409 predictedCorrection = correctionCalculator.GetCorrection(receiver, layer_corr, layer_names)
410 referenceCorrection = referenceCorrectionReader.getCorrection(receiver)
411
412 correctionDifference = (predictedCorrection-referenceCorrection)
413
414# print ("predictedCorrection=", predictedCorrection, " referenceCorrection=", referenceCorrection)
415
416 if abs(correctionDifference) <= options.hv_corr_diff: # we update only towers that changed
417 continue # skip this receiver, the correction is not high enough
418
419 calculatedCorrections[receiver] = [predictedCorrection,0]
420 print (("%5s %9s %3i %2i %.3f (%.3f)") % (receiver, coolid, eta_bin, phi_bin, predictedCorrection,referenceCorrection), file=output_text)
421
422
423 if geometry_convertor.isCoolEm(coolid):
424 if not geometry_convertor.isPPMOverlap(coolid):
425 h_corrEmb_em.Fill(eta_bin,phi_bin,predictedCorrection)
426 h_RefcorrEmb_em.Fill(eta_bin,phi_bin,referenceCorrection)
427 h_DiffcorrEmb_em.Fill(eta_bin,phi_bin,correctionDifference)
428 else:
429 if geometry_convertor.getOverlapLayer(receiver)=='EMB':
430 h_corrEmb_em.Fill(eta_bin,phi_bin,predictedCorrection)
431 h_RefcorrEmb_em.Fill(eta_bin,phi_bin,referenceCorrection)
432 h_DiffcorrEmb_em.Fill(eta_bin,phi_bin,correctionDifference)
433 else:
434 h_corrEmec_em.Fill(eta_bin,phi_bin,predictedCorrection)
435 h_RefcorrEmec_em.Fill(eta_bin,phi_bin,referenceCorrection)
436 h_DiffcorrEmec_em.Fill(eta_bin,phi_bin,correctionDifference)
437
438
439 if geometry_convertor.isCoolHad(coolid):
440 if not geometry_convertor.isPPMFCAL(coolid):
441 h_corrFcalLowEta_had.Fill(eta_bin,phi_bin,predictedCorrection)
442 h_RefcorrFcalLowEta_had.Fill(eta_bin,phi_bin,referenceCorrection)
443 h_DiffcorrFcalLowEta_had.Fill(eta_bin,phi_bin,correctionDifference)
444 else:
445 if geometry_convertor.getFCAL23RecEta(receiver)=='HighEta':
446 h_corrFcalHighEta_had.Fill(eta_bin,phi_bin,predictedCorrection)
447 h_RefcorrFcalHighEta_had.Fill(eta_bin,phi_bin,referenceCorrection)
448 h_DiffcorrFcalHighEta_had.Fill(eta_bin,phi_bin,correctionDifference)
449 else:
450 h_corrFcalLowEta_had.Fill(eta_bin,phi_bin,predictedCorrection)
451 h_RefcorrFcalLowEta_had.Fill(eta_bin,phi_bin,referenceCorrection)
452 h_DiffcorrFcalLowEta_had.Fill(eta_bin,phi_bin,correctionDifference)
453
454 writeHVToSqlite(options.output_files+".sqlite",calculatedCorrections)
455 output_text.close()
456
457 # Draw mean corrections
458
459 h_corrEmb_em.SetMinimum(1.)
460 h_corrEmb_em.SetMaximum(2.1)
461 h_corrEmb_em.Draw()
462 c1.Print(options.output_files+".ps(")
463
464 h_corrFcalLowEta_had.SetMinimum(1.)
465 h_corrFcalLowEta_had.SetMaximum(2.1)
466 h_corrFcalLowEta_had.Draw()
467 c1.Print(options.output_files+".ps")
468
469
470 h_corrEmec_em.SetMinimum(1.)
471 h_corrEmec_em.SetMaximum(2.1)
472 h_corrEmec_em.Draw()
473 c1.Print(options.output_files+".ps")
474
475 h_corrFcalHighEta_had.SetMinimum(1.)
476 h_corrFcalHighEta_had.SetMaximum(2.1)
477 h_corrFcalHighEta_had.Draw()
478 c1.Print(options.output_files+".ps")
479
480 # Now corrections from COOL
481
482 h_RefcorrEmb_em.SetMinimum(1.)
483 h_RefcorrEmb_em.SetMaximum(2.1)
484 h_RefcorrEmb_em.Draw()
485 c1.Print(options.output_files+".ps")
486
487 h_RefcorrFcalLowEta_had.SetMinimum(1.)
488 h_RefcorrFcalLowEta_had.SetMaximum(2.1)
489 h_RefcorrFcalLowEta_had.Draw()
490 c1.Print(options.output_files+".ps")
491
492
493 h_RefcorrEmec_em.SetMinimum(1.)
494 h_RefcorrEmec_em.SetMaximum(2.1)
495 h_RefcorrEmec_em.Draw()
496 c1.Print(options.output_files+".ps")
497
498 h_RefcorrFcalHighEta_had.SetMinimum(1.)
499 h_RefcorrFcalHighEta_had.SetMaximum(2.1)
500 h_RefcorrFcalHighEta_had.Draw()
501 c1.Print(options.output_files+".ps")
502
503 # Now difference
504 h_DiffcorrEmb_em.SetMinimum(-0.1)
505 h_DiffcorrEmb_em.SetMaximum(0.1)
506 h_DiffcorrEmb_em.Draw()
507 c1.Print(options.output_files+".ps")
508
509 h_DiffcorrFcalLowEta_had.SetMinimum(-0.1)
510 h_DiffcorrFcalLowEta_had.SetMaximum(0.1)
511 h_DiffcorrFcalLowEta_had.Draw()
512 c1.Print(options.output_files+".ps")
513
514
515 h_DiffcorrEmec_em.SetMinimum(-0.1)
516 h_DiffcorrEmec_em.SetMaximum(0.1)
517 h_DiffcorrEmec_em.Draw()
518 c1.Print(options.output_files+".ps")
519
520 h_DiffcorrFcalHighEta_had.SetMinimum(-0.1)
521 h_DiffcorrFcalHighEta_had.SetMaximum(0.1)
522 h_DiffcorrFcalHighEta_had.Draw()
523 c1.Print(options.output_files+".ps)")
524#
525 os.system("ps2pdf " + options.output_files+".ps")
526 # os.system("cp HVStatus.pdf /home/jb/public_web/tmp ")
527
528
529 print ("Done!")
530
531
GetCorrection(self, receiver, layer_corr, layer_names)
isEmMiddle(layerName, isOverlap)
isEmBack(layerName, isOverlap)
isHadFirstLayer(layerName, TT_part)
isHadSecondLayer(layerName, TT_part)
isEmFront(layerName, isOverlap)
isHadThirdLayer(layerName, TT_part)
isHadFourthLayer(layerName, TT_part)
isEmOverlapBack(layerName, isOverlap)
writeHVToSqlite(name, input_dict)