10. Image Formation and Phase Contrast#

This chapter describes how a thin biological specimen produces contrast in the TEM. Starting from the projection of the specimen potential and the weak phase object approximation, it is shown how defocus of the objective lens converts the phase shifts of the electron wave into intensity contrast. This leads to the contrast transfer function (CTF), which describes how each spatial frequency of the specimen is transferred into the image, and to the phase plate, which modifies it. The description uses the Fourier transform and the convolution theorem, which are summarised in Section 9.

A thin, vitrified biological specimen is almost transparent to the electron beam. Most electrons traverse it without being scattered, or are scattered only through small angles. The amplitude (scattering) contrast, which arises from electrons that are removed from the beam by an objective aperture, is therefore very low. Nevertheless, cryo-EM images reveal individual macromolecules. We first relate the three-dimensional specimen to the two-dimensional image by the projection approximation. We then describe the effect of the specimen on the electron wave, which is a small phase shift, and show that this phase shift produces no contrast in a perfectly focused image. Finally, we derive how defocus of the objective lens converts the phase shift into intensity contrast, which leads to the contrast transfer function (CTF) and the corrections required for the images obtained.

10.1. The projection approximation#

The specimen is a three-dimensional distribution of electrostatic potential \(V(x,y,z)\), whereas the TEM records a two-dimensional image. For sufficiently thin specimens, the relation between the two is a projection along the beam direction \(z\), in the same way as a radiograph is a projection of the absorption of the body. At the high energies used in cryo-EM, the electrons travel almost parallel to the optical axis, and the deflection by individual atoms is very small, of the order of milliradians. An electron that enters the specimen at the lateral position \((x,y)\) therefore leaves it at practically the same position, and all information that it acquires on its way is a sum over the potential along this line. The exit wave, and thus the image, depends on the projected potential

(10.1)#\[ V_\mathrm{p}(x,y) = \int V(x,y,z)\,\mathrm{d}z \]

in which features at different heights \(z\) overlap and the information on their position along the beam is integrated out (Fig. 10.1). This is the reason why a single TEM image does not contain the three-dimensional structure of the object. This is also immediately clear if considering that a volume of \(N \times N \times N\) voxels has \(N^3\) unknown density values, whereas a single projection image of that volume provides only \(N^2\) pixels. Images from many different directions are therefore required to determine all unknowns. How the projection depends on the orientation of the object is described in Section 9.5.

Schematic of the projection of a specimen along the beam, for an untilted and a tilted specimen.

Fig. 10.1 Projection of a specimen along the beam, shown for a two-dimensional slice. (a) The detector records the sum of the density along each beam path, so that features at similar positions but at different heights overlap in the projection and appear as a single peak. (b) After tilting the specimen, the same features project to different positions and can be distinguished. A three-dimensional object is projected in the same way onto a two-dimensional image.#

The above approximation holds if diffraction within the specimen can be neglected, that is, if the curvature of the Ewald sphere is irrelevant over the thickness \(t\) of the specimen. For a structural feature of spacing \(d\), the diffracted beam is retarded relative to the direct beam by \(\pi\lambda t/d^2\) over the thickness of the specimen (this retardation is derived in the next sections). The projection approximation therefore requires \(t \ll d^2/2\lambda\). Equivalently, the defocus is no longer the same for features at the top and at the bottom of a thick specimen. For \(d = 3\) Å and 300 keV electrons (\(\lambda = 0.0197\) Å), this is about 23 nm, so that the approximation becomes increasingly restrictive towards high resolution and for thick specimens.

The projection concept is central to the methods discussed in the following chapters. A single image of a particle in a given orientation provides one projection of its structure. The three-dimensional structure is accessed by recording projections from many different directions, either from many copies of a molecule in random orientations in single-particle analysis (Section 11), or from a single specimen that is tilted in the microscope in electron tomography (Section 12). The mathematical relation between projections and the three-dimensional object is the projection-slice theorem (Section 9.5).

10.2. The weak phase object approximation#

An electron that passes through a region of positive electrostatic potential gains kinetic energy, so that its wavelength is locally shorter. After leaving the specimen it has accumulated a phase advance relative to an electron that traversed vacuum or ice, in the same way as a light wave is retarded in a transparent medium of higher refractive index. The amplitude of the wave is hardly affected. A specimen that modulates mainly the phase of the incident wave is called a phase object. In the projection approximation, the phase shift \(\phi(\mathbf{r})\) at position \(\mathbf{r}=(x,y)\) is proportional to the projected potential, the electrostatic potential \(V\) integrated along the beam direction \(z\) [eq. (10.1)]:

(10.2)#\[ \phi(\mathbf{r}) = \sigma\, V_\mathrm{p}(\mathbf{r}) = \sigma\,\int V(x,y,z)\,\mathrm{d}z \]

The interaction constant \(\sigma\) depends only on the electron energy \(E\),

\[ \sigma = \frac{2\pi}{\lambda E}\,\frac{E_0 + E}{2E_0 + E}, \]

where \(E_0 = m_0c^2\) = 511 keV is the electron rest energy. It has the values \(\sigma\) = 0.86, 0.73 and 0.65 mrad V⁻¹ Å⁻¹ at 120, 200 and 300 keV, respectively. These are phase shifts per volt of potential and per ångström of path, that is a potential of 1 V acting over 1 Å shifts the phase by 0.65 mrad at 300 keV. The interaction constant should not be confused with the scattering cross section introduced in Section 5.1.4. Both originate from the Coulomb interaction between the electron and the potential of the atoms, and both decrease with increasing electron energy. The cross section, however, gives the probability that an electron is scattered, which is proportional to the square of the scattered amplitude, whereas \(\sigma\) relates the phase of the coherent wave linearly to the potential. The weak phase object approximation described below therefore requires that scattering is rare, which means that the specimen thickness is much smaller than the mean free path (Section 5.1.6). The contrast is determined by the difference between the potential of the macromolecule and that of its surroundings. The mean inner potential (i.e. the spatial average of the electrostatic potential) of vitreous ice is about 5 V and that of protein about 7–8 V. For a protein of 10 nm thickness embedded in ice, the phase shift at 200 keV is therefore approximately

\[ \phi \approx 0.73\times10^{-3}\ \mathrm{rad\,V^{-1}\,\mathring{\mathrm{A}}^{-1}} \times 2.5\ \mathrm{V} \times 100\ \text{Å} \approx 0.2\ \mathrm{rad}, \]

whereas a single light atom shifts the phase by less than a milliradian. These phase shifts are small, \(|\phi| \ll 1\) rad, so that the exit wave \(\psi(\mathbf{r}) = e^{i\phi(\mathbf{r})}\) can be approximated by the first two terms of its series expansion, \(1 + i\phi - \phi^2/2 + \dots\), because the neglected terms are smaller by factors of order \(\phi\):

(10.3)#\[ \psi(\mathbf{r}) = e^{i\phi(\mathbf{r})} \approx 1 + i\phi(\mathbf{r}) \]

This is the weak phase object (WPO) approximation, which is valid for thin specimens of light atoms (typically a thickness below about 50 nm). The first term represents the unscattered wave, which is unchanged. The second term represents a weak scattered wave, and the factor \(i\) indicates that it is shifted by 90° with respect to the unscattered wave.

A detector records the intensity, the squared magnitude of the wave. In the complex plane, the unscattered wave is a vector of length 1 and the scattered wave is a short vector perpendicular to it, which for small phase shifts changes the length of the sum only in second order: \(|1 + i\phi(\mathbf{r})|^2 = 1 + \phi(\mathbf{r})^2 \approx 1\). The intensity is therefore uniform, and a pure phase object produces no contrast in a perfectly focused image. The information on the specimen is contained in the phase of the wave but is not recorded by the detector. For the conversion of phase into intensity, the phase relation between the scattered and the unscattered wave has to be changed.

10.3. Origin of phase contrast: wave propagation behind the specimen#

Directly behind the specimen, the scattered wave has a phase relation of 90° to the unscattered wave. This relation changes on propagation, because the scattered wave travels at a small angle to the optical axis, so that its wavefronts are spaced slightly further apart along the axis than those of the unscattered wave and its phase accumulates more slowly. When the relative phase has changed by a further 90°, the scattered wave is in phase (or in antiphase) with the unscattered wave, and the two interfere constructively (or destructively), as illustrated by the phasors in Fig. 10.3. The phase shift is thereby converted into an intensity variation. The unscattered wave serves as a reference wave against which the scattered wave is compared, as in holography, so that a TEM image can be regarded as an in-line hologram of the specimen.

Phasor diagrams of the unscattered and scattered waves for four distances behind the specimen.

Fig. 10.3 Phasor picture of phase contrast, in the complex plane with the real part on the horizontal and the imaginary part on the vertical axis. The unscattered wave (blue) is a long vector along the real axis, to which the weak scattered wave (orange) is added; the intensity is the squared length of the resulting vector (dashed). Directly behind the specimen (\(\gamma = 0\)), the scattered wave is perpendicular to the unscattered wave, and the length of the sum is unchanged to first order. With increasing distance, the scattered wave rotates by the retardation \(\gamma = \pi\lambda z/d^2\). At \(\gamma = \pi/2\) it points along the unscattered wave and the intensity increases, at \(\gamma = \pi\) it is perpendicular again, and at \(\gamma = 3\pi/2\) it points against the unscattered wave and the intensity decreases. The phase amplitude is exaggerated for clarity.#

