21 import Alignment.MillePedeAlignmentAlgorithm.mpslib.Mpslibclass
as mpslib
22 import Alignment.MillePedeAlignmentAlgorithm.mpslib.tools
as mps_tools
23 from Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.helper
import checked_out_MPS
24 from functools
import reduce
28 """Extracts different weight configurations from `config`.
31 - `config`: ConfigParser object containing the alignment configuration
34 weight_dict = collections.OrderedDict()
38 for section
in config.sections():
39 if 'general' in section:
41 elif section ==
"weights":
42 for option
in config.options(section):
43 common_weights[option] = [x.strip()
for x
in
44 config.get(section, option).
split(
",")]
45 elif section.startswith(
"dataset:"):
47 if config.has_option(section,
'weight'):
48 weight_dict[name] = [x.strip()
for x
in
49 config.get(section,
"weight").
split(
",")]
51 weight_dict[name] = [
'1.0']
53 weights_list = [[(name, weight)
for weight
in weight_dict[name]]
54 for name
in weight_dict]
56 common_weights_list = [[(name, weight)
for weight
in common_weights[name]]
57 for name
in common_weights]
58 common_weights_dicts = []
59 for item
in itertools.product(*common_weights_list):
61 for name,weight
in item:
63 common_weights_dicts.append(d)
66 for weight_conf
in itertools.product(*weights_list):
67 if len(common_weights) > 0:
68 for common_weight
in common_weights_dicts:
69 configs.append([(dataset[0],
70 reduce(
lambda x,y: x.replace(y, common_weight[y]),
71 common_weight, dataset[1]))
72 for dataset
in weight_conf])
74 configs.append(weight_conf)
81 Create sqlite file with single-IOV tags and use it to override the GT. If
82 the GT is already customized by the user, the customization has higher
83 priority. Returns a snippet to be appended to the configuration file
86 - `cfg`: path to python configuration
87 - `run_number`: run from which to extract the alignment payloads
90 sys.path.append(os.path.dirname(cfg))
91 cache_stdout = sys.stdout
92 sys.stdout = open(os.devnull,
"w")
94 importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
95 sys.stdout = cache_stdout
97 run_number = int(run_number)
98 if not run_number > 0:
99 print "'FirstRunForStartGeometry' must be positive, but is", run_number
102 global_tag = __configuration.process.GlobalTag.globaltag.value()
103 input_db_name = os.path.abspath(
"alignment_input.db")
104 tags = mps_tools.create_single_iov_db(global_tag, run_number, input_db_name)
106 for condition
in __configuration.process.GlobalTag.toGet.value():
107 if condition.record.value()
in tags: del tags[condition.record.value()]
110 for record,tag
in tags.iteritems():
112 result += (
"\nimport "
113 "Alignment.MillePedeAlignmentAlgorithm.alignmentsetup."
114 "SetCondition as tagwriter\n")
115 result += (
"\ntagwriter.setCondition(process,\n"
116 " connect = \""+tag[
"connect"]+
"\",\n"
117 " record = \""+record+
"\",\n"
118 " tag = \""+tag[
"tag"]+
"\")\n")
126 helpEpilog =
'''Builds the config-templates from a universal config-template for each
127 dataset specified in .ini-file that is passed to this script.
128 Then calls mps_setup.pl for all datasets.'''
130 description=
'Setup the alignment as configured in the alignment_config file.',
133 parser.add_argument(
'-v',
'--verbose', action=
'store_true',
134 help=
'display detailed output of mps_setup')
136 parser.add_argument(
'-w',
'--weight', action=
'store_true',
137 help=
'create an additional mergejob with (possibly new) weights from .ini-config')
139 parser.add_argument(
'alignmentConfig', action=
'store',
140 help=
'name of the .ini config file that specifies the datasets to be used')
142 args = parser.parse_args()
143 aligmentConfig = args.alignmentConfig
146 config = ConfigParser.ConfigParser()
147 config.optionxform = str
148 config.read(aligmentConfig)
156 mpsTemplates = os.path.join(
"src",
"Alignment",
"MillePedeAlignmentAlgorithm",
"templates")
158 mpsTemplates = os.path.join(os.environ[
"CMSSW_BASE"], mpsTemplates)
160 mpsTemplates = os.path.join(os.environ[
"CMSSW_RELEASE_BASE"], mpsTemplates)
161 milleScript = os.path.join(mpsTemplates,
"mps_runMille_template.sh")
162 pedeScript = os.path.join(mpsTemplates,
"mps_runPede_rfcp_template.sh")
165 currentDir = os.getcwd()
167 match = re.search(re.compile(
'mpproduction\/mp(.+?)$', re.M|re.I),currentDir)
169 mpsdirname =
'mp'+match.group(1)
171 print "Current location does not seem to be a MillePede campaign directory:",
176 mssDir =
'/store/caf/user/'+os.environ[
'USER']+
'/MPproduction/'+mpsdirname
179 eos =
'/afs/cern.ch/project/eos/installation/cms/bin/eos.select'
180 os.system(eos+
' mkdir -p '+mssDir)
189 for var
in [
"classInf",
"pedeMem",
"jobname",
"FirstRunForStartGeometry"]:
191 generalOptions[var] = config.get(
'general',var)
192 except ConfigParser.NoOptionError:
193 print "No", var,
"found in [general] section. Please check ini-file."
197 generalOptions[
'datasetdir'] =
''
198 if config.has_option(
'general',
'datasetdir'):
199 generalOptions[
'datasetdir'] = config.get(
'general',
'datasetdir')
201 os.environ[
"datasetdir"] = generalOptions[
'datasetdir']
203 print "No datasetdir given in [general] section.",
204 print "Be sure to give a full path in inputFileList."
207 for var
in [
'globaltag',
'configTemplate',
'json']:
209 generalOptions[var] = config.get(
'general',var)
210 except ConfigParser.NoOptionError:
211 print 'No default', var,
'given in [general] section.'
215 pedesettings = ([x.strip()
for x
in config.get(
"general",
"pedesettings").
split(
",")]
216 if config.has_option(
"general",
"pedesettings")
else [
None])
226 if not os.path.isdir(
"jobData"):
227 print "No jobData-folder found. Properly set up the alignment before using the -w option."
229 if not os.path.exists(
"mps.db"):
230 print "No mps.db found. Properly set up the alignment before using the -w option."
235 configTemplate = config.get(
'general',
'configTemplate')
236 except ConfigParser.NoOptionError:
237 print 'No default configTemplate given in [general] section.'
238 print 'When using -w, a default configTemplate is needed to build a merge-config.'
243 globalTag = config.get(
'general',
'globaltag')
244 except ConfigParser.NoOptionError:
245 print "No default 'globaltag' given in [general] section."
246 print "When using -w, a default configTemplate is needed to build a merge-config."
250 with open(configTemplate,
"r") as f:
253 print "The config-template '"+configTemplate+
"' cannot be found."
256 tmpFile = re.sub(
'setupGlobaltag\s*\=\s*[\"\'](.*?)[\"\']',
257 'setupGlobaltag = \"'+globalTag+
'\"',
260 thisCfgTemplate =
"tmp.py"
261 with open(thisCfgTemplate,
"w")
as f:
264 for setting
in pedesettings:
268 print "Creating pede job."
270 print "Creating pede jobs using settings from '{0}'.".
format(setting)
271 for weight_conf
in weight_confs:
274 os.system(
"mps_weight.pl -c > /dev/null")
276 for name,weight
in weight_conf:
277 os.system(
"mps_weight.pl -N "+name+
" "+weight)
280 os.system(
"mps_setupm.pl")
283 lib = mpslib.jobdatabase()
287 command =
"rm -f jobData/"+lib.JOBDIR[-1]+
"/alignment_merge.py"
292 command = (
"mps_merge.py -w "+thisCfgTemplate+
" jobData/"+
293 lib.JOBDIR[-1]+
"/alignment_merge.py jobData/"+
294 lib.JOBDIR[-1]+
" "+str(lib.nJobs))
295 if setting
is not None: command +=
" -a "+setting
298 subprocess.call(command, stderr=subprocess.STDOUT, shell=
True)
300 with open(os.devnull,
'w')
as FNULL:
301 subprocess.call(command, stdout=FNULL,
302 stderr=subprocess.STDOUT, shell=
True)
305 os.system(
"rm "+thisCfgTemplate)
313 for section
in config.sections():
314 if 'general' in section:
316 elif section.startswith(
"dataset:"):
321 datasetOptions[
'name'] = section[8:]
324 for var
in [
'inputFileList',
'collection']:
326 datasetOptions[var] = config.get(section,var)
327 except ConfigParser.NoOptionError:
328 print 'No', var,
'found in', section+
'. Please check ini-file.'
332 for var
in [
'configTemplate',
'globaltag']:
333 if config.has_option(section,var):
334 datasetOptions[var] = config.get(section,var)
337 datasetOptions[var] = generalOptions[var]
339 print "No",var,
"found in ["+section+
"]",
340 print "and no default in [general] section."
344 datasetOptions[
'cosmicsZeroTesla'] =
False
345 if config.has_option(section,
'cosmicsZeroTesla'):
346 datasetOptions[
'cosmicsZeroTesla'] = config.getboolean(section,
'cosmicsZeroTesla')
348 datasetOptions[
'cosmicsDecoMode'] =
False
349 if config.has_option(section,
'cosmicsDecoMode'):
350 datasetOptions[
'cosmicsDecoMode'] = config.getboolean(section,
'cosmicsDecoMode')
352 datasetOptions[
'primaryWidth'] = -1.0
353 if config.has_option(section,
'primaryWidth'):
354 datasetOptions[
'primaryWidth'] = config.getfloat(section,
'primaryWidth')
356 datasetOptions[
'json'] =
''
357 if config.has_option(section,
'json'):
358 datasetOptions[
'json'] = config.get(section,
'json')
361 datasetOptions[
'json'] = generalOptions[
'json']
363 print "No json given in either [general] or ["+section+
"] sections.",
364 print "Proceeding without json-file."
368 datasetOptions[
'inputFileList'] = os.path.expandvars(datasetOptions[
'inputFileList'])
371 datasetOptions[
'configTemplate'] = os.path.expandvars(datasetOptions[
'configTemplate'])
375 datasetOptions[
'njobs'] = 0
377 with open(datasetOptions[
'inputFileList'],
'r') as filelist:
378 for line
in filelist:
379 if 'CastorPool' in line:
382 if not line.strip()==
'':
383 datasetOptions[
'njobs'] += 1
385 print 'Inputfilelist', datasetOptions[
'inputFileList'],
'does not exist.'
387 if datasetOptions[
'njobs'] == 0:
388 print 'Number of jobs is 0. There may be a problem with the inputfilelist:'
389 print datasetOptions[
'inputFileList']
393 if config.has_option(section,
'njobs'):
394 if config.getint(section,
'njobs')<=datasetOptions[
'njobs']:
395 datasetOptions[
'njobs'] = config.getint(section,
'njobs')
397 print 'njobs is bigger than the default',datasetOptions[
'njobs'],
'. Using default.'
399 print 'No number of jobs specified. Using number of files in inputfilelist as the number of jobs.'
404 with open(datasetOptions[
'configTemplate'],
'r') as INFILE:
405 tmpFile = INFILE.read()
407 print 'The config-template called',datasetOptions[
'configTemplate'],
'cannot be found.'
410 tmpFile = re.sub(
'setupGlobaltag\s*\=\s*[\"\'](.*?)[\"\']',
411 'setupGlobaltag = \"'+datasetOptions[
'globaltag']+
'\"',
413 tmpFile = re.sub(
'setupCollection\s*\=\s*[\"\'](.*?)[\"\']',
414 'setupCollection = \"'+datasetOptions[
'collection']+
'\"',
416 if datasetOptions[
'cosmicsZeroTesla']:
417 tmpFile = re.sub(re.compile(
'setupCosmicsZeroTesla\s*\=\s*.*$', re.M),
418 'setupCosmicsZeroTesla = True',
420 if datasetOptions[
'cosmicsDecoMode']:
421 tmpFile = re.sub(re.compile(
'setupCosmicsDecoMode\s*\=\s*.*$', re.M),
422 'setupCosmicsDecoMode = True',
424 if datasetOptions[
'primaryWidth'] > 0.0:
425 tmpFile = re.sub(re.compile(
'setupPrimaryWidth\s*\=\s*.*$', re.M),
426 'setupPrimaryWidth = '+str(datasetOptions[
'primaryWidth']),
428 if datasetOptions[
'json'] !=
'':
429 tmpFile = re.sub(re.compile(
'setupJson\s*\=\s*.*$', re.M),
430 'setupJson = \"'+datasetOptions[
'json']+
'\"',
433 thisCfgTemplate =
'tmp.py'
434 with open(thisCfgTemplate,
'w')
as OUTFILE:
435 OUTFILE.write(tmpFile)
443 configTemplate = tmpFile
445 generalOptions[
"FirstRunForStartGeometry"])
447 with open(thisCfgTemplate,
"a")
as f: f.write(overrideGT)
451 command =
'mps_setup.pl -m%s -M %s -N %s %s %s %s %d %s %s %s cmscafuser:%s' % (
453 generalOptions[
'pedeMem'],
454 datasetOptions[
'name'],
457 datasetOptions[
'inputFileList'],
458 datasetOptions[
'njobs'],
459 generalOptions[
'classInf'],
460 generalOptions[
'jobname'],
464 print 'Submitting dataset:', datasetOptions[
'name']
465 print 'Baseconfig: ', datasetOptions[
'configTemplate']
466 print 'Collection: ', datasetOptions[
'collection']
467 if datasetOptions[
"collection"]
in (
"ALCARECOTkAlCosmicsCTF0T",
468 "ALCARECOTkAlCosmicsInCollisions"):
469 print 'cosmicsDecoMode: ', datasetOptions[
'cosmicsDecoMode']
470 print 'cosmicsZeroTesla: ', datasetOptions[
'cosmicsZeroTesla']
471 print 'Globaltag: ', datasetOptions[
'globaltag']
472 print 'Number of jobs: ', datasetOptions[
'njobs']
473 print 'Inputfilelist: ', datasetOptions[
'inputFileList']
474 if datasetOptions[
'json'] !=
'':
475 print 'Jsonfile: ', datasetOptions[
'json']
476 print 'Pass to mps_setup: ', command
480 subprocess.call(command, stderr=subprocess.STDOUT, shell=
True)
482 with open(os.devnull,
'w')
as FNULL:
483 subprocess.call(command, stdout=FNULL,
484 stderr=subprocess.STDOUT, shell=
True)
487 os.system(
"rm "+thisCfgTemplate)
490 print "No dataset section defined in '{0}'".
format(aligmentConfig)
491 print "At least one section '[dataset:<name>]' is required."
494 firstPedeConfig =
True
495 for setting
in pedesettings:
499 print "Creating pede job."
501 print "Creating pede jobs using settings from '{0}'.".
format(setting)
502 for weight_conf
in weight_confs:
505 os.system(
"mps_weight.pl -c > /dev/null")
507 for name,weight
in weight_conf:
508 os.system(
"mps_weight.pl -N "+name+
" "+weight)
511 firstPedeConfig =
False
514 os.system(
"mps_setupm.pl")
517 lib = mpslib.jobdatabase()
521 command =
"rm -f jobData/"+lib.JOBDIR[-1]+
"/alignment_merge.py"
525 thisCfgTemplate =
"tmp.py"
526 with open(thisCfgTemplate,
"w")
as f:
527 f.write(configTemplate+overrideGT)
530 command = (
"mps_merge.py -w "+thisCfgTemplate+
" jobData/"+lib.JOBDIR[-1]+
531 "/alignment_merge.py jobData/"+lib.JOBDIR[-1]+
" "+
533 if setting
is not None: command +=
" -a "+setting
536 subprocess.call(command, stderr=subprocess.STDOUT, shell=
True)
538 with open(os.devnull,
'w')
as FNULL:
539 subprocess.call(command, stdout=FNULL,
540 stderr=subprocess.STDOUT, shell=
True)
543 os.system(
"rm "+thisCfgTemplate)
545 if overrideGT.strip() !=
"":
547 msg = (
"Overriding global tag with single-IOV tags extracted from '{}' for "
548 "run number '{}'.".
format(generalOptions[
"globaltag"],
549 generalOptions[
"FirstRunForStartGeometry"]))