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.20 by ewv, Wed Jun 17 20:58:08 2009 UTC vs.
Revision 1.30 by ewv, Wed Oct 6 13:57:46 2010 UTC

# Line 17 | Line 17 | import xml.dom.minidom
17   from random import SystemRandom
18  
19   from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
20 from FWCore.ParameterSet.Config                       import include
20   import FWCore.ParameterSet.Types as CfgTypes
21  
22   MyRandom  = SystemRandom()
# Line 39 | Line 38 | def main(argv) :
38      """
39      writeCfg
40  
41 <    - Read in existing, user supplied cfg or pickled pycfg file
41 >    - Read in existing, user supplied pycfg or pickled pycfg file
42      - Modify job specific parameters based on environment variables and arguments.xml
43 <    - Write out modified cfg or pickled pycfg file
43 >    - Write out pickled pycfg file
44  
45      required parameters: none
46  
# Line 102 | Line 101 | def main(argv) :
101      firstEvent = -1
102      compHEPFirstEvent = 0
103      firstRun   = 0
104 +    # FUTURE: Remove firstRun
105 +    firstLumi  = 0
106  
107      dom = xml.dom.minidom.parse(os.environ['RUNTIME_AREA']+'/arguments.xml')
108  
# Line 115 | Line 116 | def main(argv) :
116                  firstEvent = int(elem.getAttribute("FirstEvent"))
117              if elem.getAttribute("FirstRun"):
118                  firstRun = int(elem.getAttribute("FirstRun"))
119 +            if elem.getAttribute("FirstLumi"):
120 +                firstLumi = int(elem.getAttribute("FirstLumi"))
121  
122              generator      = str(elem.getAttribute('Generator'))
123              inputFiles     = str(elem.getAttribute('InputFiles'))
124              parentFiles    = str(elem.getAttribute('ParentFiles'))
125 +            lumis          = str(elem.getAttribute('Lumis'))
126  
127 <  # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
127 >  # Read Input python config file
128  
129 <    if fileName.endswith('py'):
130 <        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:
129 >    handle = open(fileName, 'r')
130 >    try:   # Nested form for Python < 2.5
131          try:
132 <            print "Importing .cfg file"
133 <            cfo = include(fileName)
134 <            cmsProcess = cfo
132 >            print "Importing .py file"
133 >            cfo = imp.load_source("pycfg", fileName, handle)
134 >            cmsProcess = cfo.process
135          except Exception, ex:
136 <            msg =  "The cfg file is not valid, %s\n" % str(ex)
136 >            msg = "Your pycfg file is not valid python: %s" % str(ex)
137              raise ConfigException(msg)
138 +    finally:
139 +        handle.close()
140  
141      cfg = CfgInterface(cmsProcess)
142  
# Line 151 | Line 146 | def main(argv) :
146      if maxEvents:
147          cfg.maxEvents.setMaxEventsInput(maxEvents)
148  
149 <    if skipEvents:
149 >    if skipEvents and inModule.sourceType not in ['EmptySource']:
150          inModule.setSkipEvents(skipEvents)
151  
152      # Set "skip events" for various generators
153      if generator == 'comphep':
154          cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(firstEvent)
155      elif generator == 'lhe':
156 <        cmsProcess.LHESource.skipEvents = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
156 >        cmsProcess.source.skipEvents = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
157 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent+1))
158      elif firstEvent != -1: # (Old? Madgraph)
159          cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
160  
# Line 171 | Line 167 | def main(argv) :
167          parentFileNames = parentFiles.split(',')
168          inModule.setSecondaryFileNames(*parentFileNames)
169  
170 +    if lumis:
171 +        if CMSSW_major < 3: # FUTURE: Can remove this check
172 +            print "Cannot skip lumis for CMSSW 2_x"
173 +        else:
174 +            lumiRanges = lumis.split(',')
175 +            inModule.setLumisToProcess(*lumiRanges)
176 +
177      # Pythia parameters
178      if (firstRun):
179          inModule.setFirstRun(firstRun)
180 +    if (firstLumi):
181 +        inModule.setFirstLumi(firstLumi)
182  
183 <    incrementSeedList = []
184 <    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
183 >    # Check if there are random #'s to deal with
184 >    if cfg.data.services.has_key('RandomNumberGeneratorService'):
185          print "RandomNumberGeneratorService found, will attempt to change seeds"
186 +        from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
187          ranGenerator = cfg.data.services['RandomNumberGeneratorService']
188 +
189          ranModules   = getattr(ranGenerator, "moduleSeeds", None)
190          oldSource    = getattr(ranGenerator, "sourceSeed",  None)
191 <        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
192 <            print "Old-style random number seeds found, will be changed."
193 <            if oldSource != None:
194 <                sourceSeed = int(ranGenerator.sourceSeed.value())
195 <                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)
191 >        if ranModules != None or oldSource != None:
192 >            msg = "Your random number seeds are set in an old,\n"
193 >            msg += "deprecated style. Please change to new style:\n"
194 >            msg += "https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideEDMRandomNumberGeneratorService"
195 >            raise ConfigException(msg)
196  
197 <            # Randomize remaining seeds
198 <            randSvc.populate(*preserveSeedList)
199 <        else:
200 <            print "Neither old nor new seed format found!"
197 >        randSvc = RandomNumberServiceHelper(ranGenerator)
198 >
199 >        incrementSeedList = []
200 >        preserveSeedList  = []
201  
202 <      # End version specific code
202 >        if incrementSeeds:
203 >            incrementSeedList = incrementSeeds.split(',')
204 >        if preserveSeeds:
205 >            preserveSeedList  = preserveSeeds.split(',')
206 >
207 >        # Increment requested seed sets
208 >        for seedName in incrementSeedList:
209 >            curSeeds = randSvc.getNamedSeed(seedName)
210 >            newSeeds = [x+nJob for x in curSeeds]
211 >            randSvc.setNamedSeed(seedName, *newSeeds)
212 >            preserveSeedList.append(seedName)
213  
214 <    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
214 >        # Randomize remaining seeds
215 >        randSvc.populate(*preserveSeedList)
216 >
217 >    # Write out new config file
218 >    pklFileName = outFileName + '.pkl'
219      outFile = open(outFileName,"w")
220 <    if outFileName.endswith('py'):
221 <        outFile.write("import FWCore.ParameterSet.Config as cms\n")
222 <        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())
220 >    outFile.write("import FWCore.ParameterSet.Config as cms\n")
221 >    outFile.write("import pickle\n")
222 >    outFile.write("process = pickle.load(open('%s', 'rb'))\n" % pklFileName)
223      outFile.close()
224  
225 +    pklFile = open(pklFileName,"wb")
226 +    myPickle = pickle.Pickler(pklFile)
227 +    myPickle.dump(cmsProcess)
228 +    pklFile.close()
229 +
230 +    if (debug):
231 +        print "writeCfg output (May not be exact):"
232 +        print "import FWCore.ParameterSet.Config as cms"
233 +        print cmsProcess.dumpPython()
234 +
235  
236   if __name__ == '__main__' :
237      exit_status = main(sys.argv[1:])

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines