CMS 3D CMS Logo

Functions | Variables
tools Namespace Reference

Functions

def _test ()
 
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 read_constant_graph (graph_path, create_session=None, as_text=None)
 
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)
 
def visualize_graph (graph, log_dir=None, start_tensorboard=False, tensorboard_args="", **kwargs)
 
def write_constant_graph (session, output_names, graph_path, **kwargs)
 

Variables

 __all__
 
 TF1
 
 tf1
 
 TF2
 

Function Documentation

◆ _test()

def tools._test ( )
private
Internal test of the above functions based on the deepjet model.

Definition at line 193 of file tools.py.

193 def _test():
194  """
195  Internal test of the above functions based on the deepjet model.
196  """
197  deepjet_model = "/cvmfs/cms.cern.ch/slc7_amd64_gcc820/cms/data-RecoBTag-Combined/V01-02-01/" \
198  "RecoBTag/Combined/data/DeepFlavourV03_10X_training/constant_graph.pb"
199  deepjet_output = "ID_pred/Softmax"
200 
201  if not os.path.exists(deepjet_model):
202  print("cannot run tests as deepjet model '{}' does not exist".format(deepjet_model))
203  sys.exit(1)
204 
205  # load the graph
206  read_constant_graph(deepjet_model, create_session=False)
207  if tf1:
208  g, s = read_constant_graph(deepjet_model, create_session=True)
209 
210  # write the graph
211  if tf1:
212  with tempfile.NamedTemporaryFile(suffix=".pb") as ntf:
213  write_constant_graph(s, [deepjet_output], ntf.name)
214 
215  # visualize the graph
216  if tf1:
217  visualize_graph(g)
218 
219 

References print(), read_constant_graph(), visualize_graph(), and write_constant_graph().

◆ check_proxy()

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

Definition at line 221 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 
232 

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

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 
220 

References dqmMemoryStats.float, and str.

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

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 six.iteritems(inputs):
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 six.iteritems(inputs):
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 
67 

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

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

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 
193 

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

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

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 
114 

References print().

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

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 
167 

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

◆ 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 

◆ getTerminalSize()

def tools.getTerminalSize ( )

Definition at line 96 of file tools.py.

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

References createfilelist.int.

Referenced by CrabHelper.CrabHelper.check_crabtask().

◆ haddLocal()

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

Definition at line 41 of file tools.py.

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

References listFilesLocal().

Referenced by DTWorkflow.DTWorkflow.prepare_common_write().

◆ interrupt()

def tools.interrupt (   signum,
  frame 
)

Definition at line 93 of file tools.py.

93 def interrupt(signum, frame):
94  raise Exception("")
95 

◆ 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 

Referenced by haddLocal().

◆ loadCmsProcess()

def tools.loadCmsProcess (   psetPath)

◆ loadCmsProcessFile()

def tools.loadCmsProcessFile (   psetName)

Definition at line 52 of file tools.py.

52 def loadCmsProcessFile(psetName):
53  pset = imp.load_source("psetmodule",psetName)
54  return pset.process
55 

◆ 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 115 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 
132 

References createfilelist.int.

◆ prependPaths()

def tools.prependPaths (   process,
  seqname 
)

Definition at line 66 of file tools.py.

66 def prependPaths(process,seqname):
67  for path in process.paths:
68  getattr(process,path)._seq = getattr(process,seqname)*getattr(process,path)._seq
69 

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

◆ read_constant_graph()

def tools.read_constant_graph (   graph_path,
  create_session = None,
  as_text = None 
)
Reads a saved TensorFlow graph from *graph_path* and returns it. When *create_session* is
*True*, a session object (compatible with the v1 API) is created and returned as well as the
second value of a 2-tuple. The default value of *create_session* is *True* when TensorFlow v1
is detected, and *False* otherwise. When *as_text* is *True*, or *None* and the file extension
is ``".pbtxt"`` or ``".pb.txt"``, the content of the file at *graph_path* is expected to be a
human-readable text file. Otherwise, it is expected to be a binary protobuf file. Example:

.. code-block:: python

    graph = read_constant_graph("path/to/model.pb", create_session=False)

    graph, session = read_constant_graph("path/to/model.pb", create_session=True)

Definition at line 38 of file tools.py.

38 def read_constant_graph(graph_path, create_session=None, as_text=None):
39  """
40  Reads a saved TensorFlow graph from *graph_path* and returns it. When *create_session* is
41  *True*, a session object (compatible with the v1 API) is created and returned as well as the
42  second value of a 2-tuple. The default value of *create_session* is *True* when TensorFlow v1
43  is detected, and *False* otherwise. When *as_text* is *True*, or *None* and the file extension
44  is ``".pbtxt"`` or ``".pb.txt"``, the content of the file at *graph_path* is expected to be a
45  human-readable text file. Otherwise, it is expected to be a binary protobuf file. Example:
46 
47  .. code-block:: python
48 
49  graph = read_constant_graph("path/to/model.pb", create_session=False)
50 
51  graph, session = read_constant_graph("path/to/model.pb", create_session=True)
52  """
53  if as_text is None:
54  as_text = graph_path.endswith((".pbtxt", ".pb.txt"))
55 
56  graph = tf.Graph()
57  with graph.as_default():
58  graph_def = graph.as_graph_def()
59 
60  if as_text:
61  # use a simple pb reader to load the file into graph_def
62  from google.protobuf import text_format
63  with open(graph_path, "r") as f:
64  text_format.Merge(f.read(), graph_def)
65 
66  else:
67  # use the gfile api depending on the TF version
68  if TF1:
69  from tensorflow.python.platform import gfile
70  with gfile.FastGFile(graph_path, "rb") as f:
71  graph_def.ParseFromString(f.read())
72  else:
73  with tf.io.gfile.GFile(graph_path, "rb") as f:
74  graph_def.ParseFromString(f.read())
75 
76  # import the graph_def (pb object) into the actual graph
77  tf.import_graph_def(graph_def, name="")
78 
79  # determine the create_session default
80  if create_session is None:
81  create_session = TF1
82 
83  if create_session:
84  if not tf1:
85  raise NotImplementedError("the v1 compatibility layer of TensorFlow v2 (tf.compat.v1) "
86  "is required by read_constant_graph when create_session is True, but missing")
87  session = tf1.Session(graph=graph)
88  return graph, session
89  else:
90  return graph
91 
92 

Referenced by _test(), and visualize_graph().

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

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)

References print(), and FastTimerService_cff.range.

Referenced by create_single_iov_db().

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

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))))
209 

References str.

◆ replaceTemplate()

def tools.replaceTemplate (   template,
**  opts 
)

Definition at line 10 of file tools.py.

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 

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

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

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 
87 

References join(), and print().

Referenced by create_single_iov_db().

◆ stdinWait()

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

Definition at line 70 of file tools.py.

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

References print().

Referenced by CrabHelper.CrabHelper.check_crabtask().

◆ visualize_graph()

def tools.visualize_graph (   graph,
  log_dir = None,
  start_tensorboard = False,
  tensorboard_args = "",
**  kwargs 
)
Visualizes a TensorFlow *graph* by adding it to a ``tf.summary.FileWriter``. *graph* can be
either a graph object or a path to a pb file. In the latter case, :py:func:`read_constant_graph`
is used and all *kwargs* are forwarded. The file writer object is instantiated with a *log_dir*
which, when empty, defaults to a temporary directory. This is especially usefull when
*start_tensorboard* is *True*, in which case a subprocesses is started to run a *tensorboard*
instance with additional arguments given as a string *tensorboard_args*. The subprocess is
terminated on keyboard interrupt.

.. note::

    When used with TensorFlow v2, this function requires the v1 API compatibility layer. When
    :py:attr:`tf.compat.v1` is not available, a *NotImplementedError* is raised.

Definition at line 132 of file tools.py.

132 def visualize_graph(graph, log_dir=None, start_tensorboard=False, tensorboard_args="", **kwargs):
133  """
134  Visualizes a TensorFlow *graph* by adding it to a ``tf.summary.FileWriter``. *graph* can be
135  either a graph object or a path to a pb file. In the latter case, :py:func:`read_constant_graph`
136  is used and all *kwargs* are forwarded. The file writer object is instantiated with a *log_dir*
137  which, when empty, defaults to a temporary directory. This is especially usefull when
138  *start_tensorboard* is *True*, in which case a subprocesses is started to run a *tensorboard*
139  instance with additional arguments given as a string *tensorboard_args*. The subprocess is
140  terminated on keyboard interrupt.
141 
142  .. note::
143 
144  When used with TensorFlow v2, this function requires the v1 API compatibility layer. When
145  :py:attr:`tf.compat.v1` is not available, a *NotImplementedError* is raised.
146  """
147  # complain when the v1 compatibility layer is not existing
148  if not tf1:
149  raise NotImplementedError("the v1 compatibility layer of TensorFlow v2 (tf.compat.v1) is "
150  "required by visualize_graph, but missing")
151 
152  # prepare the log_dir
153  is_tmp = not log_dir
154  if is_tmp:
155  log_dir = tempfile.mkdtemp()
156  elif not os.path.exists(log_dir):
157  os.makedirs(log_dir)
158 
159  # read the graph when a string is passed
160  if isinstance(graph, six.string_types):
161  graph = read_constant_graph(graph, create_session=False, **kwargs)
162 
163  # switch to non-eager mode for the FileWriter to work
164  eager = getattr(tf1, "executing_eagerly", lambda: False)()
165  if eager:
166  tf1.disable_eager_execution()
167 
168  # write to file
169  writer = tf1.summary.FileWriter(log_dir)
170  writer.add_graph(graph)
171 
172  # reset the eager mode
173  if eager:
174  tf1.enable_eager_execution()
175 
176  # optionally start a tensorboard process
177  if start_tensorboard:
178  print("starting tensorboard with logdir {}".format(log_dir))
179  cmd = "tensorboard --logdir '{}' {}".format(log_dir, tensorboard_args)
180  p = subprocess.Popen(cmd, shell=True, executable="/bin/bash", preexec_fn=os.setsid)
181  try:
182  p.communicate()
183  except (Exception, KeyboardInterrupt):
184  print("tensorboard terminated")
185  os.killpg(os.getpgid(p.pid), signal.SIGTERM)
186  pass
187 
188  # cleanup when log_dir is temporary
189  if is_tmp:
190  shutil.rmtree(log_dir)
191 
192 

References print(), and read_constant_graph().

Referenced by _test().

◆ write_constant_graph()

def tools.write_constant_graph (   session,
  output_names,
  graph_path,
**  kwargs 
)
Takes a TensorFlow *session* object (compatible with the v1 API), converts its contained graph
into a simpler version with variables translated into constant tensors, and saves it to a pb
file defined by *graph_path*. *output_numes* must be a list of names of output tensors to save.
In turn, TensorFlow internally determines which subgraph(s) to convert and save. All *kwargs*
are forwarded to :py:func:`tf.compat.v1.train.write_graph`. Intermediate output directories are
created, the output file is removed when already existing, and the absolute and normalized
output path is returned.

.. note::

    When used with TensorFlow v2, this function requires the v1 API compatibility layer. When
    :py:attr:`tf.compat.v1` is not available, a *NotImplementedError* is raised.

Definition at line 93 of file tools.py.

