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 (files, 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

◆ check_proxy()

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

Definition at line 220 of file tools.py.

220 def check_proxy():
221  """Check if GRID proxy has been initialized."""
222 
223  try:
224  with open(os.devnull, "w") as dump:
225  subprocess.check_call(["voms-proxy-info", "--exists"],
226  stdout = dump, stderr = dump)
227  except subprocess.CalledProcessError:
228  return False
229  return True
230 
231 
def check_proxy()
Definition: tools.py:220

◆ compute_product_string()

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 209 of file tools.py.

References nano_mu_digi_cff.float, and str.

209 def compute_product_string(product_string):
210  """Takes `product_string` and returns the product of the factors as string.
211 
212  Arguments:
213  - `product_string`: string containing product ('<factor>*<factor>*...')
214  """
215 
216  factors = [float(f) for f in product_string.split("*")]
217  return str(reduce(lambda x,y: x*y, factors))
218 
219 
#define str(s)
def compute_product_string(product_string)
Definition: tools.py:209

◆ create_single_iov_db()

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 14 of file tools.py.

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

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

◆ get_iovs()

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 167 of file tools.py.

References python.cmstools.all(), ALCARECOTkAlBeamHalo_cff.filter, createfilelist.int, print(), and python.rootplot.root2matplotlib.replace().

167 def get_iovs(db, tag):
168  """Retrieve the list of IOVs from `db` for `tag`.
169 
170  Arguments:
171  - `db`: database connection string
172  - `tag`: tag of database record
173  """
174 
175  db = db.replace("sqlite_file:", "").replace("sqlite:", "")
176  db = db.replace("frontier://FrontierProd/CMS_CONDITIONS", "pro")
177  db = db.replace("frontier://FrontierPrep/CMS_CONDITIONS", "dev")
178 
179  con = conddb.connect(url = conddb.make_url(db))
180  session = con.session()
181  IOV = session.get_dbtype(conddb.IOV)
182 
183  iovs = set(session.query(IOV.since).filter(IOV.tag_name == tag).all())
184  if len(iovs) == 0:
185  print("No IOVs found for tag '"+tag+"' in database '"+db+"'.")
186  sys.exit(1)
187 
188  session.close()
189 
190  return sorted([int(item[0]) for item in iovs])
191 
192 
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:25
def replace(string, replacements)
def get_iovs(db, tag)
Definition: tools.py:167
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47

◆ get_process_object()

def tools.get_process_object (   cfg)
Returns cms.Process object defined in `cfg`.

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

Definition at line 87 of file tools.py.

References print().

87 def get_process_object(cfg):
88  """Returns cms.Process object defined in `cfg`.
89 
90  Arguments:
91  - `cfg`: path to CMSSW config file
92  """
93 
94  sys.path.append(os.path.dirname(cfg)) # add location to python path
95  cache_stdout = sys.stdout
96  sys.stdout = open(os.devnull, "w") # suppress unwanted output
97  try:
98  __configuration = \
99  importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
100  except Exception as e:
101  print("Problem detected in configuration file '{0}'.".format(cfg))
102  raise e
103  sys.stdout = cache_stdout
104  sys.path.pop() # clean up python path again
105  try:
106  os.remove(cfg+"c") # try to remove temporary .pyc file
107  except OSError as e:
108  if e.args == (2, "No such file or directory"): pass
109  else: raise
110 
111  return __configuration.process
112 
113 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def get_process_object(cfg)
Definition: tools.py:87

◆ get_tags()

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 132 of file tools.py.

References python.cmstools.all(), ALCARECOTkAlBeamHalo_cff.filter, and print().

132 def get_tags(global_tag, records):
133  """Get tags for `records` contained in `global_tag`.
134 
135  Arguments:
136  - `global_tag`: global tag of interest
137  - `records`: database records of interest
138  """
139 
140  if len(records) == 0: return {} # avoid useless DB query
141 
142  # check for auto GT
143  if global_tag.startswith("auto:"):
144  import Configuration.AlCa.autoCond as AC
145  try:
146  global_tag = AC.autoCond[global_tag.split("auto:")[-1]]
147  except KeyError:
148  print("Unsupported auto GT:", global_tag)
149  sys.exit(1)
150 
151  # setting up the DB session
152  con = conddb.connect(url = conddb.make_url())
153  session = con.session()
154  GlobalTagMap = session.get_dbtype(conddb.GlobalTagMap)
155 
156  # query tag names for records of interest contained in `global_tag`
157  tags = session.query(GlobalTagMap.record, GlobalTagMap.tag_name).\
158  filter(GlobalTagMap.global_tag_name == global_tag,
159  GlobalTagMap.record.in_(records)).all()
160 
161  # closing the DB session
162  session.close()
163 
164  return {item[0]: {"tag": item[1], "connect": "pro"} for item in tags}
165 
166 
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:25
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def get_tags(global_tag, records)
Definition: tools.py:132

◆ getDatasetStr()

def tools.getDatasetStr (   datasetpath)

Definition at line 20 of file tools.py.

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

◆ getTerminalSize()

def tools.getTerminalSize ( )

Definition at line 94 of file tools.py.

References createfilelist.int.

Referenced by CrabHelper.CrabHelper.check_crabtask().

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

◆ haddLocal()

def tools.haddLocal (   files,
  result_file,
  extension = 'root' 
)

Definition at line 41 of file tools.py.

References join().

Referenced by DTWorkflow.DTWorkflow.prepare_common_write().

41 def haddLocal(files,result_file,extension = 'root'):
42  log.info("hadd command: {}".format(" ".join(['hadd','-f', result_file] + files)))
43  process = subprocess.Popen( ['hadd','-f', result_file] + files,
44  stdout=subprocess.PIPE,
45  stderr=subprocess.STDOUT)
46  stdout = process.communicate()[0]
47  log.info(f"hadd output: {stdout}")
48  return process.returncode
49 
def haddLocal(files, result_file, extension='root')
Definition: tools.py:41
static std::string join(char **cmd)
Definition: RemoteFile.cc:19

◆ interrupt()

def tools.interrupt (   signum,
  frame 
)

Definition at line 91 of file tools.py.

91 def interrupt(signum, frame):
92  raise Exception("")
93 
def interrupt(signum, frame)
Definition: tools.py:91

◆ listFilesLocal()

def tools.listFilesLocal (   paths,
  extension = '.root' 
)

Definition at line 28 of file tools.py.

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

◆ loadCmsProcess()

def tools.loadCmsProcess (   psetPath)

Definition at line 54 of file tools.py.

Referenced by DTVdriftWorkflow.DTvdriftWorkflow.prepare_meantimer_submit(), DTVdriftWorkflow.DTvdriftWorkflow.prepare_meantimer_write(), 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().

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

◆ loadCmsProcessFile()

def tools.loadCmsProcessFile (   psetName)

Definition at line 50 of file tools.py.

50 def loadCmsProcessFile(psetName):
51  pset = imp.load_source("psetmodule",psetName)
52  return pset.process
53 
def loadCmsProcessFile(psetName)
Definition: tools.py:50

◆ make_unique_runranges()

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 114 of file tools.py.

References createfilelist.int.

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

◆ prependPaths()

def tools.prependPaths (   process,
  seqname 
)

Definition at line 64 of file tools.py.

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

64 def prependPaths(process,seqname):
65  for path in process.paths:
66  getattr(process,path)._seq = getattr(process,seqname)*getattr(process,path)._seq
67 
def prependPaths(process, seqname)
Definition: tools.py:64

◆ remove_existing_object()

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 232 of file tools.py.

References print(), and FastTimerService_cff.range.

Referenced by create_single_iov_db().

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

◆ replace_factors()

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 193 of file tools.py.

References str.

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

◆ replaceTemplate()

def tools.replaceTemplate (   template,
  opts 
)

Definition at line 10 of file tools.py.

References print(), fileinputsource_cfi.read, and str.

10 def replaceTemplate(template,**opts):
11  result = open(template).read()
12  for item in opts:
13  old = '@@%s@@'%item
14  new = str(opts[item])
15  print("Replacing",old,"to",new)
16  result = result.replace(old,new)
17 
18  return result
19 
def replaceTemplate(template, opts)
Definition: tools.py:10
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
#define str(s)

◆ run_checked()

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 67 of file tools.py.

References join(), and print().

Referenced by create_single_iov_db().

67 def run_checked(cmd, suppress_stderr = False):
68  """Run `cmd` and exit in case of failures.
69 
70  Arguments:
71  - `cmd`: list containing the strings of the command
72  - `suppress_stderr`: suppress output from stderr
73  """
74 
75  try:
76  with open(os.devnull, "w") as devnull:
77  if suppress_stderr:
78  subprocess.check_call(cmd, stdout = devnull, stderr = devnull)
79  else:
80  subprocess.check_call(cmd, stdout = devnull)
81  except subprocess.CalledProcessError as e:
82  print("Problem in running the following command:")
83  print(" ".join(e.cmd))
84  sys.exit(1)
85 
86 
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:67
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:19

◆ stdinWait()

def tools.stdinWait (   text,
  default,
  time,
  timeoutDisplay = None,
  kwargs 
)

Definition at line 68 of file tools.py.

References print().

Referenced by CrabHelper.CrabHelper.check_crabtask().

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