Skip to content

Migration

This guide is for users of py_replay_bg 1.x moving to ReplayBG 2.x. It covers what changed, how each 1.x call maps onto the new API, and how to convert the twins you already saved so you do not have to twin again.

In a hurry?

The physiological model did not change. A twin saved by 1.x converts to 2.x with one command and replays to the same glucose trace:

python -m py_replay_bg.utils.convert_legacy_twin results/map/map_day_1.pkl -o results_v2

What stays the same

  • The package name. It is still py-replay-bg on PyPI and from py_replay_bg import ReplayBG in code.
  • The physiological models. The single-meal and multi-meal models have the same equations, the same integration scheme (Backward Euler, 1-minute step), the same parameter names and units, and the same default values for the parameters that are not estimated.
  • The data format. The DataFrame columns (t, glucose, cho, bolus, basal, bolus_label, cho_label) and their units are unchanged. See Choosing Data for Twinning.
  • The CGM error model. Vettoretti19CGM is still the default sensor model.

What changed

Topic 1.x 2.x
Python ≥ 3.11 ≥ 3.12
Install pip install py-replay-bg pip install --pre py-replay-bg while 2.x is in beta
Blueprint ReplayBG(blueprint='multi-meal', ...) You instantiate a data class and a model class yourself (Choosing a Blueprint)
Twinning method twinning_method='map' or 'mcmc' MAP only: multi-start Powell plus a polish (Twinning Procedure)
Priors Hard-coded in the package Declared by you in unknown_parameters_prior, with optional correlations
Which parameters are estimated Decided by the package from the data Exactly the keys of unknown_parameters_prior
A twin is A file found by save_name in results/map/ or results/mcmc/ The theta dict returned by twin() (optionally pickled)
Results location <save_folder>/results/{map,mcmc,workspaces}/ Any path you pass; twin_<save_name>.pkl and replay_<save_name>.pkl (Saving Results)
Replay inputs bolus_source, basal_source, cho_source, *_handler arguments Edit the DataFrame for offline what-ifs, or pass callbacks for closed-loop policies (Replay)
Replay output A dict of signals with median and confidence intervals over n_replay runs One simulation: a dict with output, input, actions, ...
Analysis and plots Analyzer, Visualizer classes Functions in py_replay_bg.utils (Analyzing Results, Plotting Utilities)

Removed in 2.x, with no direct replacement: MCMC twinning (and with it posterior samples and confidence intervals on the replayed trace), the exercise flag, and the yts constructor argument (the data classes assume one row every 5 minutes).

Imports

1.x 2.x
from py_replay_bg.py_replay_bg import ReplayBG from py_replay_bg import ReplayBG
from py_replay_bg.sensors.Vettoretti19CGM import Vettoretti19CGM from py_replay_bg.sensors import Vettoretti19CGM
from py_replay_bg.visualizer import Visualizer from py_replay_bg.utils.plot_replay import plot_replay, from py_replay_bg.utils.plot_twinning import plot_twinning
from py_replay_bg.analyzer import Analyzer from py_replay_bg.utils.agata_analysis import analyze_replay, analyze_twin
from py_replay_bg.dss.default_dss_handlers import ... from py_replay_bg.callbacks import CorrectionBolus, HypoTreatment

The ReplayBG object

# 1.x
rbg = ReplayBG(blueprint='multi-meal', save_folder=save_folder,
               yts=5, exercise=False, seed=1, plot_mode=False, verbose=True)

# 2.x
rbg = ReplayBG(ts=1, seed=1, plot_mode=False, verbose=True)

blueprint and save_folder are gone: the blueprint is the pair of classes you instantiate, and the save location is passed to each twin() / replay() call.

Preparing the data and choosing the blueprint

In 1.x you passed the raw DataFrame and the body weight to every call. In 2.x you prepare the data once, and build the matching model:

from py_replay_bg.data.multi_meal_t1d_data import MultiMealT1DData
from py_replay_bg.model.multi_meal_t1d import MultiMealT1DModel

rbg_data = MultiMealT1DData(data=df, body_weight=bw, environment=rbg.environment)
model = MultiMealT1DModel(u2ss=rbg_data.u2ss, tsteps=rbg_data.tsteps,
                          t_start=rbg_data.t_start)
from py_replay_bg.data.single_meal_t1d_data import SingleMealT1DData
from py_replay_bg.model.single_meal_t1d import SingleMealT1DModel

rbg_data = SingleMealT1DData(data=df, body_weight=bw, environment=rbg.environment)
model = SingleMealT1DModel(u2ss=rbg_data.u2ss, tsteps=rbg_data.tsteps)

Three things to watch:

  • t must be a datetime column. 1.x examples already converted it with pd.to_datetime; 2.x requires it.
  • body_weight defaults to 100 kg. The 1.x bw argument was mandatory; pass it as body_weight= or your inputs are scaled for a 100 kg person.
  • u2ss. 1.x took an optional u2ss in twin() and saved it with the twin. In 2.x it is rbg_data.u2ss (the mean basal rate, in mU/kg/min, the same default 1.x used) and you pass it to the model. To use your own value, pass it to the model constructor instead of rbg_data.u2ss.

The 1.x extended=True twinning option corresponds to the Multi Meal Extended blueprint, which is now a blueprint of its own with second-day meal labels (B2, L2, S2).

Twinning

# 1.x
rbg.twin(data=data, bw=bw, save_name='day_1',
         twinning_method='map', parallelize=True, n_processes=None)

# 2.x
result = rbg.twin(rbg_data=rbg_data, model=model,
                  unknown_parameters_prior=unknown_parameters_prior,
                  correlations=None,
                  n_starts=64, n_polish=8,
                  parallelize=True, n_jobs=-1,
                  path='results', save_name='day_1')
theta = result['theta']
1.x argument 2.x
data, bw rbg_data (built with body_weight=bw)
save_name path + save_name; nothing is saved unless path is given
twinning_method Removed (MAP only)
extended Use the Multi Meal Extended blueprint
find_start_guess_first Removed; the multi-start optimisation replaces it
n_steps, n_walkers, save_chains Removed (MCMC options)
u2ss The u2ss argument of the model constructor
x0, previous_data_name The x0 and theta_prev arguments of the model constructor (intervals)
parallelize, n_processes parallelize, n_jobs

The main new requirement is unknown_parameters_prior: 1.x chose the parameters to estimate from the meals found in the data and used built-in priors; 2.x estimates exactly what you list, with the priors and bounds you give. A complete, ready-to-copy dictionary for the multi-meal model is in Getting Started, and the rules are in Twinning Procedure. Two differences from 1.x are worth knowing:

  • f (the fraction of absorbed carbohydrates reaching plasma) was fixed at 0.9 in 1.x and can now be estimated.
  • 1.x estimated Gb, SG, p2, ka2, kd, kempt, the insulin sensitivities and, for each meal type present in the data, its kabs and beta. Listing the same names reproduces that choice.

Replay

# 1.x: the twin is looked up on disk by save_name
replay_results = rbg.replay(data=data, bw=bw, save_name='day_1',
                            twinning_method='map',
                            save_workspace=True, save_suffix='_replay_map')

# 2.x: you build the model with the twin, then replay
from py_replay_bg.utils.numba_dicts import to_typed_f64_dict

model = MultiMealT1DModel(u2ss=rbg_data.u2ss, tsteps=rbg_data.tsteps,
                          theta0=to_typed_f64_dict(theta), t_start=rbg_data.t_start)
out = rbg.replay(rbg_data=rbg_data, model=model,
                 path='results', save_name='day_1')
1.x argument 2.x
data, bw rbg_data
save_name, twinning_method Build the model with theta0=to_typed_f64_dict(theta)
x0, previous_data_name x0 and theta_prev of the model constructor (intervals)
bolus_source, basal_source, cho_source Edit the DataFrame (offline what-if) or use a callback (closed loop)
meal_generator_handler, bolus_calculator_handler, basal_handler (+ *_params) A custom ReplayCallback
enable_correction_boluses, correction_boluses_handler callbacks=[CorrectionBolus(...)], or a custom callback
enable_hypotreatments, hypotreatments_handler callbacks=[HypoTreatment(...)], or a custom callback
enable_forcing_ip, forcing_ip_handler The forcing_ip input channel: write the signal into that column of rbg_data.u, or call ctx.set_input('forcing_ip', ...) in a callback
enable_forcing_ra, forcing_ra_handler, custom_ra The forcing_ra input channel, in the same way
snack_absorption, snack_absorption_delay, hypotreatment_absorption Set theta['kabs_S'], theta['beta_S'], theta['kabs_H'] before building the model
sensors, sensor_cgm sensor=Vettoretti19CGM() (The CGM Error Model)
n_replay Removed: one call is one simulation. Loop, changing rbg.environment.seed, for several sensor realizations
save_workspace, save_suffix path + save_name

The replay output

The returned dict changed shape:

1.x 2.x
replay_results['glucose']['median'] Plasma glucose: read model.G after the replay. out['output'] is interstitial glucose
replay_results['cgm']['median'] out['measurement'] (with a sensor), sampled at out['measurement_time']
insulin_bolus, insulin_basal, cho, hypotreatments, correction_bolus out['input'] (the inputs actually applied, one column per channel of out['data_to_input'], in model units) and out['actions'] (what each callback did)
ci5th, ci25th, ci75th, ci95th, realizations Removed

output is interstitial glucose, not plasma glucose

In 1.x glucose was the simulated plasma glucose and cgm the sensor reading of the interstitial compartment. In 2.x the model output is the interstitial glucose, the quantity a CGM measures, so out['output'] lags the 1.x glucose trace by a few minutes and can differ from it by several mg/dL around meals. The plasma trace is still simulated: it is model.G once replay() returns.

Multi-day intervals

1.x chained consecutive portions of data with x0= and previous_data_name=, reloading the previous twin from disk. 2.x passes the carry-over explicitly, from the previous segment's model:

model = MultiMealT1DModel(u2ss=rbg_data.u2ss, tsteps=rbg_data.tsteps,
                          theta0=to_typed_f64_dict(theta), t_start=rbg_data.t_start,
                          x0=prev_model.get_final_x0(),
                          theta_prev=prev_model.get_theta())

get_final_x0() is the state at the end of the previous segment (the 1.x x0 array) and get_theta() the previous segment's parameters (what 1.x read from the previous_data_name file). See Twinning multi-day intervals and Replaying multi-day intervals.

Analysis and plotting

# 1.x
Visualizer.plot_replay_results(replay_results, data=data)
analysis = Analyzer.analyze_replay_results(replay_results, data=data)
tir = analysis['median']['glucose']['time_in_ranges']['time_in_target']

# 2.x
from py_replay_bg.utils.plot_replay import plot_replay
from py_replay_bg.utils.agata_analysis import analyze_replay

fig = plot_replay(out, thresholds=[70, 180])
analysis = analyze_replay(out, ts=5)
tir = analysis['output']['time_in_ranges']['time_in_target']

The metrics are still computed by AGATA. Without a sensor they are computed on out['output'] (interstitial glucose); with one, the sensor trace is analysed too, under analysis['measurement']. See Analyzing Results.

Converting your saved twins

Twinning is the expensive step, so 2.x ships a converter for the twins 1.x saved in results/map/map_<save_name>.pkl and results/mcmc/mcmc_<save_name>.pkl.

Because the model is unchanged, the conversion is a name-by-name copy of the estimated parameters into a 2.x theta. Replaying a converted MAP twin on the same data reproduces the 1.x plasma glucose trace to numerical precision (compare it with model.G, not with out['output']).

From the command line

python -m py_replay_bg.utils.convert_legacy_twin results/map/map_day_1.pkl -o results_v2

This writes results_v2/twin_day_1.pkl. The map_ / mcmc_ prefix of the 1.x file name is dropped; use --name to choose another save name. Several files can be converted at once:

