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

Classes

class  HandleMaker
 gallery More...
 
class  EventIterator
 
class  ConfigurationHelper
 
class  ConfigurationString
 
class  ConfigurationClass
 
class  ServiceRegistryClass
 
class  startMessageFacility
 
class  TemporaryFile
 

Functions

def makeFileList
 
def makeEvent
 
def forEach
 
def eventLoop
 
def findFHiCL
 Infrastructure. More...
 
def getTableIfPresent
 
def loadConfiguration
 

Variables

string __doc__
 
list __all__
 
 SourceCode = cppUtils.SourceCode
 Pass-through. More...
 
 readHeader = cppUtils.readHeader
 
tuple make_getValidHandle = HandleMaker()
 

Function Documentation

def galleryUtils.eventLoop (   inputFiles,
  process,
  options = {} 
)
Applies the `process` function to each and every event from the specified
input files, in sequence.

The `inputFiles` list may be a single file, or a list (or any iterable object)
of files, or a `std::vector<std::string>` object.

The `process` callable is executed with two arguments: the number of argument
in the loop, and the event itself. No information on which file the event is
taken from is provided. If a call returns exactly `False`, it is considered
to have failed and an error counter is incremented. Exceptions raised in
`process` are not handled.

The error counter is returned at the end of the execution.

Options:
- 'nEvents': number of events to be processed (does not include skipped ones)
- 'nSkip': number of events from the beginning of the sample to be skipped

Definition at line 233 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

234  ):
235  """
236  Applies the `process` function to each and every event from the specified
237  input files, in sequence.
238 
239  The `inputFiles` list may be a single file, or a list (or any iterable object)
240  of files, or a `std::vector<std::string>` object.
241 
242  The `process` callable is executed with two arguments: the number of argument
243  in the loop, and the event itself. No information on which file the event is
244  taken from is provided. If a call returns exactly `False`, it is considered
245  to have failed and an error counter is incremented. Exceptions raised in
246  `process` are not handled.
247 
248  The error counter is returned at the end of the execution.
249 
250  Options:
251  - 'nEvents': number of events to be processed (does not include skipped ones)
252  - 'nSkip': number of events from the beginning of the sample to be skipped
253  """
254 
255  # option reading
256  nSkip = options.get('nSkip', 0)
257  nEvents = options.get('nEvents', None)
258 
259  # make sure the input file list is in the right format
260  if not isinstance(inputFiles, ROOT.vector(ROOT.string)):
261  if isinstance(inputFiles, str): inputFiles = [ inputFiles, ]
262  inputFiles = makeFileList(*inputFiles)
263  # if
264 
265  event = ROOT.gallery.Event(inputFiles)
266 
267  # ROOT.gStyle.SetOptStat(0)
268 
269  iEvent = 0
270  nProcessedEvents = 0
271  nErrors = 0
272 
273  iFile = None
274  for iEvent, event in enumerate(forEach(event)):
275 
276  if iFile != event.fileEntry():
277  iFile = event.fileEntry()
278  print("Opening: '%s'" % inputFiles[iFile])
279  # if new file
280 
281  # event flow control
282  if iEvent < nSkip: continue
283  if (nEvents is not None) and (nProcessedEvents >= nEvents): break
284  nProcessedEvents += 1
285 
286  ###
287  ###
288  ###
289  res = process(event, iEvent)
290  if isinstance(res, bool) and not res: nErrors += 1
291 
292  ###
293  ### all done
294  ###
295 
296  # for
297  if nErrors > 0:
298  print("Encountered %d/%d errors." % (nErrors, nProcessedEvents),file=sys.stderr)
299  return nErrors
300 # eventLoop()
301 
302 
303 
304 # this does not really work...
305 # ROOT.gallery.Event.__iter__ = lambda self: EventIterator(self)
306 
do one_file $F done echo for F in find $TOP name CMakeLists txt print
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:69
def galleryUtils.findFHiCL (   configRelPath,
  extraDirs = [] 
)

Infrastructure.

Definition at line 311 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

312 def findFHiCL(configRelPath, extraDirs = []):
313 
314  if os.path.isfile(configRelPath):
315  return os.path.join(os.getcwd(), str(configRelPath))
316  for path in extraDirs + os.environ.get('FHICL_FILE_PATH', "").split(':'):
317  candidate = os.path.join(path, str(configRelPath))
318  if os.path.isfile(candidate): return candidate
319  else: return None
320 
321 # findFHiCL()
322 
def galleryUtils.forEach (   event)
Simplifies sequential event looping.

This function handles the state of `event`, moving the current event around.
Therefore, it has side effects.
The function returns `event` itself, after it has set to the next available
event.

This function is actually a generator.

Example of loop:
    
    for iEvent, event in enumerate(forEach(event)):
      ...

Definition at line 173 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

174 def forEach(event):
175  """
176  Simplifies sequential event looping.
177 
178  This function handles the state of `event`, moving the current event around.
179  Therefore, it has side effects.
180  The function returns `event` itself, after it has set to the next available
181  event.
182 
183  This function is actually a generator.
184 
185  Example of loop:
186 
187  for iEvent, event in enumerate(forEach(event)):
188  ...
189 
190 
191  """
192  while (not event.atEnd()):
193  yield event
194  event.next()
195  # while
196 # forEach()
197 
def galleryUtils.getTableIfPresent (   pset)

Definition at line 324 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

325  pset: "fhicl.ParameterSet object containing the desired configuration table",
326  key: "name of the table to be extracted",
327  defValue: "value returned if the key is not present (None by default)" = None,
328  type_: "type to look for (instead of ROOT.fhicl.ParameterSet)" = None,
329  ) -> "ParameterSet with `key` in `pset`, or `defValue` if not present":
330 
331  try: return pset.get(type_ if type_ else ROOT.fhicl.ParameterSet)(key)
332  except Exception: return defValue
333 
334 # getTableIfPresent()
335 
def galleryUtils.loadConfiguration (   configSpec)

Definition at line 411 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

412 def loadConfiguration(configSpec):
413  # this utility actually relies on generic utilities that while not LArSoft
414  # specific, are nevertheless distributed with LArSoft (`larcorealg`).
415  SourceCode.loadHeaderFromUPS("larcorealg/Geometry/StandaloneBasicSetup.h")
416 
417  if isinstance(configSpec, ConfigurationString):
418  import tempfile
419  configFile = tempfile.NamedTemporaryFile("w+")
420  configFile.write(str(configSpec))
421  configFile.flush()
422  configPath = configFile.name
423  else:
424  configFile = None
425  configPath = configSpec
426  # if
427 
428  fullPath = findFHiCL(configPath)
429  if not fullPath:
430  raise RuntimeError("Couldn't find configuration file '%s'" % configPath)
431  return ROOT.lar.standalone.ParseConfiguration(fullPath)
432 # loadConfiguration()
433 
def galleryUtils.makeEvent (   files)

Definition at line 166 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

167  files: "files or file lists, as supported by `ROOTutils.makeFileList()`",
168  **kwargs: "additional arguments to `gallery::Event` constructor"
169  ) -> "a gallery.Event object reading the specified input files":
170  return ROOT.gallery.Event(makeFileList(files), **kwargs)
171 # makeEvent()
172 
def galleryUtils.makeFileList ( )
Creates a file list suitable for `gallery::Event`.

Definition at line 147 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

148  *filePaths: "a list of input files"
149  ) -> "a list of files suitable to construct a `gallery.Event object":
150  """Creates a file list suitable for `gallery::Event`.
151 
152  If a file ends with `.root`, it is added directly to the list.
153  Otherwise, it is interpreted as a file list and treated as such
154  (see `ROOTutils.expandFileList()`).
155  File list recursion is disabled.
156  """
157  files = ROOT.vector(ROOT.string)()
158  for path in filePaths:
159  entries = [ path ] if path.endswith('.root') else expandFileList(path)
160  for entry in entries: files.push_back(entry)
161  # for
162  return files
163 # makeFileList()
164 
std::vector< std::string > expandFileList(std::string const &listPath)
Expands the content of a file list into a vector of file paths (recursive).

Variable Documentation

list galleryUtils.__all__
Initial value:
1 = [
2  'readHeader', # imported from `cppUtils`
3  'SourceCode', # imported from `cppUtils`
4  'make_getValidHandle',
5  'makeFileList',
6  'forEach',
7  'eventLoop',
8  'findFHiCL',
9  'loadConfiguration',
10  'ConfigurationClass',
11  'startMessageFacility',
12  'ServiceRegistryClass',
13  'ConfigurationHelper',
14  ]

Definition at line 31 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

string galleryUtils.__doc__
Initial value:
1 = """
2 Collection of utilities to interface gallery with python.
3 
4 This module requires ROOT.
5 
6 An example of a interactive session counting the number of muons
7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8 import galleryUtils
9 import ROOT
10 sampleEvents = galleryUtils.makeEvent("data.root")
11 LArG4tag = ROOT.art.InputTag("largeant")
12 
13 getParticleHandle \\
14  = galleryUtils.make_getValidHandle("std::vector<simb::MCParticle>", sampleEvents)
15 for event in galleryUtils.forEach(sampleEvents):
16  particles = getParticleHandle(LArG4tag).product()
17 
18  nMuons = sum(1 for part in particles if abs(part.PdgCode()) == 13)
19  print("%s: %d muons" % (event.eventAuxiliary().id(), nMuons))
20 
21 # for all events
22 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
23 
24 
25 """

Definition at line 5 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

tuple galleryUtils.make_getValidHandle = HandleMaker()

Definition at line 143 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

galleryUtils.readHeader = cppUtils.readHeader

Definition at line 56 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.

galleryUtils.SourceCode = cppUtils.SourceCode

Pass-through.

Definition at line 55 of file icarusalg/icarusalg/gallery/helpers/python/galleryUtils.py.