
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "generated/autoexamples/04-model-based-imaging/02-nonlinear-inversion.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_04-model-based-imaging_02-nonlinear-inversion.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_04-model-based-imaging_02-nonlinear-inversion.py:


================================
Nonlinear inversion from k-space
================================

In this Application you reconstruct T2 maps directly from k-space, with the
signal model inside the forward operator, and compare the result with gridding
followed by a fit.

The forward operator is the chain

.. math::

   F = P \, \mathcal{F} \, C \, M

of sampling :math:`P`, Fourier encoding :math:`\mathcal{F}`, coil sensitivities
:math:`C` and the signal model :math:`M` [1]_. Only :math:`M` changes with the
sequence, and it is the only factor blochsim supplies: a
:class:`~blochsim.ModelOperator` wraps any simulator as :math:`M`. The encoding
and the Gauss-Newton solver come from
`bartorch <https://github.com/pulserver/bartorch>`_. The problem is nonlinear
in the maps, so it needs a starting guess and an outer Gauss-Newton loop. In
exchange the model can have any number of parameters, where a linear subspace
would have to span the product of their ranges.

Prerequisites: Course lessons :doc:`../01-framework/01-first-simulation` and
:doc:`../01-framework/03-custom-signal-model`.

.. GENERATED FROM PYTHON SOURCE LINES 31-36

.. colab-link::
   :needs_gpu: 1

   !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 38-44

Setup
-----

blochsim simulates the signal. bartorch provides the non-uniform Fourier
transform, the nonlinear operator that carries the signal model into BART, and
the iteratively regularized Gauss-Newton solver.

.. GENERATED FROM PYTHON SOURCE LINES 44-104

.. code-block:: Python

    import time

    import numpy as np
    import torch

    from bartorch import linop, nlop

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









.. GENERATED FROM PYTHON SOURCE LINES 105-107

The experiment is a 96 x 96 matrix read as 16 radial spokes of 192 samples per
echo, with 8 echoes. The baseline estimator uses a rank-3 temporal basis.

.. GENERATED FROM PYTHON SOURCE LINES 107-119

.. code-block:: Python

    SIZE = 96
    ECHOES = 8
    SPOKES = 16
    SAMPLES = 192
    RANK = 3
    STEPS = 8  # Gauss-Newton iterations
    CG_ITERATIONS = 20  # conjugate-gradient iterations per linearized problem
    ALPHA = 1e-3  # initial damping, halved at every iteration

    # The simulation and the transform run on a GPU when one is available.
    device = "cuda" if torch.cuda.is_available() else "cpu"








.. GENERATED FROM PYTHON SOURCE LINES 120-127

Phantom
-------

The phantom is BrainWeb subject 0, slice 90, resampled to 96 x 96. BrainWeb
gives fuzzy tissue memberships, not labels. Weighting the tabulated T2 and
proton density of each tissue by its membership gives maps in which mixed
voxels lie between the pure tissues, known everywhere.

.. GENERATED FROM PYTHON SOURCE LINES 127-160








.. GENERATED FROM PYTHON SOURCE LINES 161-167

Sequence and sampling
---------------------

The sequence is a multi-echo spin echo with eight echoes from 10 to 150 ms.
Simulating it over the T2 map gives one image per echo, scaled by the proton
density:

.. GENERATED FROM PYTHON SOURCE LINES 167-175

.. code-block:: Python

    TE = torch.linspace(10.0, 150.0, ECHOES)
    simulator = MultiEchoSimulator(TE=TE)

    images = (
        torch.as_tensor(simulator.to(device).simulate(T2=T2_true)).to(torch.complex64)
        * M0_true.to(torch.complex64)[..., None]
    )








.. GENERATED FROM PYTHON SOURCE LINES 176-185

Each echo is sampled by 16 radial spokes, rotated by the golden angle from the
echo before, so the echoes together cover k-space more evenly than any one
does. 16 spokes across a 96-sample matrix is about ninefold undersampling,
which is where the reconstructions differ.

The trajectory is ``(echoes, spokes, samples, 2)`` in grid units. Each echo
has its own :class:`bartorch.linop.NUFFT` along its own spokes, and
:func:`bartorch.linop.block_diag` stacks them into one operator from the
``(echoes, y, x)`` images to the ``(echoes, spokes, samples)`` k-space:

.. GENERATED FROM PYTHON SOURCE LINES 185-200

.. code-block:: Python

    golden = torch.pi * (3.0 - 5.0**0.5)
    angle = golden * torch.arange(ECHOES * SPOKES).reshape(ECHOES, SPOKES, 1)
    radius = torch.linspace(-SIZE / 2, SIZE / 2, SAMPLES + 1)[:-1]
    trajectory = torch.stack(
        (radius * torch.cos(angle), radius * torch.sin(angle)), dim=-1
    ).to(device)

    encoding = linop.block_diag(
        [
            linop.NUFFT(trajectory[echo : echo + 1], image_shape=(1, SIZE, SIZE))
            for echo in range(ECHOES)
        ]
    )
    kspace = encoding(images.movedim(-1, 0).contiguous())








.. GENERATED FROM PYTHON SOURCE LINES 201-204

Gridding is the adjoint after a ramp density compensation. Scale the k-space
so that the gridded image peaks at one; the damping weights below are then
numbers about the model, not about the receiver gain:

.. GENERATED FROM PYTHON SOURCE LINES 204-236

.. code-block:: Python

    ramp = (radius.abs() + 0.5).to(device) / (SIZE / 2)
    gridded = encoding.H(kspace * ramp).movedim(0, -1)
    scale = float(gridded.abs().max())
    kspace, gridded = kspace / scale, gridded / scale





.. image-sg:: /generated/autoexamples/04-model-based-imaging/images/sphx_glr_02-nonlinear-inversion_001.png
   :alt: ground truth, proton density, 3 of 8 echoes
   :srcset: /generated/autoexamples/04-model-based-imaging/images/sphx_glr_02-nonlinear-inversion_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    16 spokes per echo: 9x undersampled




.. GENERATED FROM PYTHON SOURCE LINES 237-247

The maps are what both reconstructions below recover, and the spokes are all
that is measured of them.

Gridding baseline
-----------------

The baseline reconstructs the eight images and then fits them. The fit needs
an estimator, here a dictionary match over a rank-3 temporal basis, which
holds essentially all of an eight-echo exponential decay. The nonlinear
reconstruction has no such step, because its result is the maps.

.. GENERATED FROM PYTHON SOURCE LINES 247-277

.. code-block:: Python

    grid = torch.linspace(20.0, 400.0, 500)
    mapping = DictionaryMatcher(simulator).fit(T2=grid, M0=1.0, rank=RANK, seed=0)

    adjoint = mapping(gridded)["T2"]





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

 .. code-block:: none

    rank 3 of 8 keeps 0.999992 of the signal
    adjoint per echo       0.0s   T2 error  27.9 ms (20.3%)

    tensor([[ 48.9379,  20.7615,  32.1844,  ..., 164.6894, 400.0000, 400.0000],
            [ 87.0140,  54.2685,  61.8838,  ..., 400.0000, 400.0000, 400.0000],
            [400.0000,  90.8216,  39.0381,  ..., 400.0000, 120.5210,  84.7295],
            ...,
            [400.0000, 400.0000, 305.5711,  ...,  23.0461,  43.6072,  27.6152],
            [ 78.6373,  84.7295, 190.5812,  ...,  20.0000,  39.0381,  39.7996],
            [ 41.3226, 362.6854, 223.3266,  ...,  21.5230,  23.0461,  20.0000]])



.. GENERATED FROM PYTHON SOURCE LINES 278-296

Gridding is the adjoint with density compensation. 16 spokes of 192 samples are
3072 measurements per echo against 9216 unknowns, so each echo alone is
underdetermined and iterating per echo does not reduce the error. The
improvement has to come from a constraint across the echoes, which is the
signal model.

Signal model
------------

The model stays in the forward operator and the maps are solved for against
k-space. You declare two things:

- the unknowns: ``T2`` and the complex amplitude the operator carries with it,
  which combines proton density and receive phase;
- the range of T2. The bound is enforced by solving for a transformed
  variable, so no iterate leaves it. This matters more here than in a voxelwise
  fit, because the model is evaluated in every voxel to predict every k-space
  sample, and one unphysical voxel corrupts the whole residual.

.. GENERATED FROM PYTHON SOURCE LINES 296-298

.. code-block:: Python

    operator = ModelOperator(simulator.to(device), "T2", bounds={"T2": (20.0, 400.0)})








.. GENERATED FROM PYTHON SOURCE LINES 299-303

:class:`bartorch.nlop.ModelOperator` carries it into BART as a nonlinear
operator from ``(channels, y, x)`` maps to ``(echoes, y, x)`` images. The
amplitude starts from the first gridded echo, which costs nothing and makes the
first Gauss-Newton step well conditioned:

.. GENERATED FROM PYTHON SOURCE LINES 303-306

.. code-block:: Python

    M = nlop.ModelOperator(operator, (SIZE, SIZE))
    initial = M.initial(T2=100.0, amplitude=gridded[..., 0]).to(device)








.. GENERATED FROM PYTHON SOURCE LINES 307-315

Gauss-Newton solve
------------------

The forward operator is the composition ``encoding @ M``. Each iteration of
:class:`bartorch.nlop.IRGNM` linearizes it at the current maps, solves the
linearized least-squares problem by conjugate gradients and steps, then halves
the damping. blochsim provides the model and its derivative; the loop and the
encoding are BART's.

.. GENERATED FROM PYTHON SOURCE LINES 315-328

.. code-block:: Python


    solver = nlop.IRGNM(iterations=STEPS, alpha=ALPHA, cg_maxiter=CG_ITERATIONS)
    found = solver(kspace, encoding @ M, x0=initial)

    modelled = M.split(found)["T2"]






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

 .. code-block:: none

    model-based            4.9s   T2 error  11.6 ms ( 9.4%)

    tensor([[100.6599, 100.7362, 101.6446,  ..., 101.3332, 102.0920,  98.8412],
            [100.9760,  98.9134,  97.5945,  ..., 101.4106,  98.1081,  95.5713],
            [101.0719, 100.0212,  98.4344,  ..., 105.0602, 104.9652, 104.2936],
            ...,
            [101.5598, 101.8553, 101.8542,  ..., 100.2069, 102.2180, 100.3509],
            [100.4984, 100.6146, 101.2237,  ...,  99.1370, 104.5606, 106.4103],
            [100.9966, 100.9298, 101.3413,  ...,  94.5250,  98.9798, 104.0367]])



.. GENERATED FROM PYTHON SOURCE LINES 329-338

``found`` holds the solved variables and ``M.split`` separates them into named
maps. No fit follows.

Time and memory
---------------

Each conjugate-gradient step applies the Jacobian and its adjoint once. Each
product is one application of the encoding operator and one of the model.
Timing the four shows which part a faster reconstruction has to speed up.

.. GENERATED FROM PYTHON SOURCE LINES 338-375

.. code-block:: Python

    point = operator.initial((SIZE, SIZE), T2=100.0).to(device)
    tangent = torch.randn_like(point)
    predicted = operator.A_jvp(point, tangent)
    adjoint_image = encoding.H(kspace).movedim(0, -1)






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

 .. code-block:: none

    per conjugate-gradient step, 3 channels solved for:
      model    J  v      4.2 ms
      model    J^H v     1.7 ms
      encoding A         1.1 ms
      encoding A^H       1.1 ms
    the Jacobian this avoids holding: 1.7 MiB, against 0.6 MiB for a signal




.. GENERATED FROM PYTHON SOURCE LINES 376-384

The products do not build the Jacobian. Its blocks are voxels x channels x
contrasts, where a signal is voxels x contrasts, so avoiding it saves the
channel count times the signal size at every iteration.

Maps
----

The T2 maps use a perceptually uniform colormap reserved for T2 [2]_.

.. GENERATED FROM PYTHON SOURCE LINES 384-413




.. image-sg:: /generated/autoexamples/04-model-based-imaging/images/sphx_glr_02-nonlinear-inversion_002.png
   :alt: truth, adjoint, model-based
   :srcset: /generated/autoexamples/04-model-based-imaging/images/sphx_glr_02-nonlinear-inversion_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 414-448

Alternative signal model
------------------------

The model is the only part that names a relaxation time, and it is an ordinary
:class:`~blochsim.Simulator`, the object used in the fitting and design
Applications. Water-fat separation, T2* with a field map or a Look-Locker
inversion recovery each require a different simulator. The operator, the loop
and the encoding are unchanged.

References
----------

.. [1] Wang X, Tan Z, Scholand N, Roeloffs V, Uecker M. Physics-based
       reconstruction methods for magnetic resonance imaging. Phil Trans R Soc
       A 379:20200196 (2021).
.. [2] Fuderer M, et al. Recommended colour maps for relaxation parameter
       maps. Magn Reson Med (2025).

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

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

.. code-block:: text

   With blochsim and bartorch, simulate an 8-echo multi-echo spin echo (TE 10
   to 150 ms) on a BrainWeb T2 phantom of 96 x 96 voxels, sampled by 16
   golden-angle radial spokes per echo. Reconstruct T2 two ways: gridding
   followed by a dictionary match, and a blochsim ModelOperator over the
   simulator with T2 bounded to 20-400 ms, wrapped as bartorch's
   nlop.ModelOperator under linop.NUFFT and solved by nlop.IRGNM from a T2 of
   100 ms.
   Report time and mean T2 error over the brain, the time of each Jacobian
   product, and the size of the Jacobian that the operator avoids storing.


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

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


.. _sphx_glr_download_generated_autoexamples_04-model-based-imaging_02-nonlinear-inversion.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/04-model-based-imaging/02-nonlinear-inversion.ipynb
        :alt: Launch binder
        :width: 150 px

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

      :download:`Download Jupyter notebook: 02-nonlinear-inversion.ipynb <02-nonlinear-inversion.ipynb>`

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

      :download:`Download Python source code: 02-nonlinear-inversion.py <02-nonlinear-inversion.py>`

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

      :download:`Download zipped: 02-nonlinear-inversion.zip <02-nonlinear-inversion.zip>`


.. only:: html

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

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