CMS 3D CMS Logo

Functions
tools Namespace Reference

Functions

def check_proxy ()
 
def compute_product_string (product_string)
 
def create_single_iov_db (inputs, run_number, output_db)
 
def get_iovs (db, tag)
 
def get_process_object (cfg)
 
def get_tags (global_tag, records)
 
def getDatasetStr (datasetpath)
 
def getTerminalSize ()
 
def haddLocal (localdir, result_file, extension='root')
 
def interrupt (signum, frame)
 
def listFilesLocal (paths, extension='.root')
 
def loadCmsProcess (psetPath)
 
def loadCmsProcessFile (psetName)
 
def make_unique_runranges (ali_producer)
 
def prependPaths (process, seqname)
 
def remove_existing_object (path)
 
def replace_factors (product_string, name, value)
 
def replaceTemplate (template, opts)
 
def run_checked (cmd, suppress_stderr=False)
 
def stdinWait (text, default, time, timeoutDisplay=None, kwargs)
 

Function Documentation

def tools.check_proxy ( )
Check if GRID proxy has been initialized.

Definition at line 217 of file tools.py.

218  """Check if GRID proxy has been initialized."""
219 
220  try:
221  with open(os.devnull, "w") as dump:
222  subprocess.check_call(["voms-proxy-info", "--exists"],
223  stdout = dump, stderr = dump)
224  except subprocess.CalledProcessError:
225  return False
226  return True
227 
228 
def check_proxy()
Definition: tools.py:217
def tools.compute_product_string (   product_string)
Takes `product_string` and returns the product of the factors as string.

Arguments:
- `product_string`: string containing product ('<factor>*<factor>*...')

Definition at line 206 of file tools.py.

References objects.autophobj.float, and harvestTrackValidationPlots.str.

206 def compute_product_string(product_string):
207  """Takes `product_string` and returns the product of the factors as string.
208 
209  Arguments:
210  - `product_string`: string containing product ('<factor>*<factor>*...')
211  """
212 
213  factors = [float(f) for f in product_string.split("*")]
214  return str(reduce(lambda x,y: x*y, factors))
215 
216 
def compute_product_string(product_string)
Definition: tools.py:206
def tools.create_single_iov_db (   inputs,
  run_number,
  output_db 
)
Create an sqlite file with single-IOV tags for alignment payloads.

Arguments:
- `inputs`: dictionary with input needed for payload extraction
- `run_number`: run for which the IOVs are selected
- `output_db`: name of the output sqlite file

Definition at line 11 of file tools.py.

References join(), remove_existing_object(), run_checked(), and harvestTrackValidationPlots.str.

11 def create_single_iov_db(inputs, run_number, output_db):
12  """Create an sqlite file with single-IOV tags for alignment payloads.
13 
14  Arguments:
15  - `inputs`: dictionary with input needed for payload extraction
16  - `run_number`: run for which the IOVs are selected
17  - `output_db`: name of the output sqlite file
18  """
19 
20  # find the IOV containing `run_number`
21  for record,tag in inputs.iteritems():
22  run_is_covered = False
23  for iov in reversed(tag["iovs"]):
24  if iov <= run_number:
25  tag["since"] = str(iov)
26  run_is_covered = True
27  break
28  if not run_is_covered:
29  msg = ("Run number {0:d} is not covered in '{1:s}' ({2:s}) from"
30  " '{3:s}'.".format(run_number, tag["tag"], record,
31  global_tag))
32  print msg
33  print "Aborting..."
34  sys.exit(1)
35 
36  result = {}
37  remove_existing_object(output_db)
38 
39  for record,tag in inputs.iteritems():
40  result[record] = {"connect": "sqlite_file:"+output_db,
41  "tag": "_".join([tag["tag"], tag["since"]])}
42 
43  if tag["connect"] == "pro":
44  source_connect = "frontier://FrontierProd/CMS_CONDITIONS"
45  elif tag["connect"] == "dev":
46  source_connect = "frontier://FrontierPrep/CMS_CONDITIONS"
47  else:
48  source_connect = tag["connect"]
49 
50  cmd = ("conddb_import",
51  "-f", source_connect,
52  "-c", result[record]["connect"],
53  "-i", tag["tag"],
54  "-t", result[record]["tag"],
55  "-b", str(run_number),
56  "-e", str(run_number))
57  run_checked(cmd)
58  if len(inputs) > 0:
59  run_checked(["sqlite3", output_db, "update iov set since=1"])
60 
61  return result
62 
63 
def remove_existing_object(path)
Definition: tools.py:229
def create_single_iov_db(inputs, run_number, output_db)
Definition: tools.py:11
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:64
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def tools.get_iovs (   db,
  tag 
)
Retrieve the list of IOVs from `db` for `tag`.

Arguments:
- `db`: database connection string
- `tag`: tag of database record

Definition at line 164 of file tools.py.

References Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), ALCARECOTkAlBeamHalo_cff.filter, createfilelist.int, and python.rootplot.root2matplotlib.replace().

164 def get_iovs(db, tag):
165  """Retrieve the list of IOVs from `db` for `tag`.
166 
167  Arguments:
168  - `db`: database connection string
169  - `tag`: tag of database record
170  """
171 
172  db = db.replace("sqlite_file:", "").replace("sqlite:", "")
173  db = db.replace("frontier://FrontierProd/CMS_CONDITIONS", "pro")
174  db = db.replace("frontier://FrontierPrep/CMS_CONDITIONS", "dev")
175 
176  con = conddb.connect(url = conddb.make_url(db))
177  session = con.session()
178  IOV = session.get_dbtype(conddb.IOV)
179 
180  iovs = set(session.query(IOV.since).filter(IOV.tag_name == tag).all())
181  if len(iovs) == 0:
182  print "No IOVs found for tag '"+tag+"' in database '"+db+"'."
183  sys.exit(1)
184 
185  session.close()
186 
187  return sorted([int(item[0]) for item in iovs])
188 
189 
def replace(string, replacements)
def get_iovs(db, tag)
Definition: tools.py:164
def tools.get_process_object (   cfg)
Returns cms.Process object defined in `cfg`.

Arguments:
- `cfg`: path to CMSSW config file

Definition at line 84 of file tools.py.

85  """Returns cms.Process object defined in `cfg`.
86 
87  Arguments:
88  - `cfg`: path to CMSSW config file
89  """
90 
91  sys.path.append(os.path.dirname(cfg)) # add location to python path
92  cache_stdout = sys.stdout
93  sys.stdout = open(os.devnull, "w") # suppress unwanted output
94  try:
95  __configuration = \
96  importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
97  except Exception as e:
98  print "Problem detected in configuration file '{0}'.".format(cfg)
99  raise e
100  sys.stdout = cache_stdout
101  sys.path.pop() # clean up python path again
102  try:
103  os.remove(cfg+"c") # try to remove temporary .pyc file
104  except OSError as e:
105  if e.args == (2, "No such file or directory"): pass
106  else: raise
107 
108  return __configuration.process
109 
110 
def get_process_object(cfg)
Definition: tools.py:84
def tools.get_tags (   global_tag,
  records 
)
Get tags for `records` contained in `global_tag`.

Arguments:
- `global_tag`: global tag of interest
- `records`: database records of interest

Definition at line 129 of file tools.py.

References Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), and ALCARECOTkAlBeamHalo_cff.filter.

129 def get_tags(global_tag, records):
130  """Get tags for `records` contained in `global_tag`.
131 
132  Arguments:
133  - `global_tag`: global tag of interest
134  - `records`: database records of interest
135  """
136 
137  if len(records) == 0: return {} # avoid useless DB query
138 
139  # check for auto GT
140  if global_tag.startswith("auto:"):
141  import Configuration.AlCa.autoCond as AC
142  try:
143  global_tag = AC.autoCond[global_tag.split("auto:")[-1]]
144  except KeyError:
145  print "Unsupported auto GT:", global_tag
146  sys.exit(1)
147 
148  # setting up the DB session
149  con = conddb.connect(url = conddb.make_url())
150  session = con.session()
151  GlobalTagMap = session.get_dbtype(conddb.GlobalTagMap)
152 
153  # query tag names for records of interest contained in `global_tag`
154  tags = session.query(GlobalTagMap.record, GlobalTagMap.tag_name).\
155  filter(GlobalTagMap.global_tag_name == global_tag,
156  GlobalTagMap.record.in_(records)).all()
157 
158  # closing the DB session
159  session.close()
160 
161  return {item[0]: {"tag": item[1], "connect": "pro"} for item in tags}
162 
163 
def get_tags(global_tag, records)
Definition: tools.py:129
def tools.getDatasetStr (   datasetpath)

Definition at line 19 of file tools.py.

19 def getDatasetStr(datasetpath):
20  datasetstr = datasetpath
21  datasetstr.strip()
22  if datasetstr[0] == '/': datasetstr = datasetstr[1:]
23  datasetstr = datasetstr.replace('/','_')
24 
25  return datasetstr
26 
def getDatasetStr(datasetpath)
Definition: tools.py:19
def tools.getTerminalSize ( )

Definition at line 95 of file tools.py.

References createfilelist.int.

Referenced by CrabHelper.CrabHelper.check_crabtask().

96  #taken from http://stackoverflow.com/a/566752
97  # returns width, size of terminal
98  env = os.environ
99  def ioctl_GWINSZ(fd):
100  try:
101  import fcntl, termios, struct, os
102  cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
103  '1234'))
104  except:
105  return
106  return cr
107  cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
108  if not cr:
109  try:
110  fd = os.open(os.ctermid(), os.O_RDONLY)
111  cr = ioctl_GWINSZ(fd)
112  os.close(fd)
113  except:
114  pass
115  if not cr:
116  cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
117 
118  ### Use get(key[, default]) instead of a try/catch
119  #try:
120  # cr = (env['LINES'], env['COLUMNS'])
121  #except:
122  # cr = (25, 80)
123  return int(cr[1]), int(cr[0])
124 
def getTerminalSize()
Definition: tools.py:95
def tools.haddLocal (   localdir,
  result_file,
  extension = 'root' 
)

Definition at line 40 of file tools.py.

References listFilesLocal().

Referenced by DTWorkflow.DTWorkflow.prepare_common_write().

40 def haddLocal(localdir,result_file,extension = 'root'):
41  if not os.path.exists( localdir ):
42  raise ValueError("localdir for hadd operation does not exist" )
43 
44  files = listFilesLocal([localdir],extension)
45  process = subprocess.Popen( ['hadd','-f', result_file] + files,
46  stdout=subprocess.PIPE,
47  stderr=subprocess.STDOUT)
48  stdout = process.communicate()[0]
49  return process.returncode
50 
def haddLocal(localdir, result_file, extension='root')
Definition: tools.py:40
def listFilesLocal(paths, extension='.root')
Definition: tools.py:27
def tools.interrupt (   signum,
  frame 
)

Definition at line 92 of file tools.py.

92 def interrupt(signum, frame):
93  raise Exception("")
94 
def interrupt(signum, frame)
Definition: tools.py:92
def tools.listFilesLocal (   paths,
  extension = '.root' 
)

Definition at line 27 of file tools.py.

Referenced by haddLocal().

27 def listFilesLocal(paths, extension = '.root'):
28  file_paths = []
29  for path in paths:
30  if not os.path.exists( path ):
31  log.error( "Specified input path '%s' does not exist!" % path )
32  continue
33  if path.endswith( extension ):
34  file_paths.append( path )
35  for root, dirnames, filenames in os.walk( path ):
36  for filename in fnmatch.filter( filenames, '*' + extension ):
37  file_paths.append( os.path.join( root, filename ) )
38  return file_paths
39 
def listFilesLocal(paths, extension='.root')
Definition: tools.py:27
def tools.loadCmsProcess (   psetPath)

Definition at line 55 of file tools.py.

Referenced by DTTtrigWorkflow.DTttrigWorkflow.prepare_residuals_correction(), DTTtrigWorkflow.DTttrigWorkflow.prepare_residuals_submit(), DTVdriftWorkflow.DTvdriftWorkflow.prepare_segment_write(), DTTtrigWorkflow.DTttrigWorkflow.prepare_timeboxes_correction(), DTTtrigWorkflow.DTttrigWorkflow.prepare_validation_submit(), and DTTtrigWorkflow.DTttrigWorkflow.prepare_validation_write().

55 def loadCmsProcess(psetPath):
56  module = __import__(psetPath)
57  process = sys.modules[psetPath].process
58 
59  import copy
60  #FIXME: clone process
61  #processNew = copy.deepcopy(process)
62  processNew = copy.copy(process)
63  return processNew
64 
def loadCmsProcess(psetPath)
Definition: tools.py:55
def tools.loadCmsProcessFile (   psetName)

Definition at line 51 of file tools.py.

51 def loadCmsProcessFile(psetName):
52  pset = imp.load_source("psetmodule",psetName)
53  return pset.process
54 
def loadCmsProcessFile(psetName)
Definition: tools.py:51
def tools.make_unique_runranges (   ali_producer)
Derive unique run ranges from AlignmentProducer PSet.

Arguments:
- `ali_producer`: cms.PSet containing AlignmentProducer configuration

Definition at line 111 of file tools.py.

References createfilelist.int.

111 def make_unique_runranges(ali_producer):
112  """Derive unique run ranges from AlignmentProducer PSet.
113 
114  Arguments:
115  - `ali_producer`: cms.PSet containing AlignmentProducer configuration
116  """
117 
118  if (hasattr(ali_producer, "RunRangeSelection") and
119  len(ali_producer.RunRangeSelection) > 0):
120  iovs = set([int(iov)
121  for sel in ali_producer.RunRangeSelection
122  for iov in sel.RunRanges])
123  if len(iovs) == 0: return [1] # single IOV starting from run 1
124  return sorted(iovs)
125  else:
126  return [1] # single IOV starting from run 1
127 
128 
def make_unique_runranges(ali_producer)
Definition: tools.py:111
def tools.prependPaths (   process,
  seqname 
)

Definition at line 65 of file tools.py.

Referenced by DTWorkflow.DTWorkflow.add_preselection(), and DTWorkflow.DTWorkflow.add_raw_option().

65 def prependPaths(process,seqname):
66  for path in process.paths:
67  getattr(process,path)._seq = getattr(process,seqname)*getattr(process,path)._seq
68 
def prependPaths(process, seqname)
Definition: tools.py:65
def tools.remove_existing_object (   path)
Tries to remove file or directory located at `path`. If the user
has no delete permissions, the object is moved to a backup
file. If this fails it tries 5 times in total and then asks to
perform a cleanup by a user with delete permissions.

Arguments:
- `name`: name of the object to be (re)moved

Definition at line 229 of file tools.py.

Referenced by create_single_iov_db().

230  """
231  Tries to remove file or directory located at `path`. If the user
232  has no delete permissions, the object is moved to a backup
233  file. If this fails it tries 5 times in total and then asks to
234  perform a cleanup by a user with delete permissions.
235 
236  Arguments:
237  - `name`: name of the object to be (re)moved
238  """
239 
240  if os.path.exists(path):
241  remove_method = shutil.rmtree if os.path.isdir(path) else os.remove
242  move_method = shutil.move if os.path.isdir(path) else os.rename
243  try:
244  remove_method(path)
245  except OSError as e:
246  if e.args != (13, "Permission denied"): raise
247  backup_path = path.rstrip("/")+"~"
248  for _ in xrange(5):
249  try:
250  if os.path.exists(backup_path): remove_method(backup_path)
251  move_method(path, backup_path)
252  break
253  except OSError as e:
254  if e.args != (13, "Permission denied"): raise
255  backup_path += "~"
256  if os.path.exists(path):
257  msg = ("Cannot remove '{}' due to missing 'delete' ".format(path)
258  +"permissions and the limit of 5 backups is reached. Please "
259  "ask a user with 'delete' permissions to clean up.")
260  print msg
261  sys.exit(1)
262 
def remove_existing_object(path)
Definition: tools.py:229
def tools.replace_factors (   product_string,
  name,
  value 
)
Takes a `product_string` and replaces all factors with `name` by `value`.

