TimescaleBank#

class pypillometry.signal.gaussmarkov.TimescaleBank(timescales=(3000.0, 10000.0, 30000.0, 100000.0, 300000.0), nu=1.5, v0=0.25, channels=1, kappa=10000000.0)[source]#

Bases: object

Structure of a timescale-bank model (see bank) and the map between its parameter vector and state-space matrices.

The object holds no data and no parameter values. The parameter vector theta (see names) is unconstrained apart from box bounds (bounds()): logs of the standard deviations and of the length scale, and \(u_k = \log(v_k + v_0)\) for the atoms.

Parameters:
  • timescales (sequence of float) – time scales (length scales) of the atoms in ms, increasing; default 3, 10, 30, 100 and 300 s

  • nu (float) – smoothness of the atoms (1.5 (default) or 0.5, 2.5, …)

  • v0 (float) – offset of the variances of the atoms (signal units squared); atoms with a variance far below it are treated alike. Default 0.25, i.e. a standard deviation of 0.5, which suits signals in log-% (\(100 \log(x / \mathrm{median})\)).

  • channels (int or sequence of str) – 1 (default) or 2 channels, or their names (e.g. ("left", "right"))

  • kappa (float) – variance of the diffuse prior of the means

Examples

>>> bank = TimescaleBank()
>>> bank.names
['log_fast_sd', 'log_fast_ell', 'log_noise_sd', 'u_3s', 'u_10s', 'u_30s', 'u_100s', 'u_300s']
>>> theta = bank.theta(fast_sd=8., fast_ell=700., noise_sd=0.2, sd_30s=4.)
>>> {k: round(float(v), 3) for k, v in bank.params(theta).items()}
{'fast_sd': 8.0, 'fast_ell': 700.0, 'noise_sd': 0.2, 'sd_3s': 0.0, 'sd_10s': 0.0, 'sd_30s': 4.0, 'sd_100s': 0.0, 'sd_300s': 0.0}
>>> bank.lgssm(theta, fs=20).dim_state
13
>>> TimescaleBank(channels=("left", "right")).names[2:7]
['log_noise_sd_left', 'log_noise_sd_right', 'log_diff_sd', 'log_diff_ell', 'log_gain']

Methods

atom_var

variances of the atoms, \(v_k = \max(e^{u_k} - v_0, 0)\)

bounds

list of (lower, upper) bounds of the entries of theta

filter

Kalman filter (FilterResult); arguments as for loglik().

forecast_errors

Errors of forecasts horizons samples ahead (see forecast_errors()).

gains

Gain of the common components in each channel: 1 for one channel, \((g^{-1/2}, g^{1/2})\) for two (1 without theta).

lgssm

Discrete-time model for sampling rate fs (Hz).

loglik

Restricted log-likelihood of the parameters (Kalman filter).

obs_matrix

Observation matrix, (channels, dim).

params

Parameters on their natural scale.

psd

One-sided power spectral density of a channel at frequencies freq (Hz), in signal units squared per Hz.

select

Weights of the state for a part of the signal of one channel.

simulate

Simulate n samples at fs Hz (the means are 0).

slow_sd

Total standard deviation of the atoms with a time scale of at least cutoff (ms): \(\sqrt{\sum_{\tau_k \ge cutoff} v_k}\).

smooth

Kalman filter and smoother; arguments as for loglik().

start

Starting values from an empirical semivariogram.

theta

Parameter vector from parameters on their natural scale (the inverse of params()); atoms that are not given have no variance, the other parameters are required.

upsample

Posterior mean and variance of parts of the signal at a factor times higher sampling rate than the data the smoother was run on.

variogram

Semivariogram of a channel at lags lags (ms), with the nugget (the mean does not enter).

Details

atom_var(theta)[source]#

variances of the atoms, \(v_k = \max(e^{u_k} - v_0, 0)\)

Return type:

ndarray

bounds()[source]#

list of (lower, upper) bounds of the entries of theta

Return type:

list[tuple[float, float]]

filter(theta, y, fs, segments=None)[source]#

Kalman filter (FilterResult); arguments as for loglik().

Return type:

FilterResult

forecast_errors(theta, y, fs, horizons, step=20, segments=None)[source]#

Errors of forecasts horizons samples ahead (see forecast_errors()).

Return type:

tuple[ndarray, ndarray]

gains(theta=None)[source]#

Gain of the common components in each channel: 1 for one channel, \((g^{-1/2}, g^{1/2})\) for two (1 without theta).

Return type:

ndarray

lgssm(theta, fs, diffuse=True)[source]#

Discrete-time model for sampling rate fs (Hz).

Parameters:
  • theta (array) – parameter vector

  • fs (float) – sampling rate in Hz

  • diffuse (bool) – if False, the means are fixed at 0 (for simulation)

Return type:

LGSSM

loglik(theta, y, fs, segments=None)[source]#

Restricted log-likelihood of the parameters (Kalman filter).

Parameters:
  • theta (array) – parameter vector

  • y (array, (T,) or (T, channels)) – the signal, NaN where missing

  • fs (float) – sampling rate of y in Hz

  • segments (list of (start, stop), optional) – sample indices of independent segments, each with its own mean(s); default: one segment

