Generator, Kolmogorov, Fokker-Planck and Feynman-Kac
Connect SDEs and PDEs through the infinitesimal generator, Dynkin's formula, backward Kolmogorov and forward Fokker-Planck equations, stationary densities, exit times and Feynman-Kac.
After this lesson you can
- Calculate a diffusion generator and use Dynkin's formula for exit probabilities and expected times.
- Derive backward Kolmogorov and Fokker-Planck equations and explain their adjoint relationship.
- Obtain stationary densities of scalar and gradient diffusions and check them by simulation.
- Solve a parabolic PDE with Feynman-Kac Monte Carlo and compare with finite differences.
- Relate Fokker-Planck density evolution to continuity and probability current.
Before you start
- 26Stochastic differential equationItô's lemmaOrnstein-Uhlenbeck processLangevin dynamicsRate matrix (Q-matrix)Kolmogorov equations for CTMCsReversibility and detailed balanceEuler-Maruyama scheme
- 03Heat equationTransport and continuity equationsClassification and well-posedness of PDEsDivergence theorem
- 29Finite difference stencils for PDEs
- 09Finite differences
One law, two ways to evolve
A particle follows a random path; a density describes where a collection of particles may be found. To value a payoff, estimate the probability of escaping a safe region or understand a generative model, you can simulate paths or solve an equation for their probabilities. The descriptions are connected but ask about different variables.
In the figure, density equation and particles share drift, diffusion and boundary. Change the potential and observe how mass is distributed. Discrepancy between histogram and curve includes Monte Carlo fluctuation and discretization errors; conserving mass does not guarantee the numerical density is exact.
The infinitesimal generator
For Itô diffusion , with , and coefficients ensuring a nonexplosive solution, the generator acts on sufficiently regular functions:
For and under the usual assumptions permitting passage to the limit, . The first term is transport; the second comes from quadratic variation. It is analogous to the generator matrix of a continuous-time chain: both describe instantaneous change in a state function.
Applying Itô and integrating gives Dynkin’s formula. If is a stopping time and the integrals are integrable, then
Bounded stopping and integrability assumptions allow the stochastic term to have zero expectation. Removing the time limit or using unbounded functions requires justification of convergence and boundary conditions.
Let be the first exit from a regular domain and part of its boundary. If inside, on and on the remainder, Dynkin identifies under assumptions guaranteeing exit and a solution. Mean time satisfies inside and on the boundary when finite. Points where the boundary condition changes abruptly may require appropriate interpretation.
For standard Brownian motion on , and with , so . The numerical exercise asks you to evaluate this solution at another position. The figure uses a discrete domain and walk: its results approximate the continuous problem under refinement and suitable conditions; they are not exact continuous Brownian paths.
Backward and forward
For terminal payoff , define in a homogeneous model. The Markov property gives . Expanding in , or applying Itô to , yields the backward Kolmogorov equation
Variable represents the initial state of the remaining interval and a terminal condition is prescribed. This derivation requires sufficient regularity of and an integrable martingale; when regularity is absent, weaker solution notions are used.
For law , by contrast, an initial condition is prescribed. If is smooth and compactly supported, Itô and expectation give . Integration by parts yields adjoint and the Fokker-Planck equation:
State-dependent diffusion remains inside both derivatives. Integration by parts requires boundary conditions that cancel or account for edge terms. In one dimension, with , this is a continuity equation , where
A reflecting boundary imposes zero normal current; an absorbing boundary loses mass from the domain and the loss represents exit. On a circle endpoints are identified and flows leaving one enter the other. These conditions describe different processes.
Equilibrium and current
A stationary density satisfies and the boundary conditions. In one dimension, where stationary flow is zero and in the interior,
if the expression is integrable and satisfies the boundary. Normalization and endpoint behavior are part of the problem. For , , this gives when the density is normalizable and flow is zero. In CIR we recover the previous lesson’s Gamma law, with shape and scale .
This law explains the use of Langevin for sampling. Discretizing continuous dynamics introduces bias; MALA adds a Metropolis acceptance correction to preserve the target distribution under its assumptions.
Stationarity does not imply reversibility. Consider , with and . Its stationary density is isotropic Gaussian for any , but . Its divergence is zero because is tangent to circles and divergence-free. With there is detailed balance; with mass circulates even though the density does not change. Time reversal reverses the current’s direction. See Pavliotis.
Feynman-Kac: solve a PDE with paths
For discount or potential and terminal payoff , the Feynman-Kac formula represents, under suitable existence, regularity and integrability assumptions,
The proof applies Itô to the product of and the exponential factor: drift vanishes by the PDE and, if the stochastic integral is a true martingale, endpoint expectations agree. In a domain with exit, incorporate the boundary condition and stop the process.
The formula links path functionals and parabolic equations; Kac’s work studies distributions of Wiener functionals. For a statement with explicit regularity and growth assumptions, see the Stanford notes.
With standard Brownian motion, constant and , Gaussian expectation gives . This case allows comparison of finite differences, Monte Carlo and an exact solution. In finance the Black-Scholes PDE is a discounted backward equation under the appropriate pricing measure; physical drift is not simply replaced by a risk-free rate. The probability-flow ODE of diffusion models shares an SDE’s marginal evolution under its assumptions, although their paths differ.
Lab: conserving mass
On with reflecting boundaries, divide space into cells. At each face approximate with upwind drift and centered diffusion. Updating a cell by incoming minus outgoing flux makes all interior fluxes cancel when summed; at endpoints impose zero flux. The explicit step condition must keep coefficients nonnegative.
For an interior cell of width , the coefficient of its own density is . A sufficient bound for all coefficients is . It is sufficient, not necessary. Remaining neighboring coefficients are nonnegative and boundary fluxes are zero: thus the update conserves mass and preserves positivity in exact arithmetic.
We compare Euler for the same diffusion and reflect each step in the box. This discrete reflection approximates a reflected diffusion; it does not exactly reproduce what happens between nodes. Boundaries and time step matter. The initial histogram of both descriptions comes from the same particles.
import numpy as np
rng=np.random.default_rng(2828)
L,D,n=2.5,.3,100
edges=np.linspace(-L,L,n+1)
dx=edges[1]-edges[0]
centers=(edges[:-1]+edges[1:])/2
faces=edges[1:-1]
drift=lambda x:x-x**3
potential=lambda x:(x*x-1)**2/4
dt=.001
assert dt*(2*D/dx**2+2*np.max(np.abs(drift(edges)))/dx)<1
m=4000
initial=np.where(rng.random(m)<.5,-.8,.8)+.1*rng.normal(size=m)
def reflect(x):
z=np.mod(x+L,4*L)
return -L+np.where(z<=2*L,z,4*L-z)
particles=reflect(initial)
density=np.histogram(particles,bins=edges)[0]/(m*dx)
initial_mass=density.sum()*dx
for _ in range(1000):
v=drift(faces)
J=v*np.where(v>=0,density[:-1],density[1:])-D*np.diff(density)/dx
flux=np.r_[0.,J,0.]
density-=dt*np.diff(flux)/dx
particles=reflect(particles+drift(particles)*dt+np.sqrt(2*D*dt)*rng.normal(size=m))
hist=np.histogram(particles,bins=edges)[0]/(m*dx)
equilibrium=np.exp(-potential(centers)/D)
equilibrium/=equilibrium.sum()*dx
assert density.min()>-1e-12
print("masa inicial y final:",initial_mass,density.sum()*dx)
print("densidad mínima y distancia L1 al histograma:",density.min(),np.sum(np.abs(density-hist))*dx)
print("distancia L1 a Gibbs en t=1:",np.sum(np.abs(density-equilibrium))*dx)The Gibbs density in the box has zero current and is normalized over that box. The initial state is not stationary: distance to Gibbs at a finite time need not be small. Distance to the histogram depends on sample size and both discretizations.
from scipy.stats import gamma
from scipy.integrate import quad
normalizer,_=quad(lambda x:np.exp(-potential(x)/D),-L,L)
print("doble pozo: normalización y densidad en cero:",
normalizer,np.exp(-potential(0)/D)/normalizer)
kappa,theta,sigma=1.2,.05,.4
shape=2*kappa*theta/sigma**2
scale=sigma**2/(2*kappa)
cir=gamma(a=shape,scale=scale)
print("CIR: forma, escala, media teórica y P(X≤0,05):",
shape,scale,cir.mean(),cir.cdf(.05))
assert np.isclose(cir.mean(),theta)Lab: one expectation three ways
For the discounted heat problem use remaining time . Crank-Nicolson averages the spatial operator between two dates and solves a tridiagonal system; at the box endpoints impose values of the known solution. This isolates interior numerical error, but for a problem without a known solution the boundary must also be justified or approximated. Finite-difference stencils and their errors are studied in more detail in simulation.
The Monte Carlo sample directly uses the exact Gaussian transition at the terminal date, so it has no time discretization error in this example. Compare its standard error with distance to the exact solution.
from scipy.linalg import solve_banded
T,r,q=1.,.3,1.1
grid=np.linspace(-5.,5.,101)
h=grid[1]-grid[0]
steps=200
dt=T/steps
alpha=.5*dt/h**2
u=np.cos(q*grid)
band=np.zeros((3,len(grid)-2))
band[0,1:]=-alpha/2
band[1,:]=1+alpha+r*dt/2
band[2,:-1]=-alpha/2
exact=lambda tau,x:np.exp(-(r+q*q/2)*tau)*np.cos(q*x)
for step in range(steps):
tau=(step+1)*dt
rhs=(1-alpha-r*dt/2)*u[1:-1]+alpha/2*(u[:-2]+u[2:])
left,right=exact(tau,grid[0]),exact(tau,grid[-1])
rhs[0]+=alpha/2*left
rhs[-1]+=alpha/2*right
u[1:-1]=solve_banded((1,1),band,rhs)
u[0],u[-1]=left,right
index=np.argmin(abs(grid-.4))
x=grid[index]
sample=np.exp(-r*T)*np.cos(q*(x+np.sqrt(T)*rng.normal(size=30000)))
mc=sample.mean()
se=sample.std(ddof=1)/np.sqrt(len(sample))
truth=exact(T,x)
print("x, exacto, diferencias finitas, Monte Carlo y error estándar:",
x,truth,u[index],mc,se)
print("errores absolutos de PDE y Monte Carlo:",
abs(u[index]-truth),abs(mc-truth))
assert abs(u[index]-truth)<.002
assert abs(mc-truth)<5*seThe Monte Carlo interval concerns sampling for this exact transition. In a general SDE, discretizing the path and discount integral would add bias; reducing that bias and increasing the number of paths are different tasks.
Exercises
Step 1 of 3. What drift appears in d u(s,Xₛ)?
Step 1 of 3. What is Lf?
Step 1 of 3. What is the derivative of π?
import numpy as np
def feynman_kac_mc(sde,g,r,x,T,n=100,m=5000,seed=28):
passThe generator acts on state functions and its adjoint on densities. Dynkin connects exit and boundary problems; Feynman-Kac turns a discounted expectation into a backward equation when regularity and integrability assumptions hold.
print("tiempo medio desde x=0,5:",1-.5**2)