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.2 by ewv, Tue Feb 19 17:19:14 2008 UTC vs.
Revision 1.7 by ewv, Tue May 6 01:09:58 2008 UTC

# Line 11 | Line 11 | from ProdCommon.CMSConfigTools.ConfigAPI
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 34 | Line 42 | def main(argv) :
42    """
43  
44    # defaults
37  maxEvents      = 0
38  skipEvents     = 0
45    inputFileNames = None
46    firstRun       = 0
47    sourceSeed     = 0
# Line 43 | Line 49 | def main(argv) :
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
60    elif opt == "--maxEvents":
61      maxEvents = int(arg)
62    elif opt == "--skipEvents":
63      skipEvents = int(arg)
64    elif opt == "--inputFiles":
65      inputFiles = arg
66      inputFiles = inputFiles.replace('\\','')
67      inputFiles = inputFiles.replace('"','')
68      inputFileNames = inputFiles.split(',')
69    elif opt == "--firstRun":
70      firstRun = int(arg)
71    elif opt == "--sourceSeed":
72      sourceSeed = int(arg)
73    elif opt == "--vtxSeed":
74      vtxSeed = int(arg)
75    elif opt == "--g4Seed":
76      g4Seed = int(arg)
77    elif opt == "--mixSeed":
78      mixSeed = int(arg)
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 >  inputFiles     = os.environ.get('InputFiles','')
96 >  preserveSeeds  = os.environ.get('PreserveSeeds','')
97 >  incrementSeeds = os.environ.get('IncrementSeeds','')
98  
99 <  # Input cfg or python cfg file
99 > # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
100  
101 <  if (fileName.endswith('py') or fileName.endswith('pycfg') ):
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()
97    cfg = CfgInterface(cfo.process)
112    else:
113      try:
114        cfo = include(fileName)
115 <      cfg = CfgInterface(cfo)
115 >      cmsProcess = cfo
116      except Exception, ex:
117        msg =  "The cfg file is not valid, %s\n" % str(ex)
118        raise "Error: ",msg
119 +  cfg = CfgInterface(cmsProcess)
120  
121    # Set parameters for job
107
122    inModule = cfg.inputSource
123 +  if maxEvents:
124 +    cfg.maxEvents.setMaxEventsInput(maxEvents)
125  
126 <  cfg.maxEvents.setMaxEventsInput(maxEvents)
126 >  if skipEvents:
127 >    inModule.setSkipEvents(skipEvents)
128  
129 <  inModule.setSkipEvents(skipEvents)
130 <  if (inputFileNames):
129 >  if inputFiles:
130 >    inputFiles = inputFiles.replace('\\','')
131 >    inputFiles = inputFiles.replace('"','')
132 >    inputFileNames = inputFiles.split(',')
133      inModule.setFileNames(*inputFileNames)
134  
135    # Pythia parameters
136    if (firstRun):
137      inModule.setFirstRun(firstRun)
119  if (sourceSeed) :
120    ranGenerator = cfg.data.services['RandomNumberGeneratorService']
121    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed))
122    if (vtxSeed) :
123      ranModules   = ranGenerator.moduleSeeds
124      ranModules.VtxSmeared = CfgTypes.untracked(CfgTypes.uint32(vtxSeed))
125    if (g4Seed) :
126      ranModules   = ranGenerator.moduleSeeds
127      ranModules.g4SimHits = CfgTypes.untracked(CfgTypes.uint32(g4Seed))
128    if (mixSeed) :
129      ranModules   = ranGenerator.moduleSeeds
130      ranModules.mix = CfgTypes.untracked(CfgTypes.uint32(mixSeed))
138  
139 <  # Randomize all seeds
139 >  incrementSeedList = []
140 >  preserveSeedList  = []
141  
142 <  print "There are ",cfg.seedCount()," seeds"
143 <  seedList = [random.randint(100,200) for i in range(cfg.seedCount)]
144 <  seedTuple = seedList.tuple()
142 >  if incrementSeeds:
143 >    incrementSeedList = incrementSeeds.split(',')
144 >  if preserveSeeds:
145 >    preserveSeedList  = preserveSeeds.split(',')
146 >
147 >  # FUTURE: This function tests the CMSSW version. Can be simplified as we drop support for old versions
148 >  if CMSSW_major < 2 or (CMSSW_major == 2 and CMSSW_minor == 0): # Treatment for seeds, CMSSW < 2_1_x
149 >    if cfg.data.services.has_key('RandomNumberGeneratorService'):
150 >      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
151 >      ranModules   = ranGenerator.moduleSeeds
152  
153 <  cfg.insertSeeds(*seedTuple)
153 >      sourceSeed = int(ranGenerator.sourceSeed.value())
154 >      if 'sourceSeed' in preserveSeedList:
155 >        pass
156 >      elif 'sourceSeed' in incrementSeedList:
157 >        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
158 >      else:
159 >        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
160 >
161 >      for seed in incrementSeedList:
162 >        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
163 >        if curSeed:
164 >          curValue = int(curSeed.value())
165 >          setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
166 >          preserveSeedList.append(seed)
167 >
168 >      for seed in ranGenerator.moduleSeeds.parameterNames_():
169 >        if seed not in preserveSeedList:
170 >          curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
171 >          if curSeed:
172 >            curValue = int(curSeed.value())
173 >            setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT))))
174 >  else: # Treatment for  seeds, CMSSW 2_1_x and later
175 >    if cfg.data.services.has_key('RandomNumberGeneratorService'):
176 >      from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
177 >
178 >      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
179 >      randSvc = RandomNumberServiceHelper(ranGenerator)
180 >      # sourceSeed is different from the rest, John says will become "theSource"
181 >      if 'sourceSeed' in preserveSeedList:
182 >        pass
183 >      elif 'sourceSeed' in incrementSeedList:
184 >        sourceSeed = int(ranGenerator.sourceSeed.value())
185 >        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
186 >      else:
187 >        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
188 >
189 >      # Increment requested seed sets
190 >      for seedName in incrementSeedList:
191 >        curSeeds = randSvc.getNamedSeed(seedName)
192 >        newSeeds = [x+nJob for x in curSeeds]
193 >        randSvc.setNamedSeed(seedName,*newSeeds)
194 >        preserveSeedList.append(seedName)
195  
196 <  # Write out new config file
196 >      # Randomize remaining seeds
197 >      randSvc.populate(*preserveSeedList)
198  
199 +  # End version specific code
200 +
201 +  # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
202    outFile = open(outFileName,"w")
203 <  outFile.write("import FWCore.ParameterSet.Config as cms\n")
204 <  outFile.write(cfo.dumpPython())
203 >  if outFileName.endswith('py'):
204 >    outFile.write("import FWCore.ParameterSet.Config as cms\n")
205 >    outFile.write(cmsProcess.dumpPython())
206 >    if (debug):
207 >      print "writeCfg output:"
208 >      print "import FWCore.ParameterSet.Config as cms"
209 >      print cmsProcess.dumpPython()
210 >  else:
211 >    outFile.write(str(cfg))
212 >    if (debug):
213 >      print "writeCfg output:"
214 >      print str(cfg)
215    outFile.close()
216  
147  if (debug):
148    print "writeCfg output:"
149    print "import FWCore.ParameterSet.Config as cms"
150    print cfo.dumpPython()
151
217  
218   if __name__ == '__main__' :
219      exit_status = main(sys.argv[1:])
220      sys.exit(exit_status)
156

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines