Algorithm Search⌘K

Algorithmadvanced

Goldstein branch cut algorithm

Also called branch cut phase unwrapping.

Unwrap a 2D phase by connecting residues of opposite sign with cuts and integrating along paths that do not cross the cuts.

Time
O(N + R b^3 + R sqrt(N)) worst
Space
O(N) extra
Where
N = the number of pixels; R = the number of residues; b = the largest box radius
Properties
congruentdeterministicnot exactiterative
Origin
Richard M. Goldstein, Howard A. Zebker, Charles L. Werner, 1988

The Goldstein branch cut algorithm unwraps a two-dimensional phase image by integrating the wrapped differences of neighbouring pixels along paths that never cross a set of cuts. A residue is a 2×22 \times 2 square of pixels whose wrapped differences sum to ±2π\pm 2\pi. A path that goes around a residue gains or loses one turn, so the integral would depend on the path. Goldstein, Zebker and Werner (1988) join each residue to residues of opposite sign, or to the border, by cuts, so that every group of joined residues is neutral or ends at the border. Then no closed path that avoids the cuts encloses a net charge, and a breadth first search over the free edges gives a result that does not depend on the path and differs from the data only by multiples of 2π2\pi. The method is fast and local. Its weak point is the placement of the cuts, which is greedy. The cuts are not the shortest possible, and finding the result with the fewest bad edges is NP-hard. It is a classic answer to the phase unwrapping problem, especially in SAR interferometry.

In plain words

A wrapped phase only shows each value up to whole turns. If you walk across the image and add up the small wrapped steps between neighbours, you get the true phase back, as long as no step is larger than half a turn.

Noise and real jumps break this at a few points, the residues. Walk around a residue and you come back one turn higher or lower than where you started. The algorithm builds fences, the cuts, between residues of opposite sign, or from a residue to the edge of the image. Then it walks only along paths that do not cross a fence. Every closed walk of this kind adds up to zero, so the answer does not depend on the route.

The problem

Input. A wrapped phase image ψ(i,j)∈(−π,π]\psi(i, j) \in (-\pi, \pi] on an m×nm \times n grid with N=mnN = mn pixels, and a largest box radius bb. W(x)=x−2πkW(x) = x - 2\pi k with the integer kk that puts the value in (−π,π](-\pi, \pi].

Residues. For the square with the corners (r,c)(r, c), (r,c+1)(r, c+1), (r+1,c+1)(r+1, c+1) and (r+1,c)(r+1, c), in this order, the charge is

q(r,c)=12π∑4 edgesW(ψ(next corner)−ψ(corner))∈{−1,0,1}.q(r, c) = \frac{1}{2\pi} \sum_{\text{4 edges}} W(\psi(\text{next corner}) - \psi(\text{corner})) \in \{-1, 0, 1\}.

Output. A set of blocked edges (the cuts) and an image φ\varphi with φ−ψ∈2πZ\varphi - \psi \in 2\pi\mathbb{Z} at every pixel, such that φ(b)−φ(a)=W(ψ(b)−ψ(a))\varphi(b) - \varphi(a) = W(\psi(b) - \psi(a)) on every edge that is not blocked. The goal is to block few edges, and to block them where the true phase really jumps.

The algorithm

  1. GOLDSTEIN(ψ, b)
  2. 1q ← charges of all 2 × 2 squares
  3. for each residue s0 in raster order that is not in a tree
  4. 2tree ← [s0]
  5. 3charge ← q(s0)
  6. 4for k ← 1 to b while charge ≠ 0
  7. for each t in tree while charge ≠ 0
  8. 5for each residue u not in a tree in the box of radius k around t
  9. 6cut from t to u; add u to tree; charge ← charge + q(u)
  10. 7if charge ≠ 0 and the box passes the border: cut from t to the border; charge ← 0
  11. 8k ← k + 1
  12. 9if charge ≠ 0: cut from s0 to the border
  13. 10flood fill over the free edges: φ(next) ← φ(current) + W(ψ(next) - ψ(current))
  14. 11return φ and the cuts

A cut is a chain of squares. Each step from one square to the next blocks the pixel edge that they share, so the cut is a fence that the flood fill of line L10 cannot cross. The cut of line L6 is a staircase, first along the rows and then along the columns. A cut to the border goes straight to the nearest side and blocks the last edge on the border too. Each region of pixels joined by free edges starts at its first pixel in raster order, with φ=ψ\varphi = \psi there.

The box is the set of squares at Chebyshev distance at most kk from a member of the tree. The box grows only when no member of the tree has found a partner at the present size, so close residues are joined first.

Example

An adjacent dipole. Take a 4×54 \times 5 image of zeros with ψ(1,2)=−2\psi(1, 2) = -2 and ψ(2,2)=2\psi(2, 2) = 2. The true difference across the edge from (1,2)(1, 2) to (2,2)(2, 2) is 4, which is more than π\pi, and it wraps to 4−2π4 - 2\pi. Line L1 finds two residues, q(1,1)=−1q(1, 1) = -1 and q(1,2)=+1q(1, 2) = +1, the two squares on either side of that edge. Line L2 starts a tree at (1,1)(1, 1), and line L5 finds (1,2)(1, 2) in the box of radius 1. Line L6 steps from square (1,1)(1, 1) to square (1,2)(1, 2) and blocks the one edge they share, which is the edge from (1,2)(1, 2) to (2,2)(2, 2). The charge is 0 and the search stops. Line L10 reaches (2,2)(2, 2) around the cut and gets φ(2,2)−φ(1,2)=4\varphi(2, 2) - \varphi(1, 2) = 4, the true difference. One edge disagrees with its wrapped difference, which is the minimum.

Greedy cuts are not shortest. Take the 3×43 \times 4 image

ψ=(1.86−1.671.17−0.71−2.62−0.43−1.892.22.241.742.192.8).\psi = \begin{pmatrix} 1.86 & -1.67 & 1.17 & -0.71 \\ -2.62 & -0.43 & -1.89 & 2.2 \\ 2.24 & 1.74 & 2.19 & 2.8 \end{pmatrix}.

Its squares have the charges +1+1 at (0,2)(0, 2), −1-1 at (1,1)(1, 1) and +1+1 at (1,0)(1, 0). The raster order meets (0,2)(0, 2) first, and its box of radius 1 holds (1,1)(1, 1). The staircase cut blocks two edges. Then (1,0)(1, 0) has no free partner, its box passes the border, and line L7 blocks one more edge, to the bottom. That is three blocked edges and an L0 cost of 3. Joining (1,0)(1, 0) to (1,1)(1, 1) (one edge) and (0,2)(0, 2) to the top border (one edge) gives cost 2, and an exhaustive search over all congruent results confirms that 2 is the minimum.

Correctness

The proofs are in proofs/correctness.md. Items 1 to 5 below are theorems. The quality of the cut placement is a heuristic.

  1. Loop sums are enclosed charge. For any closed walk γ\gamma on the pixel grid, the sum of the wrapped differences along γ\gamma is 2π∑fwγ(f)q(f)2\pi \sum_f w_\gamma(f) q(f), where wγ(f)w_\gamma(f) is the winding number of γ\gamma around square ff.
  2. The cut invariant. After line L9, every connected group of squares joined by cuts that contains a residue has total charge 0 or is joined to the border. A tree stops only when its charge is 0 (lines L4 and L5) or when a member is cut to the border (lines L7 and L9).
  3. Path independence. A closed walk that uses only free edges cannot cross a cut, so its winding number is the same on all the squares of one group, and 0 on a group that touches the border. By 1 and 2, its loop sum is 0.
  4. What the flood fill returns. By 3, every free edge inside a region has φ(b)−φ(a)=W(ψ(b)−ψ(a))\varphi(b) - \varphi(a) = W(\psi(b) - \psi(a)), not only the edges of the search tree. Every pixel has φ−ψ∈2πZ\varphi - \psi \in 2\pi\mathbb{Z}. Another seed changes a region only by a constant multiple of 2π2\pi.
  5. Exact without residues. Then nothing is blocked, and if the true phase changes by less than π\pi between neighbours (Itoh's condition), the output is the true phase plus 2πk2\pi k.

The theorems say nothing about the blocked edges. Whether the cuts lie where the true phase really jumps is not proven, and the L0 cost of the output, the number of edges that disagree with their wrapped difference, is not minimal in general.

Proof: After Goldstein's cuts every closed path of free edges has a zero sum of wrapped differences, so the flood fill is independent of the path, congruent to the data and exact on every free edgefull

Notation. The image has m×nm \times n pixels and N=mnN = mn. A primal edge joins two neighbouring pixels. For an edge walked from aa to bb, g(a,b)=W(ψ(b)−ψ(a))g(a, b) = W(\psi(b) - \psi(a)), so g(b,a)=−g(a,b)g(b, a) = -g(a, b) except when ψ(b)−ψ(a)=±π\psi(b) - \psi(a) = \pm\pi exactly; we assume, as the code does implicitly, that no wrapped difference is exactly ±π\pm \pi (this holds with probability one for noisy data). A square ff is a 2×22 \times 2 block of pixels, and q(f)q(f) is its charge from line L1: the sum of gg around ff in the fixed orientation, divided by 2π2\pi. The cut graph has the squares as nodes and a node for the outside; two squares (or a square and the outside) are joined when the primal edge between them is blocked. Line L10 runs on the free (not blocked) edges.

Lemma 1 (charges). q(f)q(f) is an integer, and ∣q(f)∣≤1|q(f)| \le 1.

Proof. Around ff, the true differences ψ(b)−ψ(a)\psi(b) - \psi(a) sum to zero, and each gg differs from them by a multiple of 2π2\pi, so the sum of gg is a multiple of 2π2\pi. Each of the four terms lies in (−π,π)(-\pi, \pi), so the sum lies in (−4π,4π)(-4\pi, 4\pi), and the multiple is −1-1, 00 or 11. □\square

Lemma 2 (loop sums are enclosed charge). For a closed walk γ\gamma along primal edges, ∑γg=2π∑fwγ(f) q(f)\sum_{\gamma} g = 2\pi \sum_f w_\gamma(f)\, q(f), where wγ(f)w_\gamma(f) is the winding number of γ\gamma around the center of ff.

Proof. Consider the integer combination Γ=∑fwγ(f) ∂f\Gamma = \sum_f w_\gamma(f)\, \partial f of square boundaries. An edge ee lies between two squares ff and f′f' (or between a square and the outside, whose winding number is 0), and its coefficient in Γ\Gamma is wγ(f)−wγ(f′)w_\gamma(f) - w_\gamma(f') with the sign of the orientation. Crossing ee changes the winding number by the net number of times γ\gamma traverses ee, so this coefficient equals the net number of traversals of ee by γ\gamma. So γ\gamma and Γ\Gamma traverse every edge the same net number of times, and since gg is antisymmetric, ∑γg=∑fwγ(f)∑∂fg=2π∑fwγ(f)q(f)\sum_\gamma g = \sum_f w_\gamma(f) \sum_{\partial f} g = 2\pi \sum_f w_\gamma(f) q(f). □\square

