Algorithm Search⌘K

Algorithmadvanced

Charge flipping

Also called charge flipping algorithm.

Solve a crystal structure by iterating between imposing the measured magnitudes and flipping the sign of electron density below a small threshold.

Time
O(K N log N) worst
Space
O(N) extra
Where
K = the number of cycles; N = the number of grid points in the unit cell, with an FFT
Properties
randomizednot exactnot in placeoffline
Origin
Gabor Oszlanyi, Andras Suto, 2004

Charge flipping is an iterative method that finds the phases of the structure factors of a crystal from their measured amplitudes. It repeats two steps: in real space it changes the sign of all density below a small threshold δ\delta, and in reciprocal space it puts back the measured amplitudes while it keeps the new phases. It needs no atomic model, no knowledge of the chemistry and no symmetry, and it works in the space group P1P1. It is a direct solution of the crystallographic phase problem, a case of phase retrieval for a periodic object.

In plain words

A crystal scatters X-rays into sharp spots. The brightness of each spot can be measured, but not its phase, and without the phases the picture of the atoms cannot be computed.

Charge flipping starts with random phases and computes a first picture, which is mostly noise. A real crystal picture is almost empty, with a few strong peaks at the atoms. So the method keeps the strong positive parts and turns every weak part upside down. It then computes the spots of this changed picture, keeps their new phases and puts back the measured brightness. After many rounds of this, the picture often jumps quickly from noise to the true atoms. The atoms can come out shifted or mirrored, because the measured brightness is the same for all those pictures.

The problem

The density ρ\rho is a real function on a grid of NN points in the unit cell. Its structure factors are the unnormalized DFT F(h)=∑xρ(x)e−2πi h⋅xF(h) = \sum_x \rho(x) e^{-2\pi i\, h \cdot x}, with h⋅xh \cdot x the scaled product of the index and the grid point. The data are the amplitudes ∣Fobs(h)∣|F_{\text{obs}}(h)| for the observed reflections hh, usually without F(0)F(0), the total charge. Friedel symmetry F(−h)=F(h)‾F(-h) = \overline{F(h)} holds because ρ\rho is real. The task is to find the phases, and so ρ\rho. Any solution can be shifted on the grid or inverted through a point without a change of the data, so the answer is unique at best up to these changes.

The algorithm

  1. CHARGE-FLIPPING(|F_obs|, δ, K)
  2. 1F(h) <- |F_obs(h)| e^{iφ(h)} with random φ, φ(-h) = -φ(h); F(h) <- 0 if h is not observed
  3. 2for cycle <- 1 .. K do
  4. 3ρ <- IDFT(F)
  5. 4g(x) <- ρ(x) if ρ(x) > δ, else -ρ(x) ▷ flip the weak density
  6. 5G <- DFT(g)
  7. 6for each index h do
  8. 7if h is observed then F(h) <- |F_obs(h)| G(h) / |G(h)|
  9. 8else if h = 0 then F(0) <- G(0) ▷ the total charge is free
  10. 9else F(h) <- 0
  11. 10return IDFT(F)

At cycle 0, F(0)=0F(0) = 0 unless it is observed. The threshold δ\delta is the only parameter. It must be small compared with the peaks of the density but larger than the ripple of the truncated Fourier series. The Superflip manual recommends finding it by trial. The progress is followed with the R-value R=∑h∣∣Fobs(h)∣−∣G(h)∣∣/∑h∣Fobs(h)∣R = \sum_h \big| |F_{\text{obs}}(h)| - |G(h)| \big| / \sum_h |F_{\text{obs}}(h)| over the observed hh.

Example

The test file builds a two-dimensional cell of 16×1616 \times 16 grid points with 8 point atoms, seven of weight 1 and one of weight 2, and zero density elsewhere. All reflections except F(0)F(0) are observed. With δ=0.2\delta = 0.2 and the start phases of seed 1, the R-value develops as follows (measurement).

cycle 1 5 10 20 30 40 50 60 80 100 150
R 0.510 0.420 0.401 0.387 0.323 0.368 0.165 0.060 0.011 0.007 0.004

The R-value stays high for about 40 cycles and then falls in a few cycles; this sudden drop is the typical sign of a solution in charge flipping. After 150 cycles the density matches the true one, after the best shift and inversion, with a relative error below 0.25. Of 10 random starts with 150 cycles, 7 reached the structure. The other 3 stayed at an R-value between 0.15 and 0.26, so the usual practice is to run several starts and keep the one with a low R-value.

