Algorithm Search⌘K

Algorithmresearch

Spectral initialization for phase retrieval

Also called spectral method for phase retrieval.

Estimate a signal from y_r = |a_r^* x|^2, up to a global phase, as the top eigenvector of (1/m) sum y_r a_r a_r^* scaled to the estimated norm. It gives the start for Wirtinger flow.

Time
O(K m n) worst
Space
O(n) extra
Where
K = the number of power iterations; m = the number of measurements; n = the length of the signal
Properties
deterministicnot exactnot in placeoffline
Origin
Praneeth Netrapalli, Prateek Jain, Sujay Sanghavi, Emmanuel Candès, Xiaodong Li, Mahdi Soltanolkotabi, 2015

Spectral initialization is a way to get a first estimate in phase retrieval with known random sampling vectors. The data are yr=∣ar∗x∣2y_r = |a_r^* x|^2 for r=1,…,mr = 1, \dots, m. The method forms the matrix Y=1m∑ryrarar∗Y = \frac1m \sum_r y_r a_r a_r^*, takes its top eigenvector, and scales it to an estimate of ∥x∥\|x\|. For Gaussian ara_r the mean of YY is ∥x∥2I+xx∗\|x\|^2 I + x x^*, so with enough measurements the top eigenvector points almost along xx. The result is used to start nonconvex methods such as Wirtinger flow, which need a start close to the signal.

In plain words

Each measurement tells you how strongly the unknown signal lines up with one known random direction, but not the sign or phase. Directions that line up well give large values.

So add up all the directions, each with the weight of its measurement. Directions close to the signal get large weights, and the sum leans toward the signal. The direction in which this weighted sum is largest is a good guess for the direction of the signal. The average of the measurements gives a guess for its length. The phase of the whole signal stays unknown, and no method can find it from these data.

The problem

The input is mm sampling vectors ar∈Cna_r \in \mathbb{C}^n and the values yr=∣ar∗x∣2y_r = |a_r^* x|^2 for an unknown xx. The output is a vector z0z_0 with a small dist⁡(z0,x)=min⁡φ∥z0−eiφx∥\operatorname{dist}(z_0, x) = \min_\varphi \|z_0 - e^{i\varphi} x\|. The data are the same for xx and eiφxe^{i\varphi} x, so this distance is the right measure of error.

The algorithm

  1. SPECTRAL-INIT(a₁, …, a_m, y, K, α_y)
  2. 1λ ← sqrt(n · Σ_r y_r / Σ_r ‖a_r‖²)
  3. 2T ← {r : y_r ≤ α_y² · mean(y)} ▷ all r if α_y is not given
  4. 3v ← a random unit vector
  5. 4for k ← 1 to K do
  6. 5w ← (1/m) Σ_{r ∈ T} y_r a_r (a_r* v)
  7. 6v ← w / ‖w‖
  8. 7return λ v

Line L1 estimates ∥x∥\|x\|: for Gaussian vectors E[yr]=∥x∥2\mathbb{E}[y_r] = \|x\|^2 and E∥ar∥2=n\mathbb{E}\|a_r\|^2 = n. Lines L4 to L6 are power iteration for YY, and line L5 applies YY without forming it, with two passes over the vectors. Line L2 is the truncation of Chen and Candès (2017), who leave out the largest values; without αy\alpha_y it is the plain method of Candès, Li and Soltanolkotabi (2015).

Example

A small real case by hand. Take x=(2,1)x = (2, 1) and the four vectors e1e_1, e2e_2, (1,1)(1, 1), (1,−1)(1, -1). The data are y=(4,1,9,1)y = (4, 1, 9, 1), and

Y=14[4e1e1T+e2e2T+9(1111)+(1−1−11)]=(3.5222.75).Y = \frac14 \Bigl[ 4 e_1 e_1^T + e_2 e_2^T + 9 \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix} + \begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix} \Bigr] = \begin{pmatrix} 3.5 & 2 \\ 2 & 2.75 \end{pmatrix}.

