import Xoshiro128p from '../core/xoshiro'; /** * Base class implementing a general Markov chain Monte Carlo sampler. All MCMC samplers extend this class. * MCMC samplers approximate integrals by efficiently sampling a density that cannot be normalized or * sampled directly. Every public subclass (RWM, AdaptiveMetropolis, Slice, HMC, Gibbs, MALA, NUTS) * exposes an options-object-only constructor; this base constructor's positional * (logDensity, config, initialState) signature is an internal contract those subclasses forward to, * not part of the public API. * * @class MCMC * @memberof ran.mc * @param {Function} logDensity The logarithm of the (unnormalized) target density. * @param {Object=} config Sampler configuration. Supported properties: * * @param {Object=} initialState Initial state of the sampler. Supported properties: {x} (starting * position), {samplingRate} (thinning interval), and {internal} for subclass-specific state. * @constructor * @throws {Error} If config.dim is provided but is not a positive integer, or exceeds the maximum allowed dimension. * @throws {Error} If config.maxLag is provided but is not a positive integer, or exceeds the maximum allowed lag. * @throws {Error} If config.arWindow is provided but is not a positive integer, or exceeds the maximum allowed window. * @throws {Error} If the combined dim*maxLag accumulator footprint exceeds the maximum allowed memory budget. */ export default class MCMC { dim: any; maxLag: any; _arWindow: any; lnp: any; r: Xoshiro128p; _xProvided: any; x: any; samplingRate: any; internal: any; lastLnp: any; _daMu: any; _daHbar: any; _daLogEpsBar: any; _daT: any; _welford: { n: number; mean: number; M2: number; }[]; _acN: number; _acBuf: Float64Array[]; _acCross: Float64Array[]; _arN: number; _arCount: number; _arBuf: Uint8Array; constructor(logDensity: any, config?: {}, initialState?: {}); /** * Sets the seed for the sampler's pseudo random number generator. If the initial position * was not explicitly provided at construction, it is redrawn from the newly seeded generator * so that sampling is fully reproducible. * * @method seed * @memberof ran.mc.MCMC * @param {number|string} value The value of the seed, either a number or a string (for the ease of tracking seeds). * @returns {this} Reference to the current sampler. */ seed(value: number | string): this; /** * Returns the current state of the sampler. The return value can be passed to a sampler of the * same type to resume from this position. * * @method state * @memberof ran.mc.MCMC * @returns {Object} Object with properties: x (current position), samplingRate (thinning * interval), internal (subclass state), and prng (the PRNG's exact stream position, restored * on reconstruction so a resumed sampler's subsequent draws are bit-for-bit identical to an * uninterrupted run — decisions/0035-mcmc-exact-stream-reproducible-resume.md). */ state(): any; /** * Computes mean, standard deviation, and coefficient of variation for each dimension based on * observations seen since the last reset (start of sampling or construction). * * @method statistics * @memberof ran.mc.MCMC * @returns {Object[]} Array of {mean, std, cv} objects, one per dimension. */ statistics(): any[]; /** * Computes the acceptance rate over the most recent arWindow iterations (a sliding window, * default 1000). During the partial-fill phase, before arWindow iterations have occurred since * the last reset, this equals the exact cumulative rate. * * @method ar * @memberof ran.mc.MCMC * @returns {number} Fraction of proposals accepted in the current window. */ ar(): number; /** * Computes the autocorrelation function for each dimension at lags 0 to maxLag-1. Uses an * online estimator: O(dim * maxLag) memory, O(dim * maxLag) per update, O(1) per query. * * @method ac * @memberof ran.mc.MCMC * @returns {number[][]} Array of autocorrelation-vs-lag arrays, one per dimension. Lags with * fewer than r+1 observations return NaN. */ ac(): number[][]; /** * Computes the effective sample size for each dimension using Geyer's initial positive * monotone sequence estimator (IPSM; Geyer 1992, Vehtari et al. 2021 — the estimator used by * Stan and ArviZ): $\Gamma_m = \rho_{2m} + \rho_{2m+1}$ pairs consecutive lags starting at lag * 0 (so the first pair always includes $\rho_0 = 1$), clamped to be no larger than * $\Gamma_{m-1}$ (the true autocovariance sequence is convex, so a non-increasing sequence of * pair sums has strictly lower variance than summing raw lags). The sum stops at the first pair * whose clamped value is not positive; * $$\mathrm{ESS} = \frac{N}{-1 + 2 \sum_m \Gamma_m},$$ * or $\mathrm{ESS} = N$ ($\tau = 1$) if even the first pair is non-positive (sum = 0) -- that * $-1 + 2 \cdot 0 = -1$ would otherwise give a nonsensical negative $\tau$. Anchoring the * pairing at lag 0 means $\rho_1$ alone can never prematurely truncate the sum: * $\Gamma_0 = 1 + \rho_1$ is non-positive only when $\rho_1 \le -1$, an extreme case, unlike the * old single-lag rule which underestimated $\tau$ (overestimated ESS) whenever an otherwise * well-mixing chain had one merely-negative early lag. Built directly on the same accumulators * as ac() and statistics() — no additional accumulator state. If the first pair itself is * already non-positive ($\rho_1 \le -1$, an extreme case), $\mathrm{ESS} = N$ exactly: a * legitimate output of this truncation rule when the sampler genuinely produces that strong an * anti-correlation, not necessarily a sign of a broken sampler. A milder resonance -- e.g. HMC's * fixed pathLength resonating with the target's geometry, see hmc.js -- typically lands well * short of that $\rho_1 \le -1$ boundary and instead inflates or deflates ESS relative to the * raw sample count without saturating to $N$ exactly. See #974: verified against a brute-force * autocorrelation over the raw iterate() sequence, which confirmed the online accumulator is * exact and the anti-correlation is genuine. * * A fully stuck (zero-variance) chain is a distinct case from the above: ac()'s divisor is the * population variance, so a chain that never moves produces $0/0 = \mathrm{NaN}$ at every lag * including lag 0. That NaN is not a signal of non-positive autocorrelation to saturate on — it * means the chain contributed zero effectively-independent samples, so ess() reports 1 rather * than $N$ (the $n = 0$ case, no observations at all yet, is unaffected and still reports 0). * * solutions/testing/2026-07-18-1641-ess-geyer-ipsm-pairing-offset-self-consistent-wrong-tests.md * — the pairing must start at lag 0 (anchored by rho[0] = 1), not lag 1; an off-by-one-lag * version of this method passed every hand-derived test because the tests were derived by hand * using the same wrong pairing. * * @method ess * @memberof ran.mc.MCMC * @returns {number[]} Array of effective sample sizes, one per dimension. */ ess(): number[]; /** * Performs a single iteration, updates accumulators, and optionally calls a callback. * * Advanced/low-level: most callers should use [warmUp]{@link ran.mc.MCMC#warmUp} and * [sample]{@link ran.mc.MCMC#sample} instead, which drive `iterate()` internally. Calling it manually is * for cases that need per-step control (e.g. live progress plotting, custom stopping rules). * `sample()` resets the accumulators before it starts collecting, but interleaving manual * `iterate()` calls with `warmUp()`/`sample()` otherwise does not — mixing manual draws in can * blend adaptation-phase and equilibrium-phase observations into `statistics()`, `ar()`, and `ac()`. * * @method iterate * @memberof ran.mc.MCMC * @param {Function=} callback Called with (x, accepted) after each iteration. * @param {boolean=} warmUp Whether the iteration is part of warm-up. Default is false. * @returns {{x: number[], accepted: boolean, alpha?: number}} Result of the iteration. `alpha` * is optional and subclass-defined (see decisions/0025-hmc-iter-alpha-field.md). */ iterate(callback?: Function | undefined, warmUp?: boolean | undefined): { x: number[]; accepted: boolean; alpha?: number; }; /** * Carries out the warm-up phase. Runs batches of 10K iterations, adapts internal parameters * via _adjust(), and tunes the thinning interval using the online autocorrelation estimate. * * decisions/0024-mcmc-warmup-convergence-strategy.md — deliberately fixed-length, no convergence-triggered * early stop: no signal computable from a single chain can distinguish "converged" from "stuck". Gate * convergence on gelmanRubin() across multiple independently-seeded chains instead. * * @method warmUp * @memberof ran.mc.MCMC * @param {Function=} progress Called with the percentage complete (0–100) after each batch. * @param {number=} maxBatches Number of warm-up batches. Default is 100. */ warmUp(progress?: Function | undefined, maxBatches?: number | undefined): void; /** * Samples from the target density. Resets accumulators so that statistics() reflects the * sampling phase only, and ar() reflects at most its last arWindow draws (see ADR-0021). Thins * the chain by samplingRate (set during warm-up). * * @method sample * @memberof ran.mc.MCMC * @param {Function=} progress Called with the integer percentage complete (0–99), once per percent. * @param {number=} size Number of samples to collect. Default is 1000. * @returns {number[][]} Array of sampled states. */ sample(progress?: Function | undefined, size?: number | undefined): number[][]; /** * Returns the subclass's internal variables. Must be overridden. * * @method _internal * @memberof ran.mc.MCMC * @returns {Object} Object containing the internal variables. * @protected * @ignore */ protected _internal(): any; /** * Reseeds a subclass-owned proposal/momentum generator (`this._q`) and recomputes a * subclass-owned cached log-density (`this.lastLnp`) against the current `this.x`. Explicitly * called by a subclass's own `seed()` override — never invoked automatically by base-class * control flow — so subclasses without a `_q`/`lastLnp` pair (e.g. Gibbs, Slice) are * unaffected. * * @method _reseedCachedLogDensity * @memberof ran.mc.MCMC * @param {number|string} value The seed value passed to the sampler's `seed()` method. * @protected * @ignore */ protected _reseedCachedLogDensity(value: number | string): void; /** * Restores Robbins-Monro dual-averaging state (Hoffman & Gelman 2014 S3.2) shared by HMC and * NUTS: `_daMu` the shrinkage target, `_daHbar` the running acceptance-probability-deviation * statistic, `_daLogEpsBar` the smoothed log step size, `_daT` the iteration counter. Explicitly * called by each subclass's own constructor after `this._stepSize` is set — never invoked * automatically by base-class control flow — so subclasses without dual averaging (RWM, * AdaptiveMetropolis, Slice, MALA, Gibbs) are unaffected. Restoring these (rather than always * restarting from t=0) is what makes a mid-warm-up resume's dual averaging continue from the * exact same trajectory — decisions/0035-mcmc-exact-stream-reproducible-resume.md. * * @method _restoreDualAveraging * @memberof ran.mc.MCMC * @protected * @ignore */ protected _restoreDualAveraging(): void; /** * Performs a single iteration. Must be overridden. * * @method _iter * @memberof ran.mc.MCMC * @param {number[]} x Current state of the Markov chain. * @param {boolean=} warmUp Whether the iteration takes place during warm-up. Default is false. * @returns {{x: number[], accepted: boolean, alpha?: number}} New state and whether it was * accepted. `alpha` is optional and subclass-defined — e.g. HMC returns the continuous * Metropolis acceptance probability for dual-averaging step-size adaptation (see * decisions/0025-hmc-iter-alpha-field.md). Ignored by the base class's own consumer of this * return value. * @protected * @ignore */ protected _iter(x: number[], warmUp?: boolean | undefined): { x: number[]; accepted: boolean; alpha?: number; }; /** * Adjusts internal parameters after an iteration. Must be overridden. * * @method _adjust * @memberof ran.mc.MCMC * @param {Object} i Result of the last iteration. * @protected * @ignore */ protected _adjust(i: any): void; _thinningLag(): number; _adjustSamplingRate(lag: any): void; _initAccumulators(): void; _updateAccumulators(x: any, accepted: any): void; static _validateDim(dim: any): void; static _validateMaxLag(maxLag: any): void; static _validateCombinedFootprint(dim: any, maxLag: any): void; static _validateArWindow(arWindow: any): void; static _validatePrngState(state: any, label: any): void; static _isValidPrngState(state: any): boolean; static _restoreQPrng(q: any, prngQ: any, label: any): void; static _resolveResumedField(resumed: any, key: any, fallback: any): any; static _validateFiniteScalar(value: any, label: any): void; static _validateNonNegativeInteger(value: any, label: any): void; static _validateFiniteVector(value: any, dim: any, label: any): void; static _validateFiniteMatrix(value: any, dim: any, label: any): void; static _isFiniteVectorOfLength(value: any, length: any): boolean; static _isFiniteMatrixOfDim(value: any, dim: any): boolean; static _resolveConfig(config: any): { dim: any; maxLag: any; arWindow: any; }; static _isPositiveInteger(dim: any): boolean; static get _MAX_DIM(): number; static get _MAX_LAG(): number; static get _MAX_AR_WINDOW(): number; static get _MAX_ACCUMULATOR_BYTES(): number; }