Algorithm Search⌘K

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.

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
Properties
deterministicgaussian noise modeliterativenot linearnonnegativeunique solution
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 mm, among all images whose misfit χ2\chi^2 is equal to its expected value, the number of data. In the form of Skilling, the entropy is S(x)=∑j[xj−mj−xjlog⁡(xj/mj)]S(x) = \sum_j [x_j - m_j - x_j \log(x_j/m_j)], which is minus the generalized Kullback-Leibler divergence of xx from mm. The logarithm forces every pixel to be positive, and with no data the answer is mm. 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 y=Ax+ey = Ax + e with a known real m×nm \times n matrix AA (for deblurring, the matrix of convolution with the PSF; for radio interferometry, a partial Fourier transform) and Gaussian noise ei∼N(0,σi2)e_i \sim N(0, \sigma_i^2), independent. The misfit is χ2(x)=∑i(yi−(Ax)i)2/σi2\chi^2(x) = \sum_i (y_i - (Ax)_i)^2/\sigma_i^2, with the expected value mm at the true image. The default image mj>0m_j > 0 is given (a flat image with the right total flux is the usual choice). The problem is

max⁡x>0 S(x)=∑j[xj−mj−xjlog⁡xjmj]subject toχ2(x)=C,\max_{x > 0}\ S(x) = \sum_j \Big[x_j - m_j - x_j \log\frac{x_j}{m_j}\Big] \quad\text{subject to}\quad \chi^2(x) = C,

with the target C=mC = m, the number of data. With the Lagrange multiplier written as λ/2\lambda/2, the solution minimizes

Fλ(x)=−S(x)+λ2χ2(x)F_\lambda(x) = -S(x) + \frac{\lambda}{2}\chi^2(x)

for the λ>0\lambda > 0 that gives χ2=C\chi^2 = C. The stationary condition is xj=mjexp⁡(−λ (ATW(Ax−y))j)x_j = m_j \exp\big(-\lambda\,(A^TW(Ax - y))_j\big) with W=diag⁡(1/σi2)W = \operatorname{diag}(1/\sigma_i^2): 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 −∑jxjlog⁡(xj/mj)-\sum_j x_j\log(x_j/m_j) (or −∑xjlog⁡xj-\sum x_j \log x_j) with the total flux fixed; the extra term ∑j(xj−mj)\sum_j(x_j - m_j) of Skilling's form removes the need for that constraint.

The algorithm

The implementation here is small and dense: an outer bisection on log⁡λ\log\lambda and, for each λ\lambda, Newton steps on the convex function FλF_\lambda.

  1. MEM(y, A, sigma, m, C) ▷ C = target chi^2, default the number of data
  2. 1lo ← 0; hi ← 1; grow hi by factors of 10 until chi^2(x_hi) ≤ C
  3. 2repeat until |chi^2(x) - C| ≤ tol · C
  4. 3lambda ← sqrt(lo · hi)
  5. 4x ← minimizer of F_lambda, from the last x, by Newton steps L5 to L8:
  6. 5g ← log(x / m) + lambda · A^T W (A x - y)
  7. 6H ← diag(1 / x) + lambda · A^T W A
  8. 7d ← -H^(-1) g
  9. 8x ← x + t d, with t = 1, 1/2, 1/4, ... until x > 0 and F_lambda falls enough
  10. 9if chi^2(x) > C then lo ← lambda else hi ← lambda
  11. 10return x, lambda

If χ2(m)≤C\chi^2(m) \le C, the default image already fits, and it is the answer. Line L8 is a backtracking line search: it halves tt until the new point is positive and FλF_\lambda falls by at least a quarter of the predicted decrease. The discrepancy principle with χ2=m\chi^2 = m is the classic choice of λ\lambda.

The Skilling-Bryan algorithm. For large images, HH cannot be formed. Skilling and Bryan (1984) instead search, in each iteration, a subspace of three to six directions built from ∇S\nabla S and ∇χ2\nabla\chi^2, measured in the entropy metric diag⁡(x)\operatorname{diag}(x) (the inverse of the entropy Hessian). They fit quadratic models of SS and χ2\chi^2 in the subspace, and take a step that raises SS and lowers χ2\chi^2 toward the target, with a limit on the step length in the entropy metric. Each iteration then costs a few applications of AA and ATA^T.

Example

Two pixels by hand. Take A=IA = I, σ=(1,1)\sigma = (1, 1), m=(1,1)m = (1, 1) and y=(4,1)y = (4, 1), with the target C=2C = 2. The second pixel already equals its default and its datum, so x2=1x_2 = 1. For the first pixel the stationary condition is log⁡x1=−λ(x1−4)\log x_1 = -\lambda(x_1 - 4), and the constraint is (x1−4)2=2(x_1 - 4)^2 = 2. Entropy pulls x1x_1 toward m1=1m_1 = 1, so x1=4−2=2.58579x_1 = 4 - \sqrt 2 = 2.58579, and then λ=log⁡(2.58579)/2=0.67177\lambda = \log(2.58579)/\sqrt 2 = 0.67177 and S=x1−1−x1log⁡x1=−0.87079S = x_1 - 1 - x_1\log x_1 = -0.87079. The code gets these values.

A blurred spike train. A measurement on one seed: n=16n = 16 pixels, a periodic blur with weights (0.1,0.2,0.4,0.2,0.1)(0.1, 0.2, 0.4, 0.2, 0.1), the true image 11 everywhere except 99, 55 and 77 at pixels 5, 6 and 11, Gaussian noise with σ=0.3\sigma = 0.3, and a flat default equal to the mean of the data, 2.0772.077. The flat default has χ2=219.1\chi^2 = 219.1. The table gives the minimizer of FλF_\lambda for several λ\lambda:

λ\lambda χ2\chi^2 SS error ∥x−x†∥\lVert x - x^\dagger\rVert 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 λ=0.4536\lambda = 0.4536, where χ2=16\chi^2 = 16. As λ\lambda grows, χ2\chi^2 and SS both fall, as Claim 4 of the proof says. The peaks come back, and every pixel stays positive. In this run the image with χ2=16\chi^2 = 16 is smoother than the one with the smallest error (λ=10\lambda = 10): the classic target χ2=m\chi^2 = m tends to under-fit, a known weakness that led Gull (1989) to a Bayesian choice of λ\lambda.

Correctness

The full proof is in proofs/correctness.md. The main facts, for AA real, σi>0\sigma_i > 0 and mj>0m_j > 0:

  1. Unique minimizer for each λ\lambda. FλF_\lambda is strictly convex on x≥0x \ge 0, its sublevel sets are bounded, and its minimizer xλx_\lambda has all pixels positive (the entropy has slope +∞+\infty at 00). It satisfies xj=mjexp⁡(−λ(ATW(Ax−y))j)x_j = m_j\exp(-\lambda(A^TW(Ax - y))_j).
  2. Newton steps are safe. HH is positive definite, so dd is a descent direction, the line search ends, and FλF_\lambda never increases.
  3. Maximum entropy. If χ2(xλ)=C\chi^2(x_\lambda) = C, then S(xλ)≥S(x)S(x_\lambda) \ge S(x) for every x>0x > 0 with χ2(x)≤C\chi^2(x) \le C.
  4. Monotone trade-off. χ2(xλ)\chi^2(x_\lambda) and S(xλ)S(x_\lambda) are nonincreasing in λ\lambda.
  5. Existence of λ\lambda. If inf⁡x≥0χ2(x)<C<χ2(m)\inf_{x \ge 0}\chi^2(x) < C < \chi^2(m), a λ>0\lambda > 0 with χ2(xλ)=C\chi^2(x_\lambda) = C 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. AA is a real m×nm \times n matrix, y∈Rmy \in \mathbb R^m, σi>0\sigma_i > 0, W=diag⁡(1/σi2)W = \operatorname{diag}(1/\sigma_i^2) and mj>0m_j > 0 is the default image. For x≥0x \ge 0 (with 0log⁡0=00\log 0 = 0),