Arguments:
- `product_string`: input string containing a product
- `name`: name of the factor
- `value`: value of the factor

Definition at line 190 of file tools.py.

References harvestTrackValidationPlots.str.

190 def replace_factors(product_string, name, value):
191  """Takes a `product_string` and replaces all factors with `name` by `value`.
192 
193  Arguments:
194  - `product_string`: input string containing a product
195  - `name`: name of the factor
196  - `value`: value of the factor
197  """
198 
199  value = str(value) # ensure it's a string
200  return re.sub(r"^"+name+r"$", value, # single factor
201  re.sub(r"[*]"+name+r"$", r"*"+value, # rhs
202  re.sub(r"^"+name+r"[*]", value+r"*", # lhs
203  re.sub(r"[*]"+name+r"[*]", r"*"+value+r"*",
204  product_string))))
205 
def replace_factors(product_string, name, value)
Definition: tools.py:190
def tools.replaceTemplate (   template,
  opts 
)

Definition at line 9 of file tools.py.

References harvestTrackValidationPlots.str.

9 def replaceTemplate(template,**opts):
10  result = open(template).read()
11  for item in opts:
12  old = '@@%s@@'%item
13  new = str(opts[item])
14  print "Replacing",old,"to",new
15  result = result.replace(old,new)
16 
17  return result
18 
def replaceTemplate(template, opts)
Definition: tools.py:9
def tools.run_checked (   cmd,
  suppress_stderr = False 
)
Run `cmd` and exit in case of failures.

Arguments:
- `cmd`: list containing the strings of the command
- `suppress_stderr`: suppress output from stderr

Definition at line 64 of file tools.py.

References join().

Referenced by create_single_iov_db().

64 def run_checked(cmd, suppress_stderr = False):
65  """Run `cmd` and exit in case of failures.
66 
67  Arguments:
68  - `cmd`: list containing the strings of the command
69  - `suppress_stderr`: suppress output from stderr
70  """
71 
72  try:
73  with open(os.devnull, "w") as devnull:
74  if suppress_stderr:
75  subprocess.check_call(cmd, stdout = devnull, stderr = devnull)
76  else:
77  subprocess.check_call(cmd, stdout = devnull)
78  except subprocess.CalledProcessError as e:
79  print "Problem in running the following command:"
80  print " ".join(e.cmd)
81  sys.exit(1)
82 
83 
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:64
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def tools.stdinWait (   text,
  default,
  time,
  timeoutDisplay = None,
  kwargs 
)

Definition at line 69 of file tools.py.

Referenced by CrabHelper.CrabHelper.check_crabtask().

69 def stdinWait(text, default, time, timeoutDisplay = None, **kwargs):
70  # taken and adjusted from http://stackoverflow.com/a/25860968
71  signal.signal(signal.SIGALRM, interrupt)
72  signal.alarm(time) # sets timeout
73  global timeout
74  try:
75  inp = raw_input(text)
76  signal.alarm(0)
77  timeout = False
78  except (KeyboardInterrupt):
79  printInterrupt = kwargs.get("printInterrupt", True)
80  if printInterrupt:
81  print "Keyboard interrupt"
82  timeout = True # Do this so you don't mistakenly get input when there is none
83  inp = default
84  except:
85  timeout = True
86  if not timeoutDisplay is None:
87  print timeoutDisplay
88  signal.alarm(0)
89  inp = default
90  return inp
91 
def stdinWait(text, default, time, timeoutDisplay=None, kwargs)
Definition: tools.py:69