Its eigenvalues are (25±265)/8(25 \pm \sqrt{265})/8, that is 5.1605.160 and 1.0901.090. The top eigenvector is (0.769,0.639)(0.769, 0.639), about 1313 degrees from the direction (0.894,0.447)(0.894, 0.447) of xx. The scale is λ2=2⋅15/6=5=∥x∥2\lambda^2 = 2 \cdot 15 / 6 = 5 = \|x\|^2. So z0=(1.720,1.428)z_0 = (1.720, 1.428), and dist⁡(z0,x)=0.511\operatorname{dist}(z_0, x) = 0.511. The implementation finds the same values, up to a global phase.

Random measurements. Take a unit x∈Cnx \in \mathbb{C}^n and complex Gaussian ara_r, and average dist⁡(z0,x)\operatorname{dist}(z_0, x) over ten seeds (measurements of the implementation):

m/nm / n 2 4 8 16 32
n=8n = 8 0.87 0.75 0.66 0.47 0.36
n=32n = 32 1.05 0.88 0.73 0.53 0.39

The error falls as m/nm / n grows. At these sizes the truncation with αy=3\alpha_y = 3 changed the mean error by less than 0.005; for complex Gaussian vectors and ∥x∥=1\|x\| = 1, a single yry_r is above 99 with probability e−9e^{-9}.

Correctness

The proof page shows these facts.

  • YY is positive semidefinite, so power iteration finds its top eigenvector. The error angle shrinks by the factor μ2/μ1\mu_2 / \mu_1 per step.
  • The mean. For complex Gaussian vectors E[Y]=∥x∥2I+xx∗\mathbb{E}[Y] = \|x\|^2 I + x x^*; for real ones ∥x∥2I+2xxT\|x\|^2 I + 2 x x^T. The top eigenvector of the mean is x/∥x∥x / \|x\|.
  • Perturbation. If ∥Y−E[Y]∥≤ε\|Y - \mathbb{E}[Y]\| \le \varepsilon, then the top eigenvector vv of YY has ∣u∗v∣2≥1−2ε/∥x∥2|u^* v|^2 \ge 1 - 2\varepsilon / \|x\|^2 with u=x/∥x∥u = x / \|x\|.

Candès, Li and Soltanolkotabi (2015, Theorem 3.3) show that m≥c0 nlog⁡nm \ge c_0\, n \log n Gaussian measurements give dist⁡(z0,x)≤18∥x∥\operatorname{dist}(z_0, x) \le \frac18 \|x\| with high probability. This is cited, not proved here.

Proof: The expected spectral matrix, an eigenvector perturbation bound, and power iterationfull

Vectors are in Cn\mathbb{C}^n with ⟨u,v⟩=u∗v\langle u, v \rangle = u^* v. The data are yr=∣ar∗x∣2y_r = |a_r^* x|^2 for r=1,…,mr = 1, \dots, m, and

Y=1m∑r=1myr arar∗,λ2=n∑ryr∑r∥ar∥2.Y = \frac{1}{m} \sum_{r=1}^m y_r\, a_r a_r^*, \qquad \lambda^2 = n \frac{\sum_r y_r}{\sum_r \|a_r\|^2}.

The algorithm returns λv\lambda v, where vv is the unit vector that power iteration gives for YY (lines L3 to L6). The claim of correctness has three parts: YY has the structure that makes the method work (Lemmas 1 and 2), its top eigenvector is close to the direction of xx when YY is close to its mean (Lemma 3), and power iteration finds that eigenvector (Lemma 4). How large mm must be for YY to be close to its mean is a result of Candès, Li and Soltanolkotabi (2015), which is cited and not proved here.

Lemma 1. YY is Hermitian and positive semidefinite, and the data do not change when xx is replaced by eiφxe^{i\varphi} x.

Proof. Each term yrarar∗y_r a_r a_r^* is Hermitian, and v∗(yrarar∗)v=yr∣ar∗v∣2≥0v^* (y_r a_r a_r^*) v = y_r |a_r^* v|^2 \ge 0 because yr≥0y_r \ge 0. A sum of such terms has the same two properties. Also ∣ar∗eiφx∣2=∣ar∗x∣2|a_r^* e^{i\varphi} x|^2 = |a_r^* x|^2. □\square

So the method can only find xx up to a global phase, and the error is measured by dist⁡(z,x)=min⁡φ∥z−eiφx∥\operatorname{dist}(z, x) = \min_\varphi \|z - e^{i\varphi} x\|, which equals ∥z∥2+∥x∥2−2∣x∗z∣\sqrt{\|z\|^2 + \|x\|^2 - 2|x^* z|} (the minimum is at the phase of x∗zx^* z).

Lemma 2 (the mean of YY). If the ara_r are independent with entries N(0,1/2)+i N(0,1/2)\mathcal{N}(0, 1/2) + i\,\mathcal{N}(0, 1/2), then E[Y]=∥x∥2I+xx∗\mathbb{E}[Y] = \|x\|^2 I + x x^*. If the ara_r are real with entries N(0,1)\mathcal{N}(0, 1) and xx is real, then E[Y]=∥x∥2I+2xxT\mathbb{E}[Y] = \|x\|^2 I + 2 x x^T. In both cases E[yr]=∥x∥2\mathbb{E}[y_r] = \|x\|^2 and E∥ar∥2=n\mathbb{E}\|a_r\|^2 = n.

Proof. Take the complex case and x≠0x \neq 0. Let UU be unitary with U∗x=∥x∥e1U^* x = \|x\| e_1, and put b=U∗ab = U^* a for one sampling vector aa. The distribution of aa does not change under a unitary map, so bb has the same distribution as aa. Now y=∣a∗x∣2=∣b∗U∗x∣2=∥x∥2∣b1∣2y = |a^* x|^2 = |b^* U^* x|^2 = \|x\|^2 |b_1|^2 and aa∗=Ubb∗U∗a a^* = U b b^* U^*, so

E[y aa∗]=∥x∥2 U E[∣b1∣2bb∗]U∗.\mathbb{E}[y\, a a^*] = \|x\|^2\, U\, \mathbb{E}\bigl[|b_1|^2 b b^*\bigr] U^* .

The (i,j)(i, j) entry of E[∣b1∣2bb∗]\mathbb{E}[|b_1|^2 b b^*] is E[∣b1∣2bibj‾]\mathbb{E}[|b_1|^2 b_i \overline{b_j}]. For i≠ji \neq j, at least one of the indices ii and jj is not 11, so at least one of the factors bib_i and bj‾\overline{b_j} is independent of the other factors and has mean 00, and the entry is 00. For i=j≠1i = j \neq 1 it is E∣b1∣2 E∣bi∣2=1\mathbb{E}|b_1|^2\, \mathbb{E}|b_i|^2 = 1. For i=j=1i = j = 1 it is E∣b1∣4=2\mathbb{E}|b_1|^4 = 2, because ∣b1∣2|b_1|^2 has the exponential distribution with mean 11. So E[∣b1∣2bb∗]=I+e1e1∗\mathbb{E}[|b_1|^2 b b^*] = I + e_1 e_1^*, and

E[y aa∗]=∥x∥2U(I+e1e1∗)U∗=∥x∥2I+xx∗.\mathbb{E}[y\, a a^*] = \|x\|^2 U (I + e_1 e_1^*) U^* = \|x\|^2 I + x x^* .

The mean of YY is the mean of one term. In the real case the same steps with an orthogonal UU give E[b14]=3\mathbb{E}[b_1^4] = 3 in place of 22, so the result is ∥x∥2I+2xxT\|x\|^2 I + 2 x x^T. Finally E[y]=∥x∥2E∣b1∣2=∥x∥2\mathbb{E}[y] = \|x\|^2 \mathbb{E}|b_1|^2 = \|x\|^2 and E∥a∥2=n\mathbb{E}\|a\|^2 = n. □\square

So the top eigenvector of E[Y]\mathbb{E}[Y] is x/∥x∥x / \|x\|, with eigenvalue 2∥x∥22\|x\|^2 (complex case) against ∥x∥2\|x\|^2 for all other directions. By the law of large numbers, λ2=(1m∑ryr)/(1mn∑r∥ar∥2)→∥x∥2\lambda^2 = (\frac1m \sum_r y_r) / (\frac{1}{mn} \sum_r \|a_r\|^2) \to \|x\|^2 as m→∞m \to \infty.

Lemma 3 (perturbation). Let H=∥x∥2I+xx∗H = \|x\|^2 I + x x^* with x≠0x \neq 0, let YY be Hermitian with ∥Y−H∥≤ε\|Y - H\| \le \varepsilon (spectral norm), and let vv be a unit eigenvector of YY for its largest eigenvalue. Then ∣u∗v∣2≥1−2ε/∥x∥2|u^* v|^2 \ge 1 - 2\varepsilon / \|x\|^2, where u=x/∥x∥u = x / \|x\|.

Proof. The largest eigenvalue is the maximum of w∗Yww^* Y w over unit ww, so v∗Yv≥u∗Yu≥u∗Hu−ε=2∥x∥2−εv^* Y v \ge u^* Y u \ge u^* H u - \varepsilon = 2\|x\|^2 - \varepsilon. On the other hand v∗Yv≤v∗Hv+ε=∥x∥2+∥x∥2∣u∗v∣2+εv^* Y v \le v^* H v + \varepsilon = \|x\|^2 + \|x\|^2 |u^* v|^2 + \varepsilon. Together, ∥x∥2∣u∗v∣2≥∥x∥2−2ε\|x\|^2 |u^* v|^2 \ge \|x\|^2 - 2\varepsilon. □\square

So if YY is within ε=δ∥x∥2\varepsilon = \delta \|x\|^2 of its mean, the angle θ\theta between vv and xx has sin⁡2θ≤2δ\sin^2 \theta \le 2\delta. Candès, Li and Soltanolkotabi (2015, Theorem 3.3) show that for m≥c0 nlog⁡nm \ge c_0\, n \log n, with c0c_0 a large enough constant, the estimate scaled to the norm 1m∑ryr\sqrt{\frac1m \sum_r y_r} has dist⁡(z0,x)≤18∥x∥\operatorname{dist}(z_0, x) \le \frac18 \|x\| with probability at least 1−10e−γn−8/n21 - 10 e^{-\gamma n} - 8/n^2, and they note that the same holds with λ\lambda. The log⁡n\log n is needed for this plain version because the terms yrarar∗y_r a_r a_r^* have heavy tails; Chen and Candès (2017) remove the large yry_r and work with mm of order nn.

Lemma 4 (power iteration). Let YY be Hermitian and positive semidefinite with eigenvalues μ1>μ2≥⋯≥μn≥0\mu_1 > \mu_2 \ge \dots \ge \mu_n \ge 0 and unit eigenvectors u1,…,unu_1, \dots, u_n. Let v0v_0 be a unit vector with c1=u1∗v0≠0c_1 = u_1^* v_0 \neq 0, and let vk=Yvk−1/∥Yvk−1∥v_k = Y v_{k-1} / \|Y v_{k-1}\|. Then, with θk\theta_k the angle between vkv_k and u1u_1,

tan⁡θk≤(μ2μ1)ktan⁡θ0.\tan \theta_k \le \left(\frac{\mu_2}{\mu_1}\right)^k \tan \theta_0 .

Proof. Write v0=∑jcjujv_0 = \sum_j c_j u_j. Then vkv_k is a positive multiple of Ykv0=∑jμjkcjujY^k v_0 = \sum_j \mu_j^k c_j u_j. So

tan⁡2θk=∑j≥2μj2k∣cj∣2μ12k∣c1∣2≤(μ2μ1)2k∑j≥2∣cj∣2∣c1∣2=(μ2μ1)2ktan⁡2θ0.□\tan^2 \theta_k = \frac{\sum_{j \ge 2} \mu_j^{2k} |c_j|^2}{\mu_1^{2k} |c_1|^2} \le \left(\frac{\mu_2}{\mu_1}\right)^{2k} \frac{\sum_{j \ge 2} |c_j|^2}{|c_1|^2} = \left(\frac{\mu_2}{\mu_1}\right)^{2k} \tan^2 \theta_0 . \qquad \square

Because YY is positive semidefinite, its largest eigenvalue is also the largest in absolute value, so the iteration finds the top eigenvector and not an eigenvector of a large negative eigenvalue. A random start has c1≠0c_1 \neq 0 with probability one. If μ1=μ2\mu_1 = \mu_2, the top eigenvector is not unique and the method gives some unit vector in the top eigenspace. For E[Y]\mathbb{E}[Y] the ratio μ2/μ1\mu_2 / \mu_1 is 1/21/2 in the complex case and 1/31/3 in the real case.

