---
jupytext:
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.10.3
kernelspec:
  display_name: Python 3 (ipykernel)
  language: python
  name: python3
---

(ch:single-particle-analysis)=
# Single-Particle Analysis

This chapter describes how the three-dimensional structure of a macromolecule is determined from many noisy two-dimensional images of individual copies, each in an unknown orientation. A two-dimensional model problem, in which the unknown orientation is a single in-plane rotation, introduces alignment, averaging, reference bias, maximum-likelihood estimation and classification. The workflow of a three-dimensional reconstruction is then described, and the chapter ends with the Fourier shell correlation, which measures the resolution of the result, and the sharpening of the map. It builds on the projection theorem ({numref}`sec:recon-projection-theorem`) and on the contrast transfer function ({numref}`ch:image-formation`).

(sec:spa-introduction)=
## From projections to a structure

Single-particle analysis (SPA) determines the three-dimensional structure of a macromolecule from images of many identical copies, which lie in random, unknown orientations in a thin layer of vitreous ice. Each image is a projection of the structure ({numref}`subsec:projection-approximation`), and according to the projection theorem, projections from sufficiently many directions determine the structure ({numref}`sec:recon-projection-theorem`). Because radiation damage limits the dose that a copy can receive ({numref}`sec:cryo-em-low-dose`), each copy is imaged only once. Every image is therefore a noisy projection from an unknown direction, and the orientations of the particles and the structure have to be estimated from the images themselves.

```{figure} images/Images13/spa_workflow.jpg
:name: fig:spa-workflow
:alt: Flow chart of the single-particle workflow from raw movies to the atomic model.

Workflow of single-particle analysis. The raw movies are preprocessed, and the picked particles are cleaned by 2D classification. An initial three-dimensional model is refined by iterating between the orientations of the particles and the map. Figure adapted from Jakobi (2020; DOI [10.1051/epn/2020502](https://doi.org/10.1051/epn/2020502)). Reproduced under the right to quote; no further use allowed.
```

In the below video, we explain how a three-dimensional structure is recovered from many noisy projection images via back projection in real space, the equivalent route in Fourier space via the projection theorem, and the iterative single-particle workflow that leads from micrographs to a final Coulomb potential map.

---

<div style="position: relative; width: 100%; padding-bottom: 56.25%; height: 0; overflow: hidden;">
    <iframe
        style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"
        src="https://www.youtube.com/embed/MORHfkY3UR8?si=gtoVjUWeUHd5RmWO"
        title="Single-particle analysis"
        loading="lazy"
        frameborder="0"
        allowfullscreen
    ></iframe>
</div>

---

(sec:spa-reconstruction-problem)=
## SPA illustrated by a two-dimensional model problem

Averaging increases the signal-to-noise ratio in proportion to the number of images ({numref}`sec:cryo-em-noise`, eq. {eq}`eq:snr-averaging`), but this gain is only realised if the images are aligned because the signal of particles in different orientations does not add up coherently. The orientation of each particle must therefore be determined. This can be achieved by finding the orientation of each particle relative to a common reference. The reference is used to determine the orientations, the particles in their estimated orientations are used to determine a new reference, and the two steps are iterated. The principle can be demonstrated in simplified form in two dimensions, where the unknown structure is an image $A$ and the only unknown of each particle is an in-plane rotation angle. In three dimensions, the orientation of a particle is described by three Euler angles, and there are in addition two shifts and the CTF of each image, which are not modelled here ({numref}`subsec:spa-refinement`).

### The observation model

We model each image $X_i$ as a rotated copy of the unknown structure $A$ with added noise,

$$
X_i = R^{\theta_i} A + \sigma G_i,
$$ (eq:image-model)

where $R^{\theta_i}$ denotes the rotation by the unknown angle $\theta_i$, and $G_i$ is Gaussian noise of unit variance, independent for every pixel and image, which is scaled by the standard deviation $\sigma$. Neither $A$ nor any of the angles $\theta_i$ is known. If the angles were known, the structure could be recovered by rotating each image back and averaging,

$$
A \approx \frac{1}{N} \sum_{i=1}^N (R^{\theta_i})^{-1} X_i,
$$ (eq:average-reconstruction)

in which the noise is averaged out as in eq. {eq}`eq:snr-averaging`, whereas the signal adds up coherently. As the structure, we use the letter **Q**, because its asymmetry makes a correct alignment unambiguous and the result immediately recognisable ({numref}`fig:spa-observation-model`). In a real SPA experiment the structure is of course unknown.

```{figure} images/Images13/spa_observation_model.png
:name: fig:spa-observation-model
:alt: The letter Q and five noisy images of it, rotated by different angles.

The observation model. Left: the structure $A$. Right: five images $X_i$ of the same structure, rotated by different angles $\theta_i$ and with added noise.
```

(subsec:spa-cc)=
### Alignment by cross-correlation

The angles (or more generally, orientations) are estimated by comparing each image with a reference, an estimate of $A$, which is rotated to all candidate angles $\theta$. As a measure of the similarity we use the **normalised cross-correlation** (NCC) of the image $X_i$ with the rotated reference $R^{\theta} A_\mathrm{ref}$, summed over the pixels $\mathbf{r}$, where the mean has been subtracted from both images,

$$
\mathrm{NCC}(\theta) = \frac{\sum_\mathbf{r} X_i(\mathbf{r})\, [R^{\theta} A_\mathrm{ref}](\mathbf{r})}
{\|X_i\|\,\|R^{\theta} A_\mathrm{ref}\|}.
$$ (eq:ncc)

The estimated angle is $\hat\theta_i = \arg\max_\theta \mathrm{NCC}(\theta)$. {numref}`fig:spa-ncc-angle` shows the NCC as a function of the candidate angle for one image at different noise levels. At low noise, there is a distinct maximum at the true angle. With increasing noise, the maximum becomes small compared to the fluctuations, and the estimated angle can be wrong.

```{figure} images/Images13/spa_ncc_angle.png
:name: fig:spa-ncc-angle
:alt: Normalised cross-correlation as a function of the candidate angle for three noise levels.

Normalised cross-correlation of one noisy image of Q, which is rotated by 130°, with the rotated reference as a function of the candidate angle, for three increasing noise levels. The dashed line marks the true angle, and the dot marks the maximum of the NCC.
```

The following simulation demonstrate this procedure. At the start, 36 rotated copies of the reference are calculated with a step of 10°. At every change of a slider, it (1) generates $N$ noisy images of Q with random rotations, (2) determines the NCC of every image with all 36 rotated references and the angle of the maximum, (3) rotates every image back by its estimated angle, and (4) averages the aligned images. Here, the reference is the true structure, which is not available in a real experiment. The next section shows the perils of perfoming this procedure on noisy images if the reference is wrong, and {numref}`subsec:spa-refinement` shows how to obtain an initial reference from the particle images.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code** or expand the **Show code** toggle and click ▶ to run the cell. The sliders set the number of images and the noise level $\sigma$. The panels show, from left to right, the true structure (which here is also the reference), the first noisy image, its NCC as a function of the candidate angle with the estimated angle and the true angle, the image rotated back by the estimated angle, and the average of all aligned images. The title of the last panel gives the fraction of images for which the estimated angle is correct and the correlation of the average with the structure $A$.

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults (32 images, $\sigma = 1$).** The NCC has a clear maximum at the true angle, the first image is rotated back correctly, and the average shows the Q.
2. **Increase $\sigma$ to 3 and then to 4.** The maximum of the NCC is no longer distinct, and the estimated angle is wrong for a growing fraction of the images.
3. **Keep $\sigma = 3$ and increase the number of images to 128.** The correlation recovers although a significant fraction of the angles are still wrong. The correctly aligned images add up coherently, whereas the misaligned ones contribute only a diffuse background.
4. **Conclusion.** The qaulity of the alignment depends on the noise level of the experimental images and on the quality of the reference. Here, the reference is the true structure, which makes the problem easier than in practice.
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import rotate as nd_rotate, shift as nd_shift
from ipywidgets import IntSlider, FloatSlider, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, GREY = '#25aae1', '#d91b5c', '#fcb040', '#b3b3b3'

def _letter_pm(text, size=64, fill=0.72):
    """Letter as a smooth image (1 inside the glyph), upright, centred, within a circular window."""
    S = 4
    fig = plt.figure(figsize=(size*S/100, size*S/100), dpi=100)
    fig.text(0.5, 0.5, text, fontsize=size*S*fill*72/100, ha='center', va='center', family='DejaVu Sans')
    fig.canvas.draw()
    g = 1.0 - np.asarray(fig.canvas.buffer_rgba())[:size*S, :size*S, :3].mean(2) / 255.0
    plt.close(fig)
    g = g.reshape(size, S, size, S).mean(axis=(1, 3))
    yy, xx = np.mgrid[:size, :size]
    m = g.sum()
    g = nd_shift(g, (size/2 - 0.5 - (g*yy).sum()/m, size/2 - 0.5 - (g*xx).sum()/m), order=1)
    g = g / g.max()
    return g * (np.hypot(yy - size/2 + 0.5, xx - size/2 + 0.5) < 0.49*size)

def _norm_rows_pm(M):
    M = M.reshape(len(M), -1).astype(float); M = M - M.mean(1, keepdims=True)
    return M / np.linalg.norm(M, axis=1, keepdims=True).clip(1e-10)

_N_pm = 64
_Q_pm = _letter_pm('Q', _N_pm)
_ANG_pm = np.arange(0, 360, 10)
_ROTS_pm = np.array([nd_rotate(_Q_pm, a, reshape=False, order=1) for a in _ANG_pm])
_REF_pm = _norm_rows_pm(_ROTS_pm)

_IDX_pm = np.random.default_rng(7).integers(0, len(_ANG_pm), 128)      # fixed angles of up to 128 images

def _noise_pm(n):
    """Independent noise for every image, so that the first images stay the same when their number changes."""
    return np.stack([np.random.default_rng((101, i)).standard_normal((_N_pm, _N_pm)) for i in range(n)])

def draw_pm(n_images=32, sigma=1.0):
    idx = _IDX_pm[:n_images]
    imgs = _ROTS_pm[idx] + sigma * _noise_pm(n_images)
    with np.errstate(all='ignore'):
        ncc = _norm_rows_pm(imgs) @ _REF_pm.T                       # n_images x 36
    best = ncc.argmax(1)
    recon = np.zeros((_N_pm, _N_pm))
    for j, a in enumerate(_ANG_pm):                                 # rotate back, one rotation per angle step
        m = best == j
        if m.any():
            recon += nd_rotate(imgs[m].sum(0), -a, reshape=False, order=1)
    recon /= n_images
    ok = (best == idx).mean()
    r = np.corrcoef(recon.ravel(), _Q_pm.ravel())[0, 1]

    fig, axes = plt.subplots(1, 5, figsize=(14, 3.1))
    v = 2*sigma
    axes[0].imshow(_Q_pm, cmap='gray'); axes[0].axis('off')
    axes[0].set_title('structure $A$\n(also the reference)', fontsize=9.5, color=BLUE)
    axes[1].imshow(imgs[0], cmap='gray', vmin=-v, vmax=1 + v); axes[1].axis('off')
    axes[1].set_title(f'image $X_1$ ($\\sigma$ = {sigma:.1f})', fontsize=9.5)
    axes[2].plot(_ANG_pm, ncc[0], color=BLUE, lw=1.6)
    axes[2].axvline(_ANG_pm[idx[0]], color=ORANGE, ls=':', lw=1.8, label='true angle')
    axes[2].axvline(_ANG_pm[best[0]], color=CRIMSON, ls='--', lw=1.4, label='estimated angle')
    axes[2].set_xlabel('candidate angle (°)', fontsize=9); axes[2].set_ylabel('NCC', fontsize=9)
    axes[2].set_xticks([0, 90, 180, 270, 360]); axes[2].grid(alpha=0.25); axes[2].legend(fontsize=7.5)
    axes[2].set_title('NCC of image 1', fontsize=9.5)
    aligned0 = nd_rotate(imgs[0], -_ANG_pm[best[0]], reshape=False, order=1)
    axes[3].imshow(aligned0, cmap='gray', vmin=-v, vmax=1 + v); axes[3].axis('off')
    axes[3].set_title(f'image 1 rotated back\nby {_ANG_pm[best[0]]}°', fontsize=9.5)
    axes[4].imshow(recon, cmap='gray', vmin=recon.min(), vmax=recon.max()); axes[4].axis('off')
    axes[4].set_title(f'average of {n_images} aligned images\ncorrect angles: {100*ok:.0f}%,  correlation: {r:.2f}', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=110, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_pm = {'description_width': '130px'}
n_sl_pm = IntSlider(value=32, min=4, max=128, step=4, description='Number of images', style=_style_pm, layout={'width': '420px'})
s_sl_pm = FloatSlider(value=1.0, min=0.2, max=4.0, step=0.2, description='Noise σ', style=_style_pm, layout={'width': '420px'})
out_pm = ImageWidget(format='png', layout={'max_width': '100%'})

def update_pm(_=None):
    out_pm.value = draw_pm(n_sl_pm.value, s_sl_pm.value)
for _w in (n_sl_pm, s_sl_pm):
    _w.observe(update_pm, names='value')
display(VBox([n_sl_pm, s_sl_pm, out_pm]))
update_pm()
```

(sec:spa-model-bias)=
## Reference bias

In a real experiment, the reference is typically an estimate of the true structure, such as a low-resolution map of a related structure, a map from a previous round of processing, or an initial model that has been calculated from the data. If the reference is wrong, it can nevertheless shape the result if no care is taken. The alignment selects for every image, among all candidate orientations, the one in which the noise-corrupted signal of the image resembles the reference most. For very noisy images the noise itself dominates this selection, and the average of the aligned images resembles the reference even when the images contain no signal at all. This is called **reference bias**, and in cryo-EM is sometimes referred to as ["Einstein from noise"]().

The following simulation uses images of the letter Q with an adjustable signal strength $s$, so that $X_i = s\,R^{\theta_i} A + G_i$ with noise of unit variance, and aligns them to a reference that is chosen by you. The lower panel shows the Fourier ring correlation (FRC) between the averages of two half-sets of the images, which have been aligned and averaged separately. The FRC is the two-dimensional version of the Fourier shell correlation, which is defined in {numref}`subsec:spa-fsc`. It is the correlation of the Fourier transforms of the two averages as a function of the spatial frequency. It is close to 1 if the averages agree, and about 0 if they are unrelated.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. The sliders set the number of images and the signal strength $s$, and the menu allows selecting the reference. The upper panels show the true structure, the reference, one of the images and the average of all images after alignment to the reference. The lower panel shows the FRC between two half-sets that were aligned to the same reference and between two half-sets that were aligned to the same reference after it had been low-pass filtered.

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults.** The images contain only noise, but the average shows a P. Its correlation with the reference is about 0.6, and that with the true structure is zero. The FRC curve from alignment agaist the same reference is close to 1 at low spatial frequencies and still aignificant at higher spatial frequencies, i.e. the two half-sets agree even though there is no signal in the images.
2. **Compare with the blue curve.** After low-pass filtering of the reference, the half-sets still agree at low frequencies, which they share with the reference, but the FRC falls to zero at higher spatial frequencies. A reference can imprint only the frequencies that it contains. This is the reason that the starting reference is filtered strongly, and that the new volume is judged beyond the frequencies of the filter.
3. **Increase the signal strength to about 0.2–0.3.** The average shows features of both letters, and at about 0.5 the true structure dominates, but the imprint of the reference remains visible. At $s = 0.3$, the blue curve rises above zero beyond the filter, because the half-sets now reproduce real signal.
4. **Increase the number of images at $s = 0$.** The P becomes clearer as bias is not removed by more data.
5. **Select Q as the reference at $s = 0$.** The average now shows a Q, although the images contain no signal. A result that looks correct is thus no proof that the data contain the structure. The blue curve again falls to zero beyond the filter.
6. **Compare the references P and Q at $s = 0.3$.** With the correct reference Q, the half-sets agree better at high frequencies than with the wrong reference P. The FRC is high where the half-sets reproduce the same real structure, and it is not inflated by the reference where the reference has been filtered.
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import rotate as nd_rotate, shift as nd_shift
from ipywidgets import IntSlider, FloatSlider, Dropdown, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, GREY = '#25aae1', '#d91b5c', '#fcb040', '#b3b3b3'

def _letter_rb(text, size=64, fill=0.72):
    S = 4
    fig = plt.figure(figsize=(size*S/100, size*S/100), dpi=100)
    fig.text(0.5, 0.5, text, fontsize=size*S*fill*72/100, ha='center', va='center', family='DejaVu Sans')
    fig.canvas.draw()
    g = 1.0 - np.asarray(fig.canvas.buffer_rgba())[:size*S, :size*S, :3].mean(2) / 255.0
    plt.close(fig)
    g = g.reshape(size, S, size, S).mean(axis=(1, 3))
    yy, xx = np.mgrid[:size, :size]
    m = g.sum()
    g = nd_shift(g, (size/2 - 0.5 - (g*yy).sum()/m, size/2 - 0.5 - (g*xx).sum()/m), order=1)
    g = g / g.max()
    return g * (np.hypot(yy - size/2 + 0.5, xx - size/2 + 0.5) < 0.49*size)

_N_rb = 64
_ANG_rb = np.arange(0, 360, 10)
_LET_rb = {t: _letter_rb(t, _N_rb) for t in 'QPR'}
_ROTQ_rb = np.array([nd_rotate(_LET_rb['Q'], a, reshape=False, order=1) for a in _ANG_rb])
_f_rb = np.fft.fftfreq(_N_rb)
_RING_rb = np.rint(np.hypot(*np.meshgrid(_f_rb, _f_rb)) * _N_rb).astype(int)
_NR_rb = _N_rb // 2
_KC_rb = 0.08                                                          # cut-off of the low-pass filter of the reference (cycles per pixel)

def _norm_rows_rb(M):
    M = M.reshape(len(M), -1).astype(float); M = M - M.mean(1, keepdims=True)
    return M / np.linalg.norm(M, axis=1, keepdims=True).clip(1e-10)

def _align_average_rb(imgs, ref):
    """Align every image to the best rotation of the reference and average (one round)."""
    rots = np.array([nd_rotate(ref, a, reshape=False, order=1) for a in _ANG_rb])
    with np.errstate(all='ignore'):
        best = (_norm_rows_rb(imgs) @ _norm_rows_rb(rots).T).argmax(1)
    avg = np.zeros((_N_rb, _N_rb))
    for j, a in enumerate(_ANG_rb):
        m = best == j
        if m.any():
            avg += nd_rotate(imgs[m].sum(0), -a, reshape=False, order=1)
    return avg / len(imgs)

def _frc_rb(a, b):
    fa, fb = np.fft.fft2(a), np.fft.fft2(b)
    s = lambda x: np.bincount(_RING_rb.ravel(), x.ravel(), minlength=_RING_rb.max() + 1)[:_NR_rb]
    with np.errstate(all='ignore'):
        return s((fa * fb.conj()).real) / np.sqrt(s(abs(fa)**2) * s(abs(fb)**2))

def _lowpass_rb(img, kc):
    return np.fft.ifft2(np.fft.fft2(img) * np.exp(-(np.hypot(*np.meshgrid(_f_rb, _f_rb)) / kc)**2)).real

def _corr_rb(a, b):
    return float(np.corrcoef(a.ravel(), b.ravel())[0, 1])

_IDX_rb = np.random.default_rng(2).integers(0, len(_ANG_rb), 2000)     # fixed angles of up to 2000 images

def _noise_rb(n):
    """Independent noise for every image, so that the first images stay the same when their number changes."""
    return np.stack([np.random.default_rng((202, i)).standard_normal((_N_rb, _N_rb)) for i in range(n)])

def draw_bias(n_images=1000, signal=0.0, ref_letter='P'):
    imgs = signal * _ROTQ_rb[_IDX_rb[:n_images]] + _noise_rb(n_images)
    ref = _LET_rb[ref_letter]
    h = n_images // 2
    a1 = _align_average_rb(imgs[:h], ref)                           # half-set 1, aligned to the reference
    a2 = _align_average_rb(imgs[h:], ref)                           # half-set 2, aligned to the same reference
    ref_lp = _lowpass_rb(ref, _KC_rb)                               # the same reference, low-pass filtered as in practice
    b1, b2 = _align_average_rb(imgs[:h], ref_lp), _align_average_rb(imgs[h:], ref_lp)
    avg = 0.5 * (a1 + a2)                                           # average of all images
    k = np.arange(1, _NR_rb) / _N_rb
    frc_same, frc_lp = _frc_rb(a1, a2)[1:], _frc_rb(b1, b2)[1:]

    fig = plt.figure(figsize=(13, 6.2))
    gs = fig.add_gridspec(2, 4, height_ratios=[1, 1.05], hspace=0.38, wspace=0.12)
    top = [fig.add_subplot(gs[0, i]) for i in range(4)]
    top[0].imshow(_LET_rb['Q'], cmap='gray'); top[0].set_title(f'true structure Q\nsignal strength $s$ = {signal:.2f}', fontsize=10, color=BLUE)
    top[1].imshow(ref, cmap='gray'); top[1].set_title(f'reference {ref_letter}', fontsize=10, color=CRIMSON)
    top[2].imshow(imgs[0], cmap='gray', vmin=-3, vmax=3); top[2].set_title('one of the images', fontsize=10)
    top[3].imshow(avg, cmap='gray', vmin=avg.min(), vmax=avg.max()); top[3].set_title(f'average of {n_images} aligned images', fontsize=10)
    for a in top:
        a.axis('off')
    bx = fig.add_subplot(gs[1, :3])
    bx.plot(k, frc_same, color=CRIMSON, lw=1.8, label='half-sets aligned to the same reference')
    bx.plot(k, frc_lp, color=BLUE, lw=1.8, label=f'same reference, low-pass filtered to {_KC_rb} cycles per pixel')
    bx.axvline(_KC_rb, color=BLUE, ls=':', lw=1.2)
    bx.axhline(0.143, color=GREY, ls='--', lw=1.2); bx.axhline(0, color='k', lw=0.6)
    bx.text(0.485, 0.17, '0.143', color='#808080', fontsize=8.5, ha='right')
    bx.set_xlim(0, 0.5); bx.set_ylim(-0.45, 1.05); bx.grid(alpha=0.25)
    bx.set_xlabel('spatial frequency (cycles per pixel)', fontsize=9.5); bx.set_ylabel('FRC of the two half-set averages', fontsize=9.5)
    bx.legend(fontsize=8.5, loc='upper right')
    tx = fig.add_subplot(gs[1, 3]); tx.axis('off')
    tx.text(0.0, 0.95, 'Correlation of the average with', fontsize=10, va='top')
    tx.text(0.0, 0.72, f'the true structure Q:  {_corr_rb(avg, _LET_rb["Q"]):+.2f}', fontsize=10.5, va='top', color=BLUE)
    tx.text(0.0, 0.52, f'the reference {ref_letter}:  {_corr_rb(avg, ref):+.2f}', fontsize=10.5, va='top', color=CRIMSON)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_rb = {'description_width': '130px'}
n_sl_rb = IntSlider(value=1000, min=200, max=2000, step=200, description='Number of images', style=_style_rb, layout={'width': '420px'})
s_sl_rb = FloatSlider(value=0.0, min=0.0, max=0.6, step=0.05, description='Signal strength s', style=_style_rb, layout={'width': '420px'}, readout_format='.2f')
r_dd_rb = Dropdown(options=['P', 'R', 'Q'], value='P', description='Reference', style=_style_rb, layout={'width': '260px'})
out_rb = ImageWidget(format='png', layout={'max_width': '100%'})

def update_rb(_=None):
    out_rb.value = draw_bias(n_sl_rb.value, s_sl_rb.value, r_dd_rb.value)
for _w in (n_sl_rb, s_sl_rb, r_dd_rb):
    _w.observe(update_rb, names='value')
display(VBox([n_sl_rb, s_sl_rb, r_dd_rb, out_rb]))
update_rb()
```

It is important to realise that increasing the number of images does not remove reference bias and that the bias cannot be recognised in the average alone. Two precautions are therefore used in practice. The starting reference is low-pass filtered to a low resolution (for example 40–60 Å), so that it contains no detail that could be imprinted on the noise at higher resolutions expected. In addition, the particles are divided into two half sets, which are refined independently. Their agreement is a measure of the reproducibility of the result, which is the basis of the gold-standard resolution estimate ({numref}`subsec:spa-fsc`).

(sec:spa-ml)=
## Maximum-likelihood alignment

At the SNR of cryo-EM images, the maximum of the NCC is low and broad ({numref}`fig:spa-ncc-angle`), and many orientations have almost the same score. Choosing the single best orientation ignores this uncertainty, and the images are then aligned according to the noise rather than the signal, as in the previous section. **Maximum-likelihood** (ML) alignment treats the orientation as unknown and weights all orientations by their probability. This is a more robust procedure as it carries along the uncertainty in particle orientation throughout the refinement procedure.

For Gaussian noise with variance $\sigma^2$, the probability of observing the image $X_i$ for a given orientation $\theta_j$ and structure $A$ is, according to eq. {eq}`eq:image-model`,

$$
P(X_i \mid \theta_j, A) \propto \exp\!\left[-\frac{\|X_i - R^{\theta_j} A\|^2}{2\sigma^2}\right]
\propto \exp\!\left[\frac{\mathrm{CC}_{ij}}{\sigma^2}\right], \qquad \mathrm{CC}_{ij} = \sum_\mathbf{r} X_i(\mathbf{r})\,[R^{\theta_j} A](\mathbf{r}).
$$ (eq:ml-likelihood)

The factors that do not depend on $\theta_j$, namely $\|X_i\|^2$ and $\|R^{\theta_j} A\|^2 = \|A\|^2$, have been absorbed in the proportionality, so that only the unnormalised cross-correlation $\mathrm{CC}_{ij}$ remains. For uniformly distributed orientations, the probability of each orientation, given the image, is

$$
w_{ij} = P(\theta_j \mid X_i, A) = \frac{\exp\!\left(\mathrm{CC}_{ij}/\sigma^2\right)}{\sum_{j'} \exp\!\left(\mathrm{CC}_{ij'}/\sigma^2\right)}.
$$ (eq:ml-weights)

These weights are soft assignments. For small $\sigma$, they concentrate on the orientation with the highest cross-correlation. For large $\sigma$, they are spread over many orientations. The structure is then updated as a weighted average of the images that are rotated back by each candidate angle,

$$
A \leftarrow \frac{1}{N} \sum_{i=1}^N \sum_j w_{ij}\, (R^{\theta_j})^{-1} X_i.
$$ (eq:ml-update)

Calculating the weights is the E-step (expectation) and updating the structure is the M-step (maximisation) of the **expectation–maximisation algorithm**. Repeating both steps converges to a (local) maximum of the likelihood. In software programs such as RELION, the same principle is applied to the three orientation angles and the shifts, and the weights are also used to assign particles to classes ({numref}`sec:spa-2d-classification`).

The following simulation shows the weights of eq. {eq}`eq:ml-weights` for a single image of Q with known structure.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. The sliders set the noise level $\sigma$, the true angle of the image and the realisation of the noise. The panels show the noisy image, the weights $w_j$ for all 72 candidate angles (the true angle is marked), and the prediction of the model for the image: the reference rotated by the most probable angle (hard assignment), and the sum of the reference rotated by all candidate angles, weighted by $w_j$ (soft assignment). The title of the weight panel states the probability that the true angle lies within 10° of the angle of the image, and the effective number of orientations $1/\sum_j w_j^2$.

```{admonition} Things to try
:class: dropdown
1. **Keep the default noise level $\sigma = 2$.** The weights form a narrow peak at the true angle (for most noise realisations), the probability within 10° of it is about 0.97, and the effective number of orientations is below 2. The hard and the soft prediction are almost the same sharp Q. Projection matching is the limit of ML at low noise.
2. **Increase $\sigma$ stepwise to 4 and 6.** The peak broadens and neighbouring angles receive substantial weights: the effective number of orientations grows to about 3 and 6, and the probability within 10° of the true angle falls to 0.68 and 0.43. The hard prediction remains a sharp Q at a possibly wrong angle, whereas the soft prediction is a Q that is smeared over the range of likely angles, which expresses the uncertainty.
3. **At $\sigma = 14$.** The weights are spread over about 30 orientations, and the soft prediction approaches a rotationally symmetric blob, because the image contains hardly any information on the orientation. In the update of eq. {eq}`eq:ml-update`, such an image contributes with small weights to many orientations, instead of with the full weight to one, possibly wrong, orientation.
4. **Change the noise realisation at $\sigma = 8$.** The most probable angle jumps between very different values, and the probability within 10° of the true angle stays low (0.3 or less): the true angle is neither excluded nor recognised. This is the situation for many images of a dataset at this noise level.
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import rotate as nd_rotate, shift as nd_shift
from ipywidgets import IntSlider, FloatSlider, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, GREY = '#25aae1', '#d91b5c', '#fcb040', '#b3b3b3'

def _letter_ml(text, size=64, fill=0.72):
    S = 4
    fig = plt.figure(figsize=(size*S/100, size*S/100), dpi=100)
    fig.text(0.5, 0.5, text, fontsize=size*S*fill*72/100, ha='center', va='center', family='DejaVu Sans')
    fig.canvas.draw()
    g = 1.0 - np.asarray(fig.canvas.buffer_rgba())[:size*S, :size*S, :3].mean(2) / 255.0
    plt.close(fig)
    g = g.reshape(size, S, size, S).mean(axis=(1, 3))
    yy, xx = np.mgrid[:size, :size]
    m = g.sum()
    g = nd_shift(g, (size/2 - 0.5 - (g*yy).sum()/m, size/2 - 0.5 - (g*xx).sum()/m), order=1)
    g = g / g.max()
    return g * (np.hypot(yy - size/2 + 0.5, xx - size/2 + 0.5) < 0.49*size)

_N_ml = 64
_Q_ml = _letter_ml('Q', _N_ml)
_ANG_ml = np.arange(0, 360, 5)
_ROTS_ml = np.array([nd_rotate(_Q_ml, a, reshape=False, order=1) for a in _ANG_ml])
_ROTF_ml = _ROTS_ml.reshape(len(_ANG_ml), -1)

def draw_ml(sigma=2.0, theta_true=130, seed=0):
    nang = len(_ANG_ml)
    k_true = int(round(theta_true / 5)) % nang
    G = np.random.default_rng(11 + seed).standard_normal((_N_ml, _N_ml))
    X = _ROTS_ml[k_true] + sigma * G                                # image of Q at the true angle
    cc = _ROTF_ml @ X.ravel()                                       # CC_j = sum_r X(r) [R_j A](r)
    logw = cc / sigma**2
    w = np.exp(logw - logw.max()); w /= w.sum()                     # weights w_j, eq. (ml-weights)
    j_best = int(w.argmax())
    near = np.abs((np.arange(nang) - k_true + nang // 2) % nang - nang // 2) <= 2     # within 10 degrees of the true angle
    hard = _ROTS_ml[j_best]                                         # prediction of the model, hard assignment
    soft = (w @ _ROTF_ml).reshape(_N_ml, _N_ml)                     # prediction of the model, soft assignment
    n_eff = 1.0 / np.sum(w**2)

    fig, axes = plt.subplots(1, 4, figsize=(14, 3.4), gridspec_kw={'width_ratios': [1, 1.9, 1, 1]})
    v = 2 * sigma
    axes[0].imshow(X, cmap='gray', vmin=-v, vmax=1 + v); axes[0].axis('off')
    axes[0].set_title(f'image $X$ ($\\sigma$ = {sigma:.1f})', fontsize=9.5)
    axes[1].bar(_ANG_ml, w, width=4.2, color=BLUE)
    axes[1].axvline(_ANG_ml[k_true], color=CRIMSON, ls='--', lw=1.4, label='true angle')
    axes[1].set_xlabel('candidate angle (°)', fontsize=9); axes[1].set_ylabel('weight $w_j$', fontsize=9)
    axes[1].set_xticks([0, 90, 180, 270, 360]); axes[1].set_xlim(-5, 360); axes[1].legend(fontsize=8)
    axes[1].set_title(f'probability within ±10° of the true angle: {w[near].sum():.2f}\neffective number of orientations: {n_eff:.1f}', fontsize=9)
    axes[2].imshow(hard, cmap='gray', vmin=0, vmax=1); axes[2].axis('off')
    axes[2].set_title(f'hard assignment:\nreference at {_ANG_ml[j_best]}°', fontsize=9.5)
    axes[3].imshow(soft, cmap='gray', vmin=0, vmax=1); axes[3].axis('off')
    axes[3].set_title('soft assignment:\n$\\sum_j w_j\\,R^{\\theta_j} A$', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=110, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_ml = {'description_width': '130px'}
s_sl_ml = FloatSlider(value=2.0, min=0.5, max=14.0, step=0.5, description='Noise σ', style=_style_ml, layout={'width': '420px'})
t_sl_ml = IntSlider(value=130, min=0, max=355, step=5, description='True angle (°)', style=_style_ml, layout={'width': '420px'})
n_sl_ml = IntSlider(value=0, min=0, max=9, step=1, description='Noise realisation', style=_style_ml, layout={'width': '420px'})
out_ml = ImageWidget(format='png', layout={'max_width': '100%'})

def update_ml(_=None):
    out_ml.value = draw_ml(s_sl_ml.value, t_sl_ml.value, n_sl_ml.value)
for _w in (s_sl_ml, t_sl_ml, n_sl_ml):
    _w.observe(update_ml, names='value')
display(VBox([s_sl_ml, t_sl_ml, n_sl_ml, out_ml]))
update_ml()
```

(sec:spa-2d-classification)=
## 2D classification

Real datasets are not homogeneous. The particle images include ice contamination, damaged or aggregated particles, and often several views or conformations of the protein. **2D classification** sorts the images into classes of similar appearance and averages the images in each class after alignment. It serves two purposes. It is a quality control, because junk particles form blurred classes that can be discarded. And it combines particles in similar orientations into class averages of a high SNR, in which secondary structure elements can be recognised.

The algorithm extends the alignment of the previous sections to $K$ references. It starts from $K$ initial class averages, which contain no information on the true classes, and iterates two steps. In the first step, every image is compared with all rotations of all $K$ references, and assigned to the class and angle with the highest NCC. In the second step, every reference is replaced by the average of the images assigned to it, after rotating them back. In programs such as RELION, the hard assignment is replaced by the soft assignment of the previous section.

The following simulation mixes images of three different letters (Q, P and R) with random rotations and noise. The $K$ initial class averages are averages of five randomly selected images. They have no information on the letters, and the algorithm sees none of the true labels. The labels are only used afterwards to evaluate the result, where class purity is defined as the fraction of its images that belong to the letter that is most frequent in the class.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. The sliders set the number of images per letter, the noise level $\sigma$, the number of classes $K$ and the random selection of the initial class averages. The iteration slider selects the iteration whose result is displayed. The upper row shows three of the images and the average of all images without alignment. The lower row shows the class averages, with the number of images in each class and the dominant letter with the purity of the class.

```{admonition} Things to try
:class: dropdown
1. **Move the iteration slider from 1 to 12.** The class averages sharpen in the first iterations, because the assignments and the references improve each other, and then no longer change. For the default values, the purity increases from 74% to 98%.
2. **Set $K = 1$.** A single class is the average of all images, which is a blur: images of different letters cannot be averaged.
3. **Set $K = 3$ and step through the random starts 0 to 9.** For seven of the ten starts, each letter has its own class. For the starts 1, 2 and 9, two letters share a class (purity of 64–68%): the algorithm has found a local optimum, which depends on the initial class averages.
4. **Increase $K$ to 5 or 6 and step through the starts again.** Only start 2 still fails, so that the result is less sensitive to the start, but the images of a letter are now distributed over several classes, and at $K = 8$ the classes become noisy. In practice, many more classes are requested than distinct views are expected, for this reason.
5. **Increase $\sigma$ to 2.** With 100 images per letter, the classification fails (purity of about 55%) because the images are too noisy to be assigned reliably. Increasing the number of images per letter to 300 restores it for most starts (purity of 91–97%).
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import rotate as nd_rotate, shift as nd_shift
from ipywidgets import IntSlider, FloatSlider, VBox, HBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, GREY = '#25aae1', '#d91b5c', '#fcb040', '#b3b3b3'

def _letter_cl(text, size=64, fill=0.72):
    S = 4
    fig = plt.figure(figsize=(size*S/100, size*S/100), dpi=100)
    fig.text(0.5, 0.5, text, fontsize=size*S*fill*72/100, ha='center', va='center', family='DejaVu Sans')
    fig.canvas.draw()
    g = 1.0 - np.asarray(fig.canvas.buffer_rgba())[:size*S, :size*S, :3].mean(2) / 255.0
    plt.close(fig)
    g = g.reshape(size, S, size, S).mean(axis=(1, 3))
    yy, xx = np.mgrid[:size, :size]
    m = g.sum()
    g = nd_shift(g, (size/2 - 0.5 - (g*yy).sum()/m, size/2 - 0.5 - (g*xx).sum()/m), order=1)
    g = g / g.max()
    return g * (np.hypot(yy - size/2 + 0.5, xx - size/2 + 0.5) < 0.49*size)

_N_cl = 64
_LETTERS_cl = ['Q', 'P', 'R']
_ANG_cl = np.arange(0, 360, 10)
_ROTS_cl = [np.array([nd_rotate(_letter_cl(t, _N_cl), a, reshape=False, order=1) for a in _ANG_cl]) for t in _LETTERS_cl]
_N_ITER_cl = 12
_cache_cl = {}

def _norm_rows_cl(M):
    M = M.reshape(len(M), -1).astype(float); M = M - M.mean(1, keepdims=True)
    return M / np.linalg.norm(M, axis=1, keepdims=True).clip(1e-10)

_IDX_cl = [np.random.default_rng(3 + c).integers(0, len(_ANG_cl), 300) for c in range(len(_LETTERS_cl))]   # fixed angles

def _data_cl(n_each, sigma):
    """Images of the three letters, in the order Q, P, R, Q, P, R, ...; every image has its own independent noise."""
    imgs, lab = [], []
    for i in range(n_each):
        for c in range(len(_LETTERS_cl)):
            noise = np.random.default_rng((303 + c, i)).standard_normal((_N_cl, _N_cl))
            imgs.append(_ROTS_cl[c][_IDX_cl[c][i]] + sigma * noise); lab.append(c)
    return np.array(imgs), np.array(lab)

def _classify_cl(imgs, K, seed):
    """Unsupervised classification with alignment; returns the class averages and assignments of every iteration."""
    rng = np.random.default_rng(seed + 100)
    A = _norm_rows_cl(imgs)
    refs = np.array([imgs[rng.choice(len(imgs), 5, replace=False)].mean(0) for _ in range(K)])   # random start
    hist = []
    for _ in range(_N_ITER_cl):
        rots = np.array([[nd_rotate(r, a, reshape=False, order=1) for a in _ANG_cl] for r in refs])
        with np.errstate(all='ignore'):
            best = (A @ _norm_rows_cl(rots.reshape(-1, _N_cl, _N_cl)).T).argmax(1)       # image x (class, angle)
        cls, ang = best // len(_ANG_cl), _ANG_cl[best % len(_ANG_cl)]
        new = []
        for k in range(K):
            acc, cnt = np.zeros((_N_cl, _N_cl)), 0
            for a in _ANG_cl:
                m = (cls == k) & (ang == a)
                if m.any():
                    acc += nd_rotate(imgs[m].sum(0), -a, reshape=False, order=1); cnt += m.sum()
            new.append(acc / cnt if cnt else refs[k])
        refs = np.array(new)
        hist.append((refs.copy(), cls.copy()))
    return hist

def draw_cls(n_each=100, sigma=1.25, K=5, seed=0, iteration=12):
    key = (n_each, sigma, K, seed)
    if key not in _cache_cl:
        _cache_cl.clear()
        imgs, lab = _data_cl(n_each, sigma)
        _cache_cl[key] = (imgs, lab, _classify_cl(imgs, K, seed))
    imgs, lab, hist = _cache_cl[key]
    refs, cls = hist[iteration - 1]
    purity = sum(np.bincount(lab[cls == k]).max() for k in range(K) if (cls == k).any()) / len(lab)

    rows = 1 + int(np.ceil(K / 4))
    fig = plt.figure(figsize=(11, 2.9 * rows))
    gs = fig.add_gridspec(rows, 4, hspace=0.6, wspace=0.12)
    v = 2 * sigma
    for i in range(3):
        ax = fig.add_subplot(gs[0, i]); ax.imshow(imgs[i], cmap='gray', vmin=-v, vmax=1 + v); ax.axis('off')
        ax.set_title(f'image {i + 1}', fontsize=9.5)
    ax = fig.add_subplot(gs[0, 3]); ax.imshow(imgs.mean(0), cmap='gray'); ax.axis('off')
    ax.set_title('average of all images,\nno alignment', fontsize=9.5)
    for k in range(K):
        ax = fig.add_subplot(gs[1 + k // 4, k % 4]); ax.axis('off')
        m = cls == k
        if m.any():
            ax.imshow(refs[k], cmap='gray', vmin=refs.min(), vmax=refs.max())
            comp = np.bincount(lab[m], minlength=3); top = comp.argmax()
            ax.text(0.5, -0.04, f'{_LETTERS_cl[top]}: {comp[top] / m.sum():.0%}', transform=ax.transAxes, ha='center', va='top', fontsize=9, color='#606060')
        ax.set_title(f'class {k + 1}\n{m.sum()} images', fontsize=9.5, color=BLUE)
    fig.suptitle(f'iteration {iteration}:  purity of the classes (average) = {purity:.0%}', fontsize=10.5, y=1.0)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_cl = {'description_width': '150px'}
_lay_cl = {'width': '400px'}
n_sl_cl = IntSlider(value=100, min=40, max=300, step=20, description='Images per letter', style=_style_cl, layout=_lay_cl)
s_sl_cl = FloatSlider(value=1.25, min=0.5, max=2.5, step=0.25, description='Noise σ', style=_style_cl, layout=_lay_cl)
k_sl_cl = IntSlider(value=5, min=1, max=8, step=1, description='Number of classes K', style=_style_cl, layout=_lay_cl)
r_sl_cl = IntSlider(value=0, min=0, max=9, step=1, description='Random start', style=_style_cl, layout=_lay_cl)
i_sl_cl = IntSlider(value=_N_ITER_cl, min=1, max=_N_ITER_cl, step=1, description='Iteration', style=_style_cl, layout=_lay_cl)
out_cl = ImageWidget(format='png', layout={'max_width': '100%'})

def update_cl(_=None):
    out_cl.value = draw_cls(n_sl_cl.value, s_sl_cl.value, k_sl_cl.value, r_sl_cl.value, i_sl_cl.value)
for _w in (n_sl_cl, s_sl_cl, k_sl_cl, r_sl_cl, i_sl_cl):
    _w.observe(update_cl, names='value')
display(VBox([HBox([VBox([n_sl_cl, s_sl_cl, k_sl_cl]), VBox([r_sl_cl, i_sl_cl])]), out_cl]))
update_cl()
```

(sec:spa-workflow)=
## From images to a three-dimensional map

The principles of the previous sections carry over to a real project, which adds the third dimension, the CTF and a large amount of data handling. The preparation of the specimen ({numref}`sec:plunge-freezing`) and the recording of the low-dose movies with a direct electron detector ({numref}`subsec:tem-detectors`, {numref}`sec:cryo-em-low-dose`) have been described in earlier chapters, so that this section starts with the recorded movies. 

