%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                 %
%  GEANT manual in LaTeX form                                     %
%                                                                 %
%  Michel Goossens (for translation into LaTeX)                   %
%  Version 1.00                                                   %
%  Last Mod. Jan 24 1991  1300   MG + IB                          %
%                                                                 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\Origin{R.Brun, M.Maire, J.Allison}
\Documentation{M.Maire}
\Version{Geant 3.16}\Routid{CONS110}
\Submitted{01.06.83}          \Revised{08.12.93}
\Makehead{Mixtures and Compounds}
\Shubr{GSMIXT}{(IMATE,NAMATE,A,Z,DENS,NLMAT,WMAT*)}

Defines mixture or compound {\tt IMATE} as composed by
{\tt NLMAT} materials defined via
the arrays {\tt A}, {\tt Z} and {\tt WMAT}.
Mixtures of compounds can also be defined.

\begin{DLtt}{MMMMMMMMMM}
\item[IMATE]({\tt INTEGER}) user material (mixture) number;
\item[NAMATE]({\tt CHARACTER*20}) mixture name;
\item[A]({\tt REAL}) array of atomic weights;
\item[Z]({\tt REAL}) array of atomic numbers;
\item[DENS]({\tt REAL}) density in g cm$^{-3}$;
\item[NLMAT]({\tt INTEGER}) number of elements in the mixture;
\begin{DLtt}{MMMMM}
\item[$> 0$]{\tt WMAT} contains the proportion
by weights of each material in the mixture;
\item[$< 0$]{\tt WMAT} contains the proportion by number of
atoms of each kind, the content of {\tt WMAT} in output is
changed to contain the relative weights;
\end{DLtt}
\end{DLtt}

\subsection*{Method}
For a compound ({\tt NLMAT} $< 0$), the {\it molecular} weight and charge are:
\[
A_{mol} = \sum_i n_i A_i\mbox{\hspace{3cm}} Z_{mol} = \sum_i n_i Z_i
\]
where $n_i$ {\tt = WMAT(I)} is the number of atoms of the i$^{th}$
component of the molecule. In this case the proportion by weight is:
\[
 p_i = \frac{n_i A_i}{A_{mol}}
\]
where $p_i$ {\tt = WMAT(I)} in output.
From the relative weights,
\Rind{GSMIXT} works out the effective atomic weight and atomic number
according to the following formulas:
\[
A_{eff} = \sum_i p_i A_i \mbox{\hspace{3cm}}   Z_{eff} = \sum_i p_i Z_i
\]
which are stored in the {\tt JMATE} data structure {\tt [CONS199]}
together with the radiation length.

The radiation length is computed according to the EGS
manual \cite{bib-EGS3}, formula 268 (37), for an element:
\[
\frac{1} {\rho \: X_0 }=4 \alpha r_{0}^2 N_{Av}  \frac{1}{A}
     Z(Z+ \xi (Z)) \left[ \ln \frac{183}{Z^{1/3}}
      -F_c (Z) \right]
\]
where
\begin{DLtt}{MMMMMMMM}
\item[$X_0$]   radiation length (in cm);
\item[$\rho$] density (in g cm$^{-3}$);
\item[$\alpha$] fine structure constant;
\item[$r$]classical electron radius (in cm);
\item[$N_{Av}$] Avogadro's number;
\item[$A$]atomic weight;
\item[$Z$]atomic number;
\item[$F_c(Z)$] Coulomb correction function.
\end{DLtt}
\[
F_c (Z) = (\alpha Z)^2 \left[ \frac{1}
     { 1+( \alpha Z)^2}  +0.20206-0.0369( \alpha Z)^2
      +0.0083(\alpha Z)^4 -0.0020(\alpha Z)^6 \right]
\]
\[
\xi (Z) = \frac{\ln \frac{1440}{Z^{2/3}}}
        {\ln \frac{183}{Z^{1/3}} - F_c (Z)}
\]
for a compound or mixture:
\[
 \frac{1}{\rho X_0}=\sum_i \frac{p_i}{\rho_i X_{0i}}
\]
where $p_i$ is the proportion by weight of the i$^{th}$ element.
For more information on the organisation of the data in memory
see {\tt [CONS199]}.

The effective absorption length $\lambda$ is defined as
the interaction length of a 5GeV pion in the material:
\[
\frac{1}{\lambda} = \sum_i \frac{p_i}{\lambda_i}
\hspace{2cm} \frac{1}{\lambda_i} = \frac{\sigma^{\pi}_{i}(5GeV)
 N_{Av}}{A_{i}}
\hspace{0.5cm} \mbox{g$^{-1}$ cm$^{2}$}
\]
Once this value has been determined, an effective hadronic atomic weight
($A_{h-eff}$) is calculated by the routine \Rind{GHMIX} \cite{bib-GHMI}
and stored in the data structure.


\chapter{Newton's law solutions}
\begin{abox}
	Practice set 1 solutions
	\end{abox}
\begin{enumerate}
	\item The trajectory on the $z p_{z}$ - plane (phase-space trajectory) of a ball bouncing perfectly elastically off a hard surface at $z=0$ is given by approximately by (neglect friction):
	{\exyear{NET JUNE 2011}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(3)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(4)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(5)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(6)-crop}
	\end{figure}
\end{tasks}
\begin{answer}
	$$H=\frac{P_{z}^{2}}{2 m}+m g z \text { and } E=\frac{P_{z}^{2}}{2 m}+m g z$$
	The correct option is \textbf{(a)}
\end{answer}
	\item The bob of a simple pendulum, which undergoes small oscillations, is immersed in water. Which of the following figures best represents the phase space diagram for the pendulum?
	{\exyear{NET JUNE 2012}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(7)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(8)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(9)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(10)-crop}
	\end{figure}
\end{tasks}
\begin{answer}
 When simple pendulum oscillates in water it is damped oscillation so amplitude continuously decrease and finally it stops.\\
 The correct option \textbf{(d)}
\end{answer}
	\item Which of the following set of phase-space trajectories is not possible for a particle obeying Hamilton's equations of motion?
	{\exyear{NET DEC 2012}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(13)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(14)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(15)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(16)-crop}
	\end{figure}
\end{tasks}
\begin{answer}
 Phase curve does not cut each other \\
The correct option is \textbf{(b)}
\end{answer}
	\item The Hamiltonian of a classical particle moving in one dimension is $H=\frac{p^{2}}{2 m}+\alpha q^{4}$ where $\alpha$ is a positive constant and $p$ and $q$ are its momentum and position respectively. Given that its total energy $E \leq E_{0}$ the available volume of phase space depends on $E_{0}$ as
	{\exyear{NET DEC 2014}}
\begin{tasks}(2)
	\task[\textbf{A.}] $E_{0}^{3 / 4}$
	\task[\textbf{B.}]$E_{0}$
	\task[\textbf{C.}]$\sqrt{E_{0}}$
	\task[\textbf{D.}]is independent of $E_{0}$
\end{tasks}
\begin{answer}$\left. \right. $\\
\begin{minipage}{0.5\textwidth}
$H=\frac{p^{2}}{2 m}+\alpha q^{4}$
Phase area $=\oint p \cdot d q$
$$
\begin{aligned}
&A=\oint p \cdot d q=\pi \sqrt{2 m E} \times\left(\frac{E}{\alpha}\right)^{\frac{1}{4}} \\
&A \propto E_{0}^{1 / 2} \cdot E_{0}^{1 / 4} \Rightarrow A \propto E_{0}^{3 / 4}
\end{aligned}
$$
\end{minipage}
\begin{minipage}{0.5\textwidth}
	\begin{figure}[H]
		\centering
		\includegraphics[height=5cm,width=5cm]{diagram-20210926(21)-crop}
	\end{figure}
\end{minipage}
The correct option is \textbf{(a)}
\end{answer}

	\item Which of the following figures is a schematic representation of the phase space trajectories (i.e., contours of constant energy) of a particle moving in a one-dimensional potential $V(x)=\frac{-1}{2} x^{2}+\frac{1}{4} x^{4}$
	{\exyear{NET JUNE 2015}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(24)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(25)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(26)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(27)-crop}
	\end{figure}
\end{tasks}
\begin{answer}$\left. \right. $\\
	\begin{minipage}{0.5\textwidth}
	$V(x)=\frac{-x^{2}}{2}+\frac{x^{4}}{4}$
	$$
	\frac{\partial V}{\partial x}=0 \Rightarrow x=0, x=\pm 1
	$$
	$$
	\begin{aligned}
	&\frac{\partial^{2} V}{\partial x^{2}}=-v e \text { for } x=0 \text { (unstable point) } \\
	&=+\text { ve for } x=\pm 1 \text { (stable point) }
	\end{aligned}
	$$
	\end{minipage}
	\begin{minipage}{0.5\textwidth}
	\begin{figure}[H]
		\centering
		\includegraphics[height=5cm,width=5cm]{diagram-20210926(28)-crop(2)}
		\caption{}
		\label{}
	\end{figure}
	\end{minipage}
The correct option is \textbf{(a)}
\end{answer}
	\item A particle moves in one dimension in a potential $V(x)=-k^{2} x^{4}+\omega^{2} x^{2}$ where $k$ and $\omega$ are constants. Which of the following curves best describes the trajectories of this system in phase space?
	{\exyear{NET DEC 2017}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(42)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(43)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(44)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210926(45)-crop}
	\end{figure}
\end{tasks}
\begin{answer}$\left. \right. $\\
	\begin{minipage}{0.5\textwidth}
	$V(x)=-k^{2} x^{4}+\omega^{2} x^{2}$\\
	For equation point\\
	$
	\frac{\partial V}{\partial x}=0 \Rightarrow-4 k^{2} x^{3}+2 \omega^{2} x=0, x=0 \text { or } x^{2}=\frac{\omega^{2}}{2 k^{2}}
	$\\
	Now, $\frac{d^{2} V}{d x^{2}}=-12 k^{2} x^{2}+2 \omega^{2}$ At, $x=0$\\
	$\frac{d^{2} V}{d x^{2}}=2 \omega^{2}, x=0$ is minimum.\\
	And, $\frac{d^{2} V}{d x^{2}}=-12 k^{2} \frac{\omega^{2}}{2 k^{2}}+2 \omega^{2}=-4 \omega^{2}$, at $x^{2}=\frac{\omega^{2}}{2 k^{2}}$\\
	Hence, $x=\pm \sqrt{\frac{\omega^{2}}{2 k^{2}}}$ is maxima.
	\end{minipage}
	 \begin{minipage}{0.5\textwidth}
	 \begin{figure}[H]
	 	\centering
	 	\includegraphics[height=4cm,width=5cm]{diagram-20210926(46)-crop}
	 \end{figure}
	 \end{minipage}
 The correct option is \textbf{(c)}
\end{answer}
\end{enumerate}
\newpage
\begin{abox}
	Practice set 2 solutions
	\end{abox}
\begin{enumerate}
	\item The Hamiltonian of particle of mass $m$ is given by $H=\frac{p^{2}}{2 m}-\frac{\alpha q^{2}}{2}$. Which one of the following figure describes the motion of the particle in phase space?
	{\exyear{GATE 2014}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=4cm,width=5cm]{diagram-20210915(5)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=4cm,width=5cm]{diagram-20210915(6)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=4cm,width=5cm]{diagram-20210915(7)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=4cm,width=5cm]{diagram-20210915(8)-crop}
	\end{figure}
\end{tasks}
\begin{answer}
	The corrrect option is \textbf{(d)}
\end{answer}
	\item A particle moves in one dimension under a potential $V(x)=\alpha|x|$ with some non-zero total energy. Which one of the following best describes the particle trajectory in the phase space?
	{\exyear{GATE 2018}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(11)-crop}

	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(12)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(13)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(14)-crop}
	\end{figure}
