Dictionary matching#

You map T1, T2 and proton density in a brain slice from a magnetic resonance fingerprinting (MRF) train by dictionary matching, then reduce the cost of the match in two independent ways: by working in the low-rank subspace spanned by the train, and by clustering the dictionary so that most atoms are not scored.

Prerequisites: Course lesson 1. Your first simulation.

import numpy as np
import torch

from blochsim import Subspace
from blochsim.estimators import DictionaryMatcher
from blochsim.simulators import MRFSimulator

Phantom#

The phantom is BrainWeb subject 0, slice 90: an axial 1 mm slice through the lateral ventricles. BrainWeb provides fuzzy tissue memberships, so each voxel holds a fraction of each tissue and its relaxation times are the fraction-weighted average. About a third of the voxels are mixtures, so the ground truth is a continuum of values rather than four.

BrainWeb subject 0, slice 90
Downloading tissues:   0%|          | 0/10 [00:00<?, ?it/s]


Downloading phantom_1.0mm_normal_bck: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_bck: 1.00kB [00:00, 4.38kB/s]


Downloading phantom_1.0mm_normal_bck: 257kB [00:00, 871kB/s]


Downloading phantom_1.0mm_normal_bck: 513kB [00:00, 1.43MB/s]


Downloading phantom_1.0mm_normal_bck: 769kB [00:00, 1.70MB/s]


Downloading phantom_1.0mm_normal_bck: 1.00MB [00:00, 1.86MB/s]


Downloading phantom_1.0mm_normal_bck: 1.25MB [00:00, 1.90MB/s]


Downloading phantom_1.0mm_normal_bck: 1.50MB [00:00, 1.92MB/s]


Downloading phantom_1.0mm_normal_bck: 1.75MB [00:01, 2.02MB/s]


Downloading phantom_1.0mm_normal_bck: 2.00MB [00:01, 2.09MB/s]




Downloading tissues:  10%|█         | 1/10 [00:01<00:16,  1.86s/it]


Downloading phantom_1.0mm_normal_csf: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_csf: 1.00kB [00:00, 7.46kB/s]


Downloading phantom_1.0mm_normal_csf: 181kB [00:00, 925kB/s]




Downloading tissues:  20%|██        | 2/10 [00:02<00:09,  1.18s/it]


Downloading phantom_1.0mm_normal_gry: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_gry: 1.00kB [00:00, 8.47kB/s]


Downloading phantom_1.0mm_normal_gry: 398kB [00:00, 2.07MB/s]


Downloading phantom_1.0mm_normal_gry: 1.00MB [00:00, 3.61MB/s]




Downloading tissues:  30%|███       | 3/10 [00:03<00:06,  1.02it/s]


Downloading phantom_1.0mm_normal_wht: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_wht: 1.00kB [00:00, 5.59kB/s]


Downloading phantom_1.0mm_normal_wht: 429kB [00:00, 1.82MB/s]




Downloading tissues:  40%|████      | 4/10 [00:03<00:05,  1.18it/s]


Downloading phantom_1.0mm_normal_fat: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_fat: 1.00kB [00:00, 8.23kB/s]


Downloading phantom_1.0mm_normal_fat: 257kB [00:00, 1.38MB/s]




Downloading tissues:  50%|█████     | 5/10 [00:04<00:03,  1.30it/s]


Downloading phantom_1.0mm_normal_m-s: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_m-s: 1.00kB [00:00, 4.99kB/s]


Downloading phantom_1.0mm_normal_m-s: 429kB [00:00, 1.65MB/s]


Downloading phantom_1.0mm_normal_m-s: 769kB [00:00, 2.05MB/s]


Downloading phantom_1.0mm_normal_m-s: 1.25MB [00:00, 2.83MB/s]


Downloading phantom_1.0mm_normal_m-s: 1.75MB [00:00, 3.24MB/s]


Downloading phantom_1.0mm_normal_m-s: 2.25MB [00:00, 3.42MB/s]




Downloading tissues:  60%|██████    | 6/10 [00:05<00:03,  1.08it/s]


Downloading phantom_1.0mm_normal_skn: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_skn: 1.00kB [00:00, 5.15kB/s]


Downloading phantom_1.0mm_normal_skn: 429kB [00:00, 1.68MB/s]


Downloading phantom_1.0mm_normal_skn: 769kB [00:00, 2.10MB/s]


Downloading phantom_1.0mm_normal_skn: 1.25MB [00:00, 2.80MB/s]


Downloading phantom_1.0mm_normal_skn: 1.75MB [00:00, 3.22MB/s]


Downloading phantom_1.0mm_normal_skn: 2.25MB [00:00, 3.36MB/s]


Downloading phantom_1.0mm_normal_skn: 2.75MB [00:01, 2.90MB/s]




Downloading tissues:  70%|███████   | 7/10 [00:07<00:03,  1.12s/it]


Downloading phantom_1.0mm_normal_skl: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_skl: 1.00kB [00:00, 6.01kB/s]


Downloading phantom_1.0mm_normal_skl: 181kB [00:00, 834kB/s]




Downloading tissues:  80%|████████  | 8/10 [00:07<00:01,  1.06it/s]


Downloading phantom_1.0mm_normal_gli: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_gli: 1.00kB [00:00, 6.84kB/s]




Downloading tissues:  90%|█████████ | 9/10 [00:08<00:00,  1.28it/s]


Downloading phantom_1.0mm_normal_mit: 0.00B [00:00, ?B/s]


Downloading phantom_1.0mm_normal_mit: 1.00kB [00:00, 5.08kB/s]


Downloading phantom_1.0mm_normal_mit: 257kB [00:00, 1.05MB/s]


Downloading phantom_1.0mm_normal_mit: 769kB [00:00, 2.00MB/s]


Downloading phantom_1.0mm_normal_mit: 1.25MB [00:00, 2.44MB/s]


Downloading phantom_1.0mm_normal_mit: 1.75MB [00:00, 2.76MB/s]




Downloading tissues: 100%|██████████| 10/10 [00:09<00:00,  1.09it/s]

Sequence#

The sequence is an inversion followed by 400 repetitions at TR = 10 ms. The flip angle varies smoothly along the train, so that the signal evolutions of different tissues differ by physics and not by the noise of an irregular schedule.

CONTRASTS = 400
TR_MS = 10.0
TI_MS = 20.0

repetition = torch.arange(CONTRASTS, dtype=torch.float32)
flip = 10.0 + 50.0 * torch.sin(torch.pi * repetition / CONTRASTS) ** 2

simulator = MRFSimulator(flip=flip, TR=TR_MS, TI=TI_MS, states=20, M0=1.0)

The readouts advance the configuration states and do not rewind them, so the signal evolution is real to float32 precision. The dictionary and the inner products that search it therefore need only the real part. These are the evolutions of white matter, grey matter and CSF:

fingerprints = simulator.simulate(
    T1=torch.tensor([500.0, 833.0, 2569.0]), T2=torch.tensor([70.0, 83.0, 329.0])
)
print(f"largest imaginary part: {fingerprints.imag.abs().max():.1e}")
fingerprints = fingerprints.real
flip angles, signal evolutions
largest imaginary part: 0.0e+00

Measurement#

The measurement is the evolution of every voxel at its true T1 and T2, scaled by its proton density, with Gaussian noise of 2% of the peak signal. The estimators are given the same noise level: one trained for more noise than the scan has trusts the data less and returns values closer to the prior.

NOISE_STD = float(0.02 * fingerprints.max())

truth = {
    "T1": torch.as_tensor(T1_true[mask].copy()),
    "T2": torch.as_tensor(T2_true[mask].copy()),
}
density = torch.as_tensor(M0_true[mask].copy())
clean = simulator.simulate(**truth).real * density[:, None]
generator = torch.Generator().manual_seed(42)
measured = clean + NOISE_STD * torch.randn(clean.shape, generator=generator)

Problem statement#

The unknowns are T1 and T2. Both span more than a decade, so the parameter grids and the training draws are logarithmic: uniform spacing would spend most of the atoms on long T1, where the evolutions are nearly parallel.

T1_RANGE = (200.0, 5000.0)
T2_RANGE = (20.0, 600.0)
SAMPLES = 20_000
prior = torch.Generator().manual_seed(11)

Subspace rank#

The 400 contrasts span far fewer than 400 independent directions. Subspace.fit computes a basis from simulated evolutions and reports the fraction of their energy that a given rank retains; one minus that fraction is the relative squared error of projecting onto the basis and back.

training_signals, _, _ = (
    DictionaryMatcher(simulator)
    .fit(
        T1=log_uniform(*T1_RANGE, SAMPLES),
        T2=log_uniform(*T2_RANGE, SAMPLES),
        noise_std=NOISE_STD,
        seed=0,
    )
    .training_set(SAMPLES)
)
training_signals = training_signals.real

RANK = 4
01 dictionary matching

At rank 4 the energy left outside the basis is below the energy the noise adds, so projecting onto four directions loses less than the noise already contributes. Every contrast dropped also removes arithmetic from the match.

Dictionary#

A dictionary spans the parameters jointly, so its size is the product of the grid sizes: here 200 values of T1 by 100 of T2, 20 000 atoms, fine enough that the grid spacing does not limit the result. Each additional parameter multiplies the size again. fit simulates the atoms and map returns one value per voxel for each parameter, and for M0, which follows from the scale between the measurement and the best-matching atom:

T1_GRID = torch.logspace(np.log10(T1_RANGE[0]), np.log10(T1_RANGE[1]), 200)
T2_GRID = torch.logspace(np.log10(T2_RANGE[0]), np.log10(T2_RANGE[1]), 100)
grid_t1, grid_t2 = torch.meshgrid(T1_GRID, T2_GRID, indexing="ij")

full = DictionaryMatcher(simulator).fit(
    T1=grid_t1.reshape(-1), T2=grid_t2.reshape(-1), seed=0
)

maps = full.map(measured)  # {"T1": ..., "T2": ..., "M0": ...}

Matching in the subspace#

Passing rank fits the basis, projects the dictionary onto it and stores it at that rank. The measurement is projected onto the same basis before the atoms are scored.

low = DictionaryMatcher(simulator).fit(
    T1=grid_t1.reshape(-1), T2=grid_t2.reshape(-1), seed=0, rank=RANK
)

Clustered dictionary#

Compression shortens every inner product; clustering reduces how many are computed. Atoms of neighbouring tissues have nearly parallel signal evolutions, so they fall into groups. Each voxel is scored against one representative per group, and groups that cannot contain the best match are excluded before any of their atoms is scored. The grouping is computed in the compressed basis, the space the measurement is already in.

GROUPS = 32

grouped = DictionaryMatcher(simulator, groups=GROUPS).fit(
    T1=grid_t1.reshape(-1),
    T2=grid_t2.reshape(-1),
    seed=0,
    rank=RANK,
)
32 groups of 625 atoms; 1.4 still open per voxel

Cost and accuracy#

Times are the best of three passes after a warm-up. model is the memory the fitted estimator holds between volumes. peak is the maximum GPU memory allocated while mapping the slice, which decides whether a volume fits or has to be processed in pieces; it is blank on a machine without a GPU. Errors are medians over the brain voxels, relative to the truth.

method                         train     map     model      peak      T1      T2      M0
----------------------------------------------------------------------------------------
match, 400 contrasts            8.6s   7.73s 122.3 MiB        --    0.6%    1.6%    0.4%
match, rank 4                   1.0s   1.45s   1.4 MiB        --    0.6%    1.6%    0.4%
match, rank 4 + groups          1.0s   0.08s   1.4 MiB        --    0.6%    1.6%    0.4%

Maps#

The maps of each method, and below them the absolute error on a scale of its own for each parameter.

  • truth, full, rank 4, + groups
  • Δ full, Δ rank 4, Δ + groups

Specification#

What this page did, stated the way you would ask an agent for it:

With blochsim, map T1, T2 and M0 in BrainWeb subject 0, slice 90, from an
inversion-prepared MRF train of 400 repetitions (TR 10 ms, TI 20 ms,
flip angle 10 + 50 sin^2(pi n / 400) deg) at 2% noise. Use a
DictionaryMatcher over 200 log-spaced T1 by 100 log-spaced T2 values.
Compare the full match, the match at subspace rank 4 and the match at
rank 4 with 32 groups, reporting training time, mapping time, estimator
memory and the median relative error of each map.

Total running time of the script: (0 minutes 54.780 seconds)

Gallery generated by Sphinx-Gallery