What is not claimed. The concentration of YY about its mean, and so the bound dist⁡(z0,x)≤18∥x∥\operatorname{dist}(z_0, x) \le \frac18 \|x\|, is cited, not proved. For small mm the estimate can be far from xx; the tests measure the error on fixed seeds and do not check a theorem there.

Complexity

Each power step reads all mm vectors twice, O(mn)O(m n) work, and KK steps cost O(Kmn)O(K m n). The eigenvalue ratio of the mean is 1/21/2 (complex) or 1/31/3 (real), so a few tens of steps are enough in practice. The extra space is O(n)O(n). For coded diffraction measurements the products with ara_r are fast Fourier transforms, and a step costs O(mlog⁡n)O(m \log n).

Properties

  • Up to a global phase. No method can do better with these data.
  • Not exact. The estimate is only near xx; a refinement method must follow.
  • Needs random or generic vectors. The analysis uses the Gaussian model.
  • Deterministic once the start of the power iteration is fixed.

Variants and improvements

  • Truncated spectral method. Chen and Candès (2017) leave out the yry_r above αy2\alpha_y^2 times the mean, with αy=3\alpha_y = 3 by default, because the terms yrarar∗y_r a_r a_r^* have heavy tails. Their truncated Wirtinger flow then needs mm of order nn.
  • Other weights. The weight yry_r can be replaced by another function of yry_r; the choice changes how many measurements are needed.
  • Lanczos in place of power iteration. Fewer products for the same accuracy.
  • Refinement. Wirtinger flow, alternating minimization, or a convex method such as PhaseLift.

When to use it

Use the spectral method to start a nonconvex phase retrieval method when the sampling vectors are random or close to random, such as Gaussian vectors or random coded diffraction patterns. The analysis does not cover the classical Fourier problem with a support; the methods for that problem, such as hybrid input-output, usually start from random images.

Pitfalls

  • Comparing without the phase. Measure the error with dist⁡\operatorname{dist}, not with ∥z0−x∥\|z_0 - x\|.
  • Too few measurements. With mm a small multiple of nn, the estimate can be far from xx, as the table shows.
  • Forming YY. It costs O(mn2)O(m n^2) time and O(n2)O(n^2) space. Apply it as in line L5 instead.
  • Real or complex. The mean has 2xxT2 x x^T in the real case and xx∗x x^* in the complex case; the gap of the eigenvalues differs.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

imgla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
spectral_initialization.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spectral-initialization/. The authors are listed in prov/5K2MNA.jsonl.

"""Spectral initialization for phase retrieval.

The data are y_r = |<a_r, x>|^2 = |a_r^H x|^2 for r = 1 .. m, with known
sampling vectors a_r in C^n (lists of numbers). The estimate of x, up to a
global phase, is lambda v, where v is a unit leading eigenvector of

    Y = (1/m) sum_r y_r a_r a_r^H

and lambda^2 = n sum_r y_r / sum_r ||a_r||^2 estimates ||x||^2. This is the
initialization of Candes, Li and Soltanolkotabi (2015). With alpha_y set, the
terms with y_r > alpha_y^2 mean(y) are left out (the truncated version of
Chen and Candes (2017)). The eigenvector is found by power iteration: Y is
positive semidefinite, so its largest eigenvalue is also the largest in
absolute value.
"""

import math
import random


def gaussian_design(rng, m, n, complex_valued=True):
    """m sampling vectors with entries N(0, 1/2) + i N(0, 1/2), or N(0, 1) if real."""
    if complex_valued:
        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)]
    return [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(m)]