With δ=0.1\delta = 0.1 and with δ=0.3\delta = 0.3, none of 4 starts solved the same cell in 200 cycles, while 3 of the same 4 starts solved it with δ=0.2\delta = 0.2. The choice of δ\delta matters. In a one-dimensional test with 64 points and δ=0.1\delta = 0.1, the iteration reached R<10−3R < 10^{-3} with a dense density that is not the structure. A low R-value is evidence of a solution, not a proof.

Correctness

There is no proof that charge flipping converges. The proof shows the structure of each cycle.

  • The flip is a reflection (theorem). The flip is 2Tδ−I2T_\delta - I, with TδT_\delta the hard threshold that sets values at or below δ\delta to zero. For δ=0\delta = 0 it is the reflection through the cone of nonnegative densities, ∣ρ∣=2max⁡(ρ,0)−ρ|\rho| = 2\max(\rho, 0) - \rho.
  • The amplitude step is a projection (theorem). Lines L6 to L9 give the nearest point to GG among the transforms with the measured amplitudes, zero unobserved entries and a free F(0)F(0). So a cycle is a projection after a reflection. This places charge flipping next to hybrid input-output and the difference map; error reduction uses the threshold in place of the reflection.
  • Atomic densities are fixed points (theorem). If every value of the true density is 00 or above δ\delta, and all reflections that are not observed are zero, then the iteration started at the true structure factors stays there with R=0R = 0.
  • Shift and inversion (theorem). If the start is shifted or inverted, the whole run is shifted or inverted in the same way. The data are the same for these densities, so the origin and the hand of the result are arbitrary.
  • What is not proved. That the iteration reaches the true structure. In practice the R-value often stays above zero near the solution, because the small values below δ\delta keep changing sign.
Proof: What charge flipping guarantees, and what it does notpartial

Charge flipping has no convergence proof. This page proves its structure: the flip is a reflection, the amplitude step is a projection, an atomic density is a fixed point, the iteration stays real, and it treats every translate and the inverse of a start in the same way. The last fact is why the result is found only up to a shift of the origin and an inversion.

Setting. The unit cell is an n1×n2n_1 \times n_2 grid, written Ω\Omega, with indices taken modulo the grid. A density is a real function ρ\rho on Ω\Omega, and its structure factors are the unnormalized DFT F=DρF = \mathcal{D}\rho, F(h)=∑xρ(x)e−2πi h⋅x/nF(h) = \sum_{x} \rho(x) e^{-2\pi i\, h \cdot x / n}, where h⋅x/nh \cdot x / n means h1x1/n1+h2x2/n2h_1 x_1/n_1 + h_2 x_2/n_2. The set O\mathcal{O} of observed indices does not contain 00 (the case where it does is the same with fewer words) and is symmetric, h∈O⇒−h∈Oh \in \mathcal{O} \Rightarrow -h \in \mathcal{O}. The data are A(h)=∣F∗(h)∣A(h) = |F_*(h)| for h∈Oh \in \mathcal{O}, where F∗F_* belongs to the true density ρ∗\rho_*. Since ρ∗\rho_* is real, A(−h)=A(h)A(-h) = A(h).

One cycle of the algorithm maps FF to F′F' by

  • lines L3 to L5: ρ=D−1F\rho = \mathcal{D}^{-1} F, g=Φδ(ρ)g = \Phi_\delta(\rho) with Φδ(ρ)(x)=ρ(x)\Phi_\delta(\rho)(x) = \rho(x) if ρ(x)>δ\rho(x) > \delta and −ρ(x)-\rho(x) otherwise, and G=DgG = \mathcal{D} g;
  • lines L6 to L9: F′=Π(G)F' = \Pi(G), where Π(G)(h)=A(h) G(h)/∣G(h)∣\Pi(G)(h) = A(h)\, G(h)/|G(h)| for h∈Oh \in \mathcal{O} (and A(h)A(h) if G(h)=0G(h) = 0), Π(G)(0)=G(0)\Pi(G)(0) = G(0), and Π(G)(h)=0\Pi(G)(h) = 0 for the other hh.

Lemma 1 (the flip is a reflection). Let Tδ(ρ)(x)=ρ(x)T_\delta(\rho)(x) = \rho(x) if ρ(x)>δ\rho(x) > \delta and 00 otherwise. Then Φδ=2Tδ−I\Phi_\delta = 2 T_\delta - I. For δ=0\delta = 0, T0T_0 is the nearest-point projection onto the convex cone C+C_+ of nonnegative densities, so Φ0=2PC+−I\Phi_0 = 2 P_{C_+} - I is the reflection through C+C_+, and Φ0(ρ)=∣ρ∣\Phi_0(\rho) = |\rho|.

