ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/writeCfg.py
(Generate patch)

Comparing COMP/CRAB/python/writeCfg.py (file contents):
Revision 1.1 by ewv, Fri Dec 14 17:53:36 2007 UTC vs.
Revision 1.10 by ewv, Wed May 21 19:27:30 2008 UTC

# Line 3 | Line 3
3   import sys, getopt, string
4   import imp
5   import os
6 + import random
7 + from random import SystemRandom
8 + _inst  = SystemRandom()
9  
10   from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
11   from FWCore.ParameterSet.DictTypes import SortedKeysDict
12   from FWCore.ParameterSet.Modules   import Service
13   from FWCore.ParameterSet.Types     import *
14 < from FWCore.ParameterSet.Config import include
14 > from FWCore.ParameterSet.Config    import include
15  
16   import FWCore.ParameterSet.Types   as CfgTypes
17   import FWCore.ParameterSet.Modules as CfgModules
18  
19 + class ConfigException(Exception):
20 +    def __init__(self, msg):
21 +        Exception.__init__(self, msg)
22 +        self._msg = msg
23 +        return
24 +
25 +    def __str__(self):
26 +        return self._msg
27  
28   def main(argv) :
29    """
# Line 31 | Line 42 | def main(argv) :
42    """
43  
44    # defaults
34  maxEvents = 0
35  skipEvents = 0
45    inputFileNames = None
46 <  debug = False
46 >  firstRun       = 0
47 >  sourceSeed     = 0
48 >  vtxSeed        = 0
49 >  g4Seed         = 0
50 >  mixSeed        = 0
51 >  debug          = False
52 >  _MAXINT        = 900000000
53 >  maxSeeds       = 4         # Kludge, maximum # of seeds that any engine takes
54  
55    try:
56 <    opts, args = getopt.getopt(argv, "", ["debug", "help","inputFiles=","maxEvents=","skipEvents="])
56 >    opts, args = getopt.getopt(argv, "", ["debug", "help"])
57    except getopt.GetoptError:
58      print main.__doc__
59      sys.exit(2)
60  
61 <  # Parse command line parameters
61 >  try:
62 >    CMSSW  = os.environ['CMSSW_VERSION']
63 >    parts = CMSSW.split('_')
64 >    CMSSW_major = int(parts[1])
65 >    CMSSW_minor = int(parts[2])
66 >    CMSSW_patch = int(parts[3])
67 >  except KeyError, ValueError:
68 >    msg = "Your environment doesn't specify the CMSSW version or specifies it incorrectly"
69 >    raise ConfigException(msg)
70 >
71 >  # Parse command line options
72    for opt, arg in opts :
73      if opt  == "--help" :
74        print main.__doc__
75        sys.exit()
76      elif opt == "--debug" :
77        debug = True
52    elif opt == "--maxEvents":
53      maxEvents = int(arg)
54    elif opt == "--skipEvents":
55      skipEvents = int(arg)
56    elif opt == "--inputFiles":
57      inputFiles = arg
58      inputFiles = inputFiles.replace('\\','')
59      inputFiles = inputFiles.replace('"','')
60      inputFileNames = inputFiles.split(',')
78  
79    # Parse remaining parameters
80  
81 <  fileName    = args[0];
82 <  outFileName = args[1];
81 >  try:
82 >    fileName    = args[0];
83 >    outFileName = args[1];
84 >  except IndexError:
85 >    print main.__doc__
86 >    sys.exit()
87 >
88 > # Optional Parameters
89 >
90 >  maxEvents  = int(os.environ.get('MaxEvents', '0'))
91 >  skipEvents = int(os.environ.get('SkipEvents','0'))
92 >  firstRun   = int(os.environ.get('FirstRun',  '0'))
93 >  nJob       = int(os.environ.get('NJob',      '0'))
94  
95 <  # Input cfg or python cfg file
95 >  inputFiles     = os.environ.get('InputFiles','')
96 >  preserveSeeds  = os.environ.get('PreserveSeeds','')
97 >  incrementSeeds = os.environ.get('IncrementSeeds','')
98  
99 <  if (fileName.endswith('py') or fileName.endswith('pycfg') ):
99 > # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
100 >
101 >  if fileName.endswith('py'):
102      handle = open(fileName, 'r')
103      try:   # Nested form for Python < 2.5
104        try:
105          cfo = imp.load_source("pycfg", fileName, handle)
106 +        cmsProcess = cfo.process
107        except Exception, ex:
108          msg = "Your pycfg file is not valid python: %s" % str(ex)
109          raise "Error: ",msg
110      finally:
111          handle.close()
79    cfg = CfgInterface(cfo.process)
112    else:
113      try:
114 +      print "Importing .cfg file"
115        cfo = include(fileName)
116 <      cfg = CfgInterface(cfo)
116 >      cmsProcess = cfo
117      except Exception, ex:
118        msg =  "The cfg file is not valid, %s\n" % str(ex)
119        raise "Error: ",msg
120 +  print "Getting interface"
121 +  cfg = CfgInterface(cmsProcess)
122  
123    # Set parameters for job
124 <
124 >  print "Setting parameters"
125    inModule = cfg.inputSource
126 +  if maxEvents:
127 +    cfg.maxEvents.setMaxEventsInput(maxEvents)
128  
129 <  cfg.maxEvents.setMaxEventsInput(maxEvents)
129 >  if skipEvents:
130 >    inModule.setSkipEvents(skipEvents)
131  
132 <  inModule.setSkipEvents(skipEvents)
133 <  if (inputFileNames):
132 >  if inputFiles:
133 >    inputFiles = inputFiles.replace('\\','')
134 >    inputFiles = inputFiles.replace('"','')
135 >    inputFileNames = inputFiles.split(',')
136      inModule.setFileNames(*inputFileNames)
137  
138 <  # Write out new config file
138 >  # Pythia parameters
139 >  if (firstRun):
140 >    inModule.setFirstRun(firstRun)
141 >
142 >  incrementSeedList = []
143 >  preserveSeedList  = []
144 >
145 >  if incrementSeeds:
146 >    incrementSeedList = incrementSeeds.split(',')
147 >  if preserveSeeds:
148 >    preserveSeedList  = preserveSeeds.split(',')
149 >
150 >  # FUTURE: This function tests the CMSSW version and presence of old-style seed specification. Reduce when we drop support for old versions
151 >  if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
152 >    print "RandomNumberGeneratorService found, will attempt to change seeds"
153 >    ranGenerator = cfg.data.services['RandomNumberGeneratorService']
154 >    ranModules   = getattr(ranGenerator,"moduleSeeds",None)
155 >    if ranModules != None:              # Old format present, no matter the CMSSW version
156 >      print "Old-style random number seeds found, will be changed."
157 >      sourceSeed = int(ranGenerator.sourceSeed.value())
158 >      if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
159 >        pass
160 >      elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
161 >        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
162 >      else:
163 >        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
164 >
165 >      for seed in incrementSeedList:
166 >        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
167 >        if curSeed:
168 >          curValue = int(curSeed.value())
169 >          setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
170 >          preserveSeedList.append(seed)
171 >
172 >      for seed in ranGenerator.moduleSeeds.parameterNames_():
173 >        if seed not in preserveSeedList:
174 >          curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
175 >          if curSeed:
176 >            curValue = int(curSeed.value())
177 >            setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT))))
178 >    elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
179 >      print "New-style random number seeds found, will be changed."
180 >      from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
181 >      randSvc = RandomNumberServiceHelper(ranGenerator)
182 >
183 >      # Increment requested seed sets
184 >      for seedName in incrementSeedList:
185 >        curSeeds = randSvc.getNamedSeed(seedName)
186 >        newSeeds = [x+nJob for x in curSeeds]
187 >        randSvc.setNamedSeed(seedName,*newSeeds)
188 >        preserveSeedList.append(seedName)
189 >
190 >      # Randomize remaining seeds
191 >      randSvc.populate(*preserveSeedList)
192 >    else:
193 >      print "Neither old nor new seed format found!"
194 >
195 >    # End version specific code
196  
197 +  # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
198    outFile = open(outFileName,"w")
199 <  outFile.write("import FWCore.ParameterSet.Config as cms\n")
200 <  outFile.write(cfo.dumpPython())
199 >  if outFileName.endswith('py'):
200 >    outFile.write("import FWCore.ParameterSet.Config as cms\n")
201 >    outFile.write(cmsProcess.dumpPython())
202 >    if (debug):
203 >      print "writeCfg output:"
204 >      print "import FWCore.ParameterSet.Config as cms"
205 >      print cmsProcess.dumpPython()
206 >  else:
207 >    outFile.write(str(cfg))
208 >    if (debug):
209 >      print "writeCfg output:"
210 >      print str(cfg)
211    outFile.close()
212  
105  if (debug):
106    print "writeCfg output:"
107    print "import FWCore.ParameterSet.Config as cms"
108    print cfo.dumpPython()
109
213  
214   if __name__ == '__main__' :
215      exit_status = main(sys.argv[1:])
216      sys.exit(exit_status)
114

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines