Algorithmadvanced
Maximum entropy method for image reconstruction
Also called MEM imaging, maximum entropy deconvolution.
Choose the positive image of maximum entropy relative to a default image among those that fit the data within the noise, that is with chi-squared equal to the number of data.
- Solves
- Image deblurring
- Time
- Θ(m n^2 + K n^3) worst · average · best
- Space
- Θ(n^2) extra
- Where
- K = the total number of Newton steps; m = the number of data; n = the number of pixels
- Model
- Real RAM
- Properties
- deterministicgaussian noise modeliterativenot linearnonnegativeunique solution
- Evidence
- Proof sketchCode in 1 languages
- Origin
- B. Roy Frieden, Stephen F. Gull, G. J. Daniell, John Skilling, R. K. Bryan, 1972
The maximum entropy method (MEM) reconstructs a positive image from blurred, noisy or incomplete data. Many images fit the data within the noise. MEM picks the one that is "least committal": the image of largest entropy relative to a default image , among all images whose misfit is equal to its expected value, the number of data. In the form of Skilling, the entropy is , which is minus the generalized Kullback-Leibler divergence of from . The logarithm forces every pixel to be positive, and with no data the answer is . The method came from radio and optical astronomy, where Frieden (1972), Gull and Daniell (1978) and Skilling and Bryan (1984) developed it, and it competed with CLEAN for the deconvolution of dirty images. It is a regularization of the image deblurring problem, like Tikhonov with a different penalty, and it differs from Richardson-Lucy, which maximizes a Poisson likelihood with no penalty and needs early stopping.
In plain words
You have a blurred and noisy picture of the sky. Many sharp pictures, once blurred, look like the data up to the noise. Which one should you report? MEM says: report the one that adds the least structure that the data do not ask for. "Structure" is measured against a default picture, often flat, that you would report if you had no data. The entropy is high when the picture is close to the default and falls as the picture moves away from it. So you start at the default, and move away only as far as you must to explain the data to the level of the noise. Bright points that the data demand appear; wiggles that the data do not demand stay out. Because of the logarithm in the entropy, no pixel can go negative.
The problem
The data are with a known real matrix (for deblurring, the matrix of convolution with the PSF; for radio interferometry, a partial Fourier transform) and Gaussian noise , independent. The misfit is , with the expected value at the true image. The default image is given (a flat image with the right total flux is the usual choice). The problem is
with the target , the number of data. With the Lagrange multiplier written as , the solution minimizes
for the that gives . The stationary condition is with : the image is the default times the exponential of a back projection of the residual, so it is positive by construction.
Frieden and Gull and Daniell wrote the entropy as (or ) with the total flux fixed; the extra term of Skilling's form removes the need for that constraint.
The algorithm
The implementation here is small and dense: an outer bisection on and, for each , Newton steps on the convex function .
MEM(y, A, sigma, m, C) ▷ C = target chi^2, default the number of data- 1
lo ← 0; hi ← 1; grow hi by factors of 10 until chi^2(x_hi) ≤ C - 2
repeat until |chi^2(x) - C| ≤ tol · C - 3
lambda ← sqrt(lo · hi) - 4
x ← minimizer of F_lambda, from the last x, by Newton steps L5 to L8: - 5
g ← log(x / m) + lambda · A^T W (A x - y) - 6
H ← diag(1 / x) + lambda · A^T W A - 7
d ← -H^(-1) g - 8
x ← x + t d, with t = 1, 1/2, 1/4, ... until x > 0 and F_lambda falls enough - 9
if chi^2(x) > C then lo ← lambda else hi ← lambda - 10
return x, lambda
If , the default image already fits, and it is the answer. Line L8 is a backtracking line search: it halves until the new point is positive and falls by at least a quarter of the predicted decrease. The discrepancy principle with is the classic choice of .
The Skilling-Bryan algorithm. For large images, cannot be formed. Skilling and Bryan (1984) instead search, in each iteration, a subspace of three to six directions built from and , measured in the entropy metric (the inverse of the entropy Hessian). They fit quadratic models of and in the subspace, and take a step that raises and lowers toward the target, with a limit on the step length in the entropy metric. Each iteration then costs a few applications of and .
Example
Two pixels by hand. Take , , and , with the target . The second pixel already equals its default and its datum, so . For the first pixel the stationary condition is , and the constraint is . Entropy pulls toward , so , and then and . The code gets these values.
A blurred spike train. A measurement on one seed: pixels, a periodic blur with weights , the true image everywhere except , and at pixels 5, 6 and 11, Gaussian noise with , and a flat default equal to the mean of the data, . The flat default has . The table gives the minimizer of for several :
| error | smallest pixel | pixels 5, 6, 11 | |||
|---|---|---|---|---|---|
| 0.01 | 179.72 | -0.092 | 9.339 | 1.894 | 2.44, 2.36, 2.17 |
| 0.1 | 64.63 | -2.456 | 7.045 | 1.230 | 4.46, 3.56, 2.86 |
| 0.4536 | 16.00 | -7.447 | 4.487 | 0.633 | 6.90, 4.16, 3.97 |
| 1 | 6.85 | -10.439 | 3.548 | 0.375 | 8.02, 4.21, 4.52 |
| 10 | 1.15 | -17.121 | 3.061 | 0.003 | 9.80, 4.14, 5.45 |
| 100 | 0.90 | -19.405 | 3.255 | 0.000 | 10.25, 4.02, 5.72 |
The bisection stops at , where . As grows, and both fall, as Claim 4 of the proof says. The peaks come back, and every pixel stays positive. In this run the image with is smoother than the one with the smallest error (): the classic target tends to under-fit, a known weakness that led Gull (1989) to a Bayesian choice of .
Correctness
The full proof is in proofs/correctness.md. The main facts, for real, and :
- Unique minimizer for each . is strictly convex on , its sublevel sets are bounded, and its minimizer has all pixels positive (the entropy has slope at ). It satisfies .
- Newton steps are safe. is positive definite, so is a descent direction, the line search ends, and never increases.
- Maximum entropy. If , then for every with .
- Monotone trade-off. and are nonincreasing in .
- Existence of . If , a with exists, and the bisection finds it.
Proof: The maximum entropy image is unique, positive and of largest entropy among the images that fit the datafull
Setting. is a real matrix, , , and is the default image. For (with ),
and for . The algorithm is lines L1 to L10 of the page.
Claim 1 (unique positive minimizer). For every , has exactly one minimizer over . All its entries are positive, and
Proof. Each term is continuous on , strictly convex (), at least (it is only at ) and grows like . is convex and at least . So is continuous, strictly convex, and as in the orthant. A continuous function with bounded sublevel sets on a closed set has a minimizer, and strict convexity makes it unique.
Suppose some . Move pixel to . The derivative of along this move is , where the second term stays bounded as and the first goes to . So falls for small , a contradiction. Hence , the minimizer is in the open orthant, the gradient vanishes there, and is the stated formula.
Claim 2 (the Newton steps). At , is positive definite, satisfies unless , and the search in line L8 ends with a positive point at which is lower by at least .
Proof. is positive definite and is positive semidefinite, so is positive definite and so is . Then for . The set is open, so for all small . is differentiable at , so , which is below for small . Halving reaches such a after finitely many steps.
So the values of along the Newton iterates never increase; the tests check this at every step. Near the Hessian is continuous and positive definite, and Newton's method with full steps converges quadratically there. We do not prove a global bound on the number of steps, because the entropy Hessian is unbounded near the boundary of the orthant; the code stops when the Newton decrement is below a tolerance, and the tests check the stationary condition of Claim 1 at the output.
Claim 3 (maximum entropy among the images that fit). Let minimize and let . For every with , . If , the inequality is strict.
Proof. . So , that is . If , the first inequality is strict by uniqueness.
So the output of the bisection, with , is the unique solution of the constrained problem subject to , and also of the problem with when it exists.
Claim 4 (monotone trade-off). If , then and .
Proof. Write and . Optimality of each minimizer gives and . Adding them gives , so . Then the first inequality gives , so , that is .
Claim 5 (existence of and the bisection). The map is continuous on , tends to as , and tends to as . So if , some gives , and bisection on converges to such a value.
Proof. Continuity: is jointly continuous in , the minimizer is unique, and for in a compact interval of the minimizers stay in a bounded set (since bounds , and has bounded sublevel sets). A standard argument (every limit point of minimizes the limit function, which has one minimizer) gives continuity of , hence of .
: , and is only at and has bounded sublevel sets, so .
: for any , , so . Taking close to the infimum of and then large shows that approaches the infimum.
By Claim 4 the map is nonincreasing, and by continuity it takes the value (intermediate value theorem). Line L1 finds with , and the invariant holds through line L9. The interval shrinks geometrically in and contains a point where , so by continuity along the bisection.
The tests check Claim 1 (the stationary formula, positivity, and a comparison with a per-pixel bisection when ), Claim 2 (no increase of ), Claim 3 (by random positive images with ), Claim 4 on a grid of , the two-pixel example of the page in closed form, and the gradient against central finite differences.
Complexity
In the real-RAM model, with pixels and data, forming once costs , and each Newton step costs for the dense solve plus for the gradient. So Newton steps in total cost , with extra space for . This dense form is for small problems; in the table above each needed 3 to 9 Newton steps, and 52 steps at , where pixels come close to and the line search cuts the steps (a measurement). The Skilling-Bryan form costs a few applications of and per iteration, each for a convolution done with the FFT, and needs extra space; no bound on the number of its iterations is known in general.
Properties
- Positive: every output pixel is positive, without clipping.
- Nonlinear in the data, and unique: for each there is one image, and the image with is unique when it exists.
- With no information in the data about a pixel, the pixel goes to its default.
- The total flux is not a constraint of Skilling's form. In the example the output has the flux 33.83, the data 33.24 and the true image 34 (a measurement).
- The image depends on the default and on the target .
- MEM smooths flat, low-level regions strongly and keeps bright points sharp, so its resolution depends on the brightness (Narayan and Nityananda 1986 discuss this).
Variants and improvements
- Bayesian MEM. Treat as a prior and choose by its evidence ("classic MaxEnt", Gull 1989; Skilling 1989) instead of . This is the MAP estimate with an entropy prior, with a rule for the weight.
- Poisson data. Replace by the Poisson negative log-likelihood. Iterations of Richardson-Lucy type with an entropy term then apply.
- Multichannel and intrinsic correlation function. Put the entropy on a hidden image and blur it to get the visible one, so that the result is smooth on a chosen scale (Gull 1989).
- Radio interferometry. is the sampled Fourier transform, the data are visibilities, and MEM fills in the unsampled spatial frequencies with values that keep the image positive and smooth (see aperture synthesis). Cornwell and Evans (1985) gave a widely used form.
- Dual methods. The problem has a smooth unconstrained dual over the data space, since is an exponential of ; this is useful when (see Lagrangian duality).
When to use it
Use MEM for positive images with a large dynamic range and a few bright features on a faint background, such as radio maps, spectra and some astronomical images, when the noise is close to Gaussian with a known level and you want a single best image with no negative values. For photon counts, Richardson-Lucy or a Poisson MAP method fits the noise better. For extended objects with sharp borders, total variation methods often keep edges better. When the noise level is unknown, the target cannot be set, and a Bayesian choice of is needed.
Pitfalls
- The target is a heuristic. The expected value of at the true image is , but the fitted image has fewer degrees of freedom left, so the target tends to under-fit, as in the example.
- The result depends on the default image. A flat default with the wrong total flux biases the whole image.
- The entropy is not invariant to a change of pixel size or of the zero level. A background that is not subtracted becomes part of the "positive image", and a negative true signal cannot be represented at all.
- Resolution varies across the image: bright points are sharp and faint regions are smooth. Do not compare widths of features of different brightness.
- Plain gradient ascent on is slow and unstable because the curvature of the entropy, , varies over many orders of magnitude. Use the entropy metric or Newton steps.
- If the target is below the smallest misfit any positive image can reach, no solution exists. The code then raises an error.
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
maximum_entropy_method_imaging.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-entropy-method-imaging/. The authors are listed in prov/DHVCDM.jsonl.
"""Maximum entropy image reconstruction.
The data are y = A x + e with a dense real matrix A (a list of rows),
Gaussian noise of standard deviation sigma_i per datum, and a positive
default image m. The entropy is Skilling's form
S(x) = sum_j [x_j - m_j - x_j log(x_j / m_j)],
which is at most 0, with the maximum at x = m. The misfit is
chi2(x) = sum_i (y_i - (A x)_i)^2 / sigma_i^2. The method returns the
positive image of largest S with chi2(x) = target (default: the number of
data). For a fixed lambda it minimizes F(x) = -S(x) + (lambda / 2) chi2(x)
by damped Newton steps; an outer bisection on log(lambda) meets the target.
This is a small dense version: Skilling and Bryan (1984) search a subspace
of a few directions instead of taking full Newton steps.
"""
import math
from imgla import matvec, rmatvec, solve
def entropy(x, m):
"""Skilling's entropy S(x) = sum [x - m - x log(x / m)]."""
return sum(xj - mj - (xj * math.log(xj / mj) if xj > 0 else 0.0) for xj, mj in zip(x, m))
def chi2(x, a, y, sigma):
"""sum_i ((A x)_i - y_i)^2 / sigma_i^2."""
return sum(((p - q) / s) ** 2 for p, q, s in zip(matvec(a, x), y, sigma))
def objective(x, a, y, sigma, m, lam):
"""F(x) = -S(x) + (lam / 2) chi2(x)."""
return -entropy(x, m) + 0.5 * lam * chi2(x, a, y, sigma)
def gradient(x, a, y, sigma, m, lam):
"""grad F = log(x / m) + lam A^T W (A x - y), with W = diag(1 / sigma^2)."""
r = [(p - q) / (s * s) for p, q, s in zip(matvec(a, x), y, sigma)]
g = rmatvec(a, r)
return [math.log(xj / mj) + lam * gj for xj, mj, gj in zip(x, m, g)]
def solve_fixed_lambda(a, y, sigma, m, lam, x0=None, tol=1e-16, max_steps=200, history=None):
"""Minimize F for one lambda by Newton steps with backtracking. Returns x > 0.
If history is a list, the value of F after each step is appended.
"""
n = len(m)
x = list(m) if x0 is None else list(x0)
w = [1.0 / (s * s) for s in sigma]
# A^T W A, formed once (it does not depend on x).
atwa = [[sum(a[i][p] * w[i] * a[i][q] for i in range(len(a))) for q in range(n)] for p in range(n)]
f = objective(x, a, y, sigma, m, lam)
for _ in range(max_steps):
g = gradient(x, a, y, sigma, m, lam) # @line L5
hess = [[lam * atwa[p][q] + (1.0 / x[p] if p == q else 0.0) for q in range(n)] for p in range(n)] # @line L6
d = solve(hess, [-v for v in g]) # @line L7
dec = -sum(gi * di for gi, di in zip(g, d))
if dec <= tol * max(1.0, abs(f)):
break
t = 1.0 # @line L8
while True:
xn = [xi + t * di for xi, di in zip(x, d)]
if min(xn) > 0:
fn = objective(xn, a, y, sigma, m, lam)
if fn <= f - 0.25 * t * dec:
break
t *= 0.5
if t < 1e-14:
return x
x, f = xn, fn
if history is not None:
history.append(f)
return x
def maximum_entropy(a, y, sigma, m, target=None, rel_tol=1e-6, lam_max=1e8, max_bisect=200):
"""The positive image of maximum entropy with chi2 = target (default len(y)).
Returns (x, lam). Raises ValueError if the target is below the misfit
reached at lam_max (no positive image fits the data that well).
"""
if target is None:
target = float(len(y))
if chi2(m, a, y, sigma) <= target:
return list(m), 0.0 # the default image already fits the data
lo, hi = 0.0, 1.0 # @line L1
x = solve_fixed_lambda(a, y, sigma, m, hi)
while chi2(x, a, y, sigma) > target: # grow the bracket by factors of 10
if hi >= lam_max:
raise ValueError("target misfit is below what any positive image reaches")
lo, hi = hi, 10.0 * hi
x = solve_fixed_lambda(a, y, sigma, m, hi, x0=x)
if lo == 0.0:
lo = hi / 1e6
for _ in range(max_bisect): # @line L2
lam = math.sqrt(lo * hi) # @line L3
x = solve_fixed_lambda(a, y, sigma, m, lam, x0=x) # @line L4
c = chi2(x, a, y, sigma)
if abs(c - target) <= rel_tol * target:
break
if c > target: # @line L9
lo = lam
else:
hi = lam
return x, lam # @line L10
def circulant_blur_matrix(h):
"""The n x n matrix of periodic convolution with h (h centered at index 0)."""
n = len(h)
return [[h[(i - j) % n] for j in range(n)] for i in range(n)]
test_maximum_entropy_method_imaging.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-entropy-method-imaging/. The authors are listed in prov/DHVCDM.jsonl.
import math
import random
from imgla import adjoint_gap, matvec, rmatvec
from maximum_entropy_method_imaging import (
chi2,
circulant_blur_matrix,
entropy,
gradient,
maximum_entropy,
objective,
solve_fixed_lambda,
)
def blur_problem(seed, n=16, noise=0.3):
h = [0.0] * n
for d, v in {0: 0.4, 1: 0.2, -1: 0.2, 2: 0.1, -2: 0.1}.items():
h[d % n] += v
a = circulant_blur_matrix(h)
xt = [1.0] * n
xt[5], xt[6], xt[11] = 9.0, 5.0, 7.0
rng = random.Random(seed)
y = [v + rng.gauss(0, noise) for v in matvec(a, xt)]
sigma = [noise] * n
m = [sum(y) / n] * n
return a, y, sigma, m, xt
def test_blur_matrix_adjoint():
a, _, _, _, _ = blur_problem(1)
rng = random.Random(9)
x = [rng.gauss(0, 1) for _ in range(16)]
y = [rng.gauss(0, 1) for _ in range(16)]
assert adjoint_gap(lambda v: matvec(a, v), lambda w: rmatvec(a, w), x, y) < 1e-12
def test_two_pixel_example_closed_form():
# A = I, sigma = 1, m = 1, y = (4, 1), target chi2 = 2 (the number of data).
x, lam = maximum_entropy([[1.0, 0.0], [0.0, 1.0]], [4.0, 1.0], [1.0, 1.0], [1.0, 1.0])
x1 = 4 - math.sqrt(2)
assert abs(x[0] - x1) < 1e-6 and abs(x[1] - 1.0) < 1e-9
assert abs(lam - math.log(x1) / math.sqrt(2)) < 1e-5
assert abs(entropy(x, [1.0, 1.0]) - (x1 - 1 - x1 * math.log(x1))) < 1e-6
def test_gradient_matches_finite_differences():
a, y, sigma, m, _ = blur_problem(2)
rng = random.Random(4)
x = [mj * rng.uniform(0.5, 1.5) for mj in m]
g = gradient(x, a, y, sigma, m, 0.7)
for j in (0, 5, 11):
e = 1e-6
xp = list(x)
xm = list(x)
xp[j] += e
xm[j] -= e
fd = (objective(xp, a, y, sigma, m, 0.7) - objective(xm, a, y, sigma, m, 0.7)) / (2 * e)
assert abs(fd - g[j]) < 1e-5 * max(1.0, abs(g[j]))
def test_fixed_lambda_stationarity_positivity_and_monotone_newton():
a, y, sigma, m, _ = blur_problem(1)
for lam in (0.1, 1.0, 10.0):
hist = []
x = solve_fixed_lambda(a, y, sigma, m, lam, history=hist)
assert min(x) > 0
# F never increases along the Newton steps (backtracking).
f0 = objective(m, a, y, sigma, m, lam)
seq = [f0] + hist
assert all(seq[k + 1] <= seq[k] + 1e-12 for k in range(len(seq) - 1))
# Stationarity: x_j = m_j exp(-lam (A^T W (A x - y))_j).
r = [(p - q) / (s * s) for p, q, s in zip(matvec(a, x), y, sigma)]
g = rmatvec(a, r)
for xj, mj, gj in zip(x, m, g):
assert abs(xj - mj * math.exp(-lam * gj)) < 1e-7 * max(1.0, xj)
def test_denoising_case_matches_per_pixel_bisection():
# With A = I the problem splits: log(x / m) + lam (x - y) / sigma^2 = 0 per pixel.
rng = random.Random(6)
n = 8
a = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
y = [rng.uniform(0.2, 5.0) for _ in range(n)]
sigma = [0.5] * n
m = [1.5] * n
lam = 0.8
x = solve_fixed_lambda(a, y, sigma, m, lam)
for xj, yj in zip(x, y):
lo, hi = 1e-12, 100.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if math.log(mid / 1.5) + lam * (mid - yj) / 0.25 > 0:
hi = mid
else:
lo = mid
assert abs(xj - 0.5 * (lo + hi)) < 1e-9
def test_misfit_falls_and_entropy_falls_as_lambda_grows():
a, y, sigma, m, _ = blur_problem(1)
prev_c, prev_s = float("inf"), float("inf")
x = None
for lam in (0.01, 0.1, 0.5, 1.0, 5.0, 20.0):
x = solve_fixed_lambda(a, y, sigma, m, lam, x0=x)
c, s = chi2(x, a, y, sigma), entropy(x, m)
assert c <= prev_c + 1e-9 and s <= prev_s + 1e-9
prev_c, prev_s = c, s
def test_discrepancy_target_and_maximum_entropy_among_feasible_images():
a, y, sigma, m, _ = blur_problem(1)
x, lam = maximum_entropy(a, y, sigma, m)
c = chi2(x, a, y, sigma)
assert abs(c - 16.0) < 1e-4 and lam > 0
s_best = entropy(x, m)
# Brute force: random positive images that fit at least as well have less entropy.
rng = random.Random(8)
tried = 0
for _ in range(3000):
d = [rng.gauss(0, 1) for _ in x]
eps = 10 ** rng.uniform(-4, -0.5)
z = [xi + eps * di for xi, di in zip(x, d)]
if min(z) <= 0 or chi2(z, a, y, sigma) > 16.0:
continue
tried += 1
assert entropy(z, m) <= s_best + 1e-9
assert tried > 50
def test_default_image_is_returned_when_it_already_fits():
a = [[1.0, 0.0], [0.0, 1.0]]
x, lam = maximum_entropy(a, [1.2, 0.9], [1.0, 1.0], [1.0, 1.0])
assert x == [1.0, 1.0] and lam == 0.0
def test_unreachable_target_raises():
# Data with a negative value cannot be fit by a positive image to chi2 = 0.1.
a = [[1.0, 0.0], [0.0, 1.0]]
try:
maximum_entropy(a, [3.0, -3.0], [1.0, 1.0], [1.0, 1.0], target=0.1, lam_max=1e4)
except ValueError:
return
assert False, "expected ValueError"
History
E. T. Jaynes (1957) proposed maximum entropy as a rule of inference. B. R. Frieden (1972) applied it to image restoration. S. F. Gull and G. J. Daniell (1978) used it for radio astronomy maps from incomplete and noisy data, with the chi-squared constraint, and showed its good behavior on positive images. J. Skilling and R. K. Bryan (1984) gave the general algorithm with the entropy metric and the subspace search that made the method robust for large images, and the MEMSYS programs spread it. R. Narayan and R. Nityananda (1986) reviewed the method for astronomy. Later work by Gull and Skilling turned it into a Bayesian method with a rule for the regularization weight.
References
- B. Roy Frieden, Restoring with maximum likelihood and maximum entropy, Journal of the Optical Society of America 62(4), 1972, pages 511 to 518
- S. F. Gull and G. J. Daniell, Image reconstruction from incomplete and noisy data, Nature 272, 1978, pages 686 to 690
- J. Skilling and R. K. Bryan, Maximum entropy image reconstruction, general algorithm, Monthly Notices of the Royal Astronomical Society 211(1), 1984, pages 111 to 124 (the entropy metric, the subspace search and the control of chi-squared)
- R. Narayan and R. Nityananda, Maximum entropy image restoration in astronomy, Annual Review of Astronomy and Astrophysics 24, 1986, pages 127 to 170 (survey)
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 DHVCDM Edit this page History Report an error Markdown