\end{tasks}
\begin{answer}$\left. \right. $\\
\begin{minipage}{0.5\textwidth}
 $E=\frac{p^{2}}{2 m}+\alpha|x|$
	For $x>0, E=\frac{p^{2}}{2 m}+\alpha x$ $\Rightarrow p^{2}=2 m(E-\alpha x)$
	For $x<0, E=\frac{p^{2}}{2 m}-\alpha x$ $\Rightarrow p^{2}=2 m(E+\alpha x)$
\end{minipage}
\begin{minipage}{0.5\textwidth}
\begin{figure}[H]
	\centering
	\includegraphics[height=3cm,width=4cm]{diagram-20210915(15)-crop}
\end{figure}
\begin{figure}[H]
	\centering
	\includegraphics[height=3cm,width=5cm]{diagram-20210915(16)-crop}
\end{figure}
\end{minipage}
The correct option is \textbf{(a)}
\end{answer}
	\item A ball bouncing of a rigid floor is described by the potential energy function
	$$
	V(x)=\left\{\begin{array}{lll}
	m g x & \text { for } & x>0 \\
	\infty & \text { for } & x \leq 0
	\end{array}\right.
	$$
	Which of the following schematic diagrams best represents the phase space plot of the ball?
	{\exyear{GATE 2019}}
\begin{tasks}(2)
	\task[\textbf{A.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(18)-crop}
	\end{figure}
	\task[\textbf{B.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(19)-crop}
	\end{figure}
	\task[\textbf{C.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(20)-crop}
	\end{figure}
	\task[\textbf{D.}]\begin{figure}[H]
		\centering
		\includegraphics[height=3cm,width=5cm]{diagram-20210915(21)-crop}
	\end{figure}
\end{tasks}
\begin{answer}
	$E=\frac{p^{2}}{2 m}+m g x \Rightarrow p^{2}=2 m(E-m g x) \text { which is equation of parabola }$\\
	The correct option is \textbf{(b)}
\end{answer}
\end{enumerate}

Classical Mechanics  -CSIR/chapter/Newton's law solutions.tex


\documentclass[12]{scrartcl}
\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}
\usepackage{float}
\restylefloat{table}
\makeatletter
\newcommand\Aboxed[1]{
   \@Aboxed#1\ENDDNE}
\def\@Aboxed#1&#2\ENDDNE{%
   &
   \settowidth\@tempdima{$\displaystyle#1{}$}
   \setlength\@tempdima{\@tempdima+\fboxsep+\fboxrule}
   \kern-\@tempdima
   \boxed{#1#2}
}
\makeatother

\begin{document}

\title{Homework 28, Section 5.3: 1, 6, 9, 12, 13, 15, 19, 28
}
\author{Alex Gordon}
\date{\today}
\maketitle
\section*{Homework}
\subsection*{1. A)}
ab, ac, ad, ae, ba, bc, bd, be, ca, cb, cd, ce, da, db, dc, de, ea, eb, ec, ed
\subsection*{1. B)}
\begin{table}[H]
    \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|}
    \hline
    ab & ac & ad & ae & bc & bd & be & cd & ce & de \\
    ba & ca & da & ea & cb & db & eb & dc & ec & ed \\ \hline
    \end{tabular}
\end{table}
\subsection*{1. C)}
2, 10
\subsection*{1. D)}
10 permutations
\subsection*{6.}
You can solve the solution through placing the couples last names in a circle (there are 24 ways to do this) and then decide whether the man or the woman will stand on the right, of which there are 32 ways, meaning there are 768 ways to arrange the couples.
\subsection*{9.}
$C(5,2)$
\subsection*{12.}
$P(6, 3) = 120$
\subsection*{13.}
$C(17, 3) = 680$
\subsection*{15. A)}
$C(21, 4) = 5,985$
\subsection*{15. B)}
$C(12,2)\cdot C(9, 2)  = 2,376$
\subsection*{15. C)}
2475
\subsection*{19. A)}
$2^8 = 256$
\subsection*{19. B)}
There are 2 possibilities
\subsection*{19. C)}
$C(8,3) = 56$
\subsection*{28. A)}
$3^6 = 729$
\subsection*{28. B)}
90 possibilities.
\end{document}


\section{CRWP Mobility Model}
\label{sec:mobility-model}

Here, we propose the Cyclical Random Waypoint Mobility Model (CRWP), a mobility model based on the Random Waypoint~\cite{bai2004survey}. CRWP is useful to model scenarios where some of the entities move to different destinations, and eventually, they return to their initial positions. Which is the case of people and their portable devices in offices, universities, hospitals, factories, etc.

In CRWP, the entities move independently to random destinations and speeds as in RWP. When an entity arrives at the destination, it stops for a given time $T_{pause}$. A difference in CRWP is that after $n$ chosen destinations, the mobile entity returns to its initial position. Besides that, only $k\%$ of mobile entities are outside of their initial position in each instant of time.
CRWP has four parameters:
\begin{inparaenum}[i)]
    \item \textit{PerMobNodes:} maximum percentage of entities that are mobile in each instant of time;
    \item \textit{Stops:} number of stops that the mobile entity do before returning to its original position;
    \item \textit{Speed:} speed which the mobile entity moves;
    \item \textit{$T_{pause}$:} the amount of time that the entity stays in a destination position.
\end{inparaenum}


\section{Brownian Motion}
\label{sec:chapter1}

\subsection{The Brownian motion discovery}

In 1827 the Scottish botanist Robert Brown published an article \cite{robert_xxvii_1828} on his observation on the pollen of \textit{Clarkia pulchella} with a lot of details on his reflection processes. His experiments were made to understand the flower reproduction, but, as he was looking through the microscope he observed some minute particles ejected from the pollen grains. At first, he thought the goal of this agitation was to test the presence of a male organ. To test this theory, he extended his observations to Mosses and \textit{Equiseta}, which were drying for a hundred years. However, the fact that this peculiar motion was still observable made him invalidate his theory. Interestingly, each time that he encountered a material that he could reduce to a fine enough powder to be suspended in water, he observed the same type of motion, although, he never understood its particle's movement.

The difficulty at this time to observe and capture such a movement made the study of what we call contemporarily Brownian motion difficult and the first theoretical work was done by Louis Bachelier in his PhD thesis ``The theory of speculation," where he described a stochastic analysis of the stock and option market. Nowadays, the mathematical description of random movement is still used in the modern financial industry.

It is finally in 1905 that Albert Einstein theoretically state that ``bodies of microscopically visible size suspended in a liquid will perform movements of such a magnitude that they can be easily observed in a microscope" \cite{einstein_uber_1905}. A remark to make here is that in 1948 Einstein wrote a letter to one of his friends where he stated having deduced the Brownian motion ``from mechanics, without knowing that anyone had already observed anything of the kind" \cite{peter_brownian_nodate}.

