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.1 by ewv, Fri Dec 14 17:53:36 2007 UTC vs.
Revision 1.27 by ewv, Mon Apr 5 16:47:36 2010 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 pickle
14 + import sys
15 + import xml.dom.minidom
16 +
17 + from random import SystemRandom
18  
19   from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
20 < from FWCore.ParameterSet.DictTypes import SortedKeysDict
21 < from FWCore.ParameterSet.Modules   import Service
22 < from FWCore.ParameterSet.Types     import *
23 < from FWCore.ParameterSet.Config import include
20 > from FWCore.ParameterSet.Config                       import include
21 > import FWCore.ParameterSet.Types as CfgTypes
22 >
23 > MyRandom  = SystemRandom()
24  
25 < import FWCore.ParameterSet.Types   as CfgTypes
26 < import FWCore.ParameterSet.Modules as CfgModules
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 pycfg file
43 <  - Modify job specific parameters based on environment variables
44 <  - Write out modified cfg or pycfg file
45 <
46 <  required parameters: none
47 <
48 <  optional parameters:
49 <  --help             :       help
50 <  --debug            :       debug statements
51 <
52 <  """
53 <
54 <  # defaults
55 <  maxEvents = 0
56 <  skipEvents = 0
57 <  inputFileNames = None
58 <  debug = False
38 <
39 <  try:
40 <    opts, args = getopt.getopt(argv, "", ["debug", "help","inputFiles=","maxEvents=","skipEvents="])
41 <  except getopt.GetoptError:
42 <    print main.__doc__
43 <    sys.exit(2)
44 <
45 <  # Parse command line parameters
46 <  for opt, arg in opts :
47 <    if opt  == "--help" :
48 <      print main.__doc__
49 <      sys.exit()
50 <    elif opt == "--debug" :
51 <      debug = True
52 <    elif opt == "--maxEvents":
53 <      maxEvents = int(arg)
54 <    elif opt == "--skipEvents":
55 <      skipEvents = int(arg)
56 <    elif opt == "--inputFiles":
57 <      inputFiles = arg
58 <      inputFiles = inputFiles.replace('\\','')
59 <      inputFiles = inputFiles.replace('"','')
60 <      inputFileNames = inputFiles.split(',')
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 <  # Parse remaining parameters
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 <  fileName    = args[0];
85 <  outFileName = args[1];
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 <  # Input cfg or python cfg file
128 >  # Read Input python config file
129  
69  if (fileName.endswith('py') or fileName.endswith('pycfg') ):
130      handle = open(fileName, 'r')
131      try:   # Nested form for Python < 2.5
132 <      try:
133 <        cfo = imp.load_source("pycfg", fileName, handle)
134 <      except Exception, ex:
135 <        msg = "Your pycfg file is not valid python: %s" % str(ex)
136 <        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()
79    cfg = CfgInterface(cfo.process)
80  else:
81    try:
82      cfo = include(fileName)
83      cfg = CfgInterface(cfo)
84    except Exception, ex:
85      msg =  "The cfg file is not valid, %s\n" % str(ex)
86      raise "Error: ",msg
87
88  # Set parameters for job
89
90  inModule = cfg.inputSource
91
92  cfg.maxEvents.setMaxEventsInput(maxEvents)
141  
142 <  inModule.setSkipEvents(skipEvents)
95 <  if (inputFileNames):
96 <    inModule.setFileNames(*inputFileNames)
142 >    cfg = CfgInterface(cmsProcess)
143  
144 <  # Write out new config file
145 <
146 <  outFile = open(outFileName,"w")
147 <  outFile.write("import FWCore.ParameterSet.Config as cms\n")
148 <  outFile.write(cfo.dumpPython())
149 <  outFile.close()
150 <
151 <  if (debug):
152 <    print "writeCfg output:"
153 <    print "import FWCore.ParameterSet.Config as cms"
154 <    print cfo.dumpPython()
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 >    pklFileName = outFileName + '.pkl'
211 >    outFile = open(outFileName,"w")
212 >    outFile.write("import FWCore.ParameterSet.Config as cms\n")
213 >    outFile.write("import pickle\n")
214 >    outFile.write("process = pickle.load(open('%s', 'rb'))\n" % pklFileName)
215 >    outFile.close()
216 >
217 >    pklFile = open(pklFileName,"wb")
218 >    myPickle = pickle.Pickler(pklFile)
219 >    myPickle.dump(cmsProcess)
220 >    pklFile.close()
221 >
222 >    if (debug):
223 >        print "writeCfg output (May not be exact):"
224 >        print "import FWCore.ParameterSet.Config as cms"
225 >        print cmsProcess.dumpPython()
226  
227  
228   if __name__ == '__main__' :
229      exit_status = main(sys.argv[1:])
230      sys.exit(exit_status)
114

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines