
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "generated/autoexamples/03-sequence-optimization/02-joint-relaxometry.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_03-sequence-optimization_02-joint-relaxometry.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_03-sequence-optimization_02-joint-relaxometry.py:


==================================
Joint relaxometry protocol design
==================================

In this example you choose the flip angles of a DESPOT protocol so that a joint
fit of T1 and T2 is as precise as possible [1]_. DESPOT estimates T1 from
spoiled gradient-echo scans at several flip angles and T2 from balanced SSFP
scans. A joint fit uses all the data for both parameters.

The cost is a Cramer-Rao bound: the lowest variance an unbiased estimate can
have, given the derivative of the signal with respect to every parameter
estimated. You minimize it over the flip angles, then play the designed
protocol on a BrainWeb slice and compare the error of the fitted maps with the
bound.

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

.. GENERATED FROM PYTHON SOURCE LINES 21-26

.. colab-link::
   :needs_gpu: 0

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

.. GENERATED FROM PYTHON SOURCE LINES 26-83








.. GENERATED FROM PYTHON SOURCE LINES 84-96

Sequences
---------

A design has three pieces. A simulator with the tissue fixed on it, so that
only the parameters under design are left to give. A cost. And the bounded
parameters that :class:`~blochsim.optim.SequenceDesign` adjusts.

Here the simulators are an SPGR and a bSSFP sequence, both in closed form.
You construct and call them the same way as a sequence that plays events. The
tissues are white and grey matter at 3 T, and you design for both at once.
``NOISE`` is the noise standard deviation as a fraction of the fully relaxed
magnetization:

.. GENERATED FROM PYTHON SOURCE LINES 96-109

.. code-block:: Python

    import torch

    import blochsim
    from blochsim.optim import Bounded, SequenceDesign
    from blochsim.simulators import SPGRSimulator, bSSFPSimulator

    T1_MS = torch.tensor([830.0, 1330.0])
    T2_MS = torch.tensor([80.0, 110.0])
    NOISE = 0.005

    spgr = SPGRSimulator(TE=2.0, TR=6.0, T1=T1_MS, T2star=T2_MS, M0=1.0, B0=0.0)
    ssfp = bSSFPSimulator(TE=2.5, TR=5.0, T1=T1_MS, T2=T2_MS, M0=1.0, B0=0.0)








.. GENERATED FROM PYTHON SOURCE LINES 110-123

Cost
----

You estimate four parameters jointly: T1, T2, the proton density M0 and the
off-resonance B0. M0 and B0 are nuisance parameters, estimated because they
affect the data and not because the design is for them.

The two sequences carry different information. The spoiled steady state in
closed form depends on T2* and not on T2, so its T2 row is exactly zero. Each
block is blind to something, and the Fisher matrix adds them up. ``rows``
stacks the derivatives of one block with a zero row for each parameter it is
blind to, and :func:`~blochsim.optim.crlb` turns the stacked derivatives into a
bound on each parameter:

.. GENERATED FROM PYTHON SOURCE LINES 123-141

.. code-block:: Python

    JOINT = ("T1", "T2", "M0", "B0")


    def rows(simulator, **design):
        present = [name for name in JOINT if name in simulator.exposes]
        _, jacobian = simulator.jacobian(present, **design)
        placed = jacobian.new_zeros(jacobian.shape[:-2] + (len(JOINT), jacobian.shape[-1]))
        where = torch.tensor([JOINT.index(name) for name in present])
        return placed.index_copy(-2, where, jacobian)


    def bounds(spgr_flip, ssfp_flip):
        together = torch.cat(
            (rows(spgr, flip=spgr_flip), rows(ssfp, flip=ssfp_flip)), dim=-1
        )
        return blochsim.optim.crlb(together, noise_variance=NOISE**2)









.. GENERATED FROM PYTHON SOURCE LINES 142-146

Dividing each bound by its parameter squared makes the terms dimensionless, so
a T2 of 100 ms and a T1 of 1000 ms are weighted by how well they are known and
not by how large they are. The logarithm makes the gradient relative, so the
design does not depend on the noise level:

.. GENERATED FROM PYTHON SOURCE LINES 146-155

.. code-block:: Python



    def precision(spgr_flip, ssfp_flip):
        """Relative variance of T1 and T2, averaged over the design tissues."""
        bound = bounds(spgr_flip, ssfp_flip)
        relative = bound[..., 0] / T1_MS**2 + bound[..., 1] / T2_MS**2
        return relative.mean().log()









.. GENERATED FROM PYTHON SOURCE LINES 156-162

Design
------

The protocol has four scans of each kind, initialized with a spread of angles.
:class:`~blochsim.optim.Bounded` constrains each angle to the range the scanner
plays:

.. GENERATED FROM PYTHON SOURCE LINES 162-182