(subsec:spa-preprocessing)=
### Preprocessing

The movies are recorded at a range of defocus values, typically between 0.5 and 3 μm underfocus ({numref}`subsec:ctf`), and three steps precede the alignment. In the **motion correction**, the frames of each movie are aligned by cross-correlation and summed, with the frames weighted according to the accumulated dose, because the high-resolution information is damaged first. This corrects for the motion of the specimen during the exposure, which is caused by stage drift and beam-induced motion. In the **CTF estimation**, the defocus and the astigmatism of each micrograph are determined by fitting the CTF of eq. {eq}`eq:ctf` to its power spectrum, in which the Thon rings are visible ({numref}`subsec:ctf`). They are needed for the CTF correction in the reconstruction. In the **particle picking**, the positions of the particles are determined, either by comparison with templates or with neural networks that have been trained on a set of manually picked particles, and the particles are cut out in boxes that are about 1.5–2 times as large as the particle. The picking also selects contamination and noise, which are removed by 2D classification ({numref}`sec:spa-2d-classification`).

(subsec:spa-refinement)=
### Initial model and refinement

The orientations are determined as in the two-dimensional problem, now by comparing every particle image with projections of a three-dimensional reference map in all candidate orientations. This is called **projection matching**. Five parameters are estimated for every particle: three Euler angles, which describe the viewing direction and the in-plane rotation, and two shifts. The new orientations yield a new map ({numref}`subsec:spa-fourier-reconstruction`), and the two steps are repeated until the result no longer changes, where the angular sampling is refined as the resolution improves. Current programs use the maximum-likelihood approach of {numref}`sec:spa-ml`, in which each image contributes to several orientations with a weight.

The projection theorem ({numref}`sec:recon-projection-theorem`) makes the comparison efficient. The Fourier transform of the projection of the reference map in an orientation $\Omega$ is the central section $\hat P_\Omega(\mathbf{k})$ of the three-dimensional Fourier transform of the map, perpendicular to the viewing direction. Programs therefore calculate the transform of the reference once and extract sections from it, instead of projecting the map in real space for every orientation. The comparison is the normalised cross-correlation of eq. {eq}`eq:ncc`, now evaluated in Fourier space, where the section is multiplied with the CTF of the particle image,

$$
S(\Omega) = \frac{\mathrm{Re}\sum_{0<|\mathbf{k}|\le k_\mathrm{max}} \hat X_i(\mathbf{k})\,\big[\mathrm{CTF}_i(\mathbf{k})\,\hat P_\Omega(\mathbf{k})\big]^*}
{\sqrt{\sum_{0<|\mathbf{k}|\le k_\mathrm{max}} |\hat X_i(\mathbf{k})|^2\;\sum_{0<|\mathbf{k}|\le k_\mathrm{max}} |\mathrm{CTF}_i(\mathbf{k})\,\hat P_\Omega(\mathbf{k})|^2}}.
$$ (eq:spa-fourier-matching)

