The ReplayBG Object¶
The ReplayBG object is the core entry point of the framework. You create it
once, then use its two methods — twin() and replay() — for the whole workflow.
from py_replay_bg import ReplayBG
ReplayBG(ts: int = 1, seed: int = 1, plot_mode: bool = True, verbose: bool = True)
Constructor parameters¶
ts(int, default1) — the integration time step in minutes. Models integrate at this resolution.seed(int, default1) — the random seed used to seed the CGM sensor error realization duringreplay()(except withcontinue_sensor=True, which keeps the realization of the sensor carried in from the previous run). Twinning does not use it: it is deterministic on its own (startiis sampled with seedi).plot_mode(bool, defaultTrue) — stored on the environment but currently not used:twin()andreplay()never plot; plots are produced explicitly with the plotting utilities.verbose(bool, defaultTrue) — verbosity of ReplayBG. Twinning shows progress bars for the starts and the polish, and prints a run header (starts, mode, polish setting, parameters, correlations), a convergence summary (elapsed time, failed starts, the min/median/max objective of the raw starts, the best/worst objective after polishing, and the final objective with the raw start it was polished from) and the best-fit parameters, flagging those at a bound.
These are stored on an Environment object exposed as
rbg.environment, which is passed to the data classes:
This is different from the old py_replay_bg API
There is no blueprint, save_folder, yts or exercise argument on
the constructor anymore. You choose a blueprint by instantiating the matching
data + model classes, the data sampling time is
fixed at 5 minutes by the data classes, and results are saved per-call via the
path / save_name arguments of twin() / replay().
twin()¶
Runs the twinning procedure (MAP estimation) to identify the model parameters.
rbg.twin(
rbg_data,
model: object = None,
unknown_parameters_prior: dict = None,
correlations: dict = None,
n_starts: int = 64,
n_polish: int = 8,
parallelize: bool = False,
n_jobs: int | None = None,
log_history: bool = False,
path: str | None = None,
save_name: str | None = None,
) -> dict
| Parameter | Description |
|---|---|
rbg_data |
A data object (e.g. MultiMealT1DData) holding the inputs, timestamps and observed glucose. |
model |
A model instance implementing the model interface contract (reset, step, output). |
unknown_parameters_prior |
Dict defining which parameters to estimate and their priors/bounds. See Twinning. |
correlations |
Optional pairwise prior correlations {(name_a, name_b): rho} (Gaussian copula). None ⇒ independent. |
n_starts |
Number of multi-start optimisations (default 64). |
n_polish |
Number of best distinct starts refined with a tight-tolerance polish; the best polished result is kept (default 8). Parallelised over n_jobs when parallelize=True. |
parallelize |
Whether to run the multi-start optimisation and the polish in parallel (multiprocessing; default False). Requires the if __name__ == '__main__': guard. |
n_jobs |
Number of parallel jobs; None or -1 ⇒ all CPUs (default None). |
log_history |
Whether to record the optimisation history (for plot_twinning_history). |
path |
Directory to pickle the results into; None ⇒ not saved. See Saving Results. |
save_name |
Base file name: the pickle is written to <path>/twin_<save_name>.pkl (twin_YYYY_mm_dd.pkl when None). |
Returns a dict with keys:
theta— the estimated parameters as a{name: value}mapping (this is the digital twin),correlations— the prior correlations used (orNone),history— whenlog_history=True, a dict of per-evaluation lists with keystheta,log_prior,log_likelihoodandlog_posterior(multi-start and polish evaluations), elseNone.
replay()¶
Forward-simulates the fitted model, optionally with closed-loop control policies and a CGM sensor.
rbg.replay(
rbg_data,
model: object = None,
callbacks: list | None = None,
sensor: object = None,
continue_sensor: bool = False,
path: str | None = None,
save_name: str | None = None,
) -> dict
| Parameter | Description |
|---|---|
rbg_data |
The data object holding the inputs to replay. |
model |
The model instance, rebuilt with the estimated theta0. |
callbacks |
List of ReplayCallback control policies invoked before each step. |
sensor |
Optional Sensor producing a noisy, sub-sampled measurement exposed to callbacks as ctx.measurement. |
continue_sensor |
If True, keep the sensor carried in from a previous replay (same error realization, noise memory and age) instead of reseeding and reconnecting it. See Sharing a sensor across replay runs. |
path |
Directory to pickle the results into; None ⇒ not saved. |
save_name |
Base file name: the pickle is written to <path>/replay_<save_name>.pkl (replay_YYYY_mm_dd.pkl when None). |
Returns a dict with keys:
output— predicted interstitial glucose at integration resolution (np.ndarray, lengthtsteps),input— the applied inputs, shape(tsteps, n_channels),data_to_input— the channel-index → name mapping,actions— a flat list of action records logged by the callbacks,measurementandmeasurement_time— only when a sensor is supplied (the sensor samples and their integration-step indices).
See the Replay guide for the full closed-loop story.