CMS 3D CMS Logo

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

Functions

def check_proxy
 
def compute_product_string
 
def create_single_iov_db
 
def get_iovs
 
def get_process_object
 
def get_tags
 
def getDatasetStr
 
def getTerminalSize
 
def haddLocal
 
def interrupt
 
def listFilesLocal
 
def loadCmsProcess
 
def loadCmsProcessFile
 
def make_unique_runranges
 
def prependPaths
 
def remove_existing_object
 
def replace_factors
 
def replaceTemplate
 
def run_checked
 
def stdinWait
 

Variables

tuple log = logging.getLogger(__name__)
 

Function Documentation

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

Definition at line 220 of file tools.py.

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

210 def compute_product_string(product_string):
211  """Takes `product_string` and returns the product of the factors as string.
212 
213  Arguments:
214  - `product_string`: string containing product ('<factor>*<factor>*...')
215  """
216 
217  factors = [float(f) for f in product_string.split("*")]
218  return str(reduce(lambda x,y: x*y, factors))
219 
def compute_product_string
Definition: tools.py:209
#define str(s)
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 
15 def create_single_iov_db(inputs, run_number, output_db):
16  """Create an sqlite file with single-IOV tags for alignment payloads.
17 
18  Arguments:
19  - `inputs`: dictionary with input needed for payload extraction
20  - `run_number`: run for which the IOVs are selected
21  - `output_db`: name of the output sqlite file
22  """
23 
24  # find the IOV containing `run_number`
25  for record,tag in inputs.items():
26  run_is_covered = False
27  for iov in reversed(tag["iovs"]):
28  if iov <= run_number:
29  tag["since"] = str(iov)
30  run_is_covered = True
31  break
32  if not run_is_covered:
33  msg = ("Run number {0:d} is not covered in '{1:s}' ({2:s}) from"
34  " '{3:s}'.".format(run_number, tag["tag"], record,
35  global_tag))
36  print(msg)
37  print("Aborting...")
38  sys.exit(1)
39 
40  result = {}
41  remove_existing_object(output_db)
42 
43  for record,tag in inputs.items():
44  result[record] = {"connect": "sqlite_file:"+output_db,
45  "tag": "_".join([tag["tag"], tag["since"]])}
46 
47  if tag["connect"] == "pro":
48  source_connect = "frontier://FrontierProd/CMS_CONDITIONS"
49  elif tag["connect"] == "dev":
50  source_connect = "frontier://FrontierPrep/CMS_CONDITIONS"
51  else:
52  source_connect = tag["connect"]
53 
54  cmd = ("conddb_import",
55  "-f", source_connect,
56  "-c", result[record]["connect"],
57  "-i", tag["tag"],
58  "-t", result[record]["tag"],
59  "-b", str(run_number),
60  "-e", str(run_number))
61  run_checked(cmd)
62  if len(inputs) > 0:
63  run_checked(["sqlite3", output_db, "update iov set since=1"])
64 
65  return result
66 
def run_checked
Definition: tools.py:67
def create_single_iov_db
Definition: tools.py:14
def remove_existing_object
Definition: tools.py:232
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)
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(), alcazmumu_cfi.filter, print(), and python.rootplot.root2matplotlib.replace().

