ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.20
Committed: Tue Apr 3 13:25:47 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.19: +13 -7 lines
Log Message:
changed year=2011 to global var called thisyear

File Contents

# User Rev Content
1 amott 1.1 #!/usr/bin/env python
2    
3 amott 1.15 #from AndrewGetRun import GetRun
4 amott 1.1 from DatabaseParser import *
5     from ReadConfig import RateMonConfig
6     import sys
7     import os
8     import cPickle as pickle
9     import getopt
10     import time
11     from colors import *
12     from TablePrint import *
13     from AddTableInfo_db import MoreTableInfo
14     from math import *
15    
16     WBMPageTemplate = "http://cmswbm/cmsdb/servlet/RunSummary?RUN=%s&DB=cms_omds_lb"
17     WBMRunInfoPage = "https://cmswbm/cmsdb/runSummary/RunSummary_1.html"
18    
19     RefRunNameTemplate = "RefRuns/Run_%s.pk"
20    
21     # define a function that clears the terminal screen
22     def clear():
23     print("\x1B[2J")
24    
25    
26     def usage():
27     print sys.argv[0]+" [Options]"
28     print "This script gets the current HLT trigger rates and compares them to a reference run"
29     print "Options: "
30     print "--AllowedDiff=<diff> Report only if difference in trigger rate is greater than <diff>%"
31     print "--CompareRun=<Run #> Compare run <Run #> to the reference run (Default = Current Run)"
32     print "--FindL1Zeros Look for physics paths with 0 L1 rate"
33     print "--FirstLS=<ls> Specify the first lumisection to consider. This will set LSSlidingWindow to -1"
34     print "--NumberLS=<#> Specify the last lumisection to consider. Make sure LastLS > LSSlidingWindow"
35     print " or set LSSlidingWindow = -1"
36     print "--IgnoreLowRate=<rate> Ignore triggers with an actual and expected rate below <rate>"
37     print "--ListIgnoredPaths Prints the paths that are not compared by this script and their rate in the CompareRun"
38     print "--PrintLumi Prints Instantaneous, Delivered, and Live lumi by LS for the run"
39     print "--RefRun=<Run #> Specifies <Run #> as the reference run to use (Default in defaults.cfg)"
40     print "--ShowPSTriggers Show prescaled triggers in rate comparison"
41 amott 1.2 print "--force Override the check for collisions run"
42 amott 1.1 print "--help Print this help"
43 grchrist 1.20
44     def pickYear():
45     global thisyear
46     thisyear="2011"
47     print "Year set to ",thisyear
48    
49 amott 1.1 def main():
50     try:
51     opt, args = getopt.getopt(sys.argv[1:],"",["AllowedDiff=","CompareRun=","FindL1Zeros",\
52     "FirstLS=","NumberLS=","IgnoreLowRate=","ListIgnoredPaths",\
53 amott 1.2 "PrintLumi","RefRun=","ShowPSTriggers","force","help"])
54 amott 1.1 except getopt.GetoptError, err:
55     print str(err)
56     usage()
57     sys.exit(2)
58    
59     Config = RateMonConfig(os.path.abspath(os.path.dirname(sys.argv[0])))
60     for o,a in opt:
61     if o=="--ConfigFile":
62     Config.CFGfile=a
63     Config.ReadCFG()
64 grchrist 1.12
65 amott 1.1 AllowedRateDiff = Config.DefAllowRateDiff
66     CompareRunNum = ""
67     FindL1Zeros = False
68     FirstLS = 9999
69 amott 1.2 NumLS = -10
70 amott 1.1 IgnoreThreshold = Config.DefAllowIgnoreThresh
71     ListIgnoredPaths = False
72     PrintLumi = False
73     RefRunNum = int(Config.ReferenceRun)
74     ShowPSTriggers = True
75 amott 1.2 Force = False
76 amott 1.1
77 amott 1.2 if int(Config.ShifterMode):
78 amott 1.1 print "ShifterMode!!"
79     else:
80     print "ExpertMode"
81    
82     if Config.LSWindow > 0:
83     NumLS = -1*Config.LSWindow
84    
85     for o,a in opt: # get options passed on the command line
86     if o=="--AllowedDiff":
87     AllowedRateDiff = float(a)/100.0
88     elif o=="--CompareRun":
89     CompareRunNum=int(a)
90     elif o=="--FindL1Zeros":
91     FindL1Zeros = True
92     elif o=="--FirstLS":
93     FirstLS = int(a)
94     elif o=="--NumberLS":
95     NumLS = int(a)
96     elif o=="--IgnoreLowRate":
97     IgnoreThreshold = float(a)
98     elif o=="--ListIgnoredPaths":
99     ListIgnoredPaths=True
100     elif o=="--PrintLumi":
101     PrintLumi = True
102     elif o=="--RefRun":
103     RefRunNum=int(a)
104     elif o=="--ShowPSTriggers":
105     ShowPSTriggers=True
106 amott 1.2 elif o=="--force":
107     Force = True
108 amott 1.1 elif o=="--help":
109     usage()
110     sys.exit(0)
111     else:
112     print "Invalid Option "+a
113     sys.exit(1)
114    
115    
116     RefLumisExists = False
117    
118     """
119     if RefRunNum > 0:
120     RefRates = {}
121     for Iterator in range(1,100):
122     if RefLumisExists: ## Quits at the end of a run
123     if max(RefLumis[0]) <= (Iterator+1)*10:
124     break
125    
126     RefRunFile = RefRunNameTemplate % str( RefRunNum*100 + Iterator ) # place to save the reference run info
127     print "RefRunFile=",RefRunFile
128     if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
129     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
130     print RefRunFile[:RefRunFile.rfind('/')]
131     sys.exit(0)
132    
133     if not os.path.exists(RefRunFile): # if the reference run is not saved, get it from wbm
134     print "Reference Run File for run "+str(RefRunNum)+" iterator "+str(Iterator)+" does not exist"
135     print "Creating ..."
136     try:
137     RefParser = GetRun(RefRunNum, RefRunFile, True, Iterator*10, (Iterator+1)*10)
138     print "parsing"
139     except:
140     print "GetRun failed from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
141     continue
142    
143     else: # otherwise load it from the file
144     RefParser = pickle.load( open( RefRunFile ) )
145     print "loading"
146     if not RefLumisExists:
147     RefLumis = RefParser.LumiInfo
148     RefLumisExists = True
149    
150     try:
151     RefRates[Iterator] = RefParser.TriggerRates # get the trigger rates from the reference run
152     LastSuccessfulIterator = Iterator
153     except:
154     print "Failed to get rates from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
155     """
156    
157     RefRunFile = RefRunNameTemplate % RefRunNum
158     RefParser = DatabaseParser()
159     print "Reference Run: "+str(RefRunNum)
160     if RefRunNum > 0:
161     if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
162     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
163     print RefRunFile[:RefRunFile.rfind('/')]
164     sys.exit(0)
165     return
166     if not os.path.exists(RefRunFile):
167     # create the reference run file
168     try:
169     RefParser.RunNumber = RefRunNum
170     RefParser.ParseRunSetup()
171     #RefParser.GetAllTriggerRatesByLS()
172     #RefParser.Save( RefRunFile )
173     except e:
174     print "PROBLEM GETTING REFERNCE RUN"
175     raise
176     else:
177     RefParser = pickle.load( open( RefRunFile ) )
178    
179     # OK, Got the Reference Run
180     # Now get the most recent run
181    
182     SaveRun = False
183     if CompareRunNum=="": # if no run # specified on the CL, get the most recent run
184     CompareRunNum,isCol = GetLatestRunNumber()
185    
186     if not isCol:
187     print "Most Recent run, "+str(CompareRunNum)+", is NOT collisions"
188 amott 1.16 print "Monitoring only stream A and Express"
189     #if not Force:
190     # sys.exit(0) # maybe we should walk back and try to find a collisions run, but for now just exit
191 amott 1.2 print "Most Recent run is "+str(CompareRunNum)
192 amott 1.16 else:
193     CompareRunNum,isCol = GetLatestRunNumber(CompareRunNum)
194 amott 1.1
195 amott 1.17
196     HeadParser = DatabaseParser()
197     HeadParser.RunNumber = CompareRunNum
198     HeadParser.ParseRunSetup()
199     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
200 amott 1.1 if PrintLumi:
201     for LS in HeadParser.LumiInfo[0]:
202     try:
203     if (LS < FirstLS or LS > LastLS) and not FirstLS==999999:
204     continue
205     print str(LS)+' '+str(round(HeadParser.LumiInfo[2][LS],1))+' '+str(round((HeadParser.LumiInfo[3][LS] - HeadParser.LumiInfo[3][LS-1])*1000/23.3,0))+' '+str(round((HeadParser.LumiInfo[4][LS] - HeadParser.LumiInfo[4][LS-1])*1000/23.3,0))
206     except:
207     print "Lumisection "+str(LS-1)+" was not parsed from the LumiSections page"
208    
209     sys.exit(0)
210    
211     if RefRunNum == 0:
212     RefRates = 0
213     RefLumis = 0
214     LastSuccessfulIterator = 0
215    
216     ### Now actually compare the rates, make tables and look at L1. Loops for ShifterMode
217     #CheckTriggerList(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config)
218    
219     try:
220     while True:
221 amott 1.16 if not isCol:
222     clear()
223     MoreTableInfo(HeadParser,HeadLumiRange,Config,False)
224 amott 1.2 else:
225 amott 1.16 RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config,ListIgnoredPaths)
226    
227     if FindL1Zeros:
228     CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config)
229     if int(Config.ShifterMode):
230     print "Shifter Mode. Continuing"
231     else:
232     print "Expert Mode. Quitting."
233     sys.exit(0)
234 amott 1.2
235 amott 1.1
236     print "Sleeping for 1 minute before repeating "
237 amott 1.16 for iSleep in range(20):
238 amott 1.15 write(".")
239     sys.stdout.flush()
240 amott 1.16 time.sleep(3)
241 amott 1.15 write(" Updating")
242     sys.stdout.flush()
243 amott 1.17 CurrRun,isCol = GetLatestRunNumber() ## update to the latest run and lumi range
244     if not CurrRun == CompareRunNum:
245     HeadParser.RunNumber = CompareRunNum
246     HeadParser.ParseRunSetup()
247     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
248 amott 1.1 #end while True
249     #end try
250     except KeyboardInterrupt:
251     print "Quitting. Peace Out."
252    
253    
254 grchrist 1.12 def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config,ListIgnoredPaths):
255 amott 1.1
256     Header = ["Trigger Name","Actual","Expected","% Inc","Cur PS","Comments"]
257     Data = []
258     Warn = []
259     IgnoredRates=[]
260    
261 abrinke1 1.9 [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
262 abrinke1 1.3 ##[HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
263     HeadUnprescaledRates = HeadParser.UpdateRun(HeadLumiRange)
264 abrinke1 1.9 [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS,PhysicsByLS,ActiveByLS] = HeadParser.LumiInfo
265    
266 grchrist 1.18 try:
267    
268     pkl_file = open(Config.FitFileName, 'rb')
269     FitInput = pickle.load(pkl_file)
270     pkl_file.close()
271     except:
272 grchrist 1.20 "No fit file specified"
273     sys.exit(2)
274    
275    
276     refrunfile="RefRuns/%s/Rates_HLT_10LS_JPAP.pkl" % (thisyear)
277     pkl_file = open(refrunfile, 'rb')
278 abrinke1 1.9 RefRatesInput = pickle.load(pkl_file)
279     pkl_file.close()
280 amott 1.1
281 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
282 amott 1.1 ## SKIP triggers in the skip list
283 abrinke1 1.3 ## if not HeadTotalPrescales.has_key(HeadName): ## for whatever reason we have no prescale here, so skip (calibration paths)
284     ## continue
285     ## if not HeadTotalPrescales[HeadName]: ## prescale is thought to be 0
286     ## continue
287 grchrist 1.12
288     ## unless we are Listing Ignored paths only look at triggers in the .list file specifed in defaults.cfg
289 grchrist 1.19
290     #if StripVersion(HeadName) not in Config.MonitorList and not ListIgnoredPaths:
291    
292     if HeadName not in Config.MonitorList and not ListIgnoredPaths:
293 grchrist 1.12 continue
294    
295 abrinke1 1.9 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_L2", "HLT_Zero"]
296     masked_trig = False
297     for mask in masked_triggers:
298     if str(mask) in HeadName:
299     masked_trig = True
300     if masked_trig:
301     continue
302    
303 amott 1.1 skipTrig=False
304 abrinke1 1.3 TriggerRate = round(HeadUnprescaledRates[HeadName][2],2)
305 abrinke1 1.9
306 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
307    
308 abrinke1 1.9 ##PSCorrectedExpectedRate = Config.GetExpectedRate(StripVersion(HeadName),HeadAvInstLumi)
309 grchrist 1.19 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,RefRatesInput,HeadAvLiveLumi,HeadAvDeliveredLumi)
310 abrinke1 1.9
311     if PSCorrectedExpectedRate[0] < 0: ##This means we don't have a prediction for this trigger
312 amott 1.1 continue
313 abrinke1 1.3 ## if not HeadTotalPrescales[HeadName]:
314     ## print HeadName+ " has total prescale 0"
315     ## continue
316 abrinke1 1.9 ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
317 amott 1.1 PerDiff=0
318     if ExpectedRate>0:
319     PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
320 grchrist 1.13 if abs(PerDiff) > max(AllowedRateDiff/max(sqrt(TriggerRate),sqrt(ExpectedRate)),AllowedRateDiff/2.0):
321 abrinke1 1.9 Warn.append(True)
322     else:
323     Warn.append(False)
324 amott 1.1 else:
325     Warn.append(False)
326    
327     if TriggerRate < IgnoreThreshold and ExpectedRate < IgnoreThreshold:
328     continue
329    
330     VC = ""
331    
332 abrinke1 1.3 Data.append([HeadName,TriggerRate,ExpectedRate,PerDiff,round(HeadUnprescaledRates[HeadName][1],1),VC])
333 amott 1.1
334     else: ## Use a reference run
335     ## cheap trick to only get triggers in list when in shifter mode
336     #print "shifter mode=",int(Config.ShifterMode)
337     if int(Config.ShifterMode)==1:
338     if not HeadParser.AvgL1Prescales[HeadParser.HLTSeed[HeadName]]==1:
339     continue
340    
341     RefInstLumi = 0
342     RefIterator = 0
343    
344     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
345     RefLen = -10
346    
347 abrinke1 1.3 ##[RefUnprescaledRates, RefTotalPrescales, RefL1Prescales, RefTriggerRates] = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
348     RefUnprescaledRates = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
349 amott 1.1 [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
350     RefRate = -1
351     for k,v in RefUnprescaledRates.iteritems():
352 grchrist 1.19 #if StripVersion(HeadName) == StripVersion(k): # versions may not match
353     RefRate = v
354 amott 1.1
355 abrinke1 1.3 ScaledRefRate = round( RefRate*HeadAvLiveLumi/RefAvLiveLumi/(HeadUnprescaledRates[HeadName][1]), 2 )
356 amott 1.1
357     if ScaledRefRate == 0:
358     PerDiff = 100
359     else:
360     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
361    
362     if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
363     continue
364    
365     if abs(PerDiff) > AllowedRateDiff:
366     Warn.append(True)
367     else:
368     Warn.append(False)
369     VC = ""
370 amott 1.15 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,round((HeadUnprescaledRates[HeadName][1]),1),VC])
371 amott 1.1
372 grchrist 1.18
373 amott 1.1 PrettyPrintTable(Header,Data,[80,10,10,10,10,20],Warn)
374    
375 amott 1.4 MoreTableInfo(HeadParser,HeadLumiRange,Config)
376 amott 1.1
377     def CheckTriggerList(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
378     print "checking trigger list"
379    
380     def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
381     L1Zeros=[]
382     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
383     for key in HeadParser.TriggerRates:
384     ## Skip events in the skip list
385     skipTrig=False
386     ##for trig in Config.ExcludeList:
387     ##if not trigN.find(trig) == -1:
388     ##skipTrig=True
389     ##break
390     if skipTrig:
391     continue
392     ## if no events pass the L1, add it to the L1Zeros list if not already there
393     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
394     if HeadParser.TriggerRates[key][4].find('L1_BeamHalo')==-1 and HeadParser.TriggerRates[key][4].find('L1_PreCollisions')==-1 and HeadParser.TriggerRates[key][4].find('L1_InterBunch_Bsc')==-1:
395    
396     L1Zeros.append(HeadParser.TriggerRates[key][4])
397     print "L1Zeros=", L1Zeros
398    
399     if len(L1Zeros) == 0:
400     #print "It looks like no masked L1 bits seed trigger paths"
401     pass
402     else:
403     print "The following seeds are used to seed HLT bits but accept 0 events:"
404     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
405     for Seed in L1Zeros:
406     print Seed
407    
408     if __name__=='__main__':
409 grchrist 1.20 global thisyear
410 amott 1.1 main()