Proof. If ρ(x)>δ\rho(x) > \delta, then 2Tδ(ρ)(x)−ρ(x)=ρ(x)2T_\delta(\rho)(x) - \rho(x) = \rho(x); otherwise it is −ρ(x)-\rho(x). For δ=0\delta = 0, the nearest nonnegative number to a real vv is max⁡(v,0)\max(v, 0), and the squared distance is a sum over the points, so the projection acts point by point. 2max⁡(v,0)−v=∣v∣2\max(v, 0) - v = |v|. □\square

For δ>0\delta > 0, TδT_\delta is hard thresholding. It is not the projection onto a convex set, and the reflection picture holds only in this loose sense. The flip keeps the large values and changes the sign of the small ones, which pushes weight from the region of low density into the atoms.

Lemma 2 (the amplitude step is a projection). Let MM be the set of FF with ∣F(h)∣=A(h)|F(h)| = A(h) for h∈Oh \in \mathcal{O} and F(h)=0F(h) = 0 for h∉O∪{0}h \notin \mathcal{O} \cup \{0\}, with F(0)F(0) free. Then Π(G)\Pi(G) is a nearest point of MM to GG. By the Parseval theorem, D−1ΠD\mathcal{D}^{-1}\Pi\mathcal{D} is a nearest-point map onto the densities whose transforms lie in MM.

Proof. The squared distance ∑h∣G(h)−F(h)∣2\sum_h |G(h) - F(h)|^2 splits over hh. At h∈Oh \in \mathcal{O} the nearest complex number of modulus A(h)A(h) is A(h)G(h)/∣G(h)∣A(h) G(h)/|G(h)|, by the triangle inequality, and any such number if G(h)=0G(h) = 0. At h=0h = 0 the value is free, so F(0)=G(0)F(0) = G(0). At the other hh the value must be 00. The unnormalized DFT scales all distances by the same factor n1n2\sqrt{n_1 n_2}. □\square

So one cycle is ρ↦D−1ΠD Φδ(ρ)\rho \mapsto \mathcal{D}^{-1} \Pi \mathcal{D}\, \Phi_\delta(\rho): a projection onto the data after a reflection through the constraint in real space. Error reduction would use TδT_\delta in place of Φδ\Phi_\delta. This places charge flipping in the family of reflection methods with hybrid input-output and the difference map.

Lemma 3 (the density stays real). If F(−h)=F(h)‾F(-h) = \overline{F(h)} for all hh at the start, this holds after every cycle, so every ρ\rho is real.

Proof. If FF has this symmetry, ρ\rho is real, so gg is real and G(−h)=G(h)‾G(-h) = \overline{G(h)}. Then Π(G)(−h)=A(−h)G(−h)/∣G(−h)∣=A(h)G(h)/∣G(h)∣‾\Pi(G)(-h) = A(-h) G(-h)/|G(-h)| = \overline{A(h) G(h)/|G(h)|} for h∈Oh \in \mathcal{O}, since A(−h)=A(h)A(-h) = A(h) and O\mathcal{O} is symmetric; also G(0)G(0) is real, and the zero entries stay zero. □\square

Theorem 1 (an atomic density is a fixed point). Suppose that every value of ρ∗\rho_* is either 00 or larger than δ\delta, and that F∗(h)=0F_*(h) = 0 for every h∉O∪{0}h \notin \mathcal{O} \cup \{0\} (for instance, every h≠0h \ne 0 is observed). Start the iteration at F=F∗F = F_*, the value at 00 included. Then every cycle returns F∗F_*, and R=0R = 0.

Proof. ρ=ρ∗\rho = \rho_*. At points with ρ∗>δ\rho_* > \delta the flip keeps the value, and at points with ρ∗=0\rho_* = 0 it gives −0=0-0 = 0; so g=ρ∗g = \rho_* and G=F∗G = F_*. For h∈Oh \in \mathcal{O}, A(h)G(h)/∣G(h)∣=F∗(h)A(h) G(h)/|G(h)| = F_*(h) when F∗(h)≠0F_*(h) \ne 0; when F∗(h)=0F_*(h) = 0, A(h)=0A(h) = 0 and the step gives 00. The entry at 00 is G(0)=F∗(0)G(0) = F_*(0), and the other entries are 0=F∗(h)0 = F_*(h) by the hypothesis. So F′=F∗F' = F_*. The R-value compares ∣G∣=∣F∗∣|G| = |F_*| with AA, which agree. □\square