It is in 1908 that Jean Perrin published his experimental work on Brownian motion. That way he could measure the Avogadro number and prove the kinetic theory that Einstein developed. I would also cite Chaudesaigues and Dabrowski, who helped Perrin to track the particles manually, half-minutes by half-minutes, for more than 3000 displacements (25 hours) and several particles. This impressive and daunting work is highly detailed in \textit{``Mouvement brownien et molécules"} \cite{perrin_mouvement_1910}. This is partly due to the results of this work that Perrin received the Nobel award in 1926.

\begin{figure}[h]
	\centering
	\includegraphics[scale=0.6]{02_body/chapter1/image/graph_perrin.png}
	\caption{Brownian motion of $1 ~ \mathrm{\mu m}$ particles in water tracked manually by Jean Perrin and his colleagues. The points are spaced in time by 30 seconds, and 16 divisions represent $50 ~ \mathrm{\mu m}$.}
	\label{fig:Perrin_Brownian}
\end{figure}

\subsection{Einstein's Brownian theory}

In this section we derive the main characteristics of bulk Brownian motion in the manner of Einstein in 1905 by summarizing the section 4 of \cite{einstein_uber_1905}. We then examine  the random motion of particles suspended in a liquid and its relation to diffusion, caused by thermal molecular motion. We assume that each particle motion is independent of other particles; also the motions of one particle at different times are assumed to be independent of one another provided that the time interval is not too small. Furthermore, we introduce a time interval $\tau$ which is small compared to the observation time but large enough so that  the displacements in two consecutive time intervals $\tau$ may be taken as independent events.

For simplicity, we will here look only at the Brownian motion of $n$ particles in 1D along the $x$ axis. In a time interval $\tau$ the position of each particle will increase by a displacement $\Delta$, positive or negative. The number of particles $\textnormal{d}n$ experiencing a displacement lying between $\Delta$ and $\Delta + \textnormal{d}\Delta$ in a time interval $\tau$ is written as:

\begin{equation}
	\textnormal{d}n = n\varphi(\Delta)\textnormal{d}\Delta ~,
\end{equation}

where:

\begin{equation}
	\int_{-\infty} ^{\infty} \varphi (\Delta)\textnormal{d} \Delta = 1 ~,
	\label{Eq:ein_def_phi}
\end{equation}

and $\varphi$ is the probability distribution of displacement. We assume for now, that  $\varphi$ is a Gaussian distribution, with a variance scaling linearly with $\tau$. Additionally, since such a distribution is even, it satisfies: $\varphi (\Delta) = \varphi (-\Delta)$.

Let $f(x,t)$ be the number of particles per unit volume. From the definition of the function $\varphi(\Delta)$ we can obtain the distribution of particles found at time $ t + \tau$ from their distribution at a time $t$, through:

\begin{equation}
	f(x, t+\tau) = \int_{-\infty} ^{ +\infty} f(x-\Delta, t) \varphi (\Delta) \textnormal{d}\Delta ~.
	\label{Eq:Ein_first}
\end{equation}

Since we suppose that $\tau$ is very small with respect to  $t$, we have at first order in time:

\begin{equation}
	f(x, t+\tau) \simeq f(x,t) + \tau \frac{\partial f}{\partial t} ~.
	\label{eq:e1}
\end{equation}

Besides, we can Taylor expand $f(x+\Delta, t)$ in powers of $\Delta$ since only small values of $\Delta$ contribute. We obtain:

\begin{equation}
	f(x - \Delta, t) = f(x,t) - \Delta \frac{\partial f(x,t)}{\partial x} + \frac{\Delta ^2}{2!} \frac{\partial ^2 f(x,t)}{\partial x^2} ~.
	\label{eq:e2}
\end{equation}

Combining Eqs.\ref{eq:e1}, \ref{eq:e2} and \ref{Eq:Ein_first} we obtain:

\begin{equation}
	f + \frac{\partial f}{\partial t} \tau = f \int_{-\infty}^{+\infty} \varphi(\Delta)\textnormal{d} \Delta + \frac{\partial f}{\partial x} \int_{-\infty}^{+\infty} \Delta \varphi (\Delta)\textnormal{d} \Delta + \frac{\partial ^2 f}{\partial x^2} \int_{-\infty}^{+\infty} \frac{\Delta ^2}{2} \varphi(\Delta)\textnormal{d}\Delta ~.
	\label{Eq:ein_expended}
\end{equation}

On the right-hand side, since $\varphi(x)$ is an even function, the second term vanishes. Considering Eq.~(\ref{Eq:ein_def_phi}) and invoking the following definition:

\begin{equation}
	\frac{1}{\tau} \int_{-\infty}^{+\infty} \frac{\Delta^2}{2}\varphi(\Delta)\textnormal{d}\Delta = D ~,
\end{equation}

Eq.~(\ref{Eq:ein_expended}) finally becomes:

\begin{equation}
	\frac{\partial f}{\partial t} = D \frac{\partial ^2 f}{\partial x ^2} ~.
	\label{Eq.HeatEquation}
\end{equation}

We can here recognize a partial equation of diffusion with $D$ the diffusion coefficient. We will now initiate the same position $x=0$ for all the particles at $t=0$ as in Fig.\ref{fig:bulkbrown}. $f(x,t)\textnormal{d}x$ denotes the number of particles whose positions have increased between the times  $0$ and $t$  by a quantity lying between $x$ and $x + dx$ such that we must have:

\begin{equation}
	f(x \ne 0, t=0) = 0 \text{ and } \int_{-\infty}^{+\infty}f(x,t)dx = n ~.
\end{equation}

The solution Eq.~(\ref{Eq.HeatEquation}) is then the Green's function of the heat equation in the bulk:

\begin{equation}
f(x,t) = \frac{1}{\sqrt{4\pi D}} \frac{\exp \left(\frac{-x^2}{4Dt} \right)}{\sqrt{t}} ~.
\end{equation}

From this solution we can see that the mean value of the displacement along the $x$ axis is equal to $0$ and the square root of the arithmetic mean of the squares of displacements (that we commonly call the Root Mean Square Displacement (R\gls{MSD}))  is given by:
\begin{equation}
	\lambda _x = \sqrt{\langle \Delta ^2 \rangle} =  \sqrt{2Dt}.
	\label{Eq:MSD_ein}
\end{equation}

The mean displacement is thus proportional to the square root of time. This result is generally the first behavior that we check when we study Brownian motion. In 3D, the square root of the \gls{MSD} is given by $\lambda_x \sqrt{3}$.

Previously in his article \cite{einstein_uber_1905}, Einstein had found by writing the thermodynamic equilibrium of a suspension of particles that the diffusion coefficient of a particle should read:

\begin{equation}
	D = \frac{R T}{N_\mathrm{A}}\frac{1}{6\pi \eta a} = \frac{k_\mathrm{B}T}{6 \pi \eta a}
	~,
	\label{Eq:D_einstein}
\end{equation}

\nomenclature{$R$}{Gas constant}
\nomenclature{$N_\mathrm{A}$}{Avogrado constant}
\nomenclature{$k_\mathrm{B}$}{Boltzmann Constant}
\nomenclature{$D$}{Diffusion coefficient, see Eq.~(\ref{Eq:D_einstein})}

with $R$ the gas constant, $T$ the temperature, $N_\mathrm{A}$ the Avogadro number, $\eta$ the fluid viscosity and $k_\mathrm{B}$ the Boltzmann constant. Thus, an experimental measurement of $D$ lead to a measurement of the Avogadro number since:

\begin{equation}
	N_\mathrm{A} = \frac{t}{\lambda_x^2} \frac{RT}{3\pi \eta a} ~.
\end{equation}

Furthermore, measuring $N_\mathrm{A}$ also gives us the mass of atoms and molecules since the mass of a mole is known; as an example the mass of an oxygen atom will be given by $\left(\frac{16}{N_\mathrm{A}}\right)$ and the mass of a water molecule by $\frac{18}{N_\mathrm{A}}$. Finally, Einstein ends up is article \cite{einstein_uber_1905} by writing, \textit{``Let us hope that a researcher will soon succeed in solving the problem posed here, which is of such importance in the theory of heat!"} I would like here to emphasize the importance of solving this problem at the very beginning of the 20th century. At this time two hypotheses about the fundamental matter components existed, one involving energy and a continuum description in terms of field, and the other one, discrete atoms, especially supported by Boltzmann and his kinetic theory of gases, used by Einstein. Due to a lot of conceptual misunderstandings and experimental error scientist such as Svedberg or Henri thought that Einstein's theory was false \cite{genthon_concept_2020} by even suggesting that the statistical properties of Brownian motion were changing with the pH of the solution. It is finally in 1908 that Chaudesaigues and Perrin published all the evidence to prove Einstein's theory mainly by their ability to create particle emulsions of well-controlled radii.

\begin{figure}[!h]
	\centering
	\includegraphics{02_body/chapter1/image/brown_exemple.pdf}
	\caption{Simulation of over-damped Brownian motion in the bulk (see Eq.~(\ref{Eq.shortnumlangevin})) of $1 ~ \mathrm{\mu m}$ particles in water. On the top each line represents the trajectory of a Brownian particle over 100 seconds. A total of 100 trajectories are shown. On the bottom, bullets represent the Mean Square Displacement (\gls{MSD}) computed from the simulated trajectories. The plain black line represents Einstein's theory, which is computed from the square of Eq.~(\ref{Eq:MSD_ein}).\href{https://github.com/eXpensia/Confined-Brownian-Motion/blob/main/02_body/chapter1/image/simple_Brownian.ipynb}{\faGithub}}
	\label{fig:bulkbrown}
\end{figure}

\subsection{The Langevin Equation}

in physics we generally describe Brownian motion through a particular Stochastic Differential Equations (\gls{SDE}). This model was introduced in 1908 by Langevin \cite{langevin_sur_1908}, this model is now used by the major part of physicists working on random processes. The Langevin equation for a free colloid reads:

\begin{equation}
	m \textnormal{d}V_t  = - \gamma V_t \textnormal{d}t + g \textnormal{d}W ~,
	\label{Eq.langevinEquation}
\end{equation}

\nomenclature{$V_t$}{Velocity of a particle}
\nomenclature{$g$}{Noise amplitude}
\nomenclature{$T$}{Temperature}

with $m$ the mass and $V_t$ the velocity of the particle. This \gls{SDE} is the Newton's second law, relating the particle momentum change on the left-hand side of the equation to forces on the right-hand side. We see that the total force applied on the particle is given by two terms: a friction term, with a Stokes-like fluid friction coefficient $\gamma$, a random force with $g$ that we will detail for a spherical particle, $\mathrm{d}W$ a random noise which has a Gaussian distribution of zero mean thus:

\begin{equation}
	\langle \textnormal{d}W \rangle  = 0~,
	\label{Eq.meandbt}
\end{equation}

and variance equal to:

\begin{equation}
	\langle \textnormal{d}W ^2 \rangle = \textnormal{d}t~.
	\label{Eq.meandbt2}
\end{equation}

For a spherical particle, the friction term is given by the Stoke's formula: $\gamma = 6\pi \eta a$ with $\eta$ the fluid viscosity and $g$ the particle radius. Thus, we can derive the mean value of the particle velocity as:

\nomenclature{$\eta$}{Fluid viscosity}
\nomenclature{$\gamma$}{Friction coefficient}

\begin{equation}
	\left\langle   \textnormal{d}V_t \right\rangle = - \frac{\gamma}{m} \langle V_t \rangle \textnormal{d}t  + \frac{g}{m} \langle  \textnormal{d}W \rangle ~,
	\label{Eq.langevinsd}
\end{equation}

\nomenclature{$m$}{Mass of a particle}
with the properties of $dB_t$ given by Eq.~(\ref{Eq.meandbt}), it becomes:

\begin{equation}
	\langle  \textnormal{d}V_t \rangle = - \frac{\gamma}{m} \langle V_t \rangle \textnormal{d}t ~.
	\label{Eq.dvt}
\end{equation}

Moreover, without a loss of generality, the average of a variable $x$, $\langle x \rangle$, is done over a set of $N$ observations $\{x_i\}$ such as:

\begin{equation}
	\langle x \rangle = \frac{1}{N} \sum _{i=1}^N x_i ~,
\end{equation}

one can then show that:

\begin{equation}
	\frac{\textnormal{d}}{\textnormal{d}t}\langle x \rangle = \frac{\textnormal{d}}{ \textnormal{d}t} \left[\frac{1}{N} \sum _{i=1}^N x_i \right] =
	\frac{1}{N} \sum _{i=1}^N \frac{\textnormal{d}}{ \textnormal{d}t} x_i = \langle\frac{\textnormal{d}}{\textnormal{d}t} x \rangle ~.
\end{equation}

The latter thus shows that it is possible to invert average value $\langle \cdot \rangle$ and a derivative. Therefore, Eq.~(\ref{Eq.dvt}) becomes:

\begin{equation}
	\frac{ \textnormal{d}}{\textnormal{d}t}\langle V_t \rangle = - \frac{\gamma}{m} \langle V_t \rangle ~,
\end{equation}

which has a familiar solution:
\begin{equation}
	\langle V_t (t) \rangle =   V_0 \mathrm{e}^{-\frac{\gamma}{m} t}~,
	\label{Eq.int_V_langevin}
\end{equation}

with $V_0$ an initial velocity. This result shows that the average of the velocity should decay to zero with a characteristic time $\tau_\mathrm{B} = \frac{m}{\gamma}$. For instance, the polystyrene particles used during my experiments which are micrometric we have $\tau_\mathrm{B} \approx 10^{-7}$ s. This signifies that if we measure the displacements of a particle with a time interval $ \tau  >> \tau _\mathrm{B} $ the displacement can be taken as independent events as it was stated by Einstein. In physical terms, this means that we are in the over-damped regime, in this case the Langevin equation reads:

\begin{equation}
-\gamma V_t \textnormal{d}t  + g  \textnormal{d}W = 0~.
\label{Eq.overdamped_SDE}
\end{equation}

The experiments done during my thesis used a video camera that can reach a maximum of hundreds frames per second (\gls{fps}) reaching time steps of $\approx 10^{-2}$ s. Therefore, all my work falls into the over-damped regime. Before focusing definitely on Eq.~(\ref{Eq.overdamped_SDE}), we can use Eq.~(\ref{Eq.langevinsd}) to characterize further the unknown coefficient $g$. To do so we compute the mean square value of Eq.~(\ref{Eq.langevinsd}), starting by taking the second order Taylor expansion:

\begin{equation}
	\begin{aligned}
		\textnormal{d}\left(V_t^2\right) &\simeq \frac{\partial V_t ^ 2}{\partial V_t} \textnormal{d} V_t + \frac{1}{2} \frac{\partial ^2 V_t^2}{\partial V_t ^2} \left( \textnormal{d}V_t \right)^2  \\
		& = 2 V_t \textnormal{d}V_t + (\textnormal{d}V_t)^2 \\
	\end{aligned}
	\label{Eq.compute1}
\end{equation}

combining Eqs.~(\ref{Eq.langevinEquation})~and~(\ref{Eq.compute1}), we obtain by only keeping  the terms of order $\textnormal{d}t$:

\begin{equation}
	\textnormal{d}\left(V_t^2\right) = 2V_t\left( -\frac{\gamma}{m}V_t\textnormal{d}t + \frac{g}{m}\textnormal{d}W  \right) + \frac{g^2}{m^2}\textnormal{d}W ^2 ~.
\end{equation}

Thus, the average value of $ \textnormal{d}(V_t ^2)$ reads:

\begin{equation}
	\langle \textnormal{d}(V_t ^2)\rangle = -2 \frac{\gamma}{m} \langle V_t ^2 \rangle \textnormal dt + 2 \frac{g}{m} \langle V_t \textnormal{d}W \rangle + \frac{g^2}{m^2} \langle \textnormal{d}W ^2 \rangle~.
	\label{Eq.dvt2}
\end{equation}

Moreover, since $\textnormal{d}W$ is chosen independently of the velocity $V_t$, one can write $\langle V_t \textnormal{d}W \rangle $ = $\langle V_t \rangle \langle \textnormal{d}W \rangle  =0 $. Taking the latter remark into account and the fact that $\langle \textnormal{d}W ^2\rangle = \textnormal{d}t $, Eq.~(\ref{Eq.dvt2}) becomes:

\begin{equation}
	\langle d(V_t^2) \rangle = \left[-2 \frac{\gamma}{m} \langle V_t ^2 \rangle + \frac{g^2}{m^2}\right]\textnormal{d}t~.
\end{equation}

Since equilibrium averages in thermodynamics must become time independent, we have $\langle d(V_t^2) \rangle = 0$, thus:

\begin{equation}
	\langle V_t ^2\rangle = \frac{g ^2}{2 \gamma m}~.
\end{equation}

Besides, from the equipartition of energy we also know that:

\begin{equation}
	\langle \frac{1}{2} m V_t ^2 \rangle  = \frac{1}{2} k_\mathrm{B} T~.
\end{equation}

The latter equation permits a direct determination of the amplitude of the noise $g$:

\begin{equation}
	g = \sqrt{2k_\mathrm{B}T \gamma}~.
\end{equation}

The latter result permits computing the amplitude of the random force in the Langevin equation. Taking the over-damped Langevin equation, it reads:

\begin{equation}
	V_t\textnormal{d}t  = \sqrt{2\frac{k_\mathrm{B}T}{\gamma}} \textnormal{d}W
	\label{Eq.v_t_ovdmp}
\end{equation}

Furthermore, one can write the position of the particle $X_t$ at a time $t$, such as:

\begin{equation}
	X_t = \int _0 ^t V_{t'}dt'~,
	\label{Eq:particle_position}
\end{equation}

where we can suppose at the initial time $t=0$ that $X_0 = 0$. Computing
$\langle X_t^2 \rangle$ using Eqs.~(\ref{Eq.v_t_ovdmp}),~(\ref{Eq:particle_position})~and~(\ref{Eq.meandbt2}) thus gives:

\begin{equation}
	\langle X_t ^2 \rangle =  2\frac{k_\mathrm{B}T}{\gamma}t = 2Dt
	\label{Eq.xt2}
\end{equation}

By relating $\langle X_t ^2 \rangle$ to the Mean Square Displacement (\gls{MSD}) to the initial position such as:

\begin{equation}
	\textnormal{MSD} = \langle (X_0 - X_ t)^2 \rangle =  \langle X_t ^2 \rangle~,
\end{equation}

we obtain that the \gls{MSD} should be linear with the time. This result confirms that using the over-damped Langevin equation, leads to the Einstein's result Eq.~(\ref{Eq:MSD_ein}). Where one can identify the diffusion coefficient of the particle to be $D = k_\mathrm{B}T / \gamma$. Additionally, the latter identity is called the Stokes-Einstein  relation.

Additionally, the Langevin equation can be used to compute correlator such as the velocity correlator $ \langle V_{t'}V_{t''} \rangle$ that we will detail below. Indeed, if we use the full-Langevin equation, $\langle X_t ^2 \rangle$ cannot be easily computed since $m\textnormal{d} V_t$ does not vanish. We would thus need to rewrite Eq.~(\ref{Eq.xt2})  using the velocity correletor such as:

\begin{equation}
	\langle X_t ^ 2 \rangle  = \int _0 ^ {t} \int _0 ^{t} \langle V_{t'}V_{t''} \rangle dt'dt'' ~.
	\label{Eq.int_msd}
\end{equation}

Let us now study how the two-point correlator function $ \langle V_{t'}V_{t''} \rangle $, using the full-Langevin equation multiplied by $V_0$ and following the same steps as for Eq.~(\ref{Eq.int_V_langevin}), one  has:

\begin{equation}
	\langle V_t V_0 \rangle = \langle V_0 ^2 \rangle \mathrm{e}^{-t/\tau_{\mathrm{B}}}~.
\end{equation}

As the equilibrium state is invariant under temporal translation and assuming that $V_0$ has an equilibrium steady-state distribution with $\langle V_0^2 \rangle = k_\mathrm{B} T / m$ we have:

\begin{equation}
	\langle V_t V_t' \rangle = \frac{k_\mathrm{B}T}{m} \mathrm{e}^{-|t-t'|/\tau_{\mathrm{B}}}~.
\end{equation}

One can solve Eq.~(\ref{Eq.int_msd}) by splitting the integral in two parts, where $t'>t''$ and $ t' < t''$:

\begin{equation}
	\begin{aligned}
		\langle X_t ^2 \rangle & =    \frac{k_\mathrm{B}T}{m}  \int _0 ^t \textnormal{d}t' \int _0 ^{t'} \textnormal{d}t'' \mathrm{e} ^ {- |t' - t''| / \tau_\mathrm{B}} = 2 \frac{k_\mathrm{B}T}{\gamma} \left( \int_0 ^t \textnormal{d}t' \left[1 - \mathrm{e}^{-t'/\tau_\mathrm{B}} \right] \right) \\
		& = 2 \frac{k_\mathrm{B} T}{\gamma} \left( t - \tau_\mathrm{B} \left[ 1 - \mathrm{e}^{-t/\tau_\mathrm{B}} \right] \right) ~.
	\end{aligned}
\end{equation}

We can extract two results from that equation. At a short time $t << \tau_\mathrm{B}$, one has:

\begin{equation}
	\begin{aligned}
		\langle X_t ^2 \rangle & \simeq  2 \frac{k_\mathrm{B} T}{\gamma} \left( t - \tau_\mathrm{B} \left[ 1 - 1 + \frac{t}{\tau_\mathrm{B}} - \frac{t^2}{ 2 \tau_\mathrm{B} ^2}\right]         \right) \\
		& = \frac{k_\mathrm{B} T}{m} t^2 ~.
	\end{aligned}
	\label{Eq.shorttimemsd}
\end{equation}

This is the ballistic regime. If one can experimentally explore times shorter than $\tau _ \mathrm{B} $ one will then measure the instantaneous velocity of the particle. At longer times, $t >> t_\mathrm{B}$, the \gls{MSD} is given by:

\begin{equation}
	\langle X_t ^2 \rangle \simeq 2 \frac{k_\mathrm{B}T}{\gamma} t = 2Dt ~.
	\label{eq:longtimemsd}
\end{equation}

This is the diffusive regime where the \gls{MSD}, as found earlier, Eq.~(\ref{Eq.xt2}) with the over-damped Langevin equation. To study this different result, it can be interesting to simulate the Brownian motion.

\subsection{Numerical simulation of bulk Brownian motion}

\subsubsection{The numerical Langevin Equation}

\begin{figure}[!hb]
	\centering
	\includegraphics{02_body/chapter1/image/noise_simulation/exemple.pdf}
	\caption{Bullets represents the probability density function of $w_i$, a Gaussian-distributed number with a mean value $\langle w_i \rangle$ and a variance $\langle w_i ^2 \rangle  = \tau$. The plain black line is a Gaussian distribution of zero mean and a variance $\tau$ (see Eq.~(\ref{eq.pwi})). In the first row, the simulation is done with $\tau = 10^{-3}$ s and $\tau = 1$ s on the second one. Each column corresponds to a number $N$ of draws. From the left to the right: $N=10^2, ~10^3 \text{ and } 10^4$.\href{https://github.com/eXpensia/Confined-Brownian-Motion/blob/main/02_body/chapter1/image/noise_simulation/noise_simulation.ipynb}{\faGithub}}
	\label{fig:exempleprecisionwi}
\end{figure}

The Langevin equation is an ordinary differential equation that can easily be numerically simulated in the bulk case. We approximate the continuous position $X_t$ of a particle at a time $t$ by a discrete-time sequence $x_i$ which is the solution of the equation at a time $t_i = i  \tau$, $\tau$ being the time step of the simulation. One can then use the Euler method to numerically write $V_t$ as:

\begin{equation}
	V_t \simeq \frac{x_i - x_{i-1}}{\tau} ~,
	\label{Eq.vtnum}
\end{equation}

and $\textnormal{d}V_t / \textnormal{d}t$ as

\begin{equation}
	\begin{aligned}
		\frac{\textnormal{d}V_t}{\textnormal{d}t} &\simeq
		\frac{
			\frac{x_i - x_{i-1}}{\tau}
			-
			\frac{x_{i-1} - x_{i-2}}{\tau}
		}
		{\tau} \\
		& =  \frac{x_i - 2x_{i - 1} + x_{i-2}}{\tau^2} ~.
	\end{aligned}
	\label{Eq.dvtnum}
\end{equation}

The only term remaining to be computed numerically is the random term $\textnormal{d}W$. One can thus replace $\textnormal{d}W / \textnormal{d}t$ by $w_i/\tau$ \footnote{The notation $w$ was choosen since in mathematical terms, a real-valued continuous-time stochastic process such as $\textnormal{d}W$ is called a Wiener process in honor of Norbert Wiener \cite{durrett_probability_2019}.} a Gaussian distributed random number generated with a mean $\langle w_i \rangle = 0$ and a variance $\langle w_i^2 \rangle  = \tau$. The Probability Density function (PDF) of the Gaussian distribution is thus given by:

\begin{equation}
	P(w_i) = \frac{1}{\sqrt{2\pi \tau}}\textnormal{e}^{- \frac{w_i^2}{2\tau}}.
	\label{eq.pwi}
\end{equation}

The random number $w_i$ can be generated with the following Python snippet.
\begin{minted}
	[
	frame=lines,
	framesep=2mm,
	baselinestretch=1.2,
	fontsize=\footnotesize,
	obeytabs=true,
	tabsize=2,
	linenos
	]
	{python}
import numpy as np

tau = 0.5  # time step in seconds
wi = np.random.normal(0, np.sqrt(tau))
\end{minted}

In the latter, \mintinline{python}{random.normal()} is a built-in Numpy module that permits the generation of Gaussian-distributed random numbers.
Finally, by combining Eqs.~(\ref{Eq.vtnum})~and~(\ref{Eq.dvtnum}), the full-Langevin equation becomes:

\begin{equation}
	m \frac{x_i  - 2x_{i-1} + x_{i-2}}{\tau^2} = -\gamma \frac{x_i - x_{i-1}}{\tau} + \sqrt{2k_\mathrm{B}T\gamma} \frac{w_i}{\tau}  ~.
\end{equation}

From the latter, one can write $x_i$ as:

\begin{equation}
	x_i = \frac{2 + \tau /\tau_\mathrm{B}}{1 + \tau / \tau_\mathrm{B} } x_{i-1}
	- \frac{1}{1 + \tau / \tau_\mathrm{B}}x_{i-2}
	+ \frac{\sqrt{2k_\mathrm{B}T\gamma}}{m(1 + \tau/\tau_\mathrm{B})} \tau w_i ~,
	\label{Eq.numfulllangevin}
\end{equation}

where we can observe that two initial conditions are needed, \textit{i.e} the first two positions of the particle. Numerically, these positions could be randomly generated or  set to $0$. If enough statics are generated, it will not affect the results.

\subsubsection{Simulating Brownian Motion Using Python}

\begin{figure}[h]
	\centering
	\includegraphics{02_body/chapter1/image/noise_simulation/MSE.pdf}
	\caption{Mean Relative Squared Error (\gls{MRSE}) of the Probability Density Function \gls{PDF} measured from a generation of $N$ Gaussian random numbers $w_i$ and the actual Gaussian (see Eq.~(\ref{eq.pwi})) from which the generation is done. The generation is done over a Gaussian which has a mean value $\langle w_i \rangle =0$ and variance $\langle w_i^2 \rangle = \tau$. We explore parameter ranges from $N = 10$ to $10^7$ and $\tau = 10^{-2}$ to $10$ s. \href{https://github.com/eXpensia/Confined-Brownian-Motion/blob/main/02_body/chapter1/image/noise_simulation/noise_simulation.ipynb}{\faGithub}}
	\label{fig:MSEwi}
\end{figure}

Before, diving into the simulation, it could be interesting to wonder how long the simulation should be. Indeed, at equilibrium, for the different observables' mean values to remain constant, we should wait a sufficient amount of time. It is possible to follow a qualitative approach by generating $N$ numbers $w_i$, measuring the resulting \gls{PDF} $P_\mathrm{c}(w_i)$ and looking for how much we need to increase $N$ to have $P_\mathrm{c}(w_i) \approx P(w_i)$, under some given small-error criterion. As we can see in Fig.\ref{fig:exempleprecisionwi}, for simulations made with $\tau = 10^{-3}$ s and $\tau = 1$ s, we observe that as we increase $N$, the measured PDF, gets closer to the real one given by Eq.~(\ref{eq.pwi}).

To have a more quantitative approach, one can compute the Mean Relative Squared Error (\gls{MRSE})) between the measured \gls{PDF} $P_\mathrm{c}(w_i)$ and the nominal function $P(w_i)$ as a function of the number $N$ of generated numbers, as:

\begin{equation}
	\textnormal{MRSE} = \left. \left\langle \frac{\left( P_\mathrm{c}(w_i) -P(w_i) \right)^2  } {P(w_i) ^2}\right\rangle \right|_N
\end{equation}

where the notation $\left. \right|_N$ denotes the average over $N$ realizations. Additionally, since we measure $P_c(w_i)$ by doing a histogram, the question of how many bins are used should be answered. It is possible to use the optimal Freedan-Diaconis rule \cite{freedman_histogram_1981} to compute the width of the bins to be used in a histogram. This rule reads:

\begin{equation}
	\textnormal{Bin width} = 2 \frac{\textnormal{IQR}(\{w_i\})}{\sqrt[3]{N}},
\end{equation}

where IQR is the interquartile range, and $\{w_i\}$ a sample of $N$ random numbers $w_i$. Moreover, one should at least take $2$ bins as a minimum. The optimal number of bins can be computed using the following Python snippet.

\begin{minted}
	[
	frame=lines,
	framesep=2mm,
	baselinestretch=1.2,
	fontsize=\footnotesize,
	obeytabs=true,
	tabsize=2,
	linenos
	]
	{python}

import numpy as np

def _iqr(wi):
	"""Function to compute interquartile range."""
		return np.subtract(*np.percentile(wi, [75, 25]))

	def optimal_bins(wi):
		"""
		Function to compute the optinal number of bins using Freedan-Diaconis rule.
		Input: list of random numbers | Output: optimal bins number
		"""

		n = int(diff(wi) / (2 * _iqr(wi) * np.power(len(wi), -1 / 3)))

		if n <= 2:
			return 2
		else:
			return n
\end{minted}

As we can see in Fig.\ref{fig:MSEwi}, for $\tau$ varying between $10^{-2}$ and $10$ seconds, and $N$ between $10$ and $10^6$, the \gls{MRSE} decreases as $N$ increases. Moreover, it is interesting to observe that the \gls{MRSE} is greater as $\tau$ increases for a fixed $N$ value. As an example, we would need to only generate $N = 10^{-3}$ numbers to obtain an \gls{MRSE} of $10^{-4}$ for $\tau = 0.1~\textnormal{s}$, while we would need  $N= 10^6$ for $\tau = 1 ~ \mathrm{s}$.

Now that the Langevin equation has been numerically implemented, one could use it to simulate Brownian trajectories. A simple way to do the simulation using Python is provided in appendix.\ref{app:simfulllangevin}. A set of trajectories simulated for a fictive particle of radius $a = 1 ~ \mathrm{\mu m}$ and mass $m = 10 ~ \mathrm{\mu g}$ in water is shown in Fig.\ref{fig:inertial_langevin}-a). For such a particle, the diffusive characteristic time is $\tau_\mathrm{B} = 0.53$~s. Moreover, as one can see in Fig.\ref{fig:inertial_langevin}-b), the MSD is correctly modeled by Eq.~(\ref{Eq.shorttimemsd}) for $\tau << \tau_\mathrm{B}$, and by Eq.~(\ref{eq:longtimemsd}) for $\tau >> \tau_\mathrm{B}$. Note that for non-continuous data such as the simulation data presented here or sampled experimental trajectories, and for a given time increment $\Delta t$, the \gls{MSD} is generally defined by:

\begin{equation}
	\left\langle \Delta x^2 \right\rangle_t =  \left\langle ( x_i(t + \Delta t) - x_i(t)) ^2 \right\rangle _t ~,
	\label{Eq.msdn}
\end{equation}

where the average $ \left. \langle \rangle \right|_t $ is performed over time $t$.The following Python function can be used to numerically compute the MSD Eq.~(\ref{Eq.msdn}).

\begin{minted}
	[
	frame=lines,
	framesep=2mm,
	baselinestretch=1.2,
	fontsize=\footnotesize,
	obeytabs=true,
	tabsize=2,
	linenos
	]
	{python}
def msd(x, Dt):
	"""Function that returns the MSD for a list of time indices Dt for a trajectory x"""
	_msd = lambda x, Dt: np.mean((x[:-Dt] - x[Dt:]) ** 2)
	return [_msd(x, i) for i in t]
\end{minted}

\begin{figure}[h]
	\centering
	\includegraphics{02_body/chapter1/image/simulation_full_langevin/intertial_langevin.pdf}
	\caption{a) Set of $100$ trajectories simulated using the full-Langevin equation (see Eq.~(\ref{Eq.numfulllangevin})) for particles of a radius  $a = 1 ~\mathrm{\mu m}$ and mass $m = 10 ~\mathrm{\mu g}$ in water, with viscosity $\eta = 0.001 ~\mathrm{Pa.s}$. The simulations are done with a time step $\tau = 0.01~ \mathrm{s}$. b) Bullets represent the measured Mean Squared Displacements (\gls{MSD}) of the simulated trajectories. The plain black line represents the characteristic inertial timescale, $\tau_\mathrm{B} = m / \gamma = 0.53 ~\mathrm{s}$. The dotted line represents the \gls{MSD} in the ballistic regime (see Eq.~(\ref{Eq.shorttimemsd})), when $\Delta t \ll \tau _\mathrm{B}$. The dashed line represents the \gls{MSD} in the diffusive regime (see Eq.~(\ref{eq:longtimemsd})), when $\Delta t \gg \tau _\mathrm{B}$, $\mathrm{MSD} = 2D\Delta t$. A detailed explanation of the simulation process can be found in appendix ~\ref{app:simfulllangevin}.\href{https://github.com/eXpensia/Confined-Brownian-Motion/blob/main/02_body/chapter1/image/simulation_full_langevin/inertial_Brownian_motion.ipynb}{\faGithub}}
	\label{fig:inertial_langevin}
\end{figure}

Additionally, as we have seen earlier, the Langevin Equation can be simplified to it is over-damped version of Eq.~(\ref{Eq.overdamped_SDE}). In this case, the time step $\tau$ of the simulation should be greater than the characteristic time $\tau_\mathrm{B}$. Thus, if one is interested in the long-time statistical properties of Brownian motion one can use the over-damped Langevin equation. In this case, by putting $m=0$ into Eq.
~(\ref{Eq.numfulllangevin}), one can write $x_i$ as:

\begin{equation}
	x_i = x_{i-1} + \sqrt{2D}w_i~.
	\label{Eq.shortnumlangevin}
\end{equation}

The statistical properties at a long time could be retrieved by simulating Brownian motion using the full-Langevin equation. But, since the integration scheme used for Eq.~(\ref{Eq.numfulllangevin}) requires  $\tau \ll \tau_\mathrm{B}$, long simulation runs are necessary to retrieve the over-damped properties. A simulation of the over-damped Brownian motion trajectories using Eq.~(\ref{Eq.shortnumlangevin}) is shown in Fig.\ref{fig:bulkbrown} and is realized using the following Python Snippet.

\begin{minted}
	[
	frame=lines,
	framesep=2mm,
	baselinestretch=1.2,
	fontsize=\footnotesize,
	obeytabs=true,
	tabsize=2,
	linenos
	]
	{python}
import numpy as np

N = 1000  # trajectory length
D = 1  # diffusion coefficient
tau = 0.5  # time step
trajectory = np.cumsum(np.sqrt(2 * D) * np.random.normal(0, np.sqrt(tau), N))
\end{minted}

\subsubsection{Speedup using Cython}

I would like to point out that the optimization of a simple simulation of a Brownian trajectory can be interesting. Indeed, using a pure Python code as presented in the first part of appendix. \ref{app:simfulllangevin}, the simulation of one trajectory of $10^6$ steps, needs $6$ s to be computed. Thus, more than $10$ minutes are required to compute the 100 trajectories shown in Fig.~\ref{fig:inertial_langevin}. This is long and due to how Python systematically verifies what is allowed. Indeed, it verifies at each step of the \mintinline{python}{for} loop the object type of each variable and if the mathematical operation are possible. This is  generally the main drawback \cite{ampomah_qualitative_2017} of interpreted language, and the only solution is to use a compiled language (\textit{e.g} C or Fortran).

The difference between an interpreted (\textit{e.g.} Python) and compiled language (\textit{e.g.} C) lies in the result of the process of interpreting or compiling. A compiler (\textit{e.g.} gcc for the C language \href{https://github.com/gcc-mirror/gcc}{\faGithub}) translate the source code into the computer native language, and create an executable file. The execution of compiled language does not require any more translations, and hence run significantly faster. Contrariwise, an interpreted language is not translated in advance, but is done at the execution, line by line, and each time the program is executed. This process is done by the interpreter, such as Python, Matlab or Perl for their eponymous language. At each execution, the time taken by the interpreter to read and execute each line slows the process, causing execution to take more time.

To overcome this problem with Python, the \mintinline{python}{cython} package has been developed to translate in C and compile the part of the code that is long to execute, especially the \mintinline{python}{for} loops. Thus, one can transform Python source code into a hybrid Python-C code. As presented in appendix.\ref{app:simfulllangevin}, compiling the \mintinline{python}{for} loop using \mintinline{python}{cython} in the full-Langevin simulations reduces the time to generate a $10^6$-step trajectory from $6$ s to $30$ ms thus achieving a speedup  factor of $200$. Moreover, in the hybrid version, the execution time is limited by the random number generation. Indeed, it takes $ \approx 24 ~ \mathrm{ms}$ using \mintinline{python}{numpy} to generate $10^6$ $w_i$ numbers and $\approx 6$~ms for the trajectory computation. Additionally, as shown at the end of appendix.\ref{app:simfulllangevin}, even a pure C implementation of the random generation can be slower than the \mintinline{python}{numpy} one, thanks to  \mintinline{python}{numpy}'s memory optimization. Thus, by using the above mixed-language strategy, the simulation is optimal with the current tools and language at hand.

\subsection{Conclusion}

In this chapter, we have covered the history of Brownian motion, from the first observation by Robert Brown in the middle of the 19th century to its mathematical and experimental proofs in the early 20th century. We have then described mathematically the bulk Brownian motion and its important statistical properties. Finally, we have used the latter description to simulate Brownian motion using both the full-Langevin equation, and its over-damped version.


\section{Serializable types}\label{sec:dsdl_serializable_types}

\subsection{General principles}

Values of the serializable type category can be exchanged between nodes over the UAVCAN network.
This is opposed to the expression types (section~\ref{sec:dsdl_expression_types}),
instances of which can only exist while DSDL definitions are being evaluated.
The data serialization rules are defined in section~\ref{sec:dsdl_data_serialization}.

\subsubsection{Alignment and padding}\label{sec:dsdl_serializable_alignment_padding}

For any serializable type,
its \emph{alignment} $A$ is defined as some positive integer number of bits such that the offset of a
serialized representation of an instance of this type relative to the origin of the
containing serialized representation (if any) is an integer multiple of $A$.

Given an instance of type whose alignment is $A$,
it is guaranteed that its serialized representation is always an integer multiple of $A$ bits long.

When constructing a serialized representation,
the alignment and length requirements are satisfied by means of \emph{padding},
which refers to the extension of a bit sequence with zero bits until
the resulting alignment or length requirements are satisfied.
During deserialization, the padding bits are ignored (skipped) irrespective of their value
(also see related section \ref{sec:dsdl_serialization_implicit_truncation}).

\begin{remark}
    For example, given a variable-length entity whose length varies between 1 and 3 bits,
    followed by a field whose type has the alignment requirement of 8,
    one may end up with 5, 6, or 7 bits of padding inserted before the second field at runtime.

    The exact amount of such padding cannot always be determined statically because it depends on the size of the
    preceding entity;
    however, it is guaranteed that it is always strictly less than the alignment requirement of the following field
    or, if this is the last field in a group, the alignment requirement of its container.
\end{remark}

\subsection{Void types}

Void types are used for padding purposes.
The alignment of void types is 1 bit (i.e., no alignment).

Void-typed field attributes are set to zero when an object is serialized and ignored when it is deserialized.
Void types can be used to reserve space in data type definitions for possible use in later versions of the data type.

The DSDL name pattern for void types is as follows: ``\verb|void[1-9]\d*|'',
where the trailing integer represents its width, in bits,
ranging from 1 to 64, inclusive.

Void types can be referred to directly by their name from any namespace.

\subsection{Primitive types}\label{sec:dsdl_primitive_types}

Primitive types are assumed to be known to DSDL processing tools a priori,
and as such, they need not be defined by the user.
Primitive types can be referred to directly by their name from any namespace.

The alignment of primitive types is 1 bit (i.e., no alignment).

\subsubsection{Hierarchy}

The hierarchy of primitive types is documented below.

\begin{itemize}
    \item \textbf{Boolean types.} A boolean-typed value represents a variable of the Boolean algebra.
    A Boolean-typed value can have two values: true and false.
    The corresponding DSDL data type name is ``\verb|bool|''.

    \item \textbf{Algebraic types.} Those are types for which conventional algebraic operators are defined.
    \begin{itemize}
        \item \textbf{Integer types} are used to represent signed and unsigned integer values.
        See table~\ref{table:dsd_integer_properties}.
        \begin{itemize}
            \item \textbf{Signed integer types.} These are used to represent values which can be negative.
            The corresponding DSDL data type name pattern is ``\verb|int[1-9]\d*|'',
            where the trailing integer represents the length of the
            serialized representation of the value, in bits, ranging from 2 to 64, inclusive.

            \item \textbf{Unsigned integer types.} These are used to represent non-negative values.
            The corresponding DSDL data type name pattern is ``\verb|uint[1-9]\d*|'',
            where the trailing integer represents the length of the
            serialized representation of the value, in bits, ranging from 1 to 64, inclusive.
        \end{itemize}

        \item \textbf{Floating point types} are used to approximately represent real values.
        The underlying serialized representation follows the IEEE 754 standard.
        The corresponding DSDL data type name pattern is ``\verb~float(16|32|64)~'', where the trailing
        integer represents the type of the IEEE 754 representation.
        See table~\ref{table:dsd_floating_point_properties}.
    \end{itemize}
\end{itemize}

\begin{UAVCANSimpleTable}{Properties of integer types}{|l X l|}%
    \label{table:dsd_integer_properties}%
    Category &
    DSDL names &
    Range, $X$ is bit length \\

    Signed integers &
    \texttt{int2}, \texttt{int3}, \texttt{int4} \ldots{} \texttt{int62}, \texttt{int63}, \texttt{int64} &
    $\left[-\frac{2^{X}}{2},\frac{2^{X}}{2}-1\right]$ \\

    Unsigned integers &
    \texttt{uint1}, \texttt{uint2}, \texttt{uint3} \ldots{} \texttt{uint62}, \texttt{uint63}, \texttt{uint64} &
    $\left[0,2^{X}-1\right]$ \\
\end{UAVCANSimpleTable}

\begin{UAVCANSimpleTable}{Properties of floating point types}{|X X X X|}
    DSDL name        & Representation    & Approximate epsilon   & Approximate range
    \label{table:dsd_floating_point_properties} \\

    \texttt{float16} & IEEE 754 binary16 & $0.001$               & $\pm{}65504$      \\
    \texttt{float32} & IEEE 754 binary32 & $10^{-7}$             & $\pm{}10^{39}$    \\
    \texttt{float64} & IEEE 754 binary64 & $2 \times{} 10^{-16}$ & $\pm{}10^{308}$   \\
\end{UAVCANSimpleTable}

\subsubsection{Cast mode}

The concept of \emph{cast mode} is defined for all primitive types.
The cast mode defines the behavior when a primitive-typed entity is assigned a value that exceeds its range.
Such assignment requires some of the information to be discarded;
due to the loss of information involved, it is called a \emph{lossy assignment}.

The following cast modes are defined:
\begin{description}
    \item[Truncated mode] --- denoted with the keyword ``\verb|truncated|'' placed before the primitive type name.
    \item[Saturated mode] --- denoted with the optional keyword ``\verb|saturated|''
    placed before the primitive type name. If neither cast mode is specified, saturated mode is assumed by default.
    This essentially makes the ``\verb|saturated|'' keyword redundant; it is provided only for consistency.
\end{description}

When a primitive-typed entity is assigned a value that exceeds its range,
the resulting value is chosen according to the lossy assignment rules
specified in table~\ref{table:dsdl_cast_mode}.
Cases that are marked as illegal are not permitted in DSDL definitions.

\begin{UAVCANSimpleTable}[wide]{Lossy assignment rules per cast mode}{|l X X|}
    Type category & Truncated mode & Saturated mode (default)
    \label{table:dsdl_cast_mode} \\

    Boolean &
    Illegal: boolean type with truncated cast mode is not allowed. &
    Falsity if the value is zero or false, truth otherwise. \\

    Signed integer &
    Illegal: signed integer types with truncated cast mode are not allowed. &
    Nearest reachable value. \\

    Unsigned integer &
    Most significant bits are discarded. &
    Nearest reachable value. \\

    Floating point &
    Infinity with the same sign, unless the original value is not-a-number, in which case it will be preserved. &
    If the original value is finite, the nearest finite value will be used.
    Otherwise, in the case of infinity or not-a-number, the original value will be preserved. \\
\end{UAVCANSimpleTable}

Rules of conversion between values of different type categories do not affect compatibility at the protocol level,
and as such, they are to be implementation-defined.

\subsubsection{Expressions}

At the time of DSDL definition processing,
values of primitive types are represented as instances of the \verb|rational| type (section~\ref{sec:dsdl_rational}),
with the exception of the type \verb|bool|,
instances of which are usable in DSDL expressions as-is.

\begin{UAVCANSimpleTable}{Operators defined on instances of type boolean}{|l X X|}
    Op & Type & Description \\

    \texttt{\textbf{!}}     & $(\texttt{bool}) \rightarrow \texttt{bool}$ & Logical not. \\

    \texttt{\textbf{||}}    & $(\texttt{bool}, \texttt{bool}) \rightarrow \texttt{bool}$ & Logical or. \\
    \texttt{\textbf{\&\&}}  & $(\texttt{bool}, \texttt{bool}) \rightarrow \texttt{bool}$ & Logical and. \\

    \texttt{\textbf{==}}    & $(\texttt{bool}, \texttt{bool}) \rightarrow \texttt{bool}$ & Equality. \\
    \texttt{\textbf{!=}}    & $(\texttt{bool}, \texttt{bool}) \rightarrow \texttt{bool}$ & Inequality. \\

\end{UAVCANSimpleTable}

\subsubsection{Reference list}

An exhaustive list of all void and primitive types
ordered by bit length is provided below for reference.
Note that the cast mode specifier is omitted intentionally.

\immediate\write18{rm -f ../latex.tmp}
\immediate\write18{../render_list_of_void_and_primitive_types.py > ../latex.tmp}
\immediate\input{../latex.tmp}

\subsection{Array types}

An array type represents an ordered collection of values.
All values in the collection share the same type, which is referred to as \emph{array element type}.
The array element type can be any type except:
\begin{itemize}
    \item void type;
    \item array type\footnote{%
              Meaning that nested arrays are not allowed;
              however, the array element type can be a composite type which in turn may contain arrays.
              In other words, indirect nesting of arrays is permitted.
          }.
\end{itemize}

The number of elements in the array can be specified as a constant expression at the data type definition time,
in which case the array is said to be a \emph{fixed-length array}.
Alternatively, the number of elements can vary between zero and some static limit specified
at the data type definition time,
in which case the array is said to be a \emph{variable-length array}.
Variable-length arrays with unbounded maximum number of elements are not allowed.

Arrays are defined by adding a pair of square brackets after the array element type specification,
where the brackets contain the \emph{array capacity expression}.
The array capacity expression shall yield a positive integer of type ``\verb|rational|'' upon its evaluation;
any other value or type renders the current DSDL definition invalid.

The array capacity expression can be prefixed with the following character sequences in order to define
a variable-length array:
\begin{itemize}
    \item ``\verb|<|'' (ASCII code 60) --- indicates that the integer value yielded by the array capacity expression
    specifies the non-inclusive upper boundary of the number of elements.
    In this case, the integer value yielded by the array capacity expression shall be greater than one.

    \item ``\verb|<=|'' (ASCII code 60 followed by 61) --- same as above, but the upper boundary is inclusive.
\end{itemize}
If neither of the above prefixes are provided, the resultant definition is that of a fixed-length array.

The alignment of an array equals the alignment of its element type\footnote{
    E.g., the alignment of \texttt{uint5[<=3]} or \texttt{int64[3]} is 1 bit (that is, no alignment).
}.

\subsection{Composite types}\label{sec:dsdl_composite_types}

\subsubsection{Kinds}

There are two kinds of composite type definitions: message types and service types.
All versions of a data type shall be of the same kind\footnote{%
    For example, if a data type version 0.1 is of a message kind, all later versions of it shall be messages, too.
}.

A service type defines two inner data types:
one for service request object, and one for service response object, in that order.
The two types are separated by the service response marker (``\verb|---|'') on a separate line.

The presence of the service response marker indicates that the data type definition at hand is of the service kind.
At most one service response marker shall appear in a given definition.

\subsubsection{Dependencies}

In order to refer to a composite type from another composite type definition
(e.g., for nesting or for referring to an external constant),
one has to specify the full data type name of the referred data type followed by its
major and minor version numbers separated by the namespace separator character,
as demonstrated on figure~\ref{fig:dsdl_nested_reference}.

To facilitate look-up of external dependencies,
implementations are expected to obtain from external sources\footnote{%
    For example, from user-provided configuration options.
} the list of directories that are the roots of namespaces containing the referred dependencies.

\begin{figure}[H]
    $$
    \underbrace{\texttt{\huge{uavcan.node.Heartbeat}}}_{\text{full data type name}}%
    \texttt{\huge{.}}%
    \underbrace{\texttt{\huge{1.0}}}_{\substack{\text{version} \\ \text{numbers}}}%
    $$
    \caption{Reference to an external composite data type definition\label{fig:dsdl_nested_reference}}
\end{figure}

If the referred data type and the referring data type share the same full namespace name,
it is allowed to omit the namespace from the referred data type specification
leaving only the short data type name, as demonstrated on figure~\ref{fig:dsdl_nested_reference_short}.
In this case, the referred data type will be looked for in the namespace of the referrer.
Partial omission of namespace components is not permitted.

\begin{figure}[H]
    $$
    \underbrace{\texttt{\huge{Heartbeat}}}_{\text{short data type name}}%
    \texttt{\huge{.}}%
    \underbrace{\texttt{\huge{1.0}}}_{\substack{\text{version} \\ \text{numbers}}}%
    $$
    \caption{Reference to an external composite data type definition located in the same namespace
             \label{fig:dsdl_nested_reference_short}}
\end{figure}

Circular dependencies are not permitted.
A circular dependency renders all of the definitions involved in the dependency loop invalid.

If any of the referred definitions are marked as deprecated,
the referring definition shall be marked deprecated as well\footnote{%
    Deprecation is indicated with the help of a special directive, as explained in section~\ref{sec:dsdl_directives}.
}.
If a non-deprecated definition refers to a deprecated definition,
the referring definition is malformed\footnote{%
    This tainting behavior is designed to prevent unexpected breakage of
    type hierarchies when one of the deprecated dependencies reaches its end of life.
}.

When a data type is referred to from within an expression context,
it constitutes a literal of type ``\verb|metaserializable|'' (section~\ref{sec:dsdl_metaserializable}).
If the referred data type is of the message kind,
its attributes are accessible in the referring expression through application of the
attribute reference operator ``\verb|.|''.
The available attributes and their semantics are documented in the section~\ref{sec:dsdl_local_attributes}.

\begin{remark}
    \begin{minted}{python}
        uint64 MY_CONSTANT = vendor.MessageType.1.0.OTHER_CONSTANT
        uint64 MY_CONSTANT = MessageType.1.0.OTHER_CONSTANT
        # The above is valid if the referring definition and the referred definition
        # are located inside the root namespace "vendor".
        @print MessageType.1.0
    \end{minted}
\end{remark}

\subsubsection{Tagged unions}\label{sec:dsdl_composite_tagged_unions}

Any data type definition can be supplied with a special directive (section~\ref{sec:dsdl_directives})
indicating that it forms a tagged union.

A tagged union type shall contain at least two field attributes.
A tagged union shall not contain padding field attributes.

The value of a tagged union object is a function of the field attribute which value it is currently holding
and the value of the field attribute itself.

To avoid ambiguity, a data type that is not a tagged union is referred to as a \emph{structure}.

\subsubsection{Alignment and cumulative bit length set}\label{sec:dsdl_composite_alignment_cumulative_bls}

The alignment of composite types is one byte (8 bits)\footnote{%
    Regardless of the content.
    It follows that empty composites can be inserted arbitrarily to force byte alignment
    of the next field(s) at runtime.
}.

Per the definitions given in \ref{sec:dsdl_serializable_alignment_padding},
a serialized representation of a composite type is padded to 8 bits by inserting padding bits
after its last element until the resulting length is a multiple of 8 bits.

Given a set of field attributes, their \emph{cumulative bit length set} is computed
by evaluating every permutation of their respective bit length sets plus the required padding.
\begin{itemize}
    \item For tagged unions, this amounts to the union of the bit length sets of each field
    plus the bit length set of the implicit union tag.
    \item Otherwise, the cumulative bit length set is the Cartesian product of the bit length sets of each field
    plus the required inter-field padding.
\end{itemize}
Related specifics are given in section \ref{sec:dsdl_data_serialization} on data serialization.

\subsubsection{Extent and sealing}\label{sec:dsdl_composite_extent_and_sealing}

As detailed in section \ref{sec:dsdl_versioning},
data types may evolve over time to accommodate new design requirements, new features, to rectify issues, etc.
In order to allow gradual migration of deployed systems to revised data types,
it is desirable to ensure that they can be modified in a way that does not render new definitions
incompatible with their earlier versions.
In this context there are two related concepts:

\begin{description}
    \item[Extent] --- the minimum amount of memory, in bits, that shall be allocated to store the serialized
    representation of the type.
    The extent of any type is always greater than or equal the maximal value of its bit length set.
    It is always a multiple of 8.

    \item[Sealing] --- a type that is \emph{sealed} is non-evolvable and its extent equals the maximal value
    of its bit length set\footnote{%
        I.e., the smallest possible extent.
    }.
    A type that is not sealed is also referred to as \emph{delimited}.
\end{description}

The extent is the growth limit for the maximal bit length of the type as it evolves.
The extent should be at least as large as the longest serialized representation of any compatible version of the type,
which ensures that an agent leveraging a particular version can correctly process any other compatible
version due to the avoidance of unintended truncation of serialized representations.

Serialized representations of evolvable definitions may carry additional metadata which introduces a certain overhead.
This may be undesirable in some scenarios, especially in cases where serialized representations of the
definition are expected to be highly compact, thereby making the overhead comparatively more significant.
In such cases, the designer may opt out of the extensibility by declaring the definition sealed.
Serialized representations of sealed definitions do not incur the aforementioned overhead.

The related mechanics are described in section \ref{sec:dsdl_serialization_composite_non_sealed}.

\begin{figure}[H]
    $$
    \overbrace{%
        \underbrace{%
            \blacksquare\blacksquare\blacksquare\blacksquare\blacksquare\blacksquare%
            \blacksquare\blacksquare\blacksquare\blacksquare\blacksquare\blacksquare%
        }_{\substack{\text{Longest serialized} \\ \text{representation}}}%
        \underbrace{%
            \boxtimes\boxtimes\boxtimes\boxtimes\boxtimes\boxtimes\boxtimes\boxtimes%
        }_{\substack{\text{Memory reserve} \\ \text{(none if sealed)}}}%
    }^{\substack{%
        \text{Extent} \\
        \text{(memory requirement)}
    }}
    $$
    \caption{Serialized representation and extent\label{fig:dsdl_extent}}
\end{figure}

\begin{remark}
    Because of UAVCAN's commitment to determinism, memory buffer allocation can become an issue.
    When using a flat composite type (where each field is of a primitive type) with the implicit truncation rule,
    it is clear that the last defined fields are to be truncated out shall the allocated buffer be too small
    to accommodate the serialized representation in its entirety.
    If there is a composite-typed field, this behavior can no longer be relied on.
    The technical details explaining this are given in section \ref{sec:dsdl_serialization_composite_non_sealed}.

    Conventional protocols manage this simply by delaying the memory requirement identification until runtime,
    which is unacceptable to UAVCAN.
    The solution for UAVCAN is to allow the data type author to require implementations to reserve more memory
    than required by the data type definition unless it is \verb|@sealed|
    (or unless the implementation does use dynamic memory allocation).
\end{remark}

The extent shall be set explicitly using the directive described in section \ref{sec:dsdl_directive_extent},
unless the definition is declared sealed using the directive described in section \ref{sec:dsdl_directive_sealed}.
The directives are mutually exclusive.

It is allowed for a sealed composite type to nest non-sealed (delimited) composite types, and vice versa.

\subsubsection{Bit length set}

The bit length set of a sealed composite type equals the cumulative bit length set
of its fields plus the final padding (see section \ref{sec:dsdl_composite_alignment_cumulative_bls}).

\begin{remark}
    The bit length set of the following is $\left\{ 8, 24, 40, 56 \right\}$:
    \begin{minted}{python}
        uint16[<=3] foo
        @sealed
    \end{minted}

    The bit length set of the following is $\left\{ 16, 32, 48, 64 \right\}$:
    \begin{minted}{python}
        uint16[<=3] foo
        int2 bar
        @sealed
    \end{minted}

    The bit length set of the following is $\left\{ 8, 16 \right\}$:
    \begin{minted}{python}
        bool[<=3] foo
        @sealed
    \end{minted}
\end{remark}

The bit length set of a non-sealed (delimited) composite type is dependent only on its extent $X$,
and is defined as follows:
$$
    \left\{ B_\text{DH} + 8b \mid b \in \mathbb{Z},\ 0 \leq b \leq \frac{X}{8} \right\}
$$
where $B_\text{DH}$ is the bit length of the \emph{delimiter header}
as defined in section \ref{sec:dsdl_serialization_composite_non_sealed}.

\begin{remark}
    This is intentionally not dependent on the fields of the composite because the definition of delimited
    composites should be possible to change without violating the backward compatibility.

    If the bit length set was dependent on the field composition, then a composite $A$ that nests another composite
    $B$ could have made a fragile assumption about the offset of the fields that follow $B$
    that could be broken when $B$ is modified. Example:

    \begin{minted}{python}
        # A.1.0
        B.1.0 x
        float32 assume_aligned  # B.1.0 contains a single uint64, assume this field is 32-bit aligned?
        @sealed
    \end{minted}

    \begin{minted}{python}
        # B.1.0
        uint64 x
        @extent 8 * 8
    \end{minted}

    Imagine then that \verb|B.1.0| is replaced with the following:

    \begin{minted}{python}
        # B.1.1
        uint64 x
        bool[<=64] y
        @extent 8 * 8
    \end{minted}

    Once this modification is introduced, the fragile assumption about the alignment of
    \verb|A.1.0.assume_aligned| would be violated.
    To avoid this issue, the bit length set definition of delimited types intentionally discards the information
    about its field composition, forcing dependent types to avoid any non-trivial assumptions.
\end{remark}

When serializing an object, the amount of memory needed for storing its serialized representation
may be taken as the maximal value of its bit length set minus the size of the delimiter header,
since this bound is tighter than the extent yet guaranteed to be sufficient.
This optimization is not applicable to deserialization since the actual type of the object may not be known.

\subsubsection{Type polymorphism and equivalency}

Type polymorphism is supported in DSDL through structural subtyping.
The following definition relies on the concept of \emph{field attribute},
which is introduced in section~\ref{sec:dsdl_attributes}.

Polymorphic relations are not defined on service types.

Let $B$ and $D$ be DSDL types that define $b$ and $d$ field attributes, respectively.
Let each field attribute be assigned a sequential index according to its position in the DSDL definition
(see section~\ref{sec:dsdl_grammar} on statement ordering).

\begin{enumerate}
    % -----------------------------------------------------------------------------------------------------------------
    \item Structure subtyping rule --- $D$ is a \emph{structural subtype} of $B$ if all conditions are satisfied:
    \begin{itemize}
        \item neither $B$ nor $D$ define a tagged union\footnote{%
            This is because tagged unions are serialized differently.
        };
        \item neither $B$ nor $D$ are sealed\footnote{%
            Sealed types are serialized in-place as if their definition was directly copied into the outer
            (containing) type (if any).
            This circumstance effectively renders them non-modifiable because that may break the bit layout
            of the outer types (if any).
            More on this in section \ref{sec:dsdl_serialization_composite_non_sealed}.
        };
        \item the extent of $B$ is not less than the extent of $D$\footnote{%
            This is to uphold the Liskov substitution principle.
            A deserializer expecting an instance of $B$ in a serialized representation should be invariant
            to the replacement $B \leftarrow{} D$.
            If the extent of $D$ was larger, then its serialized representation could spill beyond the allocated
            container, possibly resulting in the truncation of the following data, which in turn could result in
            incorrect deserialization.
            See \ref{sec:dsdl_data_serialization}.
        };
        \item $B$ is not $D$;
        \item $b \leq d$;
        \item for each field attribute of $B$ at index $i$ there is an equal\footnote{%
            Field attribute equality is defined in section~\ref{sec:dsdl_attributes}.
        } field attribute in $D$ at index $i$.
    \end{itemize}

    % -----------------------------------------------------------------------------------------------------------------
    \item Tagged union subtyping rule --- $D$ is a structural subtype of $B$ if all conditions are satisfied:
    \begin{itemize}
        \item both $B$ and $D$ define tagged unions;
        \item neither $B$ nor $D$ are sealed;
        \item the extent of $B$ is not less than the extent of $D$;
        \item $B$ is not $D$;
        \item $b \leq d$;
        \item $2^{\lceil\log_2 \text{max}\left(8, \lceil\log_2 b\rceil\right)\rceil} =
               2^{\lceil\log_2 \text{max}\left(8, \lceil\log_2 d\rceil\right)\rceil}$\footnote{%
            I.e., the length of the implicit union tag field should be the same.
        };
        \item for $i \in \left[0, b\right)$, the type of the field attribute of $D$ at index $i$
        is the same or is a subtype of the type of the field attribute of $B$ at index $i$.
        \item for $i \in \left[0, b\right)$, the name of the field attribute of $D$ at index $i$
        is the same as the name of the field attribute of $B$ at index $i$.
    \end{itemize}

    % -----------------------------------------------------------------------------------------------------------------
    \item Empty type subtyping rule --- $D$ is a structural subtype of $B$ if all conditions are satisfied:
    \begin{itemize}
        \item $b = 0$\footnote{%
            If $B$ contains no field attributes, the applicability of the Liskov substitution principle is invariant to
            whether its subtypes are tagged union types or not.
        };
        \item neither $B$ nor $D$ are sealed;
        \item the extent of $B$ is not less than the extent of $D$;
        \item $B$ is not $D$.
    \end{itemize}

    % -----------------------------------------------------------------------------------------------------------------
    \item Header subtyping rule --- $D$ is a structural subtype of $B$ if all conditions are satisfied:
    \begin{itemize}
        \item neither $B$ nor $D$ define a tagged union;
        \item both $B$ and $D$ are sealed;
        \item the first field attribute of $D$ is of type $B$.
    \end{itemize}
\end{enumerate}

If $D$ is a structural subtype of $B$, then $B$ is a \emph{structural supertype} of $D$.

$D$ and $B$ are \emph{structurally equivalent} if $D$ is a structural subtype and a structural supertype of $B$.

A \emph{type hierarchy} is an ordered set of data types such that for each pair of its members
one type is a subtype of another, and for any member its supertypes are located on the left.

\begin{remark}
    Subtyping example for structure (non-union) types. First type:

    \begin{minted}{python}
        float64 a       # Index 0
        int16[<=9] b    # Index 1
        @extent 32 * 8
    \end{minted}

    The second type is a structural subtype of the first type:

    \begin{minted}{python}
        float64 a       # Index 0
        int16[<=9] b    # Index 1
        uint8 foo       # Index 2
        @extent 32 * 8
    \end{minted}

    Subtyping example for union types. First type:

    \begin{minted}{python}
        @union                            # The implicit union tag field is 8 bits wide
        uavcan.primitive.Empty.1.0 foo
        float16 bar
        uint8 zoo
        @extent 128 * 8
    \end{minted}

    The second type is a structural subtype of the first type:

    \begin{minted}{python}
        @union                            # The implicit union tag field is 8 bits wide
        uavcan.diagnostic.Record.1.0 foo  # Subtype
        float16 bar                       # Same
        uint8 zoo                         # Same
        int64[<=64] baz                   # New field
        @extent 128 * 8
    \end{minted}

    A structure type that defines zero fields is a structural supertype of any other structure type,
    regardless of either or both being a union, provided that its extent is sufficient.
    A structure type may have an arbitrary number of supertypes as long as the field equality constraint is satisfied.

    Header subtyping example. The first type is named \verb|A.1.0|:

    \begin{minted}{python}
        float64 a
        int16[<=9] b
        @sealed
    \end{minted}

    The second type is a structural subtype of the first type:

    \begin{minted}{python}
        A.1.0 base
        uint8 foo
        @sealed
    \end{minted}
\end{remark}

\begin{remark}[breakable]
    The following example in C demonstrates the concept of polymorphic compatibility detached from DSDL.

    \begin{samepage}
        \begin{minted}{c}
            struct base
            {
                int a;
                float b;
            };

            struct derived_first
            {
                int a;
                float b;
                double c;
            };

            struct derived_second
            {
                int a;
                float b;
                short d;
            };

            float compute(struct base* value)
            {
                return (float)value->a + value->b;
            }

            int main()
            {
                struct derived_first foo  = { .a = 123, .b = -456.789F, .c = 123.456 };
                struct derived_second bar = { .a = -123, .b = 456.789F, .d = -123 };
                // Both derived_first and derived_second are structural subtypes of base. The program returns zero.
                return compute(&foo) + compute(&bar);
            }
        \end{minted}
    \end{samepage}
\end{remark}