4 from AthenaPython
import PyAthena
7 import histgrinder.interfaces
8 from histgrinder.HistObject
import HistObject
9 from typing
import Union, Any, Pattern, Dict, Optional
10 from collections.abc
import Iterable, Iterator, Mapping, Collection, Generator
12 StatusCode = PyAthena.StatusCode
16 super(DQPostProcessingAlg, self).
__init__(name, **kw)
18 self.
FileKey =
'/CombinedMonitoring/run_%(run)s/'
30 from histgrinder.config
import read_configuration
31 from histgrinder.transform
import Transformer
33 from DataQualityUtils._resolve_data_path
import resolve_data_path
35 self.
hsvc = PyAthena.py_svc(
'THistSvc')
39 self.
msg.
error(
"Unable to resolve DataQualityUtils data path, not running new-style postprocessing")
40 return StatusCode.Failure
45 postprocfiles = glob.glob(os.path.join(dpath,
'postprocessing/*.yaml'))
48 self.
msg.
info(f
'The postprocessing config file list is {postprocfiles}')
49 for configfile
in postprocfiles:
50 config = read_configuration(configfile)
54 selectors.update(transform.inregexes)
60 in_configuration: Mapping[str, Any] = {
'source': self}
62 in_configuration[
'prefix'] = f
'{self.FileKey}'
64 self.
_im.setSelectors(selectors)
68 out_configuration: Mapping[str, Any] = {
'target': self}
70 out_configuration[
'prefix'] = f
'{self.FileKey}'
72 return StatusCode.Success
77 self.
msg.
debug(f
'now processing for {obj.name}')
83 self.
msg.
debug(f
'consider transformer {_.tc.description}')
85 t0 = time.perf_counter()
87 if any(_.match(obj.name)
for _
in _.inregexes):
89 v = _.consider(obj, defer=
True)
91 t = time.perf_counter()-t0
104 except Exception
as e:
105 self.
msg.
info(f
'Exception running transformer {_.tc.description}: {e}')
110 if ((self.
_ctr - 1) % self.
Interval) != 0:
return StatusCode.Success
114 except Exception
as e:
116 self.
msg.
info(f
"Caught exception: {e}")
117 self.
msg.
info(traceback.format_exc())
119 return StatusCode.Success
126 self.
msg.
info(f
'{k.tc.description}, {v}')
129 except Exception
as e:
131 self.
msg.
info(f
"Caught transformation exception: {e}")
132 self.
msg.warning(traceback.format_exc())
133 return StatusCode.Success
142 def configure(self, options: Mapping[str, Any]) ->
None:
144 Configure this module. Potential elements of "options":
145 source: should be a ROOT-openable filename or URL.
146 prefix: directory path to search under. Returned histogram names
147 will not include this.
149 if 'source' not in options:
150 raise ValueError(
"Must specify 'source' as an "
151 "option to AthInputModule")
152 self.
source = options[
'source']
158 """ Do more later """
164 if hsvc.existsHist(k):
165 hptr = ROOT.MakeNullPointer(ROOT.TH1)
166 if hsvc.getHist(k, hptr).isSuccess():
167 klass = getattr(ROOT, hptr.ClassName())
171 def iterate(self, dryrun) -> Generator[HistObject, None, None]:
172 """ Iterate over all histograms in THistSvc """
176 log.debug(f
'Would like to match {specprefix}')
181 histnames = hsvc.getHists()
182 currenthists =
set(
str(histnames[_])
for _
in range(len(histnames)))
185 if not k.startswith(specprefix):
187 shortk = k.replace(specprefix,
'', 1)
189 if not any(_.match(shortk)
for _
in self.
selectors):
193 log.debug(f
'We now have {len(self.cachednames)} entries in our cache, of {len(currenthists)} total plots')
194 log.debug(f
'There are {len(self.matchednames)} matches to be considered')
199 yield HistObject(k.replace(specprefix,
'', 1),
None)
201 log.debug(f
'THistSvc input trying to read {k}')
205 hptr = ROOT.MakeNullPointer(klass)
206 if hsvc.getHist(k, hptr).isSuccess():
207 log.debug(f
'THistSvc input read {k} as {type(hptr)}')
209 ROOT.SetOwnership(obj,
False)
211 if obj.GetEntries() == self.
entries[k]:
213 self.
entries[k] = obj.GetEntries()
214 yield HistObject(k.replace(specprefix,
'', 1), obj)
216 log.error(f
'Cannot read {k}')
218 log.debug(
'Done on input side')
221 return self.
iterate(dryrun=
False)
223 def warmup(self) -> Iterable[HistObject]:
224 return self.
iterate(dryrun=
True)
230 def configure(self, options: Mapping[str, Any]) ->
None:
232 Configure this module. Potential elements of "options":
233 target: should be a ROOT-openable filename or URL which
234 can be opened for writing.
235 prefix: directory path to place results under.
236 overwrite: boolean to indicate whether results should overwrite
237 existing histograms in the file.
238 delay: only write histograms in finalize() (not during publish()).
240 if 'target' not in options:
241 raise ValueError(
"Must specify 'target' as an option "
243 self.
target = options[
'target']
247 self.
queue: Optional[Dict[str, HistObject]] = {}
249 'get': self.
target.hsvc.getHist,
250 'reg': self.
target.hsvc._cpp_regHist },
251 'graph': {
'exists': self.
target.hsvc.existsGraph,
252 'get': self.
target.hsvc.getGraph,
253 'reg': self.
target.hsvc._cpp_regGraph },
254 'eff': {
'exists': self.
target.hsvc.existsEfficiency,
255 'get': self.
target.hsvc.getEfficiency,
256 'reg': self.
target.hsvc._cpp_regEfficiency },
259 def publish(self, obj: Union[HistObject, Iterable[HistObject]]) ->
None:
260 """ Accepts a HistObject containing a ROOT object to write to file """
261 if isinstance(obj, HistObject):
263 d_obj = { _.name: _
for _
in obj }
275 """ write obj to THistSvc """
283 fulltargetname = os.path.join(self.
prefix, o.name) % {
'run': self.
target._run }
284 log.debug(f
"Attempt to publish {fulltargetname} of type {type(o.hist)}")
287 if isinstance(o.hist, ROOT.TH1):
289 parenttype = ROOT.TH1
290 elif isinstance(o.hist, ROOT.TGraph):
292 parenttype = ROOT.TGraph
293 elif isinstance(o.hist, ROOT.TEfficiency):
295 parenttype = ROOT.TEfficiency
297 log.warning(f
'Do not know how to handle object {fulltargetname} of type {type(o.hist)}; skipping')
299 o.hist.SetName(os.path.basename(fulltargetname))
300 if funcs[
'exists'](fulltargetname):
302 hptr = ROOT.MakeNullPointer(parenttype)
303 if funcs[
'get'](fulltargetname, hptr).isSuccess():
305 ROOT.SetOwnership(hptr,
True)
306 if not funcs[
'reg'](fulltargetname, o.hist).isSuccess():
307 log.error(f
"Unable to register {fulltargetname}")
309 ROOT.SetOwnership(o.hist,
False)
310 log.debug(
"Published")
314 """ Outputs outstanding HistObjects """