Result

class telescopic.Result(replicates, *, names=None, kernel=None, initial=None, tuning=None, pilot=None)

The output of a run of coupled chains.

Censored pairs appear in meeting_times as inf and are excluded from the estimates, from n_replicates and from measure.

A run with keep has two sets of replicates, each named where it is used. The moments, mean(), var(), std() and cov() (up to \(d = 100\)), come from the moments of all \(R\) replicates that met, as do the meeting times, costs and bounds on total variation. estimate(), the quantiles, the histograms, the plots of marginals, measure, chains(), to_datatree() and cov() above \(d = 100\) come from the n_kept replicates of index below keep that met, and w1_bound() from the kept replicates, censored ones included. Each set gives unbiased or consistent estimates on its own; no joint error statement holds for estimates from both.

Parameters:
replicatestelescopic.engine.Replicates

The engine’s output, with the settings and the root seed of its run.

namessequence of str, optional

Parameter names; x0, x1, … by default.

kernel, initialoptional

The frozen kernel and the initial distribution, for the record.

tuningTuningReport, optional

The report of the tuning pilot.

pilotndarray, shape (R0,), optional

The sampler’s lag-1 pilot meeting times; an automatic k came from those run before the first run.

Attributes:
k, m, lag, thinint

The settings of the run.

max_iterint or None

The cap of the run.

keepint or None

The replicates of index below keep stored their signed measures; None when every replicate did.

seednumpy.random.SeedSequence

The root seed, whose entropy and spawn_key reproduce the run.

indexndarray of int, shape (R_total,)

Replicate indices, censored ones included.

meeting_timesndarray of float, shape (R_total,)
costsndarray of int, shape (R_total,)

Kernel applications per replicate.

measureSignedMeasure

The signed measures of the kept replicates that met.

n_replicatesint

\(R\), the replicates that met.

n_keptint

The kept replicates that met, measure.n_replicates: \(R\) without keep.

n_censoredint
ndimint
n_log_prob, n_gradint

Evaluations of the log-density and its gradient by the replicates, without those of tuning and of the meeting-time pilot.

n_grad_zeroedint

Gradients of the replicates taken as 0 because they were not finite where the log-density is.

wall_timefloat

Seconds spent running the replicates, without tuning and the pilot.

interruptedbool

Whether a requested replicate never ran, so that the estimates are consistent but not exactly unbiased until it does.

abandonedndarray of int

The replicates that an error stopped while they ran and that have not run since. They tend to be those with long meeting times, so while there are any the estimates leave out a selection of the replicates.

chains()

The averaged states of the kept replicates that met, as chains of equal length.

Replicate \(r\)’s chain is \(X_t\) for \(t \in S = \{k, k + s, \dots\} \cap [k, m]\), s = thin, in time order: the atoms of the time average, without the bias correction. Shaped as ArviZ takes chains, (chain, draw, dim); to_datatree() passes them to ArviZ.

Returns:
ndarray, shape (n_kept, len(S), d)
check(strict=False)

Warn about the conditions that apply to this run.

They are listed under Warnings, in Warnings and errors.

Parameters:
strictbool

Raise RuntimeError instead of warning.

cov()

Unbiased estimate of the covariance matrix of the target.

\[\widehat{\mathrm{Cov}}_\pi(x) = R^{-1}\sum_r \hat\pi_r(xx^\top) - \bar a\bar a^\top + S_a/R\]

with \(a_r = \hat\pi_r(x)\), their mean \(\bar a\) and sample covariance \(S_a\) over the \(R\) replicates that met. With keep, it comes from the moments of all of them up to \(d = 100\), the second moments taken about \(\bar a\), and above it from the n_kept kept replicates that met, whose diagonal can then differ from var().

Returns:
ndarray, shape (d, d)
credible_interval(mass=0.68, h=None)

The central credible interval holding mass of each marginal, or of h.

The quantiles at \((1 - \mathrm{mass})/2\) and \((1 + \mathrm{mass})/2\).

Parameters:
massfloat in (0, 1)

The probability that the interval holds.

hcallable(), optional

As in quantile().

Returns:
ndarray, shape (2, d), or with h, (2,) or (2, p)

Lower and upper ends.

diagnostics()

Diagnostics of the run: meeting times, censoring, bias corrections, cost.

Returns:
dict

