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.23 by ewv, Thu Jul 30 18:45:44 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
33 +        return
34 +
35 +    def __str__(self):
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  
24  - Read in existing, user supplied cfg or pycfg file
25  - Modify job specific parameters based on environment variables
26  - Write out modified cfg or pycfg file
27
28  required parameters: none
29
30  optional parameters:
31  --help             :       help
32  --debug            :       debug statements
33
34  """
35
36  # defaults
37  maxEvents      = 0
38  skipEvents     = 0
39  inputFileNames = None
40  firstRun       = 0
41  sourceSeed     = 0
42  vtxSeed        = 0
43  g4Seed         = 0
44  mixSeed        = 0
45  debug          = False
46
47  try:
48    opts, args = getopt.getopt(argv, "", ["debug", "help","inputFiles=","maxEvents=","skipEvents="])
49  except getopt.GetoptError:
50    print main.__doc__
51    sys.exit(2)
52
53  # Parse command line parameters
54  for opt, arg in opts :
55    if opt  == "--help" :
56      print main.__doc__
57      sys.exit()
58    elif opt == "--debug" :
59      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)
79
80  # Parse remaining parameters
81
82  fileName    = args[0];
83  outFileName = args[1];
84
85  # Input cfg or python cfg file
86
87  if (fileName.endswith('py') or fileName.endswith('pycfg') ):
88    handle = open(fileName, 'r')
89    try:   # Nested form for Python < 2.5
90      try:
91        cfo = imp.load_source("pycfg", fileName, handle)
92      except Exception, ex:
93        msg = "Your pycfg file is not valid python: %s" % str(ex)
94        raise "Error: ",msg
95    finally:
96        handle.close()
97    cfg = CfgInterface(cfo.process)
98  else:
60      try:
61 <      cfo = include(fileName)
62 <      cfg = CfgInterface(cfo)
63 <    except Exception, ex:
64 <      msg =  "The cfg file is not valid, %s\n" % str(ex)
65 <      raise "Error: ",msg
66 <
67 <  # Set parameters for job
68 <
69 <  inModule = cfg.inputSource
70 <
71 <  cfg.maxEvents.setMaxEventsInput(maxEvents)
72 <
73 <  inModule.setSkipEvents(skipEvents)
74 <  if (inputFileNames):
75 <    inModule.setFileNames(*inputFileNames)
76 <
77 <  # Pythia parameters
78 <  if (firstRun):
79 <    inModule.setFirstRun(firstRun)
80 <  if (sourceSeed) :
81 <    ranGenerator = cfg.data.services['RandomNumberGeneratorService']
82 <    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed))
83 <    if (vtxSeed) :
84 <      ranModules   = ranGenerator.moduleSeeds
85 <      ranModules.VtxSmeared = CfgTypes.untracked(CfgTypes.uint32(vtxSeed))
86 <    if (g4Seed) :
87 <      ranModules   = ranGenerator.moduleSeeds
88 <      ranModules.g4SimHits = CfgTypes.untracked(CfgTypes.uint32(g4Seed))
89 <    if (mixSeed) :
90 <      ranModules   = ranGenerator.moduleSeeds
91 <      ranModules.mix = CfgTypes.untracked(CfgTypes.uint32(mixSeed))
92 <
93 <  # Randomize all seeds
94 <
95 <  print "There are ",cfg.seedCount()," seeds"
96 <  seedList = [random.randint(100,200) for i in range(cfg.seedCount)]
97 <  seedTuple = seedList.tuple()
98 <
99 <  cfg.insertSeeds(*seedTuple)
100 <
101 <  # Write out new config file
102 <
103 <  outFile = open(outFileName,"w")
104 <  outFile.write("import FWCore.ParameterSet.Config as cms\n")
105 <  outFile.write(cfo.dumpPython())
106 <  outFile.close()
107 <
108 <  if (debug):
109 <    print "writeCfg output:"
110 <    print "import FWCore.ParameterSet.Config as cms"
111 <    print cfo.dumpPython()
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 >    # 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 >            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 >        if CMSSW_major < 3: # FUTURE: Can remove this check
178 >            print "Cannot skip lumis for CMSSW 2_x"
179 >        else:
180 >            lumiRanges = lumis.split(',')
181 >            inModule.setLumisToProcess(*lumiRanges)
182 >
183 >    # Pythia parameters
184 >    if (firstRun):
185 >        inModule.setFirstRun(firstRun)
186 >
187 >    incrementSeedList = []
188 >    preserveSeedList  = []
189 >
190 >    if incrementSeeds:
191 >        incrementSeedList = incrementSeeds.split(',')
192 >    if preserveSeeds:
193 >        preserveSeedList  = preserveSeeds.split(',')
194 >
195 >    # FUTURE: This function tests the CMSSW version and presence of old-style seed specification.
196 >    # Reduce when we drop support for old versions
197 >    if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
198 >        print "RandomNumberGeneratorService found, will attempt to change seeds"
199 >        ranGenerator = cfg.data.services['RandomNumberGeneratorService']
200 >        ranModules   = getattr(ranGenerator, "moduleSeeds", None)
201 >        oldSource    = getattr(ranGenerator, "sourceSeed",  None)
202 >        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
203 >            print "Old-style random number seeds found, will be changed."
204 >            if oldSource != None:
205 >                sourceSeed = int(ranGenerator.sourceSeed.value())
206 >                if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
207 >                    pass
208 >                elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
209 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
210 >                else:
211 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1, _MAXINT)))
212 >
213 >            for seed in incrementSeedList:
214 >                curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
215 >                if curSeed:
216 >                    curValue = int(curSeed.value())
217 >                    setattr(ranGenerator.moduleSeeds, seed, CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
218 >                    preserveSeedList.append(seed)
219 >
220 >            if ranModules != None:
221 >                for seed in ranGenerator.moduleSeeds.parameterNames_():
222 >                    if seed not in preserveSeedList:
223 >                        curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
224 >                        if curSeed:
225 >                            curValue = int(curSeed.value())
226 >                            setattr(ranGenerator.moduleSeeds, seed,
227 >                                    CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1,_MAXINT))))
228 >        elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
229 >            print "New-style random number seeds found, will be changed."
230 >            from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
231 >            randSvc = RandomNumberServiceHelper(ranGenerator)
232 >
233 >            # Increment requested seed sets
234 >            for seedName in incrementSeedList:
235 >                curSeeds = randSvc.getNamedSeed(seedName)
236 >                newSeeds = [x+nJob for x in curSeeds]
237 >                randSvc.setNamedSeed(seedName, *newSeeds)
238 >                preserveSeedList.append(seedName)
239 >
240 >            # Randomize remaining seeds
241 >            randSvc.populate(*preserveSeedList)
242 >        else:
243 >            print "Neither old nor new seed format found!"
244 >
245 >      # End version specific code
246 >
247 >    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
248 >    outFile = open(outFileName,"w")
249 >    if outFileName.endswith('py'):
250 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
251 >        outFile.write("import pickle\n")
252 >        outFile.write("pickledCfg=\"\"\"%s\"\"\"\n" % pickle.dumps(cmsProcess))
253 >        outFile.write("process = pickle.loads(pickledCfg)\n")
254 >        if (debug):
255 >            print "writeCfg output (May not be exact):"
256 >            print "import FWCore.ParameterSet.Config as cms"
257 >            print cmsProcess.dumpPython()
258 >    else:
259 >        outFile.write(cfg.data.dumpConfig())
260 >        if (debug):
261 >            print "writeCfg output:"
262 >            print str(cfg.data.dumpConfig())
263 >    outFile.close()
264  
265  
266   if __name__ == '__main__' :
267      exit_status = main(sys.argv[1:])
268      sys.exit(exit_status)
156

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines