ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.21
Committed: Tue Apr 3 18:50:10 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.20: +1 -0 lines
Log Message:
preparations for 2012 collisions

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