This is a great question about particle filters, which are an important technique in state estimation, especially for nonlinear and non-Gaussian problems. Let me provide a comprehensive explanation covering:
- The basic concept of particle filters
- Why they're needed (limitations of Kalman filters)
- The particle filter algorithm (prediction and update steps)
- Resampling and why it's important
- Different resampling strategies
- Comparison with Kalman filters
- Practical considerations
Let me structure this thoroughly with good explanations and examples.
Particle Filters for State Estimation
Particle filters are a sequential Monte Carlo method for state estimation that handles arbitrary nonlinear systems and non-Gaussian distributions. Here's a comprehensive explanation:
1. Why Particle Filters?
Limitations of Kalman Filters
# Kalman filter assumes:
# x_k = A*x_{k-1} + w_k (linear dynamics)
# z_k = C*x_k + v_k (linear measurement)
# w, v ~ N(0, Q), N(0, R) (Gaussian noise)
# Particle filters handle:
# x_k = f(x_{k-1}, w_k) (nonlinear dynamics)
# z_k = h(x_k, v_k) (nonlinear measurement)
# p(w), p(v) = arbitrary (any distribution)
Example: Non-Gaussian tracking
import numpy as np
import matplotlib.pyplot as plt
# System with multimodal distribution (two possible targets)
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
# Gaussian (Kalman) vs Non-Gaussian (particle filter)
x = np.linspace(-5, 5, 1000)
# Kalman: unimodal Gaussian
gaussian = (1/np.sqrt(2*np.pi)) * np.exp(-x**2/2)
# Particle filter: multimodal
bimodal = 0.5*np.exp(-((x-2)**2)/0.5) + 0.5*np.exp(-((x+2)**2)/0.5)
bimodal /= bimodal.max()
axes[0].fill_between(x, gaussian, alpha=0.6, label='Kalman (unimodal)')
axes[0].set_title('Kalman Filter: Gaussian Assumption')
axes[0].legend()
axes[0].grid()
axes[1].fill_between(x, bimodal, alpha=0.6, color='orange', label='Particle Filter')
axes[1].set_title('Particle Filter: Multimodal Distribution')
axes[1].legend()
axes[1].grid()
plt.tight_layout()
plt.show()
2. Core Particle Filter Algorithm
Conceptual Overview
Represent probability distribution as set of samples (particles) with weights:
{x_i^(k), w_i^(k)} for i = 1,...,N
Each particle represents a possible state estimate with probability w_i^(k)
Complete Algorithm
class ParticleFilter:
"""Sequential Importance Resampling (SIR) particle filter"""
def __init__(self, N_particles, dynamics_fn, measurement_fn):
"""
N_particles: number of particles
dynamics_fn: f(x_{k-1}, w_k) → x_k
measurement_fn: h(x_k, v_k) → z_k
"""
self.N = N_particles
self.f = dynamics_fn # State transition
self.h = measurement_fn # Measurement model
def initialize(self, x0_dist, N=None):
"""Initialize particles from prior distribution"""
if N is None:
N = self.N
# Sample particles uniformly from prior
self.particles = x0_dist(N)
self.weights = np.ones(N) / N # Uniform weights
self.N = N
return self.particles, self.weights
def predict(self, process_noise_fn):
"""Prediction step: propagate through dynamics model"""
# Sample process noise
w = process_noise_fn(self.N)
# Propagate each particle
for i in range(self.N):
self.particles[i] = self.f(self.particles[i], w[i])
# Weights remain unchanged (or slightly decay in some variants)
# self.weights stay the same after prediction
def update(self, z, measurement_noise_fn):
"""Update step: evaluate likelihood and weight particles"""
# Evaluate likelihood for each particle
likelihoods = np.zeros(self.N)
for i in range(self.N):
# Optional: sample measurement noise for stochastic model
v = measurement_noise_fn()
# Compute likelihood p(z_k | x_i^(k))
z_pred = self.h(self.particles[i], v)
residual = z - z_pred
# Gaussian likelihood (can use other forms)
likelihood = np.exp(-0.5 * np.sum(residual**2))
likelihoods[i] = likelihood
# Update weights (importance weights)
self.weights *= likelihoods
# Normalize weights
weight_sum = np.sum(self.weights)
if weight_sum > 0:
self.weights /= weight_sum
else:
# Collapse: reset to uniform if all weights ~0
self.weights = np.ones(self.N) / self.N
return self.weights.copy()
def estimate(self):
"""Compute state estimate as weighted mean"""
return np.average(self.particles, weights=self.weights, axis=0)
def step(self, z, process_noise_fn, measurement_noise_fn):
"""One complete filter iteration"""
self.predict(process_noise_fn)
self.update(z, measurement_noise_fn)
return self.estimate()
3. Resampling: The Critical Step
The Problem: Particle Degeneracy
# After many iterations WITHOUT resampling:
# - Most particles have negligible weight (w_i ≈ 0)
# - Few particles carry nearly all probability mass
# - Computational effort wasted on low-weight particles
# - Effective sample size approaches 1
class DegeneracyDemo:
"""Demonstrate particle degeneracy problem"""
def __init__(self, N_particles=1000):
self.N = N_particles
self.weights = np.ones(N_particles) / N_particles
def simulate_degeneracy(self, iterations=50):
"""Simulate weight collapse without resampling"""
weight_history = []
neff_history = []
for _ in range(iterations):
# Simulate exponential weight decay
self.weights *= (0.95 ** np.random.exponential(1, self.N))
self.weights /= self.weights.sum()
# Compute effective sample size (ESS)
N_eff = 1.0 / np.sum(self.weights ** 2)
weight_history.append(self.weights.copy())
neff_history.append(N_eff)
return weight_history, neff_history
# Visualization
demo = DegeneracyDemo(N_particles=1000)
weight_hist, neff_hist = demo.simulate_degeneracy()
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# Initial weights
axes[0].hist(weight_hist[0], bins=50, alpha=0.7)
axes[0].set_title('Initial Weights (Iteration 0)')
axes[0].set_ylabel('Count')
axes[0].set_xlim([0, 0.01])
# After degeneracy
axes[1].hist(weight_hist[-1], bins=50, alpha=0.7, color='red')
axes[1].set_title('Degenerate Weights (Iteration 50)')
axes[1].set_ylabel('Count')
axes[1].set_xlim([0, 0.01])
# Effective sample size decay
axes[2].plot(neff_hist, 'b-', linewidth=2)
axes[2].axhline(1000, color='g', linestyle='--', label='Perfect (N=1000)')
axes[2].set_title('Effective Sample Size Over Time')
axes[2].set_ylabel('N_eff')
axes[2].set_xlabel('Iteration')
axes[2].legend()
axes[2].grid()
plt.tight_layout()
plt.show()
Solution: Resampling Strategies
1. Multinomial Resampling (Simplest)
def resample_multinomial(particles, weights):
"""
Resample according to weight distribution
High-weight particles duplicated, low-weight eliminated
"""
N = len(weights)
# Draw indices according to weight probabilities
indices = np.random.multinomial(N, weights)
# Expand particles according to indices
new_particles = []
new_weights = np.ones(N) / N # Reset to uniform
for i, count in enumerate(indices):
new_particles.extend([particles[i]] * count)
return np.array(new_particles), new_weights
Issues: High variance, can cause particle collapse
2. Systematic Resampling (Better - Reduces Variance)
def resample_systematic(particles, weights):
"""
Deterministic alternative to multinomial
- Lower variance
- Better particle diversity
"""
N = len(weights)
# Cumulative distribution
cum_weights = np.cumsum(weights)
# Uniform grid with random offset
u = (np.arange(N) + np.random.uniform(0, 1)) / N
# Find particles for each u value
indices = np.searchsorted(cum_weights, u)
new_particles = particles[indices]
new_weights = np.ones(N) / N
return new_particles, new_weights
# Visual example
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Multinomial resampling visualization
weights_example = np.array([0.1, 0.05, 0.5, 0.2, 0.15])
indices_multi = np.random.multinomial(100, weights_example)
axes[0].bar(range(5), indices_multi)
axes[0].set_title('Multinomial Resampling\n(High variance)')
axes[0].set_ylabel('Number of Copies')
axes[0].set_xlabel('Particle Index')
# Systematic resampling
cum_weights = np.cumsum(weights_example)
u = (np.arange(5) + np.random.uniform(0, 1)) / 5
indices_sys = np.searchsorted(cum_weights, u)
indices_counts = np.bincount(indices_sys, minlength=5)
axes[1].bar(range(5), indices_counts)
axes[1].set_title('Systematic Resampling\n(Lower variance)')
axes[1].set_ylabel('Number of Copies')
axes[1].set_xlabel('Particle Index')
plt.tight_layout()
plt.show()
3. Stratified Resampling (Also Good)
def resample_stratified(particles, weights):
"""
Like systematic but with non-overlapping strata
"""
N = len(weights)
cum_weights = np.cumsum(weights)
# Stratified uniform samples
u = (np.arange(N) + np.random.uniform(0, 1, N)) / N
indices = np.searchsorted(cum_weights, u)
return particles[indices], np.ones(N) / N
4. Residual Resampling (Deterministic)
def resample_residual(particles, weights):
"""
Deterministic resampling:
- Each particle gets floor(N*w_i) copies deterministically
- Remaining particles sampled stochastically
"""
N = len(weights)
# Deterministic copies
num_copies = (N * weights).astype(int)
residual_weights = N * weights - num_copies
residual_weights /= residual_weights.sum()
# Deterministic part
new_indices = np.repeat(np.arange(N), num_copies)
# Stochastic part for remainder
num_stoch = N - len(new_indices)
stoch_indices = np.random.choice(N, num_stoch, p=residual_weights)
new_indices = np.concatenate([new_indices, stoch_indices])
return particles[new_indices], np.ones(N) / N
When to Resample?
def adaptive_resample(particles, weights, threshold=0.5):
"""
Only resample when diversity is low
Reduces correlation between particles
"""
# Effective sample size
N_eff = 1.0 / np.sum(weights ** 2)
N_threshold = threshold * len(weights)
if N_eff < N_threshold:
print(f"Resampling: N_eff={N_eff:.0f} < threshold={N_threshold:.0f}")
return resample_systematic(particles, weights)
else:
return particles, weights
4. Complete Working Example
class TrulyNonlinearSystem:
"""
Highly nonlinear system that Kalman fails on
x_k = x_{k-1}/2 + 25*x_{k-1}/(1+x_{k-1}^2) + 8*cos(1.2*k) + w_k
z_k = x_k^2/20 + v_k
"""
def dynamics(self, x, w):
return (x/2 + 25*x/(1 + x**2) +
8*np.cos(1.2*self.k) + w)
def measurement(self, x, v):
return x**2/20 + v
def __init__(self):
self.k = 0
# Generate synthetic data
true_system = TrulyNonlinearSystem()
T = 100
np.random.seed(42)
# True state trajectory
x_true = np.zeros(T)
z_meas = np.zeros(T)
for k in range(T):
true_system.k = k
x_true[k] = true_system.dynamics(x_true[k-1] if k > 0 else 0,
np.random.randn())
z_meas[k] = true_system.measurement(x_true[k], np.random.randn())
# Particle Filter Estimation
pf = ParticleFilter(
N_particles=500,
dynamics_fn=lambda x, w: x/2 + 25*x/(1 + x**2) + w,
measurement_fn=lambda x, v: x**2/20 + v
)
# Initialize
pf.initialize(lambda N: np.random.randn(N) * 5, N=500)
# Filter
x_est = np.zeros(T)
x_std = np.zeros(T)
for k in range(T):
# Noise generators
process_noise = lambda N: np.random.randn(N) * 1.0
measurement_noise = lambda: np.random.randn() * 1.0
# Filter step
x_est[k] = pf.step(z_meas[k], process_noise, measurement_noise)
x_std[k] = np.std(pf.particles)
# Adaptive resampling
pf.particles, pf.weights = adaptive_resample(
pf.particles, pf.weights, threshold=0.5
)
# Visualization
fig, axes = plt.subplots(2, 1, figsize=(14, 8))
# Trajectory
axes[0].plot(x_true, 'ko-', linewidth=2, markersize=4, label='True State')
axes[0].plot(x_est, 'b*-', linewidth=2, markersize=8, label='PF Estimate')
axes[0].fill_between(range(T),
x_est - 2*x_std,
x_est + 2*x_std,
alpha=0.3, label='±2σ')
axes[0].scatter(range(T), z_meas, alpha=0.3, s=20, label='Measurements')
axes[0].set_ylabel('State Value')
axes[0].legend()
axes[0].grid()
axes[0].set_title('Particle Filter on Highly Nonlinear System')
# Error
error = np.abs(x_est - x_true)
axes[1].plot(error, 'r-', linewidth=2)
axes[1].fill_between(range(T), 0, error, alpha=0.3)
axes[1].set_ylabel('Absolute Error')
axes[1].set_xlabel('Time Step')
axes[1].grid()
axes[1].set_title('Estimation Error Over Time')
plt.tight_layout()
plt.show()
print(f"RMSE: {np.sqrt(np.mean(error**2)):.4f}")
5. Key Insights & Comparison
| Aspect | Kalman Filter | Particle Filter |
|---|
| Nonlinearity | Limited (EKF/UKF) | Excellent |
| Non-Gaussian | ❌ Assumes Gaussian | ✓ Handles arbitrary |
| Multimodal | ❌ Unimodal only | ✓ Multimodal |
| Computational | Fast O(n³) | Slower O(N·n²) |
| Implementation | Simple | Complex |
| Theory | Optimal (linear) | Asymptotically optimal |
6. Practical Considerations
# Common pitfalls and solutions:
pitfalls = {
"Particle collapse": {
"cause": "Too few particles or poor proposal",
"solution": "Increase N, use better proposal q(x_k|x_{k-1})"
},
"Sample impoverishment": {
"cause": "All particles identical after resampling",
"solution": "Add jitter, use auxiliary PF"
},
"Weight degeneracy": {
"cause": "High-dimensional spaces",
"solution": "Use Rao-Blackwellization, adaptive resampling"
},
"Poor proposals": {
"cause": "Simple prior as proposal",
"solution": "Use optimal proposal or extended state"
}
}
Particle filters excel where traditional methods fail—highly nonlinear systems with arbitrary noise distributions!