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.7 by ewv, Tue May 6 01:09:58 2008 UTC vs.
Revision 1.22 by ewv, Wed Jul 29 21:20:03 2009 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2  
3 < import sys, getopt, string
3 > """
4 > Re-write config file and optionally convert to python
5 > """
6 >
7 > __revision__ = "$Id$"
8 > __version__ = "$Revision$"
9 >
10 > import getopt
11   import imp
12   import os
13 < import random
13 > import pickle
14 > import sys
15 > import xml.dom.minidom
16 >
17   from random import SystemRandom
8 _inst  = SystemRandom()
18  
19   from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
20 < from FWCore.ParameterSet.DictTypes import SortedKeysDict
21 < from FWCore.ParameterSet.Modules   import Service
13 < from FWCore.ParameterSet.Types     import *
14 < from FWCore.ParameterSet.Config    import include
20 > from FWCore.ParameterSet.Config                       import include
21 > import FWCore.ParameterSet.Types as CfgTypes
22  
23 < import FWCore.ParameterSet.Types   as CfgTypes
17 < import FWCore.ParameterSet.Modules as CfgModules
23 > MyRandom  = SystemRandom()
24  
25   class ConfigException(Exception):
26 +    """
27 +    Exceptions raised by writeCfg
28 +    """
29 +
30      def __init__(self, msg):
31          Exception.__init__(self, msg)
32          self._msg = msg
# Line 26 | Line 36 | class ConfigException(Exception):
36          return self._msg
37  
38   def main(argv) :
39 <  """
40 <  writeCfg
39 >    """
40 >    writeCfg
41 >
42 >    - Read in existing, user supplied cfg or pickled pycfg file
43 >    - Modify job specific parameters based on environment variables and arguments.xml
44 >    - Write out modified cfg or pickled pycfg file
45 >
46 >    required parameters: none
47 >
48 >    optional parameters:
49 >    --help             :       help
50 >    --debug            :       debug statements
51 >
52 >    """
53 >
54 >    # defaults
55 >    inputFileNames  = None
56 >    parentFileNames = None
57 >    debug           = False
58 >    _MAXINT         = 900000000
59 >
60 >    try:
61 >        opts, args = getopt.getopt(argv, "", ["debug", "help"])
62 >    except getopt.GetoptError:
63 >        print main.__doc__
64 >        sys.exit(2)
65 >
66 >    try:
67 >        CMSSW  = os.environ['CMSSW_VERSION']
68 >        parts = CMSSW.split('_')
69 >        CMSSW_major = int(parts[1])
70 >        CMSSW_minor = int(parts[2])
71 >        CMSSW_patch = int(parts[3])
72 >    except (KeyError, ValueError):
73 >        msg = "Your environment doesn't specify the CMSSW version or specifies it incorrectly"
74 >        raise ConfigException(msg)
75 >
76 >    # Parse command line options
77 >    for opt, arg in opts :
78 >        if opt  == "--help" :
79 >            print main.__doc__
80 >            sys.exit()
81 >        elif opt == "--debug" :
82 >            debug = True
83  
84 <  - Read in existing, user supplied cfg or pycfg file
33 <  - Modify job specific parameters based on environment variables
34 <  - Write out modified cfg or pycfg file
35 <
36 <  required parameters: none
37 <
38 <  optional parameters:
39 <  --help             :       help
40 <  --debug            :       debug statements
41 <
42 <  """
43 <
44 <  # defaults
45 <  inputFileNames = None
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"])
57 <  except getopt.GetoptError:
58 <    print main.__doc__
59 <    sys.exit(2)
60 <
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
78 <
79 <  # Parse remaining parameters
80 <
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 < # 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()
112 <  else:
84 >    # Parse remaining parameters
85      try:
86 <      cfo = include(fileName)
87 <      cmsProcess = cfo
88 <    except Exception, ex:
89 <      msg =  "The cfg file is not valid, %s\n" % str(ex)
90 <      raise "Error: ",msg
91 <  cfg = CfgInterface(cmsProcess)
92 <
93 <  # Set parameters for job
94 <  inModule = cfg.inputSource
95 <  if maxEvents:
96 <    cfg.maxEvents.setMaxEventsInput(maxEvents)
97 <
98 <  if skipEvents:
99 <    inModule.setSkipEvents(skipEvents)
100 <
101 <  if inputFiles:
102 <    inputFiles = inputFiles.replace('\\','')
103 <    inputFiles = inputFiles.replace('"','')
104 <    inputFileNames = inputFiles.split(',')
105 <    inModule.setFileNames(*inputFileNames)
106 <
107 <  # Pythia parameters
108 <  if (firstRun):
109 <    inModule.setFirstRun(firstRun)
110 <
111 <  incrementSeedList = []
112 <  preserveSeedList  = []
113 <
114 <  if incrementSeeds:
115 <    incrementSeedList = incrementSeeds.split(',')
116 <  if preserveSeeds:
117 <    preserveSeedList  = preserveSeeds.split(',')
118 <
119 <  # FUTURE: This function tests the CMSSW version. Can be simplified as we drop support for old versions
120 <  if CMSSW_major < 2 or (CMSSW_major == 2 and CMSSW_minor == 0): # Treatment for seeds, CMSSW < 2_1_x
121 <    if cfg.data.services.has_key('RandomNumberGeneratorService'):
122 <      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
123 <      ranModules   = ranGenerator.moduleSeeds
124 <
125 <      sourceSeed = int(ranGenerator.sourceSeed.value())
126 <      if 'sourceSeed' in preserveSeedList:
127 <        pass
128 <      elif 'sourceSeed' in incrementSeedList:
129 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
130 <      else:
131 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
132 <
133 <      for seed in incrementSeedList:
134 <        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
135 <        if curSeed:
136 <          curValue = int(curSeed.value())
137 <          setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
138 <          preserveSeedList.append(seed)
139 <
140 <      for seed in ranGenerator.moduleSeeds.parameterNames_():
141 <        if seed not in preserveSeedList:
142 <          curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
143 <          if curSeed:
144 <            curValue = int(curSeed.value())
145 <            setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT))))
146 <  else: # Treatment for  seeds, CMSSW 2_1_x and later
147 <    if cfg.data.services.has_key('RandomNumberGeneratorService'):
148 <      from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
149 <
150 <      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
151 <      randSvc = RandomNumberServiceHelper(ranGenerator)
152 <      # sourceSeed is different from the rest, John says will become "theSource"
153 <      if 'sourceSeed' in preserveSeedList:
154 <        pass
155 <      elif 'sourceSeed' in incrementSeedList:
156 <        sourceSeed = int(ranGenerator.sourceSeed.value())
157 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
158 <      else:
159 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
160 <
161 <      # Increment requested seed sets
162 <      for seedName in incrementSeedList:
163 <        curSeeds = randSvc.getNamedSeed(seedName)
164 <        newSeeds = [x+nJob for x in curSeeds]
165 <        randSvc.setNamedSeed(seedName,*newSeeds)
166 <        preserveSeedList.append(seedName)
167 <
168 <      # Randomize remaining seeds
169 <      randSvc.populate(*preserveSeedList)
170 <
171 <  # End version specific code
172 <
173 <  # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
174 <  outFile = open(outFileName,"w")
175 <  if outFileName.endswith('py'):
176 <    outFile.write("import FWCore.ParameterSet.Config as cms\n")
177 <    outFile.write(cmsProcess.dumpPython())
178 <    if (debug):
179 <      print "writeCfg output:"
180 <      print "import FWCore.ParameterSet.Config as cms"
181 <      print cmsProcess.dumpPython()
182 <  else:
183 <    outFile.write(str(cfg))
184 <    if (debug):
185 <      print "writeCfg output:"
186 <      print str(cfg)
187 <  outFile.close()
86 >        fileName    = args[0]
87 >        outFileName = args[1]
88 >    except IndexError:
89 >        print main.__doc__
90 >        sys.exit()
91 >
92 >  # Read in Environment, XML and get optional Parameters
93 >
94 >    nJob       = int(os.environ.get('NJob',      '0'))
95 >    preserveSeeds  = os.environ.get('PreserveSeeds','')
96 >    incrementSeeds = os.environ.get('IncrementSeeds','')
97 >
98 >  # Defaults
99 >
100 >    maxEvents  = 0
101 >    skipEvents = 0
102 >    firstEvent = -1
103 >    compHEPFirstEvent = 0
104 >    firstRun   = 0
105 >
106 >    dom = xml.dom.minidom.parse(os.environ['RUNTIME_AREA']+'/arguments.xml')
107 >
108 >    for elem in dom.getElementsByTagName("Job"):
109 >        if nJob == int(elem.getAttribute("JobID")):
110 >            if elem.getAttribute("MaxEvents"):
111 >                maxEvents = int(elem.getAttribute("MaxEvents"))
112 >            if elem.getAttribute("SkipEvents"):
113 >                skipEvents = int(elem.getAttribute("SkipEvents"))
114 >            if elem.getAttribute("FirstEvent"):
115 >                firstEvent = int(elem.getAttribute("FirstEvent"))
116 >            if elem.getAttribute("FirstRun"):
117 >                firstRun = int(elem.getAttribute("FirstRun"))
118 >
119 >            generator      = str(elem.getAttribute('Generator'))
120 >            inputFiles     = str(elem.getAttribute('InputFiles'))
121 >            parentFiles    = str(elem.getAttribute('ParentFiles'))
122 >            lumis          = str(elem.getAttribute('Lumis'))
123 >
124 >  # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
125 >
126 >    if fileName.endswith('py'):
127 >        handle = open(fileName, 'r')
128 >        try:   # Nested form for Python < 2.5
129 >            try:
130 >                print "Importing .py file"
131 >                cfo = imp.load_source("pycfg", fileName, handle)
132 >                cmsProcess = cfo.process
133 >            except Exception, ex:
134 >                msg = "Your pycfg file is not valid python: %s" % str(ex)
135 >                raise ConfigException(msg)
136 >        finally:
137 >            handle.close()
138 >    else:
139 >        try:
140 >            print "Importing .cfg file"
141 >            cfo = include(fileName)
142 >            cmsProcess = cfo
143 >        except Exception, ex:
144 >            msg =  "The cfg file is not valid, %s\n" % str(ex)
145 >            raise ConfigException(msg)
146 >
147 >    cfg = CfgInterface(cmsProcess)
148 >
149 >    # Set parameters for job
150 >    print "Setting parameters"
151 >    inModule = cfg.inputSource
152 >    if maxEvents:
153 >        cfg.maxEvents.setMaxEventsInput(maxEvents)
154 >
155 >    if skipEvents:
156 >        inModule.setSkipEvents(skipEvents)
157 >
158 >    # Set "skip events" for various generators
159 >    if generator == 'comphep':
160 >        cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(firstEvent)
161 >    elif generator == 'lhe':
162 >        cmsProcess.source.skipEvents = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
163 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent+1))
164 >    elif firstEvent != -1: # (Old? Madgraph)
165 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
166 >
167 >    if inputFiles:
168 >        inputFileNames = inputFiles.split(',')
169 >        inModule.setFileNames(*inputFileNames)
170 >
171 >    # handle parent files if needed
172 >    if parentFiles:
173 >        parentFileNames = parentFiles.split(',')
174 >        inModule.setSecondaryFileNames(*parentFileNames)
175 >
176 >    if lumis:
177 >        lumiRanges = lumis.split(',')
178 >        inModule.setLumisToProcess(*lumiRanges)
179 >
180 >    # Pythia parameters
181 >    if (firstRun):
182 >        inModule.setFirstRun(firstRun)
183 >
184 >    incrementSeedList = []
185 >    preserveSeedList  = []
186 >
187 >    if incrementSeeds:
188 >        incrementSeedList = incrementSeeds.split(',')
189 >    if preserveSeeds:
190 >        preserveSeedList  = preserveSeeds.split(',')
191 >
192 >    # FUTURE: This function tests the CMSSW version and presence of old-style seed specification.
193 >    # Reduce when we drop support for old versions
194 >    if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
195 >        print "RandomNumberGeneratorService found, will attempt to change seeds"
196 >        ranGenerator = cfg.data.services['RandomNumberGeneratorService']
197 >        ranModules   = getattr(ranGenerator, "moduleSeeds", None)
198 >        oldSource    = getattr(ranGenerator, "sourceSeed",  None)
199 >        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
200 >            print "Old-style random number seeds found, will be changed."
201 >            if oldSource != None:
202 >                sourceSeed = int(ranGenerator.sourceSeed.value())
203 >                if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
204 >                    pass
205 >                elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
206 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
207 >                else:
208 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1, _MAXINT)))
209 >
210 >            for seed in incrementSeedList:
211 >                curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
212 >                if curSeed:
213 >                    curValue = int(curSeed.value())
214 >                    setattr(ranGenerator.moduleSeeds, seed, CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
215 >                    preserveSeedList.append(seed)
216 >
217 >            if ranModules != None:
218 >                for seed in ranGenerator.moduleSeeds.parameterNames_():
219 >                    if seed not in preserveSeedList:
220 >                        curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
221 >                        if curSeed:
222 >                            curValue = int(curSeed.value())
223 >                            setattr(ranGenerator.moduleSeeds, seed,
224 >                                    CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1,_MAXINT))))
225 >        elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
226 >            print "New-style random number seeds found, will be changed."
227 >            from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
228 >            randSvc = RandomNumberServiceHelper(ranGenerator)
229 >
230 >            # Increment requested seed sets
231 >            for seedName in incrementSeedList:
232 >                curSeeds = randSvc.getNamedSeed(seedName)
233 >                newSeeds = [x+nJob for x in curSeeds]
234 >                randSvc.setNamedSeed(seedName, *newSeeds)
235 >                preserveSeedList.append(seedName)
236 >
237 >            # Randomize remaining seeds
238 >            randSvc.populate(*preserveSeedList)
239 >        else:
240 >            print "Neither old nor new seed format found!"
241 >
242 >      # End version specific code
243 >
244 >    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
245 >    outFile = open(outFileName,"w")
246 >    if outFileName.endswith('py'):
247 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
248 >        outFile.write("import pickle\n")
249 >        outFile.write("pickledCfg=\"\"\"%s\"\"\"\n" % pickle.dumps(cmsProcess))
250 >        outFile.write("process = pickle.loads(pickledCfg)\n")
251 >        if (debug):
252 >            print "writeCfg output (May not be exact):"
253 >            print "import FWCore.ParameterSet.Config as cms"
254 >            print cmsProcess.dumpPython()
255 >    else:
256 >        outFile.write(cfg.data.dumpConfig())
257 >        if (debug):
258 >            print "writeCfg output:"
259 >            print str(cfg.data.dumpConfig())
260 >    outFile.close()
261  
262  
263   if __name__ == '__main__' :

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines