ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.66
Committed: Tue Nov 20 11:23:39 2012 UTC (12 years, 5 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
Changes since 1.65: +4 -6 lines
Log Message:
bug fix

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     RefParser = pickle.load( open( RefRunFile ) )
212    
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    
221 grchrist 1.22 if not isGood:
222 grchrist 1.23 print "NO TRIGGER KEY FOUND for run ",CompareRunNum
223 grchrist 1.22
224 grchrist 1.23 ##sys.exit(0)
225 amott 1.1
226     if not isCol:
227     print "Most Recent run, "+str(CompareRunNum)+", is NOT collisions"
228 amott 1.16 print "Monitoring only stream A and Express"
229     #if not Force:
230     # sys.exit(0) # maybe we should walk back and try to find a collisions run, but for now just exit
231 grchrist 1.23
232     else:
233     print "Most Recent run is "+str(CompareRunNum)
234 amott 1.16 else:
235 grchrist 1.22 CompareRunNum,isCol,isGood = GetLatestRunNumber(CompareRunNum)
236     if not isGood:
237 grchrist 1.23 print "NO TRIGGER KEY FOUND for run ", CompareRunNum
238     ##sys.exit(0)
239 amott 1.17
240 grchrist 1.23
241 amott 1.17 HeadParser = DatabaseParser()
242     HeadParser.RunNumber = CompareRunNum
243 grchrist 1.23
244     try:
245     HeadParser.ParseRunSetup()
246     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
247 grchrist 1.43 LastGoodLS=HeadParser.GetLastLS(isCol)+1
248     tempLastGoodLS=LastGoodLS
249 grchrist 1.23 CurrRun=CompareRunNum
250 grchrist 1.43 #print "done good"
251 grchrist 1.23 except:
252 grchrist 1.43 #print "exception"
253 grchrist 1.23 HeadLumiRange=[]
254     LastGoodLS=-1
255 grchrist 1.43 tempLastGoodLS=LastGoodLS-1
256 grchrist 1.23 CurrRun=CompareRunNum
257     isGood=0
258    
259     if len(HeadLumiRange) is 0:
260 grchrist 1.36 print "No lumisections that are taking physics data 0"
261 grchrist 1.23 HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
262     if len(HeadLumiRange)>0:
263     isGood=1
264     isCol=0
265     ##sys.exit(0)
266 awoodard 1.44
267 awoodard 1.45 ## This reduces the sensitivity for a rate measurement to cause a warning during the beginning of a run
268 awoodard 1.49 if len(HeadLumiRange) > 0 and len(HeadLumiRange) < 10:
269 awoodard 1.44 AllowedRateSigmaDiff = AllowedRateSigmaDiff*10 / len(HeadLumiRange)
270 grchrist 1.23
271 amott 1.1 if PrintLumi:
272     for LS in HeadParser.LumiInfo[0]:
273     try:
274     if (LS < FirstLS or LS > LastLS) and not FirstLS==999999:
275     continue
276     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))
277     except:
278     print "Lumisection "+str(LS-1)+" was not parsed from the LumiSections page"
279    
280 grchrist 1.23 sys.exit(0)
281 amott 1.1
282     if RefRunNum == 0:
283     RefRates = 0
284     RefLumis = 0
285     LastSuccessfulIterator = 0
286    
287     ### Now actually compare the rates, make tables and look at L1. Loops for ShifterMode
288 grchrist 1.23 ###isGood=1##if there is a trigger key
289 amott 1.1 try:
290     while True:
291 grchrist 1.23 if isGood:
292 grchrist 1.43 tempLastGoodLS=LastGoodLS
293 grchrist 1.23 LastGoodLS=HeadParser.GetLastLS(isCol)
294 grchrist 1.43 ##print "Last Good=",LastGoodLS, tempLastGoodLS
295     if LastGoodLS==tempLastGoodLS:
296 grchrist 1.58 write(bcolors.OKBLUE)
297 grchrist 1.43 print "Trying to get new Run"
298     write(bcolors.ENDC+"\n")
299     else:
300     RefMoreLumiArray = HeadParser.GetMoreLumiInfo()
301     isBeams=True
302     for lumisection in HeadLumiRange:
303     try:
304     if not (RefMoreLumiArray["b1pres"][lumisection] and RefMoreLumiArray["b2pres"][lumisection] and RefMoreLumiArray["b1stab"][lumisection] and RefMoreLumiArray["b2stab"][lumisection]):
305     isBeams=False
306     except:
307 grchrist 1.41 isBeams=False
308 awoodard 1.55
309 grchrist 1.43 if not (isCol and isBeams):
310 grchrist 1.23 ##clear()
311 grchrist 1.43 MoreTableInfo(HeadParser,HeadLumiRange,Config,False)
312 grchrist 1.25 else:
313 grchrist 1.43 if (len(HeadLumiRange)>0):
314 awoodard 1.55 if not isSequential(HeadLumiRange):
315     print "Some lumisections have been skipped. Averaging over most recent sequential lumisections..."
316     sequential_chunk = getSequential(HeadLumiRange)
317     HeadLumiRange = sequential_chunk
318 awoodard 1.64 RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,ListIgnoredPaths,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates,MaxBadRates)
319 grchrist 1.43 if FindL1Zeros:
320 awoodard 1.44 CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config)
321 grchrist 1.43 else:
322     print "No lumisections that are taking physics data 1"
323 amott 1.33 if ShifterMode:
324 grchrist 1.23 #print "Shifter Mode. Continuing"
325     pass
326 amott 1.2 else:
327 grchrist 1.23 print "Expert Mode. Quitting."
328     sys.exit(0)
329 amott 1.2
330 amott 1.1 print "Sleeping for 1 minute before repeating "
331 amott 1.16 for iSleep in range(20):
332 amott 1.15 write(".")
333     sys.stdout.flush()
334 amott 1.16 time.sleep(3)
335 grchrist 1.23 write(" Updating\n")
336 amott 1.15 sys.stdout.flush()
337 grchrist 1.23
338     ##print "\nminLS=",min(HeadLumiRange),"Last LS=",HeadParser.GetLastLS(isCol),"run=",HeadParser.RunNumber
339     ###Get a new run if DAQ stops
340     ##print "\nLastGoodLS=",LastGoodLS
341    
342     ##### NEED PLACEHOLDER TO COMPARE CURRENT RUN TO LATEST RUN #####
343    
344     NewRun,isCol,isGood = GetLatestRunNumber(9999999) ## update to the latest run and lumi range
345    
346     try:
347     maxLumi=max(HeadLumiRange)
348     except:
349     maxLumi=0
350    
351     ##### THESE ARE CONDITIONS TO GET NEW RUN #####
352     if maxLumi>(LastGoodLS+1) or not isGood or NewRun!=CurrRun:
353     print "Trying to get new Run"
354     try:
355     HeadParser = DatabaseParser()
356     HeadParser.RunNumber = NewRun
357     HeadParser.ParseRunSetup()
358     CurrRun,isCol,isGood=GetLatestRunNumber(9999999)
359     FirstLS=9999
360     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
361     if len(HeadLumiRange) is 0:
362     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
363 grchrist 1.36 print "No lumisections that are taking physics data 2"
364 grchrist 1.23 if len(HeadLumiRange)>0:
365     isGood=1
366     isCol=0
367    
368 grchrist 1.43 #tempLastGoodLS=LastGoodLS
369     #LastGoodLS=HeadParser.GetLastLS(isCol)
370 grchrist 1.25 ##print CurrRun, isCol, isGood
371 grchrist 1.23 except:
372     isGood=0
373     isCol=0
374     print "failed"
375 awoodard 1.49
376 grchrist 1.23 else:
377     try:
378     HeadParser.ParseRunSetup()
379     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
380     if len(HeadLumiRange) is 0:
381     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
382 grchrist 1.26 print "No lumisections that are taking physics data"
383 grchrist 1.23 if len(HeadLumiRange)>0:
384     isGood=1
385     isCol=0
386 grchrist 1.43 #LastGoodLS=HeadParser.GetLastLS(isCol)
387 grchrist 1.23
388     except:
389     isGood=0
390     isCol=0
391     clear()
392     print "NO TRIGGER KEY FOUND YET for run", NewRun ,"repeating search"
393    
394 grchrist 1.22
395 amott 1.1 except KeyboardInterrupt:
396     print "Quitting. Peace Out."
397    
398    
399 awoodard 1.64 def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,ListIgnoredPaths,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates,MaxBadRates):
400 amott 1.1 Data = []
401     Warn = []
402     IgnoredRates=[]
403 grchrist 1.23
404 abrinke1 1.9 [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
405 abrinke1 1.3 ##[HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
406     HeadUnprescaledRates = HeadParser.UpdateRun(HeadLumiRange)
407 grchrist 1.59 if Config.DoL1:
408     L1RatesALL=HeadParser.GetL1RatesALL(HeadLumiRange)
409     for L1seed in L1RatesALL.iterkeys():
410     HeadUnprescaledRates[L1seed]=L1RatesALL[L1seed]
411 grchrist 1.56
412 abrinke1 1.9 [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS,PhysicsByLS,ActiveByLS] = HeadParser.LumiInfo
413 grchrist 1.30 deadtimebeamactive=HeadParser.GetDeadTimeBeamActive(HeadLumiRange)
414 grchrist 1.18 try:
415     pkl_file = open(Config.FitFileName, 'rb')
416     FitInput = pickle.load(pkl_file)
417     pkl_file.close()
418 grchrist 1.29 ##print "fit file name=",Config.FitFileName
419 grchrist 1.31
420 grchrist 1.18 except:
421 grchrist 1.27 print "No fit file specified"
422 grchrist 1.20 sys.exit(2)
423    
424 grchrist 1.23 try:
425     refrunfile="RefRuns/%s/Rates_HLT_10LS_JPAP.pkl" % (thisyear)
426     pkl_file = open(refrunfile, 'rb')
427     RefRatesInput = pickle.load(pkl_file)
428     pkl_file.close()
429     except:
430 grchrist 1.24 RefRatesInput={}
431 grchrist 1.62 #print "Didn't open ref file"
432 amott 1.1
433 grchrist 1.30
434     trig_list=Config.MonitorList
435    
436     if Config.NoVersion:
437     trig_list=[]
438    
439     for trigger in Config.MonitorList:
440     trig_list.append(StripVersion(trigger))
441 grchrist 1.56 if Config.DoL1:
442     L1HLTseeds=HeadParser.GetL1HLTseeds()
443     for HLTkey in trig_list:
444     if "L1" in HLTkey:
445     continue
446     else:
447     try:
448     for L1seed in L1HLTseeds[HLTkey]:
449     if L1seed not in trig_list:
450     trig_list.append(L1seed)
451     except:
452     pass
453 grchrist 1.30 for trigger in FitInput.iterkeys():
454 awoodard 1.51 FitInput[StripVersion(trigger)]=FitInput.pop(trigger)
455     for trigger in HeadUnprescaledRates:
456     HeadUnprescaledRates[StripVersion(trigger)]=HeadUnprescaledRates.pop(trigger)
457 grchrist 1.57
458 awoodard 1.49 else:
459     trig_list=Config.MonitorList
460    
461 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
462 awoodard 1.49 if RefParser.RunNumber == 0: ## If not ref run then just use trigger list
463 awoodard 1.51 if HeadName not in trig_list and not ListIgnoredPaths and not ShowAllBadRates:
464     continue
465     if HeadName not in FitInput.keys() and not ListIgnoredPaths and not ShowAllBadRates:
466     continue
467 awoodard 1.49
468 grchrist 1.63 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero","HLT_BeamHalo"]
469 abrinke1 1.9 masked_trig = False
470     for mask in masked_triggers:
471     if str(mask) in HeadName:
472     masked_trig = True
473     if masked_trig:
474     continue
475    
476 amott 1.1 skipTrig=False
477 abrinke1 1.3 TriggerRate = round(HeadUnprescaledRates[HeadName][2],2)
478 awoodard 1.49
479 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
480 grchrist 1.32 try:
481 awoodard 1.66 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,RefRatesInput,HeadAvLiveLumi,HeadAvDeliveredLumi,deadtimebeamactive)
482     VC = PSCorrectedExpectedRate[2]
483 awoodard 1.52 sigma = PSCorrectedExpectedRate[1]/(sqrt(len(HeadLumiRange))* HeadUnprescaledRates[HeadName][1])
484 awoodard 1.66 ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
485 grchrist 1.32 except:
486 awoodard 1.65 sigma = 0.0
487 awoodard 1.66 ExpectedRate = 0.0 ##This means we don't have a prediction for this trigger-- gets overwritten to "--" later
488 awoodard 1.52 PerDiff = 0.0
489     SigmaDiff = 0.0
490 awoodard 1.53 if HeadUnprescaledRates[HeadName][1] != 0:
491     VC="No prediction"
492 awoodard 1.64 else:
493     VC="Path prescaled to 0"
494 grchrist 1.30
495 awoodard 1.51 if ExpectedRate > 0:
496 amott 1.1 PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
497 grchrist 1.37 else:
498 awoodard 1.52 PerDiff = 0.0
499 awoodard 1.51
500 awoodard 1.52 if sigma > 0:
501 awoodard 1.51 SigmaDiff = round( (TriggerRate - ExpectedRate)/sigma, 2)
502     else:
503 awoodard 1.64 SigmaDiff = 0.0 #Zero sigma means that when there were no rates for this trigger when the fit was made
504 amott 1.1
505 amott 1.33 if TriggerRate < IgnoreThreshold and (ExpectedRate < IgnoreThreshold and ExpectedRate!=0):
506 amott 1.1 continue
507    
508 awoodard 1.64
509     Data.append([HeadName, TriggerRate, ExpectedRate, PerDiff, SigmaDiff, round(HeadUnprescaledRates[HeadName][1],0),VC])
510 amott 1.1
511     else: ## Use a reference run
512     ## cheap trick to only get triggers in list when in shifter mode
513     #print "shifter mode=",int(Config.ShifterMode)
514 grchrist 1.34 ## continue
515 amott 1.1
516     RefInstLumi = 0
517     RefIterator = 0
518     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
519     RefLen = -10
520 grchrist 1.34
521    
522 abrinke1 1.3 RefUnprescaledRates = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
523 amott 1.1 [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
524 grchrist 1.34 deadtimebeamactive=RefParser.GetDeadTimeBeamActive(RefParser.GetLSRange(RefStartIndex,RefLen))
525    
526 amott 1.1 RefRate = -1
527     for k,v in RefUnprescaledRates.iteritems():
528 grchrist 1.34 if HeadName==k:
529     RefRate = RefUnprescaledRates[k][2]
530    
531     try:
532     ScaledRefRate = round( (RefRate*HeadAvLiveLumi/RefAvLiveLumi*(1-deadtimebeamactive)), 2 )
533    
534     except ZeroDivisionError:
535     ScaledRefRate=0
536    
537 awoodard 1.44 SigmaDiff = 0
538 amott 1.1 if ScaledRefRate == 0:
539 awoodard 1.44 PerDiff = -999
540 amott 1.1 else:
541     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
542 awoodard 1.44
543 amott 1.1 if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
544     continue
545    
546     VC = ""
547 awoodard 1.64 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,SigmaDiff,round((HeadUnprescaledRates[HeadName][1]),0),VC])
548 amott 1.1
549 amott 1.33 SortedData = []
550     if SortBy == "":
551     SortedData = Data # don't do any sorting
552 grchrist 1.35 if RefParser.RunNumber>0:
553 grchrist 1.34 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
554 amott 1.33 elif SortBy == "name":
555     SortedData=sorted(Data, key=lambda entry: entry[0])
556     elif SortBy == "rate":
557     SortedData=sorted(Data, key=lambda entry: entry[1],reverse=True)
558 awoodard 1.44 elif SortBy == "ratePercDiff":
559 amott 1.33 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
560 awoodard 1.44 elif SortBy == "rateSigmaDiff":
561     SortedData=sorted(Data, key=lambda entry: abs(entry[4]),reverse=True)
562 amott 1.33 else:
563     print "Invalid sorting option %s\n"%SortBy
564     SortedData = Data
565    
566     #check for triggers above the warning threshold
567     Warn=[]
568 awoodard 1.51 core_data=[]
569 awoodard 1.64 nBadRates = 0
570 amott 1.33 for entry in SortedData:
571 awoodard 1.51 bad_rate = (abs(entry[4]) > AllowedRateSigmaDiff and WarnOnSigmaDiff) or (abs(entry[3]) > AllowedRatePercDiff and not WarnOnSigmaDiff)
572     if entry[0] in trig_list or ListIgnoredPaths:
573     core_data.append(entry)
574 awoodard 1.64 if bad_rate and nBadRates < MaxBadRates:
575 awoodard 1.51 Warn.append(True)
576 awoodard 1.64 nBadRates += 1
577 awoodard 1.51 else:
578     Warn.append(False)
579 amott 1.33 else:
580 awoodard 1.64 if bad_rate and ShowAllBadRates and nBadRates < MaxBadRates:
581 awoodard 1.51 core_data.append(entry)
582     Warn.append(True)
583 awoodard 1.64 nBadRates += 1
584    
585     for index,entry in enumerate(core_data):#Dont show 0s if we don't actually have a prediction; it's confusing
586     if entry[6] == "No prediction (fit missing)":
587     core_data[index] = [entry[0],entry[1],"--","--","--",entry[5],entry[6]]
588 amott 1.33
589 awoodard 1.47 if ShowSigmaAndPercDiff == 1:
590     Header = ["Trigger Name", "Actual", "Expected","% Diff","Deviation", "Cur PS", "Comments"]
591 awoodard 1.51 table_data=core_data
592 awoodard 1.64 PrettyPrintTable(Header,table_data,[80,10,10,10,10,10,30],Warn)
593 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
594 awoodard 1.47 elif WarnOnSigmaDiff == 1:
595 awoodard 1.45 Header = ["Trigger Name", "Actual", "Expected","Deviation", "Cur PS", "Comments"]
596 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[4], col[5], col[6]] for col in core_data]
597 awoodard 1.64 PrettyPrintTable(Header,table_data,[80,10,10,10,10,10,30],Warn)
598 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
599 awoodard 1.44 else:
600 awoodard 1.47 Header = ["Trigger Name", "Actual", "Expected", "% Diff", "Cur PS", "Comments"]
601 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[3], col[5], col[6]] for col in core_data]
602 awoodard 1.64 PrettyPrintTable(Header,table_data,[80,10,10,10,10,30],Warn)
603 awoodard 1.44
604 muell149 1.50 if writeb:
605 awoodard 1.64 prettyCSVwriter("rateMon_newmenu.csv",[80,10,10,10,10,20,30],Header,core_data,Warn)
606 awoodard 1.45
607 awoodard 1.49 MoreTableInfo(HeadParser,HeadLumiRange,Config,True)
608 amott 1.1
609 awoodard 1.64 if nBadRates == MaxBadRates:
610     write(bcolors.WARNING)
611     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)
612     write(bcolors.ENDC+"\n")
613    
614 grchrist 1.39 for warning in Warn:
615     if warning==True:
616     write(bcolors.WARNING)
617 grchrist 1.60 print "If any trigger remains red for 5 minutes, Please consult the shift crew and if needed contact relevant experts"
618 grchrist 1.39 print "More instructions at https://twiki.cern.ch/twiki/bin/view/CMS/TriggerShiftHLTGuide"
619     write(bcolors.ENDC+"\n")
620     break
621 awoodard 1.51
622    
623 awoodard 1.44 def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedPercRateDiff,IgnoreThreshold,Config):
624 amott 1.1 L1Zeros=[]
625     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
626     for key in HeadParser.TriggerRates:
627     ## Skip events in the skip list
628     skipTrig=False
629     ##for trig in Config.ExcludeList:
630     ##if not trigN.find(trig) == -1:
631     ##skipTrig=True
632     ##break
633     if skipTrig:
634     continue
635     ## if no events pass the L1, add it to the L1Zeros list if not already there
636     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
637     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:
638    
639     L1Zeros.append(HeadParser.TriggerRates[key][4])
640     print "L1Zeros=", L1Zeros
641    
642     if len(L1Zeros) == 0:
643     #print "It looks like no masked L1 bits seed trigger paths"
644     pass
645     else:
646     print "The following seeds are used to seed HLT bits but accept 0 events:"
647     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
648     for Seed in L1Zeros:
649     print Seed
650 awoodard 1.55
651     def isSequential(t):
652     try:
653     if len(t)<2:
654     return True
655     except:
656     return True
657     for i,e in enumerate(t[1:]):
658     if not abs(e-t[i])==1:
659     return False
660     return True
661    
662     def getSequential(range):
663     for i,j in zip(range[-2::-1],range[::-1]):
664     if j-i != 1:
665     range = range[range.index(j):]
666     return range
667    
668    
669 amott 1.1 if __name__=='__main__':
670 grchrist 1.20 global thisyear
671 amott 1.1 main()