
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "generated/autoexamples/02-parameter-inference/02-lookup-table.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_02-lookup-table.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_02-lookup-table.py:


====================
MP2RAGE lookup table
====================

You map T1 from a two-block MP2RAGE acquisition in two ways, by interpolating
along the signal curve and by dictionary matching, and sweep the number of
points on the curve to see which method depends on it.

With a single unknown, the dictionary atoms lie on a curve instead of filling
a space. Interpolating between the two nearest points on the curve costs
nothing and removes the grid spacing from the error; this is what
:class:`~blochsim.estimators.LookupTable` does.

Prerequisites: Course lesson :doc:`../01-framework/01-first-simulation`.

.. GENERATED FROM PYTHON SOURCE LINES 19-24

.. 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 24-129

.. code-block:: Python


    import numpy as np
    import torch

    from blochsim.estimators import DictionaryMatcher, LookupTable
    from blochsim.simulators import MP2RAGESimulator








.. GENERATED FROM PYTHON SOURCE LINES 130-138

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 T1 is 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 138-179

.. code-block:: Python


    truth = torch.as_tensor(T1_true[mask].copy())
    density = torch.as_tensor(M0_true[mask].copy())




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





.. GENERATED FROM PYTHON SOURCE LINES 180-187

Protocol
--------

MP2RAGE applies one inversion and reads two spoiled gradient-echo blocks at
two inversion times. Each block samples the centre of k-space of its own
shot train, so a voxel contributes two values. The train is spoiled after
every readout, so T1 is the only tissue property that changes them.

.. GENERATED FROM PYTHON SOURCE LINES 187-198

.. code-block:: Python

    PROTOCOL = dict(
        TI=(800.0, 2700.0),
        flip=(4.0, 5.0),
        TRspgr=6.7,
        TRmp2rage=6000.0,
        nshots=128,
    )
    INVERSION_EFFICIENCY = 0.96

    simulator = MP2RAGESimulator(**PROTOCOL, inv_efficiency=INVERSION_EFFICIENCY)








.. GENERATED FROM PYTHON SOURCE LINES 199-205

Signal curve
------------

Neither block alone determines T1, since both are scaled by the proton
density and the receive gain. The unified combination divides this scale
out and leaves a value between -0.5 and 0.5 that depends on T1 alone:

.. GENERATED FROM PYTHON SOURCE LINES 205-212

.. code-block:: Python



    def unified(blocks):
        """The MP2RAGE unified image: independent of the scale, a function of T1."""
        return (blocks[..., 0] * blocks[..., 1]) / blocks.square().sum(-1).clamp_min(1e-12)









.. GENERATED FROM PYTHON SOURCE LINES 213-217

Whether the unified image is monotonic in T1 depends on the protocol. Where
it turns back it has no inverse, so the table keeps the longest monotonic run
and reports the range it spans. The dashed line marks the turning point of
the unified image at this protocol, beyond which T1 is not invertible.

.. GENERATED FROM PYTHON SOURCE LINES 217-241

.. code-block:: Python

    sweep = torch.arange(50.0, 6000.0, 10.0)
    curve = unified(simulator.simulate(T1=sweep, M0=1.0))





.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_002.png
   :alt: the two blocks, unified image
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 242-247

Measurement
-----------

The measurement is both blocks at the true T1 and proton density of every
brain voxel, with Gaussian noise of 0.5% of the peak magnetization.

.. GENERATED FROM PYTHON SOURCE LINES 247-268

.. code-block:: Python

    clean = simulator.simulate(T1=truth, M0=density)
    NOISE_STD = float(0.005 * clean.abs().max())

    generator = torch.Generator().manual_seed(42)
    measured = clean + NOISE_STD * torch.randn(clean.shape, generator=generator)










.. GENERATED FROM PYTHON SOURCE LINES 269-277

Estimators
----------

Both estimators are fitted on the same T1 grid, with the proton density
fixed to one. The matcher scores the two-block signal against every atom and
returns the nearest. The table reduces both blocks to the unified value and
interpolates along the curve; ``combine`` is the only information it is
given about the sequence. Neither is given the invertible range.

.. GENERATED FROM PYTHON SOURCE LINES 277-284

.. code-block:: Python

    grid = torch.linspace(50.0, 6000.0, 60)

    lookup = LookupTable(simulator.bind(M0=1.0), combine=unified).fit(T1=grid, seed=0)
    maps = lookup.map(measured)  # {"T1": ...}, one value per voxel

    match = DictionaryMatcher(simulator.bind(M0=1.0)).fit(T1=grid, seed=0)








.. GENERATED FROM PYTHON SOURCE LINES 285-290

Table size
----------

Sweeping the number of grid points separates the method from the sampling.
Times are the best of three passes over the slice.

.. GENERATED FROM PYTHON SOURCE LINES 290-351




.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_003.png
   :alt: error, time
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_003.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


     points     match     table     match     table
                error     error      time      time
    -----------------------------------------------
         30     7.93%     0.88%     2.1ms     0.6ms
         60     3.29%     0.75%     2.5ms     0.6ms
        120     0.78%     0.71%     3.5ms     0.7ms
        250     0.80%     0.71%     5.4ms     0.7ms
        500     0.62%     0.71%    11.6ms     0.7ms
       1000     0.66%     0.71%    24.0ms     0.8ms
       2000     0.71%     0.71%    45.5ms     0.9ms




.. GENERATED FROM PYTHON SOURCE LINES 352-365

The error floor is set by the noise. The table is within 0.2 percentage
points of it from 30 points on. The match is about nine times worse at 30
points and reaches the same floor at about 120, at a cost that grows with
the number of points: it takes one comparison per atom per voxel, where the table takes a
binary search that grows with the logarithm of the number of points. A
sufficiently fine grid makes the match equal to the table; the table does not
need to be told how fine the grid must be.

Maps
----

The maps use the number of points each method needs: 60 for the table and
2000 for the match, a grid fine enough not to limit it.

.. GENERATED FROM PYTHON SOURCE LINES 365-383





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

 .. code-block:: none

    the table keeps 38 of 60 points -- the monotonic run -- and spans unified -0.50 to 0.49




.. GENERATED FROM PYTHON SOURCE LINES 384-387

Neither estimator returns M0. The two blocks predicted for the estimated T1
are a shape of which the measurement is a multiple, so the proton density is
one inner product per voxel:

.. GENERATED FROM PYTHON SOURCE LINES 387-477

.. code-block:: Python



    def proton_density(maps):
        """The scale of the measurement relative to the blocks the answer predicts."""
        predicted = simulator.simulate(T1=maps["T1"], M0=1.0)
        return (predicted * measured).sum(-1) / predicted.square().sum(-1).clamp_min(1e-12)






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


    *

      .. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_004.png
         :alt: truth, lookup, match
         :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_004.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_005.png
         :alt: Δ lookup, Δ match
         :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_02-lookup-table_005.png
         :class: sphx-glr-multi-img


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

 .. code-block:: none


    method                      train      map     model      peak      T1      M0
    ------------------------------------------------------------------------------
    lookup, 60 points           0.00s    0.7ms  0.00 MiB        --   0.75%   0.46%
    match, 2000 atoms           0.00s   47.6ms  0.05 MiB        --   0.71%   0.45%




.. GENERATED FROM PYTHON SOURCE LINES 478-492

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

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

.. code-block:: text

   With blochsim, map T1 and M0 in BrainWeb subject 0, slice 90, from a
   two-block MP2RAGE (TI 800 and 2700 ms, flip angles 4 and 5 deg, TR 6.7 ms,
   128 shots, TR_MP2RAGE 6 s, inversion efficiency 0.96) at 0.5% noise.
   Fit a LookupTable on the unified image and a DictionaryMatcher over the
   same T1 grid. Sweep the grid from 30 to 2000 points and report the median
   relative T1 error and the mapping time of both; derive M0 from the
   predicted blocks.


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

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


.. _sphx_glr_download_generated_autoexamples_02-parameter-inference_02-lookup-table.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/02-lookup-table.ipynb
        :alt: Launch binder
        :width: 150 px

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

      :download:`Download Jupyter notebook: 02-lookup-table.ipynb <02-lookup-table.ipynb>`

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

      :download:`Download Python source code: 02-lookup-table.py <02-lookup-table.py>`

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

      :download:`Download zipped: 02-lookup-table.zip <02-lookup-table.zip>`


.. only:: html

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

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