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.16 by spiga, Thu Mar 5 16:49:56 2009 UTC vs.
Revision 1.25 by ewv, Fri Aug 28 18:56:43 2009 UTC

# Line 7 | Line 7 | Re-write config file and optionally conv
7   __revision__ = "$Id$"
8   __version__ = "$Revision$"
9  
10 < import sys, getopt
10 > import getopt
11   import imp
12   import os
13 + import pickle
14 + import sys
15 + import xml.dom.minidom
16 +
17   from random import SystemRandom
18  
19   from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
# Line 35 | Line 39 | def main(argv) :
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
42 >    - Read in existing, user supplied pycfg or pickled pycfg file
43 >    - Modify job specific parameters based on environment variables and arguments.xml
44 >    - Write out pickled pycfg file
45  
46      required parameters: none
47  
# Line 85 | Line 89 | def main(argv) :
89          print main.__doc__
90          sys.exit()
91  
92 <  # Optional Parameters
92 >  # Read in Environment, XML and get optional Parameters
93  
90    maxEvents  = int(os.environ.get('MaxEvents', '0'))
91    skipEvents = int(os.environ.get('SkipEvents','0'))
92    firstEvent = int(os.environ.get('FirstEvent','-1'))
93    compHEPFirstEvent = int(os.environ.get('CompHEPFirstEvent','0'))
94    firstRun   = int(os.environ.get('FirstRun',  '0'))
94      nJob       = int(os.environ.get('NJob',      '0'))
96
97    inputFiles     = os.environ.get('InputFiles','')
98    parentFiles    = os.environ.get('ParentFiles','')
95      preserveSeeds  = os.environ.get('PreserveSeeds','')
96      incrementSeeds = os.environ.get('IncrementSeeds','')
97  
98 <  # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
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 <    if fileName.endswith('py'):
125 <        handle = open(fileName, 'r')
126 <        try:   # Nested form for Python < 2.5
127 <            try:
108 <                print "Importing .py file"
109 <                cfo = imp.load_source("pycfg", fileName, handle)
110 <                cmsProcess = cfo.process
111 <            except Exception, ex:
112 <                msg = "Your pycfg file is not valid python: %s" % str(ex)
113 <                raise ConfigException(msg)
114 <        finally:
115 <            handle.close()
116 <    else:
124 >  # Read Input python config file
125 >
126 >    handle = open(fileName, 'r')
127 >    try:   # Nested form for Python < 2.5
128          try:
129 <            print "Importing .cfg file"
130 <            cfo = include(fileName)
131 <            cmsProcess = cfo
129 >            print "Importing .py file"
130 >            cfo = imp.load_source("pycfg", fileName, handle)
131 >            cmsProcess = cfo.process
132          except Exception, ex:
133 <            msg =  "The cfg file is not valid, %s\n" % str(ex)
133 >            msg = "Your pycfg file is not valid python: %s" % str(ex)
134              raise ConfigException(msg)
135 +    finally:
136 +        handle.close()
137  
138      cfg = CfgInterface(cmsProcess)
139  
# Line 132 | Line 145 | def main(argv) :
145  
146      if skipEvents:
147          inModule.setSkipEvents(skipEvents)
148 <    if firstEvent != -1:
148 >
149 >    # Set "skip events" for various generators
150 >    if generator == 'comphep':
151 >        cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(firstEvent)
152 >    elif generator == 'lhe':
153 >        cmsProcess.source.skipEvents = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
154 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent+1))
155 >    elif firstEvent != -1: # (Old? Madgraph)
156          cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
157 <    if compHEPFirstEvent:
138 <        cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(compHEPFirstEvent)
157 >
158      if inputFiles:
140        inputFiles = inputFiles.replace('\\','')
141        inputFiles = inputFiles.replace('"','')
159          inputFileNames = inputFiles.split(',')
160          inModule.setFileNames(*inputFileNames)
161  
162      # handle parent files if needed
163      if parentFiles:
147        parentFiles = parentFiles.replace('\\','')
148        parentFiles = parentFiles.replace('"','')
164          parentFileNames = parentFiles.split(',')
165          inModule.setSecondaryFileNames(*parentFileNames)
166  
167 +    if lumis:
168 +        if CMSSW_major < 3: # FUTURE: Can remove this check
169 +            print "Cannot skip lumis for CMSSW 2_x"
170 +        else:
171 +            lumiRanges = lumis.split(',')
172 +            inModule.setLumisToProcess(*lumiRanges)
173 +
174      # Pythia parameters
175      if (firstRun):
176          inModule.setFirstRun(firstRun)
177  
178 <    incrementSeedList = []
179 <    preserveSeedList  = []
158 <
159 <    if incrementSeeds:
160 <        incrementSeedList = incrementSeeds.split(',')
161 <    if preserveSeeds:
162 <        preserveSeedList  = preserveSeeds.split(',')
163 <
164 <    # FUTURE: This function tests the CMSSW version and presence of old-style seed specification.
165 <    # Reduce when we drop support for old versions
166 <    if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
178 >    # Check if there are random #'s to deal with
179 >    if cfg.data.services.has_key('RandomNumberGeneratorService'):
180          print "RandomNumberGeneratorService found, will attempt to change seeds"
181 +        from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
182          ranGenerator = cfg.data.services['RandomNumberGeneratorService']
183 <        ranModules   = getattr(ranGenerator, "moduleSeeds", None)
170 <        oldSource    = getattr(ranGenerator, "sourceSeed",  None)
171 <        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
172 <            print "Old-style random number seeds found, will be changed."
173 <            if oldSource != None:
174 <                sourceSeed = int(ranGenerator.sourceSeed.value())
175 <                if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
176 <                    pass
177 <                elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
178 <                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
179 <                else:
180 <                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1, _MAXINT)))
181 <
182 <            for seed in incrementSeedList:
183 <                curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
184 <                if curSeed:
185 <                    curValue = int(curSeed.value())
186 <                    setattr(ranGenerator.moduleSeeds, seed, CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
187 <                    preserveSeedList.append(seed)
188 <
189 <            if ranModules != None:
190 <                for seed in ranGenerator.moduleSeeds.parameterNames_():
191 <                    if seed not in preserveSeedList:
192 <                        curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
193 <                        if curSeed:
194 <                            curValue = int(curSeed.value())
195 <                            setattr(ranGenerator.moduleSeeds, seed,
196 <                                    CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1,_MAXINT))))
197 <        elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
198 <            print "New-style random number seeds found, will be changed."
199 <            from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
200 <            randSvc = RandomNumberServiceHelper(ranGenerator)
201 <
202 <            # Increment requested seed sets
203 <            for seedName in incrementSeedList:
204 <                curSeeds = randSvc.getNamedSeed(seedName)
205 <                newSeeds = [x+nJob for x in curSeeds]
206 <                randSvc.setNamedSeed(seedName, *newSeeds)
207 <                preserveSeedList.append(seedName)
183 >        randSvc = RandomNumberServiceHelper(ranGenerator)
184  
185 <            # Randomize remaining seeds
186 <            randSvc.populate(*preserveSeedList)
187 <        else:
188 <            print "Neither old nor new seed format found!"
185 >        incrementSeedList = []
186 >        preserveSeedList  = []
187 >
188 >        if incrementSeeds:
189 >            incrementSeedList = incrementSeeds.split(',')
190 >        if preserveSeeds:
191 >            preserveSeedList  = preserveSeeds.split(',')
192 >
193 >        # Increment requested seed sets
194 >        for seedName in incrementSeedList:
195 >            curSeeds = randSvc.getNamedSeed(seedName)
196 >            newSeeds = [x+nJob for x in curSeeds]
197 >            randSvc.setNamedSeed(seedName, *newSeeds)
198 >            preserveSeedList.append(seedName)
199  
200 <      # End version specific code
200 >        # Randomize remaining seeds
201 >        randSvc.populate(*preserveSeedList)
202  
203 <    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
203 >    # Write out new config file
204      outFile = open(outFileName,"w")
205 <    if outFileName.endswith('py'):
206 <        outFile.write("import FWCore.ParameterSet.Config as cms\n")
207 <        outFile.write(cmsProcess.dumpPython())
208 <        if (debug):
222 <            print "writeCfg output:"
223 <            print "import FWCore.ParameterSet.Config as cms"
224 <            print cmsProcess.dumpPython()
225 <    else:
226 <        outFile.write(cfg.data.dumpConfig())
227 <        if (debug):
228 <            print "writeCfg output:"
229 <            print str(cfg.data.dumpConfig())
205 >    outFile.write("import FWCore.ParameterSet.Config as cms\n")
206 >    outFile.write("import pickle\n")
207 >    outFile.write("pickledCfg=\"\"\"%s\"\"\"\n" % pickle.dumps(cmsProcess))
208 >    outFile.write("process = pickle.loads(pickledCfg)\n")
209      outFile.close()
210 +    if (debug):
211 +        print "writeCfg output (May not be exact):"
212 +        print "import FWCore.ParameterSet.Config as cms"
213 +        print cmsProcess.dumpPython()
214  
215  
216   if __name__ == '__main__' :

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines