1 |
#!/usr/bin/env python
|
2 |
|
3 |
import sys, getopt, string
|
4 |
import imp
|
5 |
import os
|
6 |
import random
|
7 |
from random import SystemRandom
|
8 |
_inst = SystemRandom()
|
9 |
|
10 |
from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
|
11 |
from FWCore.ParameterSet.DictTypes import SortedKeysDict
|
12 |
from FWCore.ParameterSet.Modules import Service
|
13 |
from FWCore.ParameterSet.Types import *
|
14 |
from FWCore.ParameterSet.Config import include
|
15 |
|
16 |
import FWCore.ParameterSet.Types as CfgTypes
|
17 |
import FWCore.ParameterSet.Modules as CfgModules
|
18 |
|
19 |
class ConfigException(Exception):
|
20 |
def __init__(self, msg):
|
21 |
Exception.__init__(self, msg)
|
22 |
self._msg = msg
|
23 |
return
|
24 |
|
25 |
def __str__(self):
|
26 |
return self._msg
|
27 |
|
28 |
def main(argv) :
|
29 |
"""
|
30 |
writeCfg
|
31 |
|
32 |
- Read in existing, user supplied cfg or pycfg file
|
33 |
- Modify job specific parameters based on environment variables
|
34 |
- Write out modified cfg or pycfg file
|
35 |
|
36 |
required parameters: none
|
37 |
|
38 |
optional parameters:
|
39 |
--help : help
|
40 |
--debug : debug statements
|
41 |
|
42 |
"""
|
43 |
|
44 |
# defaults
|
45 |
inputFileNames = None
|
46 |
parentFileNames = None
|
47 |
firstRun = 0
|
48 |
sourceSeed = 0
|
49 |
vtxSeed = 0
|
50 |
g4Seed = 0
|
51 |
mixSeed = 0
|
52 |
debug = False
|
53 |
_MAXINT = 900000000
|
54 |
maxSeeds = 4 # Kludge, maximum # of seeds that any engine takes
|
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 |
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 |
# 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','')
|
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 |
cfo = imp.load_source("pycfg", fileName, handle)
|
107 |
cmsProcess = cfo.process
|
108 |
except Exception, ex:
|
109 |
msg = "Your pycfg file is not valid python: %s" % str(ex)
|
110 |
raise "Error: ",msg
|
111 |
finally:
|
112 |
handle.close()
|
113 |
else:
|
114 |
try:
|
115 |
print "Importing .cfg file"
|
116 |
cfo = include(fileName)
|
117 |
cmsProcess = cfo
|
118 |
except Exception, ex:
|
119 |
msg = "The cfg file is not valid, %s\n" % str(ex)
|
120 |
raise "Error: ",msg
|
121 |
print "Getting interface"
|
122 |
cfg = CfgInterface(cmsProcess)
|
123 |
|
124 |
# Set parameters for job
|
125 |
print "Setting parameters"
|
126 |
inModule = cfg.inputSource
|
127 |
if maxEvents:
|
128 |
cfg.maxEvents.setMaxEventsInput(maxEvents)
|
129 |
|
130 |
if skipEvents:
|
131 |
inModule.setSkipEvents(skipEvents)
|
132 |
|
133 |
if inputFiles:
|
134 |
inputFiles = inputFiles.replace('\\','')
|
135 |
inputFiles = inputFiles.replace('"','')
|
136 |
inputFileNames = inputFiles.split(',')
|
137 |
inModule.setFileNames(*inputFileNames)
|
138 |
|
139 |
# handle parent files if needed
|
140 |
if parentFiles:
|
141 |
parentFiles = parentFiles.replace('\\','')
|
142 |
parentFiles = parentFiles.replace('"','')
|
143 |
parentFileNames = parentFiles.split(',')
|
144 |
inModule.setSecondaryFileNames(*parentFileNames)
|
145 |
|
146 |
# Pythia parameters
|
147 |
if (firstRun):
|
148 |
inModule.setFirstRun(firstRun)
|
149 |
|
150 |
incrementSeedList = []
|
151 |
preserveSeedList = []
|
152 |
|
153 |
if incrementSeeds:
|
154 |
incrementSeedList = incrementSeeds.split(',')
|
155 |
if preserveSeeds:
|
156 |
preserveSeedList = preserveSeeds.split(',')
|
157 |
|
158 |
# FUTURE: This function tests the CMSSW version and presence of old-style seed specification. Reduce when we drop support for old versions
|
159 |
if cfg.data.services.has_key('RandomNumberGeneratorService'): # There are random #'s to deal with
|
160 |
print "RandomNumberGeneratorService found, will attempt to change seeds"
|
161 |
ranGenerator = cfg.data.services['RandomNumberGeneratorService']
|
162 |
ranModules = getattr(ranGenerator,"moduleSeeds",None)
|
163 |
if ranModules != None: # Old format present, no matter the CMSSW version
|
164 |
print "Old-style random number seeds found, will be changed."
|
165 |
sourceSeed = int(ranGenerator.sourceSeed.value())
|
166 |
if ('sourceSeed' in preserveSeedList) or ('theSource' in preserveSeedList):
|
167 |
pass
|
168 |
elif ('sourceSeed' in incrementSeedList) or ('theSource' in incrementSeedList):
|
169 |
ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(sourceSeed+nJob))
|
170 |
else:
|
171 |
ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(_inst.randint(1,_MAXINT)))
|
172 |
|
173 |
for seed in incrementSeedList:
|
174 |
curSeed = getattr(ranGenerator.moduleSeeds,seed,None)
|
175 |
if curSeed:
|
176 |
curValue = int(curSeed.value())
|
177 |
setattr(ranGenerator.moduleSeeds,seed,CfgTypes.untracked(CfgTypes.uint32(curValue+nJob)))
|
178 |
preserveSeedList.append(seed)
|
179 |
|
180 |
for seed in ranGenerator.moduleSeeds.parameterNames_():
|
181 |
if seed not in preserveSeedList:
|
182 |
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'):
|
208 |
outFile.write("import FWCore.ParameterSet.Config as cms\n")
|
209 |
outFile.write(cmsProcess.dumpPython())
|
210 |
if (debug):
|
211 |
print "writeCfg output:"
|
212 |
print "import FWCore.ParameterSet.Config as cms"
|
213 |
print cmsProcess.dumpPython()
|
214 |
else:
|
215 |
outFile.write(str(cfg))
|
216 |
if (debug):
|
217 |
print "writeCfg output:"
|
218 |
print str(cfg)
|
219 |
outFile.close()
|
220 |
|
221 |
|
222 |
if __name__ == '__main__' :
|
223 |
exit_status = main(sys.argv[1:])
|
224 |
sys.exit(exit_status)
|