% Bibliography
\clearpage
\addcontentsline{toc}{chapter}{Bibliografia}
{\footnotesize \bibliographystyle{plain}
\renewcommand{\bibname}{Bibliografia}

\begin{thebibliography}{99}

\bibitem{Abramovich2002}
    Abramovich, Y.\,A., Aliprantis, C.\,D.,
    \emph{Problems in operator theory},
    American Mathematical Society, Rhode Island 2002.

\bibitem{adesso2007entanglement}
    Adesso, G., Illuminati, F.,
    Entanglement in continuous-variable systems: recent advances and current perspectives,
    \emph{J. Phys. A: Math. Gen.} {\bf 40} (2007), 7821.

\bibitem{araki1968classification}
    Araki, H., Woods, E.\,J.,
    A classification of factors,
    \emph{Publ. Res. I. Math. Sci.} {\bf 4} (1968), 51.

\bibitem{besenyei2011completely}
    Besenyei, {\'A}., Petz, D.,
    Completely positive mappings and mean matrices,
    \emph{Linear Algebra Appl.} {\bf 435} (2011), 984.

\bibitem{Blackadar2006}
    Blackadar, B., \emph{Operator Algebras: Theory of C*-algebras and von Neumann Algebras},
    Springer, Berlin Heidelberg New York 2006.

\bibitem{bourennane2004experimental}
    Bourennane, M., \emph{et al.},
    Experimental detection of multipartite entanglement using witness operators,
    \emph{Phys. Rev. Lett.} {\bf 92} (2004), 87902.

\bibitem{Bratteli2003}
    Bratteli, O., Robinson, D.\,W.,
    \emph{Operator Algebras and Quantum Statistical \mbox{Mechanics 1:} C*- and W*-Algebras. Symmetry Groups. Decomposition of States},
    Springer, Berlin Heidelberg New York 2003.

\bibitem{Brown2008}
    Brown, N.\,P., Ozawa, N.,
    \emph{C*-Algebras and Finite-Dimensional Approximations},
    American Mathematical Society, Rhode Island 2008.

\bibitem{choi1975completely}
    Choi, M.-D.,
    Completely positive linear maps on complex matrices,
    \emph{Linear Algebra Appl.} {\bf 10} (1975), 285.

\bibitem{choi1975positive}
    Choi, M.-D.,
    Positive semidefinite biquadratic forms,
    \emph{Linear Algebra Appl.} {\bf 12} (1975), 95.

\bibitem{choi1980some}
    Choi, M.-D.,
    Some assorted inequalities for positive linear maps on C*-algebras,
    \emph{J. Operat. Theor.} {\bf 4} (1980), 271.

\bibitem{choi1977extremal}
    Choi, M.-D., Lam, T.-Y.,
    Extremal positive semidefinite forms,
    \emph{Math. Ann.} {\bf 231} (1977), 1.

\bibitem{chow1975compact}
    Chow, H.\,L.,
    On compact affine semigroups,
    \emph{Semigroup Forum} {\bf 11} (1975), 146.

%\bibitem{chruscinski2011exposed}
%    Chru{\'s}ci{\'n}ski, D., Sarbicki, G.,
%    Exposed positive maps: a sufficient condition,
%    \emph{arXiv preprint} (2012), arXiv:1111.2012.

%\bibitem{Dixmier1981}
%    Dixmier, J., Jellet, F.,
%    \emph{von Neumann algebras}, North-Holland Publishing Company, New York 1981.

\bibitem{Effros2000}
    Effros, E.\,G., Ruan, Z.-J., \emph{Operator Spaces}, Clarendon Press, Oxford 2000.

\bibitem{einstein1935can}
    Einstein, A., \emph{et al.},
    Can quantum-mechanical description of physical reality be considered complete?,
    \emph{Phys. Rev.} {\bf 47} (1935), 777.

\bibitem{Evans1998}
    Evans, D.\,E., Kawahigashi, Y.,
    \emph{Quantum Symmetries on Operator Algebras}, Clarendon Press, Oxford 1998.

\bibitem{goyal2011geometry}
    Goyal, S.\,K. \emph{et al.},
    Geometry of the generalized Bloch sphere for qutrit,
    \emph{arXiv preprint} (2011), arXiv:1111.4427.

\bibitem{ha1998atomic}
    Ha, K.-C.,
    Atomic positive linear maps in matrix algebras,
    \emph{Publ. Res. I. Math. Sci.} {\bf 34} (1998), 591.

\bibitem{ha2011entanglement}
    Ha, K.-C., Kye, S.-H.,
    Entanglement witnesses arising from exposed positive linear maps,
    \emph{Open Syst. Inf. Dyn.} {\bf 18} (2011), 323.

\bibitem{horodecki1996separability}
      Horodecki, M., \emph{et al.},
      Separability of mixed states: necessary and sufficient conditions,
      \emph{Phys. Lett. A} {\bf 223} (1996), 1.

\bibitem{horodecki2009quantum}
    Horodecki, R., \emph{et al.},
    Quantum entanglement,
    \emph{Rev. Mod. Phys.} {\bf 81} (2009), 865.

\bibitem{jamiolkowski1974effective}
      Jamio{\l}kowski, A.,
      An effective method of investigation of positive maps on the set of positive definite operators,
      \emph{Rep. Math. Phys.} {\bf 5} (1974), 415.

\bibitem{jamiolkowski1972linear}
    Jamio{\l}kowski, A.,
    Linear transformations which preserve trace and positive semidefiniteness of operators,
    \emph{Rep. Math. Phys.} {\bf 3} (1972), 275.

\bibitem{kadison1952generalized}
    Kadison, R.\,V.,
    A generalized Schwarz inequality and algebraic invariants for operator algebras,
    \emph{The Annals of Mathematics} {\bf 56} (1952), 494.

\bibitem{kye1995positive}
    Kye, S.-H.,
    Positive linear maps between matrix algebras which fix diagonals,
    \emph{Linear Algebra Appl.} {\bf 216} (1995), 239.

\bibitem{landau1993birkhoff}
    Landau, L.\,J., Streater, R.\,F.,
    On Birkhoff's theorem for doubly stochastic completely positive maps of matrix algebras,
    \emph{Linear Algebra Appl.} {\bf 196} (1993), 107.

\bibitem{leinaas2006geometrical}
    Leinaas, J.\,M., \emph{et al.},
    Geometrical aspects of entanglement,
    \emph{Phys. Rev. A} {\bf 74} (2006), 12313.

\bibitem{loewy1975positive}
    Loewy, R., Schneider, H.,
    Positive operators on the n-dimensional ice cream cone,
    \emph{J.Math. Anal. App.} {\bf 49} (1975), 375.

\bibitem{marciniak2008extremal}
    Marciniak, M.,
    On extremal positive maps acting between type I factors,
    \emph{Banach Center Publications} {\bf 89} (2010), 201.

\bibitem{miller2015extremal}
    Miller, M., Olkiewicz, R.,
    Extremal positive maps on $M_{3}(\mathbb{C})$ and idempotent matrices,
    \emph{arXiv preprint} (2015), arXiv:1510.04920.

\bibitem{miller2014horodeckis}
    Miller, M., Olkiewicz, R.,
    Horodeckis criterion of separability of mixed states in von Neumann and C*-algebras,
    \emph{Infin. Dimens. Anal. Qu.} {\bf 17} (2014), 1450028.

\bibitem{miller2015stable}
    Miller, M., Olkiewicz, R.,
    Stable subspaces of positive maps of matrix algebras,
    \emph{Open Syst. Inf. Dyn.} {\bf 22} (2015), 1550011.

\bibitem{miller2015topology}
    Miller, M., Olkiewicz, R.,
    Topology of the cone of positive maps on qubit systems,
    \emph{J. Phys. A: Math. Theor.} {\bf 48} (2015), 255203.

\bibitem{miranda1994group}
    Miranda, H.\,F.,Thompson, R.\,C.,
    Group majorization, the convex hulls of sets of matrices, and the diagonal element-singular value inequalities,
    \emph{Linear Algebra Appl.} {\bf 199} (1994), 131.

\bibitem{modi2010unified}
    Modi, K. \emph{et al.},
    Unified view of quantum and classical correlations,
    \emph{Phys. Rev. Lett.} {\bf 104} (2010), 80501.

\bibitem{Nielsen2010}
    Nielsen, M.\,A., Chuang, I.\,L.,
    \emph{Quantum Computation and Quantum Information},
    Cambridge University Press, Cambridge 2010.

\bibitem{Hanche1984}
    Hanche-Olsen, H., St{\o}rmer, E., \emph{Jordan Operator Algebras},
    Pitman, London 1984.

\bibitem{Naber1992}
    Naber, G.\,L.,
    \emph{The Geometry of Minkowski Spacetime: An Introduction to the Mathematics of the Special Theory of Relativity},
    Springer, New York Dordrecht Heidelberg London 2012.

\bibitem{olkiewicz1999environment}
    Olkiewicz, R.,
    Environment-induced superselection rules in Markovian regime,
    \emph{Commun. Math. Phys.} {\bf 208} (1999), 245.

\bibitem{ollivier2001quantum}
    Ollivier, H., Zurek, W.\,H.,
    Quantum discord: a measure of the quantumness of correlations,
    \emph{Phys. Rev. Lett.} {\bf 88} (2001), 17901.

\bibitem{peres1996separability}
    Peres, A.
    Separability criterion for density matrices,
    \emph{Phys. Rev. Lett.} {\bf 77} (1996), 1413.

\bibitem{robertson1983schwarz}
    Robertson, A.\,G.,
    Schwarz inequalities and the decomposition of positive maps on C*-algebras,
    [w:] \emph{Mathematical Proceedings of the Cambridge Philosophical Society}
    {\bf 94} (1983), 291.

\bibitem{Rudin1991}
    Rudin, W.,
    \emph{Functional analysis},
    McGraw-Hill, New York 1991.

\bibitem{rutkowski2015class}
    Rutkowski, A., \emph{et al.},
    A class of bistochastic positive optimal maps in $M_{d}(\mathbb{C})$,
    \emph{arXiv preprint} (2015), arXiv:1505.07854.

\bibitem{Ryan2002}
    Ryan, R., \emph{Introduction to Tensor Products of Banach Spaces},
    Springer, Berlin Heidelberg New York 2002.

\bibitem{schrodinger1935gegenwartige}
    Schr{\"o}dinger, E.,
    Die gegenw{\"a}rtige Situation in der Quantenmechanik,
    \emph{Naturwissenschaften} {\bf 23} (1935), 823.

\bibitem{schwarz1955hausdorff}
    Schwarz, S.,
    On Hausdorff bicompact semigroups,
    \emph{Czechoslovak Math. J.} {\bf 5} (1955), 1.

\bibitem{stinespring1955positive}
    Stinespring, W.\,F.,
    Positive functions on C*-algebras,
    \emph{P. Am. Math. Soc.} {\bf 6} (1955), 211.

\bibitem{stormer2013decomposition}
    St{\o}rmer, E.,
    A decomposition theorem for positive maps, and the projection onto a spin factor,
    \emph{arXiv preprint} (2013), arXiv:1308.3332.

\bibitem{stormer1963positive}
    St{\o}rmer, E.,
    Positive linear maps of operator algebras,
    \emph{Acta Mathematica} {\bf 110} (1963), 233.

\bibitem{Stormer2013}
    St{\o}rmer, E.,
    \emph{Positive Linear Maps of Operator Algebras},
    Springer, Berlin Heidelberg New York 2013.

\bibitem{stormer2008separable}
    St{\o}rmer, E.,
    Separable states and positive maps,
    \emph{J. Funct. Anal.} {\bf 254} (2008), 2303.

\bibitem{stormer2009separable}
    St{\o}rmer, E.,
    Separable states and positive maps II,
    \emph{Math. Scand.} {\bf 105} (2009), 188.

\bibitem{straszewicz1935exponierte}
    Straszewicz, S.,
    {\"U}ber exponierte Punkte abgeschlossener Punktmengen,
    \emph{Fund. Math.} {\bf 24} (1935), 139.

\bibitem{Takesaki1}
    Masamichi, T., \emph{Theory of Operator Algebras}, t.\,1, Springer, Berlin Heidelberg New York 2003.

\bibitem{Takesaki2}
    Masamichi, T., \emph{Theory of Operator Algebras}, t.\,2, Springer, Berlin Heidelberg New York 2003.

\bibitem{Takesaki3}
    Masamichi, T., \emph{Theory of Operator Algebras}, t.\,3, Springer, Berlin Heidelberg New York 2003.

\bibitem{werner1989quantum}
    Werner, R.\,F.,
    Quantum states with Einstein-Podolsky-Rosen correlations admitting a hidden-variable model,
    \emph{Phys. Rev. A} {\bf 40} (1989), 4277.

\bibitem{woronowicz1976positive}
    Woronowicz, S.\,L.,
    Positive maps of low dimensional matrix algebras,
    \emph{Rep. Math. Phys.} {\bf 10} (1976), 165.

\bibitem{yngwason2005role}
    Yngvason, J.,
    The role of type III factors in quantum field theory,
    \emph{Rep. Math. Phys.} {\bf 55} (2005), 135.

\bibitem{Zhang2006}
    Zhang, F.,
    \emph{The Schur Complement and its Applications},
    Springer, Berlin Heidelberg New York 2006.

\end{thebibliography}

% Add a second set of references, if you wish...
%\renewcommand{\bibname}{Bibliografia 2}
%\begin{thebibliography}{99}
%
%\end{thebibliography}

% Print index and add to the table of content
%\chapter*{}
%\clearpage
%\addcontentsline{toc}{chapter}{Indeksy}
%\printindex{sym}{Indeks symboli}
%\printindex{idx}{Skorowidz}


\section{Discussion}

In this paper, we have presented a universe of datatypes for a
dependent type theory. We started from an unremarkable type theory
with dependent functions and tuples, but relying on few other
assumptions, especially where propositional equality is concerned.  We
added finite enumeration sufficient to account for constructor choice,
and then we built coding systems, first (as a learning experience) for
simple ML-like inductive types, then for the indexed inductive
families which dependently typed programmers in Agda, Coq and Epigram
take for granted. We adopt a bidirectional type propagation mechanism
to conceal artifacts of the encoding, giving a familiar and practicable
constructor-based presentation to data.

Crucially to our approach, we ensure that the codes describing
datatypes inhabit a datatype with a code. In a stratified setting, we
avoid paradox by ensuring that this type of codes lives uniformly one
level above the types the codes describe. The adoption of ordinary
data to describe types admits datatype-generic operations implemented
just by ordinary programming. In working this way, we make
considerable use of type equality modulo open computation, silently
specialising the types of generic operations as far as the datatype
code for any given usage is known.

\subsection{Related work in Generic Programming}

\begin{wstructure}
!!! Need Help !!!
<- Comparison with Induction Recursion
    ???
\end{wstructure}

\begin{wstructure}
!!! Need Help !!!
<- Related Work
    <- Generic in simply-typed functional languages
        <- PolyP \cite{jansson:polyp}
        <- Generic Haskell \cite{hinze:generic-haskell}
        <- Scratch your boilerplate \cite{spj:syb}
\end{wstructure}

Generic programming is a vast topic. We refer our reader to
\citet{garcia:generic-comparative-study} for a broad overview of
generic programming in various languages. For Haskell alone, there is
a myriad of proposals:
\citet{hinze:generic-approach-comparative} and
\citet{rodriguez:generic-libs-comparative} provide useful comparative
surveys.

Our approach follows the polytypic programming style, as initiated
by PolyP~\cite{jansson:polyp}. Indeed, we build generic functions by
induction on pattern functors, exploiting type-level computation
to avoid the preprocessing phase: our
datatypes are, natively, nothing but codes.

We have the \emph{type-indexed datatypes} of Generic
Haskell~\cite{hinze:generic-haskell} for free.
From one datatype, we can compute
others and equip them with relevant structure: the free monad
construction provides one example. Our approach to encoding datatypes
as data also sustains \emph{generic
  views}~\cite{holdermans:generic-view}, allowing us to rebias the
presentation of datatypes conveniently. Tagged descriptions,
giving us a sum-of-sigmas view, are a natural example.

Unlike Generic Haskell, we do not support polykinded
programming~\cite{hinze:polytypic-polykinded}. Our descriptions are
limited to endofunctors on $\Set^I$. Whilst indexing is known
to be sufficient to \emph{encode} a large class of higher-kinded
datatypes~\citep{DBLP:conf/ifip2-1/AltenkirchM02}, we should rather
hope to work in a more compositional style. We are free to write
higher-order programs manipulating codes, but is not yet clear whether
that is sufficient to deliver abstraction at higher kinds.
Similarly, it will be interesting to see whether
arity-generic programming~\cite{weirich:arity-generic} arises
just by computing with our codes, or whether a richer abstraction is
called for.

The Scrap Your Boilerplate~\cite{spj:syb} (SYB) approach to generic
programming offers a way to construct generic functions, based on
dynamic type-testing via the $\CN{Typeable}$
type class. SYB cannot compute types from codes, but its dynamic character
does allow a more flexible \emph{ad hoc} approach to generic data
traversal. By maintaining the correspondence between codes and types
whilst supporting arbitrary inspection of codes, we pursue the same
flexibility statically. The substitutive character of $\SYMBIDesc$
may allow us to observe and exploit \emph{ad hoc} substructural
relationships in data, but again, further work is needed if we
are to make a proper comparison.

\begin{wstructure}
    <- Generic in dependent types
        <- Norell \cite{norell:msc-thesis}
        <- Polytypic prog in Coq \cite{verbruggen:polytype-coq}
        <- Universes for generic prog \cite{benke:universe-generic-prog}
\end{wstructure}

\subsection{Generic Programming with Dependent Types}

Generic programming is not new to dependent
types. \citet{DBLP:conf/ifip2-1/AltenkirchM02} developed a universe
of polykinded types in Lego;
\citet{norell:msc-thesis} gave a formalisation of
polytypic programming in Alfa, a precursor to Agda;
\citet{verbruggen:polytype-prog-coq, verbruggen:polytype-coq} provided
a framework for polytypic programming in the Coq theorem
prover. However, these works aim at \emph{modelling} PolyP or Generic
Haskell in a dependently-typed setting for the purpose of proving
correctness properties of Haskell code. Our approach is different in
that we aim at building a foundation for datatypes, in a
dependently-typed system, for a dependently-typed system.

Closer to us is the work of \citet{benke:universe-generic-prog}. This
seminal work introduced the usage of universes for developing generic
programs. Our universes share similarities to theirs: our universe of
descriptions is similar to their universe of iterated induction, and
our universe of indexed descriptions is equivalent to their universe
of finitary indexed induction. This is not surprising, as we share the
same source of inspiration, namely induction-recursion.

However, we feel ready to offer a more radical prospectus. Their
approach is generative: each universe extends the base type theory
with both type formers and elimination rules. Thanks to levitation, we
rely only on a generic induction and a specialised $\SYMBswitchD$,
closing the type theory. We explore \emph{programming} with codes, but
also how to conceal the encoding when writing `ordinary' programs.

\subsection{Metatheoretical Status}

The \(\Set:\Set\) approach we have taken in this paper is convenient
from an experimental perspective, and it has allowed us to focus
primarily on the encoding of universes, leaving the question
of stratification (and with it, consistency, totality,
and decidability of type checking) to one side. However, we must
surely face up to the latter, especially since we have taken up the
habit of constructing `the set of all sets'. A proper account requires
a concrete proposal for a system of stratified universes which allows
us to make `level-polymorphic' constructions, and we are actively
pursuing such a proposal. We hope soon to have something to prove.

In the meantime, we can gain some confidence by systematically
embedding predicative fragments of our theory within
systems which already offer a universe hierarchy. We can, at the
very least, confirm that in UTT-style theories with conventional
inductive families of types~\citep{luo:utt}, as found in Coq
(and in Agda if one avoids experimental extensions), we build the
tower of universes we propose, cut off at an arbitrary height.
It is correspondingly clear that some such system can be made to
work, or else that other, longer-standing tools are troubled.

A metatheoretical issue open at time of writing concerns the
size of the \emph{index} set \(\V{I}\) in \(\IDesc{\V{I}}\). Both Agda
and recent versions of Coq allow inductive families with \emph{large}
indices, effectively allowing `higher-kind' fixpoints on
\(\Set^{\Set}\) and more. They retain the safeguard that the types of
\emph{substructures} must be as small as the inductively
defined superstructure. This liberalisation allows us large index sets
in our models, but whilst it offers no obvious route to paradox by
smuggling a large universe inside a small type, it is not yet known
to be safe. We can restrict \(\V{I}\) as necessary to avoid
paradox, provided \(\Unit\), used to index \(\SYMBIDesc\) itself, is
`small'.

\subsection{Further Work}

Apart from the need to nail down a stratified version of the system and
its metatheory, we face plenty of further problems and opportunities.
Although we have certainly covered Luo's criteria for inductive
families~\cite{luo:utt}, there are several dimensions in which to
consider expanding our universe.

Firstly, we seek to encompass
\emph{inductive-recursive} datatype families~\cite{dybjer:iir}, allowing
us to interleave the definition and interpretation of data in intricate
and powerful ways. This interleaving seems particularly useful when
reflecting the syntax of dependent type systems.

Secondly, we should very much like to extend our
universe with a codes for internal fixpoints, as
in~\cite{DBLP:conf/types/MorrisAM04}. The external knot-tying
approach we have taken here makes types like `trees with lists of subtrees'
more trouble than they should be. Moreover, if we allow the alternation
of least and greatest fixpoints, we should expect to gain types which are
not readily encoded with one external \(\SYMBIMu\).

Thirdly, it would be fascinating to extend our universe with dedicated
support for syntax with \emph{binding}, not least because a universe
with internal fixpoints has such a syntax. Harper and Licata have
demonstrated the potential for and of such an
encoding~\citep{DBLP:conf/icfp/LicataH09}, boldly encoding the invalid
definitions along with the valid. A more conservative strategy might
be to offer improved support for datatypes indexed by an extensible
context of free variables, with the associated free monad structure
avoiding capture as shown by~\citet{altenkirch:monadic-lambda}.

Lastly, we must ask how our new presentation of datatypes
should affect the tools we use to build software. It is not enough to
change the game: we must enable better play. If datatypes are data,
what is design?


\XtoCBlock{RateLimiter}
\label{block:RateLimiter}
\begin{figure}[H]\includegraphics{RateLimiter}\end{figure}

\begin{XtoCtabular}{Inports}
In & \tabularnewline
\hline
Init & Value which is loaded at rising flanke of enable signal\tabularnewline
\hline
Enable & Enable == 0: Deactivation of block; Out is set to In.

Enable != 0: Activation of block; Out is rate limited.

Enable 0->1: Preloading of output; Out is set to value of Init input\tabularnewline
\hline
\end{XtoCtabular}

\begin{XtoCtabular}{Outports}
Out & \tabularnewline
\hline
\end{XtoCtabular}

\begin{XtoCtabular}{Mask Parameters}
Tr & Rising time in seconds. Slew rate will be 1/Tr\tabularnewline
\hline
Tf & Falling time in seconds. Slew rate will be 1/Tf\tabularnewline
\hline
ts\_fact & Multiplication factor of base sampling time (in integer format)\tabularnewline
\hline
\end{XtoCtabular}

\subsubsection*{Description:}
Limitation of rising and falling rate.

    Function of Enable:

        0:       rate limiting disabled, signal is passed through

        1:       rate limiting enabled, signal is rate limited

        0->1: preload of output with value from init input

% include optional documentation file
\InputIfFileExists{\XcHomePath/Library/General/Doc/RateLimiter_Info.tex}{\vspace{1ex}}{}

\subsubsection*{Implementations:}
\begin{tabular}{l l}
\textbf{FiP8} & 8 Bit Fixed Point Implementation\tabularnewline
\textbf{FiP16} & 16 Bit Fixed Point Implementation\tabularnewline
\textbf{FiP32} & 32 Bit Fixed Point Implementation\tabularnewline
\textbf{Float32} & 32 Bit Floating Point Implementation\tabularnewline
\textbf{Float64} & 64 Bit Floating Point Implementation\tabularnewline
\end{tabular}

\XtoCImplementation{FiP8}
\index{Block ID!96}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP8 \tabularnewline
\textbf{ID} & 96 \tabularnewline
\textbf{Revision} & 1.0 \tabularnewline
\textbf{C filename} & RateLimiter\_FiP8.c \tabularnewline
\textbf{H filename} & RateLimiter\_FiP8.h \tabularnewline
\end{tabular}
\vspace{1ex}

8 Bit Fixed Point Implementation

\begin{XtoCtabular}{Controller Parameters}
RateUp & Rising time parameter\tabularnewline
\hline
RateDown & Falling time parameter\tabularnewline
\hline
out\_old & Output value from last cycle in int16 format\tabularnewline
\hline
enable\_old & Enable value from last cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int8          *In;
     int8          *Init;
     int8          *Enable;
     int8          Out;
     int16         RateUp;
     int16         RateDown;
     int16         out_old;
     int8          enable_old;
} RATELIMITER_FIP8;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/General/Doc/Test_RateLimiter_FiP8.tex}{}{}
\fi
\XtoCImplementation{FiP16}
\index{Block ID!97}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP16 \tabularnewline
\textbf{ID} & 97 \tabularnewline
\textbf{Revision} & 1.0 \tabularnewline
\textbf{C filename} & RateLimiter\_FiP16.c \tabularnewline
\textbf{H filename} & RateLimiter\_FiP16.h \tabularnewline
\end{tabular}
\vspace{1ex}

16 Bit Fixed Point Implementation

\begin{XtoCtabular}{Controller Parameters}
RateUp & Rising time parameter\tabularnewline
\hline
RateDown & Falling time parameter\tabularnewline
\hline
out\_old & Output value from last cycle in int32 format\tabularnewline
\hline
enable\_old & Enable value from last cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int16         *In;
     int16         *Init;
     int8          *Enable;
     int16         Out;
     int32         RateUp;
     int32         RateDown;
     int32         out_old;
     int8          enable_old;
} RATELIMITER_FIP16;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/General/Doc/Test_RateLimiter_FiP16.tex}{}{}
\fi
\XtoCImplementation{FiP32}
\index{Block ID!98}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & FiP32 \tabularnewline
\textbf{ID} & 98 \tabularnewline
\textbf{Revision} & 1.0 \tabularnewline
\textbf{C filename} & RateLimiter\_FiP32.c \tabularnewline
\textbf{H filename} & RateLimiter\_FiP32.h \tabularnewline
\end{tabular}
\vspace{1ex}

32 Bit Fixed Point Implementation

\begin{XtoCtabular}{Controller Parameters}
RateUp & Rising time parameter\tabularnewline
\hline
RateDown & Falling time parameter\tabularnewline
\hline
enable\_old & Enable value from last cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     int32         *In;
     int32         *Init;
     int8          *Enable;
     int32         Out;
     int32         RateUp;
     int32         RateDown;
     int8          enable_old;
} RATELIMITER_FIP32;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/General/Doc/Test_RateLimiter_FiP32.tex}{}{}
\fi
\XtoCImplementation{Float32}
\index{Block ID!99}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & Float32 \tabularnewline
\textbf{ID} & 99 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & RateLimiter\_Float32.c \tabularnewline
\textbf{H filename} & RateLimiter\_Float32.h \tabularnewline
\end{tabular}
\vspace{1ex}

