ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseParser.py
Revision: 1.42
Committed: Wed Jun 20 11:18:10 2012 UTC (12 years, 10 months ago) by grchrist
Content type: text/x-python
Branch: MAIN
CVS Tags: MenuAnalyzer_V00-00-02, MenuAnalyzer_V00-00-01, MenuAnalyzer_V1
Changes since 1.41: +14 -1 lines
Log Message:
added tier 0 transfer message to DatabaseParser.py

File Contents

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