\section{Results}

\subsection{Miss-use modeling}

\begin{table}[h!]
\footnotesize
\centering
  \caption{Summary of cascades level population.}
\resizebox{\columnwidth}{!}{%
\begin{tabular*}{\linewidth}{c @{\extracolsep{\fill}} cccccccc}
\toprule

Model       &        &                & A/NR     & A/R      & B/NR     & B/R      & C/NR     & C/R       \\
%Recycling   &       &                & No       & Yes      & No       & Yes      & No       & Yes        \\
\midrule
        &            & Feed $w\%$     & $0.71$   & $1.31$   & $0.71$   & $0.92$   & $0.71$   & $1.30$ \\
Level 0 & Assay      & Product $w\%$  & $3.97$   & $7.27$   & $3.97$   & $5.10$   & $3.97$   & $7.24$ \\
        &            & Tails $w\%$    & $0.28$   & $0.52$   & $0.28$   & $0.36$   & $0.28$   & $0.51$ \\
        & Cascades   & Impl. (Ideal)  & 25(26.5) & 25(26.5) & 24(26.4) & 25(26.3) & 25(26.5) & 25(26.2)  \\
\midrule
        &            & Feed $w\%$     & $3.97$   & $11.48$  & $3.97$   & $6.29$   & $3.97$   & $11.64$ \\
Level 1 & Assay      & Product $w\%$  & $21.29$  & $53.30$  & $19.33$  & $27.98$  & $21.41$  & $55.12$ \\
        &            & Tails $w\%$    & $1.68$   & $5.93$   & $1.58$   & $2.54$   & $1.66$   & $5.88$ \\
        & Cascades   & Impl. (Ideal)  & 3(3.1)   & 4(3.1)   & 3(3.1)   & 3(3.1)   & 3(3.1)   & 4(3.4)    \\
\midrule
        &            & Feed $w\%$     & $21.29$  & $53.3$   & $19.33$  & $31.09$  & $21.41$  & $55.12$ \\
Level 2 & Assay      & Product $w\%$  & $76.39$  & $94.70$  & $58.10$  & $72.31$  & $79.21$  & $96.37$ \\
        &            & Tails $w\%$    & $13.98$  & $47.81$  & $8.51$   & $14.91$  & $13.75$  & $49.65$ \\
        & Cascades   & Impl. (Ideal)  & 1(0.4)   & 1(0.4)   & 1(0.4)   & 1(0.5)   & 1(0.4)   & 1(0.4)   \\
\midrule
        &            & Feed $w\%$     & $76.39$  & N.A.     & $58.10$  & $72.31$  & $79.21$  & N.A.      \\
Level 3 & Assay      & Product $w\%$  & $98.09$  & N.A.     & $88.92$  & $93.79$  & $98.86$  & N.A.      \\
        &            & Tails $w\%$    & $73.51$  & N.A.     & $35.01$  & $50.36$  & $76.60$  & N.A.      \\
        & Cascades   & Impl. (Ideal)  & 1(0.04)  & N.A.     & 1(0.09)  & 1(0.1)   & 1(0.04)  & N.A.      \\
\midrule
        &            & Feed $w\%$     & N.A.     & N.A.     & $88.92$  & N.A.     & N.A.     & N.A.      \\
Level 4 & Assay      & Product $w\%$  & N.A.     & N.A.     & $97.89$  & N.A.     & N.A.     & N.A.      \\
        &            & Tails $w\%$    & N.A.     & N.A.     & $75.71$  & N.A.     & N.A.     & N.A.      \\
        & Cascades   & Impl. (Ideal)  & N.A.     & N.A.     & 1(0.04)  & N.A.     & N.A.     & N.A.      \\
\bottomrule
\end{tabular*}
}
\label{tab:level}
\end{table}

As illustrated in Figures \ref{fig:assays} and summarized on Table
\ref{tab:level}, the different models don't have the same effect on the
cascade behavior. While models A and C achieve a quick enrichment gain with
the cascades chaining, 4/21/76/98 and 4/21/79/99, respectively, model B only
achieves an enrichment gain of 4/19/58/89/98, requiring more levels to even
achieve HEU enrichment. This table also shows the integer
number of cascades implemented (Impl.) at each level in the simulation, compared
to the non-integer number of cascades that would achieve an ideal configuration (Ideal).

\begin{figure}[h!]
    \centering
    \begin{subfigure}[t]{0.45\textwidth}
        \centering
        \includegraphics[width=\linewidth]{feed_assays}
        \caption{Feed Assays}
        \label{sfig:feed_assay}
    \end{subfigure}%
    \begin{subfigure}[t]{0.45\textwidth}
        \centering
        \includegraphics[width=\linewidth]{product_assays}
        \caption{Product Assays}
        \label{sfig:product_assay}
    \end{subfigure}
    \begin{subfigure}[t]{0.45\textwidth}
        \centering
        \includegraphics[width=\linewidth]{tails_assays}
        \caption{Tails Assays}
        \label{sfig:tails_assay}
    \end{subfigure}
    \caption{Feed (\subref{sfig:feed_assay}), product
        (\subref{sfig:product_assay}) and tails assays (\subref{sfig:tails_assay})
        in $w\%$ of $^{235}$U, per cascade level from 0 to 4 (purple, red, green,
        orange, blue), per model (A/B/C) and without/with tails recycling (NR/R).
        The black dashed line represents the $90 w\%$ enrichment threshold.}
    \label{fig:assays}
\end{figure}

\subsection{Tails recycling}

As shown in Figures \ref{fig:assays}, recycling the tails increases the overall product assay at
all the different levels, requiring less levels in the configuration to achieve
the desired enrichment. As the tails assay of a level $n+1$ is always higher than
the product assay of the level $n-1$, recycling the tails of level $n+1$ will
consequently increase the feed assay of level $n$ (see Table \ref{tab:level}).
Moreover, with an increased feed assay, tails and product assays increase as
well, increasing de facto the feed assays of respective cascade levels $n-1$
and $n+1$, etc.  This effect reduces the number of cascade levels required to reach
\gls{HEU} in all cases.

\subsection{\gls{HEU} Production Rate}

As shown in Figure \ref{fig:HEU_rate}, recycling increases the final \gls{HEU}
production rate, from $5$ to almost $45$ kg/y when using models A and C, and from
$12$ to $45$ kg/y with the model B. For the reference calculation, where all the
available cascades are used within a single large cascade design for direct
\gls{HEU} production, the \gls{HEU} production rate is slightly over $60$ kg/y.

As models A and C rely on maintaining the cut values at each stage of the
cascade and share the same number of levels, they have the exact same cascade
repartition across the different levels and the same \gls{HEU} production rate.

\begin{figure}[h!] % replace 't' with 'b' to force it to be on the bottom
    \centering
    \includegraphics[scale=0.25]{HEU_prod_rate}
    \caption{Production rate at equilibrium for the different model
        configurations, the case without tails recycling (blue), with tails
        recycling (orange), and the reference one (green). A-B-C represent
        the model used, and NR-R the case without tails recycling and the case
        with tails recycling, respectively.}
    \label{fig:HEU_rate}
\end{figure}


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

\section{Lindenmayer System Drawing Library}

\subsection{Overview}

Lindenmayer systems (also commonly known as ``L-systems''), were originally
developed by Aristid Lindenmayer as a theory of algae growth patterns and then
subsequently used to model branching patterns in plants and produce fractal
patterns. Typically, an L-system consists of a set of symbols, each of which is
associated with some graphical action (such as ``turn left'' or ``move
forward'') and a set of rules (``production'' or ``rewrite'' rules). Given a
string of symbols, the rewrite rules are applied several times and the when
resulting string is processed the action associated with each symbol is
executed.

In \pgfname, L-systems can be used to create simple 2-dimensional fractal
patterns\ldots
%
\begin{codeexample}[
    preamble={\usetikzlibrary{lindenmayersystems}},
    pre={\expandafter\let\csname pgf@lsystem@Koch curve\endcsname=\relax},
]
\begin{tikzpicture}
\pgfdeclarelindenmayersystem{Koch curve}{
  \rule{F -> F-F++F-F}
}

\shadedraw [top color=white, bottom color=blue!50, draw=blue!50!black]
  [l-system={Koch curve, step=2pt, angle=60, axiom=F++F++F, order=3}]
  lindenmayer system -- cycle;
\end{tikzpicture}
\end{codeexample}
%
\noindent\ldots and ``plant like'' patterns\ldots
%
\begin{codeexample}[preamble={\usetikzlibrary{lindenmayersystems}}]
\begin{tikzpicture}
\draw [green!50!black, rotate=90]
  [l-system={rule set={F -> FF-[-F+F]+[+F-F]}, axiom=F, order=4, step=2pt,
   randomize step percent=25, angle=30, randomize angle percent=5}]
  lindenmayer system;
\end{tikzpicture}
\end{codeexample}
%
\noindent \ldots but it is important to bear in mind that even moderately
complex L-systems can exceed the available memory of \TeX, and can be very
slow. If possible, you are advised to increase the main memory and save stack
to their maximum possible values for your particular \TeX{} distribution.
However, even by doing this you may find you still run out of memory quite
quickly.

For an excellent introduction to L-systems (containing some ``really cool''
pictures -- many of which are sadly not possible in \pgfname) see \emph{The
Algorithmic Beauty of Plants} by Przemyslaw Prusinkiewicz and Aristid
Lindenmayer (which is freely available via the internet).

\begin{pgflibrary}{lindenmayersystems}
    This \pgfname-library provides basic commands for defining and using simple
    L-systems. The \tikzname-library provides, furthermore, a front end for
    using L-systems in \tikzname.
\end{pgflibrary}

\subsubsection{Declaring L-systems}

Before an L-system can be used, it must be declared using the following
command:

\begin{command}{\pgfdeclarelindenmayersystem\marg{name}\marg{specification}}
    This command declares a Lindenmayer system called \meta{name}. The
    \meta{specification} argument contains a description of the L-system's
    symbols and rules. Two commands |\symbol| and |\rule| are only defined when
    the \meta{specification} argument is executed.

    \begin{command}{\symbol\marg{name}\marg{code}}
        This defines a symbol called \meta{name} for a specific L-system,
        and associates it with \meta{code}.

        A symbol should consist of a single alpha-numeric character (i.e.,
        |A|-|Z|, |a|-|z| or |0|-|9|). The symbols |F|, |f|, |+|, |-|, |[| and
        |]| are available by default so do not need to be defined for each
        L-system. However, if you are feeling adventurous, they can be
        redefined for specific L-systems if required. The L-system treats the
        default symbols as follows (the commands they execute are described
        below):
        %
        \begin{itemize}
            \item |F| move forward a certain distance, drawing a line. Uses
                |\pgflsystemdrawforward|.
            \item |f| move forward a certain distance, without drawing a line.
                Uses |\pgflsystemmoveforward|.
            \item |+| turn left by some angle. Uses |\pgflsystemturnleft|.
            \item |-| turn right by some angle. Uses |\pgflsystemturnright|.
            \item |[| save the current state (i.e., the position and
                direction). Uses |\pgflsystemsavestate|.
            \item |]| restore the last saved state. Uses
                |\pgflsystemrestorestate|.
        \end{itemize}

        The symbols |[| and |]| act like a stack: |[| pushes the state of the
        L-system on to the stack, and |]| pops a state off the stack.

        When \meta{code} is executed, the transformation matrix is set up so
        that the origin is at the current position and the positive x-axis
        ``points forward'', so |\pgfpathlineto{\pgfpoint{1cm}{0cm}}| draws a
        line 1cm forward.

        The following keys can alter the production of an L-system. However,
        they do not store values in themselves.

        \begin{key}{/pgf/lindenmayer system/step=\meta{length} (initially 5pt)}
            How far the L-system moves forward if required. This key sets the
            \TeX{} dimension |\pgflsystemstep|.
        \end{key}

        \begin{key}{/pgf/lindenmayer system/randomize step percent=\meta{percentage} (initially 0)}
            If the step is to be randomized, this key specifies by how much.
            The value is stored in the \TeX{} macro
            |\pgflsystemrandomizesteppercent|.
        \end{key}

        \begin{key}{/pgf/lindenmayer system/left angle=\meta{angle} (initially 90)}
            This key sets the angle through which the L-system turns when it
            turns left. The value is stored in the \TeX{} macro
            |\pgflsystemrleftangle|.
        \end{key}

        \begin{key}{/pgf/lindenmayer system/right angle=\meta{angle} (initially 90)}
            This key sets the angle through which the L-system turns when it
            turns right. The value is stored in the \TeX{} macro
            |\pgflsystemrrightangle|.
        \end{key}

        \begin{key}{/pgf/lindenmayer system/randomize angle percent=\meta{percentage} (initially 0)}
            If the angles are to be randomized, this key specifies by how much.
            The value is stored in the \TeX{} macro
            |\pgflsystemrandomizeanglepercent|.
        \end{key}

        For speed and convenience, when the code for a symbol is executed, the
        following commands are available.

        \begin{command}{\pgflsystemcurrentstep}
            The current ``step'' of the L-system (i.e., how far the system
            will move forward if required). This is initially set to the
            value in the \TeX-dimensions |\pgflsystemstep|, but the actual
            value may be changed if |\pgflsystemrandomizestep| is used
            (see below).
        \end{command}

        \begin{command}{\pgflsystemcurrentleftangle}
            The angle the L-system will turn when it turns left.
            The value stored in this macro may be changed if
            |\pgflsystemrandomizeleftangle| is used.
        \end{command}

        \begin{command}{\pgflsystemcurrentrightangle}
            The angle the L-system will turn when it turns right.
            The value stored in this macro may be changed if
            |\pgflsystemrandomizerightangle| is used.
        \end{command}

        The following commands may be useful if you wish to define your own
        symbols.

        \begin{command}{\pgflsystemrandomizestep}
            Randomizes the value in |\pgflsystemcurrentstep| according to the
            current value of the key |randomize step percent|.
        \end{command}

        \begin{command}{\pgflsystemrandomizeleftangle}
            Randomizes the value in |\pgflsystemcurrentleftangle| according to
            the value of the |randomize angle percent| key.
        \end{command}

        \begin{command}{\pgflsystemrandomizerightangle}
            Randomizes the value in |\pgflsystemcurrentrightangle| according
            to the value of the |randomize angle| key.
        \end{command}

        \begin{command}{\pgflsystemdrawforward}
            Move forward in the current direction, by |\pgflsystemcurrentstep|,
            drawing a line in the process. This macro calls
            |\pgflsystemrandomizestep|. Internally, \pgfname{} simply shifts
            the transformation matrix in the positive direction of the current
            (transformed) x-axis by |\pgflsystemstep| and then executes a
            line-to to the (newly transformed) origin.
        \end{command}

        \begin{command}{\pgflsystemmoveforward}
            Move forward in the current direction, by |\pgflsystemcurrentstep|,
            without drawing a line. This macro calls
            |\pgflsystemrandomizestep|. \pgfname{} executes a transformation as
            above, but executes a move-to to the (newly transformed) origin.
        \end{command}

        \begin{command}{\pgflsystemturnleft}
            Turn left by |\pgflsystemcurrentleftangle|. Internally, \pgfname{}
            simply rotates the transformation matrix. This macro calls
            |\pgflsystemrandomizeleftangle|.
        \end{command}

        \begin{command}{\pgflsystemturnright}
            Turn right by |\pgflsystemcurrentrightangle|. Internally,
            \pgfname{} simply rotates the transformation matrix. This macro
            calls |\pgflsystemrandomizerightangle|.
        \end{command}

        \begin{command}{\pgflsystemsavestate}
            Save the current position and orientation. Internally, \pgfname{}
            simply starts a new \TeX-group.
        \end{command}

        \begin{command}{\pgflsystemrestorestate}
            Restore the last saved position and orientation. Internally,
            \pgfname{} closes a \TeX-group, restoring the transformation matrix
            of the outer scope, and a move-to command is executed to the
            (transformed) origin.
        \end{command}
    \end{command}

    \begin{command}{\rule{\ttfamily\char`\{}\meta{head}{\ttfamily->}\meta{body}{\ttfamily\char`\}}}
        Declare a rule. \meta{head} should consist of a single symbol, which
        need not have been declared using |\symbol| or exist as a default
        symbol (in fact, the more interesting L-systems depend on using symbols
        with no corresponding code, to control the ``growth'' of the system).
        \meta{body} consists of a string of symbols, which again need not
        necessarily have any code associated with them.
    \end{command}

    As an example, the following shows an L-system that uses some of these
    commands. This example illustrates the point that some symbols, in this
    case |A| and |B|, do not have to have code associated with them. They
    simply control the growth of the system.
    %
\begin{codeexample}[
    preamble={\usetikzlibrary{lindenmayersystems}},
    pre={\nullfont\expandafter\let\csname pgf@lsystem@Hilbert curve\endcsname=\relax},
]
\pgfdeclarelindenmayersystem{Hilbert curve}{
  \symbol{X}{\pgflsystemdrawforward}
  \symbol{+}{\pgflsystemturnright} % Explicitly define + and - symbols.
  \symbol{-}{\pgflsystemturnleft}
  \rule{A -> +BX-AXA-XB+}
  \rule{B -> -AX+BXB+XA-}
}
\tikz\draw[lindenmayer system={Hilbert curve, axiom=A, order=4, angle=90}]
  lindenmayer system;
\end{codeexample}
    %
\end{command}

\subsection{Using Lindenmayer Systems}

\subsubsection{Using L-Systems in PGF}

The following command is used to run an L-system in \pgfname:
%
\begin{command}{\pgflindenmayersystem\marg{name}\marg{axiom}\marg{order}}
    Runs the L-system called \meta{name} using the input string \meta{axiom}
    for \meta{order} iterations. In general, prior to calling this command, the
    transformation matrix should be set appropriately for shifting and
    rotating, and a move-to to the (transformed) origin should be executed.
    This origin will be where the L-system starts. In addition, the relevant
    keys should be set appropriately.
    %
\begin{codeexample}[preamble={\usetikzlibrary{lindenmayersystems}}]
\begin{tikzpicture}
  \draw [help lines] grid (3,2);
  \pgfset{lindenmayer system/.cd, angle=60, step=2pt}
  \foreach \x/\y in {0cm/1cm, 1.5cm/1.5cm, 2.5cm/0.5cm, 1cm/0cm}{
    \pgftransformshift{\pgfqpoint{\x}{\y}}
    \pgfpathmoveto{\pgfpointorigin}
    \pgflindenmayersystem{Koch curve}{F++F++F}{2}
    \pgfusepath{stroke}
  }
\end{tikzpicture}
\end{codeexample}

    Note that it is perfectly feasible for an L-system to define special
    symbols which perform the move-to and use-path operations.
    %
\end{command}

\subsubsection{Using L-Systems in Ti\emph{k}Z}

In \tikzname, an L-system is created using a path operation. However,
\tikzname{} is more flexible regarding the positioning of the L-system and also
provides keys to create L-systems ``on-line''.

\begin{pathoperation}{lindenmayer system}{ \opt{|[|\meta{keys}|]|}}
    This will run an L-system according to the parameters specified in
    \meta{keys} (which can also contain normal \tikz{} keys such as |draw| or
    |thin|). The syntax is flexible regarding the L-system parameters and the
    following all do the same thing:
    %
\begin{codeexample}[code only]
\draw lindenmayer system [lindenmayer system={Hilbert curve, axiom=4, order=3}];
\end{codeexample}

\begin{codeexample}[code only]
\draw [lindenmayer system={Hilbert curve, axiom=4, order=3}] lindenmayer system;
\end{codeexample}

\begin{codeexample}[code only]
\tikzset{lindenmayer system={Hilbert curve, axiom=4, order=3}}
\draw lindenmayer system;
\end{codeexample}
    %
\end{pathoperation}

\begin{pathoperation}{l-system}{ \opt{|[|\meta{keys}|]|}}
    A more compact version of the |lindenmayer system| path command.
\end{pathoperation}

This library adds some additional keys for specifying L-systems. These keys
only work in \tikzname{} and all have the same path, namely, |/pgf/lindenmayer|
|system|, but the following keys are provided for convenience, so that you do
not have to keep repeating this path:

\begin{stylekey}{/pgf/lindenmayer system=\marg{keys}}
\keyalias{tikz}
    This key changes the key path to |/pgf/lindenmayer systems| and executes
    \meta{keys}.
\end{stylekey}

\begin{stylekey}{/pgf/l-system=\marg{keys}}
\keyalias{tikz}
    A more compact version of the previous key.
\end{stylekey}

\begin{key}{/pgf/lindenmayer system/name=\marg{name}}
    Sets the name for the L-system.
\end{key}

\begin{key}{/pgf/lindenmayer system/axiom=\marg{string}}
    Sets the axiom (or input string) for the L-system.
\end{key}

\begin{key}{/pgf/lindenmayer system/order=\marg{integer}}
    Sets the number of iterations the L-system will perform.
\end{key}

\begin{key}{/pgf/lindenmayer system/rule set=\marg{list}}
    This key allows an (anonymous) L-system to be declared ``on-line''. There
    is, however, a restriction that only the default symbols can be used for
    drawing (empty symbols can still be used to control the growth of the
    system). The rules in \meta{list} should be separated by commas.
    %
\begin{codeexample}[preamble={\usetikzlibrary{lindenmayersystems}}]
\tikz[rotate=65]\draw [green!60!black] l-system
  [l-system={rule set={F -> F[+F]F[-F]}, axiom=F, order=4, angle=25,step=3pt}];
\end{codeexample}
    %
\end{key}

\begin{key}{/pgf/lindenmayer system/anchor=\meta{anchor}}
    Be default, when this key is not used, the L-system will start from the
    last specified coordinate. By using this key, the L-system will be placed
    inside a special (rectangle) node which can be positioned using
    \meta{anchor}.
    %
\begin{codeexample}[preamble={\usetikzlibrary{lindenmayersystems}}]
\begin{tikzpicture}[l-system={step=1.75pt, order=5, angle=60}]
  \pgfdeclarelindenmayersystem{Sierpinski triangle}{
    \symbol{X}{\pgflsystemdrawforward}
    \symbol{Y}{\pgflsystemdrawforward}
    \rule{X -> Y-X-Y}
    \rule{Y -> X+Y+X}
  }
  \draw [help lines] grid (3,2);
  \draw [red] (0,0) l-system
    [l-system={Sierpinski triangle, axiom=+++X, anchor=south west}];
  \draw [blue] (3,2) l-system
    [l-system={Sierpinski triangle, axiom=X, anchor=north east}];
\end{tikzpicture}
\end{codeexample}
    %
\end{key}


\documentclass[]{article}
\usepackage{graphicx}
\usepackage{caption}
\graphicspath{ {./images/} }

% Minted
\usepackage[cache=false]{minted}
	\usemintedstyle{vs}
	\usepackage{xcolor}
		\definecolor{light-gray}{gray}{0.97}

\usepackage{enumitem}

\title{Data Mining: Exercise 1-2}
\author{Brandon Hosley}
\date{\today}

\begin{document}
\maketitle

\vspace{3em}

\subsection*{Q1: Import Data}
\emph{Import the data, trucks.csv and create a DataFrame, named df4. \\
	Should be loaded using csv formatting and have headers, so that we can specify columns later} \\
	\includegraphics[width=\linewidth]{image1}
\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
>>> df4 = spark.read.format("csv").option("header", "true").load("/user/bhosl2/Geolocation/geolocation.csv")
\end{minted}

\clearpage
\subsection*{Q2: }
\emph{Write scripts to create another DataFrame, df5,
	that has normalized/scaled feature vector and
	show 10 rows of the DataFrame.}
	\begin{itemize}[before=\itshape,font=\normalfont]
		\item It should have 6 columns: truckid, driverid, event, velocity, features, and scaled Features Velocity column has numerical data.
		\item The data of some columns (truckid, driverid, event, and velocity) should copied from the DataFrame, df4
		\item The column, ‘features’, should have a feature vector transformed from velocity column. The feature vector should have float-type data. e.g. [0.123]
		\item The column, ‘scaledFeatures’, should have a scaled feature vector. The feature vector should have rescaled values (float-type) to a specific range, [0, 1] with MinMaxScale from features column.
	\end{itemize}

\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
>>> from pyspark.ml.feature import VectorAssembler
>>> from pyspark.ml.feature import MinMaxScaler
>>> from pyspark.sql.types import IntegerType
>>>
>>> assembler = VectorAssembler(inputCols=["velocity"], outputCol="features")
>>> df4 = df4.withColumn("velocity", df4["velocity"].cast("float"))
>>> df4 = assembler.transform(df4)
>>> scaler = MinMaxScaler(inputCol="features", outputCol="scaledFeatures")
>>> scalerModel = scaler.fit(df4)
>>> df5 = scalerModel.transform(df4)
>>> df5.select("truckid", "driverid", "event", "velocity", "features", "scaledFeatures").show(10)
\end{minted}

\includegraphics[width=\linewidth]{image2}

\clearpage
\subsection*{Q3: }
\emph{Write scripts to create another DataFrame, df6,
	that has a binary sparse vector transformed from
	categorical variable (column) and show 10 rows of the DataFrame.} \\
	\begin{itemize}[before=\itshape,font=\normalfont]
		\item It should have 6 columns: truckid, driverid, event, city, cityIndex, and cityVec
		\item The data of some columns (truckid, driverid, event, and city) should copied from the DataFrame, df4
		\item City column has categorical data.
		\item The column, ‘cityIndex’, should have float-type index data, e.g. 0.0 transformed/encoded from city column.
		\item The column, ‘cityVec’, should have a binary sparse vector, e.g. (10, [7], [1.0]), transformed from cityIndex column to be used in some data mining/machine learning algorithms
`	\end{itemize}

\begin{minted}[breaklines,bgcolor=light-gray,fontsize=\footnotesize]{shell-session}
from pyspark.ml.feature import StringIndexer, OneHotEncoderEstimator

df6 = df4.select("truckid", "driverid", "event", "city")
indexer = StringIndexer(inputCol="city", outputCol="cityIndex")
df6 = indexer.fit(df6).transform(df6)
encoder = OneHotEncoderEstimator(inputCols=["cityIndex"], outputCols=["cityVec"])
df6 = encoder.fit(df6).transform(df6)
df6.show(10)
\end{minted}

\includegraphics[width=\linewidth]{image3}

\end{document}


%\usepackage[latin1]{inputenc}
%\usepackage{amsmath}
%\usepackage{amsfonts}
%\usepackage{amssymb}
%\usepackage[active]{srcltx} %for kdvi and kile
%\usepackage{epsfig}         %for the figures
%\usepackage{verbatim}       %for the comment-environment

%\newtheorem{example}{Example}

%\newenvironment{code}{\begin{verbatim}}{\end{verbatim}}

\section{Example: A triangle and its altitudes}
    We want to create an applet which draws a triangle with three moveable
    points and computes the altitudes.

    \subsection*{The canvas}
      Generally for any visualization we need a so called "canvas" (or several
      of them) to draw our objects of visualization. The \appfac for this
      purpose provides different predefined canvases, such as a single or a
      side-by-side canvas for both Graphics2D or Java3D applets. Any applet
      therefore shall extend one of the abstract classes
      \begin{itemize}
        \item \verb SingleG2DCanvasApplet ,
        \item \verb SideBySideG2DCanvasApplet ,
        \item \verb SingleJ3DCanvasApplet , or
        \item \verb SideBySideJ3DCanvasApplet .
      \end{itemize}
      There is also an an applet skeleton for pure symbolic displaying with no
      canvas, the \verb NoCanvasApplet .

    \subsection*{The methods init() and initializeObjects()}
      The method \verb init()  is called from the applet context (i.e. the browser or appletviewer)
      or by a wrapper-main method (don`t forget, your applet won't work otherwise!). It calls at least
      the method \verb initializeObjects(),  and adds all created
      objects to the canvas.

      With an empty implementation,  we can already have a look at our efforts
      (see below) until now. As can be seen, some control
      icons are automatically added as well as a standard \mbox{"help"-button}.
        \begin{footnotesize}
        \begin{verbatim}
import net.mumie.mathletfactory.appletskeleton.g2d.SingleG2DCanvasApplet;
import net.mumie.mathletfactory.util.BasicApplicationFrame;

public class TriangleAltitude extends SingleG2DCanvasApplet{

  public void init() {
    super.init();
    setTitle("Triangle Altitude Applet");
    initializeObjects();
  }

  protected void initializeObjects(){
  }

  public static void main(String[] args){
    TriangleAltitude myApplet = new TriangleAltitude();
    myApplet.init();
    BasicApplicationFrame f = new BasicApplicationFrame(myApplet,500);
    f.pack();
    f.setVisible(true);
  }
}
        \end{verbatim}
        \end{footnotesize}
        \begin{center}
	  \resizebox*{7cm}{!}{\includegraphics{images/triangleAltitudeFirst}}\\
        {\sf A single canvas applet.}\\
        \label{singlecanvas}
        \end{center}
    \subsection*{Number classes}
      Almost all objects are based on a so called number class like
      \verb MDouble ,  \verb MRational ,  \verb MInteger ,  or
      \verb MComplex .  They represent the real (with IEEE \verb double  precision), rational, natural, or complex
      numbers. All computations are done within this class.
    \subsection*{Affine2DPoints}
      For the triangle we need three points A, B, C. They are realized by a so called
      \verb MMAffine2DPoint  and defined by the representing number class and the coordinates:
      \begin{footnotesize}
      \begin{verbatim}
A = new MMAffine2DPoint(MDouble.class, -0.3, 0.3);
B = new MMAffine2DPoint(MDouble.class, 0.25, 0.25);
C = new MMAffine2DPoint(MDouble.class, -0.25, -0.25).
      \end{verbatim}
      \end{footnotesize}
      \vspace{-0.8cm}
    \subsection*{MouseTranslateHandler and KeyboardTranslateHandler}
      Since we want the points to be moveable by mouse and keyboard we create a
      so called \verb Affine2DMouseTranslateHandler  and an
      \verb Affine2DKeyboardTranslateHandler  and add them to the points:
      \begin{footnotesize}
      \begin{verbatim}
amth = new Affine2DMouseTranslateHandler(getCanvas());
akth = new Affine2DKeyboardTranslateHandler(getCanvas());
A.addHandler(akth);     A.addHandler(amth);
B.addHandler(akth);     B.addHandler(amth);
C.addHandler(akth);     C.addHandler(amth);
      \end{verbatim}
      \end{footnotesize}
      \vspace{-0.8cm}
    \subsection*{Affine2DLineSegments}
      Now we need some line segments to connect the points of the triangle:
      \begin{verbatim}
AB = new MMAffine2DLineSegment(A,B);
BC = new MMAffine2DLineSegment(B,C);
CA = new MMAffine2DLineSegment(C,A).
      \end{verbatim}
      \vspace{-0.3cm}
      We also need line segments which represent the altitudes:
      \begin{verbatim}
altitude_AB = new MMAffine2DLineSegment(C,getPerpendicularFoot(A,B,C));
altitude_BC = new MMAffine2DLineSegment(A,getPerpendicularFoot(B,C,A));
altitude_CA = new MMAffine2DLineSegment(B,getPerpendicularFoot(C,A,B)).
      \end{verbatim}
      \vspace{-0.3cm}
      The method \verb getPerpendicularFoot()  returns a
      \verb MMAffine2DPoint  representing the footpoint of the altitude.
      Some mathematical computation is
      done within this method which is not of interest for us now.

      Maybe the footpoint of an altitude does not lie on an edge of the
      triangle. So we extend the edges by another line segment:
      \begin{footnotesize}
      \begin{verbatim}
aFootC = new MMAffine2DLineSegment(A,getPerpendicularFoot(A,B,C));
bFootC = new MMAffine2DLineSegment(B,getPerpendicularFoot(A,B,C));
bFootA = new MMAffine2DLineSegment(B,getPerpendicularFoot(B,C,A));
cFootA = new MMAffine2DLineSegment(C,getPerpendicularFoot(B,C,A));
cFootB = new MMAffine2DLineSegment(C,getPerpendicularFoot(C,A,B));
aFootB = new MMAffine2DLineSegment(A,getPerpendicularFoot(C,A,B)).
      \end{verbatim}
      \end{footnotesize}
      \vspace{-0.8cm}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \subsection*{Add objects to the canvas}
      Now all objects are created we have to add them to the canvas:\\\\
\begin{tabular}{l|l}
\begin{minipage}{6.5cm}
\begin{footnotesize}
\begin{verbatim}
getCanvas().addObject(A);
getCanvas().addObject(B);
getCanvas().addObject(C);

getCanvas().addObject(altitude_AB);
getCanvas().addObject(altitude_BC);
getCanvas().addObject(altitude_CA);
\end{verbatim}
\end{footnotesize}
\end{minipage}
&\begin{minipage}{6cm}
\begin{footnotesize}
\begin{verbatim}
getCanvas().addObject(AB);
getCanvas().addObject(BC);
getCanvas().addObject(CA);

getCanvas().addObject(aFootC);
getCanvas().addObject(bFootC);
getCanvas().addObject(cFootA);
getCanvas().addObject(cFootB);
getCanvas().addObject(aFootB);
getCanvas().addObject(bFootA);
\end{verbatim}
\end{footnotesize}
\end{minipage}
\end{tabular}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \subsection*{Display Properties}
      As can be seen in figure ??? all the lines and points have the standard
      color black. If we want to give them another color we have to define
      \verb PointDisplayProperties   and \verb LineDisplayProperties  and set
      them for the points and lines:
      \begin{footnotesize}
      \begin{verbatim}
private PointDisplayProperties pp = new PointDisplayProperties();
private LineDisplayProperties ll = new LineDisplayProperties();
private LineDisplayProperties mm = new LineDisplayProperties();
private LineDisplayProperties kk = new LineDisplayProperties();

\end{verbatim}
\end{footnotesize}
\begin{tabular}{l|l}
\begin{minipage}{7cm}
\begin{footnotesize}
\begin{verbatim}

pp.setObjectColor(Color.blue);
ll.setObjectColor(Color.red);
mm.setObjectColor(Color.red);
mm.setFilled(false);
kk.setObjectColor(Color.yellow);

A.setDisplayProperties(pp);
B.setDisplayProperties(pp);
C.setDisplayProperties(pp);

altitude_AB.setDisplayProperties(kk);
altitude_BC.setDisplayProperties(kk);
altitude_CA.setDisplayProperties(kk);

\end{verbatim}
\end{footnotesize}
\end{minipage}
&\begin{minipage}{6cm}

\begin{footnotesize}
\begin{verbatim}

AB.setDisplayProperties(ll);
BC.setDisplayProperties(ll);
CA.setDisplayProperties(ll);

aFootC.setDisplayProperties(mm);
bFootC.setDisplayProperties(mm);
bFootA.setDisplayProperties(mm);
cFootA.setDisplayProperties(mm);
cFootB.setDisplayProperties(mm);
aFootB.setDisplayProperties(mm);

\end{verbatim}
\end{footnotesize}
\end{minipage}
\end{tabular}

The result can be seen in figure ??.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \subsection*{Dependency}
      Now our points are moveable but the lines do not move with them.
      Obviously the position of the lines depend on the position of the points.
      This is described by a so called \verb DependencyAdapter  and the
      method \verb dependsOn().  For example for the edges of the triangle we
      have
      \begin{footnotesize}
      \begin{verbatim}
DependencyAdapter DPA = new DependencyAdapter() {
  public void doUpdate(MMObjectIF dependant, MMObjectIF[] free) {
    MMAffine2DLineSegment line = (MMAffine2DLineSegment) dependant;
    line.setInitialPoint((MMAffine2DPoint)free[0]);
    line.setEndPoint((MMAffine2DPoint)free[1]);
  }
};
AB.dependsOn(new MMObjectIF[]{A,B},DPA);
BC.dependsOn(new MMObjectIF[]{B,C},DPA);
CA.dependsOn(new MMObjectIF[]{C,A},DPA);
      \end{verbatim}
      \end{footnotesize}
      \vspace{-0.3cm}
      Hereby the first argument \verb new  \verb MMObjectIF[]{A,B}  of the
      method \verb dependsOn()  is an array of objects on which the object
      \verb AB  depends. This array is passed to the
      method \verb doUpdate  in the \verb DependencyAdapter  \verb DPA  as
      parameter \verb free.  \verb AB  is passed to the
      method \verb doUpdate  in the \verb DependencyAdapter  as parameter
      \verb dependent.  \verb doUpdate  describes the action to perform when
      an object of the array \verb free  is changed.
    \subsection*{Reset, Screenshot, About this applet button}
      With the commands
      \begin{verbatim}
addResetButton();
addScreenShotButton();
      \end{verbatim}
      \vspace{-0.3cm}
      we can add a reset and a screenshot button. The functionality of the
      reset button is defined in the method \verb reset(),  which calls the
      method \verb initializeObjects()  and repaints the canvas:
      \begin{footnotesize}
      \begin{verbatim}
public void reset(){
  initializeObjects();
  getCanvas().renderScene();
  getCanvas().repaint();
}.
      \end{verbatim}
      \end{footnotesize}
      \vspace{-0.3cm}
    A HTML-description of the functionality of the applet can be saved in a
    file with the name \verb <class_name>_info.html. This desciption is opend
    in another window by clicking the about-this-applet button.\\

    \begin{center}
	\resizebox*{6cm}{!}{\includegraphics{images/triangle_altitudes}}\\
	{\sf The completed applet}
    \end{center}
    Now our first applet is ready. The full program can be found in the Appendix (TriangleAltitude).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	\subsection*{Summary: Building Mathlets}
	\label{building_mathlets}
	These examples should illuminate the process of rapid applet development. The linear process
	model we used can be generalized to the following steps:

	\begin{enumerate}
	\item Choose the display type and numbers of displays to be used and extend the corresponding applet skeleton.
	\item Add the chosen mmobjects and their iconic or symbolic representations
	\item Add necessary handlers
	\item Create the update graph by adding updaters and creating dependencies
	\end{enumerate}


\documentclass{article}
\usepackage{amsmath, amssymb, textcomp}
\usepackage{graphicx}
\usepackage{cite}
\usepackage[hidelinks]{hyperref}
\usepackage[section]{placeins}

\newcommand{\Part}[3][ ]{\ensuremath{\frac{\partial^{#1} #2}{{\partial #3}^{#1}}}}
\newcommand{\Dif}[3][ ]{\ensuremath{\frac{d^{#1} #2}{{d #3}^{#1}}}}
\renewcommand{\O}[1]{\ensuremath{\mathcal{O}\left(#1\right)}}
\renewcommand{\vec}{\bold}

\begin{document}
\title{Plasma Analysis}
\author{Tobias de Jong \& David Kok}
\date{\today}
\maketitle
\section{Introduction}
We will use CUDA to efficiently calculate the topological properties of magnetic field lines as generated by Chris Smiet's simulations.\cite{PhysRevLett.115.095001}\\
To implement the code we were inspired by Marek Fiser.\footnote{\url{http://www.marekfiser.com/Projects/Real-time-visualization-of-3D-vector-field-with-CUDA}}
\section{Data representation}
The dataset we use is a set of $256^3$ points in a regular rectangular grid for which the $(x,y,z)$ components of the magnetic field are given. This sort of dataset has a strong correspondence with a 3D texture on a GPU. Using this representation in CUDA has several advantages, of which the hardware trilinear interpolation is the most notable.
\section{Coordinate systems}
Troughout the analysis we use three coordinate systems: cartesian $(x,y,z)$, spherical $(r,\theta,\phi)$ and toroidal $(s,\alpha, \beta)$. We use cartesian as the original dataset is cartesian and this yields the simplest line integrators. For the analysis it will however be beneficial to think in toroidal coordinates:
\[(s,\alpha,\beta)\in ([0,r_{max}],[0,2\pi],[0,2\pi])\]
where $\alpha$ is the angle in the horizontal plane, corresponding to $\theta$ in spherical coordinates, $s$ is the (shortest) distance to the core of the torus, and $\beta$ is the remaining angle on the torus, in the $r,\phi$-plane.
\subsection{Conversion}
To calculate the toroidal coordinates, we first need to know the location of the core of the torus. To do this, we can first convert the coordinates of a (set of) field line(s) to spherical, after which we can take the mean $r$ and $\phi$. So this yields a radius to the core of the torus $r_t$ and an elevation $\phi_t$. It might be beneficial to eliminate this elevation by translating the original system over the $z$-axis such that the elevation is equal to zero.\\
For a torus with a large radius (radius between the core of the torus and the central point of the torus) $r_t$ and inner radius (radius between the core of the torus and the surface of the torus) $r_{max}$ the conversion formulae between Cartesian and Toroidal coordinates are given by:
\begin{align*}
x &= \cos(\alpha)(r_{t}+\cos(\beta)r_{max})\\
y &= \sin(\alpha)(r_{t}+\cos(\beta)r_{max})\\
z &= r_{max}\sin(\beta)\\
\alpha &= \arctan\left(\frac{y}{x}\right)\\
\beta &= \arctan\left(\frac{z}{\sqrt{x^2+y^2}-r_{t}}\right)\\
d\alpha &= \frac{xdy-ydx}{x^2+y^2}\\
d\beta &= \frac{1}{\rho^2+z^2}\left(\rho dz - \frac{z}{\rho}(xdx+ydy)\right) &\text{(Where $\rho = \sqrt{x^2+y^2}-r_{t}$)}\\
\end{align*}
\section{Analysis}
The primary winding number for a field line is in toroidal coordinates simply given by:
\[N_w = \frac{\int d\alpha}{\int d\beta}\]
There are two ways of computing these integrals. We can either use the formulae for $d\alpha$ and $d\beta$ given above and integrate those numerically, or we can compute the $\alpha$ and $\beta$-value at each point along our line, check when they jump by $2\pi$ and then compare the last and the first value to find the integral. Since the numerical integration introduces another texture fetch, another integration error and seems computationally more expensive per point we will use the conversion method.
\bibliographystyle{plain}
\bibliography{introduction}
\end{document}


%!TEX root = ../copatterns-thesis.tex
\chapter{Copatterns Implementation}

\section{Desugaring}
% Why do we want to desugar?
Codata definitions and record definitions with projections, along with function definitions described with copatterns, can all be written using existing Idris constructs. In particular, we consider a function such as \texttt{dup} given in Figure\,\ref{fig:dup_copatterns} to be syntactic sugar for the definition given in Figure\,\ref{fig:dup_desugared}. Likewise, the definition of the coinductively defined Stream type with projections is desugared into a constructor-based definition with exactly one constructor.

\begin{figure}
\begin{lstlisting}
corecord Stream : Type -> Type where
  head : Stream a -> a
  tail : Stream a -> Stream a
  constructor mkStream

--| dupNth s n m duplicates every nth element of s,
--| starting with the mth element
dupNth : Stream a -> Nat -> Nat -> Stream a
head       (dupNth s n m)       = head s
head (tail (dupNth s n Z))      = head s
head (tail (dupNth s n (S m'))) = head (tail s)
tail (tail (dupNth s n Z))      = tail (dupNth s n n)
tail (tail (dupNth s n (S m'))) = tail (dupNth (tail s) n m')
\end{lstlisting}
\caption{A duplication function on streams, defined with copatterns.}
\label{fig:dup_copatterns}
\end{figure}

\begin{figure}
\begin{lstlisting}
codata Stream : Type -> Type where
  mkStream : a -> Stream a -> Stream a

head : Stream a -> a
head (mkStream h _) = h

tail : Stream a -> a
tail (mkStream _ t) = t

dupNth : Stream a -> Nat -> Nat -> Stream a
dupNth s n Z      =
  mkStream (head s)
           (mkStream (head s)
                     (tail (dupNth s n n)))
dupNth s n (S m') =
  mkStream (head s)
           (mkStream (head (tail s))
                     (tail (dupNth (tail s) n m')))
\end{lstlisting}
\caption{A desugared version of the program described in Figure \ref{fig:dup_copatterns}.}
\label{fig:dup_desugared}
\end{figure}

In order to define the desugaring mechanism which allows us to straightforwardly transform programs from a projection-based form to a constructor-based form, we recall that each projection in a type definition defines an elimination rule for that type. For a general coinductive type with product structure $\nu A. B_1 \times B_2 \times \cdots \times B_n$ where $A$ may occur in any of the types $B_i$ (for $1 \leq i \leq n$), we can define \textit{n} elimination rules in the style of Harper\,\cite[Ch. 15]{Harper:2012} as shown in Figure\,\ref{fig:nuA_elim_rules}. Since these rules define all of the ways we can eliminate a value of the given type, we can synthesize them into a single introduction rule which has \textit{n} premises; one for the result of each elimination rule. This property, as illustrated in Figure\,\ref{fig:nuA_intro_rule}, is obviously reversible, such that we can always use our elimination rules on an introduction form and vice versa.

\begin{figure}
\caption{Elimination rules $\pi_1, \pi_2 \ldots \pi_n$ for a type $\nu A. B_1 \times B_2 \times \ldots \times B_n$.}
\label{fig:nuA_elim_rules}
\end{figure}

\begin{figure}
\caption{Introduction rule for a type $\nu A. B_1 \times B_2 \times \ldots \times B_n$ based on information synthesized from the elimination rules.}
\label{fig:nuA_intro_rule}
\end{figure}

Using the intuition of going back and forth between elimination and introduction, we now present our high-level desugaring mechanism which takes constructs from projection-based form to constructor-based form. Note that all desugaring operations happen during or before elaboration.

\subsection{Desugaring record definitions}
%Record and corecords definitions are desugared according to the rule defined in Figure\,\ref{desugaring_records}. The type of each projection becomes an input type to the constructor with the given name.

A record definition defined with projections is desugared to a record definition with a single constructor, where each parameter is labeled with the name given in the projection-based form. An intuition is given in Figure\,\ref{fig:desugar_records}. In Idris, automatic generation of projection functions with the specified names happens during elaboration, and therefore desugaring becomes a matter of injecting the specified projections into the record constructor as named parameters.

\begin{figure}
\begin{lstlisting}[mathescape]
--| Projection-based form
record A : Type where
  $\pi_1$ : T$_1$
  $\pi_2$ : T$_2$
  $\vdots$
  $\pi_n$ : T$_n$
  constructor mkA

--| Desugared form
record A : Type where
  mkA : ($\pi_1$ : T$_1$) ->
        ($\pi_2$ : T$_2$) ->
        $\vdots$
        ($\pi_n$ : T$_n$) ->
        A
\end{lstlisting}
\caption{Desugaring record definitions.}
\label{fig:desugar_records}
\end{figure}

\subsection{Desugaring corecord definitions}

Corecord definitions are desugared to codata definitions with a single constructor. Similar to the desugaring of records, projections are injected into the constructor as named arguments. A general description is given in Figure\,\ref{fig:desugar_corecords}. However, as Idris does not have a corecord construct, projection functions must be generated while desugaring. Generating these functions is straightforward, since it is simply a matter of extracting the constructor argument at a specified position with pattern matching. This procedure is shown in Figure\,\ref{fig:generate_projections}.

\begin{figure}
\begin{lstlisting}[mathescape]
--| Projection-based form
corecord A : Type where
  $\pi_1$ : T$_1$
  $\pi_2$ : T$_2$
  $\vdots$
  $\pi_n$ : T$_n$
  constructor mkA

--| Desugared form
codata record A : Type where
  mkA : ($\pi_1$ : T$_1$) ->
        ($\pi_2$ : T$_2$) ->
         $\vdots$
        ($\pi_n$ : T$_n$) ->
        A
\end{lstlisting}
\caption{Desugaring corecord definitions.}
\label{fig:desugar_corecords}
\end{figure}

\begin{figure}
\begin{lstlisting}[mathescape]
generateProjection ($\pi_i$ : T$_i$) =
  $\pi_i$ (mkA (arg$_1$) (arg$_2$) $\cdots$ (arg$_i$) $\cdots$ (arg$_n$)) =  arg$_i$
\end{lstlisting}
\caption{Generating projection functions for a desugared corecord definition.}
\label{fig:generate_projections}
\end{figure}

\subsection{Desugaring left-hand side projections}
Left-hand side projections for values of both record and corecord type can be desugared in the same way. A clause with left-hand side projections is desugared in three steps: expand, reduce, and merge. To illustrate each step, we will show the steps involved in desugaring the \textit{dupNth} function from Figure\,\ref{fig:dup_copatterns}.
\begin{figure}
\begin{lstlisting}[mathescape]
dupNth : Stream a -> Nat -> Nat -> Stream a
head (dupNth s n m) =
  head (mkStream (head s) ?tail)
head (tail (dupNth s n Z)) =
  head (tail (mkStream ?head (mkStream (head s) ?tailtail)))
head (tail (dupNth s n (S m'))) =
  head (tail (mkStream ?head (mkStream (head (tail s)) ?tailtail)))
tail (tail (dupNth s n Z)) =
  tail (tail (mkStream ?head (mkStream ?headtail
                                       (tail (dupNth s n n)))))
tail (tail (dupNth s n (S m'))) =
  tail (tail (mkStream ?head (mkStream ?headtail
                                       (tail (dupNth (tail s) n m')))))
\end{lstlisting}
\caption{Desugaring, step 1: Expand right-hand sides to make projections on a constructor.}
\label{fig:desugar_step1}
\end{figure}

The first step, expansion, is shown in Figure\,\ref{fig:desugar_step1}. Since we desugar in the elaboration phase, we assume that the constructor for a given type,  \textit{mkStream} in this example, is available in the context. During expansion, the right-hand side of a clause with one or more left-hand side projections is expanded such that projections happen on an appropriate constructor, where the original right-hand side is injected as a parameter in the position specified by left-hand side projections. Due to the intuition given above, we do not have a well-formed introduction form (i.e. constructor application) before we know the result of all eliminations. Because each clause only defines one elimination rule, holes (e.g. ?tail) must therefore be left for constructor arguments unknown to a given clause. However, we defer resolving these holes to the merging step. None of the clauses try to access information unknown to them, so no undefined behaviour can arise as a result of this step.

\begin{figure}
\begin{lstlisting}[mathescape]
dupNth : Stream a -> Nat -> Nat -> Stream a
dupNth s n m      =
  mkStream (head s) ?tail
dupNth s n Z      =
  mkStream ?head (mkStream (head s) ?tailtail)
dupNth s n (S m') =
  mkStream ?head (mkStream (head (tail s)) ?tailtail)))
dupNth s n Z))    =
  mkStream ?head (mkStream ?headtail (tail (dupNth s n n)))
dupNth s n (S m') =
  mkStream ?head (mkStream ?headtail (tail (dupNth (tail s) n m')))
\end{lstlisting}
\caption{Desugaring, step 2: Reduce clauses by removing projections appearing in the same position on left and right-hand sides.}
\label{fig:desugar_step2}
\end{figure}

Reduction is the second step of desugaring, and is exemplified in Figure\,\ref{fig:desugar_step2}. In this step, each clause is reduced by removing equivalent projections on both side of a clause, similar to how one would reduce a mathematical equation. We are allowed to perform such reductions at this point because all the clauses make right-hand side projections directly on the (as yet unmerged) output of the function, while all the left-hand side projections happen directly on the input.

\begin{figure}
\begin{lstlisting}[mathescape]
dupNth : Stream a -> Nat -> Nat -> Stream a
dupNth s n Z      =
  mkStream (head s) (mkStream (head s)
                              (tail (dupNth s n n)))
dupNth s n (S m') =
  mkStream (head s)
           (mkStream (head (tail s))
                     (tail (dupNth (tail s) n m')))
\end{lstlisting}
\caption{Desugaring, step 3: Merge right-hand sides of compatible clauses.}
\label{fig:desugar_step3}
\end{figure}

The third and final step is merging, shown in Figure\,\ref{fig:desugar_step3}, where the right-hand sides of compatible clauses are merged into a single clause. Two clauses are considered to be compatible if (1) they make equivalent pattern matches on the same arguments or (2) a more specific clause is merged with a more general clause. The first condition means that \texttt{dupNth s n Z} is compatible with \texttt{dupNth s n Z}, but not \texttt{dupNth s n (S~m')}. The second condition is more subtle, expressing that \texttt{dupNth s n Z} is compatible with \texttt{dupNth s n m}, since the former is more specific than the latter. Accordingly, \texttt{dupNth s n m} is not compatible with \texttt{dupNth s n Z}.

\begin{figure}
\begin{lstlisting}[mathescape]
--| Expands the right-hand side to make
--| projections on a constructor definition
expand ($\pi_i$ (f x)) rhs = $\pi_i$ (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_i$ $\cdots$ ?arg$_n$)
expand ($\pi_j$ lhs) rhs =
  $\pi_j$ (expand lhs (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_j$ $\cdots$ ?arg$_n$))
expand lhs rhs = rhs

--| Reduce an expression by removing equal projections
--| on the left and right-hand sides of a clause
reduce (f x)    rhs     = f x = rhs
reduce ($\pi_i$ lhs) ($\pi_i$ rhs) = reduce lhs rhs
reduce _ _ = error -- Trying to reduce non-compatible projections

--| Merges the first clause with the second clause
--| if their left-hand sides are compatible
mergeWithClause (lhs$_1$ = rhs$_1$) (lhs$_2$ = rhs$_2$) =
  if compatible (lhs$_1$) (lhs$_2$)
  then (lhs$_1$ = merge (rhs$_1$) (rhs$_2$))
  else (lhs$_1$ = rhs$_1$)

--| Merges the first constructor with the second
merge (mkA ?arg$_1$ ?arg$_2$ $\cdots$ ?arg$_i$ $\cdots$ ?arg$_n$)
      (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_i$  $\cdots$ ?arg$_n$)
      = (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_i$ $\cdots$ ?arg$_n$)
merge (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_i$ $\cdots$ ?arg$_n$)
      (mkA ?arg$_1$ ?arg$_2$ $\cdots$ ?arg$_i$  $\cdots$ ?arg$_n$)
      = (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_i$ $\cdots$ ?arg$_n$)
merge (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_{i1}$ $\cdots$ ?arg$_n$)
      (mkA ?arg$_1$ ?arg$_2$ $\cdots$ rhs$_{i2}$  $\cdots$ ?arg$_n$)
      = error -- Trying to merge two different RHS
merge (mkA ?arg$_1$ ?arg$_2$ $\cdots$ mkA($\cdots$)$_{i1}$ $\cdots$ ?arg$_n$)
      (mkA ?arg$_1$ ?arg$_2$ $\cdots$ mkA($\cdots$)$_{i2}$  $\cdots$ ?arg$_n$)
      = (mkA ?arg$_1$ ?arg$_2$ $\cdots$ merge (mkA($\cdots$)$_{i1}$) (mkA($\cdots$)$_{i2}$) $\cdots$ ?arg$_n$)
merge xs ys = xs

--| Desugars a list of clauses
desugar ((lhs = rhs) :: clauses) =
  let expandedRhs = expand lhs rhs
  in let reduced = reduce lhs expandedRhs
  in foldr mergeWithClause reduced clauses
desugar [] = []
\end{lstlisting}
\caption{High-level formalization of desugaring, given in Haskell-like syntax. The constructor name \texttt{mkA} signifies a constructor for an arbitrary type A, and $\pi_i$ denotes projections.}
\label{fig:desugar_formalization}
\end{figure}

A formalization of the three steps is shown in Figure\,\ref{fig:desugar_formalization}. Expansion and reduction is straightforward. Merging tries to merge one clause with all other clauses of a definition, although only compatible clauses will lead to an actual merge. This presentation makes no mention of implicit arguments, since these are treated in the same way as explicit arguments.

% merge : Constructor A -> Constructor A -> Constructor A
% merge (Constr name args) (Constr name' args') =
%   if name == name'
%   then (Constr name (mergeArgs args args'))
%   else error

% mergeArgs : [Args] -> [Args] -> [Args]
% mergeArgs (? :: xs) (y :: ys) = y :: mergeArgs xs ys
% mergeArgs (x :: xs) (? :: ys) = x :: mergeArgs xs ys
% mergeArgs ((Constr n args) :: xs) ((Constr m args') :: ys) =
%   if n == m
%   then (Constr n (mergeArgs args args')) :: mergeArgs xs ys
%   else error
% mergeArgs (x :: xs) (y :: ys) = error

% mkRHS : Projection -> LHS -> RHS -> RHS
% mkRHS ($\pi$_i) (fun n) (r_i) = mk

\subsection{Desugaring right-hand side projections}
Since each projection is substituted with a projection function when a record or corecord definition is desugared, there should be no reason to desugar right-hand side projections. The desugared projection functions are added to the same namespace as high-level projections, and the semantics of both the projections prior to desugaring and the generated projection functions are the same.

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../copatterns-thesis"
%%% End:


\chapter{Fundamentals}

\section{Robot Operating System}
ROS (Robot Operating System) is an open-source meta operating system. It runs on top of Unix based systems and
provides abstraction over process management, low-level communication and hardware. It also provides tools and
libraries to develop applications in the field of robotics and distributed systems. ROS is build on the concept
of creating a (possibly distributed) peer-to-peer network of nodes. A node is a single, modular process that
should perform a dedicated task, which is implemented using C++ (roscpp) or Python (rospy). All nodes register
themselfs at the ROS master, which serves as a nameserver and processer manager to the rest of the network.
Nodes communicate which each other using ROS messages, which are data structures that define
the type of data that is passed. The communication is usually based on ROS topics,
which implement an asynchronous publish-subscribe pattern so that nodes are truly decoupled.
If direct, synchronous communication with an immediate response is needed, ROS services can be used.

\section{Neural Networks}
Neural networks are a emulation of a human brain with inter-connected nodes (neurons) with weighted edges (synapses).
The learning part comes from the process of altering each weight after each evaluation to better map inputs to their
expected outputs. This is called supervised learning and inputs with known outputs have to be available for that.
During the forward pass, the data passes through the network while the weights are applied. To achieve non-linear mappings,
an activation function is applied to inputs between each layer. After that, the error to the expected value is
calculated with a predefined loss function and the weights are updated accoring to a predefined optimizer in a process
called back-propagation. The process is repeated for a certain number of epochs so that the output gets closer and closer
to the expected value. After the training, the model can be used on unknown input.

\subsection{Fully Connected Neural Network}
A fully connected network is a type of network where each node of one layer is connected to each node on the following layer.
It is often divided into a input layer, multiple hidden layer and one output layer, which has to have the same number
of nodes as the amount of classes in the classification.

\subsection{Convolutional Neural Networks}
Convolulation neural networks are often used in classification problems and are a specialisation of full connected neural networks. They are escpecially used
in image and audio classification. It tries to find features or patterns in the provided data by removing noise and extracting data relevant for the actual target.
They are constructed with a convolutional layer and a pooling layer. The convolutional parts moves a kernel filter over the input matrix and calculates the inner product of
surrounding datapoints. This creates an overlap and helps neighboring neurons react to similiar data (e.g. similiar frequencies in audio data). In the pooling layer,
the amount of data gets reduced, for example by using max-pooling, a process where only the most active neuron in a certain area is kept and the rest being discarded.
This prevents the model from overfitting (valueing data not actualy relevant for the classification task) and improves training times. The data, now reduced to
its features, is then passed through a fully connected layer for the actual classification.


\documentclass[main.tex]{subfiles}
\begin{document}

\marginpar{Tuesday\\ 2020-10-13, \\ compiled \\ \today}

% 542129

We were discussing geodesics in the external Schwarzschild solution.
We wrote down the locus of the inversion point \(\dot{r} = 0\): this is
%
\begin{align}
\lambda_{\pm} = \pm x \sqrt{\frac{\Gamma x + 1}{x-1}}
\,.
\end{align}

\begin{enumerate}
    \item For \(\Gamma > 0\) there is one extremum;
    \item for \(- 1/9 < \Gamma < 0\) there are two extrema;
    \item for \(-1 < \Gamma < - 1/9\) there are no extrema.
\end{enumerate}

Let us consider the two-extrema case. Then, there is an intersection with the \(x\) axis at \(x = - 1/ \Gamma \) for the \(\lambda_{\pm }\).
Then the curve looks like a doorknob: it is a closed curve.

In this case, we are considering \emph{bound states}: the particle can start on the LHS of the curve, and if this is the case it must reach the inversion point and then go back and eventually cross the horizon.
If it is in the ``doorknob region'', then it is trapped there.

These orbits are similar to the Newtonian elliptic ones, but there are differences. These are radially bound, however they are not in general periodic: they will precess.

We can also have circular orbits, both stable and unstable.

In the no-extrema case there are no orbits. The limiting case \(\Gamma = - 1/9\) is interesting: the minimum becomes an inflection point, with zero second derivative.
This happens at \(x = 3\).
This is the ISCO: the Innermost Stable Circular Orbit.

The corresponding energy is given by \(\epsilon \), which can be determined through \(\epsilon^2 - 1 = - 1/9\): \(\epsilon = \sqrt{8/9} =  2 \sqrt{2}  /3\), so
%
\begin{align}
E _{\text{ISCO}} = \frac{2 \sqrt{2}}{3} mc^2
\,.
\end{align}

If we can bring a particle from infinity to the ISCO (which is what happens as an accretion disk is formed) it can release an energy equal to \(mc^2 - E _{\text{ISCO}} = (1 - 2 \sqrt{2} / 3) m c^2\). This is why an accretion disk can produce a large amount of energy.

The efficiency can then be computed as
%
\begin{align}
\text{efficiency} = \frac{mc^2 - 2 \sqrt{2} mc^2 / 3}{mc^2} \approx \SI{6}{\percent}
\,.
\end{align}

This is a \emph{very large} efficiency: an order of magnitude more than the efficiency of nuclear burning.

\section{Schwarzschild internal solution}

Now we try to solve the EFE under spherical symmetry \emph{with} a source:
%
\begin{align}
G_{ij} = R_{ij} - \frac{1}{2} g_{ij} R = 8 \pi T_{ij}
\,,
\end{align}
%
with a metric
%
\begin{align}
\dd{s^2} = - B(r) \dd{t^2} + A(r) \dd{r^2} + r^2 \dd{\Omega^2}
\,.
\end{align}

Birkhoff does not apply here: we are \emph{assuming} stationarity.
We will use a very simple \(T_{ij}\): a perfect fluid, where
%
\begin{align}
T_{ij}
= (\rho + P) u_i u_j + P g_{ij}
\,,
\end{align}
%
where the energy density is given by \(\rho = \rho_0 ( 1+ \epsilon )\): \(\rho_0\) is the rest energy density of the fluid, while \(\epsilon \) accounts for thermal motion and other kinds of internal energy.

We will assume that the fluid is at rest with respect to the interior: we want to find an analog of the hydrostatic equilibrium equation.
So, \(\dd{r} = \dd{\theta } = \dd{\varphi } = 0\), while only \(\dd{t} \neq 0\). This means that only \(u^{0} \neq 0\), and normalization requires \(g_{ij} u^{i} u^{j} = -1\): this means that \(u^{0} =  1/ \sqrt{B}\), and the whole vector reads \(u^{i} = \delta^{i}_{0} / \sqrt{-g_{00} }\).

Let us then write the nonzero mixed components of the stress-energy tensor:
%
\begin{align}
T^{0}_{0}
= (P + \rho ) u_0 u^0 + P g_{0}^{0}
=  -\rho &&
T^{1}_{1} = T^{2}_{2} = T^{3}_{3} = P
\,,
\end{align}
%
since if we have one upper and one lower index the normalization in \(u^{i} u_{j}\) simplifies.

Let us also skip the computations: the Einstein tensor reads
%
\begin{align}
G^{0}_{0} &= \frac{1}{A} \qty( \frac{1}{r^2} - \frac{A'}{rA}) - \frac{1}{r^2} = - 8 \pi \rho   \\
G^{1}_{1} &= \frac{1}{A} \qty( \frac{1}{r^2} - \frac{B'}{rB}) - \frac{1}{r^2} = 8 \pi  P  \\
G^{2}_{2} = G^{3}_{3}  &= - \frac{1}{2A} \qty[\frac{A'B'}{2AB} + \qty(\frac{B'}{B})^2 - \frac{B'}{Br^2} + \frac{A'}{r^2A} - \frac{B''}{2B}] = 8 \pi P
\,.
\end{align}

We need to solve for \(\rho \), \(P\), \(A\) and \(B\): the equations of motion of the particles, \(\nabla_{i} T^{ij} = 0\), will be automatically satisfied as a consequence of the Einstein equations.

We have three equations for four variables: we need an additional one, typically we combine them with an \emph{equation of state} for \(P\): a simple case, a \emph{barotropic EOS}, is in the form \(P = P(\rho )\).

The first equation can be written as
%
\begin{align}
\frac{1}{A} - \frac{r A'}{A^2} &= 1 - 8 \pi r^2 \rho  \\
\dv{r}( \frac{r}{A}) &= 1 - 8 \pi r^2 \rho
\,,
\end{align}
%
which we can integrate to find
%
\begin{align}
\frac{r}{A} = r - \int_{0}^{r} 8 \pi \widetilde{r}^2\rho \dd{\widetilde{r}}
\,.
\end{align}

We introduce the quantity
%
\begin{align}
m(r) = \int_{0}^{r} 4 \pi \widetilde{r}^2 \rho \dd{\widetilde{r}}
\,,
\end{align}
%
so that
%
\begin{align}
A(r) = \qty(1 - \frac{2 m(r)}{r})^{-1}
\,.
\end{align}

It is important to state that \(m(r)\) is \emph{not} the total mass-energy enclosed in the region below \(r\): we are not integrating with respect to a covariant volume form.

With the second two equations, we end up with
%
\begin{align}
\frac{1}{2B} \dv{B}{r} = - \frac{1}{P + \rho } \dv{P}{r}
\,.
\end{align}

We have essentially solved for \(B\).
We can also manipulate the equations to find:
%
\begin{align}
\dv{P}{r} = - \frac{m(r) \rho }{r^2} \qty(1 + \frac{P}{\rho })
\qty(1 + \frac{4 \pi r^3 P}{m(r)}) \qty(1 - \frac{2 m(r)}{r})^{-1}
\,,
\end{align}
%
the \textbf{Tolman-Oppenheimer-Volkov} (TOV) equation.
This reduces to the hydrostatic equilibrium equation in weak gravity.

The three other terms are basically three relativistic corrections, from velocity and radius: the first are applied based on whether the gas is relativistic \emph{in its own rest frame}; if this is the case, then \(P \sim \rho \).
The first term is a local correction, the second one is a global one; the third term on the other hand is the usual GR correction, based on \(r _{\text{Schw}} / r\).

We can also write
%
\begin{align}
\dv{m}{r} = 4 \pi r^2 \rho
\,.
\end{align}

This equation, the TOV one and the equation of state form a closed system for \(m\), \(\rho \) and \(P\).

As for boundary conditions, we require that \(m(0) = 0\) and \(P(R) = 0\).
This is hard to do numerically: it is a boundary value problem, not an initial condition one.

Finally, we discuss the meaning of \(m(r)\).
The total \(M\) is given by
%
\begin{align}
M = \int_{0}^{R} 4 \pi r^2 \rho \dd{r}
\,,
\end{align}
%
where \(R\) is the radius of the star. This is \emph{not} the total mass, since \(\dd{V}\) is \emph{not} \(4 \pi r^2 \dd{r}\).
The \emph{proper} three-volume element is instead given by \(\dd{V} = 4 \pi r^2 \sqrt{A(r)} \dd{r}\), since the true radial distance is calculated through the metric: \(\dd{s^2} = A(r) \dd{r^2}\) if the measured length is radial.

We call \(M_*\) the mass which is calculated including the \(\sqrt{A}\) term. Their difference is
%
\begin{align}
M - M_* = \int_{0}^{R} 4 \pi r^2 \rho \qty(1 - \sqrt{A}) \dd{r}
\,.
\end{align}

If \(r \gg 2m\) (the weak-field limit) then we can approximate \(A = 1 - 2m /r\):
%
\begin{align}
M - M_* &\approx \int_{0}^{R} 4 \pi r^2 \rho \qty(1 - 1 - \frac{m}{r}) \dd{r}    \\
&\approx - \int_{0}^{R} \frac{m}{r} \underbrace{4 \pi r^2 \rho \dd{r}}_{ \dd{m}}    \\
&\approx - \int_{M} \frac{Gm}{r} \dd{m} = E_g
\,.
\end{align}

So, in the weak field limit, the mass defect is given by the gravitational potential energy!
This is a physical consequence of the \emph{nonlinearity} of the EFE.

% The electromagnetic field behaves linearly at low energies, while in QED we can see nonlinearities.
The mass \(M\) is the one which would be measured by an outside observer through gravitational effects (since it appears in the expression for \(A = B^{-1}\) in the exterior region \(r > R\)); it is written as \(M = M_* + E_b < M_*\), with \(M_*\) being the ``true'' matter content of the interior.

\end{document}


\documentclass[leqno,labelfig,psfigt,colorlinks]{svmono}

%\usepackage[a4paper,left=1cm,right=10cm,bindingoffset=5pt, asymmetric, reversemarginpar]{geometry}

\makeatletter
\providecommand*{\input@path}{}
\edef\input@path{{./}{../}\input@path}% prepend
\makeatother

\input{../Xmacros}
\renewcommand{\blankpage}{}\renewcommand{\break}{}
\usepackage{wrapfig}
\usepackage{bbm}
\usepackage{listings}
\usepackage{natbib}
\usepackage{color}
\usepackage{cases}
\usepackage{pythonhighlight}

\usepackage{setspace}

\usepackage{pdfpages}

\usepackage{adjustbox}

\newcommand{\red}[1]{\textcolor{red}{#1}}
\newcommand{\blue}[1]{\textcolor{blue}{#1}}
\newcommand{\brown}[1]{\textcolor{blue}{#1}}
\newcommand{\green}[1]{\textcolor{green}{#1}}

\makeatletter
\newenvironment{breakablealgorithm}
{% \begin{breakablealgorithm}
	\begin{center}
		\refstepcounter{algorithm}% New algorithm
		\hrule height.8pt depth0pt \kern2pt% \@fs@pre for \@fs@ruled
		\renewcommand{\caption}[2][\relax]{% Make a new \caption
			{\raggedright\textbf{\ALG@name~\thealgorithm} ##2\par}%
			\ifx\relax##1\relax % #1 is \relax
			\addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##2}%
			\else % #1 is not \relax
			\addcontentsline{loa}{algorithm}{\protect\numberline{\thealgorithm}##1}%
			\fi
			\kern2pt\hrule\kern2pt
		}
	}{% \end{breakablealgorithm}
		\kern2pt\hrule\relax% \@fs@post for \@fs@ruled
	\end{center}
}
\makeatother

\usepackage{multirow}
\usepackage{mathtools}

\newtheorem{properties}[theorem]{Properties}
%\graphicspath{{figures/}}
\graphicspath{{../figures/}{figures/}{../}}

\begin{document}

\chapter{MgNet: a Unified Framework for CNN and MG}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{breakablealgorithm}
	\caption{$u={\rm DarcyCNN}(\kappa; f_d, coarse\_grid\_size,)$}
	\label{alg:mgnet}
	\begin{algorithmic}
		\State Initialization:  $\kappa$, $u^{0} $
		%		\State Initialization $u^{1,0}$
%		\For{$ = 1:N_{epoch}$}
%		\For{$i = 1:\nu_$}
		\State Encode
		\begin{equation}
		u^{} = K^{3}  \ast_2 \sigma \circ K^{ 2}\ast \sigma (K^{ 1}\ast \kappa).
		\end{equation}

%		\EndFor
		\State Restriction to the coarse grid
		\begin{equation}
		u^{} = \sigma \circ \theta^{. 1} \circ u^{}
		\end{equation}
		\State
		Convolution on the coarse grid
		\begin{equation}
		u^{} =  \sigma \circ K^{ 5}\ast \sigma (K^{ 4}\ast u^{}).
		\end{equation}
		\State Decode
		\begin{equation}
		u^{} =  \sigma \circ \theta^{ 3}\circ \sigma (\theta^{ 2}\circ u^{}).
		\end{equation}
%		\EndFor
	\end{algorithmic}
\end{breakablealgorithm}

	where $K^{3}  \ast_2$ is the average pooling with kernel size $2  \times 2$ and stride 2, $K^{1}$, $K^{2} $, $K^{4} $ and $K^{5}  $ are multi-channel kernels with kernel size $3  \times 3$ and the size of these kernel matrices are $(1 \times f_d/2)$, $ (f_d/2 \times f_d)$, $(1,f_d/2)$ and $(f_d/2, f_d)$ respectively.
%\input{6DL/mgnet
%
%\input{6DL/mgnet_relation}
%\input{ConstrainedLinearModel}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\bibliographystyle{abbrv}\bibliography{ref,ref_mgcnn,../3FEM/3FEM}

\end{document}


%Texlive-full Version 3.141592-1.40.3 (Web2C 7.5.6)
%Kile Version 2.0.83
%File associated : SoFa_Logo.ps , FF.ps

\documentclass[a4paper,10pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{lmodern}
\usepackage[a4paper]{geometry}
%\usepackage[frenchb]{babel}
\usepackage{graphicx}
\usepackage{hyperref}

\usepackage{pstricks}
\usepackage{pst-node}
%\usepackage{wrapfig}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{textcomp}
%\usepackage{mathaccent}
\usepackage{listings}
\lstset{language=C++,basicstyle=\scriptsize \color{green},identifierstyle=\color{orange},keywordstyle=[1]\color{blue},columns=fullflexible,commentstyle=\textit}

\usepackage{color}

\begin{document}
%%%%%%%%%%%%%%%%%%   LOGO  %%%%%%%%%%%%%%%%%%%%%%%%%
\begin{center}
\rput(6,1.5){\href{http://www.sofa-framework.org/}{\includegraphics[scale=0.3]{SoFa_Logo}}}
\rput(-4,1.5){\href{http://www.sofa-framework.org/}{
		\begin{tabular}{l}
		\resizebox{4cm}{0.6cm}{SOFA} \\
		\resizebox{6cm}{0.3cm}{Simulation Open Framework Architecture}
		\end{tabular}
		}
	    }
\end{center}
%%%%%%%%%%%%%%%%%%   LOGO  %%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%% DOCUMENT TITLE %%%%%%%%%%%%%%%%%%%%%%%%% To be deleted when include in the global document
%\chapter{Mapping} %\section{Rigid Mapping}
\vspace{1.5cm}
\begin{center}\resizebox{7cm}{0.6cm}{Linear Solver}\end{center}
%%%%%%%%%%%%%%%%%% DOCUMENT TITLE %%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%=======================================================================================%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Linear Solver}% for adding to the global document of SOFA

\section{Linear Solver}
\paragraph{Abstract : }
%%%%%%%%%%%%%%%%%%   LOGO  %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%   LOGO  %%%%%%%%%%%%%%%%%%%%%%%%%
In SOFA, all states of a mechanical object is described by its degree of freedom. The main works for the simulation are filling and inverting a matrix system in order to find the states of mechanical objects by steps of time. This system matrix can be described as below :
 \[
\left[ \textbf{MBK} \right].a=f \text{    ,  or at time n+1 :   }\left[ \textbf{MBK} \right].a_{n+1}=f_{n+1}
\]
where,
\[
\left\{
\begin{array}{l}
\textbf{M} \text { : the mass matrix   }  \\
\textbf{B} \text { : the damping matrix   }  \\
\textbf{K} \text { : the stiffness matrix   }  \\
\left[ \textbf{MBK} \right] \text {  : is a linear combination of MBK (not multiplication)   }  \\
a_{n+1} \text { : accelerator field} \\
f_{n+1} \text { : force field}
\end{array}\right.
\]
 Usually, \textbf{M} is filled by \textbf{\color{orange}mass} components, \textbf{K} is filled by \textbf{\color{orange}forcefield} or \textbf{\color{orange}interactionforcefield} components, \textbf{B} (often $\alpha\textbf{M}+\beta\textbf{K}$ ) and $\left[ \textbf{MBK} \right]$ are computed by \textbf{\color{orange}odesolver} components. The works left to invert the matrix system are done by \textbf{\color{orange}linearsolver} components.
\begin{center}
\includegraphics[scale=0.3]{matrix_bloc}
\end{center}
On the case for example when there are two mechanical objects, we can see a global stiffness matrix describing the two mechanical states, composed diagonal blocs and non-diagonal blocs. The diagonal blocs are filled by \textbf{\color{orange}mass},\textbf{\color{orange}forcefield} components, and the non-diagonal ones are filled by \textbf{\color{orange}interactionforcefield} if existed.
\paragraph{Mapping matrix contribution : } When existe a mapping on the simulation scene, the states of two mechanical objects are relied by :
\[
\begin{array}{rl}
\textbf{x}_{2} & = \Im\left(\textbf{x}_{1}\right)           \text{      ,	mapping::apply}             \\
\textbf{v}_{2} & = \left[\textbf{J}\right] \textbf{v}_{1}   \text{      ,	mapping::applyJ}
\end{array}
\]
The $\left[\textbf{J}\right]$ matrix is derivative of $\Im$ operator and is defined by the \textbf{\color{orange}mapping} components. The dynamic and matrix system of the two objects are relied by :
\[
\begin{array}{rl}
\textbf{f}                  & += \textbf{f}_{1}  +   \left[\textbf{J}\right]^{t} \textbf{f}_{2}         \text{      ,	mapping::applyJT}             \\
\left[ \textbf{MBK} \right] & += \left[ \textbf{MBK} \right]_{1}  + \left[\textbf{J}\right]^{t}  \left[ \textbf{MBK} \right]_{2} \left[\textbf{J}\right]
\end{array}
\]
The resolution of the system with the mapping is done in general :
\[
\left\{
\begin{array}{rl}
\textbf{a}^{n+1}        & = \left[ \textbf{MBK} \right]^{-1}  \textbf{f}^{n+1}    \\
\textbf{v}^{n+1}_{1}    & = \textbf{v}^{n}_{1}     + dt.\textbf{a}^{n+1}         \\
\textbf{x}^{n+1}_{1}    & = \textbf{x}^{n}_{1}     + dt.\textbf{v}^{n+1}         \\
\textbf{x}^{n+1}_{2}    &  \text{ ,	mapping::apply }     \\
\textbf{v}^{n+1}_{2}    &  \text{ ,	mapping::applyJ }
\end{array}
\right.
\]

\subsection{Direct Solvers }
The direct solver demande to build explicitly the matrix, and invert this matrix after every step of time in order to solve the mechanical response after a sollicitation.
\subsection{Context in SOFA }
In SOFA, there are a litle more complicated component called mapping, relying geometrical and mechanical propreties by master-slave (DOF-mapped object) relation. All changes of geometry or sollicitation to one object interfere to other and vice versa. If the mapped object have its own mechanical behavior, it must be counted on the mechanical propagation by the mapping.
\subsubsection{self-stiffness propagation }
\[
\begin{array}{cc}
\includegraphics[scale=0.3]{stiffness_propagation_matrix}
&
\includegraphics[scale=0.35]{stiffness_propagation}
\end{array}
\]
In the simple simulation scene, \textbf{MS2} is a mapped object to the \textbf{MS1} mechanical object by the mapping. The matrix to be inverted for all mechanical response is the filled colorized one ($K_{11}$), the matrix $K_{22}$ describing mechanical propreties of the second objects must contribute to $K_{11}$ by the formula :
\[
\left\{
\begin{array}{ll}
K_{11}       & += J^t * K_{22} * J               \\
\text{or,}   &         \\
K_{tempo}    & =  J^t * K_{22}                   \\
K_{11}       & += K_{tempo} * J                  \\
\end{array}
\right.
\]
By doing this computation, we propagate the stiffness of the mapped mechanical object to its root mechanical object.
\subsubsection{interaction-stiffness propagation }
In the general case, the may have a simulation scene where there are many level of mapped mechanical states (mapped of mapped state ...) and many interaction forcefield interacting beetween them. Therefor the stiffness of interaction forcefield and the mapped mechanical state need to be propagated through the mappings. We can imagine for one propagation, there are two simple cases.
\paragraph{Interaction beweent Real Mechanical Object and Mapped Mechanical Object}
\[
\begin{array}{cc}
\includegraphics[scale=0.3]{interaction_Real_Mapped_Matrix}
&
\includegraphics[scale=0.35]{interaction_Real_Mapped}
\end{array}
\]
In the case where one of the two mechanical states in interaction is non-mapped, the propagation can be computed directly by the formula :
\[
\left\{
\begin{array}{ll}
K_{11}       & += J^t * K_{33} * J               \\
\text{or,}   &                                   \\
K_{tempo}    & =  J^t * K_{33}                   \\
K_{11}       & += K_{tempo} * J                  \\
\text{and,}&                 \\
I_{12}       & += J^t * I_{32}                   \\
I_{21}       & += I_{23} * J
\end{array}
\right.
\]
\paragraph{Interaction beweent Mapped Mechanical Object and Mapped Mechanical Object}
\begin{center}
  \includegraphics[scale=0.3]{interaction_Mapped_Mapped}
\end{center}
In the case where the two mechanical states in interaction are mapped, the propagation can be computed by two steps. The first consist to propagate the interaction $I_{34}$ to the interation $I_{14}$ :
\[
\left\{
\begin{array}{ll}
K_{11}       & += J^t * K_{33} * J               \\
\text{or,}   &                                   \\
K_{tempo}    & =  J^t * K_{33}                   \\
K_{11}       & += K_{tempo} * J                  \\
\text{and,}&                 \\
I_{14}       & += J^t_A * I_{34}                  \\
I_{41}       & += I_{43} * J_A
\end{array}
\right.
\]
The following step can compute as the one of above paragraph, propagating the interation $I_{14}$ to $I_{12}$.
\subsection{Iterative Solvers }
\subsection{Preconditioner }

						      %%%%%%%%%%%%%%%%%%%%%%%%%%  Writer %%%%%%%%%%%%%%%%%%%%%%%%
						      \begin{flushright}
						      Document written by \\
						      \href{mailto:chi-thanh.nguyen@inria.fr}{{\textbf {Chi Thanh NGUYEN}}} \\
						      INRIA Lille
						      \end{flushright}
						      %%%%%%%%%%%%%%%%%%%%%%%%%%  Writer %%%%%%%%%%%%%%%%%%%%%%%%

%\bibliographystyle{siam}
%\bibliography{mybiblio}
\end{document}