ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.1
Committed: Mon Feb 13 19:33:53 2012 UTC (13 years, 2 months ago) by amott
Content type: text/x-python
Branch: MAIN
Log Message:
first working version

File Contents

# User Rev Content
1 amott 1.1 #!/usr/bin/env python
2    
3     from AndrewGetRun import GetRun
4     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     print "--help Print this help"
42    
43     def main():
44     try:
45     opt, args = getopt.getopt(sys.argv[1:],"",["AllowedDiff=","CompareRun=","FindL1Zeros",\
46     "FirstLS=","NumberLS=","IgnoreLowRate=","ListIgnoredPaths",\
47     "PrintLumi","RefRun=","ShowPSTriggers","help"])
48     except getopt.GetoptError, err:
49     print str(err)
50     usage()
51     sys.exit(2)
52    
53     Config = RateMonConfig(os.path.abspath(os.path.dirname(sys.argv[0])))
54     for o,a in opt:
55     if o=="--ConfigFile":
56     Config.CFGfile=a
57     Config.ReadCFG()
58    
59     AllowedRateDiff = Config.DefAllowRateDiff
60     CompareRunNum = ""
61     FindL1Zeros = False
62     FirstLS = 9999
63     NumLS = -10
64     IgnoreThreshold = Config.DefAllowIgnoreThresh
65     ListIgnoredPaths = False
66     PrintLumi = False
67     RefRunNum = int(Config.ReferenceRun)
68     ShowPSTriggers = True
69    
70    
71     if Config.ShifterMode:
72     print "ShifterMode!!"
73     else:
74     print "ExpertMode"
75    
76     if Config.LSWindow > 0:
77     NumLS = -1*Config.LSWindow
78    
79     for o,a in opt: # get options passed on the command line
80     if o=="--AllowedDiff":
81     AllowedRateDiff = float(a)/100.0
82     elif o=="--CompareRun":
83     CompareRunNum=int(a)
84     elif o=="--FindL1Zeros":
85     FindL1Zeros = True
86     elif o=="--FirstLS":
87     FirstLS = int(a)
88     elif o=="--NumberLS":
89     NumLS = int(a)
90     elif o=="--IgnoreLowRate":
91     IgnoreThreshold = float(a)
92     elif o=="--ListIgnoredPaths":
93     ListIgnoredPaths=True
94     elif o=="--PrintLumi":
95     PrintLumi = True
96     elif o=="--RefRun":
97     RefRunNum=int(a)
98     elif o=="--ShowPSTriggers":
99     ShowPSTriggers=True
100     elif o=="--help":
101     usage()
102     sys.exit(0)
103     else:
104     print "Invalid Option "+a
105     sys.exit(1)
106    
107    
108     RefLumisExists = False
109    
110     """
111     if RefRunNum > 0:
112     RefRates = {}
113     for Iterator in range(1,100):
114     if RefLumisExists: ## Quits at the end of a run
115     if max(RefLumis[0]) <= (Iterator+1)*10:
116     break
117    
118     RefRunFile = RefRunNameTemplate % str( RefRunNum*100 + Iterator ) # place to save the reference run info
119     print "RefRunFile=",RefRunFile
120     if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
121     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
122     print RefRunFile[:RefRunFile.rfind('/')]
123     sys.exit(0)
124    
125     if not os.path.exists(RefRunFile): # if the reference run is not saved, get it from wbm
126     print "Reference Run File for run "+str(RefRunNum)+" iterator "+str(Iterator)+" does not exist"
127     print "Creating ..."
128     try:
129     RefParser = GetRun(RefRunNum, RefRunFile, True, Iterator*10, (Iterator+1)*10)
130     print "parsing"
131     except:
132     print "GetRun failed from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
133     continue
134    
135     else: # otherwise load it from the file
136     RefParser = pickle.load( open( RefRunFile ) )
137     print "loading"
138     if not RefLumisExists:
139     RefLumis = RefParser.LumiInfo
140     RefLumisExists = True
141    
142     try:
143     RefRates[Iterator] = RefParser.TriggerRates # get the trigger rates from the reference run
144     LastSuccessfulIterator = Iterator
145     except:
146     print "Failed to get rates from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
147     """
148    
149     RefRunFile = RefRunNameTemplate % RefRunNum
150     RefParser = DatabaseParser()
151     print "Reference Run: "+str(RefRunNum)
152     if RefRunNum > 0:
153     if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
154     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
155     print RefRunFile[:RefRunFile.rfind('/')]
156     sys.exit(0)
157     return
158     if not os.path.exists(RefRunFile):
159     # create the reference run file
160     try:
161     RefParser.RunNumber = RefRunNum
162     RefParser.ParseRunSetup()
163     #RefParser.GetAllTriggerRatesByLS()
164     #RefParser.Save( RefRunFile )
165     except e:
166     print "PROBLEM GETTING REFERNCE RUN"
167     raise
168     else:
169     RefParser = pickle.load( open( RefRunFile ) )
170    
171     # OK, Got the Reference Run
172     # Now get the most recent run
173    
174     SaveRun = False
175     if CompareRunNum=="": # if no run # specified on the CL, get the most recent run
176     CompareRunNum,isCol = GetLatestRunNumber()
177    
178     if not isCol:
179     print "Most Recent run, "+str(CompareRunNum)+", is NOT collisions"
180     sys.exit(0) # maybe we should walk back and try to find a collisions run, but for now just exit
181     print "Most Recent run is "+CompareRunNum
182    
183     HeadRunFile = RefRunNameTemplate % CompareRunNum
184     if os.path.exists(HeadRunFile): #check if a run file for the run we want to compare already exists, it probably won't but just in case we don't have to interrogate WBM
185     HeadParser = pickle.load( open( HeadRunFile ) )
186     else:
187     HeadParser = DatabaseParser()
188     HeadParser.RunNumber = CompareRunNum
189     HeadParser.ParseRunSetup()
190     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS)
191     if PrintLumi:
192     for LS in HeadParser.LumiInfo[0]:
193     try:
194     if (LS < FirstLS or LS > LastLS) and not FirstLS==999999:
195     continue
196     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))
197     except:
198     print "Lumisection "+str(LS-1)+" was not parsed from the LumiSections page"
199    
200     sys.exit(0)
201    
202     if RefRunNum == 0:
203     RefRates = 0
204     RefLumis = 0
205     LastSuccessfulIterator = 0
206    
207     ### Now actually compare the rates, make tables and look at L1. Loops for ShifterMode
208     #CheckTriggerList(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config)
209    
210     try:
211     while True:
212     RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config)
213    
214     if FindL1Zeros:
215     CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config)
216     if int(Config.ShifterMode)==0:
217     print "Expert Mode. Quitting."
218     sys.exit(0)
219     else:
220     print "Shifter Mode. Continuing"
221    
222     print "Sleeping for 1 minute before repeating "
223     for iSleep in range(6):
224     for iDot in range(iSleep+1):
225     print ".",
226     print "."
227     time.sleep(10)
228     clear()
229     #end while True
230     #end try
231     except KeyboardInterrupt:
232     print "Quitting. Peace Out."
233    
234    
235     def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
236    
237     Header = ["Trigger Name","Actual","Expected","% Inc","Cur PS","Comments"]
238     Data = []
239     Warn = []
240     IgnoredRates=[]
241    
242     [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
243     [HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
244     [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS] = HeadParser.LumiInfo
245    
246     for HeadName in HeadTriggerRates:
247     ## SKIP triggers in the skip list
248     if not HeadTotalPrescales.has_key(HeadName): ## for whatever reason we have no prescale here, so skip (calibration paths)
249     continue
250     if not HeadTotalPrescales[HeadName]: ## prescale is thought to be 0
251     continue
252     skipTrig=False
253     TriggerRate = HeadTriggerRates[HeadName][1]
254     if RefParser.RunNumber == 0: ## Use rate prediction functions
255    
256     PSCorrectedExpectedRate = Config.GetExpectedRate(StripVersion(HeadName),HeadAvInstLumi)
257    
258     if PSCorrectedExpectedRate < 0: ##This means we don't have a prediction for this trigger
259     continue
260     if not HeadTotalPrescales[HeadName]:
261     print HeadName+ " has total prescale 0"
262     continue
263     ExpectedRate = round((PSCorrectedExpectedRate / HeadTotalPrescales[HeadName]),2)
264     PerDiff=0
265     if ExpectedRate>0:
266     PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
267     if abs(PerDiff) > AllowedRateDiff/max(sqrt(TriggerRate),sqrt(ExpectedRate)):
268     Warn.append(True)
269     else:
270     Warn.append(False)
271    
272     if TriggerRate < IgnoreThreshold and ExpectedRate < IgnoreThreshold:
273     continue
274    
275     VC = ""
276    
277     Data.append([HeadName,TriggerRate,ExpectedRate,PerDiff,round(HeadTotalPrescales[HeadName],1),VC])
278    
279     else: ## Use a reference run
280     ## cheap trick to only get triggers in list when in shifter mode
281     #print "shifter mode=",int(Config.ShifterMode)
282     if int(Config.ShifterMode)==1:
283     if not HeadParser.AvgL1Prescales[HeadParser.HLTSeed[HeadName]]==1:
284     continue
285    
286     RefInstLumi = 0
287     RefIterator = 0
288    
289     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
290     RefLen = -10
291    
292     [RefUnprescaledRates, RefTotalPrescales, RefL1Prescales, RefTriggerRates] = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
293     [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
294     RefRate = -1
295     for k,v in RefUnprescaledRates.iteritems():
296     if StripVersion(HeadName) == StripVersion(k): # versions may not match
297     RefRate = v
298    
299     ScaledRefRate = round( RefRate*HeadAvLiveLumi/RefAvLiveLumi/HeadTotalPrescales[HeadName], 2 )
300    
301     if ScaledRefRate == 0:
302     PerDiff = 100
303     else:
304     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
305    
306     if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
307     continue
308    
309     if abs(PerDiff) > AllowedRateDiff:
310     Warn.append(True)
311     else:
312     Warn.append(False)
313     VC = ""
314     Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,round(HeadTotalPrescales[HeadName],1),VC])
315    
316    
317     PrettyPrintTable(Header,Data,[80,10,10,10,10,20],Warn)
318    
319     MoreTableInfo(HeadParser,HeadLumiRange)
320    
321     def CheckTriggerList(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
322     print "checking trigger list"
323    
324     def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
325     L1Zeros=[]
326     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
327     for key in HeadParser.TriggerRates:
328     ## Skip events in the skip list
329     skipTrig=False
330     ##for trig in Config.ExcludeList:
331     ##if not trigN.find(trig) == -1:
332     ##skipTrig=True
333     ##break
334     if skipTrig:
335     continue
336     ## if no events pass the L1, add it to the L1Zeros list if not already there
337     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
338     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:
339    
340     L1Zeros.append(HeadParser.TriggerRates[key][4])
341     print "L1Zeros=", L1Zeros
342    
343     if len(L1Zeros) == 0:
344     #print "It looks like no masked L1 bits seed trigger paths"
345     pass
346     else:
347     print "The following seeds are used to seed HLT bits but accept 0 events:"
348     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
349     for Seed in L1Zeros:
350     print Seed
351    
352     if __name__=='__main__':
353     main()