The theorem does not say that the iteration reaches F∗F_*, and a density that is close to atomic but has small nonzero values below δ\delta is not a fixed point: those values change sign every cycle. In practice the iteration then wanders near the solution, which is why the R-value stays above zero after convergence.

Theorem 2 (translation and inversion). Let FF obey Friedel symmetry and let (Fk)(F_k) be the sequence of the iteration from F0=FF_0 = F, with the densities ρk=D−1Fk\rho_k = \mathcal{D}^{-1} F_k.

  1. For a grid vector tt, the iteration from F0(h)e−2πi h⋅t/nF_0(h) e^{-2\pi i\, h \cdot t/n} gives the densities ρk(x−t)\rho_k(x - t).
  2. The iteration from F0‾\overline{F_0} gives the densities ρk(−x)\rho_k(-x).

Proof. (1) Let Stρ(x)=ρ(x−t)S_t \rho(x) = \rho(x - t). Then DStρ(h)=e−2πi h⋅t/nDρ(h)\mathcal{D} S_t \rho(h) = e^{-2\pi i\, h \cdot t/n} \mathcal{D}\rho(h). The flip acts point by point, so ΦδSt=StΦδ\Phi_\delta S_t = S_t \Phi_\delta. The step Π\Pi commutes with multiplication by e−2πi h⋅t/ne^{-2\pi i\, h \cdot t/n}, because that factor has modulus 11, does not change which entries are zero, and is 11 at h=0h = 0. So one cycle maps StρkS_t \rho_k to Stρk+1S_t \rho_{k+1}, and induction gives the claim. (2) Let Jρ(x)=ρ(−x)J\rho(x) = \rho(-x). For real ρ\rho, DJρ=Dρ‾\mathcal{D} J \rho = \overline{\mathcal{D} \rho}. The flip commutes with JJ, and Π(G‾)=Π(G)‾\Pi(\overline{G}) = \overline{\Pi(G)} because AA is real and conjugation keeps moduli. The same induction applies. □\square

The data are the same for ρ∗\rho_*, its translates and its inverse. By Theorem 2 the algorithm has no way to prefer one of them, so the origin and the hand of the result are arbitrary. In the space group P1P1 every origin is allowed, so this is no loss. For other symmetries, charge flipping works in P1P1 and the symmetry elements and the origin are found from the result afterward.

What is not proved. There is no theorem that charge flipping converges, or that a fixed point with a low R-value is the true structure. Theorem 1 is about the truth, not about other fixed points; the tests on the page include a one-dimensional case in which the iteration reaches a dense density with a very low R-value that is not the structure. Success in three-dimensional crystallography is a measurement: Oszlanyi and Suto report that the method solves many structures at atomic resolution, and the Superflip manual treats the R-value as an indicator of convergence, not a proof of a solution.

Complexity

In the real RAM model with the fast Fourier transform, each cycle costs two DFTs of NN points, O(Nlog⁡N)O(N \log N), plus O(N)O(N) for the flip and the amplitude step. KK cycles cost O(KNlog⁡N)O(K N \log N), and the memory holds a few arrays of NN numbers. The number of cycles to a solution is random and depends on the structure, the resolution and δ\delta; for the small test above it is about 50 to 80.

Properties

  • Ab initio. The method uses only the amplitudes and the fact that the density is mostly near zero with a few peaks.
  • No symmetry needed. It works in P1P1. The symmetry and the origin are found from the result afterward.
  • Random start. Each run starts from random phases, and different starts can give different results. Runs are repeated, and the best is kept.
  • One parameter. Only δ\delta must be chosen.
  • Atomic resolution. The method relies on separated peaks in the density, so it needs data to near atomic resolution (a heuristic, not a sharp limit).

Variants and improvements

  • Weak reflections (Oszlanyi and Suto 2005). For the weakest observed reflections, the phase is not simply copied from GG but shifted by π/2\pi/2, which helps the iteration leave stagnation.
  • More than three dimensions. Superflip applies the same cycle to the density of modulated and incommensurate structures in superspace, which has more than three dimensions.
  • Extra constraints in real space. The flip can be combined with other constraints on the density, for example on its histogram or its symmetry, once a first map is available.
  • Relation to other methods. With the threshold in place of the flip, the method becomes error reduction. With other mixes of projection and reflection it becomes HIO, the difference map or RAAR.

When to use it

Use charge flipping to solve small molecule and inorganic crystal structures from single crystal or powder data with atomic resolution, especially when no model is available or the symmetry is uncertain. It is simple to run and often works where the space group is not known. For large structures with many atoms, or for data at lower resolution, direct methods and dual space programs or, for macromolecules, phasing by heavy atoms or molecular replacement are the usual choices. To find a few heavy atoms, the Patterson function is another classic tool.

