ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.3
Committed: Wed Feb 15 20:00:15 2012 UTC (13 years, 2 months ago) by abrinke1
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-00-04
Changes since 1.2: +17 -15 lines
Log Message:
Slight change uses accurate ps info

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