CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
Functions | Variables
mps_setup_new_align Namespace Reference

Functions

def add_campaign
 
def copy_default_templates
 
def customize_default_template
 
def get_first_match
 
def main
 

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().

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

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

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

Referenced by main().

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

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

Variable Documentation

tuple mps_setup_new_align.required_version = (2,7)

Definition at line 19 of file mps_setup_new_align.py.