Pitfalls

  • Wrong δ\delta. If δ\delta is too small, the density can settle into a wrong state with many small positive values. If it is too large, real atoms are flipped. Try several values.
  • Trust in R alone. A low R-value is a sign, not a proof. Check that the density has sensible peaks, distances and a chemically plausible structure.
  • Missing reflections. Unobserved reflections are set to zero, which adds ripple. Large gaps in the data, such as missing low angle reflections, make convergence harder.
  • Origin and hand. The result is shifted and possibly inverted. Compare structures only after a search over shifts and inversion, and fix the origin from the symmetry.
  • One run is not enough. Some starts stagnate. Run several starts and keep the best.
  • A grid that is too coarse. The grid must be fine enough to sample the peaks of the atoms at the resolution of the data, or the flip mixes atoms with their surroundings.

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.

charge_flipping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/charge-flipping/. The authors are listed in prov/3DN6XM.jsonl.

"""Charge flipping (Oszlanyi and Suto 2004) for a periodic density in P1.

Conventions:
- The density rho is a real n1 x n2 image on one unit cell (use n1 = 1 for a
  1D cell). Its structure factors are the unnormalized DFT F = DFT2(rho), so
  F(h) = sum_x rho(x) exp(-2 pi i h . x / n), and rho = IDFT2(F) (imgkit).
- The data are the amplitudes amp[h] = |F(h)| for the indices with
  observed[h] true. F(0), the total charge, is usually not observed.
- A real density has Friedel symmetry F(-h) = conj(F(h)); the random start
  phases obey it, so every density in the iteration is real.

Cost per cycle: two 2D DFTs and O(n1 n2) other work.
"""

import cmath
import math
import random

from imgkit import dft2, idft2


def neg(k, l, n1, n2):
    """The index -h of h = (k, l), modulo the grid."""
    return (-k) % n1, (-l) % n2


def random_start(amp, observed, seed):
    """F(h) = amp exp(i phi) with random phases, Friedel pairs conjugate, F = 0 elsewhere.

    An index with h = -h (the origin, or a Nyquist index) gets the phase 0
    or pi, so that F(h) is real there.
    """
    rng = random.Random(seed)
    n1, n2 = len(amp), len(amp[0])
    f = [[0j] * n2 for _ in range(n1)]
    for k in range(n1):
        for l in range(n2):
            if not observed[k][l]:
                continue
            mk, ml = neg(k, l, n1, n2)
            if (mk, ml) == (k, l):
                f[k][l] = complex(amp[k][l] * rng.choice((1.0, -1.0)))
            elif (k, l) < (mk, ml):
                phi = rng.uniform(-math.pi, math.pi)
                f[k][l] = amp[k][l] * cmath.exp(1j * phi)
                f[mk][ml] = amp[mk][ml] * cmath.exp(-1j * phi)
    return f


def flip(rho, delta):
    """g = rho where rho > delta, and -rho elsewhere."""
    return [[v if v > delta else -v for v in row] for row in rho]


def r_factor(amp, observed, g_spec):
    """R = sum | |Fobs| - |G| | / sum |Fobs| over the observed indices (a convergence indicator)."""
    num = den = 0.0
    for ra, ro, rg in zip(amp, observed, g_spec):
        for a, o, g in zip(ra, ro, rg):
            if o:
                num += abs(a - abs(g))
                den += a
    return num / den


def charge_flipping(amp, observed, delta, cycles, seed=0, start=None):
    """Run charge flipping and return (rho, R) after the given number of cycles.

    start, if given, replaces the random start structure factors, F(0)
    included (it must obey Friedel symmetry). F(0) is free: the random start
    sets it to 0 unless it is observed, and every later cycle gives it the
    value G(0) of the flipped density.
    """
    n1, n2 = len(amp), len(amp[0])
    f = [list(row) for row in start] if start is not None else random_start(amp, observed, seed)  # @line L1
    rho, r = None, 1.0
    for _ in range(cycles):  # @line L2
        rho = [[v.real for v in row] for row in idft2(f)]  # @line L3
        g = flip(rho, delta)  # @line L4
        gs = dft2(g)  # @line L5
        r = r_factor(amp, observed, gs)
        for k in range(n1):  # @line L6
            for l in range(n2):
                if observed[k][l]:
                    s = gs[k][l]
                    f[k][l] = amp[k][l] * s / abs(s) if abs(s) > 0.0 else complex(amp[k][l])  # @line L7
                elif (k, l) == (0, 0):
                    f[k][l] = gs[0][0]  # @line L8
                else:
                    f[k][l] = 0j  # @line L9
    rho = [[v.real for v in row] for row in idft2(f)]
    return rho, r  # @line L10
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.

Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
  row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
  the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
  otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
  (wrapped around), so a delta kernel gives the identity and no shift.
"""

import cmath
import math

# ------------------------------------------------------------------ images


def new_image(n1, n2, value=0.0):
    """An n1 x n2 image (n1 rows, n2 columns) filled with value."""
    return [[value] * n2 for _ in range(n1)]


def img_add(a, b):
    """The pixelwise sum a + b."""
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def img_scale(a, c):
    """The image c a."""
    return [[c * x for x in row] for row in a]


def img_dot(a, b):
    """<a, b> = sum conj(a_ij) b_ij."""
    return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def img_norm(a):
    """The Euclidean (Frobenius) norm of an image."""
    return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))


def flatten(img):
    """Row-major vector of an image."""
    return [x for row in img for x in row]


def unflatten(v, n1, n2):
    """The n1 x n2 image of a row-major vector."""
    return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]


# ------------------------------------------------------------------ DFT


def _is_pow2(n):
    return n > 0 and n & (n - 1) == 0


def _fft_pow2(x):
    """Iterative radix-2 FFT, unnormalized forward transform."""
    n = len(x)
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
        for start in range(0, n, size):
            for k in range(half):
                u = a[start + k]
                v = a[start + k + half] * tw[k]
                a[start + k] = u + v
                a[start + k + half] = u - v
        size *= 2
    return a


def dft(x):
    """X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
    n = len(x)
    if n == 0:
        return []
    if _is_pow2(n):
        return _fft_pow2(x)
    w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
    return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]


def idft(xf):
    """x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
    n = len(xf)
    if n == 0:
        return []
    y = dft([complex(v).conjugate() for v in xf])
    return [v.conjugate() / n for v in y]


def _rows_then_cols(img, f):
    rows = [f(row) for row in img]
    cols = [f(list(col)) for col in zip(*rows)]
    return [list(r) for r in zip(*cols)]


def dft2(img):
    """2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
    return _rows_then_cols(img, dft)


def idft2(img):
    """Inverse 2D DFT, with the factor 1 / (n1 n2)."""
    return _rows_then_cols(img, idft)


def _shift1(x, s):
    return list(x[s:]) + list(x[:s])


