Skip to content

Particle filtering of a renewal model with LowLevelParticleFilters.jl ​

Introduction ​

This page is for readers who want to fit a stochastic renewal model to daily case counts with a particle filter. It estimates the latent infections and two parameters of the model. The filtering and the sampling are done by LowLevelParticleFilters.jl, and a Recurrence supplies the one-step dynamics of each particle. The first part runs a bootstrap particle filter [] for fixed parameters. The second part samples the posterior distribution of the parameters by particle marginal Metropolis–Hastings []. The third part runs the same filter with the particles as strata of one recurrence, which is faster and also runs on a device array.

A particle filter is one choice among many. The operators are ordinary differentiable Julia functions, so any fitting approach works with them, from conjugate updates to optimisation and MCMC with Turing.jl or a similar package. For Bayesian fitting we recommend Wren.jl.

It assumes you have read Three towns, step by step and Forecasting, which introduces a State.

Packages used ​

julia
using ComposableRecurrences
using ComposableRecurrences: Depletion, Resume, State, advance!, select
using LowLevelParticleFilters
using StaticArrays: SVector
using Distributions: Categorical, Dirac, Normal, Poisson, product_distribution
using LogExpFunctions: logistic, logsumexp, softmax
using SpecialFunctions: loggamma
using Adapt: adapt
using JLArrays: JLArray
using Random, Statistics
using CairoMakie, AlgebraOfGraphics, DataFramesMeta

CairoMakie.activate!(type = "png", px_per_unit = 2)
small = (size = (600, 280),)

Model ​

Infections follow a renewal equation [] with multiplicative noise in transmission and depletion of a finite population of size :

where is the number of infections on day , the number of susceptible people and the number of reported cases. is the probability that the generation interval is days, the basic reproduction number, the standard deviation of the log transmission noise and the reporting probability. The latent state on day is  , and the parameters are  .

The model is three objects, one for each of its parts. renewal is the second to fourth lines given the gain  : a Recurrence with a Depletion modifier. transmission returns the gain from the parameters and a noise draw, and draws nothing itself. count_logpdf is the log density of the last line.

julia
generation_interval = [0.1, 0.3, 0.3, 0.2, 0.1]
population = 20_000.0
renewal = Recurrence(generation_interval; modifiers = (Depletion(population),))

transmission(θ, ε) = θ.R * exp(θ.σ * ε)
count_logpdf(c, I, θ) = c * log(θ.ρ * I) - θ.ρ * I - loggamma(c + 1)

We simulate   days with  ,   and  , from 5 infections on each of the days before day 1.

julia
T = 60
truth = (R = 1.8, ρ = 0.3, σ = 0.25)
seed = fill(5.0, length(generation_interval))
Random.seed!(1)
infections = renewal(transmission.(Ref(truth), randn(T)); history = seed)
cases = rand.(Poisson.(truth.ρ .* infections))

days = DataFrame(day = 1:T, infections = infections, cases = cases)
@chain days begin
    data(_) * (
        mapping(:day, :infections) * visual(Lines, linewidth = 2) +
            mapping(:day, :cases) * visual(Scatter, color = :black)
    )
    draw(_; axis = (xlabel = "Day", ylabel = "Daily count"), figure = small)
end

The line shows the simulated infections and the points the simulated cases.

The model as a state-space model ​

LowLevelParticleFilters.jl holds each particle as a static vector and asks the model for three functions: the transition of one particle, the expected observation and the log density of an observation. Its AdvancedParticleFilter takes a transition that draws its own noise, which this model needs because the noise is not additive.

A State holds what the next step of a recurrence reads, and vec returns it as one vector: the last infections, oldest first, then the susceptible pool. That vector is . before is the state before day 1, which a call with stop = 0 returns without running a step.

julia
before = renewal(; history = seed, stop = 0, record = Resume()).state
vec(before)
6-element Vector{Float64}:
     5.0
     5.0
     5.0
     5.0
     5.0
 20000.0

The transition rebuilds the state from the particle with State(before, x), runs one step with advance! and returns the new state as a vector. randn_noise(noise) is the filter's standard normal draw, and zero when the filter asks for the transition without noise. Time is absolute in every call of a recurrence and the particle holds none. Nothing in this model varies with time, so each particle steps from before.t; a model with a time-varying part passes the day as State(before, x; t).

julia
function renewal_dynamics(renewal, before)
    return function (x, u, θ, t, noise = false)
        gain = transmission(θ, randn_noise(noise))
        state = advance!(renewal, State(before, x), gain).state
        return oftype(x, vec(state))
    end
end
latest_infections(x) = x[end - 1]
expected_cases(x, u, θ, t, noise = false) = SVector(θ.ρ * latest_infections(x))
likelihood(x, u, c, θ, t) = count_logpdf(c, latest_infections(x), θ)

The state before day 1 is known, so the initial distribution is a point mass at vec(before). particle_filter builds the filter for a parameter value.