To make this quantitative, we consider the simplest specimen represented by a phase grating that varies sinusoidally with small amplitude \(\varepsilon\) and period \(d\):

(10.4)#\[ \phi(x) = \varepsilon \cos\!\left(\frac{2\pi x}{d}\right) \]

As we have seen for the Fourier decomposition in Section 9, any projected potential can be written as a sum of such gratings with different periods, orientations and amplitudes, and for small phase shifts the contributions of the individual gratings add linearly. Writing the cosine as a sum of two complex exponentials, the exit wave becomes

\[ \psi(x,0) \approx 1 + \frac{i\varepsilon}{2}\left(e^{2\pi i x/d} + e^{-2\pi i x/d}\right). \]

The grating splits the incident wave into three plane waves: the undiffracted beam and two diffracted beams with amplitude \(\varepsilon/2\) and a phase advance of 90°, which propagate at angles \(\pm\theta\) with \(\sin\theta = \lambda/d\). For \(d = 10\) Å and 200 keV electrons (\(\lambda = 0.025\) Å), \(\theta\) is only 2.5 mrad. Directly behind the specimen, the three waves add up to a uniform intensity, and there is no contrast. Along the optical axis, the wavefronts of the obliquely travelling diffracted beams are spaced by \(\lambda/\cos\theta\) and thus further apart than those of the direct beam. At a distance \(z\), they have accumulated less phase, which means that their phase is retarded by \(kz(1-\cos\theta) \approx \pi\lambda z/d^2\), where \(k = 2\pi/\lambda\). This alters the interference of the three waves, and the grating pattern appears in the intensity (Fig. 10.4). We describe it by the contrast \(\Delta I = |\psi|^2 - 1\), the deviation of the intensity from the value 1 of the incident wave, which is normalised to unit amplitude.

Geometry of the waves behind a phase grating and the resulting contrast as a function of the distance from the specimen.

Fig. 10.4 Waves behind a weak phase grating. Left: the grating splits the incident plane wave into an undiffracted beam and two diffracted beams at angles \(\pm\theta\) with \(\sin\theta = \lambda/d\). At a distance \(z\), the diffracted beams have accumulated less phase along the optical axis than the undiffracted beam, so that their phase is retarded by \(\gamma = \pi\lambda z/d^2\). Right: the resulting contrast \(\Delta I(x) = 2\phi(x)\sin\gamma\) at a maximum of the phase profile, for \(d = 10\) Å, 200 keV electrons and a phase amplitude of 0.2 rad. The contrast vanishes at the specimen, is maximal at \(z = d^2/2\lambda\) and vanishes again at \(z = d^2/\lambda\).#

At distance \(z\), the contrast \(\Delta I(x) = 2\phi(x)\sin(\pi\lambda z/d^2)\) is thus the phase pattern \(\phi(x)\) multiplied by \(2\sin(\pi\lambda z/d^2)\). The contrast is zero at \(z = 0\), reaches a maximum when the path difference is a quarter of a wavelength (a 90° change of the relative phase), vanishes again when \(\lambda z/d^2\) is an integer, and alternates between positive and negative maxima in between. The distance of maximum contrast depends on the period \(d\), so that different spatial frequencies require different distances. For \(d = 10\) Å at 200 keV, the first maximum is at \(z = d^2/2\lambda = 2000\) Å, corresponding to 80,000 wavelengths. This large distance is a consequence of the small diffraction angles, which cause the path difference to accumulate slowly. Finer detail requires a shorter distance, since \(z \propto d^2\). For \(d = 7\) Å the maximum is at \(z \approx 0.1\ \mu\)m.

The following simulation calculates the wave behind the grating numerically for a given period \(d\) and phase amplitude \(\varepsilon\) and compares the result with the weak phase prediction above.

Interactive element

Click the rocket symbol at the top of the page and select Live Code, or expand the Show code toggle and click ▶ to run the cell. Panel A shows the Fresnel carpet \(|\psi(x,z)|^2\) directly behind the grating, which is drawn above it on the same \(x\) scale. The thickness of the grating is proportional to the phase \(\phi(x)\) (scale bar: 1 rad), so that its modulation follows the slider \(\varepsilon\), and the pattern can be compared with the maxima of the phase profile. Panel B shows the contrast \(\Delta I = |\psi|^2 - 1\) at the grating centre together with the WPO sinusoidal prediction. At the small default phase amplitude \(\varepsilon\) the two agree closely. Increase \(\varepsilon\) and the grating also produces higher diffraction orders (\(\pm2\), \(\pm3\), …), which superimpose faster oscillations on the sinusoidal WPO prediction. This is a sign that the WPO breaks down.

Hide code cell source

import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from ipywidgets import FloatSlider, Dropdown, VBox, HBox, Image as ImageWidget
from IPython.display import display

def _sim_cp(d_nm, kV=200, eps=0.15, nx=512, dx_nm=0.1, nlines=201, dz_nm=10.0,
         width_nm=51.2, pad=8):
    V = kV * 1e3
    m0, ec, c, h = 9.109e-31, 1.602e-19, 2.998e8, 6.626e-34
    lam_nm = h / np.sqrt(2*m0*ec*V*(1+ec*V/(2*m0*c**2))) * 1e9
    x = (np.arange(nx) - (nx-1)/2) * dx_nm
    psi0 = np.ones(nx, dtype=complex)
    inside = np.abs(x) <= width_nm/2
    psi0[inside] = np.exp(1j * eps * np.cos(2*np.pi*x[inside]/d_nm))
    nfft = pad * nx; start = (nfft - nx) // 2
    padded = np.zeros(nfft, dtype=complex)
    padded[start:start+nx] = psi0 - 1.0
    spec = np.fft.fft(padded)
    k = 2*np.pi / lam_nm
    kx = 2*np.pi * np.fft.fftfreq(nfft, d=dx_nm)
    kz = np.sqrt(np.maximum(0.0, k**2 - kx**2))
    z_nm = np.arange(nlines, dtype=float) * dz_nm
    transfer = np.exp(1j * (kz[None,:] - k) * z_nm[:,None])
    prop = np.fft.ifft(spec[None,:] * transfer, axis=1)[:,start:start+nx]
    return np.abs(1.0 + prop)**2, x, z_nm, lam_nm

def draw(d_A, eps, kV):
    d_nm = d_A / 10
    image, x, z_nm, lam_nm = _sim_cp(d_nm, kV=kV, eps=eps)
    # the grating is simulated over a width of 51 nm, so that the edges do not reach the centre; the carpet shows the central part
    sl = slice(len(x)//4, 3*len(x)//4)
    z_max_nm  = d_nm**2 / (2*lam_nm)
    z_zero_nm = d_nm**2 / lam_nm
    clip = np.percentile(np.abs(image[:, sl] - 1.0), 99)

    fig = plt.figure(figsize=(13, 5.9))
    gs = fig.add_gridspec(2, 2, height_ratios=[0.3, 1], hspace=0.05)
    ax0 = fig.add_subplot(gs[0, 0]); ax1 = fig.add_subplot(gs[1, 0], sharex=ax0); ax2 = fig.add_subplot(gs[:, 1])

    # Panel A — Fresnel carpet
    ax1.imshow(image[:, sl], cmap='gray', origin='upper', aspect='auto',
               vmin=1-clip, vmax=1+clip, interpolation='nearest',
               extent=[x[sl][0]*10, x[sl][-1]*10, z_nm[-1]/1000, 0])
    if z_max_nm < z_nm[-1]:
        ax1.axhline(z_max_nm/1000,  color='cyan',   lw=1.5, ls='--',
                    label=f'first max  {z_max_nm:.0f} nm')
    if z_zero_nm < z_nm[-1]:
        ax1.axhline(z_zero_nm/1000, color='orange', lw=1.5, ls=':',
                    label=f'first zero  {z_zero_nm:.0f} nm')
    ax1.set_xlabel('x (Å)', fontsize=10)
    ax1.set_ylabel('z (μm)  [compressed ~50×]', fontsize=9)
    ax1.set_title('')
    # the phase grating above the carpet, on the same x scale: the thickness is proportional to the phase, with the
    # scale 1 rad per unit of the vertical axis, so that the modulation grows with ε (the mean thickness is fixed)
    xg = x[sl]*10
    ax0.fill_between(xg, 1.6 + eps*np.cos(2*np.pi*x[sl]/d_nm), 0, color='#b3b3b3', lw=0)
    ax0.set_ylim(0, 3.2); ax0.axis('off')
    ax0.text(-0.01, 0.3, 'grating', transform=ax0.transAxes, ha='right', va='center', fontsize=9)
    ax0.plot([xg[-1] + 0.012*(xg[-1]-xg[0])]*2, [1.6 - 0.5, 1.6 + 0.5], color='k', lw=1.2, clip_on=False)
    ax0.text(xg[-1] + 0.024*(xg[-1]-xg[0]), 1.6, '1 rad', ha='left', va='center', fontsize=8.5)
    ax0.set_xlim(xg[0], xg[-1])                                   # the scale bar must not widen the shared x axis
    ax0.set_title(f'(A) |ψ(x,z)|²   d={d_A:.1f} Å, {kV} keV,  ε={eps:.2f} rad', fontsize=10, fontweight='bold')
    ax1.legend(fontsize=9, loc='lower right')

    # Panel B — ΔI vs z at grating centre, with WPO prediction
    cx = np.argmin(np.abs(x))
    x0 = x[cx]
    phi0 = eps * np.cos(2*np.pi*x0/d_nm)
    z_th = np.linspace(0, z_nm[-1], 600)
    wpo = 2 * phi0 * np.sin(np.pi * lam_nm * z_th / d_nm**2)

    ax2.plot(z_nm/1000, image[:, cx] - 1, color='steelblue', lw=1.8,
             label=f'simulation  x={x0*10:.1f} Å')
    ax2.plot(z_th/1000, wpo, color='tomato', lw=1.5, ls='--',
             label=f'WPO: 2φ(x)·sin(πλz/d²)  [φ={phi0:.2f} rad]')
    ax2.axhline(0, color='k', lw=0.5)
    if z_max_nm < z_nm[-1]:
        ax2.axvline(z_max_nm/1000,  color='cyan',   lw=1.2, ls='--', alpha=0.7)
    if z_zero_nm < z_nm[-1]:
        ax2.axvline(z_zero_nm/1000, color='orange', lw=1.2, ls=':',  alpha=0.7)
    ax2.set_xlabel('z (μm)', fontsize=10)
    ax2.set_ylabel('ΔI = |ψ|² − 1', fontsize=10)
    ax2.set_title('(B) Contrast at grating centre', fontsize=10, fontweight='bold')
    ax2.legend(fontsize=9)

    fig.subplots_adjust(left=0.075, right=0.985, top=0.9, bottom=0.1, wspace=0.22)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=130); buf.seek(0); plt.close(fig)
    return buf.getvalue()

