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


=========================================
RF pulse design by optimal control
=========================================

In this example you design the samples of a slice-selective RF pulse by
gradient descent through a Bloch simulation of what they do [1]_. Across a body
at 3 T the transmit field B1 varies by about a fifth either way, and the flip
angle inside the slice varies with it. You reshape a 90 degree excitation so
that it stays close to 90 degrees over that range.

Prerequisites: Course lessons :doc:`../01-framework/01-first-simulation` and
:doc:`../01-framework/02-advanced-physics`.

.. [1] Conolly S, Nishimura D, Macovski A. Optimal control solutions to the
   magnetic resonance selective excitation problem. IEEE Trans Med Imaging
   1986;5(2):106-115.

.. GENERATED FROM PYTHON SOURCE LINES 21-26

.. colab-link::
   :needs_gpu: 0

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

.. GENERATED FROM PYTHON SOURCE LINES 26-37








.. GENERATED FROM PYTHON SOURCE LINES 38-49

Pulse and slice
---------------

The pulse has 128 samples. Under the slice-select gradient, each sample
rotates a spin at ``x`` slice thicknesses from the centre by
``2 pi TBW x / 128`` about z, where TBW is the time-bandwidth product. The
drive of each sample is in radians, so the design needs no raster and no
gradient amplitude: any pulse with this time-bandwidth product can play it.

The starting point is a Hamming-windowed sinc with the area of a 90 degree
flip. That is a small-tip design, played here at a large tip:

.. GENERATED FROM PYTHON SOURCE LINES 49-63

.. code-block:: Python

    import math

    import torch

    SAMPLES, TBW = 128, 4.0
    x = torch.linspace(-2.0, 2.0, 161, dtype=torch.float64)
    turn = 2 * math.pi * TBW / SAMPLES * x

    t = torch.arange(SAMPLES, dtype=torch.float64) - (SAMPLES - 1) / 2
    sinc = torch.sinc(TBW * t / SAMPLES) * (
        0.54 + 0.46 * torch.cos(2 * math.pi * t / SAMPLES)
    )
    start = sinc / sinc.sum() * (math.pi / 2)








.. GENERATED FROM PYTHON SOURCE LINES 64-71

Transmit field
--------------

Simulate every spin at five transmit scalings, from 0.8 to 1.2 of nominal.
``compose_spinor`` multiplies the rotations of all samples into one spinor
``(a, b)`` per spin, and the transverse magnetization after a pulse applied
to magnetization along +z is ``2 conj(a) b``:

.. GENERATED FROM PYTHON SOURCE LINES 71-83

.. code-block:: Python

    from blochsim import compose_spinor

    B1 = torch.tensor([0.8, 0.9, 1.0, 1.1, 1.2], dtype=torch.float64)


    def excited(real, imag):
        """|Mxy| after the pulse, shape (B1, x)."""
        drive = (real + 1j * imag)[:, None, None] * B1[None, :, None]
        a, b = compose_spinor(drive, turn.expand(len(B1), -1))
        return (2 * a.conj() * b).abs()









.. GENERATED FROM PYTHON SOURCE LINES 84-91

Cost
----

Inside the slice the magnetization should be fully transverse. Outside it
should be untouched. The transition band between them is left free. A small
penalty on the pulse energy prevents the optimizer from trading power for
flatness:

.. GENERATED FROM PYTHON SOURCE LINES 91-102

.. code-block:: Python

    inside = (x.abs() < 0.4).double()
    outside = (x.abs() > 0.75).double()


    def cost(real, imag):
        transverse = excited(real, imag)
        miss = inside * (transverse - 1.0) ** 2 + outside * transverse**2
        energy = (real**2 + imag**2).sum() / (start**2).sum()
        return miss.sum() / (inside.sum() + outside.sum()) / len(B1) + 1e-4 * energy









.. GENERATED FROM PYTHON SOURCE LINES 103-109

Optimization
------------

The real and imaginary parts of every sample are the design parameters, with
no limits. To respect the scanner's peak B1, you would wrap them in
:class:`~blochsim.optim.Bounded`:

.. GENERATED FROM PYTHON SOURCE LINES 109-139

.. code-block:: Python

    from blochsim.optim import SequenceDesign

    design = SequenceDesign(
        cost, real=start.clone(), imag=torch.zeros(SAMPLES, dtype=torch.float64)
    )
    result = design.minimize(iterations=100, learning_rate=2e-4)
    real, imag = result.parameters["real"], result.parameters["imag"]

    with torch.no_grad():
        before = excited(start, torch.zeros_like(start))
        after = excited(real, imag)





.. image-sg:: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_03-rf-pulse-design_001.png
   :alt: starting sinc, optimized, cost
   :srcset: /generated/autoexamples/03-sequence-optimization/images/sphx_glr_03-rf-pulse-design_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 140-143

Inside the slice, the flip now varies less across the transmit range, most of
all where B1 is low. Outside the slice the leakage stays at the level of the
sinc. Compare the mean :math:`|M_{xy}|` inside the slice at each B1:

.. GENERATED FROM PYTHON SOURCE LINES 143-148

.. code-block:: Python

    centre = inside.bool()
    for label, profile in (("starting sinc", before), ("optimized", after)):
        mean = profile[:, centre].mean(dim=1)
        print(f"{label:>14}: {[round(float(v), 3) for v in mean]}")





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

 .. code-block:: none

     starting sinc: [0.895, 0.94, 0.967, 0.976, 0.969]
         optimized: [0.945, 0.981, 0.996, 0.989, 0.963]




.. GENERATED FROM PYTHON SOURCE LINES 149-163

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

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

.. code-block:: text

   With blochsim, design a 128-sample slice-selective 90 degree excitation
   with time-bandwidth product 4, starting from a Hamming-windowed sinc.
   Simulate each spin at B1 scalings 0.8 to 1.2 with compose_spinor. Minimize
   the squared miss from |Mxy| = 1 inside the slice and 0 outside, plus a
   small energy penalty, with SequenceDesign over the real and imaginary
   parts of the samples. Report the mean |Mxy| in the slice at each B1,
   before and after.


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

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


.. _sphx_glr_download_generated_autoexamples_03-sequence-optimization_03-rf-pulse-design.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/03-rf-pulse-design.ipynb
        :alt: Launch binder
        :width: 150 px

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

      :download:`Download Jupyter notebook: 03-rf-pulse-design.ipynb <03-rf-pulse-design.ipynb>`

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

      :download:`Download Python source code: 03-rf-pulse-design.py <03-rf-pulse-design.py>`

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

      :download:`Download zipped: 03-rf-pulse-design.zip <03-rf-pulse-design.zip>`


.. only:: html

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

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