Lemma 3 (the cut invariant). When line L9 is done, every connected component KK of the cut graph that contains a residue either has total charge q(K)=∑f∈Kq(f)=0q(K) = \sum_{f \in K} q(f) = 0 or contains the outside node.

Proof. Lines L2 to L9 put every residue in exactly one tree: a residue joins a tree only if it is not yet in one, and the loop of line L2 starts a tree at every residue that is not yet in one. Line L6 joins the new residue uu to a member tt of the tree by a staircase path of squares, and blocks the edge crossed by each step, so tt and uu are in one component of the cut graph. So each tree lies inside one component. A tree ends in one of two states. Either its charge counter is 0, and then the sum of its charges is 0, since the counter adds the charge of each residue when it joins. Or line L7 or line L9 has cut a member of the tree to the border, along a straight path whose last step blocks a boundary edge, which joins the tree to the outside node. A component KK is a union of whole trees and of squares without charge. If one of its trees is cut to the border, KK contains the outside node. Otherwise all its trees have charge sum 0, and so q(K)=0q(K) = 0. □\square

Theorem 1 (path independence). For every closed walk γ\gamma that uses only free edges, ∑γg=0\sum_\gamma g = 0.

Proof. Two squares joined by a blocked edge ee have the same winding number, because γ\gamma does not use ee and crossing ee does not change wγw_\gamma. In the same way a square joined to the outside by a blocked boundary edge has wγ=0w_\gamma = 0. So wγw_\gamma is constant on each component KK of the cut graph, with the value 0 when KK contains the outside node. By Lemma 2, ∑γg=2π∑Kwγ(K) q(K)\sum_\gamma g = 2\pi \sum_K w_\gamma(K)\, q(K), summed over the components that contain a residue (the other squares have charge 0). By Lemma 3 every term has q(K)=0q(K) = 0 or wγ(K)=0w_\gamma(K) = 0. □\square

Theorem 2 (what the flood fill returns). Let RR be a region of pixels joined by free edges, and let ss be its seed. Line L10 gives (a) φ(b)−φ(a)=g(a,b)\varphi(b) - \varphi(a) = g(a, b) for every free edge (a,b)(a, b) inside RR, (b) φ(p)−ψ(p)∈2πZ\varphi(p) - \psi(p) \in 2\pi\mathbb{Z} for every pp, and (c) for another seed s′s' of RR, the new result differs from φ\varphi on RR by a constant multiple of 2π2\pi.

Proof. (a) On the edges of the breadth first search tree, (a) holds by line L10. For any other free edge (a,b)(a, b) of RR, the tree path from ss to aa, the edge (a,b)(a, b) and the tree path from bb back to ss form a closed walk of free edges; by Theorem 1 its sum of gg is 0, and the two tree paths contribute φ(a)−φ(s)\varphi(a) - \varphi(s) and φ(s)−φ(b)\varphi(s) - \varphi(b), so g(a,b)=φ(b)−φ(a)g(a, b) = \varphi(b) - \varphi(a). (b) φ(s)=ψ(s)\varphi(s) = \psi(s), and each step of line L10 adds W(ψ(b)−ψ(a))≡ψ(b)−ψ(a)(mod2π)W(\psi(b) - \psi(a)) \equiv \psi(b) - \psi(a) \pmod{2\pi}. (c) Both results satisfy (a) on the connected region RR, so their difference is constant on RR; by (b) both are congruent to ψ\psi, so the constant is a multiple of 2π2\pi. □\square

Corollary (exact without residues). If no square has a residue, no edge is blocked, the image is one region, and φ\varphi is the unique image up to a multiple of 2π2\pi that is congruent to ψ\psi and satisfies φ(b)−φ(a)=g(a,b)\varphi(b) - \varphi(a) = g(a, b) on every edge. If the true phase φ∗\varphi^* changes by less than π\pi across every edge (Itoh's condition), then φ=φ∗+2πk\varphi = \varphi^* + 2\pi k for one integer kk.

Proof. Lines L2 to L9 do nothing without residues. Under Itoh's condition, g(a,b)=φ∗(b)−φ∗(a)g(a, b) = \varphi^*(b) - \varphi^*(a), so φ−φ∗\varphi - \varphi^* is constant by Theorem 2(a), and a multiple of 2π2\pi by Theorem 2(b), since φ∗≡ψ\varphi^* \equiv \psi. □\square

What the theorems do not say. The L0 cost of the result, the number of edges with φ(b)−φ(a)≠g(a,b)\varphi(b) - \varphi(a) \ne g(a, b), is at most the number of blocked edges by Theorem 2(a), and at least 1 when a residue exists (otherwise Lemma 2 with the boundary of that square gives a contradiction). It is not minimal in general. Minimizing it over congruent results is NP-hard (Chen and Zebker 2000). On the 3×43 \times 4 image of the test with charges +1+1 at square (0,2)(0, 2), −1-1 at (1,1)(1, 1) and +1+1 at (1,0)(1, 0), Goldstein's order of search pairs (0,2)(0, 2) with (1,1)(1, 1) (two blocked edges) and sends (1,0)(1, 0) to the border (one more), cost 3, while the cut from (1,0)(1, 0) to (1,1)(1, 1) and from (0,2)(0, 2) to the top border gives cost 2; an exhaustive search over all congruent results confirms the minimum 2. Theorem 2 also says nothing about the correctness of the 2π2\pi multiples on blocked edges; whether the cuts lie where the true phase really jumps is a heuristic matter.

Theorem 3 (termination and cost). Let RR be the number of residues and bb the largest box radius. In the word-RAM model, with a Boolean array for the blocked edges, the algorithm takes O(N+Rb3+RN)O(N + R b^3 + R \sqrt{N}) time and O(N)O(N) space.

Proof. Line L1 visits each square once, O(N)O(N). Each residue joins exactly one tree, so the trees have RR members in total. A member is scanned with boxes of radius k≤bk \le b, each of O(k2)O(k^2) squares, at most once per radius, so the box scans cost O(R∑k≤bk2)=O(Rb3)O(R \sum_{k \le b} k^2) = O(R b^3). A cut of line L6 joins squares at Chebyshev distance at most kk, so it blocks at most 2k=O(b)2k = O(b) edges, and there are at most RR such cuts. A cut to the border goes straight to the nearest side, at most min⁡(m,n)≤N\min(m, n) \le \sqrt{N} edges, at most once per tree. Lines L4 to L8 end because kk grows to bb. The flood fill of line L10 enqueues every pixel once and looks at four edges per pixel, O(N)O(N). The charges, the tree marks, the blocked edges, the labels and φ\varphi take O(N)O(N) space. □\square

Complexity

In the word-RAM model, with Boolean arrays for the charges, the tree marks and the blocked edges, line L1 and the flood fill of line L10 cost O(N)O(N). Each residue joins exactly one tree. The scans of the boxes cost O(k2)O(k^2) per member and radius, O(Rb3)O(R b^3) in total. A cut of line L6 has at most 2b2b edges, and a cut to the border at most min⁡(m,n)≤N\min(m, n) \le \sqrt{N}, at most once per tree. So the worst case time is O(N+Rb3+RN)O(N + R b^3 + R \sqrt{N}) and the extra space is O(N)O(N). When the residues are sparse, the time is close to O(N)O(N).

Properties

  • Congruent (theorem). The output differs from the data by multiples of 2π2\pi at every pixel, unlike least squares unwrapping.
  • Path independent (theorem). The result in each region is fixed up to one multiple of 2π2\pi, whatever the order of the search.
  • Exact where it is free (theorem). Every free edge keeps its wrapped difference, so all the errors sit on the cuts.
  • Not optimal (theorem for the example). The greedy order can give longer cuts than needed, as in the 3×43 \times 4 example. In 200 random 3×43 \times 4 images with independent uniform phases (seed 9001), 180 had residues. The output reached the minimum L0 cost in 164 of them and was worse in 16 (measurement).
  • Holes. A region closed off by cuts gets its own constant. Its relation to the rest of the image is lost.
  • Deterministic. The result depends on the raster order of the residues and on the box radius bb.

Variants and improvements

  • Quality maps and masks. Residues on the border of a mask, or in regions of low coherence, are joined to the mask edge. The flood fill can visit the pixels in the order of a quality map, so that errors stay in the bad regions.
  • Balancing to the border first. Residues near the border are often joined to it straight away. This avoids long cuts between residues that are far apart.
  • Shortest cuts. Choosing the cuts of least total length is a minimum weight matching of the residues, with the border as a free partner. The minimum L1 problem is a minimum cost flow problem on the grid of squares (Costantini 1998). Flynn (1997) gives an exact method for the minimum weighted discontinuity problem. The minimum L0 problem is NP-hard (Chen and Zebker 2000).
  • Other path-following methods. Quality guided unwrapping without cuts, and mask cut algorithms, are collected with Goldstein's method in the book of Ghiglia and Pritt (1998).
  • Statistical cost functions in SAR use the coherence and a model of the topography to set the cost of each edge.

When to use it

Use it when the result must be congruent to the data, for example to keep the exact 2π2\pi multiples of an interferogram, and when the residues are sparse and in pairs, as in good SAR interferometry data or optical fringe patterns. Avoid it when residues are dense, because the cuts then close off whole regions. Use a minimum cost flow method when the cuts must be short, and least squares unwrapping when a smooth result everywhere matters more than congruence.

Pitfalls

  • Isolated regions. Dense cuts can close off a region. Its offset of 2πk2\pi k against the rest is then arbitrary. Report it, or join it by a quality guided step.
  • Box too small. With b=1b = 1, distant pairs are joined to the border instead of to each other, and the cuts get longer. In the test, two opposite vortices four squares apart need 4 blocked edges as a pair and 8 as two border cuts.
  • Wrong orientation of the charge. All squares must use the same orientation, or opposite charges look equal and are never paired.
  • Cuts that do not block the shared edge. The cut is a chain of squares, and each step must block the pixel edge between those two squares. Blocking pixels instead of edges, or skipping the last border edge, leaves a gap that a path can go through.
  • Seed on a cut. In each region the start value is the wrapped phase itself. Only differences inside a region are meaningful.

Implementations

The Python code stores the cuts as a set of blocked edges, where ('h', i, j) is the edge from (i,j)(i, j) to (i,j+1)(i, j+1) and ('v', i, j) is the edge from (i,j)(i, j) to (i+1,j)(i+1, j). It needs no shared helper. The tests check a single vortex, exact recovery without residues, congruence and exact free edges on random images, the cut invariant for several box sizes, the effect of the box size on two vortices, the adjacent dipole, a lower bound by exhaustive search on tiny images, the non-optimal 3×43 \times 4 example, and the change of seeds.

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.

goldstein_branch_cut.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/goldstein-branch-cut/. The authors are listed in prov/5RF5DV.jsonl.
"""Goldstein branch cut phase unwrapping (Goldstein, Zebker and Werner 1988).

The input is a wrapped phase image psi[i][j] on an m x n grid of pixels. A
residue is a 2 x 2 square of pixels around which the wrapped differences sum to
2 pi q with q = +1 or -1. The method joins residues by branch cuts until every
group of joined residues has total charge zero or touches the border, and then
unwraps by a flood fill that never crosses a cut.

Geometry. Square (r, c) has the corners (r, c), (r, c+1), (r+1, c+1), (r+1, c).
Two neighbouring squares share one primal edge, and a cut that steps from one
square to the next blocks that edge:

    step (r, c) -> (r+1, c) blocks the edge ('h', r+1, c) between (r+1, c) and (r+1, c+1),
    step (r, c) -> (r, c+1) blocks the edge ('v', r, c+1) between (r, c+1) and (r+1, c+1).

A cut to the border leaves the grid through a boundary edge. ('h', i, j) is the
edge between (i, j) and (i, j+1); ('v', i, j) is the edge between (i, j) and (i+1, j).
"""

from collections import deque
import math

TWO_PI = 2.0 * math.pi


def wrap(x):
    """The value of x - 2 pi k in (-pi, pi]."""
    y = math.fmod(x + math.pi, TWO_PI)
    if y <= 0.0:
        y += TWO_PI
    return y - math.pi


def residues(psi):
    """Charges q[r][c] in {-1, 0, 1} of the (m-1) x (n-1) squares, counterclockwise in (row, column) order."""
    m, n = len(psi), len(psi[0])
    q = [[0] * (n - 1) for _ in range(m - 1)]
    for r in range(m - 1):
        for c in range(n - 1):
            s = (wrap(psi[r][c + 1] - psi[r][c]) + wrap(psi[r + 1][c + 1] - psi[r][c + 1])
                 + wrap(psi[r + 1][c] - psi[r + 1][c + 1]) + wrap(psi[r][c] - psi[r + 1][c]))
            q[r][c] = int(round(s / TWO_PI))
    return q


def _cut_between(blocked, a, b):
    """Block the edges crossed by a staircase path of squares from a to b (rows first, then columns)."""
    r, c = a
    r2, c2 = b
    while r != r2:
        step = 1 if r2 > r else -1
        blocked.add(('h', max(r, r + step), c))
        r += step
    while c != c2:
        step = 1 if c2 > c else -1
        blocked.add(('v', r, max(c, c + step)))
        c += step


def _cut_to_border(blocked, s, m, n):
    """Block a straight path from square s to the nearest side of the grid, including the boundary edge."""
    r, c = s
    options = [(r + 1, 'up'), (m - 1 - r, 'down'), (c + 1, 'left'), (n - 1 - c, 'right')]
    _, side = min(options)
    if side == 'up':
        for i in range(r, -1, -1):
            blocked.add(('h', i, c))
    elif side == 'down':
        for i in range(r + 1, m):
            blocked.add(('h', i, c))
    elif side == 'left':
        for j in range(c, -1, -1):
            blocked.add(('v', r, j))
    else:
        for j in range(c + 1, n):
            blocked.add(('v', r, j))


def branch_cuts(q, max_box=None):
    """Goldstein's cut placement. Returns the set of blocked primal edges.

    q is the residue map of an m x n image, so it has m - 1 rows and n - 1 columns.
    max_box is the largest box radius; None means large enough to reach any border.
    """
    rows, cols = len(q), len(q[0])
    m, n = rows + 1, cols + 1
    if max_box is None:
        max_box = max(rows, cols)
    blocked = set()
    in_tree = [[False] * cols for _ in range(rows)]
    for r0 in range(rows):
        for c0 in range(cols):
            if q[r0][c0] == 0 or in_tree[r0][c0]:
                continue
            tree = [(r0, c0)]  # @line L2
            in_tree[r0][c0] = True
            charge = q[r0][c0]  # @line L3
            k = 1
            while charge != 0 and k <= max_box:  # @line L4
                t_idx = 0
                while charge != 0 and t_idx < len(tree):
                    tr, tc = tree[t_idx]
                    for r in range(max(0, tr - k), min(rows, tr + k + 1)):
                        for c in range(max(0, tc - k), min(cols, tc + k + 1)):
                            if charge != 0 and q[r][c] != 0 and not in_tree[r][c]:  # @line L5
                                _cut_between(blocked, (tr, tc), (r, c))  # @line L6
                                in_tree[r][c] = True
                                tree.append((r, c))
                                charge += q[r][c]
                    if charge != 0 and (tr - k < 0 or tc - k < 0 or tr + k >= rows or tc + k >= cols):
                        _cut_to_border(blocked, (tr, tc), m, n)  # @line L7
                        charge = 0
                    t_idx += 1
                k += 1  # @line L8
            if charge != 0:
                _cut_to_border(blocked, (r0, c0), m, n)  # @line L9
    return blocked


def _neighbours(i, j, m, n, blocked):
    """The pixels joined to (i, j) by an edge that is not blocked."""
    out = []
    if j + 1 < n and ('h', i, j) not in blocked:
        out.append((i, j + 1))
    if j > 0 and ('h', i, j - 1) not in blocked:
        out.append((i, j - 1))
    if i + 1 < m and ('v', i, j) not in blocked:
        out.append((i + 1, j))
    if i > 0 and ('v', i - 1, j) not in blocked:
        out.append((i - 1, j))
    return out


def flood_fill_unwrap(psi, blocked, seeds=None):
    """Unwrap psi by breadth first search over the edges that are not blocked.

    Each region of pixels connected by free edges starts from its first pixel in
    the order of seeds (default: raster order), whose value is psi itself.
    Returns (phi, region) where region[i][j] is the index of the region of (i, j).
    """
    m, n = len(psi), len(psi[0])
    phi = [[0.0] * n for _ in range(m)]
    region = [[-1] * n for _ in range(m)]
    order = seeds if seeds is not None else [(i, j) for i in range(m) for j in range(n)]
    label = 0
    for si, sj in order:
        if region[si][sj] >= 0:
            continue
        phi[si][sj] = psi[si][sj]
        region[si][sj] = label
        queue = deque([(si, sj)])
        while queue:
            i, j = queue.popleft()
            for a, b in _neighbours(i, j, m, n, blocked):
                if region[a][b] < 0:
                    phi[a][b] = phi[i][j] + wrap(psi[a][b] - psi[i][j])  # @line L10
                    region[a][b] = label
                    queue.append((a, b))
        label += 1
    return phi, region


def goldstein_unwrap(psi, max_box=None):
    """Return (phi, blocked edges, region labels) for the wrapped image psi."""
    q = residues(psi)  # @line L1
    blocked = branch_cuts(q, max_box)
    phi, region = flood_fill_unwrap(psi, blocked)
    return phi, blocked, region  # @line L11


def cut_components(q, blocked):
    """Group the squares into components joined by blocked edges between them.

    Returns a list of (total charge, touches_border, squares) for the
    components that contain at least one residue.
    """
    rows, cols = len(q), len(q[0])
    m, n = rows + 1, cols + 1
    seen = [[False] * cols for _ in range(rows)]
    out = []
    for r0 in range(rows):
        for c0 in range(cols):
            if seen[r0][c0]:
                continue
            seen[r0][c0] = True
            stack, squares, border = [(r0, c0)], [], False
            while stack:
                r, c = stack.pop()
                squares.append((r, c))
                if (r == 0 and ('h', 0, c) in blocked) or (r == rows - 1 and ('h', m - 1, c) in blocked):
                    border = True
                if (c == 0 and ('v', r, 0) in blocked) or (c == cols - 1 and ('v', r, n - 1) in blocked):
                    border = True
                steps = [((r + 1, c), ('h', r + 1, c)), ((r - 1, c), ('h', r, c)),
                         ((r, c + 1), ('v', r, c + 1)), ((r, c - 1), ('v', r, c))]
                for (a, b), e in steps:
                    if 0 <= a < rows and 0 <= b < cols and not seen[a][b] and e in blocked:
                        seen[a][b] = True
                        stack.append((a, b))
            charge = sum(q[r][c] for r, c in squares)
            if any(q[r][c] != 0 for r, c in squares):
                out.append((charge, border, squares))
    return out


def l0_cost(phi, psi):
    """The number of edges where the unwrapped difference is not the wrapped difference."""
    m, n = len(psi), len(psi[0])
    cost = 0
    for i in range(m):
        for j in range(n):
            if j + 1 < n and abs(phi[i][j + 1] - phi[i][j] - wrap(psi[i][j + 1] - psi[i][j])) > 1e-9:
                cost += 1
            if i + 1 < m and abs(phi[i + 1][j] - phi[i][j] - wrap(psi[i + 1][j] - psi[i][j])) > 1e-9:
                cost += 1
    return cost
test_goldstein_branch_cut.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/goldstein-branch-cut/. The authors are listed in prov/5RF5DV.jsonl.

from itertools import combinations, product
import math
import random

from goldstein_branch_cut import (branch_cuts, cut_components, flood_fill_unwrap, goldstein_unwrap, l0_cost, residues,
                                  wrap)

TWO_PI = 2.0 * math.pi


def _random_psi(rng, m, n):
    return [[rng.uniform(-math.pi, math.pi) for _ in range(n)] for _ in range(m)]


def _min_l0(psi):
    """Exact minimum L0 cost over all congruent unwrappings of a tiny image.

    A congruent unwrapping changes the wrapped difference of edge e by 2 pi n_e
    with integers n_e whose sum around every square cancels its residue. Search
    the supports of increasing size with n_e in {-2, -1, 1, 2}.
    """
    m, n = len(psi), len(psi[0])
    q = residues(psi)
    edges = [('h', i, j) for i in range(m) for j in range(n - 1)] + [('v', i, j) for i in range(m - 1) for j in range(n)]
    faces = []
    for r in range(m - 1):
        for c in range(n - 1):
            faces.append(({('h', r, c): 1, ('v', r, c + 1): 1, ('h', r + 1, c): -1, ('v', r, c): -1}, -q[r][c]))
    for size in range(len(edges) + 1):
        for support in combinations(edges, size):
            for values in product((-2, -1, 1, 2), repeat=size):
                nmap = dict(zip(support, values))
                if all(sum(sgn * nmap.get(e, 0) for e, sgn in f.items()) == want for f, want in faces):
                    return size
    raise AssertionError("unreachable")


def test_wrap() -> None:
    assert abs(wrap(3 * math.pi / 2) + math.pi / 2) < 1e-15
    assert abs(wrap(-math.pi) - math.pi) < 1e-15


def test_a_vortex_has_one_residue() -> None:
    psi = [[math.atan2(i - 1.5, j - 1.5) for j in range(4)] for i in range(4)]
    q = residues(psi)
    assert q[1][1] == 1
    assert sum(abs(v) for row in q for v in row) == 1


def test_no_residues_gives_the_true_phase() -> None:
    m, n = 7, 8
    true = [[0.8 * j - 0.6 * i + 1.2 * math.cos(0.5 * i) * math.sin(0.4 * j) + 5.0 for j in range(n)] for i in range(m)]
    psi = [[wrap(v) for v in row] for row in true]
    phi, blocked, _ = goldstein_unwrap(psi)
    assert not blocked
    k = (phi[0][0] - true[0][0]) / TWO_PI
    assert abs(k - round(k)) < 1e-12
    for i in range(m):
        for j in range(n):
            assert abs(phi[i][j] - true[i][j] - TWO_PI * round(k)) < 1e-9


def test_free_edges_keep_the_wrapped_difference_and_the_result_is_congruent() -> None:
    for seed in range(7401, 7406):
        rng = random.Random(seed)
        m, n = 8, 9
        psi = _random_psi(rng, m, n)
        phi, blocked, region = goldstein_unwrap(psi)
        for i in range(m):
            for j in range(n):
                k = (phi[i][j] - psi[i][j]) / TWO_PI
                assert abs(k - round(k)) < 1e-9
                if j + 1 < n and ('h', i, j) not in blocked:
                    assert region[i][j] == region[i][j + 1]
                    assert abs(phi[i][j + 1] - phi[i][j] - wrap(psi[i][j + 1] - psi[i][j])) < 1e-9
                if i + 1 < m and ('v', i, j) not in blocked:
                    assert abs(phi[i + 1][j] - phi[i][j] - wrap(psi[i + 1][j] - psi[i][j])) < 1e-9


def test_every_cut_component_is_balanced_or_touches_the_border() -> None:
    for seed in range(7411, 7416):
        rng = random.Random(seed)
        psi = _random_psi(rng, 9, 9)
        q = residues(psi)
        for max_box in (1, 2, None):
            blocked = branch_cuts(q, max_box)
            comps = cut_components(q, blocked)
            assert comps
            for charge, border, _ in comps:
                assert charge == 0 or border


def test_box_size_decides_between_a_pair_cut_and_border_cuts() -> None:
    # Two vortices of opposite sign, four squares apart, in a 9 x 12 image.
    m, n = 9, 12
    psi = [[wrap(math.atan2(i - 4.5, j - 3.5) - math.atan2(i - 4.5, j - 7.5)) for j in range(n)] for i in range(m)]
    q = residues(psi)
    assert q[4][3] == 1 and q[4][7] == -1
    assert sum(abs(v) for row in q for v in row) == 2
    pair = branch_cuts(q, None)
    assert len(pair) == 4
    border = branch_cuts(q, 1)
    assert len(border) == 8
    for blocked in (pair, border):
        phi, _ = flood_fill_unwrap(psi, blocked)
        assert l0_cost(phi, psi) <= len(blocked)


def test_an_adjacent_dipole_is_cut_optimally() -> None:
    # The edge between (1, 2) and (2, 2) has the true difference 4, which wraps to
    # 4 - 2 pi: the two squares beside it get charges -1 and +1.
    psi = [[0.0] * 5 for _ in range(4)]
    psi[1][2], psi[2][2] = -2.0, 2.0
    q = residues(psi)
    assert q[1][1] == -1 and q[1][2] == 1
    assert sum(abs(v) for row in q for v in row) == 2
    phi, blocked, _ = goldstein_unwrap(psi)
    assert blocked == {('v', 1, 2)}
    assert l0_cost(phi, psi) == 1 == _min_l0(psi)
    assert abs(phi[2][2] - phi[1][2] - 4.0) < 1e-12


def test_never_below_the_brute_force_minimum_on_tiny_grids() -> None:
    rng = random.Random(7421)
    checked = 0
    while checked < 12:
        psi = _random_psi(rng, 3, 4)
        if all(v == 0 for row in residues(psi) for v in row):
            continue
        phi, _, _ = goldstein_unwrap(psi)
        assert l0_cost(phi, psi) >= _min_l0(psi) >= 1
        checked += 1


def test_greedy_pairing_is_not_optimal() -> None:
    # Residues +1 at (0, 2), -1 at (1, 1) and +1 at (1, 0). Goldstein pairs (0, 2)
    # with (1, 1) by a cut of two edges and sends (1, 0) to the border with one
    # more; pairing (1, 0) with (1, 1) and (0, 2) with the top border needs two.
    psi = [[1.86, -1.67, 1.17, -0.71], [-2.62, -0.43, -1.89, 2.2], [2.24, 1.74, 2.19, 2.8]]
    assert residues(psi) == [[0, 0, 1], [1, -1, 0]]
    phi, blocked, _ = goldstein_unwrap(psi)
    assert blocked == {('h', 1, 2), ('v', 1, 2), ('h', 2, 0)}
    assert l0_cost(phi, psi) == 3
    assert _min_l0(psi) == 2


def test_another_seed_order_changes_each_region_by_a_constant() -> None:
    rng = random.Random(7431)
    m, n = 8, 8
    psi = _random_psi(rng, m, n)
    phi, blocked, region = goldstein_unwrap(psi)
    seeds = [(i, j) for i in range(m - 1, -1, -1) for j in range(n - 1, -1, -1)]
    phi2, region2 = flood_fill_unwrap(psi, blocked, seeds)
    offset = {}
    for i in range(m):
        for j in range(n):
            d = phi2[i][j] - phi[i][j]
            assert abs(d / TWO_PI - round(d / TWO_PI)) < 1e-9
            lab = region[i][j]
            offset.setdefault(lab, d)
            assert abs(offset[lab] - d) < 1e-9
            assert (region2[i][j] == region2[0][0]) == (lab == region[0][0])

History

Itoh (1982) showed that summing wrapped differences gives the true phase when the true differences are less than π\pi. Goldstein, Zebker and Werner (1988) unwrapped satellite radar interferograms. They found that the inconsistencies sit at residues, and they placed branch cuts between them, which made the integration independent of the path. Their method became the reference path-following method, and the book of Ghiglia and Pritt (1998) presents it in detail. Later work set the cut placement as an optimization problem: Flynn (1997) gave an exact method for minimum weighted discontinuity, Costantini (1998) solved the L1 problem as a minimum cost flow, and Chen and Zebker (2000) proved that the L0 problem is NP-hard.

References

  1. Richard M. Goldstein, Howard A. Zebker and Charles L. Werner, Satellite radar interferometry: two-dimensional phase unwrapping, Radio Science 23(4), 1988, 713, residues, branch cuts placed by a search in growing boxes, and integration that does not cross the cuts (general locator)
  2. Kazuyoshi Itoh, Analysis of the phase unwrapping algorithm, Applied Optics 21(14), 1982, 2470, the condition that the true phase differences lie in (-pi, pi) (general locator)
  3. Curtis W. Chen and Howard A. Zebker, Network approaches to two-dimensional phase unwrapping: intractability and two new algorithms, Journal of the Optical Society of America A 17(3), 2000, 401, the NP-hardness of minimum L0 phase unwrapping (general locator)
  4. Thomas J. Flynn, Two-dimensional phase unwrapping with minimum weighted discontinuity, Journal of the Optical Society of America A 14(10), 1997, 2692, an exact method for the minimum weighted discontinuity problem (general locator)
  5. Mario Costantini, A novel phase unwrapping method based on network programming, IEEE Transactions on Geoscience and Remote Sensing 36(3), 1998, 813 to 821, the minimum L1 unwrapping as a minimum cost flow problem (general locator)
  6. Dennis C. Ghiglia and Mark D. Pritt, Two-Dimensional Phase Unwrapping: Theory, Algorithms, and Software, Wiley, 1998, the chapter on path-following methods (Goldstein's branch cut algorithm)

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