python -m py_replay_bg.utils.convert_legacy_twin results/map/*.pkl -o results_v2

Existing files are never replaced unless you pass --overwrite, and a batch in which two inputs would get the same name (for example map_day_1.pkl and mcmc_day_1.pkl) is refused: convert MAP and MCMC twins into separate directories.

To make the converted file a complete 2.x twin, also give the recording the twin was fitted on and the patient's body weight. The prepared data object is then stored in the file, as ReplayBG.twin() does:

python -m py_replay_bg.utils.convert_legacy_twin results/map/map_day_1.pkl -o results_v2 --data data_day_1.csv --bw 100
Option Meaning
-o, --out DIR Directory where twin_<name>.pkl is written (required)
--name SAVE_NAME Save name of the converted twin (single input file only)
--data FILE The recording the twin was fitted on, .csv or .parquet (single input file only)
--bw KG Body weight, the 1.x bw; required with --data
--blueprint single-meal or multi-meal; inferred from the parameter names by default
--mcmc-draw DRAW How to reduce an MCMC twin to one parameter set (see below)
--overwrite Replace twin_<name>.pkl files that already exist in the output directory

From Python

import pandas as pd
from py_replay_bg.utils.convert_legacy_twin import convert_legacy_twin

data = pd.read_csv('data_day_1.csv')

twin = convert_legacy_twin('results/map/map_day_1.pkl',
                           path='results_v2', save_name='day_1',
                           data=data, body_weight=100.)

path, save_name, data and body_weight are all optional: with only the file name, the function returns the converted twin without writing anything. Unlike the command line, the function replaces an existing <path>/twin_<save_name>.pkl, as ReplayBG.twin() does.

Using a converted twin

A converted file is read like any other 2.x twin:

from py_replay_bg import ReplayBG
from py_replay_bg.model.multi_meal_t1d import MultiMealT1DModel
from py_replay_bg.utils.load_results import load_results
from py_replay_bg.utils.numba_dicts import to_typed_f64_dict

twin = load_results('results_v2', 'day_1', prefix='twin')
theta, rbg_data = twin['theta'], twin['rbg_data']

rbg = ReplayBG()
model = MultiMealT1DModel(u2ss=rbg_data.u2ss, tsteps=rbg_data.tsteps,
                          theta0=to_typed_f64_dict(theta), t_start=rbg_data.t_start)
out = rbg.replay(rbg_data=rbg_data, model=model)

For a single-meal twin use SingleMealT1DModel (which takes no t_start).

If you converted without --data, the file has no rbg_data: build it yourself with the matching data class, and pass the saved basal steady state to the model:

rbg_data = MultiMealT1DData(data=df, body_weight=bw, environment=rbg.environment)
model = MultiMealT1DModel(u2ss=twin['u2ss'], tsteps=rbg_data.tsteps,
                          theta0=to_typed_f64_dict(twin['theta']),
                          t_start=rbg_data.t_start)

What the converted file contains

Key Content
theta The estimated parameters, as plain {name: float}
correlations, history None (1.x had neither)
rbg_data The prepared data object, only when the recording was given
u2ss The basal steady state saved by 1.x
legacy Provenance: the source file, the twinning method (map / mcmc), the blueprint and the MCMC draw used

Details of the conversion:

  • Parameters that 1.x did not estimate are absent from theta, so the 2.x model uses its defaults for them, which are the 1.x population values.
  • Meal delays (beta, beta_B, ...) are truncated to integer minutes. Both 1.x and 2.x truncate them when simulating, so this only makes the stored value the one actually used.
  • u2ss. When the recording is given, rbg_data.u2ss is set to the value saved in the 1.x twin rather than recomputed from the data, because that is the value the twin was identified with. A warning is issued if the two differ; that is expected if you passed a custom u2ss to the 1.x twin(), and otherwise a hint that the data or body weight are not the ones used for twinning.
  • Extended twins. A 1.x twin obtained with extended=True describes the first day only (1.x discarded the second-day parameters before saving), so it converts to a regular multi-meal twin.

MCMC twins

A 1.x MCMC twin holds a posterior sample of each parameter; a 2.x twin is a single parameter set. mcmc_draw (--mcmc-draw) picks it:

Value Parameter set
'representative' (default) The single realization 1.x selected as samples_1
an integer i The i-th joint draw of the largest sample set (samples_1000)
'median', 'mean' Per-parameter median or mean over the largest sample set. Not a joint draw of the posterior, so parameter correlations are lost

To keep the spread of the posterior, convert several draws and replay each:

twins = [convert_legacy_twin('results/mcmc/mcmc_day_1.pkl', mcmc_draw=i,
                             data=data, body_weight=100.)
         for i in range(100)]

Twins saved with save_chains=True also contain the emcee sampler. It is ignored, and emcee does not need to be installed.

Limitations

  • Replay workspaces are not converted. The files in results/workspaces/ are simulation outputs, not twins, and they pickle 1.x classes that no longer exist. Replay the converted twin to regenerate them.
  • Interval twins. Each portion's twin converts on its own. The carry-over between portions was never stored in the 1.x file: chain the converted twins at replay time as shown in Multi-day intervals.
  • Data sampling. The 2.x data classes assume one row every 5 minutes. A twin fitted with another yts still converts, but --data cannot be used with it.
  • Pickle safety. Like any pickle, a twin file can execute code when loaded. Convert only files you produced yourself or trust.

The Python API is documented in the Utils reference.