93 def write_constant_graph(session, output_names, graph_path, **kwargs):
94  """
95  Takes a TensorFlow *session* object (compatible with the v1 API), converts its contained graph
96  into a simpler version with variables translated into constant tensors, and saves it to a pb
97  file defined by *graph_path*. *output_numes* must be a list of names of output tensors to save.
98  In turn, TensorFlow internally determines which subgraph(s) to convert and save. All *kwargs*
99  are forwarded to :py:func:`tf.compat.v1.train.write_graph`. Intermediate output directories are
100  created, the output file is removed when already existing, and the absolute and normalized
101  output path is returned.
102 
103  .. note::
104 
105  When used with TensorFlow v2, this function requires the v1 API compatibility layer. When
106  :py:attr:`tf.compat.v1` is not available, a *NotImplementedError* is raised.
107  """
108  # complain when the v1 compatibility layer is not existing
109  if not tf1:
110  raise NotImplementedError("the v1 compatibility layer of TensorFlow v2 (tf.compat.v1) is "
111  "required by write_constant_graph, but missing")
112 
113  # convert the graph
114  constant_graph = tf1.graph_util.convert_variables_to_constants(session,
115  session.graph.as_graph_def(), output_names)
116 
117  # prepare the output path
118  graph_path = os.path.normpath(os.path.abspath(graph_path))
119  graph_dir, graph_name = os.path.split(graph_path)
120  if not os.path.exists(graph_dir):
121  os.makedirs(graph_dir)
122  if os.path.exists(graph_path):
123  os.remove(graph_path)
124 
125  # write the graph
126  kwargs.setdefault("as_text", False)
127  tf1.train.write_graph(constant_graph, graph_dir, graph_name, **kwargs)
128 
129  return graph_path
130 
131 

Referenced by _test().

Variable Documentation

◆ __all__

tools.__all__
private

Definition at line 8 of file tools.py.

◆ TF1

tools.TF1

Definition at line 23 of file tools.py.