style = {'description_width': '100px'}
d_sl  = FloatSlider(value=10, min=4, max=20, step=0.5,
                    description='Period d (Å)', style=style, layout={'width': '340px'})
eps_sl = FloatSlider(value=0.15, min=0.05, max=1.5, step=0.05,
                     description='ε (rad)', style=style, layout={'width': '300px'})
kv_dd = Dropdown(options=[120, 200, 300], value=200, description='Voltage (keV)',
                 style=style, layout={'width': '220px'})

out_cp = ImageWidget(format='png', layout={'width': '1000px', 'max_width': '100%', 'height': 'auto'})
def update_cp(_=None):
    out_cp.value = draw(d_sl.value, eps_sl.value, kv_dd.value)
for w in [d_sl, eps_sl, kv_dd]:
    w.observe(update_cp, names='value')
display(VBox([HBox([d_sl, eps_sl, kv_dd]), out_cp]))
update_cp()

In the microscope, the specimen is not placed exactly in the object plane of the objective lens, the plane that the lens images sharply, but at a distance \(\Delta_f\) from it, which is set by the excitation of the lens. The image is the intensity of the wave in the object plane. Because the scattered and the unscattered wave leave the specimen at different angles, their phase difference depends on this distance, as in the previous section. We measure the propagation distance \(z\) along the beam from the exit surface of the specimen, so that the object plane lies at \(z = -\Delta_f\). For underfocus (\(\Delta_f > 0\), i.e. weakened lens), the object plane lies above the specimen, which corresponds to a negative propagation distance, so that the contrast of the grating becomes

\[ \Delta I(x) = |\psi|^2 - 1 = -2\phi(x)\,\sin\!\left(\frac{\pi\lambda\,\Delta_f}{d^2}\right). \]

The factor that multiplies \(2\phi\) is the contrast transfer function of the grating. With the spatial frequency \(k = 1/d\),

(10.5)#\[ \mathrm{CTF}(k) = -\sin\!\left(\pi\lambda\,\Delta_f\, k^2\right). \]

The argument of the sine, \(\gamma(k) = \pi\lambda\Delta_f k^2\), is the phase by which the scattered wave is rotated relative to the unscattered wave in the object plane, in addition to the 90° that it has directly behind the specimen. For \(k = 1/d\), it is the phase shift \(\pi\lambda z/d^2\) of the previous section evaluated at \(z = -\Delta_f\), but with the opposite sign: free propagation over \(z > 0\) retards the scattered wave, whereas an object plane at \(z = -\Delta_f\) rotates it in the other sense. This is the origin of the minus sign in eq. (10.5). What the object plane contains differs for the two signs of the defocus.

For overfocus (\(\Delta_f < 0\)), the object plane lies below the specimen. The wave there is the real wave of the previous simulation, and the image is its Fresnel pattern at the distance \(|\Delta_f|\). The scattered wave is retarded by \(|\gamma|\), and the CTF is positive at low spatial frequencies.

For underfocus (\(\Delta_f > 0\)), the object plane lies above the specimen, where the electrons have not yet been scattered. The image is nevertheless the intensity of the exit wave extrapolated backwards to this plane. We call this the virtual wave (dotted lines in the simulation below), because no electrons are actually scattered there. The formula for \(\Delta I\) therefore continues to negative \(z\), and the CTF is negative at low spatial frequencies.

Underfocus is used in practice because it makes the CTF negative at low spatial frequencies, such that regions of higher potential appear darker than their surroundings. This is the same polarity as the contrast produced by electrons that are removed from the beam at large scattering angles (amplitude contrast, see below), so that the two contributions reinforce each other.

10.4. The Contrast Transfer Function#

The CTF of eq. (10.5) takes a value between -1 and +1 for every spatial frequency \(k\) and gives the efficiency with which a component of the projected phase at that spatial frequency is transferred into the image. A value of ±1 corresponds to maximum contrast, with a negative sign meaning that regions of high potential appear dark and a positive sign that they appear bright (contrast reversal). At the zeros of the CTF, the spatial frequency is not transferred and the information is absent from the image. The microscope thus acts as a frequency filter that transmits some spatial frequencies, inverts the contrast of others and suppresses a few.

The following simulation shows how the value of the CTF arises for a single spatial frequency \(k = 1/d\). Such a component of the specimen acts as the phase grating of the previous section. The unscattered wave is the central beam, and the scattered wave is formed by the two beams that the grating diffracts to the angles \(\pm\theta\) with \(\sin\theta = \lambda k\) (Fig. 10.4). At the maximum of the phase profile, they add up to the scattered wave of the phasor diagram (Fig. 10.3). Relative to the unscattered wave, the scattered wave is rotated by the phase shift \(\gamma = \pi\lambda\Delta_f k^2\) in addition to its 90°. This is the phase shift of the diffracted beams calculated above for \(d = 1/k\), evaluated at \(z = -\Delta_f\). The phase shift is negative there, so that for underfocus the scattered wave rotates in the opposite sense to that in Fig. 10.3, and for overfocus in the same sense.

Interactive element

Click the rocket symbol at the top of the page and select Live Code, or expand the Show code toggle and click ▶ to run the cell. The sliders set the defocus and the spatial frequency of one component of the specimen (for an ideal lens with \(C_s = 0\) and an exaggerated phase amplitude). The upper left panel shows this component as a phase grating with the period \(d = 1/k\) (grey, drawn to scale in \(x\), so that a larger \(k\) gives a finer grating; note that \(x\) is in Å and \(z\) in μm), the contrast that it produces below the grating, and the virtual wave above the grating (lighter). The dashed line is the object plane of the lens at the distance \(\Delta_f\) from the grating. The contrast along this line is the contrast of the image. The unscattered wave and the two beams of the scattered wave leave the grating in their true directions, and are continued as dotted lines above the grating. In the upper right panel, the scattered wave is added to the unscattered wave in the complex plane, and the resultant wave determines the intensity. The lower panel shows the CTF of eq. (10.5) for the chosen defocus, and the black dot is its value at the chosen \(k\). In the upper right panel, the black dot on the real axis is the real part of the resultant wave, and its distance from the dotted line is the contrast.

Hide code cell source

import io
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
from ipywidgets import FloatSlider, VBox, HBox, Image as ImageWidget
from IPython.display import display

BLUE, ORANGE, CRIMSON, GREY = '#25aae1', '#fcb040', '#d91b5c', '#b3b3b3'
_LAM_ph = 0.0197                          # electron wavelength at 300 keV (Å); ideal lens, C_s = 0
_PHI_AMP_ph = 0.5                         # phase amplitude of the specimen component (exaggerated for clarity)