32 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
RateUp & Rising time parameter\tabularnewline
\hline
RateDown & Falling time parameter\tabularnewline
\hline
enable\_old & Enable value from last cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     float32       *In;
     float32       *Init;
     int8          *Enable;
     float32       Out;
     float32       RateUp;
     float32       RateDown;
     int8          enable_old;
} RATELIMITER_FLOAT32;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/General/Doc/Test_RateLimiter_Float32.tex}{}{}
\fi
\XtoCImplementation{Float64}
\index{Block ID!100}
\nopagebreak[0]
% Implementation details
\begin{tabular}{l l}
\textbf{Name} & Float64 \tabularnewline
\textbf{ID} & 100 \tabularnewline
\textbf{Revision} & 0.1 \tabularnewline
\textbf{C filename} & RateLimiter\_Float64.c \tabularnewline
\textbf{H filename} & RateLimiter\_Float64.h \tabularnewline
\end{tabular}
\vspace{1ex}

64 Bit Floating Point Implementation

\begin{XtoCtabular}{Controller Parameters}
RateUp & Rising time parameter\tabularnewline
\hline
RateDown & Falling time parameter\tabularnewline
\hline
enable\_old & Enable value from last cycle\tabularnewline
\hline
\end{XtoCtabular}

% Implementation data structure
\XtoCDataStruct{Data Structure:}
\begin{lstlisting}
typedef struct {
     uint16        ID;
     float64       *In;
     float64       *Init;
     int8          *Enable;
     float64       Out;
     float64       RateUp;
     float64       RateDown;
     int8          enable_old;
} RATELIMITER_FLOAT64;
\end{lstlisting}

