
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "generated/autoexamples/02-parameter-inference/01-dictionary-matching.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_generated_autoexamples_02-parameter-inference_01-dictionary-matching.py>`
        to download the full example code or to run this example in your browser via Binder.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_generated_autoexamples_02-parameter-inference_01-dictionary-matching.py:


===================
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 :doc:`../01-framework/01-first-simulation`.

.. GENERATED FROM PYTHON SOURCE LINES 15-20

.. colab-link::
   :needs_gpu: 0

   !pip install blochsim matplotlib brainweb-dl cmap
   !wget --quiet --no-clobber https://raw.githubusercontent.com/pulserver/blochsim/main/docs/figure_style.py

.. GENERATED FROM PYTHON SOURCE LINES 20-132

.. code-block:: Python


    import numpy as np
    import torch

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








.. GENERATED FROM PYTHON SOURCE LINES 133-141

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.

.. GENERATED FROM PYTHON SOURCE LINES 141-181




.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_001.png
   :alt: BrainWeb subject 0, slice 90
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_001.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    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.59kB/s]

    Downloading phantom_1.0mm_normal_bck: 40.1kB [00:00, 144kB/s] 

    Downloading phantom_1.0mm_normal_bck: 204kB [00:00, 605kB/s] 

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

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

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

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

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

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

                                                                  
    Downloading tissues:  10%|█         | 1/10 [00:02<00:19,  2.15s/it]

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

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

    Downloading phantom_1.0mm_normal_csf: 40.1kB [00:00, 190kB/s] 

    Downloading phantom_1.0mm_normal_csf: 134kB [00:00, 448kB/s] 

    Downloading phantom_1.0mm_normal_csf: 259kB [00:00, 718kB/s]

    Downloading phantom_1.0mm_normal_csf: 384kB [00:00, 828kB/s]

    Downloading phantom_1.0mm_normal_csf: 478kB [00:00, 759kB/s]

    Downloading phantom_1.0mm_normal_csf: 607kB [00:00, 898kB/s]

    Downloading phantom_1.0mm_normal_csf: 699kB [00:01, 803kB/s]

                                                                
    Downloading tissues:  20%|██        | 2/10 [00:03<00:15,  1.93s/it]

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

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

    Downloading phantom_1.0mm_normal_gry: 40.1kB [00:00, 174kB/s] 

    Downloading phantom_1.0mm_normal_gry: 149kB [00:00, 479kB/s] 

    Downloading phantom_1.0mm_normal_gry: 384kB [00:00, 1.01MB/s]

    Downloading phantom_1.0mm_normal_gry: 544kB [00:00, 1.17MB/s]

    Downloading phantom_1.0mm_normal_gry: 693kB [00:00, 1.11MB/s]

    Downloading phantom_1.0mm_normal_gry: 839kB [00:00, 1.07MB/s]

    Downloading phantom_1.0mm_normal_gry: 956kB [00:01, 1.09MB/s]

    Downloading phantom_1.0mm_normal_gry: 1.04MB [00:01, 1.01MB/s]

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

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

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

    Downloading phantom_1.0mm_normal_wht: 40.1kB [00:00, 164kB/s] 

    Downloading phantom_1.0mm_normal_wht: 207kB [00:00, 663kB/s] 

                                                                
    Downloading tissues:  40%|████      | 4/10 [00:07<00:09,  1.65s/it]

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

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

    Downloading phantom_1.0mm_normal_fat: 40.1kB [00:00, 201kB/s] 

    Downloading phantom_1.0mm_normal_fat: 188kB [00:00, 669kB/s] 

                                                                
    Downloading tissues:  50%|█████     | 5/10 [00:08<00:07,  1.42s/it]

    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.62kB/s]

    Downloading phantom_1.0mm_normal_m-s: 40.1kB [00:00, 144kB/s] 

    Downloading phantom_1.0mm_normal_m-s: 173kB [00:00, 506kB/s] 

    Downloading phantom_1.0mm_normal_m-s: 747kB [00:00, 1.99MB/s]

    Downloading phantom_1.0mm_normal_m-s: 1.50MB [00:00, 3.68MB/s]

    Downloading phantom_1.0mm_normal_m-s: 2.00MB [00:00, 3.76MB/s]

    Downloading phantom_1.0mm_normal_m-s: 2.50MB [00:01, 3.46MB/s]

                                                                  
    Downloading tissues:  60%|██████    | 6/10 [00:09<00:06,  1.52s/it]

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

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

    Downloading phantom_1.0mm_normal_skn: 40.1kB [00:00, 164kB/s] 

    Downloading phantom_1.0mm_normal_skn: 204kB [00:00, 651kB/s] 

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

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

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

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

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

                                                                  
    Downloading tissues:  70%|███████   | 7/10 [00:11<00:04,  1.59s/it]

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

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

    Downloading phantom_1.0mm_normal_skl: 40.1kB [00:00, 178kB/s] 

    Downloading phantom_1.0mm_normal_skl: 204kB [00:00, 685kB/s] 

                                                                
    Downloading tissues:  80%|████████  | 8/10 [00:12<00:02,  1.38s/it]

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

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

                                                                  
    Downloading tissues:  90%|█████████ | 9/10 [00:13<00:01,  1.17s/it]

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

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

    Downloading phantom_1.0mm_normal_mit: 40.1kB [00:00, 153kB/s] 

    Downloading phantom_1.0mm_normal_mit: 204kB [00:00, 625kB/s] 

    Downloading phantom_1.0mm_normal_mit: 863kB [00:00, 2.49MB/s]

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

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

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



.. GENERATED FROM PYTHON SOURCE LINES 182-189

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.

.. GENERATED FROM PYTHON SOURCE LINES 189-198

.. code-block:: Python

    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)








.. GENERATED FROM PYTHON SOURCE LINES 199-203

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:

.. GENERATED FROM PYTHON SOURCE LINES 203-220

.. code-block:: Python

    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





.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_002.png
   :alt: flip angles, signal evolutions
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_002.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    largest imaginary part: 0.0e+00




.. GENERATED FROM PYTHON SOURCE LINES 221-228

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.

.. GENERATED FROM PYTHON SOURCE LINES 228-239

.. code-block:: Python

    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)








.. GENERATED FROM PYTHON SOURCE LINES 240-246

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.

.. GENERATED FROM PYTHON SOURCE LINES 246-251

.. code-block:: Python

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








.. GENERATED FROM PYTHON SOURCE LINES 252-259

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.

.. GENERATED FROM PYTHON SOURCE LINES 259-289

.. code-block:: Python

    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





.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_003.png
   :alt: 01 dictionary matching
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 290-303

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:

.. GENERATED FROM PYTHON SOURCE LINES 303-322

.. code-block:: Python

    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": ...}









.. GENERATED FROM PYTHON SOURCE LINES 323-329

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.

.. GENERATED FROM PYTHON SOURCE LINES 329-343

.. code-block:: Python


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









.. GENERATED FROM PYTHON SOURCE LINES 344-353

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.

.. GENERATED FROM PYTHON SOURCE LINES 353-385

.. code-block:: Python

    GROUPS = 32

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






.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    32 groups of 625 atoms; 1.4 still open per voxel




.. GENERATED FROM PYTHON SOURCE LINES 386-394

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.

.. GENERATED FROM PYTHON SOURCE LINES 394-438





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    method                         train     map     model      peak      T1      T2      M0
    ----------------------------------------------------------------------------------------
    match, 400 contrasts            5.5s   5.08s 122.3 MiB        --    0.6%    1.6%    0.4%
    match, rank 4                   1.0s   1.53s   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%




.. GENERATED FROM PYTHON SOURCE LINES 439-444

Maps
----

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

.. GENERATED FROM PYTHON SOURCE LINES 444-494




.. rst-class:: sphx-glr-horizontal


    *

      .. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_004.png
         :alt: truth, full, rank 4, + groups
         :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_004.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_005.png
         :alt: Δ full, Δ rank 4, Δ + groups
         :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_01-dictionary-matching_005.png
         :class: sphx-glr-multi-img





.. GENERATED FROM PYTHON SOURCE LINES 495-509

Specification
-------------

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

.. code-block:: text

   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.


.. rst-class:: sphx-glr-timing

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


.. _sphx_glr_download_generated_autoexamples_02-parameter-inference_01-dictionary-matching.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: binder-badge

      .. image:: images/binder_badge_logo.svg
        :target: https://mybinder.org/v2/gh/pulserver/blochsim/gh-pages?urlpath=lab/tree/v0.0.17/notebooks/generated/autoexamples/02-parameter-inference/01-dictionary-matching.ipynb
        :alt: Launch binder
        :width: 150 px

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: 01-dictionary-matching.ipynb <01-dictionary-matching.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: 01-dictionary-matching.py <01-dictionary-matching.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: 01-dictionary-matching.zip <01-dictionary-matching.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
