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


=====================================
T2 mapping by nonlinear least squares
=====================================

You map T2 from a multi-echo spin echo by nonlinear least squares and compare
the result with dictionary matching on the same slice.

The comparison turns on a nuisance parameter. A magnitude reconstruction sits
on a noise floor, so the decay does not reach zero. Unlike the proton density,
this offset does not divide out of a normalized match: ignoring it biases T2,
and adding it to the dictionary multiplies the number of atoms. A fit instead
adds one column to the Jacobian, at the cost of no guarantee that it finds the
global minimum. blochsim supplies the model and its derivative; the fit is
`bartorch <https://github.com/pulserver/bartorch>`_'s ``apps.mobafit``.

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-134

.. code-block:: Python


    import numpy as np
    import torch

    from bartorch import apps, nlop

    from blochsim import ModelOperator
    from blochsim.estimators import DictionaryMatcher
    from blochsim.simulators import MultiEchoSimulator








.. GENERATED FROM PYTHON SOURCE LINES 135-143

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 T2 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 143-184

.. code-block:: Python


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




.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_001.png
   :alt: BrainWeb subject 0, slice 90
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 185-192

Measurement and noise floor
---------------------------

The sequence is a multi-echo spin echo with 16 echoes from 10 to 200 ms. The
signal is the proton density times the T2 decay, plus a constant offset. A
magnitude reconstruction rectifies the noise, so late echoes measure the
floor and not zero, and a fit that does not model it absorbs it into T2.

.. GENERATED FROM PYTHON SOURCE LINES 192-203

.. code-block:: Python

    ECHOES = 16
    TE = torch.linspace(10.0, 200.0, ECHOES)
    NOISE_STD = 0.005
    FLOOR = 0.05

    simulator = MultiEchoSimulator(TE=TE)

    clean = simulator.simulate(T2=truth, M0=density, offset=FLOOR)
    generator = torch.Generator().manual_seed(42)
    measured = clean + NOISE_STD * torch.randn(clean.shape, generator=generator)








.. GENERATED FROM PYTHON SOURCE LINES 204-206

The 70 ms decay approaches the floor only in the last echoes, where the
offset and T2 are hardest to separate; the long-T2 voxel never reaches it.

.. GENERATED FROM PYTHON SOURCE LINES 206-222




.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_002.png
   :alt: 03 nonlinear least squares
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 223-232

Nonlinear fit
-------------

A :class:`~blochsim.ModelOperator` declares the unknowns and the range of
each. The bounds are enforced by fitting a transformed variable, not by
clipping: no iterate leaves the interval and no bound is active at the
solution. The transformation also puts all parameters on a common scale,
which the damping assumes. M0 is one of the unknowns, so the operator carries
no separate complex amplitude.

.. GENERATED FROM PYTHON SOURCE LINES 232-237

.. code-block:: Python

    BOUNDS = {"T2": (10.0, 500.0), "M0": (0.1, 2.0), "offset": (0.0, 0.2)}
    START = {"T2": 100.0, "M0": 1.0, "offset": 0.02}

    operator = ModelOperator(simulator, *BOUNDS, bounds=BOUNDS, amplitude=False)








.. GENERATED FROM PYTHON SOURCE LINES 238-243

bartorch's :func:`~bartorch.apps.mobafit` fits it voxel by voxel by
Levenberg-Marquardt. All voxels are updated in the same pass; each carries its
own damping, accepts or rejects its own step, and stops when it converges.
:class:`bartorch.nlop.ModelOperator` carries the model on the voxel shape, and
the images go in with the echoes first:

.. GENERATED FROM PYTHON SOURCE LINES 243-292

.. code-block:: Python

    model = nlop.ModelOperator(operator, (measured.shape[0],))
    maps = apps.mobafit(
        measured.mT, model, **START
    )  # {"T2": ..., "M0": ..., "offset": ...}







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

 .. code-block:: none

    fitted floor, median 0.0500 against 0.05




.. GENERATED FROM PYTHON SOURCE LINES 293-300

Dictionary match
----------------

The same problem posed to a dictionary. A match normalizes both sides, so
any positive scale is free and M0 drops out of the grid. The offset survives
normalization, so modelling it requires putting it on the grid. The first
dictionary ignores the offset:

.. GENERATED FROM PYTHON SOURCE LINES 300-304

.. code-block:: Python

    T2_GRID = torch.logspace(1.0, np.log10(500.0), 400)

    match = DictionaryMatcher(simulator.bind(M0=1.0, offset=0.0)).fit(T2=T2_GRID, seed=0)








.. GENERATED FROM PYTHON SOURCE LINES 305-307

The second has the offset on the grid, which is then the product of the T2
and offset grids: 400 by 40 atoms.

.. GENERATED FROM PYTHON SOURCE LINES 307-342

.. code-block:: Python

    offsets = torch.linspace(0.0, 0.15, 40)
    grid_t2, grid_offset = torch.meshgrid(T2_GRID, offsets, indexing="ij")

    wide = DictionaryMatcher(simulator.bind(M0=1.0)).fit(
        T2=grid_t2.reshape(-1), offset=grid_offset.reshape(-1), seed=0
    )










.. GENERATED FROM PYTHON SOURCE LINES 343-350

Cost and accuracy
-----------------

Times are the best of three passes after a warm-up. *model* is the memory the
fitted estimator holds between volumes, none for a fit. *peak* is the maximum GPU memory
allocated while mapping the slice, blank on a machine without a GPU. The
error is the median relative T2 error over the brain voxels.

.. GENERATED FROM PYTHON SOURCE LINES 350-388





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

 .. code-block:: none


    method                           atoms   train     map     model      peak      T2
    ----------------------------------------------------------------------------------
    match, T2 only                     400    0.0s   0.01s   0.1 MiB        --   17.9%
    match, T2 x 10 offsets            4000    0.0s   0.07s   0.5 MiB        --    1.8%
    match, T2 x 20 offsets            8000    0.0s   0.14s   1.1 MiB        --    1.8%
    match, T2 x 40 offsets           16000    0.0s   0.28s   2.1 MiB        --    1.8%
    match, T2 x 80 offsets           32000    0.0s   0.57s   4.3 MiB        --    1.7%
    fit, T2 + M0, floor known           --    0.0s   0.68s   0.0 MiB        --    0.6%
    fit, T2 + M0 + offset               --    0.0s   1.15s   0.0 MiB        --    1.8%




.. GENERATED FROM PYTHON SOURCE LINES 389-406

Interpretation
--------------

The T2-only match is the fastest method here and the least accurate: the
model it matches is not the model that produced the data. The residual it
minimizes is small, at the wrong T2, and the estimator does not report the
mismatch.

With the offset on the grid the match recovers. The cost is the number of
offset values: ten values multiply the number of atoms and the memory by ten,
for a parameter that adds one column to the fit's Jacobian.

The fit is slower in wall-clock time, because a Levenberg-Marquardt loop takes
tens of passes where a match takes one. Each additional nuisance parameter
multiplies the number of atoms but adds one column to the Jacobian, so the
time curves cross at some number of nuisance values. The fit holds no table
between volumes at all, so its memory does not appear on the right.

.. GENERATED FROM PYTHON SOURCE LINES 406-435




.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_003.png
   :alt: time, memory
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 436-441

Maps
----

T2 from the match without the offset, the match with it, and the fit of all
three parameters, with the absolute error in the second row.

.. GENERATED FROM PYTHON SOURCE LINES 441-464




.. image-sg:: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_004.png
   :alt: truth, match, T2, match + offset, fit, all three
   :srcset: /generated/autoexamples/02-parameter-inference/images/sphx_glr_03-nonlinear-least-squares_004.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 465-494

Limits
------

The fit has no guarantee of reaching the global minimum. Here it started every
voxel at 100 ms and converged to the correct T2 everywhere, because the
residual of a single exponential decay has one minimum. A model whose
residual has several, such as a fingerprinting train or a fat-water fit at a
wrong field map, can start in the wrong basin and stay there. A match cannot,
because it scores every atom.

Equality constraints belong in the model, not in the bounds. Two fractions
that sum to one are written with one as the unknown and the other as ``1 - f``
inside the model, so the constraint holds at every iterate.

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

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

.. code-block:: text

   With blochsim and bartorch, map T2 in BrainWeb subject 0, slice 90, from a
   16-echo multi-echo spin echo (TE 10 to 200 ms) with a constant noise-floor
   offset of 0.05 and Gaussian noise of 0.005. Fit T2, M0 and the offset with
   bartorch's apps.mobafit over a blochsim ModelOperator (bounds T2 10-500 ms,
   M0 0.1-2, offset 0-0.2).
   Compare with a DictionaryMatcher over 400 log-spaced T2 values, without
   the offset and with 10 to 80 offset values on the grid. Report mapping
   time, estimator memory and median relative T2 error, and plot the maps.


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

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


.. _sphx_glr_download_generated_autoexamples_02-parameter-inference_03-nonlinear-least-squares.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/03-nonlinear-least-squares.ipynb
        :alt: Launch binder
        :width: 150 px

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

      :download:`Download Jupyter notebook: 03-nonlinear-least-squares.ipynb <03-nonlinear-least-squares.ipynb>`

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

      :download:`Download Python source code: 03-nonlinear-least-squares.py <03-nonlinear-least-squares.py>`

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

      :download:`Download zipped: 03-nonlinear-least-squares.zip <03-nonlinear-least-squares.zip>`


.. only:: html

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

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