Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Model Predictive Path Integral Control

The preceding chapters formulated deterministic trajectory optimization as a nonlinear program. Shooting and collocation turn the dynamics, costs, and constraints into a finite-dimensional problem that we can solve with an NLP solver. Gradient-based methods are effective when accurate derivatives are available. How can we improve a trajectory when we can simulate the system and evaluate its cost, but differentiating through that computation is difficult or expensive?

Model predictive path integral control (MPPI) uses sampling to construct an update. It draws candidate control sequences, simulates their trajectories, and forms a weighted average that favors lower-cost outcomes. This requires no derivatives of the dynamics or cost, and the candidate rollouts can run in parallel. The derivation begins with a distribution over control sequences: costs determine which sequences receive more probability, and fitting a Gaussian to that distribution gives the weighted-average update. This construction applies even to a deterministic simulator. An aircraft example extends the calculation to uncertain winds by estimating each candidate flight’s expected cost before assigning its weight. A reactor example applies the same update to temperature and composition fields governed by a partial differential equation, first planning with the equation itself and then with a learned surrogate. Executing the first action and planning again from the next observation connects these computations to the following chapter on receding-horizon control.

Learning Goals

After working through the examples and exercises, you should be able to:

Prerequisites

The algorithm uses the single-shooting rollout and the finite-horizon optimal-control formulation. The sampling derivation requires Gaussian distributions and expectations; KL divergence and importance sampling are developed here. The aircraft example uses conditional disturbance models from Stochastic Dynamics and Partial Observation. The reactor example states the finite-volume model it uses and assumes no background in partial differential equations.

Improving a Control Sequence by Sampling

We already know how to evaluate a control sequence: simulate the system and compute the resulting cost. How can we improve that sequence? Instead of computing a gradient, we try many random variations, evaluate each one, and form a weighted average that gives more influence to the lower-cost candidates. That average becomes our next control sequence.

If the system has dud_u control components, then uk∈Rdu\mathbf u_k\in\mathbb R^{d_u} contains the inputs applied together at time step kk. The current plan U=(u0,…,uN−1)\mathbf U=(\mathbf u_0,\ldots,\mathbf u_{N-1}) collects these vectors over all NN steps. Thus uk\mathbf u_k is one step’s control vector, while U\mathbf U is the complete sequence, with NduNd_u entries when stacked into one vector.

Draw KK Gaussian perturbation sequences ϵ(i)\boldsymbol\epsilon^{(i)} and simulate each candidate V(i)=U+ϵ(i)\mathbf V^{(i)}=\mathbf U+\boldsymbol\epsilon^{(i)}. After assigning normalized weights wiw_i to the resulting trajectories, form the new control sequence

U+=∑i=1KwiV(i)=U+∑i=1Kwiϵ(i),wi≥0,∑i=1Kwi=1.\mathbf U^+=\sum_{i=1}^K w_i\mathbf V^{(i)} =\mathbf U+\sum_{i=1}^K w_i\boldsymbol\epsilon^{(i)}, \qquad w_i\geq0,\qquad \sum_{i=1}^K w_i=1.

The same trajectory weight multiplies every action in its sequence. How should those weights depend on the costs? Giving every candidate the same weight, wi=1/Kw_i=1/K, would ignore the rollout results. Because the perturbations have mean zero, this update would return U\mathbf U on average, regardless of which candidates performed well. At the other extreme, assigning weight one to the lowest-cost candidate and zero to the others would select a single sequence. A candidate with a nearly identical cost would have no influence, and a small change in which candidate ranks first could switch the entire update.

MPPI allows several low-cost candidates to contribute, with their influence decreasing smoothly as cost increases. Consider first the initial sequence U=0\mathbf U=\mathbf0. The candidate sequences are then the zero-mean Gaussian perturbations themselves. This Gaussian is the reference distribution: it remains fixed even when later updates move the sampling mean away from zero. Let SiS_i be the accumulated state cost along rollout ii, including its terminal cost. MPPI assigns it the positive score exp⁡(−Si/λ)\exp(-S_i/\lambda) and divides by the sum of all scores:

wi=exp⁡(−Si/λ)∑j=1Kexp⁡(−Sj/λ),λ>0.w_i=\frac{\exp(-S_i/\lambda)}{\sum_{j=1}^K\exp(-S_j/\lambda)}, \qquad \lambda>0.

This is the softmax of the negative costs, with temperature λ\lambda. The minus sign makes lower costs receive larger scores, and the denominator makes the weights sum to one. The parameter λ\lambda has the same units as cost, so Si/λS_i/\lambda is dimensionless. To see how it sets the strength of the preference, compare two candidates. Their common denominator cancels:

wiwj=exp⁡(−Si/λ)exp⁡(−Sj/λ)=exp⁡ ⁣(−Si−Sjλ).\frac{w_i}{w_j} =\frac{\exp(-S_i/\lambda)}{\exp(-S_j/\lambda)} =\exp\!\left(-\frac{S_i-S_j}{\lambda}\right).

If rollout ii costs λlog⁡2\lambda\log2 more than rollout jj, it receives half as much weight. Thus cost differences, rather than the arbitrary zero of the cost scale, determine relative influence. For a fixed batch, small λ\lambda makes even modest cost differences strongly affect the weights; large λ\lambda makes them less consequential. As λ→0+\lambda\to0^+, the weights concentrate on the lowest-cost candidate, or split equally among tied minima. As λ→∞\lambda\to\infty, they approach 1/K1/K. These are the two alternatives above, now connected by a continuous weighting rule.

The curves in Figure 1 show this dependence on cost and temperature. Each curve compares a rollout’s weight with the weight of the best candidate in the same batch.

Three exponential curves plot a rollout's weight relative to the best rollout against its excess cost. The curve for temperature one half falls fastest, temperature one falls at an intermediate rate, and temperature two falls slowest. A horizontal dotted line shows the equal-weight limit. At temperature one, an excess cost of log two gives half the best rollout's weight.

Figure 1:Smaller temperatures reduce the influence of higher-cost trajectories more sharply. With Smin⁡=min⁡iSiS_{\min}=\min_i S_i, the horizontal axis is the excess cost ΔS=Si−Smin⁡\Delta S=S_i-S_{\min}, and the vertical axis is the ratio wi/wbest=exp⁡(−ΔS/λ)w_i/w_{\mathrm{best}}=\exp(-\Delta S/\lambda). Costs and temperatures use the same arbitrary cost unit. The marked point shows that ΔS=log⁡2\Delta S=\log2 halves the relative weight when λ=1\lambda=1. The dotted horizontal line is the equal-weight limit as λ→∞\lambda\to\infty. A ratio of one at ΔS=0\Delta S=0 does not mean that the best rollout receives all the normalized weight: the actual wiw_i still sum to one across the batch.

The Gaussian reference already favors small controls. Its contribution to control effort will appear explicitly in the distributional objective below; SiS_i includes only state and terminal costs. The displayed weights apply when sampling from this reference, with U=0\mathbf U=\mathbf0. Sampling around a nonzero plan changes how often each candidate is drawn and requires a corresponding correction to its weight.

The computational attraction is that each rollout and cost evaluation can run independently, making large batches suitable for GPU execution Williams et al., 2017. This parallelism does not guarantee that a modest number of samples will find low-cost control sequences: long horizons, many control variables, and narrow feasible regions can make the search difficult. We will check both sampling quality and feasibility when using the update in the aircraft and reactor examples.

So far, exponential weighting is a rule for combining a batch of trials. To justify the rule, we need an objective whose solution gives those weights, and a reason to use their average as the next plan. Both follow by treating the candidate sequences as samples from a distribution and optimizing that distribution before fitting a new control sequence to it.

From Trajectory Weights to MPPI

Which optimization problem gives the exponential weights and their weighted-average update? A distribution over control sequences lets us balance low trajectory cost against a preference for small inputs. The resulting distribution need not have a simple form, but fitting a Gaussian to it produces a mean that can serve as the next plan. Sampling then estimates this mean. Throughout this derivation, randomness comes from the search over controls; the simulator itself can be deterministic.

Reference and sampling distributions

For a general rollout, write xk+1=fk(xk,vk)\mathbf{x}_{k+1}=\mathbf{f}_k(\mathbf{x}_k,\mathbf{v}_k), where vk∈Rdu\mathbf v_k\in\mathbb R^{d_u} is the candidate control vector at step kk. Collect these vectors into the complete candidate sequence V=(v0,…,vN−1)\mathbf V=(\mathbf v_0,\ldots,\mathbf v_{N-1}), with the same structure as the nominal sequence U\mathbf U. The initial state is fixed, so each input sequence determines a simulated state sequence. Define the state and terminal cost of a rollout by

S(V)=cN(xN)+∑k=0N−1ck(xk).S(\mathbf V)=c_N(\mathbf{x}_N) +\sum_{k=0}^{N-1}c_k(\mathbf{x}_k).

Each ckc_k is the cost for one interval; if it comes from a continuous running cost, its discretization includes the interval length.

In the earlier optimal-control formulation, a stage cost ck(xk,uk)c_k(\mathbf x_k,\mathbf u_k) could penalize both the state and the control effort. Here ck(xk)c_k(\mathbf x_k) contains only the state cost; the inputs still affect S(V)S(\mathbf V) through the simulated states. Control effort will be accounted for separately by a KL-divergence penalty between the input distribution and a reference distribution.

Choose a Gaussian reference distribution P0P_0 centered at zero to express a preference for small inputs. As derived below, this choice makes the KL penalty a quadratic cost on the magnitude of the nominal controls; the penalty vanishes when the nominal sequence is zero. Use a separate Gaussian sampling distribution QUQ_{\mathbf U} over complete input sequences, centered at the current plan U\mathbf U. At each step kk, the candidate control vk\mathbf v_k has mean 0\mathbf0 under P0P_0 and mean uk\mathbf u_k under QUQ_{\mathbf U}. Both use the same positive-definite covariance Σ∈Rdu×du\Sigma\in\mathbb R^{d_u\times d_u} for the control components at a single step. Assuming independence across time gives the joint densities over the complete sequence:

p0(V)=∏k=0N−1N(vk;0,Σ),qU(V)=∏k=0N−1N(vk;uk,Σ).p_0(\mathbf V)=\prod_{k=0}^{N-1}\mathcal N(\mathbf v_k;\mathbf0,\Sigma), \qquad q_{\mathbf U}(\mathbf V)= \prod_{k=0}^{N-1}\mathcal N(\mathbf v_k;\mathbf u_k,\Sigma).

Centering the reference at zero is a modeling choice. A Gaussian reference could instead be centered on a prescribed baseline sequence; the KL penalty would then charge for squared deviations of the nominal controls from that baseline. In either case, the state and terminal costs can favor controls away from the reference mean when their benefits justify the effort.

The reference remains fixed during a planning update. The sampling mean is the entire nominal sequence U\mathbf U. This mean is taken over repeated candidate draws, with a separate mean control vector uk\mathbf u_k for each time step. Changing uk\mathbf u_k moves the center of the candidate controls at step kk. Initializing U=0\mathbf U=\mathbf0 means setting every uk=0\mathbf u_k=\mathbf0, so the sampling and reference distributions initially coincide. Later updates can change the nominal controls at each step, moving the samples toward a new plan while the reference stays centered at zero. The sampler can therefore change where it searches without changing the reference that defines the objective.

Exponentially weighting the reference

Sampling from the reference determines how often different input sequences appear in a batch. Assigning a cost weight to each draw then changes how much that occurrence contributes to the weighted average. The total weight assigned to a sequence depends on both its sampling frequency and its weight per occurrence, which is why these two factors multiply.

For example, first consider a reference with only two possible input sequences, aa and bb, selected with probabilities 3/43/4 and 1/41/4. Suppose their costs are S(a)=λlog⁡3S(a)=\lambda\log3 and S(b)=0S(b)=0, so each draw of aa receives score 1/31/3 and each draw of bb receives score 1. Their reference probabilities multiplied by these scores are

34×13=14for a,14×1=14for b.\frac34\times\frac13=\frac14 \quad\text{for }a, \qquad \frac14\times1=\frac14 \quad\text{for }b.

Dividing by the sum, 1/21/2, gives probability 1/21/2 to each sequence. The reference samples aa three times as often, but each occurrence receives one third of the weight, so the two effects cancel.