\ifdefined \AddTestReports
\InputIfFileExists{\XcHomePath/Library/General/Doc/Test_RateLimiter_Float64.tex}{}{}
\fi


% This source file is part of the Geophysical Fluids Modeling Framework (L-GAME), which is released under the MIT license.
% Github repository: https://github.com/OpenNWP/L-GAME

\documentclass[10pt]{report}
\usepackage[utf8]{inputenc}
\usepackage{a4wide, amsmath, xcolor, longtable, geometry, fancyhdr, mathtools, array, listings}
\usepackage[style = numeric, backend = biber]{biblatex}
\usepackage{fouriernc}
\usepackage[T1]{fontenc}
\usepackage[hidelinks]{hyperref}
\geometry{a4paper, top = 15mm, left = 5mm, right = 5mm, bottom = 17mm}
\fancypagestyle{plain}{
\fancyhead[L]{\texttt{L-GAME} handbook}
\fancyhead[R]{\textsc{\texttt{L-GAME} development team}}
\fancyfoot[C]{\thepage}
\addtolength\footskip{12pt}}
\definecolor{table_green}{rgb}{0, 0.6, 0}
\title{\texttt{Limited-area Geophysical Fluids Modeling Framework (L-GAME)} Handbook}
\author{\texttt{L-GAME} Development Team}
\date{}
\newcommand{\md}[1]{\frac{D#1}{Dt}}
\newcommand{\omegabi}{\text{{\osgbi ω}}}
\newcommand{\mubi}{\text{{\osgbi μ}}}
\newcommand{\sigmabi}{\text{{\osgbi σ}}}
\newcommand{\epsilonbi}{\text{{\osgbi ϵ}}}
\newcommand{\etabi}{\text{{\osgbi η}}}
\newcommand{\zetabi}{\text{{\osgbi ζ}}}
\addbibresource{references.bib}
\DeclareFieldFormat[article]{title}{{#1}}

\begin{document}

\maketitle

\tableofcontents

\chapter{Overview}
\label{chap:overview}

\texttt{L-GAME} is the application of the theory and numerics of \texttt{GAME} to a quadrilateral latitude-longitude grid in a regional domain. The spatial and temporal discretizations are identical, apart from the following differences:
%
\begin{enumerate}
\item The domain is regional and not global (as mentioned).
\item The grid is a quadrilateral (rotated) latitude-longitude grid.
\item The connections of the gridpoints in longitude direction are small circles instead of great circles.
\end{enumerate}
%
This is only the handbook (manual) of \texttt{L-GAME}, it explains how to configure, compile and run (use) the model. For a scientific derivation of the model see \cite{kompendium} and the literature cited therein. The source code of the project is maintained on Github (\url{https://github.com/OpenNWP/L-GAME}).

\chapter{Code structure}
\label{chap:code_structure}

The code of the model resides in the directory \texttt{src}.

\section{Spatial operators}
\label{sec:spatial_operators}

\begin{itemize}
\item Coriolis: \cite{thuburn_f_discrete_plane} and \cite{ringler_trsk} modified by \cite{doi:10.1002/qj.3294}
\item kinetic energy: \cite{doi:10.1002/qj.1960}
\end{itemize}

\section{Time stepping}
\label{sec:time_stepping}

A fully Eulerian time stepping is employed. The basic building structure is Runge-Kutta second order (RK2). In the vertical, at every substep, an implicit column solver is used, which makes it possible to violate the CFL criterion of vertically propagating sound and fast gravity waves. This has the cost of decreasing the accuracy of these modes, which is however a bearable trade-off, since these waves are of low meteorological relevance. Furthermore, a forward-backward scheme is used, where the divergence term is backward.

\chapter{Installation}
\label{chap:installation}

\section{Dependencies}
\label{sec:dependencies}

The following dependencies must be installed before being able to successfully build the model:

\begin{itemize}
\item geos95 (\url{https://github.com/OpenNWP/geos95})
\item atmostracers (\url{https://github.com/OpenNWP/atmostracers})
\item Clone our fork of the RTE+RRTMGP repository: \texttt{git clone \url{https://github.com/OpenNWP/rte-rrtmgp}}
\item Python and pip (only needed for the plotting routines): \texttt{sudo apt-get install python3 python3-pip}
\item Python packages (only needed for the plotting routines): \texttt{pip3 install matplotlib numpy netCDF4}
\end{itemize}

\section{Building}
\label{sec:building}

\texttt{CMake} is used for building \texttt{L-GAME}. Execute \texttt{./compile.sh} to build the model.

\chapter{Running the model}
\label{chap:running_the_model}

\section{Grid generation}
\label{sec:grid_generation}

\subsection{Vertical grid structure}
\label{sec:vertical_grid_structure}

The vertical grid structure is the same as in \texttt{GAME}, which is explained in \cite{game_handbook}.

\section{Dynamics configuration}
\label{sec:dynamics_configuration}

\section{Physics configuration}
\label{sec:physics_configuration}

\subsection{Local thermodynamic equilibrium option}
\label{sec:local_thermodynamic_equilibrium_option}

Assuming a local thermodynamic equilibrium in a heterogeneous fluid boils down to assuming that all constituents have the same temperature. This reduces the complexity of the simulation by about 40 \%, since now internal energy densities are not prognostic variables anymore.

\section{Coupling to the radiation field}
\label{sec:coupling_to_the_radiation_field}

\texttt{L-GAME} employs the so-called \texttt{RTE+RRTMGP (Radiative Transfer for Energetics + Rapid and Accurate Radiative Transfer Model for Geophysical Circulation Model Applications—Parallel)} \cite{doi:10.1029/2019MS001621}, \cite{rte-rrtmgp-github} scheme.

\section{Configuring Output}
\label{sec:configuring_output}

\chapter{Initialization}
\label{sec:initialization}

\chapter{Boundary conditions}
\label{chap:boundary_conditions}

\appendix

\printbibliography

\end{document}


\chapter{Diagramme und Graphen in \LaTeX{}}
Durch das Paket Tikz besitzt \LaTeX{} ein Werkzeug um alles zu Zeichnen was möglich ist, sei es Graphen, Diagramme, Bilder, Figuren, 3D-Modelle. Alles ist mit dem Paket möglich. Hier ein paar Beispiele:

\begin{tikzpicture} % Beta Winkel bei einem Dreieck
\draw
(3,-1) coordinate (a) node[right] {A}
-- (0,0) coordinate (b) node[left] {B}
-- (2,2) coordinate (c) node[above right] {C}
pic["$\beta$", draw=orange, <->, angle eccentricity=1.2, angle radius=1cm]
{angle=a--b--c};
\end{tikzpicture}
\hspace{3cm}
\begin{tikzpicture}[thick,scale=1,node distance=1cm] % Graph
\graph[nodes={draw,circle},edges={-{Stealth[]}}] {
	A -> ["1"] B,
	A -> C,
	C -> B
};
\end{tikzpicture}
\bigskip

\tikzset{mynode/.style={inner sep=2pt,fill,outer sep=0,circle}} % Quader mit Fläche
\begin{tikzpicture}[scale=3,line width=1pt]
\coordinate (1) at (0,0,0);
\coordinate (2) at (0,1,0);
\coordinate (3) at (1,1,0);
\coordinate (4) at (1,0,0);
\coordinate (5) at (0,0,1);
\coordinate (6) at (0,1,1);
\coordinate (7) at (1,1,1);
\coordinate (8) at (1,0,1);
\foreach \x in {1,2,...,8}{
	\node[mynode] at (\x) {};
}
\draw (1) -- (2) -- (3) -- (4) -- cycle;
\draw (5) -- (6) -- (7) -- (8) -- cycle;
\draw (1) -- (5)  (2) -- (6) (3) -- (7) (4) -- (8);
\draw[thin,fill=blue!50,opacity=0.5] (0.5,0,0) -- (0.5,0,1) -- (0.5,1,1) -- (0.5,1,0) --cycle;
\node at (0.5,-0.2,1) {(\textit{h\,k\,l})};
\end{tikzpicture}
\hspace{1cm}
\begin{tikzpicture}[scale=3,line width=1pt] % Quader mit zwei Flächen
\coordinate (1) at (0,0,0);
\coordinate (2) at (0,1,0);
\coordinate (3) at (1,1,0);
\coordinate (4) at (1,0,0);
\coordinate (5) at (0,0,1);
\coordinate (6) at (0,1,1);
\coordinate (7) at (1,1,1);
\coordinate (8) at (1,0,1);
\foreach \x in {1,2,...,8}{
	\node[mynode] at (\x) {};
}
\draw (1) -- (2) -- (3) -- (4) -- cycle;
\draw (5) -- (6) -- (7) -- (8) -- cycle;
\draw (1) -- (5)  (2) -- (6) (3) -- (7) (4) -- (8);
\draw[thin,fill=blue!50,opacity=0.5] (1) -- (8) -- (6) --cycle;
\draw[thin,fill=blue!50,opacity=0.5] (2) -- (4) -- (7) --cycle;
\node at (0.5,-0.2,1) {(\textit{h\,k\,l})};
\end{tikzpicture}

\begin{tikzpicture} % Weiterer Graph
\graph {
	A -> { subgraph I_n [V= {B,C,D}] } -> E
};
\end{tikzpicture}
\hspace{1cm}
\begin{tikzpicture}[->,>=stealth',shorten >=2pt, line width=3pt,
node distance=1cm, style ={minimum size=10mm}] % Zustandsübergangsdiagramm einer Markov-Kette
\tikzstyle{every node}=[font=\huge]
\node [circle, draw] (a) {1};
\path (a) edge [loop above] (a);
\node [circle, draw] (b) [right=of a] {2};
\path (b) edge [loop above] (b);
\draw[->] (a) -- (b);
\node [circle, draw] (c) [below=of a] {3};
\path (c) edge [loop below] (c);
\draw[->] (a) -- (c);
\draw[->] (b) -- (c);
\end{tikzpicture}

\newpage
 Diagramm des Lebenszyklus der Android-Aktivität
 \begin{center}

\tikzset{%
	>={Latex[width=2mm,length=2mm]},
	% Specifications for style of nodes:
	base/.style = {rectangle, rounded corners, draw=black,
		minimum width=4cm, minimum height=1cm,
		text centered, font=\sffamily},
	activityStarts/.style = {base, fill=blue!30},
	startstop/.style = {base, fill=red!30},
	activityRuns/.style = {base, fill=green!30},
	process/.style = {base, minimum width=2.5cm, fill=orange!15,
		font=\ttfamily},
}
\begin{tikzpicture}[node distance=2cm,
every node/.style={fill=white, font=\sffamily}, align=center]
% Specification of nodes (position, etc.)
\node (start)             [activityStarts]              {Activity starts};
\node (onCreateBlock)     [process, below of=start]          {onCreate()};
\node (onStartBlock)      [process, below of=onCreateBlock]   {onStart()};
\node (onResumeBlock)     [process, below of=onStartBlock]   {onResume()};
\node (activityRuns)      [activityRuns, below of=onResumeBlock]
{Activity is running};
\node (onPauseBlock)      [process, below of=activityRuns, yshift=-1cm]
{onPause()};
\node (onStopBlock)       [process, below of=onPauseBlock, yshift=-1cm]
{onStop()};
\node (onDestroyBlock)    [process, below of=onStopBlock, yshift=-1cm]
{onDestroy()};
\node (onRestartBlock)    [process, right of=onStartBlock, xshift=4cm]
{onRestart()};
\node (ActivityEnds)      [startstop, left of=activityRuns, xshift=-4cm]
{Process is killed};
\node (ActivityDestroyed) [startstop, below of=onDestroyBlock]
{Activity is shut down};
% Specification of lines between nodes specified above
% with aditional nodes for description
\draw[->]             (start) -- (onCreateBlock);
\draw[->]     (onCreateBlock) -- (onStartBlock);
\draw[->]      (onStartBlock) -- (onResumeBlock);
\draw[->]     (onResumeBlock) -- (activityRuns);
\draw[->]      (activityRuns) -- node[text width=6cm]
{Another activity comes in
	front of the activity} (onPauseBlock);
\draw[->]      (onPauseBlock) -- node {The activity is no longer visible}
(onStopBlock);
\draw[->]       (onStopBlock) -- node {The activity is shut down by
	user or system} (onDestroyBlock);
\draw[->]    (onRestartBlock) -- (onStartBlock);
\draw[->]       (onStopBlock) -| node[yshift=1.25cm, text width=3cm]
{The activity comes to the foreground}
(onRestartBlock);
\draw[->]    (onDestroyBlock) -- (ActivityDestroyed);
\draw[->]      (onPauseBlock) -| node(priorityXMemory)
{higher priority $\rightarrow$ more memory}
(ActivityEnds);
\draw           (onStopBlock) -| (priorityXMemory);
\draw[->]     (ActivityEnds)  |- node [yshift=-2cm, text width=3.1cm]
{User navigates back to the activity}
(onCreateBlock);
\draw[->] (onPauseBlock.east) -- ++(2.6,0) -- ++(0,2) -- ++(0,2) --
node[xshift=1.2cm,yshift=-1.5cm, text width=2.5cm]
{The activity comes to the foreground}(onResumeBlock.east);
\end{tikzpicture}
 \end{center}
\newpage
Weiterführende Anleitungen und Dokumentationen zu Tikz:
\begin{itemize}
	\item \url{http://www.math.uni-leipzig.de/~hellmund/LaTeX/pgf-tut.pdf}
	\item \url{https://cremeronline.com/LaTeX/minimaltikz.pdf}
	\item \url{https://en.wikibooks.org/wiki/LaTeX/PGF/TikZ}
	\item \url{https://www.bu.edu/math/files/2013/08/tikzpgfmanual.pdf}
\end{itemize}

Diese Dokumente zeigen was möglich ist:
\begin{itemize}
	\item\url{http://bit.ly/2pdUfCn}
	\item  \url{http://bit.ly/2G19KHy}
\end{itemize}

Quellen für die Beispiele:
\begin{itemize}
	\item \url{http://www.texample.net/tikz/examples/tag/flowcharts/}
	\item \url{http://bit.ly/2DxhAmL}
	\item \url{https://tex.stackexchange.com/questions/213075/two-tikzpictures-side-by-side}
    \item \url{http://books.goalkicker.com/LaTeXBook/}
\end{itemize}

HS Bremerhaven Latex Vorlage/chapters/Tikz.tex


\chapter{Mesh formats}\label{chap:mesh_formats}
\index{mesh!generation}
\index{grid|see{mesh}}

This chapter describes the information contained in a mesh file and the
two mesh formats that can be read by \fluidity: the gmsh and
ExodusII format.
For an overview and further pointers on how to generate these meshes
see chapter \ref{chap:meshes}.

\section{Mesh data}

A mesh describes the computational domain in which a simulation takes
place. Regardless of the mesh file format in use, the information conveyed
is essentially the same.

\subsection{Node location}

The locations of the element vertices are recorded. Usually, these have the
same dimension as the topological dimension of the mesh elements. \fluidity\
does not currently support configurations such as shells in which the node
location dimension differs from the element topology dimension.

\subsection{Element topology}

The mesh is composed of elements. In one dimension these will be intervals
with each interval joining two nodes. In two dimensions, triangles or
quadrilaterals are supported with the elements joining three or four nodes
respectively. In three dimensions, the elements can be tetrahedra or
hexahedra and will join four or eight nodes.

The element topology will store the indices of the nodes which make up
each of the elements in the mesh.

\subsection{Facets}

Facets form the surface of elements. In one dimension, the facets of an
element are its bounding nodes. In two dimensions, the facets are the edge
intervals while the facets of a three-dimensional tetrahedral element are
triangles and those of a hexahedral element are quadrilaterals. External
mesh formats tend to only supply facet topology information for facets on
the surface of each domain. For each facet specified, the node indices of
that facet will be given. These surface facets are used in combination with
surface IDs to specify the regions over which boundary conditions should be
applied.

\subsection{Surface IDs}\label{sec:surface_ids}
\index{surface ID}
Numbers can be assigned to label particular facets (boundary nodes, edges or
faces in 1, 2 or 3 dimensions respectively) in order to set
boundary conditions or other parameters. This number can then be used to
specify which surface a particular boundary condition should be applied to
in \fluidity.

\subsection{Region IDs}\label{sec:region_ids}
\index{region ID} These are analogous to surface IDs, however they are
associated with elements rather than facets. Region IDs may be used in
\fluidity\ to specify different initial conditions or material properties to
different parts of the domain.

\section{DEPRECATED: The triangle format}\label{sec:triangle_format}
\index{mesh!file formats}

The \emph{triangle} format is a ASCII file format originally designed for 2D
triangle meshes, but it can be easily extended to different dimensions and
more complex geometries.  \fluidity\ supports a version of the triangle format
which supports 1D, 2D and 3D meshes.  The following table shows the supported
combinations of element dimension and geometry.

\begin{tabular}{ l l l }
\textbf{Dimension} & \textbf{Geometry} & \textbf{Number of vertices per element} \\ \hline
1D & Line & 2\\
2D & Triangles &  3 \\
2D & Quadrilateral & 4 \\
3D & Tetrahedra & 4 \\
3D & Hexahedra & 8 \\
\end{tabular}

A complete triangle mesh consists of three files: one file defining the
nodes of the mesh, one file describing the elements (for example triangles
in 2D) and one file defining the boundary parts of the mesh.

The triangle file format is very simple. Since the data is stored in ASCII,
any text editor can be used to edit the files.  Lines starting with \# will
be interpreted as a comment by \fluidity.  The filename should end with
either .node, .ele, .bound, .edge or .face.  The structure of these files
will now be explained:

\begin{description}
\item[.node file]
This file holds the coordinates of the nodes. The file structure is:

First line
\begin{lstlisting}:
<total number of vertices> <dimension (must be 1,2 or 3)> 0 0
\end{lstlisting}
Remaining lines
\begin{lstlisting}
<vertex number> <x> [<y> [<z>]]
\end{lstlisting}
where x, y and z are the coordinates.

Vertices must be numbered consecutively, starting from one.

\item[.ele file] Saves the elements of the mesh. The file structure is:
\index{region ID}

First line:
\begin{lstlisting}
 <total number of elements> <nodes per element>  1
\end{lstlisting}
Remaining lines:
\begin{lstlisting}
<element number> <node> <node> <node> ... <region id>
\end{lstlisting}
The elements must be numbered consecutively, starting from one. Nodes are
indices into the corresponding .node file. For example in case of describing
a 2D triangle mesh, the first three nodes are the corner vertices. The
region ID can be used by \fluidity\ to set conditions on different parts of
the mesh, see section \ref{sec:region_ids}.

\item[.bound file] This file is only generated for one-dimensional meshes.
  It records the boundary points and assigns surface IDs to them. The file
  structure is:\index{surface ID}

First line:
\begin{lstlisting}
 <total number of boundary points> 1
\end{lstlisting}
Remaining lines:
\begin{lstlisting}
<boundary point number> <node> <surface id>
\end{lstlisting}
The boundary points must be numbered consecutively, starting from one. Nodes
are indices into the corresponding .node file. The surface ID is used by
\fluidity\ to specify parts of the surface where different boundary
conditions will be applied, see section \ref{sec:surface_ids}.

\item[.edge file] This file is only generated for two-dimensional meshes.
  It records the edges and assigns surface IDs to part of the mesh surface.
  The file structure is:

First line:
\begin{lstlisting}
 <total number of edges> 1
\end{lstlisting}
Remaining lines:
\begin{lstlisting}
<edge number> <node> <node> ... <surface id>
\end{lstlisting}
The edges must be numbered consecutively, starting from one. Nodes are
indices into the corresponding .node file. The surface ID is used by
\fluidity\ to specify parts of the surface where different boundary
conditions will be applied, see section \ref{sec:surface_ids}.

\item[.face file] This file is only generated for three-dimensional meshes.
  It records the faces and assigns surface IDs to part of the mesh surface. The
  file structure is:

First line:
\begin{lstlisting}
 <total number of faces> 1
\end{lstlisting}
Remaining lines:
\begin{lstlisting}
<face number> <node> <node> <node> ... <surface id>
\end{lstlisting}
The faces must be numbered consecutively, starting from one. Nodes are
indices into the corresponding .node file. The surface ID is used by
\fluidity\ to specify parts of the surface where different boundary
conditions will be applied, see section \ref{sec:surface_ids}.
\end{description}

To clarify the file format, a simple 1D example is shown:
The following .node file defines 6 equidistant nodes from 0.0 to 5.0
\begin{lstlisting}
# example.node
6 1 0 0
1 0.0
2 1.0
3 2.0
4 3.0
5 4.0
6 5.0
\end{lstlisting}
The .ele file connects these nodes to 5 lines. Two regions will be defined with the IDs 1 and 2.
\begin{lstlisting}
# example.ele
5 2 1
1 1 2 1
2 2 3 1
3 3 4 1
4 4 5 2
5 5 6 2
\end{lstlisting}
Finally, the .bound file tags the very left and very right nodes as boundary
points an assigns the surface IDs 1 and 2 to them.
\begin{lstlisting}
# example.bound
2 1
1 1 1
2 6 2
\end{lstlisting}

\section{The Gmsh format}\label{sec:gmsh_format}

\fluidity\ contains  support for the Gmsh format. Gmsh is a mesh
generator freely available on the Web at (\url{http://geuz.org/gmsh/}), and
is included in Linux distributions such as Ubuntu.

Gmsh meshes are contained within one file, which have
the extension \lstinline[language=bash]+.msh+. The file contents may
be either binary or ASCII.

This section briefly describes the Gmsh format, and is only intended
to serve as a short introduction. If you need further
information, please read the official Gmsh documentation
(\url{http://geuz.org/gmsh/doc/texinfo/gmsh.pdf}).
Typically Gmsh files used in \fluidity\ contain three parts: a header, a
section for nodes, and one for elements. These  are explained in more
detail below.

\subsubsection*{The header}\label{sec:gmsh_header_section}
This contains Gmsh file version information, and indicates whether
the main data is in ASCII or binary format. This will typically look like:
\begin{lstlisting}
$MeshFormat
2.1 0 8
[Extra data here in binary mode]
$EndMeshFormat
\end{lstlisting}

From the listing above we can tell that:
\begin{itemize}
\item the Gmsh format version is 2.1
\item it is in ASCII, as indicated by the 0 (1=binary)
\item the byte size of double precision is 8
\end{itemize}
In addition, in binary mode the integer 1 is written as 4 raw bytes, to check that the endianness of the Gmsh file and the system are the same (\textit{you will rarely have to worry about this})

\subsubsection*{The nodes section}\label{sec:gmsh_nodes_section}

The next section contains node data, viz:
\begin{lstlisting}
$Nodes
number_of_nodes
[node data]
$EndNodes
\end{lstlisting}

The \lstinline+[node data]+ part contains the listing of nodes, with ID,
followed by $x$, $y$, and $z$ coordinates. This part
will be in binary when binary mode has been selected. Note that even with 2D
problems, there will be a zeroed \textit{z} coordinate.

\subsubsection*{The elements section}\label{sec:gmsh_elements_section}

The elements section contains information on both facets and regular
elements. It also varies between binary and ASCII formats. The ASCII version
is:

\begin{lstlisting}
$Elements
element1_id element_type number_of_tags tag_list node_number_list
element2_id ...
...
...
$EndElements
\end{lstlisting}
\textit{Tags} are integer properties ascribed to the element. In \fluidity,
usually we are only concerned with the first one, the physical ID. This can mean
one of two things:

\begin{itemize}
\item A region ID - in the case of elements
\item A surface ID - in the case of facets
\end{itemize}

Since Gmsh doesn't explicitly label facets or regular elements as such,
internally \fluidity\ works this out from type: eg, if there a mesh consists
of tetrahedra and triangles, then triangles must be the facets.

\subsubsection*{Internal use }
\label{sec:gmsh_internal_use_section}

\fluidity\ occasionally augments GMSH files for its own internal use. It
does this in two cases. Firstly, when generating periodic meshes
through \lstinline+periodise+ (section \ref{sec:decomposing_meshes_periodise}), the
fourth element tag is reserved to label elements at the periodic boundary.
Secondly, when checkpointing extruded meshes, a new section called
\lstinline+$NodeData+ is created at the end of the GMSH file; this contains
essential node column ID information.

\section{The ExodusII format}
\label{sec:exodusii_format}
\index{exodusii}

Currently Fluidity support read-only support for serial ExodusII files. It is the default
output mesh format of the automated mesh generation toolkit \href{http://cubit.sandia.gov/}{Cubit}.
The mesh is stored within one binary file and typically has one of the following file extensions:
\texttt{.e}, \texttt{.E}, \texttt{.exo}, or \texttt{.EXO}.

A brief description of the structure of an ExodusII file is given. Interested readers can find a
more detailed description of the ExodusII format in the official manual at
\url{http://sourceforge.net/projects/exodusii/}.

\subsubsection*{The header}
\label{ssec:exodusii_header_section}

The header contains basic information about the ExodusII file, such as the number of dimensions,
nodes, elements, blocks, sidesets and many more. Below an excerpt of the header is given.
\begin{lstlisting}
netcdf \2dbox_with_sideset {
dimensions:
    ...
    num_dim = 2 ;
    num_nodes = 23 ;
    num_elem = 35 ;
    num_el_blk = 2 ;
    ...
    num_side_sets = 4 ;
    num_side_ss1 = 5 ;
    ...
    num_el_in_blk1 = 30 ;
    num_nod_per_el1 = 3 ;
    ...
\end{lstlisting}

From this header we can identify that the file contains a 2-dimensional
mesh (\texttt{num\_dim = 2}), with 23 nodes (\texttt{num\_nodes}), and
35 elements (\texttt{num\_elem}). Furthermore, the mesh was divided into
two blocks (\texttt{num\_el\_blk = 2}), whereas the first block has
30 elements (\texttt{num\_el\_in\_blk1}) and the number of nodes of each
element in this block is three (\texttt{num\_nod\_per\_el1 = 3}). In addition
to the blocks, four sidesets were defined (\texttt{num\_side\_sets}),
whereas the first sideset contains 5 elements (\texttt{num\_side\_ss1 = 5}).
The ids of the blocks and sidesets are not to be confused with the numbering
of the blocks and sidesets above. The corresponding ids are stored in the
\texttt{data} section of an ExodusII file, which is covered in the following
section.

\subsubsection*{The data section}
\label{ssec:exodusii_data_section}

The data section contains the actual mesh properties, such as block and sideset ids,
the list of elements and sides of each sideset, the node connectivity of each
defined block, and of course the element mapping of the entire mesh and the
coordinates of the vertices.
\begin{lstlisting}
data:
...
 ss_prop1 = 10, 11, 12, 13 ;
...
 elem_ss1 = 4, 8, 19, 20, 21 ;
...
 elem_ss2 = 2, 4, 13 ;
...
 elem_map = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35 ;
...
 eb_prop1 = 1, 2 ;
...
 connect2 =
  7, 8,
  8, 20,
  20, 23,
  23, 15,
  15, 16 ;
...
  coord =
  0.283701736685801, 0.166666666666667, 0.0265230044875502, 0.5,
    -0.0944251982348238, -0.258225085856399, -0.5, -0.5, -0.166666666666667,
    0.218376401545253, 0.283363015396065, 0.5, -0.166666666666667,
    -0.25779029343402, -0.5, -0.5, 0.0259480610716054, 0.5, 0.5, -0.5,
    -0.321383277222933, 0.166666666666667, -0.5,
  0.280428743148782, 0.5, 0.242760465386713, 0.5, -0.00227602386180678,
    0.188837287760358, 0.5, 0.3, 0.5, -0.00202880785288154,
    -0.284316506446615, -0.166666666666667, -0.5, -0.193411124527211, -0.3,
    -0.5, -0.247855406465798, -0.5, 0.166666666666667, 0.1,
    -0.00195855747202122, -0.5, -0.1 ;
\end{lstlisting}

Here \texttt{ss\_prop1} lists the id numbers of the defined sidesets, e.g.~the
id number $10$ was assigned to the first sideset. As stated in the header, the
first sideset contains five elements (\texttt{num\_side\_ss1 = 5}), which are
listed in the data section under \texttt{elem\_ss1 = 4, 8, 19, 20, 21 ;}

As stated above, the mesh was divided into two blocks. Their id numbers are 1
and 2, as can be seen under \texttt{eb\_prop1 = 1, 2;} The element connectivity
stored for each block separately under \texttt{connect1} and \texttt{connect2}.

Finally the coordinates of the vertices are stored under \texttt{coord = ...}

\subsection*{Use within Fluidity}
\label{ssec:exodusii_use_within_fluidity}

Once the mesh is generated, it can be read in by Fluidity by simply setting the
mesh format in Diamond to \texttt{exodusii} and providing its file name.

The region ids and surface ids set in Diamond are the block ids and sideset ids
in the ExodusII file respectively.

\subsection*{Current restrictions}
\label{ssec:exodusii_restrictions}

This is work in progress and the following restrictions apply to using the ExodusII
mesh format:
\begin{itemize}
 \item Currently only serial mesh files can be read in
 \item Currently Fluidity does not support writing ExodusII files, thus whenever
 an ExodusII mesh file is read in, the checkpointed mesh files that are written are
 in the gmsh mesh format.
 \item FLTools such as periodise currently do not support the ExodusII mesh format.

\end{itemize}


\documentclass[12pt,preprint]{aastex}

% has to be before amssymb it seems
\usepackage{color,hyperref}
\definecolor{linkcolor}{rgb}{0,0,0.5}
\hypersetup{colorlinks=true,linkcolor=linkcolor,citecolor=linkcolor,
            filecolor=linkcolor,urlcolor=linkcolor}

\usepackage{url}
\usepackage{algorithmic,algorithm}
\usepackage{amssymb,amsmath}

\newcommand{\arxiv}[1]{\href{http://arxiv.org/abs/#1}{arXiv:#1}}

\usepackage{listings}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\lstset{ %
    language=Python,
    basicstyle=\footnotesize\ttfamily,
    showspaces=false,
    showstringspaces=false,
    tabsize=2,
    breaklines=false,
    breakatwhitespace=true,
    identifierstyle=\ttfamily,
    keywordstyle=\bfseries\color[rgb]{0.133,0.545,0.133},
    commentstyle=\color[rgb]{0.133,0.545,0.133},
    stringstyle=\color[rgb]{0.627,0.126,0.941},
}

\newcommand{\project}[1]{{\sffamily #1}}
\newcommand{\paper}{document}
\newcommand{\license}{MIT License}

\newcommand{\foreign}[1]{\emph{#1}}
\newcommand{\etal}{\foreign{et\,al.}}
\newcommand{\etc}{\foreign{etc.}}

\newcommand{\Fig}[1]{Figure~\ref{fig:#1}}
\newcommand{\fig}[1]{\Fig{#1}}
\newcommand{\figlabel}[1]{\label{fig:#1}}
\newcommand{\Tab}[1]{Table~\ref{tab:#1}}
\newcommand{\tab}[1]{\Tab{#1}}
\newcommand{\tablabel}[1]{\label{tab:#1}}
\newcommand{\Eq}[1]{Equation~(\ref{eq:#1})}
\newcommand{\eq}[1]{\Eq{#1}}
\newcommand{\eqlabel}[1]{\label{eq:#1}}
\newcommand{\Sect}[1]{Section~\ref{sect:#1}}
\newcommand{\sect}[1]{\Sect{#1}}
\newcommand{\App}[1]{Appendix~\ref{sect:#1}}
\newcommand{\app}[1]{\App{#1}}
\newcommand{\sectlabel}[1]{\label{sect:#1}}
\newcommand{\Algo}[1]{Algorithm~\ref{algo:#1}}
\newcommand{\algo}[1]{\Algo{#1}}
\newcommand{\algolabel}[1]{\label{algo:#1}}

% math symbols
\newcommand{\dd}{\,\mathrm{d}}
\newcommand{\bvec}[1]{\boldsymbol{#1}}
\newcommand{\paramvector}[1]{\bvec{#1}}
\DeclareMathOperator*{\argmax}{arg\,max}

% other symbols
\newcommand{\bin}{\ensuremath{\hat{w}}}

\begin{document}

\title{How to make a histogram of noisy data}

\newcommand{\nyu}{2}
\newcommand{\mpia}{3}
\author{Daniel~Foreman-Mackey\altaffilmark{1,\nyu},
        David~W.~Hogg\altaffilmark{\nyu,\mpia},
        other losers?}
\altaffiltext{1}{To whom correspondence should be addressed:
                 \url{danfm@nyu.edu}}
\altaffiltext{\nyu}{Center for Cosmology and Particle Physics,
                    Department of Physics, New York University,
                    4 Washington Place, New York, NY, 10003, USA}
\altaffiltext{\mpia}{Max-Planck-Institut f\"ur Astronomie,
                     K\"onigstuhl 17, D-69117 Heidelberg, Germany}

\begin{abstract}
Dude.
\end{abstract}

\keywords{}

\section{Introduction}

\section{The Problem}

A histogram with bin edges $\bvec{\bin}$ and normalized bin heights
$\bvec{\theta}$ for some quantity $w$ can be written as the probability
density
\begin{eqnarray}
p(w\,|\,\bvec{\bin},\,\bvec{\theta}) &=& \left\{\begin{array}{ll}
\theta_1, & \mathrm{if}\,\bin_0 \le w < \bin_1 \\
\theta_2, & \mathrm{if}\,\bin_1 \le w < \bin_2 \\
\multicolumn{2}{c}{\cdots} \\
\theta_L, & \mathrm{if}\,\bin_{L-1} \le w < \bin_L\\
0 & \mathrm{otherwise}
\end{array}\right. \quad.
\end{eqnarray}
In practice, a single observation $k$ of $w$ is conditioned on some data
$\bvec{x}_k$.
In general, this constraint is given by a posterior probability density
$p(w_k\,|\,\bvec{x}_k,\,\bvec{\alpha})$ that is---or can be---represented as
a set of $N$ samples
\begin{eqnarray}\eqlabel{posts}
w_k^{(n)} &\sim& p(w_k\,|\,\bvec{x}_k,\,\bvec{\alpha}) \quad.
\end{eqnarray}

We'll leave the discussion of the choice of bin edges to another time and for
now just find the best fit bin heights.

In the above situation, there is no closed form solution for ``the best''
histogram of $w$ given the observations $\bvec{x}$.
In order to make this question quantitative, let's consider the
\emph{marginalized likelihood function}
\begin{eqnarray}\eqlabel{marglike}
p(\{\bvec{x}_k\}\,|\,\bvec{\theta}) &=&
\prod_{k=1}^K\int p(w_k,\,\bvec{x}_k\,|\,\bvec{\theta})\dd w_k \\
&=&
\prod_{k=1}^K\int p(w_k,\,|\,\bvec{\theta})\,p(\bvec{x}_k\,|\,w_k)\dd w_k
\quad.
\end{eqnarray}
This function quantifies the probability of all observations given a
particular set of bin heights.
This question becomes a constrained optimization problem
\begin{eqnarray}\eqlabel{argmax}
\bvec{\theta}_\star &=&
\argmax_{\bvec{\theta}} \log p(\{\bvec{x}_k\}\,|\,\bvec{\theta})
\end{eqnarray}
under the constraint
\begin{eqnarray}
\int p(w\,|\,\bvec{\theta}) &=& 1
\end{eqnarray}
or, equivalently
\begin{eqnarray}
\sum_{l=1}^L (\bin_l - \bin_{l-1})\,\theta_l &=& 1 \quad.
\end{eqnarray}

The key here is to be able to compute \eq{marglike} efficiently given our
constraints on $w_k$ (\eq{posts}).
To do this, we can simplify \eq{marglike} as follows
\begin{eqnarray}
p(\{\bvec{x}_k\}\,|\,\bvec{\theta}) &=&
\prod_{k=1}^K\int p(w_k,\,|\,\bvec{\theta})\,p(\bvec{x}_k\,|\,w_k) \,
\frac{p(w_k\,|\,\bvec{x}_k,\,\bvec{\alpha})}
     {p(w_k\,|\,\bvec{x}_k,\,\bvec{\alpha})}
\dd w_k \\
&=&
\prod_{k=1}^K\int
\frac{p(w_k\,|\,\bvec{\theta})}
     {p(w_k\,|\,\bvec{\alpha})} \,
p(\bvec{x}_k\,|\,\bvec{\alpha})\,
p(w_k\,|\,\bvec{x}_k,\,\bvec{\alpha})
\dd w_k
\end{eqnarray}
giving
\begin{eqnarray}
\frac{p(\{\bvec{x}_k\}\,|\,\bvec{\theta})}{p(\{\bvec{x}_k\}\,|\,\bvec{\alpha})}
&\approx&
\prod_{k=1}^K \frac{1}{N_k} \sum_{n=1}^{N_k}
\frac{p(w_k^{(n)}\,|\,\bvec{\theta})}
     {p(w_k^{(n)}\,|\,\bvec{\alpha})}
\quad.
\end{eqnarray}

\acknowledgments It is a pleasure to thank
\ldots
for helpful contributions to the ideas and code presented here.

\begin{thebibliography}{}\raggedright

\bibitem[Foreman-Mackey \etal(2013)]{emcee}
Foreman-Mackey, D., Hogg, D.~W., Lang, D., \& Goodman, J.\ 2013,
\pasp, 125, 306

\end{thebibliography}

\end{document}


\documentclass{beamer}

\mode<presentation>
{
  \usetheme{Hawke}
  % or ...

  \setbeamercovered{transparent}
  % or whatever (possibly just delete it)
}

\usepackage[english]{babel}
\usepackage[latin1]{inputenc}
\usepackage{times}
\usepackage[T1]{fontenc}
\usepackage{multimedia}

%%%%%%
% My Commands
%%%%%%

\newcommand{\bb}{{\boldsymbol{b}}}
\newcommand{\bx}{{\boldsymbol{x}}}
\newcommand{\by}{{\boldsymbol{y}}}
\newcommand{\bfm}[1]{{\boldsymbol{#1}}}
\newcommand{\pda}[2]{\frac{\partial{#1}}{\partial{#2}}}

%%%%

\title[Lecture 23] % (optional, use only with long paper titles)
{Lecture 23 - Finite difference methods for nonlinear Boundary Value Problems}

\author[I. Hawke] % (optional, use only with lots of authors)
{I.~Hawke}

\institute[University of Southampton] % (optional, but mostly needed)
{
%  \inst{1}%
  School of Mathematics, \\
  University of Southampton, UK
}

\date[Semester 1] % (optional, should be abbreviation of conference name)
{MATH3018/6141, Semester 1}

\subject{Numerical methods}

\pgfdeclareimage[height=0.5cm]{university-logo}{mathematics_7469}
\logo{\pgfuseimage{university-logo}}

\AtBeginSection[]
{
  \begin{frame}<beamer>
    \frametitle{Outline}
    \tableofcontents[currentsection]
  \end{frame}
}

\begin{document}

\begin{frame}
  \titlepage
\end{frame}

\section{Finite difference methods}

\subsection{Background}

\begin{frame}
  \frametitle{Boundary Value Problems}

  Considering simple boundary value problem
  \begin{equation*}
    y'' = f(x, y, y'), \quad y(a) = A, \,\, y(b) = B, \quad x \in [a,b].
  \end{equation*} \pause
  Boundary conditions are only examples here. \pause

  \vspace{1ex}

  Standard approach: first try \emph{shooting} method.  Next try \emph{relaxation}. Linear case: grid plus finite differences give a linear system to solve. \pause

  \vspace{1ex}

  In the nonlinear case can still use a grid and finite differences. Resulting equations not linear.

\end{frame}

\section{Nonlinear problems}

\subsection{Nonlinear problems}

\begin{frame}
  \frametitle{Nonlinear problems}

  In linear case
  \begin{equation*}
    y'' + p(x) y' + q(x) y =  f(x), \quad y(a) = A, \,\, y(b) = B,
    \quad x \in [a,b]
  \end{equation*}
  have approximate solution on grid after solving one linear
  system. In nonlinear case
  \begin{equation*}
    y'' = f(x, y, y'), \quad y(a) = A, \,\, y(b) = B, \quad x \in [a,b]
  \end{equation*}
  as the $f$ depends on unknowns cannot directly write BVP as a linear
  system. \pause

  \vspace{1ex}

  Instead guess solution $\by^{(k)}$. Then compute $f$ on grid using
  old guess $\by^{(k)}$ which is \emph{known}, giving linear system
  for $\by^{(k+1)}$. \pause

  \vspace{1ex}

  This process of computing a sequence of guesses, each of which
  requires the solution of a linear system, is called
  \emph{relaxation}.

\end{frame}

\begin{frame}
  \frametitle{Newton relaxation}

  Approximate nonlinear problem using
  \begin{equation*}
    y_{i-1} + y_{i+1} - 2 y_i - h^2 f \left( x_i, y_i, \frac{y_{i+1} -
      y_{i-1}}{2 h} \right) = r_i.
  \end{equation*}
  The $r_i$ are the \emph{residuals} to minimize. \pause Nonlinear
  root finding problem -- $\bfm{r}$ is a function of $\by$, want to
  solve $\bfm{r}(\bfm{y}) = \bfm{0}$. \pause

  \vspace{1ex}

  \begin{overlayarea}{\textwidth}{0.6\textheight}
    \only<3-4|handout:1>
    {
      Imagine doing Newton's method
      \begin{equation*}
        \by^{(k+1)} = \by^{(k)} - \frac{\bfm{r^{(k)}}}{\bfm{r^{(k)}}'}.
      \end{equation*}
    }
    \only<4|handout:1>
    {
      Meaningless as a vector equation. The equivalent is
      \begin{equation*}
        \pda{r_i^{(k)}}{y_j^{(k)}} \left( \by^{(k+1)} - \by^{(k)} \right) = -
        \bfm{r^{(k)}}.
      \end{equation*}
    }
    \only<5|handout:2>
    {
      \begin{equation*}
        \pda{r_i^{(k)}}{y_j^{(k)}} \left( \by^{(k+1)} - \by^{(k)} \right) = -
        \bfm{r^{(k)}}.
      \end{equation*}
      This is the linear system
      \begin{equation*}
        J^{(k)} \bfm{c}^{(k)} = - \bfm{r}^{(k)}
      \end{equation*}
      where $J$ is the Jacobian matrix, $\bfm{c}$ the correction, giving
      \begin{equation*}
        \by^{(k+1)} = \by^{(k)} + \bfm{c}^{(k)}.
      \end{equation*}
    }
  \end{overlayarea}

\end{frame}

\begin{frame}
  \frametitle{The algorithm}

  Construct initial guess $\by^{(0)}$ (conventionally zero). Then
  iteratively
  \begin{enumerate}
  \item<1-> construct the residual
    \begin{equation*}
      r^{(k)}_i = y^{(k)}_{i-1} + y^{(k)}_{i+1} - 2 y^{(k)}_i - h^2 f
      \left( x_i, y^{(k)}_i, \frac{y^{(k)}_{i+1} - y^{(k)}_{i-1}}{2 h}
      \right),
    \end{equation*}
  \item<2-> construct the Jacobian
    \begin{equation*}
      J^{(k)} = \pda{r_i^{(k)}}{y_j^{(k)}},
    \end{equation*}
  \item<3-> construct the correction $\bfm{c}$ by solving
    \begin{equation*}
      J^{(k)} \bfm{c}^{(k)} = - \bfm{r}^{(k)},
    \end{equation*}
  \item<4-> construct the new guess by
      \begin{equation*}
        \by^{(k+1)} = \by^{(k)} + \bfm{c}^{(k)}.
      \end{equation*}
  \end{enumerate} \pause[5]
  \vspace{-1ex}
  Repeat until the correction is sufficiently small.

\end{frame}

\begin{frame}
  \frametitle{The Jacobian}

  Choosing central differencing the Jacobian
  \begin{equation*}
    J^{(k)} = \pda{r_i^{(k)}}{y_j^{(k)}}
  \end{equation*}
  is also tridiagonal, as
  \begin{equation*}
    \pda{r_i}{y_j} = \left\{
      \begin{aligned}
        1 + \tfrac{h}{2} \pda{f}{y'} (y_{i-1}) && j & = i - 1, \\
        -2 - h^2 \pda{f}{y} (y_{i}) && j & = i, \\
        1 - \tfrac{h}{2} \pda{f}{y'} (y_{i+1}) && j & = i + 1.
      \end{aligned} \right.
  \end{equation*} \pause
  Hence solution of each individual system is still very
  efficient. \pause

  \vspace{1ex}

  Taking advantage of structure, there are Gauss-Seidel and SOR
  variants of iterative scheme. Can either accelerate convergence or
  improve stability in particular cases.

\end{frame}

\begin{frame}
  \frametitle{Example}

  \begin{columns}
    \begin{column}{0.4\textwidth}
      In the problem
      \begin{align*}
        y'' & = - \frac{1}{1 + y^2}, \\ y(0) &= 0, \\ y(1) &= 0, \\ x
        &\in [0, 1]
      \end{align*}
      use Newton relaxation. Initial guess
      trivial. \pause

      \vspace{1ex}

      First iteration already reasonable.  \pause

      \vspace{1ex}

      After 4 iterations solution has settled down.
    \end{column}
    \begin{column}{0.6\textwidth}
      \begin{center}
        \includegraphics<1|handout:0>[width=\textwidth]{figures/FDBVPNewton0}
        \includegraphics<2|handout:0>[width=\textwidth]{figures/FDBVPNewton1}
        \includegraphics<3>[width=\textwidth]{figures/FDBVPNewtonFinal}
      \end{center}
    \end{column}
  \end{columns}

\end{frame}

\section{Summary}

\subsection{Summary}

\begin{frame}
  \frametitle{Summary}

  \begin{itemize}
  \item First shoot, then relax.
  \item Finite difference methods are typically less accurate and
    efficient, and for nonlinear problems are more complex to
    implement. However, they are much more likely to work in complex
    cases.
  \item For linear problems finite difference methods convert the ODE
    to a linear system $T \by = \bfm{F}$.
    \begin{itemize}
    \item The matrix will be tri-diagonal (when using centred
      differencing).
    \item The boundary conditions are normally directly encoded in the
      known vector $\bb$ (but more complex boundary conditions may
      require modification of $A$ as well).
    \end{itemize}
  \item For nonlinear problems we construct a sequence of guesses
    $\by^{(n)}$ that converge to the solution; the previous guess is
    used to solve a linear system.
  \end{itemize}

\end{frame}

\end{document}


\chapter{Selected Operators Implementation}
\label{chap:examples}

\begin{algorithm}
\begin{lstlisting}[language=Python, xrightmargin=18pt, breaklines=true, postbreak=\mbox{$\hookrightarrow$\space}, literate={\ \ }{{\ }}1]
from typing import Tuple, Any, Dict, Union, Callable
import torch as t
from ffeat import Pipe
from ffeat.utils._parental_sampling import randint

_IFU = Union[int, float]

class Tournament(Pipe):
    def __init__(self, num_select=None, maximization=False, parents=2, parental_sampling=randint):
        self._num_select = self._handle_parameter(num_select)
        self._maximization=maximization
        self._parents = parents
        self._parental_sampling = parental_sampling

    def __call__(self, fitnesses, population, *args, **kwargs):
        originally = len(population)
        to_select = self._num_select(fitnesses, population, *args, **kwargs)

        indices = self._parental_sampling(originally, to_select, self._parents, fitnesses.device)
        operation = t.argmax if self._maximization else t.argmin
        best_indices = operation(fitnesses[indices], dim=1)
        selected = population[indices[range(to_select),best_indices]]

        return (selected, *args), kwargs
\end{lstlisting}
\caption{Tournament selection implementation}
\label{alg:impltournament}
\end{algorithm}

\begin{algorithm}
\begin{lstlisting}[language=Python, xrightmargin=18pt, breaklines=true, postbreak=\mbox{$\hookrightarrow$\space}, literate={\ \ }{{\ }}1]
from typing import Tuple, Any, Dict, Union
import torch as t
from ffeat import Pipe
from ._Shared import _CommonCrossover
from ffeat.utils._parental_sampling import randint

class OnePoint1D(Pipe, _CommonCrossover):
    def __init__(self, offsprings, replace_parents=True, in_place=True, discard_parents=False, parental_sampling=randint):
        _Shared.__init__(self, offsprings, replace_parents, in_place, discard_parents)
        self._parental_sampling = parental_sampling

    def __call__(self, population, *args, **kwargs):
        ptp = population.dtype if population.dtype != t.bool else t.uint8
        dev = population.device
        dim = population.shape[1]
        num_crossovers = self._offsprings // 2
        crossover_indices = t.randint(1, dim, size=(num_crossovers,), dtype=t.long, device=dev)
        parents_indices = self._parental_sampling(len(population), num_crossovers, 2, dev).T
        children = t.zeros((num_crossovers, dim), dtype=ptp, device=dev)
        position_mask = t.arange(dim, device=dev).as_strided((num_crossovers,dim), (0,1))
        lpos = (position_mask < crossover_indices[:, None]).type(t.int8)
        children[:num_crossovers].add_(population[parents_indices[0]] * lpos)
        children[num_crossovers:].add_(population[parents_indices[1]] * lpos)
        rpos = t.logical_not(lpos, out=lpos)
        children[:num_crossovers].add_(population[parents_indices[1]] * rpos)
        children[num_crossovers:].add_(population[parents_indices[0]] * lpos)
        children = children.to(population.dtype)
        pop = self._handle_pop(population, children, parents_indices)
        return (pop, *args), kwargs
\end{lstlisting}
\caption{One--point crossover operator}
\label{alg:implonepoint}
\end{algorithm}

\begin{algorithm}
\begin{lstlisting}[language=Python, xrightmargin=18pt, breaklines=true, postbreak=\mbox{$\hookrightarrow$\space}, literate={\ \ }{{\ }}1]
from typing import Tuple, Any, Dict, Union, Callable
import torch as t
from ffeat import Pipe, flow

class Elitism(Pipe):
    def __init__(self,
                 num_elites,
                 *following_steps,
                 maximization=False):
        self._num_elites = self._handle_parameter(num_elites)
        self._maximization = maximization
        self.__follow = flow.Sequence(*following_steps)

    def __call__(self, fitnesses, population, *args, **kwargs):
        to_select = self._num_elites(fitnesses, population, *args, **kwargs)
        elites_indices = t.topk(fitnesses, to_select, largest=self._maximization)[1]
        elites = t.clone(population[elites_indices])
        (population, *args), kargs = self.__follow(fitnesses, population, *args, **kwargs)
        population[elites_indices] = elites
        return (population, *args), kwargs
\end{lstlisting}
\caption{Elitism operator implementation}
\label{alg:implelitism}
\end{algorithm}


\documentclass{amsart}
 \newcommand{\sm}{\raisebox{2.33pt}{~\rule{6.4pt}{1.3pt}~}}
\begin{document}

\section{Rules}

Let $j\colon U\to X$ be an open immersion, and let ${\mathcal F}$ be a perverse sheaf on $X$.  Let ${\mathcal G}\subset {\mathcal F}$ be the largest subperverse sheaf supported on the complement $X\sm U$.

\end{document}


\begin{appendices}
    \section{Benchmarking Code}\label{code}
    \subsection{Performance Benchmark}
    \subsubsection{Python vs. Cython Benchmark}
    \begin{minted}[mathescape,linenos,frame=lines]{python}
    # Importing Dependencies
    import amsimp
    import time
    import csv
    import os
    import random

    # ---------------------------------------------------#

    # Output filename.
    filename = input("The name of the CSV file: ")
    filename = filename + ".csv"

    # Creates a CSV file.
    def csv_file():
        file = os.path.isfile(filename)
        csvfile = open(filename, "a")

        fieldnames = ["detail_level", "time"]
        writer = csv.DictWriter(
            csvfile, delimiter=",", lineterminator="\n", fieldnames=fieldnames
        )

        if not file:
            writer.writeheader()

        return writer

    # Write data to CSV file.
    def write_data(writer, data):
        writer.writerow(data)

    # ---------------------------------------------------#

    # Number of samples for each level of detail.
    samples = int(input("The number of samples for each level of detail: "))

    # ---------------------------------------------------#

    # Benchmark function.
    def benchmarking(samples):
        # CSV file.
        writer = csv_file()

        # Number of days in this month.
        number_of_days = amsimp.Backend.number_of_days

        # Loop by the number of samples.
        for i in range(samples):
            # Loop by each level of detail.
            for num in range(5):
                # Set level of detail.
                detail = amsimp.Dynamics(num + 1)

                # Start timer.
                start = time.time()

                # Random day of the month.
                random_day = random.randint(0, (number_of_days - 1))

                # Temperature, pressure thickness, precipitable
                # water vapor, and geostrophic wind on a random
                # day of the month.
                temp = (
                    detail.predict_temperature()[0] * random_day
                ) + detail.predict_temperature()[1]
                pressure_thickness = (
                    detail.predict_pressurethickness()[0] * random_day
                ) + detail.predict_pressurethickness()[1]

                if (num + 1) >= 3:
                    u_g = (
                        detail.predict_geostrophicwind()[0] * random_day
                    ) + detail.predict_geostrophicwind()[1]
                    P_wv = (
                        detail.predict_precipitablewater()[0] * random_day
                    ) + detail.predict_precipitablewater()[1]

                # Store runtime in variable.
                finish = time.time()
                runtime = finish - start

                # Write runtime into CSV file.
                write_data(writer, {"detail_level": num + 1, "time": runtime})

                # Sample progress.
                if (num + 1) != 5:
                    print(
                        "Progress of current sample: "
                        + str(int(((num + 1) / 5) * 100))
                        + "%"
                    )

            # Overrall progress.
            if i != (samples - 1):
                print(
                    "Progress: "
                    + str(i + 1)
                    + " samples have been run out of a total of "
                    + str(samples)
                )

        # Benchmark complete.
        print("Benchmarking Complete.")

    # ---------------------------------------------------#
    benchmarking(samples)

    \end{minted}

    \subsubsection{Performance Reliability Benchmark}
    \begin{minted}[mathescape,linenos,frame=lines]{python}
    # Importing Dependencies
    import amsimp
    import time
    from datetime import datetime
    from datetime import timedelta
    import csv
    import os
    import random

    # ---------------------------------------------------#

    # Output filename.
    filename = input("The name of the CSV file: ")
    filename = filename + ".csv"

    # Creates a CSV file.
    def csv_file():
        file = os.path.isfile(filename)
        csvfile = open(filename, "a")

        fieldnames = ["forecast_days", "time"]
        writer = csv.DictWriter(
            csvfile, delimiter=",", lineterminator="\n", fieldnames=fieldnames
        )

        if not file:
            writer.writeheader()

        return writer

    # Write data to CSV file.
    def write_data(writer, data):
        writer.writerow(data)

    # ---------------------------------------------------#

    # Number of samples.
    samples = int(input("The number of samples: "))

    # Error checking.
    if not isinstance(samples, int):
        raise Exception(
            "samples must be an integer. The value of samples was: {}".format(
                samples
            )
        )

    # ---------------------------------------------------#

    # Benchmark function.
    def benchmarking(samples):
        # CSV file.
        writer = csv_file()

        # Loop by the number of samples.
        for i in range(samples):
            s = time.time()

            # Loop by each the number of forecast days.
            for num in range(5):
                # Set the number of forecast days.
                detail = amsimp.Dynamics(5, (num + 1))

                # Start timer.
                start = time.time()

                detail.forecast_temperature()
                detail.forecast_pressure()
                detail.forecast_pressurethickness()
                detail.forecast_precipitablewater()

                # Store runtime in variable.
                finish = time.time()
                runtime = finish - start

                # Write runtime into CSV file.
                write_data(writer, {"forecast_days": num + 1, "time": runtime})

                # Sample progress.
                if (num + 1) != 5:
                    print(
                        "Progress of current sample: "
                        + str(int(((num + 1) / 5) * 100))
                        + "%"
                    )

            # Overrall progress.
            if i != (samples - 1):
                print(
                    "Progress: "
                    + str(i + 1)
                    + " samples have been run out of a total of "
                    + str(samples)
                )
                f = time.time()
                r = f - s
                r *= ((samples - i) - 1)
                finish_time = datetime.now() + timedelta(seconds=+r)
                hour = finish_time.hour
                minute = finish_time.minute
                print(
                    "Benchmarking will be finished at: "
                    + str(hour) + ":" + str(minute)
                )

        # Benchmark complete.
        print("Benchmarking Complete.")

    # ---------------------------------------------------#

    benchmarking(samples)
    \end{minted}

    \subsection{Accuracy Benchmark}
    \begin{minted}[mathescape,linenos,frame=lines]{python}
    """
    Determine the forecast prediction accuracy of AMSIMP.
    """
    # Import dependencies.
    import io
    import requests
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt

    # Read the forecast error csv file into a variable as a Pandas DataFrame.
    file = "url"
    s = requests.get(file).content
    df = pd.read_csv(io.StringIO(s.decode("utf-8")))

    # The x-component of the plots that will be generated.
    days = np.array([1, 2, 3, 4])
    # Utilised to calculate the mean MAPE and MdAPE of a given
    # atmospheric parameter on a given day.
    aggregation_functions = {"mape": "mean", "mdape": "mean", "name": "first"}

    # Deals with anything related to the MAPE.
    mape = df.sort_values(["name", "day"], ascending=[False, True])
    mape = np.split(mape, 4)
    indiviual_mape = df.sort_values(["name", "day"], ascending=[True, True])
    indiviual_mape = np.split(indiviual_mape, 4)

    # Deals with anything related to the MdAPE.
    mdape = df.sort_values(["name", "day"], ascending=[False, True])
    mdape = np.split(mdape, 4)
    indiviual_mdape = df.sort_values(["name", "day"], ascending=[True, True])
    indiviual_mdape = np.split(indiviual_mdape, 4)

    mean = []
    median = []
    list_mape = []
    list_mdape = []

    x = 0
    while x < 4:
        # Calculate the mean MAPE, and MdAPE.
        val1 = mape[x]["mape"].values
        val1 = np.mean(val1)
        val2 = mdape[x]["mdape"].values
        val2 = np.mean(val2)
        mean.append(val1)
        median.append(val2)

        # Determine the MAPE and the MdAPE of the individual atmospheric
        # parameters.
        i_mape = indiviual_mape[x]
        i_mdape = indiviual_mdape[x]

        i_mape = i_mape.groupby(df["day"]).aggregate(aggregation_functions)
        i_mape = i_mape["mape"].values
        i_mape = i_mape.tolist()
        list_mape.append(i_mape)

        i_mdape = i_mdape.groupby(df["day"]).aggregate(aggregation_functions)
        i_mdape = i_mdape["mdape"].values
        i_mdape = i_mdape.tolist()
        list_mdape.append(i_mdape)

        x += 1

    # Colors of the dashed line plots, and labels for the legened of the plot
    colors = ["blue", "green", "red", "orange"]
    names = ["Precipitable Water", "Pressure", "Temperature", "Thickness"]

    def graph(x):
        "Add SALT to the graphs."
        if x == "MAPE":
            y = "Mean"
        else:
            y = "Median"

        plt.xlabel("Forecast Day")
        plt.ylabel(y + " Absolute Percentage Error")
        plt.title("Prediction Accuracy of AMSIMP")
        plt.legend(loc=0)
        plt.savefig(x.lower() + "_graph", dpi=400)
        plt.show()

    # Plot the mean MAPE and the MAPE of the individual atmospheric
    # parameters.
    plt.plot(days, mean, color="black", linestyle="dashed", label="AMSIMP MAPE")
    x = 0
    while x < 4:
        plt.plot(
            days,
            list_mape[x],
            color=colors[x],
            linestyle="dashed",
            label=names[x]
        )

        x += 1
    graph("MAPE")

    # Plot the mean MdAPE and the MdAPE of the individual atmospheric
    # parameters.
    plt.plot(
        days, median,
        color="black",
        linestyle="dashed",
        label="AMSIMP MdAPE"
    )
    x = 0
    while x < 4:
        plt.plot(
            days,
            list_mdape[x],
            color=colors[x],
            linestyle="dashed",
            label=names[x]
        )

        x += 1
    graph("MdAPE")

    print("AMSIMP's MAPE: " + str(np.round(np.mean(df["mape"]), 2)) + "%")
    print("AMSIMP's MdAPE: " + str(np.round(np.mean(df["mdape"]), 2)) + "%")

    \end{minted}

    \subsection{Code Quailty Benchmark}
    \begin{minted}[mathescape,linenos,frame=lines]{python}
    # Import dependencies.
    import matplotlib.pyplot as plt
    import amsimp

    # Define two levels of detail. The variable detail_1 is created to
    # ensure that the methods that require a level of detail of 3, or
    # greater raise an exception when called by a lower level of
    # detail.
    detail = amsimp.Dynamics(5, 2)
    detail_1 = amsimp.Dynamics(1)
    # Ensure detail_level and forecast_days raise an exception when
    # it is appropriate to do so.
    # Ensure detail_level cannot be above 5.
    try:
        detail = amsimp.Dynamics(6)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure detail_level cannot be below 1.
    try:
        detail = amsimp.Dynamics(0)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure forecast_days cannot be above 5.
    try:
        detail = amsimp.Dynamics(3, 6)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure forecast_days cannot be below 1.
    try:
        detail = amsimp.Dynamics(3, 0)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")

    # Make Matplotlib plots interactive, so, they can be closed
    # with the command, plt.close()
    plt.ion()

    # amsimp.Backend
    # Ensure the gravitational_acceleration method functions correctly.
    detail.gravitational_acceleration()
    # Ensure that the methods, temperature and density, function at each
    # level of detail.
    for i in range(5):
        i += 1
        detail_i = amsimp.Backend(i)
        detail_i.latitude_lines()
        detail_i.temperature()
        detail_i.density()
    # Ensure the methods, sigma_coordinates, potential_temperature
    # and exner_function, function correctly.
    detail.potential_temperature()
    detail.exner_function()
    # Ensure that each plot option in the longitude_contourf method functions
    # correctly. Also ensure that an exception is raised when the value of,
    # which, is either greater than 2 or less than 0.
    for i in range(5):
        i -= 1
        if i < 0 or i > 2:
            try:
                detail.longitude_contourf(i)
            except Exception:
                pass
            else:
                raise Exception("Test Failed!")
        else:
            detail.longitude_contourf(i)
    # Ensure that an exception is raised when which is a non-integer
    # number.
    try:
        detail.longitude_contourf(1.5)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure that an exception is raised when, alt, has a value less
    # than 0.
    try:
        detail.longitude_contourf(0, -1)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    detail.altitude_contourf()
    # Ensure that an exception is raised when, which, has a value
    # greater than 0.
    try:
        detail.altitude_contourf(3)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure that an exception is raised when, central_long, has a value
    # greater than 180.
    try:
        detail.altitude_contourf(0, 200)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure that the pressurethickness_contourf method functions correctly.
    detail.pressurethickness_contourf()

    # amsimp.Wind
    # Ensure that the methods, zonal_wind and meridional method, cannot be
    # called when the level of detail is less than 3.
    try:
        detail_1.zonal_wind()
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    try:
        detail_1.meridional_wind()
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure that the zonal and meridional contour plots are generated
    # correctly.
    detail.wind_contourf()
    detail.wind_contourf(1)
    # Ensure that an exception is raised when, which, has a value greater
    # than 1.
    try:
        detail.wind_contourf(2)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure that an exception is raised when, central_long, has a value
    # greater than 180.
    try:
        detail.wind_contourf(0, 200)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure than the globe method functions correctly.
    detail.globe()
    # Ensure that an exception is raised in the globe method where it is
    # appropriate to do so.
    try:
        detail.globe(100)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    try:
        detail.globe(45, 200)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    try:
        detail.globe(45, 90, -1)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")

    # amsimp.water.Water
    # Ensure you cannot call the vapor_pressure method if the value of
    # detail_level is below zero.
    try:
        detail_1.vapor_pressure()
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure the precipitable water method is functioning correctly when
    # sum_altitude has a boolean value of True.
    detail.precipitable_water()
    # Ensure the precipitable water method only accepts boolean values
    # for sum_altitude.
    try:
        detail.precipitable_water(0)
    except Exception:
        pass
    else:
        raise Exception("Test Failed!")
    # Ensure the water_contourf method functions correctly.
    detail.water_contourf()

    # amsimp.dynamics.Dynamics
    detail.simulate()
    \end{minted}

    \newpage

    \section{Contour Plots from AMSIMP}
    \subsection{Backend Class}
    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/pressure.png}
        \caption{Atmospheric Pressure Contour Plot}
    \end{figure}

    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/density.png}
        \caption{Atmospheric Density Contour Plot}
    \end{figure}

    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/temperature.png}
        \caption{Temperature Contour Plot}
    \end{figure}

    \subsection{Wind Class}
    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/zonal_wind.png}
        \caption{Zonal Wind Contour Plot}
    \end{figure}

    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/meridional_wind.png}
        \caption{Meridional Wind Contour Plot}
    \end{figure}

    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/globe.png}
        \caption{Geostrophic Wind (Globe View) Contour Plot}
    \end{figure}

    \subsection{Water and Dynamics Class}
    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/precipitable_water.png}
        \caption{Precipitable Water Contour Plot}
    \end{figure}

    \begin{figure}[H]
        \centering
        \includegraphics[width=.8\linewidth]{Graphs/contour_plots/forecast.png}
        \caption{Motus Aeris @ AMSIMP}
    \end{figure}
\end{appendices}


%Введение и постановка задачи

\section*{Itroduction}
Review of an integration schemes for nonlinear forces been done in
\cite{Danby2013}, By investigating the characteristics of both the non-linear
elastic and the non-linear damped Hertzian contact models, it has been found
that higher orders of accuracy are recoverable and depends on the degree of the
governing non-linear equation. The numerical errors of the linear and non-linear
force models are however markedly different in character.

Symplectic Euler, Forward Euler, Backward Differenced, Runge–Kutta,
Adams–Bashforth been compared \cite{IACOBELLIS2019111373} The recommended solver
for any large scale system would be the Symplectic Euler scheme due to its
ability to produce near sec- ond order results, its general high accuracy,
simple implementation and low storage requirements.

The numerical errors in idealised discrete element method (DEM) simulations are
reviewed in \cite{Hanley2017} The truncation error has a superlinear
relationship with the simulation time-step, $\Delta t$. Reducing $\Delta t$
substantially reduces $\epsilon $; however, increasing the number of time-steps
required in a simulation inevitably increases the round-off error. This implies
that there is an optimal, implementation- specific choice of $\Delta t$, which
minimises the total error.

Efficacy of contact dynamics (CD) in a variety of indeterminate problems, including
some involving multiple materials, non-spherical shapes, and nonlinear contact
constitutive laws been shown in \cite{Olsen2018a}.

A brief overview is given on the capabilities and on the current limitations of
the Discrete Element Method (DEM) coupled with Computational Fluid Mechanics
(CFD) to simulate chemical reacting moving granular material.\cite{Scherer2017}

Impact of particle shape is inspected in \cite{Zhang2020} Simulations show that
sediment particle’s shape effect on its motion is more obvious in laminar flows
rather than in turbulent flows.

Dynamic stability of beam structures for 8, 16 and 32 layers been investigated
at \cite{Smoljanovic2020}

Among Euler, semi-implicit Euler, Runge-Kutta and Leapfrog, we found that
simulation with Leapfrog numerical integration characterizes a mass-spring-damper
system best in terms of the energy loss of the overall system. \cite{Ozguz2011}


% !TEX root = ../../main.tex
% !TEX spellcheck = en_GB
\section{Design}
The design of the MATLAB framework is shown in \cref{fig:classbdd}.

\paragraph{The TransferFunction class} implements the \mintinline{matlab}{plotResponse(f)} method, and the  abstract method \mintinline{matlab}{transform(x)}.
\mintinline{matlab}{plotResponse(f)} plots the amplitude spectrum for the frequency values given by the argument \mintinline{matlab}{f}.
It uses the, implemented by any subclass, \mintinline{matlab}{transform(x)} method to access the frequency response.

\begin{figure}
	\centering
	\includegraphics[width=\linewidth]{gfx/Design/Class_BDD}
	\caption{Class diagram of the MATLAB framework.}
	\label{fig:classbdd}
\end{figure}

\paragraph{The Speaker class} contains the objects necessary to calculate the transfer function for the complete speaker.
It's purpose is to collect the other units, to test them together, and to provide the frequency response to compare with the measured response.

\paragraph{The DriveUnit class} describes the drive unit on the basis of Thiele/Small parameters \cite{thielesmall} and \cref{eq:transdriveunit} \cite[p.~51]{Elektroakustik}.
The \mintinline{matlab}{plotResponse(f)} function plots the response of the drive unit in an infinitely large closed box.

\begin{equation}
	p = \frac{\rho S_D B l U_G}{2\pi r M_{MS} R_E}\frac{s^2}{s^2 +s \left(\frac{(Bl)^2}{R_EM_{MS}}+\frac{R_{MS}}{M_{MS}}\right)+\frac{1}{M_{MS}C_{MS}}}
	\label{eq:transdriveunit}
\end{equation}

\paragraph{The Cabinet class} describes a closed box cabinet, with the possibility to add a number of bass reflexes and check if their locations are valid.
Without bass reflexes \mintinline{matlab}{plotResponse(f)} plots the response in a cabinet of the specified volume, according to \cref{eq:dutfclosed}.
If bass reflexes are present, it should plot the frequency response according to \cref{eq:bassreflex}.

\paragraph{The CrossoverFilter class} is meant to filter the input before it reaches the physical parts of the speaker.
It is meant to either be used to filter the signal in an appropriate way if several drive units are installed, or to try to refine the signal, if the speaker response is not satisfactory.

\paragraph{The BassReflex class} is a bass reflex tube placed somewhere on the cabinet.
It cannot itself show a frequency response, but must be placed in a cabinet.