ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseParser.py
Revision: 1.47
Committed: Mon Oct 1 09:57:36 2012 UTC (12 years, 7 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
Changes since 1.46: +12 -9 lines
Log Message:
Changing default ps column when getting 'None' from the DB to 3

File Contents

# User Rev Content
1 grchrist 1.43 #!/usr/bin/python
2 amott 1.1 import cx_Oracle
3     import cPickle as pickle
4 grchrist 1.43 import os
5     import sys
6 amott 1.1 import time
7 amott 1.5 import re
8 grchrist 1.43 from colors import *
9 amott 1.20
10     try: ## set is builtin in python 2.6.4 and sets is deprecated
11     set
12     except NameError:
13     from sets import Set
14 amott 1.5
15 amott 1.1
16     class DatabaseParser:
17    
18     def __init__(self):
19 grchrist 1.34
20 amott 1.24 self.curs = ConnectDB()
21 amott 1.1 ##-- Defined in ParsePage1 --##
22     self.RunNumber = 0
23    
24     ##-- Defined in ParseRunPage --##
25     self.Date=''
26     self.L1_HLT_Key=''
27     self.HLT_Key=''
28     self.GTRS_Key=''
29     self.TSC_Key=''
30     self.GT_Key=''
31     self.ConfigId=0
32    
33     ##-- Defined in ParseHLTSummaryPage --##
34 amott 1.5 self.HLTRatesByLS = {}
35     self.HLTPSByLS = {}
36 amott 1.1
37 amott 1.4 self.nAlgoBits=0
38 amott 1.1 self.L1PrescaleTable=[]
39     self.AvgL1Prescales=[] ## contains the average L1 prescales for the current LS range range
40     self.HLTList=[]
41 amott 1.4 self.AvgTotalPrescales={}
42 amott 1.1 self.HLTPrescaleTable=[] ## can't fill this yet
43 amott 1.4 self.UnprescaledRates={}
44     self.PrescaledRates={}
45 amott 1.1 ##-- Defined in ParseLumiPage --##
46     self.LastLSParsed=-1
47 amott 1.4 self.InstLumiByLS = {}
48     self.DeliveredLumiByLS = {}
49     self.LiveLumiByLS = {}
50     self.PSColumnByLS = {}
51 amott 1.1 self.AvInstLumi = 0
52     self.AvDeliveredLumi = 0
53     self.AvLiveLumi = 0
54 amott 1.5 self.AvDeadTime = 0
55 amott 1.4 self.LumiInfo = {} ##Returns
56     self.DeadTime = {}
57     self.Physics = {}
58 amott 1.5 self.Active = {}
59 grchrist 1.21
60 grchrist 1.22
61     self.B1Pres = {}
62     self.B2Pres = {}
63     self.B1Stab = {}
64     self.B2Stab = {}
65 grchrist 1.21 self.EBP = {}
66     self.EBM = {}
67     self.EEP = {}
68     self.EEM = {}
69     self.HBHEA = {}
70     self.HBHEB = {}
71     self.HBHEC = {}
72     self.HF = {}
73     self.RPC = {}
74     self.DT0 = {}
75     self.DTP = {}
76     self.DTM = {}
77     self.CSCP = {}
78     self.CSCM = {}
79     self.TOB = {}
80     self.TIBTID= {}
81     self.TECP = {}
82     self.TECM = {}
83     self.BPIX = {}
84     self.FPIX = {}
85     self.ESP = {}
86     self.ESM = {}
87 grchrist 1.26
88     self.DeadTimeBeamActive = {}
89 grchrist 1.21
90 amott 1.5
91 amott 1.1 ##-- Defined in ParsePSColumnPage (not currently used) --##
92     self.PSColumnChanges=[] ##Returns
93    
94     ##-- Defined in ParseTriggerModePage --##
95 amott 1.2 self.L1TriggerMode={} ##
96     self.HLTTriggerMode={} ##
97 amott 1.4 self.HLTSeed={}
98 amott 1.1 self.HLTSequenceMap=[]
99     self.TriggerInfo = [] ##Returns
100    
101     ##-- Defined in AssemblePrescaleValues --##
102 amott 1.4 self.L1Prescale={}
103     self.L1IndexNameMap={}
104 amott 1.1 self.HLTPrescale=[]
105     self.MissingPrescale=[]
106     self.PrescaleValues=[] ##Returns
107    
108     ##-- Defined in ComputeTotalPrescales --##
109 amott 1.2 self.TotalPSInfo = [] ##Returns # #collection
110 amott 1.1
111     ##-- Defined in CorrectForPrescaleChange --##
112     self.CorrectedPSInfo = [] ##Returns
113 grchrist 1.46
114 amott 1.1 ##-- In the current Parser.py philosophy, only RunNumber is set globally
115     ## - LS range is set from the outside for each individual function
116     #self.FirstLS = -1
117     #self.LastLS = -1
118    
119     def GetRunInfo(self):
120     ## This query gets the L1_HLT Key (A), the associated HLT Key (B) and the Config number for that key (C)
121     KeyQuery = """
122     SELECT A.TRIGGERMODE, B.HLT_KEY, B.GT_RS_KEY, B.TSC_KEY, C.CONFIGID, D.GT_KEY FROM
123     CMS_WBM.RUNSUMMARY A, CMS_L1_HLT.L1_HLT_CONF B, CMS_HLT.CONFIGURATIONS C, CMS_TRG_L1_CONF.TRIGGERSUP_CONF D WHERE
124     B.ID = A.TRIGGERMODE AND C.CONFIGDESCRIPTOR = B.HLT_KEY AND D.TS_Key = B.TSC_Key AND A.RUNNUMBER=%d
125     """ % (self.RunNumber,)
126 grchrist 1.31 try:
127     self.curs.execute(KeyQuery)
128     self.L1_HLT_Key,self.HLT_Key,self.GTRS_Key,self.TSC_Key,self.ConfigId,self.GT_Key = self.curs.fetchone()
129     except:
130 grchrist 1.34 ##print "Unable to get L1 and HLT keys for this run"
131     pass
132 grchrist 1.31
133 amott 1.1
134     def UpdateRateTable(self): # lets not rebuild the rate table every time, rather just append new LSs
135     pass
136    
137 amott 1.5 def GetHLTRates(self,LSRange):
138 grchrist 1.39
139 amott 1.1 sqlquery = """SELECT SUM(A.L1PASS),SUM(A.PSPASS),SUM(A.PACCEPT)
140 grchrist 1.40 ,SUM(A.PEXCEPT), A.LSNUMBER, (SELECT L.NAME FROM CMS_HLT.PATHS L WHERE L.PATHID=A.PATHID) PATHNAME
141 abrinke1 1.17 FROM CMS_RUNINFO.HLT_SUPERVISOR_TRIGGERPATHS A WHERE RUNNUMBER=%s AND A.LSNUMBER IN %s
142 amott 1.1 GROUP BY A.LSNUMBER,A.PATHID"""
143    
144 abrinke1 1.17 LSRangeSTR = str(LSRange)
145     LSRangeSTR = LSRangeSTR.replace("[","(")
146     LSRangeSTR = LSRangeSTR.replace("]",")")
147    
148     StartLS = LSRange[0]
149     EndLS = LSRange[-1]
150 grchrist 1.40 LSUsed={}
151     for lumisection in LSRange:
152     LSUsed[lumisection]=False
153    
154 abrinke1 1.10 AvgL1Prescales = [0]*self.nAlgoBits
155    
156 amott 1.5 #print "Getting HLT Rates for LS from %d to %d" % (LSRange[0],LSRange[-1],)
157 abrinke1 1.17
158     query = sqlquery % (self.RunNumber,LSRangeSTR)
159 amott 1.1 self.curs.execute(query)
160 amott 1.5
161     TriggerRates = {}
162 grchrist 1.40 for L1Pass,PSPass,HLTPass,HLTExcept,LS ,name in self.curs.fetchall():
163 abrinke1 1.10 if not self.HLTSeed.has_key(name):
164     continue
165    
166 amott 1.1 rate = HLTPass/23.3
167 abrinke1 1.10 hltps = 0
168 grchrist 1.40
169 amott 1.1 if PSPass:
170 abrinke1 1.10 hltps = float(L1Pass)/PSPass
171 grchrist 1.39
172 amott 1.6 if not TriggerRates.has_key(name):
173 grchrist 1.40
174 abrinke1 1.10 try:
175 grchrist 1.40 psi = self.PSColumnByLS[LS]
176 grchrist 1.25 ##print "psi=",psi
177 abrinke1 1.10 #except:
178     #psi = self.PSColumnByLS[1]
179     #if not psi:
180     except:
181 awoodard 1.47 print "HLT in: Cannot figure out PSI for LS "+str(StartLS)+" setting to 3"
182 abrinke1 1.10 print "The value of LSRange[0] is:"
183 grchrist 1.40 print str(LS)
184 awoodard 1.47 psi = 3
185 grchrist 1.38 if psi is None:
186 awoodard 1.47 psi=3
187 abrinke1 1.10 if self.L1IndexNameMap.has_key(self.HLTSeed[name]):
188 grchrist 1.36 ##print "name=",name, "self.HLTSeed[name]=",self.HLTSeed[name],"psi=",psi,
189 abrinke1 1.10 l1ps = self.L1PrescaleTable[self.L1IndexNameMap[self.HLTSeed[name]]][psi]
190     else:
191 grchrist 1.40 ##print "zero ",LSRange[0], self.PSColumnByLS[LS]
192     AvL1Prescales = self.CalculateAvL1Prescales([LS])
193 abrinke1 1.10 l1ps = self.UnwindORSeed(self.HLTSeed[name],AvL1Prescales)
194     #l1ps = 1
195     #print "L1IndexNameMap has no key for "+str(self.HLTSeed[name])
196    
197     ps = l1ps*hltps
198 grchrist 1.22
199     ###if ps < 1: ### want PS=0 too!
200 abrinke1 1.10 #print "Oops! somehow ps for "+str(name)+" = "+str(ps)+", where L1 PS = "+str(l1ps)+" and HLT PS = "+str(hltps)
201 grchrist 1.22 # ps = 1
202 abrinke1 1.10 psrate = ps*rate
203     TriggerRates[name]= [ps,rate,psrate,1]
204 grchrist 1.40 LSUsed[LS]=True
205    
206 amott 1.6 else:
207 grchrist 1.40
208 abrinke1 1.10 [ops,orate,opsrate,on] = TriggerRates[name]
209     try:
210     psi = self.PSColumnByLS[LSRange[on]]
211     #except:
212     #psi = self.PSColumnByLS[1]
213     #if not psi:
214     except:
215 awoodard 1.47 print "HLT out: Cannot figure out PSI for index "+str(on)+" setting to 3"
216 abrinke1 1.10 print "The value of LSRange[on] is:"
217 grchrist 1.40 print str(LS)
218 awoodard 1.47 psi = 3
219 grchrist 1.38 if psi is None:
220 awoodard 1.47 psi=3
221 abrinke1 1.10 if self.L1IndexNameMap.has_key(self.HLTSeed[name]):
222     l1ps = self.L1PrescaleTable[self.L1IndexNameMap[self.HLTSeed[name]]][psi]
223     else:
224 grchrist 1.25 ##print "on ",
225 grchrist 1.40 AvL1Prescales = self.CalculateAvL1Prescales([LS])
226 abrinke1 1.10 l1ps = self.UnwindORSeed(self.HLTSeed[name],AvL1Prescales)
227     #l1ps = 1
228     #print "L1IndexNameMap has no key for "+str(self.HLTSeed[name])
229    
230     ps = l1ps*hltps
231 grchrist 1.22 #if ps < 1: ###want PS=0 too!
232 abrinke1 1.10 ##print "Oops! somehow ps for "+str(name)+" = "+str(ps)+", where L1 PS = "+str(l1ps)+" and HLT PS = "+str(hltps)
233 grchrist 1.22 # ps = 1
234 abrinke1 1.10 psrate = ps*rate
235 grchrist 1.40 TriggerRates[name]= [ops+ps,orate+rate,opsrate+psrate,on+1]
236     LSUsed[LS]=True
237    
238    
239    
240    
241     ###check if LS is used above, if not and deadtime is 100% add extra lumi for calculation
242     lumirange_one=[]
243     for key in LSUsed.iterkeys():
244     lumirange_one=[key]##set LSRange equal to one LS so can get deadtime
245     if LSUsed[key]:
246     continue
247     if self.GetDeadTimeBeamActive(lumirange_one)<=0.9999:
248     ##print "LS",key,"gottcha", LSUsed[key]
249     LSUsed[key]=True
250     print "Some strange error LS",key, "has deadtime ", self.GetDeadTimeBeamActive(lumirange_one)
251     else:
252     print "increasing # LS by one, LS", key, "has 100% deadtime"
253     for name,val in TriggerRates.iteritems():
254     [ops,orate,opsrate,on] = TriggerRates[name]
255     TriggerRates[name]= [ops,orate,opsrate,on+1]
256    
257 amott 1.6 for name,val in TriggerRates.iteritems():
258 abrinke1 1.10 [ps,rate,psrate,n] = val
259     avps = ps/n
260     try:
261     ps = psrate/rate
262     except:
263     #print "Rate = 0 for "+str(name)+", setting ps to 1"
264 abrinke1 1.13 ps = avps
265 grchrist 1.39
266 abrinke1 1.10 TriggerRates[name] = [avps,ps,rate/n,psrate/n]
267 grchrist 1.46
268 amott 1.5 return TriggerRates
269 amott 1.1
270 awoodard 1.45 def GetAvgTrigRateInLSRange(self,triggerName,LSRange):
271     sqlquery = """SELECT A.PACCEPT
272     FROM CMS_RUNINFO.HLT_SUPERVISOR_TRIGGERPATHS A, CMS_HLT.PATHS B
273     WHERE RUNNUMBER=%s AND B.NAME = \'%s\' AND A.PATHID = B.PATHID AND A.LSNUMBER IN %s
274     """
275    
276     LSRangeSTR = str(LSRange)
277     LSRangeSTR = LSRangeSTR.replace("[","(")
278     LSRangeSTR = LSRangeSTR.replace("]",")")
279    
280     query = sqlquery % (self.RunNumber,triggerName,LSRangeSTR)
281     self.curs.execute(query)
282     avg_rate = sum([counts[0] for counts in self.curs.fetchall()])/ (23.3 * len(LSRange))
283    
284     return avg_rate
285    
286     def GetTrigRatesInLSRange(self,triggerName,LSRange):
287     sqlquery = """SELECT A.LSNUMBER, A.PACCEPT
288     FROM CMS_RUNINFO.HLT_SUPERVISOR_TRIGGERPATHS A, CMS_HLT.PATHS B
289     WHERE RUNNUMBER=%s AND B.NAME = \'%s\' AND A.PATHID = B.PATHID AND A.LSNUMBER IN %s
290     ORDER BY A.LSNUMBER
291     """
292    
293     LSRangeSTR = str(LSRange)
294     LSRangeSTR = LSRangeSTR.replace("[","(")
295     LSRangeSTR = LSRangeSTR.replace("]",")")
296    
297     query = sqlquery % (self.RunNumber,triggerName,LSRangeSTR)
298     self.curs.execute(query)
299     r={}
300     for ls,accept in self.curs.fetchall():
301     r[ls] = accept/23.3
302     return r
303    
304 amott 1.5 def GetTriggerRatesByLS(self,triggerName):
305     sqlquery = """SELECT A.LSNUMBER, A.PACCEPT
306 amott 1.3 FROM CMS_RUNINFO.HLT_SUPERVISOR_TRIGGERPATHS A, CMS_HLT.PATHS B
307 amott 1.5 WHERE RUNNUMBER=%s AND B.NAME = \'%s\' AND A.PATHID = B.PATHID
308 amott 1.11 """ % (self.RunNumber,triggerName,)
309 amott 1.3
310     self.curs.execute(sqlquery)
311 amott 1.5 r={}
312     for ls,accept in self.curs.fetchall():
313     r[ls] = accept/23.3
314     return r
315    
316     def GetAllTriggerRatesByLS(self):
317     for hltName in self.HLTSeed:
318     self.HLTRatesByLS[hltName] = self.GetTriggerRatesByLS(hltName)
319 amott 1.3
320 awoodard 1.45 def GetPSColumnsInLSRange(self,LSRange):
321     sqlquery="""SELECT LUMI_SECTION,PRESCALE_INDEX FROM
322     CMS_GT_MON.LUMI_SECTIONS B WHERE B.RUN_NUMBER=%s AND B.LUMI_SECTION IN %s"""
323    
324     LSRangeSTR = str(LSRange)
325     LSRangeSTR = LSRangeSTR.replace("[","(")
326     LSRangeSTR = LSRangeSTR.replace("]",")")
327     query = sqlquery % (self.RunNumber,LSRangeSTR)
328     self.curs.execute(query)
329    
330     ps_columns={}
331     for ls, ps_index in self.curs.fetchall():
332     ps_columns[ls] = ps_index
333    
334     return ps_columns
335    
336     def GetAvDeliveredLumi(self,LSRange):
337     sqlquery="""SELECT DELIVLUMI FROM
338     CMS_RUNTIME_LOGGER.LUMI_SECTIONS A WHERE A.RUNNUMBER=%s AND A.LUMISECTION IN %s"""
339    
340     LSRangeSTR = str(LSRange)
341     LSRangeSTR = LSRangeSTR.replace("[","(")
342     LSRangeSTR = LSRangeSTR.replace("]",")")
343     query = sqlquery % (self.RunNumber,LSRangeSTR)
344     self.curs.execute(query)
345    
346     delivered = [val[0] for val in self.curs.fetchall()]
347     avg_delivered = sum(delivered)/len(LSRange)
348    
349     return avg_delivered
350    
351 grchrist 1.34 def GetLumiInfo(self):
352    
353 amott 1.5 sqlquery="""SELECT RUNNUMBER,LUMISECTION,PRESCALE_INDEX,INSTLUMI,LIVELUMI,DELIVLUMI,DEADTIME
354 grchrist 1.22 ,DCSSTATUS,PHYSICS_FLAG,CMS_ACTIVE
355 amott 1.1 FROM CMS_RUNTIME_LOGGER.LUMI_SECTIONS A,CMS_GT_MON.LUMI_SECTIONS B WHERE A.RUNNUMBER=%s
356     AND B.RUN_NUMBER(+)=A.RUNNUMBER AND B.LUMI_SECTION(+)=A.LUMISECTION AND A.LUMISECTION > %d
357     ORDER BY A.RUNNUMBER,A.LUMISECTION"""
358 abrinke1 1.13
359 amott 1.1 ## Get the lumi information for the run, just update the table, don't rebuild it every time
360     query = sqlquery % (self.RunNumber,self.LastLSParsed)
361     self.curs.execute(query)
362 grchrist 1.21
363 amott 1.1 pastLSCol=-1
364 grchrist 1.22 for run,ls,psi,inst,live,dlive,dt,dcs,phys,active in self.curs.fetchall():
365 awoodard 1.47 if psi is None:
366     self.PSColumnByLS[ls]=3
367     else:
368     self.PSColumnByLS[ls]=psi
369 amott 1.4 self.InstLumiByLS[ls]=inst
370     self.LiveLumiByLS[ls]=live
371     self.DeliveredLumiByLS[ls]=dlive
372     self.DeadTime[ls]=dt
373     self.Physics[ls]=phys
374 amott 1.5 self.Active[ls]=active
375 grchrist 1.22
376 amott 1.1 if pastLSCol!=-1 and ls!=pastLSCol:
377     self.PSColumnChanges.append([ls,psi])
378     pastLSCol=ls
379     if ls>self.LastLSParsed:
380     self.LastLSParsed=ls
381 grchrist 1.22 self.LumiInfo = [self.PSColumnByLS, self.InstLumiByLS, self.DeliveredLumiByLS, self.LiveLumiByLS, self.DeadTime, self.Physics, self.Active]
382 amott 1.1
383 abrinke1 1.13 return self.LumiInfo
384    
385 grchrist 1.19 def GetMoreLumiInfo(self):
386 grchrist 1.22 sqlquery="""SELECT RUNNUMBER,LUMISECTION,BEAM1_PRESENT, BEAM2_PRESENT, BEAM1_STABLE, BEAM2_STABLE, EBP_READY,EBM_READY,EEP_READY,EEM_READY,HBHEA_READY,HBHEB_READY,HBHEC_READY,HF_READY,RPC_READY,DT0_READY,DTP_READY,DTM_READY,CSCP_READY,CSCM_READY,TOB_READY,TIBTID_READY,TECP_READY,TECM_READY,BPIX_READY,FPIX_READY,ESP_READY,ESM_READY
387 grchrist 1.19 FROM CMS_RUNTIME_LOGGER.LUMI_SECTIONS A,CMS_GT_MON.LUMI_SECTIONS B WHERE A.RUNNUMBER=%s
388     AND B.RUN_NUMBER(+)=A.RUNNUMBER AND B.LUMI_SECTION(+)=A.LUMISECTION AND A.LUMISECTION > %d
389     ORDER BY A.RUNNUMBER,A.LUMISECTION"""
390    
391     ## Get the lumi information for the run, just update the table, don't rebuild it every time
392     query = sqlquery % (self.RunNumber,self.LastLSParsed)
393     self.curs.execute(query)
394 grchrist 1.21 pastLSCol=-1
395 grchrist 1.22 for run,ls,b1pres,b2pres,b1stab,b2stab,ebp,ebm,eep,eem,hbhea,hbheb,hbhec,hf,rpc,dt0,dtp,dtm,cscp,cscm,tob,tibtid,tecp,tecm,bpix,fpix,esp,esm in self.curs.fetchall():
396 grchrist 1.21
397 grchrist 1.22 self.B1Pres[ls]=b1pres
398     self.B2Pres[ls]=b2pres
399     self.B1Stab[ls]=b1stab
400     self.B2Stab[ls]=b2stab
401 grchrist 1.21 self.EBP[ls]= ebp
402     self.EBM[ls] = ebm
403     self.EEP[ls] = eep
404     self.EEM[ls] = eem
405     self.HBHEA[ls] = hbhea
406     self.HBHEB[ls] = hbheb
407     self.HBHEC[ls] = hbhec
408     self.HF[ls] = hf
409     self.RPC[ls] = rpc
410     self.DT0[ls] = dt0
411     self.DTP[ls] = dtp
412     self.DTM[ls] = dtm
413     self.CSCP[ls] = cscp
414     self.CSCM[ls] = cscm
415     self.TOB[ls] = tob
416     self.TIBTID[ls]= tibtid
417     self.TECP[ls] = tecp
418     self.TECM[ls] = tecm
419     self.BPIX[ls] = bpix
420     self.FPIX[ls] = fpix
421     self.ESP[ls] = esp
422     self.ESM[ls] = esm
423 grchrist 1.19
424 grchrist 1.21
425 grchrist 1.19 pastLSCol=ls
426     if ls>self.LastLSParsed:
427     self.LastLSParsed=ls
428    
429 grchrist 1.27
430 grchrist 1.46
431 grchrist 1.22 self.MoreLumiInfo ={'b1pres':self.B1Pres,'b2pres':self.B2Pres,'b1stab':self.B1Stab,'b2stab':self.B2Stab,'ebp':self.EBP,'ebm':self.EBM,'eep':self.EEP,'eem':self.EEM,'hbhea':self.HBHEA,'hbheb':self.HBHEB,'hbhec':self.HBHEC,'hf':self.HF,'rpc':self.RPC,'dt0':self.DT0,'dtp':self.DTP,'dtm':self.DTM,'cscp':self.CSCP,'cscm':self.CSCM,'tob':self.TOB,'tibtid':self.TIBTID,'tecp':self.TECP,'tecm':self.TECM,'bpix':self.BPIX,'fpix':self.FPIX,'esp':self.ESP,'esm':self.ESM}
432 grchrist 1.21
433 grchrist 1.19 return self.MoreLumiInfo
434 grchrist 1.46
435    
436     def GetL1HLTseeds(self):
437     #print self.HLTSeed
438     L1HLTseeds={}
439     for HLTkey in self.HLTSeed.iterkeys():
440     #print HLTkey, self.HLTSeed[HLTkey]
441    
442     dummy=str(self.HLTSeed[HLTkey])
443    
444     if dummy.find(" OR ") == -1:
445     dummylist=[]
446     dummylist.append(dummy)
447     L1HLTseeds[StripVersion(HLTkey)]=dummylist
448     continue # Not an OR of seeds
449     seedList = dummy.split(" OR ")
450     #print seedList
451     L1HLTseeds[StripVersion(HLTkey)]=seedList
452     if len(seedList)==1:
453     print "error: zero length L1 seed"
454     continue #shouldn't get here
455     #print L1HLTseeds
456    
457     return L1HLTseeds
458 grchrist 1.19
459 grchrist 1.26 def GetDeadTimeBeamActive(self,LSRange):
460     sqlquery=""" select FRACTION
461     from
462     CMS_GT_MON.V_SCALERS_TCS_DEADTIME
463     where
464 grchrist 1.27 RUN_NUMBER=%s and
465     LUMI_SECTION in %s and
466     SCALER_NAME='DeadtimeBeamActive'"""
467    
468 grchrist 1.26
469 grchrist 1.27 LSRangeSTR = str(LSRange)
470     LSRangeSTR = LSRangeSTR.replace("[","(")
471     LSRangeSTR = LSRangeSTR.replace("]",")")
472    
473     query=sqlquery %(self.RunNumber,LSRangeSTR)
474     #print query
475     self.curs.execute(query)
476 grchrist 1.26
477 grchrist 1.27 deadtimeba_sum=0
478     ii=0
479     for deadtimebeamactive in self.curs.fetchall():
480 grchrist 1.37 try:
481     deadtimeba_sum=deadtimeba_sum+deadtimebeamactive[0]
482     except:
483     ##print "no dtba for run ",self.RunNumber, ", ls ",LSRange[ii], "using dt"
484     deadtimeba_sum=deadtimeba_sum+self.GetDeadTime(LSRange[ii])
485 grchrist 1.27 ii=ii+1
486     deadtimeba_av=deadtimeba_sum/len(LSRange)
487    
488     return deadtimeba_av
489    
490    
491    
492     def GetDeadTime(self,LS):
493     sqlquery=""" select FRACTION
494     from
495     CMS_GT_MON.V_SCALERS_TCS_DEADTIME
496     where
497     RUN_NUMBER=%s and
498     LUMI_SECTION=%s and
499     SCALER_NAME='Deadtime'"""
500    
501     query=sqlquery %(self.RunNumber,LS)
502     #print query
503 grchrist 1.26 self.curs.execute(query)
504 grchrist 1.35 dt=1.0
505 grchrist 1.27 for deadtime in self.curs.fetchall():
506     try:
507     dt=deadtime[0]
508 grchrist 1.34 #print "dt=",dt
509 grchrist 1.27 except:
510     print "no dt for run ",self.RunNumber, ", ls ",LS
511     dt=1.0
512    
513    
514     return dt
515 grchrist 1.19
516 amott 1.5 def GetAvLumiInfo(self,LSRange):
517     nLS=0;
518     AvInstLumi=0
519 amott 1.6 try:
520     StartLS = LSRange[0]
521     EndLS = LSRange[-1]
522 grchrist 1.26
523     #print "startls=",StartLS, "endls=",EndLS
524 amott 1.23 try: ## Cosmics won't have lumi info
525     maxlive = self.LiveLumiByLS[EndLS]
526     maxdelivered = self.DeliveredLumiByLS[EndLS]
527     for iterator in LSRange:
528     if self.LiveLumiByLS[iterator] > maxlive:
529     maxlive = self.LiveLumiByLS[iterator]
530     if self.DeliveredLumiByLS[iterator] > maxdelivered:
531     maxdelivered = self.DeliveredLumiByLS[iterator]
532     AvLiveLumi=maxlive-self.LiveLumiByLS[StartLS]
533     AvDeliveredLumi=maxdelivered-self.DeliveredLumiByLS[StartLS]
534     except:
535     AvLiveLumi=0
536     AvDeliveredLumi=0
537 abrinke1 1.15
538 abrinke1 1.14 if AvDeliveredLumi > 0:
539     AvDeadTime = 1 - AvLiveLumi/AvDeliveredLumi
540     else:
541     if AvLiveLumi > 0:
542     print "Live Lumi > 0 but Delivered <= 0: problem"
543     AvDeadTime = 0.0
544 abrinke1 1.17 PSCols=[]
545 amott 1.6 for ls in LSRange:
546     try:
547 amott 1.23 try:
548     AvInstLumi+=self.InstLumiByLS[ls]
549     except:
550     pass
551 abrinke1 1.17 PSCols.append(self.PSColumnByLS[ls])
552 amott 1.6 nLS+=1
553     except:
554     print "ERROR: Lumi section "+str(ls)+" not in bounds"
555     return [0.,0.,0.,0.,[]]
556 abrinke1 1.18 return [AvInstLumi/nLS,(1000.0/23.3)*AvLiveLumi/(EndLS-StartLS),(1000.0/23.3)*AvDeliveredLumi/(EndLS-StartLS), AvDeadTime,PSCols]
557 amott 1.6 except:
558 grchrist 1.26 if LSRange[0] == LSRange[-1]:
559 abrinke1 1.13 AvInstLumi = self.InstLumiByLS[StartLS]
560     try:
561     AvLiveLumi = self.LiveLumiByLS[StartLS]-self.LiveLumiByLS[StartLS-1]
562     AvDeliveredLumi = self.DeliveredLumiByLS[StartLS]-self.DeliveredLumiByLS[StartLS-1]
563 grchrist 1.26
564 abrinke1 1.13 except:
565 grchrist 1.27 try:
566     AvLiveLumi = self.LiveLumiByLS[StartLS+1]-self.LiveLumiByLS[StartLS]
567     AvDeliveredLumi = self.DeliveredLumiByLS[StartLS+1]-self.DeliveredLumiByLS[StartLS]
568     except:
569     print "missing live/delivered run ",self.RunNumber, "ls ",LSRange
570     AvLiveLumi = 0
571     AvDeliveredLumi = 0
572 abrinke1 1.14 if AvDeliveredLumi > 0:
573     AvDeadTime = 1 - AvLiveLumi/AvDeliveredLumi
574 grchrist 1.26
575 grchrist 1.27 elif AvLiveLumi > 0:
576     print "Live Lumi > 0 but Delivered <= 0: problem run ",self.RunNumber, " ls ",LSRange
577     AvDeadTime = 1.0
578 abrinke1 1.14 else:
579 grchrist 1.27 AvDeadTime=1.0
580 abrinke1 1.13 PSCols = [self.PSColumnByLS[StartLS]]
581 abrinke1 1.18 return [AvInstLumi,(1000.0/23.3)*AvLiveLumi,(1000.0/23.3)*AvDeliveredLumi,AvDeadTime,PSCols]
582 abrinke1 1.13 else:
583 abrinke1 1.18 return [0.,0.,0.,0.,[]]
584 amott 1.6
585 amott 1.1 def ParsePSColumnPage(self): ## this is now done automatically when we read the db
586     pass
587    
588     def GetL1NameIndexAssoc(self):
589     ## get the L1 algo names associated with each algo bit
590     AlgoNameQuery = """SELECT ALGO_INDEX, ALIAS FROM CMS_GT.L1T_MENU_ALGO_VIEW
591     WHERE MENU_IMPLEMENTATION IN (SELECT L1T_MENU_FK FROM CMS_GT.GT_SETUP WHERE ID='%s')
592     ORDER BY ALGO_INDEX""" % (self.GT_Key,)
593     self.curs.execute(AlgoNameQuery)
594     for index,name in self.curs.fetchall():
595 amott 1.4 self.L1IndexNameMap[name] = index
596 amott 1.1
597     def GetL1AlgoPrescales(self):
598     L1PrescalesQuery= """
599     SELECT
600     PRESCALE_FACTOR_ALGO_000,PRESCALE_FACTOR_ALGO_001,PRESCALE_FACTOR_ALGO_002,PRESCALE_FACTOR_ALGO_003,PRESCALE_FACTOR_ALGO_004,PRESCALE_FACTOR_ALGO_005,
601     PRESCALE_FACTOR_ALGO_006,PRESCALE_FACTOR_ALGO_007,PRESCALE_FACTOR_ALGO_008,PRESCALE_FACTOR_ALGO_009,PRESCALE_FACTOR_ALGO_010,PRESCALE_FACTOR_ALGO_011,
602     PRESCALE_FACTOR_ALGO_012,PRESCALE_FACTOR_ALGO_013,PRESCALE_FACTOR_ALGO_014,PRESCALE_FACTOR_ALGO_015,PRESCALE_FACTOR_ALGO_016,PRESCALE_FACTOR_ALGO_017,
603     PRESCALE_FACTOR_ALGO_018,PRESCALE_FACTOR_ALGO_019,PRESCALE_FACTOR_ALGO_020,PRESCALE_FACTOR_ALGO_021,PRESCALE_FACTOR_ALGO_022,PRESCALE_FACTOR_ALGO_023,
604     PRESCALE_FACTOR_ALGO_024,PRESCALE_FACTOR_ALGO_025,PRESCALE_FACTOR_ALGO_026,PRESCALE_FACTOR_ALGO_027,PRESCALE_FACTOR_ALGO_028,PRESCALE_FACTOR_ALGO_029,
605     PRESCALE_FACTOR_ALGO_030,PRESCALE_FACTOR_ALGO_031,PRESCALE_FACTOR_ALGO_032,PRESCALE_FACTOR_ALGO_033,PRESCALE_FACTOR_ALGO_034,PRESCALE_FACTOR_ALGO_035,
606     PRESCALE_FACTOR_ALGO_036,PRESCALE_FACTOR_ALGO_037,PRESCALE_FACTOR_ALGO_038,PRESCALE_FACTOR_ALGO_039,PRESCALE_FACTOR_ALGO_040,PRESCALE_FACTOR_ALGO_041,
607     PRESCALE_FACTOR_ALGO_042,PRESCALE_FACTOR_ALGO_043,PRESCALE_FACTOR_ALGO_044,PRESCALE_FACTOR_ALGO_045,PRESCALE_FACTOR_ALGO_046,PRESCALE_FACTOR_ALGO_047,
608     PRESCALE_FACTOR_ALGO_048,PRESCALE_FACTOR_ALGO_049,PRESCALE_FACTOR_ALGO_050,PRESCALE_FACTOR_ALGO_051,PRESCALE_FACTOR_ALGO_052,PRESCALE_FACTOR_ALGO_053,
609     PRESCALE_FACTOR_ALGO_054,PRESCALE_FACTOR_ALGO_055,PRESCALE_FACTOR_ALGO_056,PRESCALE_FACTOR_ALGO_057,PRESCALE_FACTOR_ALGO_058,PRESCALE_FACTOR_ALGO_059,
610     PRESCALE_FACTOR_ALGO_060,PRESCALE_FACTOR_ALGO_061,PRESCALE_FACTOR_ALGO_062,PRESCALE_FACTOR_ALGO_063,PRESCALE_FACTOR_ALGO_064,PRESCALE_FACTOR_ALGO_065,
611     PRESCALE_FACTOR_ALGO_066,PRESCALE_FACTOR_ALGO_067,PRESCALE_FACTOR_ALGO_068,PRESCALE_FACTOR_ALGO_069,PRESCALE_FACTOR_ALGO_070,PRESCALE_FACTOR_ALGO_071,
612     PRESCALE_FACTOR_ALGO_072,PRESCALE_FACTOR_ALGO_073,PRESCALE_FACTOR_ALGO_074,PRESCALE_FACTOR_ALGO_075,PRESCALE_FACTOR_ALGO_076,PRESCALE_FACTOR_ALGO_077,
613     PRESCALE_FACTOR_ALGO_078,PRESCALE_FACTOR_ALGO_079,PRESCALE_FACTOR_ALGO_080,PRESCALE_FACTOR_ALGO_081,PRESCALE_FACTOR_ALGO_082,PRESCALE_FACTOR_ALGO_083,
614     PRESCALE_FACTOR_ALGO_084,PRESCALE_FACTOR_ALGO_085,PRESCALE_FACTOR_ALGO_086,PRESCALE_FACTOR_ALGO_087,PRESCALE_FACTOR_ALGO_088,PRESCALE_FACTOR_ALGO_089,
615     PRESCALE_FACTOR_ALGO_090,PRESCALE_FACTOR_ALGO_091,PRESCALE_FACTOR_ALGO_092,PRESCALE_FACTOR_ALGO_093,PRESCALE_FACTOR_ALGO_094,PRESCALE_FACTOR_ALGO_095,
616     PRESCALE_FACTOR_ALGO_096,PRESCALE_FACTOR_ALGO_097,PRESCALE_FACTOR_ALGO_098,PRESCALE_FACTOR_ALGO_099,PRESCALE_FACTOR_ALGO_100,PRESCALE_FACTOR_ALGO_101,
617     PRESCALE_FACTOR_ALGO_102,PRESCALE_FACTOR_ALGO_103,PRESCALE_FACTOR_ALGO_104,PRESCALE_FACTOR_ALGO_105,PRESCALE_FACTOR_ALGO_106,PRESCALE_FACTOR_ALGO_107,
618     PRESCALE_FACTOR_ALGO_108,PRESCALE_FACTOR_ALGO_109,PRESCALE_FACTOR_ALGO_110,PRESCALE_FACTOR_ALGO_111,PRESCALE_FACTOR_ALGO_112,PRESCALE_FACTOR_ALGO_113,
619     PRESCALE_FACTOR_ALGO_114,PRESCALE_FACTOR_ALGO_115,PRESCALE_FACTOR_ALGO_116,PRESCALE_FACTOR_ALGO_117,PRESCALE_FACTOR_ALGO_118,PRESCALE_FACTOR_ALGO_119,
620     PRESCALE_FACTOR_ALGO_120,PRESCALE_FACTOR_ALGO_121,PRESCALE_FACTOR_ALGO_122,PRESCALE_FACTOR_ALGO_123,PRESCALE_FACTOR_ALGO_124,PRESCALE_FACTOR_ALGO_125,
621     PRESCALE_FACTOR_ALGO_126,PRESCALE_FACTOR_ALGO_127
622     FROM CMS_GT.GT_FDL_PRESCALE_FACTORS_ALGO A, CMS_GT.GT_RUN_SETTINGS_PRESC_VIEW B
623     WHERE A.ID=B.PRESCALE_FACTORS_ALGO_FK AND B.ID='%s'
624     """ % (self.GTRS_Key,)
625     self.curs.execute(L1PrescalesQuery)
626     ## This is pretty horrible, but this how you get them!!
627     tmp = self.curs.fetchall()
628     for ps in tmp[0]: #build the prescale table initially
629     self.L1PrescaleTable.append([ps])
630     for line in tmp[1:]: # now fill it
631     for ps,index in zip(line,range(len(line))):
632     self.L1PrescaleTable[index].append(ps)
633 amott 1.4 self.nAlgoBits=128
634 amott 1.1
635     def GetHLTIndex(self,name):
636     for i,n in enumerate(self.HLTList):
637     if n.find(name)!=-1:
638     return i
639 amott 1.2 #print name
640 amott 1.1 return -1
641    
642     def GetHLTPrescaleMatrix(self,cursor):
643     ##NOT WORKING 1/19/2012
644     return
645     SequencePathQuery ="""
646     SELECT F.SEQUENCENB,J.VALUE TRIGGERNAME
647     FROM CMS_HLT.CONFIGURATIONSERVICEASSOC A
648     , CMS_HLT.SERVICES B
649     , CMS_HLT.SERVICETEMPLATES C
650     , CMS_HLT.SUPERIDVECPARAMSETASSOC D
651     , CMS_HLT.VECPARAMETERSETS E
652     , CMS_HLT.SUPERIDPARAMSETASSOC F
653     , CMS_HLT.PARAMETERSETS G
654     , CMS_HLT.SUPERIDPARAMETERASSOC H
655     , CMS_HLT.PARAMETERS I
656     , CMS_HLT.STRINGPARAMVALUES J
657     WHERE A.CONFIGID= %d
658     AND A.SERVICEID=B.SUPERID
659     AND B.TEMPLATEID=C.SUPERID
660     AND C.NAME='PrescaleService'
661     AND B.SUPERID=D.SUPERID
662     AND D.VPSETID=E.SUPERID
663     AND E.NAME='prescaleTable'
664     AND D.VPSETID=F.SUPERID
665     AND F.PSETID=G.SUPERID
666     AND G.SUPERID=H.SUPERID
667     AND I.PARAMID=H.PARAMID
668     AND I.NAME='pathName'
669     AND J.PARAMID=H.PARAMID
670     ORDER BY F.SEQUENCENB
671     """ % (self.ConfigId,)
672    
673     cursor.execute(SequencePathQuery)
674     self.HLTSequenceMap = [0]*len(self.HLTList)
675     for seq,name in cursor.fetchall():
676     name = name.lstrip('"').rstrip('"')
677     try:
678     self.HLTSequenceMap[self.GetHLTIndex(name)]=seq
679     except:
680     print "couldn't find "+name
681    
682     for i,seq in enumerate(self.HLTSequenceMap):
683     if seq==0:
684     print self.HLTList[i]
685    
686     SequencePrescaleQuery="""
687     SELECT F.SEQUENCENB,J.SEQUENCENB,J.VALUE
688     FROM CMS_HLT.CONFIGURATIONSERVICEASSOC A
689     , CMS_HLT.SERVICES B
690     , CMS_HLT.SERVICETEMPLATES C
691     , CMS_HLT.SUPERIDVECPARAMSETASSOC D
692     , CMS_HLT.VECPARAMETERSETS E
693     , CMS_HLT.SUPERIDPARAMSETASSOC F
694     , CMS_HLT.PARAMETERSETS G
695     , CMS_HLT.SUPERIDPARAMETERASSOC H
696     , CMS_HLT.PARAMETERS I
697     , CMS_HLT.VUINT32PARAMVALUES J
698     WHERE A.CONFIGID=%d
699     AND A.SERVICEID=B.SUPERID
700     AND B.TEMPLATEID=C.SUPERID
701     AND C.NAME='PrescaleService'
702     AND B.SUPERID=D.SUPERID
703     AND D.VPSETID=E.SUPERID
704     AND E.NAME='prescaleTable'
705     AND D.VPSETID=F.SUPERID
706     AND F.PSETID=G.SUPERID
707     AND G.SUPERID=H.SUPERID
708     AND I.PARAMID=H.PARAMID
709     AND I.NAME='prescales'
710     AND J.PARAMID=H.PARAMID
711     ORDER BY F.SEQUENCENB,J.SEQUENCENB
712     """ % (self.ConfigId,)
713    
714 amott 1.2 #print self.HLTSequenceMap
715 amott 1.1 cursor.execute(SequencePrescaleQuery)
716     self.HLTPrescaleTable=[ [] ]*len(self.HLTList)
717     lastIndex=-1
718     lastSeq=-1
719     row = []
720     for seq,index,val in cursor.fetchall():
721     if lastIndex!=index-1:
722     self.HLTPrescaleTable[self.HLTSequenceMap.index(lastSeq)].append(row)
723     row=[]
724     lastSeq=seq
725     lastIndex=index
726     row.append(val)
727    
728     def GetHLTSeeds(self):
729     ## This is a rather delicate query, but it works!
730     ## Essentially get a list of paths associated with the config, then find the module of type HLTLevel1GTSeed associated with the path
731     ## Then find the parameter with field name L1SeedsLogicalExpression and look at the value
732     ##
733     ## NEED TO BE LOGGED IN AS CMS_HLT_R
734 amott 1.24 tmpcurs = ConnectDB('hlt')
735 amott 1.1 sqlquery ="""
736     SELECT I.NAME,A.VALUE
737     FROM
738     CMS_HLT.STRINGPARAMVALUES A,
739     CMS_HLT.PARAMETERS B,
740     CMS_HLT.SUPERIDPARAMETERASSOC C,
741     CMS_HLT.MODULETEMPLATES D,
742     CMS_HLT.MODULES E,
743     CMS_HLT.PATHMODULEASSOC F,
744     CMS_HLT.CONFIGURATIONPATHASSOC G,
745     CMS_HLT.CONFIGURATIONS H,
746     CMS_HLT.PATHS I
747     WHERE
748     A.PARAMID = C.PARAMID AND
749     B.PARAMID = C.PARAMID AND
750     B.NAME = 'L1SeedsLogicalExpression' AND
751     C.SUPERID = F.MODULEID AND
752     D.NAME = 'HLTLevel1GTSeed' AND
753     E.TEMPLATEID = D.SUPERID AND
754     F.MODULEID = E.SUPERID AND
755     F.PATHID=G.PATHID AND
756     I.PATHID=G.PATHID AND
757     G.CONFIGID=H.CONFIGID AND
758     H.CONFIGDESCRIPTOR='%s'
759 amott 1.2 ORDER BY A.VALUE
760 amott 1.1 """ % (self.HLT_Key,)
761     tmpcurs.execute(sqlquery)
762     for HLTPath,L1Seed in tmpcurs.fetchall():
763 amott 1.4 if not self.HLTSeed.has_key(HLTPath): ## this should protect us from L1_SingleMuOpen
764     self.HLTSeed[HLTPath] = L1Seed.lstrip('"').rstrip('"')
765 amott 1.1 #self.GetHLTPrescaleMatrix(tmpcurs)
766    
767     def ParseRunSetup(self):
768     #queries that need to be run only once per run
769     self.GetRunInfo()
770     self.GetL1NameIndexAssoc()
771     self.GetL1AlgoPrescales()
772     self.GetHLTSeeds()
773 amott 1.5 self.GetLumiInfo()
774 grchrist 1.21 self.LastLSParsed=-1
775     self.GetMoreLumiInfo()
776 grchrist 1.27 self.LastLsParsed=-1
777     #self.GetDeadTimeBeamActive()
778 amott 1.5
779     def UpdateRun(self,LSRange):
780     self.GetLumiInfo()
781     TriggerRates = self.GetHLTRates(LSRange)
782 abrinke1 1.10 #L1Prescales = self.CalculateAvL1Prescales(LSRange)
783     #TotalPrescales = self.CalculateTotalPrescales(TriggerRates,L1Prescales)
784     #UnprescaledRates = self.UnprescaleRates(TriggerRates,TotalPrescales)
785 amott 1.5
786 abrinke1 1.10 #return [UnprescaledRates, TotalPrescales, L1Prescales, TriggerRates]
787     return TriggerRates
788    
789 amott 1.23 def GetLSRange(self,StartLS, NLS,reqPhysics=True):
790 amott 1.5 """
791     returns an array of valid LumiSections
792     if NLS < 0, count backwards from StartLS
793     """
794 amott 1.1 self.GetLumiInfo()
795 amott 1.5 LS=[]
796     curLS=StartLS
797     step = NLS/abs(NLS)
798     NLS=abs(NLS)
799 grchrist 1.34
800 amott 1.5 while len(LS)<NLS:
801     if (curLS<0 and step<0) or (curLS>=self.LastLSParsed and step>0):
802     break
803 amott 1.30 if curLS>=0 and curLS<self.LastLSParsed-1:
804 amott 1.23 if (not self.Physics.has_key(curLS) or not self.Active.has_key(curLS)) and reqPhysics:
805 amott 1.5 break
806 grchrist 1.34
807 amott 1.23 if not reqPhysics or (self.Physics[curLS] and self.Active[curLS]):
808 amott 1.5 if step>0:
809     LS.append(curLS)
810     else:
811     LS.insert(0,curLS)
812     curLS += step
813     return LS
814    
815 amott 1.8 def GetLastLS(self,phys=False):
816 amott 1.7 self.GetLumiInfo()
817 grchrist 1.34
818 amott 1.7 try:
819 amott 1.8 if not phys:
820 grchrist 1.34 maxLS=-1
821     for ls, active in self.Active.iteritems():
822     if active and ls>maxLS:
823     maxLS=ls
824     if maxLS==-1:
825     return 0
826     else:
827     return maxLS
828    
829 amott 1.8 else:
830     maxLS=-1
831     for ls,phys in self.Physics.iteritems():
832     if phys and self.Active[ls] and ls > maxLS:
833     maxLS=ls
834     if maxLS==-1:
835     return 0
836     else:
837     return maxLS
838 amott 1.7 except:
839     return 0
840    
841 amott 1.5 def CalculateAvL1Prescales(self,LSRange):
842     AvgL1Prescales = [0]*self.nAlgoBits
843     for index in LSRange:
844 amott 1.1 psi = self.PSColumnByLS[index]
845     if not psi:
846 awoodard 1.47 print "L1: Cannot figure out PSI for LS "+str(index)+" setting to 3"
847     psi = 3
848 amott 1.4 for algo in range(self.nAlgoBits):
849 amott 1.5 AvgL1Prescales[algo]+=self.L1PrescaleTable[algo][psi]
850     for i in range(len(AvgL1Prescales)):
851 amott 1.6 try:
852     AvgL1Prescales[i] = AvgL1Prescales[i]/len(LSRange)
853     except:
854     AvgL1Prescales[i] = AvgL1Prescales[i]
855 amott 1.5 return AvgL1Prescales
856    
857     def CalculateTotalPrescales(self,TriggerRates, L1Prescales):
858     AvgTotalPrescales={}
859     for hltName,v in TriggerRates.iteritems():
860 amott 1.4 if not self.HLTSeed.has_key(hltName):
861     continue
862 amott 1.1 hltPS=0
863 amott 1.4 if len(v)>0:
864     hltPS = v[0]
865     l1Index=-1
866     if self.L1IndexNameMap.has_key(self.HLTSeed[hltName]):
867     l1Index = self.L1IndexNameMap[self.HLTSeed[hltName]]
868    
869 amott 1.1 l1PS=0
870     if l1Index==-1:
871 amott 1.5 l1PS = self.UnwindORSeed(self.HLTSeed[hltName],L1Prescales)
872 amott 1.1 else:
873 amott 1.5 l1PS = L1Prescales[l1Index]
874     AvgTotalPrescales[hltName]=l1PS*hltPS
875     return AvgTotalPrescales
876 amott 1.1
877 amott 1.5 def UnwindORSeed(self,expression,L1Prescales):
878 amott 1.4 """
879     Figures out the effective prescale for the OR of several seeds
880     we take this to be the *LOWEST* prescale of the included seeds
881     """
882 amott 1.2 if expression.find(" OR ") == -1:
883     return -1 # Not an OR of seeds
884     seedList = expression.split(" OR ")
885     if len(seedList)==1:
886     return -1 # Not an OR of seeds, really shouldn't get here...
887     minPS = 99999999999
888     for seed in seedList:
889 amott 1.4 if not self.L1IndexNameMap.has_key(seed):
890     continue
891 amott 1.5 ps = L1Prescales[self.L1IndexNameMap[seed]]
892 amott 1.4 if ps:
893     minPS = min(ps,minPS)
894 amott 1.2 if minPS==99999999999:
895     return 0
896     else:
897     return minPS
898    
899 amott 1.5 def UnprescaleRates(self,TriggerRates,TotalPrescales):
900     UnprescaledRates = {}
901     for hltName,v in TriggerRates.iteritems():
902     if TotalPrescales.has_key(hltName):
903     ps = TotalPrescales[hltName]
904 amott 1.4 if ps:
905 amott 1.5 UnprescaledRates[hltName] = v[1]*ps
906 amott 1.4 else:
907 amott 1.5 UnprescaledRates[hltName] = v[1]
908 amott 1.4 else:
909 amott 1.5 UnprescaledRates[hltName] = v[1]
910     return UnprescaledRates
911 abrinke1 1.13
912 amott 1.11 def GetTotalL1Rates(self):
913 grchrist 1.46 query = "SELECT RUNNUMBER, LUMISEGMENTNR, L1ASPHYSICS/23.3 FROM CMS_WBM.LEVEL1_TRIGGER_CONDITIONS WHERE RUNNUMBER=%s" % self.RunNumber
914 amott 1.11 self.curs.execute(query)
915     L1Rate = {}
916     for LS,rate in self.curs.fetchall():
917     psi = self.PSColumnByLS.get(LS,0)
918     lumi = self.InstLumiByLS.get(LS,0)
919     L1Rate[LS] = [rate,psi,lumi]
920     return L1Rate
921 grchrist 1.46
922     def GetL1RatesALL(self,LSRange):
923    
924    
925     #sqlquery = "SELECT RUN_NUMBER, LUMI_SECTION, RATE_HZ, SCALER_INDEX FROM CMS_GT_MON.V_SCALERS_TCS_TRIGGER WHERE RUN_NUMBER=%s AND LUMI_SECTION IN %s and SCALER_INDEX=9"
926    
927     ##sqlquery = "SELECT RUN_NUMBER, LUMI_SECTION, RATE_HZ, SCALER_INDEX FROM CMS_GT_MON.V_SCALERS_FDL_ALGO WHERE RUN_NUMBER=%s AND LUMI_SECTION IN %s and SCALER_INDEX IN (9,13, 71)"
928    
929     sqlquery = "SELECT RUN_NUMBER, LUMI_SECTION, RATE_HZ, SCALER_INDEX FROM CMS_GT_MON.V_SCALERS_FDL_ALGO WHERE RUN_NUMBER=%s AND LUMI_SECTION IN %s"
930    
931     LSRangeSTR = str(LSRange)
932     LSRangeSTR = LSRangeSTR.replace("[","(")
933     LSRangeSTR = LSRangeSTR.replace("]",")")
934    
935     query= sqlquery %(self.RunNumber,LSRangeSTR)
936     self.curs.execute(query)
937     L1RateAll=self.curs.fetchall()
938     L1RatesBits={}
939     ###initialize dict of L1 bits
940     for L1seed in sorted(self.L1IndexNameMap.iterkeys()):
941     L1RatesBits[self.L1IndexNameMap[L1seed]]=0
942    
943     ###sum dict of L1 bits
944     for line in L1RateAll:
945     #if line[3] in self.L1IndexNameMap: ##do not fill if empty L1 key
946     try:
947     L1RatesBits[line[3]]=line[2]+L1RatesBits[line[3]]
948     except:
949     pass
950     #print "not filling bit",line[3]
951     ###divide by number of LS
952     for name in self.L1IndexNameMap.iterkeys():
953     L1RatesBits[self.L1IndexNameMap[name]]=L1RatesBits[self.L1IndexNameMap[name]]/len(LSRange)
954    
955     ###total L1 PS table
956     L1PSdict={}
957     counter=0
958     for line in self.L1PrescaleTable:
959     L1PSdict[counter]=line
960     counter=counter+1
961     for LS in LSRange:
962     self.PSColumnByLS[LS]
963    
964     ###av ps dict
965     L1PSbits={}
966     for bit in L1PSdict.iterkeys():
967     L1PSbits[bit]=0
968     for bit in L1PSdict.iterkeys():
969     for LS in LSRange:
970     L1PSbits[bit]=L1PSbits[bit]+L1PSdict[bit][self.PSColumnByLS[LS]]
971     for bit in L1PSdict.iterkeys():
972     L1PSbits[bit]=L1PSbits[bit]/len(LSRange)
973    
974     ###convert dict of L1 bits to dict of L1 names
975     L1RatesNames={}
976     for name in self.L1IndexNameMap.iterkeys():
977     dummy=[]
978     dummy.append(L1PSbits[self.L1IndexNameMap[name]])
979     dummy.append(L1PSbits[self.L1IndexNameMap[name]])
980     dummy.append(L1RatesBits[self.L1IndexNameMap[name]])
981     dummy.append(L1RatesBits[self.L1IndexNameMap[name]]*L1PSbits[self.L1IndexNameMap[name]])
982     L1RatesNames[name+'_v1']=dummy
983    
984     return L1RatesNames
985    
986    
987    
988     def GetL1Rates(self,LSRange):
989    
990     sqlquery = "SELECT RUN_NUMBER, LUMI_SECTION, SCALER_NAME, RATE_HZ FROM CMS_GT_MON.V_SCALERS_TCS_TRIGGER WHERE RUN_NUMBER=%s and SCALER_NAME='L1AsPhysics' and LUMI_SECTION in %s"
991    
992     LSRangeSTR = str(LSRange)
993     LSRangeSTR = LSRangeSTR.replace("[","(")
994     LSRangeSTR = LSRangeSTR.replace("]",")")
995    
996     query=sqlquery %(self.RunNumber, LSRangeSTR)
997    
998     #print query
999     self.curs.execute(query)
1000    
1001     L1Rate=self.curs.fetchall()
1002    
1003     for line in L1Rate:
1004     #print line
1005     pass
1006    
1007    
1008    
1009     return L1Rate
1010 abrinke1 1.13
1011 amott 1.1 def AssemblePrescaleValues(self): ##Depends on output from ParseLumiPage and ParseTriggerModePage
1012     return ## WHAT DOES THIS FUNCTION DO???
1013     MissingName = "Nemo"
1014     for key in self.L1TriggerMode:
1015     self.L1Prescale[key] = {}
1016     for n in range(min(self.LSByLS),max(self.LSByLS)+1): #"range()" excludes the last element
1017     try:
1018     self.L1Prescale[key][n] = self.L1TriggerMode[key][self.PSColumnByLS[n]]
1019     except:
1020     if not key == MissingName:
1021     self.MissingPrescale.append(key)
1022     MissingName = key
1023     if not n < 2:
1024     print "LS "+str(n)+" of key "+str(key)+" is missing from the LumiSections page"
1025    
1026     for key in self.HLTTriggerMode:
1027     self.HLTPrescale[key] = {}
1028     for n in range(min(self.LSByLS),max(self.LSByLS)+1): #"range" excludes the last element
1029     try:
1030     self.HLTPrescale[key][n] = self.HLTTriggerMode[key][self.PSColumnByLS[n]]
1031     except:
1032     if not key == MissingName:
1033     self.MissingPrescale.append(key)
1034     MissingName = key
1035     if not n < 2:
1036     print "LS "+str(n)+" of key "+str(key)+" is missing from the LumiSections page"
1037    
1038     self.PrescaleValues = [self.L1Prescale,self.HLTPrescale,self.MissingPrescale]
1039     return self.PrescaleValues
1040    
1041     def ComputeTotalPrescales(self,StartLS,EndLS):
1042     return ## WHAT DOES THIS FUNCTION DO??
1043     IdealHLTPrescale = {}
1044     IdealPrescale = {}
1045     L1_zero = {}
1046     HLT_zero = {}
1047     n1 = {}
1048     n2 = {}
1049     L1 = {}
1050     L2 = {}
1051     H1 = {}
1052     H2 = {}
1053     InitialColumnIndex = self.PSColumnByLS[int(StartLS)]
1054    
1055     for key in self.HLTTriggerMode:
1056     try:
1057     DoesThisPathHaveAValidL1SeedWithPrescale = self.L1Prescale[self.HLTSeed[key]][StartLS]
1058     except:
1059     L1_zero[key] = True
1060     HLT_zero[key] = False
1061     continue
1062    
1063     IdealHLTPrescale[key] = 0.0
1064     IdealPrescale[key] = 0.0
1065     n1[key] = 0
1066     L1_zero[key] = False
1067     HLT_zero[key] = False
1068    
1069     for LSIterator in range(StartLS,EndLS+1): #"range" excludes the last element
1070     if self.L1Prescale[self.HLTSeed[key]][LSIterator] > 0 and self.HLTPrescale[key][LSIterator] > 0:
1071     IdealPrescale[key]+=1.0/(self.L1Prescale[self.HLTSeed[key]][LSIterator]*self.HLTPrescale[key][LSIterator])
1072     else:
1073     IdealPrescale[key]+=1.0 ##To prevent a divide by 0 error later
1074     if self.L1Prescale[self.HLTSeed[key]][LSIterator] < 0.1:
1075     L1_zero[key] = True
1076     if self.HLTPrescale[key][LSIterator] < 0.1:
1077     HLT_zero[key] = True
1078     if self.PSColumnByLS[LSIterator] == InitialColumnIndex:
1079     n1[key]+=1
1080    
1081     if L1_zero[key] == True or HLT_zero[key] == True:
1082     continue
1083    
1084     IdealPrescale[key] = (EndLS + 1 - StartLS)/IdealPrescale[key]
1085    
1086     n2[key] = float(EndLS + 1 - StartLS - n1[key])
1087     L1[key] = float(self.L1Prescale[self.HLTSeed[key]][StartLS])
1088     L2[key] = float(self.L1Prescale[self.HLTSeed[key]][EndLS])
1089     H1[key] = float(self.HLTPrescale[key][StartLS])
1090     H2[key] = float(self.HLTPrescale[key][EndLS])
1091    
1092     IdealHLTPrescale[key] = ((n1[key]/L1[key])+(n2[key]/L2[key]))/((n1[key]/(L1[key]*H1[key]))+(n2[key]/(L2[key]*H2[key])))
1093    
1094     self.TotalPSInfo = [L1_zero,HLT_zero,IdealPrescale,IdealHLTPrescale,n1,n2,L1,L2,H1,H2]
1095    
1096     return self.TotalPSInfo
1097    
1098    
1099     def CorrectForPrescaleChange(self,StartLS,EndLS):
1100     [L1_zero,HLT_zero,IdealPrescale,IdealHLTPrescale,n1,n2,L1,L2,H1,H2] = self.TotalPSInfo
1101     xLS = {}
1102     RealPrescale = {}
1103    
1104     for key in self.HLTTriggerMode:
1105     if L1_zero[key] == True or HLT_zero[key] == True:
1106     continue
1107     [TriggerRate,L1Pass,PSPass,PS,Seed,StartLS,EndLS] = self.TriggerRates[key]
1108     if PS > 0.95 * IdealHLTPrescale[key] and PS < 1.05 * IdealHLTPrescale[key]:
1109     RealPrescale[key] = IdealPrescale[key]
1110     continue
1111    
1112     if H1[key] == H2[key] and L1[key] == L2[key] and not EndLS > max(self.LSByLS) - 1: ##Look for prescale change into the next LS
1113     H2[key] = float(self.HLTPrescale[key][EndLS+1])
1114     L2[key] = float(self.L1Prescale[self.HLTSeed[key]][EndLS+1])
1115     if H1[key] == H2[key] and L1[key] == L2[key] and not StartLS < 3:
1116     H1[key] = float(self.HLTPrescale[key][StartLS-1])
1117     L1[key] = float(self.L1Prescale[self.HLTSeed[key]][StartLS-1])
1118     if H1[key] == H2[key]:
1119     xLS[key] = 0
1120     else:
1121     xLS[key] = ((-(PS/IdealHLTPrescale[key])*(L2[key]*n1[key]+L1[key]*n2[key])*(H2[key]*L2[key]*n1[key]+H1[key]*L1[key]*n2[key]))+((H2[key]*L2[key]*n1[key]+H1[key]*L1[key]*n2[key])*(L2[key]*n1[key]+L1[key]*n2[key])))/(((PS/IdealHLTPrescale[key])*(L2[key]*n1[key]+L1[key]*n2[key])*(H1[key]*L1[key]-H2[key]*L2[key]))+((H2[key]*L2[key]*n1[key]+H1[key]*L1[key]*n2[key])*(L2[key]-L1[key])))
1122    
1123     if xLS[key] > 1:
1124     xLS[key] = 1
1125     if xLS[key] < -1:
1126     xLS[key] = -1
1127     RealPrescale[key] = (n1[key] + n2[key])/(((n1[key] - xLS[key])/(H1[key]*L1[key]))+(n2[key]+xLS[key])/(H2[key]*L2[key]))
1128    
1129     self.CorrectedPSInfo = [RealPrescale,xLS,L1,L2,H1,H2]
1130    
1131     return self.CorrectedPSInfo
1132    
1133 amott 1.4 def GetAvLumiPerRange(self, NMergeLumis=10):
1134     """
1135 amott 1.5 This function returns a per-LS table of the average lumi of the previous NMergeLumis LS
1136 amott 1.4 """
1137 amott 1.5 AvLumiRange = []
1138     AvLumiTable = {}
1139     for ls,lumi in self.InstLumiByLS.iteritems():
1140     try:
1141     AvLumiRange.append(int(lumi))
1142     except:
1143     continue
1144     if len(AvLumiRange) == NMergeLumis:
1145     AvLumiRange = AvLumiRange[1:]
1146     AvLumiTable[ls] = sum(AvLumiRange)/NMergeLumis
1147 amott 1.4 return AvLumiTable
1148    
1149 amott 1.9 def GetTriggerVersion(self,triggerName):
1150     for key in self.HLTSeed.iterkeys():
1151     if StripVersion(key)==triggerName:
1152     return key
1153     return ""
1154    
1155 amott 1.1 def Save(self, fileName):
1156     dir = os.path.dirname(fileName)
1157     if not os.path.exists(dir):
1158     os.makedirs(dir)
1159     pickle.dump( self, open( fileName, 'w' ) )
1160    
1161     def Load(self, fileName):
1162     self = pickle.load( open( fileName ) )
1163 amott 1.5
1164 amott 1.24 def ConnectDB(user='trg'):
1165 grchrist 1.34 try:
1166     host = os.uname()[1]
1167     offline = 1 if host.startswith('lxplus') else 0
1168     except:
1169     print "Please setup database parsing:\nsource set.sh"
1170 grchrist 1.32 ##print offline
1171 amott 1.30 trg = ['~centraltspro/secure/cms_trg_r.txt','~/secure/cms_trg_r.txt']
1172     hlt = ['~hltpro/secure/cms_hlt_r.txt','~/secure/cms_hlt_r.txt']
1173    
1174 amott 1.24 if user == 'trg':
1175 amott 1.30 cmd = 'cat %s' % (trg[offline],)
1176 amott 1.24 elif user == 'hlt':
1177 amott 1.30 cmd='cat %s' % (hlt[offline],)
1178    
1179     try:
1180     line=os.popen(cmd).readlines()
1181     except:
1182     print "ERROR Getting the database password!"
1183     print "They should be in %s and %s" % (trg[offline],hlt[offline],)
1184     print "You may need to copy them from the online machines"
1185     sys.exit(0)
1186 amott 1.5 magic = line[0].rstrip("\n\r")
1187 amott 1.24 connect = 'cms_%s_r/%s@cms_omds_lb' % (user,magic,)
1188 amott 1.5 orcl = cx_Oracle.connect(connect)
1189 amott 1.24 return orcl.cursor()
1190 grchrist 1.42
1191 amott 1.24
1192 grchrist 1.34 def GetLatestRunNumber(runNo=9999999,newRun=False):
1193 grchrist 1.32
1194 amott 1.24 curs = ConnectDB()
1195 grchrist 1.32
1196 amott 1.23 if runNo==9999999:
1197 grchrist 1.28
1198     ##
1199     ##SELECT MAX(RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL
1200     ##SELECT MAX(RUNNUMBER) CMS_WBM.RUNSUMMARY WHERE TRIGGERS>0
1201     ## RunNoQuery="""
1202     ## SELECT MAX(A.RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL A, CMS_WBM.RUNSUMMARY B WHERE A.RUNNUMBER=B.RUNNUMBER AND B.TRIGGERS>0
1203     ## """
1204    
1205     RunNoQuery="""SELECT MAX(A.RUNNUMBER)
1206     FROM CMS_RUNINFO.RUNNUMBERTBL A, CMS_RUNTIME_LOGGER.LUMI_SECTIONS B WHERE B.RUNNUMBER=A.RUNNUMBER AND B.LUMISECTION > 0
1207 amott 1.23 """
1208 grchrist 1.31 try:
1209     curs.execute(RunNoQuery)
1210     r, = curs.fetchone()
1211 grchrist 1.34 ##print "\nr=",r
1212 grchrist 1.31 except:
1213     print "not able to get run"
1214 grchrist 1.28
1215 grchrist 1.34 ## RunNoQuery="""SELECT MAX(RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL"""
1216 grchrist 1.33 ## try:
1217     ## curs.execute(RunNoQuery)
1218     ## ra, = curs.fetchone()
1219     ## print "ra=",ra
1220     ## except:
1221     ## print "not able to get ra"
1222    
1223    
1224 grchrist 1.42 ## RunNoQuery="""SELECT TIER0_TRANSFER FROM CMS_WBM.RUNSUMMARY WHERE TRIGGERS>0 AND RUNUMBER=MAX(RUNNUMBER)"""
1225 grchrist 1.33 ## try:
1226     ## curs.execute(RunNoQuery)
1227     ## rb, = curs.fetchone()
1228     ## print "rb=",rb
1229     ## except:
1230     ## print "not able to get rb"
1231    
1232     ## RunNoQuery="""SELECT MAX(RUNNUMBER) FROM CMS_RUNTIME_LOGGER.LUMI_SECTIONS WHERE LUMISECTION > 0 """
1233     ## try:
1234     ## curs.execute(RunNoQuery)
1235     ## rc, = curs.fetchone()
1236     ## print "rc=",rc
1237     ## except:
1238     ## print "not able to get rc"
1239 grchrist 1.31
1240 amott 1.23 else:
1241     r = runNo
1242 grchrist 1.32 isCol=0
1243 grchrist 1.29
1244 amott 1.5 TrigModeQuery = """
1245     SELECT TRIGGERMODE FROM CMS_WBM.RUNSUMMARY WHERE RUNNUMBER = %d
1246     """ % r
1247     curs.execute(TrigModeQuery)
1248 grchrist 1.29 try:
1249     trigm, = curs.fetchone()
1250     except:
1251 grchrist 1.32 print "unable to get trigm from query for run ",r
1252 amott 1.5 isCol=0
1253 grchrist 1.31 isGood=1
1254 grchrist 1.42
1255 grchrist 1.43
1256     try:
1257     if trigm is None:
1258     isGood=0
1259     elif trigm.find('l1_hlt_collisions')!=-1:
1260     isCol=1
1261     except:
1262     isGood=0
1263    
1264 grchrist 1.42 Tier0xferQuery = """
1265     SELECT TIER0_TRANSFER TIER0 FROM CMS_WBM.RUNSUMMARY WHERE RUNNUMBER = %d
1266     """ % r
1267     curs.execute(Tier0xferQuery)
1268 muell149 1.44 tier0=1
1269 grchrist 1.42 try:
1270     tier0, = curs.fetchone()
1271 grchrist 1.43
1272 grchrist 1.42 except:
1273     print "unable to get tier0 from query for run ",r
1274    
1275 grchrist 1.43 if isCol and not tier0:
1276     #write(bcolors.FAIL)
1277     print "WARNING tier0 transfer is off"
1278     #write(bcolors.ENDC+"\n")
1279     elif not tier0:
1280     #write(bcolors.WARINING)
1281     print "Please check if tier0 transfer is supposed to be off"
1282     #write(bcolors.ENDC+"\n")
1283 grchrist 1.42
1284 grchrist 1.43
1285    
1286 grchrist 1.31 return (r,isCol,isGood,)
1287 amott 1.5
1288     def ClosestIndex(value,table):
1289     diff = 999999999;
1290     index = 0
1291     for i,thisVal in table.iteritems():
1292     if abs(thisVal-value)<diff:
1293     diff = abs(thisVal-value)
1294     index =i
1295     return index
1296    
1297    
1298     def StripVersion(name):
1299     if re.match('.*_v[0-9]+',name):
1300     name = name[:name.rfind('_')]
1301     return name