For continuous inputs, the same operation multiplies the reference density p0(V)p_0(\mathbf V) by the score e−S(V)/λe^{-S(\mathbf V)/\lambda} at each sequence V\mathbf V, then divides by the integral of that product:

p⋆(V)=e−S(V)/λp0(V)Z,λ>0,Z=∫e−S(V)/λp0(V) dV=EP0[e−S(V)/λ].\begin{aligned} p^\star(\mathbf V) &=\frac{e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)}{Z}, \qquad \lambda>0,\\ Z&=\int e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)\,d\mathbf V =\mathbb E_{P_0}[e^{-S(\mathbf V)/\lambda}]. \end{aligned}

The score e−S(V)/λe^{-S(\mathbf V)/\lambda} is not itself a probability density, and the product does not define a joint distribution of two random variables. Both factors concern the same input sequence: p0p_0 specifies its density before costs are considered, and the score adjusts that density according to its cost. The normalizing constant ZZ makes the resulting density integrate to one.

Assume SS is measurable and bounded below and 0<Z<∞0<Z<\infty. The normalized result is a Gibbs distribution: two trajectories with equal reference density and cost difference ΔS\Delta S have density ratio e−ΔS/λe^{-\Delta S/\lambda}. The parameter λ\lambda has the units of cost and controls how strongly those costs affect the ratio.

The opening batch weights contain only the scores because drawing from P0P_0 already accounts for the reference probabilities. Multiplication by p0p_0 appears when we describe the distribution represented by those weighted samples. This explains how weighting changes a distribution; the particular choice of an exponential score is justified by the objective combining expected cost and KL divergence below.

The objective defined by the weights

The exponential weights solve an optimization problem over distributions of input sequences. We seek a distribution QQ that reduces expected state and terminal cost while paying a penalty for departing from P0P_0. Measure that departure with the Kullback--Leibler divergence. For densities q,pq,p, it is

DKL(Q∥P)=EV∼Q[log⁡q(V)p(V)].D_{\mathrm{KL}}(Q\|P) =\mathbb E_{\mathbf V\sim Q}\left[\log\frac{q(\mathbf V)}{p(\mathbf V)}\right].

This divergence is nonnegative and equals zero only when the two distributions agree. For it to be finite, QQ must put no probability where PP has zero density, a condition called absolute continuity. With λ>0\lambda>0 setting the cost of departure from the reference, the first optimization problem is

min⁡Q  J(Q),J(Q)=EV∼Q[S(V)]+λDKL(Q∥P0).\min_Q\;\mathcal J(Q), \qquad \mathcal J(Q) =\mathbb E_{\mathbf V\sim Q}[S(\mathbf V)] +\lambda D_{\mathrm{KL}}(Q\|P_0).

Here QQ ranges over distributions on complete input sequences for which both terms are finite; it is not restricted to a Gaussian family.

Recall that P⋆P^\star is the distribution obtained by multiplying the reference density by the exponential cost score and normalizing. Its density is p⋆(V)=e−S(V)/λp0(V)/Zp^\star(\mathbf V)=e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)/Z. To verify that this distribution solves the optimization problem, we can express the difference between J(Q)\mathcal J(Q) and its minimum as a nonnegative divergence. Substituting this density into the logarithm gives

log⁡q(V)p⋆(V)=log⁡q(V)p0(V)+S(V)λ+log⁡Z.\log\frac{q(\mathbf V)}{p^\star(\mathbf V)} =\log\frac{q(\mathbf V)}{p_0(\mathbf V)} +\frac{S(\mathbf V)}{\lambda}+\log Z.

Taking the expectation under QQ recovers the two terms in J(Q)\mathcal J(Q):

DKL(Q∥P⋆)=DKL(Q∥P0)+1λEQ[S(V)]+log⁡Z=J(Q)λ+log⁡Z.\begin{aligned} D_{\mathrm{KL}}(Q\|P^\star) &=D_{\mathrm{KL}}(Q\|P_0) +\frac{1}{\lambda}\mathbb E_Q[S(\mathbf V)]+\log Z\\ &=\frac{\mathcal J(Q)}{\lambda}+\log Z. \end{aligned}

Rearranging isolates the objective:

J(Q)=−λlog⁡Z+λDKL(Q∥P⋆)≥−λlog⁡Z.\mathcal J(Q)=-\lambda\log Z +\lambda D_{\mathrm{KL}}(Q\|P^\star) \geq-\lambda\log Z.

The quantity ZZ is fixed by SS, P0P_0, and λ\lambda, so the term −λlog⁡Z-\lambda\log Z does not depend on QQ. Choosing Q=P⋆Q=P^\star makes the remaining term, λDKL(Q∥P⋆)\lambda D_{\mathrm{KL}}(Q\|P^\star), equal to zero. Every other distribution gives a positive divergence and hence a larger objective value. This proves that P⋆=arg min⁡QJ(Q)P^\star=\operatorname*{arg\,min}_Q\mathcal J(Q), with minimum value J(P⋆)=−λlog⁡Z\mathcal J(P^\star)=-\lambda\log Z.

The exponential cost weight is contained in the definition of P⋆P^\star; it is no longer explicit in the KL identity because we took logarithms. Writing out the density of the minimizing distribution gives

p⋆(V)=1Z e−S(V)/λ⏟exponential cost weight p0(V).p^\star(\mathbf V) =\frac{1}{Z}\, \underbrace{e^{-S(\mathbf V)/\lambda}}_{\text{exponential cost weight}} \,p_0(\mathbf V).

Multiplying the reference density p0(V)p_0(\mathbf V) by the indicated factor and normalizing by ZZ is the exponential weighting introduced above. The bound on J(Q)\mathcal J(Q) proves that the distribution constructed this way solves (9).

For a Gaussian QUQ_{\mathbf U} with the same covariance as the reference, the KL penalty is a quadratic function of its mean controls:

λDKL(QU∥P0)=λ2∑k=0N−1uk⊤Σ−1uk.\lambda D_{\mathrm{KL}}(Q_{\mathbf U}\|P_0) =\frac\lambda2\sum_{k=0}^{N-1} \mathbf u_k^\top\Sigma^{-1}\mathbf u_k.

For example, choose λΣ−1=hR\lambda\Sigma^{-1}=hR, where hh is the interval length and R≻0R\succ0 specifies how costly each input direction is. Then this penalty is 12h∑kuk⊤Ruk\tfrac12 h\sum_k\mathbf u_k^\top R\mathbf u_k, the discretization of the control-effort integral 12∫u(t)⊤Ru(t) dt\tfrac12\int\mathbf u(t)^\top R\mathbf u(t)\,dt for controls held constant on each interval. Thus, within this Gaussian family, departing from the zero-mean reference incurs a quadratic cost on the nominal controls. This accounts for control effort without adding it to SS. Changing λ\lambda with Σ\Sigma fixed changes this penalty as well as the concentration of the weights.

The solution P⋆P^\star assigns probabilities to complete input sequences. A controller still needs a nominal sequence to store and execute. We obtain that sequence by approximating P⋆P^\star with a Gaussian whose mean can be stored as a plan.

Fitting a Gaussian mean

The density p⋆(V)=e−S(V)/λp0(V)/Zp^\star(\mathbf V)=e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)/Z is generally neither Gaussian nor independent across time. To approximate this distribution, consider the same Gaussian family as our sampler, with a candidate mean sequence M=(m0,…,mN−1)\mathbf M=(\mathbf m_0,\ldots,\mathbf m_{N-1}):

qM(V)=∏k=0N−1N(vk;mk,Σ).q_{\mathbf M}(\mathbf V) =\prod_{k=0}^{N-1}\mathcal N(\mathbf v_k;\mathbf m_k,\Sigma).

Only the mean sequence is adjustable; the covariance Σ\Sigma at each step remains fixed. The second optimization problem chooses the Gaussian that minimizes its divergence from P⋆P^\star in the following direction:

U+=arg min⁡MDKL(P⋆∥QM).\mathbf U^+ =\operatorname*{arg\,min}_{\mathbf M} D_{\mathrm{KL}}(P^\star\|Q_{\mathbf M}).

Here P⋆P^\star is fixed, and the variable is a finite-dimensional mean sequence M\mathbf M. Expanding this objective separates the two log densities:

DKL(P⋆∥QM)=EP⋆[log⁡p⋆(V)]−EP⋆[log⁡qM(V)].D_{\mathrm{KL}}(P^\star\|Q_{\mathbf M}) =\mathbb E_{P^\star}[\log p^\star(\mathbf V)] -\mathbb E_{P^\star}[\log q_{\mathbf M}(\mathbf V)].

The first expectation does not depend on M\mathbf M. In the second, the Gaussian normalization also stays fixed because Σ\Sigma is fixed. Substituting the Gaussian log density therefore gives

DKL(P⋆∥QM)=C+12EP⋆[∑k=0N−1(vk−mk)⊤Σ−1(vk−mk)].D_{\mathrm{KL}}(P^\star\|Q_{\mathbf M}) =C+\frac12\mathbb E_{P^\star} \left[\sum_{k=0}^{N-1} (\mathbf v_k-\mathbf m_k)^\top\Sigma^{-1} (\mathbf v_k-\mathbf m_k)\right].

The constant CC collects the terms in the divergence that do not depend on M\mathbf M. Minimizing the divergence is thus equivalent to minimizing the expected squared distance from the candidate mean to an input sequence drawn from P⋆P^\star, with distances measured by Σ−1\Sigma^{-1}. Assuming finite second moments, differentiation gives

∇mkDKL(P⋆∥QM)=Σ−1(mk−EP⋆[vk]).\nabla_{\mathbf m_k}D_{\mathrm{KL}}(P^\star\|Q_{\mathbf M}) =\Sigma^{-1}\left(\mathbf m_k-\mathbb E_{P^\star}[\mathbf v_k]\right).

Setting this gradient to zero yields the unique minimizer, since Σ−1\Sigma^{-1} is positive definite:

uk+=EP⋆[vk],k=0,…,N−1.\mathbf u_k^+=\mathbb E_{P^\star}[\mathbf v_k], \qquad k=0,\ldots,N-1.

With an exact solution of (16), the updated Gaussian would have the same mean as P⋆P^\star. The equation above identifies that mean as the quantity we need to compute; it does not yet provide a way to evaluate it. We know the density of P⋆P^\star up to its normalizing constant: for any candidate sequence V\mathbf V, a rollout gives S(V)S(\mathbf V), so we can evaluate e−S(V)/λp0(V)e^{-S(\mathbf V)/\lambda}p_0(\mathbf V). In general, however, calculating ZZ or EP⋆[vk]\mathbb E_{P^\star}[\mathbf v_k] requires high-dimensional integration, and we do not have a direct sampler for P⋆P^\star.

Importance sampling in Correcting for where the samples were drawn will estimate this mean from candidates drawn from the Gaussian QUQ_{\mathbf U}, which we can sample. The normalized weights will account for the difference between the two distributions without requiring the value of ZZ. Thus the computed update will only approximate the mean of P⋆P^\star; the equality above describes the exact target of the calculation. The quadratic example below first provides a case where this target can be calculated analytically.

Even if its mean were computed exactly, the Gaussian would retain covariance Σ\Sigma at each step. It can therefore lose features of P⋆P^\star: if low-cost sequences form separate groups, their average can lie between those groups.

The first problem, (9), chooses an entire distribution by minimizing EQ[S(V)]+λDKL(Q∥P0)\mathbb E_Q[S(\mathbf V)]+\lambda D_{\mathrm{KL}}(Q\|P_0). The second, (16), holds its solution P⋆P^\star fixed and chooses a Gaussian mean by minimizing DKL(P⋆∥QM)D_{\mathrm{KL}}(P^\star\|Q_{\mathbf M}). If we instead restricted the first problem to Gaussians, the identity above would give

arg min⁡M{EQM[S(V)]+λDKL(QM∥P0)}=arg min⁡MDKL(QM∥P⋆).\operatorname*{arg\,min}_{\mathbf M} \left\{\mathbb E_{Q_{\mathbf M}}[S(\mathbf V)] +\lambda D_{\mathrm{KL}}(Q_{\mathbf M}\|P_0)\right\} =\operatorname*{arg\,min}_{\mathbf M} D_{\mathrm{KL}}(Q_{\mathbf M}\|P^\star).

The order of the distributions in this divergence is reversed relative to (16). KL divergence is not symmetric, so these two choices of Gaussian mean need not agree Williams et al., 2017.

A one-step quadratic check

For a scalar system x1=x0+vx_1=x_0+v with x0=0x_0=0 and target 1, take S(v)=κ2(v−1)2S(v)=\tfrac\kappa2(v-1)^2 with κ>0\kappa>0, P0=N(0,1)P_0=\mathcal N(0,1), and λ=1\lambda=1. The dynamics are deterministic: different endpoints result from trying different inputs. Multiplying the reference density by e−S(v)e^{-S(v)} and completing the square gives

p⋆(v)∝exp⁡ ⁣[−12(v2+κ(v−1)2)]∝exp⁡ ⁣[−1+κ2(v−κ1+κ)2].p^\star(v)\propto \exp\!\left[-\frac12\bigl(v^2+\kappa(v-1)^2\bigr)\right] \propto\exp\!\left[-\frac{1+\kappa}{2} \left(v-\frac\kappa{1+\kappa}\right)^2\right].

Thus the first optimization problem has solution P⋆=N(κ/(1+κ),1/(1+κ))P^\star=\mathcal N(\kappa/(1+\kappa),1/(1+\kappa)). Weighting has shifted the reference toward the target and reduced its variance. The second problem keeps the variance at its chosen value of one and adjusts only the Gaussian mean:

u+=arg min⁡mDKL ⁣(N ⁣(κ1+κ,11+κ) ∥ N(m,1))=κ1+κ.u^+=\operatorname*{arg\,min}_{m} D_{\mathrm{KL}}\!\left( \mathcal N\!\left(\frac{\kappa}{1+\kappa},\frac{1}{1+\kappa}\right) \,\middle\|\,\mathcal N(m,1)\right) =\frac{\kappa}{1+\kappa}.

The resulting approximation is Qu+=N(κ/(1+κ),1)Q_{u^+}=\mathcal N(\kappa/(1+\kappa),1). It has the correct mean but is broader than P⋆P^\star. Figure Figure 2 shows both optimization steps for κ=2log⁡2\kappa=2\log2.

Two density plots share the same input and probability-density scales. On the left, multiplying a zero-mean Gaussian reference by the exponential cost weight produces a narrower Gaussian centered at about 0.581. On the right, the approximating Gaussian shares that mean but retains the reference variance of one, so it is broader than the cost-weighted distribution.

Figure 2:The two MPPI optimization problems change different properties of the input distribution. For the scalar rollout x1=vx_1=v, target 1, cost S(v)=κ2(v−1)2S(v)=\tfrac\kappa2(v-1)^2, κ=2log⁡2\kappa=2\log2, and λ=1\lambda=1, the reference is P0=N(0,1)P_0=\mathcal N(0,1). Left: minimizing expected cost plus DKL(Q∥P0)D_{\mathrm{KL}}(Q\|P_0) gives the blue solid density p⋆(v)∝e−S(v)p0(v)p^\star(v)\propto e^{-S(v)}p_0(v), with mean u+≈0.581u^+\approx0.581 and variance 1/(1+κ)≈0.4191/(1+\kappa)\approx0.419. The gray dashed curve is the reference. Right: minimizing DKL(P⋆∥Qm)D_{\mathrm{KL}}(P^\star\|Q_m) over Qm=N(m,1)Q_m=\mathcal N(m,1) gives the orange dash-dotted density qu+q_{u^+}, with the same mean as p⋆p^\star and variance one. The vertical dotted lines mark the means. Both panels show analytic densities, without sampling error.

In this quadratic example, u+u^+ also minimizes the deterministic objective κ2(u−1)2+12u2\tfrac\kappa2(u-1)^2+\tfrac12u^2: setting its derivative κ(u−1)+u\kappa(u-1)+u to zero gives u=κ/(1+κ)u=\kappa/(1+\kappa). This agreement checks the update in the example; taking the mean of P⋆P^\star need not minimize the deterministic cost for a general rollout.

To check the finite-sample calculation, set κ=2log⁡2\kappa=2\log2 and start from u=0u=0. Suppose three draws from the reference, rounded for this calculation, are −1,0,1-1,0,1. Evaluating their costs gives

Candidate input vvEndpoint x1x_1Cost S(v)S(v)Unnormalized weightNormalized weight
-1-14log⁡24\log 21/161/161/251/25
00log⁡2\log 21/21/28/258/25
110116/2516/25

The weighted average is

u+=125(−1)+825(0)+1625(1)=35.u^+=\frac1{25}(-1)+\frac8{25}(0)+\frac{16}{25}(1)=\frac35.

This three-sample estimate, 0.6, is close to the exact mean 2log⁡2/(1+2log⁡2)≈0.5812\log2/(1+2\log2)\approx0.581. All three candidates contribute; the update does not simply select the best sampled input, 1. Sampling around the updated plan will produce a different mix of candidates, so preserving the same target mean requires adjusting their weights.

Correcting for where the samples were drawn

The mean uk+=EP⋆[vk]\mathbf u_k^+=\mathbb E_{P^\star}[\mathbf v_k] is the exact solution of the Gaussian approximation problem. To estimate it for a general rollout, we have two available operations: draw a sequence from QUQ_{\mathbf U}, and evaluate its cost S(V)S(\mathbf V). We can use these operations without a direct sampler for P⋆P^\star or an analytic value for its normalizing constant ZZ.

Substituting the definition of p⋆p^\star into the desired expectation and writing ZZ as its defining integral gives

uk+=∫vke−S(V)/λp0(V) dV∫e−S(V)/λp0(V) dV.\mathbf u_k^+ =\frac{\int \mathbf v_k e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)\,d\mathbf V} {\int e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)\,d\mathbf V}.

Both integrals involve the unnormalized density that we can evaluate. Multiplying and dividing their integrands by qU(V)q_{\mathbf U}(\mathbf V) expresses them as expectations under the distribution we can sample:

uk+=EQU[e−S(V)/λp0(V)qU(V)vk]EQU[e−S(V)/λp0(V)qU(V)].\mathbf u_k^+ =\frac{\mathbb E_{Q_{\mathbf U}} \left[e^{-S(\mathbf V)/\lambda} \frac{p_0(\mathbf V)}{q_{\mathbf U}(\mathbf V)}\mathbf v_k\right]} {\mathbb E_{Q_{\mathbf U}} \left[e^{-S(\mathbf V)/\lambda} \frac{p_0(\mathbf V)}{q_{\mathbf U}(\mathbf V)}\right]}.

This change of sampling distribution is importance sampling. A batch from QUQ_{\mathbf U} can estimate both expectations, using the score e−S(V)/λp0(V)/qU(V)e^{-S(\mathbf V)/\lambda}p_0(\mathbf V)/q_{\mathbf U}(\mathbf V) for each candidate. Dividing by the sum of these scores normalizes the sample weights, so we do not need to know ZZ.

For example, moving a scalar proposal to a positive mean makes positive inputs more common even if the target distribution has not changed. Weighting only by state cost would mistake that extra sampling frequency for additional target probability. The factor p0/qUp_0/q_{\mathbf U} removes it. Since both Gaussians have full support, every trajectory with positive target density remains accessible. Writing vk=uk+ϵk\mathbf v_k=\mathbf u_k+\boldsymbol\epsilon_k and expanding their quadratic exponents gives

log⁡p0(U+ϵ)qU(U+ϵ)=−12∑k[(uk+ϵk)⊤Σ−1(uk+ϵk)−ϵk⊤Σ−1ϵk]=−∑k[uk⊤Σ−1ϵk+12uk⊤Σ−1uk].\begin{aligned} \log\frac{p_0(\mathbf U+\boldsymbol\epsilon)} {q_{\mathbf U}(\mathbf U+\boldsymbol\epsilon)} &=-\frac12\sum_k\left[ (\mathbf u_k+\boldsymbol\epsilon_k)^\top\Sigma^{-1} (\mathbf u_k+\boldsymbol\epsilon_k) -\boldsymbol\epsilon_k^\top\Sigma^{-1}\boldsymbol\epsilon_k \right]\\ &=-\sum_k\left[ \mathbf u_k^\top\Sigma^{-1}\boldsymbol\epsilon_k +\frac12\mathbf u_k^\top\Sigma^{-1}\mathbf u_k\right]. \end{aligned}

The last quadratic term is identical across samples and cancels from the normalized weights. Consequently each sampled sequence ii receives the corrected cost

S~i=S(U+ϵ(i))+λ∑k=0N−1uk⊤Σ−1ϵk(i).\widetilde S_i=S(\mathbf U+\boldsymbol\epsilon^{(i)}) +\lambda\sum_{k=0}^{N-1} \mathbf u_k^\top\Sigma^{-1}\boldsymbol\epsilon_k^{(i)}.

A stable finite-sample update

The ratio of expectations above is exact. To compute an approximate update, replace both expectations by averages over KK independent samples from QUQ_{\mathbf U}. For numerical stability, subtract ρ=min⁡iS~i\rho=\min_i\widetilde S_i before exponentiation. This common subtraction leaves normalized weights unchanged and avoids overflow:

wi=e−(S~i−ρ)/λ∑j=1Ke−(S~j−ρ)/λ,uk+=uk+∑i=1Kwiϵk(i).w_i=\frac{e^{-(\widetilde S_i-\rho)/\lambda}} {\sum_{j=1}^K e^{-(\widetilde S_j-\rho)/\lambda}}, \qquad \mathbf u_k^+=\mathbf u_k+ \sum_{i=1}^K w_i\boldsymbol\epsilon_k^{(i)}.

The same full-trajectory weight updates every time slot. This ratio of sample averages is a self-normalized importance-sampling estimator. It is generally biased for finite KK and converges to the target mean when the relevant weighted moments are integrable. Further iterations move the proposal toward useful trajectories; with exact expectations, the target mean would already be independent of the proposal.

A quadratic rollout makes the effect of this correction explicit. Take xk+1=xk+hvkx_{k+1}=x_k+hv_k, x0=0x_0=0, N=10N=10, h=0.1h=0.1, and terminal cost 2(xN−1)22(x_N-1)^2. With λ=0.5\lambda=0.5 and Σ=5\Sigma=5, the exact target mean is 0.8 at every time step. Sampling around uk=0.4u_k=0.4 and omitting the correction instead estimates 0.88, even with arbitrarily many samples. Exercise Exercise 2 derives both limits. Moving the proposal should change the accuracy of the estimate, not the mean being estimated.

Receding-horizon execution

The update gives a sequence of actions for a particular initial state. Model error or physical disturbances can make the next observed state differ from the rollout prediction. Continuing with the stored sequence would ignore that discrepancy. Instead, apply only the first action and use the newly observed state as the initial condition for another planning problem. MPPI repeats the trajectory computation from that condition, as in the sampling controllers of Williams et al. (2017).

This version assumes unrestricted Gaussian inputs and finite rollout costs. Nonconvex state constraints need additional treatment: even an average of inputs from feasible trajectories can generate an infeasible trajectory. Clipping samples also changes their density, so the displayed Gaussian likelihood ratio does not apply unchanged to the clipped variables. A chosen exploration covariance different from the reference covariance requires the full corresponding density ratio.

The rollouts can be simulated in parallel. Their effectiveness still depends on overlap between proposal and target. The quantity Keff=1/∑iwi2K_{\mathrm{eff}}=1/\sum_i w_i^2 summarizes weight concentration: it is KK for equal weights and approaches one when a single rollout dominates. It diagnoses sampling concentration, rather than certifying optimality or constraint satisfaction. A finite-sample update can increase the rollout cost, particularly when only a few samples carry most of the weight. Concentrated weights suggest increasing the sample count or improving overlap between proposal and target. Increasing λ\lambda with a fixed reference weakens state-cost weighting, but also changes the optimization objective. Altering the proposal covariance alone requires the corresponding likelihood correction. Receding-horizon execution supplies feedback through repeated observations; the stored sequence itself is open loop.

Connection to diffusion-based planning

