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.13 by ewv, Mon Aug 18 15:30:43 2008 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 sys, getopt
11   import imp
12   import os
6 import random
13   from random import SystemRandom
8 _inst  = SystemRandom()
14  
15   from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
16 < from FWCore.ParameterSet.DictTypes import SortedKeysDict
17 < from FWCore.ParameterSet.Modules   import Service
13 < from FWCore.ParameterSet.Types     import *
14 < from FWCore.ParameterSet.Config    import include
16 > from FWCore.ParameterSet.Config                       import include
17 > import FWCore.ParameterSet.Types as CfgTypes
18  
19 < import FWCore.ParameterSet.Types   as CfgTypes
17 < import FWCore.ParameterSet.Modules as CfgModules
19 > MyRandom  = SystemRandom()
20  
21   class ConfigException(Exception):
22 +    """
23 +    Exceptions raised by writeCfg
24 +    """
25 +
26      def __init__(self, msg):
27          Exception.__init__(self, msg)
28          self._msg = msg
# Line 26 | Line 32 | class ConfigException(Exception):
32          return self._msg
33  
34   def main(argv) :
35 <  """
36 <  writeCfg
35 >    """
36 >    writeCfg
37  
38 <  - Read in existing, user supplied cfg or pycfg file
39 <  - Modify job specific parameters based on environment variables
40 <  - Write out modified cfg or pycfg file
41 <
42 <  required parameters: none
43 <
44 <  optional parameters:
45 <  --help             :       help
46 <  --debug            :       debug statements
47 <
48 <  """
49 <
50 <  # defaults
51 <  inputFileNames = None
52 <  firstRun       = 0
53 <  sourceSeed     = 0
54 <  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
38 >    - Read in existing, user supplied cfg or pycfg file
39 >    - Modify job specific parameters based on environment variables
40 >    - Write out modified cfg or pycfg file
41 >
42 >    required parameters: none
43 >
44 >    optional parameters:
45 >    --help             :       help
46 >    --debug            :       debug statements
47 >
48 >    """
49 >
50 >    # defaults
51 >    inputFileNames  = None
52 >    parentFileNames = None
53 >    debug           = False
54 >    _MAXINT         = 900000000
55  
56 +    try:
57 +        opts, args = getopt.getopt(argv, "", ["debug", "help"])
58 +    except getopt.GetoptError:
59 +        print main.__doc__
60 +        sys.exit(2)
61  
62 <    # This code not currently working because randSvc is not part of the actual configuration file
62 >    try:
63 >        CMSSW  = os.environ['CMSSW_VERSION']
64 >        parts = CMSSW.split('_')
65 >        CMSSW_major = int(parts[1])
66 >        CMSSW_minor = int(parts[2])
67 >        CMSSW_patch = int(parts[3])
68 >    except (KeyError, ValueError):
69 >        msg = "Your environment doesn't specify the CMSSW version or specifies it incorrectly"
70 >        raise ConfigException(msg)
71 >
72 >    # Parse command line options
73 >    for opt, arg in opts :
74 >        if opt  == "--help" :
75 >            print main.__doc__
76 >            sys.exit()
77 >        elif opt == "--debug" :
78 >            debug = True
79  
80 <    # Translate old format to new format first
186 <    randSvc = RandomSeedService()
80 >    # Parse remaining parameters
81      try:
82 <      ranGenerator = cfg.data.services['RandomNumberGeneratorService']
83 <      ranModules   = ranGenerator.moduleSeeds
84 <      for seed in ranGenerator.moduleSeeds.parameters().keys():
85 <        curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
86 <        curValue = int(curSeed.value())
87 <        setattr(randSvc,seed,CfgTypes.PSet())
88 <        curPSet = getattr(randSvc,seed,None)
89 <        curPSet.initialSeed = CfgTypes.untracked(CfgTypes.uint32(curValue))
90 <      del ranGenerator.moduleSeeds # Get rid of seeds in old format
91 < # Doesn't work, filter is false      randSvc.populate()
92 <
93 <    except:
94 <      print "Problems converting old seeds to new format"
95 <
96 <  # Write out new config file in one format or the other
97 <
98 <  outFile = open(outFileName,"w")
99 <  if (outFileName.endswith('py') or outFileName.endswith('pycfg') ):
100 <    outFile.write("import FWCore.ParameterSet.Config as cms\n")
101 <    outFile.write(cfo.dumpPython())
102 <    if (debug):
103 <      print "writeCfg output:"
104 <      print "import FWCore.ParameterSet.Config as cms"
105 <      print cfo.dumpPython()
106 <  else:
107 <    outFile.write(str(cfg))
108 <    if (debug):
109 <      print "writeCfg output:"
110 <      print str(cfg)
111 <  outFile.close()
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','')
99 >
100 >  # Read Input cfg or python cfg file, FUTURE: Get rid cfg mode
101 >
102 >    if fileName.endswith('py'):
103 >        handle = open(fileName, 'r')
104 >        try:   # Nested form for Python < 2.5
105 >            try:
106 >                print "Importing .py file"
107 >                cfo = imp.load_source("pycfg", fileName, handle)
108 >                cmsProcess = cfo.process
109 >            except Exception, ex:
110 >                msg = "Your pycfg file is not valid python: %s" % str(ex)
111 >                raise ConfigException(msg)
112 >        finally:
113 >            handle.close()
114 >    else:
115 >        try:
116 >            print "Importing .cfg file"
117 >            cfo = include(fileName)
118 >            cmsProcess = cfo
119 >        except Exception, ex:
120 >            msg =  "The cfg file is not valid, %s\n" % str(ex)
121 >            raise ConfigException(msg)
122 >
123 >    cfg = CfgInterface(cmsProcess)
124 >
125 >    # Set parameters for job
126 >    print "Setting parameters"
127 >    inModule = cfg.inputSource
128 >    if maxEvents:
129 >        cfg.maxEvents.setMaxEventsInput(maxEvents)
130 >
131 >    if skipEvents:
132 >        inModule.setSkipEvents(skipEvents)
133 >
134 >    if inputFiles:
135 >        inputFiles = inputFiles.replace('\\','')
136 >        inputFiles = inputFiles.replace('"','')
137 >        inputFileNames = inputFiles.split(',')
138 >        inModule.setFileNames(*inputFileNames)
139 >
140 >    # handle parent files if needed
141 >    if parentFiles:
142 >        parentFiles = parentFiles.replace('\\','')
143 >        parentFiles = parentFiles.replace('"','')
144 >        parentFileNames = parentFiles.split(',')
145 >        inModule.setSecondaryFileNames(*parentFileNames)
146 >
147 >    # Pythia parameters
148 >    if (firstRun):
149 >        inModule.setFirstRun(firstRun)
150 >
151 >    incrementSeedList = []
152 >    preserveSeedList  = []
153 >
154 >    if incrementSeeds:
155 >        incrementSeedList = incrementSeeds.split(',')
156 >    if preserveSeeds:
157 >        preserveSeedList  = preserveSeeds.split(',')
158 >
159 >    # FUTURE: This function tests the CMSSW version and presence of old-style seed specification.
160 >    # Reduce when we drop support for old versions
161 >    if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
162 >        print "RandomNumberGeneratorService found, will attempt to change seeds"
163 >        ranGenerator = cfg.data.services['RandomNumberGeneratorService']
164 >        ranModules   = getattr(ranGenerator, "moduleSeeds", None)
165 >        oldSource    = getattr(ranGenerator, "sourceSeed",  None)
166 >        if ranModules != None or oldSource != None:     # Old format present, no matter the CMSSW version
167 >            print "Old-style random number seeds found, will be changed."
168 >            if oldSource != None:
169 >                sourceSeed = int(ranGenerator.sourceSeed.value())
170 >                if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
171 >                    pass
172 >                elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
173 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
174 >                else:
175 >                    ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1, _MAXINT)))
176 >
177 >            for seed in incrementSeedList:
178 >                curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
179 >                if curSeed:
180 >                    curValue = int(curSeed.value())
181 >                    setattr(ranGenerator.moduleSeeds, seed, CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
182 >                    preserveSeedList.append(seed)
183 >
184 >            if ranModules != None:
185 >                for seed in ranGenerator.moduleSeeds.parameterNames_():
186 >                    if seed not in preserveSeedList:
187 >                        curSeed = getattr(ranGenerator.moduleSeeds, seed, None)
188 >                        if curSeed:
189 >                            curValue = int(curSeed.value())
190 >                            setattr(ranGenerator.moduleSeeds, seed,
191 >                                    CfgTypes.untracked(CfgTypes.uint32(MyRandom.randint(1,_MAXINT))))
192 >        elif CMSSW_major > 2 or (CMSSW_major == 2 and CMSSW_minor >= 1): # Treatment for  seeds, CMSSW 2_1_x and later
193 >            print "New-style random number seeds found, will be changed."
194 >            from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper
195 >            randSvc = RandomNumberServiceHelper(ranGenerator)
196 >
197 >            # Increment requested seed sets
198 >            for seedName in incrementSeedList:
199 >                curSeeds = randSvc.getNamedSeed(seedName)
200 >                newSeeds = [x+nJob for x in curSeeds]
201 >                randSvc.setNamedSeed(seedName, *newSeeds)
202 >                preserveSeedList.append(seedName)
203 >
204 >            # Randomize remaining seeds
205 >            randSvc.populate(*preserveSeedList)
206 >        else:
207 >            print "Neither old nor new seed format found!"
208 >
209 >      # End version specific code
210 >
211 >    # Write out new config file in one format or the other, FUTURE: Get rid of cfg mode
212 >    outFile = open(outFileName,"w")
213 >    if outFileName.endswith('py'):
214 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
215 >        outFile.write(cmsProcess.dumpPython())
216 >        if (debug):
217 >            print "writeCfg output:"
218 >            print "import FWCore.ParameterSet.Config as cms"
219 >            print cmsProcess.dumpPython()
220 >    else:
221 >        outFile.write(cfg.data.dumpConfig())
222 >        if (debug):
223 >            print "writeCfg output:"
224 >            print str(cfg.data.dumpConfig())
225 >    outFile.close()
226  
227  
228   if __name__ == '__main__' :
229      exit_status = main(sys.argv[1:])
230      sys.exit(exit_status)
223

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines