CMS 3D CMS Logo

mps_alisetup.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 #############################################################################
4 ## Builds the config-templates from the universal config-template for each
5 ## dataset specified in .ini-file that is passed to this script as argument.
6 ## Then calls mps_setup.pl for all datasets.
7 
11 
12 import argparse
13 import os
14 import re
15 import subprocess
16 import ConfigParser
17 import sys
18 import cPickle
19 import itertools
20 import collections
21 import Alignment.MillePedeAlignmentAlgorithm.mpslib.Mpslibclass as mpslib
22 import Alignment.MillePedeAlignmentAlgorithm.mpslib.tools as mps_tools
23 import Alignment.MillePedeAlignmentAlgorithm.mpsvalidate.iniparser as mpsv_iniparser
24 import Alignment.MillePedeAlignmentAlgorithm.mpsvalidate.trackerTree as mpsv_trackerTree
25 from Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.helper import checked_out_MPS
26 from functools import reduce
27 
28 
29 def handle_process_call(command, verbose = False):
30  """
31  Wrapper around subprocess calls which treats output depending on verbosity
32  level.
33 
34  Arguments:
35  - `command`: list of command items
36  - `verbose`: flag to turn on verbosity
37  """
38 
39  call_method = subprocess.check_call if verbose else subprocess.check_output
40  try:
41  call_method(command, stderr=subprocess.STDOUT)
42  except subprocess.CalledProcessError as e:
43  print "" if verbose else e.output
44  print "Failed to execute command:", " ".join(command)
45  sys.exit(1)
46 
47 
48 def get_weight_configs(config):
49  """Extracts different weight configurations from `config`.
50 
51  Arguments:
52  - `config`: ConfigParser object containing the alignment configuration
53  """
54 
55  weight_dict = collections.OrderedDict()
56  common_weights = {}
57 
58  # loop over datasets to reassign weights
59  for section in config.sections():
60  if 'general' in section:
61  continue
62  elif section == "weights":
63  for option in config.options(section):
64  common_weights[option] = [x.strip() for x in
65  config.get(section, option).split(",")]
66  elif section.startswith("dataset:"):
67  name = section[8:] # get name of dataset by stripping of "dataset:"
68  if config.has_option(section,'weight'):
69  weight_dict[name] = [x.strip() for x in
70  config.get(section, "weight").split(",")]
71  else:
72  weight_dict[name] = ['1.0']
73 
74  weights_list = [[(name, weight) for weight in weight_dict[name]]
75  for name in weight_dict]
76 
77  common_weights_list = [[(name, weight) for weight in common_weights[name]]
78  for name in common_weights]
79  common_weights_dicts = []
80  for item in itertools.product(*common_weights_list):
81  d = {}
82  for name,weight in item:
83  d[name] = weight
84  common_weights_dicts.append(d)
85 
86  configs = []
87  for weight_conf in itertools.product(*weights_list):
88  if len(common_weights) > 0:
89  for common_weight in common_weights_dicts:
90  configs.append([(dataset[0],
91  reduce(lambda x,y: x.replace(y, common_weight[y]),
92  common_weight, dataset[1]))
93  for dataset in weight_conf])
94  else:
95  configs.append(weight_conf)
96 
97  return configs
98 
99 
100 def create_input_db(cms_process, run_number):
101  """
102  Create sqlite file with single-IOV tags and use it to override the GT. If
103  the GT is already customized by the user, the customization has higher
104  priority. Returns a snippet to be appended to the configuration file
105 
106  Arguments:
107  - `cms_process`: cms.Process object
108  - `run_number`: run from which to extract the alignment payloads
109  """
110 
111  run_number = int(run_number)
112  if not run_number > 0:
113  print "'FirstRunForStartGeometry' must be positive, but is", run_number
114  sys.exit(1)
115 
116  input_db_name = os.path.abspath("alignment_input.db")
117  tags = mps_tools.create_single_iov_db(
118  check_iov_definition(cms_process, run_number),
119  run_number, input_db_name)
120 
121  result = ""
122  for record,tag in tags.iteritems():
123  if result == "":
124  result += ("\nimport "
125  "Alignment.MillePedeAlignmentAlgorithm.alignmentsetup."
126  "SetCondition as tagwriter\n")
127  result += ("\ntagwriter.setCondition(process,\n"
128  " connect = \""+tag["connect"]+"\",\n"
129  " record = \""+record+"\",\n"
130  " tag = \""+tag["tag"]+"\")\n")
131 
132  return result
133 
134 
135 def check_iov_definition(cms_process, first_run):
136  """
137  Check consistency of input alignment payloads and IOV definition.
138  Returns a dictionary with the information needed to override possibly
139  problematic input taken from the global tag.
140 
141  Arguments:
142  - `cms_process`: cms.Process object containing the CMSSW configuration
143  - `first_run`: first run for start geometry
144  """
145 
146  print "Checking consistency of IOV definition..."
147  iovs = mps_tools.make_unique_runranges(cms_process.AlignmentProducer)
148 
149  inputs = {
150  "TrackerAlignmentRcd": None,
151  "TrackerSurfaceDeformationRcd": None,
152  "TrackerAlignmentErrorExtendedRcd": None,
153  }
154 
155  for condition in cms_process.GlobalTag.toGet.value():
156  if condition.record.value() in inputs:
157  inputs[condition.record.value()] = {
158  "tag": condition.tag.value(),
159  "connect": ("pro"
160  if not condition.hasParameter("connect")
161  else condition.connect.value())
162  }
163 
164  inputs_from_gt = [record for record in inputs if inputs[record] is None]
165  inputs.update(mps_tools.get_tags(cms_process.GlobalTag.globaltag.value(),
166  inputs_from_gt))
167 
168 
169  if first_run != iovs[0]: # simple consistency check
170  if iovs[0] == 1 and len(iovs) == 1:
171  print "Single IOV output detected in configuration and",
172  print "'FirstRunForStartGeometry' is not 1."
173  print "Creating single IOV output from input conditions in run",
174  print str(first_run)+"."
175  for inp in inputs: inputs[inp]["problematic"] = True
176  else:
177  print "Value of 'FirstRunForStartGeometry' has to match first",
178  print "defined output IOV:",
179  print first_run, "!=", iovs[0]
180  sys.exit(1)
181 
182 
183  for inp in inputs.itervalues():
184  inp["iovs"] = mps_tools.get_iovs(inp["connect"], inp["tag"])
185 
186  # check consistency of input with output
187  problematic_gt_inputs = {}
188  input_indices = {key: len(value["iovs"]) -1
189  for key,value in inputs.iteritems()}
190  for iov in reversed(iovs):
191  for inp in inputs:
192  if inputs[inp].pop("problematic", False):
193  problematic_gt_inputs[inp] = inputs[inp]
194  if inp in problematic_gt_inputs: continue
195  if input_indices[inp] < 0:
196  print "First output IOV boundary at run", iov,
197  print "is before the first input IOV boundary at",
198  print inputs[inp]["iovs"][0], "for '"+inp+"'."
199  print "Please check your run range selection."
200  sys.exit(1)
201  input_iov = inputs[inp]["iovs"][input_indices[inp]]
202  if iov < input_iov:
203  if inp in inputs_from_gt:
204  problematic_gt_inputs[inp] = inputs[inp]
205  print "Found problematic input taken from global tag."
206  print "Input IOV boundary at run",input_iov,
207  print "for '"+inp+"' is within output IOV starting with",
208  print "run", str(iov)+"."
209  print "Deriving an alignment with coarse IOV granularity",
210  print "starting from finer granularity leads to wrong",
211  print "results."
212  print "A single IOV input using the IOV of",
213  print "'FirstRunForStartGeometry' ("+str(first_run)+") is",
214  print "automatically created and used."
215  continue
216  print "Found input IOV boundary at run",input_iov,
217  print "for '"+inp+"' which is within output IOV starting with",
218  print "run", str(iov)+"."
219  print "Deriving an alignment with coarse IOV granularity",
220  print "starting from finer granularity leads to wrong results."
221  print "Please check your run range selection."
222  sys.exit(1)
223  elif iov == input_iov:
224  input_indices[inp] -= 1
225 
226  # check consistency of 'TrackerAlignmentRcd' with other inputs
227  input_indices = {key: len(value["iovs"]) -1
228  for key,value in inputs.iteritems()
229  if (key != "TrackerAlignmentRcd")
230  and (inp not in problematic_gt_inputs)}
231  for iov in reversed(inputs["TrackerAlignmentRcd"]["iovs"]):
232  for inp in input_indices:
233  input_iov = inputs[inp]["iovs"][input_indices[inp]]
234  if iov < input_iov:
235  print "Found input IOV boundary at run",input_iov,
236  print "for '"+inp+"' which is within 'TrackerAlignmentRcd'",
237  print "IOV starting with run", str(iov)+"."
238  print "Deriving an alignment with inconsistent IOV boundaries",
239  print "leads to wrong results."
240  print "Please check your input IOVs."
241  sys.exit(1)
242  elif iov == input_iov:
243  input_indices[inp] -= 1
244 
245  print "IOV consistency check successful."
246  print "-"*60
247 
248  return problematic_gt_inputs
249 
250 
251 def create_mass_storage_directory(mps_dir_name, general_options):
252  """Create MPS mass storage directory where, e.g., mille binaries are stored.
253 
254  Arguments:
255  - `mps_dir_name`: campaign name
256  - `general_options`: general options dictionary
257  """
258 
259  # set directory on eos
260  mss_dir = general_options.get("massStorageDir",
261  "/store/caf/user/"+os.environ["USER"])
262  mss_dir = os.path.join(mss_dir, "MPproduction", mps_dir_name)
263 
264  cmd = ["/afs/cern.ch/project/eos/installation/cms/bin/eos.select",
265  "mkdir", "-p", mss_dir]
266 
267  # create directory
268  if not general_options.get("testMode", False):
269  try:
270  with open(os.devnull, "w") as dump:
271  subprocess.check_call(cmd, stdout = dump, stderr = dump)
272  except subprocess.CalledProcessError:
273  print "Failed to create mass storage directory:", mss_dir
274  sys.exit(1)
275 
276  return mss_dir
277 
278 
279 def create_tracker_tree(global_tag, first_run):
280  """Method to create hidden 'TrackerTree.root'.
281 
282  Arguments:
283  - `global_tag`: global tag from which the tracker geometry is taken
284  - `first_run`: run to specify IOV within `global_tag`
285  """
286 
287  config = mpsv_iniparser.ConfigData()
288  config.jobDataPath = "." # current directory
289  config.globalTag = global_tag
290  config.firstRun = first_run
291  return mpsv_trackerTree.check(config)
292 
293 # ------------------------------------------------------------------------------
294 # set up argument parser and config parser
295 
296 helpEpilog ='''Builds the config-templates from a universal config-template for each
297 dataset specified in .ini-file that is passed to this script.
298 Then calls mps_setup.pl for all datasets.'''
300  description='Setup the alignment as configured in the alignment_config file.',
301  epilog=helpEpilog)
302 # optional argmuent: verbose (toggles output of mps_setup)
303 parser.add_argument('-v', '--verbose', action='store_true',
304  help='display detailed output of mps_setup')
305 # optional argmuent: weight (new weights for additional merge job)
306 parser.add_argument('-w', '--weight', action='store_true',
307  help='create an additional mergejob with (possibly new) weights from .ini-config')
308 # positional argument: config file
309 parser.add_argument('alignmentConfig', action='store',
310  help='name of the .ini config file that specifies the datasets to be used')
311 # parse argument
312 args = parser.parse_args()
313 aligmentConfig = args.alignmentConfig
314 
315 # parse config file
316 config = ConfigParser.ConfigParser()
317 config.optionxform = str # default would give lowercase options -> not wanted
318 config.read(aligmentConfig)
319 
320 
321 
322 #------------------------------------------------------------------------------
323 # construct directories
324 
325 # set variables that are not too specific (millescript, pedescript, etc.)
326 mpsTemplates = os.path.join("src", "Alignment", "MillePedeAlignmentAlgorithm", "templates")
327 if checked_out_MPS()[0]:
328  mpsTemplates = os.path.join(os.environ["CMSSW_BASE"], mpsTemplates)
329 else:
330  mpsTemplates = os.path.join(os.environ["CMSSW_RELEASE_BASE"], mpsTemplates)
331 milleScript = os.path.join(mpsTemplates, "mps_runMille_template.sh")
332 pedeScript = os.path.join(mpsTemplates, "mps_runPede_rfcp_template.sh")
333 
334 # get working directory name
335 currentDir = os.getcwd()
336 mpsdirname = ''
337 match = re.search(re.compile('mpproduction\/mp(.+?)$', re.M|re.I),currentDir)
338 if match:
339  mpsdirname = 'mp'+match.group(1)
340 else:
341  print "Current location does not seem to be a MillePede campaign directory:",
342  print currentDir
343  sys.exit(1)
344 
345 
346 
347 #------------------------------------------------------------------------------
348 # read general-section
349 generalOptions = {}
350 
351 # essential variables
352 for var in ["classInf","pedeMem","jobname", "FirstRunForStartGeometry"]:
353  try:
354  generalOptions[var] = config.get('general',var)
355  except ConfigParser.NoOptionError:
356  print "No", var, "found in [general] section. Please check ini-file."
357  sys.exit(1)
358 
359 # check if datasetdir is given
360 generalOptions['datasetdir'] = ''
361 if config.has_option('general','datasetdir'):
362  generalOptions['datasetdir'] = config.get('general','datasetdir')
363  # add it to environment for later variable expansion:
364  os.environ["datasetdir"] = generalOptions['datasetdir']
365 else:
366  print "No datasetdir given in [general] section.",
367  print "Be sure to give a full path in inputFileList."
368 
369 # check for default options
370 for var in ("globaltag", "configTemplate", "json", "massStorageDir", "testMode"):
371  try:
372  generalOptions[var] = config.get('general',var)
373  except ConfigParser.NoOptionError:
374  if var == "testMode": continue
375  print "No '" + var + "' given in [general] section."
376 
377 # create mass storage directory
378 mssDir = create_mass_storage_directory(mpsdirname, generalOptions)
379 
380 
381 pedesettings = ([x.strip() for x in config.get("general", "pedesettings").split(",")]
382  if config.has_option("general", "pedesettings") else [None])
383 
384 weight_confs = get_weight_configs(config)
385 
386 
387 #------------------------------------------------------------------------------
388 # -w option: Get new weights from .ini and create additional mergejob with these
389 if args.weight:
390 
391  # do some basic checks
392  if not os.path.isdir("jobData"):
393  print "No jobData-folder found. Properly set up the alignment before using the -w option."
394  sys.exit(1)
395  if not os.path.exists("mps.db"):
396  print "No mps.db found. Properly set up the alignment before using the -w option."
397  sys.exit(1)
398 
399  # check if default configTemplate is given
400  try:
401  configTemplate = config.get('general','configTemplate')
402  except ConfigParser.NoOptionError:
403  print 'No default configTemplate given in [general] section.'
404  print 'When using -w, a default configTemplate is needed to build a merge-config.'
405  sys.exit(1)
406 
407  # check if default globaltag is given
408  try:
409  globalTag = config.get('general','globaltag')
410  except ConfigParser.NoOptionError:
411  print "No default 'globaltag' given in [general] section."
412  print "When using -w, a default configTemplate is needed to build a merge-config."
413  sys.exit(1)
414 
415  try:
416  first_run = config.get("general", "FirstRunForStartGeometry")
417  except ConfigParser.NoOptionError:
418  print "Missing mandatory option 'FirstRunForStartGeometry' in [general] section."
419  sys.exit(1)
420 
421  for section in config.sections():
422  if section.startswith("dataset:"):
423  try:
424  collection = config.get(section, "collection")
425  break
426  except ConfigParser.NoOptionError:
427  print "Missing mandatory option 'collection' in section ["+section+"]."
428  sys.exit(1)
429 
430  try:
431  with open(configTemplate,"r") as f:
432  tmpFile = f.read()
433  except IOError:
434  print "The config-template '"+configTemplate+"' cannot be found."
435  sys.exit(1)
436 
437  tmpFile = re.sub('setupGlobaltag\s*\=\s*[\"\'](.*?)[\"\']',
438  'setupGlobaltag = \"'+globalTag+'\"',
439  tmpFile)
440  tmpFile = re.sub('setupCollection\s*\=\s*[\"\'](.*?)[\"\']',
441  'setupCollection = \"'+collection+'\"',
442  tmpFile)
443  tmpFile = re.sub(re.compile("setupRunStartGeometry\s*\=\s*.*$", re.M),
444  "setupRunStartGeometry = "+first_run,
445  tmpFile)
446 
447  thisCfgTemplate = "tmp.py"
448  with open(thisCfgTemplate, "w") as f: f.write(tmpFile)
449 
450  cms_process = mps_tools.get_process_object(thisCfgTemplate)
451 
452  overrideGT = create_input_db(cms_process, first_run)
453  with open(thisCfgTemplate, "a") as f: f.write(overrideGT)
454 
455  for setting in pedesettings:
456  print
457  print "="*60
458  if setting is None:
459  print "Creating pede job."
460  else:
461  print "Creating pede jobs using settings from '{0}'.".format(setting)
462  for weight_conf in weight_confs:
463  print "-"*60
464  # blank weights
465  handle_process_call(["mps_weight.pl", "-c"])
466 
467  for name,weight in weight_conf:
468  handle_process_call(["mps_weight.pl", "-N", name, weight], True)
469 
470  # create new mergejob
471  handle_process_call(["mps_setupm.pl"], True)
472 
473  # read mps.db to find directory of new mergejob
474  lib = mpslib.jobdatabase()
475  lib.read_db()
476 
477  # short cut for jobm path
478  jobm_path = os.path.join("jobData", lib.JOBDIR[-1])
479 
480  # delete old merge-config
481  command = [
482  "rm", "-f",
483  os.path.join(jobm_path, "alignment_merge.py")]
484  handle_process_call(command, args.verbose)
485 
486  # create new merge-config
487  command = [
488  "mps_merge.py",
489  "-w", thisCfgTemplate,
490  os.path.join(jobm_path, "alignment_merge.py"),
491  jobm_path,
492  str(lib.nJobs),
493  ]
494  if setting is not None: command.extend(["-a", setting])
495  print " ".join(command)
496  handle_process_call(command, args.verbose)
497  create_tracker_tree(globalTag, first_run)
498 
499  # store weights configuration
500  with open(os.path.join(jobm_path, ".weights.pkl"), "wb") as f:
501  cPickle.dump(weight_conf, f, 2)
502 
503 
504  # remove temporary file
505  handle_process_call(["rm", thisCfgTemplate])
506 
507  if overrideGT.strip() != "":
508  print "="*60
509  msg = ("Overriding global tag with single-IOV tags extracted from '{}' "
510  "for run number '{}'.".format(generalOptions["globaltag"],
511  first_run))
512  print msg
513  print "-"*60
514  print overrideGT
515 
516  sys.exit()
517 
518 
519 #------------------------------------------------------------------------------
520 # loop over dataset-sections
521 firstDataset = True
522 overrideGT = ""
523 for section in config.sections():
524  if 'general' in section:
525  continue
526  elif section.startswith("dataset:"):
527  datasetOptions={}
528  print "-"*60
529 
530  # set name from section-name
531  datasetOptions['name'] = section[8:]
532 
533  # extract essential variables
534  for var in ['inputFileList','collection']:
535  try:
536  datasetOptions[var] = config.get(section,var)
537  except ConfigParser.NoOptionError:
538  print 'No', var, 'found in', section+'. Please check ini-file.'
539  sys.exit(1)
540 
541  # get globaltag and configTemplate. If none in section, try to get default from [general] section.
542  for var in ['configTemplate','globaltag']:
543  if config.has_option(section,var):
544  datasetOptions[var] = config.get(section,var)
545  else:
546  try:
547  datasetOptions[var] = generalOptions[var]
548  except KeyError:
549  print "No",var,"found in ["+section+"]",
550  print "and no default in [general] section."
551  sys.exit(1)
552 
553  # extract non-essential options
554  datasetOptions['cosmicsZeroTesla'] = False
555  if config.has_option(section,'cosmicsZeroTesla'):
556  datasetOptions['cosmicsZeroTesla'] = config.getboolean(section,'cosmicsZeroTesla')
557 
558  datasetOptions['cosmicsDecoMode'] = False
559  if config.has_option(section,'cosmicsDecoMode'):
560  datasetOptions['cosmicsDecoMode'] = config.getboolean(section,'cosmicsDecoMode')
561 
562  datasetOptions['primaryWidth'] = -1.0
563  if config.has_option(section,'primaryWidth'):
564  datasetOptions['primaryWidth'] = config.getfloat(section,'primaryWidth')
565 
566  datasetOptions['json'] = ''
567  if config.has_option(section, 'json'):
568  datasetOptions['json'] = config.get(section,'json')
569  else:
570  try:
571  datasetOptions['json'] = generalOptions['json']
572  except KeyError:
573  print "No json given in either [general] or ["+section+"] sections.",
574  print "Proceeding without json-file."
575 
576 
577  # replace '${datasetdir}' and other variables in inputFileList-path
578  datasetOptions['inputFileList'] = os.path.expandvars(datasetOptions['inputFileList'])
579 
580  # replace variables in configTemplate-path, e.g. $CMSSW_BASE
581  datasetOptions['configTemplate'] = os.path.expandvars(datasetOptions['configTemplate'])
582 
583 
584  # Get number of jobs from lines in inputfilelist
585  datasetOptions['njobs'] = 0
586  try:
587  with open(datasetOptions['inputFileList'],'r') as filelist:
588  for line in filelist:
589  if 'CastorPool' in line:
590  continue
591  # ignore empty lines
592  if not line.strip()=='':
593  datasetOptions['njobs'] += 1
594  except IOError:
595  print 'Inputfilelist', datasetOptions['inputFileList'], 'does not exist.'
596  sys.exit(1)
597  if datasetOptions['njobs'] == 0:
598  print 'Number of jobs is 0. There may be a problem with the inputfilelist:'
599  print datasetOptions['inputFileList']
600  sys.exit(1)
601 
602  # Check if njobs gets overwritten in .ini-file
603  if config.has_option(section,'njobs'):
604  if config.getint(section,'njobs')<=datasetOptions['njobs']:
605  datasetOptions['njobs'] = config.getint(section,'njobs')
606  else:
607  print 'njobs is bigger than the default',datasetOptions['njobs'],'. Using default.'
608  else:
609  print 'No number of jobs specified. Using number of files in inputfilelist as the number of jobs.'
610 
611 
612  # Build config from template/Fill in variables
613  try:
614  with open(datasetOptions['configTemplate'],'r') as INFILE:
615  tmpFile = INFILE.read()
616  except IOError:
617  print 'The config-template called',datasetOptions['configTemplate'],'cannot be found.'
618  sys.exit(1)
619 
620  tmpFile = re.sub('setupGlobaltag\s*\=\s*[\"\'](.*?)[\"\']',
621  'setupGlobaltag = \"'+datasetOptions['globaltag']+'\"',
622  tmpFile)
623  tmpFile = re.sub(re.compile("setupRunStartGeometry\s*\=\s*.*$", re.M),
624  "setupRunStartGeometry = "+
625  generalOptions["FirstRunForStartGeometry"], tmpFile)
626  tmpFile = re.sub('setupCollection\s*\=\s*[\"\'](.*?)[\"\']',
627  'setupCollection = \"'+datasetOptions['collection']+'\"',
628  tmpFile)
629  if datasetOptions['cosmicsZeroTesla']:
630  tmpFile = re.sub(re.compile('setupCosmicsZeroTesla\s*\=\s*.*$', re.M),
631  'setupCosmicsZeroTesla = True',
632  tmpFile)
633  if datasetOptions['cosmicsDecoMode']:
634  tmpFile = re.sub(re.compile('setupCosmicsDecoMode\s*\=\s*.*$', re.M),
635  'setupCosmicsDecoMode = True',
636  tmpFile)
637  if datasetOptions['primaryWidth'] > 0.0:
638  tmpFile = re.sub(re.compile('setupPrimaryWidth\s*\=\s*.*$', re.M),
639  'setupPrimaryWidth = '+str(datasetOptions['primaryWidth']),
640  tmpFile)
641  if datasetOptions['json'] != '':
642  tmpFile = re.sub(re.compile('setupJson\s*\=\s*.*$', re.M),
643  'setupJson = \"'+datasetOptions['json']+'\"',
644  tmpFile)
645 
646  thisCfgTemplate = 'tmp.py'
647  with open(thisCfgTemplate, 'w') as OUTFILE:
648  OUTFILE.write(tmpFile)
649 
650 
651  # Set mps_setup append option for datasets following the first one
652  append = "-a"
653  if firstDataset:
654  append = ''
655  firstDataset = False
656  configTemplate = tmpFile
657  cms_process = mps_tools.get_process_object(thisCfgTemplate)
658  overrideGT = create_input_db(cms_process,
659  generalOptions["FirstRunForStartGeometry"])
660 
661  with open(thisCfgTemplate, "a") as f: f.write(overrideGT)
662 
663 
664  # create mps_setup command
665  command = ["mps_setup.pl",
666  "-m",
667  append,
668  "-M", generalOptions["pedeMem"],
669  "-N", datasetOptions["name"],
670  milleScript,
671  thisCfgTemplate,
672  datasetOptions["inputFileList"],
673  str(datasetOptions["njobs"]),
674  generalOptions["classInf"],
675  generalOptions["jobname"],
676  pedeScript,
677  "cmscafuser:"+mssDir]
678  command = filter(lambda x: len(x.strip()) > 0, command)
679 
680  # Some output:
681  print 'Submitting dataset:', datasetOptions['name']
682  print 'Baseconfig: ', datasetOptions['configTemplate']
683  print 'Collection: ', datasetOptions['collection']
684  if datasetOptions["collection"] in ("ALCARECOTkAlCosmicsCTF0T",
685  "ALCARECOTkAlCosmicsInCollisions"):
686  print 'cosmicsDecoMode: ', datasetOptions['cosmicsDecoMode']
687  print 'cosmicsZeroTesla: ', datasetOptions['cosmicsZeroTesla']
688  print 'Globaltag: ', datasetOptions['globaltag']
689  print 'Number of jobs: ', datasetOptions['njobs']
690  print 'Inputfilelist: ', datasetOptions['inputFileList']
691  if datasetOptions['json'] != '':
692  print 'Jsonfile: ', datasetOptions['json']
693  print 'Pass to mps_setup: ', " ".join(command)
694 
695  # call the command and toggle verbose output
696  handle_process_call(command, args.verbose)
697 
698  # remove temporary file
699  handle_process_call(["rm", thisCfgTemplate])
700 
701 if firstDataset:
702  print "No dataset section defined in '{0}'".format(aligmentConfig)
703  print "At least one section '[dataset:<name>]' is required."
704  sys.exit(1)
705 
706 firstPedeConfig = True
707 for setting in pedesettings:
708  print
709  print "="*60
710  if setting is None:
711  print "Creating pede job."
712  else:
713  print "Creating pede jobs using settings from '{0}'.".format(setting)
714  for weight_conf in weight_confs:
715  print "-"*60
716  # blank weights
717  handle_process_call(["mps_weight.pl", "-c"])
718 
719  for name,weight in weight_conf:
720  handle_process_call(["mps_weight.pl", "-N", name, weight], True)
721 
722  if not firstPedeConfig:
723  # create new mergejob
724  handle_process_call(["mps_setupm.pl"], True)
725 
726  # read mps.db to find directory of new mergejob
727  lib = mpslib.jobdatabase()
728  lib.read_db()
729 
730  # short cut for jobm path
731  jobm_path = os.path.join("jobData", lib.JOBDIR[-1])
732 
733  # delete old merge-config
734  command = ["rm", "-f", os.path.join(jobm_path, "alignment_merge.py")]
735  handle_process_call(command, args.verbose)
736 
737  thisCfgTemplate = "tmp.py"
738  with open(thisCfgTemplate, "w") as f:
739  f.write(configTemplate+overrideGT)
740 
741  # create new merge-config
742  command = [
743  "mps_merge.py",
744  "-w", thisCfgTemplate,
745  os.path.join(jobm_path, "alignment_merge.py"),
746  jobm_path,
747  str(lib.nJobs),
748  ]
749  if setting is not None: command.extend(["-a", setting])
750  print " ".join(command)
751  handle_process_call(command, args.verbose)
752  tracker_tree_path = create_tracker_tree(datasetOptions["globaltag"],
753  generalOptions["FirstRunForStartGeometry"])
754  if firstPedeConfig:
755  os.symlink(tracker_tree_path,
756  os.path.abspath(os.path.join(jobm_path,
757  ".TrackerTree.root")))
758  firstPedeConfig = False
759 
760  # store weights configuration
761  with open(os.path.join(jobm_path, ".weights.pkl"), "wb") as f:
762  cPickle.dump(weight_conf, f, 2)
763 
764  # remove temporary file
765  handle_process_call(["rm", thisCfgTemplate])
766 
767 if overrideGT.strip() != "":
768  print "="*60
769  msg = ("Overriding global tag with single-IOV tags extracted from '{}' for "
770  "run number '{}'.".format(generalOptions["globaltag"],
771  generalOptions["FirstRunForStartGeometry"]))
772  print msg
773  print "-"*60
774  print overrideGT
def check_iov_definition(cms_process, first_run)
def checked_out_MPS()
Definition: helper.py:4
static void pop(std::vector< T > &vec, unsigned int index)
Definition: LHEEvent.cc:150
def create_input_db(cms_process, run_number)
def create_tracker_tree(global_tag, first_run)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def handle_process_call(command, verbose=False)
Definition: mps_alisetup.py:29
def get_weight_configs(config)
Definition: mps_alisetup.py:48
def create_mass_storage_directory(mps_dir_name, general_options)
double split
Definition: MVATrainer.cc:139