Algorithmcore
Morozov discrepancy principle
Also called discrepancy principle.
Choose the regularization parameter so that the residual norm equals tau times the known noise level, for a fixed tau a little above 1.
- Time
- Θ(m n + K n) worst · averageΘ(m n) best
- Space
- Θ(n) extra
- Where
- K = the number of root-finding steps once the thin SVD of A is known; m = the number of measurements; n = the number of unknowns (n <= m)
- Model
- Real RAM
- Properties
- a posterioriconvergent regularizationdeterministiciterativeneeds noise level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Vladimir A. Morozov, 1966
The discrepancy principle chooses the parameter of a regularization method from the noise level. If the data differ from the exact data by at most in norm, there is no reason to fit them more closely than . So the rule takes the parameter at which the residual equals , for a fixed safety factor , often between and . V. A. Morozov stated and analyzed it in 1966. It is an a posteriori rule: it uses both and . For Tikhonov regularization it is a proved rule. The chosen solution converges to the true solution as , and under the source condition the error is . It needs a reliable . With a wrong it over-smooths or under-smooths in proportion, and without any the Bakushinskii veto says that no rule can be convergent in the worst case. For iterative methods such as Landweber the same principle is a stopping rule: stop at the first with residual at most .
In plain words
Your measurements contain noise, and you know roughly how big the noise is. A smoothing method has a knob. Turn it down and the result follows the data more closely, noise included. Turn it up and the result becomes smoother and follows the data less. The rule says: do not follow the data more closely than the noise allows. Turn the knob until the gap between the data and what the result predicts is as large as the noise, and stop there. Anything closer means that you are fitting the noise. Anything looser throws away real information. The rule is simple and has a proof behind it, but it only works if your estimate of the noise size is good.
The problem
The model is with and a known . Here is an matrix and is the minimum norm solution of for the exact data . The Tikhonov solution for is
The page Tikhonov regularization writes for this . The task is to find with
With the thin SVD and , the squared residual is . Here is the norm of the part of outside the range of . The function is continuous and increasing, from at to at . So a root exists and is unique when .
The algorithm
The search works in , where the residual changes on a scale that does not depend on the size of . It is a safeguarded Newton method: a Newton step from the better end of a bracket, replaced by a bisection step on every second pass or when it leaves the bracket.
DISCREPANCY-TIKHONOV(U, s, V, y, delta, tau, eps) ▷ thin SVD of A, s descending, r positive values- 1
b_i ← <u_i, y> for i ≤ r; p² ← ‖y‖² - Σ b_i² ▷ p: norm of y outside the range - 2
if p ≥ tau·delta then return FAIL ▷ no alpha reaches the target - 3
if ‖y‖ ≤ tau·delta then return (∞, 0) ▷ x = 0 already fits the data - 4
F(t) := Σ_i (e^t / (s_i² + e^t))² b_i² + p² - tau² delta² ▷ increasing in t - 5
hi ← log(s_1² q / (1 - q)) with q = (1 + tau·delta/‖y‖) / 2 - 6
lo ← log(s_r² · sqrt((tau² delta² - p²) / 2) / ‖y‖) - 7
for k = 0, 1, 2, ... - 8
c ← the end of [lo, hi] with the smaller |F| - 9
if hi - lo ≤ eps or |F(c)| ≤ eps · F'(c) then exit the loop - 10
t ← c - F(c) / F'(c); if k is odd or t ∉ (lo, hi) then t ← (lo + hi) / 2 - 11
if F(t) > 0 then hi ← t else lo ← t - 12
alpha ← e^c - 13
return alpha, x = Σ_i s_i b_i / (s_i² + alpha) · v_i
Line L1 projects the data on the left singular vectors. Lines L2 and L3 handle the two cases where the equation has no root: the target is below the smallest reachable residual, or above the largest. Line L4 defines the function whose root is wanted. Its derivative is with , so each evaluation costs . Lines L5 and L6 give a bracket from two simple bounds, proved in proofs/correctness.md. At the largest filter factor is so small that the residual exceeds . At even the smallest singular value is so much larger than that the residual is below . Lines L8 to L11 shrink the bracket. Line L10 takes the Newton point, but uses the midpoint on every second pass, and when the Newton point is not strictly inside the bracket. Line L13 forms the Tikhonov solution from the SVD.
Example
Take , so , the true solution , and the noise with . The data are . With the target residual is . Line L1 gives and , and . Line L5 gives and , with residual . Line L6 gives , with residual . With the loop runs as follows:
| pass | step | residual | lo | hi | ||
|---|---|---|---|---|---|---|
| 1 | bisection (Newton point outside) | -6.1303 | 0.002176 | 0.04894 | -6.1303 | 0.1190 |
| 2 | bisection | -3.0057 | 0.04951 | 0.12625 | -6.1303 | -3.0057 |
| 3 | Newton | -4.9923 | 0.006790 | 0.06911 | -6.1303 | -4.9923 |
| 4 | bisection | -5.5613 | 0.003844 | 0.05693 | -5.5613 | -4.9923 |
| 5 | Newton | -5.3827 | 0.004596 | 0.06030 | -5.5613 | -5.3827 |
| 6 | bisection | -5.4720 | 0.004203 | 0.05856 | -5.4720 | -5.3827 |
| 7 | Newton | -5.3975 | 0.004528 | 0.06000 | -5.4720 | -5.3975 |
| 8 | bisection | -5.4348 | 0.004362 | 0.05927 | -5.4348 | -5.3975 |
| 9 | Newton | -5.3977 | 0.004527 | 0.06000 | -5.4348 | -5.3977 |
| 10 | bisection | -5.4162 | 0.004444 | 0.05963 | -5.4162 | -5.3977 |
| 11 | Newton | -5.3977 | 0.004527 | 0.06000 | -5.4162 | -5.3977 |
After pass 11 the test of line L9 holds, and the rule returns and , with error . On a fine grid of the smallest error is , at . With the rule gives and error . The third component is the hard one: is far below the noise in that component, and every reasonable rule damps it.
Correctness
The proof is in proofs/correctness.md. It has two parts.
The first part is about the algorithm. The residual is continuous and strictly increasing in , so the equation has exactly one root when . Lines L5 and L6 give , and line L11 keeps the signs, so the root stays in the bracket. On exit, , because . Under the noise model, , so line L2 never fails when .
The second part is the theorem that makes the rule a regularization method. Let and let solve the discrepancy equation. Then and . From these two bounds and a weak compactness argument, as . If , then
This holds in any Hilbert space, not only for matrices. EHN show more generally that Tikhonov with the discrepancy principle is order optimal under for , and that the rate is the best this combination can give, however smooth is (EHN chapters 4 and 5).
Proof: The discrepancy equation has one root, the safeguarded Newton search finds it, and the chosen Tikhonov solution convergesfull
Setting. is a real matrix with thin SVD , where are the positive singular values. The data are , the noise level is and is fixed. For the Tikhonov solution is . Line L1 computes for and , which is the squared norm of the part of outside the range of , because is an orthonormal basis of the range.
Claim 1 (the residual as a function of alpha). For ,
The function is continuous and nondecreasing on , with as and as . If some , it is strictly increasing.
Proof. In the basis the normal equations are diagonal: the coefficient of satisfies for , and on the null space of . This gives . Then , where is orthogonal to every and has norm . Since , Pythagoras gives . Each factor is continuous and strictly increasing, with , from at to at . The limits follow from .
With let (line L4). By the chain rule, with ,
Claim 2 (the special cases of lines L2 and L3). If , no has unless and all , and then no is singled out. If , the vector already has residual . If with and , line L2 never fails.
Proof. By Claim 1, , with equality only if all . The case is clear. Under the noise model lies in the range of , so and .
From here on assume . Then , so is strictly increasing and, by Claim 1 and the intermediate value theorem, has exactly one root . The value is the unique solution of .
Claim 3 (the starting bracket of lines L5 and L6). .
Proof. Upper end. Let . Then . Line L5 sets , so . For every , gives , and gives . So .
Lower end. Line L6 sets . For every , , so , because .
Claim 4 (loop invariant). At the start of each pass of the loop L7 to L11, and .
Proof. It holds at the start by Claim 3. Line L10 always gives a point with : the Newton point is kept only if it is inside the open bracket, and the midpoint is inside. Line L11 replaces by if and by otherwise, so the signs stay. Since is increasing, puts in .
Claim 5 (termination). Let be the width of the starting bracket. The loop makes at most passes.
Proof. Every pass replaces one end by a point inside the bracket, so the width never grows. On even passes line L10 takes the midpoint, so the width at least halves. After passes the width is at most , and the test of line L9 stops the loop once the width is at most , which happens for .
Claim 6 (accuracy). On exit, is an end of the bracket and for . The returned is .
Proof. Write . Then , the maximum of on , at . So for every . Line L9 exits in one of two cases. If , then by Claim 4, and the mean value theorem gives . Otherwise . In both cases is the stated quantity. Line L13 evaluates the formula of Claim 1.
So the algorithm is correct: it returns FAIL exactly when the target is out of reach, the zero solution when the data are within of zero, and otherwise the Tikhonov solution for an that solves the discrepancy equation to the stated accuracy, after a bounded number of steps.
Theorem (the discrepancy principle gives a convergent regularization method). Let be a bounded linear operator between Hilbert spaces, with the minimum norm solution, and . Let satisfy , where is the Tikhonov solution for the data . Then:
- and ;
- as ;
- if , then .
Proof. 1. The Tikhonov solution minimizes , so . The left side is . Since , . The second bound is the triangle inequality: .
- By part 1, for every ,
Take and write for the chosen solutions. They are bounded by , so every subsequence has a further subsequence that converges weakly to some . Since is bounded, , and by part 1, so . The norm is weakly lower semicontinuous, so . The minimum norm solution is unique, so . Then the right side of tends to along that subsequence. Every subsequence has a further subsequence along which , so the whole sequence converges.
- In , by part 1.
Complexity
In the real-RAM model with the thin SVD given, line L1 costs , each pass of the loop costs for one evaluation of and , and line L13 costs , which is at most . The total is , with extra space. The bracket has width , which grows like plus the logarithm of the signal-to-noise ratio, and the loop makes at most passes, because the width halves at least once in every two passes. In the example, and give the bound , and the loop needed . The SVD itself costs by a standard dense method and dominates.
Without an SVD, each evaluation of the residual needs a new Tikhonov solve, for example by CGLS with the shift . Then a root finder that needs few evaluations, such as the secant method in , matters more than the cost of each step.
Properties
- A posteriori: it needs and , not .
- Convergent for Tikhonov with when the root exists; the existence argument needs unless has no part outside the range.
- Order optimal for Tikhonov only up to . The a priori choice reaches at , the discrepancy principle does not.
- Scale free: replacing , and by , and multiplies the chosen by and gives the same .
- The chosen grows with , because the residual is increasing in . So a loose upper bound gives a too large and an over-smoothed solution.
Variants and improvements
- Discrete rule for iterative methods. For Landweber, CGLS or truncated SVD, stop at the first index with . For Landweber this gives order optimal rates for all when is large enough (EHN chapter 6 states the condition on ). For CG it is the standard stopping rule (EHN chapter 7).
- Statistical noise. If , then , and the rule is often used with . A variant targets , which accounts for the degrees of freedom used by the fit.
- Modified discrepancy principles. Engl (1987) and Gfrerer (1987) compare a smoothed residual with the noise level, for example , and so make Tikhonov order optimal up to . EHN treat these rules next to the plain principle.
- Other root finders. Newton in itself, the secant method in , or Brent's method. As a function of the squared residual is a sum of terms plus a constant, so it is convex and decreasing, and Newton in converges monotonically from any below the root.
- Nonlinear problems. The same equation is used for nonlinear Tikhonov and as the stopping rule of the iteratively regularized Gauss-Newton method.
When to use it
Use it when the noise level is known or can be estimated well: from the physics of the detector, from repeated measurements, or from the high frequency part of the data. It is the default a posteriori rule in the theory of regularization, and the natural stopping rule for iterative methods. When only the noise variance of white noise is known, UPRE uses the same information in a statistically sharper way. When is unknown, use a heuristic rule such as GCV, the L-curve or the quasi-optimality criterion, and accept that it can fail. The balancing principle also uses and adapts to the smoothness of without the saturation at .
Pitfalls
- A wrong is the main failure. If is too small, line L2 can fail, or the root moves toward zero and the noise blows up. If it is too large, line L3 returns or the solution is over-smoothed.
- With and exactly, line L2 fails although the noise model holds. Use .
- Searching in instead of (lines L5 to L11) makes the bracket span many orders of magnitude, and plain bisection in wastes most steps near the large end.
- An unsafeguarded Newton step in line L10 can jump far outside the bracket when started far from the root, as pass 1 of the example shows. Keep the bracket.
- The test in line L9 compares squared residuals. If is huge compared with , scale the data first, or the absolute tolerance hides a large relative error in the residual.
- In the discrete rule for iterative methods, comparing the residual with instead of with can make the iteration run far too long when the residual stalls just above .
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.
# 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
morozov_discrepancy_principle.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/morozov-discrepancy-principle/. The authors are listed in prov/6BGG92.jsonl.
"""The discrepancy principle of Morozov for Tikhonov regularization.
Tikhonov: x_alpha minimizes ||A x - y||^2 + alpha ||x||^2. With the thin SVD
A = U diag(s) V^T, x_alpha = sum_i s_i b_i / (s_i^2 + alpha) v_i with
b_i = <u_i, y>. The discrepancy principle picks the alpha with
||A x_alpha - y|| = tau delta, where delta bounds the noise norm.
The root is found by a safeguarded Newton method in t = log(alpha): every
second step is a bisection step, so the bracket width halves at least once in
every two steps.
"""
import math
from imgla import norm2, svd
class DiscrepancyFailure(ValueError):
"""No alpha in (0, infinity) reaches the target residual tau * delta."""
def coefficients(u, s, y):
"""b_i = <u_i, y> for the s_i > 0, and p2 = ||y||^2 - sum b_i^2 (clamped at 0)."""
m = len(y)
b = [sum(u[i][k] * y[i] for i in range(m)) for k in range(len(s)) if s[k] > 0.0]
p2 = max(norm2(y) ** 2 - sum(t * t for t in b), 0.0)
return b, p2
def residual_norm(s, b, p2, alpha):
"""||A x_alpha - y|| from the SVD data, for alpha > 0."""
tot = p2
for si, bi in zip(s, b):
f = alpha / (si * si + alpha)
tot += f * f * bi * bi
return math.sqrt(tot)
def tikhonov_svd(s, v, b, alpha):
"""x_alpha = sum_i s_i b_i / (s_i^2 + alpha) v_i (only the s_i > 0 are used)."""
n = len(v)
x = [0.0] * n
for k, (si, bi) in enumerate(zip(s, b)):
c = si * bi / (si * si + alpha)
for j in range(n):
x[j] += c * v[j][k]
return x
def _f_and_slope(s, b, p2, target2, t):
"""F(t) = ||A x_alpha - y||^2 - target^2 and dF/dt, with alpha = e^t."""
alpha = math.exp(t)
f = p2 - target2
d = 0.0
for si, bi in zip(s, b):
q = si * si + alpha
f += (alpha / q) ** 2 * bi * bi
d += 2.0 * alpha * alpha * si * si * bi * bi / (q * q * q)
return f, d
def discrepancy_tikhonov(u, s, v, y, delta, tau=1.1, eps=1e-10, max_steps=1000):
"""Return (alpha, x, steps) with ||A x - y|| = tau * delta, x = x_alpha.
u, s, v is the thin SVD of A (s descending). Raises DiscrepancyFailure if
the part of y outside the range of A already has norm >= tau * delta. If
||y|| <= tau * delta, returns (math.inf, 0, 0): x = 0 fits the data.
"""
s = [si for si in s if si > 0.0]
b, p2 = coefficients(u, s, y) # @line L1
target = tau * delta
if p2 >= target * target: # @line L2
raise DiscrepancyFailure("the residual cannot go below tau * delta")
ynorm = norm2(y)
if ynorm <= target: # @line L3
return math.inf, [0.0] * len(v), 0
target2 = target * target
def big_f(t): # @line L4
return _f_and_slope(s, b, p2, target2, t)
q = (1.0 + target / ynorm) / 2.0
hi = math.log(s[0] * s[0] * q / (1.0 - q)) # @line L5
lo = math.log(s[-1] * s[-1] * math.sqrt((target2 - p2) / 2.0) / ynorm) # @line L6
f_lo, d_lo = big_f(lo)
f_hi, d_hi = big_f(hi)
steps = 0
while steps < max_steps: # @line L7
if abs(f_lo) <= abs(f_hi): # @line L8
c, fc, dc = lo, f_lo, d_lo
else:
c, fc, dc = hi, f_hi, d_hi
if hi - lo <= eps or abs(fc) <= eps * dc: # @line L9
break
steps += 1
t = c - fc / dc if dc > 0.0 else lo # @line L10
if steps % 2 == 0 or not lo < t < hi:
t = (lo + hi) / 2.0
ft, dt = big_f(t)
if ft > 0.0: # @line L11
hi, f_hi, d_hi = t, ft, dt
else:
lo, f_lo, d_lo = t, ft, dt
alpha = math.exp(c) # @line L12
return alpha, tikhonov_svd(s, v, b, alpha), steps # @line L13
def discrepancy_tikhonov_matrix(a, y, delta, tau=1.1, eps=1e-10):
"""The same for a dense matrix A: compute its SVD, then call discrepancy_tikhonov."""
u, s, v = svd(a)
return discrepancy_tikhonov(u, s, v, y, delta, tau, eps)
def discrepancy_index(residuals, delta, tau=1.1):
"""The discrete rule: the first k with residuals[k] <= tau * delta, or None."""
for k, r in enumerate(residuals):
if r <= tau * delta:
return k
return None
test_morozov_discrepancy_principle.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/morozov-discrepancy-principle/. The authors are listed in prov/6BGG92.jsonl.
import math
import random
import pytest
from imgla import matvec, norm2, rmatvec, solve, svd, transpose, matmul
from morozov_discrepancy_principle import (
DiscrepancyFailure,
_f_and_slope,
coefficients,
discrepancy_index,
discrepancy_tikhonov,
discrepancy_tikhonov_matrix,
residual_norm,
tikhonov_svd,
)
def integration_matrix(n):
"""(A x)_i = h * sum_{j <= i} x_j with h = 1/n: a mildly ill-posed test operator."""
h = 1.0 / n
return [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]
def noise(rng, m, delta):
e = [rng.gauss(0.0, 1.0) for _ in range(m)]
c = delta / norm2(e)
return [c * t for t in e]
def tikhonov_solve(a, y, alpha):
"""x_alpha from the normal equations (A^T A + alpha I) x = A^T y."""
ata = matmul(transpose(a), a)
n = len(ata)
for i in range(n):
ata[i][i] += alpha
return solve(ata, rmatvec(a, y))
def residual(a, x, y):
return norm2([p - q for p, q in zip(matvec(a, x), y)])
def sine_problem(n, rel_noise, seed):
rng = random.Random(seed)
a = integration_matrix(n)
xt = [math.sin(math.pi * (j + 0.5) / n) for j in range(n)]
y0 = matvec(a, xt)
delta = rel_noise * norm2(y0)
y = [p + q for p, q in zip(y0, noise(rng, n, delta))]
return a, xt, y, delta
def test_page_example():
u = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
s = [1.0, 0.1, 0.01]
y = [1.0, 0.13, 0.045]
alpha, x, steps = discrepancy_tikhonov(u, s, u, y, 0.05, tau=1.2)
assert abs(alpha - 0.0045272) < 1e-6
assert steps == 11
assert max(abs(p - q) for p, q in zip(x, [0.99549, 0.89487, 0.09725])) < 1e-4
b, p2 = coefficients(u, s, y)
assert abs(residual_norm(s, b, p2, alpha) - 0.06) < 1e-12
assert abs(math.dist(x, [1.0, 1.0, 0.5]) - 0.41627) < 1e-4
def test_defining_equality_and_normal_equations():
for seed in range(3):
a, xt, y, delta = sine_problem(12, 0.02, seed)
for tau in (1.0, 1.1, 1.5):
alpha, x, _ = discrepancy_tikhonov_matrix(a, y, delta, tau)
assert abs(residual(a, x, y) - tau * delta) <= 1e-8 * tau * delta
xs = tikhonov_solve(a, y, alpha)
assert norm2([p - q for p, q in zip(x, xs)]) <= 1e-8 * norm2(xs)
def test_residual_is_increasing_in_alpha():
a, _, y, _ = sine_problem(10, 0.05, 7)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
grid = [10.0 ** (k / 4.0) for k in range(-40, 9)]
r = [residual_norm(s, b, p2, al) for al in grid]
assert all(r[i] < r[i + 1] for i in range(len(r) - 1))
assert r[-1] < norm2(y)
def test_slope_matches_finite_difference():
a, _, y, delta = sine_problem(8, 0.05, 3)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
for t in (-9.0, -5.0, -2.0, 0.5):
h = 1e-5
fp, _ = _f_and_slope(s, b, p2, delta * delta, t + h)
fm, _ = _f_and_slope(s, b, p2, delta * delta, t - h)
_, d = _f_and_slope(s, b, p2, delta * delta, t)
assert abs((fp - fm) / (2 * h) - d) <= 1e-6 * abs(d)
def test_failure_when_data_outside_range_is_large():
a = [[1.0, 0.0], [0.0, 0.5], [0.0, 0.0], [0.0, 0.0]]
y = [1.0, 1.0, 0.3, 0.4] # the part outside the range has norm 0.5
with pytest.raises(DiscrepancyFailure):
discrepancy_tikhonov_matrix(a, y, 0.4, tau=1.2)
alpha, x, _ = discrepancy_tikhonov_matrix(a, y, 0.5, tau=1.2)
assert abs(residual(a, x, y) - 0.6) < 1e-9
def test_small_data_gives_zero():
a = integration_matrix(5)
y = [0.01, -0.02, 0.0, 0.01, 0.0]
alpha, x, steps = discrepancy_tikhonov_matrix(a, y, 0.05, tau=1.1)
assert alpha == math.inf and steps == 0
assert all(t == 0.0 for t in x)
def test_error_within_factor_of_best_on_grid():
for seed in range(3):
a, xt, y, delta = sine_problem(16, 0.01, 10 + seed)
u, s, v = svd(a)
b, _ = coefficients(u, s, y)
alpha, x, _ = discrepancy_tikhonov(u, s, v, y, delta, tau=1.1)
err = math.dist(x, xt)
best = min(math.dist(tikhonov_svd(s, v, b, 10.0 ** (k / 8.0)), xt) for k in range(-80, 9))
assert err <= 3.0 * best
def test_rate_under_source_condition():
n, tau = 12, 1.1
a = integration_matrix(n)
w = [math.cos(math.pi * (j + 0.5) / n) for j in range(n)]
xt = rmatvec(a, w) # x_dagger = A^T w
y0 = matvec(a, xt)
u, s, v = svd(a)
rng = random.Random(5)
deltas, errs = [], []
for k in range(1, 5):
delta = 10.0 ** (-k) * norm2(y0)
y = [p + q for p, q in zip(y0, noise(rng, n, delta))]
_, x, _ = discrepancy_tikhonov(u, s, v, y, delta, tau)
err = math.dist(x, xt)
assert err <= math.sqrt(2.0 * (1.0 + tau) * norm2(w) * delta) * (1 + 1e-9)
deltas.append(math.log(delta))
errs.append(math.log(err))
slope = (errs[-1] - errs[0]) / (deltas[-1] - deltas[0])
assert slope >= 0.5 - 0.15
def plain_bisection(a, y, target):
lo, hi = -40.0, 20.0
for _ in range(80):
mid = (lo + hi) / 2
if residual(a, tikhonov_solve(a, y, math.exp(mid)), y) > target:
hi = mid
else:
lo = mid
return math.exp((lo + hi) / 2)
def test_random_matrices_against_plain_bisection():
rng = random.Random(2024)
for _ in range(6):
a = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(6)]
y = [rng.uniform(-1, 1) for _ in range(6)]
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
target = math.sqrt(p2) + 0.5 * (norm2(y) - math.sqrt(p2))
alpha, x, _ = discrepancy_tikhonov(u, s, v, y, target / 1.1, tau=1.1)
ref = plain_bisection(a, y, target)
assert abs(math.log(alpha / ref)) < 1e-6
assert abs(residual(a, x, y) - target) < 1e-9
def test_bracket_and_iteration_bound():
rng = random.Random(99)
eps = 1e-10
for trial in range(10):
a, _, y, delta = sine_problem(8, 10.0 ** (-1 - trial % 4), 200 + trial)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
tau = 1.0 + rng.random()
target = tau * delta
yn = norm2(y)
q = (1.0 + target / yn) / 2.0
hi = math.log(s[0] ** 2 * q / (1.0 - q))
lo = math.log(s[-1] ** 2 * math.sqrt((target * target - p2) / 2.0) / yn)
assert residual_norm(s, b, p2, math.exp(lo)) < target < residual_norm(s, b, p2, math.exp(hi))
_, _, steps = discrepancy_tikhonov(u, s, v, y, delta, tau, eps)
assert steps <= 2 * math.ceil(math.log2((hi - lo) / eps))
def test_discrete_rule():
assert discrepancy_index([5.0, 3.0, 1.2, 1.0, 0.9], 1.0, tau=1.1) == 3
assert discrepancy_index([5.0, 3.0], 1.0) is None
a, xt, y, delta = sine_problem(10, 0.02, 4)
u, s, v = svd(a)
b, p2 = coefficients(u, s, y)
# residual norms of truncated SVD with k = 0, 1, ..., n terms
res = [math.sqrt(p2 + sum(t * t for t in b[k:])) for k in range(len(b) + 1)]
k = discrepancy_index(res, delta, 1.1)
assert k is not None and res[k] <= 1.1 * delta and (k == 0 or res[k - 1] > 1.1 * delta)
History
D. L. Phillips (1962) chose the smoothing parameter of his method by matching the residual to the expected error, without a proof. V. A. Morozov (1966) made the rule precise and proved that it gives a convergent method for Tikhonov regularization. Later work found the rates, the saturation at and the modified rules of Engl (1987) and Gfrerer (1987), and Engl, Hanke and Neubauer (1996) put the discrepancy principle, its discrete form for iterative methods and its variants into one framework.
References
- V. A. Morozov, On the solution of functional equations by the method of regularization, Soviet Mathematics Doklady 7, 1966, pages 414 to 417
- Heinz W. Engl, Martin Hanke and Andreas Neubauer, Regularization of Inverse Problems, Kluwer, 1996, chapter 4 (a posteriori parameter choice and the discrepancy principle) and chapter 5 (Tikhonov regularization); the discrete rule for iterative methods in chapters 6 and 7
- Per Christian Hansen, Discrete Inverse Problems, Insight and Algorithms, SIAM, 2010, chapter 5 (choosing the regularization parameter)
Where this leads
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6BGG92 Edit this page History Report an error Markdown