CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
lumiValidate.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 VERSION='1.00'
3 import os,sys
4 import coral
5 import json,csv
6 #import optparse
7 from RecoLuminosity.LumiDB import inputFilesetParser,selectionParser,csvReporter,argparse,CommonUtil,dbUtil,nameDealer,lumiQueryAPI
8 
9 def getValidationData(dbsession,run=None,cmsls=None):
10  '''retrieve validation data per run or all
11  input: runnum, if not runnum, retrive all
12  output: {run:[[cmslsnum,flag,comment]]}
13  '''
14  result={}
15  try:
16  dbsession.transaction().start(True)
17  schema=dbsession.nominalSchema()
18  queryHandle=dbsession.nominalSchema().newQuery()
19  result=lumiQueryAPI.validation(queryHandle,run,cmsls)
20  del queryHandle
21  dbsession.transaction().commit()
22  except Exception, e:
23  dbsession.transaction().rollback()
24  del dbsession
25  raise Exception, 'lumiValidate.getValidationData:'+str(e)
26  return result
27 
28 def insertupdateValidationData(dbsession,data):
29  '''
30  input: data {run:[[ls,status,comment]]}
31  '''
32  toreplacenocomment=[]#[[('RUNNUM',runnum),('CMSLSNUM',cmslsnum),('FLAG',flag)],[]]
33  toreplacewcomment=[]#[[('RUNNUM',runnum),('CMSLSNUM',cmslsnum),('FLAG',flag),('COMMENT',comment)],[]]
34  toinsert=[] #[[('RUNNUM',runnum),('CMSLSNUM',cmslsnum),('FLAG',flag),('COMMENT',comment)],[]]
35  try:
36  dbsession.transaction().start(True)
37  dbutil=dbUtil.dbUtil(dbsession.nominalSchema())
38  for run,alllsdata in data.items():
39  lsselection=[]
40  if len(alllsdata)==0:#cross query lumisummary to get all the cmslsnum for this run,then insert all to default
41  queryHandle=dbsession.nominalSchema().newQuery()
42  lumisummaryData=lumiQueryAPI.lumisummaryByrun(queryHandle,run,'0001')
43  del queryHandle
44  for lumisummary in lumisummaryData:
45  if lumisummary[-1]==1:#cmsalive
46  lsselection.append([lumisummary[0],'UNKNOWN','NA'])
47  else:
48  lsselection=alllsdata
49  if len(lsselection)==0:
50  print 'no LS found for run '+str(run)+' do nothing'
51  continue
52  for lsdata in lsselection:
53  condition='RUNNUM=:runnum AND CMSLSNUM=:cmslsnum'
54  conditionDefDict={}
55  conditionDefDict['runnum']='unsigned int'
56  conditionDefDict['cmslsnum']='unsigned int'
57  conditionDict={}
58  conditionDict['runnum']=run
59  conditionDict['cmslsnum']=lsdata[0]
60  if dbutil.existRow(nameDealer.lumivalidationTableName(),condition,conditionDefDict,conditionDict):
61  if len(lsdata)>2 and lsdata[2]:
62  toreplacewcomment.append([('runnum',run),('cmslsnum',lsdata[0]),('flag',lsdata[1]),('comment',lsdata[2])])
63  else:
64  toreplacenocomment.append([('runnum',run),('cmslsnum',lsdata[0]),('flag',lsdata[1]),('comment','')])
65  else:
66  if len(lsdata)>2 and lsdata[2]:
67  toinsert.append([('RUNNUM',run),('CMSLSNUM',lsdata[0]),('FLAG',lsdata[1]),('COMMENT',lsdata[2])])
68  else:
69  toinsert.append([('RUNNUM',run),('CMSLSNUM',lsdata[0]),('FLAG',lsdata[1]),('COMMENT','N/A')])
70  dbsession.transaction().commit()
71  #print 'toreplace with comment ',toreplacewcomment
72  #print 'toreplace without comment ',toreplacenocomment
73  #print 'toinsert ',toinsert
74  #perform insert
75  if len(toinsert)!=0:
76  dbsession.transaction().start(False)
77  dbutil=dbUtil.dbUtil(dbsession.nominalSchema())
78  tabrowDef=[]
79  tabrowDef.append(('RUNNUM','unsigned int'))
80  tabrowDef.append(('CMSLSNUM','unsigned int'))
81  tabrowDef.append(('FLAG','string'))
82  tabrowDef.append(('COMMENT','string'))
83  dbutil.bulkInsert(nameDealer.lumivalidationTableName(),tabrowDef,toinsert)
84  dbsession.transaction().commit()
85  #perform update with comment
86  if len(toreplacewcomment)!=0:
87  dbsession.transaction().start(False)
88  dbutil=dbUtil.dbUtil(dbsession.nominalSchema())
89  updateAction='FLAG=:flag,COMMENT=:comment'
90  updateCondition='RUNNUM=:runnum and CMSLSNUM=:cmslsnum'
91  bindvarDef=[]
92  bindvarDef.append(('flag','string'))
93  bindvarDef.append(('comment','string'))
94  bindvarDef.append(('runnum','unsigned int'))
95  bindvarDef.append(('cmslsnum','unsigned int'))
96  dbutil.updateRows(nameDealer.lumivalidationTableName(),updateAction,updateCondition,bindvarDef,toreplacewcomment)
97  dbsession.transaction().commit()
98  #perform update with NO comment
99  if len(toreplacenocomment)!=0:
100  dbsession.transaction().start(False)
101  dbutil=dbUtil.dbUtil(dbsession.nominalSchema())
102  updateAction='FLAG=:flag'
103  updateCondition='RUNNUM=:runnum and CMSLSNUM=:cmslsnum'
104  bindvarDef=[]
105  bindvarDef.append(('flag','string'))
106  bindvarDef.append(('runnum','unsigned int'))
107  bindvarDef.append(('cmslsnum','unsigned int'))
108  dbutil.updateRows(nameDealer.lumivalidationTableName(),updateAction,updateCondition,bindvarDef,toreplacenocomment)
109  dbsession.transaction().commit()
110  except Exception, e:
111  dbsession.transaction().rollback()
112  del dbsession
113  raise Exception, 'lumiValidate.insertupdateValidationData:'+str(e)
114 
115 ##############################
116 ## ######################## ##
117 ## ## ################## ## ##
118 ## ## ## Main Program ## ## ##
119 ## ## ################## ## ##
120 ## ######################## ##
121 ##############################
122 
123 def main():
124  parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),description = "Lumi Validation",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
125  allowedActions = ['batchupdate','update','dump']
126  allowedFlags = ['UNKNOWN','GOOD','BAD','SUSPECT']
127  # parse arguments
128  parser.add_argument('action',choices=allowedActions,help='command actions')
129  parser.add_argument('-c',dest='connect',action='store',required=True,help='connect string to lumiDB')
130  parser.add_argument('-P',dest='authpath',action='store',required=True,help='path to authentication file')
131  parser.add_argument('-i',dest='inputfile',action='store',help='lumi range selection file,required for batchupdate action')
132  parser.add_argument('-o',dest='outputfile',action='store',help='output to csv file')
133  parser.add_argument('-r',dest='runnumber',action='store',type=int,help='run number,optional')
134  parser.add_argument('-runls',dest='runls',action='store',help='selection string,optional. Example [1234:[],4569:[1,1],[2,100]]')
135  parser.add_argument('-flag',dest='flag',action='store',default='UNKNOWN',help='flag string,optional')
136  parser.add_argument('--verbose',dest='verbose',action='store_true',help='verbose mode for printing' )
137  parser.add_argument('--debug',dest='debug',action='store_true',help='debug')
138  options=parser.parse_args()
139  if options.flag.upper() not in allowedFlags:
140  print 'unrecognised flag ',options.flag.upper()
141  raise
142  os.environ['CORAL_AUTH_PATH'] = options.authpath
143  connectstring=options.connect
144  svc = coral.ConnectionService()
145  msg=coral.MessageStream('')
146  if options.debug:
147  msg.setMsgVerbosity(coral.message_Level_Debug)
148  else:
149  msg.setMsgVerbosity(coral.message_Level_Error)
150  session=svc.connect(connectstring,accessMode=coral.access_Update)
151  session.typeConverter().setCppTypeForSqlType("unsigned int","NUMBER(10)")
152  session.typeConverter().setCppTypeForSqlType("unsigned long long","NUMBER(20)")
153 
154  result={}#parsing result {run:[[ls,status,comment]]}
155  if options.debug :
156  msg=coral.MessageStream('')
157  msg.setMsgVerbosity(coral.message_Level_Debug)
158 
159  if options.action=='batchupdate':
160  #populate from csv file, require -i argument
161  if not options.inputfile:
162  print 'inputfile -i option is required for batchupdate'
163  raise
164  csvReader=csv.reader(open(options.inputfile),delimiter=',')
165  for row in csvReader:
166  if len(row)==0:
167  continue
168  fieldrun=str(row[0]).strip()
169  fieldls=str(row[1]).strip()
170  fieldstatus=row[2]
171  fieldcomment=row[3]
172  if not result.has_key(int(fieldrun)):
173  result[int(fieldrun)]=[]
174  result[int(fieldrun)].append([int(fieldls),fieldstatus,fieldcomment])
175  insertupdateValidationData(session,result)
176  if options.action=='update':
177  #update flag interactively, require -runls argument
178  #runls={run:[]} populate all CMSLSNUM found in LUMISUMMARY
179  #runls={run:[[1,1],[2,5]],run:[[1,1],[2,5]]}
180  #default value
181  if not options.runls and not options.runnumber:
182  print 'option -runls or -r is required for update'
183  raise
184  if not options.flag:
185  print 'option -flag is required for update'
186  raise
187  if options.flag.upper() not in allowedFlags:
188  print 'unrecognised flag ',options.flag
189  raise
190  if options.runnumber:
191  runlsjson='{"'+str(options.runnumber)+'":[]}'
192  elif options.runls:
193  runlsjson=CommonUtil.tolegalJSON(options.runls)
194  sparser=selectionParser.selectionParser(runlsjson)
195  runsandls=sparser.runsandls()
196  commentStr='NA'
197  statusStr=options.flag
198  for run,lslist in runsandls.items():
199  if not result.has_key(run):
200  result[run]=[]
201  for ls in lslist:
202  result[run].append([ls,statusStr,commentStr])
203  insertupdateValidationData(session,result)
204  if options.action=='dump':
205  if options.runls or options.inputfile:
206  if options.runls:
207  runlsjson=CommonUtil.tolegalJSON(options.runls)
208  sparser=selectionParser.selectionParser(runlsjson)
209  runsandls=sparser.runsandls()
210  if options.inputfile:
211  p=inputFilesetParser.inputFilesetParser(options.inputfile)
212  runsandls=p.runsandls()
213  for runnum,lslist in runsandls.items():
214  dataperrun=getValidationData(session,run=runnum,cmsls=lslist)
215  if dataperrun.has_key(runnum):
216  result[runnum]=dataperrun[runnum]
217  else:
218  result[runnum]=[]
219  else:
220  result=getValidationData(session,run=options.runnumber)
221  runs=result.keys()
222  runs.sort()
223  if options.outputfile:
224  r=csvReporter.csvReporter(options.outputfile)
225  for run in runs:
226  for perrundata in result[run]:
227  r.writeRow([str(run),str(perrundata[0]),perrundata[1],perrundata[2]])
228  else:
229  for run in runs:
230  print '== ='
231  if len(result[run])==0:
232  print str(run),'no validation data'
233  continue
234  for lsdata in result[run]:
235  print str(run)+','+str(lsdata[0])+','+lsdata[1]+','+lsdata[2]
236 
237  del session
238  del svc
239 if __name__ == '__main__':
240  main()
241 
242 
243 
Definition: start.py:1
void strip(std::string &input, const std::string &blanks=" \n\t")
Definition: stringTools.cc:16
def lumivalidationTableName
Definition: nameDealer.py:56
def tolegalJSON
Definition: CommonUtil.py:105
def main
## Main Program
def insertupdateValidationData
Definition: lumiValidate.py:28
def getValidationData
Definition: lumiValidate.py:9