Referenced by CalibrationAlgorithm.analyse(), PedsFullNoiseAlgorithm.analyse(), CalibrationScanAlgorithm.analyse(), EcalLaserAnalyzerYousi.analyze(), ResolutionCreator.beginJob(), HiCentralityBiasFilter.beginJob(), L1TRate_Offline.bookHistograms(), L1TRate.bookHistograms(), BSvsPVPlots(), BTagEntry.BTagEntry(), PPSAlignmentHarvester.buildModeGraph(), ApeEstimatorSummary.calculateApe(), PixelLumiDQM.calculateBunchMask(), SiPixelSCurveCalibrationAnalysis.calibrationSetup(), chi2toMinimize(), L1TOccupancyClient.compareWithStrip(), MuonBremsstrahlungSimulator.compute(), EcalTPGParamBuilder.computeLUT(), MuonTestSummary.doEnergyTests(), SideBandSubtract.doFastSubtraction(), PPSAlignmentHarvester.doMatch(), OuterTrackerMCHarvester.dqmEndJob(), SusyPostProcessor.dqmEndJob(), DTLocalTriggerSynchTest.dqmEndJob(), EcalZmassClient.dqmEndJob(), DTResolutionAnalysisTest.dqmEndJob(), Vx3DHLTAnalyzer.dqmEndLuminosityBlock(), DTResolutionTest.dqmEndLuminosityBlock(), Comparator.DrawGaussSigmaOverMeanXSlice(), Comparator.DrawGaussSigmaSlice(), Tutils.drawGFit(), DTNoiseComputation.endJob(), EcalLaserAnalyzerYousi.endJob(), analyzer::SiPixelLorentzAngle.endJob(), HOCalibAnalyzer.endJob(), L1TRate_Offline.endLuminosityBlock(), L1TRate.endLuminosityBlock(), ESRecHitFitAlgo.ESRecHitFitAlgo(), ESTimingTask.ESTimingTask(), DTMeanTimerFitter.evaluateVDriftAndReso(), LASPeakFinder.FindPeakIn(), BSFitter.Fit_d0phi(), Fit_MaximumPoint(), LA_Filler_Fitter.fit_width_profile(), BSFitter.Fit_z_chi2(), BeamMonitor.FitAndFill(), FakeBeamMonitor.FitAndFill(), SymmetryFit.fitfunction(), EgammaObjects.fitHistos(), CSCSimHitMatcher.fitHitsInChamber(), MuScleFitUtils.fitMass(), PPSAlignmentConfigESSource.fitProfile(), DTResidualFitter.fitResiduals(), SplitVertexResolution.fitResiduals(), TrackerOfflineValidationSummary.fitResiduals(), PVValHelper.fitResiduals(), TrackerOfflineValidation.fitResiduals(), SplitVertexResolution.fitResiduals_v0(), MuScleFitUtils.fitReso(), PFJetDQMPostProcessor.fitResponse(), TkLasBeamFitter.fitter(), DTTimeBoxFitter.fitTimeBox(), DTMeanTimerFitter.fitTMax(), fpeak_convoluted(), backgroundFunctionBase.functionForIntegral(), MuonTestSummary.GaussFit(), PFClient_JetRes.getHistogramParameters(), PFClient.getHistogramParameters(), PhiSymmetryCalibration.getKfactors(), CastorLedAnalysis.GetLedConst(), HcalLedAnalysis.GetLedConst(), BTagDifferentialPlot.getMistag(), GetMPV(), SiStripGainCosmicCalculator.getPeakOfLandau(), SiStripGainsPCLHarvester.getPeakOfLandau(), SiStripGainFromData.getPeakOfLandau(), SiStripGainFromCalibTree.getPeakOfLandau(), CastorPedestalAnalysis.GetPedConst(), HcalPedestalAnalysis.GetPedConst(), L1TRate.getXSexFitsOMDS(), L1TRate_Offline.getXSexFitsPython(), L1TRate.getXSexFitsPython(), reco::modules::HICaloCompatibleTrackSelector.HICaloCompatibleTrackSelector(), HiFJRhoFlowModulationProducer.HiFJRhoFlowModulationProducer(), MuonResidualsFitter.histogramChi2GaussianFit(), EvolutionECAL.InducedAbsorptionEM(), JetResolution.initialize(), LRHelpFunctions.initLRHistsAndFits(), fastsim::MuonBremsstrahlung.interact(), JetResolution.JetResolution(), L1TkMuCorrDynamicWindows.L1TkMuCorrDynamicWindows(), L1TkMuMantra.L1TkMuMantra(), CastorLedAnalysis.LedCastorHists(), HcalLedAnalysis.LedHBHEHists(), HcalLedAnalysis.LedHFHists(), HcalLedAnalysis.LedHOHists(), DQMGenericClient.limitedFit(), BTagCalibrationReader::BTagCalibrationReaderImpl.load(), LRHelpFunctions.LRHelpFunctions(), main(), TPedValues.makePlots(), EcalUncalibRecHitRecAnalFitAlgo< EBDataFrame >.makeRecHit(), GeometryComparisonPlotter.MakeTables(), multibsvspvplots(), MuScleFit.MuScleFit(), pat::ObjectResolutionCalc.ObjectResolutionCalc(), LA_Filler_Fitter.offset_slope(), JetResolution.parameter(), JetResolution.parameterEtaEval(), ParametrizedSubtractor.ParametrizedSubtractor(), MuonResidualsAngleFitter.plot(), MuonResidualsBfieldAngleFitter.plot(), MuonResiduals1DOFFitter.plot(), MuonResidualsPositionFitter.plot(), MuonResiduals6DOFrphiFitter.plot(), MuonResiduals5DOFFitter.plot(), MuonResiduals6DOFFitter.plot(), root.plot(), SymmetryFit.pol2_from_pol2(), TH2Analyzer.ProcessSlice(), PixelVertexProducerMedian.produce(), HIPixelMedianVtxProducer.produce(), CastorFastTowerProducer.produce(), PtHatRapReweightUserHook.PtHatRapReweightUserHook(), RapReweightUserHook.RapReweightUserHook(), LRHelpFunctions.readObsHistsAndFits(), LRHelpFunctions.recreateFitFct(), BackgroundHandler.rescale(), MuonTestSummary.ResidualCheck(), LA_Filler_Fitter.result(), DTLocalTriggerLutTest.runClientDiagnostic(), DTLocalTriggerSynchTest.runClientDiagnostic(), PVFitter.runFitter(), SamplingAlgorithm.SamplingAlgorithm(), MuMatchWindow.SetCentral(), MuMatchWindow.SetLower(), MuMatchWindow.SetUpper(), SiPixelGainCalibrationAnalysis.SiPixelGainCalibrationAnalysis(), smartGausProfile(), smearFunctionType7.smear(), LA_Filler_Fitter.summarize_ensembles(), root.tf1_t(), tmtt::Histos.trackerGeometryAnalysis(), CastorPedestalAnalysis.Trendings(), HcalPedestalAnalysis.Trendings(), UnbinnedFitDeDxEstimator.UnbinnedFitDeDxEstimator(), TEcnaHistos.ViewEBGrid(), TEcnaHistos.ViewSCGrid(), TEcnaHistos.ViewSMGrid(), TEcnaHistos.ViewTowerGrid(), sistrip::MeasureLA.write_report_text_ms(), PPSAlignmentHarvester.xAlignmentRelative(), L1TOccupancyClient.xySymmetry(), and PPSAlignmentHarvester.yAlignment().

