\section{Model definition}
\label{model-definition}

This Section gives an overview of the models used on the different
training sets. We first start with the multilayer perceptrons and
end with the convolutional networks used on the image dataset.

For both models we present the architecture, the initial results
and the hyperparameter tuning phase.

\subsection{Multilayer perceptron}
\label{mlp}
The first model used in the experiments is a multilayer perceptron.
The considered training sets are the ones presented on Subsection 2.2 and 2.3
namely the first and extended datasets. For the first one, scaled and unscaled
versions are considered, while for the second the normal and PCA version are tested.

\subsubsection{Network structure}
\label{net-str}
The starting point for the neural network structure is a
reasonable network in terms of hidden neurons to prevent over-fitting,
indeed a high number of units in the hidden layers would end up in learning
too much from the dataset, leading to poor performances on the test sets.

For this reason, the rule of thumb followed to decide hidden neurons quantity is the
following:
$$\#\mathit{hidden\; neurons} = \frac{2}{3}\big(\#\mathit{input\;neurons}
+ \#\mathit{output\;neurons}\big)$$
The next step is to decide the hidden layers number. As using the rule
presented above gives a quite small amount of units, only two layers are considered,
indeed, an higher quantity would mean having a real small number of neurons per layer.

Applying this rule ended up in the following architectures on the four
different training sets, where the output layer is fixed at 10:
\begin{center}
    \begin{tabular}{ |l|r|r|r| }
        \hline
        Training set & Input & 1st Hidden & 2nd Hidden  \\
        \hline
        132 features unscaled &  132 & 60 & 30 \\
        132 features scaled &  132 & 60 & 30 \\
        180 features scaled &  180 & 80 & 46 \\
        102 features reduced with PCA &  102 & 45 & 30 \\
        \hline
    \end{tabular}
\end{center}

To build the actual model \emph{Tensorflow} and \emph{Keras} libraries
are used.~\cite{tensorflow}\cite{keras}

\paragraph{Starting point model}
To give reference, Figure \ref{mod} shows the model used on the PCA training set, mentioned at
the end of Subsection \vref{extended-dataset}, with
102 input features.
\begin{figure}
    \begin{center}
        \begin{tikzpicture}[x=1.6cm, y=0.9cm, >=stealth]

            % layers
            \foreach \m/\l [count=\y] in {1,2,3,missing,4}
            \node [every neuron/.try, neuron \m/.try] (input-\m) at (0,2.5-\y) {};

            \foreach \m [count=\y] in {1,missing,2}
            \node [every neuron/.try, neuron \m/.try ] (hidden-\m) at (1.75,3-\y*1.75) {};

            \foreach \m [count=\y] in {1,missing,2}
            \node [every neuron/.try, neuron \m/.try ] (hidden2-\m) at (3.5,2-\y*1.25) {};

            \foreach \m [count=\y] in {1,missing,2}
            \node [every neuron/.try, neuron \m/.try ] (output-\m) at (5.25,1.5-\y) {};

            %   label
            \foreach \l [count=\i] in {1,2,3,{102}}
            \draw [<-] (input-\i) -- ++(-1,0)
            node [above, midway] {$I_{\l}$};

            \foreach \l [count=\i] in {1,45}
            \node [above] at (hidden-\i.north) {$H_{\l}$};

            \foreach \l [count=\i] in {1,30}
            \node [above] at (hidden2-\i.north) {$H_{\l}$};

            \foreach \l [count=\i] in {1,10}
            \draw [->] (output-\i) -- ++(1,0)
            node [above, midway] {$O_{\l}$};

            \foreach \i in {1,...,4}
            \foreach \j in {1,...,2}
            \draw [->] (input-\i) -- (hidden-\j);

            \foreach \i in {1,...,2}
            \foreach \j in {1,...,2}
            \draw [->] (hidden-\i) -- (hidden2-\j);

            \foreach \i in {1,...,2}
            \foreach \j in {1,...,2}
            \draw [->] (hidden2-\i) -- (output-\j);

            \foreach \l [count=\x from 0] in {Input, 1st Hidden, 2nd Hidden, Output}
            \node [align=center, above] at (\x*1.75,2) {\l \\ layer};
        \end{tikzpicture}
    \end{center}
    \caption{MLP architecure used on the PCA dataset}
    \label{mod}
\end{figure}

\paragraph{Activation and loss functions}
The activation function for the input and hidden layers is a \emph{Relu},
typically used to prevent the \emph{vanishing gradient problem},
and the output one uses a \emph{Softmax} to have classification probabilities
among classes.~\cite{relu}\cite{soft}\cite{vanishing}\\
The loss used is the \emph{Sparse Categorical Crossentropy loss} as it
is well suited for multiclass classification and, since
the classes are integers and not one-hot encoded, the sparse version is preferred.~\cite{entropy}

\paragraph{Choosing an optimizer}
When choosing an optimizer for a neural network one must take into account the
cost of reaching a minimum point on the error function.
Although more complex optimizers exist, build to reduce training
cost or achieve better performances on deep networks, the one choosen
for this model is a classic Stochastic Gradient Descent optimizer.

\subsubsection{Training set results}

Section \vref{feature-extraction} talks about the four different
training sets obtained from the dataset and, without going into details,
states that there is continuous improvement.
We now give a more detailed look on training performances, after
detailing how class imbalance is faced and the applied validation method.

Note that all the random seeds used by Tensorflow are fixed
to make results reproducible. This step is necessary as many parameters initial
value is random, for instance, the neural network weights.

\paragraph{Class imbalance}
To deal with the minority of some classes, balancing techniques should be
applied when fitting the model. One of the possible approaches, and the one followed
here, is to assign class weights.

