\begin{chapter}{\LaTeX}

Producing high quality mathematical documents that show equations, figures and references clearly is very difficult in standard word processing packages. Instead the standard is to use \LaTeX, a ``document prepartion language''. Most notes, such as these, and mathematical papers, use \LaTeX.

\section{What is \LaTeX}

\LaTeX\ takes a plain text file and converts it into a document, often in PDF format, containing all the equations, figures and cross-references. In this sense it's similar to Python: you start from a plain text file and \emph{build} it to produce a result.

\LaTeX\ documents are often complex, but many are available online. A standard technique is to find a \LaTeX document that does what you want online, and take the key commands from that.

\section{Installing or finding}
\label{sec:installing}

\LaTeX\ is free software and there's lots of available implementations. As with Python, a \LaTeX\ document is plain text and can be written using any text editor. However, specific \LaTeX\ editors can help in rapidly writing documents with fewer errors.

\subsection{University machines}

Use the search function to look for \texttt{TeXnicCentre}. When first running, choose all the default options. Some of the instructions below on building a document are specific to TeXnicCentre, as it's provided on the university machines, but similar methods should work in all editors.

\subsection{Personal machines}

If using a Linux or Mac, \LaTeX\ should be installed automatically. There are many editors you can use -- \href{http://www.xm1math.net/texmaker/}{TeXMaker} is one example -- and you can experiment with which you prefer. If using a Windows machine, you can freely download \href{http://www.texniccenter.org/}{TeXnicCentre} which will install \LaTeX\ for you, or use TeXMaker as above.

\subsection{Online}

There are browser-based \LaTeX\ editors which can be used, such as \href{https://www.overleaf.com/}{Overleaf} and \href{https://www.sharelatex.com/}{ShareLaTeX}. There are obvious advantages -- there's no need to install anything, it's backed up externally, and it builds the document for you. The balancing disadvantages are also there -- needs a network connection, the online editor isn't as full featured as special desktop versions, and keeping your work private requires paying.

Overleaf also \href{https://www.overleaf.com/latex/learn/free-online-introduction-to-latex-part-1}{hosts an online tutorial on \LaTeX} that works through the essential points.

\subsection{\LaTeX\ in other formats}

A full \LaTeX\ document can be very complex as it controls \emph{every} aspect of the document appearance. Many simpler document formats have been written, often based around \href{http://daringfireball.net/projects/markdown/}{Markdown} (see also \href{https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet}{this cheatsheet}). To typeset mathematics within these document formats, \LaTeX\ \emph{syntax} is used: one particular example is \href{https://www.authorea.com}{Authorea} where a simple Markdown-based document format can be mixed with \LaTeX\ syntax to create documents both for online and offline use. We have already seen how \LaTeX\ syntax can be used within, e.g., \texttt{matplotlib}.

\section{Getting Started}

\subsection{A basic document}

Download a simple \LaTeX\ document \href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatex.tex}{from this link}. Open it in whichever editor you are using, and build it so you can see the output (which should look like \href{https://github.com/IanHawke/maths-with-python/raw/master/latex/BasicLatex.pdf}{this pdf file}). If using TeXnicCentre on the University machines, you should be able to do this by running ``Build and View'' from the ``Build'' menu.

You should compare the document with the built PDF file. In particular note, as stated in the document,
%
\begin{itemize}
  \item that anything before the ``\verb|\begin{document}|'' (the \emph{preamble}) doesn't show explicitly, but changes global properties of the document,
  \item how whitespace works,
  \item how anything ``special'' starts ``\verb|\|'',
  \item how quote characters behave (compare with ''this''),
  \item how curly braces \verb|{| and \verb|}| are used without
    appearing,
  \item how \emph{environments} always \verb|\begin| and
      \verb|\end|,
  \item and how the \verb|\section| command works.
\end{itemize}
%
You should edit and re-build the document so that you can see the effects of adding standard text, new sections (or subsections), and so on.

\subsection{Mathematics and references}

Now download \emph{both} \href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex.tex}{this \LaTeX\ document} and \href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/nummeth.bib}{this bibliography file}. The bibliography file must be saved in the same directory as the \LaTeX\ document, must have a \texttt{.bib} extension, and (in this case) should be called \texttt{nummeth.bib}. Again, build this document and view the results.

\subsubsection{The build process}

Some editors will (or will let you) build the document one step at a time. In this case you may have perform multiple build steps. For example, the first build step will produce a document that \href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex_pass1.pdf}{looks like this}. At this point none of the cross-references are correct, but appear as ``\textbf{?}'', and there is no bibliography. The second build step will create the bibliography, but will not change the document. The third build step will produce a document that \href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex_pass2.pdf}{looks like this}. At this point cross-references to sections and equations are correct, and the bibliography is included. However, the cross-references to the bibliography are not correct. A fourth build step will produce a document that \href{https://raw.githubusercontent.com/IanHawke/maths-with-python/master/latex/BasicLatexBibtex_pass3.pdf}{looks like this}, with all references correct.

\subsubsection{Mathematics}

To include mathematical notation inline, commands should be placed between dollar signs, \verb|$...$|, so that \verb|$\pi$| gives $\pi$. To create a \emph{displayed} equation, use the \texttt{equation} environment, as in
%
\begin{verbatim}
\begin{equation}
  \label{eq:label_example}
  x = y + z.
\end{equation}
\end{verbatim}
%
which gives
%
\begin{equation}
  \label{eq:label_example}
  x = y + z.
\end{equation}
%
Note that the ``\verb|\label{...}|'' command allows the equation to be cross-referenced using the ``\verb|\ref{...}|'' command, giving equation \ref{eq:label_example}.

As seen above, Greek characters in mathematics are the letter preceded by the backslash, so \verb|$\theta$| gives $\theta$. To produce subscripts, use the underscore \verb|_|, and for superscripts the caret \verb|^|. So \verb|$x_1^2$| gives $x_1^2$. To group characters together, use the curly braces \verb|{}|. You need to do this, for example, if you want more than one character to appear in sub- or superscripts. Hence \verb|$F_n-2$| gives $F_n-2$, but \verb|$F_{n-2}$| gives $F_{n-2}$.

Standard mathematical commands and symbols are also preceded by backslashes, such as \verb|$\int$| ($\int$), \verb|$\sum$| ($\sum$), and \verb|$\infty$| ($\infty$). A more complete list \href{https://en.wikibooks.org/wiki/LaTeX/Mathematics}{can be found online}, and for more obscure symbols the online \href{http://detexify.kirelabs.org/classify.html}{handwriting recognition trick} is very useful.

\subsection{Cross-referencing and bibliographies}

We saw above how the \texttt{equation} environment could include a \verb|\label| which allowed it to be cross-referenced using the \verb|\ref| command. This can be done for any environment which takes a number; for example, the section on installing \LaTeX\ above has the label \verb|\label{sec:installing}|, and can be cross-referenced using \verb|\ref{sec:installing}|, giving section~\ref{sec:installing}.

For citing references -- books, papers, websites etc.\ -- we instead use the \verb|\cite| command. This looks for the article within the \emph{Bibtex} file that has the specific \emph{key}. In the document here, the command \verb|\cite{godunov}| tells \LaTeX\ that the key is ``\verb|godunov|'', and the command \verb|\bibliography{nummeth}| tells it that the Bibtex file is in \texttt{nummeth.bib}.

The structure of the Bibtex file can look complex. There are many shortcuts -- for example, by searching for the reference on Google Scholar, and then clicking on the ``Cite'' link, it will give the Bibtex entry that you can simply copy and paste into your file. For alternatives, see section~\ref{sec:Citations}.

\LaTeX\ is most useful for creating long documents (journal articles, theses, etc.) containing substantial mathematics. Sectioning, cross-referencing and bibliographies we have already seen. There are a number of additional features to make the creation of long documents easier.

These are gathered in a logical order below, but for most purposes the discussion of commands (section~\ref{sec:commands}), provided packages (section~\ref{sec:packages_provided}), and modularity (section~\ref{sec:modularity}) will be of most use.

\section{Commands}
\label{sec:commands}

\subsection{Defining commands}
\label{sec:commands_defn}

Firstly, user-defined commands can replace long sequences with a short, or more memorable, version. For example, a simple partial derivative
%
\begin{equation}
  \label{eq:example_pd_1}
  \frac{\partial y}{\partial x}
\end{equation}
%
can be written \verb|\frac{\partial y}{\partial x}|. The equivalent shorthand
%
\begin{equation}
  \label{eq:example_pd_2}
  \pda{y}{x}
\end{equation}
%
can be written, for example, \verb|\pda{y}{x}|. This is both clearer and shorter.

The command \verb|\pda| is defined in the \emph{document preamble}: after the \verb|\documentclass| command but before the \verb|\begin{document}| statement. The definition used here is
%
\begin{center}
  \verb|\newcommand{\pda}[2]{\frac{\partial {#1}}{\partial {#2}}}|
\end{center}
%
which requires some explanation:
\begin{itemize}
\item Obviously \verb|\newcommand{\pda}| defines the new command
  \verb|\pda|.
\item The statement \verb|[2]| says that the command has two arguments
  (in the example \verb|\pda{y}{x}| the arguments are \verb|y| and
  \verb|x| respectively). For commands that take no arguments (e.g.\
  where you are just defining a shorthand, such as the command
  \verb|\uos| defined at the start of this document which expands to
  \uos) this part is absent.
\item The rest of the line defines the command, and is enclosed in
  braces \verb|{...}| for safety. The arguments are referred to by the
  \verb|#| statements; e.g., in the example above \verb|#1|
  corresponds to \verb|y| and \verb|#2| to \verb|x|. Again, the
  arguments are typically enclosed in braces \verb|{...}| for safety.
\end{itemize}

\subsection{Redefining commands}
\label{sec:commands_redefn}

Sometimes a command already exists with the shorthand name that you want to use, but does not do what you expect or want. In this case it can be redefined using the command \verb|\renewcommand|. This works in exactly the same way as \verb|\newcommand|, except the command must already exist (note that if the command already exists then trying to (re)define it with \verb|\newcommand| will give an error).

The classic example is typesetting vectors using the \LaTeX\ command \verb|\vec|. By default this puts an arrow above the argument, similar to (but smaller than) the command \verb|\overrightarrow| which produces, e.g., $\overrightarrow{AB}$. Many people typeset vectors use bold fonts, which can be done using e.g.\
%
\begin{center}
  \verb|\renewcommand{\vec}[1]{\mathbf{#1}}|
\end{center}
%
which produces the output $\vec{a}$.

\section{Environments}
\label{sec:environments}

As we have seen, commands are not the only things that \LaTeX\ provides. It also provides \emph{environments} which are enclosed within \verb|\begin{...}| and \verb|\end{...}| statements. Standard environments are \verb|equation| and \verb|document|.

Just as with commands it is possible to define new environments (using the \verb|\newenvironment| command in the document preamble) or redefine old ones (using the \verb|\renewenvironment| command). The usage is similar to that of \verb|\newcommand| as well: the main difference is that instead of defining what the command does, you define what should happen before entering and after exiting the environment.

A simple example is
%
\begin{verbatim}
\newenvironment{solution}[1]{%
  \begin{center}
    \rule{#1}{.1pt}
  \end{center}
}{%
  \begin{center}
    \rule{0.9\textwidth}{.1pt}
  \end{center}
}
\end{verbatim}
%
which defines a \verb|solution| environment.

The explanation of each piece is as follows:
\begin{itemize}
\item \verb|\newenvironment{solution}|: the definition of the name of the new environment.
\item \verb|[1]|: the number of arguments pass in (here 1).
\item \verb|{\begin{center} \rule{#1}{.1pt} \end{center} }|: in the definition these are spaced using carriage returns and comment markers for clarity, but by matching the curly braces this can be seen to be just one argument. These are the commands issued before entering the environment. \verb|#1| is the first argument passed in.
\item \verb|{\begin{center} \rule{\rule{0.9\textwidth}{.1pt} \end{center} }|: again this was spaced for clarity in the definition. These are the commands issued after exiting the environment. No arguments can be used at this point.
\end{itemize}

This environment, used as
%
\begin{verbatim}
\begin{solution}{0.9\textwidth}
  This is the solution.
\end{solution}
\end{verbatim}
%
produces the output
%
\begin{solution}{0.9\textwidth}
  This is the solution.
\end{solution}
%

\section{Packages}
\label{sec:packages}

In essence a package is just a file containing a number of useful commands and environments, as explained in sections~\ref{sec:commands} and \ref{sec:environments}. So, rather than hand-defining a large number of commands you can import them all by including code such as
%
\begin{verbatim}
\usepackage{amsmath}
\end{verbatim}
%
in the document preamble.

This is particularly important when producing journal articles. Many journals require (or strongly encourange) you to submit articles fitting in with their in-house style. Many scientific journals will therefore provide a \LaTeX\ package to use in the production of your article.

\subsection{Useful packages}
\label{sec:packages_provided}

Most \LaTeX\ distributions will include the following packages which are extremely useful:
\begin{itemize}
\item \texttt{graphicx} or \texttt{graphics}: commands to import and manipulate graphics files.
\item \texttt{amsmath} (and \texttt{amssymb} and \texttt{amsthm}): The American Mathematical Society \LaTeX\ package. A large number of useful commands, especially for aligning equations (see \verb|\align| and related).
\item \texttt{fancyhdr}, \texttt{enumerate}, \texttt{caption}, \texttt{geometry}: control the document layout and appearance in a more transparent fashion. \texttt{fancyhdr} in particular is useful for producing headers for theses.
\item \texttt{babel}: if you want to typeset anything in a language other than English, this package provides a lot of support.
\item \texttt{hyperref}: transforms citations and cross-references into hyperlinks. Particularly useful when compiling direct to PDF.
\item \texttt{natbib} or \texttt{biblatex}: most will find the default citation styles sufficient (or, for articles, journals will frequently provide their own). If you require something more controllable then these packages give you that power (\texttt{natbib} is much older and practically obsolete, but has lots of examples and is in widespread use. \texttt{biblatex} is much newer and very powerful but with far fewer examples and requires a modern \LaTeX\ distribution).
\end{itemize}

\subsection{Creating packages}
\label{sec:packages_creating}

At its heart a package just contains the commands you would have placed in the document preamble. However, there are a few additional commands and points to be careful of.

\begin{itemize}
\item \verb|\ProvidesPackage{<name>}[<string>]|: this command defines the name of the package \verb|<name>| (which should match its filename) and an optional description \verb|<string>|.
\item \verb|\RequirePackage{<package>}|: instead of putting \verb|\usepackage{<package>}| inside a package, this command allows \LaTeX\ to check if \verb|<package>| has already been loaded, and if not, does so.
\item \verb|\DeclareOption|, \verb|ExecuteOptions|, \verb|\ProcessOptions|: allows you to pass options to the package (and hence options to commands in the package).
\end{itemize}

Package files should have a \verb|.sty| extension.

\section{Modularity}
\label{sec:modularity}

Long documents are typically composed of many chapters and sections using a variety of data. Working on a single long document is inefficient and confusing. It is better to split the document into multiple chunks corresponding to the structure of the document. \LaTeX\ has two ways of doing this.

\subsection{Input}
\label{sec:modularity_input}

The command \verb|\input| simply imports a file, as if it were ``cut and paste'' into the current document. This could be done right here, with a file imported into the middle of a paragraph. The \verb|\input| command takes the name of the file to be imported without the \texttt{.tex} extension. Once the file is imported the document continues as normal.

The \verb|\input| command is somewhat inflexible. My personal viewpoint is that its main use is for importing data produced by or stored in external formats. For example, if you have a code that produces a table with 50 entries, it will be safer to make your code output the results directly into a \LaTeX\ table format which can then be \verb|\input| into a document, rather than trying to copy all the data by hand.

\subsection{Include}
\label{sec:modularity_include}

The alternative to the \verb|\input| command is the \verb|\include| command. Its use is exactly the same as the \verb|\input| command -- the only argument is the name of the file to be included, without the \texttt{.tex} extension. There are two main differences.

The first difference, as is clear from this document, is that the text imported via the \verb|\include| command always starts on a new page, and there will be a new page inserted (via a page break) after the included content as well. For this reason the \verb|\include| statement is typically used in long documents -- reports or theses -- where each included file contains a full chapter.

The second difference is the main advantage of the \verb|\include| command. You can selectively include only certain files whilst leaving all the \verb|\include| statements in place. For example, consider an outline document
%
\begin{verbatim}
\documentclass{book}

\includeonly{chapter2}

\begin{document}

\include{chapter1}
\include{chapter2}
\include{chapter3}

\end{document}
\end{verbatim}
%
This document should consist of three chapters. If we are working just on chapter 2 then we can concentrate solely on that by using the \verb|\includeonly| command to produce only the output for that chapter. However, all cross-references to the other chapters will still be correctly resolved (provided that they have been compiled at least once).

\section[Additional commands]{Additional commands for long documents}
\label{sec:additional}

This contains a list of commands that are often useful for long reports and theses.
%
\begin{itemize}
\item \verb|\maketitle|: Produces a title page based on the \verb|\author|, \verb|\title| and \verb|\date| (which must be set after the \verb|\begin{document}| but before the \verb|\maketitle|).
\item \verb|\appendix|: as just used here, this converts the section or chapter numbering to use letters instead of numbers.
\item \verb|\tableofcontents|: inserts a table of contents containing the titles of chapters, sections, subsections (there are parameters to control the depth).

Note that if a title is extremely long it may not fit in the table of contents (or in the headers). All sectioning commands provide an option for a short title to be used in headers, table of contents and similar circumstances. An example is the title for this appendix where a short title of ``Additional commands'' can be produced using
\begin{verbatim}
\section[Additional commands]{Additional commands for long documents}
\end{verbatim}
\item \verb|\listoffigures|, \verb|\listoftables|: inserts the appropriate lists based on the captions of figures and tables. Here you will almost certainly want to use the optional short form for the captions.
\item \verb|\frontmatter|, \verb|\mainmatter|, \verb|\backmatter|: only avaiable for \verb|book| class, this explicitly changes the page numbering to Roman letters or Arabic numerals respectively.
\end{itemize}

\section{Citations and bibliographies}
\label{sec:Citations}

One of \LaTeX's strengths is its cross-referencing. However, the mechanism for including and organizing the bibliography is out-dated, so requires a little work to use in the best fashion.

The command to reference a bibliography citation is \verb|\cite|. Some
additional packages (such as \verb|natbib|) introduce additional
citation commands which allow for more control of the appearance of
the reference within the text. The \verb|\cite| command takes at least
one argument, which is the \emph{key} to the article in the
bibliography.

This section introduces the two most basic ways of building a bibliography in \LaTeX. Only the \verb|Bibtex| method of section~\ref{sec:bibtex} is recommended, and it is best to look at tools mentioned later for ease. Later sections will mainly focus on tools to build, maintain and control bibliographies using the underlying \verb|Bibtex| technology.

Note that when using \LaTeX\ to build a document containing a bibliography it is usually necessary to build the document at least twice, and usually three times. On the first pass it looks in the document and finds which citations are needed. On the second pass it looks in the database and extracts the citations, putting them in the appropriate form. The third pass finalizes the document.

\subsection{Direct inclusion}
\label{sec:Direct}

The bibliography can be written directly into the \LaTeX\ document using the commands (for example)
%
\begin{verbatim}
\begin{thebibliography}{99}

\bibitem{Duncan98} R. C. Duncan, Astrophys. J. {\bf 498}, L45 (1998).

\end{thebibliography}
\end{verbatim}
%
In this case there is only one item in the bibliography. The \verb|{99}| at the beginning gives the maximum number of entries in the bibliography -- this could be increased if needed. The article key is here \verb|Duncan98|, and would be cross-referenced in the text using \verb|\cite{Duncan98}|.

The advantages of this citation method are
\begin{enumerate}
\item speed; you can directly and rapidly change the document,
\item control; you can control exactly how it appears.
\end{enumerate}

The disadvantages are numerous.
\begin{enumerate}
\item Reuse; for every document you need to copy the reference without error.
\item Modification; for every different use you need to manually change the appearance of the reference, and do it consistently.
\item Completeness; there is no simple way to store all additional information about the reference that is not explicitly required (e.g.\ the abstract).
\item Errors; if you delete the reference from the text you must consistently remove it from the bibliography. If an unpublished article is published, you must consistently update the reference in all documents.
\item Etc...
\end{enumerate}

\subsection{Bibtex}
\label{sec:bibtex}

\verb|Bibtex| was the original solution for the \LaTeX referencing issues outlined above. An example of using \verb|Bibtex| is given in the \verb|BasicLatexBibtex| document, combined with the \verb|nummeth.bib| database file.

In brief, the \verb|Bibtex| file is a database. Written as a plain-text file, each entry is a single reference. An example entry would be
%
\begin{verbatim}
@article{Pareschi2005,
author = {Pareschi, Lorenzo and Russo, Giovanni},
doi = {10.1007/s10915-004-4636-4},
issn = {0885-7474},
journal = {Journal of Scientific Computing},
keywords = {65c20,82d25,ams subject classification,high order shock capturing,
hyperbolic systems with relaxation,kutta methods,runge,schemes,stiff,systems},
month = oct,
number = {1},
pages = {129--155},
title = {{Implicit-Explicit Runge-Kutta Schemes and Applications to
Hyperbolic Systems with Relaxation}},
url = {http://www.springerlink.com/index/10.1007/s10915-004-4636-4},
volume = {25},
year = {2005}
}
\end{verbatim}
%
The \emph{document type} is \verb|article|, as denoted by the \verb|@article|. There are many other possible, including books, reports, theses, unpublished, and many more. The \emph{key} is \verb|Pareschi2005|, to be cited \verb|\cite{Pareschi2005}| in the \LaTeX\ file. Some of the information included is required, but precisely what depends on the document type. For articles the minimum is the key, the author, the journal and the year. All other information \emph{may} be used (if available).

Inside the \LaTeX\ document only two lines are required. For example, in \verb|BasicLatexBibtex| the two lines are
%
\begin{verbatim}
\bibliographystyle{plain}
\bibliography{nummeth}
\end{verbatim}
%
The first controls the appearance of the bibliography; what order the references appear (e.g.\ alphabetical or in citation order), what information is included, and so on. It also controls how the citations appear in the text (e.g.\ author-date or numerical). The second line says that the references are stored in the \verb|nummeth.bib| file. Multiple \verb|bibtex| files can be referenced, separated by commas (e.g. \verb|\bibliography{file1,file2,file3}|).

The advantages of the \verb|bibtex| database are clear.
%
\begin{enumerate}
\item Reuse across multiple documents is easy.
\item Additional information is stored with the reference.
\item Changing styles is simple.
\item Errors can be corrected in a single place.
\end{enumerate}
%

Some disadvantages remain.
%
\begin{enumerate}
\item The \verb|bibtex| database format is difficult to maintain by hand.
\item Control over the appearance of the reference is less straightforward.
\item Producing a database from scratch is a lengthy and tedious process.
\end{enumerate}

\subsection{Constructing and maintaining a database}
\label{sec:maintaining}

When starting you will build your own database from everything you read, and also inherit a database from your supervisor, group and office-mates. Merging disparate databases by hand, and typing all the details of references into a plain-text database, is a recipe for mistakes and a huge waste of time. Better tools include the following.

\subsubsection{Journal websites}
\label{sec:journals}

Most published papers have a webpage through the journal, and many of these will export all of the reference information in a standard format. For \verb|bibtex| this typically means the website sends you a plain text file which you can copy and paste into your database.

It is often the case that a little tweaking of the entry will be required -- frequently the article key is not memorable, and the appearance of special characters can be problematic. But this approach can save considerable time, as well as giving you information (DOI, URLs) that other \LaTeX\ tools can use.

\subsubsection{Endnote and similar}
\label{sec:endnote}

Many people and groups use software such as \href{http://www.endnote.com/}{Endnote} to maintain their bibliographical database. There are free tools to convert between database formats -- see, for example, the \href{http://dret.net/bibconvert/}{ShaRef} service at \verb|http://dret.net/bibconvert/|.

The advantages of packages like Endnote are their wide use (in certain fields), their tools for maintaining the database, and their tools for use with other word-processing packages such as Word. The conversion process will often require a little tweaking, as above.

\subsubsection{Cloud and social reference managers}
\label{sec:cloud}

Online reference managers are available and are, for basic services, often free. These services include the basic functions of desktop packages such as Endnote, but have two major additional advantages. Firstly, the database is stored online and so available to you anywhere, on any device. Secondly, the tools are frequently well integrated with journal websites. This means that saving a reference to the database is just a single button click.

Examples include
%
\begin{enumerate}
\item \href{http://www.citeulike.org/}{CiteULike} at \verb|http://www.citeulike.org/|
\item \href{http://www.mendeley.com/}{Mendeley} at \verb|http://www.mendeley.com/|
\item \href{http://www.zotero.org/}{Zotero} at \verb|http://www.zotero.org/|
\end{enumerate}
%
Each has their own internal database format and will export to other formats, such as \verb|bibtex|, on demand.

The advantages of online reference managers for groups of collaborators and for web integration are obvious; it is definitely worth investigating such tools, and finding out which are standard in your field and group.

\subsection{Controlling the appearance}
\label{sec:appearance}

Usually when writing a document there is a template to follow, and often that template will be prescriptive. For example, many journals provide \LaTeX\ style files to use, combined with \verb|bibtex| style files as well. In these cases there is no need to control how the references appear.

However, in certain cases (such as your thesis) you may wish for more control. There are three basic methods: using the original \verb|bibtex| styles, using the \verb|natbib| package, or using the \verb|biblatex| package.

\subsubsection{Bibtex styles}
\label{sec:bibtex_styles}

The original \verb|bibtex| package came with a small selection of styles, and a number of additional styles have been made publically available. Many can be found online -- \href{http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html}{a sample list} can be found at \verb|http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html|, and many others exist.

If you are interested in the style being approximately correct, this is usually sufficient.

\subsubsection{Natbib}
\label{sec:natbib_styles}

The \verb|natbib| package contains additional citation commands, and additional software to build a style file that does exactly what you want. I would say it is now out of date, and \verb|biblatex| is a better package, but it is still widely used.

A few examples of the \href{http://merkel.zoneo.net/Latex/natbib.php}{citation commands provided} include
%
\begin{enumerate}
\item \verb|\citet{Jones90}|, producing ``Jones et al.\ (1990)''
\item \verb|\citet[chap. 2]{Jones90}|, producing ``Jones et al.\ (1990, chap.\ 2)''
\item \verb|\citep{Jones90}|, producing ``(Jones et al.\ 1990)''
\end{enumerate}
%
The distinction is between \emph{textual} (\verb|\citet|) and \emph{parenthetical} (\verb|citep|) citations.

In addition, \verb|natbib| has tools for sorting and compressing multiple citations in a single cross-reference, for modifying the appearance of parentheses, for aliasing a citation (i.e.\ replacing a key reference by ``Paper I'' throughout), and much more.

\subsubsection{Biblatex}
\label{sec:biblatex_styles}

All of the features mentioned above, and more, have been implemented in the \verb|biblatex| package. This allows the use of standard \LaTeX\ macros and commands for controlling the layout and appearance of citations and the bibliography. The \href{http://ctan.org/pkg/biblatex}{package description} can be found at \verb|http://ctan.org/pkg/biblatex|, with \href{http://mirror.ctan.org/macros/latex/contrib/biblatex/doc/biblatex.pdf}{full documentation} at
\verb|http://mirror.ctan.org/macros/latex/contrib/biblatex/doc/biblatex.pdf|.

There are changes that can be made at the detail level when updating the \verb|biblatex|; see, for example, the \href{http://tex.stackexchange.com/questions/5091/what-to-do-to-switch-to-biblatex}{comments at StackExchange} at \\ \verb|http://tex.stackexchange.com/questions/5091/what-to-do-to-switch-to-biblatex|. This allows you to take advantage of the full features of \verb|biblatex|.

\end{chapter}


\SetPicSubDir{ch-Exp}

\chapter{Experimenting with Other Random Models}
\label{ch:exp}
\vspace{2em}

A method similar to the 3-phase method in DHAM has been adopted and used to show existential/constructive results in some other models of random digraphs. Now that we are familiar with the DHAM algorithms, we shall attempt to inpnut graphs from some of these models, and see how DHAM performs on them. We shall try to look for patterns in terms of accuracy, runtime, or number of attempts in the following models.

\section{$k$-in, $k$-out Graphs}
\subsection{Graph Generation}
The way $D_{k-in, k-out}$ is defined, it is pretty straightforward to generate instances of this graph. At every vertex $u\in V_n$, we simply have to generate 2 lists of $k$ vertices each (as in-neighbours and out-neighbours), sampling uniformly at random from the set of all vertices. Now we add an edge from $u$ to each out-neighbour and an edge from each in-neighbour to $u$.
\subsection{Observations}
Cooper and Frieze \cite{cooper:kinout} have shown that $D_{2-in, 2-out}$ is Hamiltonian with High Probability, using a 3-phase analysis.

\begin{description}
\item[Phase 1] Show that $D_{2-in, 2-out}$ contains a permutation digraph, $\Pi$ of size at most $2\log n$.
\item[Phase 2] Increase the minimum cycle length in $\Pi$ to $n_0 = \Big\lceil \frac{1000n}{\log n} \Big\rceil$.
\item[Phase 3] Convert the Phase 2 permutation digraph to a Hamilton Cycle.
\end{description}
It is interesting to note that the proof follows a very similar outline to the one for Random Digraphs $D_{n, m}$, showing the existence of a Hamiltonian Cycle but, a similar bound on the runtime has not been obtained. It is still not known if there is a polynomial time algorithm to find the same.

\begin{figure}[ht]

\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/kin_time.png}
\caption{Runtime plot of $D_{k-in, k-out}$}
\label{fig:kin:time}
\end{subfigure}
\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/kin_accr.png}
\caption{Probability of finding a Hamilton cycle in $D_{k-in, k-out}$}
\label{fig:kin:accr}
\end{subfigure}

\caption{DHAM on $D_{k-in, k-out}$}
\label{fig:kin:plots}
\end{figure}

We try to test if DHAM might be successful in finding this Hamiltonian cycle in polynomial time.
From \autoref{fig:kin:time} we can see that (to the extend of n that is feasible for testing)
that runtime grows more or less the same as on $D_{n, m}$. This is suggestive of the fact that it might be possible to give a polynomial bound the runtime of 3-phase method on this class of graphs.

We also see some spikes in the runtime and also a lower probability of finding the Hamiltonian cycle in \autoref{fig:kin:accr} for $D_{2-in, 2-out}$, even though we know that this graph is Hamiltonian with high probability. This phenomenon is observed again in the next model we take a look at and seems to suggest that the algorithm does not run as well on sparse graphs.

\section{$k$-regular Graphs}
\subsection{Graph Generation}
To generate a $k$-regular digraph, we need to make sure that the in-degree and the out-degree of each vertex are k. But simply choosing $2k$ neighbours independently like for $D_{k-in, k-out}$ does not work, since we cannot guarantee that exactly $k$ other vertices will also be in-neighbours.

Instead, we notice that in a permutation digraph, each vertex has exactly $1$ in/out neighbour. We use this fact and take the union of k random permutation digraphs (which have no mutual overlap) to obtain a $k$-regular digraph.
\subsection{Observations}
Theoretically, it has been shown that $D_{n, r}$ is Hamiltonian with high probability for $r \ge 3$ \cite{cooper:kreg}. The proof for this is again based on a 3-phase method and is very similar to that for $D_{k-in, k-out}$, since large $k$-regular graphs look very similar to $D_{k-in, k-out}$ graphs. Hence it is not very surprising that their runtime plots look similar. The runtime very closely follows the same $n^{1.5}$ curve that $D_{n, m}$ had, suggesting that it might be possible to give a polynomial bound for DHAM on this class of graphs too.

Once again we notice the spikes in runtime and the lower probabilities of success for $k = 2, 3$ in \autoref{fig:kreg:accr}, reiterating the idea that DHAM performs poorly on sparse graphs. We can trace this bad performance to the first phase of the algorithm, where we construct a subgraph of average degree 10. The bipartite matching that follows depends on the degree of vertices in this subgraph, and a lower degree limits the success probability of the matching, and hence bottle-necking DHAM.

\begin{figure}[ht]

\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/kreg_time.png}
\caption{Runtime plot of $D_{n, r}$}
\label{fig:kreg:time}
\end{subfigure}
\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/kreg_accr.png}
\caption{Probability of finding a Hamilton cycle in $D_{n, r}$}
\label{fig:kreg:accr}
\end{subfigure}

\caption{DHAM on $D_{n, r}$}
\label{fig:kreg:plots}
\end{figure}
\subsection{Closer look at sparse graphs}
Since we notice the DHAM performs poorly on sparse graphs, but still works just fine at value below the mentioned degree $10$, in the original paper, we take a closer look to see above what value of $r$, does DHAM find a cycle in $D_{n, r}$, with high probability and low number of attempts.

\begin{figure}[ht]

\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/sprc_accr.png}
\caption{Probability of Finding a cycle in sparse $D_{n, r}$}
\label{fig:kreg:spaccr}
\end{subfigure}
\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/sprc_atmp.png}
\caption{Average no. of attempts to find the cycle}
\label{fig:kreg:spatmp}
\end{subfigure}

\caption{$D_{n, r}$ with low values of $r$}
\label{fig:kreg:sparse}
\end{figure}

From \autoref{fig:kreg:sparse} we see that for $r \ge 6$, the probability of finding a cycle is almost at 1, and the number of attempts also stabilises around 5.

\section{Random Tournaments}
\subsection{Graph Generation}
We can generate every possible pair of vertices, using a nested loop, and assign a direction to every edge uniformly at random to obtain the desired tournament.
\subsection{Observations}
Random Tournaments have been shown to have $\delta = min(\delta^+, \delta^-)$ edge disjoint Hamiltonian cycles\cite{kuhn:tourna}. Though the proof does not rely on the 3-phase method, DHAM using that method, still does find cycles in such graphs (\autoref{fig:tourna:time}), with high probability (probability 1 in our tests).

Tournaments grow in size as a function of $n^2$, limiting the range of $n$ feasible for testing. From the range of sizes that we tested on it is not possible to comment on the runtime on these graphs (since the implementation overhead might be affecting the runtime more than the algorithm itself). But we do notice that every graph generated returned a valid Hamiltonian cycle, which seems to suggest that the probability of success of the 3-phase method is also very high on random tournaments.
Also, since tournaments are dense graphs, we do not run into the bottlenecks that we observed in the last 2 models.

\begin{figure}[ht]

\centering
\includegraphics[width=0.9\linewidth,height=7cm]{pic/ch-Exp/tourna_time.png}
\caption{Runtime plot of Tournaments}
\label{fig:tourna:time}

\end{figure}

\section{Random $n$-lifts of complete digraph $K_h$}
\subsection{Graph Generation}
We first create the complete digraph, $K_h$ on $h$ vertices. Now, we start constructing a new digraph $D$, with $h \times n$ vertices, with the range of vertices $[i \times n, i \times (n+1) - 1]$ corresponding to each vertex $i\in V(K_h)$.

Now, for each edge $(u, v) \in E(K_h)$, we construct arrays $U$ \& $V$, of the vertices corresponding to $u, v \in V(K_h)$. After shuffling the arrays, we obtain a random matching as $\forall i<n, (U[i], V[i])$, which is now added to the graph $D$, to obtain the required $n$-lift of $K_h$.
\subsection{Observations}
This is another class of graphs that proved to be Hamiltonian \cite{frieze:lift} (for sufficiently large values of $h$) by using the 3-phase method, with appropriate modifications.
\begin{description}
\item[Phase 1] Show that with high probability the lift $D$ contains a directed permutation digraph, $\Pi$ of size at most $2\ln n$.
\item[Phase 2] Increase the minimum cycle length in $\Pi$ to $n_0 = \Big\lceil \frac{100nh^3}{\ln n} \Big\rceil$.
\item[Phase 3] Convert the Phase 2 permutation digraph to a Hamilton Cycle.
\end{description}

We make some interesting observations here.
The first is that for $k=8$ we see that all the generated graphs are Hamiltonian, which could be considered a more precise lower bound for $h$ than the \textit{sufficiently large h} . But more importantly, none of the n-lifts of $K_3$ are Hamiltonian. Frieze in his survey\cite{frieze:2019survey}, has posed the problem to show that n-lifts of $K_3$ are Hamiltonian. What we observe with DHAM, is that the probability of lifts of $K_3$ being Hamiltonian is zero. Though this particular algorithm failing, need not imply that n-lifts of $K_3$ are not Hamiltonian (indeed it could be because of the phenomenon of DHAM doing poorly on sparse graphs, with us also observing the runtime spikes, and low probability at $k=4$), it is an interesting observation nevertheless and worth taking a deeper look into.

\begin{figure}[ht]

\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth,height=7cm]{pic/ch-Exp/nlift_time.png}
\caption{Runtime plot of n-lifts}
\label{fig:nlift:time}
\end{subfigure}
\begin{subfigure}{\textwidth}
\centering
\includegraphics[width=0.9\linewidth, height=7cm]{pic/ch-Exp/nlift_accr.png}
\caption{Probability of finding a Hamilton cycle in lifts of $K_h$}
\label{fig:lift:accr}
\end{subfigure}

\caption{DHAM on n-lifts}
\label{fig:other:plots}
\end{figure}


\subsection{Three-dimensional RTE solver \index{MYSTIC} (mystic)}
\label{sec:mystic}

The Monte Carlo method is the most straightforward way to calculate
(polarized) radiative transfer. In forward tracing mode
individual photons are traced on their random paths through the atmosphere.
Starting from top of the atmosphere (for solar radiation), or being thermally
emitted by the atmosphere or surface, the photons are followed until they
hit the surface or leave again at top of the atmosphere (TOA). For
solar radiation, the start position is either a random location in the
TOA plane, with the direction determined by the solar zenith and
azimuth. Originally, the ``Monte Carlo for the physically correct tracing of
photons in cloudy atmospheres'' MYSTIC \citep{mayer2009} has been developed as
a forward tracing method for the calculation of irradiances and radiances in
\ifthreedmystic{3D} plane-parallel atmospheres. Later the model has been extended to fully
spherical geometry and a backward tracing mode \citep{emde2007}. The backward
photon tracing option speeds up the calculation of radiances and allows very
fast calculations in the thermal spectral range.

\ifthreedmystic{MYSTIC handles three-dimensional water and ice clouds in a
one-dimensional background  atmosphere of molecular scatterers and
absorbers and aerosol particles.  MYSTIC also allows topography as well as
inhomogeneous surface albedo and BRDF to be considered.}

MYSTIC is now a full vector code: It can handle polarization and
polarization-dependent scattering by randomly oriented particles,
i.e. clouds droplets and particles, aerosol particles, and molecules
\citep{emde2010}. To keep the computational time reasonable for
accurate calculations of e.g. polarized radiances in cloudy
atmospheres several ``tricks'' are required to speed up the
calculations. The first is the so called ``local estimate method''
\citep{marshak2005}. Using this method a photon contributes to the
final result of the calculation each time it is scattered. However, in
the presence of particles with strong forward scattering in the
simulated scene, such as clouds and large aerosols, the local estimate
method will produce so-called ``spikes'', these are rare photons whose
very large contribution to the result leads to slow convergence. The spike
problem can be resolved by using the ``Variance Reduction Optimal
Options Method'' \citep[VROOM,][]{buras2011a}, a collection of several
variance reduction methods which change the photon paths such that the
spikes disappear, but without altering the result (i.e.~the variance
reduction is ``unbiased'').

A detailed introduction to the Monte Carlo technique and in particular
to MYSTIC is given in \citet{mayer2009}. For specific questions
concerning the Monte Carlo technique the reader is referred to the literature
\citep{marchuk1980,collins1972,marshak2005,cahalan2005}.

MYSTIC is switched on by the option \code{rte\_solver mystic}. If no
other options are specified MYSTIC computes unpolarized quantities for
a \ifthreedmystic{3D} plane-parallel
atmosphere\ifthreedmystic{~(domain is divided into block-shaped
boxes)}. If \codeidx{mc\_polarisation} is specified, polarized
quantities are computed. The option \codeidx{mc\_spherical 1D} enables
calculations in a 1D spherical model atmosphere. All MYSTIC-specific
options start with \code{mc\_} and
are described in detail in section~\ref{sec:uvspec_options}.

\ifthreedmystic{
MYSTIC may be provided with various 2D and 3D input files, in addition
to the standard 1D input files of {\sl uvspec}. The input files may
include the following data:
\begin{itemize}
\item 3D water clouds
\item 3D ice clouds
\item 2D surface albedo
\item 2D elevation
\item 2D BRDF
%\item Lasers and detectors for lidar
\end{itemize}

If none of these are specified, MYSTIC does basically a 1D calculation
and should compare well with other solvers, in particular \code{disort2}.

MYSTIC operates in a user-defined model-domain. Since periodic boundary
conditions are applied, the user has to make sure that the quantity to be
calculated is not affected by the boundaries. For maximum flexibility,
the different grids (sample, cloud, elevation, albedo or BRDF) are
completely independent. The only constraint is that the domain size
is equal for all grids used. E.g., clouds may be defined in 5x5x2~km$^3$
cubes while the surface albedo is defined on a 1x1~km$^2$ grid,
the elevation on a 0.1x0.2~km$^2$ grid, and the output might
be sampled on a 3x4~km$^2$ grid. The only restrictions are
the available memory, the processor speed, and the requirements on
the precision of the result (see section~\ref{sec:mc_memory}).

The sampling information for MYSTIC is defined in the input file (e.g.
with \codeidx{mc\_sample\_grid}, \codeidx{zout}, \codeidx{umu}, ...).
After initialization MYSTIC reports how it interpreted the input parameters
which gives the user a chance to see if it really does what it is
supposed to be doing.

\subsubsection{Coordinates}
Mystic in cartesian mode uses an ENU coordinate system to define the atmospheric state:
\begin{itemize}
    \item{\emph{x}: east}
    \item{\emph{y}: north}
    \item{\emph{z}: up}
\end{itemize}

\begin{figure}[h!]
\centering
\tdplotsetmaincoords{70}{20}
\begin{tikzpicture}[scale=5,tdplot_main_coords]

    \coordinate (O) at (0,0,0);
    \coordinate (Ex) at (1,0,0);
    \coordinate (Ey) at (0,1,0);
    \coordinate (Ez) at (0,0,1);

    \draw[thick, ->] (-0.2,0,0) -- (Ex) node[anchor=west]{$x~\textrm{(east)}$};
    \draw[thick, ->] (0,-0.2,0) -- (Ey) node[anchor=west]{$y~\textrm{(north)}$};
    \draw[thick, ->] (0,0,0) -- (Ez) node[anchor=south]{$z~\textrm{(up)}$};

    \tdplotsetcoord{P}{1}{45.57}{60};
    \draw[thick, ->, color=red] (O) -- (P) node[anchor=south west]{sensor};
    \draw[dashed, color=red] (O) -- (Pxy);
    \draw[dashed, color=red] (P) -- (Pxy) node[midway,anchor=west]{$\textrm{umu} = 0.7$};

    \tdplotdrawarc[color=red]{(O)}{0.3}{90}{60}{xshift=0.3cm,anchor=north west}{$\textrm{phi} = 30\degree$};
\end{tikzpicture}
\caption{Sensor coordinate specification (\codeidx{umu} and \codeidx{phi}). The red arrow is pointing into the sensor, thus a sensor with positive umu values is looking downwards.}
\label{fig_sensor_coordinates}
\end{figure}
Generally, the sensor orientation is specified using the \codeidx{umu} and \codeidx{phi} input options as shown in figure~\ref{fig_sensor_coordinates}.
The location of the sensor is given in the same $x$, $y$, $z$ coordinate system by use of the option \codeidx{mc\_sensorposition}.
The position of the sun is specified either using \codeidx{latitude}, \codeidx{lognitude} and \codeidx{time} or using \codeidx{sza} and \codeidx{phi0}.
In the latter case, the angles are (maybe depending on the mindset of the reader), defined slightly different as shown in figure~\ref{fig_sun_coordinates}.

\begin{figure}[h!]
\centering
\tdplotsetmaincoords{70}{20}
\begin{tikzpicture}[scale=5,tdplot_main_coords]

    \coordinate (O) at (0,0,0);
    \coordinate (Ex) at (1,0,0);
    \coordinate (Ey) at (0,1,0);
    \coordinate (Ez) at (0,0,1);

    \draw[thick, ->] (-0.2,0,0) -- (Ex) node[anchor=west]{$x~\textrm{(east)}$};
    \draw[thick, ->] (0,-0.2,0) -- (Ey) node[anchor=west]{$y~\textrm{(north)}$};
    \draw[thick, ->] (0,0,0) -- (Ez) node[anchor=south]{$z~\textrm{(up)}$};

    \tdplotsetcoord{P}{1}{30}{210};
    \draw[thick, ->, color=orange] (O) -- (P) node[anchor=south east]{sun};
    \draw[dashed, color=orange] (O) -- (Pxy);
    \draw[dashed, color=orange] (P) -- (Pxy);

	\tdplotsetthetaplanecoords{210};
    \tdplotdrawarc[tdplot_rotated_coords, color=orange]{(O)}{0.5}{0}{30}{xshift=0.7cm,anchor=west}{$\textrm{sza} = 30\degree$}

    \tdplotdrawarc[color=orange]{(O)}{0.15}{270}{210}{yshift=-0.2cm,anchor=north}{$\textrm{phi0} = 60\degree$};
\end{tikzpicture}
\caption{Sun coordinate specification (sza and phi0). The orange arrow is pointing into the sun.}
\label{fig_sun_coordinates}
\end{figure}

\begin{figure}[h!]
\centering
\tdplotsetmaincoords{70}{20}
\pgfmathsetmacro{\thetavec}{20}
\pgfmathsetmacro{\phivec}{320}
\begin{tikzpicture}[scale=5,tdplot_main_coords]

    \coordinate (O) at (0,0,0);
    \coordinate (Ex) at (1,0,0);
    \coordinate (Ey) at (0,1,0);
    \coordinate (Ez) at (0,0,1);

    \draw[thick, ->] (-0.2,0,0) -- (Ex) node[anchor=west]{$x~\textrm{(east)}$};
    \draw[thick, ->] (0,-0.7,0) -- (Ey) node[anchor=west]{$y~\textrm{(north)}$};
    \draw[thick, ->] (0,0,-0.7) node[anchor=north]{nadir} -- (Ez) node[anchor=south]{$z~\textrm{(up, zenith)}$};

    \tdplotsetcoord{P1}{0.6}{60}{160}
    \tdplotsetcoord{P2}{0.6}{60}{100}
    \tdplotsetcoord{P3}{0.6}{100}{100}
    \tdplotsetcoord{P4}{0.6}{100}{160}
    \tdplotsetcoord{P3a}{0.6}{90}{100}
    \tdplotsetcoord{P3b}{0.7}{90}{100}

	\draw[dashed,color=orange] (O) -- (P1) node[anchor=east]{$(0,N_y-1)$};
	\draw[dashed,color=orange] (O) -- (P2) node[xshift=0.5cm,anchor=west]{$(N_x-1,N_y-1)$};
	\draw[dashed,color=orange] (O) -- (P3) node[xshift=0.5cm,anchor=west]{$(N_x-1,0)$};
	\draw[dashed,color=orange] (O) -- (P4) node[xshift=-1.2cm,anchor=north east]{$(0,0)$};
	\draw[dashed,color=black] (P3a) -- (P3b);

    \tdplotdrawarc[color=black,dotted]{(0,0,0)}{0.6}{160}{-90}{}{}
    \tdplotdrawarc[color=orange]{(P1z)}{0.519}{100}{160}{}{}
    \tdplotdrawarc[dashed,color=blue]{(P1z)}{0.519}{95}{100}{}{}
    \tdplotdrawarc[color=orange]{(P3z)}{0.59088}{100}{160}{}{}

    \tdplotdrawarc[color=black,dashed]{(0,0,0)}{0.6}{270}{160}{xshift=0.1cm,anchor=west}{$\phi_1 = 110\degree$}
    \tdplotdrawarc[color=black,dashed]{(0,0,0)}{0.7}{270}{100}{anchor=east}{$\phi_2 = 170\degree$}
    \tdplotsetthetaplanecoords{100}
    \tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{60}{100}{}{}
    %\tdplotdrawarc[tdplot_rotated_coords,dotted,color=black]{(0,0,0)}{0.6}{0}{360}{}{}
    %\tdplotdrawarc[tdplot_rotated_coords,dashed,color=black]{(0,0,0)}{0.6}{100}{90}{}{}
    \tdplotsetthetaplanecoords{155}
    \tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{100}{180}{anchor=east}{$\theta_1 = 80\degree$}
    \tdplotsetthetaplanecoords{95}
    \tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{60}{180}{anchor=west}{$\theta_2 = 120\degree$}
    \tdplotsetthetaplanecoords{160}
    \tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{60}{100}{}{}
    %\tdplotdrawarc[tdplot_rotated_coords,dotted,color=black]{(0,0,0)}{0.6}{0}{360}{}{}
    %\tdplotdrawarc[tdplot_rotated_coords,dashed,color=black]{(0,0,0)}{0.6}{80}{90}{}{}

\end{tikzpicture}
    \caption{Panorama coordinates for the option \codeidx{mc\_panorama\_alignment} \code{zenith} (default). The camera is located at the coordinate system origin. The image is recorded on a spherical shell inside the orange box, which is behind the origin. The boundaries of this box are given by the parameters $\phi_1$, $\phi_2$, $\theta_1$, $\theta_2$ to \codeidx{mc\_panorama\_view}. $\phi_1$ and $\phi_2$ are measured in the $x-y$-plane, beginning in the south. $\theta_1$ and $\theta_2$ measure the "latitude" where nadir is 0. The coordinates given in orange show the $(x, y)$ coordinates of the resulting image. The $(x, y)$ coordinates thus correspond to $(\theta, \phi)$ coordinates.}
\label{fig_panorama_coords_zenith}
\end{figure}

\begin{figure}[h!]
\centering
\tdplotsetmaincoords{70}{20}
\pgfmathsetmacro{\thetavec}{36.87}
\pgfmathsetmacro{\phivec}{-50}
\begin{tikzpicture}[scale=5,tdplot_main_coords]

    \coordinate (O) at (0,0,0);
    \coordinate (Ex) at (1,0,0);
    \coordinate (Ey) at (0,1,0);
    \coordinate (Ez) at (0,0,1);

    \draw[thick, ->] (-0.1,0,0) -- (Ex) node[anchor=west]{$x~\textrm{(east)}$};
    \draw[thick, ->] (0,-0.6,0) -- (Ey) node[anchor=west]{$y~\textrm{(north)}$};
    \draw[thick, ->] (0,0,0) -- (Ez) node[anchor=south]{$z~\textrm{(up)}$};

    \tdplotsetcoord{P}{0.6}{\thetavec}{\phivec}
    \tdplotsetcoord{Q}{0.6}{53.13}{130}
    \draw[dashed, color=blue] (P) -- (Pxy) node[near start,anchor=west]{$\textrm{umu} = -0.8$};
    \draw[dashed, color=blue] (O) -- (Pxy);
    \tdplotdrawarc[color=red]{(O)}{0.48}{270}{130}{xshift=0.3cm,anchor=south east}{$\textrm{phi} = 140\degree$};
    \draw[dashed, color=red] (Q) -- (Qxy);

    \tdplotsetrotatedcoords{\phivec}{\thetavec}{0}

    \draw[tdplot_rotated_coords, thick, ->, color=magenta] (0,-0.1,0) -- (0,0.6,0) node[anchor=south east]{$x'$};
    \draw[tdplot_rotated_coords, thick, ->, color=red] (0.4,0,0) -- (-0.6,0,0) node[anchor=north west]{$y'$};
    \draw[tdplot_rotated_coords, thick, -, color=red] (0.6,0,0) -- (0.53,0,0);
    \draw[tdplot_rotated_coords, thick, ->, color=blue] (0,0,-0.6) -- (0,0,0.6) node[anchor=south east]{$z'$};

    \tdplotdrawarc[tdplot_rotated_coords,color=black,dotted]{(0,0,0)}{0.6}{0}{345}{}{};
    \tdplotdrawarc[tdplot_rotated_coords,color=black,dashed]{(0,0,0)}{0.6}{0}{-15}{anchor=north west}{$\phi_1=15\degree$};
    \tdplotdrawarc[tdplot_rotated_coords,color=black,dashed]{(0,0,0)}{0.8}{0}{-45}{anchor=north west}{$\phi_2=45\degree$};

    \tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0.1042)}{0.59088}{-15}{-45}{}{}
    \tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,-0.1042)}{0.59088}{-15}{-45}{}{}

    \tdplotsetrotatedthetaplanecoords{0}
    \tdplotdrawarc[tdplot_rotated_coords,color=black,dotted]{(0,0,0)}{0.6}{0}{360}{}{}
    \tdplotsetrotatedthetaplanecoords{-15} %note that this changes the rotated frame already
    \tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{80}{100}{}{}
    \tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{180}{100}{yshift=1cm,anchor=west}{$\theta_1=80\degree$}
    \tdplotsetrotatedthetaplanecoords{-30}
    \tdplotdrawarc[tdplot_rotated_coords,color=orange]{(0,0,0)}{0.6}{80}{100}{}{}
    \tdplotsetrotatedthetaplanecoords{-5}
    \tdplotdrawarc[tdplot_rotated_coords,dashed,color=blue]{(0,0,0)}{0.6}{180}{80}{yshift=0.5cm,anchor=east}{$\theta_2=100\degree$}

\end{tikzpicture}
    \caption{Panorama corrdinates for \codeidx{mc\_panorama\_alignment} \code{mu}. In \emph{mu} aligned mode, the panorama is taken as in \emph{zenith}-mode, however the whole coordinate system is rotated using the parameters \codeidx{umu} and \codeidx{phi} yielding the new coordinates $x'$, $y'$, $z'$. If $\textrm{umu} = -1$ and $\textrm{phi} = 180\degree$, the coordinates are exactly the same as in \emph{zenith} mode. Be aware that if \codeidx{umu} is $1$ or $-1$, the value of \codeidx{phi} is not accepted and the system behaves as if $\textrm{phi} = 180\degree$. In this case, the equivalent rotation can be achieved by $\phi_1$ and $\phi_2$.}
\label{fig_panorama_coords_mu}
\end{figure}

If panoramic images are calculated, the sensor specification is extended by a definition for the field of view of the camera an the option \codeidx{mc\_panorama\_view}.
The behavior of this specification can be changed by the \codeidx{mc\_panorama\_alignment}.
In the default mode (\codeidx{mc\_panorama\_alignment} \code{zenith}), \code{umu} and \code{phi} are ineffective.
The view specificatiion behaves as described in figure~\ref{fig_panorama_coords_zenith}.
If \codeidx{mc\_panorama\_alignment} \code{mu} is activated, the user can basically rotate the camera.
The angles are defined as in figure~\ref{fig_panorama_coords_mu}.

\subsubsection{Three-dimensional clouds}

The options \codeidx{wc\_file 3D}
and \codeidx{ic\_file 3D} may be used to define 3D water and ice
cloud properties respectively. The model atmosphere may contain both 3D
(defined in a \code{wc\_file/ic\_file 3D}) and 1D clouds (defined in a
\code{wc\_file/ic\_file 1D}), but for obvious reasons not in the same layer. The format
of the files is explained in section~\ref{sec:uvspec_options}.

The conversion from microphysical to optical properties
is done identically for 1D and 3D clouds and is defined
by the options \codeidx{wc\_properties} and \codeidx{ic\_properties}. All
possible settings for \code{wc\_properties} and \code{ic\_properties}
have been implemented in MYSTIC (e.g., hu, mie, yang, HEY, baum ...).
Clouds can be defined eiter as ASCII or as netCDF files.

\paragraph{ASCII}
The following example shows the easiest possible 3D
cloud file which defines a checkerboard grid of clouds:
\begin{Verbatim}[fontsize=\footnotesize, frame=single, samepage=true]
  2 2 5 3
  1.0 1.0 0 1 2 3 4 5

  1 1 2 0.1 10
  2 2 2 0.1 10
\end{Verbatim}
For the layer between 1 and 2 km a 3D cloud is defined with liquid water
content 0.1 $g/m^3$ and effective radius 10 $\mu$m for horizontal
boxes (1,1) and (2,2). Boxes (1,2) and (2,1) are cloudless. The result are
cubic clouds with a volume of 1x1x1~km$^3$. The microphysical properties are
converted to optical properties according to \code{wc\_properties}.

\paragraph{netCDF}
If the provided cloud file is a netCDF instead of an ASCII file, this will be
detected automatically. The netCDF file must have the following structure:
\begin{Verbatim}[fontsize=\footnotesize, frame=single, samepage=true]
netcdf cloud {
dimensions:
	ny = 2 ;
	nx = 2 ;
	nz = 1 ;
	nz_lev = 2 ;
variables:
	double lwc(ny, nx, nz) ;
	double z(nz_lev) ;
	double reff(ny, nx, nz) ;

// global attributes:
	:cldproperties = 3 ;
	:dx = 1. ;
	:dy = 1. ;
}
\end{Verbatim}
The order of the dimensions is important, and the size of \code{nz\_lev} must be
exactly \code{nz + 1}. The \code{cldproperties} attribute is equal to the flag
in the ASCII format. The variable names change for different \code{cldproperties}
according to the following table:
\begin{itemize}
    \item{1: \quad \code{ext g1 ssa}}
    \item{2: \quad \code{ext reff}}
    \item{3: \quad \code{lwc reff}}
\end{itemize}

\subsubsection{Two-dimensional surface albedo}

A 2D surface albedo may be defined using the option
\codeidx{mc\_albedo\_file}. The format of the file is explained in
section~\ref{sec:uvspec_options}.

\subsubsection{Topography}

A 2D elevation may be defined using the option
\codeidx{mc\_elevation\_file}. The ASCII format is explained in
section~\ref{sec:uvspec_options}. For the netcdf format please refer
to \file{README.MC}.

Caution:
\begin{itemize}
\item To avoid confusion, do not specify an \code{altitude} different
  from 0 in the uvspec input file.
\item There may be problems if the 2D surface hits 0
  (more testing required). Use 0.001 as lowest altitude.
\item  The elevation file MUST BE PERIODIC
\end{itemize}

Between the grid points, the surface is interpolated
bilinearely:
\begin{equation}
  z(x,y) = a + bx + cy + dxy
\end{equation}
where $z$ is the altitude and the coefficients $a$, $b$, $c$, and $d$
are determined from
the altitudes specified at the four corners of each pixel.
Slant surfaces are treated as they should be; e.g., photons
may be reflected downward at snow-covered mountain sides.

\subsubsection{Bidirectional reflectance distribution function}
MYSTIC allows different homogenous or 2D-inhomogeneous BRDFs. The
implementation of the different BRDFs is rather heterogeneous,
as were the requirements when each of them was first implemented.
Please note that BRDFs currently do not work together with topography. The
very simple reason for that is in structured terrain reflection
polar angles larger than 90 degree are possible for which the
existing parameterizations do not provide data. The following
parameterizations are included:
\begin{itemize}
\item Water BRDF by \citet{cox54a,cox54b}; currently only homogeneous; switched
  on with \codeidx{brdf\_cam u10}, ... like in the 1D case
\item AMBRALS (Algorithm for Modeling[MODIS] Bidirectional Reflectance
  Anisotropies of the Land Surface; \citet{wanner97}), see also
  \url{http://i3rc.gsfc.nasa.gov/phase3/brasil/phase3_step1_brasil.htm}.
  AMBRALS is three-parameter BRDF fit for vegetated and non-vegetated surfaces.
  A \codeidx{mc\_ambrals\_file} may be specified which contains the
  3 parameters for each surface pixel. The format is like
  the format of 2D surface albedo file, except that each data line
  contains (iso, vol, geo) instead of only one albedo value.
  Obviously, wavelength-dependent AMBRALS BRDFs are not
  possible at present.
\item RPV \citep{rahman93a}, a three parameter
  fit for vegetated and non-vegetated surfaces. RPV is currently the
  most flexible surface description in MYSTIC as it is currently
  the only way to define a wavelength-dependent 2D BRDF.
  Two different ways exist to define an RPV BRDF:
  \begin{itemize}
  \item 1D, using the options \codeidx{brdf\_rpv k} ... like in the 1D case
  \item using \codeidx{mc\_rpv\_file} and \codeidx{mc\_rpv\_type}.
    The first is a RPV
    type for each surface pixel; type is simply a label like
    "Grass" or "1" or whatever. For each of these types,
    \code{mc\_rpv\_type} must have an entry which connects the type to
    a file which contains wavelength-dependent RPVs. Sounds
    complicated but is a very efficient way to define a
    wavelength-dependent 2D RPV. Label ``CaM'' is reserved for Cox and Munk
    and invokes the Cox and Munk ocean BRDF for the respective pixel. Thus
    it is possible to combine land and ocean BRDFs.
  \end{itemize}
\item For calculations including polarization the option
  \codeidx{bpdf\_tsang\_u10} is available which calculates polarized
  bidirectional reflection from water surfaces.
\end{itemize}
}

\subsubsection{MYSTIC output}

{\sl uvspec} will print its output (horizontally averaged
irradiance and actinic flux) usually to stdout. MYSTIC provides
several additional output
files. We have to distinguish two classes of output:
Monochromatic and spectral output where the latter can be recognized
by the extension ``.spc''. Monochromatic output files

\begin{itemize}
\item mc.flx - irradiance, actinic flux at levels
\item mc.rad - radiance
\item mc.abs - absorption/emission
\item mc.act - actinic flux, averaged over layers
\end{itemize}

are generated only for the case of a calculation where MYSTIC is called
only once. That is, a monochromatic calculation without subbands introduced
by \code{mol\_abs\_param}. They contain ``plain'' MYSTIC output, without
consideration of extraterrestrial irradiance, sun-earth-distance, spectral
integration, etc. As such they are mainly interesting for MYSTIC developers
or for users interested in artificial cases and photon statistics since
they are as close as possible to the photon statistics of MYSTIC: e.g.
the ``irradiance'' in these files is basically the number of photons arriving
at the detector divided by the number of photons traced. In addition to the
average, a standard deviation of the result can be calculated online which is
stored in ``.std''.

For most real-world applications the user will prefer the ``.spc'' files

\begin{itemize}
 \item mc.flx.spc - spectral irradiance, actinic flux at levels
 \item mc.rad.spc - spectral radiance at levels
 \item ...
\end{itemize}

In contrast to the monochromatic files which are transmittances (E/E0, L/E0,
...) the data in ".spc" is "fully calibrated" output, as for all other
solvers. "fully calibrated" means multiplied with the extraterrestrial
irradiance, corrected for the Sun-Earth distance, integrated/summed
over wavelength, etc. Please be aware that such a calculation might require
a lot of memory because output is stored as a function of x, y, z, and
wavelength (and possibly polarization, if you switched on \code{mc\_polarisation}).
E.g. a comparatively harmless "mol\_abs\_param kato2" calculation with an sample grid of 100x100 pixels
at 10 altitudes would imply about 100x100x10x148 = 14,800,000 (Nx$\cdot$Ny$\cdot$Nz$\cdot$Nlambda) grid points. Depending
on the output chosen (irradiance, radiance, ...) up to six floating
point numbers need to be stored which amounts to 360 MBytes. Depending
on the post-processing in {\sl uvspec}, this memory may actually be used
twice which then would be 720 MBytes.

\begin{description}
\item[mc.flx / mcNN.flx]
  The output file \code{mc.flx} contains the irradiance
  at the surface defined by elevation file. Note that
  this output is {\bf not} for $z=0$, but for the actual 2D surface:
  \begin{Verbatim}[fontsize=\footnotesize, frame=single, samepage=true]
    500  500 0 0.325889 0 0 0.441766 0
    500 1500 0 0.191699 0 0 0.267122 0
    500 2500 0 0.210872 0 0 0.420268 0
  \end{Verbatim}
  The columns are:
  \begin{enumerate}
  \item  x [m] (pixel center)
  \item  y [m] (pixel center)
  \item  direct transmittance
  \item  diffuse downward transmittance
  \item  diffuse upward transmittance
  \item  direct actinic flux transmittance
  \item  diffuse downward actinic flux transmittance
  \item  diffuse upward actinic flux transmittance
  \end{enumerate}
  The transmittance is defined as irradiance devided by the extraterrestrial irradiance.
  It is not corrected for Sun-Earth-Distance.

  Note that even for an empty atmosphere, the transmittance
  would not be 1 but cos(SZA), due to the slant incidence of the radiation.

  The output files \code{mcNN.flx} contain the irradiances
  at different model levels - one for each \code{zout}. \code{NN} is the
  number of the output level counted from the bottom (ATTENTION: Levels are
  counted from 0 here!). The file format is the same as in \code{mc.flx}.

  (If interested in surface quantities, please use the irradiance data at the
  surface from \code{mc.flx}, not from \code{mc00.flx}; the data from
  \code{mc00.flx} or whatever layer coincides with the
  surface may be wrong for technical reasons).

\item[mc.rad / mcNN.rad]
  The output file \code{mc.rad} contains the radiance
  at the surface defined by \code{elevation\_file}. Note that
  this output is {\bf not} for $z=0$, but for the actual 2D surface:
  \begin{Verbatim}[fontsize=\footnotesize, frame=single, samepage=true]
    500  500 45 270 0.0239094 0 0.0623305 0.063324
    500 1500 45 270 0.0239094 0 0.0602891 0.063156
  \end{Verbatim}
  The columns are:
  \begin{enumerate}
  \item  x [m] (pixel center)
  \item  y [m] (pixel center)
  \item  viewing zenith angle  [deg]
  \item  viewing azimuth angle [deg]
  \item  aperture solid angle [sterad]
  \item  direct  radiance component
  \item  diffuse radiance component
  \item "escape" radiance
  \end{enumerate}
  For almost all applications you may safely ignore the ``direct'' and
  ``diffuse'' radiance components and use only the escape radiance. If the
  latter is 0 then you probably forgot to switch on \code{mc\_escape}.
  The "escape" radiance is the radiance "measured" by an ideal
  instrument with 0$^\circ$ opening angle. It is only calculated
  when \codeidx{mc\_escape} is selected and it usually converges
  much faster than the "cone sampled" radiance in column 7.
  It is recommended to always use \code{mc\_escape} for radiance
  calculations. For the ``direct'' and ``diffuse'' radiance, photons
  falling into the aperture are counted. This might be an option for
  instruments with a very large aperture only because otherwise the result
  is noisy.

  The output files \code{mcNN.rad} contain the radiances
  at different model levels - one for each \code{zout}. \code{NN} is the
  number of the output level counted from the bottom (ATTENTION: Levels are
  counted from 0 here!). The file format is the same as in \code{mc.rad}.

  (If interested in surface quantities, please use the radiance data
  at the surface from \code{mc.rad}, not from \code{mc00.rad}; the data from
  \code{mc00.rad} or whatever layer coincides with the
  surface may be wrong for technical reasons).

\item[mcNN.abs]
  The file \code{mcNN.abs} includes the absorption per unit area in the given layer.
  NN is the number of the output layer on the atmospheric
  grid (counted from the bottom, starting from 1). This file is generated if \code{mc\_forward\_ouput absorption}
  or \code{mc\_forward\_output emission} is specified.

  The columns are:
  \begin{enumerate}
  \item  x [m] (pixel center)
  \item  y [m] (pixel center)
  \item  absorption/emission/heating rate (W/m$^2$)
  \end{enumerate}

  If multiplied by the extraterrestrial irradiance, the column
  absorption in W/m$^2$ is obtained. In a 1D atmosphere, with a solar source,
  absorption = e\_net(top) - e\_net(bottom) (this is not true for a thermal
  source because then emission needs to be considered; see below). If
  \code{mc\_forward\_output emission} is specified, the file contains the thermal emission of
  the layer per unit area, that is, the Planck function times the optical
  thickness of the layer times 4$\pi$ (angular integral of the Planck
  radiance). If \code{mc\_forward\_output heating} is specified, the heating rate per unit area is
  provided instead of absorption (in the same units as absorption).
  For a solar source, the heating rate is identical to the absorption.
  In the thermal, however, each emitted photon is counted as cooling
  and hence the heating rate may be negative. In a 1D atmosphere, with a
  solar or thermal source, absorption = e\_net(top) - e\_net(bottom).

  For computational efficiency reasons \code{mcNN.abs} is not provided on the
  sample grid but on the atmospheric grid. For the same reason, results are
  only calculated for 3D layers. In order to obtain 3D absorption for 1D
  cloudless layer, you need to specify an optically very thin 3D cloud, e.g.
  LWC/IWC = 10$^{-20}$ g/m$^3$ (yes, this is a dirty trick but a necessary one).

\item[mcNN.act]
  \code{mcNN.act} contains the 4$\pi$ actinic flux in the given layer,
  calculated from the absorbed energy (per unit area) divided by the
  absorption optical thickness of the layer. In contrast to the
  actinic flux in \code{mcNN.flx}, this is a layer quantity the
  accuracy of which is generally much better than the level quantities
  which are calculated from radiance / cos (theta). As for the absorption
  above, \code{mcNN.act} is not provided on the sample grid but on the
  atmospheric grid. NN is the number of the output layer (counted from the
  bottom, starting from 1). This file is generated if \codeidx{mc\_forward\_output actinic} is specified.

  The columns are:
  \begin{enumerate}
  \item  x [m]
  \item  y [m]
  \item  actinic flux (W/m$^2$)
  \end{enumerate}

\end{description}

The spectral files are as follows:
\begin{description}
 \item[mc.flx.spc]
   \ifthreedmystic{This is the most versatile and useful irradiance /
     actinic flux output of MYSTIC}:
  \begin{Verbatim}[fontsize=\footnotesize, frame=single, samepage=true]
  400.0 0 0 0 1.0e+00 0.0e+00 1.5067e-01 1.0e+00 0.0e+00 3.5044e-01
  401.0 0 0 0 1.0e+00 0.0e+00 1.5044e-01 1.0e+00 0.0e+00 3.5863e-01
  402.0 0 0 0 1.0e+00 0.0e+00 1.5022e-01 1.0e+00 0.0e+00 3.4755e-01
  \end{Verbatim}

  The columns are:
  \begin{enumerate}
  \item  wavelength [nm]
  \item  ix (0 ... Nx-1)
  \item  iy (0 ... Ny-1)
  \item  iz (0 ... Nz-1)
  \item  direct irradiance
  \item  diffuse downward irradiance
  \item  diffuse upward irradiance
  \item  direct actinic flux
  \item  diffuse downward actinic flux
  \item  diffuse upward actinic flux
  \end{enumerate}
  These numbers are created the same way as the standard {\sl uvspec} output. That
  is, they are multiplied with the extraterrestrial irradiance, corrected for
  Sun-Earth-distance, integrated over wavelength, converted to reflectivity or
  brightness temperature, etc.

 \item[mc.rad.spc]
   \ifthreedmystic{This is the most versatile and useful radiance output of
   MYSTIC}:
  \begin{Verbatim}[fontsize=\footnotesize, frame=single, samepage=true]
  400.0 0 0 0 0.0398276
  401.0 0 0 0 0.0396459
  402.0 0 0 0 0.0398005
  \end{Verbatim}

  The columns are:
  \begin{enumerate}
  \item  wavelength [nm]
  \item  ix (0 ... Nx-1)
  \item  iy (0 ... Ny-1)
  \item  iz (0 ... Nz-1)
  \item  radiance
  \end{enumerate}
  These numbers are created the same way as the standard {\sl uvspec}
  output. That is, they are multiplied with the extraterrestrial irradiance,
  corrected for Sun-Earth-distance, integrated over wavelength, converted to
  reflectivity or brightness temperature, etc.

  If the {\bf polarized} mystic is used (\code{mc\_polarisation}) then the four
  components of the Stokes vector (I,Q,U,V) are output for each wavelength and
  grid point, in four separate lines.

\ifthreedmystic{
 \item[mc.abs.spc]
  \code{mc.abs.spc} contains the absorption per unit area for all layers. This
  file is generated if \code{mc\_forward\_output absorption} or \code{mc\_forward\_output emission} is specified.

  The columns are:
  \begin{enumerate}
  \item  wavelength [nm]
  \item  ix (0 ... Nx-1)
  \item  iy (0 ... Ny-1)
  \item  iz (0 ... Nz-1)
  \item  absorption/emission/heating rate
  \end{enumerate}

  These numbers are created the same way as the standard {\sl uvspec} output. That
  is, they are multiplied with the extraterrestrial irradiance, corrected for
  Sun-Earth-distance, integrated over wavelength, converted to reflectivity or
  brightness temperature, etc.  The unit is determined by an extra option to
  \code{mc\_forward\_output absorption} or \code{mc\_forward\_output emission}.

  For computational efficiency reasons \code{mc.abs.spc} is not provided on the
  sample grid but on the atmospheric grid. For the same reason, results are
  only calculated for 3D layers. In order to obtain 3D absorption for 1D
  cloudless layer, you need to specify an optically very thin 3D cloud, e.g.
  LWC/IWC = 10$^{-20}$ g/m$^3$ (yes, this is a dirty trick but a necessary one).

 \item[mc.act.spc]
  \code{mcNN.act} contains the 4$\pi$ actinic flux in the given layer,
  calculated from the absorbed energy (per unit area) divided by the
  absorption optical thickness of the layer. In contrast to the
  actinic flux in \code{mc.act.flx}, this is a layer quantity the
  accuracy of which is generally much better than the level quantities
  which are calculated from radiance / cos (theta). As for the absorption
  above, \code{mcNN.act} is not provided on the sample grid but on the
  atmospheric grid. NN is the number of the output layer (counted from the
  bottom, starting from 1). This file is generated if \codeidx{mc\_forward\_output actinic} is specified.

  The columns are:
  \begin{enumerate}
  \item  wavelength [nm]
  \item  ix (0 ... Nx-1)
  \item  iy (0 ... Ny-1)
  \item  iz (0 ... Nz-1)
  \item  actinic flux
  \end{enumerate}
}
\end{description}

\ifthreedmystic{
\subsubsection{Memory requirements and computational speed}
\label{sec:mc_memory}

\begin{enumerate}
\item  3D clouds are defined on a 3D grid and the amount of
  memory required by MYSTIC is usually determined by
  the 3D cloud grid. Several variables need to be stored
  for each grid cell, including the optical properties of
  the cell, the grid cell absorption, etc. Umpteen (20-100)
  bytes are typically required for each grid cell.
  Computational time is to a large degree determined by
  the total optical thickness of the cloud because higher
  extinction means more scattering events and a longer
  photon path. To a lesser degree, the computational time
  is influenced by the number of cells but this may become
  important if the radiance is calculated using
  local estimates.

\item 2D albedo requires some memory but usually less than
  clouds because it is defined on a 2D grid compared to the
  3D cloud grid. Only one double (8 bytes on a 32 bit machine)
  is stored per pixel. A high resolution has no influence
  on computational time.

\item 2D elevation requires somewhat more memory than a 2D albedo
  because 5 doubles are stored per pixel. Higher resolution
  will lead to higher computational times.

\item The sample grid by itself has only little influence on
  computational time because for a given number of photons,
  the computational time does not depend on the number of
  grid cells. The precision of the result, however depends
  strongly on the number of grid cells Nx $\cdot$ Ny, as it
  decreases with sqrt(Nx$\cdot$Ny). The number of altitude
  levels has only little influence on the computational
  time but of course a large influence on the memory
  requirements. The calculation of radiances has a large
  impact on computational time if local estimates are used.
  % CE: In current version it is only possible to compute 1 direction at a time
  %In the worst case, the computational time may
  %scale directly with the number of directions for which the
  %radiance is to be calculated.
\end{enumerate}
}


\documentclass[jou]{apa6}

\usepackage[american]{babel}

\usepackage{csquotes}
\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{bibliography.bib}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Discrete Structures
%% The start of RBS stuff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Working internal and external links in PDF
\usepackage{hyperref}
% Extra math symbols in LaTeX
\usepackage{amsmath}
\usepackage{gensymb}
\usepackage{amssymb}
% Enumerations with (a), (b), etc.
\usepackage{enumerate}

\let\OLDitemize\itemize
\renewcommand\itemize{\OLDitemize\addtolength{\itemsep}{-6pt}}

\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=3pt \partopsep=3pt }
\makeatother

% These sizes redefine APA for A4 paper size
\oddsidemargin 0.0in
\evensidemargin 0.0in
\textwidth 6.27in
\headheight 1.0in
\topmargin -24pt
\headheight 12pt
\headsep 12pt
\textheight 9.19in

\usepackage{xcolor}

\title{Sample Quiz 3}
\author{Discrete Structures, Fall 2020}
\affiliation{RBS}

\leftheader{Discrete Sample Quiz 3}

\abstract{%
}

%\keywords{}

\begin{document}

\twocolumn

\section{Worksheet 3: First Order Logic}

\vspace{6pt}
{\bf Question 1.} {\em Definition.} A Boolean formula is a
{\em Conjunctive Normal Form (CNF)},
if it is a conjunction of one or more clauses,
where a clause is a disjunction of literals. Each literal
is either a variable ($u,v,\ldots$) or its negation ($\neg u, \neg v, \ldots$).

Find the CNF computing the following truth table for Boolean
expression $E(a,b,c)$:\\
\begin{tabular}{ c | c | c | c }
$a$ & $b$ & $c$ & $E(a,b,c)$  \\ \hline
{\tt T} & {\tt T} & {\tt T} & {\tt T} \\ \hline
{\tt T} & {\tt T} & {\tt F} & {\tt F} \\ \hline
{\tt T} & {\tt F} & {\tt T} & {\tt F} \\ \hline
{\tt T} & {\tt F} & {\tt F} & {\tt F} \\ \hline
{\tt F} & {\tt T} & {\tt T} & {\tt T} \\ \hline
{\tt F} & {\tt T} & {\tt F} & {\tt F} \\ \hline
{\tt F} & {\tt F} & {\tt T} & {\tt F} \\ \hline
{\tt F} & {\tt F} & {\tt F} & {\tt T} \\ \hline
\end{tabular}

\vspace{6pt}
{\bf Question 2.} The following CNF is given:
$$E = (a \vee \neg c) \wedge (b \vee \neg b).$$
Find $2$ Boolean expressions equivalent to $E$:\\[3pt]
{\bf (A)} $a \rightarrow \neg b$,\\[3pt]
{\bf (B)} $a \rightarrow c$,\\[3pt]
{\bf (C)} $\neg c \rightarrow \neg a$,\\[3pt]
{\bf (D)} $(a \wedge c) \rightarrow b$,\\[3pt]
{\bf (E)} $c \rightarrow a$,\\[3pt]
{\bf (F)} $a \rightarrow (c \rightarrow b)$,\\[3pt]
{\bf (G)} $\neg a \rightarrow \neg c$.

\vspace{6pt}
{\bf Question 3.} We have six statements about Python programs $p \in \mathcal{P}$
that convert inputs $i \in \mathbb{Z}^{+}$ into results $r \in \mathbb{Z}^{+}$.
A Python program may either loop indefinitely or halt (i.e.\ it eventually stops).

\begin{enumerate}
\item Some programs return the correct result for all possible inputs and
they never loop indefinitely.
\item For any program one can find another program such that it returns
the same result for the same inputs as the first one (or loops indefinitely,
{\color{red} \bf iff} the first program does the same).
\item There is a program that only loops indefinitely for at most finitely many inputs (or maybe none at all),
but for all other inputs it produces the correct result.
\item There is at least one Python program that always halts, and for sufficiently large inputs it produces
the correct result, but it may err for some small-size inputs.
\item For a program to produce a correct result for some input $i$ it is strictly necessary to halt.\\
\item A Python program always produces exactly one result for the given input provided that it halts.
\end{enumerate}

We use these $3$ predicates:\\
$A(p_1,i_2,r_3)$ is true iff
Python program $p_1 \in \mathcal{P}$ receives input $i_2 \in \mathbb{Z}^{+}$ and outputs
result $r_3 \in \mathbb{Z}^{+}$.\\
$H(p_1,i_2)$ is true iff program $p_1 \in \mathcal{P}$ receives input $i_2$ and halts (i.e.\ does not
loop indefinitely).\\
$C(i_1,r_2)$ is true iff for input $i_1$ the correct result is $r_2$.

{\em Note.} Write your answer as a comma-separated list: For example,
{\tt F,E,D,C,B,A} tells that the 1st statement is {\bf (F)}, the 2nd one
is {\bf (E)}, $\ldots$, the last one is {\bf (A)}.

\begin{enumerate}[(A)]
\item ${\displaystyle \forall p \in \mathcal{P}\; \forall i \in \mathbb{Z}^+\; \forall r \in \mathbb{Z}^+,}$\\
${\displaystyle \left( A(p,i,r) \wedge C(i,r) \,\rightarrow\, H(p,i) \right) }$.
\item ${\displaystyle \forall p_1 \in \mathcal{P}\; \exists p_2 \in \mathcal{P}\;
\forall i \in \mathbb{Z}^{+}\; \textcolor{red}{\forall r \in \mathbb{Z}^{+},}}$\\
${\displaystyle \left( (\neg H(p_1,i) \wedge \neg H(p_2,i)) \vee
(A(p_1,i,r) \leftrightarrow A(p_2,i,r)) \right)}$
\item ${\displaystyle \exists p \in \mathcal{P}\; \exists N \in \mathbb{Z}^{+}\;
\forall i \in \mathbb{Z}^{+}\; \textcolor{red}{\exists r \in \mathbb{Z}^{+}},}$\\
${\displaystyle \left( ( i \leq N \wedge \neg H(p,i) ) \vee (A(p,i,r) \wedge C(i,r)) \right)}$.
\item ${\displaystyle \forall p \in \mathcal{P}\; \forall i \in \mathbb{Z}^{+}\; \forall r_1 \in \mathbb{Z}^{+}\;
\forall r_2 \in \mathbb{Z}^{+},}$\\
${\displaystyle \left( H(p,i) \wedge A(p,i,r_1) \wedge  A(p,i,r_2) \,\rightarrow\, r_1 = r_2 \right)}$.
\item ${\displaystyle \exists p \in \mathcal{P}\; \exists N \in \mathbb{Z}^{+}\; \forall i \in \mathbb{Z}^{+}\;
\textcolor{red}{\forall r \in \mathbb{Z}^{+}},}$\\
${\displaystyle \left( H(p,i) \,\wedge\, ( A(p,i,r) \wedge (i > N) \,\rightarrow\, C(i,r) ) \right)}$.
\item ${\displaystyle \exists p \in \mathcal{P}\; \forall i \in \mathbb{Z}^{+}\; \forall r \in \mathbb{Z}^{+},}$\\
${\displaystyle \left( H(p,i) \,\wedge\, (A(p,i,r) \rightarrow C(i,r) \right)}$.
\end{enumerate}

\vspace{10pt}
{\bf Question 4.} There is a set of $4$ students $S = \{ s_1, s_2, s_3, s_4 \}$ and
a set of $2$ chairs $C = \{ c_1, c_2 \}$.
Find, how many such functions $f\,:\,S \rightarrow C$ exist,
how many of them are injective, surjective and bijective.\\
{\em Note.} Your answer should be a comma-separated list of
4 numbers (and 3 commas): {\tt total,injective,surjective,bijective}.

\vspace{10pt}
{\bf Question 5.}
There is a predicate $S(x, y, z)$ defined for triplets
of positive integers,
$S: \mathbb{Z}^{+} \times \mathbb{Z}^{+} \times \mathbb{Z}^{+} \rightarrow \{ \mathtt{T}, \mathtt{F} \}$.
$S(x,y,z)$ is true iff $x \cdot y = z$.\\
Express these statements about positive integers
using only $S(x,y,z)$, Boolean operations and quantifiers.\\
{\em Note.} Please use only the predicate $S(\ldots)$ in your answers,
avoid any other predicates or relations (such as equality, divisibility, etc.).

\begin{enumerate}[(A)]
\item $x/y = z$,
\item $x = 1$,
\item $x = y$,
\item $x$ is divisible by $y$ (i.e. $y \,\mid\, x$).
\item $x$ has odd number of positive divisors.
\item $x$ is not a prime.
\item $x$ is a prime.
\end{enumerate}

\subsection{Answers}

\vspace{6pt}
{\bf Question 1.} Answer:
\begin{align}
 & \textcolor{red}{(\neg a \vee \neg b \vee c)} \wedge
\textcolor{blue}{(\neg a \vee b \vee \neg c)} \wedge
\textcolor{blue}{(\neg a \vee b \vee c)} \;\wedge \nonumber \\
\wedge\; & \textcolor{red}{(a \vee \neg b \vee c)} \wedge
(a \vee b \vee \neg c) \nonumber
\end{align}
Every value {\tt F} in the truth table produces one
clause in this expression. For example $E(\mathtt{T},\mathtt{T},\mathtt{F}) = \mathtt{F}$
is addressed by a disjunction $(\neg a \vee \neg b \vee c)$.

If we combine red and blue clauses, we can rewrite this into a more compact expression,
which is also CNF. Note, that this is not the only way to rewrite:
$$\textcolor{red}{(\neg b \vee c)} \wedge
\textcolor{blue}{(\neg a \vee b)} \wedge
(a \vee b \vee \neg c).$$

\vspace{6pt}
{\bf Question 2.} Answer: {\bf (E)}, {\bf (G)}.\\
$(a \vee \neg c) \wedge (b \vee \neg b) = (a \vee \neg c) \wedge \mathtt{T} = (a \vee \neg c)$.
This is same as $c \rightarrow a$ or the contrapositive variant of the same implication:
$\neg a \rightarrow \neg c$.

\vspace{6pt}
{\bf Question 3.} Answer:\\
\begin{tabular}{|c|c|c|c|c|c|} \hline
1 & 2 & 3 & 4 & 5 & 6 \\ \hline
{\bf (F)} & {\bf (B)} & {\bf (C)} & {\bf (E)} & {\bf (A)} & {\bf (D)} \\ \hline
\end{tabular}

\vspace{3pt}
In {\bf (B)} we should write: the second program loops indefinitely {\bf iff}
the first program does so. If we write {\bf if} instead, it
would mean only one-way conditional, which does not mean
equivalence between the programs $p_1$ and $p_2$, but something more complicated.

In {\bf (B)} you could write $(H(p_1,i) \leftrightarrow H(p_2,i))$
instead of $(\neg H(p_1,i) \wedge \neg H(p_2,i))$ or
even omit any reference to $H(\ldots)$ predicates.
The notation $(H(p_1,i) \leftrightarrow H(p_2,i))$ stresses the fact that $p_1$ and $p_2$ behave in the same way.
But in fact the equivalence $(A(p_1,i,r) \leftrightarrow A(p_2,i,r))$ implicitly
states the fact that $p_1$ and $p_2$ are defined on the same inputs.

Please note that {\bf (B)} should {\bf NOT} have quantifier
 $\textcolor{red}{\exists r \in \mathbb{Z}^{+}}$
(instead of  $\textcolor{red}{\forall r \in \mathbb{Z}^{+}}$), because we need
equivalence for all positive integers $r$. If we only care about the
actual result of $p$ on input $i$, then it is possible to ``cheat'' the logic formula:
pick result $r$ which is impossible for both $p_1$ and $p_2$; then $A(p_1,i,r)$
and $A(p_2,i,r)$ would both be false (and thus equivalent).

In {\bf (C)} one cannot replace $\textcolor{red}{\exists r \in \mathbb{Z}^{+}}$
with $\textcolor{red}{\forall r \in \mathbb{Z}^{+}}$ (as in an earlier draft of this test),
because it does not make sense to ask that a program $p$ on input $i$ produces
{\bf each} positive integer result; and all results turn out to be correct.
(Such a formula may have some useful meaning if predicates $A,H,C$ have different
interpretations, but for Python programs this is technically correct, but
has an absurd meaning: that a given program produces any result whatsoever.)

In {\bf (E)} it is absolutely necessary to write a quantifier
$\textcolor{red}{\forall r \in \mathbb{Z}^{+}}$, because
leaving $r$ as a free variable (without a quantifier) would
mean that the Python program always produces the same result
(the value of $r$). It is not

\vspace{6pt}
{\bf Question 4.} Answer: {\tt 16,0,14,0}\\
Please note that there can be no injections (and therefore also bijections):
students will always collide \textendash{} run to the same chair,
since there are fewer chairs than students.

The total number of functions is $2^4 = 16$. Each student
can choose between $2$ chairs, so it is $2 \times 2 \times 2 \times 2 = 16$.
Moreover, there are only $2$ ``constant'' functions (where all four
students go to $c_1$ or to $c_2$). They are not surjective, because
some chairs stay unoccupied in this case.
All the other $16 - 2 = 14$ functions from $S$ (4 elements) to $C$ (2 elements)
are surjections.

\vspace{6pt}
{\bf Question 5.} Here we write all $7$ statements with predicate $S(x,y,z)$ and quantifiers.

\begin{enumerate}[(A)]
\item $S(z,y,x)$ (or, equivalently, $S(y,z,x)$).
\item $\exists y \in \mathbb{Z}^{+},\; S(x,y,y)$.\\
Use the property: $x = 1$ can multiply with an $y$, and does not increase/decrease. \\
You could also write simply $S(x,x,x)$. Indeed, $x$ is the only
positive integer such that $x \cdot x = x$. (Allowing $x = 0$ would
spoil this, because $0^2 = 0$.)
\item $\exists z \in \mathbb{Z}^{+},\; S(x,z,y) \wedge S(z,z,z)$.\\
So, $x = y$ iff there is a $z = 1$ such that $x \cdot z = y$.
\item $\exists d \in \mathbb{Z}^{+},\; S(y,d,x)$.
\item $\exists y \in \mathbb{Z}^{+},\; S(y,y,x)$.\\
This means that $y^2 = x$ for some $y$;
hence $x$ is a full square and should have odd number of divisors.
\item $\exists y \in \mathbb{Z}^{+}\;\exists z \in \mathbb{Z}^{+},\;(S(y,z,x) \wedge \neg S(y,y,y) \wedge \neg S(z,z,z))$.\\
This means that a non-prime $x$ can be expressed as a product of two positive integers $y,z$,
where neither of them is $1$.)
\item $\forall y \in \mathbb{Z}^{+}\;\forall z \in \mathbb{Z}^{+},\;(\neg S(y,z,x) \vee S(y,y,y) \vee S(z,z,z))$.\\
We apply negation to the previous quantifier formula; all $\exists$ quantifiers turn into $\forall$;
formulas are changed according to De Morgan's laws.
\end{enumerate}

\end{document}