ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.69
Committed: Thu Nov 22 10:53:10 2012 UTC (12 years, 5 months ago) by abrinke1
Content type: text/x-python
Branch: MAIN
Changes since 1.68: +35 -1 lines
Log Message:
Now only displays L1 seeds for HLT seeds with warnings

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 grchrist 1.68
424     ###fitfile by L1seedchange
425     if Config.L1SeedChangeFit:
426     try:
427     PSfitfile=Config.FitFileName.replace("HLT_NoV","HLT_NoV_ByPS")
428     print "Opening", PSfitfile
429     pkl_filePS = open(PSfitfile, 'rb')
430     FitInputPS = pickle.load(pkl_filePS)
431     pkl_filePS.close()
432     ##print "fit file name=",Config.FitFileName
433 grchrist 1.20
434 grchrist 1.68 except:
435     print "No fit file by L1seed change specified"
436     sys.exit(2)
437     else:
438     FitInputPS={} ##define empty dict when not in use
439 grchrist 1.23 try:
440     refrunfile="RefRuns/%s/Rates_HLT_10LS_JPAP.pkl" % (thisyear)
441     pkl_file = open(refrunfile, 'rb')
442     RefRatesInput = pickle.load(pkl_file)
443     pkl_file.close()
444     except:
445 grchrist 1.24 RefRatesInput={}
446 grchrist 1.62 #print "Didn't open ref file"
447 amott 1.1
448 grchrist 1.30
449     trig_list=Config.MonitorList
450    
451     if Config.NoVersion:
452     trig_list=[]
453    
454     for trigger in Config.MonitorList:
455     trig_list.append(StripVersion(trigger))
456 grchrist 1.56 if Config.DoL1:
457     L1HLTseeds=HeadParser.GetL1HLTseeds()
458     for HLTkey in trig_list:
459     if "L1" in HLTkey:
460     continue
461     else:
462     try:
463     for L1seed in L1HLTseeds[HLTkey]:
464     if L1seed not in trig_list:
465     trig_list.append(L1seed)
466     except:
467     pass
468 grchrist 1.30 for trigger in FitInput.iterkeys():
469 awoodard 1.51 FitInput[StripVersion(trigger)]=FitInput.pop(trigger)
470     for trigger in HeadUnprescaledRates:
471     HeadUnprescaledRates[StripVersion(trigger)]=HeadUnprescaledRates.pop(trigger)
472 grchrist 1.57
473 awoodard 1.49 else:
474     trig_list=Config.MonitorList
475    
476 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
477 awoodard 1.49 if RefParser.RunNumber == 0: ## If not ref run then just use trigger list
478 awoodard 1.51 if HeadName not in trig_list and not ListIgnoredPaths and not ShowAllBadRates:
479     continue
480     if HeadName not in FitInput.keys() and not ListIgnoredPaths and not ShowAllBadRates:
481     continue
482 awoodard 1.49
483 grchrist 1.63 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero","HLT_BeamHalo"]
484 abrinke1 1.9 masked_trig = False
485     for mask in masked_triggers:
486     if str(mask) in HeadName:
487     masked_trig = True
488     if masked_trig:
489     continue
490    
491 amott 1.1 skipTrig=False
492 abrinke1 1.3 TriggerRate = round(HeadUnprescaledRates[HeadName][2],2)
493 grchrist 1.68
494    
495 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
496 grchrist 1.68 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,FitInputPS,RefRatesInput,HeadAvLiveLumi,HeadAvDeliveredLumi,deadtimebeamactive,Config.L1SeedChangeFit,HeadLumiRange,PSColumnByLS)
497 awoodard 1.67 VC = PSCorrectedExpectedRate[2]
498 grchrist 1.32 try:
499 awoodard 1.52 sigma = PSCorrectedExpectedRate[1]/(sqrt(len(HeadLumiRange))* HeadUnprescaledRates[HeadName][1])
500 awoodard 1.66 ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
501 grchrist 1.32 except:
502 awoodard 1.65 sigma = 0.0
503 awoodard 1.66 ExpectedRate = 0.0 ##This means we don't have a prediction for this trigger-- gets overwritten to "--" later
504 awoodard 1.52 PerDiff = 0.0
505     SigmaDiff = 0.0
506 awoodard 1.53 if HeadUnprescaledRates[HeadName][1] != 0:
507     VC="No prediction"
508 awoodard 1.64 else:
509     VC="Path prescaled to 0"
510 grchrist 1.30
511 awoodard 1.51 if ExpectedRate > 0:
512 amott 1.1 PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
513 grchrist 1.37 else:
514 awoodard 1.52 PerDiff = 0.0
515 awoodard 1.51
516 awoodard 1.52 if sigma > 0:
517 awoodard 1.51 SigmaDiff = round( (TriggerRate - ExpectedRate)/sigma, 2)
518     else:
519 awoodard 1.64 SigmaDiff = 0.0 #Zero sigma means that when there were no rates for this trigger when the fit was made
520 amott 1.1
521 amott 1.33 if TriggerRate < IgnoreThreshold and (ExpectedRate < IgnoreThreshold and ExpectedRate!=0):
522 amott 1.1 continue
523    
524 awoodard 1.64
525     Data.append([HeadName, TriggerRate, ExpectedRate, PerDiff, SigmaDiff, round(HeadUnprescaledRates[HeadName][1],0),VC])
526 amott 1.1
527     else: ## Use a reference run
528     ## cheap trick to only get triggers in list when in shifter mode
529     #print "shifter mode=",int(Config.ShifterMode)
530 grchrist 1.34 ## continue
531 amott 1.1
532     RefInstLumi = 0
533     RefIterator = 0
534     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
535     RefLen = -10
536 grchrist 1.34
537    
538 abrinke1 1.3 RefUnprescaledRates = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
539 amott 1.1 [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
540 grchrist 1.34 deadtimebeamactive=RefParser.GetDeadTimeBeamActive(RefParser.GetLSRange(RefStartIndex,RefLen))
541    
542 amott 1.1 RefRate = -1
543     for k,v in RefUnprescaledRates.iteritems():
544 grchrist 1.34 if HeadName==k:
545     RefRate = RefUnprescaledRates[k][2]
546    
547     try:
548     ScaledRefRate = round( (RefRate*HeadAvLiveLumi/RefAvLiveLumi*(1-deadtimebeamactive)), 2 )
549    
550     except ZeroDivisionError:
551     ScaledRefRate=0
552    
553 awoodard 1.44 SigmaDiff = 0
554 amott 1.1 if ScaledRefRate == 0:
555 awoodard 1.44 PerDiff = -999
556 amott 1.1 else:
557     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
558 awoodard 1.44
559 amott 1.1 if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
560     continue
561    
562     VC = ""
563 awoodard 1.64 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,SigmaDiff,round((HeadUnprescaledRates[HeadName][1]),0),VC])
564 amott 1.1
565 amott 1.33 SortedData = []
566     if SortBy == "":
567     SortedData = Data # don't do any sorting
568 grchrist 1.35 if RefParser.RunNumber>0:
569 grchrist 1.34 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
570 amott 1.33 elif SortBy == "name":
571     SortedData=sorted(Data, key=lambda entry: entry[0])
572     elif SortBy == "rate":
573     SortedData=sorted(Data, key=lambda entry: entry[1],reverse=True)
574 awoodard 1.44 elif SortBy == "ratePercDiff":
575 amott 1.33 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
576 awoodard 1.44 elif SortBy == "rateSigmaDiff":
577     SortedData=sorted(Data, key=lambda entry: abs(entry[4]),reverse=True)
578 amott 1.33 else:
579     print "Invalid sorting option %s\n"%SortBy
580     SortedData = Data
581    
582     #check for triggers above the warning threshold
583     Warn=[]
584 awoodard 1.51 core_data=[]
585 abrinke1 1.69 core_L1Seeds=[]
586 awoodard 1.64 nBadRates = 0
587 abrinke1 1.69 #Loop for HLT triggers
588 amott 1.33 for entry in SortedData:
589 abrinke1 1.69 if not entry[0].startswith('HLT'):
590     continue
591     bad_rate = (abs(entry[4]) > AllowedRateSigmaDiff and WarnOnSigmaDiff) or (abs(entry[3]) > AllowedRatePercDiff and not WarnOnSigmaDiff )
592     if entry[0] in trig_list or ListIgnoredPaths:
593     core_data.append(entry)
594     if bad_rate and nBadRates < MaxBadRates:
595     entry[6]=L1HLTseeds[entry[0]] ##Appends L1 names as warning message
596     for seed in L1HLTseeds[entry[0]]:
597     if not seed in core_L1Seeds:
598     core_L1Seeds.append(seed)
599     print seed
600     Warn.append(True)
601     nBadRates += 1
602     else:
603     Warn.append(False)
604     else:
605     if bad_rate and ShowAllBadRates and nBadRates < MaxBadRates:
606     core_data.append(entry)
607     entry[6]=L1HLTseeds[entry[0]] ##Appends L1 names as warning message
608     for seed in L1HLTseeds[entry[0]]:
609     if not seed in core_L1Seeds:
610     core_L1Seeds.append(seed)
611     print seed
612     core_L1Seeds.append(L1HLTseeds[entry[0]])
613     print L1HLTseeds[entry[0]]
614     Warn.append(True)
615     nBadRates += 1
616    
617     ##Loop for L1 seeds of HLT triggers with warnings
618     for entry in SortedData:
619     if not entry[0] in core_L1Seeds:
620     continue
621     bad_rate = (abs(entry[3]) > AllowedRatePercDiff)
622 awoodard 1.51 if entry[0] in trig_list or ListIgnoredPaths:
623     core_data.append(entry)
624 awoodard 1.64 if bad_rate and nBadRates < MaxBadRates:
625 awoodard 1.51 Warn.append(True)
626 awoodard 1.64 nBadRates += 1
627 awoodard 1.51 else:
628     Warn.append(False)
629 amott 1.33 else:
630 awoodard 1.64 if bad_rate and ShowAllBadRates and nBadRates < MaxBadRates:
631 awoodard 1.51 core_data.append(entry)
632     Warn.append(True)
633 awoodard 1.64 nBadRates += 1
634    
635     for index,entry in enumerate(core_data):#Dont show 0s if we don't actually have a prediction; it's confusing
636     if entry[6] == "No prediction (fit missing)":
637     core_data[index] = [entry[0],entry[1],"--","--","--",entry[5],entry[6]]
638 amott 1.33
639 awoodard 1.47 if ShowSigmaAndPercDiff == 1:
640     Header = ["Trigger Name", "Actual", "Expected","% Diff","Deviation", "Cur PS", "Comments"]
641 awoodard 1.51 table_data=core_data
642 awoodard 1.64 PrettyPrintTable(Header,table_data,[80,10,10,10,10,10,30],Warn)
643 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
644 awoodard 1.47 elif WarnOnSigmaDiff == 1:
645 awoodard 1.45 Header = ["Trigger Name", "Actual", "Expected","Deviation", "Cur PS", "Comments"]
646 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[4], col[5], col[6]] for col in core_data]
647 awoodard 1.64 PrettyPrintTable(Header,table_data,[80,10,10,10,10,10,30],Warn)
648 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
649 awoodard 1.44 else:
650 awoodard 1.47 Header = ["Trigger Name", "Actual", "Expected", "% Diff", "Cur PS", "Comments"]
651 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[3], col[5], col[6]] for col in core_data]
652 awoodard 1.64 PrettyPrintTable(Header,table_data,[80,10,10,10,10,30],Warn)
653 awoodard 1.44
654 muell149 1.50 if writeb:
655 awoodard 1.64 prettyCSVwriter("rateMon_newmenu.csv",[80,10,10,10,10,20,30],Header,core_data,Warn)
656 awoodard 1.45
657 awoodard 1.49 MoreTableInfo(HeadParser,HeadLumiRange,Config,True)
658 amott 1.1
659 awoodard 1.64 if nBadRates == MaxBadRates:
660     write(bcolors.WARNING)
661     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)
662     write(bcolors.ENDC+"\n")
663    
664 grchrist 1.39 for warning in Warn:
665     if warning==True:
666     write(bcolors.WARNING)
667 grchrist 1.60 print "If any trigger remains red for 5 minutes, Please consult the shift crew and if needed contact relevant experts"
668 grchrist 1.39 print "More instructions at https://twiki.cern.ch/twiki/bin/view/CMS/TriggerShiftHLTGuide"
669     write(bcolors.ENDC+"\n")
670     break
671 awoodard 1.51
672    
673 awoodard 1.44 def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedPercRateDiff,IgnoreThreshold,Config):
674 amott 1.1 L1Zeros=[]
675     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
676     for key in HeadParser.TriggerRates:
677     ## Skip events in the skip list
678     skipTrig=False
679     ##for trig in Config.ExcludeList:
680     ##if not trigN.find(trig) == -1:
681     ##skipTrig=True
682     ##break
683     if skipTrig:
684     continue
685     ## if no events pass the L1, add it to the L1Zeros list if not already there
686     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
687     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:
688    
689     L1Zeros.append(HeadParser.TriggerRates[key][4])
690     print "L1Zeros=", L1Zeros
691    
692     if len(L1Zeros) == 0:
693     #print "It looks like no masked L1 bits seed trigger paths"
694     pass
695     else:
696     print "The following seeds are used to seed HLT bits but accept 0 events:"
697     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
698     for Seed in L1Zeros:
699     print Seed
700 awoodard 1.55
701     def isSequential(t):
702     try:
703     if len(t)<2:
704     return True
705     except:
706     return True
707     for i,e in enumerate(t[1:]):
708     if not abs(e-t[i])==1:
709     return False
710     return True
711    
712     def getSequential(range):
713     for i,j in zip(range[-2::-1],range[::-1]):
714     if j-i != 1:
715     range = range[range.index(j):]
716     return range
717    
718    
719 amott 1.1 if __name__=='__main__':
720 grchrist 1.20 global thisyear
721 amott 1.1 main()