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
27 """Extracts different weight configurations from `config`.
30 - `config`: ConfigParser object containing the alignment configuration
33 weight_dict = collections.OrderedDict()
37 for section
in config.sections():
38 if 'general' in section:
40 elif section ==
"weights":
41 for option
in config.options(section):
42 common_weights[option] = [x.strip()
for x
in
43 config.get(section, option).
split(
",")]
44 elif section.startswith(
"dataset:"):
46 if config.has_option(section,
'weight'):
47 weight_dict[name] = [x.strip()
for x
in
48 config.get(section,
"weight").
split(
",")]
50 weight_dict[name] = [
'1.0']
52 weights_list = [[(name, weight)
for weight
in weight_dict[name]]
53 for name
in weight_dict]
55 common_weights_list = [[(name, weight)
for weight
in common_weights[name]]
56 for name
in common_weights]
57 common_weights_dicts = []
58 for item
in itertools.product(*common_weights_list):
60 for name,weight
in item:
62 common_weights_dicts.append(d)
65 for weight_conf
in itertools.product(*weights_list):
66 if len(common_weights) > 0:
67 for common_weight
in common_weights_dicts:
68 configs.append([(dataset[0],
69 reduce(
lambda x,y: x.replace(y, common_weight[y]),
70 common_weight, dataset[1]))
71 for dataset
in weight_conf])
73 configs.append(weight_conf)
80 Create sqlite file with single-IOV tags and use it to override the GT. If
81 the GT is already customized by the user, the customization has higher
82 priority. Returns a snippet to be appended to the configuration file
85 - `cfg`: path to python configuration
86 - `run_number`: run from which to extract the alignment payloads
89 sys.path.append(os.path.dirname(cfg))
90 cache_stdout = sys.stdout
91 sys.stdout = open(os.devnull,
"w")
93 importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
94 sys.stdout = cache_stdout
96 run_number = int(run_number)
97 if not run_number > 0:
98 print "'FirstRunForStartGeometry' must be positive, but is", run_number
101 global_tag = __configuration.process.GlobalTag.globaltag.value()
102 input_db_name = os.path.abspath(
"alignment_input.db")
103 tags = mps_tools.create_single_iov_db(global_tag, run_number, input_db_name)
105 for condition
in __configuration.process.GlobalTag.toGet.value():
106 if condition.record.value()
in tags: del tags[condition.record.value()]
109 for record,tag
in tags.iteritems():
111 result += (
"\nimport "
112 "Alignment.MillePedeAlignmentAlgorithm.alignmentsetup."
113 "SetCondition as tagwriter\n")
114 result += (
"\ntagwriter.setCondition(process,\n"
115 " connect = \""+tag[
"connect"]+
"\",\n"
116 " record = \""+record+
"\",\n"
117 " tag = \""+tag[
"tag"]+
"\")\n")
125 helpEpilog =
'''Builds the config-templates from a universal config-template for each
126 dataset specified in .ini-file that is passed to this script.
127 Then calls mps_setup.pl for all datasets.'''
129 description=
'Setup the alignment as configured in the alignment_config file.',
132 parser.add_argument(
'-v',
'--verbose', action=
'store_true',
133 help=
'display detailed output of mps_setup')
135 parser.add_argument(
'-w',
'--weight', action=
'store_true',
136 help=
'create an additional mergejob with (possibly new) weights from .ini-config')
138 parser.add_argument(
'alignmentConfig', action=
'store',
139 help=
'name of the .ini config file that specifies the datasets to be used')
141 args = parser.parse_args()
142 aligmentConfig = args.alignmentConfig
145 config = ConfigParser.ConfigParser()
146 config.optionxform = str
147 config.read(aligmentConfig)
155 mpsTemplates = os.path.join(
"src",
"Alignment",
"MillePedeAlignmentAlgorithm",
"templates")
157 mpsTemplates = os.path.join(os.environ[
"CMSSW_BASE"], mpsTemplates)
159 mpsTemplates = os.path.join(os.environ[
"CMSSW_RELEASE_BASE"], mpsTemplates)
160 milleScript = os.path.join(mpsTemplates,
"mps_runMille_template.sh")
161 pedeScript = os.path.join(mpsTemplates,
"mps_runPede_rfcp_template.sh")
164 currentDir = os.getcwd()
166 match = re.search(re.compile(
'mpproduction\/mp(.+?)$', re.M|re.I),currentDir)
168 mpsdirname =
'mp'+match.group(1)
170 print "Current location does not seem to be a MillePede campaign directory:",
175 mssDir =
'/store/caf/user/'+os.environ[
'USER']+
'/MPproduction/'+mpsdirname
178 eos =
'/afs/cern.ch/project/eos/installation/cms/bin/eos.select'
179 os.system(eos+
' mkdir -p '+mssDir)
188 for var
in [
"classInf",
"pedeMem",
"jobname",
"FirstRunForStartGeometry"]:
190 generalOptions[var] = config.get(
'general',var)
191 except ConfigParser.NoOptionError:
192 print "No", var,
"found in [general] section. Please check ini-file."
196 generalOptions[
'datasetdir'] =
''
197 if config.has_option(
'general',
'datasetdir'):
198 generalOptions[
'datasetdir'] = config.get(
'general',
'datasetdir')
200 os.environ[
"datasetdir"] = generalOptions[
'datasetdir']
202 print "No datasetdir given in [general] section.",
203 print "Be sure to give a full path in inputFileList."
206 for var
in [
'globaltag',
'configTemplate',
'json']:
208 generalOptions[var] = config.get(
'general',var)
209 except ConfigParser.NoOptionError:
210 print 'No default', var,
'given in [general] section.'
214 pedesettings = ([x.strip()
for x
in config.get(
"general",
"pedesettings").
split(
",")]
215 if config.has_option(
"general",
"pedesettings")
else [
None])
225 if not os.path.isdir(
"jobData"):
226 print "No jobData-folder found. Properly set up the alignment before using the -w option."
228 if not os.path.exists(
"mps.db"):
229 print "No mps.db found. Properly set up the alignment before using the -w option."
234 configTemplate = config.get(
'general',
'configTemplate')
235 except ConfigParser.NoOptionError:
236 print 'No default configTemplate given in [general] section.'
237 print 'When using -w, a default configTemplate is needed to build a merge-config.'
242 globalTag = config.get(
'general',
'globaltag')
243 except ConfigParser.NoOptionError:
244 print "No default 'globaltag' given in [general] section."
245 print "When using -w, a default configTemplate is needed to build a merge-config."
249 with open(configTemplate,
"r") as f:
252 print "The config-template '"+configTemplate+
"' cannot be found."
255 tmpFile = re.sub(
'setupGlobaltag\s*\=\s*[\"\'](.*?)[\"\']',
256 'setupGlobaltag = \"'+globalTag+
'\"',
259 thisCfgTemplate =
"tmp.py"
260 with open(thisCfgTemplate,
"w")
as f:
263 for setting
in pedesettings:
267 print "Creating pede job."
269 print "Creating pede jobs using settings from '{0}'.".
format(setting)
270 for weight_conf
in weight_confs:
273 os.system(
"mps_weight.pl -c > /dev/null")
275 for name,weight
in weight_conf:
276 os.system(
"mps_weight.pl -N "+name+
" "+weight)
279 os.system(
"mps_setupm.pl")
282 lib = mpslib.jobdatabase()
286 command =
"rm -f jobData/"+lib.JOBDIR[-1]+
"/alignment_merge.py"
291 command = (
"mps_merge.py -w "+thisCfgTemplate+
" jobData/"+
292 lib.JOBDIR[-1]+
"/alignment_merge.py jobData/"+
293 lib.JOBDIR[-1]+
" "+str(lib.nJobs))
294 if setting
is not None: command +=
" -a "+setting
297 subprocess.call(command, stderr=subprocess.STDOUT, shell=
True)
299 with open(os.devnull,
'w')
as FNULL:
300 subprocess.call(command, stdout=FNULL,
301 stderr=subprocess.STDOUT, shell=
True)
304 os.system(
"rm "+thisCfgTemplate)
312 for section
in config.sections():
313 if 'general' in section:
315 elif section.startswith(
"dataset:"):
320 datasetOptions[
'name'] = section[8:]
323 for var
in [
'inputFileList',
'collection']:
325 datasetOptions[var] = config.get(section,var)
326 except ConfigParser.NoOptionError:
327 print 'No', var,
'found in', section+
'. Please check ini-file.'
331 for var
in [
'configTemplate',
'globaltag']:
332 if config.has_option(section,var):
333 datasetOptions[var] = config.get(section,var)
336 datasetOptions[var] = generalOptions[var]
338 print "No",var,
"found in ["+section+
"]",
339 print "and no default in [general] section."
343 datasetOptions[
'cosmicsZeroTesla'] =
False
344 if config.has_option(section,
'cosmicsZeroTesla'):
345 datasetOptions[
'cosmicsZeroTesla'] = config.getboolean(section,
'cosmicsZeroTesla')
347 datasetOptions[
'cosmicsDecoMode'] =
False
348 if config.has_option(section,
'cosmicsDecoMode'):
349 datasetOptions[
'cosmicsDecoMode'] = config.getboolean(section,
'cosmicsDecoMode')
351 datasetOptions[
'primaryWidth'] = -1.0
352 if config.has_option(section,
'primaryWidth'):
353 datasetOptions[
'primaryWidth'] = config.getfloat(section,
'primaryWidth')
355 datasetOptions[
'json'] =
''
356 if config.has_option(section,
'json'):
357 datasetOptions[
'json'] = config.get(section,
'json')
360 datasetOptions[
'json'] = generalOptions[
'json']
362 print "No json given in either [general] or ["+section+
"] sections.",
363 print "Proceeding without json-file."
367 datasetOptions[
'inputFileList'] = os.path.expandvars(datasetOptions[
'inputFileList'])
370 datasetOptions[
'configTemplate'] = os.path.expandvars(datasetOptions[
'configTemplate'])
374 datasetOptions[
'njobs'] = 0
376 with open(datasetOptions[
'inputFileList'],
'r') as filelist:
377 for line
in filelist:
378 if 'CastorPool' in line:
381 if not line.strip()==
'':
382 datasetOptions[
'njobs'] += 1
384 print 'Inputfilelist', datasetOptions[
'inputFileList'],
'does not exist.'
386 if datasetOptions[
'njobs'] == 0:
387 print 'Number of jobs is 0. There may be a problem with the inputfilelist:'
388 print datasetOptions[
'inputFileList']
392 if config.has_option(section,
'njobs'):
393 if config.getint(section,
'njobs')<=datasetOptions[
'njobs']:
394 datasetOptions[
'njobs'] = config.getint(section,
'njobs')
396 print 'njobs is bigger than the default',datasetOptions[
'njobs'],
'. Using default.'
398 print 'No number of jobs specified. Using number of files in inputfilelist as the number of jobs.'
403 with open(datasetOptions[
'configTemplate'],
'r') as INFILE:
404 tmpFile = INFILE.read()
406 print 'The config-template called',datasetOptions[
'configTemplate'],
'cannot be found.'
409 tmpFile = re.sub(
'setupGlobaltag\s*\=\s*[\"\'](.*?)[\"\']',
410 'setupGlobaltag = \"'+datasetOptions[
'globaltag']+
'\"',
412 tmpFile = re.sub(
'setupCollection\s*\=\s*[\"\'](.*?)[\"\']',
413 'setupCollection = \"'+datasetOptions[
'collection']+
'\"',
415 if datasetOptions[
'cosmicsZeroTesla']:
416 tmpFile = re.sub(re.compile(
'setupCosmicsZeroTesla\s*\=\s*.*$', re.M),
417 'setupCosmicsZeroTesla = True',
419 if datasetOptions[
'cosmicsDecoMode']:
420 tmpFile = re.sub(re.compile(
'setupCosmicsDecoMode\s*\=\s*.*$', re.M),
421 'setupCosmicsDecoMode = True',
423 if datasetOptions[
'primaryWidth'] > 0.0:
424 tmpFile = re.sub(re.compile(
'setupPrimaryWidth\s*\=\s*.*$', re.M),
425 'setupPrimaryWidth = '+str(datasetOptions[
'primaryWidth']),
427 if datasetOptions[
'json'] !=
'':
428 tmpFile = re.sub(re.compile(
'setupJson\s*\=\s*.*$', re.M),
429 'setupJson = \"'+datasetOptions[
'json']+
'\"',
432 thisCfgTemplate =
'tmp.py'
433 with open(thisCfgTemplate,
'w')
as OUTFILE:
434 OUTFILE.write(tmpFile)
442 configTemplate = tmpFile
444 generalOptions[
"FirstRunForStartGeometry"])
446 with open(thisCfgTemplate,
"a")
as f: f.write(overrideGT)
450 command =
'mps_setup.pl -m%s -M %s -N %s %s %s %s %d %s %s %s cmscafuser:%s' % (
452 generalOptions[
'pedeMem'],
453 datasetOptions[
'name'],
456 datasetOptions[
'inputFileList'],
457 datasetOptions[
'njobs'],
458 generalOptions[
'classInf'],
459 generalOptions[
'jobname'],
463 print 'Submitting dataset:', datasetOptions[
'name']
464 print 'Baseconfig: ', datasetOptions[
'configTemplate']
465 print 'Collection: ', datasetOptions[
'collection']
466 if datasetOptions[
"collection"]
in (
"ALCARECOTkAlCosmicsCTF0T",
467 "ALCARECOTkAlCosmicsInCollisions"):
468 print 'cosmicsDecoMode: ', datasetOptions[
'cosmicsDecoMode']
469 print 'cosmicsZeroTesla: ', datasetOptions[
'cosmicsZeroTesla']
470 print 'Globaltag: ', datasetOptions[
'globaltag']
471 print 'Number of jobs: ', datasetOptions[
'njobs']
472 print 'Inputfilelist: ', datasetOptions[
'inputFileList']
473 if datasetOptions[
'json'] !=
'':
474 print 'Jsonfile: ', datasetOptions[
'json']
475 print 'Pass to mps_setup: ', command
479 subprocess.call(command, stderr=subprocess.STDOUT, shell=
True)
481 with open(os.devnull,
'w')
as FNULL:
482 subprocess.call(command, stdout=FNULL,
483 stderr=subprocess.STDOUT, shell=
True)
486 os.system(
"rm "+thisCfgTemplate)
489 print "No dataset section defined in '{0}'".
format(aligmentConfig)
490 print "At least one section '[dataset:<name>]' is required."
493 firstPedeConfig =
True
494 for setting
in pedesettings:
498 print "Creating pede job."
500 print "Creating pede jobs using settings from '{0}'.".
format(setting)
501 for weight_conf
in weight_confs:
504 os.system(
"mps_weight.pl -c > /dev/null")
506 for name,weight
in weight_conf:
507 os.system(
"mps_weight.pl -N "+name+
" "+weight)
510 firstPedeConfig =
False
513 os.system(
"mps_setupm.pl")
516 lib = mpslib.jobdatabase()
520 command =
"rm -f jobData/"+lib.JOBDIR[-1]+
"/alignment_merge.py"
524 thisCfgTemplate =
"tmp.py"
525 with open(thisCfgTemplate,
"w")
as f:
526 f.write(configTemplate+overrideGT)
529 command = (
"mps_merge.py -w "+thisCfgTemplate+
" jobData/"+lib.JOBDIR[-1]+
530 "/alignment_merge.py jobData/"+lib.JOBDIR[-1]+
" "+
532 if setting
is not None: command +=
" -a "+setting
535 subprocess.call(command, stderr=subprocess.STDOUT, shell=
True)
537 with open(os.devnull,
'w')
as FNULL:
538 subprocess.call(command, stdout=FNULL,
539 stderr=subprocess.STDOUT, shell=
True)
542 os.system(
"rm "+thisCfgTemplate)
544 if overrideGT.strip() !=
"":
546 msg = (
"Overriding global tag with single-IOV tags extracted from '{}' for "
547 "run number '{}'.".
format(generalOptions[
"globaltag"],
548 generalOptions[
"FirstRunForStartGeometry"]))