ATLAS Offline Software
DeMoAtlasDataLoss.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) - 2023
4 #
5 # Documentation: https://twiki.cern.ch/twiki/bin/viewauth/Atlas/DataQualityDemo
6 
7 
8 import os,sys
9 from math import fabs
10 from re import match
11 from time import strftime,localtime
12 
13 from ROOT import TFile
14 from ROOT import TH1F,TProfile
15 from ROOT import TCanvas
16 from ROOT import kTeal
17 from ROOT import gStyle,gROOT,gPad
18 from ROOT import kYellow,kOrange,kRed,kBlue,kPink,kMagenta,kGreen,kSpring,kViolet,kAzure,kCyan,kTeal,kBlack,kWhite,kGray
19 gROOT.SetBatch(False)
20 
21 sys.path.append("/afs/cern.ch/user/l/larmon/public/prod/Misc")
22 from LArMonCoolLib import GetLBTimeStamps,GetOfflineLumiFromCOOL,GetReadyFlag
23 from DeMoLib import retrieveYearTagProperties,returnPeriod,plotStack,MakeTH1,MakeLegend,strLumi
24 
25 from DQUtils import fetch_iovs
26 
27 from argparse import RawTextHelpFormatter,ArgumentParser
28 
29 global debug
30 debug = False
31 #debug = True
32 
33 
36 from DQDefects import DefectsDB
37 
38 parser = ArgumentParser(description='',formatter_class=RawTextHelpFormatter)
39 parser.add_argument('-y','--year',dest='parser_year',default = "2022",help='Year [Default: 2022]',action='store')
40 parser.add_argument('-t','--tag',dest='parser_tag',default = "AtlasReady",help='Defect tag [Default: "AtlasReady"]',action='store')
41 parser.add_argument('-b','--batch',dest='parser_batchMode',help='Batch mode',action='store_true')
42 
43 args = parser.parse_args()
44 year = args.parser_year
45 tag = args.parser_tag
46 
47 parser.print_help()
48 
49 if args.parser_batchMode:
50  gROOT.SetBatch(True)
51 
52 affectedLBs = {}
53 
54 systemList = ["LAr","Pixel","SCT","TRT","Tile","MDT","TGC","RPC","Trig_L1","Trig_HLT","Lumi","Global","ALFA","LUCID","ZDC","IDGlobal","BTag","CaloCP","MuonCP"]
55 systemList2 = systemList + ["All"]
56 
57 for iSyst in systemList2:
58  affectedLBs[iSyst] = {}
59 
60 DeMoConfig = {}
61 for iSyst in systemList:
62  recapDefectsFile = open("YearStats-%s/%s/%s/recapDefects.txt"%(iSyst,year,tag))
63 
64  runNumber = ""
65  for iline in recapDefectsFile:
66  ilineSplit = iline.split("|")
67  lbRange = ""
68  if (len(ilineSplit) == 8) and ("Run" not in ilineSplit[0]): # Found a new run
69  runNumber = ilineSplit[0]
70  lbRange = ilineSplit[5]
71  if (len(ilineSplit) == 4): # Found a new run
72  lbRange = ilineSplit[1]
73 
74  if (lbRange != ""):
75 
76  if (runNumber not in affectedLBs[iSyst].keys()):
77  affectedLBs[iSyst][runNumber] = []
78 
79  if (runNumber not in affectedLBs["All"].keys()):
80  affectedLBs["All"][runNumber] = []
81 
82  lbRangeSplit = lbRange.split("->")
83  if len(lbRangeSplit) == 1: # Single LB
84  lbAffInt = int(lbRange)
85  if (lbAffInt not in affectedLBs[iSyst][runNumber]):
86  affectedLBs[iSyst][runNumber].append(lbAffInt)
87  if (lbAffInt not in affectedLBs["All"][runNumber]):
88  affectedLBs["All"][runNumber].append(lbAffInt)
89 
90  if len(lbRangeSplit) == 2: # Single LB
91  for iLB in range(int(lbRangeSplit[0]),int(lbRangeSplit[1])+1):
92  if (iLB not in affectedLBs[iSyst][runNumber]):
93  affectedLBs[iSyst][runNumber].append(iLB)
94  if (iLB not in affectedLBs["All"][runNumber]):
95  affectedLBs["All"][runNumber].append(iLB)
96 
97  if ("Tolerable defect" in iline): # Ignore the tolerable defects
98  break
99 
100 DeMoConfig = retrieveYearTagProperties(year,tag)
101 
102 # Retrieve the luminosity for each affected LB from the COOL dbs
103 lbLumi = {}
104 for iRun in affectedLBs["All"].keys():
105  instOfflLumi = GetOfflineLumiFromCOOL(int(iRun),0,DeMoConfig["OflLumi tag"])
106  atlasready=GetReadyFlag(int(iRun))
107 
108  lbLumi[iRun] = {}
109  v_lbTimeSt = GetLBTimeStamps(int(iRun))
110 
111  lumiacct=fetch_iovs('COOLOFL_TRIGGER::/TRIGGER/OFLLUMI/LumiAccounting', tag=DeMoConfig["OflLumiAcct tag"], since=v_lbTimeSt[1][0]*1000000000, until=v_lbTimeSt[len(v_lbTimeSt)][1]*1000000000)
112 
113  for iLumiAcct in range(len(lumiacct)):
114  if (lumiacct[iLumiAcct].LumiBlock in affectedLBs["All"][iRun]):
115  if (atlasready[lumiacct[iLumiAcct].LumiBlock]):
116  lbLumi[iRun][lumiacct[iLumiAcct].LumiBlock] = lumiacct[iLumiAcct].LBTime*lumiacct[iLumiAcct].LiveFraction*lumiacct[iLumiAcct].InstLumiAll
117  lbLumi[iRun][lumiacct[iLumiAcct].LumiBlock] = lumiacct[iLumiAcct].LBTime*lumiacct[iLumiAcct].LiveFraction*instOfflLumi[lumiacct[iLumiAcct].LumiBlock]
118  else: # Special treatment needed when there are several IOVs with ATLAS ready
119  affectedLBs["All"][iRun].remove(lumiacct[iLumiAcct].LumiBlock)
120  for iSyst in systemList:
121  if (iRun in affectedLBs[iSyst].keys() and lumiacct[iLumiAcct].LumiBlock in affectedLBs[iSyst][iRun]):
122  affectedLBs[iSyst][iRun].remove(lumiacct[iLumiAcct].LumiBlock)
123 
124 # Retrieve the list of periods and the total luminosity from the TProfile.root file (Global system but should be the same for all)
125 periodFile = TFile("YearStats-Global/%s/%s/TProfiles.root"%(year,tag))
126 
127 h1_lumi = periodFile.Get("h1Period_IntLuminosity_archive")
128 periodListHash = h1_lumi.GetXaxis().GetLabels()
129 periodName = []
130 periodLumi = {}
131 
132 dataLossPerPeriod = {}
133 for iSyst in systemList2:
134  dataLossPerPeriod[iSyst]={}
135 
136 for i in range(len(periodListHash)):
137  periodName.append(str(periodListHash[i]))
138  periodLumi[periodName[i]] = h1_lumi.GetBinContent(i+1)
139  for iSyst in systemList2:
140  dataLossPerPeriod[iSyst][periodName[i]] = 0.
141 
142 hprof_dataLossPerSystem = {}
143 for iSyst in systemList2:
144  hprof_dataLossPerSystem[iSyst] = MakeTH1("dataLoss_%s"%iSyst,"Period","dataLoss_%s"%iSyst,-0.5,-0.5+len(periodName),len(periodName),kBlack)
145  for i in range(len(periodName)):
146  hprof_dataLossPerSystem[iSyst].GetXaxis().SetBinLabel(i+1,periodName[i])
147 
148 # Extract data loss per period for each system
149 colorPalette = {"Pixel":kViolet-4,
150  "SCT":kSpring-9,
151  "TRT":kPink,
152  "LAr":kRed+1,
153  "Tile":kYellow+1,
154  "MDT":kBlue+3,
155  "TGC":kBlue-4,
156  "RPC":kGreen-2,
157  "Trig_L1":kOrange,
158  "Trig_HLT":kAzure+6,
159  "Lumi":kBlue-9,
160  "Global":kCyan,
161  "IDGlobal":kMagenta+2,
162  "BTag":kPink+9,
163  "CaloCP":kGreen+3,
164  "MuonCP":kGray,
165  "All":kBlack}
166 
167 for iSyst in systemList2:
168  for iAffRun in affectedLBs[iSyst].keys():
169  period = returnPeriod(int(iAffRun),"Global",year,tag)
170  for iAffLB in affectedLBs[iSyst][iAffRun]:
171  dataLossPerPeriod[iSyst][period] = dataLossPerPeriod[iSyst][period] + lbLumi[iAffRun][iAffLB]
172  dataLossPerPeriod[iSyst]["All"] = dataLossPerPeriod[iSyst]["All"] + lbLumi[iAffRun][iAffLB]
173 
174  print("==== %s"%iSyst)
175  if (len(affectedLBs[iSyst])):
176  for i in range(len(periodName)):
177  if (periodLumi[periodName[i]] != 0.):
178  percentLoss = dataLossPerPeriod[iSyst][periodName[i]]/periodLumi[periodName[i]]/10000
179  else:
180  percentLoss = 0.
181  if percentLoss != 0.:
182  print("Period %s -> %.4f percent"%(periodName[i],percentLoss))
183  hprof_dataLossPerSystem[iSyst].Fill(i,percentLoss)
184  hprof_dataLossPerSystem[iSyst].SetBinError(i+1,0.)
185  hprof_dataLossPerSystem[iSyst].SetFillColor(colorPalette[iSyst])
186 
187 canvas = {}
188 stacks = {}
189 legends = {}
190 systemDict = {}
191 for iSyst in systemList:
192  systemDict[iSyst] = iSyst
193 
194 plotStack("Defects--Periods--%s"%DeMoConfig["Description"],hprof_dataLossPerSystem,systemList,systemDict,h1_lumi,False,stacks,canvas,legends,False)
195 hprof_dataLossPerSystem["All"].SetMarkerColor(kOrange+7)
196 hprof_dataLossPerSystem["All"].SetMarkerStyle(20)
197 hprof_dataLossPerSystem["All"].Draw("PSAME")
198 
199 ATLASLegend = MakeLegend(0.35,0.79,0.65,0.89)
200 ATLASLegend.AddEntry(hprof_dataLossPerSystem["All"], "#splitline{ATLAS inefficiency}{All periods: %.2f%% / %s (%s OK)}"%(dataLossPerPeriod["All"]["All"]/periodLumi["All"]/10000,strLumi(dataLossPerPeriod["All"]["All"]),strLumi(periodLumi["All"]-dataLossPerPeriod["All"]["All"]/1000000,"pb",True,True)), "P")
201 ATLASLegend.SetFillColor(kWhite)
202 ATLASLegend.Draw()
203 
204 canvas["Defects--Periods--%s"%DeMoConfig["Description"]].SaveAs("YearStats-Global/%s/%s/DataLoss.png"%(year,tag))
python.db.fetch_iovs
def fetch_iovs(folder_name, since=None, until=None, channels=None, tag="", what="all", max_records=-1, with_channel=True, loud=False, database=None, convert_time=False, named_channels=False, selection=None, runs=None, with_time=False, unicode_strings=False)
Definition: DQUtils/python/db.py:67
DeMoLib.MakeTH1
def MakeTH1(name, xtitle, ytitle, xmin, xmax, nbins, color)
Definition: DeMoLib.py:30
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
DeMoLib.MakeLegend
def MakeLegend(xmin, ymin, xmax, ymax)
Definition: DeMoLib.py:46
PixelModuleFeMask_create_db.remove
string remove
Definition: PixelModuleFeMask_create_db.py:83
python.LArMinBiasAlgConfig.int
int
Definition: LArMinBiasAlgConfig.py:59
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
print
void print(char *figname, TCanvas *c1)
Definition: TRTCalib_StrawStatusPlots.cxx:25
Trk::open
@ open
Definition: BinningType.h:40
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
str
Definition: BTagTrackIpAccessor.cxx:11
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:798
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
DeMoLib.plotStack
def plotStack(name, histo, index, indexName, histoIntLumi, lumiBool, resStack, resCanvas, resLegend, recovBool=True, compBool=False, approvedPlots=False)
Definition: DeMoLib.py:118