ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.76
Committed: Fri Nov 30 18:59:32 2012 UTC (12 years, 5 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
Changes since 1.75: +21 -23 lines
Log Message:
fixing crash caused by low l1 rates

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 awoodard 1.76 print "--AllTriggers Prints the paths that are not compared by this script and their rate in the CompareRun"
45 amott 1.1 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 awoodard 1.76 "FirstLS=","NumberLS=","IgnoreLowRate=","AllTriggers",\
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.76 AllTriggers = Config.AllTriggers
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 awoodard 1.76 elif o=="--AllTriggers":
122     AllTriggers=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     MoreTableInfo(HeadParser,HeadLumiRange,Config,False)
307 grchrist 1.25 else:
308 grchrist 1.43 if (len(HeadLumiRange)>0):
309 awoodard 1.55 if not isSequential(HeadLumiRange):
310     print "Some lumisections have been skipped. Averaging over most recent sequential lumisections..."
311     sequential_chunk = getSequential(HeadLumiRange)
312     HeadLumiRange = sequential_chunk
313 awoodard 1.76 RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,AllTriggers,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates,MaxBadRates)
314 grchrist 1.43 if FindL1Zeros:
315 awoodard 1.44 CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config)
316 grchrist 1.43 else:
317     print "No lumisections that are taking physics data 1"
318 awoodard 1.76
319     if not ShifterMode:
320 grchrist 1.23 print "Expert Mode. Quitting."
321     sys.exit(0)
322 amott 1.2
323 amott 1.1 print "Sleeping for 1 minute before repeating "
324 awoodard 1.76
325 amott 1.16 for iSleep in range(20):
326 amott 1.15 write(".")
327     sys.stdout.flush()
328 amott 1.16 time.sleep(3)
329 grchrist 1.23 write(" Updating\n")
330 amott 1.15 sys.stdout.flush()
331 grchrist 1.23
332     ##print "\nminLS=",min(HeadLumiRange),"Last LS=",HeadParser.GetLastLS(isCol),"run=",HeadParser.RunNumber
333     ###Get a new run if DAQ stops
334     ##print "\nLastGoodLS=",LastGoodLS
335    
336     ##### NEED PLACEHOLDER TO COMPARE CURRENT RUN TO LATEST RUN #####
337    
338     NewRun,isCol,isGood = GetLatestRunNumber(9999999) ## update to the latest run and lumi range
339    
340     try:
341     maxLumi=max(HeadLumiRange)
342     except:
343     maxLumi=0
344    
345     ##### THESE ARE CONDITIONS TO GET NEW RUN #####
346     if maxLumi>(LastGoodLS+1) or not isGood or NewRun!=CurrRun:
347     print "Trying to get new Run"
348     try:
349     HeadParser = DatabaseParser()
350     HeadParser.RunNumber = NewRun
351     HeadParser.ParseRunSetup()
352     CurrRun,isCol,isGood=GetLatestRunNumber(9999999)
353     FirstLS=9999
354     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
355     if len(HeadLumiRange) is 0:
356     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
357 grchrist 1.36 print "No lumisections that are taking physics data 2"
358 grchrist 1.23 if len(HeadLumiRange)>0:
359     isGood=1
360     isCol=0
361    
362 grchrist 1.43 #tempLastGoodLS=LastGoodLS
363     #LastGoodLS=HeadParser.GetLastLS(isCol)
364 grchrist 1.25 ##print CurrRun, isCol, isGood
365 grchrist 1.23 except:
366     isGood=0
367     isCol=0
368     print "failed"
369 awoodard 1.49
370 grchrist 1.23 else:
371     try:
372     HeadParser.ParseRunSetup()
373     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
374     if len(HeadLumiRange) is 0:
375     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
376 grchrist 1.26 print "No lumisections that are taking physics data"
377 grchrist 1.23 if len(HeadLumiRange)>0:
378     isGood=1
379     isCol=0
380 grchrist 1.43 #LastGoodLS=HeadParser.GetLastLS(isCol)
381 grchrist 1.23 except:
382     isGood=0
383     isCol=0
384     clear()
385     print "NO TRIGGER KEY FOUND YET for run", NewRun ,"repeating search"
386    
387 grchrist 1.22
388 amott 1.1 except KeyboardInterrupt:
389     print "Quitting. Peace Out."
390    
391    
392 awoodard 1.76 def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,AllTriggers,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates,MaxBadRates):
393 amott 1.1 Data = []
394     Warn = []
395     IgnoredRates=[]
396 grchrist 1.23
397 abrinke1 1.9 [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
398 abrinke1 1.3 ##[HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
399     HeadUnprescaledRates = HeadParser.UpdateRun(HeadLumiRange)
400 grchrist 1.59 if Config.DoL1:
401     L1RatesALL=HeadParser.GetL1RatesALL(HeadLumiRange)
402     for L1seed in L1RatesALL.iterkeys():
403     HeadUnprescaledRates[L1seed]=L1RatesALL[L1seed]
404 grchrist 1.56
405 abrinke1 1.9 [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS,PhysicsByLS,ActiveByLS] = HeadParser.LumiInfo
406 grchrist 1.30 deadtimebeamactive=HeadParser.GetDeadTimeBeamActive(HeadLumiRange)
407 grchrist 1.18 try:
408     pkl_file = open(Config.FitFileName, 'rb')
409     FitInput = pickle.load(pkl_file)
410     pkl_file.close()
411 grchrist 1.29 ##print "fit file name=",Config.FitFileName
412 grchrist 1.31
413 grchrist 1.18 except:
414 grchrist 1.27 print "No fit file specified"
415 grchrist 1.20 sys.exit(2)
416 grchrist 1.68
417     ###fitfile by L1seedchange
418 awoodard 1.71 if Config.L1SeedChangeFit:
419 grchrist 1.68 try:
420     PSfitfile=Config.FitFileName.replace("HLT_NoV","HLT_NoV_ByPS")
421 awoodard 1.71 #print "Opening", PSfitfile
422 grchrist 1.68 pkl_filePS = open(PSfitfile, 'rb')
423     FitInputPS = pickle.load(pkl_filePS)
424     pkl_filePS.close()
425 awoodard 1.71 #print "fit file name=",Config.FitFileName
426 grchrist 1.20
427 grchrist 1.68 except:
428 awoodard 1.71 print "No fit file by L1seed change specified. Have you run DatabaseRatePredictor with DoL1 in defaults.cfg set to true?"
429 grchrist 1.68 sys.exit(2)
430     else:
431     FitInputPS={} ##define empty dict when not in use
432 grchrist 1.23 try:
433     refrunfile="RefRuns/%s/Rates_HLT_10LS_JPAP.pkl" % (thisyear)
434     pkl_file = open(refrunfile, 'rb')
435     RefRatesInput = pickle.load(pkl_file)
436     pkl_file.close()
437     except:
438 grchrist 1.24 RefRatesInput={}
439 grchrist 1.62 #print "Didn't open ref file"
440 amott 1.1
441 grchrist 1.30
442     trig_list=Config.MonitorList
443    
444     if Config.NoVersion:
445     trig_list=[]
446    
447     for trigger in Config.MonitorList:
448     trig_list.append(StripVersion(trigger))
449 grchrist 1.70
450 awoodard 1.71 L1HLTseeds = HeadParser.GetL1HLTseeds()
451 grchrist 1.56 if Config.DoL1:
452     for HLTkey in trig_list:
453     if "L1" in HLTkey:
454     continue
455     else:
456     try:
457     for L1seed in L1HLTseeds[HLTkey]:
458     if L1seed not in trig_list:
459     trig_list.append(L1seed)
460     except:
461 awoodard 1.71 pass
462 awoodard 1.74
463 grchrist 1.30 for trigger in FitInput.iterkeys():
464 awoodard 1.71 FitInput[StripVersion(trigger)] = FitInput.pop(trigger)
465 awoodard 1.51 for trigger in HeadUnprescaledRates:
466 awoodard 1.71 HeadUnprescaledRates[StripVersion(trigger)] = HeadUnprescaledRates.pop(trigger)
467 grchrist 1.57
468 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
469 awoodard 1.76 if HeadName not in trig_list and not AllTriggers and not ShowAllBadRates:
470 awoodard 1.71 continue
471 awoodard 1.76 if HeadName not in FitInput.keys() and not AllTriggers and not ShowAllBadRates:
472 awoodard 1.71 continue
473 awoodard 1.49
474 grchrist 1.63 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero","HLT_BeamHalo"]
475 abrinke1 1.9 masked_trig = False
476     for mask in masked_triggers:
477     if str(mask) in HeadName:
478     masked_trig = True
479     if masked_trig:
480     continue
481    
482 amott 1.1 skipTrig=False
483 abrinke1 1.3 TriggerRate = round(HeadUnprescaledRates[HeadName][2],2)
484 grchrist 1.68
485 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
486 awoodard 1.71 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,FitInputPS,HeadAvLiveLumi,HeadAvDeliveredLumi,deadtimebeamactive,Config.L1SeedChangeFit,HeadLumiRange,PSColumnByLS)
487 awoodard 1.67 VC = PSCorrectedExpectedRate[2]
488 grchrist 1.32 try:
489 abrinke1 1.75 sigma = PSCorrectedExpectedRate[1]*sqrt(PSCorrectedExpectedRate[0])/(sqrt(len(HeadLumiRange))* HeadUnprescaledRates[HeadName][1])
490 awoodard 1.66 ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
491 grchrist 1.32 except:
492 awoodard 1.65 sigma = 0.0
493 awoodard 1.66 ExpectedRate = 0.0 ##This means we don't have a prediction for this trigger-- gets overwritten to "--" later
494 awoodard 1.52 PerDiff = 0.0
495     SigmaDiff = 0.0
496 awoodard 1.53 if HeadUnprescaledRates[HeadName][1] != 0:
497     VC="No prediction"
498 awoodard 1.64 else:
499     VC="Path prescaled to 0"
500 grchrist 1.30
501 awoodard 1.51 if ExpectedRate > 0:
502 amott 1.1 PerDiff = int(round( (TriggerRate-ExpectedRate)/ExpectedRate,2 )*100)
503 grchrist 1.37 else:
504 awoodard 1.52 PerDiff = 0.0
505 awoodard 1.51
506 awoodard 1.52 if sigma > 0:
507 awoodard 1.51 SigmaDiff = round( (TriggerRate - ExpectedRate)/sigma, 2)
508     else:
509 awoodard 1.64 SigmaDiff = 0.0 #Zero sigma means that when there were no rates for this trigger when the fit was made
510 amott 1.1
511 amott 1.33 if TriggerRate < IgnoreThreshold and (ExpectedRate < IgnoreThreshold and ExpectedRate!=0):
512 amott 1.1 continue
513    
514 awoodard 1.64
515     Data.append([HeadName, TriggerRate, ExpectedRate, PerDiff, SigmaDiff, round(HeadUnprescaledRates[HeadName][1],0),VC])
516 amott 1.1
517     else: ## Use a reference run
518     ## cheap trick to only get triggers in list when in shifter mode
519     #print "shifter mode=",int(Config.ShifterMode)
520 grchrist 1.34 ## continue
521 amott 1.1
522     RefInstLumi = 0
523     RefIterator = 0
524     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
525 awoodard 1.71 RefLen = -10
526 grchrist 1.34
527 abrinke1 1.3 RefUnprescaledRates = RefParser.UpdateRun(RefParser.GetLSRange(RefStartIndex,RefLen))
528 amott 1.1 [RefAvInstLumi,RefAvLiveLumi,RefAvDeliveredLumi,RefAvDeadTime,RefPSCols] = RefParser.GetAvLumiInfo(RefParser.GetLSRange(RefStartIndex,RefLen))
529 awoodard 1.71 if Config.DoL1:
530     RefL1RatesALL = RefParser.GetL1RatesALL(HeadLumiRange)
531     for L1seed in RefL1RatesALL.iterkeys():
532     RefUnprescaledRates[L1seed]=RefL1RatesALL[L1seed]
533    
534 amott 1.1 RefRate = -1
535     for k,v in RefUnprescaledRates.iteritems():
536 awoodard 1.71 if HeadName == StripVersion(k):
537 grchrist 1.34 RefRate = RefUnprescaledRates[k][2]
538    
539     try:
540     ScaledRefRate = round( (RefRate*HeadAvLiveLumi/RefAvLiveLumi*(1-deadtimebeamactive)), 2 )
541    
542     except ZeroDivisionError:
543     ScaledRefRate=0
544    
545 awoodard 1.44 SigmaDiff = 0
546 amott 1.1 if ScaledRefRate == 0:
547 awoodard 1.44 PerDiff = -999
548 amott 1.1 else:
549     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
550 awoodard 1.44
551 amott 1.1 if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
552     continue
553    
554     VC = ""
555 awoodard 1.71 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,SigmaDiff,round((HeadUnprescaledRates[HeadName][1]),0),VC])
556 amott 1.1
557 amott 1.33 SortedData = []
558     if SortBy == "":
559 awoodard 1.71 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
560 amott 1.33 elif SortBy == "name":
561     SortedData=sorted(Data, key=lambda entry: entry[0])
562     elif SortBy == "rate":
563     SortedData=sorted(Data, key=lambda entry: entry[1],reverse=True)
564 awoodard 1.44 elif SortBy == "ratePercDiff":
565 amott 1.33 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
566 awoodard 1.44 elif SortBy == "rateSigmaDiff":
567     SortedData=sorted(Data, key=lambda entry: abs(entry[4]),reverse=True)
568 amott 1.33 else:
569     print "Invalid sorting option %s\n"%SortBy
570     SortedData = Data
571    
572     #check for triggers above the warning threshold
573     Warn=[]
574 awoodard 1.51 core_data=[]
575 awoodard 1.74 core_l1_seeds=[]
576 awoodard 1.64 nBadRates = 0
577 abrinke1 1.69 #Loop for HLT triggers
578 amott 1.33 for entry in SortedData:
579 awoodard 1.71 bad_seeds_string = ""
580 abrinke1 1.69 if not entry[0].startswith('HLT'):
581     continue
582 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)
583 awoodard 1.76 if entry[0] in trig_list or AllTriggers or (bad_rate and ShowAllBadRates and nBadRates < MaxBadRates):
584 abrinke1 1.69 core_data.append(entry)
585     if bad_rate and nBadRates < MaxBadRates:
586 awoodard 1.74 if Config.DoL1:
587     for seed in L1HLTseeds[entry[0]]:
588 awoodard 1.76 if not seed in core_l1_seeds:
589     core_l1_seeds.append(seed)
590 awoodard 1.74 seed_rate = [line[3] for line in SortedData if line[0] == seed]
591 awoodard 1.76 if seed_rate:
592     bad_seed_rate = (abs(seed_rate[0]) > AllowedRatePercDiff)
593     if bad_seed_rate:
594     if bad_seeds_string != "":
595     bad_seeds_string += ", "
596     bad_seeds_string += seed
597 awoodard 1.74 entry[6] = bad_seeds_string
598 abrinke1 1.69 Warn.append(True)
599     nBadRates += 1
600     else:
601     Warn.append(False)
602    
603 awoodard 1.74 ##Loop for L1 seeds of HLT triggers with warnings
604     if Config.DoL1:
605     for entry in SortedData:
606     if not entry[0] in core_l1_seeds:
607     continue
608 awoodard 1.51 core_data.append(entry)
609 awoodard 1.74 bad_seed_rate = (abs(entry[3]) > AllowedRatePercDiff)
610     if bad_seed_rate:
611     Warn.append(True) #Currently, number of bad rates to show refers to bad HLT triggers (no limit on the number of bad L1 seeds to show)
612 awoodard 1.51 else:
613     Warn.append(False)
614 awoodard 1.64
615 awoodard 1.74 for index,entry in enumerate(core_data):
616     if entry[6] == "No prediction (fit missing)": #Dont show 0s if we don't actually have a prediction; it's confusing
617 awoodard 1.64 core_data[index] = [entry[0],entry[1],"--","--","--",entry[5],entry[6]]
618 awoodard 1.74 if entry[0].startswith('L1'): #Don't show sigma value for L1 since we don't trust them
619 awoodard 1.71 core_data[index] = [entry[0],entry[1],entry[2],entry[3],"--",entry[5],entry[6]]
620 amott 1.33
621 awoodard 1.73 try:
622     comment_width = max([30,max([len(col[6]) for col in core_data])+1])
623     except:
624     comment_width = 30
625    
626 awoodard 1.71 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()