meeting_time quantiles (50, 90, 99) and maximum over every pair, inf where one falls on a censored pair, which sorts above every meeting time; tail_index, hill() of \(\tau - L + 1\) with n_tail \(= \lfloor R/10 \rfloor\), nan below 500 replicates; censored; late_fraction, the fraction of pairs with \(\tau - L > k\), censored ones included (the leading term of the TV bound at \(k\)), with late_fraction_upper, its one-sided 95% Clopper-Pearson upper bound, which stays informative when the fraction is 0; tv_bound_at_k; variance_share, the largest share of one replicate in the sample variance of the estimate of a coordinate’s mean or variance, variance_share_of, that estimate, and variance_share_replicate, the index of that replicate, nan, None and None below 2 replicates; mean_cost, seconds_per_replicate and relative_cost, the mean cost over \(m - k + 1\).

estimate(h, level=0.95)

Estimate \(\pi(h)\) with a confidence interval.

From the kept replicates that met, n_kept of them, with \(n_\mathrm{kept} - 1\) degrees of freedom.

Parameters:
hcallable()

Maps points of shape (n, d), a read-only array, to values of shape (n,) or (n, p).

levelfloat

Confidence level of the interval, in (0, 1).

Returns:
Estimate

Examples

The probability that the first coordinate is positive is the expectation of an indicator, one value per point; replicates holds each replicate’s estimate:

>>> from telescopic import examples, sample
>>> example = examples.gaussian(2)
>>> result = sample(
...     example.log_prob, example.initial,
...     n_replicates=50, vectorize=True, rng=0,
... )
>>> estimate = result.estimate(lambda x: x[:, 0] > 0)
>>> estimate.value.shape, estimate.replicates.shape
((), (50,))
histogram(dims, bins=20, range=None)

Histogram of one coordinate or several, with standard errors.

The mass of each bin is the average over the kept replicates that met of its signed mass, so a bin can be negative. The bins are half-open, \([a, b)\), except the last, which is closed, as in numpy.histogram, so that an atom on the upper edge of range is counted. It is unbiased for a range fixed before the run; the default range, from the atoms, biases every bin, the two outer ones by a term of order \(1/R\). Memory: a few floats per atom, and per bin.

Parameters:
dimsint or sequence of int

The coordinate, or the coordinates of a joint histogram.

binsint

The number of bins along each coordinate.

rangearray_like, shape (2,) or (len(dims), 2), optional

The lower and upper edges, a pair per coordinate; by default the range of the atoms.

Returns:
masses, standard_errorsndarray, shape (bins,) or (bins,) * len(dims)

Entry [i, j] of a joint histogram is bin i of the first coordinate and bin j of the second.

edgesndarray, shape (bins + 1,), or a list of them for a sequence of coordinates
classmethod load(path)

Load a result saved by save(), with descriptions of its kernel and initial distribution.

A directory is read as the checkpoint of CoupledSampler.run: the result of every replicate its files hold, with the plan’s tuning report and pilot, interrupted while an index that a run there requested has not finished.

Parameters:
pathstr, path-like or binary file

A file, to whose name .npz is appended when it lacks it, or a checkpoint directory.

Returns:
Result
mean()

The estimate of the mean of each coordinate.

From all \(R\) replicates that met; with keep, from their moments, whose replicates are \(a_r = c_r + \hat\pi_r(x - c_r)\).

Returns:
Estimate

With value and standard_error of shape (d,).

merge(*others)

Join with runs of the same seed and configuration and disjoint replicates.

telescopic.engine.merge() checks the seeds, the settings, the dimensions and the replicates, and joins every result at once. That the runs share the target, the kernel and the initial distribution is the caller’s to ensure: their descriptions omit parameters. The merged result takes this result’s names, and its kernel, initial distribution, tuning report and pilot meeting times, each from the first of others that has one where this result has none. Its replicates are bitwise those of one run of all of them for a target evaluated point by point, and can differ from them by rounding for a vectorized one (telescopic.engine.run()).

Parameters:
*othersResult

The results to join with this one, at least one.

Returns:
Result

The union of the replicates and of the requested indices; interrupted if a requested replicate ran in none.

plot_corner(dims=None, bins=20)

Plot a corner plot of signed histograms (needs matplotlib).

Parameters:
dimsint or sequence of int, optional

Coordinates; all by default.

binsint

The number of bins along each coordinate.

Returns:
ndarray of Axes
plot_marginals(dims=None, bins=20, axes=None)

Plot signed histograms of the marginals with their errors (needs matplotlib).

