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.3.4.1 by ewv, Fri Apr 4 12:55:47 2008 UTC vs.
Revision 1.18 by ewv, Mon May 4 21:45:43 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 <
53 <  try:
54 <    opts, args = getopt.getopt(argv, "", ["debug", "help"])
55 <  except getopt.GetoptError:
56 <    print main.__doc__
57 <    sys.exit(2)
58 <
59 <  try:
60 <    CMSSW  = os.environ['CMSSW_VERSION']
61 <    parts = CMSSW.split('_')
62 <    CMSSW_major = int(parts[1])
63 <    CMSSW_minor = int(parts[2])
64 <    CMSSW_patch = int(parts[3])
65 <  except KeyError, ValueError:
66 <    msg = "Your environment doesn't specify the CMSSW version or specifies it incorrectly"
67 <    raise ConfigException(msg)
68 <
69 <  # Parse command line options
70 <  for opt, arg in opts :
71 <    if opt  == "--help" :
72 <      print main.__doc__
73 <      sys.exit()
74 <    elif opt == "--debug" :
75 <      debug = True
76 <
77 <  # Parse remaining parameters
78 <
79 <  try:
80 <    fileName    = args[0];
81 <    outFileName = args[1];
82 <  except IndexError:
83 <      print main.__doc__
84 <      sys.exit()
85 <
86 < # Optional Parameters
87 <
88 <  maxEvents  = int(os.environ.get('MaxEvents','0'))
89 <  skipEvents = int(os.environ.get('SkipEvents','0'))
90 <  inputFiles = os.environ.get('InputFiles','')
91 <  firstRun   = int(os.environ.get('FirstRun','0'))
92 <  nJob       = int(os.environ.get('NJob','0'))
93 <  preserveSeeds = os.environ.get('PreserveSeeds','')
94 <  incrementSeeds = os.environ.get('IncrementSeeds','')
95 <
96 < # Read Input cfg or python cfg file
97 <
98 <  if (fileName.endswith('py') or fileName.endswith('pycfg') ):
99 <    handle = open(fileName, 'r')
100 <    try:   # Nested form for Python < 2.5
101 <      try:
102 <        cfo = imp.load_source("pycfg", fileName, handle)
103 <      except Exception, ex:
104 <        msg = "Your pycfg file is not valid python: %s" % str(ex)
105 <        raise "Error: ",msg
106 <    finally:
107 <        handle.close()
108 <    cfg = CfgInterface(cfo.process)
109 <  else:
110 <    try:
111 <      cfo = include(fileName)
112 <      cfg = CfgInterface(cfo)
113 <    except Exception, ex:
114 <      msg =  "The cfg file is not valid, %s\n" % str(ex)
115 <      raise "Error: ",msg
116 <  inModule = cfg.inputSource
117 <
118 <  # Set parameters for job
119 <  if maxEvents:
120 <    cfg.maxEvents.setMaxEventsInput(maxEvents)
121 <
122 <  if skipEvents:
123 <    inModule.setSkipEvents(skipEvents)
124 <
125 <  if inputFiles:
126 <    inputFiles = inputFiles.replace('\\','')
127 <    inputFiles = inputFiles.replace('"','')
128 <    inputFileNames = inputFiles.split(',')
129 <    inModule.setFileNames(*inputFileNames)
130 <
131 <  # FUTURE: This function tests the CMSSW version. Can be simplified as we drop support for old versions
132 <  # Pythia parameters
133 <  if (firstRun):
134 <    inModule.setFirstRun(firstRun)
135 <
136 <  incrementSeedList = []
137 <  preserveSeedList  = []
138 <
139 <  if incrementSeeds:
140 <    incrementSeedList = incrementSeeds.split(',')
141 <  if preserveSeeds:
142 <    preserveSeedList  = preserveSeeds.split(',')
143 <
144 <  if CMSSW_major < 3: # True for now, should be < 2 when really ready
145 <  # Treatment for seeds, CMSSW < 2_0_x
146 <    if cfg.data.services.has_key('RandomNumberGeneratorService'):
147 <      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
148 <      ranModules   = ranGenerator.moduleSeeds
149 <
150 <      _MAXINT = 900000000
151 <
152 <      sourceSeed = int(ranGenerator.sourceSeed.value())
153 <      if 'sourceSeed' in preserveSeedList:
154 <        pass
155 <      elif 'sourceSeed' in incrementSeedList:
156 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
157 <      else:
158 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
159 <
160 <      for seed in incrementSeedList:
161 <        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
162 <        if curSeed:
163 <          curValue = int(curSeed.value())
164 <          setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
165 <          preserveSeedList.append(seed)
166 <
167 <      try:
168 <        seedList = ranGenerator.moduleSeeds.parameters().keys()
169 <      except: # Needed for 1_6_7. Above line is good for 1_6_10
170 <        seedList = ranGenerator.moduleSeeds.parameterNames_()
171 <
172 <      for seed in seedList:
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 <  else:
179 <    # Treatment for  seeds, CMSSW => 2_0_x
180 < #from RandomService import RandomSeedService
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 >    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 <    # This code not currently working because randSvc is not part of the actual configuration file
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 <    # Translate old format to new format first
186 <    randSvc = RandomSeedService()
84 >    # Parse remaining parameters
85      try:
86 <      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
87 <      ranModules   = ranGenerator.moduleSeeds
88 <      for seed in ranGenerator.moduleSeeds.parameters().keys():
89 <        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
90 <        curValue = int(curSeed.value())
91 <        setattr(randSvc,seed,CfgTypes.PSet())
92 <        curPSet = getattr(randSvc,seed,None)
93 <        curPSet.initialSeed = CfgTypes.untracked(CfgTypes.uint32(curValue))
94 <      del ranGenerator.moduleSeeds # Get rid of seeds in old format
95 < # Doesn't work, filter is false      randSvc.populate()
96 <
97 <    except:
98 <      print "Problems converting old seeds to new format"
99 <
100 <  # Write out new config file in one format or the other
101 <
102 <  outFile = open(outFileName,"w")
103 <  if (outFileName.endswith('py') or outFileName.endswith('pycfg') ):
104 <    outFile.write("import FWCore.ParameterSet.Config as cms\n")
105 <    outFile.write(cfo.dumpPython())
106 <    if (debug):
107 <      print "writeCfg output:"
108 <      print "import FWCore.ParameterSet.Config as cms"
109 <      print cfo.dumpPython()
110 <  else:
111 <    outFile.write(str(cfg))
112 <    if (debug):
113 <      print "writeCfg output:"
114 <      print str(cfg)
115 <  outFile.close()
86 >        fileName    = args[0]
87 >        outFileName = args[1]
88 >    except IndexError:
89 >        print main.__doc__
90 >        sys.exit()
91 >
92 >  # Read in XML and get optional Parameters
93 >
94 >    nJob       = int(os.environ.get('NJob',      '0'))
95 >
96 >  # Defaults
97 >
98 >    maxEvents  = 0
99 >    skipEvents = 0
100 >    firstEvent = -1
101 >    compHEPFirstEvent = 0
102 >    firstRun   = 0
103 >
104 >    dom = xml.dom.minidom.parse(os.environ['RUNTIME_AREA']+'/arguments.xml')
105 >
106 >    for elem in dom.getElementsByTagName("Job"):
107 >        if nJob == int(elem.getAttribute("JobID")):
108 >            if elem.getAttribute("MaxEvents"):
109 >                maxEvents = int(elem.getAttribute("MaxEvents"))
110 >            if elem.getAttribute("SkipEvents"):
111 >                skipEvents = int(elem.getAttribute("SkipEvents"))
112 >            if elem.getAttribute("FirstEvent"):
113 >                firstEvent = int(elem.getAttribute("FirstEvent"))
114 >            if elem.getAttribute("CompHEPFirstEvent"):
115 >                compHEPFirstEvent = int(elem.getAttribute("CompHEPFirstEvent"))
116 >            if elem.getAttribute("FirstRun"):
117 >                firstRun = int(elem.getAttribute("FirstRun"))
118 >
119 >            inputFiles     = str(elem.getAttribute('InputFiles'))
120 >            parentFiles    = str(elem.getAttribute('ParentFiles'))
121 >            preserveSeeds  = str(elem.getAttribute('PreserveSeeds'))
122 >            incrementSeeds = str(elem.getAttribute('IncrementSeeds'))
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 >    if firstEvent != -1:
158 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
159 >    if compHEPFirstEvent:
160 >        cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(compHEPFirstEvent)
161 >    if inputFiles:
162 >        inputFileNames = inputFiles.split(',')
163 >        inModule.setFileNames(*inputFileNames)
164 >
165 >    # handle parent files if needed
166 >    if parentFiles:
167 >        parentFileNames = parentFiles.split(',')
168 >        inModule.setSecondaryFileNames(*parentFileNames)
169 >
170 >    # Pythia parameters
171 >    if (firstRun):
172 >        inModule.setFirstRun(firstRun)
173 >
174 >    incrementSeedList = []
175 >    preserveSeedList  = []
176 >
177 >    if incrementSeeds:
178 >        incrementSeedList = incrementSeeds.split(',')
179 >    if preserveSeeds:
180 >        preserveSeedList  = preserveSeeds.split(',')
181 >
182 >    # FUTURE: This function tests the CMSSW version and presence of old-style seed specification.
183 >    # Reduce when we drop support for old versions
184 >    if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
185 >        print "RandomNumberGeneratorService found, will attempt to change seeds"
186 >        ranGenerator = cfg.data.services['RandomNumberGeneratorService']
187 >        ranModules   = getattr(ranGenerator, "moduleSeeds", None)
188 >        oldSource    = getattr(ranGenerator, "sourceSeed",  None)
189 >        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
190 >            print "Old-style random number seeds found, will be changed."
191 >            if oldSource != None:
192 >                sourceSeed = int(ranGenerator.sourceSeed.value())
193 >                if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
194 >                    pass
195 >                elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
196 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
197 >                else:
198 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1, _MAXINT)))
199 >
200 >            for seed in incrementSeedList:
201 >                curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
202 >                if curSeed:
203 >                    curValue = int(curSeed.value())
204 >                    setattr(ranGenerator.moduleSeeds, seed, CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
205 >                    preserveSeedList.append(seed)
206 >
207 >            if ranModules != None:
208 >                for seed in ranGenerator.moduleSeeds.parameterNames_():
209 >                    if seed not in preserveSeedList:
210 >                        curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
211 >                        if curSeed:
212 >                            curValue = int(curSeed.value())
213 >                            setattr(ranGenerator.moduleSeeds, seed,
214 >                                    CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1,_MAXINT))))
215 >        elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
216 >            print "New-style random number seeds found, will be changed."
217 >            from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
218 >            randSvc = RandomNumberServiceHelper(ranGenerator)
219 >
220 >            # Increment requested seed sets
221 >            for seedName in incrementSeedList:
222 >                curSeeds = randSvc.getNamedSeed(seedName)
223 >                newSeeds = [x+nJob for x in curSeeds]
224 >                randSvc.setNamedSeed(seedName, *newSeeds)
225 >                preserveSeedList.append(seedName)
226 >
227 >            # Randomize remaining seeds
228 >            randSvc.populate(*preserveSeedList)
229 >        else:
230 >            print "Neither old nor new seed format found!"
231 >
232 >      # End version specific code
233 >
234 >    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
235 >    outFile = open(outFileName,"w")
236 >    if outFileName.endswith('py'):
237 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
238 >        outFile.write("import pickle\n")
239 >        outFile.write("pickledCfg=\"\"\"%s\"\"\"\n" % pickle.dumps(cmsProcess))
240 >        outFile.write("process = pickle.loads(pickledCfg)\n")
241 >        if (debug):
242 >            print "writeCfg output (May not be exact):"
243 >            print "import FWCore.ParameterSet.Config as cms"
244 >            print cmsProcess.dumpPython()
245 >    else:
246 >        outFile.write(cfg.data.dumpConfig())
247 >        if (debug):
248 >            print "writeCfg output:"
249 >            print str(cfg.data.dumpConfig())
250 >    outFile.close()
251  
252  
253   if __name__ == '__main__' :
254      exit_status = main(sys.argv[1:])
255      sys.exit(exit_status)
223

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines