Algorithm Search⌘K

Techniqueadvanced

Coded aperture imaging

Also called uniformly redundant array imaging.

Image X-rays or gamma rays through a mask of many holes and decode the overlapping shadows by correlation with a matched decoding array.

Coded aperture imaging forms an image of X-rays or gamma rays, which no lens can focus, by placing a mask of many holes in front of a position sensitive detector. Each point of the scene casts a shifted copy of the mask pattern, so the detector records the scene convolved with the mask, and the scene is recovered by correlating the record with a decoding array. A uniformly redundant array (URA) is a mask whose periodic autocorrelation is a delta plus a constant; with the balanced decoding array G=2A−1G = 2A - 1 the decoding is exact for noiseless data (Fenimore and Cannon 1978). The mask collects about half the light, against a tiny fraction for a pinhole of the same resolution.

In plain words

A pinhole camera makes a sharp image, but the small hole lets in very little light. Make many holes and much more light gets in, but each bright point in the scene now throws a whole pattern of spots on the detector, and the patterns of all points pile up into a blur. If the holes are placed in the right pattern, the blur can be undone. The decoder slides a copy of the hole pattern over the record and, at each position, adds the counts where the copy has holes and subtracts the counts where it has none. At the true position of a point the sum is large. At every wrong position the good pattern makes the sum the same small constant, which can be removed. So each point comes back sharp, and nothing is left over.

When it applies

Setting. The radiation travels in straight lines and cannot be bent by a lens: hard X-rays, gamma rays, neutrons, and some visible light settings without lenses. The scene is far away compared with the mask, so a source at angle θ\theta casts the mask shadow shifted by Dtan⁡θD\tan\theta, with DD the distance from mask to detector. The angular resolution is about the hole size divided by DD.

The cyclic model. Let the basic array AA have vv cells with values in {0,1}\{0, 1\} (open or closed) and kk open cells, with indices in Zv\mathbb{Z}_v or in Zr×Zs\mathbb{Z}_r \times \mathbb{Z}_s. If the mask is a 2×22 \times 2 mosaic of the basic array and the detector has the size of one period, then each source in the fully coded field of view casts a complete cyclic shift of AA on the detector. For an object OO on the same grid the detector record is the circular convolution

P(j)=∑iO(i) A(j−i)+B(j)+noise,P(j) = \sum_i O(i)\,A(j - i) + B(j) + \text{noise},

where BB is the background. Without background and noise, P=A⊛OP = A \circledast O.

The URA property. Write (F⋆H)(d)=∑tF(t)H(t+d)(F \star H)(d) = \sum_t F(t)H(t + d) for the periodic cross-correlation. AA is a URA if its support is a cyclic (v,k,λ)(v, k, \lambda) difference set: every nonzero difference occurs exactly λ\lambda times among the open cells, that is

A⋆A=(k−λ) δ+λ.A \star A = (k - \lambda)\,\delta + \lambda.

The arrays used here have v=2k+1v = 2k + 1 and λ=(k−1)/2\lambda = (k - 1)/2. For the decoding array G=2A−1G = 2A - 1 (open +1+1, closed −1-1),

A⋆G=2(A⋆A)−k=2(k−λ)δ+2λ−k=(k+1) δ−1.A \star G = 2(A \star A) - k = 2(k - \lambda)\delta + 2\lambda - k = (k + 1)\,\delta - 1.

Exact decoding. Correlate the noiseless record with GG:

C(s)=∑jP(j) G(j−s)=∑iO(i) (A⋆G)(i−s)=(k+1) O(s)−∑iO(i).C(s) = \sum_j P(j)\,G(j - s) = \sum_i O(i)\,(A \star G)(i - s) = (k + 1)\,O(s) - \sum_i O(i).

Each object cell adds kk counts, so S=∑jP(j)=k∑iO(i)S = \sum_j P(j) = k\sum_i O(i), and

O(s)=C(s)+S/kk+1.O(s) = \frac{C(s) + S/k}{k + 1}.

Equivalently, the circulant matrix of AA has the power spectrum k2k^2 at frequency 0 and k−λk - \lambda at every other frequency, which is flat; the correlation with GG applies its inverse up to the known constant term.

The template

  1. CODED-APERTURE(O, v)
  2. 1A ← a 0/1 array of v cells with A ⋆ A = (k − λ)δ + λ and 2λ = k − 1 ▷ hole: the array family
  3. 2P ← A ⊛ O, the cyclic shadow on the detector ▷ the instrument
  4. 3G ← 2A − 1
  5. 4k ← Σ A; S ← Σ P
  6. 5for each shift s
  7. 6C(s) ← Σ_j P(j) G(j − s mod v)
  8. 7Ô(s) ← (C(s) + S/k) / (k + 1)
  9. 8return Ô

Line L2 is the measurement; the reconstruction is lines L3 to L8. The direct sums cost O(v2)O(v^2) operations. By the convolution theorem the correlation of line L6 for all ss costs O(vlog⁡v)O(v\log v) with the FFT. The implementation works with exact integers and returns fractions, so the delta property and the exact recovery can be checked without rounding.

Classic examples

Quadratic residues. For a prime p≡3(mod4)p \equiv 3 \pmod 4, let A(j)=1A(j) = 1 when jj is a nonzero quadratic residue mod pp, that is when the Legendre symbol (j/p)=1(j/p) = 1. Then k=(p−1)/2k = (p - 1)/2 and the support is a (p,(p−1)/2,(p−3)/4)(p, (p-1)/2, (p-3)/4) difference set.

Proof. Let N(d)N(d) be the number of pairs (a,b)(a, b) of nonzero squares with a−b=da - b = d. Multiplication by a nonzero square cc maps the squares onto themselves, so N(cd)=N(d)N(cd) = N(d): NN is constant on the squares and constant on the non-squares. The swap (a,b)↦(b,a)(a, b) \mapsto (b, a) gives N(−d)=N(d)N(-d) = N(d), and −1-1 is a non-square for p≡3(mod4)p \equiv 3 \pmod 4, so NN takes one value λ\lambda on all d≠0d \ne 0. There are k(k−1)k(k - 1) ordered pairs with a≠ba \ne b, so (p−1)λ=k(k−1)(p - 1)\lambda = k(k - 1) and λ=(k−1)/2=(p−3)/4\lambda = (k - 1)/2 = (p - 3)/4. ■\blacksquare

pp open cells kk λ\lambda A⋆AA \star A A⋆GA \star G
7 {1,2,4}\{1, 2, 4\} 3 1 (3,1,1,1,1,1,1)(3, 1, 1, 1, 1, 1, 1) (3,−1,−1,−1,−1,−1,−1)(3, -1, -1, -1, -1, -1, -1)
11 {1,3,4,5,9}\{1, 3, 4, 5, 9\} 5 2 peak 5, sidelobes 2 peak 5, sidelobes −1-1
19 the 9 squares 9 4 peak 9, sidelobes 4 peak 9, sidelobes −1-1
23 the 11 squares 11 5 peak 11, sidelobes 5 peak 11, sidelobes −1-1

Twin primes. For primes rr and s=r+2s = r + 2, the array on Zr×Zs\mathbb{Z}_r \times \mathbb{Z}_s with A(i,0)=1A(i, 0) = 1 for all ii, A(0,j)=0A(0, j) = 0 for j≠0j \ne 0, and otherwise A(i,j)=1A(i, j) = 1 when (i/r)(j/s)=1(i/r)(j/s) = 1, is a (rs,(rs−1)/2,(rs−3)/4)(rs, (rs - 1)/2, (rs - 3)/4) difference set. For r=5r = 5 it is a 5×75 \times 7 array with k=17k = 17 open cells and all sidelobes of A⋆AA \star A equal to 8. Fenimore and Cannon (1978) used arrays of this kind, which are close to square and so fit a square detector.

A point source. For p=11p = 11 and a single source of strength 7 at cell 4, the record is the mask shifted by 4 and multiplied by 7. The correlation gives C(4)=6⋅7−7=35C(4) = 6 \cdot 7 - 7 = 35 and C(s)=−7C(s) = -7 elsewhere, S=35S = 35, and the formula returns 7 at cell 4 and 0 elsewhere.

Random masks. Dicke (1968) proposed a mask with many randomly placed holes. A random mask has an autocorrelation with a peak and random sidelobes, so correlation decoding leaves artifacts that depend on the scene. A URA removes them.

Variations

  • Modified URAs. Gottesman and Fenimore (1989) gave binary arrays for every prime size, including square p×pp \times p arrays, with a decoding array that differs from 2A−12A - 1 in one cell. Square arrays fit square detectors, and a free choice of size helps the design.
  • Hexagonal and other lattices. Difference sets on hexagonal grids give masks for detectors with hexagonal pixels.
  • Iterative and variational decoding. When the model is not exactly cyclic, because of partial coding at the edge of the field, a mask of finite thickness, detector blur or a near source, correlation is no longer an exact inverse. Then the reconstruction minimizes a data fidelity term with the true forward model, with the Poisson likelihood and MLEM, or with a regularizer as in variational regularization.
  • Lensless cameras. In visible light, masks and diffusers close to a sensor replace the lens. The forward model is a calibrated convolution or a separable matrix, and the image is reconstructed by regularized least squares, often with total variation. Here the mask need not be a URA.
  • Compressive designs. Coded apertures combined with fewer measurements than unknowns lead to compressed sensing and to the single-pixel camera, which codes in time instead of space.

Pitfalls

  • The noise is spread over all pixels. With Poisson counts and G=±1G = \pm 1, Var⁡C(s)=∑jEP(j)=k∑iO(i)+∑jB(j)\operatorname{Var}C(s) = \sum_j \mathbb{E}P(j) = k\sum_i O(i) + \sum_j B(j), the total number of counts, for every ss. A faint source next to a bright one, or a source on a large diffuse background, gets the noise of the whole scene. For a single point source the coded aperture gains about a factor k\sqrt{k} in signal to noise ratio over a pinhole of the same size; for a scene with more than about kk bright cells of similar strength the gain falls below 1.
  • The fully coded field of view. Sources outside the field where they cast a complete cyclic shift produce shadows that are not cyclic, and correlation decoding then makes ghost images. Shielding or a model based reconstruction is needed.
  • Near sources. For a source at a finite distance the shadow is magnified, and the decoding array must be scaled to match.
  • Background. A nonuniform background is not removed by the constant term and appears as structure in O^\hat O. It must be measured, for example by rotating the mask, or modeled.
  • Hole size and detector resolution. If the detector pixel is not smaller than the projected hole, the record is blurred and the effective AA is not binary. The decoding must use the blurred pattern.

Code

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.

coded_aperture_imaging.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coded-aperture-imaging/. The authors are listed in prov/RBP3GB.jsonl.
"""Coded aperture imaging with uniformly redundant arrays (URAs).

Arrays are 2D lists of rows with cyclic indices; a 1D array of length v is a
single row. The mask A is 0/1. The detector records the cyclic shadow
P(j) = sum_i O(i) A(j - i), and the decoder correlates P with G = 2A - 1.
If A is a (v, k, lam) cyclic difference set with 2 lam - k = -1, then
(A corr G)(d) = (k + 1) delta(d) - 1, so the decoder returns the object exactly.
"""

from fractions import Fraction

Array = list[list[int]]


def legendre(a: int, p: int) -> int:
    """Legendre symbol (a / p) for an odd prime p, by Euler's criterion."""
    a %= p
    if a == 0:
        return 0
    return 1 if pow(a, (p - 1) // 2, p) == 1 else -1


def is_prime(n: int) -> bool:
    if n < 2:
        return False
    d = 2
    while d * d <= n:
        if n % d == 0:
            return False
        d += 1
    return True


def quadratic_residue_ura(p: int) -> Array:
    """1D URA of length p: A(j) = 1 for the nonzero squares mod p.

    For a prime p = 3 mod 4 the squares form a (p, (p-1)/2, (p-3)/4)
    cyclic difference set.
    """
    if not is_prime(p) or p % 4 != 3:
        raise ValueError("p must be a prime with p % 4 == 3")
    return [[1 if legendre(j, p) == 1 else 0 for j in range(p)]]  # @line L1


def twin_prime_ura(r: int) -> Array:
    """r x (r + 2) URA from twin primes r and s = r + 2.

    A(i, 0) = 1 for every i, A(0, j) = 0 for j != 0, and otherwise
    A(i, j) = 1 when (i / r)(j / s) = 1. This is a (rs, (rs-1)/2, (rs-3)/4)
    difference set in Z_r x Z_s.
    """
    s = r + 2
    if not (is_prime(r) and is_prime(s)) or r < 3:
        raise ValueError("r and r + 2 must be odd primes")
    a = [[0] * s for _ in range(r)]
    for i in range(r):
        for j in range(s):
            if j == 0:
                a[i][j] = 1
            elif i != 0 and legendre(i, r) * legendre(j, s) == 1:
                a[i][j] = 1
    return a  # @line L1


def periodic_correlation(a: Array, b: Array) -> Array:
    """(a corr b)(d) = sum_t a(t) b(t + d) with cyclic indices. Cost O(v^2)."""
    n1, n2 = len(a), len(a[0])
    return [[sum(a[t1][t2] * b[(t1 + d1) % n1][(t2 + d2) % n2]
                 for t1 in range(n1) for t2 in range(n2))
             for d2 in range(n2)] for d1 in range(n1)]


def encode(o: Array, a: Array) -> Array:
    """Cyclic shadow P(j) = sum_i O(i) A(j - i). Cost O(v^2)."""
    n1, n2 = len(a), len(a[0])
    return [[sum(o[i1][i2] * a[(j1 - i1) % n1][(j2 - i2) % n2]  # @line L2
                 for i1 in range(n1) for i2 in range(n2))
             for j2 in range(n2)] for j1 in range(n1)]


def adjoint_encode(p: Array, a: Array) -> Array:
    """Adjoint of encode: (A^T P)(i) = sum_j P(j) A(j - i)."""
    n1, n2 = len(a), len(a[0])
    return [[sum(p[j1][j2] * a[(j1 - i1) % n1][(j2 - i2) % n2]
                 for j1 in range(n1) for j2 in range(n2))
             for i2 in range(n2)] for i1 in range(n1)]


def decoding_array(a: Array) -> Array:
    """Balanced decoding array G = 2A - 1."""
    return [[2 * x - 1 for x in row] for row in a]  # @line L3


def decode_scaled(p: Array, a: Array) -> Array:
    """Return k (k + 1) times the decoded object: k C(s) + S.

    For integer data the result is an integer array; it equals
    k (k + 1) O exactly when P = encode(O, A) and A is a URA.
    """
    g = decoding_array(a)
    n1, n2 = len(a), len(a[0])
    k = sum(map(sum, a))  # @line L4
    total = sum(map(sum, p))  # @line L4
    out = [[0] * n2 for _ in range(n1)]
    for s1 in range(n1):  # @line L5
        for s2 in range(n2):  # @line L5
            c = sum(p[j1][j2] * g[(j1 - s1) % n1][(j2 - s2) % n2]  # @line L6
                    for j1 in range(n1) for j2 in range(n2))
            out[s1][s2] = k * c + total  # @line L7
    return out


def decode(p: Array, a: Array) -> list[list[Fraction]]:
    """Decoded object O^(s) = (C(s) + S / k) / (k + 1), as exact fractions."""
    k = sum(map(sum, a))
    scaled = decode_scaled(p, a)
    return [[Fraction(x) / (k * (k + 1)) for x in row] for row in scaled]  # @line L8
test_coded_aperture_imaging.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coded-aperture-imaging/. The authors are listed in prov/RBP3GB.jsonl.

import random
from fractions import Fraction

from coded_aperture_imaging import (
    adjoint_encode,
    decode,
    decode_scaled,
    decoding_array,
    encode,
    is_prime,
    legendre,
    periodic_correlation,
    quadratic_residue_ura,
    twin_prime_ura,
)


def shape(a):
    return len(a), len(a[0])


def delta_plus_constant(peak, side, n1, n2):
    return [[peak if (d1, d2) == (0, 0) else side for d2 in range(n2)] for d1 in range(n1)]


def all_uras():
    out = [quadratic_residue_ura(p) for p in (3, 7, 11, 19, 23, 31, 43)]
    out += [twin_prime_ura(r) for r in (3, 5, 11)]
    return out


def test_legendre_matches_squares():
    for p in range(3, 60):
        if not is_prime(p):
            continue
        squares = {(x * x) % p for x in range(1, p)}
        for a in range(p):
            want = 0 if a == 0 else (1 if a in squares else -1)
            assert legendre(a, p) == want


def test_quadratic_residue_sets():
    assert quadratic_residue_ura(7) == [[0, 1, 1, 0, 1, 0, 0]]
    assert [j for j, x in enumerate(quadratic_residue_ura(11)[0]) if x] == [1, 3, 4, 5, 9]


def test_autocorrelation_is_delta_plus_constant():
    # A corr A = (k - lam) delta + lam, exact integers, with 2 lam = k - 1.
    for a in all_uras():
        n1, n2 = shape(a)
        v = n1 * n2
        k = sum(map(sum, a))
        assert 2 * k == v - 1
        lam = (k - 1) // 2
        assert periodic_correlation(a, a) == delta_plus_constant(k, lam, n1, n2)


def test_balanced_correlation_is_delta():
    # A corr G = (k + 1) delta - 1 for G = 2A - 1: the peak is k, the sidelobes are -1.
    for a in all_uras():
        n1, n2 = shape(a)
        k = sum(map(sum, a))
        g = decoding_array(a)
        assert periodic_correlation(a, g) == delta_plus_constant(k, -1, n1, n2)


def test_twin_prime_parameters():
    a = twin_prime_ura(5)
    assert shape(a) == (5, 7)
    assert sum(map(sum, a)) == 17
    side = {x for row in periodic_correlation(a, a) for x in row[1:]}
    assert side == {8}


def test_exact_decoding_of_integer_objects():
    rng = random.Random(20261120)
    for a in all_uras():
        n1, n2 = shape(a)
        k = sum(map(sum, a))
        for _ in range(3):
            o = [[rng.randint(0, 50) for _ in range(n2)] for _ in range(n1)]
            p = encode(o, a)
            assert sum(map(sum, p)) == k * sum(map(sum, o))
            assert decode_scaled(p, a) == [[k * (k + 1) * x for x in row] for row in o]
            assert decode(p, a) == [[Fraction(x) for x in row] for row in o]


def test_point_source():
    a = quadratic_residue_ura(11)
    o = [[0] * 11]
    o[0][4] = 7
    p = encode(o, a)
    # the shadow is the mask shifted by 4 and scaled by 7
    assert p == [[7 * a[0][(j - 4) % 11] for j in range(11)]]
    assert decode(p, a) == [[Fraction(x) for x in o[0]]]


def test_adjoint():
    rng = random.Random(7)
    for a in (quadratic_residue_ura(19), twin_prime_ura(3)):
        n1, n2 = shape(a)
        o = [[rng.randint(-9, 9) for _ in range(n2)] for _ in range(n1)]
        q = [[rng.randint(-9, 9) for _ in range(n2)] for _ in range(n1)]
        lhs = sum(x * y for r1, r2 in zip(encode(o, a), q) for x, y in zip(r1, r2))
        rhs = sum(x * y for r1, r2 in zip(o, adjoint_encode(q, a)) for x, y in zip(r1, r2))
        assert lhs == rhs


def test_random_mask_is_not_a_ura():
    rng = random.Random(3)
    a = [[rng.randint(0, 1) for _ in range(11)]]
    while sum(a[0]) != 5:
        a = [[rng.randint(0, 1) for _ in range(11)]]
    side = {x for x in periodic_correlation(a, a)[0][1:]}
    assert len(side) > 1
    o = [[rng.randint(0, 50) for _ in range(11)]]
    assert decode(encode(o, a), a) != [[Fraction(x) for x in o[0]]]


def test_bad_sizes_raise():
    for bad in (13, 9, 2):
        try:
            quadratic_residue_ura(bad)
        except ValueError:
            pass
        else:
            raise AssertionError(bad)
    try:
        twin_prime_ura(7)
    except ValueError:
        pass
    else:
        raise AssertionError(7)


if __name__ == "__main__":
    for name, fn in list(globals().items()):
        if name.startswith("test_"):
            fn()
    print("ok")

Exercises

  1. Show that A⋆A=(k−λ)δ+λA \star A = (k - \lambda)\delta + \lambda is equivalent to the statement that every nonzero difference a−ba - b of open cells occurs exactly λ\lambda times.
  2. Show that for a (v,k,λ)(v, k, \lambda) difference set λ(v−1)=k(k−1)\lambda(v - 1) = k(k - 1), and that 2λ−k=−12\lambda - k = -1 forces v=2k+1v = 2k + 1.
  3. Compute the URA for p=7p = 7, the record of the object O=(0,2,0,0,5,0,1)O = (0, 2, 0, 0, 5, 0, 1) and its decoding by the formula of line L7.
  4. Prove that the discrete Fourier transform of a URA has ∣A^(ω)∣2=k−λ|\hat A(\omega)|^2 = k - \lambda for every ω≠0\omega \ne 0. What is the condition number of the circulant matrix of AA?
  5. Under Poisson noise, compute the signal to noise ratio of O^(s)\hat O(s) for a point source with NN counts on a uniform background of bb counts per detector cell, and compare it with a single pinhole.

References

  1. Robert H. Dicke, Scatter-hole cameras for X-rays and gamma rays, Astrophysical Journal 153, 1968, page L101 (a mask with many randomly placed pinholes in place of one pinhole)
  2. Edward E. Fenimore and Thomas M. Cannon, Coded aperture imaging with uniformly redundant arrays, Applied Optics 17(3), 1978, article from page 337 (the URA from twin primes, the mosaic mask and correlation decoding with flat sidelobes)
  3. Stephen R. Gottesman and Edward E. Fenimore, New family of binary arrays for coded aperture imaging, Applied Optics 28(20), 1989, article from page 4344 (modified URAs of every prime size)
  4. Ezio Caroli, John B. Stephen, Guido Di Cocco, Lorenzo Natalucci and Angela Spizzichino, Coded aperture imaging in X- and gamma-ray astronomy, Space Science Reviews 45(3-4), 1987, pages 349 to 403 (survey of mask patterns, decoding and noise)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples