---
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
mystnb:
  execution_timeout: 180
---

(ch:tomography)=
# Electron Tomography

As we have seen, single-particle analysis achieves near-atomic resolution by averaging thousands of identical copies of a purified molecule. But much of biology is irreducibly unique. The arrangement of organelles in a single cell, the architecture of a synaptic vesicle cluster, the organisation of chromatin in a nucleus are all examples of biological structures that cannot be averaged across many copies because each instance is different. **Electron tomography (cryo-ET)** addresses this by reconstructing a three-dimensional volume from a single specimen through a series of images of the same object collected at different tilt angles.

The projection theorem, which is the basis of all reconstruction methods, is described for general three-dimensional objects in {numref}`sec:recon-projection-theorem`. In this chapter it is applied to tilt series, and the reconstruction of a tilt series is developed step by step in two dimensions. The reconstruction problem in tomography, recovering a 3D volume from a set of 2D projections, is much older than cryo-ET. Its mathematical basis (the Radon transform and its inverse) was established by Johann Radon in 1917, and reconstruction from electron micrographs was demonstrated by DeRosier and Klug in 1968. The same principles underlie computed tomography (CT) scanning in medical applications. In electron tomography, however, the dose constraints of radiation-sensitive biological specimens make the problem particularly hard as the total electron dose must be spread over all tilt angles which limits the signal per image to even much less than in a single cryo-EM micrograph.

In the below video, we explain why a unique object requires a different approach than single-particle analysis, how a tilt series is assembled into a sinogram and back projected into a three-dimensional reconstruction, and how tilt range, tilt increment, the missing wedge and weighted back projection determine the quality of that reconstruction.

---

<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/kubnqAHhnSM?si=fhpfgOWMbToK8teo"
        title="Electron tomography"
        loading="lazy"
        frameborder="0"
        allowfullscreen
    ></iframe>
</div>

---

(sec:tomo-model)=
## A two-dimensional model problem

For a single tilt axis, every row of the detector image is a one-dimensional projection of a two-dimensional slice of the specimen perpendicular to the tilt axis, and the slices are independent of each other. A tilt series can therefore be analysed slice by slice, and the principles of the reconstruction can be developed in two dimensions. A slice is described by a density $A(x,z)$, where $x$ is the lateral coordinate and $z$ the direction of the beam. The test slice in the simulations of this chapter mimics a cross-section of a cell. It contains a ring (e.g. a microtubule in cross-section), two line segments (e.g. membranes in the plane of the specimen and one perpendicular to it) and a disc representing a protein complex.

In practice, a tilt series is recorded by tilting the specimen in steps of 1–3° between about -60° and +60°, which gives 41–121 images. To start with, we assume that the whole range of ±90° is available and that the images are noise-free, both of which of course are not true for a real experiment.

(sec:tomo-sinogram)=
### Tilt series and the sinogram

At the tilt angle $\alpha$, the specimen is rotated by $\alpha$ and the detector records the density summed along the beam,

$$
P_\alpha(x) = \int A_\alpha(x,z)\,\mathrm{d}z,
$$ (eq:radon)

where $A_\alpha$ is the rotated slice. This operation is the Radon transform. The projections of all tilt angles, stacked as the rows of an image with the tilt angle along one axis and the lateral coordinate along the other, form the **sinogram**.

The name stems from the curve that a single point of the slice traces in the sinogram. Describe the point by its distance $r$ from the tilt axis and by the angle $\alpha_0$ between the $x$ axis and the line from the axis to the point (polar coordinates), so that $x_0 = r\cos\alpha_0$ and $z_0 = r\sin\alpha_0$. As we rotate through $\alpha$, it is detected at the lateral position

$$
x(\alpha) = x_0\cos\alpha + z_0\sin\alpha = r\cos(\alpha - \alpha_0),
$$

for the sign convention of the tilt angle used here. This curve is a sinusoid. Its amplitude is the distance $r$ of the point from the rotation axis, and its phase $\alpha_0$ is the angle of the point, which depends on its height $z_0$. A point on the $x$ axis ($\alpha_0$ = 0) traces $r\cos\alpha$, and a point straight above the axis ($\alpha_0$ = 90°) traces $r\sin\alpha$. In particular, points at the same lateral position $x_0$ but at different heights $z_0$ have different phases, so that the information on the height of a feature is contained in the phase of its sinusoid. The sinogram of a slice is the superposition of the sinusoids of all its points, and a reconstruction has to unscramble them. Projections at $\alpha$ and $\alpha$ + 180° are mirror images of each other, so that a tilt range of $180°$ contains the complete information. The limited tilt range of a real experiment leaves part of the sinogram empty, which is the origin of the missing wedge that we will discuss in {numref}`sec:tomo-missing-wedge`.

The simulation below builds the sinogram of the test slice while the specimen is tilted.

