ATLAS Offline Software
Loading...
Searching...
No Matches
LArHVGainsPredictor.py
Go to the documentation of this file.
1# Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
2
3
4from optparse import OptionParser
5
6import PlotCalibrationHV
7
8import PlotCalibrationGains
9
10from PyCool import cool
11
12import time
13
14import sys
15
16import mergeEnergyRamps
17
18import ROOT
19
20import os
21
22
23
25
26 def __init__(self):
27
29 self.UNIX2COOL = 1000000000
30
31 # get database service and open database
32 dbSvc = cool.DatabaseSvcFactory.databaseService()
33
34 dbString = 'oracle://ATLAS_COOLPROD;schema=ATLAS_COOLONL_TRIGGER;dbname=CONDBR2'
35 try:
36 db = dbSvc.openDatabase(dbString, False)
37 except Exception as e:
38 print ('Error: Problem opening database', e)
39 sys.exit(1)
40
41 folder_name = "/TRIGGER/Receivers/Factors/CalibGains"
42 folder=db.getFolder(folder_name)
43
44 startUtime = int(time.time())
45 endUtime = int(time.time())
46 startValKey = startUtime * self.UNIX2COOL
47 endValKey = endUtime * self.UNIX2COOL
48 chsel = cool.ChannelSelection(0,sys.maxint)
49
50 try:
51 itr=folder.browseObjects(startValKey, endValKey, chsel)
52 except Exception as e:
53 print (e)
54 sys.exit(1)
55
56 for row in itr:
57 ReceiverId = hex(int(row.channelId()))
58 payload = row.payload()
59 gain = payload['factor']
60 self.reference_gains[ReceiverId]=gain
61
62 # close database
63 db.closeDatabase()
64
65
66 def getGain(self,ReceiverId):
67
68 if (ReceiverId in self.reference_gains):
69 return float(self.reference_gains[ReceiverId])
70 else:
71 return ''
72
73
75
76 def __init__(self, mapping):
77
78 self.geometry_convertor = mapping
79
80 self.layer_weights_em = {} # per eta bin
81 self.layer_weights_had = {} # per eta bin
82
83 file_name= ROOT.PathResolver.find_calib_file("TrigT1Calo/HVcorrPhysicsWeights_v1.txt")
84
85
86
87 try:
88
89 file = open(file_name)
90
91 except IOError:
92
93 print ("\ncould not find file: %s ....exiting\n" % file_name)
94
95 sys.exit()
96
97 for line in file.readlines():
98
99 parts = line.split()
100
101 self.layer_weights_em [int(parts[0])] = [float(parts[1]),float(parts[2]),float(parts[3]),float(parts[4]),float(parts[5])]
102 self.layer_weights_had[int(parts[0])] = [float(parts[6]),float(parts[7]),float(parts[8]),float(parts[9])]
103
104 file.close()
105
106
107 def GetGain(self, receiver, orig_gain, layer_corr_ref, layer_corr_new, layer_names):
108
109 coolid = self.geometry_convertor.getPPMfromReceiver(receiver)
110
111 eta_bin = self.geometry_convertor.getEtaBin(coolid)
112
113 hv_coef_ref = 0. # ref hv coefficient
114 hv_coef_new = 0. # new hv coefficient
115
116
117
118 if self.geometry_convertor.isCoolEm (coolid):
119
120 is_overlap = self.geometry_convertor.isPPMOverlap(coolid)
121
122
123
124 for n in range(len(layer_names)):
125
126 layer = layer_names[n]
127
129
130 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_em [eta_bin][0]
131 hv_coef_new += layer_corr_new[n] * self.layer_weights_em [eta_bin][0]
132
133 if PlotCalibrationHV.isEmFront(layer,is_overlap):
134
135 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_em [eta_bin][1]
136 hv_coef_new += layer_corr_new[n] * self.layer_weights_em [eta_bin][1]
137
138 if PlotCalibrationHV.isEmMiddle(layer,is_overlap):
139
140 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_em [eta_bin][2]
141 hv_coef_new += layer_corr_new[n] * self.layer_weights_em [eta_bin][2]
142
143 if PlotCalibrationHV.isEmBack(layer,is_overlap):
144
145 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_em [eta_bin][3]
146 hv_coef_new += layer_corr_new[n] * self.layer_weights_em [eta_bin][3]
147
148 if PlotCalibrationHV.isEmOverlapBack(layer,is_overlap):
149
150 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_em [eta_bin][4]
151 hv_coef_new += layer_corr_new[n] * self.layer_weights_em [eta_bin][4]
152
153
154
155 if self.geometry_convertor.isCoolHad(coolid):
156
157 regions = "EmbFcalHighEta" # (?)
158
159
160
161 for n in range(len(layer_names)):
162
163 layer = layer_names[n]
164
165 if PlotCalibrationHV.isHadFirstLayer(layer,regions):
166
167 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_had[eta_bin][0]
168 hv_coef_new += layer_corr_new[n] * self.layer_weights_had[eta_bin][0]
169
170 if PlotCalibrationHV.isHadSecondLayer(layer,regions):
171
172 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_had[eta_bin][1]
173 hv_coef_new += layer_corr_new[n] * self.layer_weights_had[eta_bin][1]
174
175 if PlotCalibrationHV.isHadThirdLayer(layer,regions):
176
177 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_had[eta_bin][2]
178 hv_coef_new += layer_corr_new[n] * self.layer_weights_had[eta_bin][2]
179
180 if PlotCalibrationHV.isHadFourthLayer(layer,regions):
181
182 hv_coef_ref += layer_corr_ref[n] * self.layer_weights_had[eta_bin][3]
183 hv_coef_new += layer_corr_new[n] * self.layer_weights_had[eta_bin][3]
184
185 pred_gain = orig_gain * (hv_coef_new/hv_coef_ref) # predicted gain
186
187 return pred_gain
188
189
190if __name__ == "__main__":
191
192
193
194 parser = OptionParser(add_help_option=False)
195
196 parser.add_option("-n", "--hv_input_new", action = "store", type = "string", dest = "hv_input_new", default = "")
197 parser.add_option("-r", "--hv_input_ref", action = "store", type = "string", dest = "hv_input_ref", default = "")
198 parser.add_option("-t", "--hv_corr_diff", action = "store", type = "float", dest = "hv_corr_diff", default = 0.01)
199 parser.add_option("-c", "--channel_list", action = "store", type = "string", dest = "channel_list", default = "")
200 parser.add_option("-o", "--output_files", action = "store", type = "string", dest = "output_files", default = "gain_updates")
201
202 parser.add_option("-h", "--help", action = "store_true")
203
204 (options, args) = parser.parse_args()
205
206 if options.help: # print helpful info
207
208 print ("\nusage: python LArHVGainsPredictor.py [options]")
209
210 print ("\noptions:\n" )
211
212 print ("-n, --hv_input_new new hv input .sqlite file (see below) (default: '') *")
213 print ("-r, --hv_input_ref ref hv input .sqlite file (see below) (default: '') *")
214 print ("-t, --hv_corr_diff minimum abs. change in hv corrections (default: 0.01)")
215 print ("-c, --channel_list file containing an input channel list (default: '')")
216 print ("-o, --output_files name assigned to all the output files (default: gains_update)")
217
218 print ("\n[*] minimal requirements")
219
220 print ("\nexample: python LArHVGainsPredictor.py -n file_1 -r file_2")
221
222 print ("\nnote: if no input channel list is given all the channels will be considered by default")
223
224 print ("\n(see https://twiki.cern.ch/twiki/bin/save/Atlas/LevelOneCaloGainPredictor for more info)\n")
225
226 sys.exit()
227
228 error_code = 2 # which error code (?)
229
230
231
232 if options.hv_input_new == "" \
233 or options.hv_input_ref == "":
234
235 print ("\ntoo few input arguments given ....exiting (see python LArHVGainsPredictor.py -h for more info)\n")
236
237 sys.exit()
238
239 hv_input_new = PlotCalibrationHV.L1CaloHVReader(options.hv_input_new)
240
241 hv_input_ref = PlotCalibrationHV.L1CaloHVReader(options.hv_input_ref)
242
243 print ("\nreading hv input: %s and hv reference: %s" % (options.hv_input_new, options.hv_input_ref))
244
245
246
248
249 geometry_convertor.LoadReceiverPPMMap()
250
251
252
253 gain_predictor = GainPredictor(geometry_convertor)
254
255
256
257 h_orig_gains_em = PlotCalibrationGains.L1CaloMap("Em: orig. gains"," #eta bin","#phi bin")
258 h_orig_gains_had = PlotCalibrationGains.L1CaloMap("Had: orig. gains"," #eta bin","#phi bin")
259
260 h_pred_gains_em = PlotCalibrationGains.L1CaloMap("Em: pred. gains"," #eta bin","#phi bin")
261 h_pred_gains_had = PlotCalibrationGains.L1CaloMap("Had: pred. gains"," #eta bin","#phi bin")
262
263 h_diff_gains_em = PlotCalibrationGains.L1CaloMap("Em: (pred. gain - orig. gain) / orig. gain","#eta bin","#phi bin")
264 h_diff_gains_had = PlotCalibrationGains.L1CaloMap("Had: (pred. gain - orig. gain) / orig. gain","#eta bin","#phi bin")
265
266
267
268 output_text = open(options.output_files+".txt","w")
269
270
271
272 pred_gains = {}
273
274
275
276 if options.channel_list != "": # from .txt file
277
278 try:
279
280 channel_list = open(options.channel_list)
281
282 except IOError:
283
284 print ("\ncould not find file: %s ....exiting\n" % options.channel_list)
285
286 sys.exit()
287
288 print ("\nreading input channel list from:", options.channel_list)
289
290 orig_gains = {}
291
292 for channel in channel_list.readlines():
293
294 parts = channel.split()
295
296 orig_gains[parts[0]] = float(parts[1])
297
298 channel_list.close()
299
300 receiver_list = orig_gains.keys()
301
302 else: # from oracle database
303
304 print ("\nreading input channel list from oracle database")
305
306 orig_gains = OracleGainReader()
307
308 receiver_list = geometry_convertor.receiver_to_ppm_map.keys()
309
310
311
312 if not receiver_list:
313
314 print ("\ninput channel list is empty ....exiting\n")
315
316 sys.exit()
317
318 print ("\nsearching %s channels for hv correction changes > %s" % (len(receiver_list), options.hv_corr_diff))
319
320
321
322 print ("\npreparing gain updates for the following list of channels:")
323
324 for receiver in receiver_list:
325
326 if receiver not in hv_input_ref.GetNLayers().keys():
327
328 continue # skip this receiver (it's non-LAr)
329
330 coolid = geometry_convertor.getPPMfromReceiver(receiver)
331
332 eta_bin = geometry_convertor.getEtaBin(coolid)
333 phi_bin = geometry_convertor.getPhiBin(coolid)
334
335
336
337 num_layers = (hv_input_ref.GetNLayers())[receiver]
338
339 layer_names = [-1,-1,-1,-1] # default layer names (see... Calorimeter/CaloIdentifier/CaloIdentifier/CaloCell_ID.h)
340
341 if num_layers > 0:
342 layer_names[0] = (hv_input_ref.GetName1()[receiver])
343 if num_layers > 1:
344 layer_names[1] = (hv_input_ref.GetName2()[receiver])
345 if num_layers > 2:
346 layer_names[2] = (hv_input_ref.GetName3()[receiver])
347 if num_layers > 3:
348 layer_names[3] = (hv_input_ref.GetName4()[receiver])
349
350
351
352 layer_corr_new = [1.,1.,1.,1.] # default hv corrections
353
354 if receiver in hv_input_new.GetMeanCorections().keys(): # if mean hv correction > 1
355
356 if num_layers > 0:
357 layer_corr_new[0] = (hv_input_new.GetCorLayer1()[receiver])
358 if num_layers > 1:
359 layer_corr_new[1] = (hv_input_new.GetCorLayer2()[receiver])
360 if num_layers > 2:
361 layer_corr_new[2] = (hv_input_new.GetCorLayer3()[receiver])
362 if num_layers > 3:
363 layer_corr_new[3] = (hv_input_new.GetCorLayer4()[receiver])
364
365
366
367 layer_corr_ref = [1.,1.,1.,1.] # default hv corrections
368
369 if receiver in hv_input_ref.GetMeanCorections().keys(): # if mean hv correction > 1
370
371 if num_layers > 0:
372 layer_corr_ref[0] = (hv_input_ref.GetCorLayer1()[receiver])
373 if num_layers > 1:
374 layer_corr_ref[1] = (hv_input_ref.GetCorLayer2()[receiver])
375 if num_layers > 2:
376 layer_corr_ref[2] = (hv_input_ref.GetCorLayer3()[receiver])
377 if num_layers > 3:
378 layer_corr_ref[3] = (hv_input_ref.GetCorLayer4()[receiver])
379
380
381
382 if abs(layer_corr_new[0] - layer_corr_ref[0]) <= options.hv_corr_diff \
383 and abs(layer_corr_new[1] - layer_corr_ref[1]) <= options.hv_corr_diff \
384 and abs(layer_corr_new[2] - layer_corr_ref[2]) <= options.hv_corr_diff \
385 and abs(layer_corr_new[3] - layer_corr_ref[3]) <= options.hv_corr_diff:
386
387 continue # skip this receiver
388
389
390
391 if options.channel_list != "": # from .txt file
392
393 orig_gain = orig_gains[receiver]
394
395 else: # from oracle database
396
397 orig_gain = orig_gains.getGain(receiver)
398
399
400
401 pred_gain = gain_predictor.GetGain(receiver,orig_gain,layer_corr_ref,layer_corr_new,layer_names)
402
403 if not pred_gains:
404
405 print ("") # just some formatting
406
407 pred_gains[receiver] = [pred_gain, error_code]
408
409 diff_gain = ((pred_gain - orig_gain) / orig_gain) * 100.0 # % change in gain
410
411
412
413 if geometry_convertor.isCoolEm (coolid):
414
415 layer = "EM"
416
417 h_orig_gains_em. Fill(eta_bin,phi_bin,orig_gain)
418 h_pred_gains_em. Fill(eta_bin,phi_bin,pred_gain)
419 h_diff_gains_em. Fill(eta_bin,phi_bin,diff_gain)
420
421 if geometry_convertor.isCoolHad(coolid):
422
423 layer = "HAD"
424
425 h_orig_gains_had.Fill(eta_bin,phi_bin,orig_gain)
426 h_pred_gains_had.Fill(eta_bin,phi_bin,pred_gain)
427 h_diff_gains_had.Fill(eta_bin,phi_bin,diff_gain)
428
429
430
431 print (("%9s %3s %3i %2i %6s %.3f %.3f %6.1f %% %1i") % (coolid, layer, eta_bin, phi_bin, receiver, orig_gain, pred_gain, diff_gain, num_layers), end='')
432
433 print ((" [%s]") % ", ".join("%.3f" % x for x in layer_corr_ref), end='')
434
435 print ((" [%s]") % ", ".join("%.3f" % x for x in layer_corr_new), end='')
436
437 print ((" [%s]") % ", ".join( "%2i" % x for x in layer_names))
438
439
440
441 print (("%6s %.3f %s") % (receiver, pred_gain, " ".join("%.3f" % x for x in layer_corr_new)), file=output_text, end='')
442
443 print ((" # "), file=output_text, end='')
444
445 print (("%9s %3i %2i %3s %.3f") % (coolid, eta_bin, phi_bin, layer, orig_gain), file=output_text, end='')
446
447 print ((" %s") % " ".join("%6.3f" % (layer_corr_new[x] - layer_corr_ref[x]) for x in range (4)), file=output_text)
448
449 output_text.close()
450
451
452
453 mergeEnergyRamps.WriteSqlite(options.output_files+".sqlite",pred_gains)
454
455
456
457 print ("\nrecreating text and ps/pdf files: %s and %s" % (options.output_files+".txt", options.output_files+".ps/pdf"))
458
459 canvas = ROOT.TCanvas("canvas","",200,10,700,500)
460
461 ROOT.gStyle.SetPalette(1)
462 ROOT.gStyle.SetOptStat(111111)
463 ROOT.gStyle.SetCanvasColor(10)
464
465 canvas.Print(options.output_files+".ps[")
466
467 h_orig_gains_em.Draw()
468 canvas.Print(options.output_files+".ps")
469
470 h_orig_gains_had.Draw()
471 canvas.Print(options.output_files+".ps")
472
473 h_pred_gains_em.Draw()
474 canvas.Print(options.output_files+".ps")
475
476 h_pred_gains_had.Draw()
477 canvas.Print(options.output_files+".ps")
478
479 h_diff_gains_em.Draw()
480 canvas.Print(options.output_files+".ps")
481
482 h_diff_gains_had.Draw()
483 canvas.Print(options.output_files+".ps")
484
485 canvas.Print(options.output_files+".ps]")
486
487 os.system("ps2pdf "+options.output_files+".ps")
488
489 print ("\nfinished.... need a drink now!\n")
GetGain(self, receiver, orig_gain, layer_corr_ref, layer_corr_new, 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)
WriteSqlite(name, input_dict)