.. code-block:: Python

    spgr_start = torch.tensor([2.0, 4.0, 8.0, 16.0])
    ssfp_start = torch.tensor([10.0, 20.0, 40.0, 60.0])

    design = SequenceDesign(
        precision,
        spgr_flip=Bounded(spgr_start, 1.0, 40.0),
        ssfp_flip=Bounded(ssfp_start, 1.0, 70.0),
    )

    result = design.minimize(iterations=120, learning_rate=0.3)

    spgr_designed = result.parameters["spgr_flip"]
    ssfp_designed = result.parameters["ssfp_flip"]








.. GENERATED FROM PYTHON SOURCE LINES 183-185

The bound gives the standard deviation of each estimate, in percent of the
value itself:

.. GENERATED FROM PYTHON SOURCE LINES 185-202





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

 .. code-block:: none

    start              sigma(T1)/T1 = 11.0%, 12.9%   sigma(T2)/T2 = 10.1%, 12.1%
    designed           sigma(T1)/T1 = 7.4%, 8.9%   sigma(T2)/T2 = 7.4%, 9.1%
    designed in 4.2 s




.. GENERATED FROM PYTHON SOURCE LINES 203-208

Flip angles
-----------

The protocol has eight scans, four spoiled and four balanced, which differ
only in flip angle:

.. GENERATED FROM PYTHON SOURCE LINES 208-234




.. image-sg:: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_001.png
   :alt: SPGR block, bSSFP block
   :srcset: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 235-244

The design collapses the eight angles onto three and repeats them. The
information sits at a few places on each curve, and a fixed number of scans is
best placed there and not on an even sampling of the curve.

The SPGR angle lands above the Ernst angle of both tissues, where the curve
separates the two T1 values most sharply. The peak itself is where the signal
is largest and says least. The two bSSFP angles sit either side of the
steady-state maximum, which makes the pair sensitive to T2. The upper one is
against its limit and not at an interior optimum.

.. GENERATED FROM PYTHON SOURCE LINES 244-268




.. image-sg:: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_002.png
   :alt: SPGR, bSSFP, convergence
   :srcset: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 269-276

Phantom
-------

The phantom is BrainWeb subject 0, slice 90, the one the parameter-inference
examples map. Its fuzzy tissue memberships give a T1, a T2 and a proton
density at every voxel. You play both protocols on it and compare the fitted
maps with the truth.

.. GENERATED FROM PYTHON SOURCE LINES 276-317




.. image-sg:: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_003.png
   :alt: BrainWeb subject 0, slice 90
   :srcset: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 318-326

Joint fit
---------

The two blocks are one experiment, and you fit them as one. A
:class:`~blochsim.Simulator` plays each block and concatenates what they
record. The fit is the same for both protocols: bartorch's per-voxel
Levenberg-Marquardt, :func:`~bartorch.apps.mobafit`, over the same four
unknowns, from the same starting values:

.. GENERATED FROM PYTHON SOURCE LINES 326-353

.. code-block:: Python

    from bartorch import apps, nlop

    from blochsim import ModelOperator, Simulator


    class JointRelaxometry(Simulator):
        """Both blocks at fixed flip angles, as one signal model."""

        properties = ("T1", "T2", "M0", "B0")

        def __init__(self, spgr_flip, ssfp_flip):
            self.spoiled = SPGRSimulator(TE=2.0, TR=6.0, flip=spgr_flip)
            self.balanced = bSSFPSimulator(TE=2.5, TR=5.0, flip=ssfp_flip)

        def evaluate(self, properties, **sequence):
            T1, T2 = properties["T1"], properties["T2"]
            M0 = properties.get("M0", 1.0)
            B0 = properties.get("B0", 0.0)
            return torch.cat(
                (
                    self.spoiled.simulate(T1=T1, T2star=T2, M0=M0, B0=B0),
                    self.balanced.simulate(T1=T1, T2=T2, M0=M0, B0=B0),
                ),
                dim=-1,
            )









.. GENERATED FROM PYTHON SOURCE LINES 354-357

The noise is independent in the real and imaginary channels, each at the
standard deviation the bound was computed with. Simulate the slice with the
designed protocol, add the noise and fit every voxel:

.. GENERATED FROM PYTHON SOURCE LINES 357-404

.. code-block:: Python

    UNKNOWN = {
        "T1": (200.0, 5000.0),
        "T2": (20.0, 600.0),
        "M0": (0.1, 2.0),
        "B0": (-50.0, 50.0),
    }
    generator = torch.Generator().manual_seed(7)

    joint = JointRelaxometry(spgr_designed, ssfp_designed)

    clean = joint.simulate(B0=0.0, **truth)
    noise = torch.randn((2, *clean.shape), generator=generator, dtype=torch.float32)
    measured = clean + NOISE * torch.complex(noise[0], noise[1])

    START = {"T1": 1000.0, "T2": 100.0, "M0": 1.0, "B0": 0.0}


    def fitted(block, images):
        """Fit the four unknowns of every voxel, images given voxel by contrast."""
        model = nlop.ModelOperator(
            ModelOperator(block, *UNKNOWN, bounds=UNKNOWN, amplitude=False),
            (images.shape[0],),
        )
        return apps.mobafit(images.mT.contiguous(), model, **START)


    maps = fitted(joint, measured)  # {"T1": ..., "T2": ..., "M0": ..., "B0": ...}







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

 .. code-block:: none

    38980 joint fits in 4.8 s




.. GENERATED FROM PYTHON SOURCE LINES 405-411

Predicted precision
-------------------

The design bound was computed for two tissues. Evaluated at the relaxation
times of each voxel, it gives a map of the predicted precision, against which
the measured error is compared:

.. GENERATED FROM PYTHON SOURCE LINES 411-439

.. code-block:: Python



    def predicted_sigma(spgr_flip, ssfp_flip):
        """Relative standard deviation the bound allows, voxel by voxel."""
        at_voxel = tuple(
            sequence.bind(T1=truth["T1"], M0=1.0, B0=0.0, **{name: truth["T2"]})
            for sequence, name in (
                (SPGRSimulator(TE=2.0, TR=6.0), "T2star"),
                (bSSFPSimulator(TE=2.5, TR=5.0), "T2"),
            )
        )
        together = torch.cat(
            (rows(at_voxel[0], flip=spgr_flip), rows(at_voxel[1], flip=ssfp_flip)), dim=-1
        )
        bound = blochsim.optim.crlb(together, noise_variance=NOISE**2)
        return {
            "T1": bound[..., 0].sqrt() / truth["T1"],
            "T2": bound[..., 1].sqrt() / truth["T2"],
        }










.. GENERATED FROM PYTHON SOURCE LINES 440-446

No unbiased estimator beats the bound. The fit below lands about a fifth
above it for both protocols, so the reduction the bound predicts is also the
reduction measured, which is the check that the design optimized the right
quantity. Both are root-mean-square, because a bound is a standard
deviation. The median absolute error is about two thirds of a standard
deviation and would understate the error by that factor:

.. GENERATED FROM PYTHON SOURCE LINES 446-465





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

 .. code-block:: none


                                              T1                        T2
                           measured        bound     measured        bound
    start                     13.8%        11.3%        13.3%        10.6%
    designed                   9.8%         8.1%         9.8%         8.1%




.. GENERATED FROM PYTHON SOURCE LINES 466-471

Maps
----

The fitted maps and the absolute error of each protocol. The designed protocol
gives lower noise in both maps.

.. GENERATED FROM PYTHON SOURCE LINES 471-503




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


    *

      .. image-sg:: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_004.png
         :alt: truth, start, designed
         :srcset: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_004.png
         :class: sphx-glr-multi-img

    *

      .. image-sg:: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_005.png
         :alt: truth, start, designed
         :srcset: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_02-joint-relaxometry_005.png
         :class: sphx-glr-multi-img





.. GENERATED FROM PYTHON SOURCE LINES 504-528

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

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

.. code-block:: text

   With blochsim, design the flip angles of a joint DESPOT protocol: four
   SPGR scans (TE 2 ms, TR 6 ms, up to 40 degrees) and four bSSFP scans (TE
   2.5 ms, TR 5 ms, up to 70 degrees), for white and grey matter at 3 T.
   Estimate T1, T2, M0 and B0 jointly. Minimize the log of the summed
   relative Cramer-Rao bounds of T1 and T2 with SequenceDesign. Play the
   start and designed protocols on BrainWeb slice 90 with noise of 0.5 %,
   fit every voxel with bartorch's apps.mobafit, and compare the RMS error of
   the T1 and T2 maps with the bound.

References
----------

.. [1] Teixeira, R. P. A. G., Malik, S. J., Hajnal, J. V., "Joint system
   relaxometry (JSR) and Cramer-Rao lower bound optimization of sequence
   parameters: a framework for enhanced precision of DESPOT T1 and T2
   estimation", Magnetic Resonance in Medicine 79.1 (2018), pp. 234-245.
   https://doi.org/10.1002/mrm.26670


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

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


.. _sphx_glr_download_generated_autoexamples_03-sequence-optimization_02-joint-relaxometry.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/03-sequence-optimization/02-joint-relaxometry.ipynb
        :alt: Launch binder
        :width: 150 px

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

      :download:`Download Jupyter notebook: 02-joint-relaxometry.ipynb <02-joint-relaxometry.ipynb>`

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

      :download:`Download Python source code: 02-joint-relaxometry.py <02-joint-relaxometry.py>`

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

      :download:`Download zipped: 02-joint-relaxometry.zip <02-joint-relaxometry.zip>`


.. only:: html

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

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