def inner(a, v):
    """<a, v> = a^H v = sum conj(a_i) v_i."""
    return sum(complex(u).conjugate() * w for u, w in zip(a, 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 kept_terms(y, alpha_y=None):
    """The indices r used in Y: all of them, or those with y_r <= alpha_y^2 mean(y)."""
    if alpha_y is None:
        return list(range(len(y)))
    cut = alpha_y * alpha_y * sum(y) / len(y)
    return [r for r, v in enumerate(y) if v <= cut]


def apply_y(a_rows, y, v, keep=None):
    """Y v = (1/m) sum_r y_r a_r (a_r^H v), over the kept indices."""
    idx = range(len(y)) if keep is None else keep
    out = [0j] * len(v)
    for r in idx:
        c = y[r] * inner(a_rows[r], v)
        for i, ai in enumerate(a_rows[r]):
            out[i] += c * ai
    m = len(y)
    return [w / m for w in out]


def spectral_matrix(a_rows, y, keep=None):
    """The n x n matrix Y, built term by term."""
    n = len(a_rows[0])
    idx = range(len(y)) if keep is None else keep
    mat = [[0j] * n for _ in range(n)]
    for r in idx:
        a = a_rows[r]
        for i in range(n):
            for j in range(n):
                mat[i][j] += y[r] * a[i] * complex(a[j]).conjugate()
    return [[v / len(y) for v in row] for row in mat]


def norm(v):
    """The Euclidean norm."""
    return math.sqrt(sum(abs(w) ** 2 for w in v))


def spectral_init(a_rows, y, iters=100, seed=0, alpha_y=None):
    """Return (z0, eig): z0 = lambda v and the Rayleigh quotient eig = v^H Y v."""
    n = len(a_rows[0])
    lam = math.sqrt(n * sum(y) / sum(norm(a) ** 2 for a in a_rows))  # @line L1
    keep = kept_terms(y, alpha_y)  # @line L2
    rng = random.Random(seed)
    v = [complex(rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)) for _ in range(n)]  # @line L3
    s = norm(v)
    v = [w / s for w in v]
    for _ in range(iters):  # @line L4
        w = apply_y(a_rows, y, v, keep)  # @line L5
        s = norm(w)
        if s == 0.0:
            break
        v = [u / s for u in w]  # @line L6
    eig = inner(v, apply_y(a_rows, y, v, keep)).real
    return [lam * w for w in v], eig  # @line L7


def dist(z, x):
    """min over phi of ||z - e^{i phi} x|| = sqrt(||z||^2 + ||x||^2 - 2 |x^H z|)."""
    d2 = norm(z) ** 2 + norm(x) ** 2 - 2.0 * abs(inner(x, z))
    return math.sqrt(max(d2, 0.0))
test_spectral_initialization.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spectral-initialization/. The authors are listed in prov/5K2MNA.jsonl.

import cmath
import random

from imgla import sym_eig
from spectral_initialization import (apply_y, dist, gaussian_design, inner, kept_terms, measure, norm,
                                     spectral_init, spectral_matrix)


def unit_signal(rng, n, complex_valued=True):
    x = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) if complex_valued else rng.gauss(0, 1) for _ in range(n)]
    s = norm(x)
    return [v / s for v in x]


def test_y_is_hermitian_and_positive_semidefinite() -> None:
    rng = random.Random(1)
    a = gaussian_design(rng, 40, 5)
    y = measure(a, unit_signal(rng, 5))
    mat = spectral_matrix(a, y)
    for i in range(5):
        for j in range(5):
            assert abs(mat[i][j] - mat[j][i].conjugate()) < 1e-12
    for _ in range(10):
        v = unit_signal(rng, 5)
        assert inner(v, apply_y(a, y, v)).real >= -1e-12


def test_power_iteration_finds_the_top_eigenvector() -> None:
    # Compare with the Jacobi method on the real form [[B, -C], [C, B]] of Y = B + iC.
    rng = random.Random(2)
    n = 6
    a = gaussian_design(rng, 60, n)
    y = measure(a, unit_signal(rng, n))
    mat = spectral_matrix(a, y)
    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)
    top = [complex(q[i][-1], q[i + n][-1]) for i in range(n)]
    z, eig = spectral_init(a, y, iters=300, seed=3)
    assert abs(eig - w[-1]) < 1e-9 * w[-1]
    v = [c / norm(z) for c in z]
    assert abs(abs(inner(top, v)) - 1.0) < 1e-8


def test_scale_lambda() -> None:
    rng = random.Random(4)
    a = gaussian_design(rng, 30, 4)
    y = measure(a, unit_signal(rng, 4))
    z, _ = spectral_init(a, y, iters=20)
    lam2 = 4 * sum(y) / sum(norm(r) ** 2 for r in a)
    assert abs(norm(z) ** 2 - lam2) < 1e-12


def test_expected_matrix_complex_and_real() -> None:
    # Monte Carlo: E[Y] = I + x x^H for complex Gaussian a and ||x|| = 1, and I + 2 x x^T for real a.
    for complex_valued, factor in ((True, 1.0), (False, 2.0)):
        rng = random.Random(5)
        n = 3
        x = unit_signal(rng, n, complex_valued)
        a = gaussian_design(rng, 20000, n, complex_valued)
        mat = spectral_matrix(a, measure(a, x))
        for i in range(n):
            for j in range(n):
                want = (1.0 if i == j else 0.0) + factor * x[i] * complex(x[j]).conjugate()
                assert abs(mat[i][j] - want) < 0.1


def test_global_phase_does_not_matter() -> None:
    rng = random.Random(6)
    x = unit_signal(rng, 5)
    a = gaussian_design(rng, 50, 5)
    y = measure(a, x)
    y2 = measure(a, [cmath.exp(0.7j) * v for v in x])
    assert max(abs(u - v) for u, v in zip(y, y2)) < 1e-12
    z, _ = spectral_init(a, y)
    assert abs(dist(z, x) - dist(z, [cmath.exp(0.7j) * v for v in x])) < 1e-12


def test_truncation_keeps_the_small_terms() -> None:
    y = [1.0, 2.0, 30.0, 0.5]  # mean 8.375; the cut for alpha_y = 1.5 is 2.25 * 8.375
    assert kept_terms(y, 1.5) == [0, 1, 3]
    assert kept_terms(y) == [0, 1, 2, 3]


def test_accuracy_measurement() -> None:
    # Measurement, not a theorem: n = 8, m = 32 n, five seeds, complex Gaussian design.
    n, m = 8, 256
    for seed in range(1, 6):
        rng = random.Random(seed)
        x = unit_signal(rng, n)
        a = gaussian_design(rng, m, n)
        z, _ = spectral_init(a, measure(a, x), 100, seed)
        assert dist(z, x) < 0.5

History

Netrapalli, Jain and Sanghavi (2015) started their alternating minimization method for phase retrieval with the top singular vector of the sum of aiaiTa_i a_i^T weighted by the measured intensities. They called this start the new part of their method and showed that it is accurate for mm of order nlog⁡3nn \log^3 n complex Gaussian measurements. Candès, Li and Soltanolkotabi (2015) used the same kind of start for Wirtinger flow, with the scale λ\lambda, and proved that it is within ∥x∥/8\|x\|/8 of the signal for mm of order nlog⁡nn \log n. Chen and Candès (2017) added the truncation, which brings the number of measurements down to the order of nn.

References

  1. Emmanuel J. Candès, Xiaodong Li and Mahdi Soltanolkotabi, Phase retrieval via Wirtinger flow, theory and algorithms, IEEE Transactions on Information Theory 61(4), 2015, 1985 to 2007, Algorithm 1 (the initialization with lambda^2 = n sum y_r / sum ||a_r||^2), Section 2.3 (the mean I + 2 x x^T in the real Gaussian model), Definition 3.1 (the Gaussian model) and Theorem 3.3 (dist(z_0, x) <= ||x|| / 8 for m >= c_0 n log n) (preprint arXiv 1407.1065)
  2. Praneeth Netrapalli, Prateek Jain and Sujay Sanghavi, Phase retrieval using alternating minimization, IEEE Transactions on Signal Processing 63(18), 2015, 4814 to 4826, Algorithm 1, step 1 (the start of AltMinPhase from the top singular vector of the sum of y_i^2 a_i a_i^T, with y_i the measured magnitudes) and Theorem 4.1 (accuracy for m >= C n log^3 n) (preprint arXiv 1306.0160)
  3. Yuxin Chen and Emmanuel J. Candès, Solving random quadratic systems of equations is nearly as easy as solving linear systems, Communications on Pure and Applied Mathematics 70(5), 2017, 822 to 883, Section 2.2, truncated spectral initialization, equation (29), with the heavy tail argument and the default alpha_y = 3 (preprint arXiv 1505.05114)

Where this leads

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