\chapter{\acro{rtn} Support}

\label{sec:openfstrtn}

%\section{Two Distinct Flavors of \acro{rtn} Support}

% See saprtn.tex.notrack
%Kleene is currently being expanded to provide support for two distinct
%flavors of Recursive Transition Networks or \acro{rtn}s.  This is work in
%progress.

%This section describes the Kleene support for \acro{rtn}s
%compatible with the off-the-shelf functions from the OpenFst library.
%\acro{sap} linguists creating pattern networks for the \acro{sap}
%\acro{rtn} pattern-matching runtime code should ignore this section and
%proceed immediately to section~\ref{sec:saprtn} starting on
%page~\pageref{sec:saprtn}.

\section{OpenFst Recursive Transition Networks (\acro{rtn}s)}

\subsection{Status}

[KRB 2013-04]  WORK IN PROGRESS:  There is currently no runtime-code support for
\init{rtn}s.  This chapter has not be reviewed recently.

Kleene supports the building of Recursive Transition Networks
(\acro{rtn}s) that are compatible with the OpenFst \texttt{Replace()} and
\texttt{ReplaceFst()} operations.  An \acro{rtn} contains arc labels that
are to be interpreted as ``references'' to subnetworks; and compatible
\acro{rtn}-savvy runtime code, when applying a network to data, will
recognize such a reference and ``push'' to the referenced subnetwork to
continue the matching, and then ``pop'' back to the calling network when
the subnetwork has successfully matched.  The references to subnetworks
can also be thought of as non-terminal labels.

\acro{rtn}s, containing references to subnetworks, are often smaller than
full-sized networks that must contain a full copy of each subnetwork
wherever it is needed.  However, \acro{rtn}s can denote context-free
languages, and so can go beyond regular power; a special subclass of
\acro{rtn}s remain regular.  The recognition/parsing of context-free
languages requires memory, in particular a push-down stack, and so any
runtime code to apply \acro{rtn}s must include such a stack.

At the time of writing (13 October 2010) there are hints that the
\acro{rtn} conventions currently required in OpenFst might change, and
there is new library support for mathematically equivalent Pushdown
Automata (\acro{pda}s) that we have not yet tested.  Kleene support for
OpenFst \acro{rtn}s and \acro{pda}s will necessarily evolve along with
the library.

\subsection{Syntax for Creating an OpenFst \acro{rtn}}

For the programmer, there needs to be a Kleene syntax to denote a
reference to a subnetwork, and it needs to be distinct from the syntax
that causes a copy of a network to be inserted.  For example, in this
example

\begin{Verbatim}[fontsize=\small]
$vowel = [aeiou] ;
$net = k $vowel t $vowel b $vowel ;
\end{Verbatim}

\noindent
the \verb!$vowel! network will be copied three times into \verb!$net!.
In real-life applications, a subnetwork might encode something much
larger, such as nouns or even noun phrases in a natural language, and
multiple copies could easily cause the final network to become very
large, or even too large to compute.

Kleene currently supports a wired-in function \verb!$^sub($s)! that
programmers can use to denote a reference to a subnetwork \verb!$s!.\footnote{I'm
not tied to \verb!$^sub($s)! and would be comfortable with alternatives such
as \verb!$^ref($s)! or \verb!$^push($s)!, or even some special syntax like
\verb!>$s<! or \verb!>>$s!.}

To continue with our trivial example,

\begin{Verbatim}[fontsize=\small]
$vowel = [aeiou] ;
$rtn = k $^sub($vowel) t $^sub($vowel) b $^sub($vowel) ;
\end{Verbatim}

\noindent
would result in an \verb!$rtn! network that contains three compact
one-label references to \verb!$vowel! rather than three full copies of
it.  In real-life applications, the savings in memory can be very
significant.

\subsection{What does a Reference Look Like in an OpenFst \acro{rtn}?}

OpenFst networks consist of states and arcs, and each arc has two labels,
an input label, and an output label.\footnote{The terminology of
\emph{input} and \emph{output} labels is that of the OpenFst tradition.
In the Xerox tradition, they are called \emph{upper} and \emph{lower}, or
sometimes \emph{lexical} and \emph{surface}.}  In the actual network, the
labels are really integers, and all Unicode characters, such as \emph{a},
\emph{b}, \emph{c}, etc.\@ are represented using their standard Unicode
code point values.  Multichar symbols are stored using code point values
selected at random from a Unicode Private Use Area.

To maximize compatibility with the off-the-shelf OpenFst
\texttt{Replace()} and \texttt{ReplaceFst()} operations, the integer
representing a reference to a subnetwork must currently appear on the
\emph{output} side of an arc.  In Kleene, multichar symbol names
representing a call to a subnetwork \verb!$s! are spelled \verb!__$s!,
with two initial underscores, and the syntax \verb!$^sub($s)!  currently
yields the following network.

% see images/README for converting .ps files to .pdf and cropping them
\begin{center}
\includegraphics{images/reference.pdf}
\end{center}

\noindent
Currently in OpenFst, the symbol \verb!__$s! could in fact appear also on
the input side.  Of course, in the real network, the labels are really
just integers, 0 for epsilon, and some arbitrary value from the Private
Use Area for the multichar symbol.

Kleene programmers should use the wired-in \verb!$^sub()! function to
denote references to subnetworks and should not try to specify special
symbols like \verb!__$s! directly.  For example, the following statement
is illegal and will cause an exception to be thrown.

\begin{Verbatim}[fontsize=\small]
$rtn = "":'__$foo' ;    // raises an exception
\end{Verbatim}

\noindent
The use of \verb!$^sub()! at the programming level will also make it easy
for Kleene to adapt to any changes to \acro{rtn} representations that
might be made in the underlying OpenFst library.

\subsection{Embedding Subnetworks in an OpenFst \acro{rtn}}

The \verb!$^embedRtnSubnets($rtn)! function takes an OpenFst \acro{rtn}
argument, i.e.\@ a network that contains OpenFst-format references to
subnetworks, and returns a network that consists of the original network
unioned with a prefixed copy of each referred-to subnetwork.  For each
referred-to network \verb!$s!, the prefix consists of the special symbol
\verb!__SUBNETWORKS! followed by the special symbol \verb!__$s!.  Thus
from the following code

\begin{Verbatim}[fontsize=\small]
$p = p ;
$q = q ;
$rtn = a $^sub($p) b $^sub($q) ;
\end{Verbatim}

\noindent
the result \verb!$rtn! is this network containing two references to subnetworks

\begin{center}
\includegraphics[width=\textwidth]{images/twoReferences.pdf}
\end{center}

\noindent
but the three referred-to networks remain separate.  After the following
call to \verb!$^embedRtnSubnets($rtn)!,

\begin{Verbatim}[fontsize=\small]
$embedded = $^embedRtnSubnets($rtn) ;
\end{Verbatim}

\noindent
the resulting \verb!$embedded! network looks like this

\begin{center}
\includegraphics[width=\textwidth]{images/embedded.pdf}
\end{center}

\noindent
The embedded network can be saved to file as a single network and could be
applied by \acro{rtn}-savvy runtime code (not yet written) that knows the prefix convention.

The unioning of the base network with the subnetworks also guarantees that
the meaning of OTHER, if present, is standardized throughout all the
networks.

\subsection{Expanding an OpenFst \acro{rtn} into a Full Normal Network}

In some cases, it may also be useful to take an OpenFst \acro{rtn} and replace
each reference to a subnetwork with an actual copy of that subnetwork,
expanding the \acro{rtn} into a full normal network.  This is mathematically and
computationally possible only if the \acro{rtn} is regular.  Using the same
\verb!$rtn! example, a call to \verb!$^expandRtn()!

\begin{Verbatim}[fontsize=\small]
$expanded = $^expandRtn($rtn) ;
\end{Verbatim}

\noindent
produces the following \verb!$expanded! network

\begin{center}
\includegraphics[width=\textwidth]{images/expanded.pdf}
\end{center}

\noindent
In real-life \acro{rtn}s, with multiple references to the same
subnetwork, the expanded network will be significantly bigger than the
original.

If the \acro{rtn} contains cyclic references to subnetworks, it is
context-free in power (i.e.\@ no longer regular in power), and its
expansion would result in an infinite network.  The
\verb!$^expandRtn($rtn)! function checks for cyclic references and throws
an exception if the \verb!$rtn! is not regular.\footnote{In the OpenFst
library, the \verb!ReplaceFst()! operation provides a convenient method
that checks for cyclic references, and \verb!$^expandRtn()! invokes this
method.}


\documentclass[twocolumn]{article}
\begin{document}
\title{Primary Jungle or How to Train Your Candidate}
\author{Phil Crow}
\maketitle

\section{Object}

You are a highly sought after campaign manager who could work for any candidate. Choose a candidate to guide to a first place finish in
the Iowa Caucuses. In this parallel universe, those are juggle caucuses where all candidates run together, regardless of party or ideology.

\section{Supplies}

\begin{itemize}
\item Candidate cards
\item Board
\item Calendar piece (small blue cube)
\item 50 White 1 point poll chips, 10 Red 5 point poll chips
\item Two white dice and one blue die
\item Money, divided into Super PAC and Candidate
\item 137 Weapon cards\footnote{You might be wondering, ``Why not 140?'' The other three were honesty, integrity, and foresight. Think of which candidates could genuinely play these. }
\item Field office pieces (small plastic stars one color per player)
\end{itemize}

\section{Starting the Game}

\subsection{Choose a Candidate}

Each player chooses one candidate card. Fight amongst yourselves (euphemistically please). Each candidate has a power.
Pay attention to that power and follow its instructions whenever they apply. For instance, now is a good time for Earnie Painter to open that
free New Hampshire field office by placing a star in New Hampshire on the board, if at least three people are playing.

\subsection{Start the Calendar}

Place the calendar piece on the board.  Starting calendar squares are marked with a line for two players, a triangle for three, etc. If you like formulas,
multiply the number of players by 15. Add one.

\subsection{Divide the Voters}

Place 15 poll chips on the undecided area of the board. Divide the remaining chips equally among the players. Place any remainder on undecided.

\subsection{Raise PAC Cash}

Each player rolls the two white dice and collects that total amount times \$100,000 in Super PAC bills. This is your candidate's PAC money. You can spend it on Warm Fuzzy Ads or
to take a risk with Attack Ads. Ronald Chump does not use PAC money, so skip this step, if he is your candidate. Jethro Shrub possesses the golden rolodex and gets double his roll.

\subsection{Raise Initial Candidate Cash}