julia
dynamics = renewal_dynamics(renewal, before)
initial = product_distribution(Dirac.(vec(before)))
function particle_filter(θ; particles = 1000)
    return AdvancedParticleFilter(
        particles, dynamics, expected_cases, likelihood, nothing, initial; p = θ
    )
end

Part 1: bootstrap particle filter ​

The filter keeps a weighted set of particles, each a guess of , and reweights them by how well they predict each day's count.

How the bootstrap filter works

The filter approximates the distribution of given by particles with weights []. On each day it draws from the transition density given and multiplies each weight by the observation density:

The effective sample size is , where are the normalised weights. When it falls below , the particles are resampled in proportion to their weights and the weights are reset to []. These are the defaults of AdvancedParticleFilter, which uses systematic resampling []. The product over days of the weighted mean of the observation densities is an unbiased estimate of the likelihood   [].

Filtered infections ​

The filter updates with an observation and then predicts, so the data start with a missing value for the state before day 1. The model has no input, which the filter still takes as a vector. We run it at the simulating parameters with  .

julia
observed = [missing; cases]
inputs = zeros(T + 1)
Random.seed!(2)
fit = forward_trajectory(particle_filter(truth), inputs, observed)

central = latest_infections.(weighted_mean(fit.x, fit.we))
lower = latest_infections.(weighted_quantile(fit, 0.05))
upper = latest_infections.(weighted_quantile(fit, 0.95))
band = DataFrame(
    day = 1:T, mean = central[2:end], lower = lower[2:end],
    upper = upper[2:end]
)
@chain band begin
    data(_) * (
        mapping(:day, :lower, :upper) * visual(Band, alpha = 0.3) +
            mapping(:day, :mean) * visual(Lines, linewidth = 2)
    ) + data(days) * mapping(:day, :infections) *
        visual(Lines, color = :black, linestyle = :dash)
    draw(_; axis = (xlabel = "Day", ylabel = "Infections"), figure = small)
end

The solid line is the filtering mean, the band the 5% to 95% filtering interval and the dashed line the simulated infections. The proportion of days on which the interval contains the simulated infections is

julia
coverage = mean(band.lower .<= infections .<= band.upper)
round(coverage; digits = 2)
0.9

Likelihood estimate ​

The estimate   varies between runs of the filter. The mean and standard deviation of 50 runs at the simulating parameters are

julia
replicates(f, n) = [f() for _ in 1:n]
summary(x) = round.((mean(x), std(x)); digits = 2)

filter_at_truth = particle_filter(truth)
by_particle = replicates(50) do
    loglik(filter_at_truth, inputs, observed)
end
summary(by_particle)
(-227.0, 0.41)

Part 2: particle marginal Metropolis–Hastings ​

Particle marginal Metropolis–Hastings is a Metropolis–Hastings sampler of in which the likelihood is replaced by the estimate of a particle filter []. It samples the parameters that part 1 held fixed.

How the sampler works

From the current value with estimate  , a proposal is drawn from a symmetric random walk, a new filter is run for it, and it is accepted with probability

where is the prior density. The estimate of an accepted proposal is kept with it. Because the estimate is unbiased, the chain targets the posterior distribution   for any number of particles.

Prior ​

We estimate and and fix at its simulating value. The parameters are sampled on unconstrained scales,  , with priors   and  .

julia
priors = [Normal(log(1.5), 0.5), Normal(0, 1)]
parameters(z) = (R = exp(z[1]), ρ = logistic(z[2]), σ = truth.σ)

Posterior ​

log_likelihood_fun returns the function     from a function that builds the filter for , and metropolis runs the sampler on it. We use   particles, 4000 iterations and a random walk with standard deviations 0.05 and 0.08, and discard the first 1000 iterations.

julia
log_target = log_likelihood_fun(
    z -> particle_filter(parameters(z); particles = 200), priors, inputs,
    observed
)
proposal(z) = z .+ [0.05, 0.08] .* randn(2)
Random.seed!(3)
chain, _ = metropolis(log_target, 4000, [log(1.5), 0.0], proposal)
kept = chain[1001:end]
acceptance = mean(kept[i] != kept[i - 1] for i in 2:length(kept))
round(acceptance; digits = 2)
0.28

The value above is the proportion of proposals accepted.

julia
draws = DataFrame(R = exp.(first.(kept)), ρ = logistic.(last.(kept)))
@chain draws begin
    data(_) * mapping(:R, :ρ) *
        visual(Scatter, color = (:grey, 0.3), markersize = 4) +
        mapping([truth.R], [truth.ρ]) *
        visual(Scatter, color = :black, marker = :cross, markersize = 18)
    draw(_; axis = (xlabel = "R", ylabel = "ρ"), figure = small)
end

Each point is a draw from the chain, and the cross marks the simulating values. The posterior mean and the 5% and 95% posterior quantiles of each parameter are

julia
function interval(x)
    return round.((mean(x), quantile(x, 0.05), quantile(x, 0.95)); digits = 2)