E(x)=−S(x)=∑j[xjlog⁡xjmj−xj+mj],χ2(x)=(Ax−y)TW(Ax−y),E(x) = -S(x) = \sum_j \Big[x_j\log\frac{x_j}{m_j} - x_j + m_j\Big], \qquad \chi^2(x) = (Ax - y)^TW(Ax - y),

and Fλ(x)=E(x)+λ2χ2(x)F_\lambda(x) = E(x) + \tfrac\lambda2\chi^2(x) for λ>0\lambda > 0. The algorithm is lines L1 to L10 of the page.

Claim 1 (unique positive minimizer). For every λ>0\lambda > 0, FλF_\lambda has exactly one minimizer xλx_\lambda over x≥0x \ge 0. All its entries are positive, and

xλ,j=mjexp⁡(−λ (ATW(Axλ−y))j).x_{\lambda,j} = m_j\exp\big(-\lambda\,(A^TW(Ax_\lambda - y))_j\big).

Proof. Each term e(t)=tlog⁡(t/mj)−t+mje(t) = t\log(t/m_j) - t + m_j is continuous on [0,∞)[0, \infty), strictly convex (e′′=1/t>0e'' = 1/t > 0), at least 00 (it is 00 only at t=mjt = m_j) and grows like tlog⁡tt\log t. χ2\chi^2 is convex and at least 00. So FλF_\lambda is continuous, strictly convex, and Fλ(x)→∞F_\lambda(x) \to \infty as ∥x∥→∞\lVert x\rVert \to \infty 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 xλ,j=0x_{\lambda,j} = 0. Move pixel jj to t>0t > 0. The derivative of FλF_\lambda along this move is log⁡(t/mj)+λ (ATW(Ax−y))j\log(t/m_j) + \lambda\,(A^TW(Ax - y))_j, where the second term stays bounded as t→0+t \to 0^+ and the first goes to −∞-\infty. So FλF_\lambda falls for small t>0t > 0, a contradiction. Hence xλ>0x_\lambda > 0, the minimizer is in the open orthant, the gradient vanishes there, and ∇Fλ=log⁡(x/m)+λATW(Ax−y)=0\nabla F_\lambda = \log(x/m) + \lambda A^TW(Ax - y) = 0 is the stated formula. □\square

Claim 2 (the Newton steps). At x>0x > 0, H=diag⁡(1/x)+λATWAH = \operatorname{diag}(1/x) + \lambda A^TWA is positive definite, d=−H−1gd = -H^{-1}g satisfies gTd<0g^Td < 0 unless g=0g = 0, and the search in line L8 ends with a positive point at which FλF_\lambda is lower by at least 14t (−gTd)\tfrac14 t\,(-g^Td).

Proof. diag⁡(1/x)\operatorname{diag}(1/x) is positive definite and ATWAA^TWA is positive semidefinite, so HH is positive definite and so is H−1H^{-1}. Then gTd=−gTH−1g<0g^Td = -g^TH^{-1}g < 0 for g≠0g \ne 0. The set x>0x > 0 is open, so x+td>0x + td > 0 for all small tt. FλF_\lambda is differentiable at xx, so Fλ(x+td)=Fλ(x)+tgTd+o(t)F_\lambda(x + td) = F_\lambda(x) + t g^Td + o(t), which is below Fλ(x)+14tgTdF_\lambda(x) + \tfrac14 t g^Td for small tt. Halving tt reaches such a tt after finitely many steps. □\square

So the values of FλF_\lambda along the Newton iterates never increase; the tests check this at every step. Near xλx_\lambda 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 1/xj1/x_j is unbounded near the boundary of the orthant; the code stops when the Newton decrement −gTd-g^Td 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 xλx_\lambda minimize FλF_\lambda and let C=χ2(xλ)C = \chi^2(x_\lambda). For every x≥0x \ge 0 with χ2(x)≤C\chi^2(x) \le C, S(x)≤S(xλ)S(x) \le S(x_\lambda). If x≠xλx \ne x_\lambda, the inequality is strict.

Proof. E(xλ)+λ2C=Fλ(xλ)≤Fλ(x)=E(x)+λ2χ2(x)≤E(x)+λ2CE(x_\lambda) + \tfrac\lambda2 C = F_\lambda(x_\lambda) \le F_\lambda(x) = E(x) + \tfrac\lambda2\chi^2(x) \le E(x) + \tfrac\lambda2 C. So E(xλ)≤E(x)E(x_\lambda) \le E(x), that is S(x)≤S(xλ)S(x) \le S(x_\lambda). If x≠xλx \ne x_\lambda, the first inequality is strict by uniqueness. □\square

So the output of the bisection, with χ2(xλ)=C\chi^2(x_\lambda) = C, is the unique solution of the constrained problem max⁡S\max S subject to χ2≤C\chi^2 \le C, and also of the problem with χ2=C\chi^2 = C when it exists.

Claim 4 (monotone trade-off). If 0<λ1<λ20 < \lambda_1 < \lambda_2, then χ2(xλ2)≤χ2(xλ1)\chi^2(x_{\lambda_2}) \le \chi^2(x_{\lambda_1}) and S(xλ2)≤S(xλ1)S(x_{\lambda_2}) \le S(x_{\lambda_1}).

Proof. Write Ek=E(xλk)E_k = E(x_{\lambda_k}) and ck=12χ2(xλk)c_k = \tfrac12\chi^2(x_{\lambda_k}). Optimality of each minimizer gives E1+λ1c1≤E2+λ1c2E_1 + \lambda_1c_1 \le E_2 + \lambda_1c_2 and E2+λ2c2≤E1+λ2c1E_2 + \lambda_2c_2 \le E_1 + \lambda_2c_1. Adding them gives (λ2−λ1)(c2−c1)≤0(\lambda_2 - \lambda_1)(c_2 - c_1) \le 0, so c2≤c1c_2 \le c_1. Then the first inequality gives E1−E2≤λ1(c2−c1)≤0E_1 - E_2 \le \lambda_1(c_2 - c_1) \le 0, so E2≥E1E_2 \ge E_1, that is S(xλ2)≤S(xλ1)S(x_{\lambda_2}) \le S(x_{\lambda_1}). □\square

Claim 5 (existence of λ\lambda and the bisection). The map λ↦χ2(xλ)\lambda \mapsto \chi^2(x_\lambda) is continuous on (0,∞)(0, \infty), tends to χ2(m)\chi^2(m) as λ→0\lambda \to 0, and tends to inf⁡x≥0χ2(x)\inf_{x \ge 0}\chi^2(x) as λ→∞\lambda \to \infty. So if inf⁡x≥0χ2<C<χ2(m)\inf_{x\ge0}\chi^2 < C < \chi^2(m), some λ\lambda gives χ2(xλ)=C\chi^2(x_\lambda) = C, and bisection on λ\lambda converges to such a value.

Proof. Continuity: Fλ(x)F_\lambda(x) is jointly continuous in (λ,x)(\lambda, x), the minimizer is unique, and for λ\lambda in a compact interval of (0,∞)(0, \infty) the minimizers stay in a bounded set (since Fλ(xλ)≤Fλ(m)=λ2χ2(m)F_\lambda(x_\lambda) \le F_\lambda(m) = \tfrac\lambda2\chi^2(m) bounds E(xλ)E(x_\lambda), and EE has bounded sublevel sets). A standard argument (every limit point of xλkx_{\lambda_k} minimizes the limit function, which has one minimizer) gives continuity of λ↦xλ\lambda \mapsto x_\lambda, hence of χ2(xλ)\chi^2(x_\lambda).

λ→0\lambda \to 0: E(xλ)≤Fλ(m)=λ2χ2(m)→0E(x_\lambda) \le F_\lambda(m) = \tfrac\lambda2\chi^2(m) \to 0, and EE is 00 only at mm and has bounded sublevel sets, so xλ→mx_\lambda \to m.

λ→∞\lambda \to \infty: for any z≥0z \ge 0, λ2χ2(xλ)≤Fλ(xλ)≤E(z)+λ2χ2(z)\tfrac\lambda2\chi^2(x_\lambda) \le F_\lambda(x_\lambda) \le E(z) + \tfrac\lambda2\chi^2(z), so χ2(xλ)≤χ2(z)+2E(z)/λ\chi^2(x_\lambda) \le \chi^2(z) + 2E(z)/\lambda. Taking zz close to the infimum of χ2\chi^2 and then λ\lambda large shows that χ2(xλ)\chi^2(x_\lambda) approaches the infimum.

By Claim 4 the map is nonincreasing, and by continuity it takes the value CC (intermediate value theorem). Line L1 finds hihi with χ2(xhi)≤C\chi^2(x_{hi}) \le C, and the invariant χ2(xlo)>C≥χ2(xhi)\chi^2(x_{lo}) > C \ge \chi^2(x_{hi}) holds through line L9. The interval [lo,hi][lo, hi] shrinks geometrically in log⁡λ\log\lambda and contains a point where χ2=C\chi^2 = C, so by continuity χ2(xλ)→C\chi^2(x_\lambda) \to C along the bisection. □\square

The tests check Claim 1 (the stationary formula, positivity, and a comparison with a per-pixel bisection when A=IA = I), Claim 2 (no increase of FλF_\lambda), Claim 3 (by random positive images with χ2≤C\chi^2 \le C), Claim 4 on a grid of λ\lambda, the two-pixel example of the page in closed form, and the gradient against central finite differences.

Complexity

In the real-RAM model, with nn pixels and mm data, forming ATWAA^TWA once costs Θ(mn2)\Theta(mn^2), and each Newton step costs Θ(n3)\Theta(n^3) for the dense solve plus Θ(mn)\Theta(mn) for the gradient. So KK Newton steps in total cost Θ(mn2+Kn3)\Theta(mn^2 + Kn^3), with Θ(n2)\Theta(n^2) extra space for HH. This dense form is for small problems; in the table above each λ\lambda needed 3 to 9 Newton steps, and 52 steps at λ=100\lambda = 100, where pixels come close to 00 and the line search cuts the steps (a measurement). The Skilling-Bryan form costs a few applications of AA and ATA^T per iteration, O(nlog⁡n)O(n\log n) each for a convolution done with the FFT, and needs O(n)O(n) 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 λ\lambda there is one image, and the image with χ2=C\chi^2 = C 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 mm and on the target CC.
  • 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 exp⁡(αS(x))\exp(\alpha S(x)) as a prior and choose α=1/λ\alpha = 1/\lambda by its evidence ("classic MaxEnt", Gull 1989; Skilling 1989) instead of χ2=m\chi^2 = m. This is the MAP estimate with an entropy prior, with a rule for the weight.
  • Poisson data. Replace χ2\chi^2 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. AA 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 xx is an exponential of ATμA^T\mu; this is useful when m≪nm \ll n (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 χ2=m\chi^2 = m cannot be set, and a Bayesian choice of λ\lambda is needed.

Pitfalls

  • The target χ2=m\chi^2 = m is a heuristic. The expected value of χ2\chi^2 at the true image is mm, 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 S−λχ2/2S - \lambda\chi^2/2 is slow and unstable because the curvature of the entropy, 1/xj1/x_j, 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.

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
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

  1. B. Roy Frieden, Restoring with maximum likelihood and maximum entropy, Journal of the Optical Society of America 62(4), 1972, pages 511 to 518
  2. S. F. Gull and G. J. Daniell, Image reconstruction from incomplete and noisy data, Nature 272, 1978, pages 686 to 690
  3. 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)
  4. 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.

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