Each player receives \$10K in candidate seed money for each opponent faced. Example: If there are five players, each player receives \$40K in candidate cash.
Note that Ronald Chump has unlimited funds. The bank covers for all of his spending. Skip this step, if he is your candidate. Melodie Whiteman and Fiona Carlson
have the power to raise extra money in this step. Follow their power instructions, if one of them is your candidate.

\subsection{Shuffle up and Deal}

Shuffle the weapon cards. Deal five to each player. Place the rest on the weapons draw pile on the board.

\subsection{Choose a First Player}

Determine who will go first in any way you like. If you can't think of a way, go in height order from tallest to shortest. Height is a great advantage in politics.

\section{Turn Phases}

Each turn has the following phases in order. Details on each phase are below.

\begin{enumerate}
\item Move the calendar piece
\item Raise money
\item Pay for staff
\item Play a weapon card (optional)
\item Open or close field offices (optional)
\item Draw (if you played a weapon)
\end{enumerate}

\subsection{Move the Calendar}
Every turns begins by moving the calendar forward one ``day.'' Pay attention so caucus day does not sneak up on you.

\subsection{Raise Money}
Ronald Chump skips this step.

Everyone participating in this step raises at least \$5k regardless of their roll.
To see if you raise more than \$5k, throw all three dice.
Pay attention to endorsement cards and Mallory Hinton's power when calculating totals.

If the blue die is three or less: subtract the total of the white dice from your current poll chip count. This is your final total.

If the blue die is four or more: add the total of the white dice to your current poll chip count. This is your final total.

In both cases, take your final total from the bank in thousands using candidate cash bills, but not less than \$5k.

\subsection{Pay for Staff}
Ronald Chump assumes the bank is covering this for him and skips this step.

Always pay \$10K for your traveling staff. Pay another \$10K for each open field office. If you run short of money, immediately close all field offices. This
means that Earnie Painter loses his free field office in New Hampshire, if he runs out of money.

\subsection{Play a Weapon}
Each weapon card has instructions. Follow them. Here are one oddity and some reminders. Only one scandal can be in effect against a player at a time.
Remember to keep Stump, Teach Your Candidate, and Endorsement cards. Only discard them if a scandal takes effect and tells you to. Keep these cards face up
where everyone can see them.

If you can't play a weapon, or simply don't want to, skip to opening and closing offices.

\subsection{Field Offices}
On each turn, you may open one field office, but no player may have no more than three offices open in any state.
You may also close as many fields offices as you like, to conserve money on future turns.

Place a field office piece on one of the states on the board to open it. Take pieces off the board to close them. Field offices improve the effect of a
successful stump speach, but they cost \$10K per turn. Plan accordingly.

If you are playing with two players, you may only open offices in Iowa. If three or four are playing, you may open offices in Iowa or New Hampshire. Add
South Carolina only if five are playing.

