xsimlab.RuntimeHook¶
-
class
xsimlab.
RuntimeHook
(*args)¶ Base class for advanced, stateful simulation runtime hooks.
Given some runtime hook functions, e.g.,
>>> @runtime_hook('initialize', 'model', 'pre') ... def start(model, context, state): ... pass
>>> @runtime_hook('run_step', 'model', 'post') ... def after_step(model, context, state): ... pass
You may create a
RuntimeHook
object with any number of them>>> rh = RuntimeHook(start, after_step)
An advantage over directly using hook functions is that you can use an instance of
RuntimeHook
either as a context manager over a model run call>>> with rh: ... in_dataset.xsimlab.run(model=model)
Or enable it globally with the
register
method>>> rh.register() >>> rh.unregister()
Another advantage is that you can subclass
RuntimeHook
and add decorated methods that may share some state>>> class PrintStepTime(RuntimeHook): ... ... @runtime_hook('run_step', 'model', 'pre') ... def start_step(self, model, context, state): ... self._start_time = time.time() ... print(f"Starting step {context['step']}") ... ... @runtime_hook('run_step', 'model', 'post') ... def finish_step(self, model, context, state): ... step_time = time.time() - self._start_time ... print(f"Step {context['step']} took {step_time} seconds")
>>> with PrintStepTime(): ... in_dataset.xsimlab.run(model=model)
-
__init__
(*args)¶ - Parameters
*args (callable) – An abitrary number of runtime_hook decorated functions.
See also
Methods
__init__
(*args)- param *args
An abitrary number of runtime_hook decorated functions.
register
()Globally register this RuntimeHook instance.
unregister
()Globally unresgister this RuntimeHook instance.
Attributes
active
-