ATLAS Offline Software
Loading...
Searching...
No Matches
DeMoScan.py
Go to the documentation of this file.
1#! /usr/bin/env python
2# Copyright (C) 2002-2025 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
12import os,sys
13from math import fabs
14from re import match
15from time import strftime,localtime
16
17from ROOT import TFile
18from ROOT import TCanvas
19from ROOT import kTeal
20from ROOT import gStyle,gROOT,gPad
21gROOT.SetBatch(False)
22
23sys.path.append("/afs/cern.ch/user/l/larmon/public/prod/Misc")
24from LArMonCoolLib import GetReadyFlag
25from DeMoLib import strLumi,initializeMonitoredDefects,retrieveYearTagProperties,MakeTH1,SetXLabel,MakeLegend,returnPeriod
26
27global debug
28debug = False
29#debug = True
30
31
34
35from argparse import RawTextHelpFormatter,ArgumentParser
36
37from DQDefects import DefectsDB
38
39parser = ArgumentParser(description='',formatter_class=RawTextHelpFormatter)
40parser.add_argument('-y','--year',dest='parser_year',default = ["2022"],nargs='*',help='Year [Default: 2022]',action='store')
41parser.add_argument('-t','--tag',dest='parser_tag',default = ["AtlasReady"],nargs='*',help='Defect tag [Default: "AtlasReady"]',action='store')
42parser.add_argument('-s','--system',dest='parser_system',default="LAr",help='System: LAr, CaloCP [Default: "LAr"]',action='store')
43parser.add_argument('-d','--directory',dest='parser_directory',default=".",help='Directory to display',action='store')
44parser.add_argument('-b','--batch',dest='parser_batchMode',help='Batch mode',action='store_true')
45parser.add_argument('--run',type=int,dest='parser_run',help='Run or run range (relevant only for lossPerRun)',nargs='*',action='store')
46parser.add_argument('--defect',type=str,dest='parser_defect',default="",help='Defect to consider (if not specified: all)',action='store')
47parser.add_argument('--veto',type=str,dest='parser_veto',default="",help='Veto to consider (if not specified: all)',action='store')
48parser.add_argument('--noRecovPlot',dest='parser_noRecovPlot',help='Do not plot the recoverable histograms',action='store_false')
49parser.add_argument('--lossPerRun',dest='parser_plotLPR',help='Plot the loss run and per type',action='store_true')
50parser.add_argument('--diffTwoTags',dest='parser_diff2tags',help='Compare run by run the data losses for two tags (same year necessary)',action='store_true')
51parser.add_argument('--restrictTagRuns',dest='parser_restrictTagRuns',help='In diffTwotags, restrict comparison to runs considered in this tag',action='store')
52parser.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')
53parser.add_argument('--retrieveComments',dest='parser_retrieveComments',help='Retrieve comments from the defect DB',action='store_true')
54parser.add_argument('--recapDefects',dest='parser_recapDefects',help='',action='store_true')
55parser.add_argument('--prepareReproc',dest='parser_reproc',help='Prepare a txt file to be updated for reprocessing signoff with recoverable defect',action='store_true')
56
57args = parser.parse_args()
58
59parser.print_help()
60
61if args.parser_batchMode:
62 gROOT.SetBatch(True)
63
64yearTagProperties = {}
65partitions = {}
66grlDef = {}
67defectVeto = {}
68veto = {}
69signOff = {}
70initializeMonitoredDefects(args.parser_system,partitions,grlDef,defectVeto,veto,signOff,args.parser_year[0],args.parser_tag[0])
71
72yearTagList = []
73yearTagDir = {}
74yearTagTag = {}
75
76for iYear in args.parser_year:
77 for iTag in args.parser_tag:
78 directory = "%s/YearStats-%s/%s/%s"%(args.parser_directory,args.parser_system,iYear,iTag)
79 if os.path.exists(directory):
80 yearTagProperties[iTag] = retrieveYearTagProperties(iYear,iTag)
81 yearTag = "%s%s"%(iYear,yearTagProperties[iTag]["Description"])
82 yearTagList.append(yearTag)
83 yearTagDir[yearTag] = directory
84 yearTagTag[yearTag] = iTag # Used only to retrieve comments
85
86if len(args.parser_year) == 1:
87 singleYear = True
88else:
89 singleYear = False
90 if (options['plotDiff2tags']):
91 print("To compare two tags, you must choose only one year. Exiting...")
92 sys.exit()
93
94if (len(args.parser_year) != 1 and len(args.parser_tag) != 1 and options['recapDefects']):
95 print("To recap defects, you must choose only one year and tag. Exiting...")
96 sys.exit()
97
98yearTagList.sort()
99
100if len(yearTagList) == 0:
101 print("No year / tag matching - Please check YearStats directory")
102 sys.exit()
103
104options = {}
105options['defect'] = [args.parser_defect]
106options['veto'] = [args.parser_veto]
107if options['defect'] == [""] and options['veto'] == [""]:
108 options['defect'] = grlDef["intol"]+grlDef["tol"]
109 options['veto'] = veto["all"]
110else:
111 if options['defect'][0] not in (grlDef["intol"]+grlDef["tol"]) and options['veto'][0] not in veto["all"]:
112 print("Defect/veto not found. Please check...")
113 print("Defect: ",grlDef["intol"])
114 print("Veto: ",veto["all"])
115 sys.exit()
116 if options['defect'] == [""]:
117 options['defect'] = []
118 if options['veto'] == [""]:
119 options['veto'] = []
120
121defVetoType = {}
122for iDefVeto in options['defect']+options['veto']:
123 if iDefVeto in options['defect']:
124 if (iDefVeto in grlDef["intol"]):
125 defVetoType[iDefVeto] = "Intolerable defect"
126 else:
127 defVetoType[iDefVeto] = "Tolerable defect"
128 else:
129 defVetoType[iDefVeto] = "Veto"
130
131
132options['recovPlot'] = args.parser_noRecovPlot
133options['plotLossPerRun'] = args.parser_plotLPR
134options['plotDiff2tags'] = args.parser_diff2tags
135options['restrictTagRuns'] = args.parser_restrictTagRuns
136options['recapDefects'] = args.parser_recapDefects
137options['prepareReproc'] = args.parser_reproc
138runsFilter = []
139# If runs filter is requested, look for the runs of the chosen year/tag
140if (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
141 fRuns = open("%s/runs-ALL.dat"%yearTagDir["%s%s"%(args.parser_year[0],yearTagProperties[options['restrictTagRuns']]["Description"])])
142 for iline in fRuns.readlines():
143 runWithoutPeriod = int(iline.split(" (")[0])
144 runsFilter.append(runWithoutPeriod)
145 fRuns.close()
146 print("I am considering only the %d runs of %s"%(len(runsFilter),options['restrictTagRuns']))
147 print(runsFilter)
148
149options['minLumiYearStatsDefect'] = args.parser_minLumiLPR
150options['retrieveComments'] = args.parser_retrieveComments
151
152if options['recapDefects']:
153 options['plotLossPerRun'] = True
154 options['retrieveComments'] = True
155
156if options['prepareReproc']:
157 options['plotLossPerRun'] = True
158 options['retrieveComments'] = True
159
160if options['retrieveComments']:
161 defRecap = {}
162 defRecapHtml = {}
163 for iDef in options['defect']:
164 defRecap[iDef] = "\n\n===== Recap for %s================================================================================================================================\n"%(iDef.ljust(15))
165 defRecap[iDef] += "Description: %s - %s\n"%(defectVeto["description"][iDef],defVetoType[iDef])
166 if (defVetoType[iDef] == "Intolerable defect"):
167 defRecap[iDef] +=" Run| Period| Tot lumi|Lost lumi|Recov. L.| LB range | Author | "
168 else:
169 defRecap[iDef] +=" Run| Period| Tot lumi|Aff. lumi|Recov. L.| LB range | Author | "
170
171 if (defVetoType[iDef] == "Intolerable defect"):
172 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)
173 defRecapHtml[iDef] +='<tr class="out0intolerable"> <th colspan="8"> Description: %s - %s</th></tr>'%(defectVeto["description"][iDef],defVetoType[iDef])
174 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> '
175 else:
176 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)
177 defRecapHtml[iDef] +='<tr class="out0tolerable"> <th colspan="8"> Description: %s - %s</th></tr>'%(defectVeto["description"][iDef],defVetoType[iDef])
178 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> '
179
180if options['prepareReproc']:
181 defReproc = {}
182 for iDef in options['defect']:
183 defReproc[iDef] = ""
184
185if args.parser_run:
186 options['runMinLossPerRun'] = min(args.parser_run)
187 options['runMaxLossPerRun'] = max(args.parser_run)
188else:
189 options['runMinLossPerRun'] = 0
190 options['runMaxLossPerRun'] = 1e9
191
192gStyle.SetOptStat(0)
193
194canvasResults = {}
195legendResults = {}
196stackResults = {}
197file = {}
198
199h1Period_IntLuminosity = {}
200subperiodNb = {}
201runsLPR = {}
202lossLPR = {}
203loss_rLPR = {}
204h1_lossLPR = {}
205h1_loss_rLPR = {}
206
207atlasReady = {}
208
209for iYT in yearTagList:
210 print("I am treating the following year/tag:%s"%iYT)
211
212 canvasResults[iYT] = {}
213 legendResults[iYT] = {}
214 stackResults[iYT] = {}
215
216 # Open the Archive filename to compare the luminosity of each period
217 if options['plotDiff2tags']:
218 yearStatsArchiveFilename = '%s/TProfiles.root'%(yearTagDir[iYT])
219 if not (os.path.exists(yearStatsArchiveFilename)):
220 print("No %s found - > Skipping"%yearStatsArchiveFilename)
221 continue
222
223 file[iYT] = TFile(yearStatsArchiveFilename)
224 h1Period_IntLuminosity[iYT] = file[iYT].Get("h1Period_IntLuminosity_archive")
225 subperiodNb[iYT] = h1Period_IntLuminosity[iYT].GetNbinsX()
226
227 if options['plotLossPerRun'] or options['plotDiff2tags']:
228 runsLPR[iYT] = {}
229 lossLPR[iYT] = {}
230 loss_rLPR[iYT] = {}
231 h1_lossLPR[iYT] = {}
232 h1_loss_rLPR[iYT] = {}
233 # Loop on defect+veto (all or single ones)
234 for iDefVeto in options['defect']+options['veto']:
235
236 # Define the file name containing the loss per run for this defect
237 if "defect" in defVetoType[iDefVeto]:
238 lossFileName = "%s/loss-%s.dat"%(yearTagDir[iYT],iDefVeto)
239 xAxisTitle = "#splitline{Luminosity loss due to}{%s [pb^{-1}]}"%(defectVeto["description"][iDefVeto])
240 if defVetoType[iDefVeto] == "Intolerable defect":
241 color = defectVeto["color"][iDefVeto]
242 else:
243 color = kTeal
244 else:
245 lossFileName = "%s/loss-%sVETO.dat"%(yearTagDir[iYT],iDefVeto)
246 xAxisTitle = "Luminosity loss due to %s[Veto] [pb^{-1}]"%(defectVeto["description"][iDefVeto])
247 color = defectVeto["color"][iDefVeto]
248
249 # Check if a dat loss file is associated to this veto/defect
250 if os.path.exists(lossFileName):
251 print("I am reading the %s file"%lossFileName)
252 runsLPR[iYT][iDefVeto] = []
253 lossLPR[iYT][iDefVeto] = []
254 loss_rLPR[iYT][iDefVeto] = []
255 f2 = open(lossFileName,'r')
256 tmpLines = f2.readlines()
257 tmpLines.sort()
258 for iline in tmpLines: # Loop on all lines of the loss-[defect/veto].dat files
259 if defVetoType[iDefVeto] == "Intolerable defect":
260 read = match(r"(\d+) \‍((\d+) ub-1.*\‍) -> (\d+.\d+) pb-1 \D+(\d+.\d+)\D+",iline)
261 else:# Veto loss is never recoverable (not tolerable defects)
262 read = match(r"(\d+) \‍((\d+) ub-1.*\‍) -> (\d+.\d+) pb-1",iline)
263 # retrieve the run number
264 runnumber = int(read.group(1))
265 # If the runs filter is activated (i.e. runsFilter != 0), check if the runs must be filtered
266 if (len(runsFilter) != 0 and runnumber not in runsFilter):
267 continue
268 if runnumber == 451936: # 29/6/2023: hack by B.Trocme to avoid a crash for a run w/o period assigned
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
378if 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)
411if (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
void sort(typename DataModel_detail::iterator< DVL > beg, typename DataModel_detail::iterator< DVL > end)
Specialization of sort for DataVector/List.
void print(char *figname, TCanvas *c1)
TGraphErrors * GetEntries(TH2F *histo)
#define min(a, b)
Definition cfImp.cxx:40
#define max(a, b)
Definition cfImp.cxx:41
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,...
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:310
bool match(std::string s1, std::string s2)
match the individual directories of two strings
Definition hcg.cxx:357
Definition index.py:1