ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.19
Committed: Fri Mar 30 08:46:54 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-00-24
Changes since 1.18: +7 -6 lines
Log Message:
removed strip version from RateMonitoring, will need long term fix for this problem

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    
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 grchrist 1.12
60 amott 1.1 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.16 print "Monitoring only stream A and Express"
184     #if not Force:
185     # sys.exit(0) # maybe we should walk back and try to find a collisions run, but for now just exit
186 amott 1.2 print "Most Recent run is "+str(CompareRunNum)
187 amott 1.16 else:
188     CompareRunNum,isCol = GetLatestRunNumber(CompareRunNum)
189 amott 1.1
190 amott 1.17
191     HeadParser = DatabaseParser()
192     HeadParser.RunNumber = CompareRunNum
193     HeadParser.ParseRunSetup()
194     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
195 amott 1.1 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 amott 1.16 if not isCol:
217     clear()
218     MoreTableInfo(HeadParser,HeadLumiRange,Config,False)
219 amott 1.2 else:
220 amott 1.16 RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config,ListIgnoredPaths)
221    
222     if FindL1Zeros:
223     CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config)
224     if int(Config.ShifterMode):
225     print "Shifter Mode. Continuing"
226     else:
227     print "Expert Mode. Quitting."
228     sys.exit(0)
229 amott 1.2
230 amott 1.1
231     print "Sleeping for 1 minute before repeating "
232 amott 1.16 for iSleep in range(20):
233 amott 1.15 write(".")
234     sys.stdout.flush()
235 amott 1.16 time.sleep(3)
236 amott 1.15 write(" Updating")
237     sys.stdout.flush()
238 amott 1.17 CurrRun,isCol = GetLatestRunNumber() ## update to the latest run and lumi range
239     if not CurrRun == CompareRunNum:
240     HeadParser.RunNumber = CompareRunNum
241     HeadParser.ParseRunSetup()
242     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
243 amott 1.1 #end while True
244     #end try
245     except KeyboardInterrupt:
246     print "Quitting. Peace Out."
247    
248    
249 grchrist 1.12 def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config,ListIgnoredPaths):
250 amott 1.1
251     Header = ["Trigger Name","Actual","Expected","% Inc","Cur PS","Comments"]
252     Data = []
253     Warn = []
254     IgnoredRates=[]
255    
256 abrinke1 1.9 [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
257 abrinke1 1.3 ##[HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
258     HeadUnprescaledRates = HeadParser.UpdateRun(HeadLumiRange)
259 abrinke1 1.9 [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS,PhysicsByLS,ActiveByLS] = HeadParser.LumiInfo
260    
261 grchrist 1.18 try:
262    
263     pkl_file = open(Config.FitFileName, 'rb')
264     FitInput = pickle.load(pkl_file)
265     pkl_file.close()
266     except:
267     "No fit file specified, opening default"
268     pkl_file = open("Fits/2011/Fit_HLT_10LS_Run179497to180252.pkl", 'rb')
269     FitInput = pickle.load(pkl_file)
270     pkl_file.close()
271 abrinke1 1.9
272 grchrist 1.14 pkl_file = open("RefRuns/2011/Rates_HLT_10LS_JPAP.pkl", 'rb')
273 abrinke1 1.9 RefRatesInput = pickle.load(pkl_file)
274     pkl_file.close()
275 amott 1.1
276 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
277 amott 1.1 ## SKIP triggers in the skip list
278 abrinke1 1.3 ## if not HeadTotalPrescales.has_key(HeadName): ## for whatever reason we have no prescale here, so skip (calibration paths)
279     ## continue
280     ## if not HeadTotalPrescales[HeadName]: ## prescale is thought to be 0
281     ## continue
282 grchrist 1.12
283     ## unless we are Listing Ignored paths only look at triggers in the .list file specifed in defaults.cfg
284 grchrist 1.19
285     #if StripVersion(HeadName) not in Config.MonitorList and not ListIgnoredPaths:
286    
287     if HeadName not in Config.MonitorList and not ListIgnoredPaths:
288 grchrist 1.12 continue
289    
290 abrinke1 1.9 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_L2", "HLT_Zero"]
291     masked_trig = False
292     for mask in masked_triggers:
293     if str(mask) in HeadName:
294     masked_trig = True
295     if masked_trig:
296     continue
297    
298 amott 1.1 skipTrig=False
299 abrinke1 1.3 TriggerRate = round(HeadUnprescaledRates[HeadName][2],2)
300 abrinke1 1.9
301 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
302    
303 abrinke1 1.9 ##PSCorrectedExpectedRate = Config.GetExpectedRate(StripVersion(HeadName),HeadAvInstLumi)
304 grchrist 1.19 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,RefRatesInput,HeadAvLiveLumi,HeadAvDeliveredLumi)
305 abrinke1 1.9
306     if PSCorrectedExpectedRate[0] < 0: ##This means we don't have a prediction for this trigger
307 amott 1.1 continue
308 abrinke1 1.3 ## if not HeadTotalPrescales[HeadName]:
309     ## print HeadName+ " has total prescale 0"
310     ## continue
311 abrinke1 1.9 ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
312 amott 1.1 PerDiff=0
313     if ExpectedRate>0:
314     PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
315 grchrist 1.13 if abs(PerDiff) > max(AllowedRateDiff/max(sqrt(TriggerRate),sqrt(ExpectedRate)),AllowedRateDiff/2.0):
316 abrinke1 1.9 Warn.append(True)
317     else:
318     Warn.append(False)
319 amott 1.1 else:
320     Warn.append(False)
321    
322     if TriggerRate < IgnoreThreshold and ExpectedRate < IgnoreThreshold:
323     continue
324    
325     VC = ""
326    
327 abrinke1 1.3 Data.append([HeadName,TriggerRate,ExpectedRate,PerDiff,round(HeadUnprescaledRates[HeadName][1],1),VC])
328 amott 1.1
329     else: ## Use a reference run
330     ## cheap trick to only get triggers in list when in shifter mode
331     #print "shifter mode=",int(Config.ShifterMode)
332     if int(Config.ShifterMode)==1:
333     if not HeadParser.AvgL1Prescales[HeadParser.HLTSeed[HeadName]]==1:
334     continue
335    
336     RefInstLumi = 0
337     RefIterator = 0
338    
339     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
340     RefLen = -10
341    
342 abrinke1 1.3 ##[RefUnprescaledRates, RefTotalPrescales, RefL1Prescales, RefTriggerRates] = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
343     RefUnprescaledRates = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
344 amott 1.1 [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
345     RefRate = -1
346     for k,v in RefUnprescaledRates.iteritems():
347 grchrist 1.19 #if StripVersion(HeadName) == StripVersion(k): # versions may not match
348     RefRate = v
349 amott 1.1
350 abrinke1 1.3 ScaledRefRate = round( RefRate*HeadAvLiveLumi/RefAvLiveLumi/(HeadUnprescaledRates[HeadName][1]), 2 )
351 amott 1.1
352     if ScaledRefRate == 0:
353     PerDiff = 100
354     else:
355     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
356    
357     if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
358     continue
359    
360     if abs(PerDiff) > AllowedRateDiff:
361     Warn.append(True)
362     else:
363     Warn.append(False)
364     VC = ""
365 amott 1.15 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,round((HeadUnprescaledRates[HeadName][1]),1),VC])
366 amott 1.1
367 grchrist 1.18
368 amott 1.1 PrettyPrintTable(Header,Data,[80,10,10,10,10,20],Warn)
369    
370 amott 1.4 MoreTableInfo(HeadParser,HeadLumiRange,Config)
371 amott 1.1
372     def CheckTriggerList(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
373     print "checking trigger list"
374    
375     def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRateDiff,IgnoreThreshold,Config):
376     L1Zeros=[]
377     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
378     for key in HeadParser.TriggerRates:
379     ## Skip events in the skip list
380     skipTrig=False
381     ##for trig in Config.ExcludeList:
382     ##if not trigN.find(trig) == -1:
383     ##skipTrig=True
384     ##break
385     if skipTrig:
386     continue
387     ## if no events pass the L1, add it to the L1Zeros list if not already there
388     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
389     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:
390    
391     L1Zeros.append(HeadParser.TriggerRates[key][4])
392     print "L1Zeros=", L1Zeros
393    
394     if len(L1Zeros) == 0:
395     #print "It looks like no masked L1 bits seed trigger paths"
396     pass
397     else:
398     print "The following seeds are used to seed HLT bits but accept 0 events:"
399     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
400     for Seed in L1Zeros:
401     print Seed
402    
403     if __name__=='__main__':
404     main()