ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRateMonitor.py
Revision: 1.61
Committed: Fri Oct 19 13:57:43 2012 UTC (12 years, 6 months ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.60: +6 -1 lines
Log Message:
error message when source set.sh not used when running script

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     ListIgnoredPaths = False
91     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 grchrist 1.23
100     ## if int(Config.ShifterMode):
101     ## print "ShifterMode!!"
102     ## else:
103     ## print "ExpertMode"
104 amott 1.1
105     if Config.LSWindow > 0:
106     NumLS = -1*Config.LSWindow
107    
108     for o,a in opt: # get options passed on the command line
109 awoodard 1.44 if o=="--AllowedPercDiff":
110     AllowedRatePercDiff = float(a)
111     elif o=="--AllowedSigmaDiff":
112     AllowedRateSigmaDiff = float(a)
113 amott 1.1 elif o=="--CompareRun":
114     CompareRunNum=int(a)
115 amott 1.33 ShifterMode = False
116 amott 1.1 elif o=="--FindL1Zeros":
117     FindL1Zeros = True
118     elif o=="--FirstLS":
119     FirstLS = int(a)
120 amott 1.33 ShifterMode = False
121 amott 1.1 elif o=="--NumberLS":
122     NumLS = int(a)
123     elif o=="--IgnoreLowRate":
124     IgnoreThreshold = float(a)
125     elif o=="--ListIgnoredPaths":
126     ListIgnoredPaths=True
127 amott 1.33 ShifterMode = False
128 amott 1.1 elif o=="--PrintLumi":
129     PrintLumi = True
130     elif o=="--RefRun":
131     RefRunNum=int(a)
132     elif o=="--ShowPSTriggers":
133     ShowPSTriggers=True
134 amott 1.33 elif o=="--sortBy":
135     SortBy = a
136 amott 1.2 elif o=="--force":
137     Force = True
138 muell149 1.50 elif o=="--write":
139     writeb = True
140 awoodard 1.51 elif o=="--ShowAllBadRates":
141     ShowAllBadRates=True
142 amott 1.1 elif o=="--help":
143     usage()
144     sys.exit(0)
145     else:
146     print "Invalid Option "+a
147     sys.exit(1)
148    
149 grchrist 1.23
150 amott 1.1 RefLumisExists = False
151     """
152 grchrist 1.34 RefRunFile=RefRunNameTemplate % str(RefRunNum)
153 amott 1.1 if RefRunNum > 0:
154     RefRates = {}
155     for Iterator in range(1,100):
156     if RefLumisExists: ## Quits at the end of a run
157     if max(RefLumis[0]) <= (Iterator+1)*10:
158     break
159    
160     RefRunFile = RefRunNameTemplate % str( RefRunNum*100 + Iterator ) # place to save the reference run info
161     print "RefRunFile=",RefRunFile
162     if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
163     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
164     print RefRunFile[:RefRunFile.rfind('/')]
165     sys.exit(0)
166    
167     if not os.path.exists(RefRunFile): # if the reference run is not saved, get it from wbm
168     print "Reference Run File for run "+str(RefRunNum)+" iterator "+str(Iterator)+" does not exist"
169     print "Creating ..."
170     try:
171     RefParser = GetRun(RefRunNum, RefRunFile, True, Iterator*10, (Iterator+1)*10)
172     print "parsing"
173     except:
174     print "GetRun failed from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
175     continue
176    
177     else: # otherwise load it from the file
178     RefParser = pickle.load( open( RefRunFile ) )
179     print "loading"
180     if not RefLumisExists:
181     RefLumis = RefParser.LumiInfo
182     RefLumisExists = True
183    
184     try:
185     RefRates[Iterator] = RefParser.TriggerRates # get the trigger rates from the reference run
186     LastSuccessfulIterator = Iterator
187     except:
188     print "Failed to get rates from LS "+str(Iterator*10)+" to "+str((Iterator+1)*10)
189 grchrist 1.34
190 amott 1.1 """
191 grchrist 1.34 RefRunFile = RefRunNameTemplate % (thisyear,RefRunNum)
192 amott 1.1 RefParser = DatabaseParser()
193 grchrist 1.23 ##print "Reference Run: "+str(RefRunNum)
194 amott 1.1 if RefRunNum > 0:
195 awoodard 1.49 print "Getting RefRunFile",RefRunFile
196 amott 1.1 if not os.path.exists(RefRunFile[:RefRunFile.rfind('/')]): # folder for ref run file must exist
197     print "Reference run folder does not exist, please create" # should probably create programmatically, but for now force user to create
198     print RefRunFile[:RefRunFile.rfind('/')]
199 grchrist 1.27 sys.exit(0)
200 grchrist 1.34 s
201 amott 1.1 return
202     if not os.path.exists(RefRunFile):
203 grchrist 1.34 print "RefRunFile does not exist"
204 amott 1.1 # create the reference run file
205     try:
206     RefParser.RunNumber = RefRunNum
207     RefParser.ParseRunSetup()
208 grchrist 1.34 print "RefParser is setup"
209 amott 1.1 #RefParser.GetAllTriggerRatesByLS()
210     #RefParser.Save( RefRunFile )
211     except e:
212     print "PROBLEM GETTING REFERNCE RUN"
213     raise
214     else:
215     RefParser = pickle.load( open( RefRunFile ) )
216    
217     # OK, Got the Reference Run
218     # Now get the most recent run
219    
220     SaveRun = False
221     if CompareRunNum=="": # if no run # specified on the CL, get the most recent run
222 grchrist 1.22 CompareRunNum,isCol,isGood = GetLatestRunNumber()
223 grchrist 1.26
224    
225 grchrist 1.22 if not isGood:
226 grchrist 1.23 print "NO TRIGGER KEY FOUND for run ",CompareRunNum
227 grchrist 1.22
228 grchrist 1.23 ##sys.exit(0)
229 amott 1.1
230     if not isCol:
231     print "Most Recent run, "+str(CompareRunNum)+", is NOT collisions"
232 amott 1.16 print "Monitoring only stream A and Express"
233     #if not Force:
234     # sys.exit(0) # maybe we should walk back and try to find a collisions run, but for now just exit
235 grchrist 1.23
236     else:
237     print "Most Recent run is "+str(CompareRunNum)
238 amott 1.16 else:
239 grchrist 1.22 CompareRunNum,isCol,isGood = GetLatestRunNumber(CompareRunNum)
240     if not isGood:
241 grchrist 1.23 print "NO TRIGGER KEY FOUND for run ", CompareRunNum
242     ##sys.exit(0)
243 amott 1.17
244 grchrist 1.23
245 amott 1.17 HeadParser = DatabaseParser()
246     HeadParser.RunNumber = CompareRunNum
247 grchrist 1.23
248     try:
249     HeadParser.ParseRunSetup()
250     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
251 grchrist 1.43 LastGoodLS=HeadParser.GetLastLS(isCol)+1
252     tempLastGoodLS=LastGoodLS
253 grchrist 1.23 CurrRun=CompareRunNum
254 grchrist 1.43 #print "done good"
255 grchrist 1.23 except:
256 grchrist 1.43 #print "exception"
257 grchrist 1.23 HeadLumiRange=[]
258     LastGoodLS=-1
259 grchrist 1.43 tempLastGoodLS=LastGoodLS-1
260 grchrist 1.23 CurrRun=CompareRunNum
261     isGood=0
262    
263     if len(HeadLumiRange) is 0:
264 grchrist 1.36 print "No lumisections that are taking physics data 0"
265 grchrist 1.23 HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
266     if len(HeadLumiRange)>0:
267     isGood=1
268     isCol=0
269     ##sys.exit(0)
270 awoodard 1.44
271 awoodard 1.45 ## This reduces the sensitivity for a rate measurement to cause a warning during the beginning of a run
272 awoodard 1.49 if len(HeadLumiRange) > 0 and len(HeadLumiRange) < 10:
273 awoodard 1.44 AllowedRateSigmaDiff = AllowedRateSigmaDiff*10 / len(HeadLumiRange)
274 grchrist 1.23
275 amott 1.1 if PrintLumi:
276     for LS in HeadParser.LumiInfo[0]:
277     try:
278     if (LS < FirstLS or LS > LastLS) and not FirstLS==999999:
279     continue
280     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))
281     except:
282     print "Lumisection "+str(LS-1)+" was not parsed from the LumiSections page"
283    
284 grchrist 1.23 sys.exit(0)
285 amott 1.1
286     if RefRunNum == 0:
287     RefRates = 0
288     RefLumis = 0
289     LastSuccessfulIterator = 0
290    
291     ### Now actually compare the rates, make tables and look at L1. Loops for ShifterMode
292 grchrist 1.23 ###isGood=1##if there is a trigger key
293 amott 1.1 try:
294     while True:
295 grchrist 1.23 if isGood:
296 grchrist 1.43 tempLastGoodLS=LastGoodLS
297 grchrist 1.23 LastGoodLS=HeadParser.GetLastLS(isCol)
298 grchrist 1.43 ##print "Last Good=",LastGoodLS, tempLastGoodLS
299     if LastGoodLS==tempLastGoodLS:
300 grchrist 1.58 write(bcolors.OKBLUE)
301 grchrist 1.43 print "Trying to get new Run"
302     write(bcolors.ENDC+"\n")
303     else:
304     RefMoreLumiArray = HeadParser.GetMoreLumiInfo()
305     isBeams=True
306     for lumisection in HeadLumiRange:
307     try:
308     if not (RefMoreLumiArray["b1pres"][lumisection] and RefMoreLumiArray["b2pres"][lumisection] and RefMoreLumiArray["b1stab"][lumisection] and RefMoreLumiArray["b2stab"][lumisection]):
309     isBeams=False
310     except:
311 grchrist 1.41 isBeams=False
312 awoodard 1.55
313 grchrist 1.43 if not (isCol and isBeams):
314 grchrist 1.23 ##clear()
315 grchrist 1.43 MoreTableInfo(HeadParser,HeadLumiRange,Config,False)
316 grchrist 1.25 else:
317 grchrist 1.43 if (len(HeadLumiRange)>0):
318 awoodard 1.55 if not isSequential(HeadLumiRange):
319     print "Some lumisections have been skipped. Averaging over most recent sequential lumisections..."
320     sequential_chunk = getSequential(HeadLumiRange)
321     HeadLumiRange = sequential_chunk
322 awoodard 1.51 RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,ListIgnoredPaths,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates)
323 grchrist 1.43 if FindL1Zeros:
324 awoodard 1.44 CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config)
325 grchrist 1.43 else:
326     print "No lumisections that are taking physics data 1"
327 amott 1.33 if ShifterMode:
328 grchrist 1.23 #print "Shifter Mode. Continuing"
329     pass
330 amott 1.2 else:
331 grchrist 1.23 print "Expert Mode. Quitting."
332     sys.exit(0)
333 amott 1.2
334 amott 1.1 print "Sleeping for 1 minute before repeating "
335 amott 1.16 for iSleep in range(20):
336 amott 1.15 write(".")
337     sys.stdout.flush()
338 amott 1.16 time.sleep(3)
339 grchrist 1.23 write(" Updating\n")
340 amott 1.15 sys.stdout.flush()
341 grchrist 1.23
342     ##print "\nminLS=",min(HeadLumiRange),"Last LS=",HeadParser.GetLastLS(isCol),"run=",HeadParser.RunNumber
343     ###Get a new run if DAQ stops
344     ##print "\nLastGoodLS=",LastGoodLS
345    
346     ##### NEED PLACEHOLDER TO COMPARE CURRENT RUN TO LATEST RUN #####
347    
348     NewRun,isCol,isGood = GetLatestRunNumber(9999999) ## update to the latest run and lumi range
349    
350     try:
351     maxLumi=max(HeadLumiRange)
352     except:
353     maxLumi=0
354    
355     ##### THESE ARE CONDITIONS TO GET NEW RUN #####
356     if maxLumi>(LastGoodLS+1) or not isGood or NewRun!=CurrRun:
357     print "Trying to get new Run"
358     try:
359     HeadParser = DatabaseParser()
360     HeadParser.RunNumber = NewRun
361     HeadParser.ParseRunSetup()
362     CurrRun,isCol,isGood=GetLatestRunNumber(9999999)
363     FirstLS=9999
364     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
365     if len(HeadLumiRange) is 0:
366     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
367 grchrist 1.36 print "No lumisections that are taking physics data 2"
368 grchrist 1.23 if len(HeadLumiRange)>0:
369     isGood=1
370     isCol=0
371    
372 grchrist 1.43 #tempLastGoodLS=LastGoodLS
373     #LastGoodLS=HeadParser.GetLastLS(isCol)
374 grchrist 1.25 ##print CurrRun, isCol, isGood
375 grchrist 1.23 except:
376     isGood=0
377     isCol=0
378     print "failed"
379    
380    
381 awoodard 1.49
382 grchrist 1.23 else:
383     try:
384     HeadParser.ParseRunSetup()
385     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,isCol)
386     if len(HeadLumiRange) is 0:
387     HeadLumiRange = HeadParser.GetLSRange(FirstLS,NumLS,False)
388 grchrist 1.26 print "No lumisections that are taking physics data"
389 grchrist 1.23 if len(HeadLumiRange)>0:
390     isGood=1
391     isCol=0
392 grchrist 1.43 #LastGoodLS=HeadParser.GetLastLS(isCol)
393 grchrist 1.23
394     except:
395     isGood=0
396     isCol=0
397     clear()
398     print "NO TRIGGER KEY FOUND YET for run", NewRun ,"repeating search"
399    
400 grchrist 1.22
401 amott 1.1 except KeyboardInterrupt:
402     print "Quitting. Peace Out."
403    
404    
405 awoodard 1.51 def RunComparison(HeadParser,RefParser,HeadLumiRange,ShowPSTriggers,AllowedRatePercDiff,AllowedRateSigmaDiff,IgnoreThreshold,Config,ListIgnoredPaths,SortBy,WarnOnSigmaDiff,ShowSigmaAndPercDiff,writeb,ShowAllBadRates):
406 amott 1.1 Data = []
407     Warn = []
408     IgnoredRates=[]
409 grchrist 1.23
410 abrinke1 1.9 [HeadAvInstLumi,HeadAvLiveLumi,HeadAvDeliveredLumi,HeadAvDeadTime,HeadPSCols] = HeadParser.GetAvLumiInfo(HeadLumiRange)
411 abrinke1 1.3 ##[HeadUnprescaledRates, HeadTotalPrescales, HeadL1Prescales, HeadTriggerRates] = HeadParser.UpdateRun(HeadLumiRange)
412     HeadUnprescaledRates = HeadParser.UpdateRun(HeadLumiRange)
413 grchrist 1.59 if Config.DoL1:
414     L1RatesALL=HeadParser.GetL1RatesALL(HeadLumiRange)
415     for L1seed in L1RatesALL.iterkeys():
416     HeadUnprescaledRates[L1seed]=L1RatesALL[L1seed]
417 grchrist 1.56
418 abrinke1 1.9 [PSColumnByLS,InstLumiByLS,DeliveredLumiByLS,LiveLumiByLS,DeadTimeByLS,PhysicsByLS,ActiveByLS] = HeadParser.LumiInfo
419 grchrist 1.30 deadtimebeamactive=HeadParser.GetDeadTimeBeamActive(HeadLumiRange)
420 grchrist 1.18 try:
421     pkl_file = open(Config.FitFileName, 'rb')
422     FitInput = pickle.load(pkl_file)
423     pkl_file.close()
424 grchrist 1.29 ##print "fit file name=",Config.FitFileName
425 grchrist 1.31
426 grchrist 1.18 except:
427 grchrist 1.27 print "No fit file specified"
428 grchrist 1.20 sys.exit(2)
429    
430 grchrist 1.23 try:
431     refrunfile="RefRuns/%s/Rates_HLT_10LS_JPAP.pkl" % (thisyear)
432     pkl_file = open(refrunfile, 'rb')
433     RefRatesInput = pickle.load(pkl_file)
434     pkl_file.close()
435     except:
436 grchrist 1.24 RefRatesInput={}
437 grchrist 1.34 print "Didn't open ref file"
438 amott 1.1
439 grchrist 1.30
440     trig_list=Config.MonitorList
441    
442     if Config.NoVersion:
443     trig_list=[]
444    
445     for trigger in Config.MonitorList:
446     trig_list.append(StripVersion(trigger))
447 grchrist 1.56 if Config.DoL1:
448     L1HLTseeds=HeadParser.GetL1HLTseeds()
449     for HLTkey in trig_list:
450     if "L1" in HLTkey:
451     continue
452     else:
453     try:
454     for L1seed in L1HLTseeds[HLTkey]:
455     if L1seed not in trig_list:
456     trig_list.append(L1seed)
457     except:
458     pass
459 grchrist 1.30 for trigger in FitInput.iterkeys():
460 awoodard 1.51 FitInput[StripVersion(trigger)]=FitInput.pop(trigger)
461     for trigger in HeadUnprescaledRates:
462     HeadUnprescaledRates[StripVersion(trigger)]=HeadUnprescaledRates.pop(trigger)
463 grchrist 1.57
464 awoodard 1.49 else:
465     trig_list=Config.MonitorList
466    
467 abrinke1 1.3 for HeadName in HeadUnprescaledRates:
468 awoodard 1.49 if RefParser.RunNumber == 0: ## If not ref run then just use trigger list
469 awoodard 1.51 if HeadName not in trig_list and not ListIgnoredPaths and not ShowAllBadRates:
470     continue
471     if HeadName not in FitInput.keys() and not ListIgnoredPaths and not ShowAllBadRates:
472     continue
473 awoodard 1.49
474 grchrist 1.28 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero"]
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 awoodard 1.49
485 amott 1.1 if RefParser.RunNumber == 0: ## Use rate prediction functions
486 awoodard 1.44
487 grchrist 1.30 PSCorrectedExpectedRate = Config.GetExpectedRate(HeadName,FitInput,RefRatesInput,HeadAvLiveLumi,HeadAvDeliveredLumi,deadtimebeamactive)
488 awoodard 1.51 VC = ""
489 abrinke1 1.9
490 grchrist 1.32 try:
491     ExpectedRate = round((PSCorrectedExpectedRate[0] / HeadUnprescaledRates[HeadName][1]),2)
492 awoodard 1.52 sigma = PSCorrectedExpectedRate[1]/(sqrt(len(HeadLumiRange))* HeadUnprescaledRates[HeadName][1])
493 awoodard 1.44
494 grchrist 1.32 except:
495 awoodard 1.52 ExpectedRate = 0.0 ##This means we don't have a prediction for this trigger
496     PerDiff = 0.0
497     SigmaDiff = 0.0
498 awoodard 1.53 if HeadUnprescaledRates[HeadName][1] != 0:
499     VC="No prediction"
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.52 SigmaDiff =-999 #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.44 Data.append([HeadName, TriggerRate, ExpectedRate, PerDiff, SigmaDiff, round(HeadUnprescaledRates[HeadName][1],1),VC])
515 amott 1.1
516     else: ## Use a reference run
517     ## cheap trick to only get triggers in list when in shifter mode
518     #print "shifter mode=",int(Config.ShifterMode)
519 grchrist 1.34 ## continue
520 amott 1.1
521     RefInstLumi = 0
522     RefIterator = 0
523     RefStartIndex = ClosestIndex(HeadAvInstLumi,RefParser.GetAvLumiPerRange())
524     RefLen = -10
525 grchrist 1.34
526    
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 grchrist 1.34 deadtimebeamactive=RefParser.GetDeadTimeBeamActive(RefParser.GetLSRange(RefStartIndex,RefLen))
530    
531 amott 1.1 RefRate = -1
532     for k,v in RefUnprescaledRates.iteritems():
533 grchrist 1.34 if HeadName==k:
534     RefRate = RefUnprescaledRates[k][2]
535    
536     try:
537     ScaledRefRate = round( (RefRate*HeadAvLiveLumi/RefAvLiveLumi*(1-deadtimebeamactive)), 2 )
538    
539     except ZeroDivisionError:
540     ScaledRefRate=0
541    
542 awoodard 1.44 SigmaDiff = 0
543 amott 1.1 if ScaledRefRate == 0:
544 awoodard 1.44 PerDiff = -999
545 amott 1.1 else:
546     PerDiff = int( round( (TriggerRate - ScaledRefRate)/ScaledRefRate , 2)*100)
547 awoodard 1.44
548 amott 1.1 if TriggerRate < IgnoreThreshold and ScaledRefRate < IgnoreThreshold:
549     continue
550    
551     VC = ""
552 awoodard 1.44 Data.append([HeadName,TriggerRate,ScaledRefRate,PerDiff,SigmaDiff,round((HeadUnprescaledRates[HeadName][1]),1),VC])
553 amott 1.1
554 amott 1.33 SortedData = []
555     if SortBy == "":
556     SortedData = Data # don't do any sorting
557 grchrist 1.35 if RefParser.RunNumber>0:
558 grchrist 1.34 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
559 amott 1.33 elif SortBy == "name":
560     SortedData=sorted(Data, key=lambda entry: entry[0])
561     elif SortBy == "rate":
562     SortedData=sorted(Data, key=lambda entry: entry[1],reverse=True)
563 awoodard 1.44 elif SortBy == "ratePercDiff":
564 amott 1.33 SortedData=sorted(Data, key=lambda entry: abs(entry[3]),reverse=True)
565 awoodard 1.44 elif SortBy == "rateSigmaDiff":
566     SortedData=sorted(Data, key=lambda entry: abs(entry[4]),reverse=True)
567 amott 1.33 else:
568     print "Invalid sorting option %s\n"%SortBy
569     SortedData = Data
570    
571     #check for triggers above the warning threshold
572     Warn=[]
573 awoodard 1.51 core_data=[]
574 amott 1.33 for entry in SortedData:
575 awoodard 1.51 bad_rate = (abs(entry[4]) > AllowedRateSigmaDiff and WarnOnSigmaDiff) or (abs(entry[3]) > AllowedRatePercDiff and not WarnOnSigmaDiff)
576     if entry[0] in trig_list or ListIgnoredPaths:
577     core_data.append(entry)
578     if bad_rate:
579     Warn.append(True)
580     else:
581     Warn.append(False)
582 amott 1.33 else:
583 awoodard 1.54 if bad_rate and ShowAllBadRates:
584 awoodard 1.51 core_data.append(entry)
585     Warn.append(True)
586 amott 1.33
587 awoodard 1.47 if ShowSigmaAndPercDiff == 1:
588     Header = ["Trigger Name", "Actual", "Expected","% Diff","Deviation", "Cur PS", "Comments"]
589 awoodard 1.51 table_data=core_data
590 awoodard 1.47 PrettyPrintTable(Header,table_data,[80,10,10,10,10,10,20],Warn)
591 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
592 awoodard 1.47 elif WarnOnSigmaDiff == 1:
593 awoodard 1.45 Header = ["Trigger Name", "Actual", "Expected","Deviation", "Cur PS", "Comments"]
594 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[4], col[5], col[6]] for col in core_data]
595 awoodard 1.47 PrettyPrintTable(Header,table_data,[80,10,10,10,10,10,20],Warn)
596 awoodard 1.49 print 'Deviation is the difference between the actual and expected rates, in units of the expected standard deviation.'
597 awoodard 1.44 else:
598 awoodard 1.47 Header = ["Trigger Name", "Actual", "Expected", "% Diff", "Cur PS", "Comments"]
599 awoodard 1.51 table_data = [[col[0], col[1], col[2], col[3], col[5], col[6]] for col in core_data]
600 awoodard 1.49 PrettyPrintTable(Header,table_data,[80,10,10,10,10,20],Warn)
601 awoodard 1.44
602 muell149 1.50 if writeb:
603 awoodard 1.51 prettyCSVwriter("rateMon_newmenu.csv",[80,10,10,10,10,20,20],Header,core_data,Warn)
604 awoodard 1.45
605 awoodard 1.49 MoreTableInfo(HeadParser,HeadLumiRange,Config,True)
606 amott 1.1
607 grchrist 1.39 for warning in Warn:
608     if warning==True:
609     write(bcolors.WARNING)
610 grchrist 1.60 print "If any trigger remains red for 5 minutes, Please consult the shift crew and if needed contact relevant experts"
611 grchrist 1.39 print "More instructions at https://twiki.cern.ch/twiki/bin/view/CMS/TriggerShiftHLTGuide"
612     write(bcolors.ENDC+"\n")
613     break
614 awoodard 1.51
615    
616 awoodard 1.44 def CheckL1Zeros(HeadParser,RefRunNum,RefRates,RefLumis,LastSuccessfulIterator,ShowPSTriggers,AllowedPercRateDiff,IgnoreThreshold,Config):
617 amott 1.1 L1Zeros=[]
618     IgnoreBits = ["L1_PreCollisions","L1_InterBunch_Bsc","L1_BeamHalo","L1_BeamGas_Hf"]
619     for key in HeadParser.TriggerRates:
620     ## Skip events in the skip list
621     skipTrig=False
622     ##for trig in Config.ExcludeList:
623     ##if not trigN.find(trig) == -1:
624     ##skipTrig=True
625     ##break
626     if skipTrig:
627     continue
628     ## if no events pass the L1, add it to the L1Zeros list if not already there
629     if HeadParser.TriggerRates[key][1]==0 and not HeadParser.TriggerRates[key][4] in L1Zeros:
630     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:
631    
632     L1Zeros.append(HeadParser.TriggerRates[key][4])
633     print "L1Zeros=", L1Zeros
634    
635     if len(L1Zeros) == 0:
636     #print "It looks like no masked L1 bits seed trigger paths"
637     pass
638     else:
639     print "The following seeds are used to seed HLT bits but accept 0 events:"
640     #print "The average lumi of this run is: "+str(round(HeadParser.LumiInfo[6],1))+"e30"
641     for Seed in L1Zeros:
642     print Seed
643 awoodard 1.55
644     def isSequential(t):
645     try:
646     if len(t)<2:
647     return True
648     except:
649     return True
650     for i,e in enumerate(t[1:]):
651     if not abs(e-t[i])==1:
652     return False
653     return True
654    
655     def getSequential(range):
656     for i,j in zip(range[-2::-1],range[::-1]):
657     if j-i != 1:
658     range = range[range.index(j):]
659     return range
660    
661    
662 amott 1.1 if __name__=='__main__':
663 grchrist 1.20 global thisyear
664 amott 1.1 main()