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_timesasinfand are excluded from the estimates, fromn_replicatesand frommeasure.A run with
keephas two sets of replicates, each named where it is used. The moments,mean(),var(),std()andcov()(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()andcov()above \(d = 100\) come from then_keptreplicates of index belowkeepthat met, andw1_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:
- replicates
telescopic.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.
- tuning
TuningReport, optional The report of the tuning pilot.
- pilot
ndarray, shape (R0,), optional The sampler’s lag-1 pilot meeting times; an automatic
kcame from those run before the first run.
- replicates
- Attributes:
- k, m, lag, thin
int The settings of the run.
- max_iter
intorNone The cap of the run.
- keep
intorNone The replicates of index below
keepstored their signed measures;Nonewhen every replicate did.- seed
numpy.random.SeedSequence The root seed, whose
entropyandspawn_keyreproduce the run.- index
ndarrayofint, shape (R_total,) Replicate indices, censored ones included.
- meeting_times
ndarrayoffloat, shape (R_total,) - costs
ndarrayofint, shape (R_total,) Kernel applications per replicate.
- measure
SignedMeasure The signed measures of the kept replicates that met.
- n_replicates
int \(R\), the replicates that met.
- n_kept
int The kept replicates that met,
measure.n_replicates: \(R\) withoutkeep.- n_censored
int - ndim
int - n_log_prob, n_grad
int Evaluations of the log-density and its gradient by the replicates, without those of tuning and of the meeting-time pilot.
- n_grad_zeroed
int Gradients of the replicates taken as 0 because they were not finite where the log-density is.
- wall_time
float 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.
- abandoned
ndarrayofint 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.
- k, m, lag, thin
- 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
RuntimeErrorinstead 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 then_keptkept replicates that met, whose diagonal can then differ fromvar().- Returns:
ndarray, shape (d, d)
- credible_interval(mass=0.68, h=None)¶
The central credible interval holding
massof each marginal, or ofh.The quantiles at \((1 - \mathrm{mass})/2\) and \((1 + \mathrm{mass})/2\).
- Parameters:
- mass
floatin (0, 1) The probability that the interval holds.
- h
callable(), optional As in
quantile().
- mass
- Returns:
ndarray, shape (2, d), or withh, (2,) or (2, p)Lower and upper ends.
- diagnostics()¶
Diagnostics of the run: meeting times, censoring, bias corrections, cost.
- Returns:
dictmeeting_timequantiles (50, 90, 99) and maximum over every pair,infwhere one falls on a censored pair, which sorts above every meeting time;tail_index,hill()of \(\tau - L + 1\) withn_tail\(= \lfloor R/10 \rfloor\),nanbelow 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\)), withlate_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, andvariance_share_replicate, the index of that replicate,nan,NoneandNonebelow 2 replicates;mean_cost,seconds_per_replicateandrelative_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_keptof them, with \(n_\mathrm{kept} - 1\) degrees of freedom.- Parameters:
- h
callable() Maps points of shape
(n, d), a read-only array, to values of shape(n,)or(n, p).- level
float Confidence level of the interval, in (0, 1).
- h
- Returns:
Examples
The probability that the first coordinate is positive is the expectation of an indicator, one value per point;
replicatesholds 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 ofrangeis counted. It is unbiased for arangefixed 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:
- dims
intor sequence ofint The coordinate, or the coordinates of a joint histogram.
- bins
int 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.
- dims
- Returns:
- 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.
- mean()¶
The estimate of the mean of each coordinate.
From all \(R\) replicates that met; with
keep, from their moments, whosereplicatesare \(a_r = c_r + \hat\pi_r(x - c_r)\).- Returns:
EstimateWith
valueandstandard_errorof 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 ofothersthat 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()).
- plot_corner(dims=None, bins=20)¶
Plot a corner plot of signed histograms (needs matplotlib).
- plot_marginals(dims=None, bins=20, axes=None)¶
Plot signed histograms of the marginals with their errors (needs matplotlib).
- plot_meeting_times(axes=None)¶
Plot the meeting times and their survival function (needs matplotlib).
- plot_tv_bound(ax=None)¶
Plot the TV bound against t, with k marked (needs matplotlib).
- 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:
- q
floator array_like offloatin [0, 1] The levels of the quantiles.
- h
callable(), optional As in
estimate(); its quantiles are taken in place of the coordinates’.
- q
- Returns:
ndarray, shapeq.shape + (d,), or withh,q.shapeorq.shape + (p,)
Notes
Cost: one sort of the atoms per column, after merging consecutive equal atoms, and with
h, one call ofhon the merged atoms.
- save(path)¶
Save as a versioned
.npzfile, without pickle.The kernel and the initial distribution are saved as their descriptions,
str(kernel)andstr(initial); the engine’s paths are not saved.- Parameters:
- path
str, path-like or binary file .npzis appended to a name that lacks it.
- path
- 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:
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
posteriorgroup holds one variable per coordinate, named bynames, 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 nosample_statsgroup, 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
posteriorhas 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
tis the bound att.
- tarray_like of
- Returns:
- bound, standard_error
ndarray, shape oft
- bound, standard_error
- 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; withkeep, 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. Withkeep, 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.
- tarray_like of
- Returns:
- bound, standard_error
ndarray, shape oft
- bound, standard_error