TimescaleModel#
- class pypillometry.TimescaleModel(data, eyes=[], binocular=None, timescales=None, segments=None, fs=20.0, policy='strict', variable='pupil', nu=None, keep_data=True, name=None, params=None)[source]#
Bases:
objectModel of the slow and fast fluctuations of the pupil size of one recording (experimental).
The log pupil size is described as a mean per segment, one fast component (Matérn-3/2 with free standard deviation and length scale), a bank of slow components (“atoms”) at fixed time scales whose variances are estimated, and white noise. The model answers how much the pupil varies at each time scale, returns the slow part of the signal (with uncertainty) and reconstructs the signal where it is missing.
The constructor prepares the data and keeps the bookkeeping that is needed to get back to the original samples:
the samples that are unusable under the mask policy are left out; the masks are used as they are, so blinks and other artifacts, with their transients, have to be masked before (see
d.pupil.blinks_detect()andd.pupil.mask_transients());the signal is reduced to about fs Hz by means of the valid samples in consecutive blocks (
block_mean(); nothing is interpolated or filtered);it is converted to log-%, \(100 \log(\text{pupil} / \text{median})\), which makes the variability independent of the size of the pupil and of its units;
it is split into segments with a mean each: the periods that are not excluded (see
exclude_intervals()), or segments.
- Parameters:
data (EyeData) – the recording, with blinks and artifacts masked
eyes (str or list) – eyes to model; if empty, all eyes with pupil data
binocular (bool) – if False (default; with params: as in params), each eye gets its own model; if True, one model for both eyes: the fast component and the atoms are common to the eyes (with a gain between the eyes, which can differ in amplitude), each eye has its own mean and noise, and one more component describes the difference between the eyes.
predict(),store()andcomponents()then also know the merged eye"mean": the average of the two eyes on the log scale (the geometric mean of the pupil sizes), in which the difference between the eyes cancels. It uses the data of both eyes, weighted by their noise, also where one eye is missing, and its posterior interval and standard deviation include the uncertainty of the missing eye, but at most as much as if the merged eye relied on the other eye alone (its signal with the average gain of the eyes, at the level of the average of the means of both eyes in the segment), so that they do not grow without limit in long gaps of one eye. In segments without data of one eye, the merged eye is the signal of the other eye on the scale of the merged eye (about its pupil size times the square root of the ratio of the median pupil sizes of the other eye to its own). A model of a single eye also accepts"mean"there: it is that eye (so that every recording of a study can have a merged eye).timescales (sequence of float, str or Quantity) – time scales of the atoms (plain numbers are ms); default 3, 10, 30, 100 and 300 s (with params: as in params)
segments (Intervals or list of tuple, optional) – independent stretches of the recording with a mean each (e.g., blocks with different luminance), as for
exclude_intervals(); data outside of them are not used. Default: the periods that are not excluded (get_included()).fs (float) – sampling rate of the model in Hz (default 20); the rate that is used is the sampling rate of the data divided by a whole number
policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable (see
mask()); default"strict": also interpolated samples are left out, so that only measured data go into the modelvariable (str) – variable to model (default
"pupil")nu (float) – smoothness of the atoms (default 1.5; with params: as in params)
keep_data (bool) – keep a reference to data (default), so that
interpolate()andstore()work without an argument; the model itself only needs the reduced dataname (str, optional) – name of the model (default: the name of data)
params (dict, optional) – parameters of an earlier model (its
params, e.g. stored ind.info). The structure of the model (eyes, binocular, timescales, nu) is taken from them; arguments that are given must agree. The model can then be used withoutfit()(components, plots, simulation,store(), …), as if it had been fitted with these parameters, but without standard errors and prior;fit()starts from them.
- Attributes:
- eyeslist of str
- unitslist of str
the separately fitted models: the eyes, or
["both"]for a binocular model- bankTimescaleBank
structure of the model
- fitsdict
- fsfloat
sampling rate of the model (Hz)
- timenp.ndarray
times of the samples of the model (centres of the blocks, ms)
- ydict
eye -> the signal the model is fitted to (log-%, NaN where missing)
- segmentslist of (start, stop)
segments in samples of the model
- scaledict
eye -> median pupil size (the reference of the log-%)
Examples
>>> import pypillometry as pp >>> d = pp.get_example_data("rlmw_002").pupil.blinks_detect() >>> m = pp.TimescaleModel(d, eyes="left").fit() >>> m.summary() >>> m.plot.decomposition() >>> d = m.interpolate()
Methods
Smoothed components at the sampling rate of the model, in log-%.
Blocked cross-validation: the log predictive density of held-out blocks given the rest of the recording (see
blocked_cv()).Estimate the parameters of the model.
Accuracy and calibration of forecasts over several horizons.
Standardised one-step prediction errors of the model (standard normal and uncorrelated if the model is right).
Replace the unusable samples of the whole recording (blinks, artifacts, signal losses of any length) by the expected signal under the model.
Parts of the signal at the original samples.
The fitted model as steps of a simulation (see
pypillometry.sim).Simulate a new recording from the fitted model.
Total standard deviation (log-%) of the atoms with a time scale of at least cutoff: how much the pupil varies slowly.
Power spectrum of the data of the model (log-%, Welch's method within the segments; see
spectrum()).Store a part of the signal as a variable of the data (in the units of the data, one value per sample; see
predict()).Table of the estimates.
Semivariogram of the data of the model (log-%, pooled within the segments) at about log-spaced lags.
Semivariogram of the data against simulations of the fitted model with the gaps of the data (see
variogram_check()).Details
- components(eyes=[], cutoff='10 s')[source]#
Smoothed components at the sampling rate of the model, in log-%.
- Parameters:
eyes (str or list) – eyes; if empty, all eyes of the model. A binocular model also has the merged eye
"mean"(see the class description); for a model of a single eye,"mean"is that eye.cutoff (float, str or Quantity) – time scale from which on the atoms count as slow (plain numbers are ms; default 10 s)
- Return type:
- Returns:
eye -> dict of name ->
(mean, sd), the posterior mean and standard deviation of each part at the timestime. The parts are the components ("mean","fast", the atoms"3s","10s", …, and"diff"for a binocular model) and the sums"slow"(mean plus atoms from cutoff),"detrended"(everything else) and"signal"(everything except the noise).
- cross_validate(block='60 s', folds=5, refit=True)[source]#
Blocked cross-validation: the log predictive density of held-out blocks given the rest of the recording (see
blocked_cv()). Unlike the likelihood, the score is sensitive to the slow components; use it to compare models of the same data (e.g., with different time scales).- Parameters:
- Return type:
- Returns:
unit -> score (higher is better)
- fit(prior='medium', hessian=True, maxiter=400, n_jobs=None, progress=None)[source]#
Estimate the parameters of the model.
Maximises the restricted likelihood of the parameters (Kalman filter; the means of the segments are integrated out) plus the log density of the prior.
- Parameters:
prior (str, GaussianPrior or None) –
"weak","medium"(default) or"strong": the general prior, which describes how the parameters vary between recordings of several experiments (seegeneral_prior())a
GaussianPrior, e.g.group.priorof aTimescaleGroupNone: maximum likelihood. Atoms without variance then stay at zero, and the split of the variance between neighbouring atoms follows the noise of the recording.
hessian (bool) – compute the Hessian at the estimate (for standard errors); default True
maxiter (int) – maximum number of iterations of the optimiser
n_jobs (int or None) – number of threads for the likelihood evaluations of the optimiser and the Hessian (at most one per parameter); None (default): all cores but one; negative as in joblib (-1: all cores). Inside a parallel process (e.g.
ds.preprocessed(n_jobs=4)), “all cores” is its share.progress (bool or None) – show a progress bar; None (default): if the logging level is “INFO” or “DEBUG”
- Return type:
- Returns:
the model itself (fitted)
Notes
The optimiser starts from the parameters given with params (see
TimescaleModel), otherwise from values derived from the semivariogram of the signal.
- forecast_calibration(horizons=('50 ms', '200 ms', '1 s', '5 s', '20 s', '60 s'), step='1 s')[source]#
Accuracy and calibration of forecasts over several horizons.
From the state given the data up to a time point, the model predicts the signal horizons later. A model that describes the dependence over a horizon gives standardised errors with a standard deviation of 1 (below 1: it expects more variability than there is, above 1: less).
- Parameters:
- Return type:
- Returns:
one row per eye and horizon:
horizon(s),rmse(root mean squared error, log-%),z_sd(standard deviation of the standardised errors) andn(number of forecasts)
- innovations(eyes=[])[source]#
Standardised one-step prediction errors of the model (standard normal and uncorrelated if the model is right).
- interpolate(data=None, eyes=[], store_as=None, sd=False, inplace=None)[source]#
Replace the unusable samples of the whole recording (blinks, artifacts, signal losses of any length) by the expected signal under the model.
The samples that are unusable under the mask policy of the model are replaced by
predict("signal"): the expected pupil size given all usable data of the segment. Other than the interpolation of single blinks (d.pupil.blinks_interpolate()), this uses one model for the whole recording, which also bridges long gaps (with the slow components). The replaced samples get the"interpolated"layer. Samples outside the segments of the model (e.g., excluded periods) are not changed.With sd, the posterior standard deviation of the replaced samples is stored as
<store_as>_sd(e.g.,d["left", "pupil_sd"]; 0 for the other samples). Segments of the data (get_segments()) take it as the uncertainty of the values, which their averages and plots include in the error of the mean (seeSegmentedEyeData).- Parameters:
data (EyeData, optional) – object to interpolate; default: the data the model was built from. It must have the same samples.
store_as (str, optional) – variable the result is stored in; default: the variable of the model (
"pupil"), which is replacedsd (
bool) – also store the posterior standard deviation of the replaced samples (see above); default Falseinplace (bool or None) – if True, change data in place and return it; if False, return a changed copy; if None, use the setting of the object
- Return type:
- Returns:
the object with the interpolated data
- predict(what='signal', eyes=[], cutoff='10 s', scale='original', interval=None, _samples=None)[source]#
Parts of the signal at the original samples.
The smoother runs at the sampling rate of the model; the model is defined in continuous time, so the posterior of the signal at the original samples follows exactly from the smoothed states (
upsample()).- Parameters:
"signal"(default): the pupil size without the noise (all components), also where the data are missing"slow": the mean and the atoms with a time scale of at least cutoff (the slowly changing level of the pupil)"detrended": the signal minus its slow partthe name of a component (
"mean","fast"for the fast component alone,"3s", …,"diff") or a list of them
eyes (str or list) – eyes; if empty, all eyes of the model. A binocular model also has the merged eye
"mean"(see the class description); for a model of a single eye,"mean"is that eye.cutoff (float, str or Quantity) – time scale from which on the atoms count as slow (plain numbers are ms; default 10 s)
scale ({"original", "log%"}) –
"original"(default): in the units of the data. Parts with the mean (signal, slow) aremedian * exp(part / 100); parts without it are the difference between the signal and the signal without the part, so that slow + detrended = signal."log%": on the scale of the model, \(100 \log(\text{pupil} / \text{median})\), where the parts add up.interval (float, optional) – if given (e.g. 0.95), also return the limits of the pointwise posterior interval with this probability. On the original scale only for parts that contain the mean.
- Return type:
- Returns:
eye -> array with one value per sample of the data (NaN outside the segments); with interval, eye ->
(estimate, lower, upper)
- process()[source]#
The fitted model as steps of a simulation (see
pypillometry.sim).- Return type:
- Returns:
one step per separately fitted unit (each eye, or both eyes for a binocular model), with the estimated parameters (without the noise, see
simulate())
Examples
>>> sim = pp.sim.Simulation("5 min", fs=20, eyes=m.eyes).pupil(*m.process())
- simulate(duration=None, fs=None, seed=None, name=None)[source]#
Simulate a new recording from the fitted model.
The latent pupil size is drawn from the model with the estimated parameters (
process()), scaled to the median pupil size of each eye (scale), and white noise with the estimated standard deviation is added.- Parameters:
duration (float, str or Quantity, optional) – duration (plain numbers are ms); default: the duration of the segments of the model
fs (float, optional) – sampling rate in Hz; default: the rate of the model. The noise of the model is that of block means at the rate of the model; at another rate, its standard deviation is scaled by \(\sqrt{f_s / f_{s,\text{model}}}\) (as for white noise of the raw samples; the noise of real trackers is not white).
seed (int, optional) – seed of the random numbers
name (str, optional) – name of the data (default: the name of the model with
_sim)
- Return type:
- Returns:
the simulated data, with the true components in
d.truth(seeTimescalePupil)
Examples
>>> d = pp.TimescaleModel(data).fit().simulate("10 min", seed=1) >>> d.plot.plot_components()
- slow_sd(cutoff='10 s')[source]#
Total standard deviation (log-%) of the atoms with a time scale of at least cutoff: how much the pupil varies slowly. A single recording determines this sum much better than its split between neighbouring atoms.
- spectrum(eyes=[], window='200 s', **kwargs)[source]#
Power spectrum of the data of the model (log-%, Welch’s method within the segments; see
spectrum()).
- store(what='slow', store_as=None, data=None, eyes=[], cutoff='10 s', interval=None, sd=True, inplace=None)[source]#
Store a part of the signal as a variable of the data (in the units of the data, one value per sample; see
predict()).store("signal")low-pass filters and interpolates in one step: it is the expected pupil size without the noise, also where the data are missing. Where the model had no data (samples unusable under its mask policy), the stored values get the"interpolated"layer, as withinterpolate().With interval, the limits of the pointwise posterior interval are stored too, as
<store_as>_lowerand<store_as>_upper(e.g.,d["left", "pupilsmooth_lower"]). They are wide where the model had no data. The interval is asymmetric, since the model works on a log scale. Later steps treat the limits as any other variable; after averaging (e.g., downsampling or segment means) they are only approximately the limits of the averaged signal.With sd (default), the posterior standard deviation is stored as
<store_as>_sd(in the units of the data, to first order), for parts that contain the mean ("signal","slow"). Segments of the data (get_segments()) take it as the uncertainty of the values (seeSegmentedEyeData).- Parameters:
what (str or list of str) – part of the signal:
"slow"(default),"signal"(the smoothed signal),"detrended"(the signal minus its slow part) or component namesstore_as (str, optional) – name of the variable; default
"pupilslow","pupilsmooth"(for"signal") or"pupildetrended"data (EyeData, optional) – object to store the result in; default: the data the model was built from. It must have the same samples.
eyes (str or list) – eyes; if empty, all eyes of the model. A binocular model also has the merged eye
"mean"(see the class description); for a model of a single eye,"mean"is that eye.cutoff (float, str or Quantity) – time scale from which on the atoms count as slow (plain numbers are ms; default 10 s)
interval (float, optional) – if given (e.g. 0.95), also store the limits of the pointwise posterior interval with this probability (see above); only for parts that contain the mean (
"signal","slow")sd (
bool) – also store the posterior standard deviation (see above); default True. Parts without the mean (e.g."detrended") have no standard deviation in the units of the data; for them it is not stored.inplace (bool or None) – if True, change data in place and return it; if False, return a changed copy; if None, use the setting of the object
- Return type:
- Returns:
the object with the new variable (e.g.,
d["left", "pupilslow"])
- summary(cutoff='10 s')[source]#
Table of the estimates.
- Parameters:
cutoff (float, str or Quantity) – time scale from which on the atoms count as slow (plain numbers are ms; default 10 s)
- Return type:
- Returns:
one row per unit: the parameters (see
params), the total slow standard deviation (slow_sd), the number of valid samples, the log-likelihood, AIC and BIC
- variogram(eyes=[], per_decade=12)[source]#
Semivariogram of the data of the model (log-%, pooled within the segments) at about log-spaced lags.
- variogram_check(eyes=[], n_sim=40, rng=None)[source]#
Semivariogram of the data against simulations of the fitted model with the gaps of the data (see
variogram_check()).- Return type:
- Returns:
eye ->
VariogramCheck
- property aic: dict[str, float]#
unit -> Akaike information criterion (see
BankFit.aic); lower is better
- property bic: dict[str, float]#
unit -> Bayesian information criterion (see
BankFit.bic); lower is better
- property loglik: dict[str, float]#
unit -> restricted log-likelihood at the estimate (without the prior)
- property params: dict[str, Any]#
Parameters of the model (estimated, or set with params), as a dict of plain numbers that can be stored (e.g., in
d.info) and passed to the params argument ofTimescaleModelto build the model with them again:"timescales": time scales of the atoms (ms)"nu": smoothness of the atomsone entry per unit (each eye, or
"both"for a binocular model): dict with the standard deviation (log-%) and length scale (ms) of the fast component (fast_sd,fast_ell), the standard deviation of the noise (noise_sd) and of each atom (sd_3s, …); seeparams().
Examples
>>> m = pp.TimescaleModel(d).fit() >>> m.params["left"]["fast_sd"] >>> m2 = pp.TimescaleModel(d, params=m.params)
- property plot: TimescalePlots#
plots of the model (
TimescalePlots)