end
estimates = (R = interval(draws.R), ρ = interval(draws.ρ))
(R = (1.64, 1.53, 1.77), ρ = (0.31, 0.29, 0.34))

For this data set the interval of contains its simulating value, 0.3, and the interval of lies below its simulating value, 1.8. A 90% interval misses the simulating value for one data set in ten.

Part 3: particles as strata ​

Implementation ​

The filter above calls the recurrence once for each particle on each day. A recurrence steps any number of independent strata in one call, so the particles can be its strata. One call of advance! then advances every particle by a day, with the noise as a gain for each stratum, PerStratum. select(state, ancestors) returns the state whose stratum is stratum ancestors[i], which is the resampling step.

batched_filter is the bootstrap filter of part 1 with multinomial resampling on every day, and returns the log likelihood estimate. It uses the same transmission and count_logpdf, and takes the noise draw and the resampler as arguments. The log weights are copied to the host, where the ancestors are drawn.

julia
multinomial(logw) = rand(Categorical(softmax(logw)), length(logw))

function batched_filter(
        renewal, θ, cases, history; noise! = randn!, resample = multinomial
    )
    state = renewal(; history, stop = 0, record = Resume()).state
    ε = similar(history, size(history, 1))
    loglik = 0.0
    for c in cases
        gain = PerStratum(transmission.(Ref(θ), noise!(ε)))
        (; y, state) = advance!(renewal, state, gain)
        logw = Array(count_logpdf.(c, vec(y), Ref(θ)))
        loglik += logsumexp(logw) - log(length(logw))
        state = select(state, resample(logw))
    end
    return loglik
end

Agreement with part 1 ​

The history has a row for each particle. The mean and standard deviation of 50 runs at the simulating parameters, with  , are

julia
history = repeat(permutedims(seed), 1000)
by_stratum = replicates(50) do
    batched_filter(renewal, truth, cases, history)
end
summary(by_stratum)
(-227.13, 0.35)

Both filters estimate the same likelihood without bias, so the logarithms of the means of their estimates agree up to Monte Carlo error. Their difference and its standard error are

julia
log_mean(x) = logsumexp(x) - log(length(x))
# The delta-method standard error of the log of a mean of estimates.
function log_mean_error(x)
    return std(exp.(x .- maximum(x))) /
        (mean(exp.(x .- maximum(x))) * sqrt(length(x)))
end
difference = log_mean(by_particle) - log_mean(by_stratum)
standard_error = hypot(log_mean_error(by_particle), log_mean_error(by_stratum))
round.((difference, standard_error); digits = 2)
(0.15, 0.08)

Time for one pass ​

The time of one pass of each filter with  , in milliseconds, on the machine that built this page:

julia
function milliseconds(f)
    f()
    return round(1000 * minimum(@elapsed(f()) for _ in 1:5); digits = 1)
end
(
    by_particle = milliseconds(() -> loglik(filter_at_truth, inputs, observed)),
    by_stratum = milliseconds(
        () -> batched_filter(renewal, truth, cases, history)
    ),
)
(by_particle = 18.2, by_stratum = 5.3)

On a device array ​

batched_filter indexes no array, so it runs unchanged when the recurrence and the history are on a device. JLArrays.jl provides a reference device array that runs on the CPU.

julia
on_device = batched_filter(
    adapt(JLArray, renewal), truth, cases, JLArray(history)
)
round(on_device; digits = 2)
-227.02

The value is one more draw of the estimate above, from the device's random number generator.

Running on a GPU ​

This page has not been run on a physical GPU. JLArrays.jl checks that the code uses only operations a device array supports, and says nothing about speed. A run on a GPU needs the following.

  • A GPU array package, such as CUDA.jl, loaded together with KernelAbstractions.jl, so that the device extension is active.

  • The recurrence and the history moved to the device with adapt, as above, and usually single precision, which convert_floats sets for the recurrence.

  • transmission and count_logpdf compiled for the device, since they run inside a broadcast over the particles.

The log weights return to the host on every day for the resampling draw, which is one transfer of numbers per observation.

References ​

  1. C. Fraser. Estimating individual and household reproduction numbers in an emerging epidemic. PLoS ONE 2, e758 (2007).

  2. N. J. Gordon, D. J. Salmond and A. F. Smith. Novel approach to nonlinear/non-Gaussian Bayesian state estimation. IEE Proceedings F (Radar and Signal Processing) 140, 107–113 (1993).

  3. C. Andrieu, A. Doucet and R. Holenstein. Particle Markov chain Monte Carlo methods. Journal of the Royal Statistical Society: Series B (Statistical Methodology) 72, 269–342 (2010).

  4. J. S. Liu and R. Chen. Sequential Monte Carlo methods for dynamic systems. Journal of the American Statistical Association 93, 1032–1044 (1998).

  5. J. Carpenter, P. Clifford and P. Fearnhead. Improved particle filter for nonlinear problems. IEE Proceedings - Radar, Sonar and Navigation 146, 2–7 (1999).