CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch12/src/RecoLuminosity/LumiDB/python/lumiQueryAPI.py

Go to the documentation of this file.
00001 import os
00002 import coral,datetime
00003 from RecoLuminosity.LumiDB import nameDealer,lumiTime,CommonUtil
00004 import array
00005 from RecoLuminosity.LumiDB import argparse, nameDealer, selectionParser, hltTrgSeedMapper, \
00006      connectstrParser, cacheconfigParser, tablePrinter, csvReporter, csvSelectionParser
00007 from RecoLuminosity.LumiDB.wordWrappers import wrap_always, wrap_onspace, wrap_onspace_strict
00008 from pprint import pprint, pformat
00009 
00010 '''
00011 This module defines lowlevel SQL query API for lumiDB 
00012 We do not like range queries so far because of performance of range scan.Use only necessary.
00013 The principle is to query by runnumber and per each coral queryhandle
00014 Try reuse db session/transaction and just renew query handle each time to reduce metadata queries.
00015 Avoid unnecessary explicit order by
00016 Do not handle transaction in here.
00017 Do not do explicit del queryhandle in here.
00018 Note: all the returned dict format are not sorted by itself.Sort it outside if needed.
00019 '''
00020 ###==============temporarilly here======###
00021 
00022 class ParametersObject (object):
00023 
00024     def __init__ (self):
00025         self.norm            = 1.0
00026         self.lumiversion     = '0001'
00027         self.NBX             = 3564  # number beam crossings
00028         self.rotationRate    = 11245.613 # for 3.5 TeV Beam energy
00029         self.normFactor      = 6.37
00030         self.beammode        = '' #possible choices stable, quiet, either
00031         self.verbose         = False
00032         self.noWarnings      = False
00033         self.lumischema      = 'CMS_LUMI_PROD'
00034         #self.lumidb          = 'oracle://cms_orcoff_prod/cms_lumi_prod'
00035         self.lumisummaryname = 'LUMISUMMARY'
00036         self.lumidetailname  = 'LUMIDETAIL'
00037         self.lumiXing        = False
00038         self.xingMinLum      = 1.0e-4
00039         self.xingIndex       = 5
00040         self.minBiasXsec     = 71300 # unit: microbarn
00041         self.pileupHistName  = 'pileup'
00042         self.maxPileupBin    = 10
00043         self.calculateTimeParameters()
00044 
00045     def calculateTimeParameters (self):
00046         '''Given the rotation rate, calculate lumi section length and
00047         rotation time.  This should be called if rotationRate is
00048         updated.'''
00049         self.rotationTime    = 1 / self.rotationRate
00050         self.lumiSectionLen  = 2**18 * self.rotationTime
00051         
00052     def defaultfrontierConfigString (self):
00053         return '''<frontier-connect><proxy url = "http://cmst0frontier.cern.ch:3128"/><proxy url = "http://cmst0frontier.cern.ch:3128"/><proxy url = "http://cmst0frontier1.cern.ch:3128"/><proxy url = "http://cmst0frontier2.cern.ch:3128"/><server url = "http://cmsfrontier.cern.ch:8000/FrontierInt"/><server url = "http://cmsfrontier.cern.ch:8000/FrontierInt"/><server url = "http://cmsfrontier1.cern.ch:8000/FrontierInt"/><server url = "http://cmsfrontier2.cern.ch:8000/FrontierInt"/><server url = "http://cmsfrontier3.cern.ch:8000/FrontierInt"/><server url = "http://cmsfrontier4.cern.ch:8000/FrontierInt"/></frontier-connect>'''
00054 
00055 def lslengthsec (numorbit, numbx):
00056     #print numorbit, numbx
00057     l = numorbit * numbx * 25.0e-09
00058     return l
00059 
00060 def lsBylsLumi (deadtable):
00061     """
00062     input: {lsnum:[deadtime, instlumi, bit_0, norbits,prescale...]}
00063     output: {lsnum:[instlumi, recordedlumi...]}
00064     """
00065     result = {}
00066     for myls, deadArray in deadtable.items():
00067         lstime = lslengthsec (deadArray[3], 3564)
00068         instlumi = deadArray[1] * lstime
00069         if float( deadArray[2] ) ==  0.0:
00070             deadfrac = 1.0
00071         else:
00072             deadfrac = float (deadArray[0]) / (float (deadArray[2])*float(deadArray[4]))
00073         recordedLumi = instlumi * (1.0 - deadfrac)
00074         myLsList = [instlumi, recordedLumi]
00075         #print myls,instlumi,recordedLumi,lstime,deadfrac
00076         if len (deadArray) > 5:
00077             myLsList.extend (deadArray[5:])
00078         result[myls] = myLsList
00079     return result
00080 
00081 
00082 def deliveredLumiForRange (dbsession, parameters, inputRange):
00083     '''Takes either single run as a string or dictionary of run ranges'''
00084     lumidata = []
00085     # is this a single string?
00086     if isinstance (inputRange, str):
00087         lumidata.append( deliveredLumiForRun (dbsession, parameters, inputRange) )
00088     else:
00089         # if not, it's one of these dictionary things
00090         for run in sorted( inputRange.runs() ):
00091             if parameters.verbose:
00092                 print "run", run
00093             lumidata.append( deliveredLumiForRun (dbsession, parameters, run) )
00094     #print lumidata
00095     return lumidata
00096 
00097 
00098 def recordedLumiForRange (dbsession, parameters, inputRange):
00099     '''Takes either single run as a string or dictionary of run ranges'''
00100     lumidata = []
00101     # is this a single string?
00102     if isinstance (inputRange, str):
00103         lumiDataPiece = recordedLumiForRun (dbsession, parameters, inputRange)
00104         if parameters.lumiXing:
00105             # get the xing information for the run
00106             xingLumiDict = xingLuminosityForRun (dbsession, inputRange,
00107                                                  parameters)
00108             mergeXingLumi (lumiDataPiece, xingLumiDict)
00109         lumidata.append (lumiDataPiece)
00110         
00111     else:
00112         # we want to collapse the lists so that every run is considered once.
00113         runLsDict = {}
00114         maxLumiSectionDict = {}
00115         for (run, lslist) in sorted (inputRange.runsandls().items() ):
00116             if(len(lslist)!=0):
00117                 maxLumiSectionDict[run] = max ( max (lslist),
00118                                            maxLumiSectionDict.get(run,0) )
00119             runLsDict.setdefault (run, []).append (lslist)
00120         for run, metaLsList in sorted (runLsDict.iteritems()):
00121             if parameters.verbose:
00122                 print "run", run
00123             runLumiData = []
00124             for lslist in metaLsList:
00125                 runLumiData.append( recordedLumiForRun (dbsession, parameters,
00126                                                         run, lslist) )
00127             if parameters.lumiXing:
00128                 # get the xing information once for the whole run
00129                 xingLumiDict = xingLuminosityForRun (dbsession, run,
00130                                                      parameters,
00131                                                      maxLumiSection = \
00132                                                      maxLumiSectionDict[run])
00133                 # merge it with every piece of lumi data for this run
00134                 for lumiDataPiece in runLumiData:
00135                     mergeXingLumi (lumiDataPiece, xingLumiDict)
00136                     lumidata.append (lumiDataPiece)
00137             else:
00138                 lumidata.extend( runLumiData )
00139     return lumidata
00140 
00141 
00142 
00143 def deliveredLumiForRun (dbsession, parameters, runnum):    
00144     """
00145     select sum (INSTLUMI), count (INSTLUMI) from lumisummary where runnum = 124025 and lumiversion = '0001';
00146     select INSTLUMI,NUMORBIT  from lumisummary where runnum = 124025 and lumiversion = '0001'
00147     query result unit E27cm^-2 (= 1 / mb)"""    
00148     #if parameters.verbose:
00149     #    print 'deliveredLumiForRun : norm : ', parameters.norm, ' : run : ', runnum
00150     #output ['run', 'totalls', 'delivered', 'beammode']
00151     delivered = 0.0
00152     totalls = 0
00153     try:
00154         conditionstring="RUNNUM = :runnum AND LUMIVERSION = :lumiversion"
00155         dbsession.transaction().start (True)
00156         schema = dbsession.nominalSchema()
00157         query = schema.tableHandle (nameDealer.lumisummaryTableName()).newQuery()
00158         #query.addToOutputList ("sum (INSTLUMI)", "totallumi")
00159         #query.addToOutputList ("count (INSTLUMI)", "totalls")
00160         query.addToOutputList("INSTLUMI",'instlumi')
00161         query.addToOutputList ("NUMORBIT", "norbits")
00162         queryBind = coral.AttributeList()
00163         queryBind.extend ("runnum", "unsigned int")
00164         queryBind.extend ("lumiversion", "string")
00165         queryBind["runnum"].setData (int (runnum))
00166         queryBind["lumiversion"].setData (parameters.lumiversion)
00167         #print parameters.beammode
00168         if len(parameters.beammode)!=0:
00169             conditionstring=conditionstring+' and BEAMSTATUS=:beamstatus'
00170             queryBind.extend('beamstatus','string')
00171             queryBind['beamstatus'].setData(parameters.beammode)
00172         result = coral.AttributeList()
00173         result.extend ("instlumi", "float")
00174         result.extend ("norbits", "unsigned int")
00175         query.defineOutput (result)
00176         query.setCondition (conditionstring,queryBind)
00177         #query.limitReturnedRows (1)
00178         #query.groupBy ('NUMORBIT')
00179         cursor = query.execute()
00180         while cursor.next():
00181             instlumi = cursor.currentRow()['instlumi'].data()
00182             norbits = cursor.currentRow()['norbits'].data()
00183 
00184             if instlumi is not None and norbits is not None:
00185                 lstime = lslengthsec(norbits, parameters.NBX)
00186                 delivered=delivered+instlumi*parameters.norm*lstime
00187                 totalls+=1
00188         del query
00189         dbsession.transaction().commit()
00190         lumidata = []
00191         if delivered == 0.0:
00192             lumidata = [str (runnum), 'N/A', 'N/A', 'N/A']
00193         else:
00194             lumidata = [str (runnum), str (totalls), '%.3f'%delivered, parameters.beammode]
00195         return lumidata
00196     except Exception, e:
00197         print str (e)
00198         dbsession.transaction().rollback()
00199         del dbsession
00200 
00201 def recordedLumiForRun (dbsession, parameters, runnum, lslist = None):
00202     """
00203     lslist = [] means take none in the db
00204     lslist = None means to take all in the db
00205     output: ['runnumber', 'trgtable{}', 'deadtable{}']
00206     """
00207     recorded = 0.0
00208     lumidata = [] #[runnumber, trgtable, deadtable]
00209     trgtable = {} #{hltpath:[l1seed, hltprescale, l1prescale]}
00210     deadtable = {} #{lsnum:[deadtime, instlumi, bit_0, norbits,bitzero_prescale]}
00211     lumidata.append (runnum)
00212     lumidata.append (trgtable)
00213     lumidata.append (deadtable)
00214     collectedseeds = [] #[ (hltpath, l1seed)]
00215     conditionstring='trghltmap.HLTKEY = cmsrunsummary.HLTKEY AND cmsrunsummary.RUNNUM = :runnumber'
00216     try:
00217         dbsession.transaction().start (True)
00218         schema = dbsession.nominalSchema()
00219         query = schema.newQuery()
00220         query.addToTableList (nameDealer.cmsrunsummaryTableName(), 'cmsrunsummary')
00221         query.addToTableList (nameDealer.trghltMapTableName(), 'trghltmap')#small table first
00222         queryCondition = coral.AttributeList()
00223         queryCondition.extend ("runnumber", "unsigned int")
00224         queryCondition["runnumber"].setData (int (runnum))
00225         query.setCondition (conditionstring,queryCondition)
00226         query.addToOutputList ("trghltmap.HLTPATHNAME", "hltpathname")
00227         query.addToOutputList ("trghltmap.L1SEED", "l1seed")
00228         result = coral.AttributeList()
00229         result.extend ("hltpathname", "string")
00230         result.extend ("l1seed", "string")
00231         query.defineOutput (result)
00232         cursor = query.execute()
00233         while cursor.next():
00234             hltpathname = cursor.currentRow()["hltpathname"].data()
00235             l1seed = cursor.currentRow()["l1seed"].data()
00236             collectedseeds.append ( (hltpathname, l1seed))
00237         #print 'collectedseeds ', collectedseeds
00238         del query
00239         dbsession.transaction().commit()
00240         #loop over hltpath
00241         for (hname, sname) in collectedseeds:
00242             l1bitname = hltTrgSeedMapper.findUniqueSeed (hname, sname)
00243             #print 'found unque seed ', hname, l1bitname
00244             if l1bitname:
00245                 lumidata[1][hname] = []
00246                 lumidata[1][hname].append (l1bitname.replace ('\"', ''))
00247         dbsession.transaction().start (True)
00248         schema = dbsession.nominalSchema()
00249         hltprescQuery = schema.tableHandle (nameDealer.hltTableName()).newQuery()
00250         hltprescQuery.addToOutputList ("PATHNAME", "hltpath")
00251         hltprescQuery.addToOutputList ("PRESCALE", "hltprescale")
00252         hltprescCondition = coral.AttributeList()
00253         hltprescCondition.extend ('runnumber', 'unsigned int')
00254         hltprescCondition.extend ('cmslsnum', 'unsigned int')
00255         hltprescCondition.extend ('inf', 'unsigned int')
00256         hltprescResult = coral.AttributeList()
00257         hltprescResult.extend ('hltpath', 'string')
00258         hltprescResult.extend ('hltprescale', 'unsigned int')
00259         hltprescQuery.defineOutput (hltprescResult)
00260         hltprescCondition['runnumber'].setData (int (runnum))
00261         hltprescCondition['cmslsnum'].setData (1)
00262         hltprescCondition['inf'].setData (0)
00263         hltprescQuery.setCondition ("RUNNUM = :runnumber and CMSLSNUM = :cmslsnum and PRESCALE != :inf",
00264                                     hltprescCondition)
00265         cursor = hltprescQuery.execute()
00266         while cursor.next():
00267             hltpath = cursor.currentRow()['hltpath'].data()
00268             hltprescale = cursor.currentRow()['hltprescale'].data()
00269             if lumidata[1].has_key (hltpath):
00270                 lumidata[1][hltpath].append (hltprescale)
00271                 
00272         cursor.close()
00273         del hltprescQuery
00274         dbsession.transaction().commit()      
00275         dbsession.transaction().start (True)
00276         schema = dbsession.nominalSchema()
00277         query = schema.newQuery()
00278         query.addToTableList (nameDealer.trgTableName(), 'trg')
00279         query.addToTableList (nameDealer.lumisummaryTableName(), 'lumisummary')#small table first--right-most
00280         queryCondition = coral.AttributeList()
00281         queryCondition.extend ("runnumber", "unsigned int")
00282         queryCondition.extend ("lumiversion", "string")
00283         queryCondition["runnumber"].setData (int (runnum))
00284         queryCondition["lumiversion"].setData (parameters.lumiversion)
00285         conditionstring='lumisummary.RUNNUM =:runnumber and lumisummary.LUMIVERSION =:lumiversion AND lumisummary.CMSLSNUM=trg.CMSLSNUM and lumisummary.RUNNUM=trg.RUNNUM'
00286         if len(parameters.beammode)!=0:
00287             conditionstring=conditionstring+' and lumisummary.BEAMSTATUS=:beamstatus'
00288             queryCondition.extend('beamstatus','string')
00289             queryCondition['beamstatus'].setData(parameters.beammode)
00290         query.setCondition(conditionstring,queryCondition)
00291         query.addToOutputList ("lumisummary.CMSLSNUM", "cmsls")
00292         query.addToOutputList ("lumisummary.INSTLUMI", "instlumi")
00293         query.addToOutputList ("lumisummary.NUMORBIT", "norbits")
00294         query.addToOutputList ("trg.TRGCOUNT",         "trgcount")
00295         query.addToOutputList ("trg.BITNAME",          "bitname")
00296         query.addToOutputList ("trg.DEADTIME",         "trgdeadtime")
00297         query.addToOutputList ("trg.PRESCALE",         "trgprescale")
00298         query.addToOutputList ("trg.BITNUM",           "trgbitnum")
00299         
00300         result = coral.AttributeList()
00301         result.extend ("cmsls",       "unsigned int")
00302         result.extend ("instlumi",    "float")
00303         result.extend ("norbits",     "unsigned int")
00304         result.extend ("trgcount",    "unsigned int")
00305         result.extend ("bitname",     "string")
00306         result.extend ("trgdeadtime", "unsigned long long")
00307         result.extend ("trgprescale", "unsigned int")
00308         result.extend ("trgbitnum",   "unsigned int")
00309         trgprescalemap = {}
00310         query.defineOutput (result)
00311         cursor = query.execute()
00312         while cursor.next():
00313             cmsls       = cursor.currentRow()["cmsls"].data()
00314             instlumi    = cursor.currentRow()["instlumi"].data()*parameters.norm
00315             norbits     = cursor.currentRow()["norbits"].data()
00316             trgcount    = cursor.currentRow()["trgcount"].data()
00317             trgbitname  = cursor.currentRow()["bitname"].data()
00318             trgdeadtime = cursor.currentRow()["trgdeadtime"].data()
00319             trgprescale = cursor.currentRow()["trgprescale"].data()
00320             trgbitnum   = cursor.currentRow()["trgbitnum"].data()
00321             if cmsls == 1:
00322                 if not trgprescalemap.has_key (trgbitname):
00323                     trgprescalemap[trgbitname] = trgprescale
00324             if trgbitnum == 0:
00325                 if not deadtable.has_key (cmsls):
00326                     deadtable[cmsls] = []
00327                     deadtable[cmsls].append (trgdeadtime)
00328                     deadtable[cmsls].append (instlumi)
00329                     deadtable[cmsls].append (trgcount)
00330                     deadtable[cmsls].append (norbits)
00331                     deadtable[cmsls].append (trgprescale)
00332         cursor.close()
00333         del query
00334         dbsession.transaction().commit()
00335         
00336         #
00337         #consolidate results
00338         #
00339         #trgtable
00340         #print 'trgprescalemap', trgprescalemap
00341         #print lumidata[1]
00342         for hpath, trgdataseq in lumidata[1].items():   
00343             bitn = trgdataseq[0]
00344             if trgprescalemap.has_key (bitn) and len (trgdataseq) == 2:
00345                 lumidata[1][hpath].append (trgprescalemap[bitn])                
00346         #filter selected cmsls
00347         lumidata[2] = filterDeadtable (deadtable, lslist)
00348         #print 'lslist ',lslist
00349         if not parameters.noWarnings:
00350             if len(lumidata[2])!=0:
00351                 for lumi, deaddata in lumidata[2].items():
00352                     if deaddata[1] == 0.0 and deaddata[2]!=0 and deaddata[0]!=0:
00353                         print '[Warning] : run %s :ls %d has 0 instlumi but trigger has data' % (runnum, lumi)
00354                     if (deaddata[2] == 0 or deaddata[0] == 0) and deaddata[1]!=0.0:
00355                         print '[Warning] : run %s :ls %d has 0 dead counts or 0 zerobias bit counts, but inst!=0' % (runnum, lumi)
00356         #print 'lumidata[2] ', lumidata[2]
00357     except Exception, e:
00358         print str (e)
00359         dbsession.transaction().rollback()
00360         del dbsession
00361     #print 'before return lumidata ', lumidata
00362     ## if parameters.lumiXing:
00363     ##     xingLumiDict =  xingLuminosityForRun (dbsession, runnum, parameters)
00364     ##     mergeXingLumi (lumidata, xingLumiDict)
00365     return lumidata
00366 
00367 
00368 def filterDeadtable (inTable, lslist):
00369     result = {}
00370     if lslist is None:
00371         return inTable
00372     if len (lslist) == 0: #if request no ls, then return nothing
00373         return result
00374     for existingLS in inTable.keys():
00375         if existingLS in lslist:
00376             result[existingLS] = inTable[existingLS]
00377     return result
00378 
00379 
00380 def printDeliveredLumi (lumidata, mode):
00381     labels = [ ('Run', 'Delivered LS', 'Delivered'+u' (/\u03bcb)'.encode ('utf-8'), 'Beam Mode')]
00382     print tablePrinter.indent (labels+lumidata, hasHeader = True, separateRows = False,
00383                                prefix = '| ', postfix = ' |', justify = 'right',
00384                                delim = ' | ', wrapfunc = lambda x: wrap_onspace (x, 20) )
00385 
00386 def dumpData (lumidata, filename):
00387     """
00388     input params: lumidata [{'fieldname':value}]
00389                   filename csvname
00390     """
00391     
00392     r = csvReporter.csvReporter(filename)
00393     r.writeRows(lumidata)
00394 
00395 def calculateTotalRecorded (deadtable):
00396     """
00397     input: {lsnum:[deadtime, instlumi, bit_0, norbits,prescale]}
00398     output: recordedLumi
00399     """
00400     recordedLumi = 0.0
00401     for myls, d in deadtable.items():
00402         instLumi = d[1]
00403         #deadfrac = float (d[0])/float (d[2]*3564)
00404         #print myls, float (d[2])
00405         if float (d[2]) == 0.0:
00406             deadfrac = 1.0
00407         else:
00408             deadfrac = float (d[0])/(float (d[2])*float (d[-1]))
00409         lstime = lslengthsec (d[3], 3564)
00410         recordedLumi += instLumi* (1.0-deadfrac)*lstime
00411     return recordedLumi
00412 
00413 
00414 def splitlistToRangeString (inPut):
00415     result = []
00416     first = inPut[0]
00417     last = inPut[0]
00418     result.append ([inPut[0]])
00419     counter = 0
00420     for i in inPut[1:]:
00421         if i == last+1:
00422             result[counter].append (i)
00423         else:
00424             counter += 1
00425             result.append ([i])
00426         last = i
00427     return ', '.join (['['+str (min (x))+'-'+str (max (x))+']' for x in result])
00428 
00429 
00430 def calculateEffective (trgtable, totalrecorded):
00431     """
00432     input: trgtable{hltpath:[l1seed, hltprescale, l1prescale]}, totalrecorded (float)
00433     output:{hltpath, recorded}
00434     """
00435     #print 'inputtrgtable', trgtable
00436     result = {}
00437     for hltpath, data in trgtable.items():
00438         if len (data) ==  3:
00439             result[hltpath] = totalrecorded/ (data[1]*data[2])
00440         else:
00441             result[hltpath] = 0.0
00442     return result
00443 
00444 
00445 def getDeadfractions (deadtable):
00446     """
00447     inputtable: {lsnum:[deadtime, instlumi, bit_0, norbits,bit_0_prescale]}
00448     output: {lsnum:deadfraction}
00449     """
00450     result = {}
00451     for myls, d in deadtable.items():
00452         #deadfrac = float (d[0])/ (float (d[2])*float (3564))
00453         if float (d[2]) == 0.0: ##no beam
00454             deadfrac = -1.0
00455         else:
00456             deadfrac = float (d[0])/ (float (d[2])*float(d[-1]))
00457         result[myls] = deadfrac
00458     return result
00459 
00460 def printPerLSLumi (lumidata, isVerbose = False):
00461     '''
00462     input lumidata  [['runnumber', 'trgtable{}', 'deadtable{}']]
00463     deadtable {lsnum:[deadtime, instlumi, bit_0, norbits,prescale]}
00464     '''
00465     datatoprint = []
00466     totalrow = []
00467     labels = [ ('Run', 'LS', 'Delivered', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'))]
00468     lastrowlabels = [ ('Selected LS', 'Delivered'+u' (/\u03bcb)'.encode ('utf-8'), 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'))]
00469     totalDeliveredLS = 0
00470     totalSelectedLS = 0
00471     totalDelivered = 0.0
00472     totalRecorded = 0.0
00473     
00474     for perrundata in lumidata:
00475         runnumber = perrundata[0]
00476         deadtable = perrundata[2]
00477         lumiresult = lsBylsLumi (deadtable)
00478         totalSelectedLS = totalSelectedLS+len (deadtable)
00479         for lsnum, dataperls in lumiresult.items():
00480             rowdata = []
00481             if len (dataperls) == 0:
00482                 rowdata  +=  [str (runnumber), str (lsnum), 'N/A', 'N/A']
00483             else:
00484                 rowdata  +=  [str (runnumber), str (lsnum), '%.3f' % (dataperls[0]), '%.3f' % (dataperls[1])]
00485                 totalDelivered = totalDelivered+dataperls[0]
00486                 totalRecorded = totalRecorded+dataperls[1]
00487             datatoprint.append (rowdata)
00488     totalrow.append ([str (totalSelectedLS), '%.3f'% (totalDelivered), '%.3f'% (totalRecorded)])
00489     print ' ==  = '
00490     print tablePrinter.indent (labels+datatoprint, hasHeader = True, separateRows = False, prefix = '| ',
00491                                postfix = ' |', justify = 'right', delim = ' | ',
00492                                wrapfunc = lambda x: wrap_onspace_strict (x, 22))
00493     print ' ==  =  Total : '
00494     print tablePrinter.indent (lastrowlabels+totalrow, hasHeader = True, separateRows = False, prefix = '| ',
00495                                postfix = ' |', justify = 'right', delim = ' | ',
00496                                wrapfunc = lambda x: wrap_onspace (x, 20))    
00497 
00498     
00499 def dumpPerLSLumi (lumidata):
00500     datatodump = []
00501     for perrundata in lumidata:
00502         runnumber = perrundata[0]
00503         deadtable = perrundata[2]
00504         lumiresult = lsBylsLumi (deadtable)
00505         for lsnum, dataperls in lumiresult.items():
00506             rowdata = []
00507             if len (dataperls) == 0:
00508                 rowdata += [str (runnumber), str (lsnum), 'N/A', 'N/A']
00509             else:
00510                 rowdata += [str (runnumber), str (lsnum), dataperls[0], dataperls[1]]
00511             if len (dataperls) > 2:
00512                 rowdata.extend ( flatten (dataperls[2:]) )
00513             datatodump.append (rowdata)
00514     return datatodump
00515 
00516 
00517 def printRecordedLumi (lumidata, isVerbose = False, hltpath = ''):
00518     datatoprint = []
00519     totalrow = []
00520     labels = [ ('Run', 'HLT path', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'))]
00521     lastrowlabels = [ ('Selected LS', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'))]
00522     if len (hltpath) != 0 and hltpath != 'all':
00523         lastrowlabels = [ ('Selected LS', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'),
00524                            'Effective '+u' (/\u03bcb) '.encode ('utf-8')+hltpath)]
00525     if isVerbose:
00526         labels = [ ('Run', 'HLT-path', 'L1-bit', 'L1-presc', 'HLT-presc', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'))]
00527     totalSelectedLS = 0
00528     totalRecorded = 0.0
00529     totalRecordedInPath = 0.0
00530     
00531     for dataperRun in lumidata:
00532         runnum = dataperRun[0]
00533         if len (dataperRun[1]) == 0:
00534             rowdata = []
00535             rowdata += [str (runnum)]+2*['N/A']
00536             datatoprint.append (rowdata)
00537             continue
00538         perlsdata = dataperRun[2]
00539         totalSelectedLS = totalSelectedLS+len (perlsdata)
00540         recordedLumi = 0.0
00541         #norbits = perlsdata.values()[0][3]
00542         recordedLumi = calculateTotalRecorded (perlsdata)
00543         totalRecorded = totalRecorded+recordedLumi
00544         trgdict = dataperRun[1]
00545         effective = calculateEffective (trgdict, recordedLumi)
00546         if trgdict.has_key (hltpath) and effective.has_key (hltpath):
00547             rowdata = []
00548             l1bit = trgdict[hltpath][0]
00549             if len (trgdict[hltpath]) !=  3:
00550                 if not isVerbose:
00551                     rowdata += [str (runnum), hltpath, 'N/A']
00552                 else:
00553                     rowdata += [str (runnum), hltpath, l1bit, 'N/A', 'N/A', 'N/A']
00554             else:
00555                 if not isVerbose:
00556                     rowdata += [str (runnum), hltpath, '%.3f'% (effective[hltpath])]
00557                 else:
00558                     hltprescale = trgdict[hltpath][1]
00559                     l1prescale = trgdict[hltpath][2]
00560                     rowdata += [str (runnum), hltpath, l1bit, str (l1prescale), str (hltprescale),
00561                                 '%.3f'% (effective[hltpath])]
00562                 totalRecordedInPath = totalRecordedInPath+effective[hltpath]
00563             datatoprint.append (rowdata)
00564             continue
00565         
00566         for trg, trgdata in trgdict.items():
00567             #print trg, trgdata
00568             rowdata = []                    
00569             if trg == trgdict.keys()[0]:
00570                 rowdata += [str (runnum)]
00571             else:
00572                 rowdata += ['']
00573             l1bit = trgdata[0]
00574             if len (trgdata) == 3:
00575                 if not isVerbose:
00576                     rowdata += [trg, '%.3f'% (effective[trg])]
00577                 else:
00578                     hltprescale = trgdata[1]
00579                     l1prescale = trgdata[2]
00580                     rowdata += [trg, l1bit, str (l1prescale), str (hltprescale), '%.3f'% (effective[trg])]
00581             else:
00582                 if not isVerbose:
00583                     rowdata += [trg, 'N/A']
00584                 else:
00585                     rowdata += [trg, l1bit, 'N/A', 'N/A', '%.3f'% (effective[trg])]
00586             datatoprint.append (rowdata)
00587     #print datatoprint
00588     print ' ==  = '
00589     print tablePrinter.indent (labels+datatoprint, hasHeader = True, separateRows = False, prefix = '| ',
00590                                postfix = ' |', justify = 'right', delim = ' | ',
00591                                wrapfunc = lambda x: wrap_onspace_strict (x, 22))
00592 
00593     if len (hltpath) != 0 and hltpath != 'all':
00594         totalrow.append ([str (totalSelectedLS), '%.3f'% (totalRecorded), '%.3f'% (totalRecordedInPath)])
00595     else:
00596         totalrow.append ([str (totalSelectedLS), '%.3f'% (totalRecorded)])
00597     print ' ==  =  Total : '
00598     print tablePrinter.indent (lastrowlabels+totalrow, hasHeader = True, separateRows = False, prefix = '| ',
00599                                postfix = ' |', justify = 'right', delim = ' | ',
00600                                wrapfunc = lambda x: wrap_onspace (x, 20))    
00601     if isVerbose:
00602         deadtoprint = []
00603         deadtimelabels = [ ('Run', 'Lumi section : Dead fraction')]
00604 
00605         for dataperRun in lumidata:
00606             runnum = dataperRun[0]
00607             if len (dataperRun[1]) == 0:
00608                 deadtoprint.append ([str (runnum), 'N/A'])
00609                 continue
00610             perlsdata = dataperRun[2]
00611             #print 'perlsdata 2 : ', perlsdata
00612             deadT = getDeadfractions (perlsdata)
00613             t = ''
00614             for myls, de in deadT.items():
00615                 if de<0:
00616                     t += str (myls)+':nobeam '
00617                 else:
00618                     t += str (myls)+':'+'%.5f'% (de)+' '
00619             deadtoprint.append ([str (runnum), t])
00620         print ' ==  = '
00621         print tablePrinter.indent (deadtimelabels+deadtoprint, hasHeader = True, separateRows = True, prefix = '| ',
00622                                    postfix = ' |', justify = 'right', delim = ' | ',
00623                                    wrapfunc = lambda x: wrap_onspace (x, 80))
00624 
00625 
00626 def dumpRecordedLumi (lumidata, hltpath = ''):
00627     #labels = ['Run', 'HLT path', 'Recorded']
00628     datatodump = []
00629     for dataperRun in lumidata:
00630         runnum = dataperRun[0]
00631         if len (dataperRun[1]) == 0:
00632             rowdata = []
00633             rowdata += [str (runnum)]+2*['N/A']
00634             datatodump.append (rowdata)
00635             continue
00636         perlsdata = dataperRun[2]
00637         recordedLumi = 0.0
00638         #norbits = perlsdata.values()[0][3]
00639         recordedLumi = calculateTotalRecorded (perlsdata)
00640         trgdict = dataperRun[1]
00641         effective = calculateEffective (trgdict, recordedLumi)
00642         if trgdict.has_key (hltpath) and effective.has_key (hltpath):
00643             rowdata = []
00644             l1bit = trgdict[hltpath][0]
00645             if len (trgdict[hltpath]) !=  3:
00646                 rowdata += [str (runnum), hltpath, 'N/A']
00647             else:
00648                 hltprescale = trgdict[hltpath][1]
00649                 l1prescale = trgdict[hltpath][2]
00650                 rowdata += [str (runnum), hltpath, effective[hltpath]]
00651             datatodump.append (rowdata)
00652             continue
00653         
00654         for trg, trgdata in trgdict.items():
00655             #print trg, trgdata
00656             rowdata = []                    
00657             rowdata += [str (runnum)]
00658             l1bit = trgdata[0]
00659             if len (trgdata) == 3:
00660                 rowdata += [trg, effective[trg]]
00661             else:
00662                 rowdata += [trg, 'N/A']
00663             datatodump.append (rowdata)
00664     return datatodump
00665 
00666 
00667 def printOverviewData (delivered, recorded, hltpath = ''):
00668     if len (hltpath) == 0 or hltpath == 'all':
00669         toprowlabels = [ ('Run', 'Delivered LS', 'Delivered'+u' (/\u03bcb)'.encode ('utf-8'), 'Selected LS', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8') )]
00670         lastrowlabels = [ ('Delivered LS', 'Delivered'+u' (/\u03bcb)'.encode ('utf-8'), 'Selected LS', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8') ) ]
00671     else:
00672         toprowlabels = [ ('Run', 'Delivered LS', 'Delivered'+u' (/\u03bcb)'.encode ('utf-8'), 'Selected LS', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'), 'Effective'+u' (/\u03bcb) '.encode ('utf-8')+hltpath )]
00673         lastrowlabels = [ ('Delivered LS', 'Delivered'+u' (/\u03bcb)'.encode ('utf-8'), 'Selected LS', 'Recorded'+u' (/\u03bcb)'.encode ('utf-8'), 'Effective '+u' (/\u03bcb) '.encode ('utf-8')+hltpath)]
00674     datatable = []
00675     totaldata = []
00676     totalDeliveredLS = 0
00677     totalSelectedLS = 0
00678     totalDelivered = 0.0
00679     totalRecorded = 0.0
00680     totalRecordedInPath = 0.0
00681     totaltable = []
00682     for runidx, deliveredrowdata in enumerate (delivered):
00683         rowdata = []
00684         rowdata += [deliveredrowdata[0], deliveredrowdata[1], deliveredrowdata[2]]
00685         if deliveredrowdata[1] == 'N/A': #run does not exist
00686             if  hltpath != '' and hltpath != 'all':
00687                 rowdata += ['N/A', 'N/A', 'N/A']
00688             else:
00689                 rowdata += ['N/A', 'N/A']
00690             datatable.append (rowdata)
00691             continue
00692         totalDeliveredLS += int (deliveredrowdata[1])
00693         totalDelivered += float (deliveredrowdata[2])
00694         selectedls = recorded[runidx][2].keys()
00695         #print 'runidx ', runidx, deliveredrowdata
00696         #print 'selectedls ', selectedls
00697         if len (selectedls) == 0:
00698             selectedlsStr = '[]'
00699             recordedLumi = 0
00700             if  hltpath != '' and hltpath != 'all':
00701                 rowdata += [selectedlsStr, 'N/A', 'N/A']
00702             else:
00703                 rowdata += [selectedlsStr, 'N/A']
00704         else:
00705             selectedlsStr = splitlistToRangeString (selectedls)
00706             recordedLumi = calculateTotalRecorded (recorded[runidx][2])
00707             lumiinPaths = calculateEffective (recorded[runidx][1], recordedLumi)
00708             if hltpath != '' and hltpath != 'all':
00709                 if lumiinPaths.has_key (hltpath):
00710                     rowdata += [selectedlsStr, '%.3f'% (recordedLumi), '%.3f'% (lumiinPaths[hltpath])]
00711                     totalRecordedInPath += lumiinPaths[hltpath]
00712                 else:
00713                     rowdata += [selectedlsStr, '%.3f'% (recordedLumi), 'N/A']
00714             else:
00715                 #rowdata += [selectedlsStr, '%.3f'% (recordedLumi), '%.3f'% (recordedLumi)]
00716                 rowdata += [selectedlsStr, '%.3f'% (recordedLumi)]
00717         totalSelectedLS += len (selectedls)
00718         totalRecorded += recordedLumi
00719         datatable.append (rowdata)
00720 
00721     if hltpath != '' and hltpath != 'all':
00722         totaltable = [[str (totalDeliveredLS), '%.3f'% (totalDelivered), str (totalSelectedLS),
00723                        '%.3f'% (totalRecorded), '%.3f'% (totalRecordedInPath)]]
00724     else:
00725         totaltable = [[str (totalDeliveredLS), '%.3f'% (totalDelivered), str (totalSelectedLS),
00726                        '%.3f'% (totalRecorded)]]
00727     print tablePrinter.indent (toprowlabels+datatable, hasHeader = True, separateRows = False, prefix = '| ',
00728                                postfix = ' |', justify = 'right', delim = ' | ',
00729                                wrapfunc = lambda x: wrap_onspace (x, 20))
00730     print ' ==  =  Total : '
00731     print tablePrinter.indent (lastrowlabels+totaltable, hasHeader = True, separateRows = False, prefix = '| ',
00732                                postfix = ' |', justify = 'right', delim = ' | ',
00733                                wrapfunc = lambda x: wrap_onspace (x, 20))
00734 
00735 
00736 def dumpOverview (delivered, recorded, hltpath = ''):
00737     #toprowlabels = ['run', 'delivered', 'recorded', 'hltpath']
00738     datatable = []
00739     for runidx, deliveredrowdata in enumerate (delivered):
00740         rowdata = []
00741         rowdata += [deliveredrowdata[0], deliveredrowdata[2]]
00742         if deliveredrowdata[1] == 'N/A': #run does not exist
00743             rowdata += ['N/A', 'N/A']
00744             datatable.append (rowdata)
00745             continue
00746         recordedLumi = calculateTotalRecorded (recorded[runidx][2])
00747         lumiinPaths = calculateEffective (recorded[runidx][1], recordedLumi)
00748         if hltpath != '' and hltpath != 'all':
00749             if lumiinPaths.has_key (hltpath):
00750                 rowdata += [recordedLumi, lumiinPaths[hltpath]]
00751             else:
00752                 rowdata += [recordedLumi, 'N/A']
00753         else:
00754             rowdata += [recordedLumi, recordedLumi]
00755         datatable.append (rowdata)
00756     return datatable
00757 
00758 
00759 def xingLuminosityForRun (dbsession, runnum, parameters, lumiXingDict = {},
00760                           maxLumiSection = None):
00761     '''Given a run number and a minimum xing luminosity value,
00762     returns a dictionary (keyed by (run, lumi section)) where the
00763     value is a list of tuples of (xingID, xingLum).
00764 
00765     - For all xing luminosities, simply set minLumValue to 0.
00766 
00767     - If you want one dictionary for several runs, pass it in to
00768       "lumiXingDict"
00769 
00770 
00771     select 
00772     s.cmslsnum, d.bxlumivalue, d.bxlumierror, d.bxlumiquality, d.algoname from LUMIDETAIL d, LUMISUMMARY s where s.runnum = 133885 and d.algoname = 'OCC1' and s.lumisummary_id = d.lumisummary_id order by s.startorbit, s.cmslsnum
00773     '''
00774     try:
00775         runnum = int (runnum)
00776         dbsession.transaction().start (True)
00777         schema = dbsession.schema (parameters.lumischema)
00778         if not schema:
00779             raise 'cannot connect to schema ', parameters.lumischema
00780         detailOutput = coral.AttributeList()
00781         detailOutput.extend ('startorbit',    'unsigned int')
00782         detailOutput.extend ('cmslsnum',      'unsigned int')
00783         detailOutput.extend ('bxlumivalue',   'blob')
00784         detailOutput.extend ('bxlumierror',   'blob')
00785         detailOutput.extend ('bxlumiquality', 'blob')
00786         detailOutput.extend ('algoname',      'string')
00787         detailCondition = coral.AttributeList()
00788         detailCondition.extend ('runnum',   'unsigned int')
00789         detailCondition.extend ('algoname', 'string')
00790         detailCondition['runnum'].setData (runnum)
00791         detailCondition['algoname'].setData ('OCC1')
00792         query = schema.newQuery()
00793         query.addToTableList(nameDealer.lumisummaryTableName(), 's')
00794         query.addToTableList(nameDealer.lumidetailTableName(),  'd')
00795         query.addToOutputList ('s.STARTORBIT',    'startorbit')
00796         query.addToOutputList ('s.CMSLSNUM',      'cmslsnum')
00797         query.addToOutputList ('d.BXLUMIVALUE',   'bxlumivalue')
00798         query.addToOutputList ('d.BXLUMIERROR',   'bxlumierror')
00799         query.addToOutputList ('d.BXLUMIQUALITY', 'bxlumiquality')
00800         query.addToOutputList ('d.ALGONAME',      'algoname')
00801         query.setCondition ('s.RUNNUM =:runnum and d.ALGONAME =:algoname and s.LUMISUMMARY_ID=d.LUMISUMMARY_ID',detailCondition)
00802         query.addToOrderList ('s.CMSLSNUM')
00803         query.defineOutput (detailOutput)
00804         cursor = query.execute()
00805         count = 0
00806         while cursor.next():
00807             ## ## Note: If you are going to break out of this loop early,
00808             ## ## make sure you call cursor.close():
00809             ## 
00810             ## if count > 20 :
00811             ##     cursor.close()
00812             ##     break
00813             ## count  +=  1
00814             cmslsnum    = cursor.currentRow()['cmslsnum'].data()
00815             algoname    = cursor.currentRow()['algoname'].data()
00816             bxlumivalue = cursor.currentRow()['bxlumivalue'].data()
00817             startorbit  = cursor.currentRow()['startorbit'].data()
00818             
00819             if maxLumiSection and maxLumiSection < cmslsnum:
00820                 cursor.close()
00821                 break
00822             
00823             xingArray = array.array ('f')
00824             xingArray.fromstring( bxlumivalue.readline() )
00825             numPrinted = 0
00826             xingLum = []
00827             for index, lum in enumerate (xingArray):
00828                 lum  *=  parameters.normFactor
00829                 if lum < parameters.xingMinLum:
00830                     continue
00831                 xingLum.append( (index, lum) )
00832             lumiXingDict[ (runnum, cmslsnum) ] = xingLum
00833         del query
00834         dbsession.transaction().commit()
00835         return lumiXingDict      
00836     except Exception, e:
00837         print str (e)
00838         print "whoops"
00839         dbsession.transaction().rollback()
00840         del dbsession
00841 
00842 
00843 def flatten (obj):
00844     '''Given nested lists or tuples, returns a single flattened list'''
00845     result = []
00846     for piece in obj:
00847         if hasattr (piece, '__iter__') and not isinstance (piece, basestring):
00848             result.extend( flatten (piece) )
00849         else:
00850             result.append (piece)
00851     return result    
00852 
00853 
00854 def mergeXingLumi (triplet, xingLumiDict):
00855     '''Given general xing information and a xingLumiDict, the xing
00856     luminosity information is merged with the general information'''
00857     runNumber = triplet[0]
00858     deadTable = triplet[2]
00859     for lumi, lumiList in deadTable.iteritems():
00860         key = ( int(runNumber), int(lumi) )
00861         xingLumiValues = xingLumiDict.get (key)
00862         if xingLumiValues:
00863             lumiList.append( flatten (xingLumiValues) )
00864 
00865 
00866 def setupSession (connectString, siteconfpath, parameters, debug = False):
00867     '''returns database session'''
00868     connectparser = connectstrParser.connectstrParser (connectString)
00869     connectparser.parse()
00870     usedefaultfrontierconfig = False
00871     cacheconfigpath = ''
00872     if connectparser.needsitelocalinfo():
00873         if not siteconfpath:
00874             cacheconfigpath = os.environ['CMS_PATH']
00875             if cacheconfigpath:
00876                 cacheconfigpath = os.path.join (cacheconfigpath, 'SITECONF', 'local', 'JobConfig', 'site-local-config.xml')
00877             else:
00878                 usedefaultfrontierconfig = True
00879         else:
00880             cacheconfigpath = siteconfpath
00881             cacheconfigpath = os.path.join (cacheconfigpath, 'site-local-config.xml')
00882         ccp = cacheconfigParser.cacheconfigParser()
00883         if usedefaultfrontierconfig:
00884             ccp.parseString (parameters.defaultfrontierConfigString)
00885         else:
00886             ccp.parse (cacheconfigpath)
00887         connectString = connectparser.fullfrontierStr (connectparser.schemaname(), ccp.parameterdict())
00888     svc = coral.ConnectionService()
00889     if debug :
00890         msg = coral.MessageStream ('')
00891         msg.setMsgVerbosity (coral.message_Level_Debug)
00892         parameters.verbose = True
00893     session = svc.connect (connectString, accessMode = coral.access_ReadOnly)
00894     session.typeConverter().setCppTypeForSqlType ("unsigned int", "NUMBER (10)")
00895     session.typeConverter().setCppTypeForSqlType ("unsigned long long", "NUMBER (20)")
00896     return session, svc
00897 
00898 
00899 
00900 ###==============real api=====###
00901 
00902 def allruns(schemaHandle,requireRunsummary=True,requireLumisummary=False,requireTrg=False,requireHlt=False):
00903     '''
00904     find all runs in the DB. By default requires cmsrunsummary table contain the run. The condition can be loosed in situation where db loading failed on certain data portions.
00905     '''
00906     if not requireRunsummary and not requireLumiummary and not requireTrg and not requireHlt:
00907         print 'must require at least one table'
00908         raise
00909     runresult=[]
00910     runlist=[]
00911     numdups=0
00912     if requireRunsummary:
00913         numdups=numdups+1
00914         queryHandle=schemaHandle.newQuery()
00915         queryHandle.addToTableList(nameDealer.cmsrunsummaryTableName())
00916         queryHandle.addToOutputList("RUNNUM","run")
00917         #queryBind=coral.AttributeList()
00918         result=coral.AttributeList()
00919         result.extend("run","unsigned int")
00920         queryHandle.defineOutput(result)
00921         cursor=queryHandle.execute()
00922         while cursor.next():
00923             r=cursor.currentRow()['run'].data()
00924             runlist.append(r)
00925         del queryHandle
00926     if requireLumisummary:
00927         numdups=numdups+1
00928         queryHandle=schemaHandle.newQuery()
00929         queryHandle.addToTableList(nameDealer.lumisummaryTableName())
00930         queryHandle.addToOutputList("distinct RUNNUM","run")
00931         #queryBind=coral.AttributeList()
00932         result=coral.AttributeList()
00933         result.extend("run","unsigned int")
00934         queryHandle.defineOutput(result)
00935         cursor=queryHandle.execute()
00936         while cursor.next():
00937             r=cursor.currentRow()['run'].data()
00938             runlist.append(r)
00939         del queryHandle
00940     if requireTrg:
00941         numdups=numdups+1
00942         queryHandle=schemaHandle.newQuery()
00943         queryHandle.addToTableList(nameDealer.trgTableName())
00944         queryHandle.addToOutputList("distinct RUNNUM","run")
00945         #queryBind=coral.AttributeList()
00946         result=coral.AttributeList()
00947         result.extend("run","unsigned int")
00948         queryHandle.defineOutput(result)
00949         cursor=queryHandle.execute()
00950         while cursor.next():
00951             r=cursor.currentRow()['run'].data()
00952             runlist.append(r)
00953         del queryHandle
00954     if requireHlt:
00955         numdups=numdups+1
00956         queryHandle=schemaHandle.newQuery()
00957         queryHandle.addToTableList(nameDealer.hltTableName())
00958         queryHandle.addToOutputList("distinct RUNNUM","run")
00959         #queryBind=coral.AttributeList()
00960         result=coral.AttributeList()
00961         result.extend("run","unsigned int")
00962         queryHandle.defineOutput(result)
00963         cursor=queryHandle.execute()
00964         while cursor.next():
00965             r=cursor.currentRow()['run'].data()
00966             runlist.append(r)
00967         del queryHandle
00968     dupresult=CommonUtil.count_dups(runlist)
00969     for dup in dupresult:
00970         if dup[1]==numdups:
00971             runresult.append(dup[0])
00972     runresult.sort()
00973     return runresult
00974 
00975 def validation(queryHandle,run=None,cmsls=None):
00976     '''retrieve validation data per run or all
00977     input: run. if not run, retrive all; if cmslsnum selection list pesent, filter out unselected result
00978     output: {run:[[cmslsnum,status,comment]]}
00979     '''
00980     result={}
00981     queryHandle.addToTableList(nameDealer.lumivalidationTableName())
00982     queryHandle.addToOutputList('RUNNUM','runnum')
00983     queryHandle.addToOutputList('CMSLSNUM','cmslsnum')
00984     queryHandle.addToOutputList('FLAG','flag')
00985     queryHandle.addToOutputList('COMMENT','comment')
00986     if run:
00987         queryCondition='RUNNUM=:runnum'
00988         queryBind=coral.AttributeList()
00989         queryBind.extend('runnum','unsigned int')
00990         queryBind['runnum'].setData(run)
00991         queryHandle.setCondition(queryCondition,queryBind)
00992     queryResult=coral.AttributeList()
00993     queryResult.extend('runnum','unsigned int')
00994     queryResult.extend('cmslsnum','unsigned int')
00995     queryResult.extend('flag','string')
00996     queryResult.extend('comment','string')
00997     queryHandle.defineOutput(queryResult)
00998     cursor=queryHandle.execute()
00999     while cursor.next():
01000         runnum=cursor.currentRow()['runnum'].data()
01001         if not result.has_key(runnum):
01002             result[runnum]=[]
01003         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01004         flag=cursor.currentRow()['flag'].data()
01005         comment=cursor.currentRow()['comment'].data()
01006         result[runnum].append([cmslsnum,flag,comment])
01007     if run and cmsls and len(cmsls)!=0:
01008         selectedresult={}
01009         for runnum,perrundata in result.items():
01010             for lsdata in perrundata:
01011                 if lsdata[0] not in cmsls:
01012                     continue
01013                 if not selectedresult.has_key(runnum):
01014                     selectedresult[runnum]=[]
01015                 selectedresult[runnum].append(lsdata)
01016         return selectedresult
01017     else:
01018         return result
01019     
01020 def allfills(queryHandle,filtercrazy=True):
01021     '''select distinct fillnum from cmsrunsummary
01022     there are crazy fill numbers. we assume they are not valid runs
01023     '''
01024     result=[]
01025     queryHandle.addToTableList(nameDealer.cmsrunsummaryTableName())
01026     queryHandle.addToOutputList('distinct FILLNUM','fillnum')
01027     
01028     if filtercrazy:
01029         queryCondition='FILLNUM>:zero and FILLNUM<:crazybig'
01030         queryBind=coral.AttributeList()
01031         queryBind.extend('zero','unsigned int')
01032         queryBind.extend('crazybig','unsigned int')
01033         queryBind['zero'].setData(int(0))
01034         queryBind['crazybig'].setData(int(29701))
01035         queryHandle.setCondition(queryCondition,queryBind)
01036     queryResult=coral.AttributeList()
01037     queryResult.extend('fillnum','unsigned int')
01038     queryHandle.defineOutput(queryResult)
01039     cursor=queryHandle.execute()
01040     while cursor.next():
01041         result.append(cursor.currentRow()['fillnum'].data())
01042     result.sort()
01043     return result
01044 def runsummaryByrun(queryHandle,runnum):
01045     '''
01046     select fillnum,sequence,hltkey,to_char(starttime),to_char(stoptime) from cmsrunsummary where runnum=:runnum
01047     output: [fillnum,sequence,hltkey,starttime,stoptime]
01048     '''
01049     t=lumiTime.lumiTime()
01050     result=[]
01051     queryHandle.addToTableList(nameDealer.cmsrunsummaryTableName())
01052     queryCondition=coral.AttributeList()
01053     queryCondition.extend('runnum','unsigned int')
01054     queryCondition['runnum'].setData(int(runnum))
01055     queryHandle.addToOutputList('FILLNUM','fillnum')
01056     queryHandle.addToOutputList('SEQUENCE','sequence')
01057     queryHandle.addToOutputList('HLTKEY','hltkey')
01058     queryHandle.addToOutputList('to_char(STARTTIME,\''+t.coraltimefm+'\')','starttime')
01059     queryHandle.addToOutputList('to_char(STOPTIME,\''+t.coraltimefm+'\')','stoptime')
01060     queryHandle.setCondition('RUNNUM=:runnum',queryCondition)
01061     queryResult=coral.AttributeList()
01062     queryResult.extend('fillnum','unsigned int')
01063     queryResult.extend('sequence','string')
01064     queryResult.extend('hltkey','string')
01065     queryResult.extend('starttime','string')
01066     queryResult.extend('stoptime','string')
01067     queryHandle.defineOutput(queryResult)
01068     cursor=queryHandle.execute()
01069     while cursor.next():
01070         result.append(cursor.currentRow()['fillnum'].data())
01071         result.append(cursor.currentRow()['sequence'].data())
01072         result.append(cursor.currentRow()['hltkey'].data())
01073         result.append(cursor.currentRow()['starttime'].data())
01074         result.append(cursor.currentRow()['stoptime'].data())
01075     #if len(result)!=5:
01076     #    print 'wrong runsummary result'
01077     #    raise
01078     return result
01079 
01080 def lumisummaryByrun(queryHandle,runnum,lumiversion,beamstatus=None,beamenergy=None,beamenergyfluctuation=0.09):
01081     '''
01082     one can impose beamstatus, beamenergy selections at the SQL query level or process them later from the general result
01083     select cmslsnum,instlumi,numorbit,startorbit,beamstatus,beamenery from lumisummary where runnum=:runnum and lumiversion=:lumiversion order by startorbit;
01084     output: [[cmslsnum,instlumi,numorbit,startorbit,beamstatus,beamenergy,cmsalive]]
01085     Note: the non-cmsalive LS are included in the result
01086     '''
01087     result=[]
01088     queryHandle.addToTableList(nameDealer.lumisummaryTableName())
01089     queryCondition=coral.AttributeList()
01090     queryCondition.extend('runnum','unsigned int')
01091     queryCondition.extend('lumiversion','string')
01092     conditionstring='RUNNUM=:runnum and LUMIVERSION=:lumiversion'
01093     queryCondition['runnum'].setData(int(runnum))
01094     queryCondition['lumiversion'].setData(lumiversion)
01095     queryHandle.addToOutputList('CMSLSNUM','cmslsnum')
01096     queryHandle.addToOutputList('INSTLUMI','instlumi')
01097     queryHandle.addToOutputList('NUMORBIT','numorbit')
01098     queryHandle.addToOutputList('STARTORBIT','startorbit')
01099     queryHandle.addToOutputList('BEAMSTATUS','beamstatus')
01100     queryHandle.addToOutputList('BEAMENERGY','beamenergy')
01101     queryHandle.addToOutputList('CMSALIVE','cmsalive')
01102     if beamstatus and len(beamstatus)!=0:
01103         conditionstring=conditionstring+' and BEAMSTATUS=:beamstatus'
01104         queryCondition.extend('beamstatus','string')
01105         queryCondition['beamstatus'].setData(beamstatus)
01106     if beamenergy:
01107         minBeamenergy=float(beamenergy*(1.0-beamenergyfluctuation))
01108         maxBeamenergy=float(beamenergy*(1.0+beamenergyfluctuation))
01109         conditionstring=conditionstring+' and BEAMENERGY>:minBeamenergy and BEAMENERGY<:maxBeamenergy'
01110         queryCondition.extend('minBeamenergy','float')
01111         queryCondition.extend('maxBeamenergy','float')
01112         queryCondition['minBeamenergy'].setData(float(minBeamenergy))
01113         queryCondition['maxBeamenergy'].setData(float(maxBeamenergy))
01114     queryResult=coral.AttributeList()
01115     queryResult.extend('cmslsnum','unsigned int')
01116     queryResult.extend('instlumi','float')
01117     queryResult.extend('numorbit','unsigned int')
01118     queryResult.extend('startorbit','unsigned int')
01119     queryResult.extend('beamstatus','string')
01120     queryResult.extend('beamenergy','float')
01121     queryResult.extend('cmsalive','unsigned int')
01122     queryHandle.defineOutput(queryResult)
01123     queryHandle.setCondition(conditionstring,queryCondition)
01124     queryHandle.addToOrderList('startorbit')
01125     cursor=queryHandle.execute()
01126     while cursor.next():
01127         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01128         instlumi=cursor.currentRow()['instlumi'].data()
01129         numorbit=cursor.currentRow()['numorbit'].data()
01130         startorbit=cursor.currentRow()['startorbit'].data()
01131         beamstatus=cursor.currentRow()['beamstatus'].data()
01132         beamenergy=cursor.currentRow()['beamenergy'].data()
01133         cmsalive=cursor.currentRow()['cmsalive'].data()
01134         result.append([cmslsnum,instlumi,numorbit,startorbit,beamstatus,beamenergy,cmsalive])
01135     return result
01136 
01137 def lumisumByrun(queryHandle,runnum,lumiversion,beamstatus=None,beamenergy=None,beamenergyfluctuation=0.09):
01138     '''
01139     beamenergy unit : GeV
01140     beamenergyfluctuation : fraction allowed to fluctuate around beamenergy value
01141     select sum(instlumi) from lumisummary where runnum=:runnum and lumiversion=:lumiversion
01142     output: float totallumi
01143     Note: the output is the raw result, need to apply LS length in time(sec)
01144     '''
01145     result=0.0
01146     queryHandle.addToTableList(nameDealer.lumisummaryTableName())
01147     queryCondition=coral.AttributeList()
01148     queryCondition.extend('runnum','unsigned int')
01149     queryCondition.extend('lumiversion','string')
01150     
01151     queryCondition['runnum'].setData(int(runnum))
01152     queryCondition['lumiversion'].setData(lumiversion)
01153     queryHandle.addToOutputList('sum(INSTLUMI)','lumitotal')
01154     conditionstring='RUNNUM=:runnum and LUMIVERSION=:lumiversion'
01155     if beamstatus and len(beamstatus)!=0:
01156         conditionstring=conditionstring+' and BEAMSTATUS=:beamstatus'
01157         queryCondition.extend('beamstatus','string')
01158         queryCondition['beamstatus'].setData(beamstatus)
01159     if beamenergy and beamenergy!=0.0:
01160         minBeamenergy=float(beamenergy*(1.0-beamenergyfluctuation))
01161         maxBeamenergy=float(beamenergy*(1.0+beamenergyfluctuation))
01162         conditionstring=conditionstring+' and BEAMENERGY>:minBeamenergy and BEAMENERGY<:maxBeamenergy'
01163         queryCondition.extend('minBeamenergy','float')
01164         queryCondition.extend('maxBeamenergy','float')
01165         queryCondition['minBeamenergy'].setData(float(minBeamenergy))
01166         queryCondition['maxBeamenergy'].setData(float(maxBeamenergy))
01167     queryHandle.setCondition(conditionstring,queryCondition)
01168     queryResult=coral.AttributeList()
01169     queryResult.extend('lumitotal','float')
01170     queryHandle.defineOutput(queryResult)
01171     cursor=queryHandle.execute()
01172     while cursor.next():
01173         result=cursor.currentRow()['lumitotal'].data()
01174     return result
01175 
01176 def trgbitzeroByrun(queryHandle,runnum):
01177     '''
01178     select cmslsnum,trgcount,deadtime,bitname,prescale from trg where runnum=:runnum and bitnum=0;
01179     output: {cmslsnum:[trgcount,deadtime,bitname,prescale]}
01180     '''
01181     result={}
01182     queryHandle.addToTableList(nameDealer.trgTableName())
01183     queryCondition=coral.AttributeList()
01184     queryCondition.extend('runnum','unsigned int')
01185     queryCondition.extend('bitnum','unsigned int')
01186     queryCondition['runnum'].setData(int(runnum))
01187     queryCondition['bitnum'].setData(int(0))
01188     queryHandle.addToOutputList('CMSLSNUM','cmslsnum')
01189     queryHandle.addToOutputList('TRGCOUNT','trgcount')
01190     queryHandle.addToOutputList('DEADTIME','deadtime')
01191     queryHandle.addToOutputList('BITNAME','bitname')
01192     queryHandle.addToOutputList('PRESCALE','prescale')
01193     queryHandle.setCondition('RUNNUM=:runnum and BITNUM=:bitnum',queryCondition)
01194     queryResult=coral.AttributeList()
01195     queryResult.extend('cmslsnum','unsigned int')
01196     queryResult.extend('trgcount','unsigned int')
01197     queryResult.extend('deadtime','unsigned int')
01198     queryResult.extend('bitname','string')
01199     queryResult.extend('prescale','unsigned int')
01200     queryHandle.defineOutput(queryResult)
01201     cursor=queryHandle.execute()
01202     while cursor.next():
01203         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01204         trgcount=cursor.currentRow()['trgcount'].data()
01205         deadtime=cursor.currentRow()['deadtime'].data()
01206         bitname=cursor.currentRow()['bitname'].data()
01207         prescale=cursor.currentRow()['prescale'].data()
01208         if not result.has_key(cmslsnum):
01209             result[cmslsnum]=[trgcount,deadtime,bitname,prescale]
01210     return result
01211 
01212 def lumisummarytrgbitzeroByrun(queryHandle,runnum,lumiversion,beamstatus=None,beamenergy=None,beamenergyfluctuation=0.09):
01213     '''
01214     select l.cmslsnum,l.instlumi,l.numorbit,l.startorbit,l.beamstatus,l.beamenery,t.trgcount,t.deadtime,t.bitname,t.prescale from trg t,lumisummary l where t.bitnum=:bitnum and l.runnum=:runnum and l.lumiversion=:lumiversion and l.runnum=t.runnum and t.cmslsnum=l.cmslsnum; 
01215     Everything you ever need to know about bitzero and avg luminosity. Since we do not know if joint query is better of sperate, support both.
01216     output: {cmslsnum:[instlumi,numorbit,startorbit,beamstatus,beamenergy,bitzerocount,deadtime,bitname,prescale]}
01217     Note: only cmsalive LS are included in the result. Therefore, this function cannot be used for calculating delivered!
01218     '''
01219     result={}
01220     queryHandle.addToTableList(nameDealer.trgTableName(),'t')
01221     queryHandle.addToTableList(nameDealer.lumisummaryTableName(),'l')
01222     queryCondition=coral.AttributeList()
01223     queryCondition.extend('bitnum','unsigned int')
01224     queryCondition.extend('runnum','unsigned int')
01225     queryCondition.extend('lumiversion','string')
01226     queryCondition['bitnum'].setData(int(0))        
01227     queryCondition['runnum'].setData(int(runnum))
01228     queryCondition['lumiversion'].setData(lumiversion)
01229     
01230     queryHandle.addToOutputList('l.CMSLSNUM','cmslsnum')
01231     queryHandle.addToOutputList('l.INSTLUMI','instlumi')
01232     queryHandle.addToOutputList('l.NUMORBIT','numorbit')
01233     queryHandle.addToOutputList('l.STARTORBIT','startorbit')
01234     queryHandle.addToOutputList('l.BEAMSTATUS','beamstatus')
01235     queryHandle.addToOutputList('l.BEAMENERGY','beamenergy')
01236     queryHandle.addToOutputList('t.TRGCOUNT','trgcount')
01237     queryHandle.addToOutputList('t.DEADTIME','deadtime')
01238     queryHandle.addToOutputList('t.BITNAME','bitname')
01239     queryHandle.addToOutputList('t.PRESCALE','prescale')
01240     conditionstring='t.BITNUM=:bitnum and l.RUNNUM=:runnum and l.LUMIVERSION=:lumiversion and l.RUNNUM=t.RUNNUM and t.CMSLSNUM=l.CMSLSNUM'
01241     if beamstatus and len(beamstatus)!=0:
01242         conditionstring=conditionstring+' and l.BEAMSTATUS=:beamstatus'
01243         queryCondition.extend('beamstatus','string')
01244         queryCondition['beamstatus'].setData(beamstatus)
01245     if beamenergy and beamenergy!=0.0:
01246         minBeamenergy=float(beamenergy*(1-beamenergyfluctuation))
01247         maxBeamenergy=float(beamenergy*(1+beamenergyfluctuation))
01248         conditionstring=conditionstring+' and l.BEAMENERGY>:minBeamenergy and l.BEAMENERGY<:maxBeamenergy'
01249         queryCondition.extend('minBeamenergy','float')
01250         queryCondition.extend('maxBeamenergy','float')
01251         queryCondition['minBeamenergy'].setData(float(minBeamenergy))
01252         queryCondition['maxBeamenergy'].setData(float(maxBeamenergy))
01253     queryHandle.setCondition(conditionstring,queryCondition)
01254     queryResult=coral.AttributeList()
01255     queryResult.extend('cmslsnum','unsigned int')
01256     queryResult.extend('instlumi','float')
01257     queryResult.extend('numorbit','unsigned int')
01258     queryResult.extend('startorbit','unsigned int')
01259     queryResult.extend('beamstatus','string')
01260     queryResult.extend('beamenergy','float')  
01261     queryResult.extend('trgcount','unsigned int')
01262     queryResult.extend('deadtime','unsigned int')
01263     queryResult.extend('bitname','string')
01264     queryResult.extend('prescale','unsigned int')
01265     queryHandle.defineOutput(queryResult)
01266     cursor=queryHandle.execute()
01267     while cursor.next():
01268         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01269         instlumi=cursor.currentRow()['instlumi'].data()
01270         numorbit=cursor.currentRow()['numorbit'].data()
01271         startorbit=cursor.currentRow()['startorbit'].data()
01272         beamstatus=cursor.currentRow()['beamstatus'].data()
01273         beamenergy=cursor.currentRow()['beamenergy'].data()
01274         trgcount=cursor.currentRow()['trgcount'].data()
01275         deadtime=cursor.currentRow()['deadtime'].data()
01276         bitname=cursor.currentRow()['bitname'].data()
01277         prescale=cursor.currentRow()['prescale'].data()
01278         if not result.has_key(cmslsnum):
01279             result[cmslsnum]=[instlumi,numorbit,startorbit,beamstatus,beamenergy,trgcount,deadtime,bitname,prescale]
01280     return result
01281 
01282 def trgBybitnameByrun(queryHandle,runnum,bitname):
01283     '''
01284     select cmslsnum,trgcount,deadtime,bitnum,prescale from trg where runnum=:runnum and bitname=:bitname;
01285     output: {cmslsnum:[trgcount,deadtime,bitnum,prescale]}
01286     '''
01287     result={}
01288     queryHandle.addToTableList(nameDealer.trgTableName())
01289     queryCondition=coral.AttributeList()
01290     queryCondition.extend('runnum','unsigned int')
01291     queryCondition.extend('bitname','string')
01292     queryCondition['runnum'].setData(int(runnum))
01293     queryCondition['bitname'].setData(bitname)        
01294     queryHandle.addToOutputList('CMSLSNUM','cmslsnum')
01295     queryHandle.addToOutputList('TRGCOUNT','trgcount')
01296     queryHandle.addToOutputList('DEADTIME','deadtime')
01297     queryHandle.addToOutputList('BITNUM','bitnum')
01298     queryHandle.addToOutputList('PRESCALE','prescale')
01299     queryHandle.setCondition('RUNNUM=:runnum and BITNAME=:bitname',queryCondition)
01300     queryResult=coral.AttributeList()
01301     queryResult.extend('cmslsnum','unsigned int')
01302     queryResult.extend('trgcount','unsigned int')
01303     queryResult.extend('deadtime','unsigned long long')
01304     queryResult.extend('bitnum','unsigned int')
01305     queryResult.extend('prescale','unsigned int')
01306     queryHandle.defineOutput(queryResult)
01307     cursor=queryHandle.execute()
01308     while cursor.next():
01309         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01310         trgcount=cursor.currentRow()['trgcount'].data()
01311         deadtime=cursor.currentRow()['deadtime'].data()
01312         bitnum=cursor.currentRow()['bitnum'].data()
01313         prescale=cursor.currentRow()['prescale'].data()
01314         if not result.has_key(cmslsnum):
01315             result[cmslsnum]=[trgcount,deadtime,bitnum,prescale]
01316     return result
01317 
01318 def trgAllbitsByrun(queryHandle,runnum):
01319     '''
01320     all you ever want to know about trigger
01321     select cmslsnum,trgcount,deadtime,bitnum,bitname,prescale from trg where runnum=:runnum order by  bitnum,cmslsnum
01322     this can be changed to blob query later
01323     output: {cmslsnum:{bitname:[bitnum,trgcount,deadtime,prescale]}}
01324     '''
01325     result={}
01326     queryHandle.addToTableList(nameDealer.trgTableName())
01327     queryCondition=coral.AttributeList()
01328     queryCondition.extend('runnum','unsigned int')
01329     queryCondition['runnum'].setData(int(runnum))
01330     queryHandle.addToOutputList('cmslsnum')
01331     queryHandle.addToOutputList('trgcount')
01332     queryHandle.addToOutputList('deadtime')
01333     queryHandle.addToOutputList('bitnum')
01334     queryHandle.addToOutputList('bitname')
01335     queryHandle.addToOutputList('prescale')
01336     queryHandle.setCondition('runnum=:runnum',queryCondition)
01337     queryResult=coral.AttributeList()
01338     queryResult.extend('cmslsnum','unsigned int')
01339     queryResult.extend('trgcount','unsigned int')
01340     queryResult.extend('deadtime','unsigned long long')
01341     queryResult.extend('bitnum','unsigned int')
01342     queryResult.extend('bitname','string')
01343     queryResult.extend('prescale','unsigned int')
01344     queryHandle.defineOutput(queryResult)
01345     queryHandle.addToOrderList('bitnum')
01346     queryHandle.addToOrderList('cmslsnum')
01347     cursor=queryHandle.execute()
01348     while cursor.next():
01349         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01350         trgcount=cursor.currentRow()['trgcount'].data()
01351         deadtime=cursor.currentRow()['deadtime'].data()
01352         bitnum=cursor.currentRow()['bitnum'].data()
01353         bitname=cursor.currentRow()['bitname'].data()
01354         prescale=cursor.currentRow()['prescale'].data()
01355         if not result.has_key(cmslsnum):
01356             dataperLS={}
01357             dataperLS[bitname]=[bitnum,trgcount,deadtime,prescale]
01358             result[cmslsnum]=dataperLS
01359         else:
01360             result[cmslsnum][bitname]=[bitnum,trgcount,deadtime,prescale]
01361     return result
01362 
01363 
01364 def hltBypathByrun(queryHandle,runnum,hltpath):
01365     '''
01366     select cmslsnum,inputcount,acceptcount,prescale from hlt where runnum=:runnum and pathname=:pathname
01367     output: {cmslsnum:[inputcount,acceptcount,prescale]}
01368     '''
01369     result={}
01370     queryHandle.addToTableList(nameDealer.hltTableName())
01371     queryCondition=coral.AttributeList()
01372     queryCondition.extend('runnum','unsigned int')
01373     queryCondition.extend('pathname','string')
01374     queryCondition['runnum'].setData(int(runnum))
01375     queryCondition['pathname'].setData(hltpath)
01376     queryHandle.addToOutputList('CMSLSNUM','cmslsnum')
01377     queryHandle.addToOutputList('INPUTCOUNT','inputcount')
01378     queryHandle.addToOutputList('ACCEPTCOUNT','acceptcount')
01379     queryHandle.addToOutputList('PRESCALE','prescale')
01380     queryHandle.setCondition('RUNNUM=:runnum and PATHNAME=:pathname',queryCondition)
01381     queryResult=coral.AttributeList()
01382     queryResult.extend('cmslsnum','unsigned int')
01383     queryResult.extend('inputcount','unsigned int')
01384     queryResult.extend('acceptcount','unsigned int')
01385     queryResult.extend('prescale','unsigned int')
01386     queryHandle.defineOutput(queryResult)
01387     cursor=queryHandle.execute()
01388     while cursor.next():
01389         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01390         inputcount=cursor.currentRow()['inputcount'].data()
01391         acceptcount=cursor.currentRow()['acceptcount'].data()
01392         prescale=cursor.currentRow()['prescale'].data()
01393         if not result.has_key(cmslsnum):
01394             result[cmslsnum]=[inputcount,acceptcount,prescale]
01395     return result
01396 
01397 def hltAllpathByrun(queryHandle,runnum):
01398     '''
01399     select cmslsnum,inputcount,acceptcount,prescale,pathname from hlt where runnum=:runnum
01400     this can be changed to blob query later
01401     output: {cmslsnum:{pathname:[inputcount,acceptcount,prescale]}}
01402     '''
01403     result={}
01404     queryHandle.addToTableList(nameDealer.hltTableName())
01405     queryCondition=coral.AttributeList()
01406     queryCondition.extend('runnum','unsigned int')
01407     queryCondition['runnum'].setData(int(runnum))
01408     queryHandle.addToOutputList('CMSLSNUM','cmslsnum')
01409     queryHandle.addToOutputList('INPUTCOUNT','inputcount')
01410     queryHandle.addToOutputList('ACCEPTCOUNT','acceptcount')
01411     queryHandle.addToOutputList('PRESCALE','prescale')
01412     queryHandle.addToOutputList('PATHNAME','pathname')
01413     queryHandle.setCondition('RUNNUM=:runnum',queryCondition)
01414     queryResult=coral.AttributeList()
01415     queryResult.extend('cmslsnum','unsigned int')
01416     queryResult.extend('inputcount','unsigned int')
01417     queryResult.extend('acceptcount','unsigned int')
01418     queryResult.extend('prescale','unsigned int')
01419     queryResult.extend('pathname','string')
01420     queryHandle.defineOutput(queryResult)
01421     cursor=queryHandle.execute()
01422     while cursor.next():
01423         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01424         inputcount=cursor.currentRow()['inputcount'].data()
01425         acceptcount=cursor.currentRow()['acceptcount'].data()
01426         prescale=cursor.currentRow()['prescale'].data()
01427         pathname=cursor.currentRow()['pathname'].data()
01428         if not result.has_key(cmslsnum):
01429             dataperLS={}
01430             dataperLS[pathname]=[inputcount,acceptcount,prescale]
01431             result[cmslsnum]=dataperLS
01432         else:
01433             result[cmslsnum][pathname]=[inputcount,acceptcount,prescale]
01434     return result
01435 
01436 
01437 def beamIntensityForRun(query,parameters,runnum):
01438     '''
01439     select CMSBXINDEXBLOB,BEAMINTENSITYBLOB_1,BEAMINTENSITYBLOB_2 from LUMISUMMARY where runnum=146315 and LUMIVERSION='0001'
01440     
01441     output : result {startorbit: [(bxidx,beam1intensity,beam2intensity)]}
01442     '''
01443     result={} #{startorbit:[(bxidx,occlumi,occlumierr,beam1intensity,beam2intensity)]}
01444     
01445     lumisummaryOutput=coral.AttributeList()
01446     lumisummaryOutput.extend('cmslsnum','unsigned int')
01447     lumisummaryOutput.extend('startorbit','unsigned int')
01448     lumisummaryOutput.extend('bxindexblob','blob');
01449     lumisummaryOutput.extend('beamintensityblob1','blob');
01450     lumisummaryOutput.extend('beamintensityblob2','blob');
01451     condition=coral.AttributeList()
01452     condition.extend('runnum','unsigned int')
01453     condition.extend('lumiversion','string')
01454     condition['runnum'].setData(int(runnum))
01455     condition['lumiversion'].setData(parameters.lumiversion)
01456     
01457     query.addToTableList(parameters.lumisummaryname)
01458     query.addToOutputList('CMSLSNUM','cmslsnum')
01459     query.addToOutputList('STARTORBIT','startorbit')
01460     query.addToOutputList('CMSBXINDEXBLOB','bxindexblob')
01461     query.addToOutputList('BEAMINTENSITYBLOB_1','beamintensityblob1')
01462     query.addToOutputList('BEAMINTENSITYBLOB_2','beamintensityblob2')
01463     query.setCondition('RUNNUM=:runnum AND LUMIVERSION=:lumiversion',condition)
01464     query.defineOutput(lumisummaryOutput)
01465     cursor=query.execute()
01466     while cursor.next():
01467         #cmslsnum=cursor.currentRow()['cmslsnum'].data()
01468         startorbit=cursor.currentRow()['startorbit'].data()
01469         if not cursor.currentRow()["bxindexblob"].isNull():
01470             bxindexblob=cursor.currentRow()['bxindexblob'].data()
01471             beamintensityblob1=cursor.currentRow()['beamintensityblob1'].data()
01472             beamintensityblob2=cursor.currentRow()['beamintensityblob2'].data()
01473             if bxindexblob.readline() is not None and beamintensityblob1.readline() is not None and beamintensityblob2.readline() is not None:
01474                 bxidx=array.array('h')
01475                 bxidx.fromstring(bxindexblob.readline())
01476                 bb1=array.array('f')
01477                 bb1.fromstring(beamintensityblob1.readline())
01478                 bb2=array.array('f')
01479                 bb2.fromstring(beamintensityblob2.readline())
01480                 for index,bxidxvalue in enumerate(bxidx):
01481                     if not result.has_key(startorbit):
01482                         result[startorbit]=[]
01483                     b1intensity=bb1[index]
01484                     b2intensity=bb2[index]
01485                     result[startorbit].append((bxidxvalue,b1intensity,b2intensity))
01486     return result
01487     
01488 def calibratedDetailForRunLimitresult(query,parameters,runnum,algoname='OCC1'):
01489     '''select 
01490     s.cmslsnum,d.bxlumivalue,d.bxlumierror,d.bxlumiquality,d.algoname from LUMIDETAIL d,LUMISUMMARY s where s.runnum=133885 and d.algoname='OCC1' and s.lumisummary_id=d.lumisummary_id order by s.startorbit,s.cmslsnum
01491     result={(startorbit,cmslsnum):[(lumivalue,lumierr),]}
01492     '''
01493     result={}
01494     detailOutput=coral.AttributeList()
01495     detailOutput.extend('cmslsnum','unsigned int')
01496     detailOutput.extend('startorbit','unsigned int')
01497     detailOutput.extend('bxlumivalue','blob')
01498     detailOutput.extend('bxlumierror','blob')
01499     detailCondition=coral.AttributeList()
01500     detailCondition.extend('runnum','unsigned int')
01501     detailCondition.extend('algoname','string')
01502     detailCondition['runnum'].setData(runnum)
01503     detailCondition['algoname'].setData(algoname)
01504 
01505     query.addToTableList(parameters.lumisummaryname,'s')
01506     query.addToTableList(parameters.lumidetailname,'d')
01507     query.addToOutputList('s.CMSLSNUM','cmslsnum')
01508     query.addToOutputList('s.STARTORBIT','startorbit')
01509     query.addToOutputList('d.BXLUMIVALUE','bxlumivalue')
01510     query.addToOutputList('d.BXLUMIERROR','bxlumierror')
01511     query.addToOutputList('d.BXLUMIQUALITY','bxlumiquality')
01512     query.setCondition('s.RUNNUM=:runnum and d.ALGONAME=:algoname and s.LUMISUMMARY_ID=d.LUMISUMMARY_ID',detailCondition)
01513     query.defineOutput(detailOutput)
01514     cursor=query.execute()
01515     while cursor.next():
01516         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01517         bxlumivalue=cursor.currentRow()['bxlumivalue'].data()
01518         bxlumierror=cursor.currentRow()['bxlumierror'].data()
01519         startorbit=cursor.currentRow()['startorbit'].data()
01520         
01521         bxlumivalueArray=array.array('f')
01522         bxlumivalueArray.fromstring(bxlumivalue.readline())
01523         bxlumierrorArray=array.array('f')
01524         bxlumierrorArray.fromstring(bxlumierror.readline())
01525         xingLum=[]
01526         #apply selection criteria
01527         maxlumi=max(bxlumivalueArray)*parameters.normFactor
01528         for index,lum in enumerate(bxlumivalueArray):
01529             lum *= parameters.normFactor
01530             lumierror = bxlumierrorArray[index]*parameters.normFactor
01531             if lum<max(parameters.xingMinLum,maxlumi*0.2): 
01532                 continue
01533             xingLum.append( (index,lum,lumierror) )
01534             if len(xingLum)!=0:
01535                 result[(startorbit,cmslsnum)]=xingLum
01536     return result
01537    
01538 def lumidetailByrunByAlgo(queryHandle,runnum,algoname='OCC1'):
01539     '''
01540     select s.cmslsnum,d.bxlumivalue,d.bxlumierror,d.bxlumiquality,s.startorbit from LUMIDETAIL d,LUMISUMMARY s where s.runnum=:runnum and d.algoname=:algoname and s.lumisummary_id=d.lumisummary_id order by s.startorbit
01541     output: [[cmslsnum,bxlumivalue,bxlumierror,bxlumiquality,startorbit]]
01542     since the output is ordered by time, it has to be in seq list format
01543     '''
01544     result=[]
01545     queryHandle.addToTableList(nameDealer.lumidetailTableName(),'d')
01546     queryHandle.addToTableList(nameDealer.lumisummaryTableName(),'s')
01547     queryCondition=coral.AttributeList()
01548     queryCondition.extend('runnum','unsigned int')
01549     queryCondition.extend('algoname','string')
01550     queryCondition['runnum'].setData(int(runnum))
01551     queryCondition['algoname'].setData(algoname)
01552     queryHandle.addToOutputList('s.CMSLSNUM','cmslsnum')
01553     queryHandle.addToOutputList('d.BXLUMIVALUE','bxlumivalue')
01554     queryHandle.addToOutputList('d.BXLUMIERROR','bxlumierror')
01555     queryHandle.addToOutputList('d.BXLUMIQUALITY','bxlumiquality')
01556     queryHandle.addToOutputList('s.STARTORBIT','startorbit')
01557     queryHandle.setCondition('s.runnum=:runnum and d.algoname=:algoname and s.lumisummary_id=d.lumisummary_id',queryCondition)
01558     queryResult=coral.AttributeList()
01559     queryResult.extend('cmslsnum','unsigned int')
01560     queryResult.extend('bxlumivalue','blob')
01561     queryResult.extend('bxlumierror','blob')
01562     queryResult.extend('bxlumiquality','blob')
01563     queryResult.extend('startorbit','unsigned int')    
01564     queryHandle.addToOrderList('s.STARTORBIT')
01565     queryHandle.defineOutput(queryResult)
01566     cursor=queryHandle.execute()
01567     while cursor.next():
01568         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01569         bxlumivalue=cursor.currentRow()['bxlumivalue'].data()
01570         bxlumierror=cursor.currentRow()['bxlumierror'].data()
01571         bxlumiquality=cursor.currentRow()['bxlumiquality'].data()
01572         startorbit=cursor.currentRow()['startorbit'].data()
01573         result.append([cmslsnum,bxlumivalue,bxlumierror,bxlumiquality,startorbit])
01574     return result
01575 
01576 def lumidetailAllalgosByrun(queryHandle,runnum):
01577     '''
01578     select s.cmslsnum,d.bxlumivalue,d.bxlumierror,d.bxlumiquality,d.algoname,s.startorbit from LUMIDETAIL d,LUMISUMMARY s where s.runnum=:runnumber and s.lumisummary_id=d.lumisummary_id order by s.startorbit,d.algoname
01579     output: {algoname:{cmslsnum:[bxlumivalue,bxlumierror,bxlumiquality,startorbit]}}
01580     '''
01581     result={}
01582     queryHandle.addToTableList(nameDealer.lumidetailTableName(),'d')
01583     queryHandle.addToTableList(nameDealer.lumisummaryTableName(),'s')
01584     queryCondition=coral.AttributeList()
01585     queryCondition.extend('runnum','unsigned int')
01586     queryCondition['runnum'].setData(int(runnum))
01587     queryHandle.addToOutputList('s.CMSLSNUM','cmslsnum')
01588     queryHandle.addToOutputList('d.BXLUMIVALUE','bxlumivalue')
01589     queryHandle.addToOutputList('d.BXLUMIERROR','bxlumierror')
01590     queryHandle.addToOutputList('d.BXLUMIQUALITY','bxlumiquality')
01591     queryHandle.addToOutputList('d.ALGONAME','algoname')
01592     queryHandle.addToOutputList('s.STARTORBIT','startorbit')
01593     queryHandle.setCondition('s.RUNNUM=:runnum and s.LUMISUMMARY_ID=d.LUMISUMMARY_ID',queryCondition)
01594     queryResult=coral.AttributeList()
01595     queryResult.extend('cmslsnum','unsigned int')
01596     queryResult.extend('bxlumivalue','blob')
01597     queryResult.extend('bxlumierror','blob')
01598     queryResult.extend('bxlumiquality','blob')
01599     queryResult.extend('algoname','string')
01600     queryResult.extend('startorbit','unsigned int')    
01601     queryHandle.addToOrderList('startorbit')
01602     queryHandle.addToOrderList('algoname')
01603     queryHandle.defineOutput(queryResult)
01604     cursor=queryHandle.execute()
01605     while cursor.next():
01606         cmslsnum=cursor.currentRow()['cmslsnum'].data()
01607         bxlumivalue=cursor.currentRow()['bxlumivalue'].data()
01608         bxlumierror=cursor.currentRow()['bxlumierror'].data()
01609         bxlumiquality=cursor.currentRow()['bxlumiquality'].data()
01610         algoname=cursor.currentRow()['algoname'].data()
01611         startorbit=cursor.currentRow()['startorbit'].data()
01612         if not result.has_key(algoname):
01613             dataPerAlgo={}
01614             dataPerAlgo[cmslsnum]=[bxlumivalue,bxlumierror,bxlumiquality,startorbit]
01615             result[algoname]=dataPerAlgo
01616         else:
01617             result[algoname][cmslsnum]=[bxlumivalue,bxlumierror,bxlumiquality,startorbit]           
01618     return result
01619 
01620 def hlttrgMappingByrun(queryHandle,runnum):
01621     '''
01622     select m.hltpathname,m.l1seed from cmsrunsummary r,trghltmap m where r.runnum=:runnum and m.hltkey=r.hltkey
01623     output: {hltpath:l1seed}
01624     '''
01625     result={}
01626     queryHandle.addToTableList(nameDealer.cmsrunsummaryTableName(),'r')
01627     queryHandle.addToTableList(nameDealer.trghltMapTableName(),'m')
01628     queryCondition=coral.AttributeList()
01629     queryCondition.extend('runnum','unsigned int')
01630     queryCondition['runnum'].setData(int(runnum))
01631     queryHandle.addToOutputList('m.HLTPATHNAME','hltpathname')
01632     queryHandle.addToOutputList('m.L1SEED','l1seed')
01633     queryHandle.setCondition('r.RUNNUM=:runnum and m.HLTKEY=r.HLTKEY',queryCondition)
01634     queryResult=coral.AttributeList()
01635     queryResult.extend('hltpathname','string')
01636     queryResult.extend('l1seed','string')
01637     queryHandle.defineOutput(queryResult)
01638     cursor=queryHandle.execute()
01639     while cursor.next():
01640         hltpathname=cursor.currentRow()['hltpathname'].data()
01641         l1seed=cursor.currentRow()['l1seed'].data()
01642         if not result.has_key(hltpathname):
01643             result[hltpathname]=l1seed
01644     return result
01645 
01646 def runsByfillrange(queryHandle,minFill,maxFill):
01647     '''
01648     find all runs in the fill range inclusive
01649     select runnum,fillnum from cmsrunsummary where fillnum>=:minFill and fillnum<=:maxFill
01650     output: fillDict={fillnum:[runlist]}
01651     '''
01652     result={}
01653     queryHandle.addToTableList(nameDealer.cmsrunsummaryTableName())
01654     queryCondition=coral.AttributeList()
01655     queryCondition.extend('minFill','unsigned int')
01656     queryCondition.extend('maxFill','unsigned int')
01657     queryCondition['minFill'].setData(int(minFill))
01658     queryCondition['maxFill'].setData(int(maxFill))
01659     queryHandle.addToOutputList('RUNNUM','runnum')
01660     queryHandle.addToOutputList('FILLNUM','fillnum')
01661     queryHandle.setCondition('FILLNUM>=:minFill and FILLNUM<=:maxFill',queryCondition)
01662     queryResult=coral.AttributeList()
01663     queryResult.extend('runnum','unsigned int')
01664     queryResult.extend('fillnum','unsigned int')
01665     queryHandle.defineOutput(queryResult)
01666     cursor=queryHandle.execute()
01667     while cursor.next():
01668         runnum=cursor.currentRow()['runnum'].data()
01669         fillnum=cursor.currentRow()['fillnum'].data()
01670         if not result.has_key(fillnum):
01671             result[fillnum]=[runnum]
01672         else:
01673             result[fillnum].append(runnum)
01674     return result
01675 
01676 def runsByTimerange(queryHandle,minTime,maxTime):
01677     '''
01678     find all runs in the time range inclusive
01679     the selected run must have started after minTime and finished by maxTime
01680     select runnum,to_char(startTime),to_char(stopTime) from cmsrunsummary where startTime>=timestamp(minTime) and stopTime<=timestamp(maxTime);
01681     input: minTime,maxTime in python obj datetime.datetime
01682     output: {runnum:[starttime,stoptime]} return in python obj datetime.datetime
01683     '''
01684     t=lumiTime.lumiTime()
01685     result={}
01686     coralminTime=coral.TimeStamp(minTime.year,minTime.month,minTime.day,minTime.hour,minTime.minute,minTime.second,0)
01687     coralmaxTime=coral.TimeStamp(maxTime.year,maxTime.month,maxTime.day,maxTime.hour,maxTime.minute,maxTime.second,0)
01688     queryHandle.addToTableList(nameDealer.cmsrunsummaryTableName())
01689     queryCondition=coral.AttributeList()
01690     queryCondition.extend('minTime','time stamp')
01691     queryCondition.extend('maxTime','time stamp')
01692     queryCondition['minTime'].setData(coralminTime)
01693     queryCondition['maxTime'].setData(coralmaxTime)
01694     queryHandle.addToOutputList('RUNNUM','runnum')
01695     queryHandle.addToOutputList('TO_CHAR(STARTTIME,\''+t.coraltimefm+'\')','starttime')
01696     queryHandle.addToOutputList('TO_CHAR(STOPTIME,\''+t.coraltimefm+'\')','stoptime')
01697     queryHandle.setCondition('STARTTIME>=:minTime and STOPTIME<=:maxTime',queryCondition)
01698     queryResult=coral.AttributeList()
01699     queryResult.extend('runnum','unsigned int')
01700     queryResult.extend('starttime','string')
01701     queryResult.extend('stoptime','string')
01702     queryHandle.defineOutput(queryResult)
01703     cursor=queryHandle.execute()
01704     while cursor.next():
01705         runnum=cursor.currentRow()['runnum'].data()
01706         starttimeStr=cursor.currentRow()['starttime'].data()
01707         stoptimeStr=cursor.currentRow()['stoptime'].data()
01708         if not result.has_key(runnum):
01709             result[runnum]=[t.StrToDatetime(starttimeStr),t.StrToDatetime(stoptimeStr)]
01710     return result
01711     
01712 if __name__=='__main__':
01713     msg=coral.MessageStream('')
01714     #msg.setMsgVerbosity(coral.message_Level_Debug)
01715     msg.setMsgVerbosity(coral.message_Level_Error)
01716     os.environ['CORAL_AUTH_PATH']='/afs/cern.ch/cms/DB/lumi'
01717     svc = coral.ConnectionService()
01718     connectstr='oracle://cms_orcoff_prod/cms_lumi_prod'
01719     session=svc.connect(connectstr,accessMode=coral.access_ReadOnly)
01720     session.typeConverter().setCppTypeForSqlType("unsigned int","NUMBER(10)")
01721     session.typeConverter().setCppTypeForSqlType("unsigned long long","NUMBER(20)")
01722     session.transaction().start(True)
01723     schema=session.nominalSchema()
01724     allruns=allruns(schema,requireLumisummary=True,requireTrg=True,requireHlt=True)
01725     print 'allruns in runsummary and lumisummary and trg and hlt ',len(allruns)
01726     #q=schema.newQuery()
01727     #runsummaryOut=runsummaryByrun(q,139400)
01728     #del q
01729     #q=schema.newQuery()
01730     #lumisummaryOut=lumisummaryByrun(q,139400,'0001')
01731     #del q
01732     #q=schema.newQuery()
01733     #lumisummaryOutStablebeam7TeV=lumisummaryByrun(q,139400,'0001',beamstatus='STABLE BEAMS',beamenergy=3.5E003,beamenergyfluctuation=0.09)
01734     #del q
01735     #q=schema.newQuery()
01736     #lumitotal=lumisumByrun(q,139400,'0001')
01737     #del q
01738     #q=schema.newQuery()
01739     #lumitotalStablebeam7TeV=lumisumByrun(q,139400,'0001',beamstatus='STABLE BEAMS',beamenergy=3.5E003,beamenergyfluctuation=0.09)
01740     #del q
01741     #q=schema.newQuery()
01742     #trgbitzero=trgbitzeroByrun(q,139400)
01743     #del q
01744     #q=schema.newQuery()
01745     #lumijointrg=lumisummarytrgbitzeroByrun(q,135525,'0001')
01746     #del q
01747     #q=schema.newQuery()
01748     #lumijointrgStablebeam7TeV=lumisummarytrgbitzeroByrun(q,135525,'0001',beamstatus='STABLE BEAMS',beamenergy=3.5E003,beamenergyfluctuation=0.09)
01749     #del q
01750     #q=schema.newQuery()
01751     #trgforbit=trgBybitnameByrun(q,139400,'L1_ZeroBias')
01752     #del q
01753     #q=schema.newQuery()
01754     #trgallbits=trgAllbitsByrun(q,139400)
01755     #del q
01756     #q=schema.newQuery()
01757     #hltbypath=hltBypathByrun(q,139400,'HLT_Mu5')
01758     #del q
01759     #q=schema.newQuery()
01760     #hltallpath=hltAllpathByrun(q,139400)
01761     #del q
01762     #q=schema.newQuery()
01763     #hlttrgmap=hlttrgMappingByrun(q,139400)
01764     #del q
01765     #q=schema.newQuery()
01766     #occ1detail=lumidetailByrunByAlgo(q,139400,'OCC1')
01767     #del q
01768     #q=schema.newQuery()
01769     #alldetail=lumidetailAllalgosByrun(q,139400)
01770     #del q
01771     #q=schema.newQuery()
01772     #runsbyfill=runsByfillrange(q,1150,1170)
01773     #del q
01774     #now=datetime.datetime.now()
01775     #aweek=datetime.timedelta(weeks=1)
01776     #lastweek=now-aweek
01777     #print lastweek
01778     #q=schema.newQuery()
01779     #runsinaweek=runsByTimerange(q,lastweek,now)
01780     #del q
01781     q=schema.newQuery()
01782     allfills=allfills(q)
01783     del q
01784     session.transaction().commit()  
01785     del session
01786     del svc
01787     #print 'runsummaryByrun : ',runsummaryOut
01788     #print
01789     #print 'lumisummaryByrun : ',lumisummaryOut
01790     #print '######'
01791     #print 'lumisummaryByrun stable beams 7TeV : ',lumisummaryOutStablebeam7TeV
01792     #print '######'
01793     #print 'totallumi : ',lumitotal
01794     #print
01795     #print
01796     #print 'totallumi stable beam and 7TeV: ',lumitotalStablebeam7TeV
01797     #print
01798     #print 'trgbitzero : ',trgbitzero
01799     #print 
01800     #print 'lumijointrg : ', lumijointrg
01801     #print 'total LS : ',len(lumijointrg)
01802     #print 'lumijointrg stable beams 7TeV :', lumijointrgStablebeam7TeV
01803     #print 'total LS : ',len(lumijointrgStablebeam7TeV)
01804     #print 'trgforbit L1_ZeroBias ',trgforbit
01805     #print
01806     #print 'trgallbits ',trgallbits[1] #big query. be aware of speed
01807     #print
01808     #print 'hltforpath HLT_Mu5',hltbypath
01809     #print
01810     #print 'hltallpath ',hltallpath
01811     #print
01812     #print 'hlttrgmap ',hlttrgmap
01813     #print
01814     #print 'lumidetail occ1 ',len(occ1detail)
01815     #print
01816     #print 'runsbyfill ',runsbyfill
01817     #print
01818     #print 'runsinaweek ',runsinaweek.keys()
01819     print 'all fills ',allfills