\subsection{Draw}
If you played a weapon card, draw one at the end of your turn. You should always start and end a turn with five cards. If you forget to draw, do so
anytime (even during another player's turn). If you did not play a card, you may elect to discard at the end of the turn and draw a replacement. Do not
worry about whether you were unable to play or chose not to. In either case you may discard and draw, or you may keep your hand as is.

\section{Voting Day}

When a player moves the calendar piece to Iowa Caucus day the game ends immediately. The player with the most poll chips wins. If there is a tie for first,
those players advance to the New Hampshire primary. All players not in the tie place their chips on undecided.
Move the calendar back two spaces for each player in the tie plus one. Continue play. Or, you could call it a draw, flip a coin, or settle in
some other non-violent manner.

\subsection{Disclaimer}

Any similarity between persons in this game and any person living or dead is purely coincidental, unless that person ran for office, hosted or appeared on a TV show
(cable or broadcast) in which case they are public figures and should expect a certain amount of humor at their expense. Oh, and I have only good things to say about Nancy Kassebaum.

\end{document}


\section{UTxO}
\label{sec:utxo}

Some of the functions related to scripts, datums and collateral need
to be adjusted for the new features. Most of these adjustments are
self-explanatory. Note that the new $\fun{collOuts}$ function
generates a single output with an index $| \txouts{txb} |$. This is to
avoid potential confusion for transactions spending that output.

\begin{figure*}[htb]
  \emph{Functions}
  %
  \begin{align*}
    & \fun{isTwoPhaseScriptAddress} : \Tx \to \hldiff{\UTxO} \to \Addr \to \Bool \\
    & \fun{isTwoPhaseScriptAddress}~tx~\hldiff{utxo}~a = \\
    &\quad\begin{cases}
        \True  & a \in \AddrScr \land \fun{validatorHash}~a \mapsto s \in \fun{txscripts}~tx~\hldiff{utxo} \land s \in \ScriptPhTwo \\
        \False & \text{otherwise}
      \end{cases}
    \nextdef
    & \fun{collBalance} : \TxBody \to \UTxO \to \Value \\
    & \fun{collBalance}~txb~utxo = \fun{ubalance}~(\var{utxo}|_{\fun{collInputs}~{txb}}) -
      \begin{cases}
         0                 & \fun{collRet}~txb = \Nothing \\
         \fun{collRet}~txb & \text{otherwise}
      \end{cases}
    \nextdef
    & \fun{collOuts} : \TxBody \to \UTxO \\
    & \fun{collOuts}~txb =
      \begin{cases}
        \emptyset                                                      & \fun{collRet}~txb = \Nothing \\
        \{ (\txid{txb}, | \txouts{txb} |) \mapsto \fun{collRet}~txb \} & \text{otherwise}
      \end{cases}
    \nextdef
    & \fun{feesOK} : \PParams \to \Tx \to \UTxO \to \Bool  \\
    & \fun{feesOK}~\var{pp}~tx~utxo = \\
    &~~      \minfee{pp}{tx} \leq \txfee{tx} \wedge (\fun{txrdmrs}~tx \neq \Nothing \Rightarrow \\
    &~~~~~~((\forall (a, \wcard, \wcard) \in \fun{range}~(\fun{collInputs}~tx \restrictdom \var{utxo}), a \in \AddrVKey) \\
    &~~~~~~\wedge \fun{adaOnly}~\var{balance} \\
    &~~~~~~\wedge \var{balance} \geq \hldiff{\lceil \txfee{txb} * \fun{collateralPercent}~pp / 100 \rceil} \\
    &~~~~~~\wedge \hldiff{(\fun{txcoll}~tx \neq \Nothing) \Rightarrow \var{balance} = \fun{txcoll}~tx} \\
    &~~~~~~\wedge \fun{collInputs}~{tx} \neq \emptyset) \\
    &~~      \where \\
    & ~~~~~~~ \var{balance}=\hldiff{\fun{collBalance}~tx~utxo}
  \end{align*}
  \caption{Functions related to fees and collateral}
  \label{fig:functions:utxo}
\end{figure*}

\begin{figure*}
  \begin{align*}
    & \fun{getDatum} : \Tx \to \UTxO \to \ScriptPurpose \to \seqof{\Datum} \\
    & \fun{getDatum}~{tx}~{utxo}~{sp} =
      \begin{cases}
        [\var{d}] & \var{sp} \in \TxIn, (\_, \_, h, \_) \in \var{utxo}~\var{sp},~ \var{d}\in\fun{txdats}~(\fun{txwits}~tx)~\var{h} \\
        [\var{d}] & \hldiff{\var{sp} \in \TxIn, (\_, \_, d, \_) \in \var{utxo}~\var{sp},~ \var{d} \in \Datum} \\
        \epsilon  & \text{otherwise}
      \end{cases}
    \nextdef
    & \fun{txscripts} : \Tx \to \hldiff{\UTxO} \to \powerset{\Script} \\
    & \fun{txscripts}~tx~utxo = \fun{txwitscripts}~tx \cup \hldiff{\{ \fun{hash}~s \mapsto s \mid (\_, \_, \_, s) \in \var{utxo}~(\fun{spendInputs}~tx \cup \fun{refInputs}~tx)\}}
    \nextdef
    & \fun{languages} : \Tx \to \UTxO \to \powerset{\Language} \\
    & \fun{languages}~tx~utxo =
      \{\fun{language}~s \mid s \in \range (\fun{txscripts}~tx~utxo) \cap \ScriptPhTwo\}
    \nextdef
    & \fun{allowedLanguages} : \Tx \to \UTxO \to \powerset{\Language} \\
    & \fun{allowedLanguages}~tx~utxo = \\
    & \begin{cases}
        \emptyset                   & \text{if}~\exists (a, \_, \_, \_) \in os, a \in \AddrBS \\
        \{ \PlutusVII \}            & \text{if}~\exists (\_, \_, d, s) \in os, d \in \Datum \lor s \neq \Nothing \lor \fun{refInputs}~tx \neq \emptyset \\
        \{ \PlutusVI, \PlutusVII \} & \text{otherwise}
      \end{cases} \\
    & \where \var{os} = \range \txouts{tx} \cup \var{utxo}~(\fun{spendInputs}~tx \cup \fun{refInputs}~tx)
  \end{align*}
  \caption{Functions related to scripts}
  \label{fig:functions:data}
\end{figure*}

\begin{figure}[htb]
  \begin{equation}
    \inference[Scripts-Yes]
    {
    \var{txb}\leteq\txbody{tx} &
    \var{sLst} := \fun{collectTwoPhaseScriptInputs}~\var{pp}~\var{tx}~\var{utxo}
    \\
    ~
    \\
    \fun{isValid}~\var{tx} = \fun{evalScripts}~\var{tx}~\var{sLst} = \True
    \\~\\
    {
      \begin{array}{r}
        \var{slot} \\
        \var{pp} \\
        \var{genDelegs} \\
      \end{array}
    }
    \vdash \var{pup} \trans{\hyperref[fig:rules:update]{ppup}}{\fun{txup}~\var{tx}} \var{pup'}
    \\~\\
    \var{refunded} \leteq \keyRefunds{pp}{txb}
    \\
    \var{depositChange} \leteq
      (\fun{totalDeposits}~{pp}~\var{poolParams}~\txcerts{txb})~-~\var{refunded}
    }
    {
    \begin{array}{l}
      \var{slot}\\
      \var{pp}\\
      \var{poolParams}\\
      \var{genDelegs}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{pup} \\
      \end{array}
      \right)
      \trans{utxos}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{\var{(\fun{spendInputs}~txb \subtractdom \var{utxo}) \cup \outs{txb}}}  \\
        \varUpdate{\var{deposits} + \var{depositChange}} \\
        \varUpdate{\var{fees} + \txfee{txb}} \\
        \varUpdate{\var{pup'}} \\
      \end{array}
      \right) \\
    }
  \end{equation}
  \begin{equation}
    \inference[Scripts-No]
    {
    \var{txb}\leteq\txbody{tx} &
    \var{sLst} := \fun{collectTwoPhaseScriptInputs}~\var{pp}~\var{tx}~\var{utxo} \\
    \hldiff{\var{collateralFees} := \fun{valueToCoin}~(\fun{collBalance}~txb~utxo)}
    \\
    ~
    \\
    \fun{isValid}~\var{tx} = \fun{evalScripts}~\var{tx}~\var{sLst} = \False
    }
    {
    \begin{array}{l}
      \var{slot}\\
      \var{pp}\\
      \var{poolParams}\\
      \var{genDelegs}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{pup} \\
      \end{array}
      \right)
      \trans{utxos}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{\var{(\fun{collInputs}~{txb} \subtractdom \var{utxo})} \cup \hldiff{\fun{collOuts}~txb}}  \\
        \var{deposits} \\
        \varUpdate{\var{fees} + \hldiff{\var{collateralFees}}} \\
        \var{pup} \\
      \end{array}
      \right)
    }
  \end{equation}
  \caption{State update rules}
  \label{fig:rules:utxo-state-upd}
\end{figure}

\begin{figure}[htb]
  \begin{equation}
    \inference[UTxO-inductive]
    {
      \var{txb}\leteq\txbody{tx} &
      \fun{ininterval}~\var{slot}~(\fun{txvldt}~{txb}) &
      \var{(\wcard, i_f)}\leteq\fun{txvldt}~{tx} \\~\\
      \Nothing \notin \{\fun{txrdmrs}~\var{tx}, i_f\} \Rightarrow \fun{epochInfoSlotToUTCTime}~\mathsf{EI}~\mathsf{SysSt}~i_f \neq \Nothing \\
      \fun{spendInputs}~txb \neq \emptyset
      & \fun{feesOK}~pp~tx~utxo
      \\
      \fun{spendInputs}~txb \cup \fun{collInputs}~txb \cup \hldiff{\fun{refInputs}~{tx}} \subseteq \dom \var{utxo} \\
      \consumed{pp}{utxo}{txb} = \produced{pp}{poolParams}~{txb}
      \\~\\
      \mathsf{adaID}\notin \supp {\fun{mint}~tx} \\~\\
      \forall txout \in \txouts{txb}, \\
      \fun{getValue}~txout \geq \fun{inject}~(\hldiff{\lceil\fun{serSize}~txout * \fun{coinsPerUTxOWord}~pp/8\rceil}) \\~
      \\
      \forall txout \in \txouts{txb},\\
      \fun{serSize}~(\fun{getValue}~txout) \leq \fun{maxValSize}~pp \\~
      \\
      \forall (\wcard\mapsto (a,~\wcard)) \in \txouts{txb}, a \in \AddrBS \Rightarrow \fun{bootstrapAttrsSize}~a \leq 64 \\
      \forall (\wcard\mapsto (a,~\wcard)) \in \txouts{txb}, \fun{netId}~a = \NetworkId
      \\
      \forall (a\mapsto\wcard) \in \txwdrls{txb}, \fun{netId}~a = \NetworkId \\
      (\fun{txnetworkid}~\var{txb} = \NetworkId) \vee (\fun{txnetworkid}~\var{txb} = \Nothing)
      \\~\\
      \fun{txsize}~{tx}\leq\fun{maxTxSize}~\var{pp} \\~\\
      \fun{totExunits}~{tx} \leq \fun{maxTxExUnits}~{pp} &  \| \fun{collInputs}~{tx} \| \leq \fun{maxCollateralInputs}~{pp}
      \\
      ~
      \\
      {
        \begin{array}{c}
          \var{slot}\\
          \var{pp}\\
          \var{poolParams}\\
          \var{genDelegs}\\
        \end{array}
      }
      \vdash
      {
        \left(
          \begin{array}{r}
            \var{utxo} \\
            \var{deposits} \\
            \var{fees} \\
            \var{pup}\\
          \end{array}
        \right)
      }
      \trans{utxos}{\var{tx}}
      {
        \left(
          \begin{array}{r}
            \var{utxo'} \\
            \var{deposits'} \\
            \var{fees'} \\
            \var{pup'}\\
          \end{array}
        \right)
      }
    }
    {
      \begin{array}{l}
        \var{slot}\\
        \var{pp}\\
        \var{poolParams}\\
        \var{genDelegs}\\
      \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{pup}\\
      \end{array}
      \right)
      \trans{utxo}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{\var{utxo'}}  \\
        \varUpdate{\var{deposits'}} \\
        \varUpdate{\var{fees'}} \\
        \varUpdate{\var{pup'}}\\
      \end{array}
      \right)
    }
  \end{equation}
  \caption{UTxO inference rules}
  \label{fig:rules:utxo-babbage}
\end{figure}

To the UTXOW rule, in addition to the changes required by the new
features, we add a check that all scripts and datums involved in the
transaction are well-formed. Also, we forbid transactions that use the
new features and try to use $\PlutusVI$ scripts.

\begin{figure}
  \begin{equation}
    \label{eq:utxo-witness-inductive-babbage}
    \inference[UTxO-witG]
    {
      \var{txb}\leteq\txbody{tx} &
      \var{txw}\leteq\fun{txwits}~{tx} \\
      (utxo, \wcard, \wcard, \wcard) \leteq \var{utxoSt} \\
      \var{witsKeyHashes} \leteq \{\fun{hashKey}~\var{vk} \vert \var{vk} \in
      \dom (\txwitsVKey{txw}) \}\\
      \var{inputHashes}\leteq \left\{ h \,\middle|
        {
          \begin{array}{l}
            (a, \_, h) \in \range(\var{utxo}|_{\fun{spendInputs}~tx}) \\
            \fun{isTwoPhaseScriptAddress}~tx~\hldiff{utxo}~a \\
          \end{array}
        }
      \right\} \cap \hldiff{\DataHash} \\~\\
      \forall \var{s} \in \range (\fun{txscripts}~txw~\hldiff{utxo}) \cap \ScriptPhOne,
      \fun{validateScript}~\var{s}~\var{tx}\\~\\
      \{ h \mid (\_, h) \in \fun{scriptsNeeded}~\var{utxo}~txb\} = \dom (\fun{txscripts}~txw~\hldiff{utxo}) \\~\\
      \var{inputHashes} \subseteq \dom (\fun{txdats}~{txw}) \\~\\
      \dom (\fun{txdats}~{txw}) \subseteq \var{inputHashes} \cup \{h \mid (\wcard, \wcard, h)\in\fun{txouts}~{tx} \cup \hldiff{\var{utxo}~(\fun{refInputs}~{tx})}\}
      \\~\\
      \dom (\fun{txrdmrs}~tx) = \left\{ \fun{rdptr}~txb~sp \,\middle|
        {
          \begin{array}{l}
            (sp,h) \in \fun{scriptsNeeded}~\var{utxo}~txb \\
            \fun{txscripts}~{txw}~\hldiff{utxo}~h \in \ScriptPhTwo
          \end{array}
        } \right\}
      \\~\\
      \var{txbodyHash}\leteq\fun{hash}~(\txbody{tx}) \\
      \forall \var{vk} \mapsto \sigma \in \txwitsVKey{tx},
      \mathcal{V}_{\var{vk}}{\serialised{txbodyHash}}_{\sigma} \\
      \fun{witsVKeyNeeded}~{utxo}~{tx}~{genDelegs} \subseteq witsKeyHashes
      \\~\\
      genSig \leteq
      \left\{
        \fun{hashKey}~gkey \vert gkey \in\dom{genDelegs}
      \right\}
      \cap
      \var{witsKeyHashes}
      \\
      \left\{
        c\in\txcerts{txb}~\cap\DCertMir
      \right\} \neq\emptyset \implies \vert genSig\vert \geq \Quorum \wedge
      \fun{d}~\var{pp} > 0
      \\~\\
      \var{adh}\leteq\fun{txADhash}~\var{txb}
      &
      \var{ad}\leteq\fun{auxiliaryData}~\var{tx}
      \\
      (\var{adh}=\Nothing \land \var{ad}=\Nothing)
      \lor
      (\var{adh}=\fun{hashAD}~\var{ad})
      \\~\\
      \hldiff{\forall x \in \range (\fun{txdats}~txw) \cup \range (\fun{txwitscripts}~txw) \cup \bigcup_{(\_, \_, d, s) \in \txouts{tx}} \{s, d\},} \\
      \hldiff{x \in \Script \cup \Datum \Rightarrow \fun{isWellFormed}~x}
      \\~\\
      \fun{languages}~tx~\hldiff{utxo} \subseteq \dom(\fun{costmdls}~pp) \cap \fun{allowedLanguages}~tx~utxo \\
      \fun{scriptIntegrityHash}~{txb} =
      \fun{hashScriptIntegrity}~\var{pp}~(\fun{languages}~{txw})~(\fun{txrdmrs}~{txw})~(\fun{txdats}~{txw})
      \\~\\
      {
        \begin{array}{r}
          \var{slot}\\
          \var{pp}\\
          \var{poolParams}\\
          \var{genDelegs}\\
        \end{array}
      }
      \vdash \var{utxoSt} \trans{\hyperref[fig:rules:utxo-shelley]{utxo}}{tx}
      \var{utxoSt'}\\
    }
    {
      \begin{array}{r}
        \var{slot}\\
        \var{pp}\\
        \var{poolParams}\\
        \var{genDelegs}\\
      \end{array}
      \vdash \var{utxoSt} \trans{utxow}{tx} \varUpdate{\var{utxoSt'}}
    }
  \end{equation}
  \caption{UTxO with witnesses inference rules for Tx}
  \label{fig:rules:utxow-babbage}
\end{figure}


\chapter{Mesh and Element Configuration} \label{chap:meshconfig}

 \NOTE{This description has not been updated for ViennaGrid 1.1.0 yet!}

A mesh and all its topological elements as well as the underlying geometric space are specified in a common configuration class.
The setup of such a configuration class is explained in detail in Section \ref{sec:config-class}.

Even though mathematically all $n$-cells of a mesh are well defined and available on paper, it may not make sense to store explicit representations of these elements in memory.
As discussed in the Introduction, a particular algorithm may not require the storage of edges and/or facets of a mesh, thus keeping these elements in memory can be a considerable waste of resources.
Section \ref{sec:customizing-storage} explains how the underlying storage scheme of {\ViennaGrid} can be adjusted to the library user's requirements and to be as memory-efficient as possible.

\section{The Configuration Class} \label{sec:config-class}
A valid configuration class for {\ViennaGrid} is any class that provides the following three public member types:
\begin{center}
\begin{tabular}{|l|p{8cm}|}
\hline
 \lstinline|numeric_type|   & The underlying scalar type of the geometric space. \\
\hline
 \lstinline|coordinate_system_tag| & A tag specifying the underlying coordinate system.\\
\hline
 \lstinline|cell_tag|       & A tag that identifies the cell type inside the mesh.\\
\hline
\end{tabular}
\end{center}

More details on the types are given in the following:
\begin{itemize}
 \item \lstinline|numeric_type|: This refers to the type of the coordinates of a point in the geometric space. In most cases, one may want to use \lstinline|double|. However, it may also be the case that the user prefers to use integer coordinates, or high-precision floating point libraries such as ARPREC \cite{arprec}.

 \item \lstinline|coordinate_system_tag|: Any of the following predefined classes from namespace \lstinline|viennagrid| can be defined as \lstinline|coordinate_system_tag| to select the coordinate system of the underlying geometric space:
   \begin{center}
   \begin{tabular}{|l|l|}
    \hline
    \lstinline|cartesian_cs<dim>|   &  Cartesian coordinate system of dimension \lstinline|dim| \\
    \hline
    \lstinline|polar_cs|       &  Polar coordinate system in two dimensions \\
    \hline
    \lstinline|spherical_cs|   &  Spherical coordinates in three dimensions \\
    \hline
    \lstinline|cylindrical_cs| &  Cylindrical coordinates in three dimensions \\
    \hline
   \end{tabular}
   \end{center}

 \item \lstinline|cell_tag|: A tag that specifies the type of the elements with maximum topological dimension in the mesh. The following two families of topological elements are provided with {\ViennaGrid} in namespace \lstinline|viennagrid|:
   \begin{center}
   \begin{tabular}{|l|l|}
    \hline
    \lstinline|simplex<n>|     &  Refers to an $n$-simplex \\
    \hline
    \lstinline|hypercube<n>|   &  Refers to an $n$-hypercube \\
    \hline
   \end{tabular}
   \end{center}
 It should be noted that \lstinline|simplex<1>| and \lstinline|hypercube<1>| both refer to a line segment. Typical examples from these families for common values of $n$ are as follows:
\begin{center}
 \begin{tabular}{|l|c|c|}
  \hline
          & {\ViennaGrid} tag type   & Convenience \lstinline|typedef| \\
  \hline
  Vertex  & \lstinline|point_tag|    &  - \\
  \hline
  Line    & \lstinline|simplex_tag<1>|   & \lstinline|line_tag| \\
  Line    & \lstinline|hypercube_tag<1>| & - \\
  \hline
  Triangle & \lstinline|simplex_tag<2>|  & \lstinline|triangle_tag| \\
  Quadrilateral & \lstinline|hypercube_tag<2>| & \lstinline|quadrilateral_tag| \\
  \hline
  Tetrahedron & \lstinline|simplex_tag<3>| & \lstinline|tetrahedron_tag| \\
  Hexahedron & \lstinline|hypercube_tag<3>| & \lstinline|hexahedron_tag| \\
  \hline
 \end{tabular}
\end{center}
 The reference orientations of these cells can be found in Appendix \ref{chap:orientations}.
\end{itemize}

All geometric and topological types inside the mesh are then derived from the configuration class. To this end, {\ViennaGrid} provides
a number of meta-functions that reside in namespace \lstinline|viennagrid::result_of|. The naming follows the conventions in the Boost libraries \cite{boost}.
For a configuration class \lstinline|Config|, the respective types are obtained as follows:
\begin{lstlisting}
 using namespace viennagrid;

 typedef result_of::mesh<Config>::type     MeshType;
 typedef result_of::segment<Config>::type    SegmentType;
 typedef result_of::ncell<Config, 0>::type   VertexType;
 typedef result_of::ncell<Config, 1>::type   EdgeType;
\end{lstlisting}
In particular, the type of any $n$-cell in the mesh is obtained as
\begin{lstlisting}
 typedef result_of::ncell<Config, n>::type   ElementType;
\end{lstlisting}
where $n$ has to be replaced with the respective value. This allows to formulate algorithms such as a mesh boundary detection in a very general manner and can be used for recursively iterating through the $n$-cells of different dimension. In order to obtain the types of cells and facets, one should use the topological dimension from the cell tag:
\begin{lstlisting}
 typedef Config::cell_tag                                CellTag;
 typedef result_of::ncell<Config, CellTag::dim-1>::type  FacetType;
 typedef result_of::ncell<Config, CellTag::dim>::type    CellType;
\end{lstlisting}

\TIP{Please note that in template classes and template functions one needs to add an extra \lstinline|typename| after each \lstinline|typedef| keyword in the code snippets above.}

{\ViennaGrid} ships with a number of default configurations, which can directly be used without the need for setting up a separate config class:
\begin{center}
 \begin{tabular}{|l|l|}
  \hline
   Class Name           & Description \\
  \hline
   \lstinline|line_1d|  & one-dimensional mesh \\
   \lstinline|line_2d|  & mesh of lines in 2d \\
   \lstinline|line_3d|  & mesh of lines in 3d \\
   \lstinline|triangular_2d| & triangular mesh in 2d \\
   \lstinline|triangular_3d| & triangular mesh in 3d \\
   \lstinline|tetrahedral_3d| & tetrahedral mesh in 2d \\
   \lstinline|quadrilateral_2d| & quadrilateral mesh in 2d \\
   \lstinline|quadrilateral_3d| & quadrilateral mesh in 3d \\
   \lstinline|hexahedral_3d| & hexahedral mesh in 2d \\
  \hline
 \end{tabular}
\end{center}
The classes reside in namespace \lstinline|viennagrid::config| and in the files \lstinline|simplex.hpp| and \lstinline|others.hpp| (for non-simplex meshes) in the \lstinline|viennagrid/config| folder.
Each of these configurations uses a numeric type \lstinline|double| and a Cartesian coordinate system.

\section{Customizing Storage of $n$-Cells} \label{sec:customizing-storage}
One of the outstanding features of {\ViennaGrid} over other libraries related to grid handling is the possibility to customize the internal storage of elements. By default, all $n$-cells of a mesh are stored explicitly inside the mesh. In addition, each $n$-cell stores links to its boundary $k$-cells, with $k<n$. While this overhead is not a concern for topologically one-dimensional meshes and moderate for topologically two-dimensional meshes, it can be a considerable issue for dimensions three and above.

As an example, linear finite elements need information about the cells and the vertices inside the mesh, while edges and facets may not be needed depending on the boundary conditions imposed.

\begin{table}[tb]
 \centering
 \begin{tabular}{|l|r|r|r|}
  \hline
         & Amount      & Bytes/Object         & Total Memory \\
  \hline
  Vertices & 4913 & 24 & 115 KB \\
  \hline
  Edges   & 31024 & 16 & 485 KB \\
  \hline
  Facets  & 50688 & 48 & 2376 KB \\
  \hline
  Cells   & 24576 & 112 & 2688 KB \\
  \hline
  \textbf{Total}  &       &     &  \textbf{5664 KB} \\
  \hline
 \end{tabular}
 \caption{Minimum memory consumption for a tetrahedral mesh of the unit cube where all $n$-cells are stored explicitly and boundary information on each $n$-cell is stored. Vertices use \lstinline|double|-precision coordinates and elements are linked with pointers sized eight bytes each.}
 \label{tab:full-mesh-memory}
\end{table}

\begin{table}[tb]
 \centering
 \begin{tabular}{|l|r|r|r|}
  \hline
         & Amount      & Bytes/Object         & Total Memory \\
  \hline
  Vertices & 4913 & 24 & 115 KB \\
  \hline
  Edges   & 0 & - & 0 KB \\
  \hline
  Facets  & 0 & - & 0 KB \\
  \hline
  Cells   & 24576 & 32 & 768 KB \\
  \hline
  \textbf{Total}  &       &     &  \textbf{883 KB} \\
  \hline
 \end{tabular}
 \caption{Minimum memory consumption for a tetrahedral mesh of the unit cube where only $0$-cells and $3$-cells are stored explicitly. $3$-cells have knowledge of their $0$-cells only. Vertices use \lstinline|double|-precision coordinates and elements are linked with pointers sized eight bytes each.}
 \label{tab:slim-mesh-memory}
\end{table}

As shown in Tab.~\ref{tab:full-mesh-memory} and Tab.~\ref{tab:slim-mesh-memory}, storing facets and edges explicitly increases the total memory consumption by a factor of more than six. In cases where additional maps for the mapping from local to global $n$-cell orientations are stored together with the topological boundary information, the difference in memory consumption is even higher.

{\ViennaGrid} can be customized to switch seamlessly between the different storage models, as will be shown in the following subsections.

\NOTE{Note that in {\ViennaGrid} a cell always stores pointers to its vertices. Similarly, the mesh always stores the cells and vertices.}

\subsection{Boundary $n$-Cells} \label{subsec:boundary-ncells-storage}

Disabling the storage of boundary $n$-cells can be achieved in two ways, which are equivalent on a source-code level, but differ with respect to convenience:
\begin{itemize}
 \item \textbf{Method 1}: Use the provided macros. The storage of elements can be customized either for a particular configuration class, or globally for all mesh configuration classes. To disable the storage of edges (i.e.~$1$-cells) inside a tetrahedron for a mesh with configuration class \lstinline|MyConfig|, the line
  \begin{lstlisting}
VIENNAGRID_DISABLE_BOUNDARY_NCELL(MyConfig,
                                  viennagrid::tetrahedron_tag, 1)
  \end{lstlisting}
right after the {\ViennaGrid}-includes in the source file containing \lstinline|main()| is sufficient. Make sure that the macro is placed in the global namespace. The first argument is the configuration class, the second class is the tag for the respective $n$-cell for which the boundary element should be disabled, and the third parameter is the topological dimension for which the handling should be disabled.
 If no edges should be stored for a tetrahedron irrespective of the configuration class, the macro
  \begin{lstlisting}
VIENNAGRID_GLOBAL_DISABLE_BOUNDARY_NCELL(viennagrid::tetrahedron_tag,
                                         1)
  \end{lstlisting}
 should be used. If one wishes to selectively enable the handling of boundary cells within a globally disabled storage of boundary $n$-cells, one can use e.g.
  \begin{lstlisting}
VIENNAGRID_ENABLE_BOUNDARY_NCELL(MyConfig,
                                 viennagrid::tetrahedron_tag, 1)
  \end{lstlisting}
 to enable the storage of edges inside a tetrahedron for a configuration class \lstinline|MyConfig|.

 \item \textbf{Method 2}: The macros above are shortcuts for class specializations. The first two macros expand to the following code:
\begin{lstlisting}
namespace viennagrid { namespace result_of {
    template <>
    struct bndcell_handling<MyConfig,
                            viennagrid::tetrahedron_tag, 1>{
      typedef no_handling_tag    type;
    };

    template <typename ConfigType>
    struct bndcell_handling<ConfigType,
                            viennagrid::tetrahedron_tag, 1>{
      typedef no_handling_tag    type;
    };
} }
\end{lstlisting}
The third macro explained for method 1 results in the same code as the first macro, with the exception that \lstinline|no_handling_tag| is replaced with \lstinline|full_handling_tag|.

Finally, we wish to point at a potential pitfall when disabling $n$-cells that are neither $0$-cells, $N-1$-cells, nor $N$-cells: Consider the case of disabling edges for a tetrahedron. Using the line
  \begin{lstlisting}
VIENNAGRID_DISABLE_BOUNDARY_NCELL(MyConfig,
                                  viennagrid::tetrahedron_tag, 1)
  \end{lstlisting}
only disables the edges for the tetrahedron, but still edges are pushed and stored inside the mesh, because the triangular facets of the tetrahedron store pointers to their edges. Thus, to completely disable the storage of any edges, one also has to disable the storage of edges for triangles. As a check, one should verify that the number of edges stored inside a mesh \lstinline|my_mesh| and obtained by
 \begin{lstlisting}
  viennagrid::ncells<1>(my_mesh).size()
 \end{lstlisting}
is zero.

\TIP{Have a look at \texttt{examples/tutorial/slim\_mesh.cpp} and selectively enable or disable the storage of elements to see the impact on total memory consumption. Note that the bytes per object may differ from Tab.~\ref{tab:full-mesh-memory} and Tab.~\ref{tab:slim-mesh-memory} depending on the use of local-to-global-orienters and the eventual use of integral IDs.}

\subsection{Local Orientations} \label{subsec:customize-local-orientations}
\begin{figure}[tb]
\centering
 \includegraphics[width=0.5\textwidth]{figures/interface-tets.eps}
 \caption{Boundary $n$-cells have different orientations with respect to different cells.}
 \label{fig:orientation-boundary-ncells}
\end{figure}

In cases where $n$-cells store boundary $k$-cells, $k<n$, it may be required to know the orientation of the globally (i.e.~in the mesh) stored $k$-cell with respect to the local reference orientation of the $n$-cell. The common facet of the two tetrahedra in Fig.~\ref{fig:orientation-boundary-ncells} may be stored globally using the sequence of vertex indices $[1, 2, 3]$. Inside the tetrahedron $[0, 1, 2, 3]$ the facet again possesses the orientation $[1, 2, 3]$, thus matching the global orientation. However, within the tetrahedron $[4, 2, 1, 3]$ the facet has the local orientation $[2, 1, 3]$ (refer to the Appendix for an overview of reference orientations). For applications such as high-order finite elements, such a local orientation with respect to the cell is required.

By default, {\ViennaGrid} stores the local orientation of each boundary $k$-cell inside the hosting $n$-cell, where one byte per vertex of each $k$-cell is consumed. In order to disable the storage of these local orientations for scenarios where the local orientation is not needed, there are again two methods provided:
\begin{itemize}
 \item \textbf{Method 1}: Using the macros provided. To disable the storage of local orientations of edges (i.e.~$1$-cells) inside a tetrahedron for a mesh with configuration class \lstinline|MyConfig|, the line
\begin{lstlisting}
VIENNAGRID_DISABLE_BOUNDARY_NCELL_ORIENTATION(MyConfig,
                              viennagrid::tetrahedron_tag, 1)
\end{lstlisting}
is sufficient. The second argument denotes the hosting $n$-cell tag, while the third argument denotes the topological dimension $k$ of the boundary $k$-cells.

Similar to the previous section, one can disable the storage of local orientations globally for all configuration classes by
\begin{lstlisting}
VIENNAGRID_GLOBAL_DISABLE_BOUNDARY_NCELL_ORIENTATION(
                              viennagrid::tetrahedron_tag, 1)
\end{lstlisting}
To selectively enable the storage of local orientations in a globally disabled setting, the macro \lstinline|VIENNAGRID_ENABLE_BOUNDARY_NCELL_ORIENTATION| can be used in the same way as \lstinline|VIENNAGRID_DISABLE_BOUNDARY_NCELL_ORIENTATION|.
Again, it is recommended to define the macros in the source file containing \lstinline|main()| after the inclusion of the {\ViennaGrid} header files.

 \item \textbf{Method 2}: Instead of using the macros, one may manually adjust the meta-function \lstinline|bndcell_orientation|. The first macro of method 1 expands to
 \begin{lstlisting}
namespace viennagrid { namespace result_of {
  template <>
  struct bndcell_orientation<MyConfig,
                             viennagrid::tetrahedron_tag, 1>
  {  typedef no_handling_tag    type;  };
}  }
 \end{lstlisting}
Using the type \lstinline|full_handling_tag| instead of \lstinline|no_handling_tag| enables the storage of local orientations.
\end{itemize}

\TIP{If the storage of boundary $k$-cells is disabled (cf.~Sec.~\ref{subsec:boundary-ncells-storage}), there are automatically no local orientations for boundary $k$-cells stored. The local orientations do not need to be disabled explicitly in this case.}

\subsection{$n$-Cell IDs} \label{subsec:ncell-ids}
It is often convenient to have enumerated $n$-cells within a mesh such that every $n$-cell is aware of its index inside the random access container it resides in. This allows for some algorithms to use fast random-accesses with $\LandauO(1)$ costs rather than searching trees with $\LandauO(\log N)$ costs or linked lists with $\LandauO(N)$ costs, where $N$ here denotes the number of $n$-cells inside the mesh. Conversely, if $\LandauO(\log N)$ access times are acceptable, then the memory for storing the container index (which we refer to in the following as \emph{$n$-cell ID}) is wasted. To accommodate for these two scenarios, {\ViennaGrid} allows to selectively enable or disable the storage of $n$-cell IDs. By default, $n$-cell IDs are stored, since they have negligible impact on the total memory consumption as soon as other boundary $k$-cells are stored for an $n$-cell.

As for the storage of boundary $k$-cells and local orientations, there are two possibilities for customizing the storage of IDs:
\begin{itemize}
 \item \textbf{Method 1}: Using the provided macros. To disable the storage of IDs for tetrahedrons inside a mesh with configuration \lstinline|MyConfig|, the line
 \begin{lstlisting}
VIENNAGRID_DISABLE_NCELL_ID(viennagrid::config::tetrahedral_3d,
                            viennagrid::tetrahedron_tag)
 \end{lstlisting}
 is sufficient. The second argument denotes the element tag for which the storage of IDs should be disabled.

 To globally disable the storage of IDs for tetrahedrons, use
 \begin{lstlisting}
VIENNAGRID_GLOBAL_DISABLE_NCELL_ID(viennagrid::tetrahedron_tag)
 \end{lstlisting}
 To selectively enable the storage of IDs for certain configuration classes in a globally disabled setting, one can use
 \begin{lstlisting}
VIENNAGRID_ENABLE_NCELL_ID(viennagrid::config::tetrahedral_3d,
                           viennagrid::tetrahedron_tag)
 \end{lstlisting}

 \item \textbf{Method 2}:
The macros from the first method expand to
\begin{lstlisting}
template <>
struct element_id_handler<MyConfig, viennagrid::tetrahedron_tag>
{  typedef pointer_id    type;  };
\end{lstlisting}
for the configuration class \lstinline|MyConfig|, and to
\begin{lstlisting}
template <typename ConfigType>
struct element_id_handler<ConfigType, viennagrid::tetrahedron_tag>
{  typedef pointer_id    type;  };
\end{lstlisting}
for globally disabling the storage of IDs. To selectively enable IDs, \lstinline|integral_id| should be used instead of \lstinline|pointer_id|.

\end{itemize}

\TIP{Have a look at \texttt{examples/tutorial/slim\_mesh.cpp} and selectively enable or disable the storage of elements, local orientations and IDs to see the impact on total memory consumption. Note that the bytes per object may differ from Tab.~\ref{tab:full-mesh-memory} and Tab.~\ref{tab:slim-mesh-memory} depending on the use of local orientations and integral IDs.}

\NOTE{Disabling $n$-cell IDs eliminates the possibility to store and access data for the respective $n$-cells with $\LandauO(1)$ costs, see Chapter \ref{chap:data}.}

\end{itemize}


\chapter{Introduction}

The \numbers\ program is a shell program which reads and stores data
from a finite element model described in the \exo\ database
format~\cite{EXODUS}.
Within this shell program are several utility routines which calculate
information about the finite element model.  The utilities currently
implemented in \numbers\ allow the analyst to determine:
\begin{itemize}
\item the volume and coordinate limits of each of the materials in the model;
\item the mass properties of the model;
\item the minimum, maximum, and average element volumes for each material;
\item the volume and change in volume of a cavity;
\item the nodes or elements that are within a specified distance from a
user-defined point, line, or plane;
\item an estimate of the explicit central-difference timestep for each
material;
\item the validity of contact surfaces or slidelines, that is, whether
two surfaces overlap at any point; and
\item the distance between two surfaces.
\end{itemize}

These utilities have been developed to automate and simplify some of the
tasks normally performed during an analysis.  The \numbers\ program
reads the finite element model and results from a file written in the
\exo\ binary file format which is used in the Engineering
Analysis Department at \SNLA.

The capabilities of \numbers\ have evolved during the past eighteen
months.  Originally, it was written solely to calculate the mass
properties of a body.  However, once the basic function of reading and
storing an \exo\ database was in place, it was realized that several
tasks that were usually performed manually could easily be implemented
in \numbers.  Tasks such as determining node and element numbers,
verifying contact surfaces, and others, are now performed more
efficiently and, hopefully, more accurately since the code performs the
repetitive calculations automatically.

Although the original reason for developing \numbers\ was to simply
calculate mass properties, the code now functions as an \exo\ shell that
can be easily extended by analysts who require specific calculations or
need to create information not currently available.  The analyst can
simply write a subroutine to perform their function, and insert it into
\numbers\ without worrying about the details of reading an \exo\
database and providing a user interface. For most cases, adding a
function to \numbers\ requires only writing the function subroutine,
adding the command name to the table of valid commands, and adding a few
statements to call the routine.

The remainder of this report is organized as follows.
Chapter~\ref{c:numerics} describes the numerical algorithms used by the
utility functions in \numbers.  A list of the commands and the command
syntax are presented in Chapter~\ref{c:commands}.
Chapter~\ref{c:examples} gives several examples of the use of the
utilities, and Chapter~\ref{c:conclude} concludes the report.  Three
appendixes are included.  Appendix~\ref{a:cmdsum} is a summary of the
command syntax for each of the commands.

The descriptions in the following chapters assume that the reader is
familiar with the \gen\ and \exo\ file formats and with the analysis,
preprocessing, and postprocessing codes used in the Engineering Analysis
Department at \SNLA.  Readers not familiar with these can check the
references at the end of this report for a list of the documentation for
these codes and file formats.


\documentclass[a4paper]{article}

\usepackage[margin=2cm]{geometry}		% For desired margins
\usepackage{fontspec}					% utf-8 support
\usepackage{enumitem}					% Continuous enumerations
\usepackage{float}						% Floating images
\usepackage[dvipsnames]{xcolor}			% Colors
\usepackage{pgfplots}					% Custom plots
\usepackage{listings}					% Code highlighting
\usepackage[hidelinks]{hyperref}		% Hyper links
\usepackage{graphicx}					% To include images
\usepackage{tikz}						% To draw images
\usepackage{pgfplots}					% To draw graphs
\usepackage[dvipsnames]{xcolor	}
\usepackage{subcaption}

\pgfplotsset{compat=1.13}
\usetikzlibrary{positioning}

\setlength{\parindent}{0pt}
\setlength{\parskip}{1em}

\title{PAR: Laboratory 5 \\
		\texttt{\large par4201}}
\author{Joan Marcè i Igual \and Es6teve Tarragó i Sanchis}

\newenvironment{questionenum}{%
\setlist[enumerate]{resume}
\restartlist{enumerate}
\newcommand{\question}[1]{
\begin{enumerate}
	\item\bfseries ##1
\end{enumerate}
}}{%
}

\lstset{
	basicstyle=\small\ttfamily,
	showspaces=false,
	showstringspaces=false,
	tabsize=4,
	numbers=left,
	numbersep=5pt,
	stringstyle=\color{orange},
	commentstyle=\color{OliveGreen},
	keywordstyle=\color{blue},
	numberstyle=\color{Gray},
	frame=single
}

\begin{document}
\maketitle
\tableofcontents

\section{Analysis with Tareador}

\begin{questionenum}
	\question{Include the relevant parts of the modified \texttt{solver-tareador.c} code and comment where the calls to the Tareador API have been placed. Comment also about the task graph generated and the causes of the dependencies that appear in the two solvers: \emph{Jacobi} and \emph{Gauss-Seidel}. How will you protect them in the parallel \texttt{OpenMP} code.}
\end{questionenum}

\begin{center}
	\begin{minipage}{0.8\textwidth}
\begin{lstlisting}[language=C, title=\texttt{heat-tareador.c}]
switch( param.algorithm ) {
	case 0: // JACOBI
		tareador_start_task("relax_jacobi");
		residual = relax_jacobi(param.u, param.uhelp, np, np);
		tareador_end_task("relax_jacobi");
		// Copy uhelp into u
		tareador_start_task("Copy_mat");
		copy_mat(param.uhelp, param.u, np, np);
		tareador_end_task("Copy_mat");
		break;
	case 1: // GAUSS
		tareador_start_task("relax_gauss");
		residual = relax_gauss(param.u, np, np);
		tareador_end_task("relax_gauss");
		break;
}
		\end{lstlisting}
	\end{minipage}

	\begin{minipage}{0.8\textwidth}
		\begin{lstlisting}[language=C, title=\texttt{solver-tareador.c}]
// Set tareador task
tareador_start_task("jacobi_relax");
// Disable sum object for better parallelization potential
tareador_disable_object(&sum);
utmp[i*sizey+j]= 0.25 * ( u[ i*sizey     + (j-1) ]+  // left
u[ i*sizey     + (j+1) ]+  // right
u[ (i-1)*sizey + j     ]+  // top
u[ (i+1)*sizey + j     ]); // bottom
diff = utmp[i*sizey+j] - u[i*sizey + j];
sum += diff * diff;

// Reenable sum object
tareador_enable_object(&u);

// End of tareador task
tareador_end_task("jacobi_relax");
		\end{lstlisting}
	\end{minipage}
\end{center}

\section{OpenMP parallelization and execution analysis: \emph{Jacobi}}
\begin{questionenum}
	\question{Describe the data decomposition strategy that is applied to solve the problem, including a picture with the part of the data structure that is assigned to each processor.}

	The decomposition strategy used is giving each thread a different part of the matrix by rows. This can be seen in the \autoref{fig:jacobi-data} where each thread has a different block of rows of the matrix to be computed.

	\begin{figure}[H]
		\centering
		\includegraphics[width=0.5\textwidth]{images/jacobi/data}
		\caption{Figure describing the data decomposition, each thread has one color}
		\label{fig:jacobi-data}
	\end{figure}

	\question{Include the relevant portions of the parallel code that you implemented to solve the heat equation using the \emph{Jacobi} solver, commenting whatever necessary. Including captures of Paraver windows to justify your explanations and the differences observed in the execution.}

	The heat computation part can be optimized in the following way with \texttt{OpenMP}.
	\begin{center}

	\begin{minipage}{0.9\textwidth}
		\begin{lstlisting}[language=C, title=\texttt{solver-tareador.c}]
double relax_jacobi (double *u, double *utmp, unsigned sizex, unsigned sizey)
{
	double diff, sum=0.0;

	// In this part max threads is used instead of get_num_threads() beacuse
	// there's only one thread at this point.
	int howmany = omp_get_max_threads();

	// Parallelize by blocks, assigning each block to one different thread
	#pragma omp parallel for reduction(+:sum) private(diff)
	for (int blockid = 0; blockid < howmany; ++blockid) {
		int i_start = lowerb(blockid, howmany, sizex);
		int i_end = upperb(blockid, howmany, sizex);
		for (int i=max(1, i_start); i<= min(sizex-2, i_end); i++) {
			for (int j=1; j<= sizey-2; j++) {
				utmp[i*sizey+j]= 0.25 * ( u[ i*sizey     + (j-1) ]+  // left
				u[ i*sizey     + (j+1) ]+  // right
				u[ (i-1)*sizey + j     ]+  // top
				u[ (i+1)*sizey + j     ]); // bottom
				diff = utmp[i*sizey+j] - u[i*sizey + j];
				sum += diff * diff;
			}
		}
	}

	return sum;
}
		\end{lstlisting}
	\end{minipage}
	\end{center}

	Also there's another complementary way to optimize. The \texttt{copy\_mat()} function can be parallelized to allow a better way of copying the matrix.

	\begin{center}
		\begin{minipage}{0.8\textwidth}
			\begin{lstlisting}[language=C, title=\texttt{solver-tareador.c}]
#pragma omp parallel for collapse(2)
for (int i=1; i<=sizex-2; i++)
	for (int j=1; j<=sizey-2; j++)
		v[ i*sizey+j] = u[ i*sizey+j ];
			\end{lstlisting}
		\end{minipage}
	\end{center}

	Another way to attack the problem is avoiding the matrix copy part and only swapping the pointers of the matrix. This can be done in the \texttt{heat-omp.c} file between the iterations.

	\begin{center}
		\begin{minipage}{0.8\textwidth}
			\begin{lstlisting}[language=C, title=\texttt{heat-omp.c}]
residual = relax_jacobi(param.u, param.uhelp, np, np);
// Swap the pointers to avoid copying the matrix
double *temp = param.u;
param.u = param.uhelp;
param.uhelp = temp;

// Disable the matrix copy
//copy_mat(param.uhelp, param.u, np, np);
			\end{lstlisting}
		\end{minipage}
	\end{center}

	\begin{figure}[H]
		\centering
		\includegraphics[width=\textwidth]{images/jacobi/paraver-8}
		\caption{Capture of \texttt{paraver} using 8 processors}
		\label{fig:jacobi-paraver}
	\end{figure}

	\begin{figure}[H]
		\centering
		\includegraphics[width=\textwidth]{images/jacobi/paraver-8-zoom}
		\caption{Zoom of \texttt{paraver} capture to show that the processor 0 is still doing work}
		\label{fig:jacobi-paraver-zoom}
	\end{figure}

	As it can be seen in the \autoref{fig:jacobi-paraver} all processors are working so the work is properly shared between all the processors. It seems that the processor 0 is only doing synchronizations but actually it's working too as it can be seen in the \autoref{fig:jacobi-paraver-zoom}.

	\question{Include the speed-up (strong scalability) plots that have been obtained for the different numbers of processors. Reason about the performance that is observed.}

	\begin{figure}[H]
		\begin{subfigure}[t]{0.49\textwidth}
			\begin{tikzpicture}
				\begin{axis}[
						width = \textwidth,
						xmin = 1, xmax = 12,
						domain = 0:12,
						xlabel = number of processors,
						ylabel = execution time,
						enlarge x limits = 0.05,
					]
					\addplot table[x = P, y = T]{data/jacobi/elapsed.csv};
					\addplot[dashed, mark = none] {4.5/x};
				\end{axis}
			\end{tikzpicture}
			\caption{Elapsed time for each number of processors}
			\label{fig:jacobi-elapsed}
		\end{subfigure}
		\hfill
		\begin{subfigure}[t]{0.49\textwidth}
			\begin{tikzpicture}
				\begin{axis}[
						width = \textwidth,
						xmin = 1, xmax = 12,
						ymin = 0, ymax = 12,
						domain = 0:12,
						xlabel = number of processors,
						ylabel = speedup,
						enlarge x limits = 0.05,
					]
					\addplot[dashed, mark=none]{x};
					\addplot table[x = P, y = S]{data/jacobi/speedup.csv};
				\end{axis}
			\end{tikzpicture}
			\caption{Speedup obtained for each number of processors}
			\label{fig:jacobi-speedup}
		\end{subfigure}
	\caption{Comparison between speedup and elapsed time by number of processors in the Jacobi solution}
	\end{figure}
\end{questionenum}

As it can bee seen in the \autoref{fig:jacobi-speedup} the speedup increases and then it remains nearly constant. This is due to the overhead caused by \texttt{OpenMP} as the number of processors increases. If the data is divided by many processors there's more time spend during the synchronization than computing the value and that's why the speedup is not increasing anymore.

\section{OpenMP parallelization and the execution analysis: \emph{Gauss-Seidel}}
\begin{questionenum}
	\question{Include the relevant portions of the parallel code that implements the \emph{Gauss-Seidel} solver, commenting how you implemented the synchronization between threads.}

	\begin{center}
		\begin{minipage}{0.8\textwidth}
			\begin{lstlisting}[language=C, title=\texttt{solver-omp-gauss.c}]
double relax_gauss (double *u, unsigned sizex, unsigned sizey)
{
	int howmany = omp_get_max_threads();
	int numblocks = howmany;
	int blocksfinished[numblocks];
	for(int i =0; i < numblocks; ++i) blocksfinished[i]=-1;
	double unew, diff, sum=0.0;

	#pragma omp parallel for reduction(+:sum) private(diff,unew)
	for (int blockid = 0; blockid < numblocks; ++blockid) {
		for (int blockidcol = 0; blockidcol < numblocks; ++blockidcol){
			if (blockid > 0) {
				// Added block waiting
				while( blocksfinished[blockid-1] < blockidcol ) {
				#pragma omp flush(blocksfinished)
			}
		}
		int i_start = lowerb(blockid, numblocks, sizex);
		int i_end = upperb(blockid, numblocks, sizex);
		int j_start = lowerb(blockidcol,numblocks, sizey);
		int j_end = upperb(blockidcol, numblocks,sizey);
		for (int i=max(1, i_start); i<= min(sizex-2, i_end); i++) {
			for (int j=max(1, j_start); j<= min(sizey-2, j_end); j++) {
				unew = 0.25 * (
					u[ i*sizey 		+ (j-1) ]+  // left
					u[ i*sizey		+ (j+1) ]+  // right
					u[ (i-1)*sizey	+ j     ]+  // top
					u[ (i+1)*sizey	+ j     ]); // bottom
				diff = unew - u[i*sizey+ j];
				sum += diff * diff;
				u[i*sizey+j]=unew;
				}
			}

			// Finish block
			blocksfinished[blockid] = blockidcol;
			#pragma omp flush(blocksfinished)
		}
	}

	return sum;
}
			\end{lstlisting}
		\end{minipage}
	\end{center}

	For the synchronization we use the array \texttt{blocksfinished [row]} in which we store the last column achieved by the row. A row can only start a block if the previous row has already been calculated.

	In order to synchronize the variable \texttt{blocksfinished}  we use the \texttt{flush} sentence. We are also using \texttt{reduction} in order to join the result.

	\question{Include the speed-up (strong-scalability) plot that has been obtained for the different numbers of processors. Reason about the performance that is observed, including captures of Paraver windows to justify your explanations.}

	\begin{figure}[H]
		\begin{subfigure}{0.49\textwidth}
			\centering
			\begin{tikzpicture}
				\begin{axis}[
						xmin = 1, xmax = 12,
						domain = 1:12,
						enlarge x limits = 0.05,
						xlabel = number of processors,
						ylabel = execution time,
						width = \textwidth
					]
					\addplot table[x=P, y=T]{data/gauss/elapsed.csv};
					\addplot[dashed, mark = none]{6.5/x};
				\end{axis}
			\end{tikzpicture}
		\end{subfigure}
		\hfill
		\begin{subfigure}{0.49\textwidth}
			\centering
			\begin{tikzpicture}
				\begin{axis}[
						xmin = 1, xmax = 12,
						domain = 1:12,
						enlarge x limits = 0.05,
						xlabel = number of processors,
						ylabel = speedup,
						width = \textwidth
					]
					\addplot table[x=P, y=S] {data/gauss/speedup.csv};
					\addplot[dashed, mark=none]{x};
				\end{axis}
			\end{tikzpicture}
		\end{subfigure}
	\end{figure}

	We can see that the synchronizations costs are more than linear. This is due to the number of blocks which is quadratic in the number of threads and a flush is need in each region.

	\question{Explain how did you obtain the optimum value for the ration computation/synchronization in the parallelization of this solver for 8 threads.}
\end{questionenum}

	\begin{figure}[H]
		\centering
		\begin{tikzpicture}
			\begin{axis}[
					xmin = 4, xmax = 16,
					ymin = 0, ymax = 7,
					xlabel = Number of blocks,
					ylabel = Time,
					enlarge x limits = 0.05,
				]
				\addplot table[x=N, y=T]{data/gauss/optimum.csv};
			\end{axis}
		\end{tikzpicture}
	\end{figure}

We can see that the optimum value is 8, which mean 8 rows with 8 columns each. With a lower number there are threads with no job and with a higher value we are increasing the synchronization cost.

\end{document}


\section{Divine Enhancement}\label{prayer:divineEnhancement}
\textbf{Cost:} 500 CP\\
\textbf{Requirements:} Disciple of a God, 6 Piety Points \\
\textbf{Active, Prayer, Repeatable, Source(100 Gold)}\\
You pray for 8 AP, and all creatures of your choice in a range of \passus{10} around you, gain one of the following benefits of your choice:
\begin{itemize}
	\item +1d4 on every attack and defense roll for the next 15 minutes
	\item Immunity to the frightened condition for the next hour
	\item +1d4 on their next stat roll, or until one hour has passed
	\item +1 armor defense against all damage types for the next hour
\end{itemize}

These effects don't stack, so for example a creature can't benefit from +2d4 on their next stat roll from Divine Enhancement.\\

Level Progression:\\
\\
II: 1,000 CP, 9 Piety Points, you can apply two effects per prayer\\
III: 2,500 CP, 15 Piety Points, you can apply three effects per prayer\\
IV: 5,000 CP, 24 Piety Points, you can apply four effects per prayer\\
V: 10,000 CP, 39 Piety Points, you can apply five effects per prayer\\


\documentclass{article}

\usepackage{fancyhdr}
\usepackage{extramarks}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usepackage{physics}
\usepackage[plain]{algorithm}
\usepackage{algpseudocode}

\usetikzlibrary{automata,positioning}

%
% Basic Document Settings
%

\topmargin=-0.45in
\evensidemargin=0in
\oddsidemargin=0in
\textwidth=6.5in
\textheight=9.0in
\headsep=0.25in

\linespread{1.1}

\pagestyle{fancy}
\lhead{\hmwkAuthorName}
\chead{\hmwkClass\ (\hmwkClassInstructor\ \hmwkClassTime): \hmwkTitle}
\rhead{\firstxmark}
\lfoot{\lastxmark}
\cfoot{\thepage}

\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

\setlength\parindent{0pt}

%
% Create Problem Sections
%

\newcommand{\enterProblemHeader}[1]{
    \nobreak\extramarks{}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
}

\newcommand{\exitProblemHeader}[1]{
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \stepcounter{#1}
    \nobreak\extramarks{Problem \arabic{#1}}{}\nobreak{}
}

\setcounter{secnumdepth}{0}
\newcounter{partCounter}
\newcounter{homeworkProblemCounter}
\setcounter{homeworkProblemCounter}{1}
\nobreak\extramarks{Problem \arabic{homeworkProblemCounter}}{}\nobreak{}

%
% Homework Problem Environment
%
% This environment takes an optional argument. When given, it will adjust the
% problem counter. This is useful for when the problems given for your
% assignment aren't sequential. See the last 3 problems of this template for an
% example.
%
\newenvironment{homeworkProblem}[1][-1]{
    \ifnum#1>0
        \setcounter{homeworkProblemCounter}{#1}
    \fi
    \section{Problem \arabic{homeworkProblemCounter}}
    \setcounter{partCounter}{1}
    \enterProblemHeader{homeworkProblemCounter}
}{
    \exitProblemHeader{homeworkProblemCounter}
}

%
% Homework Details
%   - Title
%   - Due date
%   - Class
%   - Section/Time
%   - Instructor
%   - Author
%

\newcommand{\hmwkTitle}{Homework\ \#2}
\newcommand{\hmwkDueDate}{February 12, 2014}
\newcommand{\hmwkClass}{Calculus}
\newcommand{\hmwkClassTime}{}
\newcommand{\hmwkClassInstructor}{Professor Isaac Newton}
\newcommand{\hmwkAuthorName}{\textbf{Aditya Vijaykumar}}

%
% Title Page
%

\title{
    %\vspace{2in}
    \textmd{\textbf{\hmwkClass:\ \hmwkTitle}}\\
    \normalsize\vspace{0.1in}\small{\hmwkDueDate\ }\\
%    \vspace{3in}
}

\author{\hmwkAuthorName}
\date{}

\renewcommand{\part}[1]{\textbf{\large Part \Alph{partCounter}}\stepcounter{partCounter}\\}

%
% Various Helper Commands
%

% Useful for algorithms
\newcommand{\alg}[1]{\textsc{\bfseries \footnotesize #1}}

% For derivatives
\newcommand{\deriv}[1]{\frac{\mathrm{d}}{\mathrm{d}x} (#1)}

% For partial derivatives
\newcommand{\pderiv}[2]{\frac{\partial}{\partial #1} (#2)}

% Integral dx
\newcommand{\dx}{\mathrm{d}x}

% Alias for the Solution section header
\newcommand{\solution}{\textbf{\large Solution}}

% Probability commands: Expectation, Variance, Covariance, Bias
\newcommand{\E}{\mathrm{E}}
\newcommand{\Var}{\mathrm{Var}}
\newcommand{\Cov}{\mathrm{Cov}}
\newcommand{\Bias}{\mathrm{Bias}}

\begin{document}

\maketitle

%\pagebreak

\begin{homeworkProblem}
    Give an appropriate positive constant \(c\) such that \(f(n) \leq c \cdot
    g(n)\) for all \(n > 1\).

    \begin{enumerate}
        \item \(f(n) = n^2 + n + 1\), \(g(n) = 2n^3\)
        \item \(f(n) = n\sqrt{n} + n^2\), \(g(n) = n^2\)
        \item \(f(n) = n^2 - n + 1\), \(g(n) = n^2 / 2\)
    \end{enumerate}

    \textbf{Solution}

    We solve each solution algebraically to determine a possible constant
    \(c\).
    \\

    \textbf{Part One}

    \[
        \begin{split}
            n^2 + n + 1 &=
            \\
            &\leq n^2 + n^2 + n^2
            \\
            &= 3n^2
            \\
            &\leq c \cdot 2n^3
        \end{split}
    \]

    Thus a valid \(c\) could be when \(c = 2\).
    \\

    \textbf{Part Two}

    \[
        \begin{split}
            n^2 + n\sqrt{n} &=
            \\
            &= n^2 + n^{3/2}
            \\
            &\leq n^2 + n^{4/2}
            \\
            &= n^2 + n^2
            \\
            &= 2n^2
            \\
            &\leq c \cdot n^2
        \end{split}
    \]

    Thus a valid \(c\) is \(c = 2\).
    \\

    \textbf{Part Three}

    \[
        \begin{split}
            n^2 - n + 1 &=
            \\
            &\leq n^2
            \\
            &\leq c \cdot n^2/2
        \end{split}
    \]

    Thus a valid \(c\) is \(c = 2\).

\end{homeworkProblem}

\pagebreak

\begin{homeworkProblem}
    Let \(\Sigma = \{0, 1\}\). Construct a DFA \(A\) that recognizes the
    language that consists of all binary numbers that can be divided by 5.
    \\

    Let the state \(q_k\) indicate the remainder of \(k\) divided by 5. For
    example, the remainder of 2 would correlate to state \(q_2\) because \(7
    \mod 5 = 2\).

    \begin{figure}[h]
        \centering
        \begin{tikzpicture}[shorten >=1pt,node distance=2cm,on grid,auto]
            \node[state, accepting, initial] (q_0)   {$q_0$};
            \node[state] (q_1) [right=of q_0] {$q_1$};
            \node[state] (q_2) [right=of q_1] {$q_2$};
            \node[state] (q_3) [right=of q_2] {$q_3$};
            \node[state] (q_4) [right=of q_3] {$q_4$};
            \path[->]
                (q_0)
                    edge [loop above] node {0} (q_0)
                    edge node {1} (q_1)
                (q_1)
                    edge node {0} (q_2)
                    edge [bend right=-30] node {1} (q_3)
                (q_2)
                    edge [bend left] node {1} (q_0)
                    edge [bend right=-30] node {0} (q_4)
                (q_3)
                    edge node {1} (q_2)
                    edge [bend left] node {0} (q_1)
                (q_4)
                    edge node {0} (q_3)
                    edge [loop below] node {1} (q_4);
        \end{tikzpicture}
        \caption{DFA, \(A\), this is really beautiful, ya know?}
        \label{fig:multiple5}
    \end{figure}

    \textbf{Justification}
    \\

    Take a given binary number, \(x\). Since there are only two inputs to our
    state machine, \(x\) can either become \(x0\) or \(x1\). When a 0 comes
    into the state machine, it is the same as taking the binary number and
    multiplying it by two. When a 1 comes into the machine, it is the same as
    multipying by two and adding one.
    \\

    Using this knowledge, we can construct a transition table that tell us
    where to go:

    \begin{table}[ht]
        \centering
        \begin{tabular}{c || c | c | c | c | c}
            & \(x \mod 5 = 0\)
            & \(x \mod 5 = 1\)
            & \(x \mod 5 = 2\)
            & \(x \mod 5 = 3\)
            & \(x \mod 5 = 4\)
            \\
            \hline
            \(x0\) & 0 & 2 & 4 & 1 & 3 \\
            \(x1\) & 1 & 3 & 0 & 2 & 4 \\
        \end{tabular}
    \end{table}

    Therefore on state \(q_0\) or (\(x \mod 5 = 0\)), a transition line should
    go to state \(q_0\) for the input 0 and a line should go to state \(q_1\)
    for input 1. Continuing this gives us the Figure~\ref{fig:multiple5}.
\end{homeworkProblem}

\begin{homeworkProblem}
    Write part of \alg{Quick-Sort($list, start, end$)}

    \begin{algorithm}[]
        \begin{algorithmic}[1]
            \Function{Quick-Sort}{$list, start, end$}
                \If{$start \geq end$}
                    \State{} \Return{}
                \EndIf{}
                \State{} $mid \gets \Call{Partition}{list, start, end}$
                \State{} \Call{Quick-Sort}{$list, start, mid - 1$}
                \State{} \Call{Quick-Sort}{$list, mid + 1, end$}
            \EndFunction{}
        \end{algorithmic}
        \caption{Start of QuickSort}
    \end{algorithm}
\end{homeworkProblem}

\pagebreak

\begin{homeworkProblem}
    Suppose we would like to fit a straight line through the origin, i.e.,
    \(Y_i = \beta_1 x_i + e_i\) with \(i = 1, \ldots, n\), \(\E [e_i] = 0\),
    and \(\Var [e_i] = \sigma^2_e\) and \(\Cov[e_i, e_j] = 0, \forall i \neq
    j\).
    \\

    \part

    Find the least squares esimator for \(\hat{\beta_1}\) for the slope
    \(\beta_1\).
    \\

    \solution

    To find the least squares estimator, we should minimize our Residual Sum
    of Squares, RSS:

    \[
        \begin{split}
            RSS &= \sum_{i = 1}^{n} {(Y_i - \hat{Y_i})}^2
            \\
            &= \sum_{i = 1}^{n} {(Y_i - \hat{\beta_1} x_i)}^2
        \end{split}
    \]

    By taking the partial derivative in respect to \(\hat{\beta_1}\), we get:

    \[
        \pderiv{
            \hat{\beta_1}
        }{RSS}
        = -2 \sum_{i = 1}^{n} {x_i (Y_i - \hat{\beta_1} x_i)}
        = 0
    \]

    This gives us:

    \[
        \begin{split}
            \sum_{i = 1}^{n} {x_i (Y_i - \hat{\beta_1} x_i)}
            &= \sum_{i = 1}^{n} {x_i Y_i} - \sum_{i = 1}^{n} \hat{\beta_1} x_i^2
            \\
            &= \sum_{i = 1}^{n} {x_i Y_i} - \hat{\beta_1}\sum_{i = 1}^{n} x_i^2
        \end{split}
    \]

    Solving for \(\hat{\beta_1}\) gives the final estimator for \(\beta_1\):

    \[
        \begin{split}
            \hat{\beta_1}
            &= \frac{
                \sum {x_i Y_i}
            }{
                \sum x_i^2
            }
        \end{split}
    \]

    \pagebreak

    \part

    Calculate the bias and the variance for the estimated slope
    \(\hat{\beta_1}\).
    \\

    \solution

    For the bias, we need to calculate the expected value
    \(\E[\hat{\beta_1}]\):

    \[
        \begin{split}
            \E[\hat{\beta_1}]
            &= \E \left[ \frac{
                \sum {x_i Y_i}
            }{
                \sum x_i^2
            }\right]
            \\
            &= \frac{
                \sum {x_i \E[Y_i]}
            }{
                \sum x_i^2
            }
            \\
            &= \frac{
                \sum {x_i (\beta_1 x_i)}
            }{
                \sum x_i^2
            }
            \\
            &= \frac{
                \sum {x_i^2 \beta_1}
            }{
                \sum x_i^2
            }
            \\
            &= \beta_1 \frac{
                \sum {x_i^2 \beta_1}
            }{
                \sum x_i^2
            }
            \\
            &= \beta_1
        \end{split}
    \]

    Thus since our estimator's expected value is \(\beta_1\), we can conclude
    that the bias of our estimator is 0.
    \\

    For the variance:

    \[
        \begin{split}
            \Var[\hat{\beta_1}]
            &= \Var \left[ \frac{
                \sum {x_i Y_i}
            }{
                \sum x_i^2
            }\right]
            \\
            &=
            \frac{
                \sum {x_i^2}
            }{
                \sum x_i^2 \sum x_i^2
            } \Var[Y_i]
            \\
            &=
            \frac{
                \sum {x_i^2}
            }{
                \sum x_i^2 \sum x_i^2
            } \Var[Y_i]
            \\
            &=
            \frac{
                1
            }{
                \sum x_i^2
            } \Var[Y_i]
            \\
            &=
            \frac{
                1
            }{
                \sum x_i^2
            } \sigma^2
            \\
            &=
            \frac{
                \sigma^2
            }{
                \sum x_i^2
            }
        \end{split}
    \]

\end{homeworkProblem}

\pagebreak

\begin{homeworkProblem}
    Prove a polynomial of degree \(k\), \(a_kn^k + a_{k - 1}n^{k - 1} + \hdots
    + a_1n^1 + a_0n^0\) is a member of \(\Theta(n^k)\) where \(a_k \hdots a_0\)
    are nonnegative constants.

    \begin{proof}
        To prove that \(a_kn^k + a_{k - 1}n^{k - 1} + \hdots + a_1n^1 +
        a_0n^0\), we must show the following:

        \[
            \exists c_1 \exists c_2 \forall n \geq n_0,\ {c_1 \cdot g(n) \leq
            f(n) \leq c_2 \cdot g(n)}
        \]

        For the first inequality, it is easy to see that it holds because no
        matter what the constants are, \(n^k \leq a_kn^k + a_{k - 1}n^{k - 1} +
        \hdots + a_1n^1 + a_0n^0\) even if \(c_1 = 1\) and \(n_0 = 1\).  This
        is because \(n^k \leq c_1 \cdot a_kn^k\) for any nonnegative constant,
        \(c_1\) and \(a_k\).
        \\

        Taking the second inequality, we prove it in the following way.
        By summation, \(\sum\limits_{i=0}^k a_i\) will give us a new constant,
        \(A\). By taking this value of \(A\), we can then do the following:

        \[
            \begin{split}
                a_kn^k + a_{k - 1}n^{k - 1} + \hdots + a_1n^1 + a_0n^0 &=
                \\
                &\leq (a_k + a_{k - 1} \hdots a_1 + a_0) \cdot n^k
                \\
                &= A \cdot n^k
                \\
                &\leq c_2 \cdot n^k
            \end{split}
        \]

        where \(n_0 = 1\) and \(c_2 = A\). \(c_2\) is just a constant. Thus the
        proof is complete.
    \end{proof}
\end{homeworkProblem}

\pagebreak

%
% Non sequential homework problems
%

% Jump to problem 18
\begin{homeworkProblem}[18]
    Evaluate \(\sum_{k=1}^{5} k^2\) and \(\sum_{k=1}^{5} (k - 1)^2\).
\end{homeworkProblem}

% Continue counting to 19
\begin{homeworkProblem}
    Find the derivative of \(f(x) = x^4 + 3x^2 - 2\)
\end{homeworkProblem}

% Go back to where we left off
\begin{homeworkProblem}[6]
    Evaluate the integrals
    \(\int_0^1 (1 - x^2) \dx\)
    and
    \(\int_1^{\infty} \frac{1}{x^2} \dx\).
\end{homeworkProblem}

\end{document}