Data¶
In this tutorial, we fit LQG models to data from a continuous tracking experiment using maximum likelihood estimation. The data come from Bonnen et al. (2015): Participants tracked a Gaussian blob following a random walk with the mouse cursor. The width of the blob was varied across six conditions, which makes the target position more or less uncertain.
We will
- load and visualize the data,
- fit two models from
lqg.tracking(theBoundedActorand theSubjectiveActor) to each condition withlqg.infer.mle.max_likelihood, - compare the models and check how well they reproduce the data.
Note: Fitting all models takes a few minutes on a laptop CPU.
import jax
# double precision makes the likelihood optimization numerically more stable
jax.config.update("jax_enable_x64", True)
import arviz as az
import jax.numpy as jnp
import matplotlib as mpl
import matplotlib.pyplot as plt
from jax import random
from lqg import xcorr
from lqg.io import load_tracking_data
from lqg.infer.mle import max_likelihood, Box, LogBox
from lqg.tracking import BoundedActor, SubjectiveActor
mpl.rcParams["axes.spines.right"] = False
mpl.rcParams["axes.spines.top"] = False
Loading the data¶
load_tracking_data returns an array of shape (conditions, trials, time steps, 2), where the last dimension holds the target and the cursor position (in arcmin), and the blob widths of the six conditions.
data, blob_widths = load_tracking_data(data_path="../../data/")
data = jnp.asarray(data, dtype=jnp.float64) # match the precision of the models
data.shape
(6, 20, 1068, 2)
blob_widths
array([15., 17., 22., 28., 33., 38.])
dt = 1 / 60.0 # the experiment ran at 60 Hz
time = jnp.arange(data.shape[2]) * dt
f, ax = plt.subplots(1, 2, figsize=(10, 3.5), sharey=True)
for a, condition in zip(ax, [0, 5]):
a.plot(time, data[condition, 0, :, 0], label="target")
a.plot(time, data[condition, 0, :, 1], label="cursor")
a.set_title(f"Blob width: {blob_widths[condition]:.0f} arcmin")
a.set_xlabel("Time [s]")
ax[0].set_ylabel("Position [arcmin]")
ax[0].legend(frameon=False)
plt.show()
A model-free way of summarizing tracking data is the cross-correlogram (CCG) between target and cursor velocities. With increasing blob width, the peak of the CCG gets lower and later: tracking becomes worse and slower.
colors = plt.cm.viridis(jnp.linspace(0, 0.9, len(blob_widths)))
vels = jnp.diff(data, axis=-2)
lags, correls = xcorr(vels[..., 1], vels[..., 0], maxlags=60)
for color, width, c in zip(colors, blob_widths, correls.mean(axis=1)):
plt.plot(lags * dt, c, color=color, label=f"{width:.0f}")
plt.xlabel("Lag [s]")
plt.ylabel("Cross-correlation")
plt.legend(title="Blob width [arcmin]", frameon=False)
plt.show()
Maximum likelihood estimation¶
max_likelihood maximizes the log likelihood $\log p(\mathbf x_{1:T} \mid \theta)$ of a model class (see the Overview for how the likelihood is computed) with the L-BFGS optimizer from optimistix. Its main arguments are:
x: the data of one condition, with shape(trials, time steps, 2),model: the model class whose parameters should be estimated,constraints: lower and upper bounds for the parameters. The optimization runs in an unconstrained space, which is mapped to the bounds by aBox(linear scale) or aLogBox(log scale, useful for parameters that span several orders of magnitude). Parameters you do not specify use the bounds inlqg.infer.mle.default_constraints,num_restarts: the number of random initializations. The optimizations run in parallel (viajax.vmap), and the solution with the highest likelihood is returned,- any further keyword argument (here:
dt) fixes that parameter to the given value instead of estimating it.
Bounded actor¶
The BoundedActor has four free parameters: the perceptual uncertainty about the target (sigma_target) and about the cursor (sigma_cursor), the variability of the actions (action_variability) and the cost of actions (action_cost). We fit it separately to each condition.
fixed_params = {"dt": dt}
bounded_constraints = {
"action_cost": LogBox(low=1e-7, high=1e-2),
"sigma_target": Box(low=0.01, high=100.0),
"action_variability": Box(low=0.01, high=2.0),
"sigma_cursor": Box(low=0.01, high=100.0),
}
key = random.PRNGKey(0)
bounded_params = []
for x in data:
key, subkey = random.split(key)
params = max_likelihood(
key=subkey,
x=x,
model=BoundedActor,
constraints=bounded_constraints,
max_steps=1000,
num_restarts=10,
**fixed_params,
)
bounded_params.append(params)
{name: float(value) for name, value in bounded_params[0].items()}
{'action_cost': 0.001235790519620415,
'action_variability': 0.5343653700311625,
'sigma_cursor': 9.457849094478416,
'sigma_target': 7.093193801744099}
Subjective actor¶
The SubjectiveActor additionally assumes that the participant has a subjective internal model of the target's dynamics, in which the target also has a velocity component (see the Overview). This adds two parameters, subj_noise and subj_vel_noise.
When fitting this model with the default bounds, some estimates end up at the boundaries, for example action_cost at its upper bound of $10^{-2}$. We therefore widen the range of action_cost and let the two subjective noise parameters vary over four orders of magnitude on a log scale. Always check whether estimates lie at the boundaries. If they do, the bounds are probably too narrow.
subjective_constraints = {
**bounded_constraints,
"action_cost": LogBox(low=1e-7, high=1.0),
"subj_noise": LogBox(low=1e-2, high=1e2),
"subj_vel_noise": LogBox(low=1e-2, high=1e2),
}
subjective_params = []
for x in data:
key, subkey = random.split(key)
params = max_likelihood(
key=subkey,
x=x,
model=SubjectiveActor,
constraints=subjective_constraints,
max_steps=1000,
num_restarts=10,
**fixed_params,
)
subjective_params.append(params)
{name: float(value) for name, value in subjective_params[0].items()}
{'action_cost': 0.007660893066451798,
'action_variability': 0.3854531585972854,
'sigma_cursor': 5.067780146178543,
'sigma_target': 10.97728222272217,
'subj_noise': 3.603452980617141,
'subj_vel_noise': 0.46788853536234465}
To check the boundaries systematically, we compare all estimates with the bounds of their constraints:
def at_bounds(estimates, constraints, rtol=1e-3):
# map -inf and +inf in unconstrained space to the lower and upper bounds
flagged = []
for condition, params in enumerate(estimates):
for name, value in params.items():
low = constraints[name].forward(-jnp.inf)
high = constraints[name].forward(jnp.inf)
# atol=0, otherwise every value below 1e-8 would count as close to the bound
if jnp.isclose(value, low, rtol=rtol, atol=0) or jnp.isclose(value, high, rtol=rtol, atol=0):
flagged.append((condition, name, float(value)))
return flagged
print("BoundedActor:", at_bounds(bounded_params, bounded_constraints))
print("SubjectiveActor:", at_bounds(subjective_params, subjective_constraints))
BoundedActor: [] SubjectiveActor: [(4, 'subj_vel_noise', 0.010004215942594721)]
The only remaining estimate at a boundary is subj_vel_noise at its lower bound for one condition. This is not a sign of too narrow bounds: It means that a subjective velocity component does not help to explain the data in this condition, so the noise on it is driven towards zero.
Model comparison¶
The SubjectiveActor has two more parameters than the BoundedActor, so it is more flexible. To compare the models fairly, we penalize the number of parameters with the Akaike information criterion, $\text{AIC} = 2k - 2 \log \hat{L}$, where lower is better.
T = data.shape[2] - 1 # number of transitions per trial
models = {
"BoundedActor": (BoundedActor, bounded_params),
"SubjectiveActor": (SubjectiveActor, subjective_params),
}
aic = {}
for name, (model_class, estimates) in models.items():
aic[name] = jnp.array(
[
2 * len(params) - 2 * model_class(**params, **fixed_params, T=T).log_likelihood(x).sum()
for x, params in zip(data, estimates)
]
)
delta_aic = aic["SubjectiveActor"] - aic["BoundedActor"]
for width, d in zip(blob_widths, delta_aic):
print(f"Blob width {width:3.0f} arcmin: ΔAIC (subjective − bounded) = {d:8.1f}")
Blob width 15 arcmin: ΔAIC (subjective − bounded) = -1354.0 Blob width 17 arcmin: ΔAIC (subjective − bounded) = -1084.5 Blob width 22 arcmin: ΔAIC (subjective − bounded) = -813.2 Blob width 28 arcmin: ΔAIC (subjective − bounded) = -636.5 Blob width 33 arcmin: ΔAIC (subjective − bounded) = -554.6 Blob width 38 arcmin: ΔAIC (subjective − bounded) = -782.0
Perceptual uncertainty¶
The parameter of main interest is the perceptual uncertainty about the target. In both models, it increases with blob width, as expected.
for name, (_, estimates) in models.items():
plt.plot(blob_widths, [p["sigma_target"] for p in estimates], "o-", label=name)
plt.xlabel("Blob width [arcmin]")
plt.ylabel(r"Perceptual uncertainty $\sigma_\text{target}$ [arcmin]")
plt.ylim(0)
plt.legend(frameon=False)
plt.show()
Simulating from the fitted models¶
To see how well the fitted models capture the data, we simulate cursor responses to the same target trajectories that the participants saw, using simulate_actions, and compute the CCGs of the simulated data.
action_dim_mask = jnp.array([False, True]) # the cursor is controlled, the target is given
f, ax = plt.subplots(1, 3, figsize=(12, 3.5), sharey=True, sharex=True)
ax[0].set_title("Data")
for color, c in zip(colors, correls.mean(axis=1)):
ax[0].plot(lags * dt, c, color=color)
for a, (name, (model_class, estimates)) in zip(ax[1:], models.items()):
for x, params, color, width in zip(data, estimates, colors, blob_widths):
key, subkey = random.split(key)
model = model_class(**params, **fixed_params, T=T)
x_sim = model.simulate_actions(x, action_dim_mask, subkey)
v = jnp.diff(x_sim, axis=-2)
_, c = xcorr(v[..., 1], v[..., 0], maxlags=60)
a.plot(lags * dt, c.mean(axis=0), color=color, label=f"{width:.0f}")
a.set_title(name)
for a in ax:
a.set_xlabel("Lag [s]")
ax[0].set_ylabel("Cross-correlation")
ax[-1].legend(title="Blob width [arcmin]", frameon=False)
f.tight_layout()
plt.show()
Both models reproduce the qualitative pattern in the data: the CCG peaks get lower and broader with increasing blob width. However, the simulated peaks are lower and slightly earlier than in the data, so neither model captures every aspect of the behavior.
Next steps¶
In the Hand dynamics tutorial, we extend both models with more realistic point-mass dynamics of the hand, which improves the fit to these data.
Maximum likelihood estimation gives point estimates. To quantify the uncertainty about the parameters, you can instead sample from their posterior distribution with MCMC, as shown in the Overview. lqg.infer.models also contains NumPyro models in which some parameters are shared across conditions (shared_params_lqg_model).