Parameters:
dimsint or sequence of int, optional

Coordinates; all by default.

binsint

The number of bins along each coordinate.

axessequence of Axes, optional

One per coordinate; by default, those of a new figure.

Returns:
list of Axes
plot_meeting_times(axes=None)

Plot the meeting times and their survival function (needs matplotlib).

Parameters:
axessequence of two Axes, optional

By default, those of a new figure.

Returns:
list of two Axes
plot_tv_bound(ax=None)

Plot the TV bound against t, with k marked (needs matplotlib).

Parameters:
axAxes, optional

By default, that of a new figure.

Returns:
Axes
quantile(q, h=None)

Quantiles of each coordinate, or of h, under the pooled signed measure.

Spec section 3.4. From the kept replicates that met. Consistent as their number grows, not unbiased.

Parameters:
qfloat or array_like of float in [0, 1]

The levels of the quantiles.

hcallable(), optional

As in estimate(); its quantiles are taken in place of the coordinates’.

Returns:
ndarray, shape q.shape + (d,), or with h, q.shape or q.shape + (p,)

Notes

Cost: one sort of the atoms per column, after merging consecutive equal atoms, and with h, one call of h on the merged atoms.

save(path)

Save as a versioned .npz file, without pickle.

The kernel and the initial distribution are saved as their descriptions, str(kernel) and str(initial); the engine’s paths are not saved.

Parameters:
pathstr, path-like or binary file

.npz is appended to a name that lacks it.

std()

Standard deviations \(\sqrt{\max(0, \widehat{\mathrm{Var}})}\).

Consistent as \(R\) grows, not unbiased.

Returns:
ndarray, shape (d,)
summary()

Estimates per parameter and the diagnostics of the run.

Returns:
Summary

Examples

The summary has a row per parameter and a column per estimate; print(summary) shows them as a table, with the diagnostics of the run below it:

>>> from telescopic import examples, sample
>>> example = examples.gaussian(2)
>>> result = sample(
...     example.log_prob, example.initial,
...     n_replicates=50, vectorize=True, rng=0,
... )
>>> summary = result.summary()
>>> summary.names, list(summary.table)
(['x0', 'x1'], ['mean', 'standard_error', 'std', 'q16', 'q50', 'q84'])
to_datatree()

The chains of chains() as ArviZ data, without the bias correction (needs arviz).

The posterior group holds one variable per coordinate, named by names, of dimensions (chain, draw): a chain for each kept replicate that met, whose coordinate is the replicate’s index, and a draw for each time \(t \in S\), whose coordinate is \(t\). There is no sample_stats group, since a result stores no log-density values.

ArviZ’s \(\hat R\) and effective sample sizes of these chains describe the uncorrected chains, not the estimates of this result (What replaces a judgment of convergence, in Error bars from replicates, and what replaces R-hat and ESS).

Returns:
xarray.DataTree

Each variable of posterior has shape (n_kept, len(S)).

tv_bound(t=None)

Estimated upper bound on the total variation distance from the law of X_t to the target.

The bound derived under Distance to stationarity, in Theory, with its standard error, as telescopic.diagnostics.tv_bound() computes them. A censored pair counts as meeting just after its cap, the earliest it can, so with censored pairs it is a lower bound of the estimate without a cap.

Parameters:
tarray_like of int, optional

Times; by default every time from 0 to the last at which the bound is positive, so that entry t is the bound at t.

Returns:
bound, standard_errorndarray, shape of t
var()

Unbiased estimates of the variances; they can be negative.

\[\widehat{\mathrm{Var}}_\pi(x_j) = R^{-1}\sum_r \hat\pi_r(x_j^2) - \bar a_j^2 + S_{a,jj}/R\]

This is the diagonal of cov(), whose docstring defines the notation, from all \(R\) replicates that met; with keep, from their moments.

Returns:
ndarray, shape (d,)
w1_bound(t=None)

Estimated upper bound on the 1-Wasserstein distance from the law of X_t to the target.

The bound derived under Distance to stationarity, in Theory, with its standard error, as telescopic.diagnostics.w1_bound() computes them. It depends on the parameterization of the target. A censored pair’s distances stop at its cap, so with censored pairs it is a lower bound of the estimate without a cap. With keep, it averages over the kept replicates, censored ones included.

Parameters:
tarray_like of int, optional

Times; by default every time from 0 to the last at which the bound is positive.

Returns:
bound, standard_errorndarray, shape of t