NMR and MRI physics · Intermediate

Phase encoding line by line

Written by SignalsLab

Early edition: these lessons are being reviewed.

Content

Summary

In MRI, phase encoding uses a brief gradient pulse to give spins different phases depending on their position along one axis. Repeating the sequence with a different gradient step for each line fills one row of k-space per repetition. The set of rows is then Fourier transformed to give an image in the phase-encode direction.

Intuition

Imagine a row of clock hands all spinning at the same rate. If you briefly make the clocks on the left run slower and those on the right run faster, then switch the extra effect off, the hands stay permanently twisted: the twist grows steadily with position. That twist is a spatial code. One twist pattern alone is just one measurement of the whole object, a single spatial frequency. By repeating the experiment with a stronger, weaker, or reversed twist each time, you collect many spatial frequencies, one per repetition (one per TR). Each repetition gives one line of k-space. The line near the centre (zero gradient) holds contrast and overall signal; lines far from the centre (strong gradient) hold fine detail and edges. Fourier transformation turns the stack of lines into position.

Key equations

ϕ(y)=γGyyTpe
(1)

Phase accumulated by a spin at position y after a gradient of strength G_y is applied for duration T_pe.

ky=γ2πGyTpe
(2)

Phase-encode k-space coordinate set by the gradient area; each step n gives a different k_y.

Δky=1FOVy
(3)

Spacing between k-space lines is the inverse of the field of view in the phase direction.

ky,max=Ny2FOVy⇒Δy=12ky,max
(4)

Largest k_y reached sets the resolution; N_y lines are needed for N_y pixels.

S(ky)=∫ρ(y)e−i2πkyydy
(5)

Signal for each line is the Fourier transform of the spin density along y.

Derivation

  1. Spins precess at ω=γB. Adding a gradient gives B(y)=B0+Gyy, so ω(y)=γB0+γGyy.
  2. Apply G_y for a short time T_pe, then switch it off. The extra phase gained is φ(y)=γG_y y T_pe.
  3. After the gradient ends, spins return to the same frequency but keep the position-dependent phase offset.
  4. Define k_y=γG_yT_pe/2π so that φ=2πk_y y, and the signal becomes S(k_y)=∫ρ(y)e^{-i2πk_y y}dy.
  5. Change G_y in equal steps each TR, so k_y takes values -k_max to +k_max in steps Δk.
  6. Place each acquired line at its k_y row in k-space (the readout gradient fills the kx direction).
  7. Inverse 2D Fourier transform yields ρ(x,y). Step Δk=1/FOV prevents aliasing (wrap-around) in y.

Worked example

Problem

A scan has FOV_y = 240 mm and N_y = 120 phase-encode lines, TR = 500 ms, one average. Find Δk_y, the maximum k_y, the pixel size, and the scan time.

  1. Δk_y = 1/FOV = 1/0.240 m = 4.17 m⁻¹ (1/m).
  2. k_max = (N_y/2)Δk = 60 × 4.17 = 250 m⁻¹.
  3. Pixel size Δy = 1/(2k_max) = 1/500 m = 2 mm (check: 240/120 = 2 mm).
  4. Scan time = N_y × TR × averages = 120 × 0.5 s × 1 = 60 s.

Answer Δk_y ≈ 4.17 m⁻¹, k_max ≈ 250 m⁻¹, 2 mm pixels, 60 s scan.

Common mistakes

  • Thinking phase encoding is applied during readout; it is a short pulse before readout and the gradient is off while the signal is read.
  • Believing one repetition gives one pixel row of the image; each line is a spatial frequency, not an image row.
  • Forgetting that the gradient is changed every TR, so scan time scales with the number of phase-encode lines.
  • Confusing the center of k-space (contrast, low frequencies) with the edges (detail).
  • Using too large a step Δk for the object size, causing wrap-around aliasing in the phase direction.

Animation

Animation coming soon

The animated version of this lesson is being prepared for the web. In the Signals AI app, lessons are drawn step by step.

Code

scene.py(159 lines)
from manim import *
import numpy as np
import sys
from blocks import *

# --- Configuration ---
NY = 16           # Number of phase-encoding steps
NX = 64           # Readout points (visual only)
TR_DURATION = 0.4 # Seconds per TR in animation

# --- Helper Functions ---

def compute_ky_line(step, ny):
    """
    Compute the normalized k-space coordinate ky for a given phase-encoding step.
    Uses linear ordering: -1 to +1.
    """
    # ky = -1 + (2 * step + 1) / ny  (center of the line)
    return -1.0 + (2 * step + 1) / ny

def generate_trace(ny):
    """
    Generate the full trace of the phase encoding process.
    Each state represents one TR.
    """
    states = []
    for step in range(ny):
        ky = compute_ky_line(step, ny)
        states.append({
            "step": step,
            "ky": ky,
            "gy_amp": ky
        })
    return states

class Main(Scene):
    def construct(self):
        TitleCard(self, "Phase Encoding", "Step-by-step k-space filling")

        # --- Layout Setup ---
        # Left: k-space grid
        # Right: Pulse sequence timing diagram
        
        # 1. K-Space Visualization
        # We will draw a grid of dots representing k-space lines.
        # As we step, we highlight the current line.
        ks_grid = VGroup()
        dot_radius = 0.15
        spacing = 0.4
        
        # Create dots for all possible ky positions
        all_dots = VGroup()
        for i in range(NY):
            ky_norm = -1.0 + (2 * i + 1) / NY
            y_pos = ky_norm * 2.5  # Scale to fit view
            dot = Dot(radius=dot_radius, color=C_DIM, fill_opacity=0.3)
            dot.move_to([0, y_pos, 0])
            all_dots.add(dot)
            
        # Add axes labels for k-space
        kx_label = Text("k_x (Readout)", font_size=24, color=C_DIM).next_to(all_dots, RIGHT, buff=0.5)
        ky_label = Text("k_y (Phase)", font_size=24, color=C_DIM).next_to(all_dots, UP, buff=0.5)
        ky_axis = Line(start=[-3, -2.5, 0], end=[-3, 2.5, 0], color=C_DIM)
        kx_axis = Line(start=[-3, 0, 0], end=[3, 0, 0], color=C_DIM)
        
        ks_group = VGroup(all_dots, kx_axis, ky_axis, kx_label, ky_label)
        ks_group.move_to([-3.5, 0, 0])
        
        # 2. Pulse Sequence Diagram (Simplified)
        # Show Gy amplitude changing
        seq_width = 6.0
        seq_height = 3.0
        seq_bg = Rectangle(width=seq_width, height=seq_height, fill_color=BLACK, fill_opacity=0.8, stroke_color=C_DIM)
        seq_bg.move_to([3.5, 0, 0])
        
        # Axes for pulse sequence
        seq_axes = Axes(
            x_range=[0, NY, 1],
            y_range=[-1.2, 1.2, 0.5],
            x_length=seq_width,
            y_length=seq_height * 0.8,
            axis_config={"color": C_DIM}
        )
        seq_axes.move_to(seq_bg.get_center())
        
        # Labels for pulse sequence
        seq_title = Text("Gy Amplitude", font_size=24, color=C_DIM).next_to(seq_axes, UP, buff=0.2)
        seq_x_label = Text("TR Step", font_size=24, color=C_DIM).next_to(seq_axes, RIGHT, buff=0.2)
        seq_y_label = Text("k_y", font_size=24, color=C_DIM).next_to(seq_axes, LEFT, buff=0.2)
        
        # The current Gy bar/point
        current_bar = Rectangle(width=0.4, height=0.1, fill_color=C_ACCENT, fill_opacity=1)
        current_bar.move_to(seq_axes.c2p(0, 0))
        
        # Info Text
        info_text = Text("Step 0 / 16", font_size=28, color=WHITE).next_to(seq_axes, DOWN, buff=0.5)
        info_ky = Text("k_y = -1.00", font_size=28, color=C_ACCENT).next_to(info_text, DOWN, buff=0.2)

        # Assemble and play initial setup
        self.play(FadeIn(ks_group), FadeIn(seq_bg), FadeIn(seq_axes), FadeIn(seq_title), 
                  FadeIn(seq_x_label), FadeIn(seq_y_label), FadeIn(current_bar),
                  FadeIn(info_text), FadeIn(info_ky), run_time=1.5)
        
        StepCaption(self, "Gy amplitude is stepped to fill k-space line by line")

        # --- Animation Loop ---
        trace = generate_trace(NY)
        
        for i, state in enumerate(trace):
            step = state["step"]
            ky = state["ky"]
            
            # Update Info Text
            new_info = Text(f"Step {step+1} / {NY}", font_size=28, color=WHITE)
            new_info.move_to(info_text.get_center())
            new_ky = Text(f"k_y = {ky:.2f}", font_size=28, color=C_ACCENT)
            new_ky.move_to(info_ky.get_center())
            
            self.play(Transform(info_text, new_info), Transform(info_ky, new_ky), run_time=0.1)
            
            # Update Gy Bar Position
            # Map ky (-1 to 1) to y-axis of seq_axes
            # seq_axes.y_range is [-1.2, 1.2]
            # We need to scale ky to fit within the axes height
            y_val = ky * 0.9  # Slight margin
            new_bar = Rectangle(width=0.4, height=0.1, fill_color=C_ACCENT, fill_opacity=1)
            new_bar.move_to(seq_axes.c2p(step + 0.5, y_val))
            
            self.play(Transform(current_bar, new_bar), run_time=TR_DURATION)
            
            # Highlight the corresponding k-space line
            # The dot index i corresponds to the step
            target_dot = all_dots[i]
            self.play(target_dot.animate.set_fill(C_ACCENT).set_fill_opacity(1).set_stroke(C_ACCENT), run_time=0.2)
            
            # Optional: Fade out previous dots to emphasize progression? 
            # No, let's keep them filled to show "filled" space.
            
        StepCaption(self, "Full k-space acquired after NY phase steps")
        self.wait(1)


if __name__ == "__main__" and "--selftest" in sys.argv:
    trace = generate_trace(NY)
    assert len(trace) == NY
    
    # Check first and last ky values
    assert abs(trace[0]["ky"] - (-1.0 + 1/NY)) < 1e-5
    assert abs(trace[-1]["ky"] - (-1.0 + (2*(NY-1)+1)/NY)) < 1e-5
    
    # Check monotonicity
    kys = [s["ky"] for s in trace]
    for i in range(len(kys)-1):
        assert kys[i] < kys[i+1]
        
    # Check symmetry
    assert abs(kys[0] + kys[-1]) < 1e-5
    
    print("selftest ok")

The Manim scene code that draws this lesson's animation in the Signals AI app (Python, Manim Community).

ccBYNC© 2026 SignalsLab. Lesson text shared as is under CC BY-NC 4.0.