The distribution over low-cost plans also connects this computation to modern diffusion-based trajectory optimization. In model-based diffusion, the objective defines a target density through an exponential cost weight. Gaussian perturbations and cost-weighted averages then provide estimates used to refine trajectories through a sequence of noise levels Pan et al., 2024. MPPI’s weighted mean provides a useful starting point for understanding that construction. The MPPI update here uses a fixed sampling covariance and does not train a denoising network or run a diffusion noise schedule. In both algorithms, random perturbations can serve only to explore controls. Physical disturbances introduce a separate source of variation: a single candidate plan can produce different costs under different disturbance realizations. The aircraft example uses several simulated winds to estimate the cost assigned to each candidate.

Aircraft Planning Under Uncertain Winds

Consider an Airbus A320 flying from Montréal–Trudeau (CYUL) to Toronto–Pearson (CYYZ). The task is to choose climb, cruise, descent, and flight duration to use little fuel while arriving within 1 km horizontally and 30 m vertically of the destination. A favorable wind at one altitude may justify climbing, but its later evolution is uncertain. How can the sampled-control update account for these different possible outcomes when comparing candidate flights?

The method from From Trajectory Weights to MPPI can optimize an estimated expected cost from a simulator. It requires separate samples for candidate controls and for future winds: several winds must be evaluated before a candidate is assigned its cost weight. The following model makes those two random quantities explicit.

The airborne model and its wind state

In the OpenAP A320 point-mass model Sun, 2022, the state is (pE,pN,h,m,t)(p_E,p_N,h,m,t): east and north position in a local map, altitude in meters, mass in kilograms, and elapsed time in seconds. Here hh denotes altitude; numerical time steps will be given in seconds. Controls are Mach number MM, vertical speed vzv_z in meters per second, and heading χ\chi in radians clockwise from north. If v=TAS(M,h)v=\mathrm{TAS}(M,h) is true airspeed and γ=arctan⁡(vz/v)\gamma=\arctan(v_z/v), the model is

p˙E=vcos⁡γsin⁡χ+wˉE(pE,pN,h)+gE,p˙N=vcos⁡γcos⁡χ+wˉN(pE,pN,h)+gN,h˙=vz,m˙=−ffuel(m,v,h,vz),t˙=1.\begin{aligned} \dot p_E &= v\cos\gamma\sin\chi+\bar w_E(p_E,p_N,h)+g_E,\\ \dot p_N &= v\cos\gamma\cos\chi+\bar w_N(p_E,p_N,h)+g_N,\\ \dot h &= v_z,\qquad \dot m=-f_{\mathrm{fuel}}(m,v,h,v_z),\qquad \dot t=1. \end{aligned}

The horizontal equations separate air-relative motion from wind-driven displacement: wˉ\bar w is the fixed mean wind field and gg is a gust. Fuel flow ffuelf_{\mathrm{fuel}} reduces mass as the aircraft flies. The heading convention and flight-path-angle approximation reproduce OpenAP.top’s point-mass equations. Conversions to knots, feet, and feet per minute occur only when calling OpenAP interfaces that require them. The numerical derivatives are tested against OpenAP.top’s original symbolic model at climb, cruise, and descent states. Optimization itself uses forward simulation and Gaussian sampling.

The reference flight covers the complete airborne leg, with the following initial and nominal conditions:

QuantityValue
Initial mass85%85\% of maximum takeoff mass
Departure and arrival altitude100 ft
Nominal cruise altitude7000 m
Nominal duration3600 s

Taxi, runway operations, and traffic are outside this model. Mach number, vertical speed, heading, altitude, mass, and the geographic flight corridor have explicit bounds. Thrust, lift, and excess-energy inequalities reproduce the approximate OpenAP.top envelope checks. Adjacent command changes are also checked against limits of 0.2 Mach, 500 ft/min in vertical speed, and 15 degrees in heading. These are constraints of the teaching model.

The mean field wˉ\bar w is the committed ERA5 pressure-level snapshot for June 1, 2023, at 12:00 UTC Copernicus Climate Change Service (C3S), 2018. Preprocessing converts the original GRIB values once to a numerical array. The simulator interpolates in pressure, latitude, and longitude, using ISA pressure at the aircraft’s altitude. Outside the snapshot’s pressure range of 200–925 hPa, it holds the boundary value; in particular, winds near the ground use the lowest available pressure level. The snapshot remains fixed in time during a flight.

A gust observed now should influence the near-future forecast, but it should not determine the wind for the entire flight. An Ornstein–Uhlenbeck model represents this persistence and gradual loss of predictability for g=(gE,gN)g=(g_E,g_N). Its exact transition over a time increment Δ\Delta is

gt+Δ=e−Δ/τgt+1−e−2Δ/τ [σE00σN]ξ,ξ∼N(0,I),g_{t+\Delta}=e^{-\Delta/\tau}g_t+ \sqrt{1-e^{-2\Delta/\tau}}\, \begin{bmatrix}\sigma_E&0\\0&\sigma_N\end{bmatrix}\xi, \qquad \xi\sim\mathcal N(0,I),

with τ=300\tau=300 s, σE=5\sigma_E=5 m/s, and σN=4\sigma_N=4 m/s. These parameters are illustrative assumptions, not estimates from the single ERA5 snapshot. The gust is spatially uniform in this example. The aircraft’s current state and current gust are observed at each replanning time. Conditional on that observation, the future gust has mean e−Δ/τgte^{-\Delta/\tau}g_t and increasing conditional variance. Augmenting the aircraft state with gtg_t makes this a fully observed Markov model. There is no observation filter in the example.

Expected cost under several wind futures

A candidate flight can do well under one wind and poorly under another. Suppose two equally likely winds give the following costs:

CandidateFirst windSecond windExpected cost
A02010
B888

Expected cost favors B. At λ=1\lambda=1, however, averaging exponential weights gives A the score (1+e−20)/2≈0.5(1+e^{-20})/2\approx0.5, while B receives e−8≈0.00034e^{-8}\approx0.00034. A single favorable wind dominates A’s weight. Averaging such weights would therefore optimize a different criterion. Exercise Exercise 3 develops this distinction further.

For the intended expected-cost objective, first average costs across wind futures. If z(i)z^{(i)} specifies a candidate flight and W(ℓ)W^{(\ell)} is one of LL futures conditional on the observed gust, use

C^(z(i))=1L∑ℓ=1LC(z(i),W(ℓ)).\widehat C(z^{(i)})=\frac1L\sum_{\ell=1}^L C\bigl(z^{(i)},W^{(\ell)}\bigr).

Every candidate receives the same ensemble of wind futures. Pairing the winds makes each cost difference compare two plans under the same conditions, which can reduce variance in their estimated difference. The ensemble is independent of the future wind that will actually occur.

The cost CC is fuel burned, plus quadratic penalties for horizontal and vertical arrival error and for envelope violations. Arrival error is scaled by tolerances of 1000 m horizontally and 30 m vertically. A squared unit of either scaled arrival error adds 80 kg-equivalent cost; envelope violations receive a larger penalty. The code records the physical errors separately from this combined objective.

Smooth flight parameters and their weights

The aircraft has three control channels over a full flight. Perturbing each short interval independently would produce a large and irregular control sequence. Instead, a candidate is a vector z∈R13z\in\mathbb R^{13}: one duration parameter and four interior knots for each of the three control channels. The knots define small, piecewise-linear perturbations around a geometric reference flight. The nominal reference accounts for the observed state and conditional mean wind; its forward simulation remains responsible for determining the actual endpoint. The duration is multiplied by e0.025z0e^{0.025z_0} and limited to [0.90,1.12][0.90,1.12] times the nominal remaining duration. This limited family keeps the first example computationally small. It does not span all feasible A320 trajectories.

The vertical-speed perturbation has zero time integral, so it preserves the reference altitude change. This is a restriction on the control parameterization. The simulator never projects the final aircraft position onto the destination. Mach and heading perturbations can change the arrival position, and every proposal must be checked after simulation.

Use a reference p0=N(0,0.72I)p_0=\mathcal N(0,0.7^2I) and proposal qμ=N(μ,0.72I)q_\mu=\mathcal N(\mu,0.7^2I) over the knot and duration parameters zz. The weights and proposed mean are

wi∝exp⁡ ⁣[−C^(z(i))λ]p0(z(i))qμ(z(i)),μ+=∑iwiz(i),λ=25 kg-equivalent.w_i\propto \exp\!\left[-\frac{\widehat C(z^{(i)})}{\lambda}\right] \frac{p_0(z^{(i)})}{q_\mu(z^{(i)})}, \qquad \mu^+=\sum_iw_i z^{(i)},\qquad \lambda=25\ \text{kg-equivalent}.

The likelihood ratio is computed before the deterministic mapping from parameters to bounded duration and control tapes. Clipping the duration does not turn its physical distribution into a Gaussian; the Gaussian density remains a density over zz. The proposal correction appears once per candidate, after disturbance averaging.

There are now two sample counts with different roles: KK candidate parameter vectors approximate the weighted mean, while LL wind futures approximate each candidate’s expected cost. The parameter reference regularizes the flight changes. It does not describe the physical gusts, which affect ground motion and have their own temporal dependence.

The update uses the distributional construction from From Trajectory Weights to MPPI, with C^\widehat C as its score. Even if expected costs were evaluated exactly, fitting a Gaussian mean would not generally solve the deterministic optimization over flight parameters. The finite sampling budget introduces another approximation, so the proposed plan must be checked before execution.

Accepting and executing a plan

Prediction uses 60 s control intervals. Before accepting a weighted mean, the code constructs its control tape and replays it on a 10 s grid under the conditional mean wind. It checks the envelope and both arrival tolerances. The proposed plan must also improve the estimated cost on the shared wind ensemble. The best accepted plan so far is the incumbent. An invalid or non-improving update leaves that validated plan in place. The initial geometric reference must pass the same validation. At a later decision, the remaining previous plan is also replayed from the observed state and can be retained as the incumbent. Validation includes the change from the last executed command to the new first command. If neither reference is feasible, the simulation reports a planning failure.

These checks certify feasibility only under the conditional mean and at the checked resolution. The scenario evaluations expose possible arrival and constraint violations under other winds. Neither a weighted average nor a finite collection of successful scenarios guarantees feasibility for all Gaussian disturbances.

Comparing frozen and replanned flights

The experiment asks two separate questions: does reacting to observed wind improve arrival, and does sampling uncertain future wind improve on its conditional mean? Three execution strategies use paired physical wind realizations:

  1. Frozen plan: compute a full-trip plan using mean wind at departure and execute it for the rest of the flight.

  2. Conditional-mean replanning: observe state and gust every 60 s, optimize the remaining trip using the conditional mean gust, and execute the next minute of commands.

  3. Stochastic replanning: use the same observations and execution schedule, but average each candidate’s cost over a conditional ensemble of wind futures before updating its parameters.

The saved mean-wind flight is the validated deterministic reference used to construct the frozen plan. The two replanning variants build a geometric reference from the measured state and compare it with the remaining previous plan, then perform two Gaussian mean updates. They reuse the previous flight as a candidate incumbent, while resetting the perturbation coordinates around the new geometric reference. Within one decision, each accepted mean initializes the next sampling update. Extending the shifted-sequence warm start in Algorithm 1 to reuse the previous knot coordinates is a further computational experiment.

The realized gust trajectory has its own random-number stream. The optimizer receives only the current observed gust and generates independent conditional forecasts. All candidates at one decision share the forecast ensemble, which reduces noise in their cost differences. Controllers encounter the same underlying realized gust function even when their durations differ. Realized gusts are held over each 10 s execution interval; a 5 s replay checks numerical integration while preserving those realized inputs.

Complete flight profiles for the first paired gust realization. The frozen
plan executes the same commands as the mean-wind reference, so both burn the
same fuel in this model, but their ground positions differ. Replanning changes
commands in response to the observed position and gust. The horizontal line
in the final-approach panel marks the 1 km arrival tolerance.

Figure 3:Complete flight profiles for the first paired gust realization. The frozen plan executes the same commands as the mean-wind reference, so both burn the same fuel in this model, but their ground positions differ. Replanning changes commands in response to the observed position and gust. The horizontal line in the final-approach panel marks the 1 km arrival tolerance.

Arrival, fuel, and numerical sensitivity

In the three recorded wind realizations, the frozen plan misses the arrival tolerance each time. Both replanning methods arrive within tolerance in all three trials. Their fuel difference is smaller than the distinction between arriving and missing the destination, so arrival and fuel are reported separately:

