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.
- Solves
- Phase unwrapping
- 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
- Model
- Word RAM
- Properties
- congruentdeterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 square of pixels whose wrapped differences sum to . 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 . 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 on an grid with pixels, and a largest box radius . with the integer that puts the value in .
Residues. For the square with the corners , , and , in this order, the charge is
Output. A set of blocked edges (the cuts) and an image with at every pixel, such that 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
GOLDSTEIN(ψ, b)- 1
q ← charges of all 2 × 2 squares for each residue s0 in raster order that is not in a tree- 2
tree ← [s0] - 3
charge ← q(s0) - 4
for k ← 1 to b while charge ≠ 0 for each t in tree while charge ≠ 0- 5
for each residue u not in a tree in the box of radius k around t - 6
cut from t to u; add u to tree; charge ← charge + q(u) - 7
if charge ≠ 0 and the box passes the border: cut from t to the border; charge ← 0 - 8
k ← k + 1 - 9
if charge ≠ 0: cut from s0 to the border - 10
flood fill over the free edges: φ(next) ← φ(current) + W(ψ(next) - ψ(current)) - 11
return φ 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 there.
The box is the set of squares at Chebyshev distance at most 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 image of zeros with and . The true difference across the edge from to is 4, which is more than , and it wraps to . Line L1 finds two residues, and , the two squares on either side of that edge. Line L2 starts a tree at , and line L5 finds in the box of radius 1. Line L6 steps from square to square and blocks the one edge they share, which is the edge from to . The charge is 0 and the search stops. Line L10 reaches around the cut and gets , the true difference. One edge disagrees with its wrapped difference, which is the minimum.
Greedy cuts are not shortest. Take the image
Its squares have the charges at , at and at . The raster order meets first, and its box of radius 1 holds . The staircase cut blocks two edges. Then 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 to (one edge) and 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.
- Loop sums are enclosed charge. For any closed walk on the pixel grid, the sum of the wrapped differences along is , where is the winding number of around square .
- 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).
- 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.
- What the flood fill returns. By 3, every free edge inside a region has , not only the edges of the search tree. Every pixel has . Another seed changes a region only by a constant multiple of .
- Exact without residues. Then nothing is blocked, and if the true phase changes by less than between neighbours (Itoh's condition), the output is the true phase plus .
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 pixels and . A primal edge joins two neighbouring pixels. For an edge walked from to , , so except when exactly; we assume, as the code does implicitly, that no wrapped difference is exactly (this holds with probability one for noisy data). A square is a block of pixels, and is its charge from line L1: the sum of around in the fixed orientation, divided by . 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). is an integer, and .
Proof. Around , the true differences sum to zero, and each differs from them by a multiple of , so the sum of is a multiple of . Each of the four terms lies in , so the sum lies in , and the multiple is , or .
Lemma 2 (loop sums are enclosed charge). For a closed walk along primal edges, , where is the winding number of around the center of .
Proof. Consider the integer combination of square boundaries. An edge lies between two squares and (or between a square and the outside, whose winding number is 0), and its coefficient in is with the sign of the orientation. Crossing changes the winding number by the net number of times traverses , so this coefficient equals the net number of traversals of by . So and traverse every edge the same net number of times, and since is antisymmetric, .
Lemma 3 (the cut invariant). When line L9 is done, every connected component of the cut graph that contains a residue either has total charge 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 to a member of the tree by a staircase path of squares, and blocks the edge crossed by each step, so and 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 is a union of whole trees and of squares without charge. If one of its trees is cut to the border, contains the outside node. Otherwise all its trees have charge sum 0, and so .
Theorem 1 (path independence). For every closed walk that uses only free edges, .
Proof. Two squares joined by a blocked edge have the same winding number, because does not use and crossing does not change . In the same way a square joined to the outside by a blocked boundary edge has . So is constant on each component of the cut graph, with the value 0 when contains the outside node. By Lemma 2, , summed over the components that contain a residue (the other squares have charge 0). By Lemma 3 every term has or .
Theorem 2 (what the flood fill returns). Let be a region of pixels joined by free edges, and let be its seed. Line L10 gives (a) for every free edge inside , (b) for every , and (c) for another seed of , the new result differs from on by a constant multiple of .
Proof. (a) On the edges of the breadth first search tree, (a) holds by line L10. For any other free edge of , the tree path from to , the edge and the tree path from back to form a closed walk of free edges; by Theorem 1 its sum of is 0, and the two tree paths contribute and , so . (b) , and each step of line L10 adds . (c) Both results satisfy (a) on the connected region , so their difference is constant on ; by (b) both are congruent to , so the constant is a multiple of .
Corollary (exact without residues). If no square has a residue, no edge is blocked, the image is one region, and is the unique image up to a multiple of that is congruent to and satisfies on every edge. If the true phase changes by less than across every edge (Itoh's condition), then for one integer .
Proof. Lines L2 to L9 do nothing without residues. Under Itoh's condition, , so is constant by Theorem 2(a), and a multiple of by Theorem 2(b), since .
What the theorems do not say. The L0 cost of the result, the number of edges with , 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 image of the test with charges at square , at and at , Goldstein's order of search pairs with (two blocked edges) and sends to the border (one more), cost 3, while the cut from to and from 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 multiples on blocked edges; whether the cuts lie where the true phase really jumps is a heuristic matter.
Theorem 3 (termination and cost). Let be the number of residues and the largest box radius. In the word-RAM model, with a Boolean array for the blocked edges, the algorithm takes time and space.
Proof. Line L1 visits each square once, . Each residue joins exactly one tree, so the trees have members in total. A member is scanned with boxes of radius , each of squares, at most once per radius, so the box scans cost . A cut of line L6 joins squares at Chebyshev distance at most , so it blocks at most edges, and there are at most such cuts. A cut to the border goes straight to the nearest side, at most edges, at most once per tree. Lines L4 to L8 end because grows to . The flood fill of line L10 enqueues every pixel once and looks at four edges per pixel, . The charges, the tree marks, the blocked edges, the labels and take space.
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 . Each residue joins exactly one tree. The scans of the boxes cost per member and radius, in total. A cut of line L6 has at most edges, and a cut to the border at most , at most once per tree. So the worst case time is and the extra space is . When the residues are sparse, the time is close to .
Properties
- Congruent (theorem). The output differs from the data by multiples of at every pixel, unlike least squares unwrapping.
- Path independent (theorem). The result in each region is fixed up to one multiple of , 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 example. In 200 random 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 .
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 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 against the rest is then arbitrary. Report it, or join it by a quality guided step.
- Box too small. With , 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 to and ('v', i, j) is the edge from to . 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 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.
# 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 . 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
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5RF5DV Edit this page History Report an error Markdown