Algorithm Search⌘K

Algorithmresearch

Randomize-then-optimize

Also called RTO sampler, RTO, RTO-MH.

Draw posterior samples for an inverse problem by solving perturbed optimization problems and correcting with a Metropolis step or importance weights.

Time
Θ(N k (T + M n^2)) worst · averageΘ(N (T + M n^2)) best
Space
Θ(M n + N n) extra
Where
M = the number of rows of the stacked residual (data plus prior); N = the number of samples; T = the cost of one evaluation of F and its Jacobian; k = the Newton steps per sample; n = the number of unknowns
Properties
exact with correctionneeds gradientsparallel proposalsrandomized
Origin
Johnathan M. Bardsley, Antti Solonen, Heikki Haario, Marko Laine, 2014

Randomize-then-optimize (RTO) makes posterior samples by optimization. It applies to posteriors of least squares form, π(x)∝exp⁡(−12∥F(x)−yˉ∥2)\pi(x) \propto \exp(-\frac12\lVert F(x) - \bar y\rVert^2), which covers a nonlinear forward model with Gaussian noise and a Gaussian prior. Each sample perturbs the data, yˉ+ε\bar y + \varepsilon with ε∼N(0,I)\varepsilon \sim N(0, I), and solves a projected version of the least squares problem, QTF(x)=QT(yˉ+ε)Q^TF(x) = Q^T(\bar y + \varepsilon), where QQ is an orthonormal basis of the range of the Jacobian at the MAP point. For a linear model these solutions are exact, independent posterior samples. For a nonlinear model they come from a known density qq, and the ratio π/q\pi/q can be computed, so a Metropolis-Hastings step or importance weights remove the bias. Bardsley, Solonen, Haario and Laine introduced the method in 2014. Its proposals are independent of each other, so they can be computed in parallel, and it uses the optimization tools that a MAP estimate needs anyway.

In plain words

To find the single most likely answer, you solve one least squares problem. To get a spread of plausible answers, RTO adds random noise to the data and to the prior guess, solves the problem again, and repeats. For a linear problem the spread of these answers is exactly the right one. For a nonlinear problem it is a little off. RTO knows by how much, because it can compute the density of its own proposals. A Metropolis-Hastings step then keeps or rejects each answer so that the final set has the right distribution.

The problem

Sample π(x)∝exp⁡(−12∥F(x)−yˉ∥2)\pi(x) \propto \exp(-\frac12\lVert F(x) - \bar y\rVert^2) on Rn\mathbb{R}^n, with F:Rn→RMF: \mathbb{R}^n \to \mathbb{R}^M, M≥nM \ge n, smooth, with Jacobian JJ. For a Bayesian inverse problem with forward map GG, noise N(0,Γ)N(0, \Gamma) and prior N(m0,C)N(m_0, C), LTL=C−1L^TL = C^{-1},

F(x)=[Γ−1/2G(x)L(x−m0)],yˉ=[Γ−1/2y0].F(x) = \begin{bmatrix}\Gamma^{-1/2}G(x)\\ L(x - m_0)\end{bmatrix}, \qquad \bar y = \begin{bmatrix}\Gamma^{-1/2}y\\ 0\end{bmatrix}.

The output is a Markov chain x1,…,xNx_1, \dots, x_N with invariant law π\pi.

The algorithm

  1. RTO-MH(F, J, ybar, x_0, N)
  2. 1xbar ← argmin_x ||F(x) - ybar||² by Gauss-Newton from x_0 ▷ the MAP point
  3. 2Q ← orthonormal basis of the columns of J(xbar) ▷ thin QR, M × n
  4. 3x ← xbar, w ← weight(xbar)
  5. 4for k = 1, ..., N
  6. 5eps ← N(0, I_M)
  7. 6x' ← solution of Q^T F(x') = Q^T (ybar + eps), Newton from xbar
  8. 7w' ← |det(Q^T J(x'))|^(-1) exp(-½||F(x') - ybar||² + ½||Q^T (F(x') - ybar)||²)
  9. 8with probability min(1, w' / w): x ← x', w ← w'
  10. 9append x to the chain
  11. 10return the chain and the acceptance rate

Line L1 computes the MAP point, the minimizer of the Tikhonov type functional 12∥F(x)−yˉ∥2\frac12\lVert F(x) - \bar y\rVert^2, with the Gauss-Newton algorithm. Line L2 takes a QR decomposition of the Jacobian there. Lines L5 and L6 are the "randomize" and "optimize" steps: the solution of line L6 is a stationary point of ∥QT(F(x)−yˉ−ε)∥2\lVert Q^T(F(x) - \bar y - \varepsilon)\rVert^2. Line L7 is the weight w=π/qw = \pi/q, where

q(x)∝∣det⁡(QTJ(x))∣exp⁡(−12∥QT(F(x)−yˉ)∥2)q(x) \propto \lvert\det(Q^TJ(x))\rvert\exp\big(-\tfrac12\lVert Q^T(F(x) - \bar y)\rVert^2\big)

is the density of the points made by line L6. It follows from the change of variables z=QTF(x)z = Q^TF(x), since z=QT(yˉ+ε)z = Q^T(\bar y + \varepsilon) is N(QTyˉ,In)N(Q^T\bar y, I_n). Line L8 is the independence Metropolis-Hastings test, done with logarithms in the code. If line L6 fails, the state stays.

For a linear F(x)=Hx−h0F(x) = Hx - h_0, line L6 is the least squares problem min⁡∥Hx−h0−yˉ−ε∥\min\lVert Hx - h_0 - \bar y - \varepsilon\rVert, the weight is constant, and line L8 accepts every proposal. So for linear Gaussian inverse problems, RTO is the classical "perturb the data and the prior mean, then solve" method for Gaussian sampling.

Example

A scalar nonlinear problem: G(x)=x+x3G(x) = x + x^3, noise standard deviation 0.50.5, observed y=1.5y = 1.5, prior N(0,1)N(0, 1). So F(x)=[(x+x3)/0.5; x]F(x) = [(x + x^3)/0.5;\ x] and yˉ=[3; 0]\bar y = [3;\ 0]. The posterior mean and variance, by quadrature on 40001 points in [−4,4][-4, 4], are 0.75720.7572 and 0.043210.04321.

method, 5000 draws, seed 3 mean variance
quadrature (reference) 0.7572 0.04321
MAP point (line L1) 0.8400 none
line L6 proposals, no correction 0.8141 0.03122
proposals with importance weights ww 0.7530 0.04375
RTO-MH, acceptance rate 0.836 0.7598 0.03982

The uncorrected proposals are biased toward the MAP point and too narrow. Both corrections remove the bias up to Monte Carlo error. The effective sample size of the importance weights, (∑w)2/∑w2(\sum w)^2/\sum w^2, is 4417 of 5000, which shows that qq is close to π\pi here.

For the linear version, G(x)=0.1xG(x) = 0.1x with noise 0.050.05, y=0.12y = 0.12 and prior N(0,1)N(0, 1), RTO-MH accepts all 5000 proposals (seed 1) and gives mean 0.9670.967 and variance 0.2030.203; the exact posterior is N(0.96,0.2)N(0.96, 0.2). All numbers are measurements with fixed seeds.

Correctness

The proof is in proofs/correctness.md. Under the assumption that x↦QTF(x)x \mapsto Q^TF(x) is one-to-one with nonsingular derivative and that the solver of line L6 finds its solution when there is one, the points of line L6 have the density qq above (change of variables), π/q\pi/q is proportional to the weight of line L7, and the independence Metropolis-Hastings step satisfies detailed balance for π\pi. For an affine FF the assumption holds, the weight is constant, and the proposals are exact independent posterior samples. The procedure stops: every loop in it has a fixed bound. The choice of QQ at the MAP point is for efficiency; any QQ that satisfies the assumption gives a correct chain. How fast the chain mixes depends on how close qq is to π\pi, which is a property of the problem, not a theorem.

Proof: RTO-MH stops after the given number of steps, its proposal has the stated density, and the chain leaves the posterior invariantfull

Setting. F:Rn→RMF: \mathbb{R}^n \to \mathbb{R}^M with M≥nM \ge n is continuously differentiable with Jacobian J(x)J(x), yˉ∈RM\bar y \in \mathbb{R}^M, and the target density is

π(x)=1Zexp⁡(−12∥F(x)−yˉ∥2).\pi(x) = \frac1Z\exp\big(-\tfrac12\lVert F(x) - \bar y\rVert^2\big).

For a Gaussian prior N(m0,C)N(m_0, C) with LTL=C−1L^TL = C^{-1} and noise N(0,Γ)N(0, \Gamma), F(x)=[Γ−1/2G(x);L(x−m0)]F(x) = [\Gamma^{-1/2}G(x); L(x - m_0)] and yˉ=[Γ−1/2y;0]\bar y = [\Gamma^{-1/2}y; 0] give the posterior. QQ is an M×nM \times n matrix with orthonormal columns (line L2). Write T(x)=QTF(x)T(x) = Q^TF(x), so T′(x)=QTJ(x)T'(x) = Q^TJ(x).

Assumption (A). TT is one-to-one on Rn\mathbb{R}^n, det⁡T′(x)≠0\det T'(x) \ne 0 for all xx, and whenever QT(yˉ+ε)Q^T(\bar y + \varepsilon) lies in the image T(Rn)T(\mathbb{R}^n) the solver of line L6 returns the solution x′=T−1(QT(yˉ+ε))x' = T^{-1}(Q^T(\bar y + \varepsilon)). When the target is not in the image, line L6 returns no point.

Claim 1 (termination). For N≥1N \ge 1 the procedure stops and returns a chain of NN states and an acceptance rate in [0,1][0, 1].

Proof. The Gauss-Newton loop of line L1 has at most a fixed number of outer steps (100 in the code), and each step halves its step length at most 34 times before it stops. The Gram-Schmidt step of line L2 has nn columns. The Newton solver of line L6 has at most a fixed number of steps (50). The loop of line L4 has NN passes, and each appends one state in line L9. □\square

Claim 2 (the proposal density). Under (A), the points returned by line L6 have the sub-probability density

q(x)=(2π)−n/2 ∣det⁡(QTJ(x))∣ exp⁡(−12∥QT(F(x)−yˉ)∥2),x∈Rn,q(x) = (2\pi)^{-n/2}\,\lvert\det(Q^TJ(x))\rvert\,\exp\big(-\tfrac12\lVert Q^T(F(x) - \bar y)\rVert^2\big), \qquad x \in \mathbb{R}^n,

and the remaining mass 1−∫q1 - \int q is the probability that line L6 returns no point.

Proof. Let ε∼N(0,IM)\varepsilon \sim N(0, I_M). Then z=QT(yˉ+ε)z = Q^T(\bar y + \varepsilon) is Gaussian with mean QTyˉQ^T\bar y and covariance QTQ=InQ^TQ = I_n, so it has density (2π)−n/2exp⁡(−12∥z−QTyˉ∥2)(2\pi)^{-n/2}\exp(-\frac12\lVert z - Q^T\bar y\rVert^2). By (A), line L6 returns x′=T−1(z)x' = T^{-1}(z) exactly when z∈T(Rn)z \in T(\mathbb{R}^n). TT is a C1C^1 bijection from Rn\mathbb{R}^n onto the open set T(Rn)T(\mathbb{R}^n) with nonsingular derivative, so by the change of variables formula x′x' has density (2π)−n/2exp⁡(−12∥T(x)−QTyˉ∥2)∣det⁡T′(x)∣(2\pi)^{-n/2}\exp(-\frac12\lVert T(x) - Q^T\bar y\rVert^2)\lvert\det T'(x)\rvert on Rn\mathbb{R}^n. Since T(x)−QTyˉ=QT(F(x)−yˉ)T(x) - Q^T\bar y = Q^T(F(x) - \bar y), this is qq. □\square

Claim 3 (the weight). The ratio π/q\pi/q is, up to a constant factor,

w(x)=∣det⁡(QTJ(x))∣−1exp⁡(−12∥F(x)−yˉ∥2+12∥QT(F(x)−yˉ)∥2),w(x) = \lvert\det(Q^TJ(x))\rvert^{-1}\exp\big(-\tfrac12\lVert F(x) - \bar y\rVert^2 + \tfrac12\lVert Q^T(F(x) - \bar y)\rVert^2\big),

and line L7 computes log⁡w(x′)\log w(x').

Proof. Divide π\pi by qq from Claim 2 and drop the constant (2π)n/2/Z(2\pi)^{n/2}/Z. The function log_weight computes the three terms of log⁡w\log w directly. □\square

Claim 4 (detailed balance). Under (A), one pass of lines L5 to L9 has the kernel

P(x,dx′)=q(x′) a(x,x′) dx′+r(x) δx(dx′),a(x,x′)=min⁡{1,w(x′)/w(x)},P(x, dx') = q(x')\,a(x, x')\,dx' + r(x)\,\delta_x(dx'), \qquad a(x, x') = \min\{1, w(x')/w(x)\},

where r(x)r(x) collects the rejections and the failed solves, and π(x)P(x,dx′)=π(x′)P(x′,dx)\pi(x)P(x, dx') = \pi(x')P(x', dx). So π\pi is invariant.

Proof. Line L8 accepts with probability min⁡{1,w(x′)/w(x)}\min\{1, w(x')/w(x)\}: as in Metropolis-Hastings, with UU uniform on (0,1](0, 1], the event log⁡U<log⁡w(x′)−log⁡w(x)\log U < \log w(x') - \log w(x) has this probability. If line L6 returns no point, the state stays. For the moving part, using π=cwq\pi = cwq for a constant c>0c > 0,

π(x)q(x′)a(x,x′)=c w(x)q(x)q(x′)min⁡{1,w(x′)/w(x)}=c q(x)q(x′)min⁡{w(x),w(x′)},\pi(x)q(x')a(x, x') = c\,w(x)q(x)q(x')\min\{1, w(x')/w(x)\} = c\,q(x)q(x')\min\{w(x), w(x')\},

which is symmetric in (x,x′)(x, x'). The staying part is concentrated on x=x′x = x' and is symmetric too. Integrate over xx to get invariance. □\square

This is the independence Metropolis-Hastings sampler with proposal qq. Under (A), q(x)>0q(x) > 0 for every xx, also when its total mass is below one, and ww is finite and positive. So every set of positive π\pi-measure is reached in one step with positive probability, the chain is π\pi-irreducible, and averages along the chain converge to posterior expectations for π\pi-almost every start (the standard law of large numbers for Markov chains).

Claim 5 (the linear case is exact without correction). Let F(x)=Hx−h0F(x) = Hx - h_0 be affine with HH of full column rank nn, and let the columns of QQ span the range of HH. Then (A) holds, ww is constant, every proposal is accepted, and the proposals are independent draws from π\pi, which is N((HTH)−1HT(yˉ+h0),(HTH)−1)N((H^TH)^{-1}H^T(\bar y + h_0), (H^TH)^{-1}).

Proof. Write H=QRH = QR with R=QTHR = Q^TH invertible. Then T(x)=Rx−QTh0T(x) = Rx - Q^Th_0 is an affine bijection, so (A) holds, and Newton's method solves it in one step. The determinant det⁡(QTJ)=det⁡R\det(Q^TJ) = \det R is constant. With d(x)=Hx−h0−yˉd(x) = Hx - h_0 - \bar y,

∥d(x)∥2−∥QTd(x)∥2=∥(I−QQT)d(x)∥2=∥(I−QQT)(h0+yˉ)∥2,\lVert d(x)\rVert^2 - \lVert Q^Td(x)\rVert^2 = \lVert(I - QQ^T)d(x)\rVert^2 = \lVert(I - QQ^T)(h_0 + \bar y)\rVert^2,

since (I−QQT)H=0(I - QQ^T)H = 0. So ww is constant and the ratio in line L8 is 11. The equation Rx=QT(yˉ+h0+ε)Rx = Q^T(\bar y + h_0 + \varepsilon) is equivalent to the normal equations HTHx=HT(yˉ+h0+ε)H^THx = H^T(\bar y + h_0 + \varepsilon), because HT=RTQTH^T = R^TQ^T and RTR^T is invertible. So xx is the least squares solution of the perturbed problem, a Gaussian vector with mean (HTH)−1HT(yˉ+h0)(H^TH)^{-1}H^T(\bar y + h_0) and covariance (HTH)−1HTH(HTH)−1=(HTH)−1(H^TH)^{-1}H^TH(H^TH)^{-1} = (H^TH)^{-1}, which are the mean and covariance of π∝exp⁡(−12∥Hx−h0−yˉ∥2)\pi \propto \exp(-\frac12\lVert Hx - h_0 - \bar y\rVert^2). □\square

The choice of QQ at the MAP point in line L1 is not needed for correctness: any QQ with orthonormal columns for which (A) holds gives an exact chain. It matters for efficiency, since it makes qq close to π\pi near the mode. Assumption (A) is a real restriction. If TT is not one-to-one or the solver misses solutions, the weight of Claim 3 is wrong and the chain is biased; the page lists this as a pitfall.

Complexity

Line L1 is one Gauss-Newton solve, and line L2 a QR factorization in Θ(Mn2)\Theta(Mn^2). Each Newton step of line L6 evaluates FF and JJ (cost TT), forms QTJQ^TJ in Θ(Mn2)\Theta(Mn^2), and solves an n×nn \times n system in Θ(n3)⊆O(Mn2)\Theta(n^3) \subseteq O(Mn^2). Line L7 needs one more QTJQ^TJ and a determinant. With kk Newton steps per sample, NN samples cost Θ(Nk(T+Mn2))\Theta(Nk(T + Mn^2)) after the MAP point. In the linear case k=1k = 1 and one factorization can be reused for all samples. Memory is Θ(Mn)\Theta(Mn) for QQ and JJ plus Θ(Nn)\Theta(Nn) for the chain. The NN optimizations are independent and run in parallel; only line L8 is sequential, and it is cheap.

Properties

  • Exact for linear Gaussian problems with no rejection; exact with the correction for nonlinear ones under the injectivity assumption.
  • The proposals do not depend on the current state, so they can be computed in parallel and in advance.
  • Uses optimization software: a Gauss-Newton or Newton solver, Jacobians, and a QR factorization.
  • Needs the least squares form of the posterior. A non-Gaussian prior must first be transformed into this form.
  • Works well when the posterior is close to Gaussian near the MAP point; the acceptance rate falls as the nonlinearity grows.

Variants and improvements

  • Importance sampling. Use the weights ww of line L7 directly as self-normalized importance weights instead of line L8. All samples are used, and the importance sampling effective sample size measures the quality.
  • Linear RTO for Gaussian sampling. Perturb the data and the prior mean and solve the regularized least squares problem. With conjugate gradients this samples high-dimensional Gaussian posteriors with only matrix-vector products.
  • l1 and other non-Gaussian priors. Wang, Bardsley, Solonen, Cui and Marzouk (2017) map an ℓ1\ell_1 type prior to a Gaussian reference by a change of variables and apply RTO in the new variables.
  • Subspace versions. For large nn, restrict the nonlinear solve to a low-dimensional subspace informed by the data and treat the rest as the prior, which reduces kk and the cost of line L6.
  • Randomized maximum likelihood. A related method from petroleum reservoir modeling perturbs the data and the prior sample and solves the full, unprojected problem. It is exact only in the linear case and has no simple density for a correction.

When to use it

Use RTO when the posterior has least squares form, a MAP solver with Jacobians is available, and the posterior is not far from Gaussian, so that qq is close to π\pi. It is attractive when many processors are available, because samples are independent optimizations. For linear Gaussian problems it is the method of choice for exact samples. If the posterior is strongly multimodal, the map QTFQ^TF fails to be one-to-one, or Jacobians are not available, use pCN or another MCMC method instead.

Pitfalls

  • Treating the proposals of line L6 as posterior samples for a nonlinear model. They are biased; skip lines L7 and L8 only for linear models.
  • A solve in line L6 that converges to a different root, or fails, when QTFQ^TF is not one-to-one. Then the density of line L7 is wrong and the chain is biased without warning. Check the residual of the solve and monitor failures.
  • Solving the unprojected problem min⁡∥F(x)−yˉ−ε∥2\min\lVert F(x) - \bar y - \varepsilon\rVert^2 in line L6. Its solutions do not have the density of line L7.
  • Forgetting the determinant in line L7, or computing it for JJ instead of QTJQ^TJ. In the linear case it is constant and the mistake is invisible; in the nonlinear case it biases the result.
  • Working with ww instead of log⁡w\log w in line L8. The exponentials overflow for realistic problems.
  • A rank-deficient Jacobian in line L2. Then QQ has fewer than nn columns and the method is not defined; the prior part of FF prevents this when it is present.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

imgla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
randomize_then_optimize.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomize-then-optimize/. The authors are listed in prov/27EKVH.jsonl.
"""Randomize-then-optimize (RTO) with a Metropolis-Hastings correction.

The posterior is written as pi(x) proportional to exp(-||F(x) - ybar||^2 / 2),
where F stacks the whitened forward map and the whitened prior:
F(x) = [Gamma^{-1/2} G(x); L (x - m0)], ybar = [Gamma^{-1/2} y; 0], with
L^T L = C^{-1} for a Gaussian prior N(m0, C). F maps R^n to R^M, M >= n.

RTO fixes Q, an M x n matrix with orthonormal columns that span the range of
the Jacobian J(xbar) at the MAP point xbar. A proposal is the solution x of
Q^T F(x) = Q^T (ybar + eps), eps ~ N(0, I_M). If x -> Q^T F(x) is one-to-one
and smooth, the proposal has density
    q(x) proportional to |det(Q^T J(x))| exp(-||Q^T (F(x) - ybar)||^2 / 2),
and the importance weight pi / q is
    w(x) = |det(Q^T J(x))|^{-1} exp(-||F(x) - ybar||^2 / 2 + ||Q^T (F(x) - ybar)||^2 / 2).
An independence Metropolis-Hastings step with ratio w(x') / w(x) makes the
chain exact. For a linear F the weight is constant and every proposal is an
exact posterior sample.
"""

import math

from imgla import matvec, solve, transpose


def det(a):
    """Determinant of a square matrix by Gaussian elimination with pivoting."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0.0:
            return 0.0
        if p != c:
            m[c], m[p] = m[p], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def thin_qr_q(j):
    """Q with orthonormal columns spanning the columns of the M x n matrix j
    (modified Gram-Schmidt, applied twice). Raises ValueError if the rank is
    below n."""
    mrows, n = len(j), len(j[0])
    cols = [[j[i][k] for i in range(mrows)] for k in range(n)]
    q = []
    for c in cols:
        v = list(c)
        for _ in range(2):
            for e in q:
                h = sum(a * b for a, b in zip(e, v))
                v = [a - h * b for a, b in zip(v, e)]
        nrm = math.sqrt(sum(a * a for a in v))
        if nrm <= 1e-13 * max(1.0, math.sqrt(sum(a * a for a in c))):
            raise ValueError("Jacobian does not have full column rank")
        q.append([a / nrm for a in v])
    return [[q[k][i] for k in range(n)] for i in range(mrows)]


def gauss_newton_map(f, jac, ybar, x0, iters=100, tol=1e-12):
    """Minimize ||F(x) - ybar||^2 / 2 by Gauss-Newton with step halving."""
    x = list(x0)
    r = [a - b for a, b in zip(f(x), ybar)]
    val = 0.5 * sum(t * t for t in r)
    for _ in range(iters):
        jx = jac(x)
        jt = transpose(jx)
        g = matvec(jt, r)
        if math.sqrt(sum(t * t for t in g)) <= tol:
            break
        jtj = [[sum(a * b for a, b in zip(ri, rk)) for rk in jt] for ri in jt]
        step = solve(jtj, g)
        t = 1.0
        while t > 1e-10:
            xn = [a - t * s for a, s in zip(x, step)]
            rn = [a - b for a, b in zip(f(xn), ybar)]
            vn = 0.5 * sum(e * e for e in rn)
            if vn <= val:
                break
            t *= 0.5
        else:
            break
        x, r, val = xn, rn, vn
    return x


def solve_projected(f, jac, q, target, x0, iters=50, tol=1e-11):
    """Solve Q^T F(x) = target by Newton's method from x0. Returns x, or None
    if Newton does not reach the tolerance."""
    qt = transpose(q)
    x = list(x0)
    for _ in range(iters):
        res = [a - b for a, b in zip(matvec(qt, f(x)), target)]
        if math.sqrt(sum(t * t for t in res)) <= tol * (1.0 + math.sqrt(sum(t * t for t in target))):
            return x
        jq = [matvec(qt, col) for col in transpose(jac(x))]  # columns of Q^T J
        try:
            step = solve(transpose(jq), res)
        except ValueError:
            return None
        x = [a - s for a, s in zip(x, step)]
    res = [a - b for a, b in zip(matvec(qt, f(x)), target)]
    if math.sqrt(sum(t * t for t in res)) <= tol * (1.0 + math.sqrt(sum(t * t for t in target))):
        return x
    return None


def log_weight(f, jac, q, ybar, x):
    """log w(x) = -log|det(Q^T J(x))| - ||F(x) - ybar||^2 / 2 + ||Q^T (F(x) - ybar)||^2 / 2."""
    qt = transpose(q)
    r = [a - b for a, b in zip(f(x), ybar)]
    qr = matvec(qt, r)
    qtj = [matvec(qt, col) for col in transpose(jac(x))]
    d = abs(det(qtj))
    if d == 0.0:
        return -math.inf
    return -math.log(d) - 0.5 * sum(t * t for t in r) + 0.5 * sum(t * t for t in qr)


def rto_mh(f, jac, ybar, x0, steps, rng):
    """RTO-MH. Returns (chain, acceptance_rate, xbar)."""
    xbar = gauss_newton_map(f, jac, ybar, x0)  # @line L1
    q = thin_qr_q(jac(xbar))  # @line L2
    qt = transpose(q)
    x, lw = xbar, log_weight(f, jac, q, ybar, xbar)  # @line L3
    chain = []
    accepted = 0
    for _ in range(steps):  # @line L4
        eps = [rng.gauss(0.0, 1.0) for _ in ybar]  # @line L5
        target = matvec(qt, [a + e for a, e in zip(ybar, eps)])
        xp = solve_projected(f, jac, q, target, xbar)  # @line L6
        if xp is not None:
            lwp = log_weight(f, jac, q, ybar, xp)  # @line L7
            if math.log(1.0 - rng.random()) < lwp - lw:  # @line L8
                x, lw = xp, lwp
                accepted += 1
        chain.append(x)  # @line L9
    return chain, accepted / steps, xbar  # @line L10


def linear_problem(a, y, sigma, prior_sd, m0=None):
    """F and its Jacobian for G(x) = A x, noise N(0, sigma^2 I) and prior
    N(m0, prior_sd^2 I)."""
    n = len(a[0])
    if m0 is None:
        m0 = [0.0] * n
    h = [[v / sigma for v in row] for row in a] + [[(1.0 / prior_sd if i == k else 0.0) for k in range(n)] for i in range(n)]
    ybar = [v / sigma for v in y] + [0.0] * n

    def f(x):
        return [sum(v * xk for v, xk in zip(row, x)) / sigma for row in a] + [(xi - mi) / prior_sd for xi, mi in zip(x, m0)]

    def jac(x):
        return h

    return f, jac, ybar
test_randomize_then_optimize.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomize-then-optimize/. The authors are listed in prov/27EKVH.jsonl.

import math
import random

from imgla import eye, matmul, matvec, solve, transpose
from randomize_then_optimize import (
    det,
    gauss_newton_map,
    linear_problem,
    log_weight,
    rto_mh,
    solve_projected,
    thin_qr_q,
)


def cubic_problem(c=1.0, sigma=0.5, y=1.5):
    """G(x) = x + c x^3, noise N(0, sigma^2), prior N(0, 1)."""

    def f(x):
        return [(x[0] + c * x[0] ** 3) / sigma, x[0]]

    def jac(x):
        return [[(1.0 + 3.0 * c * x[0] ** 2) / sigma], [1.0]]

    return f, jac, [y / sigma, 0.0]


def quadrature_moments(c=1.0, sigma=0.5, y=1.5):
    xs = [-4.0 + 8.0 * i / 40000 for i in range(40001)]
    p = [math.exp(-((y - x - c * x ** 3) ** 2) / (2.0 * sigma * sigma) - 0.5 * x * x) for x in xs]
    z = sum(p)
    m = sum(x * w for x, w in zip(xs, p)) / z
    v = sum((x - m) ** 2 * w for x, w in zip(xs, p)) / z
    return m, v


def moments(chain):
    k = len(chain)
    n = len(chain[0])
    m = [sum(c[i] for c in chain) / k for i in range(n)]
    cov = [[sum((c[i] - m[i]) * (c[j] - m[j]) for c in chain) / (k - 1) for j in range(n)] for i in range(n)]
    return m, cov


def test_determinant_and_orthonormal_basis():
    assert abs(det([[2.0, 1.0], [1.0, 3.0]]) - 5.0) < 1e-12
    assert abs(det([[0.0, 1.0], [1.0, 0.0]]) + 1.0) < 1e-12
    assert det([[1.0, 2.0], [2.0, 4.0]]) == 0.0
    j = [[1.0, 2.0], [0.5, -1.0], [3.0, 0.0], [0.0, 1.0]]
    q = thin_qr_q(j)
    qtq = matmul(transpose(q), q)
    for i in range(2):
        for k in range(2):
            assert abs(qtq[i][k] - (1.0 if i == k else 0.0)) < 1e-12
    # Every column of J is reproduced by its projection Q Q^T J.
    for col in transpose(j):
        proj = matvec(q, matvec(transpose(q), col))
        assert max(abs(a - b) for a, b in zip(proj, col)) < 1e-12
    try:
        thin_qr_q([[1.0, 2.0], [2.0, 4.0]])
    except ValueError:
        pass
    else:
        raise AssertionError("rank-deficient Jacobian was accepted")


def test_map_point_is_the_tikhonov_solution_for_a_linear_problem():
    a = [[1.0, 0.5], [0.2, 1.0], [0.3, 0.3]]
    y = [1.0, 0.5, 0.2]
    f, jac, ybar = linear_problem(a, y, 0.3, 1.0)
    xbar = gauss_newton_map(f, jac, ybar, [0.0, 0.0])
    # (A^T A + (sigma / prior_sd)^2 I) x = A^T y
    ata = matmul(transpose(a), a)
    lhs = [[ata[i][k] + (0.09 if i == k else 0.0) for k in range(2)] for i in range(2)]
    x = solve(lhs, matvec(transpose(a), y))
    assert max(abs(p - q) for p, q in zip(xbar, x)) < 1e-10


def test_linear_problem_has_constant_weight_and_accepts_everything():
    f, jac, ybar = linear_problem([[0.1]], [0.12], 0.05, 1.0)
    q = thin_qr_q(jac(None))
    w0 = log_weight(f, jac, q, ybar, [0.0])
    for x in (-3.0, 0.5, 0.96, 4.0):
        assert abs(log_weight(f, jac, q, ybar, [x]) - w0) < 1e-9
    chain, acc, xbar = rto_mh(f, jac, ybar, [0.0], 4000, random.Random(1))
    assert abs(xbar[0] - 0.96) < 1e-10
    assert acc > 0.999
    m, cov = moments(chain)
    assert abs(m[0] - 0.96) < 0.03
    assert abs(cov[0][0] - 0.2) < 0.02


def test_linear_two_dimensional_posterior_moments():
    a = [[1.0, 0.5], [0.2, 1.0], [0.3, 0.3]]
    y = [1.0, 0.5, 0.2]
    f, jac, ybar = linear_problem(a, y, 0.3, 1.0)
    h = jac(None)
    c_post = solve(matmul(transpose(h), h), eye(2))
    m_post = matvec(c_post, matvec(transpose(h), ybar))
    chain, _, _ = rto_mh(f, jac, ybar, [0.0, 0.0], 3000, random.Random(4))
    m, cov = moments(chain)
    for i in range(2):
        assert abs(m[i] - m_post[i]) < 0.03
        for k in range(2):
            assert abs(cov[i][k] - c_post[i][k]) < 0.02


def test_proposals_solve_the_projected_equation():
    f, jac, ybar = cubic_problem()
    xbar = gauss_newton_map(f, jac, ybar, [0.0])
    q = thin_qr_q(jac(xbar))
    qt = transpose(q)
    rng = random.Random(9)
    for _ in range(20):
        eps = [rng.gauss(0.0, 1.0) for _ in ybar]
        target = matvec(qt, [p + e for p, e in zip(ybar, eps)])
        x = solve_projected(f, jac, q, target, xbar)
        assert x is not None
        res = [p - t for p, t in zip(matvec(qt, f(x)), target)]
        assert max(abs(r) for r in res) < 1e-9


def test_nonlinear_posterior_matches_quadrature_and_correction_matters():
    f, jac, ybar = cubic_problem()
    m_true, v_true = quadrature_moments()
    chain, acc, xbar = rto_mh(f, jac, ybar, [0.0], 5000, random.Random(3))
    m, cov = moments(chain)
    assert 0.6 < acc < 0.99
    assert abs(m[0] - m_true) < 0.02
    assert abs(cov[0][0] - v_true) < 0.008
    # Without the Metropolis-Hastings step the proposals are biased.
    q = thin_qr_q(jac(xbar))
    qt = transpose(q)
    rng = random.Random(3)
    raw = []
    for _ in range(3000):
        eps = [rng.gauss(0.0, 1.0) for _ in ybar]
        raw.append(solve_projected(f, jac, q, matvec(qt, [p + e for p, e in zip(ybar, eps)]), xbar)[0])
    assert sum(raw) / len(raw) - m_true > 0.03

History

The idea of sampling a linear Gaussian posterior by perturbing the data and the prior and solving the least squares problem is older, and appears in statistics, in geostatistics and in signal processing under several names. Randomized maximum likelihood applied the same idea, without a correction, to nonlinear reservoir models in the 1990s. Bardsley, Solonen, Haario and Laine (2014) introduced the projection with QQ, derived the proposal density and added the Metropolis-Hastings correction, which made the method exact for nonlinear problems. Wang, Bardsley, Solonen, Cui and Marzouk (2017) extended RTO to ℓ1\ell_1 type priors, and later work studied scalable and subspace versions.

References

  1. Johnathan M. Bardsley, Antti Solonen, Heikki Haario and Marko Laine, Randomize-then-optimize, a method for sampling from posterior distributions in nonlinear inverse problems, SIAM Journal on Scientific Computing 36(4), 2014, pages A1895 to A1910
  2. Zheng Wang, Johnathan M. Bardsley, Antti Solonen, Tiangang Cui and Youssef M. Marzouk, Bayesian inverse problems with l1 priors, a randomize-then-optimize approach, SIAM Journal on Scientific Computing 39(5), 2017, pages S140 to S166
  3. Andrew M. Stuart, Inverse problems, a Bayesian perspective, Acta Numerica 19, 2010, pages 451 to 559

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example