Return type:

float

Returns:

does not depend on the level of the signal in each segment

obs_matrix(theta=None)[source]#

Observation matrix, (channels, dim). With two channels it depends on the gain between them (parameter vector theta; a gain of 1 without it).

Return type:

ndarray

params(theta)[source]#

Parameters on their natural scale.

Return type:

dict[str, float]

Returns:

fast_sd, fast_ell (ms), noise_sd (per channel: noise_sd_<channel>), with two channels diff_sd, diff_ell and gain, and the standard deviation of each atom (sd_3s, …)

psd(theta, freq, fs=None, channel=0)[source]#

One-sided power spectral density of a channel at frequencies freq (Hz), in signal units squared per Hz. With the sampling rate fs (Hz), the white noise of the samples is included.

Return type:

ndarray

select(what='signal', cutoff=10000.0, channel=0, theta=None)[source]#

Weights of the state for a part of the signal of one channel.

Parameters:
  • what (str or list of str) –

    • "signal": everything except the noise

    • "slow": the mean and the atoms with a time scale of at least cutoff

    • "detrended": the signal without its slow part (the fast component, the atoms below cutoff and, with two channels, the difference)

    • the name of a component (see component_names, e.g. "fast" for the fast component alone; "mean" is the mean of the channel) or a list of them

  • cutoff (float) – time scale in ms from which on the atoms are “slow” (default 10 s)

  • channel (int) – index of the channel (default 0)

  • theta (array, optional) – parameter vector; needed with two channels for the gain between them (a gain of 1 without it)

Return type:

ndarray

Returns:

vector w, so that the part of the signal is state @ w

simulate(theta, n, fs, rng=None, return_states=False)[source]#

Simulate n samples at fs Hz (the means are 0).

Return type:

ndarray | tuple[ndarray, ndarray]

Returns:

  • y ((n,) or (n, 2) array)

  • x ((n, dim) array) – states (if return_states)

slow_sd(theta, cutoff=10000.0)[source]#

Total standard deviation of the atoms with a time scale of at least cutoff (ms): \(\sqrt{\sum_{\tau_k \ge cutoff} v_k}\).

Return type:

float

smooth(theta, y, fs, segments=None)[source]#

Kalman filter and smoother; arguments as for loglik().

Return type:

tuple[FilterResult, SmootherResult]

Returns:

use sres.m_smooth @ bank.select(..., theta=theta) for parts of the signal

start(vg, vg_diff=None, floor=0.001)[source]#

Starting values from an empirical semivariogram.

The variogram of the model is linear in the variances of its components, so that for a dictionary of fast length scales and the atoms they follow from non-negative least squares on the relative errors; this cannot diverge. The variogram is used at about log-spaced lags (Variogram.at_log_lags()).

Parameters:
  • vg (Variogram) – of the signal (pooled within segments); with two channels, of their mean

  • vg_diff (Variogram, optional) – with two channels: of the difference of the channels

  • floor (float) – atoms that get no variance start at this fraction of the largest semivariance

Return type:

ndarray

Returns:

parameter vector within the bounds

theta(**params)[source]#

Parameter vector from parameters on their natural scale (the inverse of params()); atoms that are not given have no variance, the other parameters are required.

Return type:

ndarray

upsample(theta, fs, sres, factor, weights, segments=None, n_out=None)[source]#

Posterior mean and variance of parts of the signal at a factor times higher sampling rate than the data the smoother was run on.

The model is defined in continuous time, so that the distribution of the state between two samples follows exactly from the smoothed states at these samples (a Gauss-Markov bridge). Sample t of the smoothed data is taken as the centre of the fine samples t * factor ... (t + 1) * factor - 1 (block means, see block_mean()).

Parameters:
  • theta (array) – parameter vector

  • fs (float) – sampling rate (Hz) of the data the smoother was run on

  • sres (SmootherResult) – from smooth()

  • factor (int) – number of fine samples per sample

  • weights (array, (dim,) or (q, dim)) – weights of the state for the part(s) of the signal (see select(); with two channels, pass theta to it)

  • segments (list of (start, stop), optional) – the segments used in smooth(); outside of them the result is NaN

  • n_out (int, optional) – number of fine samples (default T * factor; longer outputs are padded with NaN)

Return type:

tuple[ndarray, ndarray]

Returns:

mean, var (np.ndarray, (T * factor,) or (q, T * factor))

variogram(theta, lags, channel=0)[source]#

Semivariogram of a channel at lags lags (ms), with the nugget (the mean does not enter).

Return type:

ndarray

property H: ndarray#

observation matrix for a gain of 1 (see obs_matrix())

property K: int#

number of atoms

property atom_names: list[str]#

names of the atoms, e.g. ['3s', '10s', ...]

property component_names: list[str]#

names of the components in the order of the state

property dim: int#

dimension of the state

property names: list[str]#

names of the entries of the parameter vector theta

property slices: dict[str, slice]#

dict of component name to the slice of the state that belongs to it