CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
MatrixReader.py
Go to the documentation of this file.
1 
2 import sys
3 
4 from Configuration.PyReleaseValidation.WorkFlow import WorkFlow
5 
6 # ================================================================================
7 
9  def __init__(self, msg):
10  self.msg = msg
11  def __str__(self):
12  return self.msg
13 
14 # ================================================================================
15 
17 
18  def __init__(self, opt):
19 
20  self.reset(opt.what)
21 
22  self.wm=opt.wmcontrol
23  self.addCommand=opt.command
24  self.apply=opt.apply
25  self.commandLineWf=opt.workflow
26  self.overWrite=opt.overWrite
27 
28  self.noRun = opt.noRun
29  return
30 
31  def reset(self, what='all'):
32 
33  self.what = what
34 
35  #a bunch of information, but not yet the WorkFlow object
36  self.workFlowSteps = {}
37  #the actual WorkFlow objects
38  self.workFlows = []
39  self.nameList = {}
40 
41  self.filesPrefMap = {'relval_standard' : 'std-' ,
42  'relval_highstats': 'hi-' ,
43  'relval_pileup': 'PU-' ,
44  'relval_generator': 'gen-' ,
45  'relval_production': 'prod-' ,
46  'relval_ged': 'ged-',
47  'relval_upgrade':'upg-',
48  'relval_identity':'id-'
49  }
50 
51  self.files = ['relval_standard' ,
52  'relval_highstats',
53  'relval_pileup',
54  'relval_generator',
55  'relval_production',
56  'relval_ged',
57  'relval_upgrade',
58  'relval_identity'
59  ]
60 
61  self.relvalModule = None
62 
63  return
64 
65  def makeCmd(self, step):
66 
67  cmd = ''
68  cfg = None
69  input = None
70  for k,v in step.items():
71  if 'no_exec' in k : continue # we want to really run it ...
72  if k.lower() == 'cfg':
73  cfg = v
74  continue # do not append to cmd, return separately
75  if k.lower() == 'input':
76  input = v
77  continue # do not append to cmd, return separately
78 
79  #chain the configs
80  #if k.lower() == '--python':
81  # v = 'step%d_%s'%(index,v)
82  cmd += ' ' + k + ' ' + str(v)
83  return cfg, input, cmd
84 
85  def readMatrix(self, fileNameIn, useInput=None, refRel=None, fromScratch=None):
86 
87  prefix = self.filesPrefMap[fileNameIn]
88 
89  print "processing ", fileNameIn
90 
91  try:
92  _tmpMod = __import__( 'Configuration.PyReleaseValidation.'+fileNameIn )
93  self.relvalModule = sys.modules['Configuration.PyReleaseValidation.'+fileNameIn]
94  except Exception, e:
95  print "ERROR importing file ", fileNameIn, str(e)
96  return
97 
98  print "request for INPUT for ", useInput
99 
100 
101  fromInput={}
102 
103  if useInput:
104  for i in useInput:
105  if ':' in i:
106  (ik,il)=i.split(':')
107  if ik=='all':
108  for k in self.relvalModule.workflows.keys():
109  fromInput[float(k)]=int(il)
110  else:
111  fromInput[float(ik)]=int(il)
112  else:
113  if i=='all':
114  for k in self.relvalModule.workflows.keys():
115  fromInput[float(k)]=0
116  else:
117  fromInput[float(i)]=0
118 
119  if fromScratch:
120  fromScratch=map(float,fromScratch)
121  for num in fromScratch:
122  if num in fromInput:
123  fromInput.pop(num)
124  #overwrite steps
125  if self.overWrite:
126  for p in self.overWrite:
127  self.relvalModule.steps.overwrite(p)
128 
129  #change the origin of dataset on the fly
130  if refRel:
131  if ',' in refRel:
132  refRels=refRel.split(',')
133  if len(refRels)!=len(self.relvalModule.baseDataSetRelease):
134  return
135  self.relvalModule.changeRefRelease(
136  self.relvalModule.steps,
137  zip(self.relvalModule.baseDataSetRelease,refRels)
138  )
139  else:
140  self.relvalModule.changeRefRelease(
141  self.relvalModule.steps,
142  [(x,refRel) for x in self.relvalModule.baseDataSetRelease]
143  )
144 
145 
146  for num, wfInfo in self.relvalModule.workflows.items():
147  commands=[]
148  wfName = wfInfo[0]
149  stepList = wfInfo[1]
150  # if no explicit name given for the workflow, use the name of step1
151  if wfName.strip() == '': wfName = stepList[0]
152  # option to specialize the wf as the third item in the WF list
153  addTo=None
154  addCom=None
155  if len(wfInfo)>=3:
156  addCom=wfInfo[2]
157  if not type(addCom)==list: addCom=[addCom]
158  #print 'added dict',addCom
159  if len(wfInfo)>=4:
160  addTo=wfInfo[3]
161  #pad with 0
162  while len(addTo)!=len(stepList):
163  addTo.append(0)
164 
165  name=wfName
166  stepIndex=0
167  ranStepList=[]
168 
169  #first resolve INPUT possibilities
170  if num in fromInput:
171  ilevel=fromInput[num]
172  #print num,ilevel
173  for (stepIr,step) in enumerate(reversed(stepList)):
174  stepName=step
175  stepI=(len(stepList)-stepIr)-1
176  #print stepIr,step,stepI,ilevel
177  if stepI>ilevel:
178  #print "ignoring"
179  continue
180  if stepI!=0:
181  testName='__'.join(stepList[0:stepI+1])+'INPUT'
182  else:
183  testName=step+'INPUT'
184  #print "JR",stepI,stepIr,testName,stepList
185  if testName in self.relvalModule.steps.keys():
186  #print "JR",stepI,stepIr
187  stepList[stepI]=testName
188  #pop the rest in the list
189  #print "\tmod prepop",stepList
190  for p in range(stepI):
191  stepList.pop(0)
192  #print "\t\tmod",stepList
193  break
194 
195 
196  for (stepI,step) in enumerate(stepList):
197  stepName=step
198  if self.wm:
199  #cannot put a certain number of things in wm
200  if stepName in [
201  #'HARVEST','HARVESTD','HARVESTDreHLT',
202  'RECODFROMRAWRECO','SKIMD','SKIMCOSD','SKIMDreHLT'
203  ]:
204  continue
205 
206  #replace stepName is needed
207  #if stepName in self.replaceStep
208  if len(name) > 0 : name += '+'
209  #any step can be mirrored with INPUT
210  ## maybe we want too level deep input
211  """
212  if num in fromInput:
213  if step+'INPUT' in self.relvalModule.steps.keys():
214  stepName = step+"INPUT"
215  stepList.remove(step)
216  stepList.insert(stepIndex,stepName)
217  """
218  name += stepName
219 
220  if addCom and (not addTo or addTo[stepIndex]==1):
222  copyStep=merge(addCom+[self.relvalModule.steps[stepName]])
223  cfg, input, opts = self.makeCmd(copyStep)
224  else:
225  cfg, input, opts = self.makeCmd(self.relvalModule.steps[stepName])
226 
227  if input and cfg :
228  msg = "FATAL ERROR: found both cfg and input for workflow "+str(num)+' step '+stepName
229  raise MatrixException(msg)
230 
231  if input:
232  cmd = input
233  if self.noRun:
234  cmd.run=[]
235  else:
236  if cfg:
237  cmd = 'cmsDriver.py '+cfg+' '+opts
238  else:
239  cmd = 'cmsDriver.py step'+str(stepIndex+1)+' '+opts
240  if self.wm:
241  cmd+=' --io %s.io --python %s.py'%(stepName,stepName)
242  if self.addCommand:
243  if self.apply:
244  if stepIndex in self.apply or stepName in self.apply:
245  cmd +=' '+self.addCommand
246  else:
247  cmd +=' '+self.addCommand
248  commands.append(cmd)
249  ranStepList.append(stepName)
250  stepIndex+=1
251 
252  self.workFlowSteps[(num,prefix)] = (num, name, commands, ranStepList)
253 
254  return
255 
256 
257  def showRaw(self, useInput, refRel=None, fromScratch=None, what='all',step1Only=False,selected=None):
258 
259  if selected:
260  selected=map(float,selected)
261  for matrixFile in self.files:
262 
263  self.reset(what)
264 
265  if self.what != 'all' and self.what not in matrixFile:
266  print "ignoring non-requested file",matrixFile
267  continue
268 
269  try:
270  self.readMatrix(matrixFile, useInput, refRel, fromScratch)
271  except Exception, e:
272  print "ERROR reading file:", matrixFile, str(e)
273  raise
274 
275  if not self.workFlowSteps: continue
276 
277  dataFileName = matrixFile.replace('relval_', 'cmsDriver_')+'_hlt.txt'
278  outFile = open(dataFileName,'w')
279 
280  print "found ", len(self.workFlowSteps.keys()), ' workflows for ', dataFileName
281  ids = self.workFlowSteps.keys()
282  ids.sort()
283  indexAndSteps=[]
284 
285  writtenWF=0
286  for key in ids:
287  if selected and not (key[0] in selected):
288  continue
289  #trick to skip the HImix IB test
290  if key[0]==203.1 or key[0]==204.1 or key[0]==205.1 or key[0]==4.51 or key[0]==4.52: continue
291  num, name, commands, stepList = self.workFlowSteps[key]
292 
293  wfName,stepNames= name.split('+',1)
294 
295  stepNames=stepNames.replace('+RECODFROMRAWRECO','')
296  stepNames=stepNames.replace('+SKIMCOSD','')
297  stepNames=stepNames.replace('+SKIMD','')
298  if 'HARVEST' in stepNames:
299  #find out automatically what to remove
300  exactb=stepNames.index('+HARVEST')
301  exacte=stepNames.index('+',exactb+1) if ('+' in stepNames[exactb+1:]) else (len(stepNames))
302  stepNames=stepNames.replace(stepNames[exactb:exacte],'')
303  otherSteps = None
304  if '+' in stepNames:
305  step1,otherSteps = stepNames.split('+',1)
306 
307  line = str(num) + ' ++ '+ wfName
308  if otherSteps and not step1Only:
309  line += ' ++ ' +otherSteps.replace('+',',')
310  else:
311  line += ' ++ none'
312  inputInfo=None
313  if not isinstance(commands[0],str):
314  inputInfo=commands[0]
315  if otherSteps:
316  for (i,c) in enumerate(otherSteps.split('+')):
317  #pad with set
318  for p in range(len(indexAndSteps),i+2):
319  indexAndSteps.append(set())
320  indexAndSteps[i+1].add((c,commands[i+1]))
321 
322  if inputInfo :
323  #skip the samples from INPUT when step1Only is on
324  if step1Only: continue
325  line += ' ++ REALDATA: '+inputInfo.dataSet
326  if inputInfo.run!=[]: line += ', RUN:'+'|'.join(map(str,inputInfo.run))
327  line += ', FILES: ' +str(inputInfo.files)
328  line += ', EVENTS: '+str(inputInfo.events)
329  if inputInfo.label!='':
330  line += ', LABEL: ' +inputInfo.label
331  line += ', LOCATION:'+inputInfo.location
332  line += ' @@@'
333  else:
334  line += ' @@@ '+commands[0]
335  writtenWF+=1
336  outFile.write(line+'\n')
337 
338 
339  outFile.write('\n'+'\n')
340  if step1Only: continue
341 
342  for (index,s) in enumerate(indexAndSteps):
343  for (stepName,cmd) in s:
344  stepIndex=index+1
345  if 'dasquery.log' in cmd: continue
346  line = 'STEP%d ++ '%(stepIndex,) +stepName + ' @@@ '+cmd
347  outFile.write(line+'\n')
348  outFile.write('\n'+'\n')
349  outFile.close()
350  print "wrote ",writtenWF, ' workflow'+('s' if (writtenWF!=1) else ''),' to ', outFile.name
351  return
352 
353 
354  def showWorkFlows(self, selected=None, extended=True):
355  if selected: selected = map(float,selected)
356  maxLen = 100 # for summary, limit width of output
357  fmt1 = "%-6s %-35s [1]: %s ..."
358  fmt2 = " %35s [%d]: %s ..."
359  print "\nfound a total of ", len(self.workFlows), ' workflows:'
360  if selected:
361  print " of which the following", len(selected), 'were selected:'
362  #-ap for now:
363  maxLen = -1 # for individual listing, no limit on width
364  fmt1 = "%-6s %-35s [1]: %s "
365  fmt2 = " %35s [%d]: %s"
366 
367  N=[]
368  for wf in self.workFlows:
369  if selected and float(wf.numId) not in selected: continue
370  if extended: print ''
371  #pad with zeros
372  for i in range(len(N),len(wf.cmds)): N.append(0)
373  N[len(wf.cmds)-1]+=1
374  wfName, stepNames = wf.nameId.split('+',1)
375  for i,s in enumerate(wf.cmds):
376  if extended:
377  if i==0:
378  print fmt1 % (wf.numId, stepNames, (str(s)+' ')[:maxLen])
379  else:
380  print fmt2 % ( ' ', i+1, (str(s)+' ')[:maxLen])
381  else:
382  print "%-6s %-35s "% (wf.numId, stepNames)
383  break
384  print ''
385  for i,n in enumerate(N):
386  if n: print n,'workflows with',i+1,'steps'
387 
388  return
389 
390  def createWorkFlows(self, fileNameIn):
391 
392  prefixIn = self.filesPrefMap[fileNameIn]
393 
394  # get through the list of items and update the requested workflows only
395  keyList = self.workFlowSteps.keys()
396  ids = []
397  for item in keyList:
398  id, pref = item
399  if pref != prefixIn : continue
400  ids.append(id)
401  ids.sort()
402  for key in ids:
403  val = self.workFlowSteps[(key,prefixIn)]
404  num, name, commands, stepList = val
405  nameId = str(num)+'_'+name
406  if nameId in self.nameList:
407  print "==> duplicate name found for ", nameId
408  print ' keeping : ', self.nameList[nameId]
409  print ' ignoring : ', val
410  else:
411  self.nameList[nameId] = val
412 
413  self.workFlows.append(WorkFlow(num, name, commands=commands))
414 
415  return
416 
417  def prepare(self, useInput=None, refRel='', fromScratch=None):
418 
419  for matrixFile in self.files:
420  if self.what != 'all' and self.what not in matrixFile:
421  print "ignoring non-requested file",matrixFile
422  continue
423  if self.what == 'all' and ('upgrade' in matrixFile):
424  print "ignoring",matrixFile,"from default matrix"
425  continue
426 
427  try:
428  self.readMatrix(matrixFile, useInput, refRel, fromScratch)
429  except Exception, e:
430  print "ERROR reading file:", matrixFile, str(e)
431  raise
432 
433  try:
434  self.createWorkFlows(matrixFile)
435  except Exception, e:
436  print "ERROR creating workflows :", str(e)
437  raise
438 
439 
440  def show(self, selected=None, extended=True):
441 
442  self.showWorkFlows(selected,extended)
443  print '\n','-'*80,'\n'
444 
445 
446  def updateDB(self):
447 
448  import pickle
449  pickle.dump(self.workFlows, open('theMatrix.pkl', 'w') )
450 
451  return
452 
Definition: merge.py:1
void add(const std::vector< const T * > &source, std::vector< const T * > &dest)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
list object
Definition: dbtoconf.py:77