````{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. Tilt the specimen and watch how the projection and the sinogram change. The disc is marked with a circle and follows a sinusoidal track in the sinogram.

```{admonition} Things to try
:class: dropdown
1. **Start at 0°.** The "membrane" along the beam dierction (the vertical bar) gives a tall, narrow peak, because its material lies on only a few beam paths but with many points along the viewing direction. The membrane in the plane of the specimen gives only a low plateau, because its material is spread over many beam paths. The ring gives two peaks, where the beam is tangent to its walls.
2. **Move to +90° and to −90°.** The two membranes have exchanged their roles, and the two projections are mirror images of each other. A range of 180° therefore contains all information.
3. **Follow the disc.** It circles around the tilt axis, and its position on the detector follows the dashed sinusoid. The amplitude of the sinusoid is the distance of the disc from the tilt axis, and its phase carries the height $z$ of the disc.
4. **Complete the sinogram.** Every point of the specimen traces its own sinusoid, and the sinogram is the sum of all of them. 
```
````

```{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
from ipywidgets import IntSlider, VBox, Image as ImageWidget
from IPython.display import display

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

def _phantom_ts(n=256, ss=2):
    # slice of a specimen: x lateral, z along the beam (up); ring = microtubule, bars = membranes, disc = protein complex
    m = n*ss                                                                     # supersampled grid; averaging the ss x ss subpixels smooths the edges
    y, x = (np.mgrid[0:m, 0:m] + 0.5)/ss - 0.5
    r1 = np.hypot(x - n*0.30, y - n*0.32)
    img = 0.9 * ((r1 > n*0.11) & (r1 < n*0.18))
    img = img + 0.85 * ((np.abs(y - n*0.67) < n*0.025) & (x > n*0.10) & (x < n*0.90))      # membrane in the specimen plane
    img = img + 0.85 * ((np.abs(x - n*0.55) < n*0.025) & (y > n*0.12) & (y < n*0.56))      # membrane perpendicular to it
    img = img + 0.75 * (np.hypot(x - n*0.70, y - n*0.36) < n*0.07)
    return np.clip(img, 0, 1).reshape(n, ss, n, ss).mean(axis=(1, 3))

_N_ts = 256
_S_ts = _N_ts/100                                                         # lengths in the picture were designed for 100 pixels
_C_ts = (_N_ts - 1) / 2
_ph_ts = _phantom_ts(_N_ts)
_ang_ts = np.arange(-90, 91, 1)
_sino_ts = np.array([nd_rotate(_ph_ts, -a, reshape=False, order=1).sum(axis=0) for a in _ang_ts])
_X0_ts, _Z0_ts = 0.70*_N_ts - _C_ts, _C_ts - 0.36*_N_ts       # position of the disc relative to the rotation axis (x, z up)

def draw_ts(alpha=0):
    a = np.radians(alpha)
    rot = nd_rotate(_ph_ts, -alpha, reshape=False, order=1)
    prof = rot.sum(axis=0)
    xd = _C_ts + _X0_ts*np.cos(a) + _Z0_ts*np.sin(a)             # lateral position of the disc in the tilted specimen
    zd = _Z0_ts*np.cos(a) - _X0_ts*np.sin(a)
    W, H = 9.9, 6.2                                              # figure size in inches
    fig = plt.figure(figsize=(W, H))
    def axes_in(l, b, w, h):
        return fig.add_axes([l/W, b/H, w/W, h/H])
    w_ph, h_ph, h_pr, gap, bot = 3.5, 3.5*(_N_ts - 0.5 + 12*_S_ts)/_N_ts, 0.85, 0.3, 0.7
    ax1 = axes_in(0.55, bot + h_pr + gap, w_ph, h_ph)            # specimen (with the beam arrows above it)
    ax2 = axes_in(0.55, bot, w_ph, h_pr)                         # projection, same horizontal axis as the specimen
    ax3 = axes_in(0.55 + w_ph + 1.0, bot, 4.6, h_pr + gap + h_ph)

    ax1.imshow(rot, cmap='gray', vmin=0, vmax=1.1, extent=[-0.5, _N_ts-0.5, _N_ts-0.5, -0.5], aspect='auto', interpolation='bicubic')
    for xp in np.arange(0.05*_N_ts, _N_ts, 0.1*_N_ts):
        ax1.plot([xp, xp], [-0.5, _N_ts-0.5], color=BLUE, lw=0.8, alpha=0.35)
        ax1.annotate('', xy=(xp, 4*_S_ts), xytext=(xp, -9*_S_ts), arrowprops=dict(arrowstyle='-|>', color=BLUE, lw=0.9, alpha=0.8), annotation_clip=False)
    ax1.plot(_C_ts, _C_ts, 'o', ms=10, mfc='none', mec=ORANGE, mew=1.6); ax1.plot(_C_ts, _C_ts, '.', color=ORANGE, ms=4)
    ax1.plot(xd, _C_ts - zd, 'o', ms=12, mfc='none', mec=CRIMSON, mew=1.8)
    ax1.set_xlim(-0.5, _N_ts-0.5); ax1.set_ylim(_N_ts-0.5, -12*_S_ts); ax1.axis('off')
    ax1.set_title(f'Specimen tilted by {alpha:+d}°\n tilt axis ⊙', fontsize=9.5)

    ax2.fill_between(np.arange(_N_ts), prof, color=CRIMSON, alpha=0.25); ax2.plot(prof, color=CRIMSON, lw=1.6)
    ax2.axvline(xd, color=CRIMSON, ls=':', lw=1.4)
    ax2.set_xlim(-0.5, _N_ts-0.5); ax2.set_ylim(0, 1.15*_sino_ts.max()); ax2.grid(alpha=0.25)
    ax2.set_yticks([0, 100])
    ax2.set_xlabel('position on the detector, $x$ (pixels)', fontsize=9.5); ax2.set_ylabel('$P_\\alpha(x)$', fontsize=9.5)

    sino = np.ma.masked_where(np.repeat(_ang_ts[:, None] > alpha, _N_ts, axis=1), _sino_ts)
    ax3.imshow(sino, cmap='gray', aspect='auto', extent=[-0.5, _N_ts-0.5, 90.5, -90.5], vmin=0, vmax=_sino_ts.max(), interpolation='bicubic')
    ax3.set_facecolor('#e9e9e9')
    al = np.radians(_ang_ts)
    ax3.plot(_C_ts + _X0_ts*np.cos(al) + _Z0_ts*np.sin(al), _ang_ts, color=CRIMSON, lw=1.2, ls='--', alpha=0.9)
    ax3.axhline(alpha, color=ORANGE, lw=1.5)
    ax3.set_xlim(-0.5, _N_ts-0.5); ax3.set_ylim(90.5, -90.5)
    ax3.set_xlabel('position on the detector, $x$ (pixels)', fontsize=9.5); ax3.set_ylabel('tilt angle $\\alpha$ (°)', fontsize=9.5)
    ax3.set_title('Sinogram: one row per tilt', fontsize=9.5)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_ts = {'description_width': '120px'}
al_sl_ts = IntSlider(value=0, min=-90, max=90, step=2, description='Tilt angle (°)', style=_style_ts, layout={'width': '420px'})
out_ts = ImageWidget(format='png', layout={'max_width': '100%'})
def update_ts(_=None):
    out_ts.value = draw_ts(al_sl_ts.value)
al_sl_ts.observe(update_ts, names='value')
display(VBox([al_sl_ts, out_ts]))
update_ts()
```

(sec:tomo-backprojection)=
### Direct backprojection

Given a set of 1D projections in the tilt series, how do we recover the 2D image? The simplest approach is <u>direct backprojection</u>: for each projection, "smear" the 1D signal back along the direction of the beam into a 2D slab and then accumulate all such slabs:

$$
A_\text{BP}(x, z) = \int_0^\pi P_\alpha(x\cos\alpha + z\sin\alpha)\, \mathrm{d}\alpha
$$ (eq:backprojection)

While intuitively appealing, direct backprojection overweights low spatial frequencies and produces reconstructions with a characteristic blurriness. This is because a projection records only the sum along each beam path, so that the backprojection has to spread every value evenly over the whole path. The smears of different projections add up properly only where they cross, which is the position of a feature. Everywhere else, each smear leaves a faint trace, and the traces of all projections together form a haze around every real feature of the object. This means that the direct backprojection reconstructs the object with point-spread function that enhances the low-resolution frequencies.

The origin of this blur can be described exactly. Each point of the object is reconstructed essentially as the same pattern, a halo that fades slowly with the distance from the point. This pattern is the point spread function of the backprojection, so that the reconstruction is the object blurred by it, in the same way as a microscope image is blurred by the point spread function of the microscope. Because the pattern is known exactly, the blur can be compensated, as the following sections show. The simulation below reconstructs the test slice from its sinogram by direct backprojection. 

````{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 panels show, from left to right, the test slice, the sinogram of the chosen tilt series, the reconstruction by direct backprojection and the logarithm of the amplitude of the Fourier transform of the reconstruction. The sliders set the maximum tilt angle and the tilt increment.

```{admonition} Things to try
:class: dropdown
1. **Set the maximum tilt to 90° and the increment to 3°.** All features are reconstructed, but they are blurred and sit on a bright background. The blur does not go away when you add more projections.
2. **Increase the increment to 15°.** Streaks radiate from every feature, and the Fourier panel shows the individual lines of the 13 projections, with empty space between them.
3. **Return to 3° and reduce the maximum tilt to 60° and then to 30°.** The horizontal membrane has almost disappeared at 60° and is gone at 30°, whereas the vertical one survives. The ring is stretched along the beam direction into a diamond, and a dark wedge opens around the vertical axis of the Fourier panel.
4. **Compare the centre of the Fourier panel with its edges.** The low spatial frequencies are much stronger than the high ones, because every projection contributes to them. This over-weighting is the reason for the blur, and the next sections explain it and remove it.
```
````

```{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
from ipywidgets import IntSlider, VBox, Image as ImageWidget
from IPython.display import display

def _tomo_t2(n=128, ss=1):
    m = n*ss                                                       # with ss > 1, the grid is supersampled and averaged, which smooths the edges
    y, x = (np.mgrid[0:m, 0:m] + 0.5)/ss - 0.5
    r1 = np.hypot(x - n*0.30, y - n*0.32)
    img = 0.9 * ((r1 > n*0.11) & (r1 < n*0.18))
    img = img + 0.85 * ((np.abs(y - n*0.67) < n*0.025) & (x > n*0.10) & (x < n*0.90))
    img = img + 0.85 * ((np.abs(x - n*0.55) < n*0.025) & (y > n*0.12) & (y < n*0.56))
    img = img + 0.75 * (np.hypot(x - n*0.70, y - n*0.36) < n*0.07)
    return np.clip(img, 0, 1).reshape(n, ss, n, ss).mean(axis=(1, 3))

_bp_img = _tomo_t2(128)
_bp_img_show = _tomo_t2(256, 2)                                      # the same slice at a higher resolution, for display only
_n_bp = 128
_win_bp = np.outer(np.hanning(_n_bp), np.hanning(_n_bp))          # window for the Fourier panel: avoids streaks from the image edges
_all_angles = np.arange(-90, 91, 1)
_all_sino = np.zeros((len(_all_angles), _n_bp))
for _i, _a in enumerate(_all_angles):
    _all_sino[_i] = nd_rotate(_bp_img, -_a, reshape=False, order=1).sum(axis=0)

def _bp_recon(sino, angles):
    n = _n_bp; recon = np.zeros((n, n))
    yy, xx = (np.mgrid[0:n, 0:n] - n//2).astype(float)
    for proj, ang in zip(sino, angles):
        a = np.deg2rad(ang)
        px = (xx*np.cos(a) - yy*np.sin(a) + n//2).clip(0, n-1)      # y points down, z = -y
        lo = px.astype(int); hi = np.minimum(lo+1, n-1); f = px - lo
        recon += proj[lo]*(1-f) + proj[hi]*f
    return recon / max(len(angles), 1)

def draw_bp(tilt_inc=3, max_tilt=60):
    angs = np.arange(-max_tilt, max_tilt+1, tilt_inc)
    sel = np.isin(_all_angles, angs)
    sino = _all_sino[sel]; angs_use = _all_angles[sel]
    rec  = _bp_recon(sino, angs_use)
    ft   = np.log1p(np.abs(np.fft.fftshift(np.fft.fft2(rec * _win_bp))))

    fig, axes = plt.subplots(1, 4, figsize=(16, 4.2))
    axes[0].imshow(_bp_img_show, cmap='gray', interpolation='bicubic'); axes[0].axis('off')
    axes[0].set_title("Original", fontsize=11)
    axes[1].imshow(sino, cmap='gray', aspect='auto', interpolation='bicubic'); axes[1].axis('off')
    axes[1].set_title(f"Sinogram ({len(angs_use)} projections)", fontsize=11)
    axes[2].imshow(rec, cmap='gray', interpolation='bicubic'); axes[2].axis('off')
    axes[2].set_title(f"Backprojection (Δθ={tilt_inc}°, ±{max_tilt}°)", fontsize=11)
    axes[3].imshow(ft, cmap='inferno', interpolation='bicubic'); axes[3].axis('off')
    axes[3].set_title("Fourier amplitudes of backprojection", fontsize=11)

    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

style = {"description_width": "140px"}
inc_sl  = IntSlider(value=3,  min=1, max=15, step=1,
                    description="Tilt increment (°)", style=style, layout={"width":"420px"})
tmax_sl = IntSlider(value=60, min=20, max=90, step=5,
                    description="Max tilt (°)", style=style, layout={"width":"420px"})
out_bp = ImageWidget(format='png', layout={'max_width': '100%'})
def update_bp(_=None):
    out_bp.value = draw_bp(inc_sl.value, tmax_sl.value)
for s in [inc_sl, tmax_sl]:
    s.observe(update_bp, names='value')
display(VBox([inc_sl, tmax_sl, out_bp]))
update_bp()
```

(sec:tomo-projection-theorem)=
### The Fourier slice theorem

The previous section showed that direct backprojection reconstructs every point of the object as a blurred version of that point. To see how this blur can be compensated, it is instructive to look at it in Fourier space. This section shows which part of Fourier space a single projection measures. The next section shows which part all projections together measure, and why the low spatial frequencies are measured by many projections and the high ones only by a few. The filter to correct for the blurring artefacts of direct backprojection (filtered, or <u>weighted backprojection</u>) follows from this.

Let us first turn back to the projection theorem for general three-dimensional objects, which is described in {numref}`sec:recon-projection-theorem`. For a single-axis tilt series it takes a two-dimensional form, which is easier to visualise. We denote $\hat{A}(k_x,k_z)$ as the two-dimensional Fourier transform of the slice $A(x,z)$ with the spatial frequencies $k_x$ and $k_z$, and $\hat{P}_\alpha(\nu) = \int P_\alpha(x)\,e^{-2\pi i \nu x}\,\mathrm{d}x$ as the one-dimensional Fourier transform of its projection at the tilt angle $\alpha$, with the spatial frequency $\nu$. According to the projection theorem, $\hat{P}_\alpha$ is the section of $\hat{A}$ through the origin that is perpendicular to the beam, which in two dimensions is a line. As described above, a point $(x_0,z_0)$ of the slice is detected at the lateral position $x_0\cos\alpha + z_0\sin\alpha$, so that the detector axis points in the direction $(\cos\alpha,\,\sin\alpha)$ of the slice and the beam runs perpendicular to it. The central line perpendicular to the beam is therefore the line along $(\cos\alpha,\,\sin\alpha)$, and its point at the distance $\nu$ from the origin is $(\nu\cos\alpha,\,\nu\sin\alpha)$. The theorem therefore reads

$$
\hat{P}_\alpha(\nu) = \hat{A}(\nu\cos\alpha,\; \nu\sin\alpha),
$$ (eq:fourier-slice)

so that the Fourier transform of a projection is a central line through the two-dimensional Fourier transform of the slice, perpendicular to the direction of the projection. Every projection thus fills in one central line of two-dimensional Fourier space. Collecting projections from many tilt angles fills Fourier space line by line, and an inverse two-dimensional Fourier transform would then recover the slice. The simulation below shows the theorem for the test slice.

````{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. Tilt the specimen and watch the blue line rotate through the Fourier transform of the slice. The transform of the projection and the values on the blue line are the same.

```{admonition} Things to try
:class: dropdown
1. **Start at 0°.** The line is the axis $k_z = 0$. The projection is the sum along $z$, and its transform is exactly this line of the two-dimensional transform, as in the derivation.
2. **Tilt to +30° and to −50°.** The line turns by the tilt angle, but in the opposite sense to the specimen. The specimen is drawn as the microscope sees it, with the beam fixed along $z$ and the specimen turning clockwise for a positive tilt. The transform belongs to the untilted slice, and from the point of view of this slice it is the beam and the detector that turn, counter-clockwise, so that the line along the detector turns with them.
3. **Tilt to 90°.** The horizontal membrane of the slice has a stripe in the transform along $k_z$, perpendicular to the membrane, and the blue line now runs along this stripe. In the projection the membrane is seen edge-on as a narrow, tall peak. A narrow peak has a broad spectrum, so the amplitude stays high up to high frequencies.
4. **Look at the centre.** All lines pass through the origin. The amplitude there is the total amount of material, which is the same at every tilt angle.
```
````

```{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
from ipywidgets import IntSlider, VBox, Image as ImageWidget
from IPython.display import display

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

def _phantom_fs(n=128, ss=1):
    # slice of a specimen: x lateral, z along the beam (up); ring = microtubule, bars = membranes, disc = protein complex
    m = n*ss                                                       # with ss > 1, the grid is supersampled and averaged, which smooths the edges
    y, x = (np.mgrid[0:m, 0:m] + 0.5)/ss - 0.5
    r1 = np.hypot(x - n*0.30, y - n*0.32)
    img = 0.9 * ((r1 > n*0.11) & (r1 < n*0.18))
    img = img + 0.85 * ((np.abs(y - n*0.67) < n*0.025) & (x > n*0.10) & (x < n*0.90))
    img = img + 0.85 * ((np.abs(x - n*0.55) < n*0.025) & (y > n*0.12) & (y < n*0.56))
    img = img + 0.75 * (np.hypot(x - n*0.70, y - n*0.36) < n*0.07)
    return np.clip(img, 0, 1).reshape(n, ss, n, ss).mean(axis=(1, 3))

_N_fs = 128
_S_fs = _N_fs/80                                                              # lengths in the picture were designed for 80 pixels
_ph_fs = _phantom_fs(_N_fs)
_phshow_fs = _phantom_fs(256, 2)                                      # the same slice at a higher resolution, for display only
_c_fs = (_N_fs - 1) / 2
_COL_fs, _ROW_fs = np.meshgrid(np.arange(_N_fs) - _c_fs, np.arange(_N_fs) - _c_fs)       # x and -z of every pixel (rows point down)
_FT_fs = np.log1p(np.abs(np.fft.fftshift(np.fft.fft2(_ph_fs))))[::-1]                    # amplitude of the 2D transform, k_z pointing up
_nu_fs = np.arange(-(_N_fs//2), _N_fs//2 + 1)                                           # spatial frequencies in cycles per N pixels

def draw_fs(alpha=0):
    a = np.radians(alpha)
    rot = nd_rotate(_ph_fs, -alpha, reshape=False, order=1)
    rot_show = nd_rotate(_phshow_fs, -alpha, reshape=False, order=1)                     # the tilted specimen at the higher resolution, for display
    prof = rot.sum(axis=0)
    P = np.abs(np.fft.fftshift(np.fft.fft(prof)))                                        # frequencies -N/2 ... N/2 - 1
    p_ft = np.append(P, P[0])                                                            # the Nyquist frequency +N/2 equals -N/2
    # exact value of the 2D transform of the slice on the line through the origin at the angle alpha: (k_x, k_z) = nu (cos a, sin a)
    kc, kr = _nu_fs*np.cos(a), -_nu_fs*np.sin(a)                                         # in array coordinates (column, row), row = -z
    E = np.exp(-2j*np.pi*(kc[:, None]*_COL_fs.ravel()[None, :] + kr[:, None]*_ROW_fs.ravel()[None, :])/_N_fs)
    s_ft = np.abs(E @ _ph_fs.ravel())

    W, H = 9.0, 6.5
    fig = plt.figure(figsize=(W, H))
    def axes_in(l, b, w, h):
        return fig.add_axes([l/W, b/H, w/W, h/H])
    w_ph = 3.5; h_ph = w_ph*(_N_fs - 0.5 + 10*_S_fs)/_N_fs; h_pr = 0.85; gap = 0.5; bot = 0.75
    l1, l2 = 0.55, 0.55 + w_ph + 1.0
    ax1 = axes_in(l1, bot + h_pr + gap, w_ph, h_ph)                # specimen
    ax2 = axes_in(l1, bot, w_ph, h_pr)                             # its projection
    ax3 = axes_in(l2, bot + h_pr + gap, w_ph, w_ph)                # 2D Fourier transform with the slice
    ax4 = axes_in(l2, bot, w_ph, h_pr)                             # transform of the projection and slice, same frequency axis

    n = _N_fs
    ax1.imshow(rot_show, cmap='gray', vmin=0, vmax=1.1, extent=[-0.5, n-0.5, n-0.5, -0.5], aspect='auto', interpolation='bicubic')
    for xp in np.arange(0.05*n, n, 0.1*n):
        ax1.plot([xp, xp], [-0.5, n-0.5], color=BLUE, lw=0.8, alpha=0.35)
        ax1.annotate('', xy=(xp, 3*_S_fs), xytext=(xp, -8*_S_fs), arrowprops=dict(arrowstyle='-|>', color=BLUE, lw=0.9, alpha=0.8), annotation_clip=False)
    ax1.set_xlim(-0.5, n-0.5); ax1.set_ylim(n-0.5, -10*_S_fs); ax1.axis('off')
    ax1.set_title(f'Specimen tilted by {alpha:+d}°', fontsize=9.5)

    ax2.fill_between(np.arange(n), prof, color=CRIMSON, alpha=0.25); ax2.plot(prof, color=CRIMSON, lw=1.6)
    ax2.set_xlim(-0.5, n-0.5); ax2.set_ylim(0, 1.15*max(prof.max(), 30)); ax2.grid(alpha=0.25); ax2.set_yticks([])
    ax2.set_xlabel('position on the detector, $x$ (pixels)', fontsize=9.5); ax2.set_ylabel('$P_\\alpha(x)$', fontsize=9.5)

    ax3.imshow(_FT_fs, cmap='inferno', extent=[-0.5, 0.5, -0.5, 0.5], aspect='equal', interpolation='bicubic')
    r = 0.49
    ax3.plot([-r*np.cos(a), r*np.cos(a)], [-r*np.sin(a), r*np.sin(a)], color=BLUE, lw=2.6)
    ax3.set_xlim(-0.5, 0.5); ax3.set_ylim(-0.5, 0.5)
    ax3.set_xlabel('$k_x$ (1/pixel)', fontsize=9.5); ax3.set_ylabel('$k_z$ (1/pixel)', fontsize=9.5)
    ax3.set_title(f'2D Fourier transform of the untilted slice\n(blue: central line at $\\alpha$ = {alpha:+d}°)', fontsize=9.5)

    nu = _nu_fs/_N_fs
    ax4.semilogy(nu, p_ft + 1e-9, color=CRIMSON, lw=2.4, label='transform of the projection')
    ax4.semilogy(nu, s_ft + 1e-9, color=BLUE, lw=1.5, ls='--', label='values on the blue line')
    ax4.set_xlim(-0.5, 0.5); ax4.set_ylim(1e-3, 2*s_ft.max()); ax4.grid(alpha=0.25, which='major')
    ax4.set_xlabel('spatial frequency $\\nu$ along the line (1/pixel)', fontsize=9.5); ax4.set_ylabel('amplitude', fontsize=9.5)
    ax4.legend(fontsize=7.5, loc='lower center', frameon=True, framealpha=0.85, ncol=1, borderpad=0.3, labelspacing=0.2)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_fs = {'description_width': '120px'}
al_sl_fs = IntSlider(value=30, min=-90, max=90, step=5, description='Tilt angle (°)', style=_style_fs, layout={'width': '420px'})
out_fs = ImageWidget(format='png', layout={'max_width': '100%'})
def update_fs(_=None):
    out_fs.value = draw_fs(al_sl_fs.value)
al_sl_fs.observe(update_fs, names='value')
display(VBox([al_sl_fs, out_fs]))
update_fs()
```

(sec:recon-coverage)=
### Coverage of Fourier space

The Fourier slice theorem shows which part of Fourier space a single projection measures. In this section we will ask which part a whole set of projections measures. We treat the general three-dimensional case, which applies to single-particle analysis as well, before the following sections turn to the tilt series.

An object of size $D$ has a Fourier transform that varies on the scale $1/D$. A projection therefore determines the Fourier transform not only on the central plane but in a slab of thickness of about $1/D$ around it. The set of projections covers a point of Fourier space if the point lies in one of these slabs. The geometry of the coverage differs between the two experiments.

In single-particle analysis, the viewing directions are distributed over the sphere and if all orientations occur equally often, Fourier space is covered without a preferred direction. Preferred orientations of the particles on the grid, which occur frequently in practice, leave a cone of directions with few or no views, and the reconstruction is then anisotropic. In electron tomography, all planes contain the tilt axis and ecause the tilt range is limited to about 60°, a wedge-shaped region of Fourier space around the beam direction is not covered (we call this the **missing wedge** and will treat it in {numref}`sec:tomo-missing-wedge`).

Even within the covered region (i.e. excluding the wedge of missing data), the sampling is uneven. For $m$ viewing directions distributed uniformly over the sphere, the mean number of slabs that cover a point at the spatial frequency $|\mathbf{k}|$ is

$$
\bar{n}(|\mathbf{k}|) = \frac{m}{2D\,|\mathbf{k}|}
$$ (eq:overlap-3d)

```{admonition} Derivation: overlap of the central slabs
:class: dropdown
A point $\mathbf{q}$ with $|\mathbf{q}| = k$ lies in the slab of a projection with viewing direction $\mathbf{n}$ if its distance to the plane is smaller than half the thickness, $|\mathbf{q}\cdot\mathbf{n}| < 1/(2D)$. For $\mathbf{n}$ uniformly distributed over the sphere, $\cos\theta = \mathbf{q}\cdot\mathbf{n}/k$ is uniformly distributed between $-1$ and $1$. The probability that $|\cos\theta| < 1/(2Dk)$ is therefore $1/(2Dk)$, and multiplying by the number of projections $m$ gives eq. {eq}`eq:overlap-3d`.
```

As a consequence, low spatial frequencies are measured by many projections, and high spatial frequencies only by a few. If the projections were simply summed, each Fourier component would be weighted with the number of slabs that cover it, that is, with $1/|\mathbf{k}|$, and the reconstruction would be blurred. This is exactly what we observed for direct backprojection. The weighting has to be compensated by multiplying with a weight proportional to $|\mathbf{k}|$, which in two dimensions is the ramp filter of filtered backprojection ({numref}`sec:tomo-filtered-backprojection`). At spatial frequencies where $\bar{n} < 1$, the slabs no longer overlap and gaps appear, which no weighting can fill. Gaps start at $|\mathbf{k}| = m/(2D)$ and limit the resolution that can be reached with $m$ views. For a single-axis tilt series evenly spread over 180°, the same argument in the plane perpendicular to the tilt axis gives the Crowther criterion ({numref}`sec:tomo-crowther`). In practice, many more projections than this geometric minimum are required for a number of reasons that we will discuss further on.

````{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 left panel shows a section through Fourier space, the plane $k_y = 0$, in which every slab appears as a strip through the centre. It counts how many strips cover each point, for a single-axis tilt series with $m$ views in the range $\pm\alpha_\mathrm{max}$ or for $m$ randomly oriented views. The right panel shows the coverage as a function of spatial frequency.

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults (tilt series, $m = 20$, $\pm 60°$, $D = 20$).** The slabs cover a double wedge around the $k_x$ axis, and a wedge around $k_z$ is empty. At high $|\mathbf{k}|$, the slabs separate into individual strips. The mean coverage follows $m/(\pi D|\mathbf{k}|)$ and falls below 1 at $|\mathbf{k}| = 0.32$, where the gaps start.
2. **Set the maximum tilt to 90°.** The wedge closes and the coverage becomes isotropic, but the curve does not change. 
3. **Increase the number of views to $m = 60$.** The curve stays above 1 up to the Nyquist frequency.
4. **Go back to $m = 20$ and increase the object size to $D = 40$.** The slabs become thin, and the gaps start already at $|\mathbf{k}| = 0.16$. Larger objects need more views for the same resolution.
5. **Switch to random orientations ($m = 20$, $D = 20$).** The slabs cover all directions, and the gaps start at $m/(2D) = 0.50$.
```
````

```{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 ipywidgets import IntSlider, Dropdown, VBox, HBox, Image as ImageWidget
from IPython.display import display

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

def draw_cov(m=20, tmax=60, D=20, kind='Tilt series'):
    ng = 129
    kk = np.linspace(-0.5, 0.5, ng)
    KX, KZ = np.meshgrid(kk, kk)                                      # the plane k_y = 0 (units: 1/pixel)
    if kind == 'Tilt series':
        al = np.radians(np.linspace(-tmax, tmax, m))
        nrm = np.stack([np.sin(al), np.zeros(m), np.cos(al)])         # viewing directions of a tilt series
        k_gap, formula, flab = m/(np.pi*D), lambda k: m/(np.pi*D*k), '$m/(\\pi D|k|)$'
    else:
        rng = np.random.default_rng(3)
        nrm = rng.normal(size=(3, m)); nrm /= np.linalg.norm(nrm, axis=0)    # random viewing directions
        k_gap, formula, flab = m/(2*D), lambda k: m/(2*D*k), '$m/(2D|k|)$'
    cnt = (np.abs(KX[..., None]*nrm[0] + KZ[..., None]*nrm[2]) < 1/(2*D)).sum(-1)       # number of slabs that cover (kx, 0, kz)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 4.4), gridspec_kw={'width_ratios': [1, 1.1]})
    im = ax1.imshow(cnt, cmap='magma', extent=[-0.5, 0.5, -0.5, 0.5], origin='lower', vmin=0, vmax=max(4, np.percentile(cnt, 99)))
    ax1.set_xlabel('$k_x$ (1/pixel)', fontsize=10); ax1.set_ylabel('$k_z$ (1/pixel)', fontsize=10)
    ax1.set_title(f'Number of slabs that cover each point\n({kind.lower()}, {m} views' + (f', ±{tmax}°)' if kind == 'Tilt series' else ')'), fontsize=10)
    fig.colorbar(im, ax=ax1, fraction=0.046, pad=0.03)
    ax2.axhspan(0, 1, color=CRIMSON, alpha=0.12, lw=0)
    ax2.axhline(1, color=CRIMSON, lw=1.2)
    ax2.text(0.49, 0.5, 'gaps', color=CRIMSON, fontsize=9, ha='right', va='center')
    kf = np.linspace(0.02, 0.5, 200)
    ax2.plot(kf, formula(kf), color=BLUE, lw=2.4, ls='--', label=flab)
    ymax = 12
    ax2.set_xlim(0, 0.5); ax2.set_ylim(0, ymax); ax2.grid(alpha=0.25)
    if k_gap < 0.5:
        ax2.axvline(k_gap, color=ORANGE, lw=2, ls=':')
        ax2.text(k_gap + 0.008, ymax*0.62, f'$|k|$ = {k_gap:.2f}', color='#c47f00', fontsize=9.5, va='top')
    else:
        ax2.text(0.25, ymax*0.62, 'no gaps up to the\nNyquist frequency', color='#c47f00', fontsize=9.5, va='top')
    ax2.set_xlabel('$|k|$ (1/pixel)', fontsize=10); ax2.set_ylabel('mean number of slabs', fontsize=10)
    ax2.legend(fontsize=9, loc='upper right', frameon=False)
    ax2.set_title('Coverage as a function of the spatial frequency', fontsize=10)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=96); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_cov = {'description_width': '150px'}
m_sl = IntSlider(value=20, min=5, max=200, step=5, description='Number of views m', style=_style_cov, layout={'width': '400px'})
tmax_sl_cov = IntSlider(value=60, min=30, max=90, step=5, description='Max. tilt (°)', style=_style_cov, layout={'width': '400px'})
D_sl = IntSlider(value=20, min=10, max=60, step=5, description='Object size D (px)', style=_style_cov, layout={'width': '400px'})
kind_cov = Dropdown(options=['Tilt series', 'Random orientations'], value='Tilt series', description='Views', style=_style_cov, layout={'width': '300px'})
out_cov = ImageWidget(format='png', layout={'max_width': '100%'})
def update_cov(_=None):
    out_cov.value = draw_cov(m_sl.value, tmax_sl_cov.value, D_sl.value, kind_cov.value)
for _sl_cov in [m_sl, tmax_sl_cov, D_sl, kind_cov]:
    _sl_cov.observe(update_cov, names='value')

display(VBox([HBox([VBox([m_sl, tmax_sl_cov, D_sl]), kind_cov]), out_cov]))
update_cov()
```

(sec:tomo-filtered-backprojection)=
### Filtered backprojection

Now we understand that direct backprojection produces blurry reconstructions because Fourier space is oversampled near the origin. As more projections are added, low-frequency components are reinforced more than high-frequency components, which are sparse in the collection of central slices.

<u>Filtered backprojection (FBP)</u> corrects this by applying a ramp filter $|\nu|$ to each 1D projection before backprojecting. In Fourier space, multiplying by $|\nu|$ compensates exactly for the radial oversampling density that we have seen above and yields a reconstruction with uniform frequency weighting:

$$
A(x, z) = \int_0^\pi \mathcal{F}^{-1}\!\left[ |\nu|\, \hat{P}_\alpha(\nu) \right](x\cos\alpha + z\sin\alpha)\, \mathrm{d}\alpha
$$ (eq:fbp)

where $\mathcal{F}^{-1}$ is the inverse one-dimensional Fourier transform, so that the term in brackets is the filtered projection. In the electron microscopy literature, the same method is called <u>weighted backprojection</u> (WBP), because the filter acts as weights in Fourier space. For a single tilt axis with equal tilt steps, the two are identical. The weights can also be calculated for uneven tilt steps and other tilt geometries.

In practice, the pure ramp filter is rarely used, because it amplifies noise at high spatial frequencies as strongly as the signal. It is multiplied with a window that tapers it towards zero at high frequencies and thus trade some resolution for a lower noise level. The filtered projection in real space is then backprojected normally. The filter corrects the weights of the frequencies that are covered by projections, but it cannot restore frequencies in the gaps between them, which is why reconstructions from few projections remain streaky.

The simulation below compares direct backprojection with filtered backprojection for a noisy tilt series.

````{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. Reconstruct a noisy tilt series with the ramp filter and with a windowed ramp filter, and compare both with direct backprojection. The noise is set by the total dose.

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults (90°, 200 e⁻/Å², ramp filter).** The 91 tilts receive 2.2 e⁻/Å² each. The filtered backprojection shows the ring, the membranes and the disc sharply, whereas the direct backprojection is blurred.
2. **Lower the dose to 20 e⁻/Å².** The filtered backprojection becomes speckled and streaky, and it now looks worse than the direct backprojection, which stays smooth although blurred. The ramp filter amplifies the noise at high spatial frequencies, where the projections contain little signal.
3. **Switch to the Hann window.** The finest speckle is suppressed and the structures stand out better, at the cost of slightly softer edges. The filter panel shows how the window tapers the ramp to zero at the Nyquist frequency.
4. **Go back to 200 e⁻/Å² (Hann window) and reduce the maximum tilt to 60°.** The same dose is now shared by 61 tilts of 3.3 e⁻/Å². The horizontal membrane is lost in the missing wedge, and the ring is stretched along the beam direction. The filter cannot restore what was not measured.
```
````

```{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
from ipywidgets import IntSlider, FloatLogSlider, Dropdown, VBox, HBox, Image as ImageWidget
from IPython.display import display

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

def _phantom_fb(n=128, ss=1):
    # slice of a specimen: x lateral, z along the beam (up); ring = microtubule, bars = membranes, disc = protein complex
    m = n*ss                                                       # with ss > 1, the grid is supersampled and averaged, which smooths the edges
    y, x = (np.mgrid[0:m, 0:m] + 0.5)/ss - 0.5
    r1 = np.hypot(x - n*0.30, y - n*0.32)
    img = 0.9 * ((r1 > n*0.11) & (r1 < n*0.18))
    img = img + 0.85 * ((np.abs(y - n*0.67) < n*0.025) & (x > n*0.10) & (x < n*0.90))
    img = img + 0.85 * ((np.abs(x - n*0.55) < n*0.025) & (y > n*0.12) & (y < n*0.56))
    img = img + 0.75 * (np.hypot(x - n*0.70, y - n*0.36) < n*0.07)
    return np.clip(img, 0, 1).reshape(n, ss, n, ss).mean(axis=(1, 3))

_N_fb = 128                                                        # pixels; the slice is 50 nm wide, so one pixel is 0.39 nm = 3.9 Å
_C_fb = _N_fb//2
_PIXA2_fb = (500.0/_N_fb)**2                                       # area of one pixel in Å^2
_KAPPA_fb = 0.1                                                    # contrast per unit of projected density (chosen so that the slice is crisp at 200 e/Å^2 and noisy at low doses; real tomograms are noisier)
_ph_fb = _phantom_fb(_N_fb)
_phshow_fb = _phantom_fb(256, 2)                                      # the same slice at a higher resolution, for display only
_ang_fb = np.arange(-90, 91, 2)
_sino_fb = np.array([nd_rotate(_ph_fb, -a, reshape=False, order=1).sum(axis=0) for a in _ang_fb])
_z_fb = np.random.default_rng(3).standard_normal(_sino_fb.shape)  # one fixed noise pattern, scaled by the dose
_YY_fb, _XX_fb = (np.mgrid[0:_N_fb, 0:_N_fb] - _C_fb).astype(float)
_a_fb = np.deg2rad(_ang_fb)[:, None, None]
_PX_fb = (_XX_fb[None]*np.cos(_a_fb) - _YY_fb[None]*np.sin(_a_fb) + _C_fb).clip(0, _N_fb - 1)   # y points down, z = -y
_LO_fb = _PX_fb.astype(int); _HI_fb = np.minimum(_LO_fb + 1, _N_fb - 1); _FR_fb = _PX_fb - _LO_fb
_L_fb = 2*_N_fb                                                    # projections are zero-padded to twice their length before filtering
_nu_fb = np.fft.rfftfreq(_L_fb)                                    # spatial frequency in 1/pixel, 0 ... 0.5
_bg_fb = np.zeros((_N_fb, _N_fb), bool); _bg_fb[int(0.75*_N_fb):int(0.9*_N_fb), int(0.1*_N_fb):int(0.3*_N_fb)] = True    # an empty region to measure the noise

_DISP_fb = dict(vmin=-0.8, vmax=1.6, interpolation='bicubic')          # one fixed, gentle display window, so that noise levels can be compared

def _backproject_fb(P, sel):
    idx = np.nonzero(sel)[0]; rows = np.arange(len(idx))[:, None, None]
    lo, hi, fr = _LO_fb[idx], _HI_fb[idx], _FR_fb[idx]
    return (P[rows, lo]*(1 - fr) + P[rows, hi]*fr).sum(axis=0)*np.radians(2)                # sum over the projections times the angular step (2 degrees)

def _filter_fb(kind, nu):
    if kind == 'Hann window':
        return nu*0.5*(1 + np.cos(2*np.pi*nu))                       # reaches zero at the Nyquist frequency
    return nu.copy()

def draw_fb(max_tilt=90, dose=120.0, kind='Ramp (Ram-Lak)'):
    sel = np.abs(_ang_fb) <= max_tilt
    m = int(sel.sum())
    sino = _sino_fb[sel]
    n0 = dose/m*_PIXA2_fb                                            # electrons per pixel in one tilt image
    noisy = sino + np.sqrt(1 + _KAPPA_fb*sino)/(_KAPPA_fb*np.sqrt(n0))*_z_fb[sel]     # shot noise of an image with the contrast kappa
    bp = _backproject_fb(noisy, sel)/np.pi
    pad = (_L_fb - _N_fb)//2
    f = np.fft.irfft(np.fft.rfft(np.pad(noisy, ((0, 0), (pad, pad))), axis=1)*_filter_fb(kind, _nu_fb)[None, :], n=_L_fb, axis=1)[:, pad:pad + _N_fb]
    rec = _backproject_fb(f, sel)
    cc = lambda im: np.corrcoef(im.ravel(), _ph_fb.ravel())[0, 1]
    name = 'ramp' if kind.startswith('Ramp') else 'Hann window'

    fig, axes = plt.subplots(1, 4, figsize=(13, 3.9))
    axes[0].imshow(_phshow_fb, cmap='gray', vmin=-0.2, vmax=1.2, interpolation='bicubic'); axes[0].axis('off'); axes[0].set_title('Original slice', fontsize=9.5)
    axes[1].imshow(bp/max(bp.max(), 1e-9), cmap='gray', vmin=-0.2, vmax=1.0, interpolation='bicubic'); axes[1].axis('off')
    axes[1].set_title(f'Direct backprojection', fontsize=9.5)
    axes[2].imshow(rec, cmap='gray', **_DISP_fb); axes[2].axis('off')
    axes[2].set_title(f'Filtered backprojection ({name})', fontsize=9.5)
    ax = axes[3]
    nu = np.linspace(0, 0.5, 200)
    ax.plot(nu, nu, color=GREY, lw=1.6, ls='--', label='ramp $|\\nu|$')
    ax.plot(nu, _filter_fb(kind, nu), color=CRIMSON, lw=2.2, label=name)
    ax.set_xlim(0, 0.5); ax.set_ylim(0, 0.55); ax.grid(alpha=0.25)
    ax.set_xlabel('spatial frequency $\\nu$ (1/pixel)', fontsize=9.5); ax.set_ylabel('weight of the projection', fontsize=9.5)
    ax.legend(fontsize=8.5, loc='upper left', frameon=False)
    ax.set_title('Filter applied to every projection', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_fb = {'description_width': '130px'}
tilt_fb = IntSlider(value=90, min=20, max=90, step=5, description='Max tilt (°)', style=_style_fb, layout={'width': '380px'})
dose_fb = FloatLogSlider(value=200.0, base=10, min=1, max=np.log10(200), step=0.05, description='Total dose (e⁻/Å²)', style=_style_fb, layout={'width': '380px'}, readout_format='.0f')
kind_fb = Dropdown(options=['Ramp (Ram-Lak)', 'Hann window'], value='Ramp (Ram-Lak)', description='Filter', style=_style_fb, layout={'width': '300px'})
out_fb = ImageWidget(format='png', layout={'max_width': '100%'})
def update_fb(_=None):
    out_fb.value = draw_fb(tilt_fb.value, dose_fb.value, kind_fb.value)
for _w_fb in (tilt_fb, dose_fb, kind_fb):
    _w_fb.observe(update_fb, names='value')
display(VBox([HBox([VBox([tilt_fb, dose_fb]), kind_fb]), out_fb]))
update_fb()
```

(sec:tomo-missing-wedge)=
## The missing wedge

A critical limitation of single-axis tilt series tomography is the <u>missing wedge</u>. Because the tilt angle is limited to about ±60°–70°, the central sections only cover the directions between $-\alpha_\mathrm{max}$ and $+\alpha_\mathrm{max}$, and a wedge-shaped region of three-dimensional Fourier space around the beam direction $k_z$ is never sampled. For example, a maximum tilt of 60° leaves 33% of Fourier space empty, and 70° still leaves at least 22%. Fourier components inside the wedge cannot be reconstructed, and by the Fourier slice theorem this has two consequences in real space.

1. **Elongation along the beam direction.** The sampled region is wider along $k_x$ than along $k_z$. The ratio of its root-mean-square extents is

   $$
   e = \sqrt{\frac{\alpha + \sin\alpha\cos\alpha}{\alpha - \sin\alpha\cos\alpha}}
   $$

   with $\alpha = \alpha_\mathrm{max}$ in radians, which is about 1.5 for ± 60° and 1.3 for ± 70°. The resolution along the beam direction is lower than in the plane by roughly this factor, and the point spread function is stretched along $z$ accordingly. 
   
2. **Loss of features that depend on their orientation.** A feature is only reconstructed if its Fourier components lie in the sampled region. The Fourier components of a line or a membrane are perpendicular to it. A membrane in the plane of the specimen has them along $k_z$, inside the wedge, and is largely lost, whereas a membrane perpendicular to the specimen plane has them in the sampled region and is reconstructed well.

```{admonition} Derivation: the elongation factor
:class: dropdown
Assume that the covered region of Fourier space is filled uniformly, as after weighting. Take its root-mean-square extent along $k_x$ and along $k_z$ as a measure of the resolution in these directions, which is inversely proportional to it. In polar coordinates, with the angle $\theta$ measured from $k_x$ and $|\theta| \le \alpha$, the mean squares are proportional to $\int_{-\alpha}^{\alpha}\cos^2\theta\,\mathrm{d}\theta = \alpha + \sin\alpha\cos\alpha$ for $k_x$ and to $\int_{-\alpha}^{\alpha}\sin^2\theta\,\mathrm{d}\theta = \alpha - \sin\alpha\cos\alpha$ for $k_z$, with the same radial factor. The ratio of the extents is $e$, and the resolution along $z$ is lower than that along $x$ by about this factor.
```

````{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. Reduce the tilt range and watch the sampled region of Fourier space, the reconstruction and the point spread function.

```{admonition} Things to try
:class: dropdown
1. **Start at 90°.** The sampled region is a full disc, the slice is reconstructed without distortion and the point is round.
2. **Reduce the tilt range to ±60°.** The horizontal membrane has almost disappeared, the vertical one survives, and the ring is stretched along $z$ into a diamond. The point is also stretched and is surrounded by streaks along the boundary of the wedge.
3. **Go on to ±30°.** The horizontal line is gone and the point is already noticably stretched.
4. **Compare the width ratio with $e$.** The formula follows the trend (1.3, 1.55, 2.1 and 3.3 for ±70°, ±60°, ±45° and ±30°) but lies 10–15% below the width at half maximum (1.5, 1.8, 2.4 and 3.8). It describes the root-mean-square extent of the sampled region and not the half maximum of the peak.
```
````

```{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
from ipywidgets import IntSlider, VBox, Image as ImageWidget
from IPython.display import display

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

def _phantom_mw(n=80, ss=1):
    # slice of a specimen: x lateral, z along the beam (up); ring = microtubule, bars = membranes, disc = protein complex
    m = n*ss                                                       # with ss > 1, the grid is supersampled and averaged, which smooths the edges
    y, x = (np.mgrid[0:m, 0:m] + 0.5)/ss - 0.5
    r1 = np.hypot(x - n*0.30, y - n*0.32)
    img = 0.9 * ((r1 > n*0.11) & (r1 < n*0.18))
    img = img + 0.85 * ((np.abs(y - n*0.67) < n*0.025) & (x > n*0.10) & (x < n*0.90))
    img = img + 0.85 * ((np.abs(x - n*0.55) < n*0.025) & (y > n*0.12) & (y < n*0.56))
    img = img + 0.75 * (np.hypot(x - n*0.70, y - n*0.36) < n*0.07)
    return np.clip(img, 0, 1).reshape(n, ss, n, ss).mean(axis=(1, 3))

_N_mw = 80
_C_mw = _N_mw//2
_ph_mw = _phantom_mw(_N_mw)
_phshow_mw = _phantom_mw(256, 2)                                      # the same slice at a higher resolution, for display only
_ang_mw = np.arange(-90, 91, 1)
_sino_mw = np.array([nd_rotate(_ph_mw, -a, reshape=False, order=1).sum(axis=0) for a in _ang_mw])
_pt_mw = np.exp(-(np.arange(_N_mw) - _C_mw)**2/2.0)*np.sqrt(2*np.pi)                     # projection of a point (Gaussian, sigma = 1 pixel) at the centre, the same for all angles
_YY_mw, _XX_mw = (np.mgrid[0:_N_mw, 0:_N_mw] - _C_mw).astype(float)
_L_mw = 2*_N_mw
_nu_mw = np.fft.rfftfreq(_L_mw)

def _fbp_mw(sino, angles):
    pad = (_L_mw - _N_mw)//2
    f = np.fft.irfft(np.fft.rfft(np.pad(sino, ((0, 0), (pad, pad))), axis=1)*_nu_mw[None, :], n=_L_mw, axis=1)[:, pad:pad + _N_mw]
    out = np.zeros((_N_mw, _N_mw))
    for p, a in zip(f, angles):
        a = np.deg2rad(a)
        px = (_XX_mw*np.cos(a) - _YY_mw*np.sin(a) + _C_mw).clip(0, _N_mw - 1)           # y points down, z = -y
        lo = px.astype(int); hi = np.minimum(lo + 1, _N_mw - 1); fr = px - lo
        out += p[lo]*(1 - fr) + p[hi]*fr
    return out*np.radians(1)                                                          # sum over the projections times the angular step (1 degree)

def _fwhm_mw(profile):
    p = profile/profile.max(); i0 = int(profile.argmax())
    l = i0
    while l > 0 and p[l] > 0.5: l -= 1
    r = i0
    while r < len(p) - 1 and p[r] > 0.5: r += 1
    return (r - 1 + (p[r-1] - 0.5)/(p[r-1] - p[r])) - (l + (0.5 - p[l])/(p[l+1] - p[l]))

def draw_mw(max_tilt=60):
    sel = np.abs(_ang_mw) <= max_tilt
    angs = _ang_mw[sel]
    rec = _fbp_mw(_sino_mw[sel], angs)
    psf = _fbp_mw(np.tile(_pt_mw, (len(angs), 1)), angs)
    a = np.radians(max_tilt); s = np.sin(a)*np.cos(a)
    e = np.sqrt((a + s)/(a - s)) if max_tilt < 90 else 1.0
    ratio = _fwhm_mw(psf[:, _C_mw])/_fwhm_mw(psf[_C_mw, :])
    k = np.linspace(-0.5, 0.5, 201); KX, KZ = np.meshgrid(k, k)
    mask = ((np.degrees(np.arctan2(np.abs(KZ), np.abs(KX))) <= max_tilt) & (np.hypot(KX, KZ) <= 0.5)).astype(float)

    fig, axes = plt.subplots(1, 4, figsize=(13, 3.9))
    axes[0].imshow(_phshow_mw, cmap='gray', vmin=-0.2, vmax=1.2, interpolation='bicubic'); axes[0].axis('off'); axes[0].set_title('Original slice', fontsize=9.5)
    axes[1].imshow(mask, cmap='gray', extent=[-0.5, 0.5, -0.5, 0.5], vmin=0, vmax=1.3)
    for sg in (+1, -1):
        axes[1].plot([-0.5, 0.5], [-sg*0.5*np.tan(a), sg*0.5*np.tan(a)] if max_tilt < 90 else [0, 0], color=CRIMSON, lw=1.4)
    axes[1].set_xlim(-0.5, 0.5); axes[1].set_ylim(-0.5, 0.5)
    axes[1].set_xlabel('$k_x$ (1/pixel)', fontsize=9.5); axes[1].set_ylabel('$k_z$ (1/pixel)', fontsize=9.5)
    axes[1].set_title(f'Sampled region of Fourier space\n(grey), tilt range ±{max_tilt}°', fontsize=9.5)
    axes[2].imshow(rec, cmap='gray', vmin=-0.2, vmax=1.2, interpolation='bicubic'); axes[2].axis('off')
    axes[2].set_title(f'Filtered backprojection\n±{max_tilt}°, noise-free', fontsize=9.5)
    h = 18
    axes[3].imshow(psf[_C_mw-h:_C_mw+h+1, _C_mw-h:_C_mw+h+1]/psf.max(), cmap='gray', vmin=-0.3, vmax=1.0, extent=[-h-0.5, h+0.5, h+0.5, -h-0.5])
    axes[3].set_xlabel('$x$ (pixels)', fontsize=9.5); axes[3].set_ylabel('$z$ (pixels, pointing down)', fontsize=9.5)
    axes[3].set_title(f'Reconstruction of a point\nwidth $z/x$ = {ratio:.2f} at half maximum; $e$ = {e:.2f}', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_mw = {'description_width': '120px'}
tilt_mw = IntSlider(value=60, min=20, max=90, step=5, description='Max tilt (°)', style=_style_mw, layout={'width': '420px'})
out_mw = ImageWidget(format='png', layout={'max_width': '100%'})
def update_mw(_=None):
    out_mw.value = draw_mw(tilt_mw.value)
tilt_mw.observe(update_mw, names='value')
display(VBox([tilt_mw, out_mw]))
update_mw()
```

The missing wedge can be partially mitigated by using a dual-axis tilt series, i.e. by collecting tilt series around two perpendicular axes, which replaces the missing wedge with a smaller missing pyramid. Alternatively, regularised reconstruction algorithms can impose constraints that partially fill in the missing information.

(sec:tomo-crowther)=
## The Crowther criterion

How finely must the tilt series be sampled to fill Fourier space up to a desired resolution? The answer to this questions is given by the **Crowther criterion**, which is the two-dimensional form of the overlap argument for the coverage of Fourier space that we discussed in ({numref}`sec:recon-coverage`).

Let us consider a 2D image of diameter $D$ pixels (or sample of thickness $D$ Å). Each 1D projection fills in one central line of the 2D Fourier transform, with a width of about $1/D$ (the inverse of the object size, so that larger objects need finer sampling). A central line passes through the origin and therefore crosses the circle at the spatial frequency $k = 1/d$ at two opposite points, which are both covered with the width $1/D$. The circumference of the circle is $2\pi/d$.

To fill this circumference without gaps, $m$ lines are required with

$$
m\,\frac{2}{D} \geq \frac{2\pi}{d}
\quad \Longrightarrow \quad
m \geq \frac{\pi D}{d}, \qquad \Delta\theta = \frac{\pi}{m} \leq \frac{d}{D}
$$ (eq:crowther)

where the tilt increment $\Delta\theta$ (in radians) follows from distributing the $m$ projections over 180°. This is the Crowther criterion, which gives the number of tilt angles required to achieve the resolution $d$ from a specimen of diameter $D$ as $\pi D/d$, and it scales as $D/d$.

<u>Practical consequences of sampling overlap:</u> For a specimen of thickness $D$ = 500 Å, a resolution of $d$ = 50 Å requires $m$ ≥ 31 tilts, whereas $d$ = 10 Å already requires $m$ ≥ 157, and these numbers further grow in proportion to the thickness. For the criterion, the increment matters and not the number of images, because it sets the spacing of the central lines. An increment of 3° or 2° is the same spacing as $m$ = 180°/$\Delta\theta$ = 60 or 90 projections spread over 180°. In the range of angles that the tilt series covers, Fourier space is then filled completely up to 26 Å or 17 Å for a 500 Å specimen, whereas the missing wedge of course stays empty at every resolution. These values are optimistic, because the specimen appears thicker when it is tilted. For a slab of thickness $D$, the apparent thickness is $D/\cos\alpha_\mathrm{max}$ and hence twice the original thickness at ±60°. One might expect that the available dose limits the number of tilts. In the ideal case, however, the total dose that is needed to determine every voxel of the reconstruction with a given statistical significance does not depend on the number of projections over which it is divided. A tilt series with a total dose of 120 e⁻/Å² could therefore in principle be recorded with 300 tilts of 0.4 e⁻/Å² each. What limits the number of tilts in practice is the signal that every image needs for successful alignment and CTF estimation, and the time that it takes to acquire every tilt. 

````{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. Change the number of projections and investigate the resolution that the criterion predicts.


```{admonition} Things to try
:class: dropdown
1. **Start with $m = 10$ (a step of 18°).** The reconstruction is dominated by streaks along the directions of the projections. In Fourier space, the lines are separated by gaps almost everywhere, and the circle in which Fourier space is filled completely is small ($d = 15.7$ nm).
2. **Increase $m$ to 60 and then to 90,** which is the grey band of a typical tilt series with increments of 3° and 2°. The streaks fade, and the circle grows in proportion to $m$ ($d = 2.6$ nm and 1.7 nm). Its edge lies exactly where the gaps between the lines begin.
3. **Go on to $m = 180$ (a step of 1°).** The resolution of 0.9 nm is close to the pixel limit of 0.78 nm, so that more projections hardly improve the reconstruction.
```
````

```{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
from ipywidgets import IntSlider, VBox, Image as ImageWidget
from IPython.display import display

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

def _phantom_cr(n=128, ss=1):
    # slice of a specimen: x lateral, z along the beam (up); ring = microtubule, bars = membranes, disc = protein complex
    m = n*ss                                                       # with ss > 1, the grid is supersampled and averaged, which smooths the edges
    y, x = (np.mgrid[0:m, 0:m] + 0.5)/ss - 0.5
    r1 = np.hypot(x - n*0.30, y - n*0.32)
    img = 0.9 * ((r1 > n*0.11) & (r1 < n*0.18))
    img = img + 0.85 * ((np.abs(y - n*0.67) < n*0.025) & (x > n*0.10) & (x < n*0.90))
    img = img + 0.85 * ((np.abs(x - n*0.55) < n*0.025) & (y > n*0.12) & (y < n*0.56))
    img = img + 0.75 * (np.hypot(x - n*0.70, y - n*0.36) < n*0.07)
    return np.clip(img, 0, 1).reshape(n, ss, n, ss).mean(axis=(1, 3))

_N_cr = 128                                                         # pixels; the slice is D = 50 nm wide, so one pixel is 0.39 nm = 3.9 Å
_D_cr = 50.0
_C_cr = _N_cr//2
_ph_cr = _phantom_cr(_N_cr)
_phshow_cr = _phantom_cr(256, 2)                                      # the same slice at a higher resolution, for display only
_ang_cr = np.arange(-90, 90, 1)
_sino_cr = np.array([nd_rotate(_ph_cr, -a, reshape=False, order=1).sum(axis=0) for a in _ang_cr])
_YY_cr, _XX_cr = (np.mgrid[0:_N_cr, 0:_N_cr] - _C_cr).astype(float)
_a_cr = np.deg2rad(_ang_cr)[:, None, None]
_PX_cr = (_XX_cr[None]*np.cos(_a_cr) - _YY_cr[None]*np.sin(_a_cr) + _C_cr).clip(0, _N_cr - 1)   # y points down, z = -y
_LO_cr = _PX_cr.astype(int); _HI_cr = np.minimum(_LO_cr + 1, _N_cr - 1); _FR_cr = _PX_cr - _LO_cr
_L_cr = 2*_N_cr
_nu_cr = np.fft.rfftfreq(_L_cr)
_kk_cr = np.linspace(-0.8, 0.8, 321)                                # spatial frequency in 1/nm (Nyquist: 1.28 / nm)
_KX_cr, _KZ_cr = np.meshgrid(_kk_cr, _kk_cr)

_DISP_cr = dict(vmin=-0.3, vmax=1.2, interpolation='bicubic')          # one fixed display window

def _backproject_cr(P, sel):
    idx = np.nonzero(sel)[0]; rows = np.arange(len(idx))[:, None, None]
    lo, hi, fr = _LO_cr[idx], _HI_cr[idx], _FR_cr[idx]
    return (P[rows, lo]*(1 - fr) + P[rows, hi]*fr).sum(axis=0)*np.pi/len(idx)

def draw_cr(m=40):
    angles = np.unique(np.round(np.linspace(-90, 90, m, endpoint=False)).astype(int))
    sel = np.isin(_ang_cr, angles)
    me = int(sel.sum())
    sino = _sino_cr[sel]
    pad = (_L_cr - _N_cr)//2
    f = np.fft.irfft(np.fft.rfft(np.pad(sino, ((0, 0), (pad, pad))), axis=1)*_nu_cr[None, :], n=_L_cr, axis=1)[:, pad:pad + _N_cr]
    rec = _backproject_cr(f, sel)
    d_c = np.pi*_D_cr/m                                            # Crowther resolution in nm
    cover = np.zeros_like(_KX_cr, dtype=bool)
    for th in np.deg2rad(np.linspace(-90, 90, m, endpoint=False)):
        cover |= np.abs(-np.sin(th)*_KX_cr + np.cos(th)*_KZ_cr) < 0.5/_D_cr                  # slab of thickness 1/D around the central line

    fig, axes = plt.subplots(1, 4, figsize=(13, 3.9))
    axes[0].imshow(_phshow_cr, cmap='gray', vmin=-0.2, vmax=1.2, interpolation='bicubic'); axes[0].axis('off'); axes[0].set_title('Original slice', fontsize=9.5)
    axes[1].imshow(rec, cmap='gray', **_DISP_cr); axes[1].axis('off')
    axes[1].set_title(f'{m} projections over 180°, step {180/m:.1f}°', fontsize=9.5)
    axes[2].imshow(cover, cmap='gray', extent=[-0.8, 0.8, -0.8, 0.8], vmin=0, vmax=1.4, origin='lower')
    th = np.linspace(0, 2*np.pi, 200)
    axes[2].plot(np.cos(th)/d_c, np.sin(th)/d_c, color=ORANGE, lw=2)
    axes[2].set_xlim(-0.8, 0.8); axes[2].set_ylim(-0.8, 0.8)
    axes[2].set_xlabel('$k_x$ (1/nm)', fontsize=9.5); axes[2].set_ylabel('$k_z$ (1/nm)', fontsize=9.5)
    axes[2].set_title(f'Fourier space filled by the lines\n(orange circle: $d = \\pi D/m$ = {d_c:.1f} nm)', fontsize=9.5)
    ax = axes[3]
    ms = np.arange(5, 181)
    ax.loglog(ms, np.pi*_D_cr/ms, color=BLUE, lw=2)
    ax.axvspan(60, 90, color=GREY, alpha=0.35, lw=0)
    ax.axhline(2*_D_cr/_N_cr, color=GREY, lw=1.2, ls='--')
    ax.plot([m], [d_c], 'o', ms=9, color=ORANGE, mec='k')
    ax.text(5.3, 2*_D_cr/_N_cr*1.06, 'pixel limit (Nyquist)', fontsize=8, color='#808080')
    #ax.text(41, 22, '40–60 tilts\nin practice', fontsize=8, color='#606060', va='top')
    ax.set_xlim(5, 180); ax.set_ylim(0.5, 35); ax.grid(alpha=0.25, which='both')
    ax.set_xticks([5, 10, 20, 50, 100, 180]); ax.set_xticklabels(['5', '10', '20', '50', '100', '180'])
    ax.set_yticks([1, 2, 5, 10, 20]); ax.set_yticklabels(['1', '2', '5', '10', '20'])
    ax.set_xlabel('number of projections $m$', fontsize=9.5); ax.set_ylabel('resolution $d = \\pi D/m$ (nm)', fontsize=9.5)
    ax.set_title('Crowther criterion for $D$ = 50 nm', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_cr = {'description_width': '170px'}
m_sl_cr = IntSlider(value=40, min=5, max=180, step=1, description='Number of projections m', style=_style_cr, layout={'width': '430px'})
out_cr = ImageWidget(format='png', layout={'max_width': '100%'})
def update_cr(_=None):
    out_cr.value = draw_cr(m_sl_cr.value)
m_sl_cr.observe(update_cr, names='value')
display(VBox([m_sl_cr, out_cr]))
update_cr()
```

(sec:tomo-workflow)=
## From tilt series to tomogram

The reconstruction of a real tilt series needs more steps than the model problem we have discussed so far. In practice, every tilt is recorded as a movie and processed like a micrograph in single-particle analysis. The tilt images are then aligned to a common coordinate system, and the tomogram is reconstructed with a correction of the CTF. The tomogram is inspected and segmented, or repeated structures in it are picked and averaged using [subtomogram averaging]({numref}`sec:tomo-sta`).

(sec:tomo-acquisition)=
### Tilt series acquisition

A tilt series is recorded by tilting the specimen stage between about -60° and +60° in steps of 1–3° and recording an image at every tilt. The total dose of about 100 e⁻/Å² is divided over the tilts, which typically gives 1–3 e⁻/Å² per image. The order in which these tilts are recorded matters, because the dose accumulates during the series ({numref}`fig:tilt-schemes`). In a <u>unidirectional scheme</u>, the series runs from one end of the tilt range to the other, so that the images at the end have received the most dose. In a <u>bidirectional scheme</u>, the series starts at the lowest tilt and proceeds to one end of the tilt range, and then continues from the start to the other end, so that the second side receives more dose than the first. In the <u>dose-symmetric scheme</u>, the tilt alternates between the two sides and moves away from the start in steps. In this scheme the images at low tilt, which are the least affected by the thickness of the specimen and hence provide most contrast, are then recorded first and receive the lowest accumulated dose. For a lamella that has been milled from frozen-hydrated cells at a shallow angle to the grid, the series typically starts at a pre-tilt that compensates this angle.

```{figure} images/Images14/tilt_schemes.png
:name: fig:tilt-schemes
:width: 100%
:alt: Three tilt schemes for a series of 41 images between -60° and +60°. In the upper row, the tilt angle is plotted against the order of acquisition for the unidirectional, the bidirectional and the dose-symmetric scheme. In the lower row, the dose that has accumulated before each image is plotted against its tilt angle. The dose rises from one side to the other for the unidirectional scheme, is larger on the second side for the bidirectional scheme, and is lowest at low tilt and the same on both sides for the dose-symmetric scheme.

Tilt schemes for a series of 41 images in steps of 3° between −60° and +60°, with the same dose for every image. Top, the tilt angle against the order of acquisition. The circle marks the start, and the dashed line is the return of the stage to the starting angle. Bottom, the dose that has accumulated before each image is recorded. The colour gives the order of acquisition, from the first image (yellow) to the last image (dark blue). In the dose-symmetric scheme, both sides receive the same dose, and the images at low tilt receive the least.
```

The tilt increments need not be equal. In the *Saxton scheme*, the increments are finer at high tilt, where the specimen appears thicker, so that fewer images give the same resolution. A second tilt series recorded about an axis that is perpendicular to the first (dual-axis tomography) reduces the missing wedge to a missing pyramid but comes with the caveat that now the total dose budget must be distributed over even more images.

Several practical challenges distinguish cryo-ET from single-particle data collection.

**Dose per image.** Every tilt image receives only a small fraction of the total dose, so that the images are much noisier than single-particle micrographs, which receive 30–60 e⁻/Å².

**Mechanical hysteresis.** Tilting the stage causes small translations and changes of the defocus, which are corrected during the alignment of the tilt series.

**Cosine-law thickening.** At high tilt angles, the effective thickness of the specimen increases as $1/\cos\alpha$. At $60°$, it is doubled, which increases the inelastic scattering and reduces the quality of the images. Most tilt series are therefore limited to $\pm 60°$–$70°$. The fraction of electrons that is not scattered decreases exponentially with the path length, $\propto e^{-t_\mathrm{eff}/\Lambda}$, where $\Lambda$ is the mean free path ({numref}`subsec:The-mean-free-path`), so that the signal of the images at high tilt is weaker.

(sec:tomo-alignment)=
### Alignment and CTF correction

Every tilt movie is motion-corrected and dose-weighted as in single-particle analysis ({numref}`subsec:spa-preprocessing`). The tilt images then have to be aligned to a common coordinate system, because the specimen shifts and rotates slightly between the tilts due to mechanical limitations of the specimen stage and goniometer. In <u>fiducial-based alignment</u>, gold nanoparticles that have been added to the sample before freezing are followed through the tilt series. Their high contrast and their spehrical shape iads robust tracking. Their three-dimensional positions and the parameters of the alignment (the shifts, the rotation of the tilt axis and the tilt angles) are refined by minimising the reprojection error over all tilts. Fiducial-free alignment follows patches of the specimen across tilts by cross-correlation. This procedure is called <u>patch-tracking</u> and is common for specimens without fiducials, such as lamellae.

The CTF estiimation and correction is more complex than in single-particle analysis, because the defocus changes across a tilted image. For a flat specimen that is tilted by $\alpha$, the defocus changes linearly with the position $x'$ perpendicular to the tilt axis,

$$
\Delta f(x') = \Delta f_0 + x'\tan\alpha,
$$

where $\Delta f_0$ is the defocus at the tilt axis and the sign depends on the direction of the tilt. At $60°$, the defocus changes by 1.7 µm per µm, so that a field of view of 1 µm spans a defocus range of 1.7 µm.

This gradient limits the area that can be corrected by one CTF. In a strip of width $w$ parallel to the tilt axis, the defocus differs by up to $\pm(w/2)\tan\alpha$ from its value at the centre of the strip. The phase $\gamma = \pi\lambda\Delta f k^2$ of the CTF (revisit eq. {eq}`eq:ctf-ideal`) grows with the square of the spatial frequency, so that a given defocus difference matters more at high resolution. The Thon rings of the strip are the average of the squared CTF over the defocus values in the strip, and they fade as the phase difference between the centre and the edges of the strip grows and therefore the CTF oscillations no longer match. They vanish at the spatial frequency at which this difference reaches $\pi/2$, which corresponds to the resolution

$$
d = \sqrt{\lambda\, w \tan\alpha}.
$$ (eq:ctf-strip)

At 300 keV ($\lambda = 0.0197$ Å) and a tilt of 60°, this is 18.5 Å for an image that is 1 µm wide. A single CTF therefore describes a whole tilted image only at low resolution, and obtaining high-resolution information requires CTF correction over narrow strips. 

```{admonition} Derivation: the resolution limit of a defocus strip
:class: dropdown
In a strip with the mean defocus $\Delta f_\mathrm{c}$ and defocus values that are distributed uniformly in $\Delta f_\mathrm{c} \pm \delta$, the squared CTF of eq. {eq}`eq:ctf-ideal` is $\sin^2\gamma$ with $\gamma = \pi\lambda\Delta f k^2$. Its average is

$$
\langle\sin^2\gamma\rangle = \frac{1}{2}\left[1 - \cos\!\left(2\pi\lambda\Delta f_\mathrm{c}k^2\right)\frac{\sin X}{X}\right], \qquad X = 2\pi\lambda\delta k^2 .
$$

The cosine describes the Thon rings of the central defocus, and the factor $\sin X/X$ is their contrast. It falls from 1 at low spatial frequency to 0 at $X = \pi$ and remains below 22% beyond. The phase difference between the centre and the edges of the strip is $\pi\lambda\delta k^2 = X/2$, so that $X = \pi$ is the spatial frequency at which this difference reaches $\pi/2$. It follows that $k^2 = 1/(2\lambda\delta)$, and with $\delta = (w/2)\tan\alpha$ the resolution $d = 1/k$ is the one of eq. {eq}`eq:ctf-strip`.
```

In practice, the defocus is estimated for every tilt from strips parallel to the tilt axis, or from the whole image with a model of the defocus gradient, and the CTF is corrected locally. In a thick specimen, the defocus of an object also depends on its height within the specimen, which a simple correction of a defocus gradient ignores. A three-dimensional CTF correction takes this into account and is critical for high-resolution subtomogram averaging.

````{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. Tilt the specimen and compare the Thon rings of the whole image with those of a strip. Then change the width of the strip and see up to which resolution one CTF describes it.

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults ($60°$, $\Delta f_0 = 3$ µm, strip of 200 nm).** The defocus runs from 2.1 µm to 3.9 µm across the field but only from 2.8 µm to 3.2 µm in the strip. In the power spectrum of the whole image, fewer than two dark rings are visible before the rings vanish. 
2. **Set the tilt angle to $0°$.** The defocus is constant, both power spectra are identical, and the rings reach the Nyquist frequency. A single CTF is then valid for the whole image.
3. **Return to $60°$ and reduce the strip to 100 nm and then to 50 nm.** The limit falls to 5.8 Å and to 4.1 Å, which is beyond the Nyquist frequency, so that the rings reach the edge of the power spectrum. The power spectrum becomes grainier, because the strip contains fewer pixels from which the defocus can be estimated. This is the compromise for the width of the strips. The alternative is to just assume a uniform defocus gradient across the micrograph.
```
````

```{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 gaussian_filter
from ipywidgets import IntSlider, FloatSlider, VBox, HBox, Image as ImageWidget
from IPython.display import display

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

_LAM_ct = 0.01969                                    # electron wavelength at 300 kV (Å)
_FOV_ct = 1000.0                                     # width of the field of view perpendicular to the tilt axis (nm)
_PIX_ct = 3.0                                        # pixel size (Å)
_KN_ct = 1/(2*_PIX_ct)                               # Nyquist frequency (1/Å)
_NG_ct = 256
_kk_ct = np.linspace(-_KN_ct, _KN_ct, _NG_ct)
_KR_ct = np.hypot(*np.meshgrid(_kk_ct, _kk_ct))      # spatial frequency of every pixel of the power spectrum
_E_ct = gaussian_filter(np.random.default_rng(11).exponential(1.0, (_NG_ct, _NG_ct)), 0.6)
_E_ct = (_E_ct - _E_ct.mean())/_E_ct.std()           # fixed speckle pattern with zero mean and unit variance
_TILE_ct = (128*_PIX_ct/10)**2                       # area of a 128 x 128 pixel tile (nm²)

def _ps_ct(df0, delta, area):
    """Model power spectrum of an image region whose defocus spans df0 ± delta (Å): the rings of the average of
    sin²(pi lambda df k²) over the defocus range, on a flat background, with speckle that falls with the area (nm²)."""
    ring = 0.5*(1 - np.cos(2*np.pi*_LAM_ct*df0*_KR_ct**2)*np.sinc(2*_LAM_ct*delta*_KR_ct**2))
    return (1 + ring)*(1 + _E_ct/np.sqrt(max(area/_TILE_ct, 1.0)))

def _show_ps_ct(ax, P, title, d_lim):
    ax.imshow(P, cmap='gray', vmin=0.6, vmax=2.2, extent=[-_KN_ct, _KN_ct, -_KN_ct, _KN_ct],
              origin='lower', interpolation='bicubic')
    if d_lim > 1/_KN_ct:
        ax.add_patch(plt.Circle((0, 0), 1/d_lim, fill=False, ec=CRIMSON, lw=1.6, ls='--'))
        ax.set_title(f'{title}\nrings vanish beyond {d_lim:.1f} Å (dashed)', fontsize=9.5)
    else:
        ax.set_title(f'{title}\nrings reach the Nyquist frequency', fontsize=9.5)
    ax.set_xticks([-0.1, 0, 0.1]); ax.set_yticks([-0.1, 0, 0.1]); ax.tick_params(labelsize=8)
    ax.set_xlabel('spatial frequency (1/Å)', fontsize=9)

def draw_ct(tilt=60, df0=3.0, w=200):
    t = np.tan(np.radians(tilt))
    half = _FOV_ct/2000.0                                              # half of the field of view (µm)
    f = lambda x: df0 + x*t                                            # defocus at the position x (µm), eq. for Δf(x')
    d_strip = np.sqrt(_LAM_ct*(w*10.0)*t) if t > 0 else 0.0            # resolution at which the rings of the strip vanish (Å); no limit without tilt
    d_whole = np.sqrt(_LAM_ct*(_FOV_ct*10.0)*t) if t > 0 else 0.0

    fig, axes = plt.subplots(1, 4, figsize=(13, 3.9), gridspec_kw={'width_ratios': [1.35, 1, 1, 1.25]})
    ax = axes[0]
    pad = 0.5*max(t, 0.3) + 0.6
    ax.set_xlim(-1.15, 1.15); ax.set_ylim(df0 + pad, df0 - pad); ax.set_aspect('equal')
    for xb in np.arange(-half, half + 1e-9, w/1000.0):                 # boundaries of the strips
        if (2*half)/(w/1000.0) <= 50:
            ax.plot([xb, xb], [f(xb) - 0.05, f(xb) + 0.05], color=GREY, lw=1)
    ax.plot([-half, half], [f(-half), f(half)], color=BLUE, lw=3, solid_capstyle='butt')
    xs = max(-half, -w/2000.0), min(half, w/2000.0)
    ax.plot(xs, [f(xs[0]), f(xs[1])], color=CRIMSON, lw=6, solid_capstyle='butt')
    ax.plot([-half, half], [df0, df0], color='k', lw=0.8, ls=':')
    ax.plot(0, df0, 'o', ms=10, mfc='white', mec='k', zorder=5); ax.plot(0, df0, '.', color='k', zorder=6)
    ax.text(0.04, df0 - 0.04, 'tilt axis', fontsize=8.5, va='bottom')
    for xe, ha in ((-half, 'right'), (half, 'left')):
        ax.text(xe + (-0.04 if ha == 'right' else 0.04), f(xe), f'{f(xe):.1f} µm', fontsize=9, ha=ha, va='center')
    for xa in (-0.35, 0, 0.35):
        ax.annotate('', xy=(xa, df0 - pad + 0.3), xytext=(xa, df0 - pad + 0.04), arrowprops=dict(arrowstyle='-|>', color=GREY, lw=1.5))
    ax.text(0.5, df0 - pad + 0.17, 'electron beam', fontsize=8.5, color='#777777', va='center')
    ax.set_xlabel('distance from the tilt axis (µm)', fontsize=8.5)
    ax.set_ylabel('defocus Δf (µm)', fontsize=9.5)
    ax.tick_params(labelsize=8)
    ax.spines[['top', 'right']].set_visible(False)
    ax.set_title(f'Tilted specimen, α = {tilt}°\nred: strip of {w} nm', fontsize=9.5)

    _show_ps_ct(axes[1], _ps_ct(df0*1e4, 0.5*_FOV_ct*10*t, _FOV_ct*1000.0), f'Whole image ({_FOV_ct:.0f} nm)', d_whole)
    _show_ps_ct(axes[2], _ps_ct(df0*1e4, 0.5*w*10*t, w*1000.0), f'Strip of {w} nm', d_strip)

    ax = axes[3]
    wk = np.logspace(np.log10(20), np.log10(_FOV_ct), 100)
    for a in (30, 45, 60, 70):
        ax.plot(wk, np.sqrt(_LAM_ct*wk*10*np.tan(np.radians(a))), color=GREY, lw=1.3)
        ax.text(_FOV_ct*1.04, np.sqrt(_LAM_ct*_FOV_ct*10*np.tan(np.radians(a))), f'{a}°', fontsize=8.5, color='#777777', va='center')
    if tilt > 0:
        ax.plot(wk, np.sqrt(_LAM_ct*wk*10*t), color=CRIMSON, lw=2.6)
        ax.plot([w], [d_strip], 'o', color=CRIMSON, ms=8, zorder=5)
        left = w > 100                                                  # put the label where there is room
        high = d_strip > 20
        ax.annotate(f'{w} nm: {d_strip:.1f} Å', (w, d_strip), xytext=((-10, -18) if high else (-8, 12)) if left else (10, -16), textcoords='offset points',
                    fontsize=9, color=CRIMSON, ha='right' if left else 'left')
    else:
        ax.text(0.5, 0.62, 'no defocus gradient\nwithout tilt: no limit', transform=ax.transAxes, fontsize=9.5, color=CRIMSON, ha='center')
    ax.axhspan(0, 1/_KN_ct, color=GREY, alpha=0.25, lw=0)
    ax.text(21, 0.25, 'beyond the Nyquist frequency', fontsize=8.5, color='#777777', va='bottom')
    ax.axvline(_FOV_ct, color='k', lw=0.8, ls=':')
    ax.set_xscale('log'); ax.set_xlim(20, _FOV_ct*1.0); ax.set_ylim(0, 25)
    ax.set_xticks([20, 50, 100, 200, 500, 1000]); ax.set_xticklabels(['20', '50', '100', '200', '500', '1000']); ax.minorticks_off()
    ax.set_xlabel('strip width w (nm)', fontsize=9.5); ax.set_ylabel('limit d (Å)', fontsize=9.5)
    ax.tick_params(labelsize=8); ax.grid(alpha=0.25)
    ax.spines[['top']].set_visible(False)
    ax.set_title('$d = \\sqrt{\\lambda\\, w \\tan\\alpha}$', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_ct = {'description_width': '170px'}
tilt_ct = IntSlider(value=60, min=0, max=70, step=5, description='Tilt angle α (°)', style=_style_ct, layout={'width': '400px'})
df_ct = FloatSlider(value=3.0, min=1.0, max=6.0, step=0.5, description='Defocus at the tilt axis (µm)', style=_style_ct, layout={'width': '400px'}, readout_format='.1f')
w_ct = IntSlider(value=200, min=20, max=1000, step=10, description='Strip width w (nm)', style=_style_ct, layout={'width': '400px'})
out_ct = ImageWidget(format='png', layout={'max_width': '100%'})
def update_ct(_=None):
    out_ct.value = draw_ct(tilt_ct.value, df_ct.value, w_ct.value)
for _w_ct in (tilt_ct, df_ct, w_ct):
    _w_ct.observe(update_ct, names='value')
display(VBox([VBox([tilt_ct, df_ct, w_ct]), out_ct]))
update_ct()
```

(sec:tomo-iterative)=
### Reconstruction methods

We have already introduced the WBP as the most widely used reconstruction method. It is the standard in most tomography software, because it is fast and linear and has no number of iterations to choose. Despite its popularity it also comes with limitations, some of which have been discussed.

Other, more sophisticated approaches will be treated in a future version of this book. Iterative methods, such as the algebraic reconstruction technique (ART) and the simultaneous iterative reconstruction technique (SIRT), refine an estimate until its projections agree with the measured images. Methods such as compressed sensing and deep learning use additional assumptions about the object, or knowledge that a network has learned from data, to reduce noise and artefacts.

(sec:tomo-sta)=
## Subtomogram averaging

Electron tomography preserves the three-dimensional context of molecules in their native environment, but individual protein molecules in a tomogram are typically so small and the signal-to-noise ratio is so low that a single tomogram cannot reveal atomic detail. Subtomogram averaging (STA) combines the contextual information of tomography with the averaging power of single-particle analysis. STA workflows typically include the following essential steps:

1. **Template matching/picking.** Particle positions are manualy or automatically picked, sometimes aided by geometric constraints such as the description of a membrane, or a reference volume is cross-correlated with the tomogram in three dimensions to locate all candidate positions and orientations of a given complex.
2. **Subtomogram extraction.** Three-dimensional boxes (subtomograms or subvolumes) are extracted around the detected positions.
3. **Alignment and averaging.** The subtomograms are aligned to each other and to the reference by three-dimensional cross-correlation and averaged. As in single-particle analysis, the signal-to-noise ratio of the average increases in proportion to the number of copies ({numref}`sec:cryo-em-noise`). 
4. **Classification.** Three-dimensional classification sorts the subtomograms by conformation or composition and reveals structural heterogeneity.

The averaging over many different copies that can also (partially) compensates the missing wedge. In the tomogram, every copy has the same missing wedge in the frame of the microscope. Because the copies have different orientations, the wedge points in a different direction in the frame of each copy. The copies therefore measure complementary regions of Fourier space, and the average has a much smaller missing wedge than any single copy. The same consideration applies to the alignment. A single subtomogram lacks the information in its wedge, whereas a reference that is calculated from many copies does not. The two should be compared like with like, and hence the the same missing wedge must be applied to the reference before the comparison.

````{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. Average copies that are seen through a missing wedge in a noisy reconstruction, and compare random orientations with identical ones.

```{admonition} Things to try
:class: dropdown
1. **Keep the defaults.** The average shows the duck, and the Fourier panel shows how the wedges of the rotated copies fill each other's gaps. Set the number of copies to 1 to see a single copy.
2. **Increase the number of copies.** The average should become increasingly better.
3. **Switch to identical orientations.** The wedge is now the same for all copies and affects the average, as the Fourier panel shows. The duck is smeared along the beam direction.
```
````

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

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

# Test object: the rubber duck of the CryoEM doeboek practicals, 40 x 40 pixels
_DUCK_sta = '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'
_d_sta = np.frombuffer(zlib.decompress(base64.b64decode(_DUCK_sta)), dtype=np.uint8).reshape(128, 128).astype(float)[::-1, :] / 255
_com_sta = center_of_mass(_d_sta)
_d_sta = nd_shift(_d_sta, (63.5 - _com_sta[0], 63.5 - _com_sta[1]), order=1)
_duck_sta = zoom(_d_sta, 40/128, order=1); _duck_sta = _duck_sta/_duck_sta.max()

# Every copy is reconstructed from its own simulated tilt series (the noise model of the filtered backprojection above)
_NB_sta, _L_sta, _NC_sta = 56, 80, 32                  # box that is shown, canvas of the reconstruction (wider than the diagonal of the box), number of copies
_C_sta = (_L_sta - 1)/2
_o_sta = (_L_sta - _NB_sta)//2                         # the box is the centre of the canvas
_rng_sta = np.random.default_rng(4)
_phi_sta = _rng_sta.uniform(0, 360, _NC_sta)           # random orientations of the copies (°)
_ang_sta = np.arange(-90, 91, 2)                       # tilt angles in steps of 2°
_z_sta = np.random.default_rng(6).standard_normal((_NC_sta, len(_ang_sta), _L_sta))   # one fixed noise pattern per copy, scaled by the dose
_PIXA2_sta = 3.9**2                                    # area of a pixel (Å²)
_KAPPA_sta = 0.03                                      # contrast per unit of projected density (lower than in the filtered backprojection above, so that a single copy is noisy)
_nu_sta = np.fft.rfftfreq(2*_L_sta)
_filt_sta = _nu_sta*0.5*(1 + np.cos(2*np.pi*_nu_sta))  # ramp filter with the Hann window
_YY_sta, _XX_sta = (np.mgrid[0:_L_sta, 0:_L_sta] - _C_sta).astype(float)
_sino_sta, _rec_sta = {}, {}

def _canvas_sta(same):
    """The copies on canvases of 80 x 80 pixels, in random orientations or all in the same orientation."""
    base = np.pad(_duck_sta, (_L_sta - 40)//2)
    return np.array([base if same else nd_rotate(base, p, reshape=False, order=1) for p in _phi_sta])

def _fbp_sta(sino, angles):
    """Filtered backprojection of a stack of sinograms (copies x angles x detector pixels) with the Hann window."""
    pad = _L_sta//2
    f = np.fft.irfft(np.fft.rfft(np.pad(sino, ((0, 0), (0, 0), (pad, pad))), axis=2)*_filt_sta, n=2*_L_sta, axis=2)[:, :, pad:pad + _L_sta]
    rec = np.zeros((sino.shape[0], _L_sta, _L_sta))
    for k, a in enumerate(np.deg2rad(angles)):
        px = (_XX_sta*np.cos(a) - _YY_sta*np.sin(a) + _C_sta).clip(0, _L_sta - 1)      # y points down, z = -y
        lo = px.astype(int); hi = np.minimum(lo + 1, _L_sta - 1); fr = px - lo
        rec += f[:, k, :][:, lo]*(1 - fr) + f[:, k, :][:, hi]*fr
    return rec*np.radians(2)                                                              # times the angular step

def _reconstruct_sta(same, max_tilt, dose):
    """Reconstruction of all copies. The reconstruction is linear in the tilt series, so that the noise-free part and the
    noise (for a dose of 1 e⁻/Å²) are reconstructed once, and the dose only scales the noise."""
    key = (same, max_tilt)
    if key not in _rec_sta:
        if same not in _sino_sta:                                                          # the noise-free tilt series, computed once
            cv = _canvas_sta(same)
            _sino_sta[same] = np.array([nd_rotate(cv, -a, axes=(2, 1), reshape=False, order=1).sum(axis=1) for a in _ang_sta]).transpose(1, 0, 2)
        sel = np.abs(_ang_sta) <= max_tilt; m = int(sel.sum())
        sino = _sino_sta[same][:, sel]
        unit = np.sqrt(1 + _KAPPA_sta*sino)*_z_sta[:, sel]*np.sqrt(m/_PIXA2_sta)/_KAPPA_sta   # shot noise for a total dose of 1 e⁻/Å²
        _rec_sta.clear()
        _rec_sta[key] = (_fbp_sta(sino, _ang_sta[sel]), _fbp_sta(unit, _ang_sta[sel]))
    clean, unit = _rec_sta[key]
    return clean + unit/np.sqrt(dose)

_k_sta = np.fft.fftfreq(_NB_sta)
_KX_sta, _KZ_sta = np.meshgrid(_k_sta, _k_sta)
_ANG_sta = np.degrees(np.arctan2(np.abs(_KZ_sta), np.abs(_KX_sta)))                        # angle of a frequency from the k_x axis, 0 ... 90
_true_sta = np.pad(_duck_sta, (_NB_sta - 40)//2)
_true_show_sta = zoom(_d_sta, 120/128, order=1); _true_show_sta = np.pad(_true_show_sta/_true_show_sta.max(), 24)   # the same object at 3 x the resolution, for display only
_WIN_sta = dict(cmap='gray', vmin=-0.5, vmax=1.1, interpolation='bicubic')                 # one fixed window, so that the noise levels can be compared

def _corr_sta(im):
    return np.corrcoef(im.ravel(), _true_sta.ravel())[0, 1]

def draw_sta(n=16, max_tilt=60, dose=60.0, kind='random orientations'):
    same = kind == 'all identical'
    rec = _reconstruct_sta(same, max_tilt, dose)[:n]
    phis = np.zeros(n) if same else _phi_sta[:n]
    crop = lambda im: im[_o_sta:_o_sta + _NB_sta, _o_sta:_o_sta + _NB_sta]
    aligned = [im if same else nd_rotate(im, -p, reshape=False, order=1) for im, p in zip(rec, phis)]  # rotated back by the known orientation
    avg = crop(np.mean(aligned, axis=0))
    mask = np.fft.fftshift((_ANG_sta <= max_tilt).astype(float))                           # the double wedge of the tilt series in the frame of the tomogram
    cov = np.mean([mask if same else nd_rotate(mask, -p, reshape=False, order=1) for p in phis], axis=0)
    lab = f'{n} copies' if n > 1 else '1 copy'

    fig, axes = plt.subplots(1, 4, figsize=(12.5, 3.6))
    axes[0].imshow(crop(rec[0]), **_WIN_sta); axes[0].axis('off')
    axes[0].set_title(f'Individual subvolume\n(orientation {phis[0] % 360:.0f}°)', fontsize=9.5)
    axes[1].imshow(cov, cmap='magma', vmin=0, vmax=1, extent=[-0.5, 0.5, -0.5, 0.5], interpolation='nearest')
    axes[1].set_xlabel('$k_x$ (1/pixel)', fontsize=9); axes[1].set_ylabel('$k_z$ (1/pixel)', fontsize=9); axes[1].tick_params(labelsize=8)
    axes[1].set_title('Fourier space', fontsize=9.5)
    axes[2].imshow(avg, **_WIN_sta); axes[2].axis('off')
    axes[2].set_title(f'Average of {lab}', fontsize=9.5)
    axes[3].imshow(_true_show_sta, **_WIN_sta); axes[3].axis('off'); axes[3].set_title('True object', fontsize=9.5)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=150); buf.seek(0)
    plt.close(fig); return buf.getvalue()

_style_sta = {'description_width': '130px'}
n_sta = IntSlider(value=16, min=1, max=32, step=1, description='Number of copies', style=_style_sta, layout={'width': '380px'})
t_sta = IntSlider(value=60, min=30, max=90, step=5, description='Max tilt (°)', style=_style_sta, layout={'width': '380px'})
s_sta = FloatLogSlider(value=60.0, base=10, min=1, max=3.5, step=0.05, description='Total dose (e⁻/Å²)', style=_style_sta, layout={'width': '380px'}, readout_format='.0f')
k_sta = Dropdown(options=['random orientations', 'all identical'], value='random orientations', description='Orientations', style=_style_sta, layout={'width': '300px'})
out_sta = ImageWidget(format='png', layout={'max_width': '100%'})
def update_sta(_=None):
    out_sta.value = draw_sta(n_sta.value, t_sta.value, s_sta.value, k_sta.value)
for _w_sta in (n_sta, t_sta, s_sta, k_sta):
    _w_sta.observe(update_sta, names='value')
display(VBox([HBox([VBox([n_sta, t_sta]), VBox([s_sta, k_sta])]), out_sta]))
update_sta()
```

For large, abundant complexes, subtomogram averaging can reaches near-atomic resolution. The advantage over single-particle analysis is that the positions and orientations of the averaged copies are known in their cellular context, so that the arrangement of molecular machines can be mapped directly *in situ*.


```{admonition} Practical
:class: seealso
Tilt series, backprojection, the missing wedge and subtomogram averaging are explored in Python in the corresponding practical of the CryoEM doeboek: [CryoEM doeboek: electron tomography](https://cryotud.github.io/cryoem-doeboek/tomo/)
```