ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.72
Committed: Mon Nov 26 17:31:57 2012 UTC (12 years, 5 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
Changes since 1.71: +1 -14 lines
Log Message:
fixing refrun option

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 ReadConfig import RateMonConfig
5     import sys
6     import os
7     import cPickle as pickle
8     import getopt
9     import time
10 awoodard 1.49 from StreamMonitor import *
11 amott 1.1 from colors import *
12 grchrist 1.61 try:
13     from TablePrint import *
14     except ImportError:
15     sys.stderr.write("Exception of environment variables. try:\nsource set.sh\n")
16     sys.exit(2)
17    
18 amott 1.1 from AddTableInfo_db import MoreTableInfo
19     from math import *
20 grchrist 1.43 from DatabaseParser import *
21 muell149 1.48 from TablePrint import *
22 amott 1.1
23     WBMPageTemplate = "http://cmswbm/cmsdb/servlet/RunSummary?RUN=%s&DB=cms_omds_lb"
24     WBMRunInfoPage = "https://cmswbm/cmsdb/runSummary/RunSummary_1.html"
25 grchrist 1.34 RefRunNameTemplate = "RefRuns/%s/Run_%s.pk"
26 amott 1.1
27     # define a function that clears the terminal screen
28     def clear():
29     print("\x1B[2J")
30    
31    
32     def usage():
33     print sys.argv[0]+" [Options]"
34 awoodard 1.44 print "This script gets the current HLT trigger rates and compares them to a reference run or a fit to multiple runs"
35 amott 1.1 print "Options: "
36 awoodard 1.51 print "--AllowedPercDiff=<diff> Warn only if difference in trigger rate is greater than <diff>%"
37     print "--AllowedSigmaDiff=<diff> Warn only if difference in trigger rate is greater than <diff> standard deviations"
38 amott 1.1 print "--CompareRun=<Run #> Compare run <Run #> to the reference run (Default = Current Run)"
39     print "--FindL1Zeros Look for physics paths with 0 L1 rate"
40     print "--FirstLS=<ls> Specify the first lumisection to consider. This will set LSSlidingWindow to -1"
41     print "--NumberLS=<#> Specify the last lumisection to consider. Make sure LastLS > LSSlidingWindow"
42     print " or set LSSlidingWindow = -1"
43     print "--IgnoreLowRate=<rate> Ignore triggers with an actual and expected rate below <rate>"
44     print "--ListIgnoredPaths Prints the paths that are not compared by this script and their rate in the CompareRun"
45     print "--PrintLumi Prints Instantaneous, Delivered, and Live lumi by LS for the run"
46     print "--RefRun=<Run #> Specifies <Run #> as the reference run to use (Default in defaults.cfg)"
47     print "--ShowPSTriggers Show prescaled triggers in rate comparison"
48 amott 1.33 print "--sortBy=<field> Sort the triggers by field. Valid fields are: name, rate, rateDiff"
49 amott 1.2 print "--force Override the check for collisions run"
50 muell149 1.50 print "--write Writes rates to .csv file"
51 awoodard 1.51 print "--ShowAllBadRates Show a list of all triggers (not just those in the monitor list) with bad rates"
52 amott 1.1 print "--help Print this help"
53 grchrist 1.20
54     def pickYear():
55     global thisyear
56 grchrist 1.23 thisyear="2012"
57     ##print "Year set to ",thisyear
58 grchrist 1.20
59 amott 1.1 def main():
60 grchrist 1.21 pickYear()
61 amott 1.1 try:
62 awoodard 1.44 opt, args = getopt.getopt(sys.argv[1:],"",["AllowedPercDiff=","AllowedSigmaDiff=","CompareRun=","FindL1Zeros",\
63 amott 1.1 "FirstLS=","NumberLS=","IgnoreLowRate=","ListIgnoredPaths",\
64 awoodard 1.51 "PrintLumi","RefRun=","ShowPSTriggers","force","sortBy=","write","ShowAllBadRates","help"])
65 amott 1.1 except getopt.GetoptError, err:
66     print str(err)
67     usage()
68     sys.exit(2)
69    
70     Config = RateMonConfig(os.path.abspath(os.path.dirname(sys.argv[0])))
71     for o,a in opt:
72     if o=="--ConfigFile":
73     Config.CFGfile=a
74     Config.ReadCFG()
75 grchrist 1.35
76    
77     if "NoV" in Config.FitFileName:
78     Config.NoVersion=True
79 grchrist 1.43 #print "NoVersion=",Config.NoVersion
80 grchrist 1.23
81 awoodard 1.47 ShowSigmaAndPercDiff = Config.DefShowSigmaAndPercDiff
82 awoodard 1.46 WarnOnSigmaDiff = Config.DefWarnOnSigmaDiff
83 awoodard 1.44 AllowedRatePercDiff = Config.DefAllowRatePercDiff
84     AllowedRateSigmaDiff = Config.DefAllowRateSigmaDiff
85 amott 1.1 CompareRunNum = ""
86     FindL1Zeros = False
87     FirstLS = 9999
88 amott 1.2 NumLS = -10
89 amott 1.1 IgnoreThreshold = Config.DefAllowIgnoreThresh
90 awoodard 1.64 ListIgnoredPaths = Config.ListIgnoredPaths
91 amott 1.1 PrintLumi = False
92     RefRunNum = int(Config.ReferenceRun)
93     ShowPSTriggers = True
94 amott 1.2 Force = False
95 muell149 1.50 writeb = False
96 awoodard 1.51 SortBy = "rate"
97 amott 1.33 ShifterMode = int(Config.ShifterMode) # get this from the config, but can be overridden by other options
98 awoodard 1.51 ShowAllBadRates = False
99 awoodard 1.64 MaxBadRates = Config.DefaultMaxBadRatesToShow
100 grchrist 1.23
101 amott 1.1 if Config.LSWindow > 0:
102     NumLS = -1*Config.LSWindow
103    
104     for o,a in opt: # get options passed on the command line
105 awoodard 1.44 if o=="--AllowedPercDiff":
106     AllowedRatePercDiff = float(a)
107     elif o=="--AllowedSigmaDiff":
108     AllowedRateSigmaDiff = float(a)
109 amott 1.1 elif o=="--CompareRun":
110     CompareRunNum=int(a)
111 amott 1.33 ShifterMode = False
112 amott 1.1 elif o=="--FindL1Zeros":
113     FindL1Zeros = True
114     elif o=="--FirstLS":
115     FirstLS = int(a)
116 amott 1.33 ShifterMode = False
117 amott 1.1 elif o=="--NumberLS":
118     NumLS = int(a)
119     elif o=="--IgnoreLowRate":
120     IgnoreThreshold = float(a)
121     elif o=="--ListIgnoredPaths":
122     ListIgnoredPaths=True
123 amott 1.33 ShifterMode = False
124 amott 1.1 elif o=="--PrintLumi":
125     PrintLumi = True
126     elif o=="--RefRun":
127     RefRunNum=int(a)
128     elif o=="--ShowPSTriggers":
129     ShowPSTriggers=True
130 amott 1.33 elif o=="--sortBy":
131     SortBy = a
132 amott 1.2 elif o=="--force":
133     Force = True
134 muell149 1.50 elif o=="--write":
135     writeb = True
136 awoodard 1.51 elif o=="--ShowAllBadRates":
137     ShowAllBadRates=True
138 amott 1.1 elif o=="--help":
139     usage()
140     sys.exit(0)
141     else:
142     print "Invalid Option "+a
143     sys.exit(1)
144    
145 grchrist 1.23
146 amott 1.1 RefLumisExists = False
147     """
148 grchrist 1.34 RefRunFile=RefRunNameTemplate % str(RefRunNum)
149 amott 1.1 if RefRunNum > 0:
150     RefRates = {}
151     for Iterator in range(1,100):
152     if RefLumisExists: ## Quits at the end of a run
153     if max(RefLumis[0]) <= (Iterator+1)*10:
154     break
155    
156     RefRunFile = RefRunNameTemplate % str( RefRunNum*100 + Iterator ) # place to save the reference run info
157     print "RefRunFile=",RefRunFile
158     if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
159     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
160     print RefRunFile[:RefRunFile.rfind('/')]
161     sys.exit(0)
162    
163     if not os.path.exists(RefRunFile): # if the reference run is not saved, get it from wbm
164     print "Reference Run File for run "+str(RefRunNum)+" iterator "+str(Iterator)+" does not exist"
165     print "Creating ..."
166     try:
167     RefParser = GetRun(RefRunNum, RefRunFile, True, Iterator*10, (Iterator+1)*10)
168     print "parsing"
169     except:
170     print "GetRun failed from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
171     continue
172    
173     else: # otherwise load it from the file
174     RefParser = pickle.load( open( RefRunFile ) )
175     print "loading"
176     if not RefLumisExists:
177     RefLumis = RefParser.LumiInfo
178     RefLumisExists = True
179    
180     try:
181     RefRates[Iterator] = RefParser.TriggerRates # get the trigger rates from the reference run
182     LastSuccessfulIterator = Iterator
183     except:
184     print "Failed to get rates from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
185 grchrist 1.34
186 amott 1.1 """
187 grchrist 1.34 RefRunFile = RefRunNameTemplate % (thisyear,RefRunNum)
188 amott 1.1 RefParser = DatabaseParser()
189 grchrist 1.23 ##print "Reference Run: "+str(RefRunNum)
190 amott 1.1 if RefRunNum > 0:
191 awoodard 1.49 print "Getting RefRunFile",RefRunFile
192 amott 1.1 if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
193     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
194     print RefRunFile[:RefRunFile.rfind('/')]
195 grchrist 1.27 sys.exit(0)
196 grchrist 1.34 s
197 amott 1.1 return
198     if not os.path.exists(RefRunFile):
199 grchrist 1.34 print "RefRunFile does not exist"
200 amott 1.1 # create the reference run file
201     try:
202     RefParser.RunNumber = RefRunNum
203     RefParser.ParseRunSetup()
204 grchrist 1.34 print "RefParser is setup"
205 amott 1.1 #RefParser.GetAllTriggerRatesByLS()
206     #RefParser.Save( RefRunFile )
207     except e:
208     print "PROBLEM GETTING REFERNCE RUN"
209     raise
210     else:
211 awoodard 1.71 RefParser = pickle.load(open(RefRunFile))
212 amott 1.1
213     # OK, Got the Reference Run
214     # Now get the most recent run
215    
216     SaveRun = False
217     if CompareRunNum=="": # if no run # specified on the CL, get the most recent run
218 grchrist 1.22 CompareRunNum,isCol,isGood = GetLatestRunNumber()
219 grchrist 1.26
220 grchrist 1.22 if not isGood:
221 grchrist 1.23 print "NO TRIGGER KEY FOUND for run ",CompareRunNum
222     ##sys.exit(0)
223 amott 1.1
224     if not isCol:
225     print "Most Recent run, "+str(CompareRunNum)+", is NOT collisions"
226 amott 1.16 print "Monitoring only stream A and Express"
227     #if not Force:
228     # sys.exit(0) # maybe we should walk back and try to find a collisions run, but for now just exit
229 grchrist 1.23
230     else:
231     print "Most Recent run is "+str(CompareRunNum)
232 amott 1.16 else:
233 grchrist 1.22 CompareRunNum,isCol,isGood = GetLatestRunNumber(CompareRunNum)
234     if not isGood:
235 grchrist 1.23 print "NO TRIGGER KEY FOUND for run ", CompareRunNum
236     ##sys.exit(0)
237 amott 1.17
238     HeadParser = DatabaseParser()
239     HeadParser.RunNumber = CompareRunNum
240 grchrist 1.23
241     try:
242     HeadParser.ParseRunSetup()
243     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
244 grchrist 1.43 LastGoodLS=HeadParser.GetLastLS(isCol)+1
245     tempLastGoodLS=LastGoodLS
246 grchrist 1.23 CurrRun=CompareRunNum
247 awoodard 1.71
248 grchrist 1.23 except:
249     HeadLumiRange=[]
250     LastGoodLS=-1
251 grchrist 1.43 tempLastGoodLS=LastGoodLS-1
252 grchrist 1.23 CurrRun=CompareRunNum
253     isGood=0
254    
255     if len(HeadLumiRange) is 0:
256 grchrist 1.36 print "No lumisections that are taking physics data 0"
257 grchrist 1.23 HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
258     if len(HeadLumiRange)>0:
259     isGood=1
260     isCol=0
261     ##sys.exit(0)
262 awoodard 1.44
263 awoodard 1.45 ## This reduces the sensitivity for a rate measurement to cause a warning during the beginning of a run
264 awoodard 1.49 if len(HeadLumiRange) > 0 and len(HeadLumiRange) < 10:
265 awoodard 1.44 AllowedRateSigmaDiff = AllowedRateSigmaDiff*10 / len(HeadLumiRange)
266 grchrist 1.23
267 amott 1.1 if PrintLumi:
268     for LS in HeadParser.LumiInfo[0]:
269     try:
270     if (LS < FirstLS or LS > LastLS) and not FirstLS==999999:
271     continue
272     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))
273     except:
274     print "Lumisection "+str(LS-1)+" was not parsed from the LumiSections page"
275    
276 grchrist 1.23 sys.exit(0)
277 amott 1.1
278     if RefRunNum == 0:
279     RefRates = 0
280     RefLumis = 0
281     LastSuccessfulIterator = 0
282    
283     ### Now actually compare the rates, make tables and look at L1. Loops for ShifterMode
284 grchrist 1.23 ###isGood=1##if there is a trigger key
285 amott 1.1 try:
286     while True:
287 grchrist 1.23 if isGood:
288 grchrist 1.43 tempLastGoodLS=LastGoodLS
289 grchrist 1.23 LastGoodLS=HeadParser.GetLastLS(isCol)
290 grchrist 1.43 ##print "Last Good=",LastGoodLS, tempLastGoodLS
291     if LastGoodLS==tempLastGoodLS:
292 grchrist 1.58 write(bcolors.OKBLUE)
293 grchrist 1.43 print "Trying to get new Run"
294     write(bcolors.ENDC+"\n")
295     else:
296     RefMoreLumiArray = HeadParser.GetMoreLumiInfo()
297     isBeams=True
298     for lumisection in HeadLumiRange:
299     try:
300     if not (RefMoreLumiArray["b1pres"][lumisection] and RefMoreLumiArray["b2pres"][lumisection] and RefMoreLumiArray["b1stab"][lumisection] and RefMoreLumiArray["b2stab"][lumisection]):
301     isBeams=False
302     except:
303 grchrist 1.41 isBeams=False
304 awoodard 1.55
305 grchrist 1.43 if not (isCol and isBeams):
306 grchrist 1.23 ##clear()
307 grchrist 1.43 MoreTableInfo(HeadParser,HeadLumiRange,Config,False)
308 grchrist 1.25 else:
309 grchrist 1.43 if (len(HeadLumiRange)>0):
310 awoodard 1.55 if not isSequential(HeadLumiRange):
311     print "Some lumisections have been skipped. Averaging over most recent sequential lumisections..."
312     sequential_chunk = getSequential(HeadLumiRange)
313     HeadLumiRange = sequential_chunk
314 awoodard 1.64 RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,ListIgnoredPaths,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates,MaxBadRates)
315 grchrist 1.43 if FindL1Zeros:
316 awoodard 1.44 CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config)
317 grchrist 1.43 else:
318     print "No lumisections that are taking physics data 1"
319 amott 1.33 if ShifterMode:
320 grchrist 1.23 #print "Shifter Mode. Continuing"
321     pass
322 amott 1.2 else:
323 grchrist 1.23 print "Expert Mode. Quitting."
324     sys.exit(0)
325 amott 1.2
326 amott 1.1 print "Sleeping for 1 minute before repeating "
327 amott 1.16 for iSleep in range(20):
328 amott 1.15 write(".")
329     sys.stdout.flush()
330 amott 1.16 time.sleep(3)
331 grchrist 1.23 write(" Updating\n")
332 amott 1.15 sys.stdout.flush()
333 grchrist 1.23
334     ##print "\nminLS=",min(HeadLumiRange),"Last LS=",HeadParser.GetLastLS(isCol),"run=",HeadParser.RunNumber
335     ###Get a new run if DAQ stops
336     ##print "\nLastGoodLS=",LastGoodLS
337    
338     ##### NEED PLACEHOLDER TO COMPARE CURRENT RUN TO LATEST RUN #####
339    
340     NewRun,isCol,isGood = GetLatestRunNumber(9999999) ## update to the latest run and lumi range
341    
342     try:
343     maxLumi=max(HeadLumiRange)
344     except:
345     maxLumi=0
346    
347     ##### THESE ARE CONDITIONS TO GET NEW RUN #####
348     if maxLumi>(LastGoodLS+1) or not isGood or NewRun!=CurrRun:
349     print "Trying to get new Run"
350     try:
351     HeadParser = DatabaseParser()
352     HeadParser.RunNumber = NewRun
353     HeadParser.ParseRunSetup()
354     CurrRun,isCol,isGood=GetLatestRunNumber(9999999)
355     FirstLS=9999
356     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
357     if len(HeadLumiRange) is 0:
358     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
359 grchrist 1.36 print "No lumisections that are taking physics data 2"
360 grchrist 1.23 if len(HeadLumiRange)>0:
361     isGood=1
362     isCol=0
363    
364 grchrist 1.43 #tempLastGoodLS=LastGoodLS
365     #LastGoodLS=HeadParser.GetLastLS(isCol)
366 grchrist 1.25 ##print CurrRun, isCol, isGood
367 grchrist 1.23 except:
368     isGood=0
369     isCol=0
370     print "failed"
371 awoodard 1.49
372 grchrist 1.23 else:
373     try:
374     HeadParser.ParseRunSetup()
375     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
376     if len(HeadLumiRange) is 0:
377     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
378 grchrist 1.26 print "No lumisections that are taking physics data"
379 grchrist 1.23 if len(HeadLumiRange)>0:
380     isGood=1
381     isCol=0
382 grchrist 1.43 #LastGoodLS=HeadParser.GetLastLS(isCol)
383 grchrist 1.23
384     except:
385     isGood=0
386     isCol=0
387     clear()
388     print "NO TRIGGER KEY FOUND YET for run", NewRun ,"repeating search"
389    
390 grchrist 1.22
391 amott 1.1 except KeyboardInterrupt:
392     print "Quitting. Peace Out."
393    
394    
395 awoodard 1.64 def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,ListIgnoredPaths,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates,MaxBadRates):
396 amott 1.1 Data = []
397     Warn = []
398     IgnoredRates=[]
399 grchrist 1.23
400 abrinke1 1.9 [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
401 abrinke1 1.3 ##[HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
402     HeadUnprescaledRates = HeadParser.UpdateRun(HeadLumiRange)
403 grchrist 1.59 if Config.DoL1:
404     L1RatesALL=HeadParser.GetL1RatesALL(HeadLumiRange)
405     for L1seed in L1RatesALL.iterkeys():
406     HeadUnprescaledRates[L1seed]=L1RatesALL[L1seed]
407 grchrist 1.56
408 abrinke1 1.9 [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS,PhysicsByLS,ActiveByLS] = HeadParser.LumiInfo
409 grchrist 1.30 deadtimebeamactive=HeadParser.GetDeadTimeBeamActive(HeadLumiRange)
410 grchrist 1.18 try:
411     pkl_file = open(Config.FitFileName, 'rb')
412     FitInput = pickle.load(pkl_file)
413     pkl_file.close()
414 grchrist 1.29 ##print "fit file name=",Config.FitFileName
415 grchrist 1.31
416 grchrist 1.18 except:
417 grchrist 1.27 print "No fit file specified"
418 grchrist 1.20 sys.exit(2)
419 grchrist 1.68
420     ###fitfile by L1seedchange
421 awoodard 1.71 if Config.L1SeedChangeFit:
422 grchrist 1.68 try:
423     PSfitfile=Config.FitFileName.replace("HLT_NoV","HLT_NoV_ByPS")
424 awoodard 1.71 #print "Opening", PSfitfile
425 grchrist 1.68 pkl_filePS = open(PSfitfile, 'rb')
426     FitInputPS = pickle.load(pkl_filePS)
427     pkl_filePS.close()
428 awoodard 1.71 #print "fit file name=",Config.FitFileName
429 grchrist 1.20
430 grchrist 1.68 except:
431 awoodard 1.71 print "No fit file by L1seed change specified. Have you run DatabaseRatePredictor with DoL1 in defaults.cfg set to true?"
432 grchrist 1.68 sys.exit(2)
433     else:
434     FitInputPS={} ##define empty dict when not in use
435 grchrist 1.23 try:
436     refrunfile="RefRuns/%s/Rates_HLT_10LS_JPAP.pkl" % (thisyear)
437     pkl_file = open(refrunfile, 'rb')
438     RefRatesInput = pickle.load(pkl_file)
439     pkl_file.close()
440     except:
441 grchrist 1.24 RefRatesInput={}
442 grchrist 1.62 #print "Didn't open ref file"
443 amott 1.1
444 grchrist 1.30
445     trig_list=Config.MonitorList
446    
447     if Config.NoVersion:
448     trig_list=[]
449    
450     for trigger in Config.MonitorList:
451     trig_list.append(StripVersion(trigger))
452 grchrist 1.70
453 awoodard 1.71 L1HLTseeds = HeadParser.GetL1HLTseeds()
454 grchrist 1.56 if Config.DoL1:
455     for HLTkey in trig_list:
456     if "L1" in HLTkey:
457     continue
458     else:
459     try:
460     for L1seed in L1HLTseeds[HLTkey]:
461     if L1seed not in trig_list:
462     trig_list.append(L1seed)
463     except:
464 awoodard 1.71 pass
465 grchrist 1.30 for trigger in FitInput.iterkeys():
466 awoodard 1.71 FitInput[StripVersion(trigger)] = FitInput.pop(trigger)
467 awoodard 1.51 for trigger in HeadUnprescaledRates:
468 awoodard 1.71 HeadUnprescaledRates[StripVersion(trigger)] = HeadUnprescaledRates.pop(trigger)
469 grchrist 1.57
470 awoodard 1.49 else:
471 awoodard 1.71 trig_list = Config.MonitorList
472 awoodard 1.49
473 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
474 awoodard 1.71 if HeadName not in trig_list and not ListIgnoredPaths and not ShowAllBadRates:
475     continue
476     if HeadName not in FitInput.keys() and not ListIgnoredPaths and not ShowAllBadRates:
477     continue
478 awoodard 1.49
479 grchrist 1.63 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero","HLT_BeamHalo"]
480 abrinke1 1.9 masked_trig = False
481     for mask in masked_triggers:
482     if str(mask) in HeadName:
483     masked_trig = True
484     if masked_trig:
485     continue
486    
487 amott 1.1 skipTrig=False
488 abrinke1 1.3 TriggerRate = round(HeadUnprescaledRates[HeadName][2],2)
489 grchrist 1.68
490 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
491 awoodard 1.71 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,FitInputPS,HeadAvLiveLumi,HeadAvDeliveredLumi,deadtimebeamactive,Config.L1SeedChangeFit,HeadLumiRange,PSColumnByLS)
492 awoodard 1.67 VC = PSCorrectedExpectedRate[2]
493 grchrist 1.32 try:
494 awoodard 1.52 sigma = PSCorrectedExpectedRate[1]/(sqrt(len(HeadLumiRange))* HeadUnprescaledRates[HeadName][1])
495 awoodard 1.66 ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
496 grchrist 1.32 except:
497 awoodard 1.65 sigma = 0.0
498 awoodard 1.66 ExpectedRate = 0.0 ##This means we don't have a prediction for this trigger-- gets overwritten to "--" later
499 awoodard 1.52 PerDiff = 0.0
500     SigmaDiff = 0.0
501 awoodard 1.53 if HeadUnprescaledRates[HeadName][1] != 0:
502     VC="No prediction"
503 awoodard 1.64 else:
504     VC="Path prescaled to 0"
505 grchrist 1.30
506 awoodard 1.51 if ExpectedRate > 0:
507 amott 1.1 PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
508 grchrist 1.37 else:
509 awoodard 1.52 PerDiff = 0.0
510 awoodard 1.51
511 awoodard 1.52 if sigma > 0:
512 awoodard 1.51 SigmaDiff = round( (TriggerRate - ExpectedRate)/sigma, 2)
513     else:
514 awoodard 1.64 SigmaDiff = 0.0 #Zero sigma means that when there were no rates for this trigger when the fit was made
515 amott 1.1
516 amott 1.33 if TriggerRate < IgnoreThreshold and (ExpectedRate < IgnoreThreshold and ExpectedRate!=0):
517 amott 1.1 continue
518    
519 awoodard 1.64
520     Data.append([HeadName, TriggerRate, ExpectedRate, PerDiff, SigmaDiff, round(HeadUnprescaledRates[HeadName][1],0),VC])
521 amott 1.1
522     else: ## Use a reference run
523     ## cheap trick to only get triggers in list when in shifter mode
524     #print "shifter mode=",int(Config.ShifterMode)
525 grchrist 1.34 ## continue
526 amott 1.1
527     RefInstLumi = 0
528     RefIterator = 0
529     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
530 awoodard 1.71 RefLen = -10
531 grchrist 1.34
532 abrinke1 1.3 RefUnprescaledRates = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
533 amott 1.1 [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
534 awoodard 1.71 if Config.DoL1:
535     RefL1RatesALL = RefParser.GetL1RatesALL(HeadLumiRange)
536     for L1seed in RefL1RatesALL.iterkeys():
537     RefUnprescaledRates[L1seed]=RefL1RatesALL[L1seed]
538    
539 amott 1.1 RefRate = -1
540     for k,v in RefUnprescaledRates.iteritems():
541 awoodard 1.71 if HeadName == StripVersion(k):
542 grchrist 1.34 RefRate = RefUnprescaledRates[k][2]
543    
544     try:
545     ScaledRefRate = round( (RefRate*HeadAvLiveLumi/RefAvLiveLumi*(1-deadtimebeamactive)), 2 )
546    
547     except ZeroDivisionError:
548     ScaledRefRate=0
549    
550 awoodard 1.44 SigmaDiff = 0
551 amott 1.1 if ScaledRefRate == 0:
552 awoodard 1.44 PerDiff = -999
553 amott 1.1 else:
554     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
555 awoodard 1.44
556 amott 1.1 if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
557     continue
558    
559     VC = ""
560 awoodard 1.71 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,SigmaDiff,round((HeadUnprescaledRates[HeadName][1]),0),VC])
561 amott 1.1
562 amott 1.33 SortedData = []
563     if SortBy == "":
564 awoodard 1.71 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
565 amott 1.33 elif SortBy == "name":
566     SortedData=sorted(Data, key=lambda entry: entry[0])
567     elif SortBy == "rate":
568     SortedData=sorted(Data, key=lambda entry: entry[1],reverse=True)
569 awoodard 1.44 elif SortBy == "ratePercDiff":
570 amott 1.33 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
571 awoodard 1.44 elif SortBy == "rateSigmaDiff":
572     SortedData=sorted(Data, key=lambda entry: abs(entry[4]),reverse=True)
573 amott 1.33 else:
574     print "Invalid sorting option %s\n"%SortBy
575     SortedData = Data
576    
577     #check for triggers above the warning threshold
578     Warn=[]
579 awoodard 1.51 core_data=[]
580 abrinke1 1.69 core_L1Seeds=[]
581 awoodard 1.64 nBadRates = 0
582 abrinke1 1.69 #Loop for HLT triggers
583 amott 1.33 for entry in SortedData:
584 awoodard 1.71 bad_seeds_string = ""
585 abrinke1 1.69 if not entry[0].startswith('HLT'):
586     continue
587 awoodard 1.71 bad_rate = (abs(entry[4]) > AllowedRateSigmaDiff and WarnOnSigmaDiff) or (abs(entry[3]) > AllowedRatePercDiff and not WarnOnSigmaDiff) or (abs(entry[3]) > AllowedRatePercDiff and RefParser.RunNumber > 0)
588 awoodard 1.72 if entry[0] in trig_list or ListIgnoredPaths or (bad_rate and ShowAllBadRates):
589 abrinke1 1.69 core_data.append(entry)
590     if bad_rate and nBadRates < MaxBadRates:
591 awoodard 1.71 # entry[6]=L1HLTseeds[entry[0]] ##Appends L1 names as warning message
592 abrinke1 1.69 for seed in L1HLTseeds[entry[0]]:
593 awoodard 1.71 seed_rate = [line[3] for line in SortedData if line[0] == seed]
594     if abs(seed_rate[0]) > AllowedRatePercDiff:
595     if bad_seeds_string != "":
596     bad_seeds_string += ", "
597     bad_seeds_string += seed
598 abrinke1 1.69 if not seed in core_L1Seeds:
599     core_L1Seeds.append(seed)
600 awoodard 1.71 entry[6] = bad_seeds_string
601 abrinke1 1.69 Warn.append(True)
602     nBadRates += 1
603     else:
604     Warn.append(False)
605    
606     ##Loop for L1 seeds of HLT triggers with warnings
607     for entry in SortedData:
608     if not entry[0] in core_L1Seeds:
609     continue
610     bad_rate = (abs(entry[3]) > AllowedRatePercDiff)
611 awoodard 1.71 if (entry[0] in trig_list and bad_rate and nBadRates < MaxBadRates) or ListIgnoredPaths or ShowAllBadRates:
612 awoodard 1.51 core_data.append(entry)
613 awoodard 1.71 if bad_rate:
614 awoodard 1.51 Warn.append(True)
615 awoodard 1.64 nBadRates += 1
616 awoodard 1.51 else:
617     Warn.append(False)
618 awoodard 1.64
619     for index,entry in enumerate(core_data):#Dont show 0s if we don't actually have a prediction; it's confusing
620     if entry[6] == "No prediction (fit missing)":
621     core_data[index] = [entry[0],entry[1],"--","--","--",entry[5],entry[6]]
622 awoodard 1.71 if entry[0].startswith('L1'):
623     core_data[index] = [entry[0],entry[1],entry[2],entry[3],"--",entry[5],entry[6]]
624 amott 1.33
625 awoodard 1.71 comment_width = max([30,max([len(col[6]) for col in core_data])+1])
626     if RefParser.RunNumber > 0:
627     Header = ["Trigger Name", "Actual", "Ref Run", "% Diff", "Cur PS", "Comments"]
628     table_data = [[col[0], col[1], col[2], col[3], col[5], col[6]] for col in core_data]
629     PrettyPrintTable(Header,table_data,[80,10,10,10,10,comment_width],Warn)
630     elif ShowSigmaAndPercDiff == 1:
631 awoodard 1.47 Header = ["Trigger Name", "Actual", "Expected","% Diff","Deviation", "Cur PS", "Comments"]
632 awoodard 1.51 table_data=core_data
633 awoodard 1.71 PrettyPrintTable(Header,table_data,[80,10,10,10,11,10,comment_width],Warn)
634 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
635 awoodard 1.47 elif WarnOnSigmaDiff == 1:
636 awoodard 1.45 Header = ["Trigger Name", "Actual", "Expected","Deviation", "Cur PS", "Comments"]
637 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[4], col[5], col[6]] for col in core_data]
638 awoodard 1.71 PrettyPrintTable(Header,table_data,[80,10,10,10,11,10,comment_width],Warn)
639 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
640 awoodard 1.44 else:
641 awoodard 1.47 Header = ["Trigger Name", "Actual", "Expected", "% Diff", "Cur PS", "Comments"]
642 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[3], col[5], col[6]] for col in core_data]
643 awoodard 1.71 PrettyPrintTable(Header,table_data,[80,10,10,10,10,comment_width],Warn)
644 awoodard 1.44
645 muell149 1.50 if writeb:
646 awoodard 1.71 prettyCSVwriter("rateMon_newmenu.csv",[80,10,10,10,10,20,comment_width],Header,core_data,Warn)
647 awoodard 1.45
648 awoodard 1.49 MoreTableInfo(HeadParser,HeadLumiRange,Config,True)
649 awoodard 1.71 if RefParser.RunNumber > 0:
650     print "The average instantaneous lumi for the reference run is: %s e30\n" % (round(RefAvInstLumi,1))
651 amott 1.1
652 awoodard 1.64 if nBadRates == MaxBadRates:
653     write(bcolors.WARNING)
654     print "The number of paths with rates outside limits exceeds the maximum number to display; only the first %i with the highest rate are shown above." % (MaxBadRates)
655     write(bcolors.ENDC+"\n")
656    
657 grchrist 1.39 for warning in Warn:
658     if warning==True:
659     write(bcolors.WARNING)
660 grchrist 1.60 print "If any trigger remains red for 5 minutes, Please consult the shift crew and if needed contact relevant experts"
661 grchrist 1.39 print "More instructions at https://twiki.cern.ch/twiki/bin/view/CMS/TriggerShiftHLTGuide"
662     write(bcolors.ENDC+"\n")
663     break
664 awoodard 1.51
665    
666 awoodard 1.44 def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedPercRateDiff,IgnoreThreshold,Config):
667 amott 1.1 L1Zeros=[]
668     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
669     for key in HeadParser.TriggerRates:
670     ## Skip events in the skip list
671     skipTrig=False
672     ##for trig in Config.ExcludeList:
673     ##if not trigN.find(trig) == -1:
674     ##skipTrig=True
675     ##break
676     if skipTrig:
677     continue
678     ## if no events pass the L1, add it to the L1Zeros list if not already there
679     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
680     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:
681    
682     L1Zeros.append(HeadParser.TriggerRates[key][4])
683     print "L1Zeros=", L1Zeros
684    
685     if len(L1Zeros) == 0:
686     #print "It looks like no masked L1 bits seed trigger paths"
687     pass
688     else:
689     print "The following seeds are used to seed HLT bits but accept 0 events:"
690     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
691     for Seed in L1Zeros:
692     print Seed
693 awoodard 1.55
694     def isSequential(t):
695     try:
696     if len(t)<2:
697     return True
698     except:
699     return True
700     for i,e in enumerate(t[1:]):
701     if not abs(e-t[i])==1:
702     return False
703     return True
704    
705     def getSequential(range):
706     for i,j in zip(range[-2::-1],range[::-1]):
707     if j-i != 1:
708     range = range[range.index(j):]
709     return range
710    
711    
712 amott 1.1 if __name__=='__main__':
713 grchrist 1.20 global thisyear
714 amott 1.1 main()