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.10 by ewv, Wed May 21 19:27:30 2008 UTC vs.
Revision 1.20 by ewv, Wed Jun 17 20:58:08 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 pycfg file
43 <  - Modify job specific parameters based on environment variables
44 <  - Write out modified cfg or 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 <  firstRun       = 0
57 <  sourceSeed     = 0
58 <  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:
113 <    try:
114 <      print "Importing .cfg file"
115 <      cfo = include(fileName)
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 <  print "Setting parameters"
125 <  inModule = cfg.inputSource
126 <  if maxEvents:
127 <    cfg.maxEvents.setMaxEventsInput(maxEvents)
128 <
129 <  if skipEvents:
130 <    inModule.setSkipEvents(skipEvents)
131 <
132 <  if inputFiles:
133 <    inputFiles = inputFiles.replace('\\','')
134 <    inputFiles = inputFiles.replace('"','')
135 <    inputFileNames = inputFiles.split(',')
136 <    inModule.setFileNames(*inputFileNames)
137 <
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)
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 <      # Randomize remaining seeds
61 <      randSvc.populate(*preserveSeedList)
62 <    else:
63 <      print "Neither old nor new seed format found!"
60 >    try:
61 >        opts, args = getopt.getopt(argv, "", ["debug", "help"])
62 >    except getopt.GetoptError:
63 >        print main.__doc__
64 >        sys.exit(2)
65  
66 <    # End version specific code
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 <  # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
85 <  outFile = open(outFileName,"w")
86 <  if outFileName.endswith('py'):
87 <    outFile.write("import FWCore.ParameterSet.Config as cms\n")
88 <    outFile.write(cmsProcess.dumpPython())
89 <    if (debug):
90 <      print "writeCfg output:"
91 <      print "import FWCore.ParameterSet.Config as cms"
92 <      print cmsProcess.dumpPython()
93 <  else:
94 <    outFile.write(str(cfg))
95 <    if (debug):
96 <      print "writeCfg output:"
97 <      print str(cfg)
98 <  outFile.close()
84 >    # Parse remaining parameters
85 >    try:
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 >
123 >  # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
124 >
125 >    if fileName.endswith('py'):
126 >        handle = open(fileName, 'r')
127 >        try:   # Nested form for Python < 2.5
128 >            try:
129 >                print "Importing .py file"
130 >                cfo = imp.load_source("pycfg", fileName, handle)
131 >                cmsProcess = cfo.process
132 >            except Exception, ex:
133 >                msg = "Your pycfg file is not valid python: %s" % str(ex)
134 >                raise ConfigException(msg)
135 >        finally:
136 >            handle.close()
137 >    else:
138 >        try:
139 >            print "Importing .cfg file"
140 >            cfo = include(fileName)
141 >            cmsProcess = cfo
142 >        except Exception, ex:
143 >            msg =  "The cfg file is not valid, %s\n" % str(ex)
144 >            raise ConfigException(msg)
145 >
146 >    cfg = CfgInterface(cmsProcess)
147 >
148 >    # Set parameters for job
149 >    print "Setting parameters"
150 >    inModule = cfg.inputSource
151 >    if maxEvents:
152 >        cfg.maxEvents.setMaxEventsInput(maxEvents)
153 >
154 >    if skipEvents:
155 >        inModule.setSkipEvents(skipEvents)
156 >
157 >    # Set "skip events" for various generators
158 >    if generator == 'comphep':
159 >        cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(firstEvent)
160 >    elif generator == 'lhe':
161 >        cmsProcess.LHESource.skipEvents = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
162 >    elif firstEvent != -1: # (Old? Madgraph)
163 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
164 >
165 >    if inputFiles:
166 >        inputFileNames = inputFiles.split(',')
167 >        inModule.setFileNames(*inputFileNames)
168 >
169 >    # handle parent files if needed
170 >    if parentFiles:
171 >        parentFileNames = parentFiles.split(',')
172 >        inModule.setSecondaryFileNames(*parentFileNames)
173 >
174 >    # Pythia parameters
175 >    if (firstRun):
176 >        inModule.setFirstRun(firstRun)
177 >
178 >    incrementSeedList = []
179 >    preserveSeedList  = []
180 >
181 >    if incrementSeeds:
182 >        incrementSeedList = incrementSeeds.split(',')
183 >    if preserveSeeds:
184 >        preserveSeedList  = preserveSeeds.split(',')
185 >
186 >    # FUTURE: This function tests the CMSSW version and presence of old-style seed specification.
187 >    # Reduce when we drop support for old versions
188 >    if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
189 >        print "RandomNumberGeneratorService found, will attempt to change seeds"
190 >        ranGenerator = cfg.data.services['RandomNumberGeneratorService']
191 >        ranModules   = getattr(ranGenerator, "moduleSeeds", None)
192 >        oldSource    = getattr(ranGenerator, "sourceSeed",  None)
193 >        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
194 >            print "Old-style random number seeds found, will be changed."
195 >            if oldSource != None:
196 >                sourceSeed = int(ranGenerator.sourceSeed.value())
197 >                if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
198 >                    pass
199 >                elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
200 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
201 >                else:
202 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1, _MAXINT)))
203 >
204 >            for seed in incrementSeedList:
205 >                curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
206 >                if curSeed:
207 >                    curValue = int(curSeed.value())
208 >                    setattr(ranGenerator.moduleSeeds, seed, CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
209 >                    preserveSeedList.append(seed)
210 >
211 >            if ranModules != None:
212 >                for seed in ranGenerator.moduleSeeds.parameterNames_():
213 >                    if seed not in preserveSeedList:
214 >                        curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
215 >                        if curSeed:
216 >                            curValue = int(curSeed.value())
217 >                            setattr(ranGenerator.moduleSeeds, seed,
218 >                                    CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1,_MAXINT))))
219 >        elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
220 >            print "New-style random number seeds found, will be changed."
221 >            from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
222 >            randSvc = RandomNumberServiceHelper(ranGenerator)
223 >
224 >            # Increment requested seed sets
225 >            for seedName in incrementSeedList:
226 >                curSeeds = randSvc.getNamedSeed(seedName)
227 >                newSeeds = [x+nJob for x in curSeeds]
228 >                randSvc.setNamedSeed(seedName, *newSeeds)
229 >                preserveSeedList.append(seedName)
230 >
231 >            # Randomize remaining seeds
232 >            randSvc.populate(*preserveSeedList)
233 >        else:
234 >            print "Neither old nor new seed format found!"
235 >
236 >      # End version specific code
237 >
238 >    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
239 >    outFile = open(outFileName,"w")
240 >    if outFileName.endswith('py'):
241 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
242 >        outFile.write("import pickle\n")
243 >        outFile.write("pickledCfg=\"\"\"%s\"\"\"\n" % pickle.dumps(cmsProcess))
244 >        outFile.write("process = pickle.loads(pickledCfg)\n")
245 >        if (debug):
246 >            print "writeCfg output (May not be exact):"
247 >            print "import FWCore.ParameterSet.Config as cms"
248 >            print cmsProcess.dumpPython()
249 >    else:
250 >        outFile.write(cfg.data.dumpConfig())
251 >        if (debug):
252 >            print "writeCfg output:"
253 >            print str(cfg.data.dumpConfig())
254 >    outFile.close()
255  
256  
257   if __name__ == '__main__' :

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines