ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseParser.py
Revision: 1.10
Committed: Wed Feb 15 20:00:15 2012 UTC (13 years, 2 months ago) by abrinke1
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-00-04
Changes since 1.9: +74 -12 lines
Log Message:
Slight change uses accurate ps info

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     from sets import Set
7    
8 amott 1.1
9     class DatabaseParser:
10    
11     def __init__(self):
12     cmd='cat ~centraltspro/secure/cms_trg_r.txt'
13     line=os.popen(cmd).readlines()
14     magic = line[0].rstrip("\n\r")
15     connect= 'cms_trg_r/' + magic + '@cms_omds_lb'
16     # connect to the DB
17     self.orcl = cx_Oracle.connect(connect)
18     self.curs = self.orcl.cursor()
19    
20     ##-- Defined in ParsePage1 --##
21     self.RunNumber = 0
22    
23     ##-- Defined in ParseRunPage --##
24     self.Date=''
25     self.L1_HLT_Key=''
26     self.HLT_Key=''
27     self.GTRS_Key=''
28     self.TSC_Key=''
29     self.GT_Key=''
30     self.ConfigId=0
31    
32     ##-- Defined in ParseHLTSummaryPage --##
33 amott 1.5 self.HLTRatesByLS = {}
34     self.HLTPSByLS = {}
35 amott 1.1
36 amott 1.4 self.nAlgoBits=0
37 amott 1.1 self.L1PrescaleTable=[]
38     self.AvgL1Prescales=[] ## contains the average L1 prescales for the current LS range range
39     self.HLTList=[]
40 amott 1.4 self.AvgTotalPrescales={}
41 amott 1.1 self.HLTPrescaleTable=[] ## can't fill this yet
42 amott 1.4 self.UnprescaledRates={}
43     self.PrescaledRates={}
44 amott 1.1 ##-- Defined in ParseLumiPage --##
45     self.LastLSParsed=-1
46 amott 1.4 self.InstLumiByLS = {}
47     self.DeliveredLumiByLS = {}
48     self.LiveLumiByLS = {}
49     self.PSColumnByLS = {}
50 amott 1.1 self.AvInstLumi = 0
51     self.AvDeliveredLumi = 0
52     self.AvLiveLumi = 0
53 amott 1.5 self.AvDeadTime = 0
54 amott 1.4 self.LumiInfo = {} ##Returns
55     self.DeadTime = {}
56     self.Physics = {}
57 amott 1.5 self.Active = {}
58    
59 amott 1.1 ##-- Defined in ParsePSColumnPage (not currently used) --##
60     self.PSColumnChanges=[] ##Returns
61    
62     ##-- Defined in ParseTriggerModePage --##
63 amott 1.2 self.L1TriggerMode={} ##
64     self.HLTTriggerMode={} ##
65 amott 1.4 self.HLTSeed={}
66 amott 1.1 self.HLTSequenceMap=[]
67     self.TriggerInfo = [] ##Returns
68    
69     ##-- Defined in AssemblePrescaleValues --##
70 amott 1.4 self.L1Prescale={}
71     self.L1IndexNameMap={}
72 amott 1.1 self.HLTPrescale=[]
73     self.MissingPrescale=[]
74     self.PrescaleValues=[] ##Returns
75    
76     ##-- Defined in ComputeTotalPrescales --##
77 amott 1.2 self.TotalPSInfo = [] ##Returns # #collection
78 amott 1.1
79     ##-- Defined in CorrectForPrescaleChange --##
80     self.CorrectedPSInfo = [] ##Returns
81    
82     ##-- In the current Parser.py philosophy, only RunNumber is set globally
83     ## - LS range is set from the outside for each individual function
84     #self.FirstLS = -1
85     #self.LastLS = -1
86    
87     def GetRunInfo(self):
88     ## This query gets the L1_HLT Key (A), the associated HLT Key (B) and the Config number for that key (C)
89     KeyQuery = """
90     SELECT A.TRIGGERMODE, B.HLT_KEY, B.GT_RS_KEY, B.TSC_KEY, C.CONFIGID, D.GT_KEY FROM
91     CMS_WBM.RUNSUMMARY A, CMS_L1_HLT.L1_HLT_CONF B, CMS_HLT.CONFIGURATIONS C, CMS_TRG_L1_CONF.TRIGGERSUP_CONF D WHERE
92     B.ID = A.TRIGGERMODE AND C.CONFIGDESCRIPTOR = B.HLT_KEY AND D.TS_Key = B.TSC_Key AND A.RUNNUMBER=%d
93     """ % (self.RunNumber,)
94     self.curs.execute(KeyQuery)
95     self.L1_HLT_Key,self.HLT_Key,self.GTRS_Key,self.TSC_Key,self.ConfigId,self.GT_Key = self.curs.fetchone()
96    
97     def UpdateRateTable(self): # lets not rebuild the rate table every time, rather just append new LSs
98     pass
99    
100 amott 1.5 def GetHLTRates(self,LSRange):
101 amott 1.1 sqlquery = """SELECT SUM(A.L1PASS),SUM(A.PSPASS),SUM(A.PACCEPT)
102     ,SUM(A.PEXCEPT),(SELECT L.NAME FROM CMS_HLT.PATHS L WHERE L.PATHID=A.PATHID) PATHNAME
103     FROM CMS_RUNINFO.HLT_SUPERVISOR_TRIGGERPATHS A WHERE RUNNUMBER=%s AND A.LSNUMBER>=%d AND A.LSNUMBER<%d
104     GROUP BY A.LSNUMBER,A.PATHID"""
105    
106 amott 1.6 try:
107     StartLS = LSRange[0]
108     EndLS = LSRange[-1]
109     except:
110     StartLS = 0
111     EndLS = 9999
112    
113 abrinke1 1.10 AvgL1Prescales = [0]*self.nAlgoBits
114    
115 amott 1.5 #print "Getting HLT Rates for LS from %d to %d" % (LSRange[0],LSRange[-1],)
116 amott 1.6 query = sqlquery % (self.RunNumber,StartLS,EndLS,)
117 amott 1.1 self.curs.execute(query)
118 amott 1.5
119     TriggerRates = {}
120 amott 1.1 for L1Pass,PSPass,HLTPass,HLTExcept,name in self.curs.fetchall():
121 abrinke1 1.10 if not self.HLTSeed.has_key(name):
122     continue
123    
124 amott 1.1 rate = HLTPass/23.3
125 abrinke1 1.10 hltps = 0
126 amott 1.1 if PSPass:
127 abrinke1 1.10 hltps = float(L1Pass)/PSPass
128 amott 1.6 if not TriggerRates.has_key(name):
129 abrinke1 1.10 try:
130     psi = self.PSColumnByLS[LSRange[0]]
131     #except:
132     #psi = self.PSColumnByLS[1]
133     #if not psi:
134     except:
135     print "Cannot figure out PSI for LS "+str(StartLS)+" setting to 0"
136     print "The value of LSRange[0] is:"
137     print str(LSRange[0])
138     psi = 0
139    
140     if self.L1IndexNameMap.has_key(self.HLTSeed[name]):
141     l1ps = self.L1PrescaleTable[self.L1IndexNameMap[self.HLTSeed[name]]][psi]
142     else:
143     AvL1Prescales = self.CalculateAvL1Prescales([LSRange[0]])
144     l1ps = self.UnwindORSeed(self.HLTSeed[name],AvL1Prescales)
145     #l1ps = 1
146     #print "L1IndexNameMap has no key for "+str(self.HLTSeed[name])
147    
148     ps = l1ps*hltps
149     if ps < 1:
150     #print "Oops! somehow ps for "+str(name)+" = "+str(ps)+", where L1 PS = "+str(l1ps)+" and HLT PS = "+str(hltps)
151     ps = 1
152     psrate = ps*rate
153     TriggerRates[name]= [ps,rate,psrate,1]
154 amott 1.6 else:
155 abrinke1 1.10 [ops,orate,opsrate,on] = TriggerRates[name]
156     try:
157     psi = self.PSColumnByLS[LSRange[on]]
158     #except:
159     #psi = self.PSColumnByLS[1]
160     #if not psi:
161     except:
162     print "Cannot figure out PSI for index"+str(on)+" setting to 0"
163     print "The value of LSRange[on] is:"
164     print str(LSRange[on])
165     psi = 0
166    
167     if self.L1IndexNameMap.has_key(self.HLTSeed[name]):
168     l1ps = self.L1PrescaleTable[self.L1IndexNameMap[self.HLTSeed[name]]][psi]
169     else:
170     AvL1Prescales = self.CalculateAvL1Prescales([LSRange[on]])
171     l1ps = self.UnwindORSeed(self.HLTSeed[name],AvL1Prescales)
172     #l1ps = 1
173     #print "L1IndexNameMap has no key for "+str(self.HLTSeed[name])
174    
175     ps = l1ps*hltps
176     if ps < 1:
177     ##print "Oops! somehow ps for "+str(name)+" = "+str(ps)+", where L1 PS = "+str(l1ps)+" and HLT PS = "+str(hltps)
178     ps = 1
179     psrate = ps*rate
180     TriggerRates[name]= [ops+ps,orate+rate,opsrate+psrate,on+1]
181    
182 amott 1.6 for name,val in TriggerRates.iteritems():
183 abrinke1 1.10 [ps,rate,psrate,n] = val
184     avps = ps/n
185     try:
186     ps = psrate/rate
187     except:
188     #print "Rate = 0 for "+str(name)+", setting ps to 1"
189     ps = 1
190     TriggerRates[name] = [avps,ps,rate/n,psrate/n]
191    
192 amott 1.5 return TriggerRates
193 amott 1.1
194 amott 1.5 def GetTriggerRatesByLS(self,triggerName):
195     sqlquery = """SELECT A.LSNUMBER, A.PACCEPT
196 amott 1.3 FROM CMS_RUNINFO.HLT_SUPERVISOR_TRIGGERPATHS A, CMS_HLT.PATHS B
197 amott 1.5 WHERE RUNNUMBER=%s AND B.NAME = \'%s\' AND A.PATHID = B.PATHID
198     GROUP BY A.LSNUMBER,A.PATHID""" % (self.RunNumber,triggerName,)
199 amott 1.3
200     self.curs.execute(sqlquery)
201 amott 1.5 r={}
202     for ls,accept in self.curs.fetchall():
203     r[ls] = accept/23.3
204     return r
205    
206     def GetAllTriggerRatesByLS(self):
207     for hltName in self.HLTSeed:
208     self.HLTRatesByLS[hltName] = self.GetTriggerRatesByLS(hltName)
209 amott 1.3
210 amott 1.1 def GetLumiInfo(self):
211 amott 1.5 sqlquery="""SELECT RUNNUMBER,LUMISECTION,PRESCALE_INDEX,INSTLUMI,LIVELUMI,DELIVLUMI,DEADTIME
212     ,DCSSTATUS,PHYSICS_FLAG,CMS_ACTIVE
213 amott 1.1 FROM CMS_RUNTIME_LOGGER.LUMI_SECTIONS A,CMS_GT_MON.LUMI_SECTIONS B WHERE A.RUNNUMBER=%s
214     AND B.RUN_NUMBER(+)=A.RUNNUMBER AND B.LUMI_SECTION(+)=A.LUMISECTION AND A.LUMISECTION > %d
215     ORDER BY A.RUNNUMBER,A.LUMISECTION"""
216    
217     ## Get the lumi information for the run, just update the table, don't rebuild it every time
218     query = sqlquery % (self.RunNumber,self.LastLSParsed)
219     self.curs.execute(query)
220     pastLSCol=-1
221 amott 1.5 for run,ls,psi,inst,live,dlive,dt,dcs,phys,active in self.curs.fetchall():
222 amott 1.4 self.PSColumnByLS[ls]=psi
223     self.InstLumiByLS[ls]=inst
224     self.LiveLumiByLS[ls]=live
225     self.DeliveredLumiByLS[ls]=dlive
226     self.DeadTime[ls]=dt
227     self.Physics[ls]=phys
228 amott 1.5 self.Active[ls]=active
229 amott 1.1 if pastLSCol!=-1 and ls!=pastLSCol:
230     self.PSColumnChanges.append([ls,psi])
231     pastLSCol=ls
232     if ls>self.LastLSParsed:
233     self.LastLSParsed=ls
234 amott 1.5 self.LumiInfo = [self.PSColumnByLS, self.InstLumiByLS, self.DeliveredLumiByLS, self.LiveLumiByLS, self.DeadTime]
235 amott 1.1
236 amott 1.5 def GetAvLumiInfo(self,LSRange):
237     nLS=0;
238     AvInstLumi=0
239 amott 1.6 try:
240     StartLS = LSRange[0]
241     EndLS = LSRange[-1]
242     AvLiveLumi=self.LiveLumiByLS[EndLS]-self.LiveLumiByLS[StartLS]
243     AvDeliveredLumi=self.DeliveredLumiByLS[EndLS]-self.DeliveredLumiByLS[StartLS]
244     AvDeadTime=AvDeliveredLumi/AvLiveLumi * 100
245     PSCols=Set()
246     for ls in LSRange:
247     try:
248     AvInstLumi+=self.InstLumiByLS[ls]
249     PSCols.add(self.PSColumnByLS[ls])
250     nLS+=1
251     except:
252     print "ERROR: Lumi section "+str(ls)+" not in bounds"
253     return [0.,0.,0.,0.,[]]
254     return [AvInstLumi/nLS,AvLiveLumi/nLS, AvDeliveredLumi/nLS, AvDeadTime/nLS,PSCols]
255     except:
256     return [0.,0.,0.,0.,[]]
257    
258 amott 1.1 def ParsePSColumnPage(self): ## this is now done automatically when we read the db
259     pass
260    
261     def GetL1NameIndexAssoc(self):
262     ## get the L1 algo names associated with each algo bit
263     AlgoNameQuery = """SELECT ALGO_INDEX, ALIAS FROM CMS_GT.L1T_MENU_ALGO_VIEW
264     WHERE MENU_IMPLEMENTATION IN (SELECT L1T_MENU_FK FROM CMS_GT.GT_SETUP WHERE ID='%s')
265     ORDER BY ALGO_INDEX""" % (self.GT_Key,)
266     self.curs.execute(AlgoNameQuery)
267     for index,name in self.curs.fetchall():
268 amott 1.4 self.L1IndexNameMap[name] = index
269 amott 1.1
270     def GetL1AlgoPrescales(self):
271     L1PrescalesQuery= """
272     SELECT
273     PRESCALE_FACTOR_ALGO_000,PRESCALE_FACTOR_ALGO_001,PRESCALE_FACTOR_ALGO_002,PRESCALE_FACTOR_ALGO_003,PRESCALE_FACTOR_ALGO_004,PRESCALE_FACTOR_ALGO_005,
274     PRESCALE_FACTOR_ALGO_006,PRESCALE_FACTOR_ALGO_007,PRESCALE_FACTOR_ALGO_008,PRESCALE_FACTOR_ALGO_009,PRESCALE_FACTOR_ALGO_010,PRESCALE_FACTOR_ALGO_011,
275     PRESCALE_FACTOR_ALGO_012,PRESCALE_FACTOR_ALGO_013,PRESCALE_FACTOR_ALGO_014,PRESCALE_FACTOR_ALGO_015,PRESCALE_FACTOR_ALGO_016,PRESCALE_FACTOR_ALGO_017,
276     PRESCALE_FACTOR_ALGO_018,PRESCALE_FACTOR_ALGO_019,PRESCALE_FACTOR_ALGO_020,PRESCALE_FACTOR_ALGO_021,PRESCALE_FACTOR_ALGO_022,PRESCALE_FACTOR_ALGO_023,
277     PRESCALE_FACTOR_ALGO_024,PRESCALE_FACTOR_ALGO_025,PRESCALE_FACTOR_ALGO_026,PRESCALE_FACTOR_ALGO_027,PRESCALE_FACTOR_ALGO_028,PRESCALE_FACTOR_ALGO_029,
278     PRESCALE_FACTOR_ALGO_030,PRESCALE_FACTOR_ALGO_031,PRESCALE_FACTOR_ALGO_032,PRESCALE_FACTOR_ALGO_033,PRESCALE_FACTOR_ALGO_034,PRESCALE_FACTOR_ALGO_035,
279     PRESCALE_FACTOR_ALGO_036,PRESCALE_FACTOR_ALGO_037,PRESCALE_FACTOR_ALGO_038,PRESCALE_FACTOR_ALGO_039,PRESCALE_FACTOR_ALGO_040,PRESCALE_FACTOR_ALGO_041,
280     PRESCALE_FACTOR_ALGO_042,PRESCALE_FACTOR_ALGO_043,PRESCALE_FACTOR_ALGO_044,PRESCALE_FACTOR_ALGO_045,PRESCALE_FACTOR_ALGO_046,PRESCALE_FACTOR_ALGO_047,
281     PRESCALE_FACTOR_ALGO_048,PRESCALE_FACTOR_ALGO_049,PRESCALE_FACTOR_ALGO_050,PRESCALE_FACTOR_ALGO_051,PRESCALE_FACTOR_ALGO_052,PRESCALE_FACTOR_ALGO_053,
282     PRESCALE_FACTOR_ALGO_054,PRESCALE_FACTOR_ALGO_055,PRESCALE_FACTOR_ALGO_056,PRESCALE_FACTOR_ALGO_057,PRESCALE_FACTOR_ALGO_058,PRESCALE_FACTOR_ALGO_059,
283     PRESCALE_FACTOR_ALGO_060,PRESCALE_FACTOR_ALGO_061,PRESCALE_FACTOR_ALGO_062,PRESCALE_FACTOR_ALGO_063,PRESCALE_FACTOR_ALGO_064,PRESCALE_FACTOR_ALGO_065,
284     PRESCALE_FACTOR_ALGO_066,PRESCALE_FACTOR_ALGO_067,PRESCALE_FACTOR_ALGO_068,PRESCALE_FACTOR_ALGO_069,PRESCALE_FACTOR_ALGO_070,PRESCALE_FACTOR_ALGO_071,
285     PRESCALE_FACTOR_ALGO_072,PRESCALE_FACTOR_ALGO_073,PRESCALE_FACTOR_ALGO_074,PRESCALE_FACTOR_ALGO_075,PRESCALE_FACTOR_ALGO_076,PRESCALE_FACTOR_ALGO_077,
286     PRESCALE_FACTOR_ALGO_078,PRESCALE_FACTOR_ALGO_079,PRESCALE_FACTOR_ALGO_080,PRESCALE_FACTOR_ALGO_081,PRESCALE_FACTOR_ALGO_082,PRESCALE_FACTOR_ALGO_083,
287     PRESCALE_FACTOR_ALGO_084,PRESCALE_FACTOR_ALGO_085,PRESCALE_FACTOR_ALGO_086,PRESCALE_FACTOR_ALGO_087,PRESCALE_FACTOR_ALGO_088,PRESCALE_FACTOR_ALGO_089,
288     PRESCALE_FACTOR_ALGO_090,PRESCALE_FACTOR_ALGO_091,PRESCALE_FACTOR_ALGO_092,PRESCALE_FACTOR_ALGO_093,PRESCALE_FACTOR_ALGO_094,PRESCALE_FACTOR_ALGO_095,
289     PRESCALE_FACTOR_ALGO_096,PRESCALE_FACTOR_ALGO_097,PRESCALE_FACTOR_ALGO_098,PRESCALE_FACTOR_ALGO_099,PRESCALE_FACTOR_ALGO_100,PRESCALE_FACTOR_ALGO_101,
290     PRESCALE_FACTOR_ALGO_102,PRESCALE_FACTOR_ALGO_103,PRESCALE_FACTOR_ALGO_104,PRESCALE_FACTOR_ALGO_105,PRESCALE_FACTOR_ALGO_106,PRESCALE_FACTOR_ALGO_107,
291     PRESCALE_FACTOR_ALGO_108,PRESCALE_FACTOR_ALGO_109,PRESCALE_FACTOR_ALGO_110,PRESCALE_FACTOR_ALGO_111,PRESCALE_FACTOR_ALGO_112,PRESCALE_FACTOR_ALGO_113,
292     PRESCALE_FACTOR_ALGO_114,PRESCALE_FACTOR_ALGO_115,PRESCALE_FACTOR_ALGO_116,PRESCALE_FACTOR_ALGO_117,PRESCALE_FACTOR_ALGO_118,PRESCALE_FACTOR_ALGO_119,
293     PRESCALE_FACTOR_ALGO_120,PRESCALE_FACTOR_ALGO_121,PRESCALE_FACTOR_ALGO_122,PRESCALE_FACTOR_ALGO_123,PRESCALE_FACTOR_ALGO_124,PRESCALE_FACTOR_ALGO_125,
294     PRESCALE_FACTOR_ALGO_126,PRESCALE_FACTOR_ALGO_127
295     FROM CMS_GT.GT_FDL_PRESCALE_FACTORS_ALGO A, CMS_GT.GT_RUN_SETTINGS_PRESC_VIEW B
296     WHERE A.ID=B.PRESCALE_FACTORS_ALGO_FK AND B.ID='%s'
297     """ % (self.GTRS_Key,)
298     self.curs.execute(L1PrescalesQuery)
299     ## This is pretty horrible, but this how you get them!!
300     tmp = self.curs.fetchall()
301     for ps in tmp[0]: #build the prescale table initially
302     self.L1PrescaleTable.append([ps])
303     for line in tmp[1:]: # now fill it
304     for ps,index in zip(line,range(len(line))):
305     self.L1PrescaleTable[index].append(ps)
306 amott 1.4 self.nAlgoBits=128
307 amott 1.1
308     def GetHLTIndex(self,name):
309     for i,n in enumerate(self.HLTList):
310     if n.find(name)!=-1:
311     return i
312 amott 1.2 #print name
313 amott 1.1 return -1
314    
315     def GetHLTPrescaleMatrix(self,cursor):
316     ##NOT WORKING 1/19/2012
317     return
318     SequencePathQuery ="""
319     SELECT F.SEQUENCENB,J.VALUE TRIGGERNAME
320     FROM CMS_HLT.CONFIGURATIONSERVICEASSOC A
321     , CMS_HLT.SERVICES B
322     , CMS_HLT.SERVICETEMPLATES C
323     , CMS_HLT.SUPERIDVECPARAMSETASSOC D
324     , CMS_HLT.VECPARAMETERSETS E
325     , CMS_HLT.SUPERIDPARAMSETASSOC F
326     , CMS_HLT.PARAMETERSETS G
327     , CMS_HLT.SUPERIDPARAMETERASSOC H
328     , CMS_HLT.PARAMETERS I
329     , CMS_HLT.STRINGPARAMVALUES J
330     WHERE A.CONFIGID= %d
331     AND A.SERVICEID=B.SUPERID
332     AND B.TEMPLATEID=C.SUPERID
333     AND C.NAME='PrescaleService'
334     AND B.SUPERID=D.SUPERID
335     AND D.VPSETID=E.SUPERID
336     AND E.NAME='prescaleTable'
337     AND D.VPSETID=F.SUPERID
338     AND F.PSETID=G.SUPERID
339     AND G.SUPERID=H.SUPERID
340     AND I.PARAMID=H.PARAMID
341     AND I.NAME='pathName'
342     AND J.PARAMID=H.PARAMID
343     ORDER BY F.SEQUENCENB
344     """ % (self.ConfigId,)
345    
346     cursor.execute(SequencePathQuery)
347     self.HLTSequenceMap = [0]*len(self.HLTList)
348     for seq,name in cursor.fetchall():
349     name = name.lstrip('"').rstrip('"')
350     try:
351     self.HLTSequenceMap[self.GetHLTIndex(name)]=seq
352     except:
353     print "couldn't find "+name
354    
355     for i,seq in enumerate(self.HLTSequenceMap):
356     if seq==0:
357     print self.HLTList[i]
358    
359     SequencePrescaleQuery="""
360     SELECT F.SEQUENCENB,J.SEQUENCENB,J.VALUE
361     FROM CMS_HLT.CONFIGURATIONSERVICEASSOC A
362     , CMS_HLT.SERVICES B
363     , CMS_HLT.SERVICETEMPLATES C
364     , CMS_HLT.SUPERIDVECPARAMSETASSOC D
365     , CMS_HLT.VECPARAMETERSETS E
366     , CMS_HLT.SUPERIDPARAMSETASSOC F
367     , CMS_HLT.PARAMETERSETS G
368     , CMS_HLT.SUPERIDPARAMETERASSOC H
369     , CMS_HLT.PARAMETERS I
370     , CMS_HLT.VUINT32PARAMVALUES J
371     WHERE A.CONFIGID=%d
372     AND A.SERVICEID=B.SUPERID
373     AND B.TEMPLATEID=C.SUPERID
374     AND C.NAME='PrescaleService'
375     AND B.SUPERID=D.SUPERID
376     AND D.VPSETID=E.SUPERID
377     AND E.NAME='prescaleTable'
378     AND D.VPSETID=F.SUPERID
379     AND F.PSETID=G.SUPERID
380     AND G.SUPERID=H.SUPERID
381     AND I.PARAMID=H.PARAMID
382     AND I.NAME='prescales'
383     AND J.PARAMID=H.PARAMID
384     ORDER BY F.SEQUENCENB,J.SEQUENCENB
385     """ % (self.ConfigId,)
386    
387 amott 1.2 #print self.HLTSequenceMap
388 amott 1.1 cursor.execute(SequencePrescaleQuery)
389     self.HLTPrescaleTable=[ [] ]*len(self.HLTList)
390     lastIndex=-1
391     lastSeq=-1
392     row = []
393     for seq,index,val in cursor.fetchall():
394     if lastIndex!=index-1:
395     self.HLTPrescaleTable[self.HLTSequenceMap.index(lastSeq)].append(row)
396     row=[]
397     lastSeq=seq
398     lastIndex=index
399     row.append(val)
400    
401     def GetHLTSeeds(self):
402     ## This is a rather delicate query, but it works!
403     ## Essentially get a list of paths associated with the config, then find the module of type HLTLevel1GTSeed associated with the path
404     ## Then find the parameter with field name L1SeedsLogicalExpression and look at the value
405     ##
406     ## NEED TO BE LOGGED IN AS CMS_HLT_R
407     cmd='cat ~hltpro/secure/cms_hlt_r.txt'
408     line=os.popen(cmd).readlines()
409     magic = line[0].rstrip("\n\r")
410     connect= 'cms_hlt_r/' + magic + '@cms_omds_lb'
411     # connect to the DB
412     tmporcl = cx_Oracle.connect(connect)
413     tmpcurs = tmporcl.cursor()
414     sqlquery ="""
415     SELECT I.NAME,A.VALUE
416     FROM
417     CMS_HLT.STRINGPARAMVALUES A,
418     CMS_HLT.PARAMETERS B,
419     CMS_HLT.SUPERIDPARAMETERASSOC C,
420     CMS_HLT.MODULETEMPLATES D,
421     CMS_HLT.MODULES E,
422     CMS_HLT.PATHMODULEASSOC F,
423     CMS_HLT.CONFIGURATIONPATHASSOC G,
424     CMS_HLT.CONFIGURATIONS H,
425     CMS_HLT.PATHS I
426     WHERE
427     A.PARAMID = C.PARAMID AND
428     B.PARAMID = C.PARAMID AND
429     B.NAME = 'L1SeedsLogicalExpression' AND
430     C.SUPERID = F.MODULEID AND
431     D.NAME = 'HLTLevel1GTSeed' AND
432     E.TEMPLATEID = D.SUPERID AND
433     F.MODULEID = E.SUPERID AND
434     F.PATHID=G.PATHID AND
435     I.PATHID=G.PATHID AND
436     G.CONFIGID=H.CONFIGID AND
437     H.CONFIGDESCRIPTOR='%s'
438 amott 1.2 ORDER BY A.VALUE
439 amott 1.1 """ % (self.HLT_Key,)
440     tmpcurs.execute(sqlquery)
441     for HLTPath,L1Seed in tmpcurs.fetchall():
442 amott 1.4 if not self.HLTSeed.has_key(HLTPath): ## this should protect us from L1_SingleMuOpen
443     self.HLTSeed[HLTPath] = L1Seed.lstrip('"').rstrip('"')
444 amott 1.1 #self.GetHLTPrescaleMatrix(tmpcurs)
445    
446     def ParseRunSetup(self):
447     #queries that need to be run only once per run
448     self.GetRunInfo()
449     self.GetL1NameIndexAssoc()
450     self.GetL1AlgoPrescales()
451     self.GetHLTSeeds()
452 amott 1.5 self.GetLumiInfo()
453    
454     def UpdateRun(self,LSRange):
455     self.GetLumiInfo()
456     TriggerRates = self.GetHLTRates(LSRange)
457 abrinke1 1.10 #L1Prescales = self.CalculateAvL1Prescales(LSRange)
458     #TotalPrescales = self.CalculateTotalPrescales(TriggerRates,L1Prescales)
459     #UnprescaledRates = self.UnprescaleRates(TriggerRates,TotalPrescales)
460 amott 1.5
461 abrinke1 1.10 #return [UnprescaledRates, TotalPrescales, L1Prescales, TriggerRates]
462     return TriggerRates
463    
464 amott 1.5 def GetLSRange(self,StartLS, NLS):
465     """
466     returns an array of valid LumiSections
467     if NLS < 0, count backwards from StartLS
468     """
469 amott 1.1 self.GetLumiInfo()
470 amott 1.5 LS=[]
471     curLS=StartLS
472     step = NLS/abs(NLS)
473     NLS=abs(NLS)
474     while len(LS)<NLS:
475     if (curLS<0 and step<0) or (curLS>=self.LastLSParsed and step>0):
476     break
477     if curLS>=0 and curLS<self.LastLSParsed:
478     if not self.Physics.has_key(curLS) or not self.Active.has_key(curLS):
479     break
480     if self.Physics[curLS] and self.Active[curLS]:
481     if step>0:
482     LS.append(curLS)
483     else:
484     LS.insert(0,curLS)
485     curLS += step
486     return LS
487    
488 amott 1.8 def GetLastLS(self,phys=False):
489 amott 1.7 self.GetLumiInfo()
490     try:
491 amott 1.8 if not phys:
492     return max(self.Physics.keys())
493     else:
494     maxLS=-1
495     for ls,phys in self.Physics.iteritems():
496     if phys and self.Active[ls] and ls > maxLS:
497     maxLS=ls
498     if maxLS==-1:
499     return 0
500     else:
501     return maxLS
502 amott 1.7 except:
503     return 0
504    
505 amott 1.5 def CalculateAvL1Prescales(self,LSRange):
506     AvgL1Prescales = [0]*self.nAlgoBits
507     for index in LSRange:
508 amott 1.1 psi = self.PSColumnByLS[index]
509     if not psi:
510 amott 1.5 print "Cannot figure out PSI for LS "+str(index)+" setting to 0"
511     psi = 0
512 amott 1.4 for algo in range(self.nAlgoBits):
513 amott 1.5 AvgL1Prescales[algo]+=self.L1PrescaleTable[algo][psi]
514     for i in range(len(AvgL1Prescales)):
515 amott 1.6 try:
516     AvgL1Prescales[i] = AvgL1Prescales[i]/len(LSRange)
517     except:
518     AvgL1Prescales[i] = AvgL1Prescales[i]
519 amott 1.5 return AvgL1Prescales
520    
521     def CalculateTotalPrescales(self,TriggerRates, L1Prescales):
522     AvgTotalPrescales={}
523     for hltName,v in TriggerRates.iteritems():
524 amott 1.4 if not self.HLTSeed.has_key(hltName):
525     continue
526 amott 1.1 hltPS=0
527 amott 1.4 if len(v)>0:
528     hltPS = v[0]
529     l1Index=-1
530     if self.L1IndexNameMap.has_key(self.HLTSeed[hltName]):
531     l1Index = self.L1IndexNameMap[self.HLTSeed[hltName]]
532    
533 amott 1.1 l1PS=0
534     if l1Index==-1:
535 amott 1.5 l1PS = self.UnwindORSeed(self.HLTSeed[hltName],L1Prescales)
536 amott 1.1 else:
537 amott 1.5 l1PS = L1Prescales[l1Index]
538     AvgTotalPrescales[hltName]=l1PS*hltPS
539     return AvgTotalPrescales
540 amott 1.1
541 amott 1.5 def UnwindORSeed(self,expression,L1Prescales):
542 amott 1.4 """
543     Figures out the effective prescale for the OR of several seeds
544     we take this to be the *LOWEST* prescale of the included seeds
545     """
546 amott 1.2 if expression.find(" OR ") == -1:
547     return -1 # Not an OR of seeds
548     seedList = expression.split(" OR ")
549     if len(seedList)==1:
550     return -1 # Not an OR of seeds, really shouldn't get here...
551     minPS = 99999999999
552     for seed in seedList:
553 amott 1.4 if not self.L1IndexNameMap.has_key(seed):
554     continue
555 amott 1.5 ps = L1Prescales[self.L1IndexNameMap[seed]]
556 amott 1.4 if ps:
557     minPS = min(ps,minPS)
558 amott 1.2 if minPS==99999999999:
559     return 0
560     else:
561     return minPS
562    
563 amott 1.5 def UnprescaleRates(self,TriggerRates,TotalPrescales):
564     UnprescaledRates = {}
565     for hltName,v in TriggerRates.iteritems():
566     if TotalPrescales.has_key(hltName):
567     ps = TotalPrescales[hltName]
568 amott 1.4 if ps:
569 amott 1.5 UnprescaledRates[hltName] = v[1]*ps
570 amott 1.4 else:
571 amott 1.5 UnprescaledRates[hltName] = v[1]
572 amott 1.4 else:
573 amott 1.5 UnprescaledRates[hltName] = v[1]
574     return UnprescaledRates
575    
576 amott 1.1 def AssemblePrescaleValues(self): ##Depends on output from ParseLumiPage and ParseTriggerModePage
577     return ## WHAT DOES THIS FUNCTION DO???
578     MissingName = "Nemo"
579     for key in self.L1TriggerMode:
580     self.L1Prescale[key] = {}
581     for n in range(min(self.LSByLS),max(self.LSByLS)+1): #"range()" excludes the last element
582     try:
583     self.L1Prescale[key][n] = self.L1TriggerMode[key][self.PSColumnByLS[n]]
584     except:
585     if not key == MissingName:
586     self.MissingPrescale.append(key)
587     MissingName = key
588     if not n < 2:
589     print "LS "+str(n)+" of key "+str(key)+" is missing from the LumiSections page"
590    
591     for key in self.HLTTriggerMode:
592     self.HLTPrescale[key] = {}
593     for n in range(min(self.LSByLS),max(self.LSByLS)+1): #"range" excludes the last element
594     try:
595     self.HLTPrescale[key][n] = self.HLTTriggerMode[key][self.PSColumnByLS[n]]
596     except:
597     if not key == MissingName:
598     self.MissingPrescale.append(key)
599     MissingName = key
600     if not n < 2:
601     print "LS "+str(n)+" of key "+str(key)+" is missing from the LumiSections page"
602    
603     self.PrescaleValues = [self.L1Prescale,self.HLTPrescale,self.MissingPrescale]
604     return self.PrescaleValues
605    
606     def ComputeTotalPrescales(self,StartLS,EndLS):
607     return ## WHAT DOES THIS FUNCTION DO??
608     IdealHLTPrescale = {}
609     IdealPrescale = {}
610     L1_zero = {}
611     HLT_zero = {}
612     n1 = {}
613     n2 = {}
614     L1 = {}
615     L2 = {}
616     H1 = {}
617     H2 = {}
618     InitialColumnIndex = self.PSColumnByLS[int(StartLS)]
619    
620     for key in self.HLTTriggerMode:
621     try:
622     DoesThisPathHaveAValidL1SeedWithPrescale = self.L1Prescale[self.HLTSeed[key]][StartLS]
623     except:
624     L1_zero[key] = True
625     HLT_zero[key] = False
626     continue
627    
628     IdealHLTPrescale[key] = 0.0
629     IdealPrescale[key] = 0.0
630     n1[key] = 0
631     L1_zero[key] = False
632     HLT_zero[key] = False
633    
634     for LSIterator in range(StartLS,EndLS+1): #"range" excludes the last element
635     if self.L1Prescale[self.HLTSeed[key]][LSIterator] > 0 and self.HLTPrescale[key][LSIterator] > 0:
636     IdealPrescale[key]+=1.0/(self.L1Prescale[self.HLTSeed[key]][LSIterator]*self.HLTPrescale[key][LSIterator])
637     else:
638     IdealPrescale[key]+=1.0 ##To prevent a divide by 0 error later
639     if self.L1Prescale[self.HLTSeed[key]][LSIterator] < 0.1:
640     L1_zero[key] = True
641     if self.HLTPrescale[key][LSIterator] < 0.1:
642     HLT_zero[key] = True
643     if self.PSColumnByLS[LSIterator] == InitialColumnIndex:
644     n1[key]+=1
645    
646     if L1_zero[key] == True or HLT_zero[key] == True:
647     continue
648    
649     IdealPrescale[key] = (EndLS + 1 - StartLS)/IdealPrescale[key]
650    
651     n2[key] = float(EndLS + 1 - StartLS - n1[key])
652     L1[key] = float(self.L1Prescale[self.HLTSeed[key]][StartLS])
653     L2[key] = float(self.L1Prescale[self.HLTSeed[key]][EndLS])
654     H1[key] = float(self.HLTPrescale[key][StartLS])
655     H2[key] = float(self.HLTPrescale[key][EndLS])
656    
657     IdealHLTPrescale[key] = ((n1[key]/L1[key])+(n2[key]/L2[key]))/((n1[key]/(L1[key]*H1[key]))+(n2[key]/(L2[key]*H2[key])))
658    
659     self.TotalPSInfo = [L1_zero,HLT_zero,IdealPrescale,IdealHLTPrescale,n1,n2,L1,L2,H1,H2]
660    
661     return self.TotalPSInfo
662    
663    
664     def CorrectForPrescaleChange(self,StartLS,EndLS):
665     [L1_zero,HLT_zero,IdealPrescale,IdealHLTPrescale,n1,n2,L1,L2,H1,H2] = self.TotalPSInfo
666     xLS = {}
667     RealPrescale = {}
668    
669     for key in self.HLTTriggerMode:
670     if L1_zero[key] == True or HLT_zero[key] == True:
671     continue
672     [TriggerRate,L1Pass,PSPass,PS,Seed,StartLS,EndLS] = self.TriggerRates[key]
673     if PS > 0.95 * IdealHLTPrescale[key] and PS < 1.05 * IdealHLTPrescale[key]:
674     RealPrescale[key] = IdealPrescale[key]
675     continue
676    
677     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
678     H2[key] = float(self.HLTPrescale[key][EndLS+1])
679     L2[key] = float(self.L1Prescale[self.HLTSeed[key]][EndLS+1])
680     if H1[key] == H2[key] and L1[key] == L2[key] and not StartLS < 3:
681     H1[key] = float(self.HLTPrescale[key][StartLS-1])
682     L1[key] = float(self.L1Prescale[self.HLTSeed[key]][StartLS-1])
683     if H1[key] == H2[key]:
684     xLS[key] = 0
685     else:
686     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])))
687    
688     if xLS[key] > 1:
689     xLS[key] = 1
690     if xLS[key] < -1:
691     xLS[key] = -1
692     RealPrescale[key] = (n1[key] + n2[key])/(((n1[key] - xLS[key])/(H1[key]*L1[key]))+(n2[key]+xLS[key])/(H2[key]*L2[key]))
693    
694     self.CorrectedPSInfo = [RealPrescale,xLS,L1,L2,H1,H2]
695    
696     return self.CorrectedPSInfo
697    
698 amott 1.4 def GetAvLumiPerRange(self, NMergeLumis=10):
699     """
700 amott 1.5 This function returns a per-LS table of the average lumi of the previous NMergeLumis LS
701 amott 1.4 """
702 amott 1.5 AvLumiRange = []
703     AvLumiTable = {}
704     for ls,lumi in self.InstLumiByLS.iteritems():
705     try:
706     AvLumiRange.append(int(lumi))
707     except:
708     continue
709     if len(AvLumiRange) == NMergeLumis:
710     AvLumiRange = AvLumiRange[1:]
711     AvLumiTable[ls] = sum(AvLumiRange)/NMergeLumis
712 amott 1.4 return AvLumiTable
713    
714 amott 1.9 def GetTriggerVersion(self,triggerName):
715     for key in self.HLTSeed.iterkeys():
716     if StripVersion(key)==triggerName:
717     return key
718     return ""
719    
720 amott 1.1 def Save(self, fileName):
721     dir = os.path.dirname(fileName)
722     if not os.path.exists(dir):
723     os.makedirs(dir)
724     pickle.dump( self, open( fileName, 'w' ) )
725    
726     def Load(self, fileName):
727     self = pickle.load( open( fileName ) )
728 amott 1.5
729    
730    
731     def GetLatestRunNumber():
732     cmd='cat ~centraltspro/secure/cms_trg_r.txt'
733     line=os.popen(cmd).readlines()
734     magic = line[0].rstrip("\n\r")
735     connect= 'cms_trg_r/' + magic + '@cms_omds_lb'
736     # connect to the DB
737     orcl = cx_Oracle.connect(connect)
738     curs = orcl.cursor()
739     RunNoQuery="""
740     SELECT MAX(A.RUNNUMBER) FROM CMS_RUNINFO.RUNNUMBERTBL A, CMS_WBM.RUNSUMMARY B WHERE A.RUNNUMBER=B.RUNNUMBER AND B.TRIGGERS>0
741     """
742     curs.execute(RunNoQuery)
743     r, = curs.fetchone()
744     TrigModeQuery = """
745     SELECT TRIGGERMODE FROM CMS_WBM.RUNSUMMARY WHERE RUNNUMBER = %d
746     """ % r
747     curs.execute(TrigModeQuery)
748     trigm, = curs.fetchone()
749     isCol=0
750     if trigm.find('l1_hlt_collisions')!=-1:
751     isCol=1
752     return (r,isCol,)
753    
754     def ClosestIndex(value,table):
755     diff = 999999999;
756     index = 0
757     for i,thisVal in table.iteritems():
758     if abs(thisVal-value)<diff:
759     diff = abs(thisVal-value)
760     index =i
761     return index
762    
763    
764     def StripVersion(name):
765     if re.match('.*_v[0-9]+',name):
766     name = name[:name.rfind('_')]
767     return name