ATLAS Offline Software
DeMoScan.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 # Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration
3 # Author : Benjamin Trocme (CNRS/IN2P3 - LPSC Grenoble) - 2017 - 2023
4 # Python 3 migration by Miaoran Lu (University of Iowa)- 2022
5 #
6 # Displays the run affected per defect type
7 # Perform run by run differences for difference tags
8 #
9 # Documentation: https://twiki.cern.ch/twiki/bin/viewauth/Atlas/DataQualityDemo
10 
11 
12 import os,sys
13 from math import fabs
14 from re import match
15 from time import strftime,localtime
16 
17 from ROOT import TFile
18 from ROOT import TH1F
19 from ROOT import TCanvas
20 from ROOT import kTeal
21 from ROOT import gStyle,gROOT,gPad
22 gROOT.SetBatch(False)
23 
24 sys.path.append("/afs/cern.ch/user/l/larmon/public/prod/Misc")
25 from LArMonCoolLib import GetReadyFlag
26 from DeMoLib import strLumi,initializeMonitoredDefects,retrieveYearTagProperties,MakeTH1,SetXLabel,MakeLegend,returnPeriod
27 
28 global debug
29 debug = False
30 #debug = True
31 
32 
35 import os,sys
36 
37 from argparse import RawTextHelpFormatter,ArgumentParser
38 
39 from DQDefects import DefectsDB
40 
41 parser = ArgumentParser(description='',formatter_class=RawTextHelpFormatter)
42 parser.add_argument('-y','--year',dest='parser_year',default = ["2022"],nargs='*',help='Year [Default: 2022]',action='store')
43 parser.add_argument('-t','--tag',dest='parser_tag',default = ["AtlasReady"],nargs='*',help='Defect tag [Default: "AtlasReady"]',action='store')
44 parser.add_argument('-s','--system',dest='parser_system',default="LAr",help='System: LAr, CaloCP [Default: "LAr"]',action='store')
45 parser.add_argument('-d','--directory',dest='parser_directory',default=".",help='Directory to display',action='store')
46 parser.add_argument('-b','--batch',dest='parser_batchMode',help='Batch mode',action='store_true')
47 parser.add_argument('--run',type=int,dest='parser_run',help='Run or run range (relevant only for lossPerRun)',nargs='*',action='store')
48 parser.add_argument('--defect',type=str,dest='parser_defect',default="",help='Defect to consider (if not specified: all)',action='store')
49 parser.add_argument('--veto',type=str,dest='parser_veto',default="",help='Veto to consider (if not specified: all)',action='store')
50 parser.add_argument('--noRecovPlot',dest='parser_noRecovPlot',help='Do not plot the recoverable histograms',action='store_false')
51 parser.add_argument('--lossPerRun',dest='parser_plotLPR',help='Plot the loss run and per type',action='store_true')
52 parser.add_argument('--diffTwoTags',dest='parser_diff2tags',help='Compare run by run the data losses for two tags (same year necessary)',action='store_true')
53 parser.add_argument('--restrictTagRuns',dest='parser_restrictTagRuns',help='In diffTwotags, restrict comparison to runs considered in this tag',action='store')
54 parser.add_argument('--minLumi',type=float,dest='parser_minLumiLPR',default = 0.,help='Minimal lumi loss (in pb-1) to consider a run in year stats per defect',action='store')
55 parser.add_argument('--retrieveComments',dest='parser_retrieveComments',help='Retrieve comments from the defect DB',action='store_true')
56 parser.add_argument('--recapDefects',dest='parser_recapDefects',help='',action='store_true')
57 parser.add_argument('--prepareReproc',dest='parser_reproc',help='Prepare a txt file to be updated for reprocessing signoff with recoverable defect',action='store_true')
58 
59 args = parser.parse_args()
60 
61 parser.print_help()
62 
63 if args.parser_batchMode:
64  gROOT.SetBatch(True)
65 
66 yearTagProperties = {}
67 partitions = {}
68 grlDef = {}
69 defectVeto = {}
70 veto = {}
71 signOff = {}
72 initializeMonitoredDefects(args.parser_system,partitions,grlDef,defectVeto,veto,signOff,args.parser_year[0],args.parser_tag[0])
73 
74 yearTagList = []
75 yearTagDir = {}
76 yearTagTag = {}
77 
78 for iYear in args.parser_year:
79  for iTag in args.parser_tag:
80  directory = "%s/YearStats-%s/%s/%s"%(args.parser_directory,args.parser_system,iYear,iTag)
81  if os.path.exists(directory):
82  yearTagProperties[iTag] = retrieveYearTagProperties(iYear,iTag)
83  yearTag = "%s%s"%(iYear,yearTagProperties[iTag]["Description"])
84  yearTagList.append(yearTag)
85  yearTagDir[yearTag] = directory
86  yearTagTag[yearTag] = iTag # Used only to retrieve comments
87 
88 if len(args.parser_year) == 1:
89  singleYear = True
90 else:
91  singleYear = False
92  if (options['plotDiff2tags']):
93  print("To compare two tags, you must choose only one year. Exiting...")
94  sys.exit()
95 
96 if (len(args.parser_year) != 1 and len(args.parser_tag) != 1 and options['recapDefects']):
97  print("To recap defects, you must choose only one year and tag. Exiting...")
98  sys.exit()
99 
100 yearTagList.sort()
101 
102 if len(yearTagList) == 0:
103  print("No year / tag matching - Please check YearStats directory")
104  sys.exit()
105 
106 options = {}
107 options['defect'] = [args.parser_defect]
108 options['veto'] = [args.parser_veto]
109 if options['defect'] == [""] and options['veto'] == [""]:
110  options['defect'] = grlDef["intol"]+grlDef["tol"]
111  options['veto'] = veto["all"]
112 else:
113  if options['defect'][0] not in (grlDef["intol"]+grlDef["tol"]) and options['veto'][0] not in veto["all"]:
114  print("Defect/veto not found. Please check...")
115  print("Defect: ",grlDef["intol"])
116  print("Veto: ",veto["all"])
117  sys.exit()
118  if options['defect'] == [""]:
119  options['defect'] = []
120  if options['veto'] == [""]:
121  options['veto'] = []
122 
123 defVetoType = {}
124 for iDefVeto in options['defect']+options['veto']:
125  if iDefVeto in options['defect']:
126  if (iDefVeto in grlDef["intol"]):
127  defVetoType[iDefVeto] = "Intolerable defect"
128  else:
129  defVetoType[iDefVeto] = "Tolerable defect"
130  else:
131  defVetoType[iDefVeto] = "Veto"
132 
133 
134 options['recovPlot'] = args.parser_noRecovPlot
135 options['plotLossPerRun'] = args.parser_plotLPR
136 options['plotDiff2tags'] = args.parser_diff2tags
137 options['restrictTagRuns'] = args.parser_restrictTagRuns
138 options['recapDefects'] = args.parser_recapDefects
139 options['prepareReproc'] = args.parser_reproc
140 runsFilter = []
141 # If runs filter is requested, look for the runs of the chosen year/tag
142 if (options['plotDiff2tags'] and options['restrictTagRuns'] in list(yearTagProperties.keys()) and "%s%s"%(args.parser_year[0],yearTagProperties[options['restrictTagRuns']]["Description"]) in yearTagList): #if requested, restrict the runs to be considered to the one of the tag option
143  fRuns = open("%s/runs-ALL.dat"%yearTagDir["%s%s"%(args.parser_year[0],yearTagProperties[options['restrictTagRuns']]["Description"])])
144  for iline in fRuns.readlines():
145  runWithoutPeriod = int(iline.split(" (")[0])
146  runsFilter.append(runWithoutPeriod)
147  fRuns.close()
148  print("I am considering only the %d runs of %s"%(len(runsFilter),options['restrictTagRuns']))
149  print(runsFilter)
150 
151 options['minLumiYearStatsDefect'] = args.parser_minLumiLPR
152 options['retrieveComments'] = args.parser_retrieveComments
153 
154 if options['recapDefects']:
155  options['plotLossPerRun'] = True
156  options['retrieveComments'] = True
157 
158 if options['prepareReproc']:
159  options['plotLossPerRun'] = True
160  options['retrieveComments'] = True
161 
162 if options['retrieveComments']:
163  defRecap = {}
164  defRecapHtml = {}
165  for iDef in options['defect']:
166  defRecap[iDef] = "\n\n===== Recap for %s================================================================================================================================\n"%(iDef.ljust(15))
167  defRecap[iDef] += "Description: %s - %s\n"%(defectVeto["description"][iDef],defVetoType[iDef])
168  if (defVetoType[iDef] == "Intolerable defect"):
169  defRecap[iDef] +=" Run| Period| Tot lumi|Lost lumi|Recov. L.| LB range | Author | "
170  else:
171  defRecap[iDef] +=" Run| Period| Tot lumi|Aff. lumi|Recov. L.| LB range | Author | "
172 
173  if (defVetoType[iDef] == "Intolerable defect"):
174  defRecapHtml[iDef] ='<tr class="out0intolerable" id="%s-%s-%s"> <th colspan="8"> %s - LUMILOSTTOBEREPLACED affected </th></tr>'%(iDef,args.parser_year[0],args.parser_tag[0],iDef)
175  defRecapHtml[iDef] +='<tr class="out0intolerable"> <th colspan="8"> Description: %s - %s</th></tr>'%(defectVeto["description"][iDef],defVetoType[iDef])
176  defRecapHtml[iDef] +='<tr class="out0"> <th> Run </th><th> Period </th><th> Tot lumi </th><th> Lost lumi </th><th> Recov. L. </th><th> LB range </th><th> Author </th><th> Comment </th></tr> '
177  else:
178  defRecapHtml[iDef] ='<tr class="out0tolerable" id="%s-%s-%s"> <th colspan="8"> %s - LUMILOSTTOBEREPLACED affected </th></tr>'%(iDef,args.parser_year[0],args.parser_tag[0],iDef)
179  defRecapHtml[iDef] +='<tr class="out0tolerable"> <th colspan="8"> Description: %s - %s</th></tr>'%(defectVeto["description"][iDef],defVetoType[iDef])
180  defRecapHtml[iDef] +='<tr class="out0"> <th> Run </th><th> Period </th><th> Tot lumi </th><th> Aff. lumi </th><th> Recov. L. </th><th> LB range </th><th> Author </th><th> Comment </th></tr> '
181 
182 if options['prepareReproc']:
183  defReproc = {}
184  for iDef in options['defect']:
185  defReproc[iDef] = ""
186 
187 if args.parser_run:
188  options['runMinLossPerRun'] = min(args.parser_run)
189  options['runMaxLossPerRun'] = max(args.parser_run)
190 else:
191  options['runMinLossPerRun'] = 0
192  options['runMaxLossPerRun'] = 1e9
193 
194 gStyle.SetOptStat(0)
195 
196 canvasResults = {}
197 legendResults = {}
198 stackResults = {}
199 file = {}
200 
201 h1Period_IntLuminosity = {}
202 subperiodNb = {}
203 runsLPR = {}
204 lossLPR = {}
205 loss_rLPR = {}
206 h1_lossLPR = {}
207 h1_loss_rLPR = {}
208 
209 atlasReady = {}
210 
211 for iYT in yearTagList:
212  print("I am treating the following year/tag:%s"%iYT)
213 
214  canvasResults[iYT] = {}
215  legendResults[iYT] = {}
216  stackResults[iYT] = {}
217 
218  # Open the Archive filename to compare the luminosity of each period
219  if options['plotDiff2tags']:
220  yearStatsArchiveFilename = '%s/TProfiles.root'%(yearTagDir[iYT])
221  if not (os.path.exists(yearStatsArchiveFilename)):
222  print("No %s found - > Skipping"%yearStatsArchiveFilename)
223  continue
224 
225  file[iYT] = TFile(yearStatsArchiveFilename)
226  h1Period_IntLuminosity[iYT] = file[iYT].Get("h1Period_IntLuminosity_archive")
227  subperiodNb[iYT] = h1Period_IntLuminosity[iYT].GetNbinsX()
228 
229  if options['plotLossPerRun'] or options['plotDiff2tags']:
230  runsLPR[iYT] = {}
231  lossLPR[iYT] = {}
232  loss_rLPR[iYT] = {}
233  h1_lossLPR[iYT] = {}
234  h1_loss_rLPR[iYT] = {}
235  # Loop on defect+veto (all or single ones)
236  for iDefVeto in options['defect']+options['veto']:
237 
238  # Define the file name containing the loss per run for this defect
239  if "defect" in defVetoType[iDefVeto]:
240  lossFileName = "%s/loss-%s.dat"%(yearTagDir[iYT],iDefVeto)
241  xAxisTitle = "#splitline{Luminosity loss due to}{%s [pb^{-1}]}"%(defectVeto["description"][iDefVeto])
242  if defVetoType[iDefVeto] == "Intolerable defect":
243  color = defectVeto["color"][iDefVeto]
244  else:
245  color = kTeal
246  else:
247  lossFileName = "%s/loss-%sVETO.dat"%(yearTagDir[iYT],iDefVeto)
248  xAxisTitle = "Luminosity loss due to %s[Veto] [pb^{-1}]"%(defectVeto["description"][iDefVeto])
249  color = defectVeto["color"][iDefVeto]
250 
251  # Check if a dat loss file is associated to this veto/defect
252  if os.path.exists(lossFileName):
253  print("I am reading the %s file"%lossFileName)
254  runsLPR[iYT][iDefVeto] = []
255  lossLPR[iYT][iDefVeto] = []
256  loss_rLPR[iYT][iDefVeto] = []
257  f2 = open(lossFileName,'r')
258  tmpLines = f2.readlines()
259  tmpLines.sort()
260  for iline in tmpLines: # Loop on all lines of the loss-[defect/veto].dat files
261  if defVetoType[iDefVeto] == "Intolerable defect":
262  read = match("(\d+) \‍((\d+) ub-1.*\‍) -> (\d+.\d+) pb-1 \D+(\d+.\d+)\D+",iline)
263  else:# Veto loss is never recoverable (not tolerable defects)
264  read = match("(\d+) \‍((\d+) ub-1.*\‍) -> (\d+.\d+) pb-1",iline)
265  # retrieve the run number
266  runnumber = int(read.group(1))
267  # If the runs filter is activated (i.e. runsFilter != 0), check if the runs must be filtered
268  if (len(runsFilter) != 0 and runnumber not in runsFilter):
269  continue
270  if runnumber == 451936: # 29/6/2023: hack by B.Trocme to avoid a crash for a run w/o period assigned
271  continue
272  # retrieve the total luminosity and the lost luminosity
273  luminosity = int(read.group(2))
274  lostLumi = float(read.group(3))
275  # If defect, look for potential recoverable luminosity
276  if defVetoType[iDefVeto] == "Intolerable defect":
277  recovLumi = float(read.group(4))
278  else: # Veto loss is never recoverable
279  recovLumi = 0.
280  if runnumber not in list(atlasReady.keys()):
281  atlasready_tmp=GetReadyFlag(runnumber)
282  atlasReady[runnumber] = []
283  for lb in list(atlasready_tmp.keys()):
284  if atlasready_tmp[lb]>0: atlasReady[runnumber] += [lb]
285 
286  # if the loss is above the required minimum (0 by default), store it
287  if (runnumber>options['runMinLossPerRun'] and runnumber<=options['runMaxLossPerRun'] and lostLumi > options['minLumiYearStatsDefect']): #uncomment this for real runs!!
288  runsLPR[iYT][iDefVeto].append(runnumber)
289  lossLPR[iYT][iDefVeto].append(lostLumi)
290  loss_rLPR[iYT][iDefVeto].append(recovLumi)
291  if options['retrieveComments'] and "defect" in defVetoType[iDefVeto]: # retrieve comments for defects
292  print("@%d"%(runnumber))
293  db = DefectsDB(tag=yearTagProperties[yearTagTag[iYT]]["Defect tag"])
294  system_defects = []
295  for iPrefix in grlDef["prefix"]:
296  system_defects += [d for d in (db.defect_names | db.virtual_defect_names) if (d.startswith(iPrefix) and iDefVeto in d)]
297  defects = db.retrieve((runnumber, 1), (runnumber+1, 0), system_defects)
298  defectCompact = {}
299  for defect in defects:
300  if ("SEVNOISEBURST" in defect.channel and ("HEC" in defect.channel or "FCAL" in defect.channel)): # LAr only : Skip the HEC/FCAL SEVNOISEBURST defect as they also appear in EMEC
301  continue
302  for iDef in options['defect']:
303  if (defect.channel.endswith(iDef) or # NB : some problem may arise from this incomplete test (if similar name for 2 defects) but there is a protection later when recaping
304  "EGAMMA_%s"%iDef in defect.channel): # So far, EGamma is the only system with a defect name ending with the partition (and not the generic DeMo defect name)
305  defectSinceLumiAtlasReady = -1
306  defectUntilLumiAtlasReady = -1
307  for iLumiBlock in range(defect.since.lumi,min(defect.until.lumi,max(atlasReady[runnumber])+1)):
308  if iLumiBlock in atlasReady[runnumber]:
309  defectUntilLumiAtlasReady = iLumiBlock+1
310  if defectSinceLumiAtlasReady == -1:
311  defectSinceLumiAtlasReady = iLumiBlock
312  if defectSinceLumiAtlasReady == -1: # Whole defect was outside ATLAS ready - Skip it
313  continue
314 
315  if defectSinceLumiAtlasReady == defectUntilLumiAtlasReady-1:
316  lbRange = "%10d"%(defectSinceLumiAtlasReady)
317  lbRangeReproc = defectSinceLumiAtlasReady
318  else:
319  lbRange = "%4d->%4d"%(defectSinceLumiAtlasReady,defectUntilLumiAtlasReady-1)
320  lbRangeReproc = "%d-%d"%(defectSinceLumiAtlasReady,defectUntilLumiAtlasReady-1)
321  cleanedDefect = ((defect.comment).replace('\xd7','')).replace('\xb5','').replace('\xe9','').replace('\u2013','').replace('\u03b7','').replace('\u03c6','').replace('\u2014','')
322  if ("\n %d |"%runnumber not in defRecap[iDef]):
323  # This "replace" is a dirty hack due to bad unicode in defect comment in run 355995/LAr
324  # You may need to add some others if you observe a crash...
325 
326  runperiod = returnPeriod(runnumber,args.parser_system,args.parser_year[0],args.parser_tag[0])
327  defRecap[iDef] += "\n %d |%s|%s|%s|%s|%s |%s| %s"%(runnumber,runperiod.rjust(7),strLumi(luminosity,"ub",False).rjust(9),(strLumi(lostLumi,"pb",False)).rjust(9),(strLumi(recovLumi,"pb",False)).rjust(9),lbRange,defect.user.rjust(12),cleanedDefect)
328  defRecapHtml[iDef] += '<tr class="out1"><th> %d </th> <th> %s </th> <th> %s </th><th> %s </th><th> %s </th><th> %s </th><th> %s </th><th> %s </th><tr>'%(runnumber,runperiod,strLumi(luminosity,"ub",False).rjust(9),(strLumi(lostLumi,"pb",False)).rjust(9),(strLumi(recovLumi,"pb",False)).rjust(9),lbRange,defect.user.rjust(12),cleanedDefect)
329  if (options['prepareReproc'] and recovLumi>0.):
330  defReproc[iDef] += "\n@%d"%runnumber
331  else:
332  defRecap[iDef] += "\n ---------------------------------------------|%s |%s| %s"%(lbRange,defect.user.rjust(12),cleanedDefect)
333  defRecapHtml[iDef] += '<tr class="out1"><th colspan="5"><th> %s </th><th> %s </th><th> %s </th><tr>'%(lbRange,defect.user.rjust(12),cleanedDefect)
334  for iPart in ["EMBA","EMBC","EMECA","EMECC","HECA","HECC","FCALA","FCALC"]:
335  if iPart in defect.channel and "SEVNOISEBURST" not in defect.channel: # Add the affected partition (except for SEVNOISEBURST, where the comment should contain it)
336  defRecap[iDef] += " - %s"%iPart
337 
338  if (options['prepareReproc'] and defect.recoverable):
339  defReproc[iDef] += "\n%s %s G/R # [Originally set by %s:%s] Now fixed/irrecoverable"%(defect.channel,lbRangeReproc,defect.user,cleanedDefect)
340  if ("SEVNOISEBURST" in defect.channel and "EMEC" in defect.channel):
341  defReproc[iDef] += "\n%s %s G/R # [Originally set by %s:%s] Now fixed/irrecoverable"%(defect.channel.replace("EMEC","HEC"),lbRangeReproc,defect.user,cleanedDefect)
342  defReproc[iDef] += "\n%s %s G/R # [Originally set by %s:%s] Now fixed/irrecoverable"%(defect.channel.replace("EMEC","FCAL"),lbRangeReproc,defect.user,cleanedDefect)
343 
344  f2.close()
345 
346  # if no loss found or if only diff2tags, stop the loop
347  if (len(runsLPR[iYT][iDefVeto]) == 0 or not options['plotLossPerRun']): continue
348 
349  # If loss found, create histogram to display them for the restricted run with a loss
350  h1_lossLPR[iYT][iDefVeto] = MakeTH1("h1_lossLPR_%s_%s"%(iYT,iDefVeto),"Run Number",xAxisTitle,-0.5,-0.5+len(runsLPR[iYT][iDefVeto]),len(runsLPR[iYT][iDefVeto]),color)
351  for iX in range(1,h1_lossLPR[iYT][iDefVeto].GetNbinsX()+1):
352  h1_lossLPR[iYT][iDefVeto].GetXaxis().SetBinLabel(iX,"%d"%runsLPR[iYT][iDefVeto][iX-1])
353 
354  if defVetoType[iDefVeto] == "Intolerable defect": # recoverable loss for defect
355  h1_loss_rLPR[iYT][iDefVeto] = MakeTH1("h1_loss_rLPR_%s_%s"%(iYT,iDefVeto),"Run Number",xAxisTitle,-0.5,-0.5+len(runsLPR[iYT][iDefVeto]),len(runsLPR[iYT][iDefVeto]),kTeal-7)
356 
357  # Fill the new histogram(s)
358  for irun in range(len(runsLPR[iYT][iDefVeto])):
359  h1_lossLPR[iYT][iDefVeto].Fill(irun,lossLPR[iYT][iDefVeto][irun])
360  if defVetoType[iDefVeto] == "Intolerable defect":
361  h1_loss_rLPR[iYT][iDefVeto].Fill(irun,loss_rLPR[iYT][iDefVeto][irun])
362 
363  # Display the new histograms
364  index = "LPR_%s"%iDefVeto
365  canvasResults[iYT][index] = TCanvas("cLPR_%s_%s"%(iYT,iDefVeto),"%s (only run losses >%.1f pb-1)"%(xAxisTitle,options['minLumiYearStatsDefect']), 200, 10, 1200, 500)
366  canvasResults[iYT][index].SetGridy(1)
367  h1_lossLPR[iYT][iDefVeto].SetTitle("")
368  h1_lossLPR[iYT][iDefVeto].SetMinimum(0.)
369  h1_lossLPR[iYT][iDefVeto].Draw("HIST")
370  if (options['recovPlot'] and defVetoType[iDefVeto] == "Intolerable defect"):
371  h1_lossLPR[iYT][iDefVeto].Draw("HIST SAME")
372  legendResults[iYT][index] = MakeLegend(0.855,0.75,0.95,0.95)
373  legendResults[iYT][index].SetHeader("%s"%iYT)
374  legendResults[iYT][index].AddEntry(h1_lossLPR[iYT][iDefVeto],"Total:%s"%(strLumi(h1_lossLPR[iYT][iDefVeto].Integral(),"pb^{-1}")),"f")
375  if (options['recovPlot'] and defVetoType[iDefVeto] == "Intolerable defect"):
376  legendResults[iYT][index].AddEntry(h1_lossLPR[iYT][iDefVeto],"Recov:%s"%(strLumi(h1_loss_rLPR[iYT][iDefVeto].Integral(),"pb^{-1}")),"f")
377  legendResults[iYT][index].Draw()
378 
379 # Enf of comment recap
380 if options['plotLossPerRun'] and options['retrieveComments']:
381  f = open("%s/YearStats-%s/%s/%s/recapDefects.txt"%(args.parser_directory,args.parser_system,args.parser_year[0],args.parser_tag[0]),'w')
382  fHtml = open("%s/YearStats-%s/%s/%s/recapDefects.html"%(args.parser_directory,args.parser_system,args.parser_year[0],args.parser_tag[0]),'w')
383  fHtml.write('<table class="report">')
384  fHtml.write('<tr class="out0"> <th width="60pix"></th><th width="60pix"></th><th width="80pix"></th></th><th width="80pix"></th><th width="80pix"></th><th width="80pix"></th><th width="100pix"></th><th></th></tr>')
385  fHtml.write('<tr class="out0"> <th colspan="8"> Recap generated on %s </th></tr>'%(strftime("%a, %d %b %Y %H:%M", localtime())))
386  if options['prepareReproc']:
387  fReproc = open("YearStats-%s/%s/%s/defectsForReproc.txt"%(args.parser_system,args.parser_year[0],args.parser_tag[0]),'w')
388 
389  defTocHtml = '<div style="text-align:left" class="rectangle">'
390  for iDef in options['defect']:
391  if (iDef in list(h1_lossLPR[iYT].keys())): # This protection is needed as defRecap may have duplication in some rare cases. See Muon system with "MDT_ROD_PROBLEM_1" and "RPC_PROBLEM_1"
392  if ("b-1" in defRecap[iDef]):# At least one data loss in the whole YearStats for this defect
393  defTocHtml += "Direct link to <a href='#%s-%s-%s' target='_self'> %s </a> (%s - %s affected) <br>"%(iDef,args.parser_year[0],args.parser_tag[0],iDef,defVetoType[iDef],strLumi(h1_lossLPR[iYT][iDef].Integral(),"pb^{-1}"))
394  defTocHtml += '</div>'
395 
396  fHtml.write(defTocHtml)
397  for iDef in options['defect']:
398  if (iDef in list(h1_lossLPR[iYT].keys())): # This protection is needed as defRecap may have duplication in some rare cases. See Muon system with "MDT_ROD_PROBLEM_1" and "RPC_PROBLEM_1"
399  if ("b-1" in defRecap[iDef]):# At least one data loss in the whole YearStats for this defect
400  print(defRecap[iDef])
401  f.write(defRecap[iDef])
402  fHtml.write("%s</tr>"%defRecapHtml[iDef].replace("LUMILOSTTOBEREPLACED",strLumi(h1_lossLPR[iYT][iDef].Integral(),"pb^{-1}")))
403  if options['prepareReproc']:
404  fReproc.write(defReproc[iDef])
405 
406  f.close()
407  fHtml.write('</table>')
408  fHtml.close()
409  if options['prepareReproc']:
410  fReproc.close()
411 
412 # Compare defects/veto run by run (if the year is the same for both)
413 if (len(yearTagList) == 2 and options['plotDiff2tags'] and singleYear):
414  print("I am now comparing run by run the defects and their affected luminosity")
415 
416  # First basic check about the datasets used in both tags
417  YT0 = yearTagList[0]
418  YT1 = yearTagList[1]
419  if (subperiodNb[YT0] != subperiodNb[YT1]):
420  print("Warning : different number of subperiods...")
421  else:
422  for iBin in range(subperiodNb[YT0]):
423  if (h1Period_IntLuminosity[YT0].GetBinContent(iBin) != h1Period_IntLuminosity[YT1].GetBinContent(iBin)):
424  print("Warning : different luminosities in bin %s/%s: %f vs %f"%(h1Period_IntLuminosity[YT0].GetXaxis().GetBinLabel(iBin),h1Period_IntLuminosity[YT1].GetXaxis().GetBinLabel(iBin),h1Period_IntLuminosity[YT0].GetBinContent(iBin),h1Period_IntLuminosity[YT1].GetBinContent(iBin)))
425 
426  runs_diff2tags = {}
427  lumi_diff2tags = {}
428  suffixList = ["miss_%s"%yearTagList[0],"miss_%s"%yearTagList[1],"diff"]
429  suffixTitle = {"miss_%s"%yearTagList[0]:"No loss in %s"%yearTagList[0],"miss_%s"%yearTagList[1]:"No loss in %s"%yearTagList[1],"diff":"Different losses in both year/tag"}
430 
431  for iDefOrVeto in ["defect","veto"]:
432  for iSuffix in suffixList:
433  runs_diff2tags["%s_%s"%(iDefOrVeto,iSuffix)] = []
434 
435  for iDefVeto in options['defect']+options['veto']:
436  for iSuffix in suffixList:
437  lumi_diff2tags["%s_%s"%(iDefVeto,iSuffix)] = {}
438 
439  if "defect" in defVetoType[iDefVeto]:
440  defOrVeto = "defect"
441  else:
442  defOrVeto = "veto"
443 
444  firstYT = True # Bool used to avoid displaying twice the same disagreement
445  for iYT in yearTagList:
446  if iYT==yearTagList[0]:
447  iYT2=yearTagList[1]
448  sign = +1
449  else:
450  iYT2=yearTagList[0]
451  sign = -1
452  if (iDefVeto in runsLPR[iYT] and iDefVeto not in runsLPR[iYT2]):
453  for irun in range(len(runsLPR[iYT][iDefVeto])):
454  print("%s contains %s %s (%.6f pb-1) for run %d but %s does not!"%(iYT,defOrVeto,iDefVeto,lossLPR[iYT][iDefVeto][irun],runsLPR[iYT][iDefVeto][irun],iYT2))
455  defVeto_type = "%s_miss_%s"%(iDefVeto,iYT2)
456  defOrVeto_type = "%s_miss_%s"%(defOrVeto,iYT2)
457 
458  lumi_diff2tags[defVeto_type][runsLPR[iYT][iDefVeto][irun]] = sign * lossLPR[iYT][iDefVeto][irun]
459  if runsLPR[iYT][iDefVeto][irun] not in runs_diff2tags[defOrVeto_type]:
460  runs_diff2tags[defOrVeto_type].append(runsLPR[iYT][iDefVeto][irun])
461 
462  if (iDefVeto in runsLPR[iYT] and iDefVeto in runsLPR[iYT2]):
463  for irun in range(len(runsLPR[iYT][iDefVeto])):
464  if runsLPR[iYT][iDefVeto][irun] not in runsLPR[iYT2][iDefVeto]:
465  print("%s contains %s %s (%.6f pb-1) for run %d but %s does not!"%(iYT,defOrVeto,iDefVeto,lossLPR[iYT][iDefVeto][irun],runsLPR[iYT][iDefVeto][irun],iYT2))
466  defVeto_type = "%s_miss_%s"%(iDefVeto,iYT2)
467  defOrVeto_type = "%s_miss_%s"%(defOrVeto,iYT2)
468 
469  lumi_diff2tags[defVeto_type][runsLPR[iYT][iDefVeto][irun]] = sign * lossLPR[iYT][iDefVeto][irun]
470  if runsLPR[iYT][iDefVeto][irun] not in runs_diff2tags[defOrVeto_type]:
471  runs_diff2tags[defOrVeto_type].append(runsLPR[iYT][iDefVeto][irun])
472  else:
473  irun2 = runsLPR[iYT2][iDefVeto].index(runsLPR[iYT][iDefVeto][irun])
474  if (lossLPR[iYT][iDefVeto][irun] != lossLPR[iYT2][iDefVeto][irun2] and firstYT):
475  print("%s contains %s %s (%.6f pb-1) for run %d; %s also but with a different luminosity %.6f pb-1!"%(iYT,defOrVeto,iDefVeto,lossLPR[iYT][iDefVeto][irun],runsLPR[iYT][iDefVeto][irun],iYT2,lossLPR[iYT2][iDefVeto][irun2]))
476  defVeto_type = "%s_diff"%(iDefVeto)
477  defOrVeto_type = "%s_diff"%(defOrVeto)
478 
479  lumi_diff2tags[defVeto_type][runsLPR[iYT][iDefVeto][irun]] = sign * (lossLPR[iYT][iDefVeto][irun]-lossLPR[iYT2][iDefVeto][irun2])
480  if runsLPR[iYT][iDefVeto][irun] not in runs_diff2tags[defOrVeto_type]:
481  runs_diff2tags[defOrVeto_type].append(runsLPR[iYT][iDefVeto][irun])
482 
483  firstYT = False
484 
485  h1Run_diffTwoYT = {}
486  h1_diffTwoYT = {}
487  maxAbsLumiDiff = {}
488  for iDefOrVeto in ["defect","veto"]:
489  for iSuffix in suffixList:
490  runs_diff2tags["%s_%s"%(iDefOrVeto,iSuffix)].sort()
491  maxAbsLumiDiff["%s_%s"%(iDefOrVeto,iSuffix)] = 0.
492 
493  for iDefVeto in options['defect']+options['veto']:
494  if "defect" in defVetoType[iDefVeto]:
495  defOrVeto = "defect"
496  color = defectVeto["color"][iDefVeto]
497  else:
498  defOrVeto = "veto"
499  color = defectVeto["color"][iDefVeto]
500 
501  for iSuffix in suffixList:
502  defVeto_type = "%s_%s"%(iDefVeto,iSuffix)
503  defOrVeto_type = "%s_%s"%(defOrVeto,iSuffix)
504  if len(runs_diff2tags[defOrVeto_type]) != 0:
505  h1Run_diffTwoYT[defVeto_type] = MakeTH1("h1Run_diffTwoYT_%s"%(defVeto_type),"Run","Defect luminosity loss difference (pb^{-1})", -0.5,-0.5+len(runs_diff2tags[defOrVeto_type]),len(runs_diff2tags[defOrVeto_type]),color)
506  h1Run_diffTwoYT[defVeto_type].SetTitle("")
507  SetXLabel(h1Run_diffTwoYT[defVeto_type],runs_diff2tags[defOrVeto_type])
508  h1_diffTwoYT[defVeto_type] = MakeTH1("h1_diffTwoYT_%s"%(defVeto_type),"Defect luminosity loss difference %s - %s (pb^{-1})"%(YT0,YT1),"Nb of runs",-10.,10.,500,color)
509  h1_diffTwoYT[defVeto_type].SetTitle("")
510  h1_diffTwoYT[defVeto_type].SetMaximum(len(runs_diff2tags[defOrVeto_type]))
511 
512  for iRun in range(len(runs_diff2tags[defOrVeto_type])):
513  if runs_diff2tags[defOrVeto_type][iRun] in list(lumi_diff2tags[defVeto_type].keys()):
514  h1Run_diffTwoYT[defVeto_type].Fill(iRun,lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]])
515  h1_diffTwoYT[defVeto_type].Fill(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]])
516  if fabs(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]]) > maxAbsLumiDiff[defOrVeto_type]:
517  maxAbsLumiDiff[defOrVeto_type] = fabs(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]])
518  if fabs(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]]) > maxAbsLumiDiff[defOrVeto_type]:
519  maxAbsLumiDiff[defOrVeto_type] = fabs(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]])
520 
521  c_diffTwoYT = {}
522  leg_diffTwoYT = {}
523  for iDefOrVeto in ["defect","veto"]:
524  if iDefOrVeto == "defect":
525  listOfDefVeto = options['defect']
526  else:
527  listOfDefVeto = options['veto']
528 
529  for iSuffix in suffixList:
530  defOrVeto_type = "%s_%s"%(iDefOrVeto,iSuffix)
531  if (len(runs_diff2tags[defOrVeto_type]) != 0):
532  c_diffTwoYT[defOrVeto_type] = TCanvas( "c_%s"%defOrVeto_type,"Differences between %s and %s"%(iYT2,iYT), 200, 10, 1400, 800)
533  c_diffTwoYT[defOrVeto_type].Divide(1,2)
534  c_diffTwoYT[defOrVeto_type].cd(2)
535  leg_diffTwoYT[defOrVeto_type] = MakeLegend(0.855,0.25,0.95,0.95)
536  first = True
537 
538  for iDefVeto in listOfDefVeto:
539  c_diffTwoYT[defOrVeto_type].cd(1)
540  defVeto_type = "%s_%s"%(iDefVeto,iSuffix)
541 
542  if (defVeto_type in list(h1Run_diffTwoYT.keys()) and h1Run_diffTwoYT[defVeto_type].GetEntries() != 0):
543  leg_diffTwoYT[defOrVeto_type].AddEntry(h1_diffTwoYT[defVeto_type],"#splitline{%s: %d runs}{Underflow: %d Overflow: %d}"%(defectVeto["description"][iDefVeto],h1_diffTwoYT[defVeto_type].GetEntries(),h1_diffTwoYT[defVeto_type].GetBinContent(0),h1_diffTwoYT[defVeto_type].GetBinContent(h1_diffTwoYT[defVeto_type].GetNbinsX()+1)),"P")
544  if (first):
545  gPad.SetGridy(1)
546  h1Run_diffTwoYT[defVeto_type].SetMinimum(-1.2*maxAbsLumiDiff[defOrVeto_type])
547  h1Run_diffTwoYT[defVeto_type].SetMaximum(1.2*maxAbsLumiDiff[defOrVeto_type])
548  h1Run_diffTwoYT[defVeto_type].Draw("L")
549  c_diffTwoYT[defOrVeto_type].cd(2)
550  gPad.SetGrid(1)
551  h1_diffTwoYT[defVeto_type].Draw("L")
552  first = False
553  else:
554  h1Run_diffTwoYT[defVeto_type].Draw("L SAME")
555  c_diffTwoYT[defOrVeto_type].cd(2)
556  h1_diffTwoYT[defVeto_type].Draw("L SAME")
557 
558  c_diffTwoYT[defOrVeto_type].cd(2)
559  leg_diffTwoYT[defOrVeto_type].SetHeader(suffixTitle[iSuffix])
560  leg_diffTwoYT[defOrVeto_type].Draw()
561 
replace
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition: hcg.cxx:307
max
#define max(a, b)
Definition: cfImp.cxx:41
index
Definition: index.py:1
DeMoScan.float
float
Definition: DeMoScan.py:54
DeMoLib.MakeTH1
def MakeTH1(name, xtitle, ytitle, xmin, xmax, nbins, color)
Definition: DeMoLib.py:30
DeMoScan.int
int
Definition: DeMoScan.py:47
GetEntries
TGraphErrors * GetEntries(TH2F *histo)
Definition: TRTCalib_makeplots.cxx:4019
python.html.AtlRunQueryDQSummary.SetXLabel
def SetXLabel(h, labels)
Definition: AtlRunQueryDQSummary.py:520
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
DeMoLib.MakeLegend
def MakeLegend(xmin, ymin, xmax, ymax)
Definition: DeMoLib.py:46
Get
T * Get(TFile &f, const std::string &n, const std::string &dir="", const chainmap_t *chainmap=0, std::vector< std::string > *saved=0)
get a histogram given a path, and an optional initial directory if histogram is not found,...
Definition: comparitor.cxx:178
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
DeMoLib.retrieveYearTagProperties
def retrieveYearTagProperties(year, tag)
Return the year/tag properties (defect/veto/lumi tags...) stored in YearStats-common/DeMoConfig-[year...
Definition: DeMoLib.py:68
min
#define min(a, b)
Definition: cfImp.cxx:40
Trk::open
@ open
Definition: BinningType.h:40
DeMoLib.initializeMonitoredDefects
def initializeMonitoredDefects(system, partitions, defects0, defectVeto, veto, signOff, year, tag, runlist={})
Definition: DeMoLib.py:294
calibdata.cd
cd
Definition: calibdata.py:51
DeMoLib.returnPeriod
def returnPeriod(runNb, system, year, tag)
Return the data period of a run based on the information stored in YearStats-[system]/[year]/[tag]/ru...
Definition: DeMoLib.py:56
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:798
dbg::print
void print(std::FILE *stream, std::format_string< Args... > fmt, Args &&... args)
Definition: SGImplSvc.cxx:70
DeMoLib.strLumi
def strLumi(lumi, unit="ub", latex=True, floatNumber=False)
Return a string with the luminosity in a human readable way If the unit is %%, this is a percentage.
Definition: DeMoLib.py:86
match
bool match(std::string s1, std::string s2)
match the individual directories of two strings
Definition: hcg.cxx:356