Algorithmresearch
PhaseLift
Phase retrieval as a convex problem. Lift x to the matrix X = x x^*, in which the data are linear, and find a positive semidefinite X that fits them with the least trace.
- Solves
- Phase retrieval
- Time
- O(K (m n^2 + n^3)) worst
- Space
- O(n^2) extra
- Where
- K = the number of iterations; m = the number of measurements; n = the length of the signal
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Emmanuel Candès, Thomas Strohmer, Vladislav Voroninski, 2013
PhaseLift is a convex method for phase retrieval with known sampling vectors. The data are quadratic in , but they are linear in the matrix , because . The method looks for in place of . The condition that has rank one is not convex, so PhaseLift keeps only the condition that is positive semidefinite, and uses the trace to prefer matrices of low rank:
This is a semidefinite program. Candès, Strohmer and Voroninski (2013) proved that for about Gaussian vectors its only solution is . Candès and Li (2014) brought the number down to the order of , and showed that then is the only feasible point. The signal is the top eigenvector of , up to a global phase.
In plain words
The unknown is a list of complex numbers, and each measurement gives a squared size, which mixes the numbers in pairs. That makes the equations hard: there are many false answers, and a search can get stuck in one.
The trick is to treat each product of two unknowns as a new unknown of its own. Put all these products in a square table. Then every measurement is a simple sum over the table, and simple sums are easy. The price is that the table has many more entries than the list, and a true table has a special form. The method keeps a weaker property of that form, which turns the search into one with a single best answer. With enough random measurements, that answer is the true table, and the list can be read off from it.
The problem
The input is vectors and the values . The output is a with a small ; no method can find the global phase. Write for the linear map on the Hermitian matrices.
The algorithm
The semidefinite program can be solved by any SDP method, such as an interior point method for small . The implementation here uses projected gradient descent on the penalized form
with by default. When is the only feasible point, as in the theorem of Candès and Li, the minimizer of with is , and the trace does not matter.
PHASELIFT(a₁, …, a_m, y, K, λ)- 1
L ← ‖𝒜‖² ▷ or any bound L ≥ ‖𝒜‖², such as Σ_r ‖a_r‖⁴ - 2
X ← 0 (n × n) - 3
for k ← 1 to K do - 4
ρ ← 𝒜(X) − y ▷ ρ_r = a_r* X a_r − y_r - 5
G ← Σ_r ρ_r a_r a_r* + λ I - 6
X ← P₊(X − G / L) ▷ set the negative eigenvalues to 0 - 7
return X
Then from the top eigenpair of . Line L5 is the gradient . Line L6 is the projection onto the positive semidefinite matrices: write and replace each by . The implementation does this on the real symmetric form of , with the Jacobi eigenvalue method of the shared helper. It gets from the singular values of the real matrix of .
Example
A case by hand. Take and the four vectors , , and . Write with real and . The four values are
and the data are . These four linear equations give , and , so
Its eigenvalues are and , and times the top unit eigenvector is up to a phase. Here the four real numbers of a Hermitian matrix are fixed by four equations, so the lifted problem has one solution. The implementation starts from with , and reaches after 100 steps and after 500 steps.
Random measurements. Take , , a unit and complex Gaussian vectors, all from seed 1, with (measurements of the implementation):
| step | 0 | 10 | 50 | 100 | 200 | 300 |
|---|---|---|---|---|---|---|
| 1 | 0.22 | 0.034 | 0.0053 | 1.4e-4 | 3.8e-6 | |
| 1 | 0.35 | 0.065 | 0.010 | 2.5e-4 | 6.5e-6 | |
| 28 | 0.47 | 0.011 | 2.7e-4 | 1.7e-7 | 1.1e-10 |
Here , and the cheap bound is 3.55 times larger. With that bound the step is shorter, and after 300 steps is only . With the result has rank one and trace , and : the penalty adds a small bias toward a smaller trace.
Correctness
The proof page shows these facts.
- Lifting. is linear in , and . The top eigenpair of gives up to a phase.
- The projection. Clipping the eigenvalues at gives the unique nearest positive semidefinite matrix, and the real form gives the same result.
- The rate. With the step and , does not increase, does not increase, and .
- Recovery. If is the only positive semidefinite matrix that fits the data, then and up to a phase.
Candès and Li (2014, Theorem 1.2) show that for Gaussian vectors, with probability at least , PhaseLift recovers every at once, and their Lemma 2.2 gives the unique feasible point. This is cited, not proved here.
Proof: The lifted linear map, the projection onto the semidefinite cone, and the rate of projected gradientfull
Matrices are Hermitian, with the real inner product and the Frobenius norm. means positive semidefinite, and is the set of these matrices. The data are for . Put
The implementation runs from with (lines L1 to L6), and then takes from the top eigenpair of the result. The claim of correctness has four parts: the data are linear in (Lemma 1), the projection step is the exact projection onto (Lemmas 2 and 3), the iteration converges to the minimum of at the rate (Lemma 4), and when the feasible set is the single point the iterates and the extracted vector converge to the signal (Lemma 5). When the feasible set is a single point is the result of Candès and Li (2014), which is cited and not proved here.
Lemma 1 (lifting). is real linear, , and its adjoint is . If with , its top eigenvalue is with the eigenvector , and for some real .
Proof. , which is real for Hermitian and linear in . For it is . Then for real . Finally and for , so the top eigenvalue is with a one dimensional eigenspace; a unit eigenvector is .
So the quadratic equations in become linear equations in , with the two extra conditions and . PhaseLift keeps the first condition and drops the second.
Lemma 2 (projection onto ). Let with unitary. Then is the unique nearest point of to . It satisfies for all , and .
Proof. For put , which is also positive semidefinite, so . The norm does not change under unitary maps, so
The second inequality uses for each with . So is a nearest point. is closed and convex, so the nearest point is unique and is characterized by the variational inequality. Also , and for each .
Lemma 3 (the real form). For with real and , put . Then , , , and . If is Hermitian, is real symmetric with the same eigenvalues, each twice, and , the clipping of .
Proof. The first three are direct computations with . Each of and appears twice in , which gives the norm. If with , then maps to and to , which is the eigenvector for . These two real vectors are orthogonal, and an orthonormal basis of gives an orthonormal basis of in this way. So the eigenvalues of are those of , each twice. Let be a real polynomial with for every eigenvalue of . Then and , because both matrices have the same eigenvalues. By the rules above, .
The implementation computes from the eigenvectors of the Jacobi method, and reads off its blocks. Each block appears twice, so it takes the mean of the two copies.
Lemma 4 (projected gradient). is convex on , , and for all and
Let be the minimum of over and a minimizer. A minimizer exists when , because then on , and when and the data are exact, because then . Then the iterates satisfy , , and
Proof. is a convex quadratic plus a linear term, so the expansion is exact: the linear terms give by Lemma 1, and the quadratic term is . Fix , put and . By Lemma 2 with the point , every has , that is . Convexity gives . With the expansion for ,
The right side equals , by the expansion of . With this is the decrease of . With and it gives . Add the inequalities for over the steps : the right sides telescope, so . does not increase, so the left side is at least .
The implementation takes , where is the largest singular value of the real matrix of in the orthonormal basis , , of the Hermitian matrices. The cheaper bound is also valid, because by the Cauchy-Schwarz inequality.
Lemma 5 (recovery when the feasible point is unique). Let and suppose that . Then , and , where .
Proof. and , so , and the minimizers are exactly the feasible points, so is the only one. By Lemma 4, and does not increase, so the sequence is bounded. Every limit point of the sequence lies in the closed set and has by continuity, so . A bounded sequence with a single limit point converges to it. For the vector, is a continuous function of , so . The top eigenvalue of is simple, so the projection onto its eigenspace is continuous at , and . For this says . Then and , so .
The cited results. Candès, Strohmer and Voroninski (2013) take the problem "minimize subject to and " and show that, for Gaussian vectors and a fixed , its unique solution is with high probability (Theorem 1.1 in the statement of Candès and Li). Candès and Li (2014, Theorem 1.2) show the same for , with probability at least , and for all at once. Their proof shows that is the only feasible point (their Lemma 2.2), so the condition of Lemma 5 holds and the trace does not matter. In that case the projected gradient with finds .
What is not claimed. The probabilistic results above are cited, not proved. With the minimizer of is not in general ; the penalty pulls the trace down, which helps with noise but adds a bias. The rate is the worst case; the faster, linear decrease in the example on the main page is a measurement. The tests check Lemmas 1 to 4 on random data, and they measure the recovery on fixed seeds without a theorem for those sizes.
Complexity
One step computes and in time and an eigenvalue decomposition in time, so steps cost . The extra space is for the matrices. The exact costs more than one step, because it works with an matrix; the bound costs . For coded diffraction patterns the products with the are fast Fourier transforms, but the matrix still has entries. This size is the main limit of PhaseLift: a signal of samples gives a matrix of entries.
Properties
- Convex. There are no false local minima, and the result does not depend on a start.
- Up to a global phase. The lifted matrix does not change when is replaced by .
- Order measurements are enough for Gaussian vectors, by Candès and Li (2014).
- Universal. For one draw of the vectors, the result of Candès and Li holds for all signals at once.
- Expensive. The unknown has entries in place of .
Variants and improvements
- Noisy data. Candès and Li (2014, problem (1.6)) fit the data in the norm over the positive semidefinite matrices, and bound the error by a constant times for the noise (Theorem 1.3).
- Feasibility only. When the feasible point is unique, the trace can be dropped, as in the implementation here. Candès and Li note a similar argument by Demanet and Hand.
- Other solvers. ADMM, accelerated gradient methods, or a factored form with few columns, which gives up convexity to save memory.
- Nonconvex methods. Wirtinger flow works with itself, from a spectral start. It needs about Gaussian measurements in its theorem, but each step costs only .
When to use it
Use PhaseLift for small or medium , when a guarantee that does not depend on a start matters, and when the vectors are random, as in Gaussian or coded diffraction measurements. It is also a good reference to test nonconvex methods against. For large images use Wirtinger flow or other nonconvex methods. For the classical Fourier problem with a support, the theory does not apply.
Pitfalls
- Memory. The matrix has entries. Do not form as an matrix for large .
- A step that is too long. The step needs . An estimate of from a few power steps is a lower bound and can be too small.
- Rank above one. With noise or with too few measurements, the result can have rank above one. Take the top eigenpair, and check how large the second eigenvalue is.
- Too few measurements. If the data do not fix up to a phase, no relaxation can help. Balan, Casazza and Edidin showed that generic measurements fix (see the complement property), and the theorem of PhaseLift needs a larger multiple of .
- The trace weight. A large shrinks the result; the trace is a convex stand-in for the rank, not the rank itself.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
phaselift.py 224 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phaselift/. The authors are listed in prov/K3F300.jsonl.
"""PhaseLift for phase retrieval (Candes, Strohmer and Voroninski 2013).
The data are y_r = |a_r^H x|^2 = a_r^H (x x^H) a_r, which are linear in the
lifted matrix X = x x^H. PhaseLift replaces the rank one condition by
X >= 0 (positive semidefinite) and solves
minimize tr(X) subject to A(X) = y, X >= 0, A(X)_r = a_r^H X a_r.
This file solves the penalized form
minimize F(X) = (1/2) ||A(X) - y||^2 + lam tr(X) over X >= 0
by projected gradient steps with the step 1 / L, L = sum_r ||a_r||^4 >= ||A||^2.
With lam = 0 it finds a point of {X >= 0 : A(X) = y}; Candes and Li (2014)
show that for m >= c0 n Gaussian vectors this set is the single point x x^H.
The estimate of x is the top eigenvector of X times the root of its eigenvalue.
Hermitian matrices are lists of rows of complex numbers. The projection onto
the positive semidefinite cone uses the real form [[B, -C], [C, B]] of
X = B + iC and the Jacobi eigenvalue method of the shared helper.
"""
import math
import random
from imgla import svd, sym_eig
def gaussian_design(rng, m, n):
"""m sampling vectors with entries N(0, 1/2) + i N(0, 1/2)."""
s = math.sqrt(0.5)
return [[complex(rng.gauss(0.0, s), rng.gauss(0.0, s)) for _ in range(n)] for _ in range(m)]
def inner(a, v):
"""<a, v> = a^H v."""
return sum(complex(u).conjugate() * w for u, w in zip(a, v))
def norm(v):
"""The Euclidean norm of a vector."""
return math.sqrt(sum(abs(w) ** 2 for w in v))
def measure(a_rows, x):
"""The phaseless data y_r = |a_r^H x|^2."""
return [abs(inner(a, x)) ** 2 for a in a_rows]
def lift(x):
"""The rank one matrix x x^H."""
return [[complex(u) * complex(v).conjugate() for v in x] for u in x]
def apply_a(a_rows, mat):
"""A(X)_r = a_r^H X a_r, a real number for Hermitian X."""
out = []
for a in a_rows:
xa = [sum(row[j] * a[j] for j in range(len(a))) for row in mat]
out.append(inner(a, xa).real)
return out
def apply_a_adjoint(a_rows, v):
"""A^*(v) = sum_r v_r a_r a_r^H."""
n = len(a_rows[0])
out = [[0j] * n for _ in range(n)]
for a, vr in zip(a_rows, v):
for i in range(n):
c = vr * a[i]
row = out[i]
for j in range(n):
row[j] += c * a[j].conjugate()
return out
def frob_inner(p, q):
"""Re tr(P^H Q), the real inner product of matrices."""
return sum((complex(u).conjugate() * v).real for rp, rq in zip(p, q) for u, v in zip(rp, rq))
def frob_norm(p):
"""The Frobenius norm."""
return math.sqrt(sum(abs(v) ** 2 for row in p for v in row))
def trace(p):
"""The trace, a real number for Hermitian P."""
return sum(p[i][i] for i in range(len(p))).real
def hermitian_eig(mat):
"""Eigenvalues (ascending) and unit eigenvectors of a Hermitian matrix.
The real form R = [[B, -C], [C, B]] of X = B + iC has each eigenvalue of X
twice; the eigenvector (p, q) of R gives the eigenvector p + iq of X. One
vector of each pair is kept, by a Gram-Schmidt test.
"""
n = len(mat)
real_form = [[mat[i][j].real for j in range(n)] + [-mat[i][j].imag for j in range(n)] for i in range(n)]
real_form += [[mat[i][j].imag for j in range(n)] + [mat[i][j].real for j in range(n)] for i in range(n)]
w, q = sym_eig(real_form)
vals, vecs = [], []
for k in sorted(range(2 * n), key=lambda t: -w[t]):
v = [complex(q[i][k], q[i + n][k]) for i in range(n)]
for u in vecs:
c = inner(u, v)
v = [vi - c * ui for vi, ui in zip(v, u)]
s = norm(v)
if s > 0.5 and len(vecs) < n:
vecs.append([vi / s for vi in v])
vals.append(w[k])
order = sorted(range(n), key=lambda t: vals[t])
return [vals[t] for t in order], [vecs[t] for t in order]
def psd_project(mat):
"""The nearest positive semidefinite matrix in the Frobenius norm.
Spectral clipping X+ = sum_k max(w_k, 0) u_k u_k^H, done on the real form:
R+ = Q diag(max(w, 0)) Q^T has the same block form, and X+ = R+_11 + i R+_21.
"""
n = len(mat)
real_form = [[mat[i][j].real for j in range(n)] + [-mat[i][j].imag for j in range(n)] for i in range(n)]
real_form += [[mat[i][j].imag for j in range(n)] + [mat[i][j].real for j in range(n)] for i in range(n)]
w, q = sym_eig(real_form)
keep = [k for k in range(2 * n) if w[k] > 0.0]
out = [[0j] * n for _ in range(n)]
for i in range(n):
for j in range(n):
b = sum(w[k] * (q[i][k] * q[j][k] + q[i + n][k] * q[j + n][k]) for k in keep) / 2.0
c = sum(w[k] * (q[i + n][k] * q[j][k] - q[i][k] * q[j + n][k]) for k in keep) / 2.0
out[i][j] = complex(b, c)
return out
def real_rows(a_rows):
"""The m x n^2 real matrix of A in an orthonormal basis of the Hermitian matrices.
The basis is E_ii, (E_ij + E_ji) / sqrt 2 and i (E_ij - E_ji) / sqrt 2 for
i < j, orthonormal for Re tr(P^H Q). The coordinates of a a^H are |a_i|^2,
sqrt 2 Re(a_i conj(a_j)) and sqrt 2 Im(a_i conj(a_j)).
"""
n = len(a_rows[0])
out = []
for a in a_rows:
row = [abs(a[i]) ** 2 for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
p = a[i] * a[j].conjugate()
row += [math.sqrt(2.0) * p.real, math.sqrt(2.0) * p.imag]
out.append(row)
return out
def op_norm_sq(a_rows):
"""||A||^2, the largest eigenvalue of A^* A, from the singular values of real_rows."""
_, s, _ = svd(real_rows(a_rows))
return s[0] ** 2
def objective(a_rows, y, mat, lam=0.0):
"""F(X) = (1/2) ||A(X) - y||^2 + lam tr(X)."""
r = [u - v for u, v in zip(apply_a(a_rows, mat), y)]
return 0.5 * sum(t * t for t in r) + lam * trace(mat)
def phaselift(a_rows, y, iters, lam=0.0, x0=None, record=None, big_l=None):
"""Projected gradient for min F(X) over X >= 0. Returns X.
The step is 1 / L with L = ||A||^2 (times 1 + 1e-9 against rounding) unless
big_l is given; any L >= ||A||^2, such as sum_r ||a_r||^4, is safe. x0 is the
start matrix (zero by default). If record is a list, X_0 .. X_iters are
appended to it.
"""
n = len(a_rows[0])
if big_l is None:
big_l = op_norm_sq(a_rows) * (1.0 + 1e-9) # @line L1
mat = [[0j] * n for _ in range(n)] if x0 is None else [list(row) for row in x0] # @line L2
if record is not None:
record.append(mat)
for _ in range(iters): # @line L3
resid = [u - v for u, v in zip(apply_a(a_rows, mat), y)] # @line L4
grad = apply_a_adjoint(a_rows, resid) # @line L5
for i in range(n):
grad[i][i] += lam
step = [[mat[i][j] - grad[i][j] / big_l for j in range(n)] for i in range(n)]
mat = psd_project(step) # @line L6
if record is not None:
record.append(mat)
return mat # @line L7
def extract(mat):
"""The vector sqrt(w_max) u_max from the top eigenpair of X."""
w, v = hermitian_eig(mat)
return [math.sqrt(max(w[-1], 0.0)) * c for c in v[-1]]
def dist(z, x):
"""min over phi of ||z - e^{i phi} x||."""
c = inner(x, z)
phase = c / abs(c) if abs(c) > 0.0 else 1.0
return norm([u - phase * v for u, v in zip(z, x)])
def random_hermitian(rng, n):
"""A random Hermitian matrix, for tests."""
g = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)] for _ in range(n)]
return [[(g[i][j] + g[j][i].conjugate()) / 2.0 for j in range(n)] for i in range(n)]
def demo(seed=1, n=4, m=24, iters=300):
"""dist(extract(X_k), x) for a random unit x; a small measurement."""
rng = random.Random(seed)
x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
s = norm(x)
x = [v / s for v in x]
a = gaussian_design(rng, m, n)
mat = phaselift(a, measure(a, x), iters)
return dist(extract(mat), x), frob_norm([[u - v for u, v in zip(r1, r2)] for r1, r2 in zip(mat, lift(x))])
test_phaselift.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phaselift/. The authors are listed in prov/K3F300.jsonl.
import random
from phaselift import (apply_a, apply_a_adjoint, dist, extract, frob_inner, frob_norm, gaussian_design,
hermitian_eig, lift, measure, norm, objective, op_norm_sq, phaselift, psd_project,
random_hermitian, real_rows, trace)
def unit_signal(rng, n):
x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
s = norm(x)
return [v / s for v in x]
def sub(p, q):
return [[u - v for u, v in zip(rp, rq)] for rp, rq in zip(p, q)]
def matmul(p, q):
return [[sum(p[i][k] * q[k][j] for k in range(len(q))) for j in range(len(q[0]))] for i in range(len(p))]
def test_lifted_data_are_linear() -> None:
rng = random.Random(1)
x = unit_signal(rng, 4)
a = gaussian_design(rng, 10, 4)
assert max(abs(u - v) for u, v in zip(apply_a(a, lift(x)), measure(a, x))) < 1e-12
def test_adjoint() -> None:
rng = random.Random(2)
a = gaussian_design(rng, 9, 4)
for _ in range(3):
mat = random_hermitian(rng, 4)
v = [rng.gauss(0, 1) for _ in range(9)]
left = sum(u * w for u, w in zip(apply_a(a, mat), v))
right = frob_inner(mat, apply_a_adjoint(a, v))
assert abs(left - right) < 1e-10 * max(1.0, abs(left))
def test_hermitian_eig_reconstructs() -> None:
rng = random.Random(3)
mat = random_hermitian(rng, 4)
w, v = hermitian_eig(mat)
back = [[sum(w[k] * v[k][i] * v[k][j].conjugate() for k in range(4)) for j in range(4)] for i in range(4)]
assert frob_norm(sub(back, mat)) < 1e-10
assert all(u <= t for u, t in zip(w, w[1:]))
def test_psd_projection_is_the_nearest_point() -> None:
rng = random.Random(4)
for _ in range(3):
mat = random_hermitian(rng, 4)
proj = psd_project(mat)
w, _ = hermitian_eig(proj)
assert w[0] > -1e-10
for i in range(4):
for j in range(4):
assert abs(proj[i][j] - proj[j][i].conjugate()) < 1e-12
# The parts X+ and X+ - X are orthogonal: X+ (X+ - X) = 0.
assert frob_norm(matmul(proj, sub(proj, mat))) < 1e-10
# Variational inequality <X - X+, Y - X+> <= 0 for every PSD Y.
for _ in range(5):
g = random_hermitian(rng, 4)
psd = matmul(g, g)
assert frob_inner(sub(mat, proj), sub(psd, proj)) < 1e-10
# A PSD matrix is its own projection.
assert frob_norm(sub(psd_project(proj), proj)) < 1e-10
def test_operator_norm() -> None:
rng = random.Random(5)
a = gaussian_design(rng, 12, 3)
big_l = op_norm_sq(a)
fourth = sum(norm(r) ** 4 for r in a)
assert fourth / 3 <= big_l * (1 + 1e-12) and big_l <= fourth * (1 + 1e-12)
rows = real_rows(a)
mat = random_hermitian(rng, 3)
coords = [mat[i][i].real for i in range(3)]
for i in range(3):
for j in range(i + 1, 3):
coords += [2 ** 0.5 * mat[i][j].real, 2 ** 0.5 * mat[i][j].imag]
direct = apply_a(a, mat)
via_rows = [sum(u * v for u, v in zip(row, coords)) for row in rows]
assert max(abs(u - v) for u, v in zip(direct, via_rows)) < 1e-10
assert sum(t * t for t in direct) <= big_l * frob_norm(mat) ** 2 * (1 + 1e-9)
def test_hand_example_two_by_two() -> None:
# x = (1, 1 + i), vectors e1, e2, e1 + e2, e1 + i e2: A is one to one on 2 x 2 Hermitian matrices.
a = [[1, 0], [0, 1], [1, 1], [1, 1j]]
a = [[complex(v) for v in row] for row in a]
x = [1 + 0j, 1 + 1j]
y = measure(a, x)
assert max(abs(u - v) for u, v in zip(y, [1.0, 2.0, 5.0, 5.0])) < 1e-12
rec = []
mat = phaselift(a, y, 1000, record=rec)
want = [[1, 1 - 1j], [1 + 1j, 2]]
assert frob_norm(sub(mat, want)) < 1e-9
w, _ = hermitian_eig(mat)
assert abs(w[-1] - 3.0) < 1e-9 and abs(w[0]) < 1e-9
assert dist(extract(mat), x) < 1e-9
def test_monotone_and_rate_bound() -> None:
# F(X_k) - F* <= L ||X_0 - X*||^2 / (2 k), with X* = x x^H, F* = 0 and X_0 = 0.
rng = random.Random(6)
n = 3
x = unit_signal(rng, n)
a = gaussian_design(rng, 18, n)
y = measure(a, x)
big_l = op_norm_sq(a) * (1.0 + 1e-9)
rec = []
phaselift(a, y, 60, record=rec)
values = [objective(a, y, mat) for mat in rec]
assert all(v <= u + 1e-12 for u, v in zip(values, values[1:]))
for k in range(1, len(values)):
assert values[k] <= big_l * 1.0 / (2 * k) + 1e-12
def test_trace_penalty_is_monotone() -> None:
rng = random.Random(7)
n = 3
x = unit_signal(rng, n)
a = gaussian_design(rng, 18, n)
y = measure(a, x)
rec = []
phaselift(a, y, 40, lam=0.5, record=rec)
values = [objective(a, y, mat, 0.5) for mat in rec]
assert all(v <= u + 1e-12 for u, v in zip(values, values[1:]))
assert trace(rec[-1]) < 1.0
def test_recovery_measurement() -> None:
# Measurement, not a theorem: n = 3, m = 8 n, complex Gaussian design, 300 steps.
for seed in range(1, 4):
rng = random.Random(seed)
x = unit_signal(rng, 3)
a = gaussian_design(rng, 24, 3)
mat = phaselift(a, measure(a, x), 300)
assert dist(extract(mat), x) < 5e-3
History
Candès, Eldar, Strohmer and Voroninski, in a paper on phase retrieval through matrix completion, and Candès, Strohmer and Voroninski (2013) proposed to lift the problem to and to replace the rank by the trace. The second paper proved exact recovery from about Gaussian measurements for a fixed signal. Candès and Li (2014) removed the logarithm, made the result hold for all signals at once, and gave the error bound for noisy data. The use of the trace as a convex stand-in for the rank links PhaseLift to low rank matrix recovery and matrix completion.
References
- Emmanuel J. Candès, Thomas Strohmer and Vladislav Voroninski, PhaseLift, exact and stable signal recovery from magnitude measurements via convex programming, Communications on Pure and Applied Mathematics 66(8), 2013, 1241 to 1274, the trace minimization relaxation and its exact recovery theorem for m of order n log n, as restated in Theorem 1.1 of Candès and Li (2014)
- Emmanuel J. Candès and Xiaodong Li, Solving quadratic equations via PhaseLift when there are about as many equations as unknowns, Foundations of Computational Mathematics 14(5), 2014, 1017 to 1026, problem (1.2) (PhaseLift), Theorem 1.2 (m >= c_0 n, all signals at once), Lemma 2.2 (the lifted signal as the unique feasible point), problem (1.6) and Theorem 1.3 (noisy data) (preprint arXiv 1208.6247)
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 K3F300 Edit this page History Report an error Markdown