% Copyright 2019 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\section{Tutorial: Euclid's Amber Version of the \emph{Elements}}

In this third tutorial we have a look at how \tikzname\ can be used to draw
geometric constructions.

Euclid is currently quite busy writing his new book series, whose working title
is ``Elements'' (Euclid is not quite sure whether this title will convey the
message of the series to future generations correctly, but he intends to change
the title before it goes to the publisher). Up to now, he wrote down his text
and graphics on papyrus, but his publisher suddenly insists that he must submit
in electronic form. Euclid tries to argue with the publisher that electronics
will only be discovered thousands of years later, but the publisher informs him
that the use of papyrus is no longer cutting edge technology and Euclid will
just have to keep up with modern tools.

Slightly disgruntled, Euclid starts converting his papyrus entitled ``Book I,
Proposition I'' to an amber version.

\subsection{Book I, Proposition I}

The drawing on his papyrus looks like this:\footnote{The text is taken from the
wonderful interactive version of Euclid's Elements by David E. Joyce, to be
found on his website at Clark University.}

\bigskip
\noindent
\begin{tikzpicture}[thick,help lines/.style={thin,draw=black!50}]
  \pgfmathsetseed{1}
  \def\A{\textcolor{input}{$A$}}
  \def\B{\textcolor{input}{$B$}}
  \def\C{\textcolor{output}{$C$}}
  \def\D{$D$}
  \def\E{$E$}

  \colorlet{input}{blue!80!black}
  \colorlet{output}{red!70!black}
  \colorlet{triangle}{orange}

  \coordinate [label=left:\A]
    (A) at ($ (0,0) + .1*(rand,rand) $);
  \coordinate [label=right:\B]
    (B) at ($ (1.25,0.25) + .1*(rand,rand) $);

  \draw [input] (A) -- (B);

  \node [name path=D,help lines,draw,label=left:\D] (D) at (A) [circle through=(B)] {};
  \node [name path=E,help lines,draw,label=right:\E] (E) at (B) [circle through=(A)] {};

  \path [name intersections={of=D and E,by={[label=above:\C]C}}];

  \draw [output] (A) -- (C);
  \draw [output] (B) -- (C);

  \foreach \point in {A,B,C}
    \fill [black,opacity=.5] (\point) circle (2pt);

  \begin{pgfonlayer}{background}
    \fill[triangle!80] (A) -- (C) -- (B) -- cycle;
  \end{pgfonlayer}

  \node [below right,text width=10cm,align=justify] at (4,3)
  {
    \small
    \textbf{Proposition I}\par
    \emph{To construct an \textcolor{triangle}{equilateral triangle}
      on a given \textcolor{input}{finite straight line}.}
    \par
    \vskip1em
    Let \A\B\ be the given \textcolor{input}{finite straight line}. It
    is required to construct an \textcolor{triangle}{equilateral
      triangle} on the \textcolor{input}{straight line}~\A\B.

    Describe the circle \B\C\D\ with center~\A\ and radius \A\B. Again
    describe the circle \A\C\E\ with center~\B\ and radius \B\A. Join the
    \textcolor{output}{straight lines} \C\A\ and \C\B\ from the
    point~\C\ at which the circles cut one another to the points~\A\ and~\B.

    Now, since the point~\A\ is the center of the circle \C\D\B,
    therefore \A\C\ equals \A\B. Again, since the point \B\ is the
    center of the circle \C\A\E, therefore \B\C\ equals \B\A. But
    \A\C\ was proved equal to \A\B, therefore each of the straight
    lines \A\C\ and \B\C\ equals \A\B. And
    things which equal the same thing also equal one another,
    therefore \A\C\ also equals \B\C. Therefore the three straight
    lines \A\C, \A\B, and \B\C\ equal one another.
    Therefore the \textcolor{triangle}{triangle} \A\B\C\ is
    equilateral, and it has been  constructed on the given finite
    \textcolor{input}{straight line}~\A\B.
  };
\end{tikzpicture}
\bigskip

Let us have a look at how Euclid can turn this into \tikzname\ code.

\subsubsection{Setting up the Environment}

As in the previous tutorials, Euclid needs to load \tikzname, together with
some libraries. These libraries are |calc|, |intersections|, |through|, and
|backgrounds|. Depending on which format he uses, Euclid would use one of the
following in the preamble:
%
\begin{codeexample}[code only]
% For LaTeX:
\usepackage{tikz}
\usetikzlibrary{calc,intersections,through,backgrounds}
\end{codeexample}

\begin{codeexample}[code only]
% For plain TeX:
\input tikz.tex
\usetikzlibrary{calc,intersections,through,backgrounds}
\end{codeexample}

\begin{codeexample}[code only]
% For ConTeXt:
\usemodule[tikz]
\usetikzlibrary[calc,intersections,through,backgrounds]
\end{codeexample}

\subsubsection{The Line \emph{AB}}

The first part of the picture that Euclid wishes to draw is the line $AB$. That
is easy enough, something like |\draw (0,0) -- (2,1);| might do. However,
Euclid does not wish to reference the two points $A$ and $B$ as $(0,0)$ and
$(2,1)$ subsequently. Rather, he wishes to just write |A| and |B|. Indeed, the
whole point of his book is that the points $A$ and $B$ can be arbitrary and all
other points (like $C$) are constructed in terms of their positions. It would
not do if Euclid were to write down the coordinates of $C$ explicitly.

So, Euclid starts with defining two coordinates using the |\coordinate|
command:
%
\begin{codeexample}[]
\begin{tikzpicture}
  \coordinate (A) at (0,0);
  \coordinate (B) at (1.25,0.25);

  \draw[blue] (A) -- (B);
\end{tikzpicture}
\end{codeexample}

That was easy enough. What is missing at this point are the labels for the
coordinates. Euclid does not want them \emph{on} the points, but next to them.
He decides to use the |label| option:
%
\begin{codeexample}[]
\begin{tikzpicture}
  \coordinate [label=left:\textcolor{blue}{$A$}]  (A) at (0,0);
  \coordinate [label=right:\textcolor{blue}{$B$}] (B) at (1.25,0.25);

  \draw[blue] (A) -- (B);
\end{tikzpicture}
\end{codeexample}

At this point, Euclid decides that it would be even nicer if the points $A$ and
$B$ were in some sense ``random''. Then, neither Euclid nor the reader can make
the mistake of taking ``anything for granted'' concerning these position of
these points. Euclid is pleased to learn that there is a |rand| function in
\tikzname\ that does exactly what he needs: It produces a number between $-1$
and $1$. Since \tikzname\ can do a bit of math, Euclid can change the
coordinates of the points as follows:
%
\begin{codeexample}[code only]
\coordinate [...] (A) at (0+0.1*rand,0+0.1*rand);
\coordinate [...] (B) at (1.25+0.1*rand,0.25+0.1*rand);
\end{codeexample}

This works fine. However, Euclid is not quite satisfied since he would prefer
that the ``main coordinates'' $(0,0)$ and $(1.25,0.25)$ are ``kept separate''
from the perturbation $0.1(\mathit{rand},\mathit{rand})$. This means, he would
like to specify that coordinate $A$ as ``the point that is at $(0,0)$ plus one
tenth of the vector  $(\mathit{rand},\mathit{rand})$''.

It turns out that the |calc| library allows him to do exactly this kind of
computation. When this library is loaded, you can use special coordinates that
start with |($| and end with |$)| rather than just |(| and~|)|. Inside these
special coordinates you can give a linear combination of coordinates. (Note
that the dollar signs are only intended to signal that a ``computation'' is
going on; no mathematical typesetting is done.)

The new code for the coordinates is the following:
%
\begin{codeexample}[code only]
\coordinate [...] (A) at ($ (0,0) + .1*(rand,rand) $);
\coordinate [...] (B) at ($ (1.25,0.25) + .1*(rand,rand) $);
\end{codeexample}

Note that if a coordinate in such a computation has a factor (like |.1|), you
must place a |*| directly before the opening parenthesis of the coordinate. You
can nest such computations.

\subsubsection{The Circle Around \emph{A}}

The first tricky construction is the circle around~$A$. We will see later how
to do this in a very simple manner, but first let us do it the ``hard'' way.

The idea is the following: We draw a circle around the point $A$ whose radius
is given by the length of the line $AB$. The difficulty lies in computing the
length of this line.

Two ideas ``nearly'' solve this problem: First, we can write |($ (A) - (B) $)|
for the vector that is the difference between $A$ and~$B$. All we need is the
length of this vector. Second, given two numbers $x$ and $y$, one can write
|veclen(|$x$|,|$y$|)| inside a mathematical expression. This gives the value
$\sqrt{x^2+y^2}$, which is exactly the desired length.

The only remaining problem is to access the $x$- and $y$-coordinate of the
vector~$AB$. For this, we need a new concept: the \emph{let operation}. A let
operation can be given anywhere on a path where a normal path operation like a
line-to or a move-to is expected. The effect of a let operation is to evaluate
some coordinates and to assign the results to special macros. These macros make
it easy to access the $x$- and $y$-coordinates of the coordinates.

Euclid would write the following:
%
\begin{codeexample}[preamble={\usetikzlibrary{calc}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);

  \draw (A) let
              \p1 = ($ (B) - (A) $)
            in
              circle ({veclen(\x1,\y1)});
\end{tikzpicture}
\end{codeexample}

Each assignment in a let operation starts with |\p|, usually followed by a
\meta{digit}. Then comes an equal sign and a coordinate. The coordinate is
evaluated and the result is stored internally. From then on you can use the
following expressions:
%
\begin{enumerate}
    \item |\x|\meta{digit} yields the $x$-coordinate of the resulting point.
    \item |\y|\meta{digit} yields the $y$-coordinate of the resulting point.
    \item |\p|\meta{digit} yields the same as
        |\x|\meta{digit}|,\y|\meta{digit}.
\end{enumerate}
%
You can have multiple assignments in a let operation, just separate them with
commas. In later assignments you can already use the results of earlier
assignments.

Note that |\p1| is not a coordinate in the usual sense. Rather, it just expands
to a string like |10pt,20pt|. So, you cannot write, for instance,
|(\p1.center)| since this would just expand to |(10pt,20pt.center)|, which
makes no sense.

Next, we want to draw both circles at the same time. Each time the radius is
|veclen(\x1,\y1)|. It seems natural to compute this radius only once. For this,
we can also use a let operation: Instead of writing |\p1 = ...|, we write
|\n2 = ...|. Here, ``n'' stands for ``number'' (while ``p'' stands for
``point''). The assignment of a number should be followed by a number in curly
braces.
%
\begin{codeexample}[preamble={\usetikzlibrary{calc}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);

  \draw let \p1 = ($ (B) - (A) $),
            \n2 = {veclen(\x1,\y1)}
        in
          (A) circle (\n2)
          (B) circle (\n2);
\end{tikzpicture}
\end{codeexample}
%
In the above example, you may wonder, what |\n1| would yield? The answer is
that it would be undefined -- the |\p|, |\x|, and |\y| macros refer to the same
logical point, while the |\n| macro has ``its own namespace''. We could even
have replaced |\n2| in the example by |\n1| and it would still work. Indeed,
the digits following these macros are just normal \TeX\ parameters. We could
also use a longer name, but then we have to use curly braces:
%
\begin{codeexample}[preamble={\usetikzlibrary{calc}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);

  \draw let \p1        = ($ (B) - (A) $),
            \n{radius} = {veclen(\x1,\y1)}
        in
          (A) circle (\n{radius})
          (B) circle (\n{radius});
\end{tikzpicture}
\end{codeexample}

At the beginning of this section it was promised that there is an easier way to
create the desired circle. The trick is to use the |through| library. As the
name suggests, it contains code for creating shapes that go through a given
point.

The option that we are looking for is |circle through|. This option is given to
a \emph{node} and has the following effects: First, it causes the node's inner
and outer separations to be set to zero. Then it sets the shape of the node to
|circle|. Finally, it sets the radius of the node such that it goes through the
parameter given to |circle through|. This radius is computed in essentially the
same way as above.
%
\begin{codeexample}[preamble={\usetikzlibrary{through}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);

  \node [draw,circle through=(B),label=left:$D$] at (A) {};
\end{tikzpicture}
\end{codeexample}

\subsubsection{The Intersection of the Circles}

Euclid can now draw the line and the circles. The final problem is to compute
the intersection of the two circles. This computation is a bit involved if you
want to do it ``by hand''. Fortunately, the |intersections| library allows us
to compute the intersection of arbitrary paths.

The idea is simple: First, you ``name'' two paths using the |name path| option.
Then, at some later point, you can use the option |name intersections|, which
creates coordinates called |intersection-1|, |intersection-2|, and so on at all
intersections of the paths. Euclid assigns the names |D| and |E| to the paths
of the two circles (which happen to be the same names as the nodes themselves,
but nodes and their paths live in different ``namespaces'').
%
\begin{codeexample}[preamble={\usetikzlibrary{intersections,through}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);

  \node (D) [name path=D,draw,circle through=(B),label=left:$D$]  at (A) {};
  \node (E) [name path=E,draw,circle through=(A),label=right:$E$] at (B) {};

  % Name the coordinates, but do not draw anything:
  \path [name intersections={of=D and E}];

  \coordinate [label=above:$C$] (C) at (intersection-1);

  \draw [red] (A) -- (C);
  \draw [red] (B) -- (C);
\end{tikzpicture}
\end{codeexample}

It turns out that this can be further shortened: The |name intersections| takes
an optional argument |by|, which lets you specify names for the coordinates and
options for them. This creates more compact code. Although Euclid does not need
it for the current picture, it is just a small step to computing the bisection
of the line $AB$:
%
\begin{codeexample}[preamble={\usetikzlibrary{intersections,through}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw [name path=A--B] (A) -- (B);

  \node (D) [name path=D,draw,circle through=(B),label=left:$D$]  at (A) {};
  \node (E) [name path=E,draw,circle through=(A),label=right:$E$] at (B) {};

  \path [name intersections={of=D and E, by={[label=above:$C$]C, [label=below:$C'$]C'}}];

  \draw [name path=C--C',red] (C) -- (C');

  \path [name intersections={of=A--B and C--C',by=F}];
  \node [fill=red,inner sep=1pt,label=-45:$F$] at (F) {};
\end{tikzpicture}
\end{codeexample}

\subsubsection{The Complete Code}

Back to Euclid's code. He introduces a few macros to make life simpler, like a
|\A| macro for typesetting a blue $A$. He also uses the |background| layer for
drawing the triangle behind everything at the end.
%
\begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{backgrounds,calc,intersections,through}}]
\begin{tikzpicture}[thick,help lines/.style={thin,draw=black!50}]
  \def\A{\textcolor{input}{$A$}}     \def\B{\textcolor{input}{$B$}}
  \def\C{\textcolor{output}{$C$}}    \def\D{$D$}
  \def\E{$E$}

  \colorlet{input}{blue!80!black}    \colorlet{output}{red!70!black}
  \colorlet{triangle}{orange}

  \coordinate [label=left:\A]  (A) at ($ (0,0) + .1*(rand,rand) $);
  \coordinate [label=right:\B] (B) at ($ (1.25,0.25) + .1*(rand,rand) $);

  \draw [input] (A) -- (B);

  \node [name path=D,help lines,draw,label=left:\D]   (D) at (A) [circle through=(B)] {};
  \node [name path=E,help lines,draw,label=right:\E]  (E) at (B) [circle through=(A)] {};

  \path [name intersections={of=D and E,by={[label=above:\C]C}}];

  \draw [output] (A) -- (C) -- (B);

  \foreach \point in {A,B,C}
    \fill [black,opacity=.5] (\point) circle (2pt);

  \begin{pgfonlayer}{background}
    \fill[triangle!80] (A) -- (C) -- (B) -- cycle;
  \end{pgfonlayer}

  \node [below right, text width=10cm,align=justify] at (4,3) {
    \small\textbf{Proposition I}\par
    \emph{To construct an \textcolor{triangle}{equilateral triangle}
      on a given \textcolor{input}{finite straight line}.}
    \par\vskip1em
    Let \A\B\ be the given \textcolor{input}{finite straight line}.  \dots
  };
\end{tikzpicture}
\end{codeexample}

\subsection{Book I, Proposition II}

The second proposition in the Elements is the following:

\bigskip\noindent
\begin{tikzpicture}[thick,help lines/.style={thin,draw=black!50}]
  \pgfmathsetseed{1}
  \def\A{\textcolor{orange}{$A$}}   \def\B{\textcolor{input}{$B$}}
  \def\C{\textcolor{input}{$C$}}    \def\D{$D$}
  \def\E{$E$}                       \def\F{$F$}
  \def\G{$G$}                       \def\H{$H$}
  \def\K{$K$}                       \def\L{\textcolor{output}{$L$}}

  \colorlet{input}{blue!80!black}    \colorlet{output}{red!70!black}

  \coordinate [label=left:\A]  (A) at ($ (0,0) + .1*(rand,rand) $);
  \coordinate [label=right:\B] (B) at ($ (1,0.2) + .1*(rand,rand) $);
  \coordinate [label=above:\C] (C) at ($ (1,2) + .1*(rand,rand) $);

  \draw [input] (B) -- (C);
  \draw [help lines] (A) -- (B);

  \coordinate [label=above:\D] (D) at ($ (A)!.5!(B) ! {sin(60)*2} ! 90:(B) $);

  \draw [help lines] (D) -- ($ (D)!3.75!(A) $) coordinate [label=-135:\E] (E);
  \draw [help lines] (D) -- ($ (D)!3.75!(B) $) coordinate [label=-45:\F] (F);

  \node (H) at (B) [name path=H,help lines,circle through=(C),draw,label=135:\H] {};
  \path [name path=B--F] (B) -- (F);
  \path [name intersections={of=H and B--F}]
    coordinate [label=right:\G] (G) at (intersection-1);

  \node (K) at (D) [name path=K,help lines,circle through=(G),draw,label=135:\K] {};

  \path [name path=A to E line] (A) -- (E);
  \path [name intersections={of=K and A to E line}]
    coordinate [label=below:\L] (L) at (intersection-1);

  \draw [output] (A) -- (L);

  \foreach \point in {A,B,C,D,G,L}
    \fill [black,opacity=.5] (\point) circle (2pt);

  \node [below right, text width=9cm,align=justify] at (4,4) {
    \small\textbf{Proposition II}\par
    \emph{To place a \textcolor{output}{straight line} equal to a
      given \textcolor{input}{straight line} with
      one end at a \textcolor{orange}{given point}.}
    \par\vskip1em
    Let \A\ be the given point, and \B\C\ the given
    \textcolor{input}{straight line}.
    It is required to place a \textcolor{output}{straight line} equal
    to the given \textcolor{input}{straight line} \B\C\ with one end
    at the point~\A.

    Join the straight line \A\B\ from the point \A\ to the point \B, and
    construct the equilateral triangle \D\A\B\ on it.

    Produce the straight lines \A\E\ and \B\F\ in a straight line with
    \D\A\ and \D\B. Describe the circle \C\G\H\ with center \B\ and
    radius \B\C, and  again, describe the circle \G\K\L\ with center
    \D\ and radius \D\G.

    Since the point \B\ is the center of the circle \C\G\H, therefore
    \B\C\ equals \B\G. Again, since the point \D\ is the center of the
    circle \G\K\L, therefore \D\L\ equals \D\G. And in these \D\A\
    equals \D\B, therefore the remainder \A\L\ equals the remainder
    \B\G. But \B\C\ was also proved  equal to \B\G, therefore each of
    the straight lines \A\L\ and \B\C\ equals \B\G. And things which
    equal the same thing also equal one another, therefore \A\L\ also
    equals \B\C.

    Therefore the \textcolor{output}{straight line} \A\L\ equal to the
    given \textcolor{input}{straight line} \B\C\  has been placed with
    one end at the \textcolor{orange}{given point}~\A.
  };
\end{tikzpicture}

\subsubsection{Using Partway Calculations for the Construction of \emph{D}}

Euclid's construction starts with ``referencing'' Proposition~I for the
construction of the point~$D$. Now, while we could simply repeat the
construction, it seems a bit bothersome that one has to draw all these circles
and do all these complicated constructions.

For this reason, \tikzname\ supports some simplifications. First, there is a
simple syntax for computing a point that is ``partway'' on a line from $p$
to~$q$: You place these two points in a coordinate calculation -- remember,
they start with |($| and end with |$)| -- and then combine them using
|!|\meta{part}|!|. A \meta{part} of |0| refers to the \emph{first} coordinate,
a \meta{part} of |1| refers to the second coordinate, and a value in between
refers to a point on the line from $p$ to~$q$. Thus, the syntax is similar to
the |xcolor| syntax for mixing colors.

Here is the computation of the point in the middle of the line $AB$:
%
\begin{codeexample}[preamble={\usetikzlibrary{calc}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);
  \node [fill=red,inner sep=1pt,label=below:$X$] (X) at ($ (A)!.5!(B) $) {};
\end{tikzpicture}
\end{codeexample}

The computation of the point $D$ in Euclid's second proposition is a bit more
complicated. It can be expressed as follows: Consider the line from $X$ to $B$.
Suppose we rotate this line around $X$ for 90$^\circ$ and then stretch it by a
factor of $\sin(60^\circ) \cdot 2$. This yields the desired point~$D$. We can
do the stretching using the partway modifier above, for the rotation we need a
new modifier: the rotation modifier. The idea is that the second coordinate in
a partway computation can be prefixed by an angle. Then the partway point is
computed normally (as if no angle were given), but the resulting point is
rotated by this angle around the first point.
%
\begin{codeexample}[preamble={\usetikzlibrary{calc}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);
  \node [fill=red,inner sep=1pt,label=below:$X$] (X) at ($ (A)!.5!(B) $) {};
  \node [fill=red,inner sep=1pt,label=above:$D$] (D) at
    ($ (X) ! {sin(60)*2} ! 90:(B) $) {};
  \draw (A) -- (D) -- (B);
\end{tikzpicture}
\end{codeexample}

Finally, it is not necessary to explicitly name the point $X$. Rather, again
like in the |xcolor| package, it is possible to chain partway modifiers:
%
\begin{codeexample}[preamble={\usetikzlibrary{calc}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (1.25,0.25);
  \draw (A) -- (B);
  \node [fill=red,inner sep=1pt,label=above:$D$] (D) at
    ($ (A) ! .5 ! (B) ! {sin(60)*2} ! 90:(B) $) {};
  \draw (A) -- (D) -- (B);
\end{tikzpicture}
\end{codeexample}

\subsubsection{Intersecting a Line and a Circle}

The next step in the construction is to draw a circle around $B$ through $C$,
which is easy enough to do using the |circle through| option. Extending the
lines $DA$ and $DB$ can be done using partway calculations, but this time with
a part value outside the range $[0,1]$:
%
\begin{codeexample}[preamble={\usetikzlibrary{calc,through}}]
\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (0.75,0.25);
  \coordinate [label=above:$C$] (C) at (1,1.5);
  \draw (A) -- (B) -- (C);
  \coordinate [label=above:$D$] (D) at
    ($ (A) ! .5 ! (B) ! {sin(60)*2} ! 90:(B) $) {};
  \node (H) [label=135:$H$,draw,circle through=(C)] at (B) {};
  \draw (D) -- ($ (D) ! 3.5 ! (B) $) coordinate [label=below:$F$] (F);
  \draw (D) -- ($ (D) ! 2.5 ! (A) $) coordinate [label=below:$E$] (E);
\end{tikzpicture}
\end{codeexample}

We now face the problem of finding the point $G$, which is the intersection of
the line $BF$ and the circle $H$. One way is to use yet another variant of the
partway computation: Normally, a partway computation has the form
\meta{p}|!|\meta{factor}|!|\meta{q}, resulting in the point
$(1-\meta{factor})\meta{p} + \meta{factor}\meta{q}$. Alternatively, instead of
\meta{factor} you can also use a \meta{dimension} between the points. In this
case, you get the point that is \meta{dimension} away from \meta{p} on the
straight line to \meta{q}.

We know that the point $G$ is on the way from $B$ to $F$. The distance is given
by the radius of the circle~$H$. Here is the code for computing $H$:
%
{\ifpgfmanualexternalize\tikzexternaldisable\fi
\begin{codeexample}[
    preamble={\usetikzlibrary{calc,through}},
    pre={\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (0.75,0.25);
  \coordinate [label=above:$C$] (C) at (1,1.5);
  \draw (A) -- (B) -- (C);
  \coordinate [label=above:$D$] (D) at
    ($ (A) ! .5 ! (B) ! {sin(60)*2} ! 90:(B) $) {};
  \draw (D) -- ($ (D) ! 3.5 ! (B) $) coordinate [label=below:$F$] (F);
  \draw (D) -- ($ (D) ! 2.5 ! (A) $) coordinate [label=below:$E$] (E);},
    post={\end{tikzpicture}},
]
  \node (H) [label=135:$H$,draw,circle through=(C)] at (B) {};
  \path let \p1 = ($ (B) - (C) $) in
    coordinate [label=left:$G$] (G) at ($ (B) ! veclen(\x1,\y1) ! (F) $);
  \fill[red,opacity=.5] (G) circle (2pt);
\end{codeexample}

However, there is a simpler way: We can simply name the path of the circle and
of the line in question and then use |name intersections| to compute the
intersections.
%
\begin{codeexample}[
    preamble={\usetikzlibrary{calc,intersections,through}},
    pre={\begin{tikzpicture}
  \coordinate [label=left:$A$]  (A) at (0,0);
  \coordinate [label=right:$B$] (B) at (0.75,0.25);
  \coordinate [label=above:$C$] (C) at (1,1.5);
  \draw (A) -- (B) -- (C);
  \coordinate [label=above:$D$] (D) at
    ($ (A) ! .5 ! (B) ! {sin(60)*2} ! 90:(B) $) {};
  \draw (D) -- ($ (D) ! 3.5 ! (B) $) coordinate [label=below:$F$] (F);
  \draw (D) -- ($ (D) ! 2.5 ! (A) $) coordinate [label=below:$E$] (E);},
    post={\end{tikzpicture}},
]
  \node (H) [name path=H,label=135:$H$,draw,circle through=(C)] at (B) {};
  \path [name path=B--F] (B) -- (F);
  \path [name intersections={of=H and B--F,by={[label=left:$G$]G}}];
  \fill[red,opacity=.5] (G) circle (2pt);
\end{codeexample}
}%

\subsubsection{The Complete Code}

\begin{codeexample}[pre={\pgfmathsetseed{1}},preamble={\usetikzlibrary{calc,intersections,through}}]
\begin{tikzpicture}[thick,help lines/.style={thin,draw=black!50}]
  \def\A{\textcolor{orange}{$A$}}   \def\B{\textcolor{input}{$B$}}
  \def\C{\textcolor{input}{$C$}}    \def\D{$D$}
  \def\E{$E$}                       \def\F{$F$}
  \def\G{$G$}                       \def\H{$H$}
  \def\K{$K$}                       \def\L{\textcolor{output}{$L$}}

  \colorlet{input}{blue!80!black}    \colorlet{output}{red!70!black}

  \coordinate [label=left:\A]  (A) at ($ (0,0) + .1*(rand,rand) $);
  \coordinate [label=right:\B] (B) at ($ (1,0.2) + .1*(rand,rand) $);
  \coordinate [label=above:\C] (C) at ($ (1,2) + .1*(rand,rand) $);

  \draw [input] (B) -- (C);
  \draw [help lines] (A) -- (B);

  \coordinate [label=above:\D] (D) at ($ (A)!.5!(B) ! {sin(60)*2} ! 90:(B) $);

  \draw [help lines] (D) -- ($ (D)!3.75!(A) $) coordinate [label=-135:\E] (E);
  \draw [help lines] (D) -- ($ (D)!3.75!(B) $) coordinate [label=-45:\F] (F);

  \node (H) at (B) [name path=H,help lines,circle through=(C),draw,label=135:\H] {};
  \path [name path=B--F] (B) -- (F);
  \path [name intersections={of=H and B--F,by={[label=right:\G]G}}];

  \node (K) at (D) [name path=K,help lines,circle through=(G),draw,label=135:\K] {};
  \path [name path=A--E] (A) -- (E);
  \path [name intersections={of=K and A--E,by={[label=below:\L]L}}];

  \draw [output] (A) -- (L);

  \foreach \point in {A,B,C,D,G,L}
    \fill [black,opacity=.5] (\point) circle (2pt);

  % \node ...
\end{tikzpicture}
\end{codeexample}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 2003-2018 by The University of Queensland
% http://www.uq.edu.au
%
% Primary Business: Queensland, Australia
% Licensed under the Apache License, version 2.0
% http://www.apache.org/licenses/LICENSE-2.0
%
% Development until 2012 by Earth Systems Science Computational Center (ESSCC)
% Development 2012-2013 by School of Earth Sciences
% Development from 2014 by Centre for Geoscience Computing (GeoComp)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Point Sources}
\label{POINT SOURCES}
In the chapter we will show the usage of point sources and sinks.
A simple example is a block of material with heat source at a location
$p$ and heat sink at a location $q$. Under the assumption of a constant
conductivity the steady heat diffusion equation for the temperature $u$
is given as
\begin{equation}
        -u_{,ii} = s(p_{in}) \; \delta_{p_{in}} + s(p_1) \; \delta_{p_1}
        \label{EX:DIRAC1}
\end{equation}
where $\delta_{p_{in}}$ and $\delta_{p_{out}}$ refer to the Dirac $\delta$-function and
$s({p_{in}})$ and $s({p_{out}})$ define the heat production and heat extraction rates at
locations ${p_{in}}$ and ${p_{out}}$, respectively.

First the locations of  point sources and sinks need to be added to the
domain. This is done at generation time:
\begin{python}
mydomain=Rectangle(30,30, l0=3, l1=2,
                diracPoints=[(1.,1.), (2.,1.)],  diracTags=['in', 'out'])
\end{python}
In this case the points are located at $p_{in}=(1.,1.)$ and $p_{out}=(2.,1.)$.
For easier reference the points are tagged with the name \var{in} and \var{out}.

The values at the point source locations are defined using a \Data object. One possible
way to define the values at the locations defined through the \var{diracPoint} list is using tagging:
\begin{python}
s=Scalar(0., DiracDeltaFunctions(mydomain))
s.setTaggedValue('in', +1.)
s.setTaggedValue('out', -1.)
\end{python}
Here we set value $1$ at locations tagged with \var{in} (in this case this is just point $p_{in}=(1.,1.)$ ) and value $-1$ at locations tagged with \var{out} (in this case this is just point $p_{out}=(2.,1.)$). The point source in the right hande side of the PDE~\eqn{EX:DIRAC1} is then set as
\begin{python}
mypde = LinearSinglePDE(domain=mydomain)
mypde.setValue(y_dirac=s)
\end{python}
Under the assumption that we fix the temperature to zero on the entire boundary
the script to solve the PDE is given as follows:
\begin{python}
from esys.escript import *
from esys.weipa import *
from esys.finley import Rectangle
from esys.escript.linearPDEs import LinearSinglePDE

mydomain=Rectangle(30,30, l0=3, l1=2,
                diracPoints=[(1.,1.), (2.,1.)],  diracTags=['in', 'out'])
x = mydomain.getX()
gammaD = whereZero(x[0])+whereZero(x[1])+whereZero(x[0]-3.)+whereZero(x[1]-2.)

s=Scalar(0., DiracDeltaFunctions(mydomain))
s.setTaggedValue('in', +1.)
s.setTaggedValue('out', -1.)

mypde = LinearSinglePDE(domain=mydomain)
mypde.setValue(q=gammaD, A=kronecker(2), y_dirac=s)
u = mypde.getSolution()
saveVTK("u.vtu",sol=u)
\end{python}
%
Result is shown in Figure~\ref{FIG:EX:DIRAC}.
%
\begin{figure}[ht]
\center
\includegraphics[height=5cm]{diracplot}
%\includegraphics[scale=0.25]{stokes-fluid-colorbar}
\caption{Results diffusion problem with nodal source and sink.}
\label{FIG:EX:DIRAC}
\end{figure}


\documentclass[a4paper]{article}
\usepackage[top=2cm,left=2cm,right=2cm]{geometry}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage[svgnames]{xcolor}
\usepackage[colorlinks=true,
            linkcolor=blue,
            citecolor=blue,
            urlcolor=blue]{hyperref}
\usepackage{todonotes}

\newcommand{\R}{\mathbb{R}} % set of real numbers
\newcommand{\enorm}[1]{\lVert#1\rVert_2} % Euclidean norm

\renewcommand{\vec}[1]{\mathbf{#1}} % vector
\newcommand{\vx}{\vec{x}}
\newcommand{\vp}{\vec{p}}
\newcommand{\vv}{\vec{v}}

\newcommand{\hH}{\widehat{H}}
\newcommand{\hh}{\widehat{h}}
\newcommand{\hf}{\widehat{f}}
\newcommand{\hG}{\widehat{G}}

\newcommand{\I}{\textbf{I}} % identity matrix
\newcommand{\Z}{\vec{0}} % zero matrix

\newcommand{\pitch}{\psi}
\newcommand{\yaw}{\phi}
\newcommand{\roll}{\theta}

%------------------------------------------------------------------------------

\begin{document}

\title{Segway Model}
\maketitle

\section{Parameters and notation}

Our notation is similar to \cite{nxtway-gs}.
\begin{center}
\begin{tabular}{l@{\ =\ }c@{\quad:\quad}l}
    $g$ & $9.80665$ & gravitational acceleration ($m/s^2$) \\
    \hline
    $m$ & $0.0165 \,/\, 0.0295$ & NXT2/RCX wheel weight ($kg$) \\
    $R$ & $0.0216 \,/\, 0.0408$ & NXT2/RCX wheel radius ($m$) \\
    $w$ & $0.022 \,/\, 0.015$ & NXT2/RCX wheel width ($m$) \\
    $J_w$ & $m R^2 / 2$ & wheel inertia moment ($kg \cdot m^2$) \\
    \hline
    $M$ & $0.55$ & body weight ($kg$) \\
    $W$ & $0.15$ & body width ($m$) \\
    $D$ & $0.045$ & body depth ($m$) \\
    $H$ & $0.158$ & body height ($m$) \\
    $L$ & $H/2$ & center of mass distance from the wheel axle ($m$) \\
    $J_\pitch$ & $0.00805$
                & body pitch moment of inertia ($kg \cdot m^2$) \\
    $J_\yaw$ & $0.005$
                    & body yaw moment of inertia ($kg \cdot m^2$) \\
    $\pitch_0$ & $-2$ & balanced pitch deviation from upright position (deg) \\
    \hline
    $B$ & $0.18$ & DC motor constant ($Nm \cdot s/rad$) \\
    $K$ & $20$ & DC motor constant ($Nm / V$) \\
    \hline
    $\pitch$ & & body pitch angle ($rad$) \\
    $\roll_{l/r}$ & $\roll \mp W \yaw / (2 R)$
                        & left/right wheel roll angles ($rad$) \\
    $\roll$ & $(\roll_l + \roll_r)/2$ & axle midpoint roll angle ($rad$) \\
    $\yaw$ & $R \, (\roll_r - \roll_l) / W$ & body yaw angle ($rad$) \\
    $\vp_{l/r}$ & $[x_{l/r} \,\, y_{l/r} \,\, R]^T$
                    & left/right wheel positions ($m$) \\
    $\vp_m$ & $[x_m \,\, y_m \,\, R]^T$ & axle midpoint position ($m$) \\
    $\vp_c$ & $[x_c \,\, y_c \,\, z_c]^T$
                    & body center of mass position ($m$) \\
    $v_{l/r}$ & & left/right DC motor control power (V) \\
\end{tabular}
\end{center}

\subsection{Robot position}

The position of the center of mass and its derivative can be expressed as
\begin{equation}
    \vp_c = \vp_m + L \left[ \begin{array}{c}
                                \sin\pitch \cos\yaw \\
                                \sin\pitch \sin\yaw \\
                                \cos\pitch \\
                             \end{array} \right]
    \quad , \quad
    \dot{\vp}_c = \dot{\vp}_m
    + L \left[ \begin{array}{c}
               \dot\pitch \cos\pitch \cos\yaw - \dot\yaw \sin\pitch \sin\yaw \\
               \dot\pitch \cos\pitch \sin\yaw + \dot\yaw \sin\pitch \cos\yaw \\
               - \dot\pitch \sin\pitch
               \end{array} \right]
    \,,
\end{equation}
where $\vp_m = (\vp_l + \vp_r) / 2$.
Furthermore, if the $\yaw$ is constant and the wheels are rotating
$\delta\roll_l$ and $\delta\roll_r$ radians in $\delta t$ seconds, then
the wheel positions are changing by
\begin{equation}
    \delta \vp_l = R \, \delta\roll_l \left[ \begin{array}{c}
                                                \cos\yaw \\
                                                \sin\yaw \\
                                                0 \\
                                             \end{array} \right]
    \quad , \quad
    \delta \vp_r = R \, \delta\roll_r \left[ \begin{array}{c}
                                                \cos\yaw \\
                                                \sin\yaw \\
                                                0 \\
                                             \end{array} \right]
    \,.
\end{equation}
As we take $\delta t \rightarrow 0$, $\yaw$ becomes constant on
this infinitely short $\delta t$ interval, and so we obtain
\begin{equation}
    \dot{\vp}_l = R \, \dot\roll_l \left[ \begin{array}{c}
                                    \cos\yaw \\
                                    \sin\yaw \\
                                    0 \\
                                   \end{array} \right]
    \quad , \quad
    \dot{\vp}_r = R \, \dot\roll_r \left[ \begin{array}{c}
                                    \cos\yaw \\
                                    \sin\yaw \\
                                    0 \\
                                   \end{array} \right]
    \quad , \quad
    \dot{\vp}_m = R \, \dot\roll \left[ \begin{array}{c}
                                    \cos\yaw \\
                                    \sin\yaw \\
                                    0 \\
                                   \end{array} \right]
    \,.
\end{equation}

\subsection{Pitch equilibrium}

This model assumes that the center of mass is of the robot body is just
above the axle at the middle when the robot is in equilibrium. In real it
is not quite true, so one can shift the pitch angle by a constant $\pitch_0$
and use $\pitch - \pitch_0$ in the model.

But notice that moving the body center of mass also changes the body moment of
inertias, $J_\pitch$ and $J_\yaw$, so these quantities should be identified
for a fixed $\pitch_0$.

\section{Motion equations}

The system is divided into two subsystems: the driven segway robot
and the driving DC motors.

\subsection{Segway robot dynamics}

The Lagrangian of the system (without the DC motor) is
\begin{equation}
    L = E_t + E_r - E_p \,,
\end{equation}
where $E_t$ is the translational kinetic energy, $E_r$ is the rotational
kinetic energy and $E_p$ is the potential energy defined as
\begin{equation} \begin{split}
    E_t &= \frac{m}{2} \big( \dot{x}_l^2 + \dot{y}_l^2 \big)
         + \frac{m}{2} \big( \dot{x}_r^2 + \dot{y}_r^2 \big)
         + \frac{M}{2} \big( \dot{x}_c^2 + \dot{y}_c^2 + \dot{z}_c^2 \big)
        \,, \\
    E_r &= \frac{J_w}{2} \dot{\roll}_l^2 + \frac{J_w}{2} \dot{\roll}_r^2
         + \frac{J_\pitch}{2} \dot{\pitch}^2 + \frac{J_\yaw}{2} \dot{\yaw}^2
        \,, \\
    E_p &= m g R + m g R + M g z_c
        \,.
\end{split} \end{equation}
Then to find the equations of motion with respect to $\pitch$, $\yaw$ and
$\roll$, we write the Euler-Lagrange equations for the $F_\pitch$, $F_\yaw$,
$F_\roll$ generalized forces (see appendix \ref{sec:euler-lagrange-deriv}) as
\begin{equation} \begin{split}
    F_\pitch &= \frac{d}{dt}\left(\frac{\partial L}{\partial\dot\pitch}\right)
              - \frac{\partial L}{\partial\pitch}
              = \big( M L^2 + J_\pitch \big) \ddot\pitch
              + \big( M L R \cos\pitch \big) \ddot\roll
              - M L^2 \dot\yaw^2 \sin\pitch \cos\pitch
              - M g L \sin\pitch
    \,, \\
    F_\roll &= \frac{d}{dt}\left(\frac{\partial L}{\partial\dot\roll}\right)
             - \frac{\partial L}{\partial\roll}
             = \bigg( \frac{M L R}{2} \cos\pitch \bigg) \ddot\pitch
             + \bigg( m R^2 + J_w + \frac{M R^2}{2} \bigg) \ddot\roll
             - \frac{M L R}{2} \dot\pitch^2 \sin\pitch
    \,, \\
    F_\yaw &= \frac{d}{dt}\left(\frac{\partial L}{\partial\dot\yaw}\right)
            - \frac{\partial L}{\partial\yaw}
            = \bigg( m R^2 + J_w
                   + \frac{2 R^2}{W^2}
                     \big( M L^2 \sin^2\pitch + J_\yaw \big)
              \bigg) \ddot\yaw
            + \frac{2 M R^2 L^2}{W^2}
              \dot\yaw \dot\pitch \sin\pitch \cos\pitch
    \,.
\end{split} \end{equation}

\subsection{DC motor dynamics}

A detailed description of a DC motor model can be found in
\cite{robot-modeling}. However, now we will use a simplified model, which
captures only that the torque is damped by the shaft's rotational velocity
and proportional to the applied power. So
\begin{equation}
    F_{\roll_{l/r}} = -B (\dot\roll_{l/r} - \dot\pitch)
                       + K v_{l/r}
    \,,
\end{equation}
where $B$ ($Nm \cdot rad/s$) and $K$ ($Nm / V$) are DC motor constants.
Then we can express the generalized forces as
\begin{equation} \begin{split}
    F_\pitch &= -(F_{\roll_l} + F_{\roll_r})
              = 2 B (\dot\roll - \dot\pitch) - K(v_l + v_r)
    \,, \\
    F_\roll &= \frac{1}{2}(F_{\roll_l} + F_{\roll_r})
             = -B (\dot\roll - \dot\pitch) + K \frac{v_l + v_r}{2}
    \,, \\
    F_\yaw &= \frac{R}{W}(F_{\roll_r} - F_{\roll_l})
            = -B \dot\yaw + \frac{R}{W} (v_r - v_l)
    \,.
\end{split} \end{equation}

\subsection{State space form}

By connecting the two subsystems and rearranging the equations, we get
\begin{equation} \begin{split}
\label{eq:motion-raw}
        \Big( M L^2 + J_\psi \Big) \ddot\pitch
      + (M L R \cos\pitch) \ddot\roll
    &=  M L^2 \dot\yaw^2 \sin\pitch \cos\pitch
      + M g L \sin\pitch
      + 2 B \big( \dot\roll - \dot\pitch \big)
      - K \big( v_l + v_r \big)
    \,, \\
        (M L R \cos\pitch) \ddot\pitch
      + \Big( (2 m + M) R^2 + 2 J_w \Big) \ddot\roll
    &=  M L R \dot\pitch^2 \sin\pitch
      - 2 B \big( \dot\roll - \dot\pitch \big)
      + K \big( v_l + v_r \big)
    \,, \\
        \Big( m R^2 W^2 + W^2 J_w
            + 2 R^2 \big( M L^2 \sin^2\pitch + J_\yaw \big)
        \Big) \ddot\yaw
    &=  -2 M R^2 L^2 \dot\yaw \dot\pitch \sin\pitch \cos\pitch
      - B W^2 \dot\yaw + R W K \big( v_r - v_l \big)
    \,.
\end{split} \end{equation}
By introducing the $\vx = [\pitch \,\, \roll \,\, \yaw \,\,
                           \dot\pitch \,\, \dot\roll \,\, \dot\yaw \,\,
                           x_m \,\, y_m]^T$ state
           and the $\vv = [v_l \,\, v_r]^T$ control,
we can write (\ref{eq:motion-raw}) into
\begin{equation}
    H(\vx) \, \dot{\vx} = \hf(\vx) + \hG \, \vv \,,
\end{equation}
where $H : \R^8 \rightarrow \R^{8 \times 8}$,
      $\hf : \R^8 \rightarrow \R^8$,
      $\hG \in \R^{8 \times 2}$,
\begin{equation}
   H(\vx)
   = \left[ \begin{array}{cccc}
     \I_{3 \times 3} & \Z_{3 \times 2}  & \Z_{3 \times 1}  & \Z_{3 \times 2} \\
     \Z_{2 \times 3} & \hH(\vx)         & \Z_{2 \times 1}  & \Z_{1 \times 2} \\
     \Z_{1 \times 3} & \Z_{1 \times 2}  & \hh(\vx)         & \Z_{1 \times 2} \\
     \Z_{2 \times 3} & \Z_{2 \times 2}  & \Z_{2 \times 1}  & \I_{2 \times 2} \\
     \end{array} \right]
   \quad , \quad
   \hf(\vx) = \left[ \begin{array}{c}
                     \dot\pitch \\
                     \dot\roll \\
                     \dot\yaw \\
                     \hf_4(\vx) \\
                     \hf_5(\vx) \\
                     \hf_6(\vx) \\
                     R \, \dot\roll \cos\yaw \\
                     R \, \dot\roll \sin\yaw \\
                     \end{array} \right]
    \quad , \quad
    \hG = K \left[ \begin{array}{cc}
                   0    & 0 \\
                   0    & 0 \\
                   0    & 0 \\
                   -1   & -1 \\
                   1    & 1 \\
                   -R W & R W \\
                   0    & 0 \\
                   0    & 0 \\
                   \end{array} \right]
    \,,
\end{equation}
with
\begin{equation} \begin{split}
    \widehat{H}(\vx) &= \left[ \begin{array}{cc}
                        \hH_{11} & \hH_{12}(\vx) \\
                        \hH_{12}(\vx) & \hH_{22} \\
                        \end{array} \right]
    \qquad , \qquad
    \begin{array}{r@{\,=\,}l}
        \hH_{11} & M L^2 + J_\pitch \\
        \hH_{12}(\vx) & M L R \cos\pitch \\
        \hH_{22} & (2 m + M) R^2 + 2 J_w \\
    \end{array}
    \,, \\
    \hh(\vx) &= m R^2 W^2 + W^2 J_w
              + 2 R^2 \big( M L^2 \sin^2\pitch + J_\yaw \big)
    \,, \\
    \hf_4(\vx) &= M L^2 \dot\yaw^2 \sin\pitch \cos\pitch
                + M g L \sin\pitch
                + 2 B \big( \dot\roll - \dot\pitch \big)
    \,, \\
    \hf_5(\vx) &= M L R \dot\pitch^2 \sin\pitch
                - 2 B \big( \dot\roll - \dot\pitch \big)
    \,, \\
    \hf_6(\vx) &= -2 M R^2 L^2 \dot\yaw \dot\pitch \sin\pitch \cos\pitch
                - B W^2 \dot\yaw
    \,.
\end{split} \end{equation}
Notice that $\det\hH(\vx) > 0$ for all $\vx$ because
\begin{equation} \begin{split}
    \det\hH(\vx) &= \big( M L^2 + J_\psi \big)
                    \Big( (2m + M) R^2 + 2 J_w \Big)
                  - \big( M L R \cos\pitch \big)^2
                 \\
                 &> M^2 L^2 R^2
                  - M^2 L^2 R^2 \cos^2\pitch
                  = M^2 L^2 R^2 \big( 1 - \cos^2\pitch \big)
                  \ge 0
                  \,.
\end{split} \end{equation}
Furthermore, for all $\vx$, we have $\hh(\vx) > 0$ and so $\det H(\vx) > 0$.
Hence, $\exists H(\vx)^{-1}$ for all $\vx$, and the state space form becomes
\begin{equation}
    \dot{\vx} = H(\vx)^{-1} \Big(\hf(\vx) + \hG \, \vv\Big)
              = H(\vx)^{-1} \hf(\vx) + H(\vx)^{-1} \hG \, \vv
              = f(\vx) + G(\vx) \, \vv
              \,,
\end{equation}
where
\begin{equation}
    f(\vx) = \left[ \begin{array}{c}
                    \dot\pitch \\
                    \dot\roll \\
                    \dot\yaw \\
                    f_4(\vx) \\
                    f_5(\vx) \\
                    f_6(\vx) \\
                    R \dot\roll \cos\yaw \\
                    R \dot\roll \sin\yaw \\
                    \end{array} \right]
    \qquad , \qquad
    G(\vx) = \left[ \begin{array}{cc}
                    0 & 0 \\
                    0 & 0 \\
                    0 & 0 \\
                    g_4(\vx) & g_4(\vx) \\
                    g_5(\vx) & g_5(\vx) \\
                    -g_6(\vx) & g_6(\vx) \\
                    0 & 0 \\
                    0 & 0 \\
                    \end{array} \right]
    \,,
\end{equation}
with
\begin{equation} \begin{aligned}
    f_4(\vx) &= \frac{\hH_{22}\hf_4(\vx) - \hH_{12}(\vx)\hf_5(\vx)}
                     {\hH_{11}\hH_{22} - \hH_{12}(\vx)^2}
    \quad &, \quad
    g_4(\vx) &= \frac{-K\big(\hH_{22} + \hH_{12}(\vx)\big)}
                     {\hH_{11}\hH_{22} - \hH_{12}(\vx)^2}
    \,, \\
    f_5(\vx) &= \frac{-\hH_{12}(\vx)\hf_4(\vx) + \hH_{11}\hf_5(\vx)}
                     {\hH_{11}\hH_{22} - \hH_{12}(\vx)^2}
    \quad &, \quad
    g_5(\vx) &= \frac{K\big(\hH_{12}(\vx) + \hH_{11}\big)}
                     {\hH_{11}\hH_{22} - \hH_{12}(\vx)^2}
    \,, \\
    f_6(\vx) &= \frac{\hf_6(\vx)}
                     {\hh(\vx)}
    \quad &, \quad
    g_6(\vx) &= \frac{K R W}{\hh(\vx)}
    \,.
\end{aligned} \end{equation}

\appendix

\section{Derivation of the Euler-Lagrange equations}
\label{sec:euler-lagrange-deriv}

Notice that
\begin{equation} \begin{split}
\label{eq:dot-xy}
    \dot{x}_c \cos\yaw + \dot{y}_c \sin\yaw
        &= \dot{x}_m \cos\yaw + \dot{y}_m \sin\yaw
         + L \dot\pitch \cos\pitch \big( \cos^2\yaw + \sin^2\yaw \big)
         = R \dot\roll + L \dot\pitch \cos\pitch
    \,, \\
    \dot{x}_c \sin\yaw - \dot{y}_c \cos\yaw
        &= \dot{x}_m \sin\yaw - \dot{y}_m \cos\yaw
         - L \dot\yaw \sin\pitch \big( \sin^2\yaw + \cos^2\yaw \big)
         = - L \dot\yaw \sin\pitch
    \,.
\end{split} \end{equation}
Then
\begin{equation} \begin{split}
    F_\pitch
    &= \frac{d}{dt} \left( \frac{\partial L}{\partial \dot\pitch} \right)
     - \frac{\partial L}{\partial \pitch}
    \\
    &= \frac{d}{dt} \Big( M L \big( \dot{x}_c \cos\pitch \cos\yaw
                                  + \dot{y}_c \cos\pitch \sin\yaw
                                  - \dot{z}_c \sin\pitch
                              \big)
                        + J_\pitch \dot\pitch
                    \Big)
    \\ &\quad + M L \Big( \dot{x}_c \big( \dot\pitch \sin\pitch \cos\yaw
                                        + \dot\yaw \cos\pitch \sin\yaw
                                    \big)
                        + \dot{y}_c \big( \dot\pitch \sin\pitch \sin\yaw
                                        - \dot\yaw \cos\pitch \cos\yaw
                                    \big)
                        + \dot{z}_c \dot\pitch \cos\pitch
                        - g \sin\pitch
                    \Big)
    \\
    &= \frac{d}{dt} \Big( M L \cos\pitch \big( \dot{x}_c \cos\yaw
                                             + \dot{y}_c \sin\yaw
                                         \big)
                        + M L^2 \dot\pitch \sin^2\pitch
                        + J_\pitch \dot\pitch
                    \Big)
    \\ &\quad + M L \Big( \dot\pitch \sin\pitch \big( \dot{x}_c \cos\yaw
                                                    + \dot{y}_c \sin\yaw
                                                \big)
                        + \dot\yaw \cos\pitch \big( \dot{x}_c \sin\yaw
                                                  - \dot{y}_c \cos\yaw
                                              \big)
                        - L \, \dot\pitch^2 \sin\pitch \cos\pitch
                        - g \sin\pitch
                    \Big)
    \\
    &\hspace{-1.5mm} \stackrel{(\ref{eq:dot-xy})}{=}
        \frac{d}{dt} \Big( M L R \, \dot\roll \cos\pitch
                         + M L^2 \, \dot\pitch
                         + J_\pitch \dot\pitch
                     \Big)
    \\ &\quad + M L \big( R \, \dot\roll \, \dot\pitch \sin\pitch
                        + L \, \dot\pitch^2 \sin\pitch \cos\pitch
                        - L \, \dot\yaw^2 \cos\pitch \sin\pitch
                        - L \, \dot\pitch^2 \sin\pitch \cos\pitch
                        - g \sin\pitch
                    \big)
    \\
    &= M L R \, \ddot\roll \cos\pitch
     - M L R \, \dot\roll \, \dot\pitch \sin\pitch
     + \big( M L^2 + J_\pitch \big) \ddot\pitch
     + M L \big( R \, \dot\roll \, \dot\pitch \sin\pitch
               - L \, \dot\yaw^2 \sin\pitch \cos\pitch
               - g \sin\pitch
           \big)
    \\
    &= \big( M L^2 + J_\pitch \big) \ddot\pitch
     + \big( M L R \cos\pitch \big) \ddot\roll
     - M L^2 \, \dot\yaw^2 \sin\pitch \cos\pitch
     - M g L \sin\pitch
    \,.
\end{split} \end{equation}
Furthermore, notice that $\partial\yaw / \partial\roll_{l/r} = \mp R/W$ and
\begin{equation} \begin{split}
\label{eq:xy-lr}
    \dot{x}_{l/r} \cos\yaw + \dot{y}_{l/r} \sin\yaw
        &= R \, \dot\roll_{l/r} \cos^2\yaw + R \, \dot\roll_{l/r} \sin^2\yaw
         = R \, \dot\roll_{l/r}
    \,, \\
    \dot{x}_{l/r} \sin\yaw - \dot{y}_{l/r} \cos\yaw
        &= R \, \dot\roll_{l/r} \cos\yaw \sin\yaw
         - R \, \dot\roll_{l/r} \sin\yaw \cos\yaw
         = 0
    \,, \\
    \dot{x}_c \cos\yaw + \dot{y}_c \sin\yaw
        &= R \, \dot\roll \cos^2\yaw
         + L \big( \dot\pitch \cos\pitch \cos^2\yaw
                 - \dot\yaw \sin\pitch \sin\yaw \cos\yaw
             \big)
        \\ &\quad
         + R \, \dot\roll \sin^2\yaw
         + L \big( \dot\pitch \cos\pitch \sin^2\yaw
                 + \dot\yaw \sin\pitch \cos\yaw \sin\yaw
             \big)
         = R \, \dot\roll + L \dot\pitch \cos\pitch
    \,, \\
    \dot{x}_c \sin\yaw - \dot{y}_c \cos\yaw
        &= R \, \dot\roll \cos\yaw \sin\yaw
         + L \big( \dot\pitch \cos\pitch \cos\yaw \sin\yaw
                 - \dot\yaw \sin\pitch \sin^2\yaw
             \big)
        \\ &\quad
         - R \, \dot\roll \sin\yaw \cos\yaw
         - L \big( \dot\pitch \cos\pitch \sin\yaw \cos\yaw
                 + \dot\yaw \sin\pitch \cos^2\yaw
             \big)
         = - L \dot\yaw \sin\pitch
    \,.
\end{split} \end{equation}
Then the forces of the left/right axle endpoints can be expressed as
\begin{equation} \begin{split}
    F_{\roll_{l/r}}
    &= \frac{d}{dt} \left( \frac{\partial L}{\partial \dot\roll_{l/r}} \right)
     - \frac{\partial L}{\partial \roll_{l/r}}
    \\
    &= \frac{d}{dt} \bigg( m R \big( \dot{x}_{l/r} \cos\yaw
                                   + \dot{y}_{l/r} \sin\yaw
                               \big)
    \\ &\hspace{2cm}
                         + \frac{M R}{2}
                           \Big[ \dot{x}_c
                                 \Big( \cos\yaw
                                   \pm \frac{2 L}{W} \sin\pitch \sin\yaw
                                 \Big)
                               + \dot{y}_c
                                 \Big( \sin\yaw
                                   \mp \frac{2 L}{W} \sin\pitch \cos\yaw
                                 \Big)
                           \Big]
                          + J_w \dot\roll_{l/r}
                          \mp \frac{R}{W} J_\yaw \dot\yaw
                      \bigg)
    \\ &\quad \mp \frac{m R^2}{W} \big( \dot{x}_l \dot\roll_l \sin\yaw
                                      - \dot{y}_l \dot\roll_l \cos\yaw
                                      + \dot{x}_r \dot\roll_r \sin\yaw
                                      - \dot{x}_r \dot\roll_r \cos\yaw
                                \big)
    \\ &\quad \mp \frac{M R}{W}
                  \Big( \dot{x}_c \big[ R \, \dot\roll \sin\yaw
                                      + L \big( \dot\pitch \cos\pitch \sin\yaw
                                              + \dot\yaw \sin\pitch \cos\yaw
                                          \big)
                                  \big]
    \\ &\hspace{6cm}
                      + \dot{y}_c \big[ - R \, \dot\roll \cos\yaw
                                      + L \big( -\dot\pitch \cos\pitch \cos\yaw
                                              + \dot\yaw \sin\pitch \sin\yaw
                                          \big)
                                  \big]
                  \Big)
    \\
    &\hspace{-1.5mm} \stackrel{(\ref{eq:xy-lr})}{=}
        \frac{d}{dt} \bigg( m R^2 \dot\roll_l
                          + \frac{M R}{2} \big( R \, \dot\roll
                                              + L \dot\pitch \cos\pitch
                                          \big)
                          \mp \frac{M R L^2}{W} \dot\yaw \sin^2\pitch
                          + J_w \dot\roll_{l/r}
                          \mp \frac{R}{W} J_\yaw \dot\yaw
                     \bigg)
    \\ &\quad \mp 0
              \mp \frac{M R}{W} \Big( R \dot\roll
                                    + L \dot\pitch \cos\pitch
                                \Big)
                                \big( - L \dot\yaw \sin\pitch \big)
              \pm \frac{M R L}{W} \dot\yaw \sin\pitch
                                  \big( R \, \dot\roll
                                      + L \dot\pitch \cos\pitch \big)
    \\
    &= m R^2 \ddot\roll_{l/r}
     + \frac{M R}{2} \big( R \, \ddot\roll
                         + L \ddot\pitch \cos\pitch
                         - L \dot\pitch^2 \sin\pitch
                     \big)
     \mp \frac{M R L^2}{W} \big( \ddot\yaw \sin^2\pitch
                               + 2 \dot\yaw \dot\pitch \sin\pitch \cos\pitch
                           \big)
     \\ &\hspace{12cm}
     + J_w \ddot\roll_{l/r}
     \mp \frac{R}{W} J_\yaw \ddot\yaw
     \\
     &= \Big( m R^2 + J_w \Big) \ddot\roll_{l/r}
      + \frac{M R^2}{2} \ddot\roll
      + \bigg( \frac{M R L}{2} \cos\pitch \bigg) \ddot\pitch
      - \frac{M R L}{2} \dot\pitch^2 \sin\pitch
     \\ &\hspace{6cm}
      \mp \frac{R}{W}
          \bigg( M L^2 \sin^2\pitch + J_\yaw \bigg) \ddot\yaw
      \mp \frac{2 M R L^2}{W} \dot\yaw \dot\pitch \sin\pitch \cos\pitch
     \,.
\end{split} \end{equation}
By using $F_{\roll_l}$ and $F_{\roll_r}$, we can compute
the $F_\roll$, $F_\yaw$ generalized forces as
\begin{equation} \begin{split}
    F_\roll &= F_{\roll_l} \frac{\partial \roll}{\partial \roll_l}
             + F_{\roll_r} \frac{\partial \roll}{\partial \roll_r}
             = \frac{F_{\roll_l} + F_{\roll_r}}{2}
            \\
            &= \left( m R^2 + J_w + \frac{M R^2}{2} \right) \ddot\roll
             + \left( \frac{M L R}{2} \cos\pitch \right) \ddot\pitch
             - \frac{M L R}{2} \dot\pitch^2 \sin\pitch
    \,, \\
    F_\yaw &= F_{\roll_l} \frac{\partial \yaw}{\partial \roll_l}
            + F_{\roll_r} \frac{\partial \yaw}{\partial \roll_r}
            = \frac{R}{W} \Big( F_{\roll_r} - F_{\roll_r} \Big)
           \\
           &= \bigg( m R^2 + J_w
                   + \frac{2 R^2}{W^2}
                     \big( M L^2 \sin^2\pitch + J_\yaw \big)
              \bigg) \ddot\yaw
            + \frac{2 M R^2 L^2}{W^2}
              \dot\yaw \dot\pitch \sin\pitch \cos\pitch
    \,.
\end{split} \end{equation}

\begin{thebibliography}{99}

\bibitem{nxtway-gs}
    Yorihisa Yamamoto \\
    \textsl{NXTway-GS (Self-Balancing Two-Wheeled Robot) Controller Design} \\
    \href{http://www.mathworks.com/matlabcentral/fileexchange/19147}
         {http://www.mathworks.com/matlabcentral/fileexchange/19147}

\bibitem{nxt-motor-philo}
    Philippe E. Hurbain \\
    \textsl{NXT Motor Internals} \\
    \href{http://www.philohome.com/nxtmotor/nxtmotor.htm}
         {http://www.philohome.com/nxtmotor/nxtmotor.htm}

\if0
\bibitem{nxt-motor}
    Ryo Watanabe \\
    \textsl{NXT Motor} \\
    \href{http://web.mac.com/ryo_watanabe/iWeb/Ryo%27s%20Holiday/NXT%20Motor.html}
         {http://web.mac.com/ryo\_watanabe/iWeb/Ryo\%27s\%20Holiday/NXT\%20Motor.html}
\fi

\bibitem{robot-modeling}
    Mark W. Spong, Seth Hutchinson, M. Vidyasagar \\
    \textsl{Robot Modeling and Control} \\
    John Wiley \& Sons, 2005

\end{thebibliography}

\end{document}


%#########################################################
\chapter{Fundamentals of MRI}
%#########################################################
Among various medical imaging modalities Magnetic Resonance Imaging (MRI) is currently the most powerful technique to study structure and functions of human body \textit{in-vivo} and non-invasively at the level of the detail that is not available with any other imaging method.
The power of MRI comes from the ability to to obtain quantitative spatial information for different types of human body tissue and fluids placed inside a strong magnetic field by manipulating Radio-frequency (RF) and gradient pulses.
Magnetic Resonance Imaging is a fascinating combination of quantum physics, electrodynamics, advanced engineering and computation methods.
This chapter is a short introduction to the fundamentals of MRI.
%=========================================================
\section{Larmor Precession}
%=========================================================
A charged particle placed in an external magnetic field will precess at a frequency proportional to this external field.
In classical description magnetic dipole moment for a charged particle $\boldsymbol\mu$ is proportional to the angular momentum $\mathbf{J}$:
%.........................................................
\begin{equation}\label{eq: Classical magnetic moment}
	\boldsymbol{\mu}=\frac{q}{2m}\mathbf{J}
\end{equation}
%.........................................................
where $q$ is the charge of a particle and $m$ is its mass.
Torque on a magnetic dipole in external magnetic filed $\mathbf{B}$ is:
%.........................................................
\begin{equation}\label{eq: Torque}
	\boldsymbol{\tau}=\frac{d\mathbf{J}}{dt}=\boldsymbol{\mu}\times\mathbf{B}=\frac{q}{2m}\mathbf{J}\times\mathbf{B}
\end{equation}
%.........................................................
Precessional frequency is then:
%.........................................................
\begin{equation}\label{eq: Classic Larmor frequency}
	\omega=\frac{d\phi}{dt}=-\frac{d\phi}{d\mathbf{J}}\cdot \frac{d\mathbf{J}}{dt}=\frac{1}{J\sin{\theta}}\cdot \frac{q}{2m}\ - J B \sin{\theta}
\end{equation}
%.........................................................
where $d\phi$ is the rotation angle and $\theta$ is the angle enclosed by angular momentum $\mathbf{J}$ and magnetic field $\mathbf{B}$:
%.........................................................
\begin{equation}\label{eq: Classic Larmor frequency 2}
	\omega=-\frac{q}{2m}\ B
\end{equation}
%.........................................................
In quantum mechanics description magnetic dipole moment is quantized:
%.........................................................
\begin{equation}\label{eq: Quantum magnetic moment}
	\boldsymbol{\mu}=\gamma\hbar \mathbf{I}
\end{equation}
%.........................................................
where  $\gamma$ is gyromagnetic ratio (for protons: $\gamma/2\pi = \SI{42.57}{\mega\hertz /\tesla}$), $\hbar = \SI{1.05e-34}{\joule \cdot \second}$ is reduced Planck constant and $\mathbf{I}$ is nuclear spin angular momentum. For each proton energy is:
%.........................................................
\begin{equation}\label{eq: Quantum energy}
	\varepsilon=-\boldsymbol{\mu}\cdot \mathbf{B}=-\gamma\hbar\mathbf{I}\cdot\mathbf{B}
\end{equation}
%.........................................................
and since there are only two possible states (magnetic moment is almost parallel or anti-parallel to the external magnetic field $\mathbf{B}$) with $ I = \pm 1/2$  the energy difference between these states is:
%.........................................................
\begin{equation}\label{eq: Quantum energy delta}
	\Delta\varepsilon=-\left(\frac{1}{2} + \frac{1}{2}\right)\gamma\hbar B
\end{equation}
%.........................................................
using Einstein-Planck relation $\Delta\varepsilon=\hbar\omega$ and Equation~\ref{eq: Quantum energy delta} the Larmor frequency:
%.........................................................
\begin{equation}\label{eq: Quantum Larmor frequency}
	\omega=-\gamma B
\end{equation}
%.........................................................
Comparing Equations~\ref{eq: Classic Larmor frequency 2} and \ref{eq: Quantum Larmor frequency} one can see that the precessional frequency is same as the frequency of the photon that can be absorbed or emitted by proton to go from one energy state to another.
%=========================================================
\section{Population of Energy States}
%=========================================================
The signal measured in MRI is the net magnetization $\mathbf{M_{0}}$ which is a result of difference in proton energy level population density given by Boltzmann distribution:
%.........................................................
\begin{equation}\label{eq: Boltzmann distribution}
	\frac{N_{\mathrm{up}}}{N_{\mathrm{down}}}=\exp\left(\frac{-\Delta\varepsilon}{k_{B}T}\right)\approx 1 + \frac{{\gamma\hbar B}}{k_{B}T}
\end{equation}
%.........................................................
where $k_{B} = \SI{1.38e-23}{\joule \cdot {\kelvin}^{-1}}$ is Boltzmann constant the difference is then:
%.........................................................
\begin{equation} \label{eq: Population difference}
	\Delta N = \frac{N_{\mathrm{total}}}{2}\frac{\gamma\hbar B}{k_{B}T}
\end{equation}
%.........................................................
multiplying Equation~\ref{eq: Population difference} by magnetic moment $\mu = \gamma \hbar / 2$ and dividing by a total number of protons gives the equation for magnetization per unit volume:
%.........................................................
\begin{equation}\label{eq: Magnetization per volume}
	\mathbf{M_{0}}=\frac{\rho\gamma^2\hbar^2\mathbf{B}}{4k_{B}T}
\end{equation}
%.........................................................
where $\rho$ is proton density.
From the Equation~\ref{eq: Magnetization per volume} one can see that the measured signal is directly proportional to the strength of the external magnetic field and inversely proportional to the tissue or fluid temperature.
The direction of net magnetization is matched with the direction of the external magnetic field $\mathbf{B}$ since there are more protons in a low level energy state (aligned with external magnetic field).
Equation~\ref{eq: Magnetization per volume} provides an estimate for the signal to be measured.
Simple example would be magnetization for $\SI{1}{\milli\liter}$ of water at temperature $\SI{310}{\kelvin}$) placed in the $\SI{1}{\tesla}$ magnetic field.
Calculating proton density $\rho$ of water using the Avogadro number gives:
%.........................................................
\begin{equation}\label{eq: Magnetization estimation}
	\mathbf{M_{0}}\approx \SI{3}{\milli\ampere / \meter}
\end{equation}
%.........................................................
Compared to the strength of the external magnetic field $\mathbf{B}$ the magnetization of the tissue of interest is much smaller which makes it hard to measure when at equilibrium.
If tipped to the transverse plane by applying RF-pulse the signal becomes distinct and easier to measure.
%=========================================================
\section{Bloch Equations}
%=========================================================
The evolution of net magnetization is described by Bloch equation~\cite{Bloch1946}:
%.........................................................
\begin{equation}\label{eq: Bloch equation}
	\frac{d\mathbf{M}}{dt}=\gamma\mathbf{M} \times \mathbf{B}
\end{equation}
%.........................................................
relaxation and diffusion terms are dropped to simplify further examination. To flip magnetization to the plane perpendicular to the direction of the applied strong magnetic field and produce transverse magnetization an RF-pulse should be applied. A common approach is to switch from laboratory reference frame defined with respect to the scanner to the frame rotating at some constant angular frequency $\Omega$. Magnetic field $\mathbf{B}$ in the laboratory reference frame can be chosen as following form:
%.........................................................
\begin{equation}\label{eq: External B field}
	\mathbf{B}=\hat{x}B_{1}(t)\cos{\omega_{\text{rf}} t}-\hat{y}B_{1}(t)\sin{\omega_{\text{rf}} t} +\hat{z}B_0
\end{equation}
%.........................................................
where $B_0$ is constant strong magnetic field aligned with the $z$-axis and $B_1$ is the time-varying component in the transverse plane.
Rewriting Bloch equation using Equation~\ref{eq: External B field}:
%.........................................................
\begin{equation}\label{eq: Bloch equation lab frame}
\left(\frac{d\mathbf{M}}{dt}\right)_{\text{lab}}=\gamma\mathbf{M}\times\biggl[\hat{x}B_1(t)\cos{\omega_{\text{rf}}t}-\hat{y}\sin{\omega_{\text{rf}}t}+\hat{z}B_0\biggr]
\end{equation}\\
%.........................................................
In matrix form and frame of reference rotating at constant frequency $\Omega$ time-varying field $\mathbf{B_{1}}$ is the following:
%.........................................................
\begin{equation}\label{eq: External B field rotating frame}
\begin{bmatrix}
    B_{1,x}(t)\\
    B_{1,y}(t)\\
    B_{1,z}(t)\\
\end{bmatrix}_{\mathrm{rot}} =
	\begin{bmatrix}
    \cos{\Omega t} & -\sin{\Omega t} & 0\\
    \sin{\Omega t} & \cos{\Omega t} & 0\\
    0 & 0 & 1\\
	\end{bmatrix}
	\begin{bmatrix}
    \phantom{-}B_{1}(t)\cos{\omega_{\text{rf}} t}\\
    -B_{1}(t)\sin{\omega_{\text{rf}} t}\\
    0\\
	\end{bmatrix}
\end{equation}
%.........................................................
after performing multiplication and making use of trigonometric identities the transverse component $\mathbf{B_{1}}$ in the rotating frame of reference is:
%.........................................................
\begin{equation}\label{eq: External B field rotating frame 2}
	\mathbf{B_{1}}_{\mathrm{rot}}(t)=
	\begin{bmatrix}
	B_{1}(t) \cos(\Omega -\omega_{\text{rf}})t\\
	B_{1}(t) \sin(\Omega -\omega_{\text{rf}})t\\
	0
	\end{bmatrix}
\end{equation}
%.........................................................
Closely following~\cite{Slichter1990, RNDT24} Equation~\ref{eq: Bloch equation lab frame} the Bloch equation in the rotating frame becomes:
%.........................................................
\begin{equation}\label{eq: Bloch equation rot}
\begin{split}
	\left(\frac{d\mathbf{M}}{dt}\right)_{\text{rot}} &=\left(\frac{d\mathbf{M}}{dt}\right)_{\text{lab}} + \Omega \hat{z} \times \mathbf{M} =\\ \\
	&= \gamma\mathbf{M}\times\biggl[B_1(t)(\hat{x}\cos{(\omega_{\text{rf}}-\Omega)}t-\hat{y}\sin{(\omega_{\text{rf}}-\Omega)t)}+
		 \hat{z}\left(B_0-\frac{\Omega}{\gamma}\right)\biggr]
\end{split}
\end{equation}\\ \\
%.........................................................
Carrying out vector cross product the system of equation in scalar form:
%.........................................................
\begin{equation}\label{eq: scalar form of Bloch}
\begin{aligned}
	\left(\frac{M_x}{dt}\right)_\mathrm{rot} &= \gamma M_y\left(B_0-\frac{\Omega}{\gamma}\right)+\gamma M_zB_1(t)\sin(\omega_{\text{rf}}-\Omega)t\\
	\left(\frac{M_y}{dt}\right)_\mathrm{rot} &= -\gamma M_x\left(B_0-\frac{\Omega}{\gamma}\right)+\gamma M_zB_1(t)\cos(\omega_{\text{rf}}-\Omega)t\\
	\left(\frac{M_z}{dt}\right)_\mathrm{rot} &= -\gamma M_xB_1(t)\sin(\omega_{\text{rf}}-\Omega)t - \gamma M_yB_1(t)\cos(\omega_{\text{rf}}-\Omega)t
\end{aligned}
\end{equation}
%.........................................................
Three special cases are:
\begin{itemize}
	\item \textit{RF reference frame: }$\Omega=\omega_{\text{rf}}$\\
	Frequency of rotating frame $\Omega$ same as the RF-pulse frequency $\omega_{\mathrm{rf}}$
%.........................................................
\begin{equation}\label{eq: Bloch case 1}
	\left(\frac{d\mathbf{M}}{dt}\right)_{\text{rot}}=\gamma\mathbf{M}\times\left[\hat{x}B_1(t)+\hat{z}\left(B_0-\frac{\omega_{\text{rf}}}{\gamma}\right)\right]
\end{equation}
%.........................................................
here $B_1$ field is stationary. and due to the choice for $\mathbf{B}$ in Equation~\ref{eq: External B field} the filed $B_1$ is oriented along $x$ axis.
In general $B_1$ field can have both $x$ and $y$ component.
\item \textit{Larmor reference frame: }$\Omega=\omega$\\
Rotating frame frequency $\Omega$ equals Larmor frequency $\omega = \gamma B_{0}$
%.........................................................
\begin{equation}\label{eq: Bloch case 2}
	\left(\frac{d\mathbf{M}}{dt}\right)_{\text{rot}}=\gamma\mathbf{M}\times\left[B_1(t)(\hat{x}\cos{(\omega_{\text{rf}}-\omega)}t-\hat{y}\sin{(\omega_{\text{rf}}-\omega)t)}\right]
\end{equation}
%.........................................................
in this case the am$B_0$ filed is eliminated.
\item \textit{Resonance case:} $\omega=\omega_{\text{rf}}=\omega_{0}$
%.........................................................
\begin{equation}\label{eq: Bloch case 3}
	\left(\frac{d\mathbf{M}}{dt}\right)_{\text{rot}}=\gamma\mathbf{M}\times \hat{x}B_1(t)
\end{equation}
%.........................................................
\end{itemize}
Rotating reference frame vastly simplifies the study of the time evolution of net magnetization by transforming rapidly oscillating RF field into the time-dependent field $B_1(t)$.
Since $x$ and $y$ components of magnetization is of the most interest a complex magnetization $\bar{M}$ is usually introduced:
%.........................................................
\begin{equation}\label{eq: Transverse magnetization}
	\bar{M}=M_x+iM_y
\end{equation}
%.........................................................
which simplifies Equation~\ref{eq: Bloch equation rot} and gives the following compact form useful in solving for transverse components of magnetization after RF excitation pulse:
%.........................................................
\begin{equation}\label{eq: Bloch transverse}
	\left(\frac{d\bar{M}}{dt}\right)_\mathrm{rot}=-i\gamma\bar{M}\left(B_0-\frac{\Omega}{\gamma}\right)+i\gamma M_z
B_1(t)e^{-i(\omega_{\mathrm{rf}}-\Omega)t}
\end{equation}
%.........................................................
%=========================================================
\section{Building Blocks of MRI Pulse Sequences}
%=========================================================
An MRI pulse sequence is a set of programmed time-varying magnetic field pulses applied to the object of study placed inside an MRI system.
There are two categories of pulses:
\begin{itemize}
\item \textit{RF-pulses}: used for a number of different purposes, primarily to create measurable signal (excitation), form an echo for the signal lost during free induction decay (refocusing), selectively null the signal for certain types of tissues (inversion).
\item \textit{Gradients}: the major purpose is to create linear variation in the external magnetic field that can be exploited to spatially encode Magnetic Resonance (MR) signal, which is further reconstructed into an image (imaging gradients), control signal phase due to motion (motion-sensitizing) and various correction gradients reducing imaging artifacts~\cite{RNDT24} such as crusher gradients, eddy-current compensation and spoiler gradients.
\end{itemize}
An infinite number of shapes for RF-pulses and gradients can be used in MRI~\cite{RNDT24, Brown:2014uy} in this section my focus is on those pulses that I used in my experiments.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\subsection{RF-pulses}
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Every MRI pulse sequence must have at least one excitation RF-pulse.
The purpose of excitation RF-pulse is to flip the magnetization vector $\mathbf{M}$ to allow measurements of MR signal.
Hence flip angle $\theta$ is the major characteristics of the RF excitation pulses:
%.........................................................
\begin{equation}\label{eq: Flip Angle}
\theta (t) = \gamma \int \limits_{0}^t dt' B_{1}(t')
\end{equation}
%.........................................................
For spin-echo sequence~\cite{Hahn} a flip angle of $\SI{90}{\degree}$ is used while gradient echo sequences utilize a range of values $5-\SI{70}{\degree}$~\cite{RNDT24}.
To calculate magnetization after applying RF-pulse Equation~\ref{eq: Bloch transverse} is used leading to the solution given in~\cite{Joseph:1998fo}:
%.........................................................
\begin{equation}\label{eq: Bloch RF solution}
	\bar{M}\left( t \right) = i \gamma e^{-i\Delta\omega t} \int\limits_{0}^t dt' M_z\left( t' \right) B_1 (t')e^{i\Delta\omega t'}
\end{equation}
%.........................................................
where $\Delta \omega$ is off resonance angular frequency offset.
This equation states that transverse complex magnetization is directly proportional to inverse Fourier transform of the product of longitudinal component of the magnetization $M_z$ and strength of the magnetic field $B_1$.
Since $M_z$ is not constant while RF-pulse is applied a small flip angle approximation is usually used ($M_z \approx M_0$)~\cite{RNDT24} resulting in:
%.........................................................
\begin{equation}\label{eq: flip angle dependency}
	\sin{\theta} (\Delta \omega) \approx \theta (\Delta \omega)  \approx \pm \gamma \left| \int\limits_{0}^t dt' B_1 (t')e^{i\Delta\omega t'} \right|
\end{equation}
%.........................................................
Which means that the slice profile can be calculated by performing inverse Fourier transformation of the RF waveform, subject to low flip angle $\theta$.
Another important characteristics of the RF-pulse is the carrier wave frequency usually chosen at or near Larmor frequency.
Currently full body human scanners have the $\mathbf{B_0}$ field strength up to $\SI{7}{\tesla}$~\cite{Nowogrodzki:2018eb} giving the RF-pulses frequency range within $1 - \SI{300}{\MHz}$ for $\mathrm{^1H}$ imaging.
%---------------------------------------------------------
\subsubsection{SINC pulses}
%---------------------------------------------------------
One of the most common choice for an excitation RF-pulse is SINC pulse.
The RF envelope of SINC pulse can be written as following:
%.........................................................
\begin{equation}\label{eq: SINC}
\begin{aligned}
B_1(t) = \begin{cases} A t_0 \dfrac{\sin \left( \tfrac{\pi t}{t_0}\right)}{\pi t},& -N_L t_0 \leq t \leq N_R t_0\\
0,& \mathrm{elsewhere}
\end{cases}
\end{aligned}
\end{equation}
%.........................................................
where $A$ is the amplitude at $t = 0$, and $N_L$ and $N_R$  are the number of zero-crossings in the SINC pulse to the left and fight of the central peak, respectively.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If flip angle is small and the pulse is applied for infinitely long time it will result in a slice profile described by rect($\Delta \omega$) function.
Infinitely-long pulses are obviously impractical thus SINC pulse is usually truncated and apodized.
It is primarily used for selective excitation, saturation and refocusing.
Greatest advantage of SINC pulse is its uniform slice profile.
%---------------------------------------------------------
\subsubsection{The Shinnar-Le Roux (SLR) pulse}
%---------------------------------------------------------
SLR pulse design algorithm~\cite{Leroux:1990tk} allows to calculate parameters of RF-pulse from a given slice profile and  the orientation of magnetization vector $\mathbf{M}$.
The algorithm is based on two key concepts: rotations in three-dimensional space and hard pulse approximation~\cite{RNDT24}.
In three dimensions rotations are equivalently represented by $\mathbf{SO(3)}$ or $\mathbf{SU(2)}$ groups.
In $\mathbf{SU(2)}$ representation the rotation matrix $\mathbf{Q}$ is:
%.........................................................
\begin{equation}\label{eq: Rotation matrix Q}
\mathbf{Q} =
	\begin{bmatrix}
    \alpha & -\beta^*\\
    \beta & \alpha^*\\
   	\end{bmatrix}
\end{equation}
%.........................................................
where $\alpha, \beta$ are Cayley-Klein parameters.
Matrix $\mathbf{Q}$ contains total of four real numbers which together with three rotation angles needed to describe rotation in three dimensions results into a single constraint obtained from matrix $\mathbf{Q}$ being unitary:
%.........................................................
\begin{equation}\label{eq: C-K normalization}
\alpha \alpha^*+\beta\beta^* = 1
\end{equation}
%.........................................................
The total rotation as a result of multiple pulses is given:
%.........................................................
\begin{equation}\label{eq: Q rotations}
\mathbf{Q} = \mathbf{Q}_{i}\mathbf{Q}_{i-1}\cdots\mathbf{Q}_{1}
\end{equation}
%.........................................................
Hard pulse approximation allows the soft pulse to be approximated by a set of hard pulses separated by free precession time~(Figure~\ref{fig:SLR}).
%*********************************************************
\begin{figure}[!ht]
\vspace{+0.2cm}
\centering
\includegraphics[scale=0.45]{Figures/SLR.pdf}
\caption[Hard pulse approximation]{Hard pulse approximation.}
\label{fig:SLR}
\end{figure}
%*********************************************************
The effect from a series of hard pulses is approximated by series of two consecutive rotations.
The first rotation being free precession due to local gradient field by an angle $-\gamma G x \Delta t$ and the second being the rotation about applied RF vector by an angle $-\gamma B_1 \Delta t$~\cite{Pauly:1991ge}.
Representing the $j$-th state after two consecutive rotations by spinor $s_j$ gives:
%.........................................................
\begin{equation}\label{eq: SLR j-th rotation}
s_j =
\begin{bmatrix}
    \alpha_j\\
    \beta_j\\
\end{bmatrix} =
	\begin{bmatrix}
    C_j & -S_j^*\\
    S_j & \phantom{-}C_j\\
	\end{bmatrix}
	\begin{bmatrix}
    z^{1/2} & 0\\
    0 & z^{-1/2}\\
	\end{bmatrix}
	\begin{bmatrix}
    \alpha_{j-1}\\
    \beta_{j-1}\\
	\end{bmatrix}
\end{equation}
%.........................................................
where:
%.........................................................
\begin{equation}\label{eq: SLR two rotations}
\begin{aligned}
C_j &= \cos(\gamma \vert B_{1,j} \vert \Delta t /2) \\
S_j &= i e^{i \angle B_{1,j} }\sin(\gamma \vert B_{1,j} \vert \Delta t /2) \\
z &= e^{i \gamma G x \Delta t}
\end{aligned}
\end{equation}
%.........................................................
After N hard pulses are applied N-th state is given:
%.........................................................
\begin{equation}\label{eq: SLR rotation N}
s_N = z^{N/2}
\begin{bmatrix}
    A_N(z)\\
    B_N(z)\\
\end{bmatrix}
\end{equation}
%.........................................................
where $A_N(z)$ and $B_N(z)$ are two polynomials:
%.........................................................
\begin{equation}\label{eq: SLR rotation N}
\begin{aligned}
	A_N(z) & = \sum\limits_{n-1}^{j=0}\alpha_{j}z^{-j}\\[1mm]
	B_N(z) & = \sum\limits_{n-1}^{j=0}\beta_{j}z^{-j}
\end{aligned}
\end{equation}
%.........................................................
these polynomials must also satisfy normalization condition, which follows from Equation~\ref{eq: C-K normalization}:
%.........................................................
\begin{equation}\label{eq: C-K normalization polynom}
|A_N(z)|^2 + |B_N(z)|^2 = 1
\end{equation}
%.........................................................
Thus RF-pulse design becomes the inverse SLR transformation problem, where the profile of RF-pulse is calculated from the set of polynomials Equation~\ref{eq: SLR rotation N} that represent the initial and final state of the magnetization vector $\mathbf{M}$.
The only missing element at this stage is interpretation of $\mathbf{SU(2)}$ results in terms of $\mathbf{SO(3)}$ since the quantity of interest is magnetization, which is a real three-dimensional vector.
In $\mathbf{SO(3)}$ representation~\cite{1955PhRevJaynes}, components of the magnetization vector are given by the following equation:
%.........................................................
\begin{equation}\label{eq: PauliSO3_mag}
\begin{bmatrix}
    \bar{M}\phantom{^*}(+)\\
    \bar{M}^{*}(+)\\
    {M}_{z}(+)\\
\end{bmatrix} =
	\begin{bmatrix}
    (\alpha^*)^2 & -\beta^2 & 2\alpha^*\beta\\
    -(\beta^*)^2 & \alpha^2 & 2\alpha\beta^*\\
    -(\alpha\beta)^* & -\alpha\beta & \alpha\alpha^*-\beta\beta^*\\
	\end{bmatrix}
	\begin{bmatrix}
    \bar{M}\phantom{^*}(-)\\
    \bar{M}^{*}(-)\\
    {M}_{z}(-)\\
    \end{bmatrix}
\end{equation}
%.........................................................
Using Equation~\ref{eq: PauliSO3_mag} the components of magnetization vector for three most interesting special cases of given initial conditions can be summarized in a Table~\ref{tab: SLR-Table}.
%=========================================================
\begin{table}[!htb]
\vspace{+0.2cm}
\caption[Magnetization vector response to Shinnar-Le Roux RF-pulses]{Magnetization vector response to Shinnar-Le Roux RF-pulses.}
\label{tab: SLR-Table}
\begin{center}
\begin{tabular}{@{}lcc@{}}
\toprule[1pt]\midrule[0.3pt]
Pulse Type               & \multicolumn{1}{c}{\begin{tabular}[c]{@{}c@{}}Initial Condition\\ $(M_x, M_y, M_z)$\end{tabular}} & Final State \\ \midrule
Excitation or saturation &     (0, 0, $M_0$)              &    \begin{tabular}[c]{@{}l@{}}$M_x=2M_0\text{Re}(\alpha^*\beta)$\\[1mm] $M_y=2M_0\text{Im}(\alpha^*\beta)$\\[1mm] $M_z=2M_0\alpha^*\beta$\end{tabular}         \\[9mm]
Inversion                &      (0, 0, $M_0$)             &     $M_z=M_0(\alpha\alpha^*-\beta\beta^*)$   \\[3mm]
Refocus &       ($\bar{M}$, $\bar{M^*}$, 0)            &        $\bar{M}=\bar{M}(\alpha^*)^2-\bar{M^*}\beta^2$     \\[1mm] \midrule[0.3pt]\toprule[1pt]
\end{tabular}
\end{center}
\vspace{-0.2cm}
\end{table}
%=========================================================

Although SLR design algorithm accounts for nonlinearity of Bloch equations the procedure should be repeated every time that the flip angle is changed.
Among the advantages is the ability to make trade-offs between the parameters of RF-pulse, such as pulse duration, bandwidth, passband and stopband ripple, flip angle.
%---------------------------------------------------------
\subsubsection{Spectral Spatial Excitation Pulses (SPSP)}
%---------------------------------------------------------
This type of RF-pulse excites magnetization at specified location and with the specified spectral content~\cite{Schick:1998hu, Block:1997cv}.
Among the advantages of SPSP pulses is the ability to replace two different conventional pulses as well as high tolerance to the $B_1$ field inhomogeneities.
Signal from the SPSP pulses consist of a multiple short RF sub-pulses modulated by broad RF envelope combined with the bipolar slice-selective gradients~Figure~\ref{fig:SPSP}.
The broad RF envelope performs spectral selection while sub-pulses and slice selective gradients are responsible for spatial selection.
%*********************************************************
\begin{figure}[!ht]
\vspace{+0.2cm}
\centering
\includegraphics[scale=.35]{Figures/SPSP.pdf}
\caption[Spectral Spatial RF-pulse]{Spectral Spatial RF-pulse (SPSP).}
\label{fig:SPSP}
\end{figure}
%*********************************************************
When designing RF-pulse it is convenient to use the concept of RF \mbox{\textit{k-}space}.
Defining $k_{\omega}$ and $k_{z}$ to be the spectral and spatial axis respectively, then:
%.........................................................
\begin{equation}\label{eq: SPSP_kspace}
\begin{aligned}
	k_z &= \frac{\gamma}{2 \pi}\int\limits_{T_{\mathrm{end}}}^t dt' \, G_{sl}(t')\\
	k_{\omega} &= T_{\mathrm{end}}-t
\end{aligned}
\end{equation}
%.........................................................
where $G_{sl}$ is a slice selective gradient, and $T_{\mathrm{end}}$ is the end of slice rephasing gradient.
The design of SPSP pulses includes several important stages: choice of of the slice-selection gradient form as well as it's amplitude and frequency, the placement of the desired and undesired components relative to the frequency side-lobes, the form of the RF envelope, which determines the \mbox{\textit{k-}space} weighting and thus the spatial and spectral slice profiles, the length of the pulse and the modulation of these pulses to shift them in space and frequency~\cite{RNDT24}.
	\begin{itemize}
	\item For the slice-selection gradient oscillating trapezoidal lobes with minimal rise time and maximum amplitude are the possible choice. The oscillations are needed to sample $k_{\omega}$ axis. Such selection minimizes slice thickness since $\Delta z \propto 1/k_{z}$.
	\item The desired and undesired components in human MRI are usually water and fat signals respectively. Simplest option is to place water at the central lobe and fat at the null between the main lobe and the first side-lobe, so called $\mathit{true-null}$ design~\cite{Meyer:1990cv}. For example a system with $B_0 = \SI{1.5}{\tesla}$ has $f = \SI{220}{\hertz}$. The required gradient modulation frequency for this method is twice the water/fat frequency difference. The period for the slice-selective gradient is then:
%.........................................................
\begin{equation}\label{eq: SPSP_period}
	T=\frac{1}{2f}=\SI{2.27}{\milli\second}
\end{equation}
%.........................................................
The width for each trapezoidal lobe is then $T/2 = \SI{1.14}{\milli\second}$.
Alternatively for the systems with low performance gradients hardware $\mathit{opposed-null}$ method could be used~\cite{RNDT24}.
The period of the oscillating gradients is chosen to correspond to the closest secondary peak, increasing the width for each trapezoidal lobe by the factor of two.
This method is however prone to partial volume artifacts, thus is less desirable to use.
\item Lastly for the choice of the RF envelope three factors are taken into account~\cite{RNDT24}.
%.........................................................
\begin{equation}\label{eq: SPSP_RF}
B_1(t)=C(\theta)|G_z(t)|A_{spec}(t)A_{spat}(k_z)
\end{equation}
where $C(\theta)$ is a normalization factor:
%.........................................................
\begin{equation}\label{eq: SPSP_C}
	C(\theta)=\frac{1}{\gamma\displaystyle\int dt A_{spec}(t)A_{spat}(k_z)}
\end{equation}
%.........................................................
and $A_{spec}$, $A_{spat}$ is a spectral modulation envelope and spatial kernel.
Possible choices for both $A_{spec}$ and $A_{spat}$ are SINC and SLR pulses.
\end{itemize}
A well known disadvantage of SPSP pulses is that due to the short duration of the individual sub-pulse RF they are not very spatially selective and as a result have small time-bandwidth products.
That leads to either  broad spatial profiles transition regions or large minimum-slice thickness.
To address these deficiencies, SPSP pulses are typically played with a high RF duty cycle~\cite{RNDT24}.
Another issue with SPSP pulses is related to the fact that RF sub-pulses are played simultaneously with rapidly oscillating slice-selective gradients.
If eddy currents of slice-selective gradients are not accurately compensated, the actual \mbox{\textit{k-}space} trajectory will deviate from expected and the performance of the SPSP pulse will degrade.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\subsection{Gradients}
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While excitation RF-pulses create measurable MR signal, gradients perform its spatial and motion encoding.
Gradients are created by pairs of coils capable of producing additional spatial linear variation to the external field $\mathbf{B}$ in each of the three orthogonal directions.
Considering a simple case where gradient along the $x$ axis is introduced, the  magnetic field is then expressed as:
%.........................................................
\begin{equation}\label{eq: Field with gradient}
	\mathbf{B} = \mathbf{B_0} + G_x(t) \mathbf{x}
\end{equation}
%.........................................................
As a result of the spatial linear variation of the magnetic field the precession frequency for the protons will also vary linearly according to Equations~\ref{eq: Quantum Larmor frequency}~and~\ref{eq: Field with gradient}.
 Protons subject to stronger magnetic field $\mathbf{B}$ precess faster, while those subject to weaker field precess slower~(Figure~\ref{fig: ProtonGradient}).
%*********************************************************
\begin{figure}[!h]
\vspace{+0.2cm}
\centering
\includegraphics[scale=.4]{Figures/ProtonGradient.pdf}
\caption[Precession of protons in the magnetic field with the spatial linear gradient]{Precession of protons in the magnetic field with the spatial linear gradient applied.}
\label{fig: ProtonGradient}
\end{figure}
%*********************************************************
More general definition of gradients can be given in form of Jacobian:
%.........................................................
\begin{equation}\label{eq: Gradients}
	\mathbf{G}(t) =
	\begin{bmatrix}
    \dfrac{\partial B_x(t)}{\partial x} & \dfrac{\partial B_x(t)}{\partial y} & \dfrac{\partial B_x(t)}{\partial z}\\[8pt]
    \dfrac{\partial B_y(t)}{\partial x} & \dfrac{\partial B_y(t)}{\partial y} & \dfrac{\partial B_y(t)}{\partial z}\\[8pt]
    \dfrac{\partial B_z(t)}{\partial x} & \dfrac{\partial B_z(t)}{\partial y} & \dfrac{\partial B_z(t)}{\partial z}\\
	\end{bmatrix}
\end{equation}
%.........................................................
For most applications the desired shape of the gradient pulse is $\mathrm{rect}(t)$ function, which would allow instantaneous change in the magnetic field.
Yet in practice rectangular gradient pulses are impossible and are commonly approximated by trapezoid.
Two important characteristics of the gradient pulses limited by hardware capabilities are amplitude $G_{\mathrm{max}}$ and slew rate $\sigma = G_{\mathrm{max}} / \epsilon_{\mathrm{rise}}$ ~(Figure~\ref{fig: TrapGrad}).
%*********************************************************
\begin{figure}[!htb]
\vspace{+0.2cm}
\centering
\includegraphics[scale=.48]{Figures/Trapezoid.pdf}
\caption[Trapezoid gradient shape]{Trapezoid gradient shape.}
\label{fig: TrapGrad}
\end{figure}
%*********************************************************
For modern MRI systems gradients can be applied with slew rate up to $\SI{500}{\tesla / \meter / \second}$ and amplitude up to $\SI{70}{\milli\tesla / \meter}$~\cite{Tan:2020ht}, still the full performance sometimes may not be used to avoid peripheral nerve simulation~\cite{Ham:1997is}.
%---------------------------------------------------------
\subsubsection{Imaging gradients}
%---------------------------------------------------------
Every MRI pulse sequence incorporates imaging gradients.
Signal is encoded spatially in 3D using three types of gradients:
\begin{itemize}
	\item \textit{Slice selection}: First imaging gradient in the pulse sequence which accompanies the initial RF excitation pulse. Slice selection gradient is applied perpendicularly to the desired slice plane and translates the band of frequencies into the desired band of locations. For the same RF-pulse band stronger slice selection gradient results in thiner slice.
	\item \textit{Phase-encoding}: Once magnetization in the selected slice is tipped to the transverse plane phase-encoding gradient is applied. Same as shown in Figure~\ref{fig: ProtonGradient} protons will experience change in angular frequency.
%*********************************************************
\begin{figure}[!htb]
\vspace{+0.2cm}
\centering
\includegraphics[scale=.45]{Figures/PhaseEncode.pdf}
\caption[Accumulated phase due to applied gradient]{Accumulated phase due to applied gradient.}
\label{fig: PhaseEncode}
\end{figure}
%*********************************************************
	The phase-encoding gradient is then switched~off eliminating frequency variation but keeping the variation in accumulated phase intact~ Figure~\ref{fig: PhaseEncode}. Procedure should be repeated to collect data at multiple phase-encoded levels. This is achieved by varying the area under phase-encoding gradient.
	\item \textit{Frequency-encoding}: Applied continuously while the MR signal is measured it introduces spatial variation in angular frequency.\end{itemize}
Together phase- and frequency-encoding introduce an import MRI concept -- \textbf{\mbox{\textit{k-}space}}, which can be defined as a data matrix that holds phase- and frequency-encoded MR signal related to image matrix by Fourier transform.
%---------------------------------------------------------
\subsubsection{Motion-Sensitizing}
%---------------------------------------------------------
First described by Stejskal and Tanner~\cite{Stejskal} and commonly placed in the MRI sequence as a set of balanced bipolar gradients.
These gradients are utilized to quantify the dynamics of  tissue or fluid such as diffusion and flow.
Application of motion-sensitizing gradients for Velocity Encoded Phase-Contrast (VEPC) imaging and Diffusion Weighted Imaging (DWI) is discussed in more details in Chapters~\ref{ch: VEPC}~and~\ref{ch: Diffusion} respectively.
%---------------------------------------------------------
\subsubsection{Spoiler and Crusher}
%---------------------------------------------------------
Auxiliary gradients used to manipulate phase coherence of the magnetization vector.
Spoiler gradients eliminate transverse magnetization by dephasing, while crushers are used to retain desired signal pathway by either dephasing or rephasing~\cite{RNDT24}.
Crushers gradients must be used for Stimulated Echo Acquisition Mode (STEAM) which is discussed in more details in~Chapter~\ref{ch: Diffusion}.


\newpage
\subsection{Voxel Cone Tracing}\paragraph{}
With the volume data for this frame complete, the next step is to ray march through it. Voxel cone tracing is an existing ray marching technique that utilizes texture mips.

Along with a simple ray march, voxel cone tracing keeps track of the radius of a cone encompassing the ray.
The cone radius is used to sample different mip levels within the volume.
The further the ray is sampling, the larger the radius, and therefore the higher the mip level is used.

% TODO : image

For our voxel cone tracing method, we render the same billboards as before but this time from the user-camera's perspective. We use the same spherical distribution calculation to find the surface of the sphere for each billboard. This is where we begin our cone trace through the volume.

We cone trace in the direction of the light source, sampling the volume at higher and higher mip levels as we go. The end result gives us the final shading for our clouds.

\newpage % for alignment
% Code defining voxel cone trace
\begin{lstlisting}[caption={conetrace\_frag.glsl, 63}]
// Start position and direction of ray march
vec3 startPosition = calculateVoxelPosition(sphereSurfacePosition);
vec3 direction = lightPosition - startPosition;

// Scale to volume dimension's
position /= volumeDimension;
direction /= volumeDimension;

// Ray march
vec3 color = vec3(0, 0, 0);
for (int i = 1; i <= steps; i++) {
    // Update the cone radius at this step in the ray march
    // Cone angle is the angle of the cone's tip
    float coneRadius = coneHeight * tan(coneAngle / 2.f);
    // Calculate the mip level using the cone radius
    float lod = log2(max(1.f, 2.f * coneRadius));
    // Sample the volume
    vec4 sampleColor = textureLod(volume, position + coneHeight * direction, lod);
    // Update the output if the voxel is valid
    if (sampleColor.a > 0.f) {
        color += sampleColor.rgb;
    }
    coneHeight += coneRadius;
}
return color;
\end{lstlisting}\paragraph{}

% cone trace
\begin{figure}[h]
\centering
\includegraphics[width=0.85\textwidth]{../res/conetrace.png}
\caption{Cone tracing results of a single billboard}
\end{figure}

With added billboards we get the final shading of our clouds. Cone-traced shading of billboards nearer to the light will be brighter than that of billboards that are concealed.

Our cone trace method is fully paramterized. The user can change the number of ray march steps, the angle of cone's head, and the start offset of the cone along the ray.