5.14. pypfilt.context¶
-
class
pypfilt.context.
Context
(params)¶ A simulation context, which encapsulates the simulation parameters, simulation components, data tables, event handlers, etc.
Parameters: params – The simulation parameters. Examples: >>> import pypfilt >>> import pypfilt.examples.predation >>> from pypfilt.context import Context >>> pypfilt.examples.predation.write_example_files() >>> config_file = 'predation.toml' >>> for forecast in pypfilt.forecasts_iter(config_file): ... ctx = Context(forecast.params) ... # Inspect parameters. ... print(ctx.params['prng_seed']) ... # Inspect components. ... print(ctx.component['time'].__class__) ... # Inspect data tables. ... print(ctx.data['obs']['x'].shape) ... # Inspect event handlers. ... print(ctx.hook) 42 <class 'pypfilt.time.Scalar'> (15,) {'log_llhd': []}
-
install_hook
(hook_name, hook_fn)¶ Register a function that should be called in response to an event.
Parameters: - hook_name – The event name.
- hook_fn – The event-handler function.
-
call_hooks
(hook_name, *args, **kwargs)¶ Call all event-handler functions associated with an event name.
Parameters: - hook_name – The event name.
- *args – Positional arguments to pass to the event handlers.
- **kwargs – Keyword arguments to pass to the event handlers.
-
-
class
pypfilt.context.
Params
(params)¶ A non-mutable dictionary wrapper that ensures the simulation parameters remain unchanged during each simulation.
-
get
(key, default=None)¶ Return the value associated with key, if present; otherwise return
default
.
-
get_chained
(keys, default=None)¶ Return the value associated with a sequence of keys, if all keys are present, otherwise return
default
.Examples: >>> from pypfilt.context import Params >>> x = {'a': 1, 'b': {'c': 2}} >>> params = Params(x) >>> params.get_chained(['b', 'c']) 2 >>> params.get_chained(['b', 'd']) is None True
-
-
class
pypfilt.context.
Scaffold
(**entries)¶ Convenience class for defining minimal context objects.
This is useful when, e.g., writing test cases for functions that require a context object.
Examples: >>> import numpy as np >>> import pypfilt.resample >>> from pypfilt.context import Scaffold >>> params = {'resample': {'method': 'basic', 'regularisation': False}} >>> component = {'random': {'resample': np.random.default_rng()}} >>> ctx = Scaffold(params=params, component=component) >>> weights = np.array([0.50, 0.25, 0.1, 0.1, 0.02, 0.02, 0.01]) >>> ixs = np.zeros(weights.shape) >>> attempts = 10 >>> for i in range(attempts): ... x = np.array([weights, ixs]).T ... pypfilt.resample.resample(ctx, x) ... if any(x[:, 1] == 0): ... # The first particle (weight 0.5) was selected at least once. ... break