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.11 by spiga, Thu Jun 5 07:13:31 2008 UTC vs.
Revision 1.26 by ewv, Mon Dec 14 22:33:54 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 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 >
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 >    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 <  - Read in existing, user supplied cfg or pycfg file
85 <  - Modify job specific parameters based on environment variables
86 <  - Write out modified cfg or pycfg file
87 <
88 <  required parameters: none
89 <
90 <  optional parameters:
91 <  --help             :       help
92 <  --debug            :       debug statements
93 <
94 <  """
95 <
96 <  # defaults
97 <  inputFileNames  = None
98 <  parentFileNames = None
99 <  firstRun        = 0
100 <  sourceSeed      = 0
101 <  vtxSeed         = 0
102 <  g4Seed          = 0
103 <  mixSeed         = 0
104 <  debug           = False
105 <  _MAXINT         = 900000000
106 <  maxSeeds        = 4         # Kludge, maximum # of seeds that any engine takes
107 <
108 <  try:
109 <    opts, args = getopt.getopt(argv, "", ["debug", "help"])
110 <  except getopt.GetoptError:
111 <    print main.__doc__
112 <    sys.exit(2)
113 <
114 <  try:
115 <    CMSSW  = os.environ['CMSSW_VERSION']
116 <    parts = CMSSW.split('_')
117 <    CMSSW_major = int(parts[1])
118 <    CMSSW_minor = int(parts[2])
119 <    CMSSW_patch = int(parts[3])
120 <  except KeyError, ValueError:
121 <    msg = "Your environment doesn't specify the CMSSW version or specifies it incorrectly"
122 <    raise ConfigException(msg)
123 <
124 <  # Parse command line options
125 <  for opt, arg in opts :
126 <    if opt  == "--help" :
75 <      print main.__doc__
76 <      sys.exit()
77 <    elif opt == "--debug" :
78 <      debug = True
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 <  parentFiles     = os.environ.get('ParentFiles','')
97 <  preserveSeeds  = os.environ.get('PreserveSeeds','')
98 <  incrementSeeds = os.environ.get('IncrementSeeds','')
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 >    # FUTURE: Remove firstRun
106 >    firstLumi  = 0
107 >
108 >    dom = xml.dom.minidom.parse(os.environ['RUNTIME_AREA']+'/arguments.xml')
109 >
110 >    for elem in dom.getElementsByTagName("Job"):
111 >        if nJob == int(elem.getAttribute("JobID")):
112 >            if elem.getAttribute("MaxEvents"):
113 >                maxEvents = int(elem.getAttribute("MaxEvents"))
114 >            if elem.getAttribute("SkipEvents"):
115 >                skipEvents = int(elem.getAttribute("SkipEvents"))
116 >            if elem.getAttribute("FirstEvent"):
117 >                firstEvent = int(elem.getAttribute("FirstEvent"))
118 >            if elem.getAttribute("FirstRun"):
119 >                firstRun = int(elem.getAttribute("FirstRun"))
120 >            if elem.getAttribute("FirstLumi"):
121 >                firstLumi = int(elem.getAttribute("FirstLumi"))
122 >
123 >            generator      = str(elem.getAttribute('Generator'))
124 >            inputFiles     = str(elem.getAttribute('InputFiles'))
125 >            parentFiles    = str(elem.getAttribute('ParentFiles'))
126 >            lumis          = str(elem.getAttribute('Lumis'))
127  
128 < # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
128 >  # Read Input python config file
129  
102  if fileName.endswith('py'):
130      handle = open(fileName, 'r')
131      try:   # Nested form for Python < 2.5
132 <      try:
133 <        cfo = imp.load_source("pycfg", fileName, handle)
134 <        cmsProcess = cfo.process
135 <      except Exception, ex:
136 <        msg = "Your pycfg file is not valid python: %s" % str(ex)
137 <        raise "Error: ",msg
132 >        try:
133 >            print "Importing .py file"
134 >            cfo = imp.load_source("pycfg", fileName, handle)
135 >            cmsProcess = cfo.process
136 >        except Exception, ex:
137 >            msg = "Your pycfg file is not valid python: %s" % str(ex)
138 >            raise ConfigException(msg)
139      finally:
140          handle.close()
141 <  else:
142 <    try:
143 <      print "Importing .cfg file"
144 <      cfo = include(fileName)
145 <      cmsProcess = cfo
146 <    except Exception, ex:
147 <      msg =  "The cfg file is not valid, %s\n" % str(ex)
148 <      raise "Error: ",msg
149 <  print "Getting interface"
150 <  cfg = CfgInterface(cmsProcess)
151 <
152 <  # Set parameters for job
153 <  print "Setting parameters"
154 <  inModule = cfg.inputSource
155 <  if maxEvents:
156 <    cfg.maxEvents.setMaxEventsInput(maxEvents)
157 <
158 <  if skipEvents:
159 <    inModule.setSkipEvents(skipEvents)
160 <
161 <  if inputFiles:
162 <    inputFiles = inputFiles.replace('\\','')
163 <    inputFiles = inputFiles.replace('"','')
164 <    inputFileNames = inputFiles.split(',')
165 <    inModule.setFileNames(*inputFileNames)
166 <
167 <  # handle parent files if needed
168 <  if parentFiles:
169 <    parentFiles = parentFiles.replace('\\','')
170 <    parentFiles = parentFiles.replace('"','')
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. Reduce when we drop support for old versions
187 <  if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
188 <    print "RandomNumberGeneratorService found, will attempt to change seeds"
189 <    ranGenerator = cfg.data.services['RandomNumberGeneratorService']
190 <    ranModules   = getattr(ranGenerator,"moduleSeeds",None)
191 <    if ranModules != None:              # Old format present, no matter the CMSSW version
192 <      print "Old-style random number seeds found, will be changed."
193 <      sourceSeed = int(ranGenerator.sourceSeed.value())
194 <      if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
195 <        pass
196 <      elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
197 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
198 <      else:
199 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
200 <
201 <      for seed in incrementSeedList:
202 <        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
203 <        if curSeed:
204 <          curValue = int(curSeed.value())
205 <          setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
206 <          preserveSeedList.append(seed)
207 <
208 <      for seed in ranGenerator.moduleSeeds.parameterNames_():
209 <        if seed not in preserveSeedList:
210 <          curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
183 <          if curSeed:
184 <            curValue = int(curSeed.value())
185 <            setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT))))
186 <    elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
187 <      print "New-style random number seeds found, will be changed."
188 <      from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
189 <      randSvc = RandomNumberServiceHelper(ranGenerator)
190 <
191 <      # Increment requested seed sets
192 <      for seedName in incrementSeedList:
193 <        curSeeds = randSvc.getNamedSeed(seedName)
194 <        newSeeds = [x+nJob for x in curSeeds]
195 <        randSvc.setNamedSeed(seedName,*newSeeds)
196 <        preserveSeedList.append(seedName)
197 <
198 <      # Randomize remaining seeds
199 <      randSvc.populate(*preserveSeedList)
200 <    else:
201 <      print "Neither old nor new seed format found!"
202 <
203 <    # End version specific code
204 <
205 <  # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
206 <  outFile = open(outFileName,"w")
207 <  if outFileName.endswith('py'):
141 >
142 >    cfg = CfgInterface(cmsProcess)
143 >
144 >    # Set parameters for job
145 >    print "Setting parameters"
146 >    inModule = cfg.inputSource
147 >    if maxEvents:
148 >        cfg.maxEvents.setMaxEventsInput(maxEvents)
149 >
150 >    if skipEvents:
151 >        inModule.setSkipEvents(skipEvents)
152 >
153 >    # Set "skip events" for various generators
154 >    if generator == 'comphep':
155 >        cmsProcess.source.CompHEPFirstEvent = CfgTypes.int32(firstEvent)
156 >    elif generator == 'lhe':
157 >        cmsProcess.source.skipEvents = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
158 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent+1))
159 >    elif firstEvent != -1: # (Old? Madgraph)
160 >        cmsProcess.source.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent))
161 >
162 >    if inputFiles:
163 >        inputFileNames = inputFiles.split(',')
164 >        inModule.setFileNames(*inputFileNames)
165 >
166 >    # handle parent files if needed
167 >    if parentFiles:
168 >        parentFileNames = parentFiles.split(',')
169 >        inModule.setSecondaryFileNames(*parentFileNames)
170 >
171 >    if lumis:
172 >        if CMSSW_major < 3: # FUTURE: Can remove this check
173 >            print "Cannot skip lumis for CMSSW 2_x"
174 >        else:
175 >            lumiRanges = lumis.split(',')
176 >            inModule.setLumisToProcess(*lumiRanges)
177 >
178 >    # Pythia parameters
179 >    if (firstRun):
180 >        inModule.setFirstRun(firstRun)
181 >    if (firstLumi):
182 >        inModule.setFirstLumi(firstLumi)
183 >
184 >    # Check if there are random #'s to deal with
185 >    if cfg.data.services.has_key('RandomNumberGeneratorService'):
186 >        print "RandomNumberGeneratorService found, will attempt to change seeds"
187 >        from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
188 >        ranGenerator = cfg.data.services['RandomNumberGeneratorService']
189 >        randSvc = RandomNumberServiceHelper(ranGenerator)
190 >
191 >        incrementSeedList = []
192 >        preserveSeedList  = []
193 >
194 >        if incrementSeeds:
195 >            incrementSeedList = incrementSeeds.split(',')
196 >        if preserveSeeds:
197 >            preserveSeedList  = preserveSeeds.split(',')
198 >
199 >        # Increment requested seed sets
200 >        for seedName in incrementSeedList:
201 >            curSeeds = randSvc.getNamedSeed(seedName)
202 >            newSeeds = [x+nJob for x in curSeeds]
203 >            randSvc.setNamedSeed(seedName, *newSeeds)
204 >            preserveSeedList.append(seedName)
205 >
206 >        # Randomize remaining seeds
207 >        randSvc.populate(*preserveSeedList)
208 >
209 >    # Write out new config file
210 >    outFile = open(outFileName,"w")
211      outFile.write("import FWCore.ParameterSet.Config as cms\n")
212 <    outFile.write(cmsProcess.dumpPython())
213 <    if (debug):
214 <      print "writeCfg output:"
215 <      print "import FWCore.ParameterSet.Config as cms"
213 <      print cmsProcess.dumpPython()
214 <  else:
215 <    outFile.write(str(cfg))
212 >    outFile.write("import pickle\n")
213 >    outFile.write("pickledCfg=\"\"\"%s\"\"\"\n" % pickle.dumps(cmsProcess))
214 >    outFile.write("process = pickle.loads(pickledCfg)\n")
215 >    outFile.close()
216      if (debug):
217 <      print "writeCfg output:"
218 <      print str(cfg)
219 <  outFile.close()
217 >        print "writeCfg output (May not be exact):"
218 >        print "import FWCore.ParameterSet.Config as cms"
219 >        print cmsProcess.dumpPython()
220  
221  
222   if __name__ == '__main__' :

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines