CMS 3D CMS Logo

Functions | Variables
mps_setup_new_align Namespace Reference

Functions

def add_campaign (campaign_file, campaign, args)
 
def copy_default_templates (args, next_campaign)
 
def customize_default_template (file_name, regex_replace_pairs)
 
def get_first_match (regex, directory)
 
def main (argv=None)
 

Variables

tuple required_version = (2,7)
 

Function Documentation

def mps_setup_new_align.add_campaign (   campaign_file,
  campaign,
  args 
)
Adds a line with campaign information from `args` to `campaign_file`.

Arguments:
- `campaign_file`: output file
- `campaign`: name of the campaign
- `args`: command line arguments for this campaign

Definition at line 142 of file mps_setup_new_align.py.

References split.

Referenced by main().

142 def add_campaign(campaign_file, campaign, args):
143  """Adds a line with campaign information from `args` to `campaign_file`.
144 
145  Arguments:
146  - `campaign_file`: output file
147  - `campaign`: name of the campaign
148  - `args`: command line arguments for this campaign
149  """
150 
151  campaign_info = campaign.ljust(10)
152  campaign_info += os.environ["USER"].ljust(12)
153  campaign_info += datetime.date.today().isoformat().ljust(11)
154 
155  version = os.environ["CMSSW_VERSION"]
156  if args.checked_out[1]:
157  local_area = os.path.join(os.environ["CMSSW_BASE"], "src")
158  with open(os.devnull, 'w') as devnull:
159  # check which tags (-> e.g. release names) point at current commit
160  p = subprocess.Popen(["git", "tag", "--points-at", "HEAD"],
161  cwd = local_area, stdout=subprocess.PIPE,
162  stderr=devnull)
163  tags = p.communicate()[0].split()
164  # check for deleted, untracked, modified files respecting .gitignore:
165  p = subprocess.Popen(["git", "ls-files", "-d", "-o", "-m",
166  "--exclude-standard"],
167  cwd = local_area, stdout=subprocess.PIPE,
168  stderr=devnull)
169  files = p.communicate()[0].split()
170  # check for staged tracked files:
171  p = subprocess.Popen(["git", "diff", "--name-only", "--staged"],
172  cwd = local_area, stdout=subprocess.PIPE,
173  stderr=devnull)
174  files.extend(p.communicate()[0].split())
175  if version not in tags or len(files) != 0:
176  version += " (mod.)"
177 
178  campaign_info += version.ljust(34)
179  campaign_info += args.type.ljust(17)
180  campaign_info += args.description.strip() + "\n"
181 
182  fcntl.flock(campaign_file, fcntl.LOCK_EX)
183  campaign_file.write(campaign_info)
184  fcntl.flock(campaign_file, fcntl.LOCK_UN)
185 
186  return campaign_info
187 
188 
def add_campaign(campaign_file, campaign, args)
double split
Definition: MVATrainer.cc:139
def mps_setup_new_align.copy_default_templates (   args,
  next_campaign 
)
Copies the default configuration templates.

Arguments:
- `args`: container with the needed information
- `next_campaign`: destination for the copy operation

Definition at line 189 of file mps_setup_new_align.py.

References customize_default_template(), and join().

Referenced by main().

189 def copy_default_templates(args, next_campaign):
190  """Copies the default configuration templates.
191 
192  Arguments:
193  - `args`: container with the needed information
194  - `next_campaign`: destination for the copy operation
195  """
196 
197  default_conf_dir = os.path.join(args.MPS_dir, "templates")
198  template_files = ("universalConfigTemplate.py", "alignment_config.ini")
199  for f in template_files:
200  shutil.copy(os.path.join(default_conf_dir, f), next_campaign)
201 
202  # customize alignment_config.ini
203  # - replace job name with campaign ID as initial value
204  # - replace global tag with the corresponding auto GT depending on data type
205  customize_default_template(os.path.join(next_campaign, "alignment_config.ini"),
206  (r"(jobname\s*[=:])(.*)", r"\1 "+next_campaign),
207  (r"(globaltag\s*[=:])(.*)",
208  r"\1 auto:run2_"+args.type.lower()))
209 
210  print " - copied default configuration templates from",
211  print "'"+default_conf_dir+"'"
212  print " - please modify these template files according to your needs:",
213  print ", ".join(template_files)
214 
215 
def copy_default_templates(args, next_campaign)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def customize_default_template(file_name, regex_replace_pairs)
def mps_setup_new_align.customize_default_template (   file_name,
  regex_replace_pairs 
)
Replace all lines in `file_name` matching `regex_string` with
`replace_string`.
Lines starting with '#' or ';' are ignored.

Arguments:
- `file_name`: path to the file to be customized
- `regex_replace_pairs`: tuples containing a regex string and its
                         replacement

Definition at line 216 of file mps_setup_new_align.py.

Referenced by copy_default_templates().

216 def customize_default_template(file_name, *regex_replace_pairs):
217  """
218  Replace all lines in `file_name` matching `regex_string` with
219  `replace_string`.
220  Lines starting with '#' or ';' are ignored.
221 
222  Arguments:
223  - `file_name`: path to the file to be customized
224  - `regex_replace_pairs`: tuples containing a regex string and its
225  replacement
226  """
227 
228  comment = re.compile(r"^\s*[;#]")
229  replacements = []
230  for regex_string, replace_string in regex_replace_pairs:
231  replacements.append((re.compile(regex_string), replace_string))
232 
233  customized = ""
234  with open(file_name, "r") as f:
235  for line in f:
236  custom_line = line
237  if not re.match(comment, custom_line):
238  for regex,replace_string in replacements:
239  custom_line = re.sub(regex, replace_string, custom_line)
240  customized += custom_line
241  with open(file_name, "w") as f:
242  f.write(customized)
243 
244 
def customize_default_template(file_name, regex_replace_pairs)
def mps_setup_new_align.get_first_match (   regex,
  directory 
)
Checks if `directory` matches `regex` and returns the first match converted
to an integer. If it does not match -1 is returned.

Arguments:
- `regex`: Regular expression to be tested against
- `directory`: name of the directory under test

Definition at line 125 of file mps_setup_new_align.py.

References createfilelist.int.

Referenced by main().

125 def get_first_match(regex, directory):
126  """
127  Checks if `directory` matches `regex` and returns the first match converted
128  to an integer. If it does not match -1 is returned.
129 
130  Arguments:
131  - `regex`: Regular expression to be tested against
132  - `directory`: name of the directory under test
133  """
134 
135  result = regex.search(directory)
136  if result is None:
137  return -1
138  else:
139  return int(result.group(1))
140 
141 
def get_first_match(regex, directory)
def mps_setup_new_align.main (   argv = None)
Main routine of the script.

Arguments:
- `argv`: arguments passed to the main routine

Definition at line 28 of file mps_setup_new_align.py.

References add_campaign(), helper.checked_out_MPS(), copy_default_templates(), get_first_match(), join(), genParticles_cff.map, and harvestTrackValidationPlots.str.

28 def main(argv = None):
29  """Main routine of the script.
30 
31  Arguments:
32  - `argv`: arguments passed to the main routine
33  """
34 
35  if argv == None:
36  argv = sys.argv[1:]
37 
38  parser = argparse.ArgumentParser(
39  description="Setup a new alignment campaign in the MPproduction area.")
40  parser.add_argument("-d", "--description", dest="description", required=True,
41  help="comment to describe the purpose of the campaign")
42  parser.add_argument("-t", "--data-type", dest="type", required=True,
43  metavar="TYPE", choices=["MC", "data"],
44  help="type of the input data (choices: %(choices)s)")
45  parser.add_argument("-c", "--copy", dest="copy", metavar="CAMPAIGN",
46  help="input campaign (optional)")
47  args = parser.parse_args(argv)
48 
49 
50  if os.path.basename(os.path.normpath(os.getcwd())) != "MPproduction":
51  print ">>> Cannot create a campaign outside of the 'MPproduction' area."
52  print ">>> Please change to the 'MPproduction' directory first."
53  sys.exit(1)
54 
55  if len(args.description.strip()) == 0:
56  print ">>> Please provide a non-empty description of the campaign"
57  sys.exit(1)
58 
59  MPS_dir = os.path.join("src", "Alignment", "MillePedeAlignmentAlgorithm")
60  args.checked_out = checked_out_MPS()
61  if args.checked_out[0]:
62  MPS_dir = os.path.join(os.environ["CMSSW_BASE"], MPS_dir)
63  else:
64  MPS_dir = os.path.join(os.environ["CMSSW_RELEASE_BASE"], MPS_dir)
65  args.MPS_dir = MPS_dir
66 
67  mp_regex = re.compile(r"mp([0-9]+).*")
68  all_campaign_numbers = sorted(map(lambda x: get_first_match(mp_regex, x),
69  os.listdir(".")))
70  next_number = (0
71  if len(all_campaign_numbers) == 0
72  else sorted(all_campaign_numbers)[-1] + 1)
73 
74  while True:
75  try:
76  number_of_digits = len(str(next_number))
77  number_of_digits = 4 if number_of_digits <= 4 else number_of_digits
78  next_campaign = "mp{{0:0{0}d}}".format(number_of_digits)
79  next_campaign = next_campaign.format(next_number)
80  os.makedirs(next_campaign)
81  print ">>> Created new campaign:", next_campaign
82 
83  campaign_list = "MP_ali_list.txt"
84  with open(campaign_list, "a") as f:
85  campaign_info = add_campaign(f, next_campaign, args)
86  backup_dir = ".MP_ali_list"
87  try:
88  os.makedirs(backup_dir)
89  except OSError as e:
90  if e.args == (17, 'File exists'):
91  pass
92  else:
93  raise
94  with open(os.path.join(backup_dir, campaign_list), "a") as f:
95  fcntl.flock(f, fcntl.LOCK_EX)
96  f.write(campaign_info)
97  fcntl.flock(f, fcntl.LOCK_UN)
98  print " - updated campaign list '"+campaign_list+"'"
99 
100  if args.copy is None:
101  copy_default_templates(args, next_campaign)
102  else:
103  copied_files = []
104  for ext in ("py", "ini", "txt"):
105  for config_file in glob.glob(args.copy+"/*."+ext):
106  copied_files.append(os.path.basename(config_file))
107  shutil.copy(config_file, next_campaign)
108  if len(copied_files) == 0:
109  print " - no configuration files for '"+args.copy+"'"
110  copy_default_templates(args, next_campaign)
111  else:
112  print " - copied configuration files from",
113  print "'"+args.copy+"':", ", ".join(copied_files)
114 
115  except OSError as e:
116  if e.args == (17, 'File exists'):
117  next_number += 1 # someone created a campaign ~at the same time
118  continue
119  else:
120  raise
121  break
122 
123 
def checked_out_MPS()
Definition: helper.py:4
def copy_default_templates(args, next_campaign)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def add_campaign(campaign_file, campaign, args)
def get_first_match(regex, directory)

Variable Documentation

tuple mps_setup_new_align.required_version = (2,7)

Definition at line 19 of file mps_setup_new_align.py.