ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseParser.py
Revision: 1.43
Committed: Tue Jul 17 15:12:27 2012 UTC (12 years, 9 months ago) by grchrist
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-01-06, V00-01-05, V00-01-04, V00-01-03, V00-01-02, V00-01-01, V00-00-34, V00-00-33
Changes since 1.42: +24 -10 lines
Log Message:
log monitoring, tier0 warnings, correct prompt stream A rate

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