def fftshift(x):
    """Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [fftshift(r) for r in x]
        return _shift1(rows, (len(rows) + 1) // 2)
    return _shift1(x, (len(x) + 1) // 2)


def ifftshift(x):
    """The inverse of fftshift (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [ifftshift(r) for r in x]
        return _shift1(rows, len(rows) // 2)
    return _shift1(x, len(x) // 2)


def circ_conv(x, h):
    """Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
    n = len(x)
    nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
    return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]


def circ_conv2(img, h):
    """Periodic 2D convolution with the kernel h centered at index (0, 0)."""
    n1, n2 = len(img), len(img[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    out = new_image(n1, n2)
    for i in range(n1):
        for j in range(n2):
            out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
    return out


# ------------------------------------------------------------------ phantoms


def pixel_centers(n):
    """(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    return xs, ys


# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
    (2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
    (-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
    (-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
    (-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
    (0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
    (0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
    (0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
    (0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
    (0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
    (0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]

# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
    (rho, a, b, x0, y0, phi)
    for rho, (_, a, b, x0, y0, phi) in zip(
        (1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
    )
]


def ellipse_value(x, y, table):
    """The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
    total = 0.0
    for rho, a, b, x0, y0, phi in table:
        c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
        dx, dy = x - x0, y - y0
        u = dx * c + dy * s
        v = -dx * s + dy * c
        if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
            total += rho
    return total


def ellipse_phantom(n, table):
    """The n x n image of an ellipse table, sampled at the pixel centers."""
    xs, ys = pixel_centers(n)
    return [[ellipse_value(x, y, table) for x in xs] for y in ys]


def disk_phantom(n, radius):
    """1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
    xs, ys = pixel_centers(n)
    r2 = radius * radius
    return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]


def spikes_1d(n, positions, amplitudes):
    """A signal of length n with the given amplitudes at the given positions."""
    out = [0.0] * n
    for p, a in zip(positions, amplitudes):
        out[p] += a
    return out


# ------------------------------------------------------------------ projector


def parallel_beam_matrix(n, angles, nbins):
    """Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.

    Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
    value times the pixel area over the bin width is split linearly between
    the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
    a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
    Returns the sparse rows, each a list of (column, weight) pairs.
    Pixel-driven projection has a ripple: with a bin width close to the pixel
    size, a disk projection is off by up to about 10 percent in some bins. A
    bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
    1 percent.
    """
    xs, ys = pixel_centers(n)
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    scale = (2.0 / n) ** 2 / width
    rows = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        acc = [dict() for _ in range(nbins)]
        for i, y in enumerate(ys):
            for j, x in enumerate(xs):
                t = (x * c + y * s + smax) / width - 0.5
                b0 = math.floor(t)
                frac = t - b0
                col = i * n + j
                for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
                    if 0 <= b < nbins and w > 0.0:
                        acc[b][col] = acc[b].get(col, 0.0) + w * scale
        rows.extend(sorted(d.items()) for d in acc)
    return rows


def sp_matvec(rows, x):
    """y = A x for sparse rows of (column, weight) pairs."""
    return [sum(w * x[c] for c, w in row) for row in rows]


def sp_rmatvec(rows, y, ncols):
    """x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
    out = [0.0] * ncols
    for row, yi in zip(rows, y):
        if yi == 0:
            continue
        for c, w in row:
            out[c] += w.conjugate() * yi
    return out


# ------------------------------------------------------------------ noise


def gauss_noise(rng, shape, sigma):
    """Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
    if isinstance(shape, int):
        return [rng.gauss(0.0, sigma) for _ in range(shape)]
    n1, n2 = shape
    return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]


def _poisson_small(rng, lam):
    """Knuth's product method, exact for a mean lam <= 30."""
    limit = math.exp(-lam)
    k, p = 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
test_charge_flipping.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/charge-flipping/. The authors are listed in prov/3DN6XM.jsonl.

import cmath
import math
import random

from charge_flipping import charge_flipping, flip, r_factor, random_start
from imgkit import dft2, idft2


def structure(n1, n2, natoms, seed):
    """Point atoms of weight 1 or 2 on distinct grid points, zero elsewhere."""
    rng = random.Random(seed)
    rho = [[0.0] * n2 for _ in range(n1)]
    for i, j in rng.sample([(i, j) for i in range(n1) for j in range(n2)], natoms):
        rho[i][j] = rng.choice((1.0, 1.0, 2.0))
    return rho


def data(rho, observe_origin=False):
    f = dft2(rho)
    n1, n2 = len(rho), len(rho[0])
    amp = [[abs(v) for v in row] for row in f]
    obs = [[True] * n2 for _ in range(n1)]
    obs[0][0] = observe_origin
    return f, amp, obs


def match_error(rho, true):
    """Relative error after the best shift and inversion, with the mean set to that of true."""
    n1, n2 = len(rho), len(rho[0])
    shift = (sum(map(sum, true)) - sum(map(sum, rho))) / (n1 * n2)
    best = math.inf
    for inv in (1, -1):
        for si in range(n1):
            for sj in range(n2):
                e = sum(
                    (rho[(inv * i + si) % n1][(inv * j + sj) % n2] + shift - true[i][j]) ** 2
                    for i in range(n1)
                    for j in range(n2)
                )
                best = min(best, e)
    return math.sqrt(best / sum(v * v for row in true for v in row))


def max_diff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def test_flip_with_zero_threshold_is_the_reflector():
    rng = random.Random(1)
    rho = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(5)]
    g = flip(rho, 0.0)
    for rr, rg in zip(rho, g):
        for v, w in zip(rr, rg):
            assert w == abs(v)
            assert abs(w - (2 * max(v, 0.0) - v)) < 1e-15


def test_random_start_obeys_friedel_and_gives_a_real_density():
    true = structure(8, 16, 6, 2)
    _, amp, obs = data(true)
    f = random_start(amp, obs, 3)
    for k in range(8):
        for l in range(16):
            assert abs(f[k][l] - f[-k % 8][-l % 16].conjugate()) < 1e-12
            assert abs(abs(f[k][l]) - (amp[k][l] if obs[k][l] else 0.0)) < 1e-12
    assert max(abs(v.imag) for row in idft2(f) for v in row) < 1e-12


def test_atomic_density_is_a_fixed_point():
    true = structure(8, 8, 5, 4)
    f, amp, obs = data(true)
    for delta in (0.0, 0.3, 0.9):
        rho, r = charge_flipping(amp, obs, delta, 5, start=f)
        assert max_diff(rho, true) < 1e-12
        assert r < 1e-13


def test_one_cycle_matches_direct_sums():
    true = structure(4, 4, 3, 5)
    _, amp, obs = data(true)
    start = random_start(amp, obs, 6)
    delta = 0.25
    n = 4
    f = [list(row) for row in start]
    for _ in range(3):
        rho = [
            [sum(f[k][l] * cmath.exp(2j * math.pi * (k * i + l * j) / n) for k in range(n) for l in range(n)).real / 16 for j in range(n)]
            for i in range(n)
        ]
        g = [[v if v > delta else -v for v in row] for row in rho]
        gs = [
            [sum(g[i][j] * cmath.exp(-2j * math.pi * (k * i + l * j) / n) for i in range(n) for j in range(n)) for l in range(n)]
            for k in range(n)
        ]
        f = [[amp[k][l] * gs[k][l] / abs(gs[k][l]) if obs[k][l] else (gs[k][l] if (k, l) == (0, 0) else 0j) for l in range(n)] for k in range(n)]
    want = [[v.real for v in row] for row in idft2(f)]
    got, _ = charge_flipping(amp, obs, delta, 3, start=start)
    assert max_diff(got, want) < 1e-10


def test_translation_and_inversion_equivariance():
    true = structure(8, 8, 5, 7)
    _, amp, obs = data(true)
    start = random_start(amp, obs, 8)
    base, _ = charge_flipping(amp, obs, 0.2, 15, start=start)
    t1, t2 = 3, 5
    moved = [[start[k][l] * cmath.exp(-2j * math.pi * (k * t1 + l * t2) / 8) for l in range(8)] for k in range(8)]
    out, _ = charge_flipping(amp, obs, 0.2, 15, start=moved)
    assert max_diff(out, [[base[(i - t1) % 8][(j - t2) % 8] for j in range(8)] for i in range(8)]) < 1e-9
    inverted = [[v.conjugate() for v in row] for row in start]
    out, _ = charge_flipping(amp, obs, 0.2, 15, start=inverted)
    assert max_diff(out, [[base[-i % 8][-j % 8] for j in range(8)] for i in range(8)]) < 1e-9


def test_solves_a_small_2d_structure():
    true = structure(16, 16, 8, 1)
    _, amp, obs = data(true)
    rho10, r10 = charge_flipping(amp, obs, 0.2, 10, seed=1)
    rho, r = charge_flipping(amp, obs, 0.2, 150, seed=1)
    assert r10 > 0.3 and match_error(rho10, true) > 0.5
    assert r < 0.01
    assert match_error(rho, true) < 0.25


def test_r_factor_is_zero_at_the_truth():
    true = structure(8, 8, 4, 9)
    f, amp, obs = data(true)
    assert r_factor(amp, obs, f) < 1e-15


def test_low_r_does_not_prove_a_solution_in_1d():
    # With a small threshold in 1D, the iteration finds a dense density with the
    # right moduli: a low R, a wrong structure.
    true = structure(1, 64, 6, 1)
    _, amp, obs = data(true)
    rho, r = charge_flipping(amp, obs, 0.1, 200, seed=0)
    assert r < 1e-3
    assert match_error(rho, true) > 0.5

History

Oszlanyi and Suto (2004) introduced charge flipping and showed that it solved a range of known structures from their amplitudes alone. In 2005 they added the special treatment of weak reflections. Palatinus and Chapuis (2007) released Superflip, which made the method a standard tool and extended it to structures in more than three dimensions. Oszlanyi and Suto (2008) reviewed the method and its relation to the iterative projection methods of optical phase retrieval, such as the work of Fienup and of Elser.

References

  1. Gabor Oszlanyi and Andras Suto, Ab initio structure solution by charge flipping, Acta Crystallographica A 60(2), 2004, 134 to 141, the algorithm, the threshold delta and the tests on known structures (general locator)
  2. Gabor Oszlanyi and Andras Suto, Ab initio structure solution by charge flipping. II. Use of weak reflections, Acta Crystallographica A 61(1), 2005, 147 to 152, the special treatment of weak reflections (general locator)
  3. Gabor Oszlanyi and Andras Suto, The charge flipping algorithm, Acta Crystallographica A 64(1), 2008, 123 to 134, review of the algorithm, its variants and its relation to other iterative phasing methods (general locator)
  4. Lukas Palatinus and Gervais Chapuis, SUPERFLIP, a computer program for the solution of crystal structures by charge flipping in arbitrary dimensions, Journal of Applied Crystallography 40(4), 2007, 786 to 790, the program Superflip (general locator)
  5. Lukas Palatinus, Superflip user manual, Chapter 2, the charge flipping algorithm (random start phases, F(000), the threshold delta, the R-value as a convergence indicator)

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 correctness
  • 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