The main idea is to penalize errors made on not well represented classes to account
for their minority, in particular, each class has weight:
$$w_i = \frac{\#\mathit{total\;samples}}{\#\mathit{classes} * \#\mathit{samples\;of\;class\;i}}$$

Class weights computation relies on the \emph{compute class weights} function with the balanced logic
from sklearn.~\cite{classweight}\\
The following are the computed quantities for the dataset classes:
\begin{center}
    \begin{tabular}{ |l|c|c| }
        \hline
        Class name & Number of samples & Class weight \\
        \hline
        air conditioner & 500 & 0.8998 \\
        car horn & 208 & 2.1629 \\
        children playing & 500 & 0.8998 \\
        dog bark & 500 & 0.8998 \\
        drilling & 500 & 0.8998 \\
        engine idling & 517 & 0.8702 \\
        gun shot & 190 & 2.3678 \\
        jackhammer & 548 & 0.8209 \\
        siren & 536 & 0.8393 \\
        street music & 500 & 0.8998 \\
        \hline
    \end{tabular}
\end{center}
As expected, the less numerous classes have higher class weight than the rest,
in particular, the misclassification of a car horn sample
counts more than double than an air conditioner one.

\paragraph{Stratified cross-validation}
To estimate performance on the training set, stratified cross-validation with
five folds is used. Basically the dataset is divided into five parts
and a model is repeatedly trained on four and tested on one, all while considering class
distribution, indeed, the original distribution of the classes is maintained
in the splits.~\cite{stratified}

The stratified approach is required as there is class imbalance on the training set.
In fact, applying a classical cross-validation could show misleading results,
for instance when the minority classes are more present
in the test fold rather than the training ones; in such cases the loss would be
higher.
The mean accuracy on the test folds gives a hint about the model performance.

For this step the \emph{Stratified KFold} class from scikit learn is used.~\cite{cross-scikit}

\paragraph{Results}
The following are the results on the training sets, using the architectures
presented at \vref{net-str}.

The runs are performed with a five fold stratified cross-validation.
At each fit, epochs are fixed at 100,
batch size is set at 64 and class weights, computed once on
the entire training set, are considered.
The optimizer is the stochastic gradient descent with zero momentum and
0.01 learning rate.

Mean accuracy and standard deviation are computed on the
folds results.
\begin{center}
    \begin{tabular}{ |l|r|r| }
        \hline
        Training set & Mean accuracy & St. deviation \\
        \hline
        132 features unscaled &  0.1138 & 0.0039 \\
        132 features scaled &  0.5743 & 0.0324 \\
        180 features scaled &  0.6363 & 0.0494 \\
        102 features reduced with PCA &  0.6188 & 0.0420 \\
        \hline
    \end{tabular}
\end{center}

There is a great improvement after scaling the training set, after
that small refinements are made.
As accuracy is the best on the last two training sets, those are the two selected to
perform the hyperparameter tuning.

\subsubsection{Hyperparameter tuning}

The last two tries with feature extraction lead to the best results
with stratified cross-validation. Although the two models are reasonable,
they can not be the final ones as many parameters are left on their default value,
for instance, learning rate and momentum of the optimizer are untouched.

The main goal now is to experiments with ranges of model parameters
to find a better one. From now on, the model build on the 180 features training set is
called \emph{Extended model},
while the one tested on the PCA training set is named \emph{PCA model}.

\paragraph{Grid and random search comparison}
Two of the most commonly used strategies in hyperparameter optimization
are \emph{grid} and \emph{random search}~\cite{random-grid}.

In both cases we define ranges of parameters to test different combinations,
for instance, fixed the number of neurons, one could try to find the best
combination of learning rate and momentum that optimize accuracy on the training set.

While similar, the two methodologies differs in the amount of exploration they do.
The grid search try all the possible combinations of parameters, while the
random approach fixes a number of iterations and picks an arbitrary unseen
combination each time.

Obviously the first one is more computationally expensive than the second, if
we fix a small amount of possible iterations, but in theory it finds a better result
than going the random route.
Nonetheless the grid search can led to over-fitting and in practice random
search in preferred.

\paragraph{Random search}
We now run a random search with various parameters
to optimize the initial models.
Note that class weights are still considered and the models are evaluated
again with a five fold stratified cross-validation.
The optimizer used is the stochastic gradient descent.

The considered ranges for parameters for this run are:
\begin{enumerate}
    \item \emph{Neurons}: input layer has dimension $I$, last layer is fixed at 10, while
    the two hidden layers are tested with a number of neurons respectively
    equals to:
    $$H_1 + 2i\;\;\text{and}\;\;H_2 + 2j,\;\;\text{with}\;\; i, j \in \{-2,-1,0,1,2\}$$
    \item \emph{Learning rate}: $0.001, 0.01, 0.1, 0.5$;
    \item \emph{Momentum}: $0.0, 0.01, 0.1, 1$;
    \item \emph{Epochs}: $60, 80, 100$;
    \item \emph{Batch size}: $32, 64$.
\end{enumerate}

The quantities $I$, $H_1$, $H_2$, which are input, first hidden and second hidden
layer dimensions, depend on the initial network architecture.
As stated before, the two models considered are the following:
\begin{center}
    \begin{tabular}{ |l|r|r|r|}
        \hline
        Model name & $I$ & $H_1$ & $H_2$ \\
        \hline
        Extended model & 180 & 80 & 46 \\
        PCA model & 102 & 45 & 30 \\
        \hline
    \end{tabular}
\end{center}

An \emph{early stopper} with patience equals to three is used on the training to stop it when no progress is made with
respect to the last three epochs result.~\cite{early}
The search is performed with 100 iterations for both rounds.

The Extended model is trained on the 180 features dataset,
while the PCA model on the 102 features dataset.

\paragraph{Final models}
The first round of the random search, performed on the Extended model, results
in the following parameters:
\begin{itemize}
    \item Neurons: 180 for input, 76 for the first hidden layer, 50 for the second and 10 for output;
    \item Momentum: 0.01
    \item Learning rate: 0.01
    \item Epochs: 80
    \item Batch size: 64
\end{itemize}
We can see an improvement in accuracy by comparing it to the starting point model:
\begin{center}
    \begin{tabular}{ |l|r|r| }
        \hline
        Model & Mean accuracy & St. deviation \\
        \hline
        Initial extended model & 0.6363 & 0.0494\\
        Tuned extended model & 0.6497 & 0.0431\\
        \hline
    \end{tabular}
\end{center}

The second random search on the smaller PCA model, finds these parameters:
\begin{itemize}
    \item Neurons: 102 for input, 45 for the first hidden layer, 32 for the second and 10 for output;
    \item Momentum: 0.01
    \item Learning rate: 0.1
    \item Epochs: 80
    \item Batch size: 32
\end{itemize}
As before, comparing it with the starting model, we can see some better results:
\begin{center}
    \begin{tabular}{ |l|r|r| }
        \hline
        Model & Mean accuracy & St. deviation \\
        \hline
        Initial PCA model & 0.6188 & 0.0420\\
        Tuned PCA model & 0.6270 & 0.0315\\
        \hline
    \end{tabular}
\end{center}

\paragraph{Final remarks on MLP}
Unexpectedly PCA application lead to worse results compared to the 180
feature dataset. Even after the random search, the so called Tuned Extended model
performs better. For this reason this is the final multilayer perceptron
evaluated on the test set.

\subsection{Convolutional neural network}
\label{cnn}
This Subsection presents the results obtained by a convolutional
neural network trained on the image datasets presented at the end of
Section \vref*{feature-extraction}.
We start by giving an overview of the network, to then proceed
with the training results and hyperparameter tuning.

\subsubsection{Network structure}
The structure of a neural network for image classification
consists of convolutional layers followed by pooling layers,
and, at the end, densely connected ones to have the output classification.

The main idea is to extract relevant features from the images
with the convolutional layers, that apply a kernel to the input
to detect patterns and image features.
After the convolution part there is a pooling layer that reduces dimensionality.
At the end, densely connected layers classify the obtained features.

\paragraph{Stacking convolutions}
Taking inspiration from the \emph{VGG19 architecture}, that stacks two or more
convolutional layers to then apply pooling, the network is built with
the following layers:~\cite{vgg}
\begin{itemize}
    \item \emph{Two Convolution layers}: each one with 8 filters, kernel size of $5 \times 5$, Relu activation, $1 \times 1$ stride;
    \item \emph{MaxPooling}: pooling size of $2 \times 2$, $3 \times 3$ strides;
    \item \emph{Two Convolution layers}: each one with 16 filters, kernel size of $3 \times 3$, Relu activation, $1 \times 1$ stride;
    \item \emph{MaxPooling}: pooling size of $2 \times 2$, $3 \times 3$ strides;
    \item \emph{Flatten layer};
    \item \emph{Dense layers}: dimensions are 2000, 800, 200 and 60, Relu activation;
    \item \emph{Output}: 10 neurons and softmax activation.
\end{itemize}

\begin{figure}[h]
    \includegraphics[width=\textwidth]{images/cnn.png}
    \caption{Diagram of the network used in the experiments. We can see
    the first two convolutions, followed by the max pooling layer, first two blue layers and
    the red one respectively. After that, two other convolutions and
    another max pooling, and finally the densely connected ones, in gray. We can see the principle of
    learning higher level features and fine grain ones, indeed the dimensionality increases
    from the first convolutions to the seconds.}
    \label{cnn}
\end{figure}

\paragraph{Network parameters}
Two crucial parameters for a convolutional layer are the number of filters,
the kernel size and strides dimensions.
The filter number represent the number of ways the layer sees the image,
while the kernel size makes the area
considered by the layer bigger or smaller. One can see a small kernel size as a way
of learning fine grain features, on the opposite, a bigger size capture higher level image characteristics.
Finally, strides determine the reduction on the output shape, for instance, a stride equals to
two, reduces the output shape in half.

One important factor in choosing the values for this parameters is the output dimensionality,
in fact, while strides reduces it, higher filters and smaller kernels increase
the feature space.

For this reasons, filters number is smaller and kernel size is bigger for the first
convolutional layers, while we have more filters and smaller kernel for the consequent ones.
The idea is to learn higher level features first, to then capture small peculiarities.
For the first architecture stride on convolutional layers is kept at one, later, an higher value is tested.

Regarding the max pooling layers, they run a window on the convolution result
to apply a max function and reduce dimensionality. A crucial parameter is the pool size. The
first architecture keeps it at two,  but later three is tested.

\subsubsection{Training set results}
We now present the results on the image dataset using the model introduced in
the \emph{Stacking convolutions} paragraph. Stratified
cross validation with five folds is once again used, the number of epochs
is fixed at 15 and we use an early stopper with patience equals to two, to stop training
if no improvement is made on accuracy for two epochs. The principle of
class weights, introduced with the previous MLP experiments, is reused this time.
The optimizer is the Adam one, as it is built to speed up training on
deep neural networks, with learning rate set to 0.001. Batch size is fixed at 32.

We can compare results with previously tuned multilayer perceptrons, as the validation
technique is the same.
\begin{center}
    \begin{tabular}{ |l|r|r| }
        \hline
        Model & Mean accuracy & St. deviation \\
        \hline
        Tuned extended model& 0.6497 & 0.0431 \\
        Tuned PCA model & 0.6270 & 0.0315 \\
        Initial CNN & 0.5383 & 0.0395 \\
        \hline
    \end{tabular}
\end{center}
Results with the CNN are a big downgrade from previously tested models,
but we need to consider the fact that those have their
hyperparameters tuned.

\subsubsection{Hyperparameter tuning}
Training a CNN is really expensive compared to the MLP networks.
Performing a full random search is infeasible with the resources we have, therefore,
to have an idea about the impact on accuracy of the network parameters, we run
cross-validation on the following models, that, for simplicity, have a name.
\begin{center}
    \begin{tabular}{ |c|r|r|r|l| }
        \hline
        Name & Filters & C. strides & P. strides & Dense structure \\
        \hline
        $C_0$ & 8 &  $1 \times 1$ & $3 \times 3$ & 2000, 800, 200, 60 \\
        $C_1$ & 8 &  $2 \times 2$ & $2 \times 2$ & 300, 150, 80, 25 \\
        $C_2$ & 16 & $1 \times 1$ & $3 \times 3$ & 5000, 2000, 800, 200, 60 \\
        $C_2$ & 16 & $2 \times 2$ & $2 \times 2$ & 600, 200, 80, 25 \\
        \hline
    \end{tabular}
\end{center}

The filter quantity represent the number of filters for the first convolutions.
The subsequent ones have double that quantity.
Kernel size is fixed at $5 \times 5$ and $3 \times 3$ for the first two and last
two convolutional layers respectively.

The \emph{C. strides} values are the strides for convolutions, a value of one does not
reduce dimensionality, while a value of three reduces the output dimensionality by an  half.\\
The \emph{P. strides} are the pooling layers strides. As before, two reduces dimensionality
by an half and three by two thirds.\\
Lastly, the \emph{dense structure} sums up the last layers architecture. For instance,
the model $C_1$ have four consequent densely connected layers, with 300, 150, 80 and
25 neurons respectively, followed by a final output layer of 10 neurons.

A different learning rate is also tested for the Adam optimizer,
indeed 0.001 and 0.003 runs are performed.
Also, two different batch sizes are tested, 32 and 64.
The rest of the network is the same as the initial CNN, thus activation is always a Relu,
apart from the Softmax on the output layer.

Trying all combinations of learning rate and batch size is too expensive, so,
we first try to increase learning rate with 32 batch size, then, on the best learning rate,
we try to increase batch size to 64.

\paragraph{Cross-validation results}
The following are cross-validation results, again with five folds stratified cross-validation
and class weights for training.

We can see that the $C_3$ model is the best performer, even if the differences among models are not really big.
\begin{center}
    \begin{tabular}{ |c|r|r|r|r| }
        \hline
        \multirow{2}{*}{Model name} & \multicolumn{2}{c|}{0.001 l.r.} & \multicolumn{2}{c|}{0.003 l.r.}  \\
        \cline{2-5}
        & M. accuracy & St. deviation & M. accuracy & St. deviation \\
        \hline
        $C_0$ & 0.5383 & 0.0395 & 0.5150 & 0.0253 \\
        $C_1$ & 0.5347 & 0.0480 & 0.5223 & 0.0480 \\
        $C_2$ & 0.5285 & 0.0325 & 0.3909 & 0.1455 \\
        $C_3$ & 0.5412 & 0.0474 & 0.5341 & 0.0451 \\
        \hline
    \end{tabular}
\end{center}

The table shows that increasing the learning rate always leads to worse results, thus
we now keep learning rate at 0.001 and try with 64 batch size.

\begin{center}
    \begin{tabular}{ |c|r|r|r|r| }
        \hline
        \multirow{2}{*}{Model name} & \multicolumn{2}{c|}{32 batch size} & \multicolumn{2}{c|}{64 batch size}  \\
        \cline{2-5}
        & M. accuracy & St. deviation & M. accuracy & St. deviation \\
        \hline
        $C_0$ & 0.5383 & 0.0395 & 0.5272 & 0.0446 \\
        $C_1$ & 0.5347 & 0.0480 & 0.5096 & 0.0403 \\
        $C_2$ & 0.5285 & 0.0325 & 0.5325 & 0.0512 \\
        $C_3$ & 0.5412 & 0.0474 & 0.5212 & 0.0427 \\
        \hline
    \end{tabular}
\end{center}

No improvement again after increasing the batch size, apart on $C_2$ architecture.
The best model found, and the one that is measured on the test set is
the $C_3$ architecture with 0.001 learning rate for the Adam optimizer
and 32 batch size.

\paragraph{Overfitting and underfitting}
Cross-validation results gives an hint about overfitting and underfitting. Indeed,
by looking at the trainable parameters quantity using Keras summary function we have the following results.
\begin{center}
    \begin{tabular}{ |c|r| }
        \hline
        Model name & Trainable parameters\\
        \hline
        $C_0$ & 13011950 \\
        $C_1$ & 256095 \\
        $C_2$ & 67957294 \\
        $C_3$ & 923789 \\
        \hline
    \end{tabular}
\end{center}
The numbers might indicate that the $C_1$ model is underfitting, as the number
of parameters does not create the required complexity in the model to capture the dataset,
the $C_2$ and initial models are overfitting, as they have too many parameters
thus they are learning too much from the training.
$C_3$ seems to be at a sweet spot between the two, confirmed by the higher accuracy.

\paragraph{Final remarks on CNN}
Unfortunately, the high cost of training a CNN made impossibile to run a Random search
starting from the initial network structure, nonetheless a total
of twelve models are tested. Results are worse than the ones obtained
with the MLP models.
\newpage


\subsection{\texorpdfstring{The 1\textsuperscript{st} Law of Thermodynamics}{The 1st Law of Thermodynamics}}
Let $\Delta E$ be the change in energy of a system, $Q$ be the heat that flows in/out the system, and W the work done on the system. The first law of thermodynamics simply states that the total change in energy of a system is equal to the sum of its mechanical and non-mechanical transfers of energy, or
\begin{equation}
    \Delta E=Q+W
\end{equation}
Be careful with the signs when using this equation! For example, had I defined $W$ as the amount of work done \textit{by} the system, this equation would instead be
\begin{equation*}
    \Delta E=Q-W
\end{equation*}
It is worth noting here that while $W$ and $Q$ are both \textbf{functions of path}; how much work I do or a system does, or how much heat flows in/out of a system depends on how a process happens. However, internal energy is a \textbf{function of state}; it depends only on the current state of the system, but not how the system got there. The moral is that while how a system might gain or lose energy is a function of the path, the internal energy itself is a function of the state of the system only.


\documentclass[11pt, letterpaper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}

\newcommand{\e}{\epsilon}
\newcommand{\SI}{\Sigma}
\newcommand{\dij}{\delta_{ij}}
\newcommand{\1}{\textbf{1}}
\newcommand{\gd}{\dot \gamma}
\newcommand{\pd}[2]{\frac{\partial #1}{\partial #2}}
\newcommand{\vect}[1]{\underline{#1}} %\vect can be changed to make vectors appear bold or underlined or with arrow on top
\newcommand{\p}[1]{\grave{#1}} %\p is for primed variables. The accent on top can be changed to \hat \tilde etc.

\title{Lecture 8: The Stress Tensor}
\author{}
\begin{document}
\maketitle

\section*{Overview}

We start by introducing the two kinds of forces studied in continuum mechanics - body forces and surface forces. While body forces only vary with position and time, surface forces also depend on the orientation of the chosen surface. In order to remove the arbitrariness intoduced by orientation and describe the behaviour of surface forces in terms of intrinsic properties of the fluid, we define the quantity called the stress tensor. It is obtained by a force balance on a small fluid element in static equilibrium. Balancing torques shows that the stress tensor is symmetric. Then we look at the hydrostatic variation of pressure due to body forces and motion induced due to density stratification.

Finally, we will look at a case where the stress tensor is in fact antisymmetric due to the magnetic interactions of constituent molecules.

\section{Body forces and surface forces}
The continuum mechanics approach to fluid mechanics makes the approximation that we are operating at length scales much larger than the microscopic length scales. Any small volume of fluid that we may consider will still be large enough to contain a large number of fluid molecules so that averaging makes sense and a smooth variation of the property can be obtained. E.g. density of the fluid can be precisely written as $\rho(\vect X, t)=\sum_{i=1}^N m_i \delta(\vect X -\vect X_i(t))$ which is a highly singular function. But in practice $N$ is very large even for small volumes (check the Loschmidt Number) which allows us to consider the average quantity $\rho_{avg}=\frac{1}{V}\int \rho dV$. This gives us a smoothly varying density field. We can now define the body forces.

\subsection{Body forces}

Body forces are forces that act through the bulk of the fluid and hence scale with the volume of the fluid $(\sim O(\delta l^3))$ in any small element. These are usually long ranged. If $\vect{F}$ is a body force per unit mass, then total body force on an element of volume $dV$ will be $\rho \vect F dV$. Some examples of body forces are
\begin{itemize}
\item gravity: $\rho \vect g$
\item centrifugal force: $\rho \Omega^2(\vect X - (\vect X \cdot \vect\Omega)\vect\Omega)$ where $\vect\Omega$ is the axis of rotation.
\item Lorentz force: $\vect j \wedge \vect B$ where $\vect j$ is the current density vector and $\vect B$ is the magnetic field. Since $\vect B$ is a psuedo vector, the cross product gives us a true vector - the force.
\end{itemize}

\subsection{Surface forces}
Surface forces arise due to the discrete structure of the fluid. Since the continuum model ignores the discrete structure, they must be accounted for the surface forces seperately. They are manifestations of momentum transport from one small volume of fluid to another, either through collisions or via dipole (Van der Wall's) interactions. In gases the main source of momentum transport is through collisions. This is called the kinetic transport. In fluids, the key contribution is due to the electrostatic dipole interactions - potential transport besides a small fraction due to kinetic transport.

These interactions only take place across the surface of a small element in consideration and hence surface forces scale with area $(\sim O(\delta l^2))$

\section{The stress tensor}
Body forces are, in general, functions of $(\vect X, t)$ but surface forces also depend on the orientation of the chosen surface. If $\vect\SI$ is a surface force, then $\vect \SI \equiv \vect\SI(\vect X, \vect n, t)$ where $\vect n$ is the unit normal to the surface. But the normal is not a quantity intrinsic to the fluid and hence we want a representation of the surface forces free from such arbitrary variables. This is given by the stress tensor and we can derive it in three steps. Consider a small fluid element of characterstic length $\delta l$. Then-
\begin{itemize}
\item Show that $\vect\SI(\vect X, -\vect n, t) = -\vect\SI(\vect X, \vect n, t)$ using force balance on a massles surface element.
\item Body forces scale as $\sim \delta l^3$ whereas surface forces scale as $\sim \delta l^2$. Therefore for $\lim \delta l \to 0$, only surface forces are important and the force balance only needs to account for surface forces.
\item Show that $\SI_i(\vect n, \vect X, t) = \sigma_{ij} n_j$ using force balance on a small fluid element.
\end{itemize}

$\sigma_{ij}$ is the stress tensor which allows us to find force on any given surface by contracting it with the surface normal. Being a second order tensor, it has in general nine independent elements but using moment balance (conservation of angular momentum) it can be shown that the stress tensor is in fact symmetric and hence has only 6 independent elements.

For moment balance on a small element, we again only need to consider surface forces because they are $O(\delta l^3)$ while the body forces are $O(\delta l^4)$. Then balancing torques implies
\begin{align*}
&\int x_i \wedge (\sigma_{jk} n_k) dA = 0 \\
\Rightarrow &\int \epsilon_{ijk} x_j \sigma_{kl} n_l dA = 0 \\
\Rightarrow &\int \pd{}{x_l} \big(\epsilon_{ijk} x_j \sigma_{kl} \big) dV = 0 \text{\quad (\footnotesize{Divergence theorem})} \\
\Rightarrow &\int \big(\epsilon_{ijk} \pd{x_j}{x_l} \sigma_{kl} \big) dV = 0 \\
\Rightarrow & \epsilon_{ijk} \delta_{jl} \sigma_{kl} = 0 \\
\Rightarrow & \epsilon_{ijk} \sigma_{kj} = 0 \\
\end{align*}
Since double contraction of a symmetric and an antisymmetric tensor equals zero, we have the result that stress tensor is a second order symmetric tensor. Notice that we have condsidered $\sigma_{ij}$ to be constant in space. This is justified because we are considering a small volume with $\lim \delta l \to 0$. As all properties vary smoothly, we can consider the stresses to be nearly constant in this small element.

Essentially we have shown that
\begin{itemize}
\item $\sigma_{ij}$ is a symmetric tensor. Therefore $\sigma_{12} = \sigma_{21}$ if they are measured at the same point.
\item $\sigma_{ij}n_jdA$ gives us force on the surface with area $dA \vect n$
\end{itemize}

The off-diagonal elemets of $\sigma_{ij}$ give us the shear stress on a face with normal in the $i^{th}$ direction and force in the $j^{th}$. The diagonal elements give us the normal stresses. However, if the fluid is isotropic and at rest, then we must have
\begin{align*}
\sigma_{ij} &\propto \delta_{ij} \\
\Rightarrow\sigma_{ij} &= -p \delta_{ij} \\
\end{align*}
In an isotropic fluid at rest, we will only have normal stress and the force per unit area is given by $\SI_i = \sigma_{ij}n_j = -p n_i$. If we are looking at an interface with normal $\vect n$ then certainly we cannot have forces perpendicular to the interface. Therefore we remove the normal component of the stress tensor and write
\begin{align*}
\sigma_{ij} &= T (\delta_{ij} - n_in_j)
\end{align*}
where $T$ is the surface tension.

\section{Hydrostatic pressure variation}
A hydrostatic force balance of surface and body forces can be written as
\begin{align*}
\int \rho \vect F dV + \int \sigma_{ij} n_j dA &= 0\\
\end{align*}
For statics, $\sigma_{ij} = -p \delta_{ij}$. Then, using divergence theorem to convert area to volume integral, we can write
\begin{align*}
\pd{p}{x_i} &= \rho F_i \\
\end{align*}
If density is constant
\begin{align*}
p &= p_0 + \rho_0 g_ix_i
\end{align*}
If we allow density to vary, then
\begin{align*}
\pd{p}{x_i} &= \rho g_i \\
\end{align*}
Taking the curl of the equation and noting that curl of gradient vanishes, we get
\begin{align*}
\epsilon_{ijk}\pd{\rho}{x_j}g_k &= 0\\
\Rightarrow \nabla \rho \wedge \vect g &= 0
\end{align*}

Therefore hydrostatic equilibrium can be maintained as long as density gradient is parallel to gravity or lines of constant density are parallel to constant body force contours. If density variation is not parallel to gravity, then $\sigma_{ij}$ will not be isotropic and shear forces will cause motion.

Density stratification also generates vorticity. While deriving the vorticity equation by taking the curl of the Navier-Stokes, we encounter the term $\nabla \wedge \nabla p/\rho$. If density is constant, the term simply vanishes. But otherwise we get
\begin{align*}
\frac{D\vect\omega}{Dt} = \vect\omega\cdot\vect u + \nu \nabla^2 \vect \omega + \underbrace{\frac{1}{\rho^2}\nabla\rho \wedge \nabla p}_{\substack{\text{\footnotesize{Baroclinic source}}\\ \text{\footnotesize{of vorticity}}}}
\end{align*}

This indicates that if pressure gradient is not parallel to density stratification, vorticity will be generated. This can be used to explain inertial oscillations of water in vessel (sloshing). These are essentially standing gravity waves. In lakes, similar waves generated due to wind are known as Seiches.

\section{Asymmetric stress tensor}

We will consider a special case of ferrofluids where torque balance shows that the stress tensor cannot be symmetric. Ferrofluids are essentially ferromagnetic particles suspended in a fluid medium. In the presence of a magnetic field, these particles will have the tendency to align with the field. The crucial difference here is that the torque due to body forces also scales as $\delta l^3$ which is the same for surface forces.

Surface forces, on a small cube of size $\delta l$, are proportional to area of its faces and hence scale as $\delta l^2$. Their moment, therefore, scales as $\delta l^3$. Body forces are proportional to volume of the cube. So they scale as $\delta l^3$ and their moments as $\delta l^4$. But in the case of ferrofluids in magnetic field, body forces scale as $\delta l^3$ and so do their couple. This is because, for gravity, when we compute couple from force, an additional $\delta l$ must be factored in. But magnetic torque is proportional to $\vect p \wedge \vect B$ and no new $\delta l$ comes in.

Therefore in the moment balance, we must consider both these contributions. Let $M\vect p$ denote a magnetic dipole with magnetic moment $M$ and orientation $p$ in a magnetic field $B$. Then
\begin{align*}
\text{Surface couple} &\sim \text{Body couple}\\
\Rightarrow \int\vect X \wedge (\sigma_{ij}n_j)  dA &= -\sum_{i=1}^N Mp_i \wedge B_j
\end{align*}

Since the orientations of the magnetic dipoles differ, we must use a probability density function to evaluate the RHS. Let $P(\vect p)$ denote the probability density of obtaining a dipole with an orientation $\vect p$ and $n$ be the number of particles per unit volume. Then body couple due to all the particles is given by
\begin{align*}
\sum_{i=1}^N Mp_i \wedge B_j &= \underbrace{\int \underbrace{dV n}_{\substack{\text{total number}\\ \text{of particles}\\ \text{in dV}}} \underbrace{P(\vect p)d\vect p}_{\substack{\text{fraction of}\\ \text{particles with}\\ \text{orientation}\\ \text{$(\vect p \pm d\vect p)$}}} \underbrace{M\vect p \wedge \vect B}_{\substack{\text{couple due to}\\ \text{one particle}}}}_{\text{Orientation averaged couple}} \\
\end{align*}
Substituting this expression in the force balance
\begin{align*}
\int\vect X \wedge (\sigma_{ij}n_j)  dA &= -\int dV n P(\vect p) d\vect p M\vect p \wedge \vect B\\
\end{align*}
Then using divergence theorem for the LHS as done before, we get
\begin{align*}
\epsilon_{ijk}\sigma_{kj} &= -\int dV n P(\vect p) d\vect p M\vect p \wedge \vect B\\
\end{align*}
The RHS is now a vector (say $\beta_i$) which is not zero. Therefore $\sigma_{ij}$ cannot be symmetric.
\section*{Appendix}
\subsection{Derivation of the stress tensor}
\subsection{Torque balance for the stress tensor}
\subsection{Normalization of the probability distribution}
Let $P(\vect p)$ denote the probability density of obtaining a dipole with an orientation $\vect p$. Then, probability of obtaining a particle with orienatation between $(\theta , \theta\pm d\theta)$ and $(\phi, \phi\pm d\phi)$ is $P(\vect p)$ times the solid angle between $d\theta$ and $d\phi$ which is $P(\vect p)\sin\theta d\theta d\phi$. Therefore,
\begin{align*}
\int P(\vect p)\sin\theta d\theta d\phi &= 1\\
\end{align*}
This will determine the normalization constant for the probability distribution.
\end{document}


% Copyright 2019 by Mark Wibrow
%
% 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{Mathematical Expressions}
\label{pgfmath-syntax}

The easiest way of using \pgfname's mathematical engine is to provide a
mathematical expression given in familiar infix notation, for example,
|1cm+4*2cm/5.5| or |2*3+3*sin(30)|. This expression can be parsed by the
mathematical engine and the result can be placed in a dimension register, a
counter, or a macro.

It should be noted that all calculations must not exceed $\pm16383.99999$ at
\emph{any} point, because the underlying computations rely on \TeX{}
dimensions. This means that many of the underlying computations are necessarily
approximate and, in addition, not very fast. \TeX{} is, after all, a
typesetting language and not ideally suited to relatively advanced mathematical
operations. However, it is possible to change the computations as described in
Section~\ref{pgfmath-reimplement}.

In the present section, the high-level macros for parsing an expression are
explained first, then the syntax for expression is explained.

\subsection{Parsing Expressions}
\label{pgfmath-registers}
\label{pgfmath-parsing}

\subsubsection{Commands}

The \todosp{why 2 labels?}basic command for invoking the parser of \pgfname's
mathematical engine is the following:

\begin{command}{\pgfmathparse\marg{expression}}
    This macro parses \meta{expression} and returns the result without units in
    the macro |\pgfmathresult|.

    \example |\pgfmathparse{2pt+3.5pt}| will set |\pgfmathresult| to the text
    |5.5|.

    In the following, the special properties of this command are explained. The
    exact syntax of mathematical expressions is explained in Sections
    \ref{pgfmath-operators} and~\ref{pgfmath-functions}.
    %
    \begin{itemize}
        \item The result stored in the macro |\pgfmathresult| is a decimal
            \emph{without units}. This is true regardless of whether the
            \meta{expression} contains any unit specification. All numbers with
            units are converted to points first. See
            Section~\ref{pgfmath-units} for details on units.
        \item The parser will recognize \TeX{} registers and box dimensions, so
            |\mydimen|, |0.5\mydimen|, |\wd\mybox|, |0.5\dp\mybox|,
            |\mycount\mydimen| and so on can be parsed.
        \item The $\varepsilon$-TeX\ extensions |\dimexpr|, |\numexpr|,
            |\glueexpr|, and |\muexpr| are recognized and evaluated. The values
            they result in will be used in the further evaluation, as if you
            had put |\the| before them.
        \item Parenthesis can be used to change the order of the evaluation.
        \item Various functions are recognized, so it is possible to parse
            |sin(.5*pi r)*60|, which means ``the sine of $0.5$ times $\pi$
            radians, multiplied by 60''. The argument of functions can be any
            expression.
        \item Scientific notation in the form |1.234e+4| is recognized (but the
            restriction on the range of values still applies). The exponent
            symbol can be upper or lower case (i.e., |E| or |e|).
        \item An integer with a zero-prefix (excluding, of course zero itself),
            is interpreted as an octal number and is automatically converted to
            base 10.
        \item An integer with prefix |0x| or |0X| is interpreted as a
            hexadecimal number and is automatically converted to base 10.
            Alphabetic digits can be in uppercase or lowercase.
        \item An integer with prefix |0b| or |0B| is interpreted as a binary
            number and is automatically converted to base 10.
        \item An expression (or part of an expression) surrounded with double
            quotes (i.e., the character |"|) will not be evaluated. Obviously
            this should be used with great care.
    \end{itemize}
\end{command}

\begin{command}{\pgfmathqparse\marg{expression}}
    This macro is similar to |\pgfmathparse|: it parses \meta{expression} and
    returns the result in the macro |\pgfmathresult|. It differs in two
    respects. Firstly, |\pgfmathqparse| does not parse functions, scientific
    notation, the prefixes for binary octal, or hexadecimal numbers, nor does
    it accept the special use of |"|, |?| or |:| characters. Secondly, numbers
    in \meta{expression} \emph{must} specify a \TeX{} unit (except in such
    instances as |0.5\pgf@x|), which greatly simplifies the problem of parsing
    real numbers. As a result of these restrictions |\pgfmathqparse| is about
    twice as fast as |\pgfmathparse|. Note that the result will still be a
    number without units.
\end{command}

\begin{command}{\pgfmathpostparse}
    At the end of the parse this command is executed, allowing some custom
    action to be performed on the result of the parse. When this command is
    executed, the macro |\pgfmathresult| will hold the result of the parse (as
    always, without units). The result of the custom action should be used to
    redefine |\pgfmathresult| appropriately. By default, this command is
    equivalent to |\relax|. This differs from previous versions, where, if the
    parsed expression contained no units, the result of the parse was scaled
    according to the value in |\pgfmathresultunitscale| (which by default was
    |1|).

    This scaling can be  turned on again using:
    |\let\pgfmathpostparse=\pgfmathscaleresult|. Note, however that by scaling
    the result, the base conversion functions will not work, and the |"|
    character should not be used to quote parts of an expression.
\end{command}

Instead of the |\pgfmathparse| macro you can also use wrapper commands, whose
usage is very similar to their cousins in the \calcname{} package. The only
difference is that the expressions can be any expression that is handled by
|\pgfmathparse|. For all of the following commands, if \meta{expression} starts
with |+|, no parsing is done and a simple assignment or increment is done using
normal \TeX\ assignments or increments. This will be orders of magnitude faster
than calling the parser.

The effect of the following commands is always local to the current \TeX\
scope.

\begin{command}{\pgfmathsetlength\marg{register}\marg{expression}}
    Basically, this command sets the length of the \TeX{} \meta{register} to
    the value specified by \meta{expression}. However, there is some fine
    print:

    First, in case \meta{expression} starts with a |+|, a simple \TeX\
    assignment is done. In particular, \meta{register} can be a glue register
    and \meta{expression} be something like |+1pt plus 1fil| and the
    \meta{register} will be assigned the expected value.

    Second, when the \meta{expression} does not start with |+|, it is first
    parsed using |\pgfmathparse|, resulting in a (dimensionless) value
    |\pgfmathresult|. Now, if the parser encountered the unit |mu| somewhere in
    the expression, it assumes that \meta{register} is a |\muskip| register and
    will try to assign to \meta{register} the value |\pgfmathresult| followed
    by |mu|. Otherwise, in case |mu| was not encountered, it is assumed that
    \meta{register} is a dimension register or a glue register and we assign
    |\pgfmathresult| followed by |pt| to it.

    The net effect of the above is that you can write things like
    %
\begin{codeexample}[]
  \muskipdef\mymuskip=0
  \pgfmathsetlength{\mymuskip}{1mu+3*4mu} \the\mymuskip
\end{codeexample}
    %
\begin{codeexample}[]
  \dimendef\mydimen=0
  \pgfmathsetlength{\mydimen}{1pt+3*4pt}  \the\mydimen
\end{codeexample}
    %
\begin{codeexample}[]
  \skipdef\myskip=0
  \pgfmathsetlength{\myskip}{1pt+3*4pt}  \the\myskip
\end{codeexample}

    One thing that will \emph{not} work is
    |\pgfmathsetlength{\myskip}{1pt plus 1fil}| since the parser does not
    support fill's. You can, however, use the |+| notation in this case:
    %
\begin{codeexample}[]
  \skipdef\myskip=0
  \pgfmathsetlength{\myskip}{+1pt plus 1fil}  \the\myskip
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfmathaddtolength\marg{register}\marg{expression}}
    Adds the value of \meta{expression} to the \TeX{} \meta{register}. All of
    the special consideration mentioned for |\pgfmathsetlength| also apply here
    in the same way.
\end{command}

\begin{command}{\pgfmathsetcount\marg{count register}\marg{expression}}
    Sets the value of the \TeX{} \meta{count register}, to the \emph{truncated}
    value specified by \meta{expression}.
\end{command}

\begin{command}{\pgfmathaddtocount\marg{count register}\marg{expression}}
    Adds the \emph{truncated} value  of \meta{expression} to the \TeX{}
    \meta{count register}.
\end{command}

\begin{command}{\pgfmathsetcounter\marg{counter}\marg{expression}}
    Sets the value of the \LaTeX{} \meta{counter} to the \emph{truncated} value
    specified by \meta{expression}.
\end{command}

\begin{command}{\pgfmathaddtocounter\marg{counter}\marg{expression}}
    Adds the \emph{truncated} value  of \meta{expression} to \meta{counter}.
\end{command}

\begin{command}{\pgfmathsetmacro\marg{macro}\marg{expression}}
    Defines \meta{macro} as the  value of \meta{expression}. The result is a
    decimal without units.
\end{command}

\begin{command}{\pgfmathsetlengthmacro\marg{macro}\marg{expression}}
    Defines \meta{macro} as the value of \meta{expression} \LaTeX{} \emph{in
    points}.
\end{command}

\begin{command}{\pgfmathtruncatemacro\marg{macro}\marg{expression}}
    Defines \meta{macro} as the truncated value of \meta{expression}.
\end{command}

\subsubsection{Considerations Concerning Units}
\label{pgfmath-units}

As was explained earlier, the parser commands like |\pgfmathparse| will always
return a result without units in it and all dimensions that have a unit like
|10pt| or |1in| will first be converted to \TeX\ points (|pt|) and, then, the
unit is dropped.

Sometimes it is useful, nevertheless, to find out whether an expression or not.
For this, you can use the following commands:

{\let\ifpgfmathunitsdeclared\relax
  \begin{command}{\ifpgfmathunitsdeclared}
    After a call  of |\pgfmathparse| this if will be true exactly if
    some unit was encountered in the expression. It is always set
    globally in each call.

    Note that \emph{any} ``mentioning'' of a unit inside an
    expression will set this \TeX-if to true. In particular, even an
    expressionlike |2pt/1pt|, which arguably should be considered
    ``scalar'' or ``unit-free'' will still have this \TeX-if set to
    true. However, see the |scalar| function for a way to change
    this.
  \end{command}
}

\begin{math-function}{scalar(\mvar{value})}
\mathcommand
    This function is the identity function on its input, but it will reset the
    \TeX-if |\ifpgfmathunitsdeclared|. Thus, it can be used to indicate that
    the given \meta{value} should be considered as a ``scalar'' even when it
    contains units; but note that it will work even when the \meta{value} is a
    string or something else. The only effect of this function is to clear the
    unit declaration.
    %
\begin{codeexample}[]
\pgfmathparse{scalar(1pt/2pt)} \pgfmathresult\
\ifpgfmathunitsdeclared with \else without \fi unit
\end{codeexample}

    Note, however, that this command (currently) really just clears the \TeX-if
    as the input is scanned from left-to-right. Thus, even if there is a use of
    a unit before the |scalar| function is used, the \TeX-if will be cleared:
    %
\begin{codeexample}[]
\pgfmathparse{1pt+scalar(1pt)} \pgfmathresult\
\ifpgfmathunitsdeclared with \else without \fi unit
\end{codeexample}

    The other way round, a use of a unit after the |scalar| function will set
    the units once more.
    %
\begin{codeexample}[]
\pgfmathparse{scalar(1pt)+1pt} \pgfmathresult\
\ifpgfmathunitsdeclared with \else without \fi unit
\end{codeexample}

    For these reasons, you should use the function only on the outermost level
    of an expression.

    A typical use of this function is the following:
    %
\begin{codeexample}[preamble={\usetikzlibrary{calc,quotes}}]
\tikz{
  \coordinate["$A$"]       (A) at (2,2);
  \coordinate["$B$" below] (B) at (0,0);
  \coordinate["$C$" below] (C) at (3,0);
  \draw (A) -- (B) -- (C) -- cycle;
  \path
    let \p1 =($(A)-(B)$), \p2 =($(A)-(C)$),
        \n1 = {veclen(\x1,\y1)}, \n2 = {veclen(\x2,\y2)}
    in  coordinate ["$D$" below] (D) at ($ (B)!scalar(\n1/(\n1+\n2))!(C) $);
  \draw (A) -- (D);
}
\end{codeexample}
    %
\end{math-function}

A special kind of units are \TeX's ``math units'' (|mu|). It will be treated as
if |pt| had been used, but you can check whether an expression contained a math
unit using the following:
%
{\let\ifpgfmathmathunitsdeclared\relax
  \begin{command}{\ifpgfmathmathunitsdeclared}
    This \TeX-if is similar to |\ifpgfmathunitsdeclared|, but it
    is only set when the unit |mu| is encountered at least
    once. In this case, |\ifpgfmathunitsdeclared| will \emph{also}
    be set to true. The |scalar| function has no effect on this \TeX-if.
  \end{command}
}

\subsection{Syntax for Mathematical Expressions: Operators}

The syntax for the expressions recognized by |\pgfmathparse| and friends is
rather straightforward. Let us start with the operators.

\label{pgfmath-operators}

The following operators (presented in the context in which they are used) are
recognized:
%
\begin{math-operator}{+}{infix}{add}
    Adds \mvar{x} to \mvar{y}.
\end{math-operator}

\begin{math-operator}{-}{infix}{subtract}
    Subtracts \mvar{y} from \mvar{x}.
\end{math-operator}

\begin{math-operator}{-}{prefix}{neg}
    Reverses the sign of \mvar{x}.
\end{math-operator}

\begin{math-operator}{*}{infix}{multiply}
    Multiplies \mvar{x} by \mvar{y}.
\end{math-operator}

\begin{math-operator}{/}{infix}{divide}
    Divides \mvar{x} by \mvar{y}. An error will result if \mvar{y} is 0, or if
    the result of the division is too big for the mathematical engine. Please
    remember when using this command that accurate (and reasonably quick)
    division of real numbers that are not integers is particularly tricky in
    \TeX.
\end{math-operator}

\begin{math-operator}{\char`\^}{infix}{pow}
    Raises \mvar{x} to the power \mvar{y}.
\end{math-operator}

\begin{math-operator}{\protect\exclamationmarktext}{postfix}{factorial}
    Calculates the factorial of \mvar{x}.
\end{math-operator}

\begin{math-operator}{r}{postfix}{deg}
    Converts \mvar{x} to degrees (\mvar{x} is assumed to be in radians). This
    operator has the same precedence as multiplication.
\end{math-operator}

\begin{math-operators}{?}{:}{conditional}{ifthenelse}
    |?| and |:| are special operators which can be used as a shorthand for |if|
    \mvar{x} |then| \mvar{y} |else| \mvar{z} inside the parser. The expression
    \mvar{x} is taken to be true if it evaluates to any non-zero value.
\end{math-operators}

\begin{math-operator}{==}{infix}{equal}
    Returns |1| if \mvar{x}$=$\mvar{y}, |0| otherwise.
\end{math-operator}

\begin{math-operator}{>}{infix}{greater}
    Returns |1| if \mvar{x}$>$\mvar{y}, |0| otherwise.
\end{math-operator}

\begin{math-operator}{<}{infix}{less}
    Returns |1| if \mvar{x}$<$\mvar{y}, |0| otherwise.
\end{math-operator}

\begin{math-operator}{\protect\exclamationmarktext=}{infix}{notequal}
    Returns |1| if \mvar{x}$\neq$\mvar{y}, |0| otherwise.
\end{math-operator}

\begin{math-operator}{>=}{infix}{notless}
    Returns |1| if \mvar{x}$\geq$\mvar{y}, |0| otherwise.
\end{math-operator}

\begin{math-operator}{<=}{infix}{notgreater}
    Returns |1| if \mvar{x}$\leq$\mvar{y}, |0| otherwise.
\end{math-operator}

\begin{math-operator}{{\char`\&}{\char`\&}}{infix}{and}
    Returns |1| if both \mvar{x} and \mvar{y} evaluate to some non-zero value.
    Both arguments are evaluated.
\end{math-operator}

{
 \catcode`\|=12
\begin{math-operator}[no index]{||}{infix}{or}
        \index{*pgfmanualvbarvbarr@\protect\texttt{\protect\pgfmanualvbarvbar} math operator}%
        \index{Math operators!*pgfmanualvbarvbar@\protect\texttt{\protect\pgfmanualvbarvbar}}%
    Returns {\tt 1} if either \mvar{x} or \mvar{y} evaluate to some non-zero
    value.
\end{math-operator}
}

\begin{math-operator}{\protect\exclamationmarktext}{prefix}{not}
    Returns |1| if \mvar{x} evaluates to zero, |0| otherwise.
\end{math-operator}

\begin{math-operators}{(}{)}{group}{}
    These operators act in the usual way, that is, to control the order in
    which operators are executed, for example, |(1+2)*3|. This includes the
    grouping of arguments for functions, for example, |sin(30*10)| or
    |mod(72,3)| (the comma character is also treated as an operator).

    Parentheses for functions with one argument are not always necessary,
    |sin 30| (note the space) is the same as |sin(30)|. However, functions have
    the highest precedence so, |sin 30*10| is the same as |sin(30)*10|.
\end{math-operators}

\begin{math-operators}{\char`\{}{\char`\}}{array}{}
    These operators are used to process array-like structures (within an
    expression these characters do not act like \TeX{} grouping tokens). The
    \meta{array specification} consists of comma separated elements, for
    example, |{1, 2, 3, 4, 5}|. Each element in the array will be evaluated as
    it is parsed, so expressions can be used. In addition, an element of an
    array can be an array itself, allowing multiple dimension arrays to be
    simulated: |{1, {2,3}, {4,5}, 6}|. When storing an array in a macro, do not
    forget the surrounding braces: |\def\myarray{{1,2,3}}| not
    |\def\myarray{1,2,3}|.
    %
\begin{codeexample}[]
\def\myarray{{1,"two",2+1,"IV","cinq","sechs",sin(\i*5)*14}}
\foreach \i in  {0,...,6}{\pgfmathparse{\myarray[\i]}\pgfmathresult, }
\end{codeexample}
    %
\end{math-operators}

\chardef\lbrack=`\[
\chardef\rbrack=`\]
\begin{math-operators}{\lbrack}{\rbrack}{array access}{array}
    |[| and |]| are two operators used in one particular circumstance: to
    access an array (specified using the |{| and |}| operators) using the index
    \mvar{x}. Indexing starts from zero, so, if the index is greater than, or
    equal to, the number of values in the array, an error will occur, and zero
    will be returned.
    %
\begin{codeexample}[]
\def\myarray{{7,-3,4,-9,11}}
\pgfmathparse{\myarray[3]} \pgfmathresult
\end{codeexample}

    If the array is defined to have multiple dimensions, then the array access
    operators can be immediately repeated.
    %
\begin{codeexample}[]
\def\print#1{\pgfmathparse{#1}\pgfmathresult}
\def\identitymatrix{{{1,0,0},{0,1,0},{0,0,1}}}
\tikz[x=0.5cm,y=0.5cm]\foreach \i in {0,1,2} \foreach \j in {0,1,2}
  \node at (\j,-\i) [anchor=base] {\print{\identitymatrix[\i][\j]}};
\end{codeexample}
    %
\end{math-operators}

\begin{math-operators}{\char`\"}{\char`\"}{group}{}
    These operators are used to quote \mvar{x}. However, as every expression is
    expanded with |\edef| before it is parsed, macros (e.g., font commands like
    |\tt| or |\Huge|) may need to be ``protected'' from this expansion (e.g.,
    |\noexpand\Huge|). Ideally, you should avoid such macros anyway. Obviously,
    these operators should be used with great care as further calculations are
    unlikely to be possible with the result.
    %
\begin{codeexample}[]
\def\x{5}
\foreach \y in {0,10}{
  \pgfmathparse{\x > \y ? "\noexpand\Large Bigger" : "\noexpand\tiny smaller"}
  \x\ is \pgfmathresult\ than \y.
}
\end{codeexample}
    %
\end{math-operators}

\subsection{Syntax for Mathematical Expressions: Functions}
\label{pgfmath-functions}

The following functions are recognized:

\medskip
\def\mathlink#1{\hyperlink{math:#1}{\tt#1}}
\begin{tikzpicture}
\foreach \f [count=\i from 0] in
{abs,acos,add,and,array,asin,atan,atan2,bin,ceil,cos,
 cosec,cosh,cot,deg,depth,div,divide,e,equal,factorial, false,
 floor,frac,gcd,greater,height,hex,Hex,int,ifthenelse,iseven,isodd,isprime,
 less,ln,log10,log2,max,min,mod,Mod,multiply,
 neg,not,notequal,notgreater,notless,
 oct,or,pi,pow,rad,rand,random,real,rnd,round,
 scalar,sec,sign,sin,sinh,sqrt,subtract,tan,tanh,true, veclen,width}
\node [anchor=base west] at ({int(\i/12)*2.5cm},{-mod(\i,12)*1.1*\baselineskip}) {\mathlink{\f}};
\end{tikzpicture}
\bigskip

Each function has a \pgfname{} command associated with it (which is also shown
with the function below). In general, the command is simply the name of the
function prefixed with |\pgfmath|, for example, |\pgfmathadd|, but there are
some notable exceptions.

\subsubsection{Basic arithmetic functions}
\label{pgfmath-functions-basic}

\begin{math-function}{add(\mvar{x},\mvar{y})}
\mathcommand
    Adds $x$ and $y$.
    %
\begin{codeexample}[]
\pgfmathparse{add(75,6)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{subtract(\mvar{x},\mvar{y})}
\mathcommand
    Subtract $y$ from $x$.
    %
\begin{codeexample}[]
\pgfmathparse{subtract(75,6)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{neg(\mvar{x})}
\mathcommand
    This returns $-\mvar{x}$.
    %
\begin{codeexample}[]
\pgfmathparse{neg(50)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{multiply(\mvar{x},\mvar{y})}
\mathcommand
    Multiply $x$ by $y$.
    %
\begin{codeexample}[]
\pgfmathparse{multiply(75,6)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{divide(\mvar{x},\mvar{y})}
\mathcommand
    Divide $x$ by $y$.
    %
\begin{codeexample}[]
\pgfmathparse{divide(75,6)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{div(\mvar{x},\mvar{y})}
\mathcommand
    Divide $x$ by $y$ and return the integer part of the result.
    %
\begin{codeexample}[]
\pgfmathparse{div(75,9)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{factorial(\mvar{x})}
\mathcommand
    Return \mvar{x}!.
    %
\begin{codeexample}[]
\pgfmathparse{factorial(5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{sqrt(\mvar{x})}
\mathcommand
    Calculates $\sqrt{\textrm{\mvar{x}}}$.
    %
\begin{codeexample}[]
\pgfmathparse{sqrt(10)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{sqrt(8765.432)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{pow(\mvar{x},\mvar{y})}
\mathcommand
    Raises \mvar{x} to the power \mvar{y}. For greatest accuracy, \mvar{y}
    should be an integer. If \mvar{y} is not an integer, the actual calculation
    will be an approximation of $e^{y \ln(x)}$.
    %
\begin{codeexample}[]
\pgfmathparse{pow(2,7)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{e}
\mathcommand
    Returns the value 2.718281828.
    %
{
\catcode`\^=7
\begin{codeexample}[]
\pgfmathparse{(e^2-e^-2)/2} \pgfmathresult
\end{codeexample}
}
\end{math-function}

\begin{math-function}{exp(\mvar{x})}
\mathcommand
{ \catcode`\^=7

    Maclaurin series for $e^x$.
}
\begin{codeexample}[]
\pgfmathparse{exp(1)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{exp(2.34)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{ln(\mvar{x})}
\mathcommand
{ \catcode`\^=7
    An approximation for $\ln(\textrm{\mvar{x}})$. This uses an algorithm of
    Rouben Rostamian, and coefficients suggested by Alain Matthes.
}
\begin{codeexample}[]
\pgfmathparse{ln(10)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{ln(exp(5))} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{log10(\mvar{x})}
\mathcommand[logten(\mvar{x})]
    An approximation for $\log_{10}(\textrm{\mvar{x}})$.
    %
\begin{codeexample}[]
\pgfmathparse{log10(100)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{log2(\mvar{x})}
\mathcommand[logtwo(\mvar{x})]
    An approximation for $\log_2(\textrm{\mvar{x}})$.
    %
\begin{codeexample}[]
\pgfmathparse{log2(128)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{abs(\mvar{x})}
\mathcommand
    Evaluates the absolute value of $x$.
    %
\begin{codeexample}[]
\pgfmathparse{abs(-5)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{-abs(4*-3)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{mod(\mvar{x},\mvar{y})}
\mathcommand
    This evaluates \mvar{x} modulo \mvar{y}, using truncated division. The sign
    of the result is the same as the sign of
    $\frac{\textrm{\mvar{x}}}{\textrm{\mvar{y}}}$.
    %
\begin{codeexample}[]
\pgfmathparse{mod(20,6)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{mod(-100,30)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{Mod(\mvar{x},\mvar{y})}
\mathcommand
    This evaluates \mvar{x} modulo \mvar{y}, using floored division. The sign
    of the result is never negative.
    %
\begin{codeexample}[]
\pgfmathparse{Mod(-100,30)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{sign(\mvar{x})}
\mathcommand
    Returns the sign of $x$.
    %
\begin{codeexample}[]
\pgfmathparse{sign(-5)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{sign(0)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{sign(5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\subsubsection{Rounding functions}
\label{pgfmath-functions-rounding}

\begin{math-function}{round(\mvar{x})}
\mathcommand
    Rounds \mvar{x} to the nearest integer. It uses ``asymmetric half-up''
    rounding. So |1.5| is rounded to |2|, but |-1.5| is rounded to |-2|
    (\emph{not} |-1|).
    %
\begin{codeexample}[]
\pgfmathparse{round(32.5/17)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{round(398/12)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{floor(\mvar{x})}
\mathcommand
    Rounds \mvar{x} down to the nearest integer.
    %
\begin{codeexample}[]
\pgfmathparse{floor(32.5/17)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{floor(398/12)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{floor(-398/12)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{ceil(\mvar{x})}
\mathcommand
    Rounds \mvar{x} up to the nearest integer.
    %
\begin{codeexample}[]
\pgfmathparse{ceil(32.5/17)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{ceil(398/12)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{ceil(-398/12)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{int(\mvar{x})}
\mathcommand
    Returns the integer part of \mvar{x}.
    %
\begin{codeexample}[]
\pgfmathparse{int(32.5/17)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{frac(\mvar{x})}
\mathcommand
    Returns the fractional part of \mvar{x}.
    %
\begin{codeexample}[]
\pgfmathparse{frac(32.5/17)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{real(\mvar{x})}
\mathcommand
    Ensures \mvar{x} contains a decimal point.
    %
\begin{codeexample}[]
\pgfmathparse{real(4)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\subsubsection{Integer arithmetics functions}
\label{pgfmath-functions-integerarithmetics}

\begin{math-function}{gcd(\mvar{x},\mvar{y})}
\mathcommand
    Computes the greatest common divider of \mvar{x} and \mvar{y}.
    %
\begin{codeexample}[]
\pgfmathparse{gcd(42,56)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{isodd(\mvar{x})}
\mathcommand
    Returns |1| if the integer part of \mvar{x} is odd. Otherwise, returns |0|.
    %
\begin{codeexample}[]
\pgfmathparse{isodd(2)} \pgfmathresult,
\pgfmathparse{isodd(3)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{iseven(\mvar{x})}
\mathcommand
    Returns |1| if the integer part of \mvar{x} is even. Otherwise, returns |0|.
    %
\begin{codeexample}[]
\pgfmathparse{iseven(2)} \pgfmathresult,
\pgfmathparse{iseven(3)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{isprime(\mvar{x})}
\mathcommand
    Returns |1| if the integer part of \mvar{x} is prime. Otherwise, returns |0|.
    %
\begin{codeexample}[]
\pgfmathparse{isprime(1)} \pgfmathresult,
\pgfmathparse{isprime(2)} \pgfmathresult,
\pgfmathparse{isprime(31)} \pgfmathresult,
\pgfmathparse{isprime(64)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\subsubsection{Trigonometric functions}
\label{pgfmath-functions-trigonometric}

\begin{math-function}{pi}
\mathcommand
    Returns the value $\pi=3.141592654$.
    %
\begin{codeexample}[]
\pgfmathparse{pi} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{pi r} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{rad(\mvar{x})}
\mathcommand
    Convert \mvar{x} to radians. \mvar{x} is assumed to be in degrees.
    %
\begin{codeexample}[]
\pgfmathparse{rad(90)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{deg(\mvar{x})}
\mathcommand
    Convert \mvar{x} to degrees. \mvar{x} is assumed to be in radians.
    %
\begin{codeexample}[]
\pgfmathparse{deg(3*pi/2)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{sin(\mvar{x})}
\mathcommand
    %
    Sine of \mvar{x}. By employing the |r| operator, \mvar{x} can be in
    radians.
    %
\begin{codeexample}[]
\pgfmathparse{sin(60)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{sin(pi/3 r)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{cos(\mvar{x})}
\mathcommand
    Cosine of \mvar{x}. By employing the |r| operator, \mvar{x} can be in
    radians.
    %
\begin{codeexample}[]
\pgfmathparse{cos(60)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{cos(pi/3 r)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{tan(\mvar{x})}
\mathcommand
    Tangent of \mvar{x}. By employing the |r| operator, \mvar{x} can be in
    radians.
    %
\begin{codeexample}[]
\pgfmathparse{tan(45)} \pgfmathresult
\end{codeexample}

\begin{codeexample}[]
\pgfmathparse{tan(2*pi/8 r)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{sec(\mvar{x})}
\mathcommand
    Secant of \mvar{x}. By employing the |r| operator, \mvar{x} can be in
    radians.
    %
\begin{codeexample}[]
\pgfmathparse{sec(45)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{cosec(\mvar{x})}
\mathcommand
    Cosecant of \mvar{x}. By employing the |r| operator, \mvar{x} can be in
    radians.
    %
\begin{codeexample}[]
\pgfmathparse{cosec(30)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{cot(\mvar{x})}
\mathcommand
    Cotangent of \mvar{x}. By employing the |r| operator, \mvar{x} can be in
    radians.
    %
\begin{codeexample}[]
\pgfmathparse{cot(15)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{asin(\mvar{x})}
\mathcommand
    Arcsine of \mvar{x}. The result is in degrees and in the range $\pm90^\circ$.
    %
\begin{codeexample}[]
\pgfmathparse{asin(0.7071)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{acos(\mvar{x})}
\mathcommand
    Arccosine of \mvar{x} in degrees. The result is in the range $[0^\circ,180^\circ]$.
    %
\begin{codeexample}[]
\pgfmathparse{acos(0.5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{atan(\mvar{x})}
\mathcommand
    Arctangent of $x$ in degrees.
    %
\begin{codeexample}[]
\pgfmathparse{atan(1)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{atan2(\mvar{y},\mvar{x})}
\mathcommand[atantwo(\mvar{y},\mvar{x})]
    Arctangent of $y\div x$ in degrees. This also takes into account the
    quadrants.
    %
\begin{codeexample}[]
\pgfmathparse{atan2(-4,3)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{key}{/pgf/trig format=\mchoice{deg,rad} (initially deg)}
    Allows to define whether trigonometric math functions (i.e.\ all in this
    subsection) operate with degrees or with radians.
    %
\begin{codeexample}[]
\pgfmathparse{cos(45)} \pgfmathresult
\end{codeexample}
\begin{codeexample}[]
\pgfkeys{/pgf/trig format=rad}
\pgfmathparse{cos(pi/2)} \pgfmathresult
\end{codeexample}

    The initial configuration |trig format=deg| is the base of \pgfname: almost
    all of it is based on degrees.

    Specifying |trig format=rad| is most useful for data visualization where
    the angles are typically given in radians. However, it is applied to all
    trigonometric functions for which the option applies, including any drawing
    instructions which operate on angles.
    %
\begin{codeexample}[]
\begin{tikzpicture}
    \draw[-stealth]
        (0:1) -- (45:1) -- (90:1) -- (135:1) -- (180:1);

    \draw[-stealth,trig format=rad,red]
        (pi:1) -- (5/4*pi:1) -- (6/4*pi:1) -- (7/4*pi:1) -- (2*pi:1);
\end{tikzpicture}
\end{codeexample}

    \paragraph{Warning:}
    At the time of this writing, this feature is ``experimental''. Please
    handle it with care: there may be path instructions or libraries in
    \pgfname\ which rely on |trig format=deg|. The intended usage of
    |trig format=rad| is for local scopes -- and as option for data
    visualization.
\end{key}

\subsubsection{Comparison and logical functions}
\label{pgfmath-functions-comparison}

\begin{math-function}{equal(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if $\mvar{x}=\mvar{y}$ and |0| otherwise.
    %
\begin{codeexample}[]
\pgfmathparse{equal(20,20)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{greater(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if $\mvar{x}>\mvar{y}$ and |0| otherwise.
    %
\begin{codeexample}[]
\pgfmathparse{greater(20,25)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{less(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if $\mvar{x}<\mvar{y}$ and |0| otherwise.
    %
\begin{codeexample}[]
\pgfmathparse{greater(20,25)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{notequal(\mvar{x},\mvar{y})}
\mathcommand
    This returns |0| if $\mvar{x}=\mvar{y}$ and |1| otherwise.
    %
\begin{codeexample}[]
\pgfmathparse{notequal(20,25)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{notgreater(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if $\mvar{x}\leq\mvar{y}$ and |0| otherwise.
    %
\begin{codeexample}[]
\pgfmathparse{notgreater(20,25)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{notless(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if $\mvar{x}\geq\mvar{y}$ and |0| otherwise.
    %
\begin{codeexample}[]
\pgfmathparse{notless(20,25)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{and(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if \mvar{x} and \mvar{y} both evaluate to non-zero values.
    Otherwise |0| is returned.
    %
\begin{codeexample}[]
\pgfmathparse{and(5>4,6>7)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{or(\mvar{x},\mvar{y})}
\mathcommand
    This returns |1| if either \mvar{x} or \mvar{y} evaluate to non-zero
    values. Otherwise |0| is returned.
    %
\begin{codeexample}[]
\pgfmathparse{or(5>4,6>7)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{not(\mvar{x})}
\mathcommand
    This returns |1| if $\mvar{x}=0$, otherwise |0|.
    %
\begin{codeexample}[]
\pgfmathparse{not(true)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{ifthenelse(\mvar{x},\mvar{y},\mvar{z})}
\mathcommand
    This returns \mvar{y} if \mvar{x} evaluates to some non-zero value,
    otherwise \mvar{z} is returned.
    %
\begin{codeexample}[]
\pgfmathparse{ifthenelse(5==4,"yes","no")} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{true}
\mathcommand
    This evaluates to |1|.
    %
\begin{codeexample}[]
\pgfmathparse{true ? "yes" : "no"} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{false}
\mathcommand
    This evaluates to |0|.
    %
\begin{codeexample}[]
\pgfmathparse{false ? "yes" : "no"} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\subsubsection{Pseudo-random functions}
\label{pgfmath-functions-random}

\begin{math-function}{rnd}
\mathcommand
    Generates a pseudo-random number between $0$ and $1$ with a uniform
    distribution.
    %
\begin{codeexample}[pre={\pgfmathsetseed{1}}]
\foreach \x in {1,...,10}{\pgfmathparse{rnd}\pgfmathresult, }
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{rand}
\mathcommand
    Generates a pseudo-random number between $-1$ and $1$ with a uniform
    distribution.
    %
\begin{codeexample}[pre={\pgfmathsetseed{1}}]
\foreach \x in {1,...,10}{\pgfmathparse{rand}\pgfmathresult, }
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{random(\opt{\mvar{x},\mvar{y}})}
\mathcommand
    This function takes zero, one or two arguments. If there are zero
    arguments, a uniform random number between $0$ and $1$ is generated. If
    there is one argument \mvar{x}, a random integer between $1$ and \mvar{x}
    is generated. Finally, if there are two arguments, a random integer between
    \mvar{x} and \mvar{y} is generated. If there are no arguments, the
    \pgfname{} command should be called as follows: |\pgfmathrandom{}|.
    %
\begin{codeexample}[pre={\pgfmathsetseed{1}}]
\foreach \x in {1,...,10}{\pgfmathparse{random()}\pgfmathresult, }
\end{codeexample}

\begin{codeexample}[pre={\pgfmathsetseed{1}}]
\foreach \x in {1,...,10}{\pgfmathparse{random(100)}\pgfmathresult, }
\end{codeexample}

\begin{codeexample}[pre={\pgfmathsetseed{1}}]
\foreach \x in {1,...,10}{\pgfmathparse{random(232,762)}\pgfmathresult, }
\end{codeexample}
    %
\end{math-function}

\subsubsection{Base conversion functions}
\label{pgfmath-functions-base}

\begin{math-function}{hex(\mvar{x})}
\mathcommand
    Convert \mvar{x}{} (assumed to be an integer in base 10) to a hexadecimal
    representation, using lower case alphabetic digits. No further calculation
    will be possible with the result.
    %
\begin{codeexample}[]
\pgfmathparse{hex(65535)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{Hex(\mvar{x})}
\mathcommand
    Convert \mvar{x}{} (assumed to be an integer in base 10) to a hexadecimal
    representation, using upper case alphabetic digits. No further calculation
    will be possible with the result.
    %
\begin{codeexample}[]
\pgfmathparse{Hex(65535)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{oct(\mvar{x})}
\mathcommand
    Convert \mvar{x}{} (assumed to be an integer in base 10) to an octal
    representation. No further calculation should be attempted with the result,
    as the parser can only process numbers converted to base 10.
    %
\begin{codeexample}[]
\pgfmathparse{oct(63)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{bin(\mvar{x})}
\mathcommand
    Convert \mvar{x}{} (assumed to be an integer in base 10) to a binary
    representation. No further calculation should be attempted with the result,
    as the parser can only process numbers converted to base 10.
    %
\begin{codeexample}[]
\pgfmathparse{bin(185)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\subsubsection{Miscellaneous functions}
\label{pgfmath-functions-misc}

\begin{math-function}{min(\mvar{x$_1$},\mvar{x$_2$},\ldots,\mvar{x$_n$})}
\mathcommand[min({\mvar{x$_1$},\mvar{x$_2$},\ldots},{\ldots,\mvar{x$_{n-1}$},\mvar{x$_n$}})]
    Return the minimum value from \mvar{x$_1$}\ldots\mvar{x$_n$}. For
    historical reasons, the command |\pgfmathmin| takes two arguments, but each
    of these can contain an arbitrary number of comma separated values.
    %
\begin{codeexample}[]
\pgfmathparse{min(3,4,-2,250,-8,100)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{max(\mvar{x$_1$},\mvar{x$_2$},\ldots,\mvar{x$_n$})}
\mathcommand[max({\mvar{x$_1$},\mvar{x$_2$},\ldots},{\ldots,\mvar{x$_{n-1}$},\mvar{x$_n$}})]
    Return the maximum value from \mvar{x$_1$}\ldots\mvar{x$_n$}. Again, for
    historical reasons, the command |\pgfmathmax| takes two arguments, but each
    of these can contain an arbitrary number of comma separated values.
    %
\begin{codeexample}[]
\pgfmathparse{max(3,4,-2,250,-8,100)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{veclen(\mvar{x},\mvar{y})}
\mathcommand
    Calculates $\sqrt{\left(\textrm{\mvar{x}}^2+\textrm{\mvar{y}}^2\right)}$.
    This uses a polynomial approximation, based on ideas of Rouben Rostamian
    %
\begin{codeexample}[]
\pgfmathparse{veclen(12,5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{array(\mvar{x},\mvar{y})}
\mathcommand
    This accesses the array \mvar{x} at the index \mvar{y}. The array must
    begin and end with braces (e.g., |{1,2,3,4}|) and array indexing starts at
    |0|.
    %
\begin{codeexample}[]
\pgfmathparse{array({9,13,17,21},2)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

The following hyperbolic functions were adapted from code suggested by Martin
Heller:

\begin{math-function}{sinh(\mvar{x})}
\mathcommand
    The hyperbolic sine of \mvar{x}
    %
\begin{codeexample}[]
\pgfmathparse{sinh(0.5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{cosh(\mvar{x})}
\mathcommand
    The hyperbolic cosine of \mvar{x}
    %
\begin{codeexample}[]
\pgfmathparse{cosh(0.5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{tanh(\mvar{x})}
\mathcommand
    The hyperbolic tangent of \mvar{x}
    %

\begin{codeexample}[]
\pgfmathparse{tanh(0.5)} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{width("\mvar{x}")}
\mathcommand
    Return the width of a \TeX{} (horizontal) box containing \mvar{x}. The
    quote characters are necessary to prevent \mvar{x}{} from being parsed. It
    is important to remember that any expression is expanded with |\edef|
    before being parsed, so any macros (e.g., font commands like |\tt| or
    |\Huge|) will need to be ``protected'' (e.g., |\noexpand\Huge| is usually
    sufficient).
    %
\begin{codeexample}[]
\pgfmathparse{width("Some Lovely Text")} \pgfmathresult
\end{codeexample}

    Note that results of this method are provided in points.
\end{math-function}

\begin{math-function}{height("\mvar{x}")}
\mathcommand
    Return the height of a box containing \mvar{x}.
    %
\begin{codeexample}[]
\pgfmathparse{height("Some Lovely Text")} \pgfmathresult
\end{codeexample}
    %
\end{math-function}

\begin{math-function}{depth("\mvar{x}")}
\mathcommand
    Returns the depth of a box containing \mvar{x}.
    %
\begin{codeexample}[]
\pgfmathparse{depth("Some Lovely Text")} \pgfmathresult
\end{codeexample}
    %
\end{math-function}


\section{Conclusions}
The goal of this article is to review the knowledge that I
had learnt during the winter holiday and pave the way for
further study in the future. First we formulated the framework
of neural networks, introduced the basic component in network
and the gradient descent optimization together with the computation
method: backward propagation. Then we summarized the dominating
problems, especially the vanishing/explosion and the saddle points,
in training a neural network and provided a few tricks
including LSUV initialization and Adam optimization that
help boost the training efficiency. Finally, we went through
the main three questions about the mechanism of neural networks
and obtained some straight-forward intuition like the landscape
comprised of flat basins.
\par There are several potential work to be done in the
future. The tensorflow and keras framework can be used to
compare the performance of various tricks and empirically
test the results given in \autoref{sec:Question}. Besides,
due to lack of mathematic knowledge, the majority work in
the generalization is beyond my comprehension. With further
study of the basic convex optimization, a good command of
mathematic terminology and definition may help me have more
insight into the essence of neural networks generalization.


\documentclass[a4paper]{report}
\usepackage[english]{babel}
\usepackage[utf8x]{inputenc}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage[sc]{mathpazo} % Use the Palatino font
\usepackage{microtype} % Slightly tweak font spacing for aesthetics
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{longtable}
\usepackage{tkz-graph}
\usepackage{tabularx}

\title{CommunityAlg reference manual\\Version 0.1}
\author{Carlo Nicolini}
\date{\today}

\begin{document}
\maketitle

\section*{Functions list}\label{matlaboctave-algorithms-and-functions}

  \subsection*{ami.m} Returns the adjusted mutual information between two
  membership vectors.

  \subsection*{association\_score.m} Returns the association score between
  pairs of communities specified by the graph and membership.

  \subsection*{asymptotic\_modularity.m} Compute asymptotic modularity of a
  graph with respect to a membership vector.

  \subsection*{asymptotic\_modularity\_sum.m} TODO

  \subsection*{asymptotic\_surprise.m} Compute asymptotic surprise of a graph
  with respect to a membership vector.

  \subsection*{clique.m} Generate an adjacency matrix of a clique graph with
  \texttt{n} nodes.

  \subsection*{cluster\_similarity.m} Compare two membership vectors.

  \subsection*{clustering\_entropy.m} Compute the clustering entropy of an
  agreement matrix as in ``Gfeller, Newman, 2006''.

  \subsection*{community\_robustness\_weighted.m} TODO

  \subsection*{community\_size2memb.m} Convert an array where every element
  is the size of a clique to the correspondig membership vector.

  \subsection*{comm\_mat.m} Returns the block matrix of a graph and its
  community structure as membership.

  \subsection*{compute\_surprise.m} Compute the surprise given surprise
  paramenters.

  \subsection*{consensus\_clustering.m} TODO

  \subsection*{consensus\_clustering\_weighted.m} TODO

  \subsection*{consensus\_entropy.m} TODO

  \subsection*{consensus\_robustness.m} TODO

  \subsection*{correlation\_louvain.m} Adaptation of the BCT
  \texttt{community\_louvain} method for correlation matrices, as
  described in MacMahon,2015.

  \subsection*{count\_comm.m} Plot the histogram with the community size
  given a membership vector.

  \subsection*{cycle\_graph.m} Generate the adjacency matrix of a cycle graph
  with n nodes.

  \subsection*{effcommplot.m} TODO

  \subsection*{generate\_agreement.m} Generate the agreement matrix for a
  given community detection method.

  \subsection*{generate\_agreement\_weighted.m} Generate the weighted
  agreement matrix for a given community detection method.

  \subsection*{generate\_connected\_components.m} TODO

  \subsection*{graph\_JS\_similarity.m} Compute the quantum Jensen Shannon
  divergence between two adjacency matrices.

  \subsection*{graph\_laplacian.m} Compute the graph combinatorial Laplacian
  matrix \texttt{L=D-A}.

  \subsection*{group2membership.m} Convert a cell of arrays representing the
  nodes in the communities to a membership vector.

  \subsection*{image\_to\_network.m} Convert a gray index image to its
  corresponding adjacency graph.

  \subsection*{imagesctxt.m} Show a matrix like \texttt{imagesc} but with
  text values of elements displayed on the pixels.

  \subsection*{isoctave.m} Returns true if using Octave, false if using
  Matlab.

  \subsection*{jensen\_shannon\_sim.m} Returns the Jensen-Shannon symmetrized
  information theoretic distance between two graph Laplacians.

  \subsection*{k\_regular.m} Generate a \texttt{k}-regular graph, a graph
  where the degree of every vertex is \texttt{k}.

  \subsection*{KL.m} Returns the binary Kullback-Leibler divergence between
  Bernoulli distribution \texttt{p} and \texttt{q}.

  \subsection*{kullback\_leibler\_sim.m} Returns the Kullback-Leibler
  divergence between two graph Laplacians.

  \subsection*{logHyperProbability.m} Compute the logarithm of the
  hypergeometric probability in base 10.

  \subsection*{membership2groups.m} Convert a membership vector to a cell of
  arrays of nodes in every community.

  \subsection*{membership\_agreement.m} DEPRECATE

  \subsection*{membership\_similarity.m} TODO

  \subsection*{method\_best.m} Functio handle to the community detection
  method that returns the best value over a set of repetitions.

  \subsection*{modularity.m} Returns the modularity of a graph with respect
  to a membership vector.

  \subsection*{nearcorr.m} Returns the nearest correlation matrix of a square
  matrix. Implementation by Nick Higham.

  \subsection*{nearestSPD.m} Returns the positive definite matrix of a square
  matrix. Implementation by Nick Higham.

  \subsection*{norm\_conf\_mat.m} DEPRECATE

  \subsection*{number\_connected\_components.m} Returns the number of
  connected components of a graph.

  \subsection*{number\_of\_edges.m} Returns the number of edges of a binary
  or weighted graph.

  \subsection*{paco.m} Function handle to the MEX implementation of PACO.

  \subsection*{partition\_params.m} Returns the partition parameters for use
  with \texttt{compute\_surprise}.

  \subsection*{quantum\_density.m} Returns the quantum density of a graph,
  \texttt{Brauenstein\ et\ al.} ``Ann. of Combinatorics, 10, no 3
  (2006), 291-317.''

  \subsection*{reindex\_membership.m} Transform a membership vector to have
  community indices sorted by community size from \texttt{1} to
  \texttt{\textbar{}C\textbar{}}

  \subsection*{reorder\_membership.m} Linearize a membership vector to have
  continuous indices of communities from \texttt{1} to
  \texttt{\textbar{}C\textbar{}}

  \subsection*{ring\_of\_cliques.m} Returns a network ring of cliques, with
  given number of cliques and clique size and its membership.

  \subsection*{ring\_of\_custom\_cliques.m} Returns a network ring of
  cliques, with given size of cliques specified as input and its
  membership.

  \subsection*{rmtdecompose.m} Returns the Random Matrix Theory decomposition
  of a correlation matrix.

  \subsection*{robustness\_configuration\_interp\_und.m}

  \subsection*{robustness\_edge\_weight\_und.m}

  \subsection*{run\_cluster\_similarity.m}

  \subsection*{rwalkent.m} Returns the random walk entropy of a graph as in
  \texttt{Estrada\ et\ al.} Walk entropies in graphs, ``Linear Algebra
  and its Applications 443 (2014) 235--244''

  \subsection*{significance.m} Returns the significance of a graph
  partitioning, \texttt{Traag\ (2013)}.

  \subsection*{smi.m} Returns the standardized mutual information of two
  membership vectors.

  \subsection*{sort\_group\_by\_size.m} Sort community groups by size.

  \subsection*{star\_of\_custom\_cliques.m} Returns a star of cliques, every
  clique is connected to all other cliques with one edge.

  \subsection*{surprise.m} Returns the surprise of a graph partitioning.

  \subsection*{threshold\_by\_giant\_component.m} Returns the threshold over
  which the graph has more than one connected component.

  \subsection*{threshold\_by\_num\_edges.m} Returns a graph thresholded to
  have a specific number of edges.

  \subsection*{vonneumann\_entropy.m} Returns the VonNeumann quantum entropy
  of graph \texttt{Brauenstein\ et\ al.} ``Ann. of Combinatorics, 10, no
  3 (2006), 291-317.''

  \subsection*{write\_brainet.m} Write a graph with coordinates of nodes and
  membership to Brainet format.

  \subsection*{write\_brainet\_community.m} TODO

  \subsection*{writetoEdgesList.m} TODO

  \subsection*{writetoPAJ\_labels.m}

  \subsection*{writetoPAJ\_labels\_coords.m}

% \item
%   \textbf{asymptotic\_modularity.m} Compute asymptotic modularity of a
%   graph with respect to a membership vector.
% \item
%   \textbf{asymptotic\_modularity\_sum.m} TODO
% \item
%   \textbf{asymptotic\_surprise.m} Compute asymptotic surprise of a graph
%   with respect to a membership vector.
% \item
%   \textbf{clique.m} Generate an adjacency matrix of a clique graph with
%   \texttt{n} nodes.
% \item
%   \textbf{cluster\_similarity.m} Compare two membership vectors.
% \item
%   \textbf{clustering\_entropy.m} Compute the clustering entropy of an
%   agreement matrix as in ``Gfeller, Newman, 2006''.
% \item
%   \textbf{community\_robustness\_weighted.m} TODO
% \item
%   \textbf{community\_size2memb.m} Convert an array where every element
%   is the size of a clique to the correspondig membership vector.
% \item
%   \textbf{comm\_mat.m} Returns the block matrix of a graph and its
%   community structure as membership.
% \item
%   \textbf{compute\_surprise.m} Compute the surprise given surprise
%   paramenters.
% \item
%   \textbf{consensus\_clustering.m} TODO
% \item
%   \textbf{consensus\_clustering\_weighted.m} TODO
% \item
%   \textbf{consensus\_entropy.m} TODO
% \item
%   \textbf{consensus\_robustness.m} TODO
% \item
%   \textbf{correlation\_louvain.m} Adaptation of the BCT
%   \texttt{community\_louvain} method for correlation matrices, as
%   described in MacMahon,2015.
% \item
%   \textbf{count\_comm.m} Plot the histogram with the community size
%   given a membership vector.
% \item
%   \textbf{cycle\_graph.m} Generate the adjacency matrix of a cycle graph
%   with n nodes.
% \item
%   \textbf{effcommplot.m} TODO
% \item
%   \textbf{generate\_agreement.m} Generate the agreement matrix for a
%   given community detection method.
% \item
%   \textbf{generate\_agreement\_weighted.m} Generate the weighted
%   agreement matrix for a given community detection method.
% \item
%   \textbf{generate\_connected\_components.m} TODO
% \item
%   \textbf{graph\_JS\_similarity.m} Compute the quantum Jensen Shannon
%   divergence between two adjacency matrices.
% \item
%   \textbf{graph\_laplacian.m} Compute the graph combinatorial Laplacian
%   matrix \texttt{L=D-A}.
% \item
%   \textbf{group2membership.m} Convert a cell of arrays representing the
%   nodes in the communities to a membership vector.
% \item
%   \textbf{image\_to\_network.m} Convert a gray index image to its
%   corresponding adjacency graph.
% \item
%   \textbf{imagesctxt.m} Show a matrix like \texttt{imagesc} but with
%   text values of elements displayed on the pixels.
% \item
%   \textbf{isoctave.m} Returns true if using Octave, false if using
%   Matlab.
% \item
%   \textbf{jensen\_shannon\_sim.m} Returns the Jensen-Shannon symmetrized
%   information theoretic distance between two graph Laplacians.
% \item
%   \textbf{k\_regular.m} Generate a \texttt{k}-regular graph, a graph
%   where the degree of every vertex is \texttt{k}.
% \item
%   \textbf{KL.m} Returns the binary Kullback-Leibler divergence between
%   Bernoulli distribution \texttt{p} and \texttt{q}.
% \item
%   \textbf{kullback\_leibler\_sim.m} Returns the Kullback-Leibler
%   divergence between two graph Laplacians.
% \item
%   \textbf{logHyperProbability.m} Compute the logarithm of the
%   hypergeometric probability in base 10.
% \item
%   \textbf{membership2groups.m} Convert a membership vector to a cell of
%   arrays of nodes in every community.
% \item
%   \textbf{membership\_agreement.m} DEPRECATE
% \item
%   \textbf{membership\_similarity.m} TODO
% \item
%   \textbf{method\_best.m} Functio handle to the community detection
%   method that returns the best value over a set of repetitions.
% \item
%   \textbf{modularity.m} Returns the modularity of a graph with respect
%   to a membership vector.
% \item
%   \textbf{nearcorr.m} Returns the nearest correlation matrix of a square
%   matrix. Implementation by Nick Higham.
% \item
%   \textbf{nearestSPD.m} Returns the positive definite matrix of a square
%   matrix. Implementation by Nick Higham.
% \item
%   \textbf{norm\_conf\_mat.m} DEPRECATE
% \item
%   \textbf{number\_connected\_components.m} Returns the number of
%   connected components of a graph.
% \item
%   \textbf{number\_of\_edges.m} Returns the number of edges of a binary
%   or weighted graph.
% \item
%   \textbf{paco.m} Function handle to the MEX implementation of PACO.
% \item
%   \textbf{partition\_params.m} Returns the partition parameters for use
%   with \texttt{compute\_surprise}.
% \item
%   \textbf{quantum\_density.m} Returns the quantum density of a graph,
%   \texttt{Brauenstein\ et\ al.} ``Ann. of Combinatorics, 10, no 3
%   (2006), 291-317.''
% \item
%   \textbf{reindex\_membership.m} Transform a membership vector to have
%   community indices sorted by community size from \texttt{1} to
%   \texttt{\textbar{}C\textbar{}}
% \item
%   \textbf{reorder\_membership.m} Linearize a membership vector to have
%   continuous indices of communities from \texttt{1} to
%   \texttt{\textbar{}C\textbar{}}
% \item
%   \textbf{ring\_of\_cliques.m} Returns a network ring of cliques, with
%   given number of cliques and clique size and its membership.
% \item
%   \textbf{ring\_of\_custom\_cliques.m} Returns a network ring of
%   cliques, with given size of cliques specified as input and its
%   membership.
% \item
%   \textbf{rmtdecompose.m} Returns the Random Matrix Theory decomposition
%   of a correlation matrix.
% \item
%   \textbf{robustness\_configuration\_interp\_und.m}
% \item
%   \textbf{robustness\_edge\_weight\_und.m}
% \item
%   \textbf{run\_cluster\_similarity.m}
% \item
%   \textbf{rwalkent.m} Returns the random walk entropy of a graph as in
%   \texttt{Estrada\ et\ al.} Walk entropies in graphs, ``Linear Algebra
%   and its Applications 443 (2014) 235--244''
% \item
%   \textbf{significance.m} Returns the significance of a graph
%   partitioning, \texttt{Traag\ (2013)}.
% \item
%   \textbf{smi.m} Returns the standardized mutual information of two
%   membership vectors.
% \item
%   \textbf{sort\_group\_by\_size.m} Sort community groups by size.
% \item
%   \textbf{star\_of\_custom\_cliques.m} Returns a star of cliques, every
%   clique is connected to all other cliques with one edge.
% \item
%   \textbf{surprise.m} Returns the surprise of a graph partitioning.
% \item
%   \textbf{threshold\_by\_giant\_component.m} Returns the threshold over
%   which the graph has more than one connected component.
% \item
%   \textbf{threshold\_by\_num\_edges.m} Returns a graph thresholded to
%   have a specific number of edges.
% \item
%   \textbf{vonneumann\_entropy.m} Returns the VonNeumann quantum entropy
%   of graph \texttt{Brauenstein\ et\ al.} ``Ann. of Combinatorics, 10, no
%   3 (2006), 291-317.''
% \item
%   \textbf{write\_brainet.m} Write a graph with coordinates of nodes and
%   membership to Brainet format.
% \item
%   \textbf{write\_brainet\_community.m} TODO
% \item
%   \textbf{writetoEdgesList.m} TODO
% \item
%   \textbf{writetoPAJ\_labels.m}
% \item
%   \textbf{writetoPAJ\_labels\_coords.m}
% \end{itemize}

% \section{Python algorithms}\label{python-algorithms}

% \begin{itemize}[<+->]
% \item
%   \textbf{find\_intersections.py} Find the intersections of edges in a
%   bipartite graph (TODO)
% \end{itemize}

% \section{Datasets}\label{datasets}

% This repository contains the 638 areas template used by Crossley (2013).
% It consists of two files:

% \begin{enumerate}[<+->]
% \item
%   \texttt{template.nii} is the NIFTI file describing the template, MNI
%   space
% \item
%   \texttt{template\_638.txt} is the description of anatomical a
% \end{enumerate}

% Additionally the file \texttt{template\_638\_coords\_abbr.txt} is
% organized as follows

% \begin{longtable}[]{@{}llllll@{}}
% \toprule
% Node & X & Y & Z & Label & Abbr\tabularnewline
% \midrule
% \endhead
% \bottomrule
% \end{longtable}

% and differently from \texttt{template\_638.txt} the NodeID starts from 0
% to 637 (for indexing with Python).

\end{document}