168 def get_iovs(db, tag):
169  """Retrieve the list of IOVs from `db` for `tag`.
170 
171  Arguments:
172  - `db`: database connection string
173  - `tag`: tag of database record
174  """
175 
176  db = db.replace("sqlite_file:", "").replace("sqlite:", "")
177  db = db.replace("frontier://FrontierProd/CMS_CONDITIONS", "pro")
178  db = db.replace("frontier://FrontierPrep/CMS_CONDITIONS", "dev")
179 
180  con = conddb.connect(url = conddb.make_url(db))
181  session = con.session()
182  IOV = session.get_dbtype(conddb.IOV)
183 
184  iovs = set(session.query(IOV.since).filter(IOV.tag_name == tag).all())
185  if len(iovs) == 0:
186  print("No IOVs found for tag '"+tag+"' in database '"+db+"'.")
187  sys.exit(1)
188 
189  session.close()
190 
191  return sorted([int(item[0]) for item in iovs])
192 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def all
workaround iterator generators for ROOT classes
Definition: cmstools.py:25
def get_iovs
Definition: tools.py:167
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 
88 def get_process_object(cfg):
89  """Returns cms.Process object defined in `cfg`.
90 
91  Arguments:
92  - `cfg`: path to CMSSW config file
93  """
94 
95  sys.path.append(os.path.dirname(cfg)) # add location to python path
96  cache_stdout = sys.stdout
97  sys.stdout = open(os.devnull, "w") # suppress unwanted output
98  try:
99  __configuration = \
100  importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
101  except Exception as e:
102  print("Problem detected in configuration file '{0}'.".format(cfg))
103  raise e
104  sys.stdout = cache_stdout
105  sys.path.pop() # clean up python path again
106  try:
107  os.remove(cfg+"c") # try to remove temporary .pyc file
108  except OSError as e:
109  if e.args == (2, "No such file or directory"): pass
110  else: raise
111 
112  return __configuration.process
113 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def get_process_object
Definition: tools.py:87
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(), alcazmumu_cfi.filter, and print().

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

Definition at line 20 of file tools.py.

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

Definition at line 96 of file tools.py.

Referenced by CrabHelper.CrabHelper.check_crabtask().

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

Definition at line 41 of file tools.py.

References listFilesLocal().

Referenced by DTWorkflow.DTWorkflow.prepare_common_write().

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

Definition at line 93 of file tools.py.

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

Definition at line 28 of file tools.py.

Referenced by haddLocal().

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

Definition at line 56 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().

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

Definition at line 52 of file tools.py.

52 
53 def loadCmsProcessFile(psetName):
54  pset = imp.load_source("psetmodule",psetName)
55  return pset.process
def loadCmsProcessFile
Definition: tools.py:52
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.

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

Definition at line 66 of file tools.py.

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

66 
67 def prependPaths(process,seqname):
68  for path in process.paths:
69  getattr(process,path)._seq = getattr(process,seqname)*getattr(process,path)._seq
def prependPaths
Definition: tools.py:66
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 sistrip::SpyUtilities.range().

Referenced by create_single_iov_db().

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

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

Definition at line 10 of file tools.py.

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

10 
11 def replaceTemplate(template,**opts):
12  result = open(template).read()
13  for item in opts:
14  old = '@@%s@@'%item
15  new = str(opts[item])
16  print("Replacing",old,"to",new)
17  result = result.replace(old,new)
18 
19  return result
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def replaceTemplate
Definition: tools.py:10
#define str(s)
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 
68 def run_checked(cmd, suppress_stderr = False):
69  """Run `cmd` and exit in case of failures.
70 
71  Arguments:
72  - `cmd`: list containing the strings of the command
73  - `suppress_stderr`: suppress output from stderr
74  """
75 
76  try:
77  with open(os.devnull, "w") as devnull:
78  if suppress_stderr:
79  subprocess.check_call(cmd, stdout = devnull, stderr = devnull)
80  else:
81  subprocess.check_call(cmd, stdout = devnull)
82  except subprocess.CalledProcessError as e:
83  print("Problem in running the following command:")
84  print(" ".join(e.cmd))
85  sys.exit(1)
86 
def run_checked
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
def tools.stdinWait (   text,
  default,
  time,
  timeoutDisplay = None,
  kwargs 
)

Definition at line 70 of file tools.py.

References print().

Referenced by CrabHelper.CrabHelper.check_crabtask().

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

Variable Documentation

tuple tools.log = logging.getLogger(__name__)

Definition at line 8 of file tools.py.