ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseParser.py
Revision: 1.50
Committed: Wed Oct 3 11:23:25 2012 UTC (12 years, 7 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-02-03
Changes since 1.49: +9 -12 lines
Log Message:
Backing up to r 1.46

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 awoodard 1.49
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.50 print "HLT in: Cannot figure out PSI for LS "+str(StartLS)+" setting to 0"
182 abrinke1 1.10 print "The value of LSRange[0] is:"
183 grchrist 1.40 print str(LS)
184 awoodard 1.50 psi = 0
185 grchrist 1.38 if psi is None:
186 awoodard 1.50 psi=0
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 awoodard 1.49 #except:
212     #psi = self.PSColumnByLS[1]
213     #if not psi:
214 abrinke1 1.10 except:
215 awoodard 1.50 print "HLT out: Cannot figure out PSI for index "+str(on)+" setting to 0"
216 abrinke1 1.10 print "The value of LSRange[on] is:"
217 grchrist 1.40 print str(LS)
218 awoodard 1.50 psi = 0
219 grchrist 1.38 if psi is None:
220 awoodard 1.50 psi=0
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 awoodard 1.49
268 amott 1.5 return TriggerRates
269 amott 1.1
270 awoodard 1.49 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.49 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.50 self.PSColumnByLS[ls]=psi
366 amott 1.4 self.InstLumiByLS[ls]=inst
367     self.LiveLumiByLS[ls]=live
368     self.DeliveredLumiByLS[ls]=dlive
369     self.DeadTime[ls]=dt
370     self.Physics[ls]=phys
371 amott 1.5 self.Active[ls]=active
372 awoodard 1.49
373 amott 1.1 if pastLSCol!=-1 and ls!=pastLSCol:
374     self.PSColumnChanges.append([ls,psi])
375     pastLSCol=ls
376     if ls>self.LastLSParsed:
377     self.LastLSParsed=ls
378 grchrist 1.22 self.LumiInfo = [self.PSColumnByLS, self.InstLumiByLS, self.DeliveredLumiByLS, self.LiveLumiByLS, self.DeadTime, self.Physics, self.Active]
379 amott 1.1
380 abrinke1 1.13 return self.LumiInfo
381    
382 grchrist 1.19 def GetMoreLumiInfo(self):
383 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
384 grchrist 1.19 FROM CMS_RUNTIME_LOGGER.LUMI_SECTIONS A,CMS_GT_MON.LUMI_SECTIONS B WHERE A.RUNNUMBER=%s
385     AND B.RUN_NUMBER(+)=A.RUNNUMBER AND B.LUMI_SECTION(+)=A.LUMISECTION AND A.LUMISECTION > %d
386     ORDER BY A.RUNNUMBER,A.LUMISECTION"""
387    
388     ## Get the lumi information for the run, just update the table, don't rebuild it every time
389     query = sqlquery % (self.RunNumber,self.LastLSParsed)
390     self.curs.execute(query)
391 grchrist 1.21 pastLSCol=-1
392 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():
393 grchrist 1.21
394 grchrist 1.22 self.B1Pres[ls]=b1pres
395     self.B2Pres[ls]=b2pres
396     self.B1Stab[ls]=b1stab
397     self.B2Stab[ls]=b2stab
398 grchrist 1.21 self.EBP[ls]= ebp
399     self.EBM[ls] = ebm
400     self.EEP[ls] = eep
401     self.EEM[ls] = eem
402     self.HBHEA[ls] = hbhea
403     self.HBHEB[ls] = hbheb
404     self.HBHEC[ls] = hbhec
405     self.HF[ls] = hf
406     self.RPC[ls] = rpc
407     self.DT0[ls] = dt0
408     self.DTP[ls] = dtp
409     self.DTM[ls] = dtm
410     self.CSCP[ls] = cscp
411     self.CSCM[ls] = cscm
412     self.TOB[ls] = tob
413     self.TIBTID[ls]= tibtid
414     self.TECP[ls] = tecp
415     self.TECM[ls] = tecm
416     self.BPIX[ls] = bpix
417     self.FPIX[ls] = fpix
418     self.ESP[ls] = esp
419     self.ESM[ls] = esm
420 grchrist 1.19
421 grchrist 1.21
422 grchrist 1.19 pastLSCol=ls
423     if ls>self.LastLSParsed:
424     self.LastLSParsed=ls
425    
426 grchrist 1.27
427 awoodard 1.49
428 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}
429 grchrist 1.21
430 grchrist 1.19 return self.MoreLumiInfo
431 awoodard 1.49
432    
433     def GetL1HLTseeds(self):
434     #print self.HLTSeed
435     L1HLTseeds={}
436     for HLTkey in self.HLTSeed.iterkeys():
437     #print HLTkey, self.HLTSeed[HLTkey]
438    
439     dummy=str(self.HLTSeed[HLTkey])
440    
441     if dummy.find(" OR ") == -1:
442     dummylist=[]
443     dummylist.append(dummy)
444     L1HLTseeds[StripVersion(HLTkey)]=dummylist
445     continue # Not an OR of seeds
446     seedList = dummy.split(" OR ")
447     #print seedList
448     L1HLTseeds[StripVersion(HLTkey)]=seedList
449     if len(seedList)==1:
450     print "error: zero length L1 seed"
451     continue #shouldn't get here
452     #print L1HLTseeds
453    
454     return L1HLTseeds
455 grchrist 1.19
456 grchrist 1.26 def GetDeadTimeBeamActive(self,LSRange):
457     sqlquery=""" select FRACTION
458     from
459     CMS_GT_MON.V_SCALERS_TCS_DEADTIME
460     where
461 grchrist 1.27 RUN_NUMBER=%s and
462     LUMI_SECTION in %s and
463     SCALER_NAME='DeadtimeBeamActive'"""
464    
465 grchrist 1.26
466 grchrist 1.27 LSRangeSTR = str(LSRange)
467     LSRangeSTR = LSRangeSTR.replace("[","(")
468     LSRangeSTR = LSRangeSTR.replace("]",")")
469    
470     query=sqlquery %(self.RunNumber,LSRangeSTR)
471     #print query
472     self.curs.execute(query)
473 grchrist 1.26
474 grchrist 1.27 deadtimeba_sum=0
475     ii=0
476     for deadtimebeamactive in self.curs.fetchall():
477 grchrist 1.37 try:
478     deadtimeba_sum=deadtimeba_sum+deadtimebeamactive[0]
479     except:
480     ##print "no dtba for run ",self.RunNumber, ", ls ",LSRange[ii], "using dt"
481     deadtimeba_sum=deadtimeba_sum+self.GetDeadTime(LSRange[ii])
482 grchrist 1.27 ii=ii+1
483     deadtimeba_av=deadtimeba_sum/len(LSRange)
484    
485     return deadtimeba_av
486    
487    
488    
489     def GetDeadTime(self,LS):
490     sqlquery=""" select FRACTION
491     from
492     CMS_GT_MON.V_SCALERS_TCS_DEADTIME
493     where
494     RUN_NUMBER=%s and
495     LUMI_SECTION=%s and
496     SCALER_NAME='Deadtime'"""
497    
498     query=sqlquery %(self.RunNumber,LS)
499     #print query
500 grchrist 1.26 self.curs.execute(query)
501 grchrist 1.35 dt=1.0
502 grchrist 1.27 for deadtime in self.curs.fetchall():
503     try:
504     dt=deadtime[0]
505 grchrist 1.34 #print "dt=",dt
506 grchrist 1.27 except:
507     print "no dt for run ",self.RunNumber, ", ls ",LS
508     dt=1.0
509    
510    
511     return dt
512 grchrist 1.19
513 amott 1.5 def GetAvLumiInfo(self,LSRange):
514     nLS=0;
515     AvInstLumi=0
516 amott 1.6 try:
517     StartLS = LSRange[0]
518     EndLS = LSRange[-1]
519 grchrist 1.26
520     #print "startls=",StartLS, "endls=",EndLS
521 amott 1.23 try: ## Cosmics won't have lumi info
522     maxlive = self.LiveLumiByLS[EndLS]
523     maxdelivered = self.DeliveredLumiByLS[EndLS]
524     for iterator in LSRange:
525     if self.LiveLumiByLS[iterator] > maxlive:
526     maxlive = self.LiveLumiByLS[iterator]
527     if self.DeliveredLumiByLS[iterator] > maxdelivered:
528     maxdelivered = self.DeliveredLumiByLS[iterator]
529     AvLiveLumi=maxlive-self.LiveLumiByLS[StartLS]
530     AvDeliveredLumi=maxdelivered-self.DeliveredLumiByLS[StartLS]
531     except:
532     AvLiveLumi=0
533     AvDeliveredLumi=0
534 abrinke1 1.15
535 abrinke1 1.14 if AvDeliveredLumi > 0:
536     AvDeadTime = 1 - AvLiveLumi/AvDeliveredLumi
537     else:
538     if AvLiveLumi > 0:
539     print "Live Lumi > 0 but Delivered <= 0: problem"
540     AvDeadTime = 0.0
541 abrinke1 1.17 PSCols=[]
542 amott 1.6 for ls in LSRange:
543     try:
544 amott 1.23 try:
545     AvInstLumi+=self.InstLumiByLS[ls]
546     except:
547     pass
548 abrinke1 1.17 PSCols.append(self.PSColumnByLS[ls])
549 amott 1.6 nLS+=1
550     except:
551     print "ERROR: Lumi section "+str(ls)+" not in bounds"
552     return [0.,0.,0.,0.,[]]
553 abrinke1 1.18 return [AvInstLumi/nLS,(1000.0/23.3)*AvLiveLumi/(EndLS-StartLS),(1000.0/23.3)*AvDeliveredLumi/(EndLS-StartLS), AvDeadTime,PSCols]
554 amott 1.6 except:
555 grchrist 1.26 if LSRange[0] == LSRange[-1]:
556 abrinke1 1.13 AvInstLumi = self.InstLumiByLS[StartLS]
557     try:
558     AvLiveLumi = self.LiveLumiByLS[StartLS]-self.LiveLumiByLS[StartLS-1]
559     AvDeliveredLumi = self.DeliveredLumiByLS[StartLS]-self.DeliveredLumiByLS[StartLS-1]
560 grchrist 1.26
561 abrinke1 1.13 except:
562 grchrist 1.27 try:
563     AvLiveLumi = self.LiveLumiByLS[StartLS+1]-self.LiveLumiByLS[StartLS]
564     AvDeliveredLumi = self.DeliveredLumiByLS[StartLS+1]-self.DeliveredLumiByLS[StartLS]
565     except:
566     print "missing live/delivered run ",self.RunNumber, "ls ",LSRange
567     AvLiveLumi = 0
568     AvDeliveredLumi = 0
569 abrinke1 1.14 if AvDeliveredLumi > 0:
570     AvDeadTime = 1 - AvLiveLumi/AvDeliveredLumi
571 grchrist 1.26
572 grchrist 1.27 elif AvLiveLumi > 0:
573     print "Live Lumi > 0 but Delivered <= 0: problem run ",self.RunNumber, " ls ",LSRange
574     AvDeadTime = 1.0
575 abrinke1 1.14 else:
576 grchrist 1.27 AvDeadTime=1.0
577 abrinke1 1.13 PSCols = [self.PSColumnByLS[StartLS]]
578 abrinke1 1.18 return [AvInstLumi,(1000.0/23.3)*AvLiveLumi,(1000.0/23.3)*AvDeliveredLumi,AvDeadTime,PSCols]
579 abrinke1 1.13 else:
580 abrinke1 1.18 return [0.,0.,0.,0.,[]]
581 amott 1.6
582 amott 1.1 def ParsePSColumnPage(self): ## this is now done automatically when we read the db
583     pass
584    
585     def GetL1NameIndexAssoc(self):
586     ## get the L1 algo names associated with each algo bit
587     AlgoNameQuery = """SELECT ALGO_INDEX, ALIAS FROM CMS_GT.L1T_MENU_ALGO_VIEW
588     WHERE MENU_IMPLEMENTATION IN (SELECT L1T_MENU_FK FROM CMS_GT.GT_SETUP WHERE ID='%s')
589     ORDER BY ALGO_INDEX""" % (self.GT_Key,)
590     self.curs.execute(AlgoNameQuery)
591     for index,name in self.curs.fetchall():
592 amott 1.4 self.L1IndexNameMap[name] = index
593 amott 1.1
594     def GetL1AlgoPrescales(self):
595     L1PrescalesQuery= """
596     SELECT
597     PRESCALE_FACTOR_ALGO_000,PRESCALE_FACTOR_ALGO_001,PRESCALE_FACTOR_ALGO_002,PRESCALE_FACTOR_ALGO_003,PRESCALE_FACTOR_ALGO_004,PRESCALE_FACTOR_ALGO_005,
598     PRESCALE_FACTOR_ALGO_006,PRESCALE_FACTOR_ALGO_007,PRESCALE_FACTOR_ALGO_008,PRESCALE_FACTOR_ALGO_009,PRESCALE_FACTOR_ALGO_010,PRESCALE_FACTOR_ALGO_011,
599     PRESCALE_FACTOR_ALGO_012,PRESCALE_FACTOR_ALGO_013,PRESCALE_FACTOR_ALGO_014,PRESCALE_FACTOR_ALGO_015,PRESCALE_FACTOR_ALGO_016,PRESCALE_FACTOR_ALGO_017,
600     PRESCALE_FACTOR_ALGO_018,PRESCALE_FACTOR_ALGO_019,PRESCALE_FACTOR_ALGO_020,PRESCALE_FACTOR_ALGO_021,PRESCALE_FACTOR_ALGO_022,PRESCALE_FACTOR_ALGO_023,
601     PRESCALE_FACTOR_ALGO_024,PRESCALE_FACTOR_ALGO_025,PRESCALE_FACTOR_ALGO_026,PRESCALE_FACTOR_ALGO_027,PRESCALE_FACTOR_ALGO_028,PRESCALE_FACTOR_ALGO_029,
602     PRESCALE_FACTOR_ALGO_030,PRESCALE_FACTOR_ALGO_031,PRESCALE_FACTOR_ALGO_032,PRESCALE_FACTOR_ALGO_033,PRESCALE_FACTOR_ALGO_034,PRESCALE_FACTOR_ALGO_035,
603     PRESCALE_FACTOR_ALGO_036,PRESCALE_FACTOR_ALGO_037,PRESCALE_FACTOR_ALGO_038,PRESCALE_FACTOR_ALGO_039,PRESCALE_FACTOR_ALGO_040,PRESCALE_FACTOR_ALGO_041,
604     PRESCALE_FACTOR_ALGO_042,PRESCALE_FACTOR_ALGO_043,PRESCALE_FACTOR_ALGO_044,PRESCALE_FACTOR_ALGO_045,PRESCALE_FACTOR_ALGO_046,PRESCALE_FACTOR_ALGO_047,
605     PRESCALE_FACTOR_ALGO_048,PRESCALE_FACTOR_ALGO_049,PRESCALE_FACTOR_ALGO_050,PRESCALE_FACTOR_ALGO_051,PRESCALE_FACTOR_ALGO_052,PRESCALE_FACTOR_ALGO_053,
606     PRESCALE_FACTOR_ALGO_054,PRESCALE_FACTOR_ALGO_055,PRESCALE_FACTOR_ALGO_056,PRESCALE_FACTOR_ALGO_057,PRESCALE_FACTOR_ALGO_058,PRESCALE_FACTOR_ALGO_059,
607     PRESCALE_FACTOR_ALGO_060,PRESCALE_FACTOR_ALGO_061,PRESCALE_FACTOR_ALGO_062,PRESCALE_FACTOR_ALGO_063,PRESCALE_FACTOR_ALGO_064,PRESCALE_FACTOR_ALGO_065,
608     PRESCALE_FACTOR_ALGO_066,PRESCALE_FACTOR_ALGO_067,PRESCALE_FACTOR_ALGO_068,PRESCALE_FACTOR_ALGO_069,PRESCALE_FACTOR_ALGO_070,PRESCALE_FACTOR_ALGO_071,
609     PRESCALE_FACTOR_ALGO_072,PRESCALE_FACTOR_ALGO_073,PRESCALE_FACTOR_ALGO_074,PRESCALE_FACTOR_ALGO_075,PRESCALE_FACTOR_ALGO_076,PRESCALE_FACTOR_ALGO_077,
610     PRESCALE_FACTOR_ALGO_078,PRESCALE_FACTOR_ALGO_079,PRESCALE_FACTOR_ALGO_080,PRESCALE_FACTOR_ALGO_081,PRESCALE_FACTOR_ALGO_082,PRESCALE_FACTOR_ALGO_083,
611     PRESCALE_FACTOR_ALGO_084,PRESCALE_FACTOR_ALGO_085,PRESCALE_FACTOR_ALGO_086,PRESCALE_FACTOR_ALGO_087,PRESCALE_FACTOR_ALGO_088,PRESCALE_FACTOR_ALGO_089,
612     PRESCALE_FACTOR_ALGO_090,PRESCALE_FACTOR_ALGO_091,PRESCALE_FACTOR_ALGO_092,PRESCALE_FACTOR_ALGO_093,PRESCALE_FACTOR_ALGO_094,PRESCALE_FACTOR_ALGO_095,
613     PRESCALE_FACTOR_ALGO_096,PRESCALE_FACTOR_ALGO_097,PRESCALE_FACTOR_ALGO_098,PRESCALE_FACTOR_ALGO_099,PRESCALE_FACTOR_ALGO_100,PRESCALE_FACTOR_ALGO_101,
614     PRESCALE_FACTOR_ALGO_102,PRESCALE_FACTOR_ALGO_103,PRESCALE_FACTOR_ALGO_104,PRESCALE_FACTOR_ALGO_105,PRESCALE_FACTOR_ALGO_106,PRESCALE_FACTOR_ALGO_107,
615     PRESCALE_FACTOR_ALGO_108,PRESCALE_FACTOR_ALGO_109,PRESCALE_FACTOR_ALGO_110,PRESCALE_FACTOR_ALGO_111,PRESCALE_FACTOR_ALGO_112,PRESCALE_FACTOR_ALGO_113,
616     PRESCALE_FACTOR_ALGO_114,PRESCALE_FACTOR_ALGO_115,PRESCALE_FACTOR_ALGO_116,PRESCALE_FACTOR_ALGO_117,PRESCALE_FACTOR_ALGO_118,PRESCALE_FACTOR_ALGO_119,
617     PRESCALE_FACTOR_ALGO_120,PRESCALE_FACTOR_ALGO_121,PRESCALE_FACTOR_ALGO_122,PRESCALE_FACTOR_ALGO_123,PRESCALE_FACTOR_ALGO_124,PRESCALE_FACTOR_ALGO_125,
618     PRESCALE_FACTOR_ALGO_126,PRESCALE_FACTOR_ALGO_127
619     FROM CMS_GT.GT_FDL_PRESCALE_FACTORS_ALGO A, CMS_GT.GT_RUN_SETTINGS_PRESC_VIEW B
620     WHERE A.ID=B.PRESCALE_FACTORS_ALGO_FK AND B.ID='%s'
621     """ % (self.GTRS_Key,)
622     self.curs.execute(L1PrescalesQuery)
623     ## This is pretty horrible, but this how you get them!!
624     tmp = self.curs.fetchall()
625     for ps in tmp[0]: #build the prescale table initially
626     self.L1PrescaleTable.append([ps])
627     for line in tmp[1:]: # now fill it
628     for ps,index in zip(line,range(len(line))):
629     self.L1PrescaleTable[index].append(ps)
630 amott 1.4 self.nAlgoBits=128
631 amott 1.1
632     def GetHLTIndex(self,name):
633     for i,n in enumerate(self.HLTList):
634     if n.find(name)!=-1:
635     return i
636 amott 1.2 #print name
637 amott 1.1 return -1
638    
639     def GetHLTPrescaleMatrix(self,cursor):
640     ##NOT WORKING 1/19/2012
641     return
642     SequencePathQuery ="""
643     SELECT F.SEQUENCENB,J.VALUE TRIGGERNAME
644     FROM CMS_HLT.CONFIGURATIONSERVICEASSOC A
645     , CMS_HLT.SERVICES B
646     , CMS_HLT.SERVICETEMPLATES C
647     , CMS_HLT.SUPERIDVECPARAMSETASSOC D
648     , CMS_HLT.VECPARAMETERSETS E
649     , CMS_HLT.SUPERIDPARAMSETASSOC F
650     , CMS_HLT.PARAMETERSETS G
651     , CMS_HLT.SUPERIDPARAMETERASSOC H
652     , CMS_HLT.PARAMETERS I
653     , CMS_HLT.STRINGPARAMVALUES J
654     WHERE A.CONFIGID= %d
655     AND A.SERVICEID=B.SUPERID
656     AND B.TEMPLATEID=C.SUPERID
657     AND C.NAME='PrescaleService'
658     AND B.SUPERID=D.SUPERID
659     AND D.VPSETID=E.SUPERID
660     AND E.NAME='prescaleTable'
661     AND D.VPSETID=F.SUPERID
662     AND F.PSETID=G.SUPERID
663     AND G.SUPERID=H.SUPERID
664     AND I.PARAMID=H.PARAMID
665     AND I.NAME='pathName'
666     AND J.PARAMID=H.PARAMID
667     ORDER BY F.SEQUENCENB
668     """ % (self.ConfigId,)
669    
670     cursor.execute(SequencePathQuery)
671     self.HLTSequenceMap = [0]*len(self.HLTList)
672     for seq,name in cursor.fetchall():
673     name = name.lstrip('"').rstrip('"')
674     try:
675     self.HLTSequenceMap[self.GetHLTIndex(name)]=seq
676     except:
677     print "couldn't find "+name
678    
679     for i,seq in enumerate(self.HLTSequenceMap):
680     if seq==0:
681     print self.HLTList[i]
682    
683     SequencePrescaleQuery="""
684     SELECT F.SEQUENCENB,J.SEQUENCENB,J.VALUE
685     FROM CMS_HLT.CONFIGURATIONSERVICEASSOC A
686     , CMS_HLT.SERVICES B
687     , CMS_HLT.SERVICETEMPLATES C
688     , CMS_HLT.SUPERIDVECPARAMSETASSOC D
689     , CMS_HLT.VECPARAMETERSETS E
690     , CMS_HLT.SUPERIDPARAMSETASSOC F
691     , CMS_HLT.PARAMETERSETS G
692     , CMS_HLT.SUPERIDPARAMETERASSOC H
693     , CMS_HLT.PARAMETERS I
694     , CMS_HLT.VUINT32PARAMVALUES J
695     WHERE A.CONFIGID=%d
696     AND A.SERVICEID=B.SUPERID
697     AND B.TEMPLATEID=C.SUPERID
698     AND C.NAME='PrescaleService'
699     AND B.SUPERID=D.SUPERID
700     AND D.VPSETID=E.SUPERID
701     AND E.NAME='prescaleTable'
702     AND D.VPSETID=F.SUPERID
703     AND F.PSETID=G.SUPERID
704     AND G.SUPERID=H.SUPERID
705     AND I.PARAMID=H.PARAMID
706     AND I.NAME='prescales'
707     AND J.PARAMID=H.PARAMID
708     ORDER BY F.SEQUENCENB,J.SEQUENCENB
709     """ % (self.ConfigId,)
710    
711 amott 1.2 #print self.HLTSequenceMap
712 amott 1.1 cursor.execute(SequencePrescaleQuery)
713     self.HLTPrescaleTable=[ [] ]*len(self.HLTList)
714     lastIndex=-1
715     lastSeq=-1
716     row = []
717     for seq,index,val in cursor.fetchall():
718     if lastIndex!=index-1:
719     self.HLTPrescaleTable[self.HLTSequenceMap.index(lastSeq)].append(row)
720     row=[]
721     lastSeq=seq
722     lastIndex=index
723     row.append(val)
724    
725     def GetHLTSeeds(self):
726     ## This is a rather delicate query, but it works!
727     ## Essentially get a list of paths associated with the config, then find the module of type HLTLevel1GTSeed associated with the path
728     ## Then find the parameter with field name L1SeedsLogicalExpression and look at the value
729     ##
730     ## NEED TO BE LOGGED IN AS CMS_HLT_R
731 amott 1.24 tmpcurs = ConnectDB('hlt')
732 amott 1.1 sqlquery ="""
733     SELECT I.NAME,A.VALUE
734     FROM
735     CMS_HLT.STRINGPARAMVALUES A,
736     CMS_HLT.PARAMETERS B,
737     CMS_HLT.SUPERIDPARAMETERASSOC C,
738     CMS_HLT.MODULETEMPLATES D,
739     CMS_HLT.MODULES E,
740     CMS_HLT.PATHMODULEASSOC F,
741     CMS_HLT.CONFIGURATIONPATHASSOC G,
742     CMS_HLT.CONFIGURATIONS H,
743     CMS_HLT.PATHS I
744     WHERE
745     A.PARAMID = C.PARAMID AND
746     B.PARAMID = C.PARAMID AND
747     B.NAME = 'L1SeedsLogicalExpression' AND
748     C.SUPERID = F.MODULEID AND
749     D.NAME = 'HLTLevel1GTSeed' AND
750     E.TEMPLATEID = D.SUPERID AND
751     F.MODULEID = E.SUPERID AND
752     F.PATHID=G.PATHID AND
753     I.PATHID=G.PATHID AND
754     G.CONFIGID=H.CONFIGID AND
755     H.CONFIGDESCRIPTOR='%s'
756 amott 1.2 ORDER BY A.VALUE
757 amott 1.1 """ % (self.HLT_Key,)
758     tmpcurs.execute(sqlquery)
759     for HLTPath,L1Seed in tmpcurs.fetchall():
760 amott 1.4 if not self.HLTSeed.has_key(HLTPath): ## this should protect us from L1_SingleMuOpen
761     self.HLTSeed[HLTPath] = L1Seed.lstrip('"').rstrip('"')
762 amott 1.1 #self.GetHLTPrescaleMatrix(tmpcurs)
763    
764     def ParseRunSetup(self):
765     #queries that need to be run only once per run
766     self.GetRunInfo()
767     self.GetL1NameIndexAssoc()
768     self.GetL1AlgoPrescales()
769     self.GetHLTSeeds()
770 amott 1.5 self.GetLumiInfo()
771 grchrist 1.21 self.LastLSParsed=-1
772     self.GetMoreLumiInfo()
773 grchrist 1.27 self.LastLsParsed=-1
774     #self.GetDeadTimeBeamActive()
775 amott 1.5
776     def UpdateRun(self,LSRange):
777     self.GetLumiInfo()
778     TriggerRates = self.GetHLTRates(LSRange)
779 abrinke1 1.10 #L1Prescales = self.CalculateAvL1Prescales(LSRange)
780     #TotalPrescales = self.CalculateTotalPrescales(TriggerRates,L1Prescales)
781     #UnprescaledRates = self.UnprescaleRates(TriggerRates,TotalPrescales)
782 amott 1.5
783 abrinke1 1.10 #return [UnprescaledRates, TotalPrescales, L1Prescales, TriggerRates]
784     return TriggerRates
785    
786 amott 1.23 def GetLSRange(self,StartLS, NLS,reqPhysics=True):
787 amott 1.5 """
788     returns an array of valid LumiSections
789     if NLS < 0, count backwards from StartLS
790     """
791 amott 1.1 self.GetLumiInfo()
792 amott 1.5 LS=[]
793     curLS=StartLS
794     step = NLS/abs(NLS)
795     NLS=abs(NLS)
796 grchrist 1.34
797 amott 1.5 while len(LS)<NLS:
798     if (curLS<0 and step<0) or (curLS>=self.LastLSParsed and step>0):
799     break
800 amott 1.30 if curLS>=0 and curLS<self.LastLSParsed-1:
801 amott 1.23 if (not self.Physics.has_key(curLS) or not self.Active.has_key(curLS)) and reqPhysics:
802 amott 1.5 break
803 grchrist 1.34
804 amott 1.23 if not reqPhysics or (self.Physics[curLS] and self.Active[curLS]):
805 amott 1.5 if step>0:
806     LS.append(curLS)
807     else:
808     LS.insert(0,curLS)
809     curLS += step
810     return LS
811    
812 amott 1.8 def GetLastLS(self,phys=False):
813 amott 1.7 self.GetLumiInfo()
814 grchrist 1.34
815 amott 1.7 try:
816 amott 1.8 if not phys:
817 grchrist 1.34 maxLS=-1
818     for ls, active in self.Active.iteritems():
819     if active and ls>maxLS:
820     maxLS=ls
821     if maxLS==-1:
822     return 0
823     else:
824     return maxLS
825    
826 amott 1.8 else:
827     maxLS=-1
828     for ls,phys in self.Physics.iteritems():
829     if phys and self.Active[ls] and ls > maxLS:
830     maxLS=ls
831     if maxLS==-1:
832     return 0
833     else:
834     return maxLS
835 amott 1.7 except:
836     return 0
837    
838 amott 1.5 def CalculateAvL1Prescales(self,LSRange):
839     AvgL1Prescales = [0]*self.nAlgoBits
840     for index in LSRange:
841 amott 1.1 psi = self.PSColumnByLS[index]
842     if not psi:
843 awoodard 1.50 #print "L1: Cannot figure out PSI for LS "+str(index)+" setting to 0"
844     psi = 0
845 amott 1.4 for algo in range(self.nAlgoBits):
846 amott 1.5 AvgL1Prescales[algo]+=self.L1PrescaleTable[algo][psi]
847     for i in range(len(AvgL1Prescales)):
848 amott 1.6 try:
849     AvgL1Prescales[i] = AvgL1Prescales[i]/len(LSRange)
850     except:
851     AvgL1Prescales[i] = AvgL1Prescales[i]
852 amott 1.5 return AvgL1Prescales
853    
854     def CalculateTotalPrescales(self,TriggerRates, L1Prescales):
855     AvgTotalPrescales={}
856     for hltName,v in TriggerRates.iteritems():
857 amott 1.4 if not self.HLTSeed.has_key(hltName):
858     continue
859 amott 1.1 hltPS=0
860 amott 1.4 if len(v)>0:
861     hltPS = v[0]
862     l1Index=-1
863     if self.L1IndexNameMap.has_key(self.HLTSeed[hltName]):
864     l1Index = self.L1IndexNameMap[self.HLTSeed[hltName]]
865    
866 amott 1.1 l1PS=0
867     if l1Index==-1:
868 amott 1.5 l1PS = self.UnwindORSeed(self.HLTSeed[hltName],L1Prescales)
869 amott 1.1 else:
870 amott 1.5 l1PS = L1Prescales[l1Index]
871     AvgTotalPrescales[hltName]=l1PS*hltPS
872     return AvgTotalPrescales
873 amott 1.1
874 amott 1.5 def UnwindORSeed(self,expression,L1Prescales):
875 amott 1.4 """
876     Figures out the effective prescale for the OR of several seeds
877     we take this to be the *LOWEST* prescale of the included seeds
878     """
879 amott 1.2 if expression.find(" OR ") == -1:
880     return -1 # Not an OR of seeds
881     seedList = expression.split(" OR ")
882     if len(seedList)==1:
883     return -1 # Not an OR of seeds, really shouldn't get here...
884     minPS = 99999999999
885     for seed in seedList:
886 amott 1.4 if not self.L1IndexNameMap.has_key(seed):
887     continue
888 amott 1.5 ps = L1Prescales[self.L1IndexNameMap[seed]]
889 amott 1.4 if ps:
890     minPS = min(ps,minPS)
891 amott 1.2 if minPS==99999999999:
892     return 0
893     else:
894     return minPS
895    
896 amott 1.5 def UnprescaleRates(self,TriggerRates,TotalPrescales):
897     UnprescaledRates = {}
898     for hltName,v in TriggerRates.iteritems():
899     if TotalPrescales.has_key(hltName):
900     ps = TotalPrescales[hltName]
901 amott 1.4 if ps:
902 amott 1.5 UnprescaledRates[hltName] = v[1]*ps
903 amott 1.4 else:
904 amott 1.5 UnprescaledRates[hltName] = v[1]
905 amott 1.4 else:
906 amott 1.5 UnprescaledRates[hltName] = v[1]
907     return UnprescaledRates
908 abrinke1 1.13
909 amott 1.11 def GetTotalL1Rates(self):
910 awoodard 1.49 query = "SELECT RUNNUMBER, LUMISEGMENTNR, L1ASPHYSICS/23.3 FROM CMS_WBM.LEVEL1_TRIGGER_CONDITIONS WHERE RUNNUMBER=%s" % self.RunNumber
911 amott 1.11 self.curs.execute(query)
912     L1Rate = {}
913     for LS,rate in self.curs.fetchall():
914 awoodard 1.49 psi = self.PSColumnByLS.get(LS,0)
915 amott 1.11 lumi = self.InstLumiByLS.get(LS,0)
916     L1Rate[LS] = [rate,psi,lumi]
917     return L1Rate
918 awoodard 1.49
919     def GetL1RatesALL(self,LSRange):
920    
921    
922     #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"
923    
924     ##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)"
925    
926     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"
927    
928     LSRangeSTR = str(LSRange)
929     LSRangeSTR = LSRangeSTR.replace("[","(")
930     LSRangeSTR = LSRangeSTR.replace("]",")")
931    
932     query= sqlquery %(self.RunNumber,LSRangeSTR)
933     self.curs.execute(query)
934     L1RateAll=self.curs.fetchall()
935     L1RatesBits={}
936     ###initialize dict of L1 bits
937     for L1seed in sorted(self.L1IndexNameMap.iterkeys()):
938     L1RatesBits[self.L1IndexNameMap[L1seed]]=0
939    
940     ###sum dict of L1 bits
941     for line in L1RateAll:
942     #if line[3] in self.L1IndexNameMap: ##do not fill if empty L1 key
943     try:
944     L1RatesBits[line[3]]=line[2]+L1RatesBits[line[3]]
945     except:
946     pass
947     #print "not filling bit",line[3]
948     ###divide by number of LS
949     for name in self.L1IndexNameMap.iterkeys():
950     L1RatesBits[self.L1IndexNameMap[name]]=L1RatesBits[self.L1IndexNameMap[name]]/len(LSRange)
951    
952     ###total L1 PS table
953     L1PSdict={}
954     counter=0
955     for line in self.L1PrescaleTable:
956     L1PSdict[counter]=line
957     counter=counter+1
958     for LS in LSRange:
959     self.PSColumnByLS[LS]
960    
961     ###av ps dict
962     L1PSbits={}
963     for bit in L1PSdict.iterkeys():
964     L1PSbits[bit]=0
965     for bit in L1PSdict.iterkeys():
966     for LS in LSRange:
967     L1PSbits[bit]=L1PSbits[bit]+L1PSdict[bit][self.PSColumnByLS[LS]]
968     for bit in L1PSdict.iterkeys():
969     L1PSbits[bit]=L1PSbits[bit]/len(LSRange)
970    
971     ###convert dict of L1 bits to dict of L1 names
972     L1RatesNames={}
973     for name in self.L1IndexNameMap.iterkeys():
974     dummy=[]
975     dummy.append(L1PSbits[self.L1IndexNameMap[name]])
976     dummy.append(L1PSbits[self.L1IndexNameMap[name]])
977     dummy.append(L1RatesBits[self.L1IndexNameMap[name]])
978     dummy.append(L1RatesBits[self.L1IndexNameMap[name]]*L1PSbits[self.L1IndexNameMap[name]])
979     L1RatesNames[name+'_v1']=dummy
980    
981     return L1RatesNames
982    
983    
984    
985     def GetL1Rates(self,LSRange):
986    
987     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"
988    
989     LSRangeSTR = str(LSRange)
990     LSRangeSTR = LSRangeSTR.replace("[","(")
991     LSRangeSTR = LSRangeSTR.replace("]",")")
992    
993     query=sqlquery %(self.RunNumber, LSRangeSTR)
994    
995     #print query
996     self.curs.execute(query)
997    
998     L1Rate=self.curs.fetchall()
999    
1000     for line in L1Rate:
1001     #print line
1002     pass
1003    
1004    
1005    
1006     return L1Rate
1007 abrinke1 1.13
1008 amott 1.1 def AssemblePrescaleValues(self): ##Depends on output from ParseLumiPage and ParseTriggerModePage
1009     return ## WHAT DOES THIS FUNCTION DO???
1010     MissingName = "Nemo"
1011     for key in self.L1TriggerMode:
1012     self.L1Prescale[key] = {}
1013     for n in range(min(self.LSByLS),max(self.LSByLS)+1): #"range()" excludes the last element
1014     try:
1015     self.L1Prescale[key][n] = self.L1TriggerMode[key][self.PSColumnByLS[n]]
1016     except:
1017     if not key == MissingName:
1018     self.MissingPrescale.append(key)
1019     MissingName = key
1020     if not n < 2:
1021     print "LS "+str(n)+" of key "+str(key)+" is missing from the LumiSections page"
1022    
1023     for key in self.HLTTriggerMode:
1024     self.HLTPrescale[key] = {}
1025     for n in range(min(self.LSByLS),max(self.LSByLS)+1): #"range" excludes the last element
1026     try:
1027     self.HLTPrescale[key][n] = self.HLTTriggerMode[key][self.PSColumnByLS[n]]
1028     except:
1029     if not key == MissingName:
1030     self.MissingPrescale.append(key)
1031     MissingName = key
1032     if not n < 2:
1033     print "LS "+str(n)+" of key "+str(key)+" is missing from the LumiSections page"
1034    
1035     self.PrescaleValues = [self.L1Prescale,self.HLTPrescale,self.MissingPrescale]
1036     return self.PrescaleValues
1037    
1038     def ComputeTotalPrescales(self,StartLS,EndLS):
1039     return ## WHAT DOES THIS FUNCTION DO??
1040     IdealHLTPrescale = {}
1041     IdealPrescale = {}
1042     L1_zero = {}
1043     HLT_zero = {}
1044     n1 = {}
1045     n2 = {}
1046     L1 = {}
1047     L2 = {}
1048     H1 = {}
1049     H2 = {}
1050     InitialColumnIndex = self.PSColumnByLS[int(StartLS)]
1051    
1052     for key in self.HLTTriggerMode:
1053     try:
1054     DoesThisPathHaveAValidL1SeedWithPrescale = self.L1Prescale[self.HLTSeed[key]][StartLS]
1055     except:
1056     L1_zero[key] = True
1057     HLT_zero[key] = False
1058     continue
1059    
1060     IdealHLTPrescale[key] = 0.0
1061     IdealPrescale[key] = 0.0
1062     n1[key] = 0
1063     L1_zero[key] = False
1064     HLT_zero[key] = False
1065    
1066     for LSIterator in range(StartLS,EndLS+1): #"range" excludes the last element
1067     if self.L1Prescale[self.HLTSeed[key]][LSIterator] > 0 and self.HLTPrescale[key][LSIterator] > 0:
1068     IdealPrescale[key]+=1.0/(self.L1Prescale[self.HLTSeed[key]][LSIterator]*self.HLTPrescale[key][LSIterator])
1069     else:
1070     IdealPrescale[key]+=1.0 ##To prevent a divide by 0 error later
1071     if self.L1Prescale[self.HLTSeed[key]][LSIterator] < 0.1:
1072     L1_zero[key] = True
1073     if self.HLTPrescale[key][LSIterator] < 0.1:
1074     HLT_zero[key] = True
1075     if self.PSColumnByLS[LSIterator] == InitialColumnIndex:
1076     n1[key]+=1
1077    
1078     if L1_zero[key] == True or HLT_zero[key] == True:
1079     continue
1080    
1081     IdealPrescale[key] = (EndLS + 1 - StartLS)/IdealPrescale[key]
1082    
1083     n2[key] = float(EndLS + 1 - StartLS - n1[key])
1084     L1[key] = float(self.L1Prescale[self.HLTSeed[key]][StartLS])
1085     L2[key] = float(self.L1Prescale[self.HLTSeed[key]][EndLS])
1086     H1[key] = float(self.HLTPrescale[key][StartLS])
1087     H2[key] = float(self.HLTPrescale[key][EndLS])
1088    
1089     IdealHLTPrescale[key] = ((n1[key]/L1[key])+(n2[key]/L2[key]))/((n1[key]/(L1[key]*H1[key]))+(n2[key]/(L2[key]*H2[key])))
1090    
1091     self.TotalPSInfo = [L1_zero,HLT_zero,IdealPrescale,IdealHLTPrescale,n1,n2,L1,L2,H1,H2]
1092    
1093     return self.TotalPSInfo
1094    
1095    
1096     def CorrectForPrescaleChange(self,StartLS,EndLS):
1097     [L1_zero,HLT_zero,IdealPrescale,IdealHLTPrescale,n1,n2,L1,L2,H1,H2] = self.TotalPSInfo
1098     xLS = {}
1099     RealPrescale = {}
1100    
1101     for key in self.HLTTriggerMode:
1102     if L1_zero[key] == True or HLT_zero[key] == True:
1103     continue
1104     [TriggerRate,L1Pass,PSPass,PS,Seed,StartLS,EndLS] = self.TriggerRates[key]
1105     if PS > 0.95 * IdealHLTPrescale[key] and PS < 1.05 * IdealHLTPrescale[key]:
1106     RealPrescale[key] = IdealPrescale[key]
1107     continue
1108    
1109     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
1110     H2[key] = float(self.HLTPrescale[key][EndLS+1])
1111     L2[key] = float(self.L1Prescale[self.HLTSeed[key]][EndLS+1])
1112     if H1[key] == H2[key] and L1[key] == L2[key] and not StartLS < 3:
1113     H1[key] = float(self.HLTPrescale[key][StartLS-1])
1114     L1[key] = float(self.L1Prescale[self.HLTSeed[key]][StartLS-1])
1115     if H1[key] == H2[key]:
1116     xLS[key] = 0
1117     else:
1118     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])))
1119    
1120     if xLS[key] > 1:
1121     xLS[key] = 1
1122     if xLS[key] < -1:
1123     xLS[key] = -1
1124     RealPrescale[key] = (n1[key] + n2[key])/(((n1[key] - xLS[key])/(H1[key]*L1[key]))+(n2[key]+xLS[key])/(H2[key]*L2[key]))
1125    
1126     self.CorrectedPSInfo = [RealPrescale,xLS,L1,L2,H1,H2]
1127    
1128     return self.CorrectedPSInfo
1129    
1130 amott 1.4 def GetAvLumiPerRange(self, NMergeLumis=10):
1131     """
1132 amott 1.5 This function returns a per-LS table of the average lumi of the previous NMergeLumis LS
1133 amott 1.4 """
1134 amott 1.5 AvLumiRange = []
1135     AvLumiTable = {}
1136     for ls,lumi in self.InstLumiByLS.iteritems():
1137     try:
1138     AvLumiRange.append(int(lumi))
1139     except:
1140     continue
1141     if len(AvLumiRange) == NMergeLumis:
1142     AvLumiRange = AvLumiRange[1:]
1143     AvLumiTable[ls] = sum(AvLumiRange)/NMergeLumis
1144 amott 1.4 return AvLumiTable
1145    
1146 amott 1.9 def GetTriggerVersion(self,triggerName):
1147     for key in self.HLTSeed.iterkeys():
1148     if StripVersion(key)==triggerName:
1149     return key
1150     return ""
1151    
1152 amott 1.1 def Save(self, fileName):
1153     dir = os.path.dirname(fileName)
1154     if not os.path.exists(dir):
1155     os.makedirs(dir)
1156     pickle.dump( self, open( fileName, 'w' ) )
1157    
1158     def Load(self, fileName):
1159     self = pickle.load( open( fileName ) )
1160 amott 1.5
1161 amott 1.24 def ConnectDB(user='trg'):
1162 grchrist 1.34 try:
1163     host = os.uname()[1]
1164     offline = 1 if host.startswith('lxplus') else 0
1165     except:
1166     print "Please setup database parsing:\nsource set.sh"
1167 grchrist 1.32 ##print offline
1168 amott 1.30 trg = ['~centraltspro/secure/cms_trg_r.txt','~/secure/cms_trg_r.txt']
1169     hlt = ['~hltpro/secure/cms_hlt_r.txt','~/secure/cms_hlt_r.txt']
1170    
1171 amott 1.24 if user == 'trg':
1172 amott 1.30 cmd = 'cat %s' % (trg[offline],)
1173 amott 1.24 elif user == 'hlt':
1174 amott 1.30 cmd='cat %s' % (hlt[offline],)
1175    
1176     try:
1177     line=os.popen(cmd).readlines()
1178     except:
1179     print "ERROR Getting the database password!"
1180     print "They should be in %s and %s" % (trg[offline],hlt[offline],)
1181     print "You may need to copy them from the online machines"
1182     sys.exit(0)
1183 amott 1.5 magic = line[0].rstrip("\n\r")
1184 amott 1.24 connect = 'cms_%s_r/%s@cms_omds_lb' % (user,magic,)
1185 amott 1.5 orcl = cx_Oracle.connect(connect)
1186 amott 1.24 return orcl.cursor()
1187 grchrist 1.42
1188 amott 1.24
1189 grchrist 1.34 def GetLatestRunNumber(runNo=9999999,newRun=False):
1190 grchrist 1.32
1191 amott 1.24 curs = ConnectDB()
1192 grchrist 1.32
1193 amott 1.23 if runNo==9999999:
1194 grchrist 1.28
1195     ##
1196     ##SELECT MAX(RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL
1197     ##SELECT MAX(RUNNUMBER) CMS_WBM.RUNSUMMARY WHERE TRIGGERS>0
1198     ## RunNoQuery="""
1199     ## SELECT MAX(A.RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL A, CMS_WBM.RUNSUMMARY B WHERE A.RUNNUMBER=B.RUNNUMBER AND B.TRIGGERS>0
1200     ## """
1201    
1202     RunNoQuery="""SELECT MAX(A.RUNNUMBER)
1203     FROM CMS_RUNINFO.RUNNUMBERTBL A, CMS_RUNTIME_LOGGER.LUMI_SECTIONS B WHERE B.RUNNUMBER=A.RUNNUMBER AND B.LUMISECTION > 0
1204 amott 1.23 """
1205 grchrist 1.31 try:
1206     curs.execute(RunNoQuery)
1207     r, = curs.fetchone()
1208 grchrist 1.34 ##print "\nr=",r
1209 grchrist 1.31 except:
1210     print "not able to get run"
1211 grchrist 1.28
1212 grchrist 1.34 ## RunNoQuery="""SELECT MAX(RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL"""
1213 grchrist 1.33 ## try:
1214     ## curs.execute(RunNoQuery)
1215     ## ra, = curs.fetchone()
1216     ## print "ra=",ra
1217     ## except:
1218     ## print "not able to get ra"
1219    
1220    
1221 grchrist 1.42 ## RunNoQuery="""SELECT TIER0_TRANSFER FROM CMS_WBM.RUNSUMMARY WHERE TRIGGERS>0 AND RUNUMBER=MAX(RUNNUMBER)"""
1222 grchrist 1.33 ## try:
1223     ## curs.execute(RunNoQuery)
1224     ## rb, = curs.fetchone()
1225     ## print "rb=",rb
1226     ## except:
1227     ## print "not able to get rb"
1228    
1229     ## RunNoQuery="""SELECT MAX(RUNNUMBER) FROM CMS_RUNTIME_LOGGER.LUMI_SECTIONS WHERE LUMISECTION > 0 """
1230     ## try:
1231     ## curs.execute(RunNoQuery)
1232     ## rc, = curs.fetchone()
1233     ## print "rc=",rc
1234     ## except:
1235     ## print "not able to get rc"
1236 grchrist 1.31
1237 amott 1.23 else:
1238     r = runNo
1239 grchrist 1.32 isCol=0
1240 grchrist 1.29
1241 amott 1.5 TrigModeQuery = """
1242     SELECT TRIGGERMODE FROM CMS_WBM.RUNSUMMARY WHERE RUNNUMBER = %d
1243     """ % r
1244     curs.execute(TrigModeQuery)
1245 grchrist 1.29 try:
1246     trigm, = curs.fetchone()
1247     except:
1248 grchrist 1.32 print "unable to get trigm from query for run ",r
1249 amott 1.5 isCol=0
1250 grchrist 1.31 isGood=1
1251 grchrist 1.42
1252 grchrist 1.43
1253     try:
1254     if trigm is None:
1255     isGood=0
1256     elif trigm.find('l1_hlt_collisions')!=-1:
1257     isCol=1
1258     except:
1259     isGood=0
1260    
1261 grchrist 1.42 Tier0xferQuery = """
1262     SELECT TIER0_TRANSFER TIER0 FROM CMS_WBM.RUNSUMMARY WHERE RUNNUMBER = %d
1263     """ % r
1264     curs.execute(Tier0xferQuery)
1265 awoodard 1.49 tier0=1
1266 grchrist 1.42 try:
1267     tier0, = curs.fetchone()
1268 grchrist 1.43
1269 grchrist 1.42 except:
1270     print "unable to get tier0 from query for run ",r
1271    
1272 grchrist 1.43 if isCol and not tier0:
1273     #write(bcolors.FAIL)
1274     print "WARNING tier0 transfer is off"
1275     #write(bcolors.ENDC+"\n")
1276     elif not tier0:
1277     #write(bcolors.WARINING)
1278     print "Please check if tier0 transfer is supposed to be off"
1279     #write(bcolors.ENDC+"\n")
1280 grchrist 1.42
1281 grchrist 1.43
1282    
1283 grchrist 1.31 return (r,isCol,isGood,)
1284 amott 1.5
1285     def ClosestIndex(value,table):
1286     diff = 999999999;
1287     index = 0
1288     for i,thisVal in table.iteritems():
1289     if abs(thisVal-value)<diff:
1290     diff = abs(thisVal-value)
1291     index =i
1292     return index
1293    
1294    
1295     def StripVersion(name):
1296     if re.match('.*_v[0-9]+',name):
1297     name = name[:name.rfind('_')]
1298     return name