def draw_phasor(df_um, k):
    gamma = np.pi * _LAM_ph * df_um * 1e4 * k**2                  # phase shift of the ideal CTF, in rad
    scat = _PHI_AMP_ph * np.exp(1j*(np.pi/2 + gamma))             # scattered wave: 90° ahead, rotated by gamma
    tip = 1 + scat
    ctf = -np.sin(gamma)

    fig = plt.figure(figsize=(10, 9.6))
    gs = fig.add_gridspec(2, 2, height_ratios=[1.3, 0.9])
    ag = fig.add_subplot(gs[0, 0]); ax = fig.add_subplot(gs[0, 1]); bx = fig.add_subplot(gs[1, :])

    # upper left: the grating with the period d = 1/k, the waves and the carpet of its weak phase contrast (x drawn to scale)
    zmax = 5.0                                                          # μm
    xmax = 50.0                                                         # half width of the displayed region (Å)
    z = np.linspace(-zmax, zmax, 1800)
    xr = np.linspace(-xmax, xmax, 1500)                                 # x in Å: a larger k gives a finer grating
    carpet = 2*_PHI_AMP_ph * np.cos(2*np.pi*k*xr)[None, :] * np.sin(np.pi*_LAM_ph*k**2*z*1e4)[:, None]
    ag.imshow(carpet, extent=[-xmax, xmax, zmax, -zmax], cmap='gray', vmin=-1, vmax=1, aspect='auto')
    ag.axhspan(-zmax, 0, facecolor='white', alpha=0.35, lw=0)           # above the grating: no wave field, the formula is only continued
    ag.fill_between(xr, 0, -(0.3 + 0.25*np.cos(2*np.pi*k*xr)), color=GREY, lw=0)           # the grating (thickness ~ phase)
    ag.text(-0.975*xmax, -0.65, 'grating', fontsize=9, va='bottom', ha='left', color='k', bbox=dict(fc='white', ec='none', alpha=0.7, pad=1))
    ag.plot([0, 0], [0, zmax], color=BLUE, lw=2)                        # unscattered wave
    ag.plot([0, 0], [0, -zmax], color=BLUE, lw=1.2, ls=':')
    slope = _LAM_ph * k * 1e4                                           # lateral displacement of the beams per μm (Å), tan θ ≈ λk
    z_end = min(zmax, 0.975*xmax/max(slope, 1e-9))
    for sgn in (-1, 1):                                                 # scattered wave: the two beams at ±θ
        ag.plot([0, sgn*slope*z_end], [0, z_end], color=ORANGE, lw=1.8)
        ag.plot([0, -sgn*slope*z_end], [0, -z_end], color=ORANGE, lw=1.2, ls=':')
    ag.axhline(-df_um, color=CRIMSON, ls='--', lw=1.4)                  # object plane of the lens: above the grating for underfocus
    kind = 'underfocus' if df_um > 0 else 'overfocus' if df_um < 0 else 'in focus'
    ag.text(0.975*xmax, -df_um - 0.15, f'object plane at z = −Δ$_f$ ({kind})', fontsize=9, ha='right', va='bottom', color=CRIMSON, bbox=dict(fc='white', ec='none', alpha=0.7, pad=1))
    ag.text(-0.05*xmax, 4.75, 'unscattered wave', color=BLUE, fontsize=9, va='bottom', ha='right', bbox=dict(fc='white', ec='none', alpha=0.7, pad=1))
    ag.text(0.05*xmax, 4.75, 'scattered wave', color=ORANGE, fontsize=9, va='bottom', ha='left', bbox=dict(fc='white', ec='none', alpha=0.7, pad=1))
    ag.set_xlim(-xmax, xmax); ag.set_ylim(zmax, -zmax)
    ag.set_xticks([-50, -25, 0, 25, 50]); ag.set_xlabel('x (Å)', fontsize=9); ag.set_ylabel('z (μm)', fontsize=9)
    ag.set_title(f'Grating (d = 1/k = {1/max(k, 1e-6):.1f} Å) and the contrast above and below it', fontsize=9.5)
    ag.text(-0.975*xmax, -4.85, '↓ electron beam', fontsize=8.5, ha='left', va='top', bbox=dict(fc='white', ec='none', alpha=0.7, pad=1))
    ag.text(1.03, 0.75, 'above the specimen: underfocus', transform=ag.transAxes, rotation=90, ha='left', va='center', fontsize=8.5, color=CRIMSON)
    ag.text(1.03, 0.25, 'below the specimen: overfocus', transform=ag.transAxes, rotation=90, ha='left', va='center', fontsize=8.5, color=CRIMSON)

    # middle: complex plane
    ax.set_xlim(-0.2, 1.8); ax.set_ylim(-0.75, 0.75); ax.set_aspect('equal')
    for sp in ax.spines.values():
        sp.set_visible(False)
    ax.axhline(0, color=GREY, lw=0.8); ax.axvline(0, color=GREY, lw=0.8)
    ax.plot([1, 1], [-0.7, 0.7], color='k', ls=':', lw=0.8)                       # intensity without scattered wave
    ax.add_patch(FancyArrowPatch((0, 0), (1, 0), arrowstyle='-|>', mutation_scale=12, lw=2.2, color=BLUE))
    ax.add_patch(FancyArrowPatch((1, 0), (tip.real, tip.imag), arrowstyle='-|>', mutation_scale=12, lw=2.2, color=ORANGE))
    ax.add_patch(FancyArrowPatch((0, 0), (tip.real, tip.imag), arrowstyle='-|>', mutation_scale=10, lw=1.4, color=CRIMSON, ls='--'))
    ax.plot([tip.real, tip.real], [tip.imag, 0], color=GREY, ls=':', lw=1)
    ax.plot([tip.real], [0], 'o', color='k', ms=5)
    ax.set_xticks([0, 1]); ax.set_yticks([]); ax.tick_params(length=0, labelsize=9)
    ax.set_xlabel('real part', fontsize=9); ax.set_ylabel('imaginary part', fontsize=9)
    ax.text(0.5, -0.45, 'unscattered wave', color=BLUE, ha='center', fontsize=9)
    ax.text(0.5, -0.58, 'scattered wave', color=ORANGE, ha='center', fontsize=9)
    ax.text(0.5, -0.71, 'resultant wave', color=CRIMSON, ha='center', fontsize=9)
    ax.set_title(f'Waves at k = {k:.3f} Å⁻¹ (d = {1/max(k, 1e-6):.1f} Å)', fontsize=9.5)

    # right: CTF of an ideal lens
    kk = np.linspace(0, 0.3, 4000)
    bx.plot(kk, -np.sin(np.pi*_LAM_ph*df_um*1e4*kk**2), color=CRIMSON, lw=2)
    bx.axhline(0, color='k', lw=0.6)
    bx.axvline(k, color='k', ls=':', lw=0.8)
    bx.plot([k], [ctf], 'o', color='k', ms=6, zorder=5)
    bx.set_xlim(0, 0.3); bx.set_ylim(-1.15, 1.15)
    bx.set_xlabel('Spatial frequency k (Å⁻¹)', fontsize=10); bx.set_ylabel('CTF(k)', fontsize=10)
    bx.set_title(f'CTF = −sin γ,  γ = πλΔ$_f$ k² = {gamma/np.pi:.2f} π,  CTF = {ctf:+.2f}', fontsize=9.5)
    for side in ('top', 'right'):
        bx.spines[side].set_visible(False)
    top = bx.twiny(); top.set_xlim(bx.get_xlim()); tks = [0.05, 0.10, 0.20, 0.30]
    top.set_xticks(tks); top.set_xticklabels([f'{1/t:.0f}' for t in tks], fontsize=8); top.set_xlabel('Resolution (Å)', fontsize=9)
    fig.tight_layout(h_pad=3.0)
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=130); buf.seek(0); plt.close(fig)
    return buf.getvalue()

style = {'description_width': '150px'}
sl = {'layout': {'width': '380px'}}
df_ph = FloatSlider(value=1.5, min=-5.0, max=5.0, step=0.1, description='Defocus Δf (μm, + = under)', style=style, **sl)
k_ph  = FloatSlider(value=0.04, min=0.0, max=0.3, step=0.005, description='Spatial frequency k (Å⁻¹)', style=style, readout_format='.3f', **sl)

out_ph = ImageWidget(format='png', layout={'width': '760px', 'max_width': '100%', 'height': 'auto'})
def update_ph(_=None):
    out_ph.value = draw_phasor(df_ph.value, k_ph.value)
for w in [df_ph, k_ph]:
    w.observe(update_ph, names='value')
display(VBox([HBox([df_ph, k_ph]), out_ph]))
update_ph()

A general specimen is a sum of many gratings, each transferred with its own factor \(\mathrm{CTF}(k)\). In Fourier space, the image contrast is therefore the product of the Fourier transform of the projected phase and the CTF (a hat denotes the Fourier transform, see Section 9):

(10.6)#\[ \Delta\hat{I}(\mathbf{k}) \approx 2\,\mathrm{CTF}(\mathbf{k})\,\hat{\phi}(\mathbf{k}) \]

In real space, this product corresponds to a convolution of the phase object with the point spread function of the microscope, whose Fourier transform is the CTF (see Section 9.4). A central task of cryo-EM image processing is to correct for this filtering.

The detector records the square of the wave, which is a nonlinear operation, and it is therefore not self-evident that the image contrast is proportional to the phase of the specimen. For a weak scatterer the intensity contains a term that is linear in the scattered wave, which arises from its interference with the unscattered wave, and a term that is quadratic in the scattered wave and can be neglected. Owing to this linearity, each spatial frequency can be treated independently, and a single transfer function describes the whole image.

A further consequence concerns the phase of the Fourier coefficients. The Fourier transform of the projected potential is the structure factor, in analogy to X-ray crystallography. In a diffraction experiment, only the intensity of the diffracted waves is recorded, and the phases of the structure factors are lost (this is the phase problem in X-ray crystallogrpahy). In an image, the diffracted waves interfere with the unscattered reference wave, so that the Fourier transform of the image, \(\mathrm{CTF}\cdot\hat{\phi}\) in (10.6), is complex-valued and retains both the amplitudes and the phases of the structure factors, up to the known influence of the CTF. A cryo-EM image thus provides the phases directly, which is a decisive advantage for the reconstruction of three-dimensional maps.

So far, we have assumed an ideal objective lens. Real magnetic lenses refract rays at large angles more strongly than rays close to the axis. This spherical aberration (see Section 2.1.2.1), quantified by the coefficient \(C_s\) (about 2–3 mm in modern cryo-EMs), is equivalent to a reduction of the defocus for waves scattered to high angles and adds a second term to the argument of the sine. Both terms are combined in the phase shift \(\gamma(k)\), also called the wave aberration function:

(10.7)#\[ \gamma(k) = \pi \lambda \Delta_f k^2 - \frac{\pi}{2} C_s \lambda^3 k^4 \]

The defocus term increases as \(k^2\) and dominates at low and intermediate spatial frequencies. The \(C_s\) term increases as \(k^4\) and is therefore only relevant at high resolution (from about 3–5 Å for \(C_s \approx 2\)–\(3\) mm). With these two terms, the CTF of a pure phase object is \(-\sin\gamma(k)\). As before, \(\Delta_f > 0\) denotes underfocus, the convention used in most cryo-EM software.

The exit wave in (10.3) is the leading term of a more complete description. The structural information of interest is carried by the elastically scattered electrons, which are described by the phase shift above. In specimens made of light atoms, however, inelastic scattering is several times more frequent than elastic scattering (see Section 5.1.4). Inelastically scattered electrons have lost energy, so that they are focused differently by the objective lens, and they contribute mainly a diffuse background and radiation damage to the specimen. They are partially removed from the image by the objective aperture and, in microscopes equipped with an energy filter, by an energy-selecting slit. The loss of electrons from the coherent image gives rise to a weak amplitude modulation \(\mu(\mathbf{r}) \ll 1\), which scales with the specimen thickness divided by the mean free path (Section 5.1.6):

(10.8)#\[ \psi(\mathbf{r}) \approx 1 - \mu(\mathbf{r}) + i\phi(\mathbf{r}) \]

The amplitude part \(-\mu\) is in phase with the unscattered wave and therefore generates contrast without defocus. The two scattered contributions are transferred differently, the phase part with \(\sin\gamma\) and the amplitude part with \(\cos\gamma\). Their relative strength is described by the amplitude contrast ratio \(A\), which is typically 7–10% for biological specimens (\(A = \mu/\sqrt{\mu^2+\phi^2}\) if both have the same spatial dependence). As a consequence, the CTF does not vanish at zero spatial frequency and is \(\mathrm{CTF}(0) = -A\). A constant \(A\) is an approximation. The part of the amplitude contrast that arises from inelastic scattering is expected to be confined to low spatial frequencies, because an inelastic event is delocalised over about 1 nm around the atom. Since \(A\) is small to begin with, this is of limited practical importance. For the same reason, an energy filter brings only a modest gain for thin specimens (below about 50 nm) at 300 keV and is most valubale for thicker specimen.

The resolution of a real image is limited irrespective of the defocus. The transfer decays at high spatial frequencies because the illumination is not perfectly coherent and because of other blurring effects. This is described by an envelope function that multiplies the CTF:

(10.9)#\[ E(k) = \exp\!\left(-\frac{B k^2}{4}\right) \]

The B-factor (in Ų) combines all contributions that lead to frequency-dependent blurring. The most important is spatial incoherence due the finite size of the electron source, which causes electrons to arrive at slightly different angles \(\alpha_\mathrm{s}\), and each of them projects the specimen pattern with a lateral shift of about \(\Delta_f \cdot \alpha_\mathrm{s}\). For \(\Delta_f = 1\ \mu\)m and an angular spread of \(10^{-3}\) rad (typical for a thermionic source), the shift is 1 nm, which averages out a 1 nm periodicity completely. The small, bright source of a field emission gun (FEG) reduces the angular spread to \(10^{-5}\)–\(10^{-6}\) rad, which makes it possible to use large defocus values at high resolution. Further contributions are temporal incoherence (the energy spread of the electrons and instabilities of the lens current, which cause a spread of the focus), specimen charging, specimen movement during the exposure, and the the detector, whose modulation transfer function falls off with spatial frequency because the signal of each electron is spread over neighbouring pixels. For good cryo-EM data, \(B\) is typically 50–100 Ų. At \(B = 100\) Ų, a 5 Å feature is attenuated to \(1/e\) of its amplitude, and finer features are attenuated more strongly. The envelope hence sets the information limit of the image. Combining all contributions, and using \(\sqrt{1-A^2}\,\sin\gamma + A\cos\gamma = \sin(\gamma + \Delta\varphi)\) with \(\Delta\varphi = \arcsin A\), the contrast transfer function of a weak specimen is

(10.10)#\[\begin{split} \begin{aligned} \text{CTF}(k) &= -\sin\!\left[\gamma(k) + \Delta\varphi\right] \cdot E(k) \\ &= -\sin\!\left[\pi\lambda\Delta_f k^2 - \frac{\pi}{2} C_s \lambda^3 k^4 + \Delta\varphi\right] \cdot \exp\!\left(-\frac{B k^2}{4}\right) \end{aligned} \end{split}\]

The additional phase shift \(\Delta\varphi\) is 4–6° for the amplitude contrast of 7–10% and is increased to about 90° by a phase plate (see below). For \(\Delta\varphi = 0\), \(C_s = 0\) and \(B = 0\), this reduces to the ideal CTF of eq. (10.5). The term “phase” is used with three different meanings in this context. The phase \(\phi(\mathbf{r})\) of the electron wave behind the specimen, which carries the information on the specimen; the phase shifts \(\gamma(k)\) and \(\Delta\varphi\) introduced by the microscope (including the phase plate, see below), where “phase contrast” denotes the conversion of the former into intensity by means of the latter; and the phase of a Fourier coefficient of the recorded image. The last meaning is relevant for “phase flipping” in CTF correction, where the Fourier coefficients are multiplied by -1 wherever the CTF is negative, which changes their phase by \(\pi\) .

Key insight: defocus and contrast

At exact focus (\(\Delta_f = 0\)), the CTF is weak and nearly constant for biological specimens, so that there is almost no contrast. Underfocus causes the CTF to oscillate which causes some frequency bands to be transferred with negative contrast, others with positive contrast (contrast reversal), and the transfer vanishes at the CTF zeros. Cryo-EM data processing therefore includes a CTF correction step, in which the CTF of each image is determined and corrected before the information from many images is combined.

The choice of the defocus is a compromise. A larger defocus shifts the first maximum of the CTF to lower spatial frequency, so that large features of the particle (its overall shape, which is important for particle picking and alignment) obtain more contrast. At the same time, the CTF oscillates faster and the envelope attenuates the high-resolution oscillations more strongly. Typical cryo-EM data are recorded at 0.5–3 \(\mu\)m underfocus, often with a range of defocus values within one dataset, so that the zeros fall at different frequencies in different images and the information that is lost in one image is recovered from another. For given \(C_s\) and \(\lambda\) there is a special defocus (the Scherzer defocus, \(\Delta_f \approx 1.2\sqrt{C_s\lambda}\), roughly 85 nm for \(C_s = 2\) mm at 200 keV) at which the \(C_s\) term compensates the defocus term, so that the CTF stays close to its maximum over a wide band of frequencies. This is useful in materials science but provides insufficient low-frequency contrast for biological specimens.

The interactive figure below shows how the CTF of eq. (10.10) depends on defocus, spherical aberration, amplitude contrast, envelope and accelerating voltage. The amplitude contrast ratio \(A\) enters as the phase shift \(\Delta\varphi = \arcsin A\). The red dashed lines show the envelope \(\pm E(k)\) that limits the transfer at high spatial frequency, and the orange dotted line marks the first zero of the CTF. The right panel shows the projection of a weak phase object, imaged with the current CTF.

Interactive element

Click the rocket symbol at the top of the page and select Live Code, or expand the Show code toggle and click ▶ to run the cell. The defocus slider shifts the CTF zeros: a higher defocus gives more low-frequency contrast but faster oscillations. Increasing the \(B\)-factor reduces the transfer at high spatial frequency, \(C_s = 0\) isolates the defocus term, and setting the amplitude contrast to zero removes the offset \(\mathrm{CTF}(0) = -A\). The accelerating voltage can be varied.

Hide code cell source

import io, zlib, base64
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from ipywidgets import FloatSlider, Dropdown, VBox, HBox, Image as ImageWidget
from IPython.display import display

def _lam_A_exp(kV=300):
    V = kV * 1e3
    m0, ec, c, h = 9.109e-31, 1.602e-19, 2.998e8, 6.626e-34
    return h / np.sqrt(2*m0*ec*V*(1+ec*V/(2*m0*c**2))) * 1e10

def _ctf_exp(k, df_um, Cs_mm, B=0, A=0.07, kV=300):
    lam = _lam_A_exp(kV)
    df = df_um * 1e4; Cs = Cs_mm * 1e7
    gamma = np.pi*lam*df*k**2 - 0.5*np.pi*Cs*lam**3*k**4
    return -np.sin(gamma + np.arcsin(A)) * np.exp(-B*k**2/4)       # additional phase shift: arcsin(A)

_k_exp = np.linspace(0.0, 0.50, 2500)

# Test specimen: the rubber duck of the CryoEM doeboek practicals (128 x 128, 8 bit, compressed),
# with an internal texture that represents density variations inside a molecule
_DUCK_128_exp = 'eNrtWmtMm+cVrm8YsB2T2CEQLiYQCMVdIBDiBApJKCWKabNgN2lCEy6FGoxtHNsk2GAbAwZjG2yM77c0XZZsWVW1W6tNW7dqVSutWrtJW9utnaZ1WlW1TXrR1EvSpp32fp/v5jP+TEx++fmD+OPnfM8573nPOe+5554MMsgggwwyyCCDDBIDkwh3hxuLw+GRgMNhN9YGmBtPIOaQyGRKPMhkUg6RgN8wG4LcueQ8ekFxKWM1SosL6Hnk3KAN6ScPcBeW7mTW729uaWmNRUtL8/565s7SwoANaTUhQE6lQdwNTW1sbndPX19/LPr6erq57LamBsgGGjVgQto+PYdC215eU9/U1sk9MyiQKZRq9VQs1GqlQiYYPMPtbGuqrynfTqPkpEMEwI4nkqj5pdUNrUcBt1A2oZkzmJYtFstKNMD/yybDnGZCJgQ2HG1tqC7Np5KI+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cPGoFJOA3b0yw/7IDq9gGVyRlTAsb4XwHKA6/TpBpor6alWX74BBY3dolmLW4fcvw/KtauuL0uy6yoq7GYjE/3dhIGS9xS2dot08XWoNHnHxTUbqtO1t1auYWITft2FCjbtzHb++SGmNF/VP4zOdxu0H70tTO3kfDpX86CaqCiOjZPuWiPnj+E8/+K0+22gf6PXVdEIWA3YDkMeABU7sf5SkPM60vw/gPsrmD/SyViN2Y3DXQuFQeO8+TQ60f0uoLPC+BxWnRylP3/ukMgl16xjw3tSwSWRaJWglw2aAeCva+CnovfsO1ALD6Xxqhr7xapdGZoEhSE2+WwmnQqUXd7HQPd/OcOFrWoRczWrgHJ5Kwe7o8t8E6YfnZSMtDVyiyiZuOxG7ocCe0LVTa2c3r5UnmgP1arlXIpv5fT3lgZW+ltkAQE0pZiaE+OczrQH/f19ZzmQG1k8RYSAbvh26lQAU2mbd9Rs4cV6I9bWpoD7cyqQnOj9lOBBblUWqQ/Li0ugHYh8di7spsb2hMN98eBnVjc3WIPm4CL3Qm+5y7jbu9EZ5BBBhlkkEEGGWSQKv4PPkrrzg=='
_duck_exp = np.frombuffer(zlib.decompress(base64.b64decode(_DUCK_128_exp)),
                      dtype=np.uint8).reshape(128, 128).astype(float)[::-1, :] / 255
_tex_exp = gaussian_filter(np.random.default_rng(2).standard_normal((128, 128)), 1.6)
_tex_exp = (_tex_exp - _tex_exp.min()) / (_tex_exp.max() - _tex_exp.min())

_N_exp, _PIX_exp = 256, 2.0                                  # image size (px), pixel size (Å)
_img_exp = np.zeros((_N_exp, _N_exp)); _o_exp = (_N_exp - 128) // 2
_img_exp[_o_exp:_o_exp+128, _o_exp:_o_exp+128] = _duck_exp * (0.5 + 0.5*_tex_exp)
_F_exp = np.fft.fft2(_img_exp)
_fx_exp = np.fft.fftfreq(_N_exp, d=_PIX_exp)
_K2D_exp = np.hypot(*np.meshgrid(_fx_exp, _fx_exp))

def draw_ctf(df_um, Cs_mm, B, A, kV):
    ctf = _ctf_exp(_k_exp, df_um, Cs_mm, B, A, kV)
    env = np.exp(-B * _k_exp**2 / 4)
    flips = np.where(np.diff(np.sign(ctf)) != 0)[0]
    k_zero = _k_exp[flips[0]] if len(flips) else np.nan

    fig = plt.figure(figsize=(13, 4.2))
    gs = fig.add_gridspec(1, 2, width_ratios=[2.2, 1])
    ax = fig.add_subplot(gs[0, 0]); bx = fig.add_subplot(gs[0, 1])
    ax.plot(_k_exp, ctf, color='#2c7bb6', linewidth=2, label='CTF(k)')
    ax.plot(_k_exp,  env, color='#d62728', linewidth=1.5, linestyle='--', label='envelope')
    ax.plot(_k_exp, -env, color='#d62728', linewidth=1.5, linestyle='--')
    ax.axhline(0, color='k', linewidth=0.6)
    if np.isfinite(k_zero):
        ax.axvline(k_zero, color='orange', lw=1.2, ls=':',
                   label=f'1st zero ≈ {1/k_zero:.1f} Å')
    ax.set_xlabel('Spatial frequency k (Å⁻¹)', fontsize=10)
    ax.set_ylabel('CTF(k)', fontsize=10)
    ax.set_title(f'Δf={df_um:.1f} μm, Cs={Cs_mm:.1f} mm, B={B:.0f} Ų, '
                 f'A={A:.2f}, {kV:.0f} kV', fontsize=10)
    ax.set_ylim(-1.3, 1.5); ax.set_xlim(0, 0.5)
    ax.legend(fontsize=9, loc='upper right')
    ax_top = ax.twiny(); ax_top.set_xlim(ax.get_xlim())
    tks = [0.05, 0.10, 0.20, 0.33]
    ax_top.set_xticks(tks); ax_top.set_xticklabels([f'{1/t:.0f}' for t in tks], fontsize=8)
    ax_top.set_xlabel('Resolution (Å)', fontsize=9)

    # the duck (a weak phase object) as it is imaged with this CTF
    img = np.real(np.fft.ifft2(_ctf_exp(_K2D_exp, df_um, Cs_mm, B, A, kV)*_F_exp))
    bx.imshow(img, cmap='gray', vmin=-0.5, vmax=0.5); bx.axis('off')
    bx.set_title('Duck imaged with this CTF', fontsize=10)

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

style = {'description_width': '110px'}
sl = {'layout': {'width': '320px'}}
df_sl = FloatSlider(value=1.5, min=0.2, max=5.0, step=0.1,  description='Defocus (μm)',  style=style, **sl)
Cs_sl = FloatSlider(value=2.7, min=0.0, max=4.0, step=0.1,  description='Cs (mm)',       style=style, **sl)
B_sl  = FloatSlider(value=80,  min=0,   max=400, step=10,   description='B-factor (Ų)', style=style, **sl)
A_sl  = FloatSlider(value=0.07, min=0.0, max=0.3, step=0.01, description='Amp. contrast A', style=style, **sl)
kV_dd = Dropdown(options=[120, 200, 300], value=300, description='Voltage (kV)',
                 style=style, layout={'width': '260px'})

out_ctf = ImageWidget(format='png', layout={'width': '900px', 'max_width': '100%', 'height': 'auto'})
def update_ctf(_=None):
    out_ctf.value = draw_ctf(df_sl.value, Cs_sl.value, B_sl.value, A_sl.value, kV_dd.value)
for w in [df_sl, Cs_sl, B_sl, A_sl, kV_dd]:
    w.observe(update_ctf, names='value')
display(VBox([HBox([VBox([df_sl, Cs_sl]), VBox([B_sl, A_sl, kV_dd])]), out_ctf]))
update_ctf()

The CTF also has a consequence in real space. Its Fourier transform is the point spread function of the image formation, which is spatially extended. A spatial frequency \(k\) is displaced laterally by about \(\lambda\Delta_f\, k\), the derivative of \(\gamma/2\pi\) with respect to \(k\), so that the signal of a fine feature appears at a different position than the feature itself (signal delocalisation). At \(\Delta_f = 1\ \mu\)m and 300 keV, information at a resolution of 3 Å is displaced by about 6.6 nm. The displacement equals the size of the feature at \(d \approx \sqrt{\lambda\Delta_f}\), which is about 14 Å for these values. The delocalisation increases with the defocus and is a further reason why large defocus values are not used for high-resolution imaging.

In the power spectrum of a recorded micrograph (the squared magnitude of its Fourier transform, see Section 9), the squared CTF appears as concentric Thon rings. Their positions are used to determine the defocus and the astigmatism (Section 10.5) of every image, which is the first step of CTF estimation in any cryo-EM processing workflow. The subsequent CTF correction (see the preprocessing step of the single-particle workflow in Section 11.6.1) restores the signal in the bands where the CTF is negative and weights the frequencies by their reliability. Phase plates (Section 10.6) provide a different solution to the problem of low-frequency contrast.

Because the image contrast is the product of the CTF and the Fourier transform of the specimen (eq. (10.6)), the specimen could in principle be recovered by dividing the Fourier transform of the image by the estimated CTF. This is not done directly, because noise is strongly amplified where the CTF is close to zero, and the division is undefined at the zeros themselves. Two strategies are used instead. In phase flipping, the Fourier coefficients are multiplied by the sign of the estimated CTF. This restores the correct sign of the contrast in every frequency band but leaves the amplitudes weighted by \(|\mathrm{CTF}|\). A Wiener filter,

(10.11)#\[ \hat{f}_\mathrm{corrected}(\mathbf{k}) = \frac{\mathrm{CTF}(\mathbf{k})\,\hat{I}(\mathbf{k})}{\mathrm{CTF}(\mathbf{k})^2 + 1/\mathrm{SNR}(\mathbf{k})}, \]

additionally corrects the amplitudes where the CTF is large, while the term 1/SNR, with the signal-to-noise ratio of the data, prevents the amplification of noise where the CTF is small. Neither method recovers the information that is lost at the zeros of a single image. That information is contributed by images that were recorded at other defocus values, which is why the images of a dataset are combined with weights that depend on their CTFs.

The demonstration below applies both corrections to a test specimen, which is the duck with an internal texture. The observed image is the specimen filtered by the CTF, with added noise. The right panel shows the transfer of the observed image before and after the correction. Phase flipping makes all bands positive but leaves the CTF zeros and the weights |CTF|. The Wiener filter restores the amplitudes smoothly and approaches zero transfer where the CTF is small. Increasing the noise shows why the parameter 1/SNR has to be adapted to the noise level.

Interactive element

Click the rocket symbol at the top of the page and select Live Code, or expand the Show code toggle and click ▶ to run the cell. The sliders set the defocus and the noise. The dropdown selects the correction method, and the last slider sets the Wiener parameter \(1/\mathrm{SNR}\). The number in the title of the corrected image is its correlation with the true image.

Hide code cell source

import io, zlib, base64
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from ipywidgets import FloatSlider, FloatLogSlider, Dropdown, VBox, HBox, Image as ImageWidget
from IPython.display import display

# Test specimen: the rubber duck of the CryoEM doeboek practicals (128 x 128, 8 bit, compressed),
# with an internal texture that represents density variations inside a molecule
_DUCK_128_corr = 'eNrtWmtMm+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
                      dtype=np.uint8).reshape(128, 128).astype(float)[::-1, :] / 255
_tex_corr = gaussian_filter(np.random.default_rng(2).standard_normal((128, 128)), 1.6)
_tex_corr = (_tex_corr - _tex_corr.min()) / (_tex_corr.max() - _tex_corr.min())

_N_corr, _PIX_corr = 256, 2.0                                  # image size (px), pixel size (Å)
_img_corr = np.zeros((_N_corr, _N_corr)); _o_corr = (_N_corr - 128) // 2
_img_corr[_o_corr:_o_corr+128, _o_corr:_o_corr+128] = _duck_corr * (0.5 + 0.5*_tex_corr)
_F_corr = np.fft.fft2(_img_corr)
_fx_corr = np.fft.fftfreq(_N_corr, d=_PIX_corr)
_S_corr = np.hypot(*np.meshgrid(_fx_corr, _fx_corr))
_noise_corr = np.random.default_rng(5).standard_normal((_N_corr, _N_corr))

def _lam_A_corr(kV=300):
    V = kV * 1e3
    m0, ec, c, h = 9.109e-31, 1.602e-19, 2.998e8, 6.626e-34
    return h / np.sqrt(2*m0*ec*V*(1+ec*V/(2*m0*c**2))) * 1e10

def _ctf_corr(k, df_um, Cs_mm=2.7, B=50.0, dphi_deg=4.0, kV=300):
    lam = _lam_A_corr(kV); df = df_um * 1e4; Cs = Cs_mm * 1e7
    gamma = np.pi*lam*df*k**2 - 0.5*np.pi*Cs*lam**3*k**4
    return -np.sin(gamma + np.radians(dphi_deg)) * np.exp(-B*k**2/4)

def _correction_corr(method, ctf, nsr):
    """The filter that is multiplied with the Fourier transform of the observed image."""
    if method == 'Phase flipping':
        return np.sign(ctf)
    return ctf / (ctf**2 + nsr)                      # Wiener filter, nsr = 1/SNR

def draw_corr(df, noise, method, nsr):
    ctf = _ctf_corr(_S_corr, df)
    observed = np.real(np.fft.ifft2(ctf*_F_corr)) + noise*_noise_corr
    H = _correction_corr(method, ctf, nsr)
    corrected = np.real(np.fft.ifft2(np.fft.fft2(observed)*H))
    cc = np.corrcoef(corrected.ravel(), _img_corr.ravel())[0, 1]

    s1 = np.linspace(0, 0.25, 600)
    c1 = _ctf_corr(s1, df); h1 = _correction_corr(method, c1, nsr)
    fig, ax = plt.subplots(1, 4, figsize=(15, 3.6))
    ax[0].imshow(_img_corr, cmap='gray', vmin=0, vmax=1); ax[0].set_title("True image", fontsize=9)
    v = 3*observed.std()
    ax[1].imshow(observed, cmap='gray', vmin=-v, vmax=v); ax[1].set_title("Observed: CTF and noise", fontsize=9)
    lo, hi = np.percentile(corrected, [0.5, 99.5])
    ax[2].imshow(corrected, cmap='gray', vmin=lo, vmax=hi)
    ax[2].set_title(f"{method}\ncorrelation with true image: {cc:.2f}", fontsize=9)
    for a in ax[:3]:
        a.axis('off')
    ax[3].plot(s1, c1, color='#2c7bb6', label='CTF')
    ax[3].plot(s1, c1*h1, color='#d95f02', label='CTF × correction')
    ax[3].axhline(0, color='k', lw=0.5); ax[3].axhline(1, color='gray', lw=0.5, ls=':')
    ax[3].set_ylim(-1.2, 1.5); ax[3].set_xlabel('Spatial frequency k (Å⁻¹)')
    ax[3].legend(fontsize=8); ax[3].set_title("Transfer before and after correction", fontsize=9)
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=96); buf.seek(0)
    plt.close(fig); return buf.getvalue()

style = {'description_width': '130px'}
sl = {'layout': {'width': '360px'}}
df_c   = FloatSlider(value=1.5, min=0.5, max=4.0, step=0.1, description='Defocus (μm)', style=style, **sl)
nz_c   = FloatSlider(value=0.02, min=0.0, max=0.1, step=0.005, description='Noise', style=style, readout_format='.3f', **sl)
meth_c = Dropdown(options=['Phase flipping', 'Wiener filter'], value='Wiener filter',
                  description='Method', style=style, layout={'width': '300px'})
nsr_c  = FloatLogSlider(value=0.01, base=10, min=-4, max=0, step=0.1, description='Wiener 1/SNR', style=style, **sl)

out_corr = ImageWidget(format='png', layout={'max_width': '100%'})
def update_corr(_=None):
    out_corr.value = draw_corr(df_c.value, nz_c.value, meth_c.value, nsr_c.value)
for w in [df_c, nz_c, meth_c, nsr_c]:
    w.observe(update_corr, names='value')
display(VBox([HBox([VBox([df_c, nz_c]), VBox([meth_c, nsr_c])]), out_corr]))
update_corr()

10.5. Astigmatism#

A real objective lens is never perfectly rotationally symmetric, because of inhomogeneities of the pole piece and charging of contamination. The focal length then depends on the azimuth \(\varphi\) in the plane perpendicular to the optical axis, a defect that is called astigmatism (see also Section 4.10). In the CTF, this means that the defocus depends on the direction of the spatial frequency \(\mathbf{k}\):

(10.12)#\[ \Delta_f(\varphi) = \Delta_f + \tfrac{1}{2}\Delta_{f,\mathrm{a}}\cos\left[2(\varphi - \varphi_\mathrm{a})\right], \]

where \(\Delta_f\) is the mean defocus, \(\Delta_{f,\mathrm{a}}\) is the difference between the largest and the smallest defocus, and \(\varphi_\mathrm{a}\) is the direction of the largest defocus. The CTF of eq. (10.10) is evaluated with this \(\Delta_f(\varphi)\) in the phase shift \(\gamma\) of eq. (10.7). The rings of the two-dimensional CTF, and thus the Thon rings of the power spectrum, become ellipses. In the image, features are transferred with a different contrast and a different lateral displacement, depending on their orientation, which distorts the image and limits the resolution in the direction of the stronger defocus error.

The astigmatism of the lens is corrected with the stigmators of the microscope, which is demonstrated with an interactive simulation in Section 8.1.3. The residual astigmatism of the recorded images is estimated together with the defocus during CTF estimation and included in the CTF correction.

10.6. Phase plates#

The CTF of a conventional image is a compromise. It is close to zero at low spatial frequencies, where the overall shape of a particle is encoded, and defocus is required to restore the contrast at the expense of faster oscillations and additional zeros at higher frequencies. This is particularly limiting for small particles, for which the low-frequency contrast determines whether they can be detected and aligned at all.

A phase plate makes defocus unnecessary for the generation of phase contrast. It is a thin film (for example of carbon) placed in the back focal plane of the objective lens, where the unscattered beam is focused to a small spot while the scattered electrons are distributed around it. The plate shifts the phase of the unscattered beam by an additional amount, typically 90° (\(\pi/2\)). Because the scattered wave is already shifted by 90° with respect to the unscattered wave, an additional shift of \(\pi/2\) brings the two in phase (or in antiphase) without propagation. Mathematically, the phase plate increases the additional phase shift \(\Delta\varphi\) in (10.10). For \(\Delta\varphi = 90°\), the sine-like CTF turns into a cosine-like CTF,

\[ \mathrm{CTF}(k) = -\cos\gamma(k)\, E(k), \]