The orientation with the largest $S$ is the best match. Except for the CTF and the limit $k_\mathrm{max}$, this is the correlation of eq. {eq}`eq:ncc`, because the correlation of two images equals that of their Fourier transforms (Parseval's theorem), and leaving out $\mathbf{k} = 0$ corresponds to subtracting the mean. The Fourier space has three advantages: the CTF is a simple multiplication, the comparison can be restricted to spatial frequencies below a **resolution limit** $k_\mathrm{max}$, and, as shown below, the calculations are much faster.

The limit has two purposes. Frequencies at which the reference contains no information cannot improve the orientation, but cost computing time, so that $k_\mathrm{max}$ is chosen according to the resolution of the reference. The limit also determines how accurately an orientation can be defined. A rotation by $\Delta\Omega$ moves a feature at a distance $r$ from the centre of the particle by $r\,\Delta\Omega$, which is visible only if it exceeds the resolution $d = 1/k_\mathrm{max}$. The maximum of $S$ therefore has a width of the order of $d/r$, which is about 3.4° for a resolution of 3 Å and a particle radius of 50 Å. A refinement thus starts with a low limit and coarse angular steps, and both are refined as the map improves. The following simulation shows projection matching for a model particle.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. Can you tell from which direction a noisy image was taken? Match it against references from all directions.

```{admonition} Things to try
:class: dropdown
1. **Look at the default view and click Draw new noise.** The image shows hardly more than noise, but the maximum sits at the true orientation.
2. **Increase the noise to 25.** The maximum jumps across the map.
3. **Lower the resolution limit to 0.03.** The maximum dissolves into a plateau, and the best match is most likely wrong.
4. **Set the noise to 0.** The maximum is sharp, and a second, weaker maximum appears corresponding to a view that looks similar.
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import map_coordinates
from ipywidgets import IntSlider, FloatSlider, Button, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, TEAL, GREY = '#25aae1', '#d91b5c', '#fcb040', '#13a89e', '#b3b3b3'

# a model particle: 14 Gaussian blobs (centre in pixels, width, amplitude) at fixed random positions
_rng_pj = np.random.default_rng(4)
_BLOBS_pj = []
while len(_BLOBS_pj) < 14:
    _c = _rng_pj.uniform(-15, 15, 3)
    if np.linalg.norm(_c) < 15:
        _BLOBS_pj.append((tuple(_c), _rng_pj.uniform(2.0, 3.2), _rng_pj.uniform(0.5, 1.0)))
_N_pj, _STEP_pj, _KCAP_pj = 64, 6, 0.25
_g_pj = np.arange(_N_pj) - _N_pj / 2
_X_pj, _Y_pj = np.meshgrid(_g_pj, _g_pj)

def _rot_pj(az, tilt):
    """Orientation with viewing direction (azimuth, tilt) and no further in-plane rotation: R = Rz(az) Ry(tilt) Rz(-az)."""
    a, b = np.radians(az), np.radians(tilt)
    Rz = lambda t: np.array([[np.cos(t), -np.sin(t), 0], [np.sin(t), np.cos(t), 0], [0, 0, 1]])
    Ry = np.array([[np.cos(b), 0, np.sin(b)], [0, 1, 0], [-np.sin(b), 0, np.cos(b)]])
    return Rz(a) @ Ry @ Rz(-a)

def _project_pj(R):
    """Projection of the object along the viewing direction R e_z (a Gaussian projects to a Gaussian)."""
    img = np.zeros((_N_pj, _N_pj))
    for c, s, amp in _BLOBS_pj:
        p = (R.T @ np.array(c, dtype=float))[:2]
        img += amp * s * np.sqrt(2 * np.pi) * np.exp(-((_X_pj - p[0])**2 + (_Y_pj - p[1])**2) / (2 * s**2))
    return img

# Fourier pixels (without the origin) within the radius _KCAP_pj, in cycles per pixel
_ki_pj, _kj_pj = np.meshgrid(_g_pj, _g_pj)
_kx_pj, _ky_pj = (_ki_pj / _N_pj).ravel(), (_kj_pj / _N_pj).ravel()
_kr_pj = np.hypot(_kx_pj, _ky_pj)
_sel_pj = (_kr_pj <= _KCAP_pj) & (_kr_pj > 0)
_kx_pj, _ky_pj, _kr_pj = _kx_pj[_sel_pj], _ky_pj[_sel_pj], _kr_pj[_sel_pj]

# voxel map of the model particle and its three-dimensional Fourier transform, calculated once (the box is padded to twice its size)
_M_pj = 2 * _N_pj
_x3_pj, _y3_pj, _z3_pj = np.meshgrid(_g_pj, _g_pj, _g_pj, indexing='ij')
_vol_pj = np.zeros((_N_pj,) * 3)
for _c_pj, _s_pj, _a_pj in _BLOBS_pj:
    _vol_pj += _a_pj * np.exp(-((_x3_pj - _c_pj[0])**2 + (_y3_pj - _c_pj[1])**2 + (_z3_pj - _c_pj[2])**2) / (2 * _s_pj**2))
_pad_pj = np.zeros((_M_pj,) * 3)
_pad_pj[_N_pj//2:_N_pj//2 + _N_pj, _N_pj//2:_N_pj//2 + _N_pj, _N_pj//2:_N_pj//2 + _N_pj] = _vol_pj
_F3_pj = np.fft.fftshift(np.fft.fftn(np.fft.ifftshift(_pad_pj)))
_F3re_pj, _F3im_pj = np.ascontiguousarray(_F3_pj.real), np.ascontiguousarray(_F3_pj.imag)
del _x3_pj, _y3_pj, _z3_pj, _pad_pj, _F3_pj

def _section_pj(R):
    """Central section of the three-dimensional transform perpendicular to the viewing direction R e_z (projection theorem):
    the points (kx, ky, 0) of the image plane are rotated into the frame of the map and interpolated."""
    idx = _M_pj / 2 + _M_pj * (np.outer(R[:, 0], _kx_pj) + np.outer(R[:, 1], _ky_pj))
    return map_coordinates(_F3re_pj, idx, order=1) + 1j * map_coordinates(_F3im_pj, idx, order=1)

# reference sections for viewing directions covering the whole sphere in steps of _STEP_pj degrees
_AZ_pj = np.arange(0, 360, _STEP_pj)
_TI_pj = np.arange(0, 180 + _STEP_pj, _STEP_pj)
_ANG_pj = [(a, t) for t in _TI_pj for a in _AZ_pj]
_REF_pj = np.array([_section_pj(_rot_pj(a, t)) for a, t in _ANG_pj]).astype(np.complex64)

def _ft_pj(img):
    """Fourier transform of an image at the same Fourier pixels as the reference sections."""
    return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(img))).ravel()[_sel_pj]

def draw_match(azimuth=60, tilt=70, noise=10.0, kmax=0.10, rng=None):
    R_true = _rot_pj(azimuth, tilt)
    rng = np.random.default_rng() if rng is None else rng                 # new noise at every call
    img = _project_pj(R_true) + rng.normal(0, noise, (_N_pj, _N_pj))
    X = _ft_pj(img)
    m = _kr_pj <= kmax
    num = (_REF_pj[:, m].conj() @ X[m]).real
    den = np.linalg.norm(_REF_pj[:, m], axis=1) * np.linalg.norm(X[m])
    S = (num / den).reshape(len(_TI_pj), len(_AZ_pj))
    ib = np.unravel_index(np.argmax(S), S.shape)
    best = (_AZ_pj[ib[1]], _TI_pj[ib[0]])
    R_best = _rot_pj(*best)
    err = np.degrees(np.arccos(np.clip((np.trace(R_true.T @ R_best) - 1) / 2, -1, 1)))

    fig = plt.figure(figsize=(14.5, 4.3))
    gs = fig.add_gridspec(1, 5, width_ratios=[1, 1, 1, 0.45, 3.0], wspace=0.12)
    ax = fig.add_subplot(gs[0]); ax.imshow(img[8:56, 8:56], cmap='gray'); ax.axis('off')
    ax.set_title('particle image\n(noisy projection)', fontsize=10, color=BLUE, loc='left')
    ax = fig.add_subplot(gs[1]); ax.imshow(_project_pj(R_true)[8:56, 8:56], cmap='gray'); ax.axis('off')
    ax.set_title(f'true projection\nazimuth {azimuth}°, tilt {tilt}°', fontsize=10, color='#e08a00', loc='left')
    ax = fig.add_subplot(gs[2]); ax.imshow(_project_pj(R_best)[8:56, 8:56], cmap='gray'); ax.axis('off')
    ax.set_title(f'best match\nazimuth {best[0]}°, tilt {best[1]}°', fontsize=10, color=CRIMSON, loc='left')
    ax = fig.add_subplot(gs[4])
    im = ax.imshow(S, cmap='viridis', extent=[-_STEP_pj/2, 360 - _STEP_pj/2, 180 + _STEP_pj/2, -_STEP_pj/2], aspect='auto')
    ax.plot(azimuth, tilt, 'o', mfc='none', mec=ORANGE, mew=2.2, ms=13, label='true orientation')
    ax.plot(best[0], best[1], 'x', color=CRIMSON, mew=2.6, ms=10, label=f'best match ({err:.0f}° from the true orientation)')
    ax.set_xlim(0, 360); ax.set_ylim(180, 0); ax.set_xticks(range(0, 361, 60)); ax.set_yticks(range(0, 181, 30))
    ax.set_xlabel('azimuth of the viewing direction (°)'); ax.set_ylabel('tilt (°)')
    ax.legend(loc='upper right', fontsize=8.5, framealpha=0.9)
    cb = fig.colorbar(im, ax=ax, pad=0.015); cb.set_label('correlation with the reference')
    ax.set_title('correlation of the particle image with the reference at every orientation', fontsize=10)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_pj = {'description_width': '300px'}
_lay_pj = {'width': '620px'}
az_sl_pj = IntSlider(value=60, min=0, max=359, step=1, description='True orientation: azimuth (°)', style=_style_pj, layout=_lay_pj)
ti_sl_pj = IntSlider(value=70, min=0, max=180, step=1, description='True orientation: tilt (°)', style=_style_pj, layout=_lay_pj)
no_sl_pj = FloatSlider(value=10.0, min=0.0, max=40.0, step=1.0, description='Noise (standard deviation per pixel)', readout_format='.0f', style=_style_pj, layout=_lay_pj)
km_sl_pj = FloatSlider(value=0.10, min=0.02, max=0.20, step=0.01, description='Resolution limit used (cycles per pixel)', readout_format='.2f', style=_style_pj, layout=_lay_pj)
new_btn_pj = Button(description='Draw new noise', icon='refresh', layout={'width': '200px'})
out_pj = ImageWidget(format='png', layout={'max_width': '100%'})

def update_pj(_=None):
    out_pj.value = draw_match(az_sl_pj.value, ti_sl_pj.value, no_sl_pj.value, km_sl_pj.value)
for _w in (az_sl_pj, ti_sl_pj, no_sl_pj, km_sl_pj):
    _w.observe(update_pj, names='value')
new_btn_pj.on_click(update_pj)
display(VBox([az_sl_pj, ti_sl_pj, no_sl_pj, km_sl_pj, new_btn_pj, out_pj]))
update_pj()
```

Working in Fourier space also makes projection matching much cheaper. The following box explains why and compares the time of the calculations in real space and in Fourier space.

````{admonition} Why programs work in Fourier space: the cost of projection matching
:class: dropdown

Two operations dominate the cost of projection matching, and both are much cheaper in Fourier space. The first is the calculation of the references. In real space, the projection of a map with $N^3$ voxels in a given orientation requires rotating the map and summing along the viewing direction, which takes of the order of $N^3$ operations per orientation. In Fourier space, the three-dimensional transform is calculated once, and the central section for each orientation then requires only the $N^2$ points of the section. The second operation is the comparison of a particle image with a reference, in which the shifts are also searched. In real space, the correlation for one shift is a sum over $N^2$ pixels, so that all $N^2$ shifts require $N^4$ operations. According to the cross-correlation theorem, the correlation for all shifts is the inverse Fourier transform of the product $\hat X_i\,\hat P_\Omega^*$, which requires only of the order of $N^2 \log N$ operations. {numref}`fig:spa-timing` compares the times of both routes.

```{figure} images/Images13/spa_timing.png
:name: fig:spa-timing
:alt: Time of the calculation of a reference by projection and by central section, and of the correlation for all shifts by direct summation and by Fourier transforms, as a function of the box size.

Time of the two operations of projection matching in real space (blue) and in Fourier space (crimson), measured with NumPy and SciPy on one computer (median of three measurements). **Left:** one reference for one orientation, calculated by rotating and summing a voxel map (real space) or by extracting the central section from its three-dimensional transform (Fourier space). **Middle:** the total time for $K$ references in a box of 64 pixels, where the Fourier route includes the calculation of the three-dimensional transform. **Right:** the correlation of an image with a reference for all shifts, calculated by summing for every shift or with Fourier transforms. The dotted lines show the scaling with the box size $N$, and the numbers give the factor between the two routes at $N = 64$.
```

At $N = 64$, the central section is 27 times faster than the projection, and the correlation with Fourier transforms is 197 times faster than the direct sum. The blue curves rise with the third and fourth power of $N$ and the crimson curves with the second power, so that the factors increase with the box size, and the advantage is larger for the boxes of a few hundred pixels that are used in practice. The three-dimensional transform that the sections require costs as much as about 6 projections in real space, so that it pays off after only a few orientations. For $K = 1860$ orientations, as in the simulation above, the real-space route takes 12 s and the Fourier route 0.5 s. The two routes give the same result: the central section and the transform of the real-space projection differ by about 2%, which is caused by the interpolation of the section, and the two correlations are identical to the numerical accuracy. The absolute times depend on the computer and on the numerical libraries, but the exponents do not.
````

Projection matching needs a reference. In the first iteration, this is an **initial model**, which is either a map of a related structure or a map that is calculated *ab initio* from the data. Ab initio models are nowadays calculated by **stochastic gradient descent** (SGD), which is implemented in several variants, for example in cryoSPARC (Punjani et al., 2017) and RELION (Kimanius et al., 2021). The map is started as a featureless, strongly low-pass filtered volume. In every iteration, a small random subset of the particle images, a *minibatch* of some hundred images, is compared with the projections of the current map in all orientations, and each image contributes to the orientations with the weights of the maximum-likelihood approach ({numref}`sec:spa-ml`). These weights define the gradient of the likelihood with respect to the map, which is the sum over the images and orientations of the back-projected differences between the images and the projections of the current map. A small step of the map in the direction of the gradient improves it, and the next minibatch is used for the next step. The resolution limit of the comparison is increased during the iterations. The orientations need not be known in advance, and only a part of the data is used in every step, which makes the method fast compared with a refinement. The following simulation shows the principle in a two-dimensional analogue.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or click ▶ to run the cell. From noisy images in unknown rotations to a rubber duck, starting from a featureless blob.
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import base64
import zlib
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import rotate as nd_rotate
from ipywidgets import IntSlider, FloatSlider, Button, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, TEAL, GREY = '#25aae1', '#d91b5c', '#fcb040', '#13a89e', '#b3b3b3'

# the rubber duck of the CryoEM doeboek practicals (128 x 128, 8 bit, compressed), reduced to 32 x 32 pixels and a circular window
_DUCK_128_ab = 'eNrtWmtMm+cVrm8YsB2T2CEQLiYQCMVdIBDiBApJKCWKabNgN2lCEy6FGoxtHNsk2GAbAwZjG2yM77c0XZZsWVW1W6tNW7dqVSutWrtJW9utnaZ1WlW1TXrR1EvSpp32fp/v5jP+TEx++fmD+OPnfM8573nPOe+5554MMsgggwwyyCCDDBIDkwh3hxuLw+GRgMNhN9YGmBtPIOaQyGRKPMhkUg6RgN8wG4LcueQ8ekFxKWM1SosL6Hnk3KAN6ScPcBeW7mTW729uaWmNRUtL8/565s7SwoANaTUhQE6lQdwNTW1sbndPX19/LPr6erq57LamBsgGGjVgQto+PYdC215eU9/U1sk9MyiQKZRq9VQs1GqlQiYYPMPtbGuqrynfTqPkpEMEwI4nkqj5pdUNrUcBt1A2oZkzmJYtFstKNMD/yybDnGZCJgQ2HG1tqC7Np5KI+Du0ALBnQ59+34EObi9fCnOv2JwuDxJcTtsKbIOU38vtOHAfJEI2/g68gMHgski0kuqGg52neFLlLMzt9nh9fmT4vB43bMOsUso71XmwobqERsrCrVcC6OOphVWN7dxewQX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2FCjbtzHb++SGmNF/VP4zOdxu0H70tTO3kfDpX86CaqCiOjZPuWiPnj+E8/+K0+22gf6PXVdEIWA3YDkMeABU7sf5SkPM60vw/gPsrmD/SyViN2Y3DXQuFQeO8+TQ60f0uoLPC+BxWnRylP3/ukMgl16xjw3tSwSWRaJWglw2aAeCva+CnovfsO1ALD6Xxqhr7xapdGZoEhSE2+WwmnQqUXd7HQPd/OcOFrWoRczWrgHJ5Kwe7o8t8E6YfnZSMtDVyiyiZuOxG7ocCe0LVTa2c3r5UnmgP1arlXIpv5fT3lgZW+ltkAQE0pZiaE+OczrQH/f19ZzmQG1k8RYSAbvh26lQAU2mbd9Rs4cV6I9bWpoD7cyqQnOj9lOBBblUWqQ/Li0ugHYh8di7spsb2hMN98eBnVjc3WIPm4CL3Qm+5y7jbu9EZ5BBBhlkkEEGGWSQKv4PPkrrzg=='
_N_ab = 32
_duck_ab = np.frombuffer(zlib.decompress(base64.b64decode(_DUCK_128_ab)), dtype=np.uint8).reshape(128, 128).astype(float)[::-1, :] / 255
_duck_ab = _duck_ab.reshape(_N_ab, 4, _N_ab, 4).mean(axis=(1, 3))
_yy_ab, _xx_ab = np.mgrid[:_N_ab, :_N_ab]
_win_ab = np.hypot(_yy_ab - _N_ab / 2 + 0.5, _xx_ab - _N_ab / 2 + 0.5) < _N_ab / 2
_duck_ab = _duck_ab * _win_ab
_K_ab = 60                                                          # number of candidate rotations (steps of 6 degrees)
_ANG_ab = np.arange(_K_ab) * 360.0 / _K_ab

def _images_ab(n, sigma, rng):
    """n noisy images of the duck in random, unknown rotations."""
    ang = rng.uniform(0, 360, n)
    return np.array([nd_rotate(_duck_ab, a, reshape=False, order=3) for a in ang]) + rng.normal(0, sigma, (n, _N_ab, _N_ab))

def _start_ab(rng):
    """Featureless start: a smooth blob with a little random low-resolution noise."""
    V = rng.normal(0, 1, (_N_ab, _N_ab))
    f = np.fft.fftfreq(_N_ab)
    V = np.fft.ifft2(np.fft.fft2(V) * np.exp(-(np.hypot(*np.meshgrid(f, f)) / 0.06)**2)).real
    return 0.1 * V / V.std() + 0.5 * np.exp(-((_yy_ab - _N_ab / 2)**2 + (_xx_ab - _N_ab / 2)**2) / (2 * (_N_ab / 6)**2))

def _sgd_ab(imgs, sigma, batch, steps, rng, record):
    """Stochastic gradient descent: in every step, a minibatch is compared with the current map in all rotations, the images are
    averaged into an estimate of the map with the weights of the maximum-likelihood approach, and the map moves towards the estimate."""
    V, frames = _start_ab(rng), {}
    if 0 in record:
        frames[0] = V.copy()
    for t in range(1, steps + 1):
        refs = np.array([nd_rotate(V, a, reshape=False, order=1) for a in _ANG_ab]) * _win_ab
        X = imgs[rng.choice(len(imgs), batch, replace=False)] * _win_ab
        d2 = ((X[:, None] - refs[None])**2).reshape(batch, _K_ab, -1).sum(axis=2)
        logw = -d2 / (2 * sigma**2)
        w = np.exp(logw - logw.max(axis=1, keepdims=True)); w /= w.sum(axis=1, keepdims=True)         # weight of every rotation for every image
        A = np.tensordot(w.T, X, axes=(1, 0))                                                          # images weighted per rotation
        estimate = sum(nd_rotate(A[k], -_ANG_ab[k], reshape=False, order=1) for k in range(_K_ab)) / w.sum()
        eta = 0.4 + (0.1 - 0.4) * (t - 1) / max(steps - 1, 1)                                          # step size, decreasing from 0.4 to 0.1
        V = (1 - eta) * V + eta * estimate
        if t in record:
            frames[t] = V.copy()
    return frames

def _align_ab(V):
    """The orientation and the hand of an ab initio map are arbitrary: rotate (and mirror) it to match the true duck for display."""
    best, arg = -2.0, V
    for W in (V, V[:, ::-1]):
        for a in range(0, 360, 3):
            R = nd_rotate(W, a, reshape=False, order=1)
            c = np.corrcoef(R[_win_ab], _duck_ab[_win_ab])[0, 1]
            if c > best:
                best, arg = c, R
    return best, arg

def draw_sgd(noise=1.0, n_images=500, batch=20, steps=60, rng=None):
    rng = np.random.default_rng() if rng is None else rng
    batch = min(batch, n_images)
    imgs = _images_ab(n_images, noise, rng)
    record = sorted({0, 1, 3, 10, 30, steps} & set(range(0, steps + 1)) | {steps})
    frames = _sgd_ab(imgs, noise, batch, steps, rng, set(record))
    fig, axes = plt.subplots(2, 6, figsize=(13, 5.3))
    axes[0, 0].imshow(_duck_ab, cmap='gray'); axes[0, 0].set_title('true object)', fontsize=9.5, color=BLUE, loc='left')
    for j in range(4):
        axes[0, j + 1].imshow(imgs[j], cmap='gray'); axes[0, j + 1].set_title(f'image {j + 1}\n(random rotation, noise)', fontsize=9.5, loc='left')
    axes[0, 5].imshow(imgs.mean(axis=0), cmap='gray'); axes[0, 5].set_title(f'average of all {n_images} images\n(without alignment)', fontsize=9.5, loc='left')
    for j, t in enumerate(record[:6]):
        c, R = _align_ab(frames[t])
        axes[1, j].imshow(R, cmap='gray')
        axes[1, j].set_title(('start: featureless blob' if t == 0 else f'after {t} step' + ('s' if t > 1 else '')), fontsize=9.5, loc='left',
                             color=TEAL if t == steps else 'k')
    for a in axes.ravel():
        a.axis('off')
    fig.text(0.5, 0.03, 'The maps in the lower row are rotated (and mirrored if necessary) to the orientation of the true object, because the orientation of an ab initio map is arbitrary.',
             ha='center', fontsize=9.5)
    fig.tight_layout(rect=(0, 0.05, 1, 1))
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_ab = {'description_width': '300px'}
_lay_ab = {'width': '620px'}
no_sl_ab = FloatSlider(value=1.0, min=0.2, max=4.0, step=0.2, description='Noise (standard deviation per pixel)', readout_format='.1f', continuous_update=False, style=_style_ab, layout=_lay_ab)
n_sl_ab = IntSlider(value=500, min=20, max=1000, step=10, description='Number of images', continuous_update=False, style=_style_ab, layout=_lay_ab)
b_sl_ab = IntSlider(value=20, min=2, max=100, step=1, description='Images per minibatch', continuous_update=False, style=_style_ab, layout=_lay_ab)
s_sl_ab = IntSlider(value=60, min=3, max=100, step=1, description='Number of steps', continuous_update=False, style=_style_ab, layout=_lay_ab)
run_btn_ab = Button(description='Run again (new images, new start)', icon='refresh', layout={'width': '300px'})
out_ab = ImageWidget(format='png', layout={'max_width': '100%'})

def update_ab(_=None):
    out_ab.value = draw_sgd(no_sl_ab.value, n_sl_ab.value, b_sl_ab.value, s_sl_ab.value)
for _w in (no_sl_ab, n_sl_ab, b_sl_ab, s_sl_ab):
    _w.observe(update_ab, names='value')
run_btn_ab.on_click(update_ab)
display(VBox([no_sl_ab, n_sl_ab, b_sl_ab, s_sl_ab, run_btn_ab, out_ab]))
update_ab()
```

Since the map is derived from the data and not from a known structure, it does not suffer from the reference bias of a wrong starting model ({numref}`sec:spa-model-bias`), but the result has to be checked. The images of a structure and of its mirror image cannot be distinguished when the orientations are unknown, so that the hand of the ab initio map is arbitrary and is determined from the refined map, for example from the handedness of α-helices. The method also requires a reasonable distribution of the viewing directions, and the map is checked by comparing its projections with the class averages of {numref}`sec:spa-2d-classification`.

Before ab initio methods became available, initial models were calculated from class averages by <u>angular reconstitution</u>, which makes use of the projection theorem ({numref}`sec:recon-projection-theorem`). The Fourier transforms of two projections are two planes through the origin of Fourier space, which intersect along a line, the <u>common line</u>, on which the two transforms are identical. The directions of this line in the two transforms determine the relative orientation of the two images, up to an ambiguity that a third image resolves. This approach has largely been replaced by the ab initio methods described above.

The initial model is the reference of the first refinement, where it is strongly low-pass filtered to avoid reference bias. The refinement iterates two steps. In the first step, every particle image is compared with the projections of the current map in all orientations (projection matching, eq. {eq}`eq:spa-fourier-matching`, with the weights of {numref}`sec:spa-ml`), and in the second step, a new map is calculated from all images with these orientations ({numref}`subsec:spa-fourier-reconstruction`). The resolution limit of the comparison and the angular sampling follow the resolution that has been reached. The resolution is measured with the gold-standard procedure ({numref}`subsec:spa-fsc`) in which the particles are divided into two halves, which are refined independently, and the resolution is determined from the Fourier shell correlation of the two half-maps. The limit of the next iteration is chosen slightly beyond this resolution, and the angular step is reduced with the limit, because the maximum of the correlation becomes narrower. The iterations are repeated until the resolution no longer improves, which is the case when the information in the data has been exhausted. The following simulation shows this for the two-dimensional analogue of the previous simulation, where the Fourier ring correlation (FRC) takes the place of the FSC.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. Sharpen a blurry initial model by iterating matching and reconstruction, and watch the resolution improve.
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import base64
import zlib
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import rotate as nd_rotate, zoom
from ipywidgets import IntSlider, FloatSlider, Button, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, TEAL, GREY = '#25aae1', '#d91b5c', '#fcb040', '#13a89e', '#b3b3b3'

# the rubber duck of the CryoEM doeboek practicals (128 x 128, 8 bit, compressed), reduced to 64 x 64 pixels and a circular window
_DUCK_128_rf = 'eNrtWmtMm+cVrm8YsB2T2CEQLiYQCMVdIBDiBApJKCWKabNgN2lCEy6FGoxtHNsk2GAbAwZjG2yM77c0XZZsWVW1W6tNW7dqVSutWrtJW9utnaZ1WlW1TXrR1EvSpp32fp/v5jP+TEx++fmD+OPnfM8573nPOe+5554MMsgggwwyyCCDDBIDkwh3hxuLw+GRgMNhN9YGmBtPIOaQyGRKPMhkUg6RgN8wG4LcueQ8ekFxKWM1SosL6Hnk3KAN6ScPcBeW7mTW729uaWmNRUtL8/565s7SwoANaTUhQE6lQdwNTW1sbndPX19/LPr6erq57LamBsgGGjVgQto+PYdC215eU9/U1sk9MyiQKZRq9VQs1GqlQiYYPMPtbGuqrynfTqPkpEMEwI4nkqj5pdUNrUcBt1A2oZkzmJYtFstKNMD/yybDnGZCJgQ2HG1tqC7Np5KI+Du0ALBnQ59+34EObi9fCnOv2JwuDxJcTtsKbIOU38vtOHAfJEI2/g68gMHgski0kuqGg52neFLlLMzt9nh9fmT4vB43bMOsUso71XmwobqERsrCrVcC6OOphVWN7dxewQXNgtnqCHJfTISgDQ6reUFzQdDLbW+sKqSuVwIMlkCiMXYf4g5IlFqjxeFemzvGBrfDY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PXVdEIWA3YDkMeABU7sf5SkPM60vw/gPsrmD/SyViN2Y3DXQuFQeO8+TQ60f0uoLPC+BxWnRylP3/ukMgl16xjw3tSwSWRaJWglw2aAeCva+CnovfsO1ALD6Xxqhr7xapdGZoEhSE2+WwmnQqUXd7HQPd/OcOFrWoRczWrgHJ5Kwe7o8t8E6YfnZSMtDVyiyiZuOxG7ocCe0LVTa2c3r5UnmgP1arlXIpv5fT3lgZW+ltkAQE0pZiaE+OczrQH/f19ZzmQG1k8RYSAbvh26lQAU2mbd9Rs4cV6I9bWpoD7cyqQnOj9lOBBblUWqQ/Li0ugHYh8di7spsb2hMN98eBnVjc3WIPm4CL3Qm+5y7jbu9EZ5BBBhlkkEEGGWSQKv4PPkrrzg=='
_N_rf = 64
_yy_rf, _xx_rf = np.mgrid[:_N_rf, :_N_rf]
_win_rf = np.hypot(_yy_rf - _N_rf / 2 + 0.5, _xx_rf - _N_rf / 2 + 0.5) < _N_rf / 2
_duck_rf = np.frombuffer(zlib.decompress(base64.b64decode(_DUCK_128_rf)), dtype=np.uint8).reshape(128, 128).astype(float)[::-1, :] / 255
_duck_rf = _duck_rf.reshape(_N_rf, 2, _N_rf, 2).mean(axis=(1, 3)) * _win_rf
_k_rf = np.hypot(*np.meshgrid(np.fft.fftfreq(_N_rf), np.fft.fftfreq(_N_rf)))      # spatial frequency of every Fourier pixel (cycles per pixel)

def _images_rf(n, sigma, rng):
    """n noisy images of the duck in random, unknown rotations."""
    ang = rng.uniform(0, 360, n)
    return np.array([nd_rotate(_duck_rf, a, reshape=False, order=3) for a in ang]) + rng.normal(0, sigma, (n, _N_rf, _N_rf))

def _lowpass_rf(V, kc):
    return np.fft.ifft2(np.fft.fft2(V) * np.exp(-(_k_rf / kc)**4)).real

def _ab_initio_rf(imgs, sigma, rng, steps=60, batch=20, K=36):
    """Initial model: stochastic gradient descent as in the previous simulation, with the images reduced to 16 x 16 pixels."""
    n, M = len(imgs), 16
    small = imgs.reshape(n, M, 4, M, 4).mean(axis=(2, 4)); sigma = sigma / 4                      # averaging 4 x 4 pixels reduces the noise by a factor of 4
    yy, xx = np.mgrid[:M, :M]; win = np.hypot(yy - M / 2 + 0.5, xx - M / 2 + 0.5) < M / 2
    ang = np.arange(K) * 360.0 / K
    V = rng.normal(0, 1, (M, M)); f = np.fft.fftfreq(M)
    V = np.fft.ifft2(np.fft.fft2(V) * np.exp(-(np.hypot(*np.meshgrid(f, f)) / 0.06)**2)).real
    V = 0.1 * V / V.std() + 0.5 * np.exp(-((yy - M / 2)**2 + (xx - M / 2)**2) / (2 * (M / 6)**2))
    for t in range(1, steps + 1):
        refs = np.array([nd_rotate(V, a, reshape=False, order=1) for a in ang]) * win
        X = small[rng.choice(n, batch, replace=False)] * win
        d2 = ((X[:, None] - refs[None])**2).reshape(batch, K, -1).sum(axis=2)
        logw = -d2 / (2 * sigma**2); w = np.exp(logw - logw.max(axis=1, keepdims=True)); w /= w.sum(axis=1, keepdims=True)
        A = np.tensordot(w.T, X, axes=(1, 0))
        estimate = sum(nd_rotate(A[k], -ang[k], reshape=False, order=1) for k in range(K)) / w.sum()
        eta = 0.4 - 0.3 * (t - 1) / (steps - 1)
        V = (1 - eta) * V + eta * estimate
    return zoom(V, 4, order=3)                                                                 # on the grid of 64 x 64 pixels, resolution limit 8 pixels

def _match_rf(V, X, sigma, K, kc):
    """One iteration: projection matching of all images X with the map V in K orientations, new map from the weighted images, resolution limit kc."""
    ang = np.arange(K) * 360.0 / K; n = len(X)
    Rf = (np.array([nd_rotate(V, a, reshape=False, order=1) for a in ang]) * _win_rf).reshape(K, -1)
    Xf = (X * _win_rf).reshape(n, -1)
    d2 = (Xf**2).sum(axis=1)[:, None] + (Rf**2).sum(axis=1)[None, :] - 2 * Xf @ Rf.T
    logw = -d2 / (2 * sigma**2); w = np.exp(logw - logw.max(axis=1, keepdims=True)); w /= w.sum(axis=1, keepdims=True)
    A = (w.T @ Xf).reshape(K, _N_rf, _N_rf)
    return _lowpass_rf(sum(nd_rotate(A[k], -ang[k], reshape=False, order=1) for k in range(K)) / w.sum(), kc)

def _frc_rf(A, B, nb=32):
    """Fourier ring correlation of two maps (the two-dimensional counterpart of the FSC)."""
    FA, FB = np.fft.fftshift(np.fft.fft2(A * _win_rf)), np.fft.fftshift(np.fft.fft2(B * _win_rf))
    idx = np.minimum(np.hypot(_yy_rf - _N_rf / 2, _xx_rf - _N_rf / 2).astype(int), nb - 1).ravel()
    num = np.bincount(idx, (FA * FB.conj()).real.ravel(), nb)
    return np.arange(nb) / _N_rf, num / np.sqrt(np.bincount(idx, (abs(FA)**2).ravel(), nb) * np.bincount(idx, (abs(FB)**2).ravel(), nb) + 1e-12)

def _resolution_rf(k, f, kc):
    """Spatial frequency at which the FRC falls below 0.143, searched up to the resolution limit kc."""
    m = (k > 0.03) & (k <= kc + 1e-9); kk, ff = k[m], f[m]
    below = np.where(ff < 0.143)[0]
    if len(below) == 0:
        return kk[-1]
    i = below[0]
    return kk[0] if i == 0 else kk[i - 1] + (0.143 - ff[i - 1]) * (kk[i] - kk[i - 1]) / (ff[i] - ff[i - 1])

def _frame_rf(V0):
    """Rotation and mirror that bring the initial model to the orientation of the true duck (the orientation of an ab initio map is arbitrary)."""
    best, arg = -2.0, (False, 0)
    for mirror in (False, True):
        W = V0[:, ::-1] if mirror else V0
        for a in range(0, 360, 3):
            c = np.corrcoef(nd_rotate(W, a, reshape=False, order=1)[_win_rf], _duck_rf[_win_rf])[0, 1]
            if c > best:
                best, arg = c, (mirror, a)
    return arg

def _show_rf(V, frame):
    W = V[:, ::-1] if frame[0] else V
    R = nd_rotate(W, frame[1], reshape=False, order=1)
    return R, np.corrcoef(R[_win_rf], _duck_rf[_win_rf])[0, 1]

def refine_rf(noise, n_images, iterations, rng):
    imgs = _images_rf(n_images, noise, rng)
    V0 = _ab_initio_rf(imgs, noise, rng); frame = _frame_rf(V0)
    halves = (imgs[:n_images // 2], imgs[n_images // 2:])                                       # two independent half sets (gold standard)
    VA = VB = V0; kc = 0.125; history = []
    for it in range(1, iterations + 1):
        K = int(np.clip(round(4 * np.pi * 32 * kc), 36, 180))                                   # the angular step decreases with the resolution limit
        VA, VB = _match_rf(VA, halves[0], noise, K, kc), _match_rf(VB, halves[1], noise, K, kc)
        k, f = _frc_rf(VA, VB); res = _resolution_rf(k, f, kc)
        history.append(dict(it=it, V=(VA + VB) / 2, k=k, f=f, res=res, kc=kc, K=K))
        kc = min(0.45, res + 0.06)                                                              # the next limit is slightly beyond the resolution reached
    return V0, frame, history

def draw_refine(noise=2.0, n_images=800, iterations=8, rng=None):
    rng = np.random.default_rng() if rng is None else rng
    imgs_example = _images_rf(3, noise, rng)
    V0, frame, history = refine_rf(noise, n_images, iterations, rng)
    shown = sorted(({1, 2, 4} & set(range(1, iterations + 1))) | {iterations})
    fig = plt.figure(figsize=(15, 6.2)); gs = fig.add_gridspec(2, 6, hspace=0.55, wspace=0.45)
    ax = fig.add_subplot(gs[0, 0]); ax.imshow(_duck_rf, cmap='gray'); ax.set_title('true object\n(unknown in practice)', fontsize=9.5, color=BLUE, loc='left'); ax.axis('off')
    for j in range(3):
        ax = fig.add_subplot(gs[0, j + 1]); ax.imshow(imgs_example[j], cmap='gray'); ax.set_title(f'image {j + 1}\n(random rotation, noise)', fontsize=9.5, loc='left'); ax.axis('off')
    R, c = _show_rf(V0, frame)
    ax = fig.add_subplot(gs[0, 4]); ax.imshow(R, cmap='gray'); ax.axis('off')
    ax.set_title(f'initial model (ab initio)\n8.0 px, correlation {c:.2f}', fontsize=9.5, color='#e08a00', loc='left')
    ax = fig.add_subplot(gs[0, 5])                                                              # resolution against iteration
    its = [0] + [h['it'] for h in history]; res_px = [8.0] + [1 / h['res'] for h in history]
    ax.plot(its, res_px, 'o-', color=CRIMSON, lw=2); ax.set_xlim(-0.5, max(iterations, 2) + 0.5); ax.set_ylim(0, max(10, max(res_px) + 1))
    ax.set_xlabel('iteration', fontsize=9); ax.set_ylabel('resolution (px)', fontsize=9); ax.grid(alpha=0.25)
    ax.set_title('resolution of the half maps)', fontsize=9.5, loc='left')
    for j, it in enumerate(shown):
        h = history[it - 1]; R, c = _show_rf(h['V'], frame)
        ax = fig.add_subplot(gs[1, j]); ax.imshow(R, cmap='gray'); ax.axis('off')
        ax.set_title(f'iteration {it}\n{1 / h["res"]:.1f} px, correlation {c:.2f}', fontsize=9.5, loc='left', color=TEAL if it == iterations else 'k')
    ax = fig.add_subplot(gs[1, 4:6])
    colors = [GREY, '#92d4f0', BLUE, CRIMSON]
    for j, it in enumerate(shown):
        h = history[it - 1]; m = h['k'] <= h['kc'] + 1e-9
        ax.plot(h['k'][m], h['f'][m], color=colors[j + len(colors) - len(shown)], lw=2, label=f'iteration {it}')
    ax.axhline(0.143, color='k', ls='--', lw=1); ax.text(0.495, 0.17, '0.143', ha='right', fontsize=8.5)
    ax.set_xlim(0, 0.5); ax.set_ylim(-0.05, 1.05); ax.set_xlabel('spatial frequency (cycles per pixel)', fontsize=9); ax.set_ylabel('FRC of the half maps', fontsize=9)
    ax.legend(fontsize=8, loc='upper right'); ax.grid(alpha=0.25)
    ax.set_title('Fourier ring correlation of the half maps', fontsize=9.5, loc='left')
    fig.text(0.5, -0.06, 'The maps are the averages of the two half maps, rotated (and mirrored) to the orientation of the true object. '
             'The resolution is the spatial frequency\nat which the FRC falls below 0.143, and it is determined up to the resolution limit of the iteration.', ha='center', fontsize=9)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_rf = {'description_width': '300px'}
_lay_rf = {'width': '620px'}
no_sl_rf = FloatSlider(value=2.0, min=1.0, max=8.0, step=0.5, description='Noise (standard deviation per pixel)', readout_format='.1f', continuous_update=False, style=_style_rf, layout=_lay_rf)
n_sl_rf = IntSlider(value=800, min=100, max=1000, step=50, description='Number of images', continuous_update=False, style=_style_rf, layout=_lay_rf)
it_sl_rf = IntSlider(value=8, min=1, max=12, step=1, description='Number of iterations', continuous_update=False, style=_style_rf, layout=_lay_rf)
run_btn_rf = Button(description='Run again (new images, new start)', icon='refresh', layout={'width': '300px'})
out_rf = ImageWidget(format='png', layout={'max_width': '100%'})

def update_rf(_=None):
    out_rf.value = draw_refine(no_sl_rf.value, n_sl_rf.value, it_sl_rf.value)
for _w in (no_sl_rf, n_sl_rf, it_sl_rf):
    _w.observe(update_rf, names='value')
run_btn_rf.on_click(update_rf)
display(VBox([no_sl_rf, n_sl_rf, it_sl_rf, run_btn_rf, out_rf]))
update_rf()
```

Macromolecules are often present in several conformations. **3D classification** sorts the particles into discrete states by the same principle as the 2D classification and yields a separate map for each state. Continuous flexibility is described by methods such as 3D variability analysis or multi-body refinement.

(subsec:spa-fourier-reconstruction)=
### Three-dimensional reconstruction and CTF correction

For known orientations, the map is reconstructed by Fourier inversion. According to the projection slice theorem ({numref}`sec:recon-projection-theorem`), the two-dimensional Fourier transform of each particle image is a central section through the three-dimensional Fourier transform of the structure. The sections are inserted into a three-dimensional Fourier volume in the orientations of the particles, which is then transformed back ({numref}`sec:recon-methods`).

Every image is the product of the structure and its own CTF in Fourier space (eq. {eq}`eq:ctf-product`). A Fourier coefficient $\hat V(\mathbf{k})$ of the map is therefore estimated from all sections that pass through $\mathbf{k}$, by a weighted sum that corresponds to the Wiener filter of eq. {eq}`eq:wiener`,

$$
\hat V(\mathbf{k}) \approx \frac{\sum_i \mathrm{CTF}_i(\mathbf{k})\,\hat X_i(\mathbf{k})}{\sum_i \mathrm{CTF}_i^2(\mathbf{k}) + 1/\mathrm{SNR}(\mathbf{k})},
$$ (eq:spa-ctf-weighting)

where $\hat X_i$ is the Fourier transform of image $i$ and $\mathrm{CTF}_i$ its CTF. The term $1/\mathrm{SNR}(\mathbf{k})$ prevents the division by zero near the CTF zeros and limits the amplification of noise. Since the zeros fall at different spatial frequencies for different defocus values, the information that is missing in one image is provided by others, which is the reason that images are recorded with a range of defocus values. In contrast to tomography, there is no systematic missing wedge, as the particles lie in random orientations. If the particles prefer certain orientations, however, regions of Fourier space are poorly sampled, which leads to an anisotropic resolution.

(sec:spa-resolution)=
## Resolution and the Fourier shell correlation

The **resolution** of a map is the period $d = 1/k$ of the highest spatial frequency at which the map reproduces the structure reliably ({numref}`sec:ft-resolution`). In SPA, the true structure is unknown and cannot be used for a comparison. The resolution is therefore estimated from the agreement of two maps that have been determined independently.

(subsec:spa-fsc)=
### The Fourier shell correlation

In the gold-standard procedure, the particles are divided randomly into two halves before the refinement. Each half is refined separately, so that the two resulting half-maps contain the same signal but independent noise. A common starting model may be used, provided that it is filtered so strongly that it contains no information at the frequencies at which the resolution is assessed. The <u>Fourier shell correlation</u> (FSC) is the correlation of the Fourier transforms $\hat F_1$ and $\hat F_2$ of the two half-maps in a thin shell of spatial frequencies $|\mathbf{k}'| \approx k$,

$$
\mathrm{FSC}(k) = \frac{\mathrm{Re}\sum_{|\mathbf{k}'| \approx k} \hat F_1(\mathbf{k}')\,\hat F_2^*(\mathbf{k}')}
{\sqrt{\sum_{|\mathbf{k}'| \approx k} |\hat F_1(\mathbf{k}')|^2 \;\sum_{|\mathbf{k}'| \approx k} |\hat F_2(\mathbf{k}')|^2}},
$$ (eq:fsc)

where the asterisk denotes the complex conjugate. For two-dimensional images, the shells are rings, and the quantity is called the Fourier ring correlation (FRC). At low spatial frequency, the signal dominates and the FSC is close to 1. At high spatial frequency, the signal is smaller than the noise, and the FSC falls to 0, because the noise in the two half-maps is independent.

```{admonition} Derivation: the FSC and the signal-to-noise ratio
:class: dropdown
Write the Fourier coefficients of the half-maps as the sum of the common signal $\hat S$ and independent noise $\hat N_j$, $\hat F_j = \hat S + \hat N_j$ with $j = 1, 2$. If the noise has zero mean and is independent of the signal and between the half-maps, the cross terms $\hat S\hat N_2^*$, $\hat N_1\hat S^*$ and $\hat N_1\hat N_2^*$ average to zero in the shell. The numerator of eq. {eq}`eq:fsc` is then $\sum|\hat S|^2$, and each of the sums in the denominator is $\sum|\hat S|^2 + \sum|\hat N|^2$. With the SNR of a half-map in the shell, $\mathrm{SNR}(k) = \sum|\hat S|^2 / \sum|\hat N|^2$, this gives

$$
\mathrm{FSC}(k) = \frac{\mathrm{SNR}(k)}{1 + \mathrm{SNR}(k)}, \qquad \mathrm{SNR}(k) = \frac{\mathrm{FSC}(k)}{1 - \mathrm{FSC}(k)}.
$$ (eq:fsc-snr)
```

The resolution of the map is defined as the spatial frequency at which the FSC falls below the threshold 0.143.

```{admonition} Key insight: the 0.143 criterion
:class: note
According to eq. {eq}`eq:fsc-snr`, an FSC of 0.143 corresponds to an SNR of $0.143/0.857 \approx 1/6$ in each half-map. The final map is calculated from both halves and has twice this SNR, $1/3$. Its correlation with the noise-free structure is $\sqrt{\mathrm{SNR}/(1+\mathrm{SNR})} = 0.5$. The threshold thus corresponds to a correlation of 0.5 between the final map and the true structure. In general, the correlation of the full map with the true structure follows from the FSC of the half-maps as $\sqrt{2\,\mathrm{FSC}/(1+\mathrm{FSC})}$ (Rosenthal and Henderson, 2003).
```

The following simulation determines the FRC of two half-maps in two dimensions. The object is the letter Q with a pixel size of 2 Å, which is blurred by a B-factor to represent the loss of high-resolution information in the images ({numref}`subsec:ctf`). Every half-map is the average of $N/2$ images with independent noise of standard deviation $\sigma$, which is calculated directly as the object plus noise of standard deviation $\sigma/\sqrt{N/2}$. The SNR of a single image is the variance of the object divided by $\sigma^2$. The simulation compares the FRC of the two half-maps with the expected FRC of eq. {eq}`eq:fsc-snr`, which is calculated from the SNR of the half-maps, and determines the resolution at the threshold 0.143. The last slider lets the two half-maps share a part of their noise, as would happen if they were not independent.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. The sliders set the number of particles $N$, the noise $\sigma$ of a single image, the B-factor and the fraction of noise that the two half-maps share. The left panels show the two half-maps, the map that is calculated from all particles, and the same map after low-pass filtering at the resolution that is determined from the FRC. The right panel shows the FRC, the FRC that is expected from the SNR (blue), the threshold 0.143 and the resulting resolution. 
```{admonition} Things to try
:class: dropdown
1. **Keep the defaults and compare the two curves.** The FRC falls from 1 at low frequencies to 0 at high frequencies. The curve that is expected from $\mathrm{SNR}/(1+\mathrm{SNR})$ follows it without the fluctuations. The vertical line marks the resolution at the threshold 0.143, which is 6.9 Å for the default values.
2. **Increase $N$ by a factor of 10.** The SNR increases at every frequency by this factor, and the crossing moves from 6.9 Å to 4.7 Å. The gain in resolution is much smaller than the factor of 10, because the signal decreases steeply with the spatial frequency.
3. **Compare $B = 0$ and $B = 300$ Å² at $N = 10^5$.** Without blurring, the resolution reaches the Nyquist limit of 4 Å. With $B = 300$ Å², it is only 6.2 Å, and every further factor of 10 in $N$ then gains only about 1 Å, because the envelope attenuates the signal at high frequencies.
4. **Increase the noise $\sigma$.** The effect is the same as reducing $N$: only the ratio $N/\sigma^2$ matters.
5. **Let the half-maps share 10% and then 30% of their noise.** The FRC no longer falls to 0 at high frequencies, but to a plateau at the shared fraction. With 10%, the apparent resolution improves from 6.9 Å to 5.8 Å, and with 30% the plateau is above the threshold 0.143, so that the resolution is given by the Nyquist limit. Shared noise thus leads to an overestimate of the resolution, which is the reason that the half-sets must be independent.
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import shift as nd_shift
from ipywidgets import FloatLogSlider, FloatSlider, IntSlider, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, GREY = '#25aae1', '#d91b5c', '#fcb040', '#b3b3b3'

def _letter_fs(text, size=128, fill=0.72):
    S = 4
    fig = plt.figure(figsize=(size*S/100, size*S/100), dpi=100)
    fig.text(0.5, 0.5, text, fontsize=size*S*fill*72/100, ha='center', va='center', family='DejaVu Sans')
    fig.canvas.draw()
    g = 1.0 - np.asarray(fig.canvas.buffer_rgba())[:size*S, :size*S, :3].mean(2) / 255.0
    plt.close(fig)
    g = g.reshape(size, S, size, S).mean(axis=(1, 3))
    yy, xx = np.mgrid[:size, :size]
    m = g.sum()
    g = nd_shift(g, (size/2 - 0.5 - (g*yy).sum()/m, size/2 - 0.5 - (g*xx).sum()/m), order=1)
    g = g / g.max()
    return g * (np.hypot(yy - size/2 + 0.5, xx - size/2 + 0.5) < 0.49*size)

_BOX_fs, _PIX_fs = 128, 2.0                                         # pixels, Å per pixel
_Q_fs = _letter_fs('Q', _BOX_fs)
_f_fs = np.fft.fftfreq(_BOX_fs, d=_PIX_fs)                          # cycles per Å
_KX_fs, _KY_fs = np.meshgrid(_f_fs, _f_fs)
_K2_fs = _KX_fs**2 + _KY_fs**2
_RING_fs = np.rint(np.sqrt(_K2_fs) * _BOX_fs * _PIX_fs).astype(int)  # ring index, one ring = 1/(box x pixel size)
_NR_fs = _BOX_fs // 2
_KAX_fs = np.arange(_NR_fs) / (_BOX_fs * _PIX_fs)                   # spatial frequency of the rings (1/Å)
_NYQ_fs = 0.5 / _PIX_fs
_rng_fs = np.random.default_rng(4)
_NZ_fs = [_rng_fs.standard_normal((_BOX_fs, _BOX_fs)) for _ in range(3)]   # fixed noise patterns: common, half 1, half 2

def _ringsum_fs(x):
    return np.bincount(_RING_fs.ravel(), x.ravel(), minlength=_RING_fs.max() + 1)[:_NR_fs]

def draw_fsc(n_particles=3000, sigma=3.0, B=60.0, shared=0.0):
    f = shared / 100.0
    obj = np.fft.ifft2(np.fft.fft2(_Q_fs) * np.exp(-B * _K2_fs / 4)).real     # object, blurred by the B-factor
    sh = sigma / np.sqrt(n_particles / 2.0)                                    # noise per pixel of a half-map
    n1 = np.sqrt(f) * _NZ_fs[0] + np.sqrt(1 - f) * _NZ_fs[1]
    n2 = np.sqrt(f) * _NZ_fs[0] + np.sqrt(1 - f) * _NZ_fs[2]
    h1, h2 = obj + sh * n1, obj + sh * n2
    F1, F2 = np.fft.fft2(h1), np.fft.fft2(h2)
    with np.errstate(all='ignore'):
        frc = _ringsum_fs((F1 * F2.conj()).real) / np.sqrt(_ringsum_fs(abs(F1)**2) * _ringsum_fs(abs(F2)**2))
    nring = np.maximum(np.bincount(_RING_fs.ravel(), minlength=_RING_fs.max() + 1)[:_NR_fs], 1)
    snr = _ringsum_fs(abs(np.fft.fft2(obj))**2) / nring / (sh**2 * _BOX_fs**2)  # SNR of a half-map in each ring
    expected = (snr + f) / (snr + 1)                                           # = SNR/(1+SNR) for independent halves
    below = np.where(frc[1:] < 0.143)[0]
    k_res = _KAX_fs[below[0] + 1] if len(below) else _NYQ_fs
    res = 1.0 / k_res
    full = 0.5 * (h1 + h2)
    Ff = np.fft.fft2(full)
    filt = np.fft.ifft2(Ff * (np.sqrt(_K2_fs) <= k_res)).real                  # low-pass filter at the resolution
    snr1 = _Q_fs.var() / sigma**2

    fig = plt.figure(figsize=(13, 5.0))
    gs = fig.add_gridspec(1, 2, width_ratios=[1, 1.8], wspace=0.2)            # maps | FRC plot
    gm = gs[0].subgridspec(2, 2, wspace=0.12, hspace=0.22)                     # the four maps close together
    vmin, vmax = -0.4, 1.3
    panels = [(h1, 'half-map 1'), (h2, 'half-map 2'), (full, f'all {n_particles:,.0f} particles'), (filt, f'low-pass filtered at {res:.1f} Å')]
    for (r, c), (im, t) in zip([(0, 0), (0, 1), (1, 0), (1, 1)], panels):
        ax = fig.add_subplot(gm[r, c]); ax.imshow(im, cmap='gray', vmin=vmin, vmax=vmax); ax.axis('off'); ax.set_title(t, fontsize=9.5)
    bx = fig.add_subplot(gs[0, 1])
    bx.plot(_KAX_fs[1:], frc[1:], color=CRIMSON, lw=1.8, label='FRC of the half-maps')
    bx.plot(_KAX_fs[1:], expected[1:], color=BLUE, lw=1.4, ls='--', label='expected: SNR/(1 + SNR)' if f == 0 else 'expected from SNR and shared noise')
    bx.axhline(0.143, color=GREY, ls='--', lw=1.2); bx.axhline(0, color='k', lw=0.6)
    bx.axvline(k_res, color=ORANGE, ls=':', lw=2)
    bx.text(k_res, -0.22, ('  ' if k_res < 0.15 else '') + f'{res:.1f} Å' + (' (Nyquist limit)' if not len(below) else '') + ('' if k_res < 0.15 else '  '),
            color='#c47f00', fontsize=10, va='bottom', ha='left' if k_res < 0.15 else 'right', fontweight='bold')
    bx.text(_NYQ_fs, 0.16, '0.143', color='#808080', fontsize=8.5, ha='right')
    bx.set_xlim(0, _NYQ_fs); bx.set_ylim(-0.25, 1.1); bx.grid(alpha=0.25)
    bx.set_xlabel('spatial frequency (1/Å)', fontsize=10); bx.set_ylabel('FRC', fontsize=10)
    bx.legend(fontsize=8.5, loc='upper center', bbox_to_anchor=(0.5, -0.14), ncol=2, frameon=False)
    top = bx.secondary_xaxis('top', functions=(lambda k: k, lambda k: k))
    top.set_xticks([1/20, 1/10, 1/6, 1/5, 1/4]); top.set_xticklabels(['20 Å', '10 Å', '6 Å', '5 Å', '4 Å'], fontsize=8.5)
    fig.suptitle(f'N = {n_particles:,.0f} particles,  $\\sigma$ = {sigma:.1f} (SNR of one image = {snr1:.3f}),  B = {B:.0f} Å²,  shared noise {shared:.0f}%', fontsize=10.5, y=1.0)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_fs = {'description_width': '170px'}
_lay_fs = {'width': '430px'}
n_sl_fs = FloatLogSlider(value=3000, base=10, min=2, max=6, step=0.1, description='Number of particles N', style=_style_fs, layout=_lay_fs, readout_format='.0f')
s_sl_fs = FloatSlider(value=3.0, min=1.0, max=10.0, step=0.5, description='Noise σ per image', style=_style_fs, layout=_lay_fs)
b_sl_fs = FloatSlider(value=60.0, min=0.0, max=300.0, step=10.0, description='B-factor (Å²)', style=_style_fs, layout=_lay_fs, readout_format='.0f')
h_sl_fs = IntSlider(value=0, min=0, max=50, step=5, description='Shared noise (%)', style=_style_fs, layout=_lay_fs)
out_fs = ImageWidget(format='png', layout={'max_width': '100%'})

def update_fs(_=None):
    out_fs.value = draw_fsc(n_sl_fs.value, s_sl_fs.value, b_sl_fs.value, h_sl_fs.value)
for _w in (n_sl_fs, s_sl_fs, b_sl_fs, h_sl_fs):
    _w.observe(update_fs, names='value')
display(VBox([n_sl_fs, s_sl_fs, b_sl_fs, h_sl_fs, out_fs]))
update_fs()
```

The FSC has to be interpreted with care and several things should be considered when doing so:

- **Half-set independence.** The FSC measures the reproducibility of the map. It is only meaningful if the half-sets are independent, which is the reason for the "gold-standard procedure" ({numref}`sec:spa-model-bias`). The simulation shows that shared noise inflates the resolution.
- **Masks.** The FSC is calculated for masked half-maps, so that the noise of the solvent does not dominate. A mask that is too tight introduces correlations between the half-maps, which is checked by repeating the calculation with half-maps in which the phases beyond a chosen frequency have been randomised.
- **Resolution limit.** The resolution cannot be better than the Nyquist limit, which is twice the pixel size ({numref}`sec:ft-resolution`). It does not need to be uniform over the map, for examples flexible regions have a lower local resolution than the core of the particle.
- **Validation of models.** A model that has been built into the map is compared with the map by an FSC between the map and the model, for which the threshold is 0.5.

(sec:spa-sharpening)=
## Map postprocessing

The high-resolution components of a map from the refinement are attenuated, by the envelope of the CTF and by inaccuracies of the alignment (eq. {eq}`eq:ctf-envelope`), so that fine details appear weak. The attenuation is described by a B-factor, which multiplies the Fourier transform of the map by $e^{-B k^2/4}$. In the **sharpening**, the Fourier transform of the map is multiplied by the inverse factor $e^{+B_\mathrm{sharp} k^2/4}$, which restores the amplitudes at high spatial frequencies. Programs report $B_\mathrm{sharp}$ as a negative B-factor.

The B-factor is determined from a **Guinier plot**, which shows the logarithm of the amplitude of the map, averaged over a shell, as a function of $k^2$. In the range of spatial frequencies in which the amplitudes of the structure itself are about constant, which is for proteins between about 10 Å and the resolution, the curve of the attenuated map is a straight line with the slope $-B/4$. At higher frequencies, the map contains mainly noise, and the curve flattens to the level of the noise. Sharpening would amplify this noise, so that the sharpened map is low-pass filtered at the resolution that is determined from the FSC ({numref}`subsec:spa-fsc`). Before the resolution is determined, a mask is applied that excludes the solvent around the particle.

The following simulation applies the sharpening to the two-dimensional model. The structure is the letter Q with fine internal details, which have a spectrum that is approximately constant, like the atomic details of a protein. The map is blurred by a B-factor of 200 Å² and calculated from $N$ particles with noise $\sigma = 3$ of a single image, as in the simulation of the previous section. The resolution is determined from the FRC of two half-maps.

````{admonition} Interactive element
:class: tip
Click the rocket symbol <i class="fas fa-rocket"></i> at the top of the page and select **Live Code**, or expand the **Show code** toggle and click ▶ to run the cell. The sliders set the number of particles and the B-factor $B_\mathrm{sharp}$ of the sharpening, and the box selects whether the sharpened map is low-pass filtered at the resolution. 

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults ($B_\mathrm{sharp} = 0$).** The map is a blurred Q with weak internal details. In the Guinier plot, the curve of the map without noise (dotted) falls linearly with $k^2$ with the slope $-B/4$, whereas the curve of the map (solid) follows it until it reaches the level of the noise, near the resolution.
2. **Increase $B_\mathrm{sharp}$ to 200 Å², the B-factor of the map.** The curve of the sharpened map becomes flat up to the resolution, at the level of the structure, and the fine details appear with more contrast. Beyond the resolution, the low-pass filter removes the noise.
3. **Increase $B_\mathrm{sharp}$ to 400 Å².** The map is over-sharpened: the curve rises towards the resolution, the high-frequency noise and artefacts dominate, and the image looks coarser.
4. **Switch off the low-pass filter at $B_\mathrm{sharp} = 200$ Å².** The curve rises above the structure beyond the resolution, because the noise is amplified, and the map is dominated by noise. The sharpening therefore requires the low-pass filter at the resolution.
5. **Increase the number of particles to $10^4$.** The resolution improves from 5.1 Å to 4.2 Å, so that the sharpening can restore the details up to a higher resolution.
```
````

```{code-cell} ipython3
:tags: [hide-input, thebe-init]
import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import shift as nd_shift, gaussian_filter
from ipywidgets import FloatLogSlider, FloatSlider, Checkbox, VBox, Image as ImageWidget
from IPython.display import display

BLUE, CRIMSON, ORANGE, GREY = '#25aae1', '#d91b5c', '#fcb040', '#b3b3b3'

def _letter_sh(text, size=128, fill=0.72):
    S = 4
    fig = plt.figure(figsize=(size*S/100, size*S/100), dpi=100)
    fig.text(0.5, 0.5, text, fontsize=size*S*fill*72/100, ha='center', va='center', family='DejaVu Sans')
    fig.canvas.draw()
    g = 1.0 - np.asarray(fig.canvas.buffer_rgba())[:size*S, :size*S, :3].mean(2) / 255.0
    plt.close(fig)
    g = g.reshape(size, S, size, S).mean(axis=(1, 3))
    yy, xx = np.mgrid[:size, :size]
    m = g.sum()
    g = nd_shift(g, (size/2 - 0.5 - (g*yy).sum()/m, size/2 - 0.5 - (g*xx).sum()/m), order=1)
    g = g / g.max()
    return g * (np.hypot(yy - size/2 + 0.5, xx - size/2 + 0.5) < 0.49*size)

_BOX_sh, _PIX_sh = 128, 2.0                                         # pixels, Å per pixel
_B_MAP_sh, _SIGMA_sh = 200.0, 3.0                                   # B-factor of the map (Å²), noise of a single image
_Qs_sh = gaussian_filter(_letter_sh('Q', _BOX_sh), 0.8)
_OBJ_sh = _Qs_sh * (1 + 0.8 * np.random.default_rng(5).standard_normal((_BOX_sh, _BOX_sh)))   # letter with fine details (flat spectrum)
_f_sh = np.fft.fftfreq(_BOX_sh, d=_PIX_sh)                          # cycles per Å
_K2_sh = np.add.outer(_f_sh**2, _f_sh**2)
_K_sh = np.sqrt(_K2_sh)
_RING_sh = np.rint(_K_sh * _BOX_sh * _PIX_sh).astype(int)
_NR_sh = _BOX_sh // 2
_KAX_sh = np.arange(_NR_sh) / (_BOX_sh * _PIX_sh)
_CNT_sh = np.maximum(np.bincount(_RING_sh.ravel(), minlength=_RING_sh.max() + 1)[:_NR_sh], 1)
_NZ_sh = [np.random.default_rng(10 + i).standard_normal((_BOX_sh, _BOX_sh)) for i in range(3)]   # noise: full map, half-map 1, half-map 2
_F0_sh = np.fft.fft2(_OBJ_sh)
_ATT_sh = np.exp(-_B_MAP_sh * _K2_sh / 4)                           # attenuation of the map by the B-factor

def _ring_sh(x):
    return np.bincount(_RING_sh.ravel(), x.ravel(), minlength=_RING_sh.max() + 1)[:_NR_sh]

def _amp_sh(F):
    return _ring_sh(abs(F)) / _CNT_sh                               # amplitude averaged over a ring

def draw_sharp(n_particles=3000, B_sharp=0.0, lowpass=True):
    obj_b = np.fft.ifft2(_F0_sh * _ATT_sh).real                     # map without noise
    full = obj_b + _SIGMA_sh / np.sqrt(n_particles) * _NZ_sh[0]     # map from all particles
    sh = _SIGMA_sh / np.sqrt(n_particles / 2.0)                     # noise of a half-map
    F1, F2 = np.fft.fft2(obj_b + sh * _NZ_sh[1]), np.fft.fft2(obj_b + sh * _NZ_sh[2])
    with np.errstate(all='ignore'):
        frc = _ring_sh((F1 * F2.conj()).real) / np.sqrt(_ring_sh(abs(F1)**2) * _ring_sh(abs(F2)**2))
    below = np.where(frc[1:] < 0.143)[0]
    k_res = _KAX_sh[below[0] + 1] if len(below) else 0.5 / _PIX_sh   # resolution from the FRC of the half-maps
    Fm = np.fft.fft2(full)
    w = 0.015                                                       # width of the soft edge of the low-pass filter (1/Å)
    edge = 0.5 * (1 + np.cos(np.pi * (_K_sh - (k_res - w)) / (2 * w)))
    lp = np.where(_K_sh <= k_res - w, 1.0, np.where(_K_sh >= k_res + w, 0.0, edge)) if lowpass else 1.0
    Fs = Fm * np.exp(B_sharp * _K2_sh / 4) * lp                     # sharpening and low-pass filter
    sharp = np.fft.ifft2(Fs).real

    fig = plt.figure(figsize=(12, 6.6))
    gs = fig.add_gridspec(2, 3, height_ratios=[1, 1.2], hspace=0.42, wspace=0.06)
    panels = [(_OBJ_sh, 'structure', BLUE),
              (full, f'map from {n_particles:,.0f} particles', 'k'),
              (sharp, f'sharpened map, $B_\\mathrm{{sharp}}$ = {B_sharp:.0f} Å²' + ('' if lowpass else ', no low-pass filter'), CRIMSON)]
    for j, (im, title, col) in enumerate(panels):
        ax = fig.add_subplot(gs[0, j]); lo, hi = np.percentile(im, (1, 99.5))
        ax.imshow(im, cmap='gray', vmin=lo, vmax=hi); ax.axis('off'); ax.set_title(title, fontsize=10, color=col)
    bx = fig.add_subplot(gs[1, :])
    k2 = _KAX_sh**2
    bx.plot(k2[1:], np.log(_amp_sh(_F0_sh)[1:]), color=GREY, ls='--', lw=1.8, label='structure')
    bx.plot(k2[1:], np.log(_amp_sh(_F0_sh * _ATT_sh)[1:]), color=BLUE, ls=':', lw=1.8, label='map without noise')
    bx.plot(k2[1:], np.log(_amp_sh(Fm)[1:]), color=BLUE, lw=2, label='map')
    bx.plot(k2[1:], np.log(_amp_sh(Fs)[1:] + 1e-6), color=CRIMSON, lw=2, label='sharpened map')
    bx.axvline(k_res**2, color=ORANGE, ls=':', lw=2)
    bx.text(k_res**2, 6.75, f'  resolution {1/k_res:.1f} Å' + (' (Nyquist limit)' if not len(below) else ''), color='#c47f00', fontsize=10, fontweight='bold', va='top')
    bx.set_xlim(0, (0.5/_PIX_sh)**2); bx.set_ylim(0, 7); bx.grid(alpha=0.25)
    bx.set_xlabel('$k^2$ (1/Å²)', fontsize=10); bx.set_ylabel('ln (amplitude)', fontsize=10)
    bx.set_title('Guinier plot', fontsize=10, pad=28)
    bx.legend(fontsize=8.5, loc='upper center', bbox_to_anchor=(0.5, -0.2), ncol=4, frameon=False)
    top = bx.secondary_xaxis('top', functions=(lambda x: np.sqrt(np.maximum(x, 0)), lambda k: k**2))
    top.set_xticks([1/20, 1/10, 1/6, 1/5, 1/4]); top.set_xticklabels(['20 Å', '10 Å', '6 Å', '5 Å', '4 Å'], fontsize=8.5)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=100, bbox_inches='tight'); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_sh = {'description_width': '190px'}
_lay_sh = {'width': '470px'}
n_sl_sh = FloatLogSlider(value=3000, base=10, min=2, max=5, step=0.1, description='Number of particles N', style=_style_sh, layout=_lay_sh, readout_format='.0f')
b_sl_sh = FloatSlider(value=0.0, min=0.0, max=500.0, step=10.0, description='Sharpening B (Å²)', style=_style_sh, layout=_lay_sh, readout_format='.0f')
lp_cb_sh = Checkbox(value=True, description='Low-pass filter at the resolution', style=_style_sh, layout=_lay_sh, indent=False)
out_sh = ImageWidget(format='png', layout={'max_width': '100%'})

def update_sh(_=None):
    out_sh.value = draw_sharp(n_sl_sh.value, b_sl_sh.value, lp_cb_sh.value)
for _w in (n_sl_sh, b_sl_sh, lp_cb_sh):
    _w.observe(update_sh, names='value')
display(VBox([n_sl_sh, b_sl_sh, lp_cb_sh, out_sh]))
update_sh()
```

```{admonition} Practical
:class: seealso
Alignment, averaging and classification of noisy particle images are explored in Python in the corresponding practical of the CryoEM doeboek: [CryoEM doeboek: single-particle analysis](https://cryotud.github.io/cryoem-doeboek/spa/)
```
