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  # retrieve the total luminosity and the lost luminosity
271  luminosity = int(read.group(2))
272  lostLumi = float(read.group(3))
273  # If defect, look for potential recoverable luminosity
274  if defVetoType[iDefVeto] == "Intolerable defect":
275  recovLumi = float(read.group(4))
276  else: # Veto loss is never recoverable
277  recovLumi = 0.
278  if runnumber not in list(atlasReady.keys()):
279  atlasready_tmp=GetReadyFlag(runnumber)
280  atlasReady[runnumber] = []
281  for lb in list(atlasready_tmp.keys()):
282  if atlasready_tmp[lb]>0: atlasReady[runnumber] += [lb]
283 
284  # if the loss is above the required minimum (0 by default), store it
285  if (runnumber>options['runMinLossPerRun'] and runnumber<=options['runMaxLossPerRun'] and lostLumi > options['minLumiYearStatsDefect']): #uncomment this for real runs!!
286  runsLPR[iYT][iDefVeto].append(runnumber)
287  lossLPR[iYT][iDefVeto].append(lostLumi)
288  loss_rLPR[iYT][iDefVeto].append(recovLumi)
289  if options['retrieveComments'] and "defect" in defVetoType[iDefVeto]: # retrieve comments for defects
290  print("@%d"%(runnumber))
291  db = DefectsDB(tag=yearTagProperties[yearTagTag[iYT]]["Defect tag"])
292  system_defects = []
293  for iPrefix in grlDef["prefix"]:
294  system_defects += [d for d in (db.defect_names | db.virtual_defect_names) if (d.startswith(iPrefix) and iDefVeto in d)]
295  defects = db.retrieve((runnumber, 1), (runnumber+1, 0), system_defects)
296  defectCompact = {}
297  for defect in defects:
298  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
299  continue
300  for iDef in options['defect']:
301  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
302  "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)
303  defectSinceLumiAtlasReady = -1
304  defectUntilLumiAtlasReady = -1
305  for iLumiBlock in range(defect.since.lumi,min(defect.until.lumi,max(atlasReady[runnumber])+1)):
306  if iLumiBlock in atlasReady[runnumber]:
307  defectUntilLumiAtlasReady = iLumiBlock+1
308  if defectSinceLumiAtlasReady == -1:
309  defectSinceLumiAtlasReady = iLumiBlock
310  if defectSinceLumiAtlasReady == -1: # Whole defect was outside ATLAS ready - Skip it
311  continue
312 
313  if defectSinceLumiAtlasReady == defectUntilLumiAtlasReady-1:
314  lbRange = "%10d"%(defectSinceLumiAtlasReady)
315  lbRangeReproc = defectSinceLumiAtlasReady
316  else:
317  lbRange = "%4d->%4d"%(defectSinceLumiAtlasReady,defectUntilLumiAtlasReady-1)
318  lbRangeReproc = "%d-%d"%(defectSinceLumiAtlasReady,defectUntilLumiAtlasReady-1)
319  cleanedDefect = ((defect.comment).replace('\xd7','')).replace('\xb5','').replace('\xe9','').replace('\u2013','').replace('\u03b7','').replace('\u03c6','').replace('\u2014','')
320  if ("\n %d |"%runnumber not in defRecap[iDef]):
321  # This "replace" is a dirty hack due to bad unicode in defect comment in run 355995/LAr
322  # You may need to add some others if you observe a crash...
323 
324  runperiod = returnPeriod(runnumber,args.parser_system,args.parser_year[0],args.parser_tag[0])
325  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)
326  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)
327  if (options['prepareReproc'] and recovLumi>0.):
328  defReproc[iDef] += "\n@%d"%runnumber
329  else:
330  defRecap[iDef] += "\n ---------------------------------------------|%s |%s| %s"%(lbRange,defect.user.rjust(12),cleanedDefect)
331  defRecapHtml[iDef] += '<tr class="out1"><th colspan="5"><th> %s </th><th> %s </th><th> %s </th><tr>'%(lbRange,defect.user.rjust(12),cleanedDefect)
332  for iPart in ["EMBA","EMBC","EMECA","EMECC","HECA","HECC","FCALA","FCALC"]:
333  if iPart in defect.channel and "SEVNOISEBURST" not in defect.channel: # Add the affected partition (except for SEVNOISEBURST, where the comment should contain it)
334  defRecap[iDef] += " - %s"%iPart
335 
336  if (options['prepareReproc'] and defect.recoverable):
337  defReproc[iDef] += "\n%s %s G/R # [Originally set by %s:%s] Now fixed/irrecoverable"%(defect.channel,lbRangeReproc,defect.user,cleanedDefect)
338  if ("SEVNOISEBURST" in defect.channel and "EMEC" in defect.channel):
339  defReproc[iDef] += "\n%s %s G/R # [Originally set by %s:%s] Now fixed/irrecoverable"%(defect.channel.replace("EMEC","HEC"),lbRangeReproc,defect.user,cleanedDefect)
340  defReproc[iDef] += "\n%s %s G/R # [Originally set by %s:%s] Now fixed/irrecoverable"%(defect.channel.replace("EMEC","FCAL"),lbRangeReproc,defect.user,cleanedDefect)
341 
342  f2.close()
343 
344  # if no loss found or if only diff2tags, stop the loop
345  if (len(runsLPR[iYT][iDefVeto]) == 0 or not options['plotLossPerRun']): continue
346 
347  # If loss found, create histogram to display them for the restricted run with a loss
348  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)
349  for iX in range(1,h1_lossLPR[iYT][iDefVeto].GetNbinsX()+1):
350  h1_lossLPR[iYT][iDefVeto].GetXaxis().SetBinLabel(iX,"%d"%runsLPR[iYT][iDefVeto][iX-1])
351 
352  if defVetoType[iDefVeto] == "Intolerable defect": # recoverable loss for defect
353  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)
354 
355  # Fill the new histogram(s)
356  for irun in range(len(runsLPR[iYT][iDefVeto])):
357  h1_lossLPR[iYT][iDefVeto].Fill(irun,lossLPR[iYT][iDefVeto][irun])
358  if defVetoType[iDefVeto] == "Intolerable defect":
359  h1_loss_rLPR[iYT][iDefVeto].Fill(irun,loss_rLPR[iYT][iDefVeto][irun])
360 
361  # Display the new histograms
362  index = "LPR_%s"%iDefVeto
363  canvasResults[iYT][index] = TCanvas("cLPR_%s_%s"%(iYT,iDefVeto),"%s (only run losses >%.1f pb-1)"%(xAxisTitle,options['minLumiYearStatsDefect']), 200, 10, 1200, 500)
364  canvasResults[iYT][index].SetGridy(1)
365  h1_lossLPR[iYT][iDefVeto].SetTitle("")
366  h1_lossLPR[iYT][iDefVeto].SetMinimum(0.)
367  h1_lossLPR[iYT][iDefVeto].Draw("HIST")
368  if (options['recovPlot'] and defVetoType[iDefVeto] == "Intolerable defect"):
369  h1_lossLPR[iYT][iDefVeto].Draw("HIST SAME")
370  legendResults[iYT][index] = MakeLegend(0.855,0.75,0.95,0.95)
371  legendResults[iYT][index].SetHeader("%s"%iYT)
372  legendResults[iYT][index].AddEntry(h1_lossLPR[iYT][iDefVeto],"Total:%s"%(strLumi(h1_lossLPR[iYT][iDefVeto].Integral(),"pb^{-1}")),"f")
373  if (options['recovPlot'] and defVetoType[iDefVeto] == "Intolerable defect"):
374  legendResults[iYT][index].AddEntry(h1_lossLPR[iYT][iDefVeto],"Recov:%s"%(strLumi(h1_loss_rLPR[iYT][iDefVeto].Integral(),"pb^{-1}")),"f")
375  legendResults[iYT][index].Draw()
376 
377 # Enf of comment recap
378 if options['plotLossPerRun'] and options['retrieveComments']:
379  f = open("%s/YearStats-%s/%s/%s/recapDefects.txt"%(args.parser_directory,args.parser_system,args.parser_year[0],args.parser_tag[0]),'w')
380  fHtml = open("%s/YearStats-%s/%s/%s/recapDefects.html"%(args.parser_directory,args.parser_system,args.parser_year[0],args.parser_tag[0]),'w')
381  fHtml.write('<table class="report">')
382  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>')
383  fHtml.write('<tr class="out0"> <th colspan="8"> Recap generated on %s </th></tr>'%(strftime("%a, %d %b %Y %H:%M", localtime())))
384  if options['prepareReproc']:
385  fReproc = open("YearStats-%s/%s/%s/defectsForReproc.txt"%(args.parser_system,args.parser_year[0],args.parser_tag[0]),'w')
386 
387  defTocHtml = '<div style="text-align:left" class="rectangle">'
388  for iDef in options['defect']:
389  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"
390  if ("b-1" in defRecap[iDef]):# At least one data loss in the whole YearStats for this defect
391  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}"))
392  defTocHtml += '</div>'
393 
394  fHtml.write(defTocHtml)
395  for iDef in options['defect']:
396  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"
397  if ("b-1" in defRecap[iDef]):# At least one data loss in the whole YearStats for this defect
398  print(defRecap[iDef])
399  f.write(defRecap[iDef])
400  fHtml.write("%s</tr>"%defRecapHtml[iDef].replace("LUMILOSTTOBEREPLACED",strLumi(h1_lossLPR[iYT][iDef].Integral(),"pb^{-1}")))
401  if options['prepareReproc']:
402  fReproc.write(defReproc[iDef])
403 
404  f.close()
405  fHtml.write('</table>')
406  fHtml.close()
407  if options['prepareReproc']:
408  fReproc.close()
409 
410 # Compare defects/veto run by run (if the year is the same for both)
411 if (len(yearTagList) == 2 and options['plotDiff2tags'] and singleYear):
412  print("I am now comparing run by run the defects and their affected luminosity")
413 
414  # First basic check about the datasets used in both tags
415  YT0 = yearTagList[0]
416  YT1 = yearTagList[1]
417  if (subperiodNb[YT0] != subperiodNb[YT1]):
418  print("Warning : different number of subperiods...")
419  else:
420  for iBin in range(subperiodNb[YT0]):
421  if (h1Period_IntLuminosity[YT0].GetBinContent(iBin) != h1Period_IntLuminosity[YT1].GetBinContent(iBin)):
422  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)))
423 
424  runs_diff2tags = {}
425  lumi_diff2tags = {}
426  suffixList = ["miss_%s"%yearTagList[0],"miss_%s"%yearTagList[1],"diff"]
427  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"}
428 
429  for iDefOrVeto in ["defect","veto"]:
430  for iSuffix in suffixList:
431  runs_diff2tags["%s_%s"%(iDefOrVeto,iSuffix)] = []
432 
433  for iDefVeto in options['defect']+options['veto']:
434  for iSuffix in suffixList:
435  lumi_diff2tags["%s_%s"%(iDefVeto,iSuffix)] = {}
436 
437  if "defect" in defVetoType[iDefVeto]:
438  defOrVeto = "defect"
439  else:
440  defOrVeto = "veto"
441 
442  firstYT = True # Bool used to avoid displaying twice the same disagreement
443  for iYT in yearTagList:
444  if iYT==yearTagList[0]:
445  iYT2=yearTagList[1]
446  sign = +1
447  else:
448  iYT2=yearTagList[0]
449  sign = -1
450  if (iDefVeto in runsLPR[iYT] and iDefVeto not in runsLPR[iYT2]):
451  for irun in range(len(runsLPR[iYT][iDefVeto])):
452  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))
453  defVeto_type = "%s_miss_%s"%(iDefVeto,iYT2)
454  defOrVeto_type = "%s_miss_%s"%(defOrVeto,iYT2)
455 
456  lumi_diff2tags[defVeto_type][runsLPR[iYT][iDefVeto][irun]] = sign * lossLPR[iYT][iDefVeto][irun]
457  if runsLPR[iYT][iDefVeto][irun] not in runs_diff2tags[defOrVeto_type]:
458  runs_diff2tags[defOrVeto_type].append(runsLPR[iYT][iDefVeto][irun])
459 
460  if (iDefVeto in runsLPR[iYT] and iDefVeto in runsLPR[iYT2]):
461  for irun in range(len(runsLPR[iYT][iDefVeto])):
462  if runsLPR[iYT][iDefVeto][irun] not in runsLPR[iYT2][iDefVeto]:
463  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))
464  defVeto_type = "%s_miss_%s"%(iDefVeto,iYT2)
465  defOrVeto_type = "%s_miss_%s"%(defOrVeto,iYT2)
466 
467  lumi_diff2tags[defVeto_type][runsLPR[iYT][iDefVeto][irun]] = sign * lossLPR[iYT][iDefVeto][irun]
468  if runsLPR[iYT][iDefVeto][irun] not in runs_diff2tags[defOrVeto_type]:
469  runs_diff2tags[defOrVeto_type].append(runsLPR[iYT][iDefVeto][irun])
470  else:
471  irun2 = runsLPR[iYT2][iDefVeto].index(runsLPR[iYT][iDefVeto][irun])
472  if (lossLPR[iYT][iDefVeto][irun] != lossLPR[iYT2][iDefVeto][irun2] and firstYT):
473  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]))
474  defVeto_type = "%s_diff"%(iDefVeto)
475  defOrVeto_type = "%s_diff"%(defOrVeto)
476 
477  lumi_diff2tags[defVeto_type][runsLPR[iYT][iDefVeto][irun]] = sign * (lossLPR[iYT][iDefVeto][irun]-lossLPR[iYT2][iDefVeto][irun2])
478  if runsLPR[iYT][iDefVeto][irun] not in runs_diff2tags[defOrVeto_type]:
479  runs_diff2tags[defOrVeto_type].append(runsLPR[iYT][iDefVeto][irun])
480 
481  firstYT = False
482 
483  h1Run_diffTwoYT = {}
484  h1_diffTwoYT = {}
485  maxAbsLumiDiff = {}
486  for iDefOrVeto in ["defect","veto"]:
487  for iSuffix in suffixList:
488  runs_diff2tags["%s_%s"%(iDefOrVeto,iSuffix)].sort()
489  maxAbsLumiDiff["%s_%s"%(iDefOrVeto,iSuffix)] = 0.
490 
491  for iDefVeto in options['defect']+options['veto']:
492  if "defect" in defVetoType[iDefVeto]:
493  defOrVeto = "defect"
494  color = defectVeto["color"][iDefVeto]
495  else:
496  defOrVeto = "veto"
497  color = defectVeto["color"][iDefVeto]
498 
499  for iSuffix in suffixList:
500  defVeto_type = "%s_%s"%(iDefVeto,iSuffix)
501  defOrVeto_type = "%s_%s"%(defOrVeto,iSuffix)
502  if len(runs_diff2tags[defOrVeto_type]) != 0:
503  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)
504  h1Run_diffTwoYT[defVeto_type].SetTitle("")
505  SetXLabel(h1Run_diffTwoYT[defVeto_type],runs_diff2tags[defOrVeto_type])
506  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)
507  h1_diffTwoYT[defVeto_type].SetTitle("")
508  h1_diffTwoYT[defVeto_type].SetMaximum(len(runs_diff2tags[defOrVeto_type]))
509 
510  for iRun in range(len(runs_diff2tags[defOrVeto_type])):
511  if runs_diff2tags[defOrVeto_type][iRun] in list(lumi_diff2tags[defVeto_type].keys()):
512  h1Run_diffTwoYT[defVeto_type].Fill(iRun,lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]])
513  h1_diffTwoYT[defVeto_type].Fill(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]])
514  if fabs(lumi_diff2tags[defVeto_type][runs_diff2tags[defOrVeto_type][iRun]]) > maxAbsLumiDiff[defOrVeto_type]:
515  maxAbsLumiDiff[defOrVeto_type] = fabs(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 
519  c_diffTwoYT = {}
520  leg_diffTwoYT = {}
521  for iDefOrVeto in ["defect","veto"]:
522  if iDefOrVeto == "defect":
523  listOfDefVeto = options['defect']
524  else:
525  listOfDefVeto = options['veto']
526 
527  for iSuffix in suffixList:
528  defOrVeto_type = "%s_%s"%(iDefOrVeto,iSuffix)
529  if (len(runs_diff2tags[defOrVeto_type]) != 0):
530  c_diffTwoYT[defOrVeto_type] = TCanvas( "c_%s"%defOrVeto_type,"Differences between %s and %s"%(iYT2,iYT), 200, 10, 1400, 800)
531  c_diffTwoYT[defOrVeto_type].Divide(1,2)
532  c_diffTwoYT[defOrVeto_type].cd(2)
533  leg_diffTwoYT[defOrVeto_type] = MakeLegend(0.855,0.25,0.95,0.95)
534  first = True
535 
536  for iDefVeto in listOfDefVeto:
537  c_diffTwoYT[defOrVeto_type].cd(1)
538  defVeto_type = "%s_%s"%(iDefVeto,iSuffix)
539 
540  if (defVeto_type in list(h1Run_diffTwoYT.keys()) and h1Run_diffTwoYT[defVeto_type].GetEntries() != 0):
541  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")
542  if (first):
543  gPad.SetGridy(1)
544  h1Run_diffTwoYT[defVeto_type].SetMinimum(-1.2*maxAbsLumiDiff[defOrVeto_type])
545  h1Run_diffTwoYT[defVeto_type].SetMaximum(1.2*maxAbsLumiDiff[defOrVeto_type])
546  h1Run_diffTwoYT[defVeto_type].Draw("L")
547  c_diffTwoYT[defOrVeto_type].cd(2)
548  gPad.SetGrid(1)
549  h1_diffTwoYT[defVeto_type].Draw("L")
550  first = False
551  else:
552  h1Run_diffTwoYT[defVeto_type].Draw("L SAME")
553  c_diffTwoYT[defOrVeto_type].cd(2)
554  h1_diffTwoYT[defVeto_type].Draw("L SAME")
555 
556  c_diffTwoYT[defOrVeto_type].cd(2)
557  leg_diffTwoYT[defOrVeto_type].SetHeader(suffixTitle[iSuffix])
558  leg_diffTwoYT[defOrVeto_type].Draw()
559 
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
python.html.AtlRunQueryDQSummary.SetXLabel
def SetXLabel(h, labels)
Definition: AtlRunQueryDQSummary.py:520
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:94
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
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
python.KeyStore.list
def list(self, key=None)
Definition: KeyStore.py:318
generate::GetEntries
double GetEntries(TH1D *h, int ilow, int ihi)
Definition: rmsFrac.cxx:20
Muon::print
std::string print(const MuPatSegment &)
Definition: MuonTrackSteering.cxx:28
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:790
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