which has its maximum at low spatial frequency, even at zero defocus. In practice, a phase plate cannot shift the unscattered beam exclusively: electrons scattered to very low angles pass through the same spot and are shifted as well, so that the coarsest features are not transferred with the full phase shift. Further practical limitations are a phase shift that is not perfectly controlled (it can change with the exposure of the plate), the limited lifetime of the film, and additional scattering by the film.

The simulation below illustrates the effect assuming an ideal phase plate that shifts all spatial frequencies by the same amount. A conventional image at a typical defocus is compared with an image recorded with a phase plate at small defocus.

Interactive element

Click the rocket symbol at the top of the page and select Live Code, or expand the Show code toggle and click ▶ to run the cell. At the conventional defocus, the large features of the duck are suppressed and mainly its outline remains visible. With the phase plate (\(\Delta\varphi = 90°\)), the whole body of the duck appears with stronger contrast. Varying the phase shift changes the CTF between sine-like (a few degrees) and cosine-like (90°); at a small phase shift, the second image is a conventional image at the second defocus. Increasing the noise shows the importance of low-frequency contrast for the visibility of the object.

Hide code cell source

import io, zlib, base64
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from ipywidgets import FloatSlider, VBox, HBox, Image as ImageWidget
from IPython.display import display

# Test object: the rubber duck of the CryoEM doeboek practicals (128 x 128, 8 bit, compressed)
_DUCK_128_pp = 'eNrtWmtMm+cVrm8YsB2T2CEQLiYQCMVdIBDiBApJKCWKabNgN2lCEy6FGoxtHNsk2GAbAwZjG2yM77c0XZZsWVW1W6tNW7dqVSutWrtJW9utnaZ1WlW1TXrR1EvSpp32fp/v5jP+TEx++fmD+OPnfM8573nPOe+5554MMsgggwwyyCCDDBIDkwh3hxuLw+GRgMNhN9YGmBtPIOaQyGRKPMhkUg6RgN8wG4LcueQ8ekFxKWM1SosL6Hnk3KAN6ScPcBeW7mTW729uaWmNRUtL8/565s7SwoANaTUhQE6lQdwNTW1sbndPX19/LPr6erq57LamBsgGGjVgQto+PYdC215eU9/U1sk9MyiQKZRq9VQs1GqlQiYYPMPtbGuqrynfTqPkpEMEwI4nkqj5pdUNrUcBt1A2oZkzmJYt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CUva3lVEJ6d1NA2bC9gSPR2WMFiP3+BYcPGoFJOA3b0yw/7IDq9gGVyRlTAsb4XwHKA6/TpBpor6alWX74BBY3dolmLW4fcvw/KtauuL0uy6yoq7GYjE/3dhIGS9xS2dot08XWoNHnHxTUbqtO1t1auYWITft2FCjbtzHb++SGmNF/VP4zOdxu0H70tTO3kfDpX86CaqCiOjZPuWiPnj+E8/+K0+22gf6PXVdEIWA3YDkMeABU7sf5SkPM60vw/gPsrmD/SyViN2Y3DXQuFQeO8+TQ60f0uoLPC+BxWnRylP3/ukMgl16xjw3tSwSWRaJWglw2aAeCva+CnovfsO1ALD6Xxqhr7xapdGZoEhSE2+WwmnQqUXd7HQPd/OcOFrWoRczWrgHJ5Kwe7o8t8E6YfnZSMtDVyiyiZuOxG7ocCe0LVTa2c3r5UnmgP1arlXIpv5fT3lgZW+ltkAQE0pZiaE+OczrQH/f19ZzmQG1k8RYSAbvh26lQAU2mbd9Rs4cV6I9bWpoD7cyqQnOj9lOBBblUWqQ/Li0ugHYh8di7spsb2hMN98eBnVjc3WIPm4CL3Qm+5y7jbu9EZ5BBBhlkkEEGGWSQKv4PPkrrzg=='
_duck_pp = np.frombuffer(zlib.decompress(base64.b64decode(_DUCK_128_pp)),
                      dtype=np.uint8).reshape(128, 128).astype(float)[::-1, :] / 255   # flipped so that the duck is upright

_N_pp, _PIX_pp, _PHI0_pp = 256, 2.0, 0.2            # image size (px), pixel size (Å), peak phase shift (rad)
_phi_pp = np.zeros((_N_pp, _N_pp))
_o_pp = (_N_pp - 128) // 2
_phi_pp[_o_pp:_o_pp+128, _o_pp:_o_pp+128] = _duck_pp
_fx_pp = np.fft.fftfreq(_N_pp, d=_PIX_pp)
_S_pp = np.hypot(*np.meshgrid(_fx_pp, _fx_pp))
_phi_ft_pp = np.fft.fft2(_phi_pp)
_noise_pp = np.random.default_rng(1).standard_normal((_N_pp, _N_pp))

def _lam_A_pp(kV=300):
    V = kV * 1e3
    m0, ec, c, h = 9.109e-31, 1.602e-19, 2.998e8, 6.626e-34
    return h / np.sqrt(2*m0*ec*V*(1+ec*V/(2*m0*c**2))) * 1e10

def _ctf_pp(k, df_um, dphi_deg=4.0, Cs_mm=2.7, B=80.0, kV=300):
    lam = _lam_A_pp(kV); df = df_um * 1e4; Cs = Cs_mm * 1e7
    gamma = np.pi*lam*df*k**2 - 0.5*np.pi*Cs*lam**3*k**4
    return -np.sin(gamma + np.radians(dphi_deg)) * np.exp(-B*k**2/4)     # dphi_deg: additional phase shift

def draw_pp(df_conv, df_pp, shift_deg, noise):
    c_conv = _ctf_pp(_S_pp, df_conv)                       # conventional image: 4° from the amplitude contrast
    c_pp   = _ctf_pp(_S_pp, df_pp, shift_deg)              # phase plate: total additional phase shift
    imgs = [2*_PHI0_pp*np.real(np.fft.ifft2(_phi_ft_pp*c)) + noise*_noise_pp*_PHI0_pp
            for c in (c_conv, c_pp)]
    v = 2*_PHI0_pp * 0.9

    s1 = np.linspace(0, 0.25, 800)
    fig = plt.figure(figsize=(11, 6.6))
    gs = fig.add_gridspec(2, 3, height_ratios=[1, 1.15])
    ax = fig.add_subplot(gs[0, :])
    ax.plot(s1, _ctf_pp(s1, df_conv), color='#2c7bb6', lw=2, label=f'conventional, Δf={df_conv:.1f} μm')
    ax.plot(s1, _ctf_pp(s1, df_pp, shift_deg), color='#d95f02', lw=2,
            label=f'phase plate, Δφ={shift_deg:.0f}°, Δf={df_pp:.1f} μm')
    ax.axhline(0, color='k', lw=0.6)
    ax.set_xlim(0, 0.25); ax.set_ylim(-1.15, 1.15)
    ax.set_xlabel('Spatial frequency k (Å⁻¹)'); ax.set_ylabel('CTF(k)')
    ax.legend(fontsize=9, loc='upper right')
    ax_top = ax.twiny(); ax_top.set_xlim(ax.get_xlim())
    tks = [0.02, 0.05, 0.10, 0.20]
    ax_top.set_xticks(tks); ax_top.set_xticklabels([f'{1/t:.0f}' for t in tks], fontsize=8)
    ax_top.set_xlabel('Resolution (Å)', fontsize=9)

    for k, (img, title) in enumerate([(_phi_pp, 'Phase object (duck)'),
                                      (imgs[0], 'Conventional image'),
                                      (imgs[1], 'Phase-plate image')]):
        a = fig.add_subplot(gs[1, k])
        if k == 0:
            a.imshow(img, cmap='gray', vmin=0, vmax=1)
        else:
            a.imshow(img, cmap='gray', vmin=-v, vmax=v)
        a.set_title(title, fontsize=10); a.axis('off')
    fig.tight_layout()
    buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=90); buf.seek(0); plt.close(fig)
    return buf.getvalue()

style = {'description_width': '150px'}
sl = {'layout': {'width': '340px'}}
dfc_sl = FloatSlider(value=1.5, min=0.0, max=4.0, step=0.1,  description='Defocus no PP (μm)',  style=style, **sl)
dfp_sl = FloatSlider(value=0.1, min=0.0, max=4.0, step=0.1,  description='Defocus PP (μm)',  style=style, **sl)
sh_sl  = FloatSlider(value=90,  min=0,   max=180, step=5,    description='Phase shift Δφ (°)',  style=style, **sl)
nz_sl  = FloatSlider(value=0.4, min=0.0, max=2.0, step=0.1,  description='Noise',               style=style, **sl)

out_pp = ImageWidget(format='png', layout={'max_width': '100%'})
def update_pp(_=None):
    out_pp.value = draw_pp(dfc_sl.value, dfp_sl.value, sh_sl.value, nz_sl.value)
for w in [dfc_sl, dfp_sl, sh_sl, nz_sl]:
    w.observe(update_pp, names='value')
display(VBox([HBox([VBox([dfc_sl, dfp_sl]), VBox([sh_sl, nz_sl])]), out_pp]))
update_pp()

Practical

The contrast transfer function, the effect of a phase plate, the correction of the CTF by phase flipping and Wiener filtering, and signal delocalisation are explored in the corresponding practical of the CryoEM doeboek: CryoEM doeboek: Fourier analysis and the CTF