ControllerFuel (kg)Arrival error (m)Feasible arrivalsLargest constraint violation
Mean-wind plan2577.866.21/10
Frozen plan + gusts2577.82491.30/30
Mean-wind replanning2587.0102.93/31.15e-13
Stochastic replanning2560.1110.03/31.5e-13

The repeated runs use 3 independent gust seeds. The figures show mean and sample standard deviation across those seeds, with individual runs also plotted. The mean-wind plan is one deterministic reference run. Prediction uses 32 candidates, 6 shared wind scenarios, and 2 updates per decision. Arrival tolerances are 1000 m horizontally and 30 m vertically. Constraint residuals and replay differences are available in the downloadable metrics.

ControllerMean ESSTotal planning time per flight (s)Rejected updates
Frozen plan + gusts11.71.30
Mean-wind replanning22.256.1110
Stochastic replanning8.852.292

Planning times are measured wall-clock times on the build machine; they include validation and vary with competing workloads. Rejected-update counts are totals across the recorded flights. The largest 5 s versus 10 s replay difference is 0.261 m in position and 0.0020 kg in fuel. All vertical arrival errors are below 8.3e-13 m.

Individual outcomes across three independent gust realizations, with mean and
sample-standard-deviation bars. The small trial count supports inspection of
these examples; it does not establish a reliable fuel advantage or a failure
probability. Tiny residuals near machine precision arise from floating-point
integration at the terminal altitude boundary.

Figure 4:Individual outcomes across three independent gust realizations, with mean and sample-standard-deviation bars. The small trial count supports inspection of these examples; it does not establish a reliable fuel advantage or a failure probability. Tiny residuals near machine precision arise from floating-point integration at the terminal altitude boundary.

Replanning compensates for displacement accumulated under the frozen plan. Whether sampling future gusts also improves fuel consumption depends on the wind model, the trajectory family, and the sampling budget. Conditional-mean replanning is therefore a substantive baseline. A favorable single run is insufficient evidence that the stochastic planner is better.

Left: the predicted terminal-error 10th–90th percentile range from the current
planning ensemble. The conditional-mean planner has one deterministic future,
so its band has zero width. Right: conditional scenario endpoints at one
replanning time, with the 1 km arrival region. These small-ensemble ranges are
forecast diagnostics, not calibrated confidence regions or constraints.

Figure 5:Left: the predicted terminal-error 10th–90th percentile range from the current planning ensemble. The conditional-mean planner has one deterministic future, so its band has zero width. Right: conditional scenario endpoints at one replanning time, with the 1 km arrival region. These small-ensemble ranges are forecast diagnostics, not calibrated confidence regions or constraints.

Increasing the number of candidate samples and increasing the number of wind scenarios address different approximations. Candidate counts of 16,32,64,12816,32,64,128 are compared at L=6L=6; scenario counts of 1,3,6,12,241,3,6,12,24 are compared at K=32K=32. Four independent planning seeds are used at the initial full-trip decision. Each resulting plan is evaluated on 128 fresh, shared wind futures that no optimizer saw. This separates variation in the candidate search from variation in the estimated expected cost. Two projected updates need not improve monotonically with either sample count, and this first-decision check does not establish convergence of the entire feedback policy.

The endpoint comparisons in the recorded sweep are:

Varied budgetFixed budgetMean held-out cost at the smaller budgetMean held-out cost at the larger budget
K:16→128K:16\to128L=6L=657,39657{,}39650,11050{,}110
L:1→24L:1\to24K=32K=3258,35358{,}35351,31951{,}319

Costs are in kg-equivalent and include large penalties for rare unsuccessful wind futures. They are not fuel totals. In the candidate-count comparison, sample standard deviations across planning seeds are 10,00810{,}008 and 7,3387{,}338. Intermediate budgets give nonmonotone results, so these endpoints show sensitivity to sampling budgets without establishing convergence.

The flight diagnostics include fuel, arrival errors, fine-grid residuals, effective sample sizes, accepted and rejected updates, runtimes, and the sampling study. The local replay displays the corresponding paths and observations. To extend the experiment, increase the number of independent realized winds before drawing conclusions about reliability, and compare the gain from a richer control parameterization with the gain from more samples.

Select a controller and replay the recorded flight. The displayed forecast belongs to the most recent planning decision, while the gust display follows the observed realized wind.

Heater Control of a Flow-Through Reactor

The aircraft state contained a few physical quantities and a gust. Many process systems are instead described by fields: the temperature and composition at every point of a vessel. In a flash calciner, clay particles carried by hot gas are heated rapidly while an endothermic reaction converts them into a reactive material that can replace part of the clinker in cement Cantisani et al., 2024. Heaters act on broad regions of such a reactor, while the quantities that matter, such as the conversion of the material leaving it and the highest local temperature, depend on how heat is distributed along the flow.

MPPI needs only the ability to simulate a candidate control sequence and evaluate its cost, and a discretized partial differential equation (PDE) provides both. The number of state values does not enter the update directly: the weights depend on candidate costs, and the update averages control parameters. The state dimension determines the cost of each rollout and how much of the state a few actuators can influence. This section controls a reactor with 4,096 state values through 24 sampled parameters, first planning with the PDE itself and then with a learned surrogate.

A two-field reactor model

Material flows from left to right through a rectangular domain of length 8 m and width 2 m, with xx measured downstream and yy across the width. Two fields describe its state: temperature T(x,y,t)T(x,y,t) in kelvin and remaining reactant fraction c(x,y,t)∈[0,1]c(x,y,t)\in[0,1]. Conversion is a=1−ca=1-c. Both fields are carried by a prescribed downstream velocity vx(y)v_x(y), spread by diffusion, and coupled through a temperature-dependent reaction:

∂tc+vx(y) ∂xc=D∇2c−k(T) c,∂tT+vx(y) ∂xT=D∇2T−β(T−Twall)−ΔTrxn k(T) c+qmax⁡∑j=14uj 1Ωj(x,y).\begin{aligned} \partial_t c+v_x(y)\,\partial_x c&=D\nabla^2c-k(T)\,c,\\ \partial_t T+v_x(y)\,\partial_x T&=D\nabla^2T-\beta(T-T_{\mathrm{wall}}) -\Delta T_{\mathrm{rxn}}\,k(T)\,c +q_{\max}\sum_{j=1}^4u_j\,\mathbb 1_{\Omega_j}(x,y). \end{aligned}

The reaction rate has the Arrhenius form k(T)=0.1exp⁡[12000(1/950−1/T)]k(T)=0.1\exp[12000(1/950-1/T)] s−1^{-1}. Converting a unit of reactant cools the material by ΔTrxn\Delta T_{\mathrm{rxn}}, and heat is lost toward the wall temperature at rate β\beta. Each heater covers one quadrant Ωj\Omega_j of the domain, and its input uj∈[0,1]u_j\in[0,1] is a fraction of the maximum heating rate qmax⁡q_{\max}. Heater H1 covers the upstream half of the bottom (y<1y<1 m), H2 the downstream half of the bottom, H3 the upstream half of the top, and H4 the downstream half of the top. Material enters with reactant fraction one.

QuantityValue
Domain and mesh8 m ×\times 2 m, 64×3264\times32 cells
Diffusivity DD of both fields5×10−45\times10^{-4} m2^2/s
Heat-loss rate β\beta and wall temperature0.01 s−1^{-1}, 700 K
Reaction cooling ΔTrxn\Delta T_{\mathrm{rxn}}60 K per unit of reactant
Maximum heating rate qmax⁡q_{\max}20 K/s
Inlet temperature800+10cos⁡(πy/2)800+10\cos(\pi y/2) K
Operating limitsmax⁡T≤1070\max T\leq1070 K, outlet conversion ≥95%\geq95\%

These are teaching assumptions inspired by flash calcination, not calibrated calciner parameters. The model omits separate solid and gas phases, detailed chemistry, residence-time distributions, and industrial geometry.

The Arrhenius factor makes conversion sensitive to temperature. At 950 K the rate is 0.1 s−1^{-1}, a time constant of 10 s. At 900 K it falls to about 0.050 s−1^{-1}, and at 1000 K it rises to about 0.19 s−1^{-1}. Material spends about 40 s in the reactor, so a parcel that remains 50 K colder than its surroundings for part of that time leaves with noticeably more unreacted material. More heating raises the rate, but it also raises the peak temperature, which must stay below 1070 K everywhere. Because the flow speed can vary across the width, the outlet conversion is weighted by flux,

aout=1−∑ivx(yi) c(8,yi)∑ivx(yi),a_{\mathrm{out}}=1-\frac{\sum_i v_x(y_i)\,c(8,y_i)}{\sum_i v_x(y_i)},

where the sums run over the outlet cells. It must remain at least 95%95\%.

A finite-volume discretization with 64×3264\times32 cells turns the PDE into 2×64×32=4,0962\times64\times32=4{,}096 ordinary differential equations. Advection uses first-order upwind fluxes; diffusion uses centered fluxes with no diffusive flux through the boundaries. An explicit two-stage strong-stability-preserving Runge–Kutta method advances time in substeps of at most 0.1 s. Heater inputs are held for Δt=2\Delta t=2 s, and integrating over one control interval defines the transition

Xk+1=F(Xk,uk),Xk∈R4096,uk∈[0,1]4,X_{k+1}=F(X_k,u_k),\qquad X_k\in\mathbb R^{4096},\quad u_k\in[0,1]^4,

which plays the role of the rollout map fk\mathbf f_k in Algorithm 1. The mesh partitions physical space; it is not a grid over the 4,096-dimensional state space. Refining it makes each rollout more expensive without changing the number of heater inputs.

Two flow profiles appear below, both with mean speed 0.2 m/s. The field-recovery problem uses a shear flow that is fastest at the center of the channel, vx(y)=0.16+0.24 η(1−η)v_x(y)=0.16+0.24\,\eta(1-\eta) m/s with η=y/2\eta=y/2. Material then takes about 36 s to cross the reactor at the center and nearly 50 s near the walls, so a disturbance tilts and stretches as it moves. The surrogate experiment uses uniform flow at 0.2 m/s.

Restoring the operating field

Holding all four heaters at 0.46 for 400 s under the shear flow produces a steady operating state. Its temperature rises from about 800 K at the inlet to a maximum of 1063.54 K, and its outlet conversion is about 95.8%95.8\%. Denote its fields by T⋆T_\star and a⋆a_\star. Starting from this state, a cold patch enters through the lower part of the inlet:

ΔTin(y,t)=−100exp⁡ ⁣[−(y−0.55)22(0.22)2]sin⁡2 ⁣(π(t−6)8) K,6≤t≤14 s,\Delta T_{\mathrm{in}}(y,t)=-100\exp\!\left[-\frac{(y-0.55)^2}{2(0.22)^2}\right] \sin^2\!\left(\frac{\pi(t-6)}{8}\right)\ \mathrm K, \qquad 6\leq t\leq14\ \mathrm s,

and ΔTin=0\Delta T_{\mathrm{in}}=0 otherwise. Control starts at 14 s, when the whole patch has entered the reactor and is traveling through the bottom half where H1 and H2 act. If the heaters stay at 0.46, the colder material reacts too slowly: outlet conversion falls to 94.75%94.75\% and remains below the 95%95\% limit for 7.5 s.

The task is to return both fields to the operating state while respecting the limits. The inlet is known to have returned to its normal profile, both fields are measured exactly at each decision, and the PDE is deterministic. As in the derivation of the update, randomness enters only through the candidate controls.

Departure from the operating state is measured by the normalized field error

E(X)=12048∑cells[(T−T⋆20 K)2+(a−a⋆0.1)2].E(X)=\frac1{2048}\sum_{\text{cells}}\left[ \left(\frac{T-T_\star}{20\ \mathrm K}\right)^2+ \left(\frac{a-a_\star}{0.1}\right)^2\right].

A cell that is 20 K too cold contributes as much as a cell whose conversion is 0.1 too low. The squared error penalizes warming as well as cooling, so heat delivered to material outside the cold patch counts against a plan. Each heater acts on a quadrant of 512 cells, and four such inputs cannot set the 4,0964{,}096 state values independently. Some error must remain until the cold material leaves the reactor.

MPPI plans over N=20N=20 intervals, a 40 s horizon equal to the mean residence time. With u−1u_{-1} the control applied during the previous interval, the planning objective is

J=120∑k=019[E(Xk+1)+0.014∑j=14(uk,j−0.460.05)2+0.0054∑j=14(uk,j−uk−1,j0.05)2]+E(X20).J=\frac1{20}\sum_{k=0}^{19}\left[E(X_{k+1}) +\frac{0.01}{4}\sum_{j=1}^4\left(\frac{u_{k,j}-0.46}{0.05}\right)^2 +\frac{0.005}{4}\sum_{j=1}^4\left(\frac{u_{k,j}-u_{k-1,j}}{0.05}\right)^2\right] +E(X_{20}).

The second term discourages departures from nominal heating, and the third discourages abrupt changes between intervals. Earlier in the chapter, control effort entered only through the KL penalty and SS contained state costs. Here JJ plays the role of SS and includes control terms written in physical heater units. The derivation of P⋆P^\star used only that SS assigns a cost to each complete candidate sequence, so these terms change the target distribution without changing the update.

The limits enter in two ways. During sampling, a candidate whose states at the 2 s decision times exceed 1070 K anywhere, or bring outlet conversion below 95%95\%, receives infinite cost and therefore zero weight. In the distributional objective, this restricts the reference to sequences that pass the check. That set need not be convex, so the mean of the resulting Gibbs distribution need not satisfy the limits, as in Exercise Exercise 4. Each proposed update therefore requires its own check before it can replace the stored plan.

Sampling in a bounded control space

A plan contains 20×4=8020\times4=80 heater values. Sampling each independently would produce irregular schedules and spend samples on rapid fluctuations that the third term of JJ penalizes. As in the aircraft example, a candidate is described by a few smooth parameters: six knots for each heater, linearly interpolated to the 20 decision times. This gives 24 sampled parameters, collected in a 6×46\times4 array zz.

Heater inputs must stay in [0,1][0,1], while Gaussian samples are unbounded. Clipping would change the distribution of the clipped values, as noted after Algorithm 1. Instead, a logistic map takes latent parameters to physical knot values,

uknots(z)=sigmoid⁡(logit⁡(useed)+0.12 z),u_{\mathrm{knots}}(z)=\operatorname{sigmoid}\bigl(\operatorname{logit}(u_{\mathrm{seed}})+0.12\,z\bigr),

applied elementwise. The array useedu_{\mathrm{seed}} contains the stored plan evaluated at the six knot times, so z=0z=0 reproduces the stored plan up to interpolation error. The derivative of the sigmoid is u(1−u)u(1-u), which is about 0.25 near u=0.46u=0.46. A latent change of 0.7, one standard deviation of the sampling distribution below, therefore moves a knot by about 0.12×0.7×0.25≈0.0210.12\times0.7\times0.25\approx0.021, or two percentage points of heating.

Gaussian densities are defined on zz. The reference is p0=N(0,0.49I)p_0=\mathcal N(0,0.49I) and the proposal is qμ=N(μ,0.49I)q_\mu=\mathcal N(\mu,0.49I). At each decision the decoder and the reference stay fixed while μ\mu starts at zero. Each of four updates draws K=256K=256 candidates z(i)∼qμz^{(i)}\sim q_\mu, decodes them, simulates them in the PDE, and computes

wi∝exp⁡ ⁣[−J(z(i))λ]p0(z(i))qμ(z(i)),μweighted=∑i=1Kwi z(i),λ=0.01.w_i\propto\exp\!\left[-\frac{J(z^{(i)})}{\lambda}\right] \frac{p_0(z^{(i)})}{q_\mu(z^{(i)})}, \qquad \mu_{\mathrm{weighted}}=\sum_{i=1}^Kw_i\,z^{(i)}, \qquad \lambda=0.01.

This is the importance-corrected update in latent coordinates, with Σ=0.49I\Sigma=0.49I and the mean μ\mu in place of the nominal controls. The weighting temperature λ\lambda is dimensionless, like JJ, and unrelated to temperature in kelvin. Since latent zero decodes to the stored plan, the KL penalty charges for changing that plan, not for heating as such. This is the alternative, noted with the reference distribution, of centering the reference on a baseline sequence, with the previous plan as the baseline. The average is taken in latent coordinates, so the decoded heater schedule generally differs from the weighted average of the candidates’ physical schedules.

The temperature sets which cost differences matter. At the first decision, the stored plan has J=0.0488J=0.0488. Before correction, a candidate whose cost exceeds another’s by λlog⁡2≈0.0069\lambda\log2\approx0.0069, about 14%14\% of that value, receives half the weight.

The likelihood correction changes the weights substantially once μ\mu has moved. At the fourth update of the first decision, after three accepted updates, candidate 12 had cost 0.05649 and candidate 180 had cost 0.05840. Exponential cost weighting alone would give candidate 12 about e0.191≈1.21e^{0.191}\approx1.21 times the weight of candidate 180. Its recorded weight, 0.0682, was instead less than half of candidate 180’s weight, 0.1565. The ratio corresponds to corrected costs that differ by −λlog⁡(0.0682/0.1565)≈0.0083-\lambda\log(0.0682/0.1565)\approx0.0083 in favor of candidate 180, so the correction term contributes about 0.0102. Candidate 12 lies farther in the direction in which the proposal had already moved, where the proposal samples more often than the reference. Exercise Exercise 6 works through this calculation.

Validating and executing a sampled update

Each update ends by checking the proposed mean. The controller decodes μ+α(μweighted−μ)\mu+\alpha(\mu_{\mathrm{weighted}}-\mu) for step fractions α∈{1,12,14,18}\alpha\in\{1,\tfrac12,\tfrac14,\tfrac18\} in turn, and accepts the first that lowers JJ below the stored plan’s value and passes a finer check. The finer check records the PDE state every 0.25 s over the 40 s plan, followed by another 40 s at nominal heating, and tests both limits at every record. If no step fraction succeeds, both μ\mu and the stored plan remain unchanged.

After four updates, the controller applies the first 2 s of the stored plan to the PDE, shifts the plan by one interval, and appends nominal heating. The stored plan is the exact heater sequence that passed validation; its six-knot approximation useedu_{\mathrm{seed}} only centers the next round of sampling. Because the plant is the same deterministic PDE with a known inlet, executing the first action reproduces the predicted state. The shifted plan followed by nominal heating then repeats a trajectory that has already passed the finer check, except for its final 2 s. The validation tail at nominal heating is what makes this continuation available: if every later update is rejected, the controller still holds a checked plan. Receding-horizon control develops this property, recursive feasibility, with terminal conditions in place of a simulated tail.

The procedure needs a feasible plan at the first decision. Unchanged heating does not qualify, since it violates the conversion limit. The experiment supplies an initial schedule that holds H1 at 0.50 for 8 s and returns it to 0.46 over the following 8 s, with the other heaters at nominal. This schedule is given to the controller, not found by it; MPPI starts from it and revises it at every decision.

Recorded recovery

All three schedules start from the same disturbed state at 14 s and are recorded until 80 s on a 0.25 s output grid. The integrated field error is ∫1480E(X(t)) dt\int_{14}^{80}E(X(t))\,dt, and heating energy is the integral of the mean heater fraction over the same interval. Both are measured in seconds; heating energy counts seconds at full average heating, since the model has no heat capacity to convert it to joules.

ScheduleIntegrated field errorHeating energyMaximum temperatureLowest outlet conversion
Unchanged heating3.709 s30.360 s1063.54 K94.747%94.747\%
Supplied initial schedule, executed unchanged2.098 s30.484 s1066.94 K95.271%95.271\%
MPPI1.962 s30.439 s1066.16 K95.329%95.329\%

The supplied schedule alone removes 43%43\% of the integrated error of unchanged heating and restores the conversion limit. MPPI removes 47.1%47.1\%, which is 6.5%6.5\% less error than the supplied schedule, while using slightly less heat than that schedule and staying 3.8 K below the temperature limit.

Four rows of reactor maps at 22, 34, and 46 seconds show temperature and conversion error relative to the operating state. A blue cold region in the lower half moves from about 2.5 meters to the outlet. Under MPPI the blue region is fainter and surrounded by faint red warming at 22 seconds.

Figure 7:Departures from the operating state at 22, 34, and 46 s. The first two rows show temperature error under unchanged heating and under MPPI; the last two rows show conversion error. Blue marks colder material or lower conversion. Dotted lines mark the heater quadrants. The deficit is carried downstream and tilted by the shear flow. MPPI reduces it, while each heater also warms material around the patch.

The controls in Figure 8 follow the patch. MPPI raises H1 by about five percentage points while the patch crosses the upstream bottom quadrant, then returns it to nominal by about 32 s. Between about 36 and 62 s it lowers H2, by up to 0.8 percentage points near 48 s, as material warmed by H1 passes through the downstream bottom quadrant; the squared error penalizes that excess warmth. The top heaters change by less than one percentage point. Outlet conversion still dips as the patch leaves, but its lowest value is 95.33%95.33\% instead of 94.75%94.75\%.

Four panels over 14 to 80 seconds. Normalized field error falls fastest for MPPI and the supplied schedule. Outlet conversion dips below 0.95 only under unchanged heating. Maximum temperature stays below the 1070 kelvin limit for all schedules. The heater panel shows H1 about 0.05 above nominal early, H2 slightly below nominal between about 36 and 62 seconds, and H3 and H4 near nominal.

Figure 8:Recovery from the disturbed state at 14 s. Top left: normalized field error E(X(t))E(X(t)). Top right: outlet conversion, with the 95%95\% limit dashed. Bottom left: maximum temperature, with the 1070 K limit dashed. Bottom right: executed MPPI heater inputs relative to nominal heating 0.46, each held for 2 s.

The sampling statistics show how much of this result comes from accepted updates. Over 33 decisions, 24 of 132 updates were accepted. Only four of the accepted updates used the full weighted mean; the other 20 needed a step fraction of 12\tfrac12 or less. Nine acceptances occurred in the first three decisions and eleven more between 32 and 42 s, as the patch approached the outlet. From 44 s on, only 3 of 72 updates were accepted. By then the stored plan was already returning to nominal heating, and random perturbations tended to add error to a field that was recovering on its own. The effective sample size ranged from 19.8 to 64.1 of 256 candidates, and between 108 and 217 candidates per batch passed the constraint check. With the weight concentrated on a few dozen candidates, the weighted mean is a noisy proposal, and the step fractions trade progress for reliability.

The opening decision was also repeated with three optimizer seeds at each of 128, 256, and 512 candidates. All nine runs lowered the objective of the supplied schedule, by between 5.3%5.3\% and 6.7%6.7\%. The effective sample size grew with the number of candidates, from 4.3–18.9 at 128 to 32.5–63.0 at 512. The final objectives did not improve with the count: their spread across seeds at a fixed count exceeded the differences between the averages at different counts. These repetitions measure optimizer variability at one physical state. They do not establish that the recorded plan is globally optimal.

Planning took 13.9 s per decision on average, including the finer checks and first-use compilation. This is longer than the 2 s control interval: the recording is an offline computation, not a demonstration of real-time control. The numerical model was checked separately by repeating the executed MPPI controls with halved integration steps, which changes the temperature field by 0.0014 K root-mean-square, and on a 128×64128\times64 mesh, which changes it by 0.78 K. The finer mesh reaches 1068.42 K and a lowest outlet conversion of 95.36%95.36\%, still within both limits. First-order upwind advection adds numerical diffusion of roughly vxΔx/2≈0.013v_x\Delta x/2\approx0.013 m2^2/s, much larger than DD, so part of the visible spreading of the patch is a property of the discretization.

Planning with a learned surrogate

Each recovery decision simulated 256 candidates over 20 intervals in each of four updates, or 20,48020{,}480 interval rollouts before validation. For this coarse PDE the budget is affordable. A finer mesh, separate gas and solid phases, or a computational fluid dynamics model of an industrial calciner would make it expensive. A common response is to learn a fast approximate transition model, a surrogate, from simulations and to use it for the candidate rollouts. MPPI requires only rollouts and costs, so the substitution changes no part of the update. It changes which model ranks the candidates: the weights now favor candidates that the surrogate predicts to be good.

The surrogate experiment uses the uniform-flow version of the reactor with a different task. Nominal heating is 0.48 in all four quadrants, and the inlet temperature 800+10cos⁡(πy/2)+gt800+10\cos(\pi y/2)+g_t K fluctuates. The deviation gtg_t follows the Ornstein–Uhlenbeck model of the aircraft example with correlation time 20 s and stationary standard deviation 15 K, held constant over each 2 s interval and observed at each decision. The objective is economic: use as little heat as possible while keeping outlet conversion at least 95%95\% and temperature at most 1070 K. The planning cost averages, over 20 steps,

ℓk=14∑j=14uk,j+5[(0.95−aout,k+1)+0.05]2+10[(max⁡Tk+1−1070 K)+20 K]2+0.054∑j=14(uk,j−uk−1,j0.1)2,\ell_k=\frac14\sum_{j=1}^4u_{k,j} +5\left[\frac{(0.95-a_{\mathrm{out},k+1})_+}{0.05}\right]^2 +10\left[\frac{(\max T_{k+1}-1070\ \mathrm K)_+}{20\ \mathrm K}\right]^2 +\frac{0.05}{4}\sum_{j=1}^4\left(\frac{u_{k,j}-u_{k-1,j}}{0.1}\right)^2,

where (⋅)+=max⁡(⋅,0)(\cdot)_+=\max(\cdot,0) and the conversion and temperature are evaluated at the end of interval kk.

The surrogate is a residual convolutional network that predicts the change of both fields over one 2 s interval. Its six input channels are the normalized temperature and reactant fields, the map of heater fractions, the normalized inlet temperature, and two coordinate channels. Four 3×33\times3 convolutions with 16 hidden channels and dilations 1,2,4,11,2,4,1 let each output cell depend on inputs up to eight cells away, more than the 3.2 cells that material travels in one interval. After each predicted step, the reactant fraction is projected onto [0,1][0,1]; temperature is not modified. Training used 256 PDE episodes of 120 s with varied heating, warm and cold starts, smooth spatial transients, and inlet fluctuations, split by whole episode into 179 training, 38 validation, and 39 test episodes. The loss combined one-step error, five-step rollout error, and outlet error. The checkpoint used here was selected after three epochs of Adam within a local CPU budget.

Held-out 40 s rollouts, 39 test episodesResult
Temperature root-mean-square error4.59 K
Outlet-conversion mean absolute error0.0039
95th percentile of peak-temperature underprediction8.31 K
Largest reactant-fraction bound excess before projection0.068

These averages must be read against the margins that decide feasibility. Under constant heating, the lowest outlet conversion in the trials below is 95.09%95.09\%, a margin of 0.09 percentage points, while the surrogate’s average conversion error is 0.39 percentage points. A plan accepted on the surrogate’s predictions alone could violate the conversion limit in the PDE, and an 8 K underprediction of the peak temperature could hide a violation of the temperature limit.

The controller therefore keeps two roles for the PDE. Every applied control advances the PDE under the realized inlet, and every proposed plan is simulated in the PDE before it is accepted. The planner samples K=128K=128 candidates in latent coordinates with u(z)=sigmoid⁡(logit⁡(0.48)+0.35z)u(z)=\operatorname{sigmoid}(\operatorname{logit}(0.48)+0.35z) and the reference p0=N(0,0.49I)p_0=\mathcal N(0,0.49I), which now decodes to constant nominal heating. Its KL penalty charges departures from nominal heating, while the proposal mean is initialized from the shifted previous plan. Candidate costs come from surrogate rollouts, and the weights use λ=0.025\lambda=0.025. A candidate that uses one percentage point less heat on average, with no penalty active, receives about e0.01/0.025≈1.5e^{0.01/0.025}\approx1.5 times the weight. After each of two updates per decision, the weighted mean is accepted only if it lowers the surrogate cost and a PDE rollout under the conditional mean inlet keeps conversion at or above 95%95\% and temperature at or below 1070 K at every 2 s output. Otherwise the previous plan is kept. If the shifted previous plan fails the PDE check at the next decision, constant nominal heating is checked instead; if both fail, the episode stops and records a planning failure.

Two forecast variants separate reaction to the observed inlet from planning under its uncertainty, as in the aircraft example. The mean-forecast controller scores each candidate under the conditional mean of the future inlet. The stochastic controller scores it under four conditional futures, shared by all candidates, and averages the four costs before weighting.

Surrogate and PDE planning compared

Eight paired trials start from the warm state and last 160 s. Within a trial, constant heating and both MPPI controllers face the same realized inlet sequence.

ControllerMean heating energyLowest outlet conversionHighest temperatureAccepted updatesPlanning time per decision
Constant heating76.800 s95.09%95.09\%1059.5 Knonenone
Surrogate MPPI, mean forecast75.807 s95.30%95.30\%1051.9 K127 of 12801.32 s
Surrogate MPPI, stochastic forecast75.759 s95.16%95.16\%1052.4 K143 of 12804.45 s

Lowest and highest values are taken over all trials at the 2 s outputs. No episode stopped, and every execution stayed within both limits on the 2 s grid and on a separate 0.1 s audit of the executed controls. Paired differences in heating energy, with 95%95\% Student-t intervals over the eight trials, are −0.99±0.30-0.99\pm0.30 s for mean-forecast MPPI minus constant heating, −1.04±0.34-1.04\pm0.34 s for stochastic MPPI minus constant heating, and −0.048±0.099-0.048\pm0.099 s for stochastic minus mean-forecast MPPI. Both MPPI variants use about 1.3%1.3\% less heat than constant heating. The trials do not establish a difference between the two forecast variants. About one proposed update in ten was accepted.

Three dot plots compare constant heating, mean-forecast MPPI, and stochastic MPPI over eight trials. Heating energy is 76.8 seconds for constant heating and between about 75.1 and 76.4 seconds for both MPPI variants. Lowest outlet conversion stays above the 0.95 line for all trials. Highest temperature stays below the 1070 kelvin line, lower for MPPI than for constant heating.

Figure 9:Eight paired 160 s trials of surrogate MPPI in the uniform-flow reactor. Left: heating energy. Center: lowest outlet conversion, with the 95%95\% limit dashed. Right: highest temperature, with the 1070 K limit dashed. Each dot is one trial, and the three controllers in a trial share one realized inlet sequence.

To isolate the effect of the rollout model, the same planner was run from the warm state with zero inlet deviation, once with surrogate rollouts and once with PDE rollouts, using the same random seed and settings. Each resulting 40 s plan was then evaluated in the PDE on 32 fresh inlet futures. The first heater commands were nearly identical, (0.484,0.474,0.486,0.480)(0.484,0.474,0.486,0.480) from the surrogate and (0.484,0.472,0.486,0.478)(0.484,0.472,0.486,0.478) from the PDE, and the held-out PDE costs were 0.47331 and 0.47250. Planning took 14.57 s with the surrogate and 11.25 s with the PDE, both including PDE validation and the recording of candidate snapshots. For this coarse PDE the surrogate brought no speed advantage. A surrogate pays for itself only when the model it replaces is substantially more expensive to roll out.

The two plans nearly coincide because of the structure of ℓk\ell_k. For a candidate that triggers neither penalty, the cost consists of mean heating and the slew term, which depend only on the controls. The surrogate and the PDE assign such a candidate the same cost. For both selected plans, the cost on the planning forecasts agreed with the held-out PDE cost to within 10-6. Such agreement between different models and inlet futures means that the penalties contributed essentially nothing in either evaluation. The rollout model affects the weights only through the penalties, that is, through deciding which low-heating candidates violate the conversion limit and which high-heating candidates exceed the temperature limit. Surrogate accuracy matters near the boundary of the feasible set, which is also where an economic objective drives the plan. Average errors over held-out trajectories do not measure accuracy there. The PDE acceptance check instead tests the one plan that will be executed, under the conditional mean inlet.

Both experiments use the same structure. Sampling explores a small, bounded parameterization of the heater schedule; exponential weights with a likelihood correction propose an update; and the full model decides whether the update replaces a plan that is already known to be feasible. In the recovery experiment the full model also generates the candidate costs. In the surrogate experiment a learned model generates them, and its errors matter where the constraints are nearly active.

The replay opens on the field-recovery experiment. Play the recording to follow the cold patch under unchanged heating and MPPI, display the error relative to the operating state, or open the sampled control update to see six candidates and their full-batch weights at 14, 22, and 34 s. The Surrogate vs PDE tab compares the learned model with the PDE under identical controls and inlet histories in the uniform-flow experiment. Every field image is a recorded numerical rollout; the page performs no simulation.

Summary and Outlook

MPPI begins with the single-shooting rollout and changes how its candidate inputs are combined. A reference distribution favors small inputs; exponential state-cost weights favor useful trajectories; a Gaussian fit turns the resulting distribution into a stored control sequence. Importance correction preserves the target when samples are drawn around a nonzero nominal sequence.

The aircraft application separates control exploration from wind uncertainty and averages wind costs before assigning a candidate its weight. Increasing the number of candidate controls and increasing the number of wind futures address different estimation errors. Neither guarantees that a weighted mean is feasible or improves the cost, so candidate updates are validated before they replace the stored plan.

The reactor application uses the same update on a discretized PDE with 4,096 state values. Six bounded knots per heater reduce the search to 24 latent parameters, in which the Gaussian densities and the likelihood correction are computed, and candidates that violate a limit receive zero weight. Because the mean of feasible candidates need not be feasible, each proposed update is checked in the PDE, damped when necessary, and otherwise rejected; once the field was recovering, most updates were rejected. Replacing the PDE by a learned surrogate in the sampling loop changes the model that ranks candidates, while the PDE still decides which plan is executed. With an economic objective, the surrogate’s errors matter mainly near the operating limits, which is where the plan operates.

The controller still needs an execution rule. Applying one action, observing the result, and solving again provides feedback even though each stored sequence is open loop. Receding-horizon control develops that rule further, including the choice of horizon, terminal conditions, and feasibility safeguards. These questions apply whether the planner uses derivatives or sampled trajectories.

The method’s name also reflects a connection to expectations over entire stochastic paths. Path-integral stochastic control, after stochastic dynamic programming, develops that connection and states the additional assumptions under which path weighting yields an optimal current feedback action.

Computational Sources

The aircraft and reactor experiments use small numerical modules and read precomputed results when the book is built. The aircraft evaluator averages each candidate’s costs over a shared ensemble of possible wind futures.

The experiment scripts record the physical parameters, planner settings, seeds, and validation diagnostics alongside their results. The aircraft replay and the reactor replay display recorded simulations without a Python kernel. Regeneration commands are in the repository README.

Exercises

Solution to Exercise 1

(a) The unnormalized weights are (1/4,1/2,1)(1/4,1/2,1), whose sum is 7/47/4. The normalized weights are (1/7,2/7,4/7)(1/7,2/7,4/7), giving u+=−(1/7)+(4/7)=3/7u^+=-(1/7)+(4/7)=3/7.

(b) The common factor e−1000e^{-1000} cancels between numerator and denominator. Direct evaluation would underflow in ordinary floating-point arithmetic. Subtracting the minimum corrected cost before exponentiating recovers the original three weights.

(c) The unique minimum cost belongs to perturbation 1. Its normalized weight approaches one, so u+→1u^+\to1. The qualification that corrected costs are fixed matters: a likelihood correction can itself depend on λ\lambda.

Solution to Exercise 2

(a) Up to a constant, the negative log Gibbs density is

rh2λ∑kvk2+κ2λ(h∑kvk−a)2.\frac{rh}{2\lambda}\sum_kv_k^2 +\frac\kappa{2\lambda}\left(h\sum_kv_k-a\right)^2.

Its first-order condition is rvk+κ(h∑jvj−a)=0r v_k+\kappa(h\sum_jv_j-a)=0. All coordinates of its minimizer are equal, giving

EP⋆vk=κar+κNh=0.8.\mathbb E_{P^\star}v_k=\frac{\kappa a}{r+\kappa Nh}=0.8.

The result is independent of the proposal mean because the likelihood ratio cancels the proposal density in the expectation.

(b) Omitting that ratio replaces the reference quadratic ∑kvk2\sum_kv_k^2 by ∑k(vk−0.4)2\sum_k(v_k-0.4)^2. The corresponding first-order condition is r(vk−0.4)+κ(h∑jvj−a)=0r(v_k-0.4)+\kappa(h\sum_jv_j-a)=0, so its mean is

0.4r+κar+κNh=0.88.\frac{0.4r+\kappa a}{r+\kappa Nh}=0.88.

Thus the two procedures converge to different expectations.

(c) A minimal implementation uses the same perturbations for both estimates so that their difference is easier to observe:

import numpy as np

rng = np.random.default_rng(728)
N, h, r, kappa, lam = 10, 0.1, 1.0, 4.0, 0.5
U = np.full(N, 0.4)
for K in (1_000, 10_000, 100_000):
    eps = rng.normal(size=(K, N)) * np.sqrt(lam / (r * h))
    inputs = U + eps
    cost = 0.5 * kappa * (h * inputs.sum(axis=1) - 1.0) ** 2
    corrected = cost + h * r * (eps @ U)
    estimates = []
    for scores in (corrected, cost):
        weights = np.exp(-(scores - scores.min()) / lam)
        weights /= weights.sum()
        estimates.append((weights @ inputs).mean())
    print(K, *estimates)

The estimates approach 0.8 and 0.88. More samples reduce Monte Carlo error; they do not repair an omitted likelihood ratio. Individual runs need not approach their limits monotonically.

Solution to Exercise 3

(a) For a fixed candidate, averaging the weights estimates EW[e−C/λ]\mathbb E_W[e^{-C/\lambda}], whereas the desired score depends on EWC\mathbb E_W C. The exponential is nonlinear. Favorable gust histories receive disproportionate weight, so this procedure can favor a candidate whose expected cost is larger. The reference-to-proposal correction for control sampling does not remove this difference in the disturbance objective.

(b) The safe candidate has expected cost 1 and exponential score 1. The risky candidate has expected cost 2 but exponential score −log⁡(0.9+0.1e−20)≈0.105-\log(0.9+0.1e^{-20})\approx0.105. Expected cost favors the safe candidate; the exponential score favors the risky candidate.

(c) For each candidate, simulate multiple gust histories and form C^(U)=L−1∑ℓ=1LC(U,W(ℓ))\widehat C(\mathbf U)=L^{-1}\sum_{\ell=1}^L C(\mathbf U,W^{(\ell)}). Then use C^\widehat C as the candidate score in the sampling optimizer. Shared gust histories across candidates can make paired comparisons less variable. As the number of disturbance samples increases, this score estimates the intended expected cost. The subsequent Gaussian mean fit need not minimize that cost over deterministic plans. Finite sampling introduces further error, and an average of feasible plans may violate nonconvex constraints. The proposed plan still needs cost and feasibility checks.

Solution to Exercise 4

(a) The controller executed 0.6. Its shifted initial guess is (0.4,0.2,0.2)(0.4,0.2,0.2), and the measured state becomes the initial state for every new rollout. The guess is then updated by sampling; it is not a commitment to execute all three entries.

(b) The mean is u=0u=0, which produces x1=0x_1=0 outside both allowed intervals. Feasible samples do not ensure a feasible mean under nonconvex constraints. The implementation should validate the proposal and retain the feasible incumbent when that validation fails, as in the aircraft example.

Solution to Exercise 5

(a) Each of the 2,0482{,}048 cells carries a temperature and a reactant fraction, so a rollout advances 4,0964{,}096 state values. The weighted mean averages the 6×4=246\times4=24 latent parameters.

(b) One decision simulates 256×4×20=20,480256\times4\times20=20{,}480 intervals. Each interval needs at least 2/0.1=202/0.1=20 substeps, so at least 409,600409{,}600 substeps are required, each evaluating the right-hand side twice in the two-stage Runge–Kutta method.

(c) The refined mesh has Δx=8/128=0.0625\Delta x=8/128=0.0625 m, so the advective condition allows Δt≤0.0625/0.22≈0.28\Delta t\leq0.0625/0.22\approx0.28 s, and the 0.1 s cap remains binding. The state dimension grows by a factor of four, to 16,38416{,}384. The number of sampled parameters stays 24. Each substep updates four times as many cells, so the work per decision grows by about a factor of four. The weights and the update keep the same dimension.

(d) A single 2 s increase of one heater in the middle of the horizon, with all neighboring values at nominal, is not piecewise linear between the six knot times and cannot be represented. MPPI searches only within the knot family, so the recorded schedule is at best a good member of that family. Finite sampling, the Gaussian mean fit, the regularizing reference, and the step fractions limit even that statement, so the result supports an improvement over the supplied schedule, not optimality.

Solution to Exercise 6

(a) Here logit⁡(0.9)=log⁡9≈2.197\operatorname{logit}(0.9)=\log9\approx2.197 and sz=±0.7sz=\pm0.7. The decoded inputs are sigmoid⁡(2.897)≈0.948\operatorname{sigmoid}(2.897)\approx0.948 and sigmoid⁡(1.497)≈0.817\operatorname{sigmoid}(1.497)\approx0.817, whose average is about 0.882. The latent mean is zˉ=0\bar z=0, which decodes to 0.9. The controller averages latent parameters and proposes u(zˉ)=0.9u(\bar z)=0.9, subject to validation. Both numbers lie in (0,1)(0,1): the sigmoid maps every real number into (0,1)(0,1), and an average of numbers in (0,1)(0,1) stays there. They differ because the sigmoid is curved: near the upper bound, equal latent steps produce a smaller increase than decrease.

(b) For Gaussians with a common covariance,

log⁡p0(z)qμ(z)=−∥z∥22σ2+∥z−μ∥22σ2=−μ⊤zσ2+∥μ∥22σ2.\log\frac{p_0(z)}{q_\mu(z)} =-\frac{\|z\|^2}{2\sigma^2}+\frac{\|z-\mu\|^2}{2\sigma^2} =-\frac{\mu^\top z}{\sigma^2}+\frac{\|\mu\|^2}{2\sigma^2}.

The last term is the same for every candidate and cancels after normalization. Thus e−Ji/λp0/qμ∝exp⁡[−(Ji+λμ⊤z(i)/σ2)/λ]e^{-J_i/\lambda}p_0/q_\mu\propto\exp[-(J_i+\lambda\mu^\top z^{(i)}/\sigma^2)/\lambda]. Writing z(i)=μ+ϵ(i)z^{(i)}=\mu+\boldsymbol\epsilon^{(i)} changes the correction only by another common constant, giving the form λμ⊤Σ−1ϵ(i)\lambda\mu^\top\Sigma^{-1}\boldsymbol\epsilon^{(i)} of the earlier corrected cost, with Σ=σ2I\Sigma=\sigma^2I.

(c) The weight ratio gives the difference in corrected costs,

J~12−J~180=−λlog⁡0.06820.1565≈0.0083.\widetilde J_{12}-\widetilde J_{180} =-\lambda\log\frac{0.0682}{0.1565}\approx0.0083.

The cost difference is J12−J180=−0.0019J_{12}-J_{180}=-0.0019, so the correction contributes 0.0102=λμ⊤(z(12)−z(180))/σ20.0102=\lambda\mu^\top(z^{(12)}-z^{(180)})/\sigma^2. Hence μ⊤(z(12)−z(180))≈0.0102×0.49/0.01≈0.50\mu^\top(z^{(12)}-z^{(180)})\approx0.0102\times0.49/0.01\approx0.50. The positive sign means that candidate 12 lies farther along the direction in which the proposal mean has already moved. The proposal draws such candidates more often than the reference would, and the correction lowers their weight to compensate.

(d) The Gaussian density belongs to the unclipped sample, so the ratio must be computed for that variable, with clipping treated as part of the deterministic map from samples to controls, as for the aircraft duration. Every sample beyond a bound then produces the same control and the same cost. Those samples are indistinguishable to the weights, and the weighted mean of unclipped values can itself lie outside [0,1][0,1]. The logistic decoder keeps distinct latent samples distinct and always decodes the mean inside the bounds.

Solution to Exercise 7

(a) Without active penalties, ℓk\ell_k reduces to mean heating plus the slew term, both functions of the controls alone. Any rollouts that remain valid therefore give the same cost under either model. Surrogate errors can change the cost only of candidates for which at least one model predicts an active penalty, that is, candidates near the conversion or temperature limit. Minimizing heating pushes the plan toward the conversion limit, so these are the candidates that matter.

(b) No. The 8.31 K figure is a percentile over held-out windows, not a bound: one window in twenty underpredicted by more, and an optimized plan is not drawn from the held-out distribution. Adding 8.31 K to 1064 K already exceeds 1070 K. The PDE acceptance check simulates the proposed plan before it replaces the stored one. It uses the conditional mean of the future inlet, so it does not guarantee feasibility under the inlet that is actually realized. The audit on a 0.1 s grid checks the executed controls only after the fact.

(c) Larger margins make surrogate rollouts reject more candidates near the limits. Fewer proposals then fail the PDE check, and violations under the realized inlet become less likely, but the controller gives up heating reductions that were feasible. Smaller margins allow plans closer to the limits, at the price of more rejected proposals and less protection against surrogate error and inlet uncertainty. Margins calibrated from surrogate errors near the limits, rather than from average errors, would make this choice less arbitrary.

(d) A surrogate reduces planning time when rollouts of the full model dominate the computation and the surrogate is much cheaper to evaluate in large batches, for example with a finer mesh, multiphase physics, or computational fluid dynamics. Removing the PDE check would require evidence about errors near the constraint boundary for the kinds of plans the optimizer proposes, not only average errors on training-like trajectories, together with closed-loop trials whose executed controls are audited in the full model.

Solution to Exercise 8

Answers depend on the training data and budget. Useful comparisons keep the initial state, supplied schedule, planner settings, and optimizer seeds fixed, so that differences come from the rollout model. Since the tracking objective depends on the entire field, surrogate errors affect every candidate’s cost, unlike in the economic objective of Exercise Exercise 7. When the surrogate ranks candidates differently from the PDE, an accepted update can lower the surrogate objective while raising the PDE objective, so both should be recorded for every proposal. For part (c), the fraction of proposals rejected by the PDE check, the gap between the surrogate’s predicted objective and the PDE objective of each proposal, and raw reactant-fraction values outside [0,1][0,1] before projection all signal that the surrogate is operating outside its training distribution.

Self-checks

Solution to Exercise 9

Conditioning a new plan on the observed state supplies feedback. A control sequence computed from many samples and then frozen still executes open loop.

Solution to Exercise 10

Only the candidate controls are random. The PDE is deterministic and the inlet is known after the pulse, so random numbers serve only to explore heater schedules. A different seed changes the sampled candidates and therefore the plan. Across the nine repetitions of the opening decision, the final objective varied by about 1.5%1.5\%.

References
  1. Williams, G., Drews, P., Goldfain, B., Rehg, J. M., & Theodorou, E. A. (2017). Information Theoretic Model Predictive Control: Theory and Applications to Autonomous Driving. 10.48550/arXiv.1707.02342
  2. Williams, G., Aldrich, A., & Theodorou, E. A. (2017). Model Predictive Path Integral Control: From Theory to Parallel Computation. Journal of Guidance, Control, and Dynamics, 40(2), 344–357. 10.2514/1.G001921
  3. Pan, C., Yi, Z., Shi, G., & Qu, G. (2024). Model-Based Diffusion for Trajectory Optimization. Advances in Neural Information Processing Systems, 37. https://proceedings.neurips.cc/paper_files/paper/2024/file/6a5c38a730b17f3827c09cf6b192be04-Paper-Conference.pdf
  4. Sun, J. (2022). OpenAP.top: Open Flight Trajectory Optimization for Air Transport and Sustainability Research. Aerospace, 9(7), 383. 10.3390/aerospace9070383
  5. Copernicus Climate Change Service (C3S). (2018). ERA5 hourly data on pressure levels from 1940 to present. Copernicus Climate Change Service (C3S) Climate Data Store (CDS). 10.24381/cds.bd0915c6
  6. Cantisani, N., Svensen, J. L., Hansen, O. F., & Jørgensen, J. B. (2024). Dynamic modeling and simulation of a flash clay calciner. IFAC-PapersOnLine, 58(14), 283–288. 10.1016/j.ifacol.2024.08.350