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