Sequential Monte Carlo and particle MCMC
Importance sampling in stages: move particles, reweight, resample. Learn sequential Monte Carlo as a general tool, why weights collapse and paths degenerate, and how a particle filter's likelihood estimate makes exact MCMC possible.
What runs in CodeSplash
- INF015Sequential Monte Carlo (SMC) and particle filtering Runs in CodeSplash
- INF016Particle Markov chain Monte Carlo (PMCMC) Partly runs in CodeSplash
- Particle filter (state-space model with PMMH) Verified in Python and R
You will be able to
- Write a sequential importance weight and explain when resampling resets it
- Read weight ESS, likelihood-estimate spread and unique ancestors as particle diagnostics
- State the condition that makes particle marginal Metropolis–Hastings exact
- Explain why a noisy likelihood estimate makes PMMH sticky
Importance sampling, one step at a time
ReadImportance sampling fails when the target is far from any simple proposal. Sequential Monte Carlo (SMC) gets there in stages through a sequence of distributions, each close to the last: the posterior of a hidden state after each new observation (a particle filterParticle filterTracks a hidden state with many weighted guesses: each step moves them by the model and reweights them by the new observation.), a prior slowly tempered into a posterior, or a dataset growing one row at a time. A cloud of weighted particles is carried from one stage to the next.
Without resampling, each particle's weight is multiplied by an incremental factor:
Reference · INF015 · Runs in CodeSplashSequential Monte Carlo (SMC) and particle filteringApproximates a sequence of probability distributions using particles, importance weights, and resampling. Particle filtering applies SMC to latent states observed over time;Move, reweight, resample
ReadThe bootstrap filter proposes from the model's own transition , so only the observation likelihood is left in the weight. After resampling (draw particles in proportion to their weights, then reset all weights to equal), the old weights must not be multiplied in again; ancestor selection already used them.
In the reference's one-step example with five particles, the weight ESS is 3.19 of 5, and the average incremental weight, 0.423, is that step's factor of the likelihood estimate. Multiply those factors across steps to estimate ; averaging log likelihood estimates is a different, biased operation.
Weights collapse, paths degenerate
ReadTwo failures to watch:
- Weight degeneracyWeight degeneracyWhen a few importance weights dominate, so most draws or particles count for nothing and the effective sample size collapses.. An informative observation puts nearly all weight on a few particles. Resampling resets the weights but copies those few particles; it can't recreate a region no particle visited. More particles or a better proposal help.
- Path degeneracy. After many resampling steps, every surviving particle descends from a handful of early ancestors. The current state is tracked well; the whole history (smoothing) is not.
Weight ESS can look fine right after resampling even when diversity is poor, so also watch unique ancestors and the spread of repeated likelihood estimates.
Compare plain importance weights with tempered SMC on the same target and watch the effective sample size.
EExplorable · Importance weights and SMC
When do importance weights collapse onto a few particles, and how does tempering with resampling keep them useful?
Method
Weight once, or move from the proposal to the target in small steps, resampling as needed.
The target is a normal with this mean and SD 1 in every dimension.
The proposal is a normal centered at 0 with this spread.
Weights multiply across dimensions, so mismatch compounds.
Draws from the proposal.
SMC only: how many small steps from proposal to target.
- Target (one coordinate)
- Proposal
Effective sample size
64.1%
of 300 particles, from one round of weighting.
- ESS share (lowest)
- 0.641
- Largest weight
- 0.007
- Estimate of the mean
- 1.011
- Log evidence (truth 0)
- 0.044
- Resampling steps
- 0
- Puzzle: In 10 or more dimensions, keep the lowest ESS above 20% of the particles.
- Puzzle: In one dimension, find a proposal that leaves plain importance sampling with an ESS under 10% of the particles.
Plain importance sampling with 300 particles in 1 dimension: the effective sample size is 64.1% of the particles, the largest weight is 0.007, the estimate of the mean is 1.01 (truth 1.00) and the log evidence is 0.04 (truth 0).
A filter in CodeSplash
ReadParticle filter (state-space model with PMMH) runs a bootstrap filter on built-in state-space models. On the Nile flows with a local-level model, a linear-Gaussian case where the Kalman filter gives the exact answer, the check is direct.
A local level particle filter of flow (100 steps, 800 particles; parameters set) has log-likelihood -638.78 (SD 0.22 over five runs); the exact Kalman value is -638.66. The last filtered level is 794.2 (90% band 682.5 to 897.2).
- Log-likelihood (particle)
- −638.78
- Log-likelihood SD
- 0.2218
- Log-likelihood (Kalman)
- −638.66
Plots
View data
| series | year | flow |
|---|---|---|
| Observed | 1,871 | 1,120 |
| Observed | 1,872 | 1,160 |
| Observed | 1,873 | 963 |
| Observed | 1,874 | 1,210 |
| Observed | 1,875 | 1,160 |
| Observed | 1,876 | 1,160 |
| Observed | 1,877 | 813 |
| Observed | 1,878 | 1,230 |
| Observed | 1,879 | 1,370 |
| Observed | 1,880 | 1,140 |
| Observed | 1,881 | 995 |
| Observed | 1,882 | 935 |
| Observed | 1,883 | 1,110 |
| Observed | 1,884 | 994 |
| Observed | 1,885 | 1,020 |
| Observed | 1,886 | 960 |
| Observed | 1,887 | 1,180 |
| Observed | 1,888 | 799 |
| Observed | 1,889 | 958 |
| Observed | 1,890 | 1,140 |
| Observed | 1,891 | 1,100 |
| Observed | 1,892 | 1,210 |
| Observed | 1,893 | 1,150 |
| Observed | 1,894 | 1,250 |
| Observed | 1,895 | 1,260 |
| Observed | 1,896 | 1,220 |
| Observed | 1,897 | 1,030 |
| Observed | 1,898 | 1,100 |
| Observed | 1,899 | 774 |
| Observed | 1,900 | 840 |
| Observed | 1,901 | 874 |
| Observed | 1,902 | 694 |
| Observed | 1,903 | 940 |
| Observed | 1,904 | 833 |
| Observed | 1,905 | 701 |
| Observed | 1,906 | 916 |
| Observed | 1,907 | 692 |
| Observed | 1,908 | 1,020 |
| Observed | 1,909 | 1,050 |
| Observed | 1,910 | 969 |
| Observed | 1,911 | 831 |
| Observed | 1,912 | 726 |
| Observed | 1,913 | 456 |
| Observed | 1,914 | 824 |
| Observed | 1,915 | 702 |
| Observed | 1,916 | 1,120 |
| Observed | 1,917 | 1,100 |
| Observed | 1,918 | 832 |
| Observed | 1,919 | 764 |
| Observed | 1,920 | 821 |
| Observed | 1,921 | 768 |
| Observed | 1,922 | 845 |
| Observed | 1,923 | 864 |
| Observed | 1,924 | 862 |
| Observed | 1,925 | 698 |
| Observed | 1,926 | 845 |
| Observed | 1,927 | 744 |
| Observed | 1,928 | 796 |
| Observed | 1,929 | 1,040 |
| Observed | 1,930 | 759 |
First 60 of 300 rows.
Assumptions
- Model form — Assumed, not checked from the data: the series follows a local level model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 800 particles gave log-likelihoods with SD 0.22 (≤ 1).
- MCMC mixing — The parameters were set, not estimated, so there is no MCMC chain.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123 | — | — | — | set |
| Level noise SD | 38 | — | — | — | set |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (800 particles) | −638.78 |
| SD over five filter runs | 0.2218 |
| Exact (Kalman filter) | −638.66 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1124.72 | 966.78 | 1286.22 | 1111.77 | 1013.35 | 1220.32 |
| 1872 | 1,160 | 1138.90 | 1005.35 | 1272.49 | 1118.30 | 1019.78 | 1221.07 |
| 1873 | 963 | 1078.42 | 969.96 | 1192.31 | 1113.15 | 1032.17 | 1207.71 |
| 1874 | 1,210 | 1117.16 | 1001.09 | 1221.86 | 1122.46 | 1045.84 | 1211.80 |
| 1875 | 1,160 | 1129.76 | 1018.02 | 1236.48 | 1123.05 | 1034.74 | 1210.95 |
| 1876 | 1,160 | 1140.10 | 1030.04 | 1248.14 | 1111.56 | 1024.74 | 1190.32 |
| 1877 | 813 | 1055.18 | 970.36 | 1158.20 | 1099.60 | 1015.59 | 1189.15 |
| 1878 | 1,230 | 1100.10 | 999.54 | 1206.40 | 1108.19 | 1031.15 | 1202.77 |
| 1879 | 1,370 | 1171.20 | 1067.43 | 1278.13 | 1119.75 | 1028.81 | 1219.10 |
| 1880 | 1,140 | 1163.19 | 1056.74 | 1268.41 | 1098.47 | 1028.21 | 1189.15 |
| 1881 | 995 | 1116.60 | 1003.11 | 1221.08 | 1077.45 | 999.17 | 1163.69 |
| 1882 | 935 | 1068.61 | 974.68 | 1171.89 | 1060.38 | 986.41 | 1140.51 |
| 1883 | 1,110 | 1079.32 | 975.10 | 1182.95 | 1061.56 | 968.48 | 1142.51 |
| 1884 | 994 | 1055.04 | 939.76 | 1156.74 | 1053.03 | 958.54 | 1132.80 |
| 1885 | 1,020 | 1047.49 | 943.73 | 1152.87 | 1048.23 | 973.22 | 1139.25 |
| 1886 | 960 | 1025.07 | 914.65 | 1131.21 | 1040.59 | 982.27 | 1125.28 |
| 1887 | 1,180 | 1069.06 | 964.04 | 1184.66 | 1049.97 | 981.23 | 1124.34 |
| 1888 | 799 | 999.17 | 899.40 | 1103.00 | 1033.04 | 966.53 | 1091.04 |
| 1889 | 958 | 990.00 | 889.01 | 1093.02 | 1048.25 | 971.66 | 1135.40 |
| 1890 | 1,140 | 1022.67 | 927.07 | 1120.96 | 1070.56 | 984.97 | 1130.77 |
| 1891 | 1,100 | 1043.13 | 941.74 | 1142.17 | 1089.01 | 1016.96 | 1153.97 |
| 1892 | 1,210 | 1090.00 | 983.56 | 1188.22 | 1104.06 | 1024.51 | 1176.62 |
| 1893 | 1,150 | 1107.53 | 1000.21 | 1208.66 | 1110.78 | 1052.65 | 1181.41 |
| 1894 | 1,250 | 1141.94 | 1043.12 | 1240.10 | 1111.23 | 1045.32 | 1192.66 |
| 1895 | 1,260 | 1171.37 | 1072.40 | 1268.24 | 1101.99 | 1020.52 | 1169.80 |
| 1896 | 1,220 | 1184.31 | 1076.68 | 1286.21 | 1077.62 | 1016.84 | 1155.66 |
| 1897 | 1,030 | 1143.91 | 1035.03 | 1253.36 | 1038.98 | 985.36 | 1117.86 |
| 1898 | 1,100 | 1132.47 | 1034.80 | 1238.32 | 995.42 | 929.86 | 1069.80 |
| 1899 | 774 | 1046.82 | 932.08 | 1142.12 | 955.49 | 908.57 | 1019.99 |
| 1900 | 840 | 994.77 | 889.16 | 1094.56 | 918.69 | 857.98 | 984.45 |
| 1901 | 874 | 963.24 | 861.87 | 1067.84 | 895.83 | 813.53 | 961.98 |
| 1902 | 694 | 896.32 | 781.72 | 999.72 | 874.21 | 773.58 | 953.12 |
| 1903 | 940 | 907.42 | 799.06 | 1012.17 | 865.29 | 782.03 | 937.96 |
| 1904 | 833 | 885.40 | 777.11 | 993.23 | 855.96 | 786.67 | 936.52 |
| 1905 | 701 | 833.53 | 722.79 | 942.36 | 850.30 | 774.69 | 926.13 |
| 1906 | 916 | 855.81 | 753.03 | 959.32 | 859.97 | 788.90 | 923.11 |
| 1907 | 692 | 810.20 | 713.53 | 910.55 | 857.52 | 765.78 | 932.64 |
| 1908 | 1,020 | 865.48 | 757.08 | 971.43 | 877.24 | 797.25 | 971.43 |
| 1909 | 1,050 | 916.60 | 810.35 | 1015.70 | 879.71 | 795.87 | 966.38 |
| 1910 | 969 | 932.43 | 830.19 | 1033.62 | 861.96 | 767.61 | 929.82 |
First 40 of 100 rows.
- A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are resampled systematically at every step.
- Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.
- The first hidden state starts at the first observation with the series' variance; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.
The exact R script · R R version 4.5.1 (2025-06-13)
# Particle filter (state-space model with PMMH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.particle_filter 1.0.0 · spec d3fb0d755c492ddb
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_nile.parquet", col_select = c("flow", "year")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("flow", "year")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("flow", "year")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "flow"
TIME <- "year"
TEMPORAL <- FALSE
MODEL <- "local_level"
ESTIMATE <- "fixed"
N_FINAL <- as.integer(800)
N_PMMH <- as.integer(200)
ITERATIONS <- as.integer(2000)
BURN_IN <- as.integer(500)
THRESHOLD <- if ("always" == "always") 1 else 0.5 # resample when ESS < threshold * N
SMOOTH <- TRUE
SMOOTH_PATHS <- as.integer(100)
SEED <- 42
FIXED <- list(sigma_obs = 123, sigma_level = 38, sigma_slope = NULL,
mu = NULL, phi = NULL, sigma = NULL)
d <- df
if (!is.null(TIME)) d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
rownames(d) <- NULL
y_raw <- as.numeric(d[[VALUE]])
cs_check_rows(length(y_raw), 10, "A particle filter")
cs_check_not_constant(y_raw, VALUE)
if (ESTIMATE == "pmmh" && BURN_IN >= ITERATIONS)
cs_error("CS_E_INVALID_OPTION", option = "Burn-in", allowed = sprintf("fewer than the %d MCMC iterations", ITERATIONS), value = BURN_IN)
y_mean <- mean(y_raw)
y <- if (MODEL == "stochastic_volatility") y_raw - y_mean else y_raw # the volatility model describes centered returns
TT <- length(y)
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else seq_len(TT)
pnames <- cs_pf_param_names(MODEL)
LABELS <- c(sigma_obs = "Observation noise SD", sigma_level = "Level noise SD", sigma_slope = "Slope noise SD",
mu = "Mean log-variance μ", phi = "Persistence φ", sigma = "Volatility of volatility σ")
MODEL_LABEL <- c(local_level = "local level", local_trend = "local linear trend", stochastic_volatility = "stochastic volatility")[[MODEL]]
start <- cs_pf_defaults(MODEL, y)
# %% Parameters: PMMH (Andrieu, Doucet & Holenstein 2010) or set by hand
values <- list()
param_rows <- list()
chain_nat <- NULL
mcmc <- NULL
params <- list()
if (ESTIMATE == "pmmh") {
mcmc <- cs_pf_pmmh(MODEL, y, start, N_PMMH, ITERATIONS, BURN_IN, SEED, THRESHOLD)
chain_nat <- t(apply(mcmc$chain, 1, function(row) unlist(cs_pf_from_free(MODEL, row)[pnames])))
kept_nat <- chain_nat[(BURN_IN + 1):ITERATIONS, , drop = FALSE]
ess_all <- numeric(0)
for (j in seq_along(pnames)) {
k <- pnames[j]
colv <- kept_nat[, j]
est <- mean(colv)
qq <- stats::quantile(colv, c(0.05, 0.95), type = 7, names = FALSE)
e <- cs_pf_ess(colv)
ess_all <- c(ess_all, e)
params[[k]] <- est
values[sprintf("param[%s]", k)] <- list(est)
values[sprintf("param_lo[%s]", k)] <- list(qq[1])
values[sprintf("param_hi[%s]", k)] <- list(qq[2])
values[sprintf("param_ess[%s]", k)] <- list(e)
param_rows[[length(param_rows) + 1]] <- list(param = LABELS[[k]], estimate = est, lo = qq[1], hi = qq[2], ess = e, source = "PMMH posterior mean")
}
values$iterations <- ITERATIONS
values$burn_in <- BURN_IN
values$acceptance <- mcmc$acceptance
values$ess_min <- min(ess_all)
} else {
for (k in pnames) {
v <- FIXED[[k]]
params[[k]] <- if (!is.null(v)) as.numeric(v) else start[[k]]
values[sprintf("param[%s]", k)] <- list(params[[k]])
param_rows[[length(param_rows) + 1]] <- list(param = LABELS[[k]], estimate = params[[k]], lo = NULL, hi = NULL, ess = NULL,
source = if (!is.null(v)) "set" else "from the data")
}
values["iterations"] <- list(NULL)
values["burn_in"] <- list(NULL)
values["acceptance"] <- list(NULL)
values["ess_min"] <- list(NULL)
}
chk <- tryCatch({
cs_pf_check_params(MODEL, params)
NULL
}, error = function(e) conditionMessage(e))
if (!is.null(chk)) cs_error("CS_E_INVALID_OPTION", option = "Model parameters", allowed = "valid values for the model", value = chk)
# %% Final filter at the estimates, repeated runs for the likelihood's noise, smoother, Kalman
B <- cs_pf_block_size(MODEL, N_FINAL, TT)
run <- cs_pf_filter(MODEL, y, params, N_FINAL, cs_runif(cs_rng(SEED + 1), B), THRESHOLD, store = SMOOTH)
if (run$failed) cs_error("CS_E_UNDEFINED", what = "The particle filter", reason = "every particle got zero weight at some step; check the parameters")
lls <- c(run$loglik, vapply(1:4, function(r) cs_pf_filter(MODEL, y, params, N_FINAL, cs_runif(cs_rng(SEED + 10 + r), B), THRESHOLD, summarize = FALSE)$loglik, numeric(1)))
ll_sd <- stats::sd(lls)
sm <- if (SMOOTH) cs_pf_smooth(MODEL, run, params, SMOOTH_PATHS, SEED + 2) else NULL
kal <- cs_pf_kalman(MODEL, y, params)
if (MODEL == "stochastic_volatility") {
vol <- function(h) exp(h / 2) # volatility = exp(h/2); quantiles map exactly
f_mid <- vol(run$median[, 1]); f_lo <- vol(run$lo[, 1]); f_hi <- vol(run$hi[, 1])
s_mid <- if (!is.null(sm)) vol(sm$mean[, 1]) else NULL
s_lo <- if (!is.null(sm)) vol(sm$lo[, 1]) else NULL
s_hi <- if (!is.null(sm)) vol(sm$hi[, 1]) else NULL
} else {
f_mid <- run$mean[, 1]; f_lo <- run$lo[, 1]; f_hi <- run$hi[, 1]
s_mid <- if (!is.null(sm)) sm$mean[, 1] else NULL
s_lo <- if (!is.null(sm)) sm$lo[, 1] else NULL
s_hi <- if (!is.null(sm)) sm$hi[, 1] else NULL
}
values$n_obs <- TT
values$model <- MODEL
values$model_label <- MODEL_LABEL
values$estimate <- ESTIMATE
values$particles <- N_FINAL
values$loglik <- run$loglik
values$loglik_sd <- ll_sd
values["kalman_loglik"] <- list(if (!is.null(kal)) kal$loglik else NULL)
values$mean_ess <- run$mean_ess
values$resamples <- run$resamples
values$last_state <- f_mid[TT]
values$last_state_lo <- f_lo[TT]
values$last_state_hi <- f_hi[TT]
values["kalman_last_state"] <- list(if (!is.null(kal)) kal$mean[TT, 1] else NULL)
values["y_mean"] <- list(if (MODEL == "stochastic_volatility") y_mean else NULL)
# %% Assumptions
assumptions <- list(list(key = "model_form", label = "Model form", status = "info",
detail = sprintf("Assumed, not checked from the data: the series follows a %s model with Gaussian noise and equally spaced steps.", MODEL_LABEL)))
if (ll_sd <= 1) {
assumptions[[2]] <- list(key = "particle_count", label = "Enough particles", status = "pass",
detail = sprintf("Five filter runs with %d particles gave log-likelihoods with SD %.2f (≤ 1).", N_FINAL, ll_sd))
} else {
assumptions[[2]] <- list(key = "particle_count", label = "Enough particles", status = "warn",
detail = sprintf("Five filter runs with %d particles gave log-likelihoods with SD %.2f; use more particles for a steadier estimate.", N_FINAL, ll_sd))
}
if (ESTIMATE == "pmmh") {
acc <- mcmc$acceptance
emin <- values$ess_min
ok <- acc >= 0.1 && acc <= 0.5 && emin >= 100
assumptions[[3]] <- list(key = "mixing", label = "MCMC mixing", status = if (ok) "pass" else "warn",
detail = paste0(sprintf("The chain accepted %s of proposals after burn-in; the smallest effective sample size is %s", sprintf("%.0f%%", 100 * acc), sprintf("%.0f", emin)),
if (ok) "." else ". Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low."))
} else {
assumptions[[3]] <- list(key = "mixing", label = "MCMC mixing", status = "info", detail = "The parameters were set, not estimated, so there is no MCMC chain.")
}
# %% Charts
charts <- list()
xkind <- if (TEMPORAL) "temporal" else "numeric"
xname <- if (is.null(TIME)) "step" else TIME
if (MODEL == "stochastic_volatility") {
charts[[1]] <- cs_chart("states", "volatility-band", sprintf("%s (centered) with the filtered volatility exp(h/2)", VALUE), list(
time = cs_col(xname, labels, kind = xkind), sigma = cs_col("volatility", f_mid), value = cs_col(VALUE, y),
mean = cs_col("mean", rep(0, TT))))
} else {
gnames <- c("Observed", "Filtered level")
gvals <- list(y, f_mid)
if (!is.null(sm)) {
gnames <- c(gnames, "Smoothed level")
gvals[[3]] <- s_mid
}
charts[[1]] <- cs_chart("states", "series-line", sprintf("%s with the hidden level", VALUE), list(
x = cs_col(xname, rep(labels, times = length(gnames)), kind = xkind),
y = cs_col(VALUE, unlist(gvals)),
group = cs_col("series", rep(gnames, each = TT), kind = "categorical")))
}
if (!is.null(mcmc)) {
stp <- max(1L, ITERATIONS %/% 500L)
it_idx <- seq(1L, ITERATIONS, by = stp)
charts[[length(charts) + 1]] <- cs_chart("trace", "series-line", "PMMH chains (every parameter, natural scale)", list(
x = cs_col("iteration", rep(as.numeric(it_idx), times = length(pnames))),
y = cs_col("value", as.vector(chain_nat[it_idx, , drop = FALSE])),
group = cs_col("parameter", rep(unname(LABELS[pnames]), each = length(it_idx)), kind = "categorical")))
for (j in seq_along(pnames)) {
k <- pnames[j]
colv <- chain_nat[(BURN_IN + 1):ITERATIONS, j]
grid <- cs_pf_density_grid(colv)
post <- cs_pf_kde(colv, grid)
prior <- cs_pf_prior_density(mcmc$prior[[j]], grid)
charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", k), "prior-posterior", sprintf("%s: prior and PMMH posterior", LABELS[[k]]), list(
x = cs_col(LABELS[[k]], c(grid, grid)), density = cs_col("density", c(prior, post)),
curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
}
# %% Tables
lik_rows <- list(list(what = sprintf("Particle estimate (%d particles)", N_FINAL), value = run$loglik),
list(what = "SD over five filter runs", value = ll_sd))
if (!is.null(kal)) lik_rows[[3]] <- list(what = "Exact (Kalman filter)", value = kal$loglik)
tables <- list(
list(key = "parameters", title = "Parameters",
columns = list(list(key = "param", label = "Parameter", type = "string"), list(key = "estimate", label = "Value", type = "number"),
list(key = "lo", label = "5%", type = "number"), list(key = "hi", label = "95%", type = "number"),
list(key = "ess", label = "Effective draws", type = "number"), list(key = "source", label = "Source", type = "string")),
rows = param_rows),
list(key = "likelihood", title = "Log-likelihood",
columns = list(list(key = "what", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = lik_rows))
CAP <- 2000
st_label <- if (MODEL == "stochastic_volatility") "volatility" else "level"
state_rows <- lapply(seq_len(min(TT, CAP)), function(t) {
r <- list(time = as.character(labels[[t]]), observed = y_raw[t], filtered = f_mid[t], f_lo = f_lo[t], f_hi = f_hi[t])
if (!is.null(sm)) {
r$smoothed <- s_mid[t]
r$s_lo <- s_lo[t]
r$s_hi <- s_hi[t]
}
if (MODEL == "local_trend") r$slope <- run$mean[t, 2]
r
})
state_cols <- list(list(key = "time", label = if (is.null(TIME)) "Step" else TIME, type = "string"), list(key = "observed", label = VALUE, type = "number"),
list(key = "filtered", label = paste0("Filtered ", st_label, if (MODEL == "stochastic_volatility") " (median)" else ""), type = "number"),
list(key = "f_lo", label = "5%", type = "number"), list(key = "f_hi", label = "95%", type = "number"))
if (!is.null(sm)) {
state_cols <- c(state_cols, list(list(key = "smoothed", label = paste0("Smoothed ", st_label), type = "number"),
list(key = "s_lo", label = "5% (smoothed)", type = "number"), list(key = "s_hi", label = "95% (smoothed)", type = "number")))
}
if (MODEL == "local_trend") state_cols <- c(state_cols, list(list(key = "slope", label = "Filtered slope", type = "number")))
tables[[3]] <- list(key = "states", title = paste0("Hidden state at each step", if (TT > CAP) sprintf(" (first %d of %d)", CAP, TT) else ""),
columns = state_cols, rows = state_rows)
# %% Result
g4 <- function(v) sprintf("%.4g", v)
est_txt <- if (ESTIMATE == "pmmh") "estimated by PMMH" else "set"
summary <- paste0(sprintf("A %s particle filter of %s (%d steps, %d particles; parameters %s) has log-likelihood %.2f (SD %.2f over five runs)",
MODEL_LABEL, VALUE, TT, N_FINAL, est_txt, run$loglik, ll_sd),
if (!is.null(kal)) sprintf("; the exact Kalman value is %.2f", kal$loglik) else "",
sprintf(". The last filtered %s is %s (90%% band %s to %s).", st_label, g4(f_mid[TT]), g4(f_lo[TT]), g4(f_hi[TT])))
notes <- c(paste0("A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are ",
"resampled systematically ", if (THRESHOLD >= 1) "at every step." else "when the effective sample size drops below half the particles."),
"Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.")
if (MODEL == "stochastic_volatility") {
notes <- c(notes, sprintf("Returns are centered (mean %s removed); the volatility is exp(h/2) and its band maps h's quantiles.", g4(y_mean)))
} else {
notes <- c(notes, paste0("The first hidden state starts at the first observation with the series' variance",
if (MODEL == "local_trend") " (slope at 0 with the differences' variance)" else "",
"; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches."))
}
if (ESTIMATE == "pmmh") {
notes <- c(notes, paste0(sprintf("PMMH ran %d iterations (%d burn-in, step size adapted during burn-in) with %d particles per step; priors: normal on log σ ", ITERATIONS, BURN_IN, N_PMMH),
"centered at the data-based value (SD 2)", if (MODEL == "stochastic_volatility") ", normal on μ (SD 3), uniform φ on (−1, 1)" else "",
". The final filter uses the posterior means."))
}
statistics <- list(list(key = "loglik", label = "Log-likelihood (particle)", value = run$loglik), list(key = "loglik_sd", label = "Log-likelihood SD", value = ll_sd))
if (!is.null(kal)) statistics[[length(statistics) + 1]] <- list(key = "kalman_loglik", label = "Log-likelihood (Kalman)", value = kal$loglik)
if (!is.null(mcmc)) statistics[[length(statistics) + 1]] <- list(key = "acceptance", label = "Acceptance rate", value = mcmc$acceptance)
cs_publish(list(
method = "ts.particle_filter",
methodVersion = "1.0.0",
title = "Particle filter",
engine = cs_engine_info("stats", "nanoparquet"),
n = TT,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
A local level particle filter of flow (100 steps, 800 particles; parameters set) has log-likelihood -638.78 (SD 0.22 over five runs); the exact Kalman value is -638.66. The last filtered level is 794.2 (90% band 682.5 to 897.2).
- Log-likelihood (particle)
- −638.78
- Log-likelihood SD
- 0.2218
- Log-likelihood (Kalman)
- −638.66
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Model form — Assumed, not checked from the data: the series follows a local level model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 800 particles gave log-likelihoods with SD 0.22 (≤ 1).
- MCMC mixing — The parameters were set, not estimated, so there is no MCMC chain.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123 | — | — | — | set |
| Level noise SD | 38 | — | — | — | set |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (800 particles) | −638.78 |
| SD over five filter runs | 0.2218 |
| Exact (Kalman filter) | −638.66 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1124.72 | 966.78 | 1286.22 | 1111.77 | 1013.35 | 1220.32 |
| 1872 | 1,160 | 1138.90 | 1005.35 | 1272.49 | 1118.30 | 1019.78 | 1221.07 |
| 1873 | 963 | 1078.42 | 969.96 | 1192.31 | 1113.15 | 1032.17 | 1207.71 |
| 1874 | 1,210 | 1117.16 | 1001.09 | 1221.86 | 1122.46 | 1045.84 | 1211.80 |
| 1875 | 1,160 | 1129.76 | 1018.02 | 1236.48 | 1123.05 | 1034.74 | 1210.95 |
| 1876 | 1,160 | 1140.10 | 1030.04 | 1248.14 | 1111.56 | 1024.74 | 1190.32 |
| 1877 | 813 | 1055.18 | 970.36 | 1158.20 | 1099.60 | 1015.59 | 1189.15 |
| 1878 | 1,230 | 1100.10 | 999.54 | 1206.40 | 1108.19 | 1031.15 | 1202.77 |
| 1879 | 1,370 | 1171.20 | 1067.43 | 1278.13 | 1119.75 | 1028.81 | 1219.10 |
| 1880 | 1,140 | 1163.19 | 1056.74 | 1268.41 | 1098.47 | 1028.21 | 1189.15 |
| 1881 | 995 | 1116.60 | 1003.11 | 1221.08 | 1077.45 | 999.17 | 1163.69 |
| 1882 | 935 | 1068.61 | 974.68 | 1171.89 | 1060.38 | 986.41 | 1140.51 |
| 1883 | 1,110 | 1079.32 | 975.10 | 1182.95 | 1061.56 | 968.48 | 1142.51 |
| 1884 | 994 | 1055.04 | 939.76 | 1156.74 | 1053.03 | 958.54 | 1132.80 |
| 1885 | 1,020 | 1047.49 | 943.73 | 1152.87 | 1048.23 | 973.22 | 1139.25 |
| 1886 | 960 | 1025.07 | 914.65 | 1131.21 | 1040.59 | 982.27 | 1125.28 |
| 1887 | 1,180 | 1069.06 | 964.04 | 1184.66 | 1049.97 | 981.23 | 1124.34 |
| 1888 | 799 | 999.17 | 899.40 | 1103.00 | 1033.04 | 966.53 | 1091.04 |
| 1889 | 958 | 990.00 | 889.01 | 1093.02 | 1048.25 | 971.66 | 1135.40 |
| 1890 | 1,140 | 1022.67 | 927.07 | 1120.96 | 1070.56 | 984.97 | 1130.77 |
| 1891 | 1,100 | 1043.13 | 941.74 | 1142.17 | 1089.01 | 1016.96 | 1153.97 |
| 1892 | 1,210 | 1090.00 | 983.56 | 1188.22 | 1104.06 | 1024.51 | 1176.62 |
| 1893 | 1,150 | 1107.53 | 1000.21 | 1208.66 | 1110.78 | 1052.65 | 1181.41 |
| 1894 | 1,250 | 1141.94 | 1043.12 | 1240.10 | 1111.23 | 1045.32 | 1192.66 |
| 1895 | 1,260 | 1171.37 | 1072.40 | 1268.24 | 1101.99 | 1020.52 | 1169.80 |
| 1896 | 1,220 | 1184.31 | 1076.68 | 1286.21 | 1077.62 | 1016.84 | 1155.66 |
| 1897 | 1,030 | 1143.91 | 1035.03 | 1253.36 | 1038.98 | 985.36 | 1117.86 |
| 1898 | 1,100 | 1132.47 | 1034.80 | 1238.32 | 995.42 | 929.86 | 1069.80 |
| 1899 | 774 | 1046.82 | 932.08 | 1142.12 | 955.49 | 908.57 | 1019.99 |
| 1900 | 840 | 994.77 | 889.16 | 1094.56 | 918.69 | 857.98 | 984.45 |
| 1901 | 874 | 963.24 | 861.87 | 1067.84 | 895.83 | 813.53 | 961.98 |
| 1902 | 694 | 896.32 | 781.72 | 999.72 | 874.21 | 773.58 | 953.12 |
| 1903 | 940 | 907.42 | 799.06 | 1012.17 | 865.29 | 782.03 | 937.96 |
| 1904 | 833 | 885.40 | 777.11 | 993.23 | 855.96 | 786.67 | 936.52 |
| 1905 | 701 | 833.53 | 722.79 | 942.36 | 850.30 | 774.69 | 926.13 |
| 1906 | 916 | 855.81 | 753.03 | 959.32 | 859.97 | 788.90 | 923.11 |
| 1907 | 692 | 810.20 | 713.53 | 910.55 | 857.52 | 765.78 | 932.64 |
| 1908 | 1,020 | 865.48 | 757.08 | 971.43 | 877.24 | 797.25 | 971.43 |
| 1909 | 1,050 | 916.60 | 810.35 | 1015.70 | 879.71 | 795.87 | 966.38 |
| 1910 | 969 | 932.43 | 830.19 | 1033.62 | 861.96 | 767.61 | 929.82 |
First 40 of 100 rows.
- A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are resampled systematically at every step.
- Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.
- The first hidden state starts at the first observation with the series' variance; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Particle filter (state-space model with PMMH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.particle_filter 1.0.0 · spec d3fb0d755c492ddb
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import particle as pf # bootstrap filter, smoother, PMMH (twin of codesplashr cs_pf_*)
from codesplash.stats import ts
from codesplash.stats.rng import Rng
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_nile.parquet", columns=["flow", "year"])
n_input = len(df)
df = df.dropna(subset=["flow", "year"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["flow", "year"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "flow"
TIME = "year"
TEMPORAL = False
MODEL = "local_level"
ESTIMATE = "fixed"
N_FINAL = int(800)
N_PMMH = int(200)
ITERATIONS = int(2000)
BURN_IN = int(500)
THRESHOLD = 1.0 if "always" == "always" else 0.5 # resample when ESS < threshold · N
SMOOTH = True
SMOOTH_PATHS = int(100)
SEED = 42
FIXED = {"sigma_obs": 123, "sigma_level": 38, "sigma_slope": None,
"mu": None, "phi": None, "sigma": None}
d = df.sort_values(TIME, kind="mergesort").reset_index(drop=True) if TIME else df.reset_index(drop=True)
y_raw = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(y_raw), 10, "A particle filter")
check_not_constant(y_raw, VALUE)
if ESTIMATE == "pmmh" and BURN_IN >= ITERATIONS:
cs.cs_error("CS_E_INVALID_OPTION", option="Burn-in", allowed=f"fewer than the {ITERATIONS} MCMC iterations", value=BURN_IN)
y_mean = float(np.mean(y_raw))
y = y_raw - y_mean if MODEL == "stochastic_volatility" else y_raw # the volatility model describes centered returns
T = len(y)
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else list(range(1, T + 1))
names = pf.param_names(MODEL)
LABELS = {"sigma_obs": "Observation noise SD", "sigma_level": "Level noise SD", "sigma_slope": "Slope noise SD",
"mu": "Mean log-variance μ", "phi": "Persistence φ", "sigma": "Volatility of volatility σ"}
MODEL_LABEL = {"local_level": "local level", "local_trend": "local linear trend", "stochastic_volatility": "stochastic volatility"}[MODEL]
start = pf.defaults(MODEL, y)
# %% Parameters: PMMH (Andrieu, Doucet & Holenstein 2010) or set by hand
values = {}
param_rows = []
chain_nat = None
mcmc = None
if ESTIMATE == "pmmh":
mcmc = pf.pmmh(MODEL, y, start, N_PMMH, ITERATIONS, BURN_IN, SEED, THRESHOLD)
kept = mcmc["chain"][BURN_IN:]
chain_nat = np.array([[pf.from_free(MODEL, row)[k] for k in names] for row in mcmc["chain"]])
kept_nat = chain_nat[BURN_IN:]
params = {}
ess_all = []
for j, k in enumerate(names):
col = kept_nat[:, j]
est = float(np.mean(col))
lo, hi = (float(v) for v in np.quantile(col, [0.05, 0.95], method="linear"))
e = pf.ess(col)
ess_all.append(e)
params[k] = est
values[f"param[{k}]"], values[f"param_lo[{k}]"], values[f"param_hi[{k}]"], values[f"param_ess[{k}]"] = est, lo, hi, e
param_rows.append({"param": LABELS[k], "estimate": est, "lo": lo, "hi": hi, "ess": e, "source": "PMMH posterior mean"})
values.update({"iterations": ITERATIONS, "burn_in": BURN_IN, "acceptance": mcmc["acceptance"], "ess_min": float(min(ess_all))})
else:
params = {}
for k in names:
v = FIXED[k]
params[k] = float(v) if v is not None else float(start[k])
values[f"param[{k}]"] = params[k]
param_rows.append({"param": LABELS[k], "estimate": params[k], "lo": None, "hi": None, "ess": None,
"source": "set" if v is not None else "from the data"})
values.update({"iterations": None, "burn_in": None, "acceptance": None, "ess_min": None})
try:
pf.check_params(MODEL, params)
except ValueError as e:
cs.cs_error("CS_E_INVALID_OPTION", option="Model parameters", allowed="valid values for the model", value=str(e))
# %% Final filter at the estimates, repeated runs for the likelihood's noise, smoother, Kalman
B = pf.block_size(MODEL, N_FINAL, T)
run = pf.filter_run(MODEL, y, params, N_FINAL, Rng(SEED + 1).uniform(B), THRESHOLD, store=SMOOTH)
if run["failed"]:
cs.cs_error("CS_E_UNDEFINED", what="The particle filter", reason="every particle got zero weight at some step; check the parameters")
lls = [run["loglik"]] + [pf.filter_run(MODEL, y, params, N_FINAL, Rng(SEED + 10 + r).uniform(B), THRESHOLD, summarize=False)["loglik"] for r in range(1, 5)]
ll_sd = float(np.std(lls, ddof=1))
sm = pf.smooth(MODEL, run, params, SMOOTH_PATHS, SEED + 2) if SMOOTH else None
kal = pf.kalman(MODEL, y, params)
if MODEL == "stochastic_volatility":
vol = lambda h: np.exp(h / 2.0) # noqa: E731 volatility = exp(h/2); quantiles map exactly
f_mid, f_lo, f_hi = vol(run["median"][:, 0]), vol(run["lo"][:, 0]), vol(run["hi"][:, 0])
s_mid = vol(sm["mean"][:, 0]) if sm else None
s_lo, s_hi = (vol(sm["lo"][:, 0]), vol(sm["hi"][:, 0])) if sm else (None, None)
else:
f_mid, f_lo, f_hi = run["mean"][:, 0], run["lo"][:, 0], run["hi"][:, 0]
s_mid = sm["mean"][:, 0] if sm else None
s_lo, s_hi = (sm["lo"][:, 0], sm["hi"][:, 0]) if sm else (None, None)
values.update({
"n_obs": T, "model": MODEL, "model_label": MODEL_LABEL, "estimate": ESTIMATE, "particles": N_FINAL,
"loglik": run["loglik"], "loglik_sd": ll_sd, "kalman_loglik": kal["loglik"] if kal else None,
"mean_ess": run["mean_ess"], "resamples": run["resamples"],
"last_state": float(f_mid[-1]), "last_state_lo": float(f_lo[-1]), "last_state_hi": float(f_hi[-1]),
"kalman_last_state": float(kal["mean"][-1, 0]) if kal else None,
"y_mean": y_mean if MODEL == "stochastic_volatility" else None,
})
# %% Assumptions
assumptions = [{"key": "model_form", "label": "Model form", "status": "info",
"detail": f"Assumed, not checked from the data: the series follows a {MODEL_LABEL} model with Gaussian noise and equally spaced steps."}]
if ll_sd <= 1.0:
assumptions.append({"key": "particle_count", "label": "Enough particles", "status": "pass",
"detail": f"Five filter runs with {N_FINAL} particles gave log-likelihoods with SD {ll_sd:.2f} (≤ 1)."})
else:
assumptions.append({"key": "particle_count", "label": "Enough particles", "status": "warn",
"detail": f"Five filter runs with {N_FINAL} particles gave log-likelihoods with SD {ll_sd:.2f}; use more particles for a steadier estimate."})
if ESTIMATE == "pmmh":
acc, emin = mcmc["acceptance"], values["ess_min"]
ok = 0.1 <= acc <= 0.5 and emin >= 100
assumptions.append({"key": "mixing", "label": "MCMC mixing", "status": "pass" if ok else "warn",
"detail": f"The chain accepted {acc:.0%} of proposals after burn-in; the smallest effective sample size is {emin:.0f}"
+ ("." if ok else ". Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.")})
else:
assumptions.append({"key": "mixing", "label": "MCMC mixing", "status": "info", "detail": "The parameters were set, not estimated, so there is no MCMC chain."})
# %% Charts
charts = []
xkind = "temporal" if TEMPORAL else "numeric"
xname = TIME or "step"
if MODEL == "stochastic_volatility":
charts.append(cs.chart("states", "volatility-band", f"{VALUE} (centered) with the filtered volatility exp(h/2)", {
"time": cs.col(xname, labels, kind=xkind), "sigma": cs.col("volatility", f_mid), "value": cs.col(VALUE, y),
"mean": cs.col("mean", np.zeros(T))}))
else:
groups = [("Observed", y), ("Filtered level", f_mid)] + ([("Smoothed level", s_mid)] if sm else [])
charts.append(cs.chart("states", "series-line", f"{VALUE} with the hidden level", {
"x": cs.col(xname, [v for _ in groups for v in labels], kind=xkind),
"y": cs.col(VALUE, np.concatenate([g[1] for g in groups])),
"group": cs.col("series", [g[0] for g in groups for _ in range(T)], kind="categorical")}))
if mcmc is not None:
step = max(1, ITERATIONS // 500)
it_idx = list(range(0, ITERATIONS, step))
charts.append(cs.chart("trace", "series-line", "PMMH chains (every parameter, natural scale)", {
"x": cs.col("iteration", [float(i + 1) for _ in names for i in it_idx]),
"y": cs.col("value", np.concatenate([chain_nat[it_idx, j] for j in range(len(names))])),
"group": cs.col("parameter", [LABELS[k] for k in names for _ in it_idx], kind="categorical")}))
for j, k in enumerate(names):
col = chain_nat[BURN_IN:, j]
grid = pf.density_grid(col)
post = pf.kde(col, grid)
prior = pf.prior_density(mcmc["prior"][j], grid)
charts.append(cs.chart(f"posterior_{k}", "prior-posterior", f"{LABELS[k]}: prior and PMMH posterior", {
"x": cs.col(LABELS[k], np.concatenate([grid, grid])), "density": cs.col("density", np.concatenate([prior, post])),
"curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
# %% Tables
tables = [{"key": "parameters", "title": "Parameters",
"columns": [{"key": "param", "label": "Parameter", "type": "string"}, {"key": "estimate", "label": "Value", "type": "number"},
{"key": "lo", "label": "5%", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
{"key": "ess", "label": "Effective draws", "type": "number"}, {"key": "source", "label": "Source", "type": "string"}],
"rows": param_rows},
{"key": "likelihood", "title": "Log-likelihood",
"columns": [{"key": "what", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"what": f"Particle estimate ({N_FINAL} particles)", "value": run["loglik"]},
{"what": "SD over five filter runs", "value": ll_sd}]
+ ([{"what": "Exact (Kalman filter)", "value": kal["loglik"]}] if kal else [])}]
CAP = 2000
st_label = "volatility" if MODEL == "stochastic_volatility" else "level"
state_rows = []
for t in range(min(T, CAP)):
r = {"time": str(labels[t]), "observed": float(y_raw[t]), "filtered": float(f_mid[t]), "f_lo": float(f_lo[t]), "f_hi": float(f_hi[t])}
if sm:
r.update({"smoothed": float(s_mid[t]), "s_lo": float(s_lo[t]), "s_hi": float(s_hi[t])})
if MODEL == "local_trend":
r["slope"] = float(run["mean"][t, 1])
state_rows.append(r)
state_cols = [{"key": "time", "label": TIME or "Step", "type": "string"}, {"key": "observed", "label": VALUE, "type": "number"},
{"key": "filtered", "label": f"Filtered {st_label}" + (" (median)" if MODEL == "stochastic_volatility" else ""), "type": "number"},
{"key": "f_lo", "label": "5%", "type": "number"}, {"key": "f_hi", "label": "95%", "type": "number"}]
if sm:
state_cols += [{"key": "smoothed", "label": f"Smoothed {st_label}", "type": "number"},
{"key": "s_lo", "label": "5% (smoothed)", "type": "number"}, {"key": "s_hi", "label": "95% (smoothed)", "type": "number"}]
if MODEL == "local_trend":
state_cols.append({"key": "slope", "label": "Filtered slope", "type": "number"})
tables.append({"key": "states", "title": "Hidden state at each step" + (f" (first {CAP} of {T})" if T > CAP else ""), "columns": state_cols, "rows": state_rows})
# %% Result
est_txt = "estimated by PMMH" if ESTIMATE == "pmmh" else "set"
summary = (f"A {MODEL_LABEL} particle filter of {VALUE} ({T} steps, {N_FINAL} particles; parameters {est_txt}) has log-likelihood "
f"{run['loglik']:.2f} (SD {ll_sd:.2f} over five runs)" + (f"; the exact Kalman value is {kal['loglik']:.2f}" if kal else "")
+ f". The last filtered {st_label} is {f_mid[-1]:.4g} (90% band {f_lo[-1]:.4g} to {f_hi[-1]:.4g}).")
notes = ["A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are "
"resampled systematically " + ("at every step." if THRESHOLD >= 1.0 else "when the effective sample size drops below half the particles."),
"Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series."]
if MODEL == "stochastic_volatility":
notes.append(f"Returns are centered (mean {y_mean:.4g} removed); the volatility is exp(h/2) and its band maps h's quantiles.")
else:
notes.append("The first hidden state starts at the first observation with the series' variance" + (" (slope at 0 with the differences' variance)" if MODEL == "local_trend" else "")
+ "; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.")
if ESTIMATE == "pmmh":
notes.append(f"PMMH ran {ITERATIONS} iterations ({BURN_IN} burn-in, step size adapted during burn-in) with {N_PMMH} particles per step; priors: normal on log σ "
"centered at the data-based value (SD 2)" + (", normal on μ (SD 3), uniform φ on (−1, 1)" if MODEL == "stochastic_volatility" else "")
+ ". The final filter uses the posterior means.")
statistics = [{"key": "loglik", "label": "Log-likelihood (particle)", "value": run["loglik"]}, {"key": "loglik_sd", "label": "Log-likelihood SD", "value": ll_sd}]
if kal:
statistics.append({"key": "kalman_loglik", "label": "Log-likelihood (Kalman)", "value": kal["loglik"]})
if mcmc is not None:
statistics.append({"key": "acceptance", "label": "Acceptance rate", "value": mcmc["acceptance"]})
cs.publish({
"method": "ts.particle_filter",
"methodVersion": "1.0.0",
"title": "Particle filter",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": T,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
With 800 particles, the log-likelihood estimate is −638.8 against the Kalman filter's −638.7, with an SD across repeats of 0.22. The mean weight ESS is 647.
Fixed parameters: particle MCMC
ReadA filter needs the model's parameters (noise variances). Treating a fixed parameter as one more slowly drifting state degenerates fast. Particle MCMC puts the filter inside an MCMC step instead. Particle marginal Metropolis–HastingsParticle marginal Metropolis–Hastings (PMMH)MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step. (PMMH) proposes , runs a filter to get a likelihood estimate , and accepts with
Remarkably, this is exact: the chain targets the true posterior even though is noisy, provided the estimate is unbiased and non-negative.
Reference · INF016 · Partly runs in CodeSplashParticle Markov chain Monte Carlo (PMCMC)Uses particle methods inside a correctly constructed MCMC transition to infer static parameters and latent trajectories in state-space models. Particle marginal MH and particle Gibbs are related members;Keep the old estimate
ReadThe exactness depends on bookkeeping. On rejection, PMMH keeps both the old and its old . Recomputing the current state's likelihood at every step gives a different, inexact "noisy MH". In the reference's example the acceptance probability is 0.595; the proposal is rejected and the retained log-likelihood stays at −10.0.
The unbiasedness needed is of , not of . And particle Gibbs, the other member of the family, uses a conditional filter and a different update; it isn't this acceptance rule.
Noisy likelihoods make sticky chains
ReadWhen happens to come out high, later proposals rarely beat it, and the chain sticks. The fix is more particles per step, balanced against the cost.
A local level particle filter of flow (100 steps, 500 particles; parameters estimated by PMMH) has log-likelihood -639.51 (SD 0.45 over five runs); the exact Kalman value is -638.76. The last filtered level is 783.1 (90% band 652.7 to 906.1).
- Log-likelihood (particle)
- −639.51
- Log-likelihood SD
- 0.4484
- Log-likelihood (Kalman)
- −638.76
- Acceptance rate
- 0.3800
Assumptions
- Model form — Assumed, not checked from the data: the series follows a local level model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 500 particles gave log-likelihoods with SD 0.45 (≤ 1).
- MCMC mixing — The chain accepted 38% of proposals after burn-in; the smallest effective sample size is 8. Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123.59 | 106.47 | 138.10 | 30.381 | PMMH posterior mean |
| Level noise SD | 43.419 | 29.083 | 64.891 | 8.164 | PMMH posterior mean |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (500 particles) | −639.51 |
| SD over five filter runs | 0.4484 |
| Exact (Kalman filter) | −638.76 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1125.52 | 967.55 | 1283.00 | 1112.06 | 1015.67 | 1210.42 |
| 1872 | 1,160 | 1140.12 | 1007.44 | 1271.96 | 1104.74 | 1017.41 | 1166.61 |
| 1873 | 963 | 1070.30 | 960.34 | 1195.89 | 1093.12 | 1008.39 | 1163.70 |
| 1874 | 1,210 | 1114.50 | 998.91 | 1232.27 | 1099.02 | 987.89 | 1176.70 |
| 1875 | 1,160 | 1127.27 | 1011.92 | 1242.84 | 1105.62 | 1008.48 | 1180.09 |
| 1876 | 1,160 | 1133.53 | 1026.55 | 1251.18 | 1106.19 | 1047.94 | 1154.98 |
| 1877 | 813 | 1041.53 | 928.32 | 1144.00 | 1090.46 | 1025.72 | 1136.53 |
| 1878 | 1,230 | 1098.48 | 992.72 | 1203.46 | 1119.96 | 1047.46 | 1200.71 |
| 1879 | 1,370 | 1175.29 | 1067.88 | 1280.58 | 1127.98 | 1041.69 | 1184.94 |
| 1880 | 1,140 | 1166.26 | 1050.34 | 1279.88 | 1107.29 | 1019.43 | 1184.17 |
| 1881 | 995 | 1121.37 | 1011.89 | 1219.27 | 1091.29 | 1009.09 | 1176.63 |
| 1882 | 935 | 1071.85 | 954.57 | 1181.12 | 1070.05 | 985.55 | 1161.14 |
| 1883 | 1,110 | 1082.01 | 970.38 | 1188.03 | 1063.11 | 967.66 | 1159.21 |
| 1884 | 994 | 1057.67 | 952.27 | 1168.61 | 1045.09 | 980.74 | 1131.36 |
| 1885 | 1,020 | 1046.58 | 937.13 | 1154.69 | 1036.06 | 951.30 | 1114.20 |
| 1886 | 960 | 1020.12 | 914.56 | 1132.41 | 1025.14 | 966.24 | 1086.58 |
| 1887 | 1,180 | 1065.12 | 957.40 | 1182.11 | 1044.47 | 954.28 | 1094.51 |
| 1888 | 799 | 985.70 | 868.19 | 1094.73 | 1034.30 | 962.57 | 1110.02 |
| 1889 | 958 | 979.04 | 864.37 | 1089.21 | 1064.47 | 1007.20 | 1121.07 |
| 1890 | 1,140 | 1028.36 | 914.58 | 1135.79 | 1083.18 | 993.46 | 1151.88 |
| 1891 | 1,100 | 1049.80 | 936.77 | 1142.95 | 1103.85 | 1060.87 | 1186.58 |
| 1892 | 1,210 | 1096.28 | 986.40 | 1198.21 | 1110.39 | 1047.21 | 1176.68 |
| 1893 | 1,150 | 1111.58 | 999.97 | 1214.61 | 1114.66 | 1036.97 | 1197.72 |
| 1894 | 1,250 | 1150.42 | 1045.38 | 1246.45 | 1122.45 | 1062.25 | 1188.46 |
| 1895 | 1,260 | 1175.55 | 1074.75 | 1282.66 | 1106.22 | 1047.60 | 1196.37 |
| 1896 | 1,220 | 1189.65 | 1080.02 | 1290.90 | 1077.23 | 998.82 | 1142.24 |
| 1897 | 1,030 | 1144.40 | 1040.29 | 1251.47 | 1035.30 | 959.14 | 1102.39 |
| 1898 | 1,100 | 1132.61 | 1031.02 | 1247.00 | 1002.03 | 930.12 | 1059.18 |
| 1899 | 774 | 1035.63 | 951.65 | 1134.70 | 958.11 | 864.00 | 1012.01 |
| 1900 | 840 | 985.76 | 887.99 | 1088.57 | 919.50 | 857.11 | 980.13 |
| 1901 | 874 | 956.00 | 852.79 | 1063.37 | 891.70 | 803.04 | 962.23 |
| 1902 | 694 | 881.25 | 778.74 | 986.51 | 867.75 | 781.17 | 923.53 |
| 1903 | 940 | 898.30 | 788.04 | 1000.80 | 865.58 | 802.10 | 942.40 |
| 1904 | 833 | 880.48 | 773.82 | 986.56 | 851.36 | 771.00 | 935.92 |
| 1905 | 701 | 831.37 | 714.10 | 941.68 | 839.33 | 772.31 | 904.43 |
| 1906 | 916 | 858.37 | 746.87 | 971.39 | 846.56 | 779.80 | 913.78 |
| 1907 | 692 | 808.32 | 692.82 | 920.45 | 844.33 | 773.45 | 915.91 |
| 1908 | 1,020 | 869.32 | 762.15 | 978.60 | 860.79 | 798.61 | 947.77 |
| 1909 | 1,050 | 919.50 | 810.05 | 1008.54 | 877.67 | 787.56 | 982.69 |
| 1910 | 969 | 931.07 | 822.87 | 1037.93 | 863.64 | 780.36 | 933.26 |
First 40 of 100 rows.
- A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are resampled systematically when the effective sample size drops below half the particles.
- Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.
- The first hidden state starts at the first observation with the series' variance; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.
- PMMH ran 300 iterations (100 burn-in, step size adapted during burn-in) with 100 particles per step; priors: normal on log σ centered at the data-based value (SD 2). The final filter uses the posterior means.
The exact R script · R R version 4.5.1 (2025-06-13)
# Particle filter (state-space model with PMMH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.particle_filter 1.0.0 · spec 0a0d9d82db3e9bac
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_nile.parquet", col_select = c("flow", "year")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("flow", "year")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("flow", "year")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "flow"
TIME <- "year"
TEMPORAL <- FALSE
MODEL <- "local_level"
ESTIMATE <- "pmmh"
N_FINAL <- as.integer(500)
N_PMMH <- as.integer(100)
ITERATIONS <- as.integer(300)
BURN_IN <- as.integer(100)
THRESHOLD <- if ("ess" == "always") 1 else 0.5 # resample when ESS < threshold * N
SMOOTH <- TRUE
SMOOTH_PATHS <- as.integer(40)
SEED <- 42
FIXED <- list(sigma_obs = NULL, sigma_level = NULL, sigma_slope = NULL,
mu = NULL, phi = NULL, sigma = NULL)
d <- df
if (!is.null(TIME)) d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
rownames(d) <- NULL
y_raw <- as.numeric(d[[VALUE]])
cs_check_rows(length(y_raw), 10, "A particle filter")
cs_check_not_constant(y_raw, VALUE)
if (ESTIMATE == "pmmh" && BURN_IN >= ITERATIONS)
cs_error("CS_E_INVALID_OPTION", option = "Burn-in", allowed = sprintf("fewer than the %d MCMC iterations", ITERATIONS), value = BURN_IN)
y_mean <- mean(y_raw)
y <- if (MODEL == "stochastic_volatility") y_raw - y_mean else y_raw # the volatility model describes centered returns
TT <- length(y)
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else seq_len(TT)
pnames <- cs_pf_param_names(MODEL)
LABELS <- c(sigma_obs = "Observation noise SD", sigma_level = "Level noise SD", sigma_slope = "Slope noise SD",
mu = "Mean log-variance μ", phi = "Persistence φ", sigma = "Volatility of volatility σ")
MODEL_LABEL <- c(local_level = "local level", local_trend = "local linear trend", stochastic_volatility = "stochastic volatility")[[MODEL]]
start <- cs_pf_defaults(MODEL, y)
# %% Parameters: PMMH (Andrieu, Doucet & Holenstein 2010) or set by hand
values <- list()
param_rows <- list()
chain_nat <- NULL
mcmc <- NULL
params <- list()
if (ESTIMATE == "pmmh") {
mcmc <- cs_pf_pmmh(MODEL, y, start, N_PMMH, ITERATIONS, BURN_IN, SEED, THRESHOLD)
chain_nat <- t(apply(mcmc$chain, 1, function(row) unlist(cs_pf_from_free(MODEL, row)[pnames])))
kept_nat <- chain_nat[(BURN_IN + 1):ITERATIONS, , drop = FALSE]
ess_all <- numeric(0)
for (j in seq_along(pnames)) {
k <- pnames[j]
colv <- kept_nat[, j]
est <- mean(colv)
qq <- stats::quantile(colv, c(0.05, 0.95), type = 7, names = FALSE)
e <- cs_pf_ess(colv)
ess_all <- c(ess_all, e)
params[[k]] <- est
values[sprintf("param[%s]", k)] <- list(est)
values[sprintf("param_lo[%s]", k)] <- list(qq[1])
values[sprintf("param_hi[%s]", k)] <- list(qq[2])
values[sprintf("param_ess[%s]", k)] <- list(e)
param_rows[[length(param_rows) + 1]] <- list(param = LABELS[[k]], estimate = est, lo = qq[1], hi = qq[2], ess = e, source = "PMMH posterior mean")
}
values$iterations <- ITERATIONS
values$burn_in <- BURN_IN
values$acceptance <- mcmc$acceptance
values$ess_min <- min(ess_all)
} else {
for (k in pnames) {
v <- FIXED[[k]]
params[[k]] <- if (!is.null(v)) as.numeric(v) else start[[k]]
values[sprintf("param[%s]", k)] <- list(params[[k]])
param_rows[[length(param_rows) + 1]] <- list(param = LABELS[[k]], estimate = params[[k]], lo = NULL, hi = NULL, ess = NULL,
source = if (!is.null(v)) "set" else "from the data")
}
values["iterations"] <- list(NULL)
values["burn_in"] <- list(NULL)
values["acceptance"] <- list(NULL)
values["ess_min"] <- list(NULL)
}
chk <- tryCatch({
cs_pf_check_params(MODEL, params)
NULL
}, error = function(e) conditionMessage(e))
if (!is.null(chk)) cs_error("CS_E_INVALID_OPTION", option = "Model parameters", allowed = "valid values for the model", value = chk)
# %% Final filter at the estimates, repeated runs for the likelihood's noise, smoother, Kalman
B <- cs_pf_block_size(MODEL, N_FINAL, TT)
run <- cs_pf_filter(MODEL, y, params, N_FINAL, cs_runif(cs_rng(SEED + 1), B), THRESHOLD, store = SMOOTH)
if (run$failed) cs_error("CS_E_UNDEFINED", what = "The particle filter", reason = "every particle got zero weight at some step; check the parameters")
lls <- c(run$loglik, vapply(1:4, function(r) cs_pf_filter(MODEL, y, params, N_FINAL, cs_runif(cs_rng(SEED + 10 + r), B), THRESHOLD, summarize = FALSE)$loglik, numeric(1)))
ll_sd <- stats::sd(lls)
sm <- if (SMOOTH) cs_pf_smooth(MODEL, run, params, SMOOTH_PATHS, SEED + 2) else NULL
kal <- cs_pf_kalman(MODEL, y, params)
if (MODEL == "stochastic_volatility") {
vol <- function(h) exp(h / 2) # volatility = exp(h/2); quantiles map exactly
f_mid <- vol(run$median[, 1]); f_lo <- vol(run$lo[, 1]); f_hi <- vol(run$hi[, 1])
s_mid <- if (!is.null(sm)) vol(sm$mean[, 1]) else NULL
s_lo <- if (!is.null(sm)) vol(sm$lo[, 1]) else NULL
s_hi <- if (!is.null(sm)) vol(sm$hi[, 1]) else NULL
} else {
f_mid <- run$mean[, 1]; f_lo <- run$lo[, 1]; f_hi <- run$hi[, 1]
s_mid <- if (!is.null(sm)) sm$mean[, 1] else NULL
s_lo <- if (!is.null(sm)) sm$lo[, 1] else NULL
s_hi <- if (!is.null(sm)) sm$hi[, 1] else NULL
}
values$n_obs <- TT
values$model <- MODEL
values$model_label <- MODEL_LABEL
values$estimate <- ESTIMATE
values$particles <- N_FINAL
values$loglik <- run$loglik
values$loglik_sd <- ll_sd
values["kalman_loglik"] <- list(if (!is.null(kal)) kal$loglik else NULL)
values$mean_ess <- run$mean_ess
values$resamples <- run$resamples
values$last_state <- f_mid[TT]
values$last_state_lo <- f_lo[TT]
values$last_state_hi <- f_hi[TT]
values["kalman_last_state"] <- list(if (!is.null(kal)) kal$mean[TT, 1] else NULL)
values["y_mean"] <- list(if (MODEL == "stochastic_volatility") y_mean else NULL)
# %% Assumptions
assumptions <- list(list(key = "model_form", label = "Model form", status = "info",
detail = sprintf("Assumed, not checked from the data: the series follows a %s model with Gaussian noise and equally spaced steps.", MODEL_LABEL)))
if (ll_sd <= 1) {
assumptions[[2]] <- list(key = "particle_count", label = "Enough particles", status = "pass",
detail = sprintf("Five filter runs with %d particles gave log-likelihoods with SD %.2f (≤ 1).", N_FINAL, ll_sd))
} else {
assumptions[[2]] <- list(key = "particle_count", label = "Enough particles", status = "warn",
detail = sprintf("Five filter runs with %d particles gave log-likelihoods with SD %.2f; use more particles for a steadier estimate.", N_FINAL, ll_sd))
}
if (ESTIMATE == "pmmh") {
acc <- mcmc$acceptance
emin <- values$ess_min
ok <- acc >= 0.1 && acc <= 0.5 && emin >= 100
assumptions[[3]] <- list(key = "mixing", label = "MCMC mixing", status = if (ok) "pass" else "warn",
detail = paste0(sprintf("The chain accepted %s of proposals after burn-in; the smallest effective sample size is %s", sprintf("%.0f%%", 100 * acc), sprintf("%.0f", emin)),
if (ok) "." else ". Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low."))
} else {
assumptions[[3]] <- list(key = "mixing", label = "MCMC mixing", status = "info", detail = "The parameters were set, not estimated, so there is no MCMC chain.")
}
# %% Charts
charts <- list()
xkind <- if (TEMPORAL) "temporal" else "numeric"
xname <- if (is.null(TIME)) "step" else TIME
if (MODEL == "stochastic_volatility") {
charts[[1]] <- cs_chart("states", "volatility-band", sprintf("%s (centered) with the filtered volatility exp(h/2)", VALUE), list(
time = cs_col(xname, labels, kind = xkind), sigma = cs_col("volatility", f_mid), value = cs_col(VALUE, y),
mean = cs_col("mean", rep(0, TT))))
} else {
gnames <- c("Observed", "Filtered level")
gvals <- list(y, f_mid)
if (!is.null(sm)) {
gnames <- c(gnames, "Smoothed level")
gvals[[3]] <- s_mid
}
charts[[1]] <- cs_chart("states", "series-line", sprintf("%s with the hidden level", VALUE), list(
x = cs_col(xname, rep(labels, times = length(gnames)), kind = xkind),
y = cs_col(VALUE, unlist(gvals)),
group = cs_col("series", rep(gnames, each = TT), kind = "categorical")))
}
if (!is.null(mcmc)) {
stp <- max(1L, ITERATIONS %/% 500L)
it_idx <- seq(1L, ITERATIONS, by = stp)
charts[[length(charts) + 1]] <- cs_chart("trace", "series-line", "PMMH chains (every parameter, natural scale)", list(
x = cs_col("iteration", rep(as.numeric(it_idx), times = length(pnames))),
y = cs_col("value", as.vector(chain_nat[it_idx, , drop = FALSE])),
group = cs_col("parameter", rep(unname(LABELS[pnames]), each = length(it_idx)), kind = "categorical")))
for (j in seq_along(pnames)) {
k <- pnames[j]
colv <- chain_nat[(BURN_IN + 1):ITERATIONS, j]
grid <- cs_pf_density_grid(colv)
post <- cs_pf_kde(colv, grid)
prior <- cs_pf_prior_density(mcmc$prior[[j]], grid)
charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", k), "prior-posterior", sprintf("%s: prior and PMMH posterior", LABELS[[k]]), list(
x = cs_col(LABELS[[k]], c(grid, grid)), density = cs_col("density", c(prior, post)),
curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
}
# %% Tables
lik_rows <- list(list(what = sprintf("Particle estimate (%d particles)", N_FINAL), value = run$loglik),
list(what = "SD over five filter runs", value = ll_sd))
if (!is.null(kal)) lik_rows[[3]] <- list(what = "Exact (Kalman filter)", value = kal$loglik)
tables <- list(
list(key = "parameters", title = "Parameters",
columns = list(list(key = "param", label = "Parameter", type = "string"), list(key = "estimate", label = "Value", type = "number"),
list(key = "lo", label = "5%", type = "number"), list(key = "hi", label = "95%", type = "number"),
list(key = "ess", label = "Effective draws", type = "number"), list(key = "source", label = "Source", type = "string")),
rows = param_rows),
list(key = "likelihood", title = "Log-likelihood",
columns = list(list(key = "what", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = lik_rows))
CAP <- 2000
st_label <- if (MODEL == "stochastic_volatility") "volatility" else "level"
state_rows <- lapply(seq_len(min(TT, CAP)), function(t) {
r <- list(time = as.character(labels[[t]]), observed = y_raw[t], filtered = f_mid[t], f_lo = f_lo[t], f_hi = f_hi[t])
if (!is.null(sm)) {
r$smoothed <- s_mid[t]
r$s_lo <- s_lo[t]
r$s_hi <- s_hi[t]
}
if (MODEL == "local_trend") r$slope <- run$mean[t, 2]
r
})
state_cols <- list(list(key = "time", label = if (is.null(TIME)) "Step" else TIME, type = "string"), list(key = "observed", label = VALUE, type = "number"),
list(key = "filtered", label = paste0("Filtered ", st_label, if (MODEL == "stochastic_volatility") " (median)" else ""), type = "number"),
list(key = "f_lo", label = "5%", type = "number"), list(key = "f_hi", label = "95%", type = "number"))
if (!is.null(sm)) {
state_cols <- c(state_cols, list(list(key = "smoothed", label = paste0("Smoothed ", st_label), type = "number"),
list(key = "s_lo", label = "5% (smoothed)", type = "number"), list(key = "s_hi", label = "95% (smoothed)", type = "number")))
}
if (MODEL == "local_trend") state_cols <- c(state_cols, list(list(key = "slope", label = "Filtered slope", type = "number")))
tables[[3]] <- list(key = "states", title = paste0("Hidden state at each step", if (TT > CAP) sprintf(" (first %d of %d)", CAP, TT) else ""),
columns = state_cols, rows = state_rows)
# %% Result
g4 <- function(v) sprintf("%.4g", v)
est_txt <- if (ESTIMATE == "pmmh") "estimated by PMMH" else "set"
summary <- paste0(sprintf("A %s particle filter of %s (%d steps, %d particles; parameters %s) has log-likelihood %.2f (SD %.2f over five runs)",
MODEL_LABEL, VALUE, TT, N_FINAL, est_txt, run$loglik, ll_sd),
if (!is.null(kal)) sprintf("; the exact Kalman value is %.2f", kal$loglik) else "",
sprintf(". The last filtered %s is %s (90%% band %s to %s).", st_label, g4(f_mid[TT]), g4(f_lo[TT]), g4(f_hi[TT])))
notes <- c(paste0("A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are ",
"resampled systematically ", if (THRESHOLD >= 1) "at every step." else "when the effective sample size drops below half the particles."),
"Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.")
if (MODEL == "stochastic_volatility") {
notes <- c(notes, sprintf("Returns are centered (mean %s removed); the volatility is exp(h/2) and its band maps h's quantiles.", g4(y_mean)))
} else {
notes <- c(notes, paste0("The first hidden state starts at the first observation with the series' variance",
if (MODEL == "local_trend") " (slope at 0 with the differences' variance)" else "",
"; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches."))
}
if (ESTIMATE == "pmmh") {
notes <- c(notes, paste0(sprintf("PMMH ran %d iterations (%d burn-in, step size adapted during burn-in) with %d particles per step; priors: normal on log σ ", ITERATIONS, BURN_IN, N_PMMH),
"centered at the data-based value (SD 2)", if (MODEL == "stochastic_volatility") ", normal on μ (SD 3), uniform φ on (−1, 1)" else "",
". The final filter uses the posterior means."))
}
statistics <- list(list(key = "loglik", label = "Log-likelihood (particle)", value = run$loglik), list(key = "loglik_sd", label = "Log-likelihood SD", value = ll_sd))
if (!is.null(kal)) statistics[[length(statistics) + 1]] <- list(key = "kalman_loglik", label = "Log-likelihood (Kalman)", value = kal$loglik)
if (!is.null(mcmc)) statistics[[length(statistics) + 1]] <- list(key = "acceptance", label = "Acceptance rate", value = mcmc$acceptance)
cs_publish(list(
method = "ts.particle_filter",
methodVersion = "1.0.0",
title = "Particle filter",
engine = cs_engine_info("stats", "nanoparquet"),
n = TT,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
A local level particle filter of flow (100 steps, 500 particles; parameters estimated by PMMH) has log-likelihood -639.51 (SD 0.45 over five runs); the exact Kalman value is -638.76. The last filtered level is 783.1 (90% band 652.7 to 906.1).
- Log-likelihood (particle)
- −639.51
- Log-likelihood SD
- 0.4484
- Log-likelihood (Kalman)
- −638.76
- Acceptance rate
- 0.3800
Assumptions
- Model form — Assumed, not checked from the data: the series follows a local level model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 500 particles gave log-likelihoods with SD 0.45 (≤ 1).
- MCMC mixing — The chain accepted 38% of proposals after burn-in; the smallest effective sample size is 8. Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123.59 | 106.47 | 138.10 | 30.381 | PMMH posterior mean |
| Level noise SD | 43.419 | 29.083 | 64.891 | 8.164 | PMMH posterior mean |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (500 particles) | −639.51 |
| SD over five filter runs | 0.4484 |
| Exact (Kalman filter) | −638.76 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1125.52 | 967.55 | 1283.00 | 1112.06 | 1015.67 | 1210.42 |
| 1872 | 1,160 | 1140.12 | 1007.44 | 1271.96 | 1104.74 | 1017.41 | 1166.61 |
| 1873 | 963 | 1070.30 | 960.34 | 1195.89 | 1093.12 | 1008.39 | 1163.70 |
| 1874 | 1,210 | 1114.50 | 998.91 | 1232.27 | 1099.02 | 987.89 | 1176.70 |
| 1875 | 1,160 | 1127.27 | 1011.92 | 1242.84 | 1105.62 | 1008.48 | 1180.09 |
| 1876 | 1,160 | 1133.53 | 1026.55 | 1251.18 | 1106.19 | 1047.94 | 1154.98 |
| 1877 | 813 | 1041.53 | 928.32 | 1144.00 | 1090.46 | 1025.72 | 1136.53 |
| 1878 | 1,230 | 1098.48 | 992.72 | 1203.46 | 1119.96 | 1047.46 | 1200.71 |
| 1879 | 1,370 | 1175.29 | 1067.88 | 1280.58 | 1127.98 | 1041.69 | 1184.94 |
| 1880 | 1,140 | 1166.26 | 1050.34 | 1279.88 | 1107.29 | 1019.43 | 1184.17 |
| 1881 | 995 | 1121.37 | 1011.89 | 1219.27 | 1091.29 | 1009.09 | 1176.63 |
| 1882 | 935 | 1071.85 | 954.57 | 1181.12 | 1070.05 | 985.55 | 1161.14 |
| 1883 | 1,110 | 1082.01 | 970.38 | 1188.03 | 1063.11 | 967.66 | 1159.21 |
| 1884 | 994 | 1057.67 | 952.27 | 1168.61 | 1045.09 | 980.74 | 1131.36 |
| 1885 | 1,020 | 1046.58 | 937.13 | 1154.69 | 1036.06 | 951.30 | 1114.20 |
| 1886 | 960 | 1020.12 | 914.56 | 1132.41 | 1025.14 | 966.24 | 1086.58 |
| 1887 | 1,180 | 1065.12 | 957.40 | 1182.11 | 1044.47 | 954.28 | 1094.51 |
| 1888 | 799 | 985.70 | 868.19 | 1094.73 | 1034.30 | 962.57 | 1110.02 |
| 1889 | 958 | 979.04 | 864.37 | 1089.21 | 1064.47 | 1007.20 | 1121.07 |
| 1890 | 1,140 | 1028.36 | 914.58 | 1135.79 | 1083.18 | 993.46 | 1151.88 |
| 1891 | 1,100 | 1049.80 | 936.77 | 1142.95 | 1103.85 | 1060.87 | 1186.58 |
| 1892 | 1,210 | 1096.28 | 986.40 | 1198.21 | 1110.39 | 1047.21 | 1176.68 |
| 1893 | 1,150 | 1111.58 | 999.97 | 1214.61 | 1114.66 | 1036.97 | 1197.72 |
| 1894 | 1,250 | 1150.42 | 1045.38 | 1246.45 | 1122.45 | 1062.25 | 1188.46 |
| 1895 | 1,260 | 1175.55 | 1074.75 | 1282.66 | 1106.22 | 1047.60 | 1196.37 |
| 1896 | 1,220 | 1189.65 | 1080.02 | 1290.90 | 1077.23 | 998.82 | 1142.24 |
| 1897 | 1,030 | 1144.40 | 1040.29 | 1251.47 | 1035.30 | 959.14 | 1102.39 |
| 1898 | 1,100 | 1132.61 | 1031.02 | 1247.00 | 1002.03 | 930.12 | 1059.18 |
| 1899 | 774 | 1035.63 | 951.65 | 1134.70 | 958.11 | 864.00 | 1012.01 |
| 1900 | 840 | 985.76 | 887.99 | 1088.57 | 919.50 | 857.11 | 980.13 |
| 1901 | 874 | 956.00 | 852.79 | 1063.37 | 891.70 | 803.04 | 962.23 |
| 1902 | 694 | 881.25 | 778.74 | 986.51 | 867.75 | 781.17 | 923.53 |
| 1903 | 940 | 898.30 | 788.04 | 1000.80 | 865.58 | 802.10 | 942.40 |
| 1904 | 833 | 880.48 | 773.82 | 986.56 | 851.36 | 771.00 | 935.92 |
| 1905 | 701 | 831.37 | 714.10 | 941.68 | 839.33 | 772.31 | 904.43 |
| 1906 | 916 | 858.37 | 746.87 | 971.39 | 846.56 | 779.80 | 913.78 |
| 1907 | 692 | 808.32 | 692.82 | 920.45 | 844.33 | 773.45 | 915.91 |
| 1908 | 1,020 | 869.32 | 762.15 | 978.60 | 860.79 | 798.61 | 947.77 |
| 1909 | 1,050 | 919.50 | 810.05 | 1008.54 | 877.67 | 787.56 | 982.69 |
| 1910 | 969 | 931.07 | 822.87 | 1037.93 | 863.64 | 780.36 | 933.26 |
First 40 of 100 rows.
- A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are resampled systematically when the effective sample size drops below half the particles.
- Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.
- The first hidden state starts at the first observation with the series' variance; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.
- PMMH ran 300 iterations (100 burn-in, step size adapted during burn-in) with 100 particles per step; priors: normal on log σ centered at the data-based value (SD 2). The final filter uses the posterior means.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Particle filter (state-space model with PMMH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.particle_filter 1.0.0 · spec 0a0d9d82db3e9bac
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import particle as pf # bootstrap filter, smoother, PMMH (twin of codesplashr cs_pf_*)
from codesplash.stats import ts
from codesplash.stats.rng import Rng
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_nile.parquet", columns=["flow", "year"])
n_input = len(df)
df = df.dropna(subset=["flow", "year"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["flow", "year"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "flow"
TIME = "year"
TEMPORAL = False
MODEL = "local_level"
ESTIMATE = "pmmh"
N_FINAL = int(500)
N_PMMH = int(100)
ITERATIONS = int(300)
BURN_IN = int(100)
THRESHOLD = 1.0 if "ess" == "always" else 0.5 # resample when ESS < threshold · N
SMOOTH = True
SMOOTH_PATHS = int(40)
SEED = 42
FIXED = {"sigma_obs": None, "sigma_level": None, "sigma_slope": None,
"mu": None, "phi": None, "sigma": None}
d = df.sort_values(TIME, kind="mergesort").reset_index(drop=True) if TIME else df.reset_index(drop=True)
y_raw = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(y_raw), 10, "A particle filter")
check_not_constant(y_raw, VALUE)
if ESTIMATE == "pmmh" and BURN_IN >= ITERATIONS:
cs.cs_error("CS_E_INVALID_OPTION", option="Burn-in", allowed=f"fewer than the {ITERATIONS} MCMC iterations", value=BURN_IN)
y_mean = float(np.mean(y_raw))
y = y_raw - y_mean if MODEL == "stochastic_volatility" else y_raw # the volatility model describes centered returns
T = len(y)
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else list(range(1, T + 1))
names = pf.param_names(MODEL)
LABELS = {"sigma_obs": "Observation noise SD", "sigma_level": "Level noise SD", "sigma_slope": "Slope noise SD",
"mu": "Mean log-variance μ", "phi": "Persistence φ", "sigma": "Volatility of volatility σ"}
MODEL_LABEL = {"local_level": "local level", "local_trend": "local linear trend", "stochastic_volatility": "stochastic volatility"}[MODEL]
start = pf.defaults(MODEL, y)
# %% Parameters: PMMH (Andrieu, Doucet & Holenstein 2010) or set by hand
values = {}
param_rows = []
chain_nat = None
mcmc = None
if ESTIMATE == "pmmh":
mcmc = pf.pmmh(MODEL, y, start, N_PMMH, ITERATIONS, BURN_IN, SEED, THRESHOLD)
kept = mcmc["chain"][BURN_IN:]
chain_nat = np.array([[pf.from_free(MODEL, row)[k] for k in names] for row in mcmc["chain"]])
kept_nat = chain_nat[BURN_IN:]
params = {}
ess_all = []
for j, k in enumerate(names):
col = kept_nat[:, j]
est = float(np.mean(col))
lo, hi = (float(v) for v in np.quantile(col, [0.05, 0.95], method="linear"))
e = pf.ess(col)
ess_all.append(e)
params[k] = est
values[f"param[{k}]"], values[f"param_lo[{k}]"], values[f"param_hi[{k}]"], values[f"param_ess[{k}]"] = est, lo, hi, e
param_rows.append({"param": LABELS[k], "estimate": est, "lo": lo, "hi": hi, "ess": e, "source": "PMMH posterior mean"})
values.update({"iterations": ITERATIONS, "burn_in": BURN_IN, "acceptance": mcmc["acceptance"], "ess_min": float(min(ess_all))})
else:
params = {}
for k in names:
v = FIXED[k]
params[k] = float(v) if v is not None else float(start[k])
values[f"param[{k}]"] = params[k]
param_rows.append({"param": LABELS[k], "estimate": params[k], "lo": None, "hi": None, "ess": None,
"source": "set" if v is not None else "from the data"})
values.update({"iterations": None, "burn_in": None, "acceptance": None, "ess_min": None})
try:
pf.check_params(MODEL, params)
except ValueError as e:
cs.cs_error("CS_E_INVALID_OPTION", option="Model parameters", allowed="valid values for the model", value=str(e))
# %% Final filter at the estimates, repeated runs for the likelihood's noise, smoother, Kalman
B = pf.block_size(MODEL, N_FINAL, T)
run = pf.filter_run(MODEL, y, params, N_FINAL, Rng(SEED + 1).uniform(B), THRESHOLD, store=SMOOTH)
if run["failed"]:
cs.cs_error("CS_E_UNDEFINED", what="The particle filter", reason="every particle got zero weight at some step; check the parameters")
lls = [run["loglik"]] + [pf.filter_run(MODEL, y, params, N_FINAL, Rng(SEED + 10 + r).uniform(B), THRESHOLD, summarize=False)["loglik"] for r in range(1, 5)]
ll_sd = float(np.std(lls, ddof=1))
sm = pf.smooth(MODEL, run, params, SMOOTH_PATHS, SEED + 2) if SMOOTH else None
kal = pf.kalman(MODEL, y, params)
if MODEL == "stochastic_volatility":
vol = lambda h: np.exp(h / 2.0) # noqa: E731 volatility = exp(h/2); quantiles map exactly
f_mid, f_lo, f_hi = vol(run["median"][:, 0]), vol(run["lo"][:, 0]), vol(run["hi"][:, 0])
s_mid = vol(sm["mean"][:, 0]) if sm else None
s_lo, s_hi = (vol(sm["lo"][:, 0]), vol(sm["hi"][:, 0])) if sm else (None, None)
else:
f_mid, f_lo, f_hi = run["mean"][:, 0], run["lo"][:, 0], run["hi"][:, 0]
s_mid = sm["mean"][:, 0] if sm else None
s_lo, s_hi = (sm["lo"][:, 0], sm["hi"][:, 0]) if sm else (None, None)
values.update({
"n_obs": T, "model": MODEL, "model_label": MODEL_LABEL, "estimate": ESTIMATE, "particles": N_FINAL,
"loglik": run["loglik"], "loglik_sd": ll_sd, "kalman_loglik": kal["loglik"] if kal else None,
"mean_ess": run["mean_ess"], "resamples": run["resamples"],
"last_state": float(f_mid[-1]), "last_state_lo": float(f_lo[-1]), "last_state_hi": float(f_hi[-1]),
"kalman_last_state": float(kal["mean"][-1, 0]) if kal else None,
"y_mean": y_mean if MODEL == "stochastic_volatility" else None,
})
# %% Assumptions
assumptions = [{"key": "model_form", "label": "Model form", "status": "info",
"detail": f"Assumed, not checked from the data: the series follows a {MODEL_LABEL} model with Gaussian noise and equally spaced steps."}]
if ll_sd <= 1.0:
assumptions.append({"key": "particle_count", "label": "Enough particles", "status": "pass",
"detail": f"Five filter runs with {N_FINAL} particles gave log-likelihoods with SD {ll_sd:.2f} (≤ 1)."})
else:
assumptions.append({"key": "particle_count", "label": "Enough particles", "status": "warn",
"detail": f"Five filter runs with {N_FINAL} particles gave log-likelihoods with SD {ll_sd:.2f}; use more particles for a steadier estimate."})
if ESTIMATE == "pmmh":
acc, emin = mcmc["acceptance"], values["ess_min"]
ok = 0.1 <= acc <= 0.5 and emin >= 100
assumptions.append({"key": "mixing", "label": "MCMC mixing", "status": "pass" if ok else "warn",
"detail": f"The chain accepted {acc:.0%} of proposals after burn-in; the smallest effective sample size is {emin:.0f}"
+ ("." if ok else ". Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.")})
else:
assumptions.append({"key": "mixing", "label": "MCMC mixing", "status": "info", "detail": "The parameters were set, not estimated, so there is no MCMC chain."})
# %% Charts
charts = []
xkind = "temporal" if TEMPORAL else "numeric"
xname = TIME or "step"
if MODEL == "stochastic_volatility":
charts.append(cs.chart("states", "volatility-band", f"{VALUE} (centered) with the filtered volatility exp(h/2)", {
"time": cs.col(xname, labels, kind=xkind), "sigma": cs.col("volatility", f_mid), "value": cs.col(VALUE, y),
"mean": cs.col("mean", np.zeros(T))}))
else:
groups = [("Observed", y), ("Filtered level", f_mid)] + ([("Smoothed level", s_mid)] if sm else [])
charts.append(cs.chart("states", "series-line", f"{VALUE} with the hidden level", {
"x": cs.col(xname, [v for _ in groups for v in labels], kind=xkind),
"y": cs.col(VALUE, np.concatenate([g[1] for g in groups])),
"group": cs.col("series", [g[0] for g in groups for _ in range(T)], kind="categorical")}))
if mcmc is not None:
step = max(1, ITERATIONS // 500)
it_idx = list(range(0, ITERATIONS, step))
charts.append(cs.chart("trace", "series-line", "PMMH chains (every parameter, natural scale)", {
"x": cs.col("iteration", [float(i + 1) for _ in names for i in it_idx]),
"y": cs.col("value", np.concatenate([chain_nat[it_idx, j] for j in range(len(names))])),
"group": cs.col("parameter", [LABELS[k] for k in names for _ in it_idx], kind="categorical")}))
for j, k in enumerate(names):
col = chain_nat[BURN_IN:, j]
grid = pf.density_grid(col)
post = pf.kde(col, grid)
prior = pf.prior_density(mcmc["prior"][j], grid)
charts.append(cs.chart(f"posterior_{k}", "prior-posterior", f"{LABELS[k]}: prior and PMMH posterior", {
"x": cs.col(LABELS[k], np.concatenate([grid, grid])), "density": cs.col("density", np.concatenate([prior, post])),
"curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
# %% Tables
tables = [{"key": "parameters", "title": "Parameters",
"columns": [{"key": "param", "label": "Parameter", "type": "string"}, {"key": "estimate", "label": "Value", "type": "number"},
{"key": "lo", "label": "5%", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
{"key": "ess", "label": "Effective draws", "type": "number"}, {"key": "source", "label": "Source", "type": "string"}],
"rows": param_rows},
{"key": "likelihood", "title": "Log-likelihood",
"columns": [{"key": "what", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"what": f"Particle estimate ({N_FINAL} particles)", "value": run["loglik"]},
{"what": "SD over five filter runs", "value": ll_sd}]
+ ([{"what": "Exact (Kalman filter)", "value": kal["loglik"]}] if kal else [])}]
CAP = 2000
st_label = "volatility" if MODEL == "stochastic_volatility" else "level"
state_rows = []
for t in range(min(T, CAP)):
r = {"time": str(labels[t]), "observed": float(y_raw[t]), "filtered": float(f_mid[t]), "f_lo": float(f_lo[t]), "f_hi": float(f_hi[t])}
if sm:
r.update({"smoothed": float(s_mid[t]), "s_lo": float(s_lo[t]), "s_hi": float(s_hi[t])})
if MODEL == "local_trend":
r["slope"] = float(run["mean"][t, 1])
state_rows.append(r)
state_cols = [{"key": "time", "label": TIME or "Step", "type": "string"}, {"key": "observed", "label": VALUE, "type": "number"},
{"key": "filtered", "label": f"Filtered {st_label}" + (" (median)" if MODEL == "stochastic_volatility" else ""), "type": "number"},
{"key": "f_lo", "label": "5%", "type": "number"}, {"key": "f_hi", "label": "95%", "type": "number"}]
if sm:
state_cols += [{"key": "smoothed", "label": f"Smoothed {st_label}", "type": "number"},
{"key": "s_lo", "label": "5% (smoothed)", "type": "number"}, {"key": "s_hi", "label": "95% (smoothed)", "type": "number"}]
if MODEL == "local_trend":
state_cols.append({"key": "slope", "label": "Filtered slope", "type": "number"})
tables.append({"key": "states", "title": "Hidden state at each step" + (f" (first {CAP} of {T})" if T > CAP else ""), "columns": state_cols, "rows": state_rows})
# %% Result
est_txt = "estimated by PMMH" if ESTIMATE == "pmmh" else "set"
summary = (f"A {MODEL_LABEL} particle filter of {VALUE} ({T} steps, {N_FINAL} particles; parameters {est_txt}) has log-likelihood "
f"{run['loglik']:.2f} (SD {ll_sd:.2f} over five runs)" + (f"; the exact Kalman value is {kal['loglik']:.2f}" if kal else "")
+ f". The last filtered {st_label} is {f_mid[-1]:.4g} (90% band {f_lo[-1]:.4g} to {f_hi[-1]:.4g}).")
notes = ["A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are "
"resampled systematically " + ("at every step." if THRESHOLD >= 1.0 else "when the effective sample size drops below half the particles."),
"Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series."]
if MODEL == "stochastic_volatility":
notes.append(f"Returns are centered (mean {y_mean:.4g} removed); the volatility is exp(h/2) and its band maps h's quantiles.")
else:
notes.append("The first hidden state starts at the first observation with the series' variance" + (" (slope at 0 with the differences' variance)" if MODEL == "local_trend" else "")
+ "; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.")
if ESTIMATE == "pmmh":
notes.append(f"PMMH ran {ITERATIONS} iterations ({BURN_IN} burn-in, step size adapted during burn-in) with {N_PMMH} particles per step; priors: normal on log σ "
"centered at the data-based value (SD 2)" + (", normal on μ (SD 3), uniform φ on (−1, 1)" if MODEL == "stochastic_volatility" else "")
+ ". The final filter uses the posterior means.")
statistics = [{"key": "loglik", "label": "Log-likelihood (particle)", "value": run["loglik"]}, {"key": "loglik_sd", "label": "Log-likelihood SD", "value": ll_sd}]
if kal:
statistics.append({"key": "kalman_loglik", "label": "Log-likelihood (Kalman)", "value": kal["loglik"]})
if mcmc is not None:
statistics.append({"key": "acceptance", "label": "Acceptance rate", "value": mcmc["acceptance"]})
cs.publish({
"method": "ts.particle_filter",
"methodVersion": "1.0.0",
"title": "Particle filter",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": T,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
For the Nile model, PMMH accepts 38% of proposals, with a log-likelihood SD of 0.45. For stochastic volatility on returns, the SD is 1.14 and acceptance falls to 20%; its smallest effective sample size across parameters is only 4.7. These short example runs are for speed: a real analysis needs far more iterations.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| SMC and particle filtering (INF015) | Runs in CodeSplash: Particle filter (state-space model with PMMH) (local level, local trend, stochastic volatility and more), Python ≡ R; SMC-ABC in Calibrate a scenario model |
| Particle MCMC (INF016) | Partly runs in CodeSplash: PMMH (estimate: pmmh) in the particle filter; particle Gibbs isn't offered |
The lesson Tracking a hidden state: particle filters (Time series) walks through the method's own options.
Check your understanding
CheckpointCheck yourself
After an informative observation, 3 of 1,000 particles carry 95% of the weight. You resample. What have you gained?
Show the answer
Answer: b
Resampling fights weight degeneracy by duplicating, not by exploring. More particles, a proposal that looks at the observation, or move steps after resampling restore diversity.
Check yourself
How does a particle filter estimate the likelihood of the whole series?
Show the answer
Answer: b
The product of mean incremental weights is an unbiased estimate of . Averaging logs answers a different question.
Check yourself
Why does the Nile local-level example compare the particle filter's log-likelihood with the Kalman filter's?
Show the answer
Answer: b
Validate on a special case with a known answer before trusting the filter on nonlinear or non-Gaussian models.
Check yourself
What makes PMMH exact despite using a noisy likelihood estimate?
Show the answer
Answer: b
The algorithm is MH on an extended space that includes the filter's randomness. Recomputing the current estimate breaks that construction.
Check yourself
A PMMH chain accepts very few proposals and its trace shows long flat runs. The log-likelihood estimate's SD at typical parameters is large. What's the first fix?
Show the answer
Answer: b
A lucky high estimate is hard to beat, so the chain sticks. Fewer-noise estimates (more particles) or better filter proposals cure it; recomputing breaks exactness.
Recap
Recap- SMC carries weighted particles through a sequence of distributions: move, reweight, resample.
- Resampling fixes unequal weights, not missing regions; long histories degenerate.
- Multiply mean incremental weights to estimate the likelihood; check against Kalman when you can.
- PMMH is exact with an unbiased likelihood estimate and kept-on-rejection bookkeeping; noisy estimates make it sticky.
Concepts in this lesson