◆ tf1

tools.tf1

Definition at line 31 of file tools.py.

◆ TF2

tools.TF2

Definition at line 24 of file tools.py.

Referenced by TtFullLepKinSolver.TtFullLepKinSolver().

FastTimerService_cff.range
range
Definition: FastTimerService_cff.py:34
tools.visualize_graph
def visualize_graph(graph, log_dir=None, start_tensorboard=False, tensorboard_args="", **kwargs)
Definition: tools.py:132
tools.compute_product_string
def compute_product_string(product_string)
Definition: tools.py:210
dqmMemoryStats.float
float
Definition: dqmMemoryStats.py:127
tools.getDatasetStr
def getDatasetStr(datasetpath)
Definition: tools.py:20
tools.create_single_iov_db
def create_single_iov_db(inputs, run_number, output_db)
Definition: tools.py:15
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
tools._test
def _test()
Definition: tools.py:193
tools.loadCmsProcess
def loadCmsProcess(psetPath)
Definition: tools.py:56
tools.make_unique_runranges
def make_unique_runranges(ali_producer)
Definition: tools.py:115
python.cmstools.all
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:26
tools.listFilesLocal
def listFilesLocal(paths, extension='.root')
Definition: tools.py:28
tools.prependPaths
def prependPaths(process, seqname)
Definition: tools.py:66
str
#define str(s)
Definition: TestProcessor.cc:51
tools.get_iovs
def get_iovs(db, tag)
Definition: tools.py:168
tools.write_constant_graph
def write_constant_graph(session, output_names, graph_path, **kwargs)
Definition: tools.py:93
ALCARECOTkAlBeamHalo_cff.filter
filter
Definition: ALCARECOTkAlBeamHalo_cff.py:27
tools.read_constant_graph
def read_constant_graph(graph_path, create_session=None, as_text=None)
Definition: tools.py:38
tools.run_checked
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:68
tools.stdinWait
def stdinWait(text, default, time, timeoutDisplay=None, **kwargs)
Definition: tools.py:70
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
Exception
tools.replaceTemplate
def replaceTemplate(template, **opts)
Definition: tools.py:10
createfilelist.int
int
Definition: createfilelist.py:10
tools.interrupt
def interrupt(signum, frame)
Definition: tools.py:93
tools.check_proxy
def check_proxy()
Definition: tools.py:221
tools.getTerminalSize
def getTerminalSize()
Definition: tools.py:96
tools.get_process_object
def get_process_object(cfg)
Definition: tools.py:88
tools.loadCmsProcessFile
def loadCmsProcessFile(psetName)
Definition: tools.py:52
readEcalDQMStatus.read
read
Definition: readEcalDQMStatus.py:38
tools.replace_factors
def replace_factors(product_string, name, value)
Definition: tools.py:194
format
tools.remove_existing_object
def remove_existing_object(path)
Definition: tools.py:233
tools.get_tags
def get_tags(global_tag, records)
Definition: tools.py:133
tools.haddLocal
def haddLocal(localdir, result_file, extension='root')
Definition: tools.py:41
python.rootplot.root2matplotlib.replace
def replace(string, replacements)
Definition: root2matplotlib.py:444