% Copyright 2019 by Renée Ahrens, Olof Frahm, Jens Kluttig, Matthias Schulz, Stephan Schuster
% Copyright 2019 by Till Tantau
% Copyright 2019 by Jannis Pohlmann
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\section{Introduction to Algorithmic Graph Drawing}
\label{section-intro-gd}

\emph{by Till Tantau}

\ifluatex
\else
    This section of the manual can only be typeset using Lua\TeX.
    \expandafter\endinput
\fi

\subsection{What Is Algorithmic Graph Drawing?}

\emph{Algorithmic graph drawing} (or just \emph{graph drawing} in the
following) is the process of computing algorithmically where the nodes of a
graph are positioned on a page so that the graph ``looks nice''. The idea is
that you, as human (or you, as a machine, if you happen to be a machine and
happen to be reading this document) just specify which nodes are present in a
graph and which edges are present. Additionally, you may add some ``hints''
like ``this node should be near the center'' or ``this edge is pretty
important''. You do \emph{not} specify where, exactly, the nodes and edges
should be. This is something you leave to a \emph{graph drawing algorithm}. The
algorithm gets your description of the graph as an input and then decides where
the nodes should go on the page.
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz \graph [binary tree layout, level distance=5mm] {
  4 -- {
    3 -- 0 -- 1[second],
    10 -- {
      8 -- {
        6 -- {5,7},
        9
  } } }
};
\end{codeexample}

\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing,quotes}
\usegdlibrary{force}}]
\tikz \graph [spring layout,
  edge quotes mid,
  edges={nodes={font=\scriptsize, fill=white, sloped, inner sep=1pt}}]
{
  1 ->["Das"] 2 ->["ist"] 3 ->["das"] 4 ->["Haus"]
  2 ->["vom" near start] 5 ->["Ni"] 4 ->["ko" near start]
  1 ->["laus", orient=right] 5;
};
\end{codeexample}

Naturally, graph drawing is a bit of a (black?) art. There is no ``perfect''
way of drawing a graph, rather, depending on the circumstances there are
several different ways of drawing the same graph and often it will just depend
on the aesthetic sense of the reader which layout he or she would prefer. For
this reason, there are a huge number of graph drawing algorithms ``out there''
and there are scientific conference devoted to such algorithms, where each year
dozens of new algorithms are proposed.

Unlike the rest of \pgfname\ and \tikzname, which is implemented purely in
\TeX, the graph drawing algorithms are simply too complex to be implemented
directly in \TeX. Instead, the programming language Lua is used by the
|graphdrawing| library -- a programming language that has been integrated into
recent versions of \TeX. This means that (a) as a user of the graph drawing
engine you run \TeX\ on your documents in the usual way, no external programs
are called since Lua is already integrated into \TeX, and (b) it is pretty easy
to implement new graph drawing algorithms for \tikzname\ since Lua can be used
and no \TeX\ programming knowledge is needed.

\subsection{Using the Graph Drawing System}

``Users'' of the graph drawing engine can invoke the graph drawing algorithms
often by just adding a single option to their picture. Here is a typical
example, where the |layered layout| option tells \tikzname\ that the graph
should be drawn (``should be laid out'') using a so-called ``layered graph
drawing algorithm'' (what these are will be explained later):
%
\begin{codeexample}[preamble={\usetikzlibrary{arrows.meta,graphs,graphdrawing}
\usegdlibrary{layered}}]
\tikz [>={Stealth[round,sep]}]
  \graph [layered layout, components go right top aligned, nodes=draw, edges=rounded corners]
  {
    first root -> {1 -> {2, 3, 7} -> {4, 5}, 6 }, 4 -- 5;
    second root -> x -> {a -> {u,v}, b, c -> d -> {w,z} };
    third root -> child -> grandchild -> youngster -> third root;
  };
\end{codeexample}
%
Here is another example, where a different layout method is used that is more
appropriate for trees:
%
\begin{codeexample}[preamble={\usetikzlibrary{graphdrawing}
\usegdlibrary{trees}}]
\tikz [grow'=up, binary tree layout, nodes={circle,draw}]
  \node {1}
  child { node {2}
    child { node {3} }
    child { node {4}
      child { node {5} }
      child { node {6} }
    }
  }
  child { node {7}
    child { node {8}
      child[missing]
      child { node {9} }
    }
  };
\end{codeexample}
%
A final example, this time using a ``spring electrical layout'' (whatever that
might be\dots):
%
\begin{codeexample}[
    preamble={\usetikzlibrary{decorations.pathmorphing,graphdrawing}
\usegdlibrary{force}}]
\tikz [spring electrical layout, node distance=1.3cm,
       every edge/.style={
         decoration={coil, aspect=-.5, post length=1mm,
                     segment length=1mm, pre length=2mm},
         decorate, draw}]
{
  \foreach \i in {1,...,6}
    \node (node \i) [fill=blue!50, text=white, circle] {\i};

  \draw (node 1) edge (node 2)
        (node 2) edge (node 3)
                 edge (node 4)
        (node 3) edge (node 4)
                 edge (node 5)
                 edge (node 6);
}
\end{codeexample}
%
In all of the example, the positions of the nodes have only been computed
\emph{after} all nodes have been created and the edges have been specified. For
instance, in the last example, without the option |spring electrical layout|,
all of the nodes would have been placed on top of each other.

\subsection{Extending the Graph Drawing System}

The graph drawing engine is also intended to make is (relatively) easy to
implement new graph drawing algorithms. These algorithms can either be
implemented in the Lua programming language (which is \emph{much} easier to
program than \TeX\ itself) or in C/C++ (but at a great cost regarding
portability). The Lua code for a graph drawing algorithm gets an
object-oriented model of the input graph as an input and must just compute the
desired new positions of the nodes. The complete handling of passing options
and configurations back-and-forth between the different \tikzname\ and
\pgfname\ layers is handled by the graph drawing engine.

As a caveat, the graph drawing engine comes with a library of functions and
methods that simplify the writing of new graph drawing algorithms. As a typical
example, when you implement a graph drawing algorithm for trees, you typically
require that your input is a tree; but you can bet that users will feed all
sorts of graphs to your algorithm, including disjoint unions of cliques. The
graph drawing engine offers you to say that a precondition to running your
algorithm is that the graph is a |tree| and instead of the original graph your
algorithm will be provided with a spanning tree of the graph on which it can
work. There are numerous further automatic pre- and postprocessing steps that
include orienting, anchoring, and packing of components, to name a few.

The bottom line is that the graph drawing engine makes it easy
to try out new graph drawing algorithms for medium sized graphs (up
to a few hundred nodes) in Lua. For larger graphs, C/C++ code must be
used.

\subsection{The Layers of the Graph Drawing System}
\label{section-gd-layers}

Even though the graph drawing system presented in the following sections was
developed as part of \pgfname, it can be used independently of \pgfname\ and
\tikzname: It was (re)designed so that it can be used by arbitrary programs as
long as they are able to run Lua. To achieve this, the graph drawing system
consists of three layers:
%
\begin{enumerate}
    \item At the ``bottom'' we have the \emph{algorithmic layer}. This layer,
        written in Lua, contains all graph drawing algorithms. Interestingly,
        options must also be declared on this layer, so an algorithm together
        with all options it uses can and must be specified entirely on this
        layer. If you intend to implement a new graph drawing algorithm, you
        will only be interested in the functionality of this layer.

        Algorithm ``communicate'' with the graph drawing system through a
        well-defined interface, encapsulated in the class
        |InterfaceToAlgorithms|.
    \item At the ``top'' we have the \emph{display layer}. This layer is not
        actually part of the graph drawing system. Rather, it is a piece of
        software that ``displays'' graphs and \tikzname\ is just one example of
        such a software. Another example might be a graph editor that uses the
        graph drawing system to lay out the graph it displays. Yet another
        example might be a command line tool for drawing graphs described in a
        file. Finally, you may also wish to use the graph drawing system as a
        simple subroutine for rendering graphs produced in a larger program.

        Since the different possible instantiations of the display layer are
        quite heterogeneous, all display layers must communicate with the graph
        drawing system through a special interface, encapsulated in the class
        |InterfaceToDisplay|.

        The main job of this class is to provide a set of methods for
        specifying that a graph has certain nodes and edges and that certain
        options have been set for them. However, this interface also allows you
        to query all options that have been declared by algorithms, including
        their documentation. This way, an editor or a command line tool can
        display a list of all graph drawing algorithms and how they can be
        configured.
    \item The algorithm layer and the display layer are ``bound together''
        through the \emph{binding layer}. Most of the bookkeeping concerning
        the to-be-drawn graphs is done by the graph drawing system
        independently of which algorithm is used and also independently of
        which display layer is used, but some things are still specific to each
        display layer. For instance, some algorithms may create new nodes and
        the algorithms may then need to know how large these nodes will be. For
        this, the display layer must be ``queried'' during a run of the
        algorithm -- and it is the job of the binding layer to achieve this
        callback.

        As a rule, the binding layer implements the ``backward'' communication
        from the graph drawing system back to the display layer, while the
        display layer's interface class provides only functions that are called
        from the display layer but which will not ``talk back''.
\end{enumerate}

All of the files concerned with graph drawing reside in the |graphdrawing|
subdirectory of |generic/pgf|.

\subsection{Organisation of the Graph Drawing Documentation}

The documentation of the graph drawing engine is structured as follows:
%
\begin{enumerate}
    \item Following this overview section, the next section documents the graph
        drawing engine from ``the \tikzname\ user's point of view''. No
        knowledge of Lua or algorithmic graph drawing is needed for this
        section, everyone who intends to use algorithmic graph drawing in
        \tikzname\ may be interested in reading it.
    \item You will normally only use \tikzname's keys and commands in order to
        use the graph drawing system, but, internally, these keys call more
        basic \pgfname\ commands that do the ``hard work'' of binding the world
        of \TeX\ boxes and macros to the object-oriented world of Lua.
        Section~\ref{section-gd-pgf} explains how this works and which commands
        are available for authors of packages that directly need to use the
        graph drawing system inside \pgfname, avoiding the overhead incurred by
        \tikzname.

        Most readers can safely skip this section.
    \item The next sections detail which graph drawing algorithms are currently
        implemented as part of the \tikzname\ distribution, see
        Sections~\ref{section-first-graphdrawing-library-in-manual}
        to~\ref{section-last-graphdrawing-library-in-manual}.
    \item Section~\ref{section-gd-algorithm-layer} is addressed at readers who
        wish to implement their own graph drawing algorithms. For this,
        \emph{no knowledge at all} of \TeX\ programming is needed. The section
        explains the graph model used in Lua, the available libraries, the
        graph drawing pipeline, and everything else that is part of the Lua
        side of the engine.
    \item Section~\ref{section-gd-display-layer} details the display layer of
        the graph drawing system. You should read this section if you wish to
        implement a new display system (that is, a non-\TeX-based program) that
        intends to use the graph drawing system.
    \item Section~\ref{section-gd-binding-layer} explains how binding layers
        can be implemented. This section, too, is of interest only to readers
        who wish to write new display systems.
\end{enumerate}

\subsection{Acknowledgements}

Graph drawing in \tikzname\ began as a student's project under my supervision.
Ren\'ee Ahrens, Olof-Joachim Frahm, Jens Kluttig, Matthias Schulz, and Stephan
Schuster wrote the first prototype of a graph drawing system inside \tikzname\
that uses Lua\TeX\ for the implementation of graph drawing algorithms.

This first, early version was greatly extended on the algorithmic side by
Jannis Pohlmann who wrote his Diploma thesis on graph drawing under my
supervision. He implemented, in particular, the Sugiyama method
(|layered layout|) and force based algorithms. Also, he rewrote some of the
code of the prototype.

At some point it became apparent that the first implementation had a number of
deficiencies, both concerning the structure, the interfaces, and (in
particular) the performance. Because of this, I rewrote the code of the graph
drawing system, both on the \TeX\ side and on the Lua side in its current form.
However, I would like to stress that without the work of the people mentioned
above graph drawing in \tikzname\ would not exist.

The documentation was written almost entirely by myself, though I did copy some
paragraphs from Jannis's Diploma thesis, which I can highly recommend everyone
to read.

In the future, I hope that other people will contribute algorithms, which will
be available as libraries.


% The LaTeX below is mostly computer-generated (for reasons of speed); don't expect it to be very readable. Sorry.

\documentclass[paper=a4, fontsize=12pt]{scrartcl}%
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{mathrsfs}
\usepackage{sectsty}
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{framed}
\usepackage{ifthen}
\usepackage{lastpage}
\usepackage[headsepline,footsepline,manualmark]{scrlayer-scrpage}
\usepackage[height=10in,a4paper,hmargin={1in,0.8in}]{geometry}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{tikz}
\usepackage{verbatim}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}%
\setcounter{MaxMatrixCols}{30}
%TCIDATA{OutputFilter=latex2.dll}
%TCIDATA{Version=5.50.0.2960}
%TCIDATA{LastRevised=Tuesday, February 12, 2019 21:04:52}
%TCIDATA{<META NAME="GraphicsSave" CONTENT="32">}
%TCIDATA{<META NAME="SaveForMode" CONTENT="1">}
%TCIDATA{BibliographyScheme=Manual}
%BeginMSIPreambleData
\providecommand{\U}[1]{\protect\rule{.1in}{.1in}}
%EndMSIPreambleData
\allsectionsfont{\centering \normalfont\scshape}
\setlength\parindent{20pt}
\newcommand{\CC}{\mathbb{C}}
\newcommand{\RR}{\mathbb{R}}
\newcommand{\QQ}{\mathbb{Q}}
\newcommand{\NN}{\mathbb{N}}
\newcommand{\PP}{\mathbb{P}}
\newcommand{\Z}[1]{\mathbb{Z}/#1\mathbb{Z}}
\newcommand{\ZZ}{\mathbb{Z}}
\newcommand{\id}{\operatorname{id}}
\newcommand{\lcm}{\operatorname{lcm}}
\newcommand{\set}[1]{\left\{ #1 \right\}}
\newcommand{\abs}[1]{\left| #1 \right|}
\newcommand{\tup}[1]{\left( #1 \right)}
\newcommand{\ive}[1]{\left[ #1 \right]}
\newcommand{\floor}[1]{\left\lfloor #1 \right\rfloor}
\newcommand{\underbrack}[2]{\underbrace{#1}_{\substack{#2}}}
\newcommand{\powset}[2][]{\ifthenelse{\equal{#2}{}}{\mathcal{P}\left(#1\right)}{\mathcal{P}_{#1}\left(#2\right)}}
\newcommand{\horrule}[1]{\rule{\linewidth}{#1}}
\newcommand{\nnn}{\nonumber\\}
\let\sumnonlimits\sum
\let\prodnonlimits\prod
\let\cupnonlimits\bigcup
\let\capnonlimits\bigcap
\renewcommand{\sum}{\sumnonlimits\limits}
\renewcommand{\prod}{\prodnonlimits\limits}
\renewcommand{\bigcup}{\cupnonlimits\limits}
\renewcommand{\bigcap}{\capnonlimits\limits}
\newtheoremstyle{plainsl}
{8pt plus 2pt minus 4pt}
{8pt plus 2pt minus 4pt}
{\slshape}
{0pt}
{\bfseries}
{.}
{5pt plus 1pt minus 1pt}
{}
\theoremstyle{plainsl}
\newtheorem{theorem}{Theorem}[section]
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{conjecture}[theorem]{Conjecture}
\theoremstyle{definition}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{example}[theorem]{Example}
\newtheorem{exercise}[theorem]{Exercise}
\newtheorem{examples}[theorem]{Examples}
\newtheorem{algorithm}[theorem]{Algorithm}
\newtheorem{question}[theorem]{Question}
\theoremstyle{remark}
\newtheorem{remark}[theorem]{Remark}
\newenvironment{statement}{\begin{quote}}{\end{quote}}
\newenvironment{fineprint}{\begin{small}}{\end{small}}
\iffalse
\newenvironment{proof}[1][Proof]{\noindent\textbf{#1.} }{\ \rule{0.5em}{0.5em}}
\newenvironment{question}[1][Question]{\noindent\textbf{#1.} }{\ \rule{0.5em}{0.5em}}
\fi
\newcommand{\myname}{Darij Grinberg}
\newcommand{\myid}{00000000}
\newcommand{\mymail}{dgrinber@umn.edu}
\newcommand{\psetnumber}{1}
\ihead{Solutions to homework set \#\psetnumber}
\ohead{page \thepage\ of \pageref{LastPage}}
\ifoot{\myname, \myid}
\ofoot{\mymail}
\begin{document}

\title{ \normalfont {\normalsize \textsc{University of Minnesota, School of
Mathematics} }\\[25pt] \rule{\linewidth}{0.5pt} \\[0.4cm] {\huge Math 4281: Introduction to Modern Algebra, }\\Spring 2019: Homework 1\\\rule{\linewidth}{2pt} \\[0.5cm] }
\author{Darij Grinberg}
\maketitle

%----------------------------------------------------------------------------------------
%	EXERCISE 1
%----------------------------------------------------------------------------------------
\rule{0pt}{0.3pt} \\[0.4cm]

\section{Exercise 1: Mutual divisibility is rare}

\subsection{Problem}

Let $a$ and $b$ be two integers such that $a \mid b$ and $b \mid a$. Prove
that $\left|  a \right|  = \left|  b \right|  $.

\subsection{Solution}

See \href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class
notes}, where this is Exercise 2.2.2. (The numbering may shift; it is one of
the exercises in the \textquotedblleft Divisibility\textquotedblright\ section.)

%----------------------------------------------------------------------------------------
%	EXERCISE 2
%----------------------------------------------------------------------------------------
\rule{\linewidth}{0.3pt} \\[0.4cm]

\section{Exercise 2: Congruence means equal remainders}

\subsection{Problem}

Let $n$ be a positive integer. Let $u$ and $v$ be two integers. Prove that
$u\equiv v\mod n$ if and only if $u\%n=v\%n$.

\subsection{Solution}

See \href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class
notes}, where this is Exercise 2.6.1. (The numbering may shift; it is one of
the exercises in the \textquotedblleft Division with
remainder\textquotedblright\ section.)

%----------------------------------------------------------------------------------------
%	EXERCISE 2
%----------------------------------------------------------------------------------------
\rule{\linewidth}{0.3pt} \\[0.4cm]

\section{Exercise 3: Even and odd}

\subsection{Problem}

Let $u$ be an integer.

\begin{enumerate}
\item[\textbf{(a)}] Prove that $u$ is even if and only if $u \% 2 = 0$.

\item[\textbf{(b)}] Prove that $u$ is odd if and only if $u \% 2 = 1$.

\item[\textbf{(c)}] Prove that $u$ is even if and only if $u \equiv0 \mod 2$.

\item[\textbf{(d)}] Prove that $u$ is odd if and only if $u \equiv1 \mod 2$.

\item[\textbf{(e)}] Prove that $u$ is odd if and only if $u + 1$ is even.

\item[\textbf{(f)}] Prove that exactly one of the two numbers $u$ and $u + 1$
is even.

\item[\textbf{(g)}] Prove that $u \left(  u+1 \right)  \equiv0 \mod 2$.

\item[\textbf{(h)}] Prove that $u^{2} \equiv-u \equiv u \mod 2$.
\end{enumerate}

\subsection{Solution}

See \href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class
notes}, where this is Exercise 2.7.1 parts \textbf{(a)} to \textbf{(h)}. (The
numbering may shift; it is one of the exercises in the \textquotedblleft Even
and odd numbers\textquotedblright\ section.)

%----------------------------------------------------------------------------------------
%	EXERCISE 4
%----------------------------------------------------------------------------------------
\rule{\linewidth}{0.3pt} \\[0.4cm]

\section{Exercise 4: Factorials 102}

\subsection{Problem}

\begin{enumerate}
\item[\textbf{(a)}] Prove that
\[
\dfrac{1! \cdot2! \cdot\cdots\cdot\left(  2n \right)  !}{n!} = 2^{n}
\cdot\prod_{i=1}^{n} \left(  \left(  2i-1 \right)  ! \right)  ^{2}
\qquad\text{for each } n \in\mathbb{N} .
\]

\item[\textbf{(b)}] Prove that
\[
\sum_{k=0}^{n} \dfrac{1}{k! \cdot\left(  k+2 \right)  } = 1 - \dfrac
{1}{\left(  n+2 \right)  !} \qquad\text{for each } n \in\mathbb{N} .
\]

\end{enumerate}

\subsection{Solution}

We first recall that%
\begin{equation}
n!=n\cdot\left(  n-1\right)  !\qquad\text{for each positive integer }n.
\label{sol.factorials.102.fac-rec}%
\end{equation}
(This was the claim of Exercise 2 \textbf{(a)} on
\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw0s.pdf}{homework set \#0}.)

\vspace{0.809pc}

\textbf{(a)} This is precisely \cite[Exercise 3.5 \textbf{(c)}]{detnotes},
with only a superficial difference (namely, I write \textquotedblleft$\left(
\prod_{i=1}^{n}\left(  \left(  2i-1\right)  !\right)  \right)  ^{2}%
$\textquotedblright\ instead of \textquotedblleft$\prod_{i=1}^{n}\left(
\left(  2i-1\right)  !\right)  ^{2}$\textquotedblright\ in \cite[Exercise 3.5
\textbf{(c)}]{detnotes}, but these two expressions are clearly equivalent). I
give two solutions in \cite[solution to Exercise 3.5 \textbf{(c)}]{detnotes}:
one by manipulation and one by induction. Here I will only show the solution
by manipulation:

Let $n\in\mathbb{N}$. Then, we can group the factors of the product
$1!\cdot2!\cdot\cdots\cdot\left(  2n\right)  !$ into pairs of successive
factors. We thus obtain\footnote{Strictly speaking, we are tacitly using the
fact that each integer between $1$ and $2n$ (inclusive) can be written either
in the form $2i$ or in the form $2i-1$ for some $i\in\left\{  1,2,\ldots
,n\right\}  $, and that this $i$ is unique. The proof of this fact relies on
division with remainder.}%
\begin{align*}
&  1!\cdot2!\cdot\cdots\cdot\left(  2n\right)  !\\
&  =\left(  1!\cdot2!\right)  \cdot\left(  3!\cdot4!\right)  \cdot\cdots
\cdot\left(  \left(  2n-1\right)  !\cdot\left(  2n\right)  !\right)
=\prod_{i=1}^{n}\left(  \left(  2i-1\right)  !\cdot\underbrace{\left(
2i\right)  !}_{\substack{=\left(  2i\right)  \cdot\left(  2i-1\right)
!\\\text{(by \eqref{sol.factorials.102.fac-rec})}}}\right)  \\
&  =\prod_{i=1}^{n}\underbrace{\left(  \left(  2i-1\right)  !\cdot\left(
2i\right)  \cdot\left(  2i-1\right)  !\right)  }_{=\left(  2i\right)
\cdot\left(  \left(  2i-1\right)  !\right)  ^{2}}=\prod_{i=1}^{n}\left(
\left(  2i\right)  \cdot\left(  \left(  2i-1\right)  !\right)  ^{2}\right)  \\
&  =\underbrace{\left(  \prod_{i=1}^{n}\left(  2i\right)  \right)  }%
_{=2^{n}\prod_{i=1}^{n}i}\cdot\prod_{i=1}^{n}\left(  \left(  2i-1\right)
!\right)  ^{2}=2^{n}\underbrace{\left(  \prod_{i=1}^{n}i\right)  }%
_{=1\cdot2\cdot\cdots\cdot n=n!}\cdot\prod_{i=1}^{n}\left(  \left(
2i-1\right)  !\right)  ^{2}=2^{n}n!\cdot\prod_{i=1}^{n}\left(  \left(
2i-1\right)  !\right)  ^{2}.
\end{align*}
Dividing both sides of this equality by $n!$, we find%
\[
\dfrac{1!\cdot2!\cdot\cdots\cdot\left(  2n\right)  !}{n!}=2^{n}\cdot
\prod_{i=1}^{n}\left(  \left(  2i-1\right)  !\right)  ^{2}.
\]
This solves part \textbf{(a)} of the exercise.

\vspace{0.806pc}

\textbf{(b)} Again, the exercise can be proven by induction or by the
telescope principle. Let me show the latter solution. First, I quote the
telescope principle:

\begin{proposition}
\label{prop.sums.telescope}Let $m\in\mathbb{N}$. Let $a_{0},a_{1},\ldots
,a_{m}$ be $m+1$ real numbers. Then,
\[
\sum_{i=1}^{m}\left(  a_{i}-a_{i-1}\right)  =a_{m}-a_{0}.
\]

\end{proposition}

Now, let me solve the exercise. Let $n\in\mathbb{N}$. For each $i\in\left\{
0,1,\ldots,n\right\}  $, we set $a_{i}=\dfrac{-1}{\left(  i+2\right)  !}$.
Thus, $a_{0},a_{1},\ldots,a_{n}$ are $n+1$ real numbers. We state the following:

\begin{statement}
\textit{Claim 1:} For each $i\in\left\{  0,1,\ldots,n\right\}  $, we have%
\[
a_{i}-a_{i-1}=\dfrac{1}{i!\cdot\left(  i+2\right)  }.
\]

\end{statement}

[\textit{Proof of Claim 1:} Let $i\in\left\{  0,1,\ldots,n\right\}  $. Then,
\eqref{sol.factorials.102.fac-rec} (applied to $i+1$ instead of $n$) yields
$\left(  i+1\right)  !=\left(  i+1\right)  \cdot i!$. Also,
\eqref{sol.factorials.102.fac-rec} (applied to $i+2$ instead of $n$) yields
$\left(  i+2\right)  !=\left(  i+2\right)  \cdot\left(  i+1\right)  !$.

The definition of $a_{i}$ yields%
\[
a_{i}=\dfrac{-1}{\left(  i+2\right)  !}=\dfrac{-1}{\left(  i+2\right)
\cdot\left(  i+1\right)  !}\qquad\left(  \text{since }\left(  i+2\right)
!=\left(  i+2\right)  \cdot\left(  i+1\right)  !\right)  .
\]
The definition of $a_{i-1}$ yields%
\[
a_{i-1}=\dfrac{-1}{\left(  \left(  i-1\right)  +2\right)  !}=\dfrac
{-1}{\left(  i+1\right)  !}\qquad\left(  \text{since }\left(  i-1\right)
+2=i+1\right)  .
\]
Subtracting this equality from the previous one, we obtain
\begin{align*}
a_{i}-a_{i-1}  &  =\dfrac{-1}{\left(  i+2\right)  \cdot\left(  i+1\right)
!}-\dfrac{-1}{\left(  i+1\right)  !}=\dfrac{1}{\left(  i+1\right)  !}%
-\dfrac{1}{\left(  i+2\right)  \cdot\left(  i+1\right)  !}=\dfrac{\left(
i+2\right)  -1}{\left(  i+2\right)  \cdot\left(  i+1\right)  !}\\
&  =\dfrac{i+1}{\left(  i+2\right)  \cdot\left(  i+1\right)  !}=\dfrac
{i+1}{\left(  i+2\right)  \cdot\left(  i+1\right)  \cdot i!}\qquad\left(
\text{since }\left(  i+1\right)  !=\left(  i+1\right)  \cdot i!\right) \\
&  =\dfrac{1}{\left(  i+2\right)  \cdot i!}=\dfrac{1}{i!\cdot\left(
i+2\right)  }.
\end{align*}
This proves Claim 1.]

Now, Proposition \ref{prop.sums.telescope} (applied to $m=n$) yields%
\begin{align*}
\sum_{i=1}^{n}\left(  a_{i}-a_{i-1}\right)   &  =\underbrace{a_{n}%
}_{\substack{=\dfrac{-1}{\left(  n+2\right)  !}\\\text{(by the definition of
}a_{n}\text{)}}}-\underbrace{a_{0}}_{\substack{=\dfrac{-1}{\left(  0+2\right)
!}\\\text{(by the definition of }a_{0}\text{)}}}\\
&  =\dfrac{-1}{\left(  n+2\right)  !}-\dfrac{-1}{\left(  0+2\right)
!}=\underbrace{\dfrac{1}{\left(  0+2\right)  !}}_{=\dfrac{1}{2!}=\dfrac{1}{2}%
}-\dfrac{1}{\left(  n+2\right)  !}=\dfrac{1}{2}-\dfrac{1}{\left(  n+2\right)
!}.
\end{align*}
Comparing this with%
\[
\sum_{i=1}^{n}\underbrace{\left(  a_{i}-a_{i-1}\right)  }_{\substack{=\dfrac
{1}{i!\cdot\left(  i+2\right)  }\\\text{(by Claim 1)}}}=\sum_{i=1}^{n}%
\dfrac{1}{i!\cdot\left(  i+2\right)  },
\]
we obtain%
\begin{equation}
\sum_{i=1}^{n}\dfrac{1}{i!\cdot\left(  i+2\right)  }=\dfrac{1}{2}-\dfrac
{1}{\left(  n+2\right)  !}. \label{sol.factorials.102.b.6}%
\end{equation}
But%
\begin{align*}
\sum_{k=0}^{n}\dfrac{1}{k!\cdot\left(  k+2\right)  }  &  =\sum_{i=0}^{n}%
\dfrac{1}{i!\cdot\left(  i+2\right)  }\qquad\left(  \text{here, we have
renamed the summation index }k\text{ as }i\right) \\
&  =\underbrace{\dfrac{1}{0!\cdot\left(  0+2\right)  }}_{=\dfrac{1}{1\cdot
2}=\dfrac{1}{2}}+\underbrace{\sum_{i=1}^{n}\dfrac{1}{i!\cdot\left(
i+2\right)  }}_{\substack{=\dfrac{1}{2}-\dfrac{1}{\left(  n+2\right)
!}\\\text{(by \eqref{sol.factorials.102.b.6})}}}=\underbrace{\dfrac{1}%
{2}+\dfrac{1}{2}}_{=1}-\dfrac{1}{\left(  n+2\right)  !}=1-\dfrac{1}{\left(
n+2\right)  !}.
\end{align*}
This solves part \textbf{(b)} of the exercise.

%----------------------------------------------------------------------------------------
%	EXERCISE 5
%----------------------------------------------------------------------------------------
\rule{\linewidth}{0.3pt} \\[0.4cm]

\section{Exercise 5: Binomial coefficients 102}

\subsection{Problem}

Prove that
\[
\dfrac{\left(  ab \right)  !}{a! \left(  b! \right)  ^{a}} = \prod_{k=1}^{a}
\dbinom{kb-1}{b-1}
\]
for all $a \in\mathbb{N}$ and all positive integers $b$.

\subsection{Solution}

First, let us state an analogue of the telescope principle (Proposition
\ref{prop.sums.telescope}) for products instead of sums:

\begin{proposition}
\label{prop.sums.telescope-prod}Let $m\in\mathbb{N}$. Let $a_{0},a_{1}%
,\ldots,a_{m}$ be $m+1$ nonzero real numbers. Then,
\[
\prod_{i=1}^{m}\dfrac{a_{i}}{a_{i-1}}=\dfrac{a_{m}}{a_{0}}.
\]

\end{proposition}

\begin{proof}
[Proof of Proposition \ref{prop.sums.telescope-prod}.]Take your favorite proof
of Proposition \ref{prop.sums.telescope}, and replace addition by
multiplication, subtraction by division and sums by products. This will yield
a proof of Proposition \ref{prop.sums.telescope-prod}.
\end{proof}

Furthermore, recall the following facts:

\begin{proposition}
\label{prop.sol.binom.102.fac-form}If $n\in\mathbb{N}$ and $k\in\mathbb{N}$
are such that $n\geq k$, then
\[
\dbinom{n}{k}=\dfrac{n!}{k!\left(  n-k\right)  !}.
\]

\end{proposition}

Proposition \ref{prop.sol.binom.102.fac-form} is Exercise 3 \textbf{(a)} on
\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw0s.pdf}{homework set \#0}.

\begin{proposition}
\label{prop.sol.binom.102.absorb}Any $n\in\mathbb{Q}$ and $k\in\mathbb{Q}$
satisfy
\[
k\dbinom{n}{k}=n\dbinom{n-1}{k-1}.
\]

\end{proposition}

Proposition \ref{prop.sol.binom.102.absorb} is Exercise 3 \textbf{(f)} on
\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/hw0s.pdf}{homework set \#0}.

Now, let $a\in\mathbb{N}$, and let $b$ be a positive integer. Thus, $b\neq0$
(since $b$ is positive).

\begin{statement}
\textit{Claim 1:} We have
\[
\dbinom{kb-1}{b-1}=\dfrac{1}{k}\cdot\dfrac{1}{b!}\cdot\dfrac{\left(
kb\right)  !}{\left(  \left(  k-1\right)  b\right)  !}%
\]
for each positive integer $k$.
\end{statement}

[\textit{Proof of Claim 1:} Let $k$ be a positive integer. Then, Proposition
\ref{prop.sol.binom.102.absorb} (applied to $kb$ and $b$ instead of $n$ and
$k$) yields%
\[
b\dbinom{kb}{b}=kb\dbinom{kb-1}{k-1}.
\]
We can cancel $b$ from this equality (since $b$ is nonzero), and thus obtain%
\[
\dbinom{kb}{b}=k\dbinom{kb-1}{k-1}.
\]
On the other hand, $k\geq1$ (since $k$ is a positive integer). We can multiply
this inequality by $b$ (since $b$ is positive) and thus obtain $kb\geq1b=b$.
Hence, Proposition \ref{prop.sol.binom.102.fac-form} (applied to $kb$ and $b$
instead of $n$ and $k$) yields $\dbinom{kb}{b}=\dfrac{\left(  kb\right)
!}{b!\left(  kb-b\right)  !}=\dfrac{\left(  kb\right)  !}{b!\left(  \left(
k-1\right)  b\right)  !}$ (since $kb-b=\left(  k-1\right)  b$). Comparing this
equality with $\dbinom{kb}{b}=k\dbinom{kb-1}{k-1}$, we obtain%
\[
k\dbinom{kb-1}{k-1}=\dfrac{\left(  kb\right)  !}{b!\left(  \left(  k-1\right)
b\right)  !}.
\]
We can divide both sides of this equality by $k$ (since $k$ is positive and
thus nonzero); thus we obtain%
\[
\dbinom{kb-1}{b-1}=\dfrac{1}{k}\cdot\dfrac{\left(  kb\right)  !}{b!\left(
\left(  k-1\right)  b\right)  !}=\dfrac{1}{k}\cdot\dfrac{1}{b!}\cdot
\dfrac{\left(  kb\right)  !}{\left(  \left(  k-1\right)  b\right)  !}.
\]
This proves Claim 1.]

Now,
\begin{align*}
&  \prod_{k=1}^{a}\underbrace{\dbinom{kb-1}{b-1}}_{\substack{=\dfrac{1}%
{k}\cdot\dfrac{1}{b!}\cdot\dfrac{\left(  kb\right)  !}{\left(  \left(
k-1\right)  b\right)  !}\\\text{(by Claim 1)}}}\\
&  =\prod_{k=1}^{a}\left(  \dfrac{1}{k}\cdot\dfrac{1}{b!}\cdot\dfrac{\left(
kb\right)  !}{\left(  \left(  k-1\right)  b\right)  !}\right)
=\underbrace{\left(  \prod_{k=1}^{a}\dfrac{1}{k}\right)  }_{\substack{=\dfrac
{1}{\prod_{k=1}^{a}k}=\dfrac{1}{a!}\\\text{(since }\prod_{k=1}^{a}%
k=a!\text{)}}}\cdot\underbrace{\left(  \prod_{k=1}^{a}\dfrac{1}{b!}\right)
}_{=\left(  \dfrac{1}{b!}\right)  ^{a}=\dfrac{1}{\left(  b!\right)  ^{a}}%
}\cdot\underbrace{\left(  \prod_{k=1}^{a}\dfrac{\left(  kb\right)  !}{\left(
\left(  k-1\right)  b\right)  !}\right)  }_{\substack{=\prod_{i=1}^{a}%
\dfrac{\left(  ib\right)  !}{\left(  \left(  i-1\right)  b\right)
!}\\\text{(here, we have renamed the}\\\text{index }k\text{ as }i\text{ in the
product)}}}\\
&  =\dfrac{1}{a!}\cdot\dfrac{1}{\left(  b!\right)  ^{a}}\cdot\underbrace{\prod
_{i=1}^{a}\dfrac{\left(  ib\right)  !}{\left(  \left(  i-1\right)  b\right)
!}}_{\substack{=\dfrac{\left(  ab\right)  !}{\left(  0b\right)  !}\\\text{(by
Proposition \ref{prop.sums.telescope-prod},}\\\text{applied to }m=a\text{ and
}a_{i}=\left(  ib\right)  !\text{)}}}=\dfrac{1}{a!}\cdot\dfrac{1}{\left(
b!\right)  ^{a}}\cdot\underbrace{\dfrac{\left(  ab\right)  !}{\left(
0b\right)  !}}_{\substack{=\dfrac{\left(  ab\right)  !}{1}\\\text{(since
}\left(  0b\right)  !=0!=1\text{)}}}\\
&  =\dfrac{1}{a!}\cdot\dfrac{1}{\left(  b!\right)  ^{a}}\cdot\dfrac{\left(
ab\right)  !}{1}=\dfrac{1}{a!}\cdot\dfrac{1}{\left(  b!\right)  ^{a}}%
\cdot\left(  ab\right)  !=\dfrac{\left(  ab\right)  !}{a!\left(  b!\right)
^{a}}.
\end{align*}
This solves the exercise.

\subsection{Remark}

Proposition 2.17.12 in
\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes}
says that $\dbinom{n}{k}$ is an integer for all
$n \in \ZZ$ and $k \in \QQ$.
In other words,
\begin{align}
\dbinom{n}{k} \in \ZZ
\qquad \text{for all } n \in \ZZ \text{ and } k \in \QQ .
\label{sol.binom.102.rmk.nkinZ}
\end{align}
Using this fact and the above exercise, we can show the
following:

\begin{corollary}
\label{cor.binom.102.rmk.div}
Let $a \in \NN$. Let $b$ be a positive integer.
Then, $a! \tup{b!}^a \mid \tup{ab}!$.
\end{corollary}

\begin{proof}[Proof of Corollary \ref{cor.binom.102.rmk.div}.]
The exercise yields
\[
\dfrac{\left(  ab \right)  !}{a! \left(  b! \right)  ^{a}}
= \prod_{k=1}^{a} \underbrack{\dbinom{kb-1}{b-1}}{\in \ZZ \\ \text{(by \eqref{sol.binom.102.rmk.nkinZ}, applied to $kb-1$ and $b-1$} \\ \text{instead of $n$ and $k$)}}
\in \ZZ .
\]
In other words, $a! \tup{b!}^a \mid \tup{ab}!$.
This proves Corollary \ref{cor.binom.102.rmk.div}.
\end{proof}

We refer to \cite[Chapter 5]{GKP} for further properties
of binomial coefficients.

%----------------------------------------------------------------------------------------
%	EXERCISE 6
%----------------------------------------------------------------------------------------
\rule{\linewidth}{0.3pt} \\[0.4cm]

\section{Exercise 6: Binomial coefficients and coprimality}

\subsection{Problem}

It is well-known (see, e.g., \cite[Proposition 3.20]{detnotes}) that
\begin{equation}
\dbinom{n}{k}\in\mathbb{Z}\text{ for all }n\in\mathbb{Z}\text{ and }%
k\in\mathbb{N}. \label{eq.exe.binom.coprime-rat-cat-1.inZ}%
\end{equation}
(This is not at all clear from the definition of $\dbinom{n}{k}$; it is saying
that the product of any $k$ consecutive integers is divisible by $k!$. The
case of $k=2$ is the statement of Exercise 3 \textbf{(g)}.) Thus, we can study
the divisibility of binomial coefficients by various integers. There are
hundreds of theorems about this; this exercise is about one of them.

Let $a$ and $b$ be two coprime positive integers.

\begin{enumerate}
\item[\textbf{(a)}] Prove that $\dfrac{a}{a+b} \dbinom{a+b}{a} =
\dbinom{a+b-1}{a-1}$ and $\dfrac{b}{a+b} \dbinom{a+b}{a} = \dbinom{a+b-1}%
{b-1}$.

\item[\textbf{(b)}] Prove that if $h \in\mathbb{Q}$ satisfies $ah
\in\mathbb{Z}$ and $bh \in\mathbb{Z}$, then $h \in\mathbb{Z}$. (This is where
the coprimality of $a$ and $b$ comes into play.)

\item[\textbf{(c)}] Prove that $a+b \mid\dbinom{a+b}{a}$.

\item[\textbf{(d)}] Find a counterexample to the claim of part \textbf{(c)} if
$a$ and $b$ are allowed to not be coprime.
\end{enumerate}

\subsection{Solution}

We recall \textit{Bezout's theorem} (proven in
\href{http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.pdf}{the class notes}):

\begin{theorem}
\label{thm.ent.gcd.bezout}Let $a$ and $b$ be two integers. Then, there exist
integers $x\in\mathbb{Z}$ and $y\in\mathbb{Z}$ such that%
\[
\gcd\left(  a,b\right)  =xa+yb.
\]

\end{theorem}

Both $a$ and $b$ are positive integers. Hence, the sum $a+b$ is a positive
integer as well. Thus, in particular, $a+b$ is nonzero.

\textbf{(a)} We have $a+b\geq a$ (since $b$ is positive and thus nonnegative).
Hence, Proposition \ref{prop.sol.binom.102.fac-form} (applied to $n=a+b$ and
$k=a$) yields
\[
\dbinom{a+b}{a}=\dfrac{\left(  a+b\right)  !}{a!\left(  \left(  a+b\right)
-a\right)  !}=\dfrac{\left(  a+b\right)  !}{a!b!}\qquad\left(  \text{since
}\left(  a+b\right)  -a=b\right)  .
\]
The same argument (but with the roles of $a$ and $b$ interchanged) yields
\[
\dbinom{b+a}{b}=\dfrac{\left(  b+a\right)  !}{b!a!}=\dfrac{\left(  b+a\right)
!}{a!b!}=\dfrac{\left(  a+b\right)  !}{a!b!}\qquad\left(  \text{since
}b+a=a+b\right)  .
\]
Comparing these two equalities, we obtain%
\begin{equation}
\dbinom{b+a}{b}=\dbinom{a+b}{a}. \label{sol.binom.coprime-rat-cat-1.symm}%
\end{equation}

Proposition \ref{prop.sol.binom.102.absorb} (applied to $n=a+b$ and $k=a$)
yields $a\dbinom{a+b}{a}=\left(  a+b\right)  \dbinom{a+b-1}{a-1}$. We can
divide both sides of this equality by $a+b$ (since $a+b$ is nonzero). We thus
obtain
\begin{equation}
\dfrac{a}{a+b}\dbinom{a+b}{a}=\dbinom{a+b-1}{a-1}.
\label{sol.binom.coprime-rat-cat-1.a.1}%
\end{equation}

The same argument (but with the roles of $a$ and $b$ interchanged) yields%
\[
\dfrac{b}{b+a}\dbinom{b+a}{b}=\dbinom{b+a-1}{b-1}.
\]
In view of \eqref{sol.binom.coprime-rat-cat-1.symm}, this rewrites as%
\[
\dfrac{b}{b+a}\dbinom{a+b}{a}=\dbinom{b+a-1}{b-1}.
\]
In view of $b+a=a+b$, this rewrites as%
\begin{equation}
\dfrac{b}{a+b}\dbinom{a+b}{b}=\dbinom{a+b-1}{b-1}.
\label{sol.binom.coprime-rat-cat-1.a.2}%
\end{equation}

Having proven both \eqref{sol.binom.coprime-rat-cat-1.a.1} and
\eqref{sol.binom.coprime-rat-cat-1.a.2}, we have thus solved part \textbf{(a)}
of the exercise. \\[0.4cm]

\textbf{(b)} Let $h\in\mathbb{Q}$ satisfy $ah\in\mathbb{Z}$ and $bh\in
\mathbb{Z}$. We must prove that $h\in\mathbb{Z}$.

Theorem \ref{thm.ent.gcd.bezout} shows that there exist integers
$x\in\mathbb{Z}$ and $y\in\mathbb{Z}$ such that $\gcd\left(  a,b\right)
=xa+yb$. Consider these $x$ and $y$.

But we know that $a$ and $b$ are coprime. In other words, $\gcd\left(
a,b\right)  =1$. Hence, $1=\gcd\left(  a,b\right)  =xa+yb$. Multiplying both
sides of this equality by $h$, we find%
\[
h\cdot1=h\left(  xa+yb\right)  =x\cdot\left(  ah\right)  +y\cdot\left(
bh\right)  .
\]
All four numbers $x$, $ah$, $y$ and $bh$ on the right hand side of this
equality are integers (since $x\in\mathbb{Z}$, $ah\in\mathbb{Z}$,
$y\in\mathbb{Z}$ and $bh\in\mathbb{Z}$). Thus, the right hand side of this
equality is an integer. Therefore, so is the left hand side. In other words,
$h\cdot1\in\mathbb{Z}$. In other words, $h\in\mathbb{Z}$. This solves part
\textbf{(b)} of the exercise. \\[0.4cm]

\textbf{(c)} Recall that $a$ is a positive integer; hence, $a\in\mathbb{N}$
and $a-1\in\mathbb{N}$. Also, $b-1\in\mathbb{N}$ (since $b$ is a positive
integer). Now, \eqref{eq.exe.binom.coprime-rat-cat-1.inZ} yields $\dbinom
{a+b}{a}\in\mathbb{Z}$ (since $a+b\in\mathbb{Z}$ and $a\in\mathbb{N}$) and
$\dbinom{a+b-1}{a-1}\in\mathbb{Z}$ (since $a+b-1\in\mathbb{Z}$ and
$a-1\in\mathbb{N}$) and $\dbinom{a+b-1}{b-1}\in\mathbb{Z}$ (since
$a+b-1\in\mathbb{Z}$ and $b-1\in\mathbb{N}$).

Define $h\in\mathbb{Q}$ by $h=\dfrac{1}{a+b}\dbinom{a+b}{a}$. (This is
well-defined, since $a+b$ is nonzero and $\dbinom{a+b}{a}$ belongs to
$\mathbb{Z}$.)

From $h=\dfrac{1}{a+b}\dbinom{a+b}{a}$, we obtain%
\begin{align*}
ah  &  =a\cdot\dfrac{1}{a+b}\dbinom{a+b}{a}=\dfrac{a}{a+b}\dbinom{a+b}%
{a}=\dbinom{a+b-1}{a-1}\qquad\left(  \text{by part \textbf{(a)} of this
exercise}\right) \\
&  \in\mathbb{Z}.
\end{align*}

From $h=\dfrac{1}{a+b}\dbinom{a+b}{a}$, we also obtain%
\begin{align*}
bh  &  =b\cdot\dfrac{1}{a+b}\dbinom{a+b}{a}=\dfrac{b}{a+b}\dbinom{a+b}%
{a}=\dbinom{a+b-1}{b-1}\qquad\left(  \text{by part \textbf{(a)} of this
exercise}\right) \\
&  \in\mathbb{Z}.
\end{align*}
Thus, part \textbf{(b)} of this exercise yields $h\in\mathbb{Z}$. In view of
$h=\dfrac{1}{a+b}\dbinom{a+b}{a}=\dfrac{\dbinom{a+b}{a}}{a+b}$, this rewrites
as $\dfrac{\dbinom{a+b}{a}}{a+b}\in\mathbb{Z}$. In other words, $a+b\mid
\dbinom{a+b}{a}$ (since $a+b$ is nonzero). This solves part \textbf{(c)} of
the exercise. \\[0.4cm]

\textbf{(d)} For example, setting $a=2$ and $b=2$ yields a counterexample,
since $2+2\nmid\dbinom{2+2}{2}$. (In fact, $2+2=4\nmid6=\dbinom{4}{2}%
=\dbinom{2+2}{2}$.)

\begin{thebibliography}{99999999}                                                                                %

%Feel free to add your sources -- or copy some from the source code
%of the class notes ( http://www.cip.ifi.lmu.de/~grinberg/t/19s/notes.tex ).

%This is the bibliography: The list of papers/books/articles/blogs/...
%cited. The syntax is: "\bibitem[name]{tag}Reference",
%where "name" is the name that will appear in the compiled
%bibliography, and "tag" is the tag by which you will refer to
%the source in the TeX file. For example, the following source
%has name "GrKnPa94" (so you will see it referenced as
%"[GrKnPa94]" in the compiled PDF) and tag "GKP" (so you
%can cite it by writing "\cite{GKP}").

\bibitem[GrKnPa94]{GKP}Ronald L. Graham, Donald E. Knuth, Oren Patashnik,
\textit{Concrete Mathematics, Second Edition}, Addison-Wesley 1994.\newline
See \url{https://www-cs-faculty.stanford.edu/~knuth/gkp.html} for errata.

\bibitem[Grinbe19]{detnotes}Darij Grinberg, \textit{Notes on the combinatorial
fundamentals of algebra}, 10 January 2019. \newline%
\url{http://www.cip.ifi.lmu.de/~grinberg/primes2015/sols.pdf} \newline The
numbering of theorems and formulas in this link might shift when the project
gets updated; for a ``frozen'' version whose numbering is guaranteed to match
that in the citations above, see
\url{https://github.com/darijgr/detnotes/releases/tag/2019-01-10} .
\end{thebibliography}

\end{document}


\chapter{Regions}
\label{chap:regions}

Regions are the primary abstraction for managing data in Legion.  Futures,
which the examples in Chapter~\ref{chap:tasks} emphasize, are for passing small amounts of data
between tasks. Regions are for holding and processing bulk data.

Because data placement and movement are crucial to performance in modern machines,
Legion provides extensive facilities for managing regions.  These features are a
distinctive aspect of Legion and also probably the most novel and unfamiliar
to new Legion programmers.  Most programming systems hide the placement,
movement and organization of data; in Legion, these operations are exposed to
the application.

Figure~\ref{fig:lr1} shows a very simple program that
creates a {\em logical region}.  A logical region is a table (or,
equivalently, a relation), with an {\em index space} defining the rows
and a {\em field space} defining the columns. The example
in Figure~\ref{fig:lr1} illustrates a number of points:

\begin{itemize}

\item An {\tt IndexSpace} defines a set of indices for a region.  The {\tt create\_index\_space}
call in this program creates a index space with 100 elements.  Multidimensional index spaces can be
created from multidimensional {\tt Rect}s.

\item Field spaces are created in a manner analogous to index spaces.
  Unlike indices, whose size must be declared, there is a global upper
  bound on the number of fields in a field space (and exceeding this bound will cause
  the Legion runtime to report an error).  This particular
  field space has only a single field {\tt FIELD\_A}.  Note that each field has an associated type, the
  size of which is the first argument to {\tt allocate\_field}.

\item Once the index space and field space are created, they are used to create
a logical region {\tt lr1}.  A second call to {\tt create\_logical\_region}
creates a separate logical region {\tt lr2}.  It is very common to build
multiple logical regions with either the same index space, field space or both.
By providing separate steps for creating the field and index spaces prior to creating
a logical region, application programmers can reuse them in the creation of multiple
regions, thereby making it easier to keep all the regions in synch as the program
evolves.
\end{itemize}

The logical regions in this example never hold any data.  In
fact, the logical regions consume no space except for their metadata
(number of entries, names of the fields, etc.).  A {\em physical
  instance} of a logical region holds a copy of the actual data for
that region.  The reason for having both concepts, logical region and
physical instance, is that there is not a one-to-one relationship
between logical regions and instances.  It is common, for example, to
have multiple physical instances of the same logical region (i.e.,
multiple copies) distributed around the system in some fashion to
improve read performance.  Because this program does not create any
physical instances, no real computation takes place, either; the
example simply shows how to create, and then destroy, a logical
region.

\begin{figure}
{\small
\begin{lstlisting}
  // create an index space
  Rect<1> rec(Point<1>(0),Point<1>(99));
  IndexSpace is = runtime->create_index_space(ctx,rec);

  // create a field space
  FieldSpace fs = runtime->create_field_space(ctx);
  FieldAllocator field_allocator = runtime->create_field_allocator(ctx,fs);
  FieldID fida = field_allocator.allocate_field(sizeof(float), FIELD_A);
  assert(fida == FIELD_A);

  // create two distinct logical regions
  LogicalRegion lr1 = runtime->create_logical_region(ctx,is,fs);
  LogicalRegion lr2 = runtime->create_logical_region(ctx,is,fs);

  // Clean up.  IndexAllocators and FieldAllocators automatically have their resources reclaimed
  // when they go out of scope.
  runtime->destroy_logical_region(ctx,lr1);
  runtime->destroy_logical_region(ctx,lr2);
  runtime->destroy_field_space(ctx,fs);
  runtime->destroy_index_space(ctx,is);
\end{lstlisting}
}
\caption{\legionbook{Regions/logicalregions/logicalregions.cc}}
\label{fig:lr1}
\end{figure}

\section{Physical Instances, Region Requirements, Permissions and Accessors}
\label{sec:permissions}

Actually doing something with a logical region requires a {\em
  physical instance}.  The simplest way to create a physical instance
is to pass a logical region to a subtask, as Legion automatically
provides a physical instance to the subtask.  This instance is
guaranteed to be up-to-date, meaning it reflects any changes made to
the region by previous tasks that the subtask depends on.  In the
common case, this means that the results of all previously launched
tasks that updated the region will be reflected in the instance, but
the programmer can specify other semantics if desired; see
Section~\ref{sec:coherence}.

\begin{figure}
{\small
\begin{lstlisting}
  TaskLauncher init_launcher(INIT_TASK_ID, TaskArgument(NULL,0));
  init_launcher.add_region_requirement(RegionRequirement(lr, WRITE_DISCARD, EXCLUSIVE, lr));
  init_launcher.add_field(0, FIELD_A);
  rt->execute_task(ctx, init_launcher);

  TaskLauncher sum_launcher(SUM_TASK_ID, TaskArgument(NULL,0));
  sum_launcher.add_region_requirement(RegionRequirement(lr, READ_ONLY, EXCLUSIVE, lr));
  sum_launcher.add_field(0, FIELD_A);
  rt->execute_task(ctx, sum_launcher);
\end{lstlisting}
}
\caption{Task launches from \legionbook{Regions/physicalregions/physicalregions.cc.}}
\label{fig:permissions}
\end{figure}

Figure~\ref{fig:permissions} shows an excerpt from the top level task in \\
\legionbook{Regions/physicalregions/physicalregions.cc}.  This program is an extension of the
program in Figure~\ref{fig:lr1}---the creation of the (single) logical region is exactly the same as in the
previous example.  Here we call two tasks that operate on the logical region {\tt lr}. The first
task intializes the elements of the region and the second sums the elements and prints out the results.
As in previous examples, a {\tt TaskLauncher} object describes the task to be called and its non-region arguments,
of which there are none.  When tasks also have region arguments, additional information must be added
to the {\tt TaskLauncher}.
For each region the task will access, a {\em region requirement} must be added to the launcher using the
method {\tt add\_region\_requirement}.  A {\tt RegionRequirement} has four components:

\begin{itemize}

\item The logical region that will be accessed.

\item A {\em permission}, which indicates how the subtask will
  use the logical region.  In this program, the two tasks have
  different permissions: the initialization task accesses the region
  with permission {\tt WRITE\_DISCARD} (which means it will overwrite
  everything that was previously in the region) and the sum task
  accesses the region with permission {\tt READ\_ONLY}.  Permissions are
  used by the Legion runtime to determine which tasks can run in
  parallel.  For example, if two tasks only read from a region, they
  can execute simultaneously.  Other interesting permissions that we
  will see in future examples are {\tt READ\_WRITE} (the task both
  reads and writes the region), {\tt WRITE} (the task only writes the
  region, but may not update every element as in {\tt
    WRITE\_DISCARD}), and {\tt REDUCE} (the task performs reductions
  to the region).  It is an error to attempt to access a region in a
  manner inconsistent with the permissions, and most such errors can be
  checked by the Legion runtime with appropriate debugging settings.
  The runtime cannot check
  that every element is updated when using permission {\tt
    WRITE\_DISCARD} and failure to do so may result in incorrect
  behavior.

\item A {\em coherence mode}, which indicates what the subtask expects to see from {\em other} tasks that may access the
region simultaneously.  The mode {\tt EXCLUSIVE} means that this subtask must appear to have exclusive access to the region---if
any other tasks do access the region, any changes they make cannot be visible to this subtask. Furthermore, the subtask
must see all updates from previously launched tasks. Other coherence modes that we will discuss are {\tt ATOMIC} and
{\tt SIMULTANEOUS} (see Chapter~\ref{chap:coherence}).

\item Finally, the region requirement names its {\em parent region}.
  We have not yet discussed subregions (see
  Chapter~\ref{chap:partitioning}), so we defer a full explanation of
  this argument.  Suffice it to say that it should either be the
  parent region or, if the region in question has no parent, the
  region itself, as in this example.

\end{itemize}

Finally, each region requirement applies to one or more fields of the region, and the method {\tt add\_field} is
used to record which field(s) each region requirement applies to.
In this example, there is only one region requirement with index 0 (region requirements
are numbered from 0 in the order they are added to the launcher) and a single field {\tt FIELD\_A} that will be
accessed by the subtask.

\begin{figure}
{\small
\begin{lstlisting}
void sum_task(const Task *task,
		    const std::vector<PhysicalRegion> &rgns,
		    Context ctx, Runtime *rt)
{
  const FieldAccessor<READ_ONLY,int,1> fa_a(rgns[0], FIELD_A);
  Rect<1> d = rt->get_index_space_domain(ctx,task->regions[0].region.get_index_space());
  int sum = 0;
  for (PointInRectIterator<1> itr(d); itr(); itr++)
    {
      sum += fa_a[*itr];
    }
  printf("The sum of the elements of the region is %d\n",sum);
}
\end{lstlisting}
}
\caption{Region accessors from \legionbook{Regions/physicalregions/physicalregions.cc}.}
\label{fig:accessors}
\end{figure}
We now turn our attention to the two subtasks.  The initialization task and the sum task have very similar
structures, differing only in that the intialization task writes a ``1'' in {\tt FIELD\_A} of every element of the region and
the sum task adds these numbers up and reports the sum.  The sum task is shown in Figure~\ref{fig:accessors}.

When {\tt sum\_task} is called, the Legion runtime guarantees that it
will have access to an up-to-date physical instance of the region {\tt
  lr} reflecting all the changes made by previously launched tasks
that modify the {\tt FIELD\_A} of the region (which in this case is
just the initialization task {\tt init\_task}).  The only new feature
that we need to discuss, then, is how the task accesses the data in {\tt FIELD\_A}.

Access to the fields of a region is done through a {\tt FieldAccessor}.  Accessors in Legion provide a level of indirection
that shields application code from the details of how physical instances  are represented in memory.  Under the hood,
the Legion runtime chooses among many different representations depending on the circumstances, so this extra level
of abstraction avoids having those details exposed and fixed in application code.  There are several different types of
region accessors provided by Legion.  The {\tt Generic} accessor has
extensive debugging but  it is also very slow and should never be used in production code.
The {\tt FieldAccessor} used in Figure~\ref{fig:accessors} does no checking and is much more performant.

In Figure~\ref{fig:accessors}, the field
{\tt FIELD\_A} is named in the creation of a {\tt RegionAccessor} for the first (and only) physical region argument.
Note that the type of the field is also included as part of the construction of the accessor.
The other requirement to access the region is knowledge of the region's index space.  Figure~\ref{fig:accessors}
illustrates how to recover a region's index space from a physical instance of the region using the {\tt get\_index\_space} method.
Since this region has a dense index space, we convert the domain to a rectangle (using the {\tt get\_rect} method).
All that is left, then, is to iterate over all the points of the index space (the rectangle {\tt rect}) and read the
field {\tt FIELD\_A} for each such point in the region using the field accessor {\tt acc}.

\section{Fill Fields}
\label{sec:fill}

It is common to initialize all instances of a particular field in a region to the same value, and so Legion
provides direct support for this idiom.  Figure~\ref{fig:fill} gives an excerpt from an example identical
to the one in Figure~\ref{fig:accessors}, except that the initialization task has been replaced by a call to
the runtime that fills every occurrence of {\tt FIELD\_A} with a default value.

\begin{figure}
{\small
\begin{lstlisting}
LogicalRegion lr = rt->create_logical_region(ctx,is,fs);

int init = 1;
rt->fill_field(ctx,lr,lr,fida,&init,sizeof(init));
\end{lstlisting}
}
\caption{\legionbook{Regions/fillfields/fillfields.cc}}
\label{fig:fill}
\end{figure}
The code in Figure~\ref{fig:fill} uses the Legion runtime method {\tt fill\_field} to initialize every
occurrence of {\tt FIELD\_A} to 1.  The {\tt fill\_field} method takes six arguments:

\begin{itemize}

\item Like almost all runtime calls, the first argument is the current task's context.

\item The second argument is the region to be initialized.

\item The third argument is the parent region, or the region itself if it has no parent.  The parent region is needed
to ensure that there are sufficient privileges to perform the initialization ({\tt READ\_WRITE} permission
is required).

\item The fourth argument is the ID of the field to be initialized.

\item The fifth argument is a buffer holding the initial value.

\item The sixth argument is the size of the buffer.
The {\tt fill\_field} call makes a copy of the buffer.

\end{itemize}

The advantage of using {\tt fill\_field} is that the Legion runtime performs the initializaion lazily the next time that
the field is used, which makes the operation less expensive than a normal task call.  Thus, {\tt fill\_field} is preferred
whenever all instances of a field are initialized to the same value.

\section{Inline Launchers}
\label{sec:inlinelaunch}

The most common way to gain access to a region $r$ is by launching a
task $t$ with a region requirement on $r$, in which case the Legion
runtime will automatically map a physical instance of $r$ that will be
accessible in $t$.  There are situations where a task may need to map
a physical instance of a region explicitly, such as when a task needs
to access a newly created region or a new region is returned from a
child task.  Figure~\ref{fig:inlinelaunch} shows the use of an {\em
  inline mapping} to explicitly map a physical region.  After creating
a new logical region an {\tt InlineLauncher} object (so named because
it has similar functionality to a {\tt TaskLauncher} object) is
created with a region requirement and any associated fields.  The
runtime methods $\tt map\_region$ and $\tt unmap\_region$ assign and
unassign a physical instance to {\tt pr}.  Note that $\tt map\_region$
is an asynchronous call and it is necessary to wait for the physical
instance to become valid before it can be used.

\begin{figure}
{\small
\begin{lstlisting}
  LogicalRegion lr = rt->create_logical_region(ctx,is,fs);
  InlineLauncher launcher(RegionRequirement(lr, WRITE_DISCARD, EXCLUSIVE, lr).add_field(0,FIELD_A));
  PhysicalRegion pr = rt->map_region(ctx, launcher);
  pr.wait_until_valid();

  ... computation omitted, see Examples/Regions/inlinemapping/inlinemapping.cc

  // cleanup
  rt->unmap_region(ctx, pr);
\end{lstlisting}
}
\caption{\legionbook{Regions/inlinemapping/inlinemapping.cc}}
\label{fig:inlinelaunch}
\end{figure}

A important invariant maintained by the Legion runtime system is that
tasks have exclusive access to regions to which they have write access
(we will see how to relax this requirement in
Chapter~\ref{chapter:coherence}).  This invariant implies that when a
parent task calls a child task, any regions passed to the child that
may be written must be unmapped before the call and remapped after the
call.  (To see that unmapping a region before passing it to a child
task is necessary, keep in mind that task calls are asynchronous, and
so the parent and child tasks may execute in parallel.  If a
parent task does not unmap a region required by a child task with
write privileges, the application will most likely deadlock.)  For
regions passed as region requirements to task launches and where the
programmer has not explicitly mapped (or unmapped) the region, the
runtime system automatically wraps the task call in the necessary
calls to $\tt unmap\_region$ and $\tt map\_region$.  In cases where
the parent task does not touch the region across many child task
calls, performance can be improved if the application explicitly
unmaps the region at the earliest possible point and maps the region
again at the latest possible point, thereby avoiding any
mapping/unmapping of the region during intermediate task calls.
Whenever a program explicitly maps or unmaps a region $r$ within a
task, the Legion runtime will no longer silently wrap child task
invocations with calls to unmap/map $r$.


\documentclass[12pt, titlepage]{article}

\usepackage{amsmath, mathtools}

\usepackage[round]{natbib}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{colortbl}
\usepackage{xr}
\usepackage{hyperref}
\usepackage{longtable}
\usepackage{xfrac}
\usepackage{tabularx}
\usepackage{float}
\usepackage{siunitx}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage[section]{placeins}
\usepackage{caption}
\usepackage{fullpage}

\hypersetup{
bookmarks=true,     % show bookmarks bar?
colorlinks=true,       % false: boxed links; true: colored links
linkcolor=red,          % color of internal links (change box color with linkbordercolor)
citecolor=blue,      % color of links to bibliography
filecolor=magenta,  % color of file links
urlcolor=cyan          % color of external links
}

\usepackage{array}

%% Comments
\newif\ifcomments\commentstrue

\ifcomments
\newcommand{\authornote}[3]{\textcolor{#1}{[#3 ---#2]}}
\newcommand{\todo}[1]{\textcolor{red}{[TODO: #1]}}
\else
\newcommand{\authornote}[3]{}
\newcommand{\todo}[1]{}
\fi

\newcommand{\wss}[1]{\authornote{blue}{SS}{#1}}
\newcommand{\bmac}[1]{\authornote{red}{BM}{#1}}

\newcommand{\progname}{SWHS}

\begin{document}

\title{Module Interface Specification for Solar Water Heating Systems
  Incorporating Phase Change Material}

\author{Brooks MacLachlan and Spencer Smith}

\date{\today}

\maketitle

\pagenumbering{roman}

\newpage

\tableofcontents

\newpage

\section{Symbols, Abbreviations and Acronyms}

See SRS Documentation at \url{https://github.com/smiths/swhs}

\pagenumbering{arabic}

\section{Introduction}

The following document details the Module Interface Specifications for the
implemented modules in a program simulating a Solar Water Heating System with
Phase Change Material.  It is intended to ease navigation through the program
for design and maintenance purposes.

Complementary documents include the System Requirement Specifications
and Module Guide.  The full documentation and implementation can be
found at \url{https://github.com/smiths/swhs}.

The specification is given in terms of functions, rather than sequences.  For
instance, the predicted temperature of the water is given as a function of time
($\mathbb{R} \rightarrow \mathbb{R})$, not as a sequence ($\mathbb{R}^n$).  This
approach is more straightforward for the specification, but in the
implementation stage, it will likely be necessary to introduce a
sequence, assuming that a numerical solver is used for the system of ODEs.

\section{Notation}

The structure of the MIS for modules comes from \citet{HoffmanAndStrooper1995},
with the addition that template modules have been adapted from
\cite{GhezziEtAl2003}.  The mathematical notation comes from Chapter 3 of
\citet{HoffmanAndStrooper1995}.  For instance, the symbol := is used for a
multiple assignment statement and conditional rules follow the form $(c_1
\Rightarrow r_1 | c_2 \Rightarrow r_2 | ... | c_n \Rightarrow r_n )$.

The following table summarizes the primitive data types used by \progname.

\begin{center}
\renewcommand{\arraystretch}{1.2}
\noindent
\begin{tabular}{l l p{7.5cm}}
\toprule
\textbf{Data Type} & \textbf{Notation} & \textbf{Description}\\
\midrule
character & char & a single symbol or digit\\
integer & $\mathbb{Z}$ & a number without a fractional component in (-$\infty$, $\infty$) \\
natural number & $\mathbb{N}$ & a number without a fractional component in [1, $\infty$) \\
real & $\mathbb{R}$ & any number in (-$\infty$, $\infty$)\\
\bottomrule
\end{tabular}
\end{center}

\noindent
The specification of \progname \ uses some derived data types: sequences, strings, and
tuples. Sequences are lists filled with elements of the same data type. Strings
are sequences of characters. Tuples contain a list of values, potentially of
different types. In addition, \progname \ uses functions, which
are defined by the data types of their inputs and outputs. Local functions are
described by giving their type signature followed by their specification.

\section{Module Decomposition}

The following table is taken directly from the Module Guide document for this project.

\begin{table}[h!]
\centering
\begin{tabular}{p{0.3\textwidth} p{0.6\textwidth}}
\toprule
\textbf{Level 1} & \textbf{Level 2}\\
\midrule

{Hardware-Hiding} & ~ \\
\midrule

\multirow{7}{0.3\textwidth}{Behaviour-Hiding} & Input Parameters\\
& Output Format\\
& Output Verification\\
& Temperature ODEs\\
& Energy Equations\\
& Control Module\\
& Specification Parameters Module\\
\midrule

\multirow{3}{0.3\textwidth}{Software Decision} & {Sequence Data Structure}\\
& ODE Solver\\
& Plotting\\
\bottomrule

\end{tabular}
\caption{Module Hierarchy}
\label{TblMH}
\end{table}

\newpage
~\newpage

\section{MIS of Control Module} \label{Main}

\subsection{Module}

main

\subsection{Uses}

Param (Section~\ref{Parameters}), Temperature
(Section~\ref{Temperature}), Solver
(Section~\ref{ODE}), Energy (Section~\ref{Energy}), verify\_output (Section~\ref{VerifyOutput}), plot
(Section~\ref{Plot}), output (Section~\ref{Output})

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{4cm} p{4cm} p{2cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
main & - & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

None

\subsubsection{Access Routine Semantics}

\noindent main():
\begin{itemize}
\item transition: Modify the state of Param module and the environment variables
  for the Plot and Output modules by following these steps\\
\end{itemize}

\noindent Get (filenameIn: string) and (filenameOut: string) from user\\

\noindent load\_params(filenameIn)\\

\noindent \#\textit{Find temperature function} ($T_W^\text{Solid},
  T_W^\text{Melting}, T_W^\text{Liquid}$, $T_P^\text{Solid},
  T_P^\text{Melting}, T_P^\text{Liquid}$), \textit{and energy} ($Q_P$) \textit{and times of transition between solid,
  melting and liquid phases} ($t_\text{melt}^{\text{init}}, t_\text{melt}^{\text{final}}$)\\

\noindent $t_\text{melt}^\text{init}, [T_W^{\text{Solid}}, T_P^{\text{Solid}}]^T := \text{solve}(\text{ODE\_SolidPCM}, 0.0,
[T_\text{init}, T_\text{init}]^T, \text{event\_StartMelt} , t_\text{final})$\\

\noindent $t_\text{melt}^\text{final}$, $[T_W^{\text{Melting}},
T_P^{\text{Melting}}, Q_p]^T$ := solve(ODE\_MeltingPCM,
$t_\text{melt}^\text{init}$, $[T_W^{\text{Solid}}(t_\text{melt}^\text{init}),
  T_P^{\text{Solid}}(t_\text{melt}^\text{init}), 0.0]^T$,
  event\_EndMelt, $t_\text{final}$)\\

\noindent $[ T_W^{\text{Liquid}}, T_P^{\text{Liquid}}]^T$ := solveNoE(ODE\_LiquidPCM, $t_\text{melt}^\text{final}$,
[$T_W^{\text{Melting}}(t_\text{melt}^\text{final})$,
$T_P^{\text{Melting}}(t_\text{melt}^\text{final})$]$^T$, $t_\text{final}$)\\

\noindent \#\textit{Combine temperatures for $0 \leq t \leq t_\text{final}$}\\

\noindent $T_W(t) = (0 \leq t < t_\text{melt}^{\text{init}} \Rightarrow
T_W^{\text{Solid}} | t_\text{melt}^{\text{init}} \leq t <
t_\text{melt}^{\text{final}} \Rightarrow T_W^{\text{Melting}} |
t_\text{melt}^{\text{final}} \leq t \leq
t_\text{final} \Rightarrow T_W^{\text{Liquid}} )$\\

\noindent $T_P(t) = (0 \leq t < t_\text{melt}^{\text{init}} \Rightarrow
T_P^{\text{Solid}} | t_\text{melt}^{\text{init}} \leq t <
t_\text{melt}^{\text{final}} \Rightarrow T_P^{\text{Melting}} | t_\text{melt}^{\text{final}} \leq t \leq
t_\text{final} \Rightarrow T_P^{\text{Liquid}} )$\\

\noindent \#\textit{Energy values} $(E_W(t), E_P(t))$ \textit{for} $0 \leq t \leq t_\text{final}$\\

\noindent $E_W(t) = (0 \leq t < t_\text{melt}^{\text{init}} \Rightarrow
\text{energyWater}(T_W^{\text{Solid}}) | t_\text{melt}^{\text{init}} \leq t <
t_\text{melt}^{\text{final}} \Rightarrow \text{energyWater}(T_W^{\text{Melting}}) | t_\text{melt}^{\text{final}} \leq t \leq
t_\text{final} \Rightarrow \text{energyWater}(T_W^{\text{Liquid}}) )$\\

\noindent $E_P(t) = (0 \leq t < t_\text{melt}^{\text{init}} \Rightarrow
\text{energySolidPCM}(T_P^{\text{Solid}}) | t_\text{melt}^{\text{init}} \leq t <
t_\text{melt}^{\text{final}} \Rightarrow \text{energyMeltingPCM}(Q_P) | t_\text{melt}^{\text{final}} \leq t \leq
t_\text{final} \Rightarrow \text{energyLiquidPCM}(T_P^{\text{Liquid}}) )$\\

\noindent \#\textit{Output calculated values to a file and to a plot.  Verify
  calculated values obey conservation of energy.}\\

\noindent verify\_output($T_w$, $T_p$, $E_w$, $E_p$, $t_\text{final}$)\\

\noindent plot($T_w$, $T_p$, $E_w$, $E_p$, $t_\text{final}$)\\

\noindent output(filenameOut, $T_w$, $T_p$, $E_w$, $E_p$, $t_\text{final}$)\\

\newpage

\section{MIS of Input Parameters Module} \label{Parameters}

The secrets of this module are the data structure for input parameters, how the
values are input and how the values are verified.  The load and verify secrets
are isolated to their own access programs.

\subsection{Module}

Param

\subsection{Uses}

SpecParam (Section~\ref{SpecParam})

\subsection{Syntax}

\begin{tabular}{p{3cm} p{1cm} p{1cm} >{\raggedright\arraybackslash}p{9cm}}
\toprule
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\midrule
load\_params & string & - &  FileError \\
verify\_params & - & - & badLength, badDiam, badPCMVolume, badPCMAndTankVol,
                        badPCMArea, badPCMDensity, badMeltTemp,
                        badCoilAndInitTemp, badCoilTemp, badPCMHeatCapSolid,
                        badPCMHeatCapLiquid, badHeatFusion, badCoilArea,
                        badWaterDensity, badWaterHeatCap, badCoilCoeff,
                        badPCMCoeff, badInitTemp, badFinalTime,
                        badInitAndMeltTemp \\
$L$ & - & $\mathbb{R}$\\
$D$ & - & $\mathbb{R}$\\
$V_P$ & - & $\mathbb{R}$\\
$A_P$ & - & $\mathbb{R}$\\
... & ... & ...\\
$m_W^{\text{noPCM}}$ & - & $\mathbb{R}$ \\
$\tau_W^{\text{noPCM}}$ & - & $\mathbb{R}$\\
\bottomrule
\end{tabular}

\subsection{Semantics}

\subsubsection{Environment Variables}

inputFile: sequence of string \#\textit{f[i] is the ith string in the text file f}\\

\subsubsection{State Variables}

\renewcommand{\arraystretch}{1.2}
\begin{longtable*}[l]{l}
\# From R1\\
$L$: $\mathbb{R}$ \\
$D$: $\mathbb{R}$ \\
$V_P$: $\mathbb{R}$ \\
$A_P$: $\mathbb{R}$ \\
$\rho_P$ : $\mathbb{R}$ \\
$T_\text{melt}^{P}$: $\mathbb{R}$ \\
$C^S_P$: $\mathbb{R}$ \\
$C^L_P$: $\mathbb{R}$ \\
$H_f$: $\mathbb{R}$ \\
$A_C$: $\mathbb{R}$ \\
$T_C$: $\mathbb{R}$ \\
$\rho_W$: $\mathbb{R}$ \\
$C_W$: $\mathbb{R}$ \\
$h_C$: $\mathbb{R}$ \\
$h_P$: $\mathbb{R}$ \\
$T_\text{init}$: $\mathbb{R}$ \\
$t_\text{step}$: $\mathbb{R}$ \\
$t_\text{final}$: $\mathbb{R}$ \\
$\mathit{AbsTol}$: $\mathbb{R}$ \\
$\mathit{RelTol}$: $\mathbb{R}$ \\
$\mathit{ConsTol}$: $\mathbb{R}$ \\
~\\
\# From R2\\
$V_\text{tank}$: $\mathbb{R}$ \\
$m_W$: $\mathbb{R}$ \\
$m_P$: $\mathbb{R}$ \\
~\\
\noindent \# From R3\\
$\tau_W$: $\mathbb{R}$ \\
$\eta$: $\mathbb{R}$ \\
$\tau_P^S$: $\mathbb{R}$ \\
$\tau_P^L$: $\mathbb{R}$ \\
~\\
\# To Support IM4\\
$E_{P\text{melt}}^{\text{init}}$: $\mathbb{R}$ \\
$E_{P\text{melt}}^{\text{all}}$: $\mathbb{R}$ \\
~\\
\# To Support Testing\\
$m_W^{\text{noPCM}}$: $\mathbb{R}$ \\
$\tau_W^{\text{noPCM}}$: $\mathbb{R}$\\
\end{longtable*}

\subsubsection{Assumptions}

\begin{itemize}

\item load\_params will be called before the values of any state variables will be accessed.

\item The file contains the string equivalents of the numeric values for
each input parameter in order, each on a new line. The order is the same as in
the table in R1 of the SRS. Any comments in the input file should be denoted
with a '\#' symbol.

\end{itemize}

\subsubsection{Access Routine Semantics}

\noindent Param.$L$:
\begin{itemize}
\item output: \textit{out} := $L$
\item exception: none
\end{itemize}

\noindent Param.$D$:
\begin{itemize}
\item output: \textit{out} := $D$
\item exception: none
\end{itemize}

...
~\newline

\noindent Param.$m_W^{\text{noPCM}}$:
\begin{itemize}
\item output: \textit{out} := $m_W^{\text{noPCM}}$
\item exception: none
\end{itemize}

\noindent Param.$\tau_W^{\text{noPCM}}$:
\begin{itemize}
\item output: \textit{out} := $\tau_W^{\text{noPCM}}$
\item exception: none
\end{itemize}

\noindent load\_params($s$):
\begin{itemize}
\item transition: The filename $s$ is first associated with the file f.  {inputFile} is used to
  modify the state variables using the following procedural specification:
\begin{enumerate}
\item Read data sequentially from inputFile to populate the state variables from
  R1 ($L$ to $\mathit{ConsTol}$).
\item Calculate the derived quantities (all other state variables) as follows:
\begin{itemize}
\item $V_{\text{tank}} := \pi \times L \times (\frac{D}{2}) ^ 2$
\item $m_W := \rho_w (V_t - V_p)$
\item $m_P := \rho_p V_p$
\item $\tau_W := \frac{m_w C_w}{A_c h_c}$
\item $\eta := \frac{h_p A_p}{h_c A_c}$
\item $\tau_P^S := \frac{m_p C_{ps}}{h_p A_p}$
\item $\tau_P^L := \frac{m_p C_{pl}}{h_p A_p}$
\item $E_{P\text{melt}}^{\text{init}} := C_{ps} m_p (T_{\text{melt}} - T_{\text{init}})$
\item $E_{P\text{melt}}^{\text{all}} := H_f m_p$
\item $m_W^{\text{noPCM}} := \rho_w  V_t$
\item $\tau_W^{\text{noPCM}} := \frac{m_W^{\text{noPCM}} C_w}{h_c A_c}$
\end{itemize}
\item verify\_params()
\end{enumerate}

\item exception: exc := a file name $s$ cannot be found OR the format of
  inputFile is incorrect $\Rightarrow$  FileError
\end{itemize}

\noindent verify\_params():
\begin{itemize}
\item out: \textit{out} := none
\item exception: exc :=
\end{itemize}
\noindent \begin{longtable*}[l]{l l}
$\neg (L > 0)$ & $\Rightarrow$ badLength\\
$\neg (L_{\text{min}} \leq L \leq L_{\text{max}})$ & $\Rightarrow$ warnLength\\
$\neg (D > 0)$ & $\Rightarrow$ badDiam\\
$\neg ({\frac{D}{L}}_\text{min} \leq \frac{D}{L} \leq {\frac{D}{L}}_\text{max})$ & $\Rightarrow$ warnDiam\\
$\neg (V_P > 0)$ & $\Rightarrow$ badPCMVolume\\
$ \neg (V_P \geq \text{minfract} \cdot V_{\text{tank}}(D, L)) $ & $\Rightarrow$ warnPCMVol\\
$\neg (V_P < V_{\text{tank}}(D, L))$ & $\Rightarrow$ badPCMAndTankVol\\
$\neg (A_P > 0)$ & $\Rightarrow$ badPCMArea\\
$\neg (V_P \leq A_P \leq \frac{2}{h_\text{min}} V_P)$ & $\Rightarrow$ warnVolArea\\
$\neg (\rho_P > 0)$  & $\Rightarrow$ badPCMDensity\\
$\neg (\rho_P^{\text{min}} < \rho_P < \rho_P^{\text{max}})$ & $\Rightarrow$ warnPCMDensity\\
%   $T_\text{melt}^{P}$ 	& $0 < T_\text{melt}^{P} < T_C$ (+) & &  44.2
% 	\si[per-mode=symbol] {\celsius} & 10\%
%   \\
%   $C_P^S$ & $C_P^S > 0$ & $C_{P\text{min}}^S < C_P^S < C_{P\text{max}}^S$ & 1760
% 	\si[per-mode=symbol] {\joule\per\kilo\gram\per\celsius} & 10\%
%   \\
%   $C_P^L$ & $C_P^L > 0$ & $C_{P\text{min}}^L < C_P^S < C_{P\text{max}}^L$ & 2270
% 	\si[per-mode=symbol] {\joule\per\kilo\gram\per\celsius} & 10\%
%   \\
%   $H_f$ & $H_f > 0$ & $H_f^{\text{min}} < H_f < H_f^{\text{max}}$ & 211600
% 	\si[per-mode=symbol] {\joule\per\kilo\gram} & 10\%
%   \\
%   $A_C$ & $A_C > 0$ (*) & $A_C \leq A_C^{\text{max}}$ & 0.12 \si[per-mode=symbol] {\square\metre} & 10\%
%   \\
%   $T_C$ & $0 < T_C < 100$ (+)	& & 50 \si[per-mode=symbol] {\celsius} & 10\%
%   \\
%   $\rho_W$ & $\rho_W > 0$ & $\rho_W^{\text{min}} < \rho_W \leq \rho_W^{\text{max}}$
% 	& 1000 \si[per-mode=symbol] {\kilo\gram\per\cubic\metre} & 10\%
%   \\
%   $C_W$ & $C_W > 0$ & $C_W^{\text{min}} < C_W < C_W^{\text{max}}$ & 4186
% 	\si[per-mode=symbol] {\joule\per\kilo\gram\per\celsius} & 10\%
%   \\
%   $h_C$ & $h_C > 0$ & $h_C^{\text{min}} \leq h_C \leq h_C^{\text{max}}$
% 	& 1000 \si[per-mode=symbol] {\watt\per\square\metre\per\celsius} & 10\%
%   \\
%   $h_P$ & $h_P > 0$ & $h_P^{\text{min}} \leq h_P \leq h_P^{\text{max}}$
% 	& 1000 \si[per-mode=symbol] {\watt\per\square\metre\per\celsius} & 10\%
%   \\
%   $T_\text{init}$ & $0 < T_\text{init} < T_\text{melt} $ (+) & & 40 \si[per-mode=symbol] {\celsius} & 10\%
%   \\
%   $t_\text{final}$ & $t_\text{final} > 0$ & $t_\text{final} < t_{\text{final}}^{\text{max}}$ (**)
% 		& 50000 \si[per-mode=symbol] {\second} & 10\%
%   \\
\end{longtable*}

etc.  See Appendix (Section~\ref{Appendix}) for the complete list of exceptions and
associated error messages.

\subsection{Considerations}

The value of each state variable can be accessed through its name (getter).  An
access program is available for each state variable.  There are no setters for
the state variables, since the values will be set and checked by load params and
not changed for the life of the program.

\newpage

% \section{MIS of Input Verification Module} \label{VerifyInput}

% \subsection{Module}

% verify\_params

% \subsection{Uses}

% Param (Section~\ref{Parameters})

% \subsection{Syntax}

% \subsubsection{Exported Access Programs}

% \begin{center}
% \begin{tabular}{p{3cm} p{1cm} p{1cm} p{9cm}}
% \hline
% \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
% \hline
% verify\_valid & - & - & badLength, badDiam, badPCMVolume, badPCMAndTankVol,
%                         badPCMArea, badPCMDensity, badMeltTemp,
%                         badCoilAndInitTemp, badCoilTemp, badPCMHeatCapSolid,
%                         badPCMHeatCapLiquid, badHeatFusion, badCoilArea,
%                         badWaterDensity, badWaterHeatCap, badCoilCoeff,
%                         badPCMCoeff, badInitTemp, badFinalTime,
%                         badInitAndMeltTemp \\
% \hline
% verify\_recommend & - & - & - \\
% \hline
% \end{tabular}
% \end{center}

% \subsection{Semantics}

% \subsubsection{Environment Variables}

% $win$: 2D array of pixels displayed on the screen.

% \subsubsection{Assumptions}

% All of the fields Param have been assigned values before any of the access
% routines for this module are called.

% \subsubsection{Access Routine Semantics}

% verify\_valid():
% \begin{itemize}
% \item transition: none
% \item exceptions: exc := (\\
% Param.getL() $\leq 0 \Rightarrow$ badLength $|$\\
% Param.get\_diam() $\leq 0 \Rightarrow$ badDiam $|$\\
% Params.get\_Vp() $\leq 0 \Rightarrow$ badPCMVolume $|$\\
% Params.getVp() $\geq$ Params.Vt $\Rightarrow$ badPCMAndTankVol $|$\\
% Params.getAp() $\leq 0 \Rightarrow$ badPCMArea $|$\\
% Params.get\_rho\_p() $\leq 0 \Rightarrow$ badPCMDensity $|$\\
% Params.getTmelt() $\leq 0 \Rightarrow$ badMeltTemp $|$\\
% Params.getTmelt() $\geq$ Params.getTc() $\Rightarrow$ badMeltTemp $|$\\
% Params.getTc() $\leq$ Params.getTinit() $\Rightarrow$ badCoilAndInitTemp $|$\\
% Params.getTc() $\geq 100 \lor$ Params.getTc() $\leq 0 \Rightarrow$ badCoilTemp $|$\\
% Params.getC\_ps() $\leq 0 \Rightarrow$ badPCMHeatCapSolid $|$\\
% Params.getC\_pl() $\leq 0 \Rightarrow$ badPCMHeatCapLiquid $|$\\
% Params.getHf() $\leq 0 \Rightarrow$ badHeatFusion $|$\\
% Params.getAc() $\leq 0 \Rightarrow$ badCoilArea $|$\\
% Params.get\_rho()\_w $\leq 0 \Rightarrow$ badWaterDensity $|$\\
% Params.getC\_w() $\leq 0 \Rightarrow$ badWaterHeatCap $|$\\
% Params.get\_hc() $\leq 0 \Rightarrow$ badCoilCoeff $|$\\
% Params.get\_hp() $\leq 0 \Rightarrow$ badPCMCoeff $|$\\
% Params.getTinit() $\leq 0 \lor$ Params.getTinit() $\geq 100 \Rightarrow$
% badInitTemp $|$\\
% Params.get\_tfinal() $\leq 0 \Rightarrow$ badFinalTime $|$\\
% Params.getTinit() $\geq$ Params.getTmelt() $\Rightarrow$ badInitAndMeltTemp)
% \end{itemize}

% verify\_recommend():
% \begin{itemize}
% \item transition: none
% \item exceptions: exc := (\\
% Params.getL() $< 0.1 \lor$ Params.getL() $> 50 \Rightarrow$ warnLength $|$\\
% Params.getdiam() / Params.getL() $< 0.002 \lor$ Params.getdiam() / Params.getL() $> 200
% \Rightarrow$ warnDiam $|$\\
% Params.getVp() $<$ Params.getVt() $\times 10 ^ -6 \Rightarrow$ warnPCMVol $|$\\
% Params.getVp() $>$ Params.getAp() $\lor$ Params.getAp $> (2/0.001) \times$ Params.getVp()
% $\Rightarrow$ warnVolArea $|$\\
% (Params.get\_rho\_p() $\leq 500) \lor ($ Params.get\_rho\_p() $\geq 20000) \Rightarrow$
% warnPCMDensity $|$ ... )\\
% \# \textit{Need to continue for the rest of the example - tabular form?}
% \# \textit{Should add a module (Configuration Module) to store symbolic constants}
%  % Params.getC\_ps \leq 100 \lor Params.getC\_ps \geq 4000 \Rightarrow$
%  % warnPCMHeatCapSolid $|$\\
%  % Params.getC\_pl \leq 100 \lor Params.getC\_pl \geq 5000 \Rightarrow$
%  % warnPCMHeatCapLiquid $|$\\
%  % Params.getAc > \pi \times (Params.getdiam / 2) ^ 2 \Rightarrow$ warnCoilArea
%  % $|$\\
%  % Params.getrho\_w \leq 950 \lor Params.getrho\_w > 1000 \Rightarrow$
%  % warnWaterDensity $|$\\
%  % Params.getC\_w \leq 4170 \lor Params.getC\_w \geq 4210 \Rightarrow$
%  % warnWaterHeatCap $|$\\
%  % Params.gethc \leq 10 \lor Params.gethc \geq 10000 \Rightarrow$ warnCoilCoeff $|$\\
%  % Params.gethp \leq 10 \lor Params.gethp \geq 10000 \Rightarrow$ warnPCMCoeff $|$\\
%  % Params.gettfinal \leq 0 \lor Params.gettfinal \geq 86400 \Rightarrow$ warnFinalTime)
% \end{itemize}

% \subsection{Considerations}

% See Appendix (Section~\ref{Appendix}) for the complete list of exceptions and
% associated error messages.

\newpage
\section{MIS of Temperature ODEs Module} \label{Temperature}

\subsection{Module}

Temperature

\subsection{Uses}

Param (Section~\ref{Parameters})

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3.5cm} p{1cm} p{7cm} p{2cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
ODE\_SolidPCM & -- & $(\mathbb{R}^{3} \rightarrow \mathbb{R})^2$ & - \\
\hline
ODE\_MeltingPCM & -- &  $(\mathbb{R}^{4} \rightarrow \mathbb{R})^3$ & - \\
\hline
ODE\_LiquidPCM & -- & $(\mathbb{R}^{3} \rightarrow \mathbb{R})^2$ & - \\
\hline
event\_StartMelt & -- & $\mathbb{R}^2 \rightarrow \mathbb{R}$ & - \\
\hline
event\_EndMelt & -- & $\mathbb{R}^3 \rightarrow \mathbb{R}$ & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

none

\subsubsection{Assumptions}

none

\subsubsection{Access Routine Semantics}

ODE\_SolidPCM():
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out :=
\dfrac{d}{dt} \left [
\begin{array}{c}
T_W\\
T_P
\end{array}
\right] =
\left [
\begin{array}{c}
\frac{1}{\tau_W}[(T_C - T_W(t)) + {\eta}(T_P(t) - T_W(t))]\\
\frac{1}{\tau^S_P}(T_W(t) - T_P(t))
\end{array}
\right]
$
\item exception: none
\end{itemize}

ODE\_MeltingPCM():
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out :=
\dfrac{d}{dt} \left [
\begin{array}{c}
T_W\\
T_P\\
Q_P
\end{array}
\right] =
\left [
\begin{array}{c}
\frac{1}{\tau_W}[(T_C - T_W(t)) + {\eta}(T_P(t) - T_W(t))]\\
0 \\
h_P A_P (T_W(t) - T_\text{melt}^P)
\end{array}
\right]
$
\item exception: none
\end{itemize}

ODE\_LiquidPCM():
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out :=
\dfrac{d}{dt} \left [
\begin{array}{c}
T_W\\
T_P
\end{array}
\right] =
\left [
\begin{array}{c}
\frac{1}{\tau_W}[(T_C - T_W(t)) + {\eta}(T_P(t) - T_W(t))]\\
\frac{1}{\tau^L_P}(T_W(t) - T_P(t))
\end{array}
\right]
$
\item exception: none
\end{itemize}

event\_StartMelt():
\begin{itemize}
\item output: $out := g([T_W, T_P]^T) = T_\text{melt}^P - T_P$
\item exception: none
\end{itemize}

event\_EndMelt():
\begin{itemize}
\item output: $out := g([T_W, T_P, Q_P]^T) = 1 - \phi$, where $\phi = \frac{Q_P}{E_{P\text{melt}}^{\text{all}}}$
\item exception: none
\end{itemize}

\newpage
\section{MIS of ODE Solver Module} \label{ODE}

\#\textit{Bold font is used to indicate variables that are a sequence
  type}

\subsection{Module}

Solver($n: \mathbb{N}$) \#\textit{$n$ is the length of the sequences}

\subsection{Uses}

None

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{1.5cm} >{\raggedright\arraybackslash}p{9.25cm} >{\raggedright\arraybackslash}p{2.4cm} p{1.5cm}}
  \hline
  \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Except.} \\
  \hline
  solve & $\textbf{f}: (\mathbb{R}^{n+1} \rightarrow \mathbb{R}^n), t_0 : \mathbb{R},
          \textbf{y}_0: \mathbb{R}^n, g: \mathbb{R}^n \rightarrow \mathbb{R},
          t_\text{fin}: \mathbb{R}$ & $t_1: \mathbb{R},
                                      \textbf{y}:
                                      (\mathbb{R}
                                      \rightarrow
                                      \mathbb{R})^n$ & ODE\_ERR, NO\_EVENT\\
  solveNoE & $\textbf{f}: (\mathbb{R}^{n+1} \rightarrow \mathbb{R}^n), t_0 : \mathbb{R},
             \textbf{y}_0: \mathbb{R}^n, t_\text{fin}: \mathbb{R}$ & $\textbf{y}: (\mathbb{R}
                                                            \rightarrow
                                                            \mathbb{R})^n$ & ODE\_ERR\\

  \hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

None

\subsubsection{Access Routine Semantics}

\#\textit{Solving} $\frac{d}{dt} \mathbf{y} = \mathbf{f}(t,
\mathbf{y}(t))$\\

\noindent solve($\textbf{f}, t_0, \textbf{y}_0, g, t_\text{fin}$):
\begin{itemize}
\item output: $out := t_1, \textbf{y}(t)$ where
$$\textbf{y}(t) = \textbf{y}_0 + \int_{t_0}^{t} \textbf{f}(s, \textbf{y}(s)) ds$$
with $t_1$ determined by the first time where $g(\textbf{y}(t_1)) = 0$.  $\textbf{y}(t)$ is
calculated from $t = t_0$ to $t = t_1$.
\item exception: $exc :=$ ( $\neg (\exists t: \mathbb{R}| t_0 \leq t
  \leq t_\text{fin} : g(\textbf{y}(t)) = 0) \Rightarrow$ NO\_EVENT $|$ ODE Solver Fails $\Rightarrow$
  ODE\_ERR)
\end{itemize}

solveNoE($\textbf{f}$, $t_0$, $\textbf{y}_0$, $t_\text{fin}$):
\begin{itemize}
\item output: $out := \textbf{y}(t)$ where
$$\textbf{y}(t) = \textbf{y}_0 + \int_{t_0}^{t_\text{fin}} \textbf{f}(s, \textbf{y}(s)) ds$$
$y(t)$ is calculated from $t = t_0$ to $t = t_\text{fin}$.
\item exception: $exc :=$ ( ODE Solver Fails $\Rightarrow$ ODE\_ERR)
\end{itemize}

\newpage
\section{MIS of Energy Module} \label{Energy}

\subsection{Module}

Energy

\subsection{Uses}

Param (Section~\ref{Parameters})

\subsection{Syntax}

\subsubsection{External Access Programs}

\begin{center}
\begin{tabular}{p{4cm} p{4cm} p{3cm} p{2cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
energyWater & $\mathbb{R} \rightarrow \mathbb{R}$ & $\mathbb{R} \rightarrow \mathbb{R}$ & - \\
\hline
energySolidPCM & $\mathbb{R} \rightarrow \mathbb{R}$ & $\mathbb{R} \rightarrow \mathbb{R}$ & - \\
\hline
energyMeltingPCM & $\mathbb{R} \rightarrow \mathbb{R}$ & $\mathbb{R} \rightarrow \mathbb{R}$ & - \\
\hline
energyLiquidPCM & $\mathbb{R} \rightarrow \mathbb{R}$ & $\mathbb{R} \rightarrow \mathbb{R}$ & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

None

\subsubsection{Assumptions}

None

\subsubsection{Access Routine Semantics}

energyWater($T_W$):
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out := C_W m_W (T_W - T_\text{init})$
\item exception: none
\end{itemize}

\noindent energySolidPCM($T_P$):
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out := C^S_P m_P (T_P - T_\text{init})$
\item exception: none
\end{itemize}

\noindent energyMeltingPCM($Q_P$):
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out := E_{P\text{melt}}^{\text{init}} + Q_P$
\item exception: none
\end{itemize}

\noindent energyLiquidPCM($T_P$):
\renewcommand*{\arraystretch}{1.5}
\begin{itemize}
\item output: $out := E_{P\text{melt}}^{\text{init}}+H_f m_p + C_P^L m_P(T_P(t) - T_\text{melt}^P)$
\item exception: none
\end{itemize}

\newpage
\section{MIS of Output Verification Module} \label{VerifyOutput}

\subsection{Module}

verify\_output

\subsection{Uses}

Param (Section~\ref{Parameters})

\subsection{Syntax}

\subsubsection{Exported Constant}

ADMIS\_ER = $1 \times 10^{-6}$

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{3cm} p{7cm} p{1cm} p{2cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
verify\_output & $T_W(t):\mathbb{R} \rightarrow \mathbb{R},
                 T_P(t):\mathbb{R} \rightarrow \mathbb{R},
                 E_W(t):\mathbb{R} \rightarrow \mathbb{R},
                 E_P(t):\mathbb{R} \rightarrow \mathbb{R},
                 t_\text{final}: \mathbb{R}$ & - & EWAT\_NOT\_CONSERVE, EPCM\_NOT\_CONSERVE \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

None

\subsubsection{Assumptions}

All of the fields of the input parameters structure have been assigned a
value.

\subsubsection{Access Routine Semantics}

\noindent verify\_output($T_W, T_P, E_W, E_P$, $t_\text{final}$):
\begin{itemize}
\item exception: exc := (
\end{itemize}

\noindent $
(\forall t | 0 \leq t \leq t_\text{final} : \text{relErr}(E_W,
\int_{0}^{t} h_C A_C (T_C - T_W(t)) dt - \int_{0}^{t} h_P A_P (T_W(t)
- T_P(t)) dt) < \text{ADMIS\_ER}) \Rightarrow \text{EWAT\_NOT\_CONSERVE}
$

$|$

\noindent $
(\forall t | 0 \leq t \leq t_\text{final} : \text{relErr}(E_{P}, \int_{0}^{t}
h_{P} A_{P} (T_{W}(t) - T_{P}(t)) dt) < \text{ADMIS\_ER}) \Rightarrow
\text{EPCM\_NOT\_CONSERVE}
$
)

\subsubsection{Local Functions}

relErr: $\mathbb{R}$ $\times$ $\mathbb{R}$ $\rightarrow$ $\mathbb{R}$ \\
$\text{relErr}(t, e) \equiv \frac{|t - e|}{|t|}$ \\
\newline

\newpage
\section{MIS of Plotting Module} \label{Plot}

\subsection{Module}

plot

\subsection{Uses}

N/A

\subsection{Syntax}

\subsubsection{Exported Access Programs}

\begin{center}
\begin{tabular}{p{2cm} p{8cm} p{2cm} p{2cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
plot & $T_W(t):\mathbb{R} \rightarrow \mathbb{R},
                 T_P(t):\mathbb{R} \rightarrow \mathbb{R},
                 E_W(t):\mathbb{R} \rightarrow \mathbb{R},
       E_P(t):\mathbb{R} \rightarrow \mathbb{R}$, $t_\text{final}: \mathbb{R}$ & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

None

\subsubsection{Environment Variables}

win: 2D sequence of pixels displayed on the screen\\

\subsubsection{Assumptions}

None

\subsubsection{Access Routine Semantics}

\noindent plot($T_w$, $T_p$, $E_w$, $E_p$, $t_\text{final}$):
\begin{itemize}
\item transition: Modify win to display a plot where the vertical axis
  is time and one horizontal axis is temperature and the other
  horizontal axis is energy.  The time should run from $0$ to $t_\text{final}$
\item exception: none
\end{itemize}

\newpage

\section{MIS of Output Module} \label{Output}

\subsection{Module}

output

\subsection{Uses}

Param (Section~\ref{Parameters})

\subsection{Syntax}

\subsubsection{Exported Constants}

$max\_width$: integer

\subsubsection{Exported Access Program}

\begin{center}
\begin{tabular}{p{3cm} p{7cm} p{2cm} p{2cm}}
\hline
\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\
\hline
output & fname: string, $T_W(t):\mathbb{R} \rightarrow \mathbb{R},
                 T_P(t):\mathbb{R} \rightarrow \mathbb{R},
                 E_W(t):\mathbb{R} \rightarrow \mathbb{R},
       E_P(t):\mathbb{R} \rightarrow \mathbb{R}$, $t_\text{final}: \mathbb{R}$ & - & - \\
\hline
\end{tabular}
\end{center}

\subsection{Semantics}

\subsubsection{State Variables}

None

\subsubsection{Environment Variables}

file: A text file

\subsubsection{Access Routine Semantics}

\noindent output(fname, $T_w$, $T_p$, $E_w$, $E_p$, $t_\text{final}$):
\begin{itemize}
\item transition:  Write to environment variable named fname the
  following: the input
    parameters from Param, and the calculated values $T_w$, $T_p$, $E_w$,
    $E_p$ from times $0$ to $t_\text{final}$.  The functions will be output as
    sequences in this file.  The spacing between points in the sequence should
    be selected so that the heating behaviour is captured in the data.
\item exception: none
\end{itemize}

\newpage

\section{MIS of Specification Parameters} \label{SpecParam}

The secrets of this module is the value of the specification parameters.

\subsection{Module}

SpecParam

\subsection{Uses}

N/A

\subsection{Syntax}

\subsubsection{Exported Constants}

\renewcommand{\arraystretch}{1.2}
\begin{longtable*}[l]{l}
\# From Table 2 in SRS\\
  $L_\text{min}$ := 0.1\\
  $L_\text{max}$ := 50\\
  ${\frac{D}{L}}_\text{min}$ := 0.002 \\
  ${\frac{D}{L}}_\text{max}$ := 200 \\
  $\text{minfrac} $ := $10^{-6}$\\
  $h_\text{min}$ := 0.001 \\
  $\rho_P^{\text{min}}$ := 500\\
  $\rho_P^{\text{max}}$ := 20000\\
  $C_{P\text{min}}^S$ := 100 \\
  $C_{P\text{max}}^S$ := 4000\\
  $C_{P\text{min}}^L$ := 100 \\
  $C_{P\text{max}}^L$ := 5000\\
  $A_C^{\text{max}}$ := $\pi(\frac{D}{2})^2$\\
  $\rho_W^{\text{min}}$ := 950\\
  $\rho_W^{\text{max}}$ := 1000\\
  $C_W^{\text{min}}$ := 4170\\
  $C_W^{\text{max}}$ := 4210\\
  $h_C^{\text{min}}$ := 10\\
  $h_C^{\text{max}}$ := 10000\\
  $h_P^{\text{min}}$ := 10\\
  $h_P^{\text{max}}$ := 10000\\
  $t_{\text{final}}^{\text{max}}$ := 86400\\
\end{longtable*}

\wss{$A_C^{\text{max}}$ shouldn't be in this table of constants}

\subsection{Semantics}

N/A

\newpage

\bibliographystyle {plainnat}
\bibliography {MIS}

\newpage

\section{Appendix} \label{Appendix}

\renewcommand{\arraystretch}{1.2}

\begin{longtable}{l p{12cm}}
\caption{Possible Exceptions} \\
\toprule
\textbf{Message ID} & \textbf{Error Message} \\
\midrule
badLength & Error: Tank length must be $> 0$ \\
badDiam & Error: Tank diameter must be $> 0$ \\
badPCMVolume & Error: PCM volume must be $> 0$ \\
badPCMAndTankVol & Error: PCM volume must be $<$ tank volume \\
badPCMArea & Error: PCM area must be $> 0$ \\
badPCMDensity & Error: rho\_p must be $> 0$ \\
badMeltTemp & Error: Tmelt must be $> 0$ and $< Tc$ \\
badCoilAndInitTemp & Error: Tc must be $>$ Tinit \\
badCoilTemp & Error: Tc must be $> 0$ and $< 100$ \\
badPCMHeatCapSolid & Error: C\_ps must be $> 0$ \\
badPCMHeatCapLiquid & Error: C\_pl must be $> 0$ \\
badHeatFusion & Error: Hf must be $> 0$ \\
badCoilArea & Error: Ac must be $> 0$ \\
badWaterDensity & Error: rho\_w must be $> 0$ \\
badWaterHeatCap & Error: C\_w must be $> 0$ \\
badCoilCoeff & Error: hc must be $> 0$ \\
badPCMCoeff & Error: hp must be $> 0$ \\
badInitTemp & Error: Tinit must be $> 0$ and $< 100$ \\
badFinalTime & Error: tfinal must be $> 0$ \\
badInitAndMeltTemp & Error: Tinit must be $<$ Tmelt \\
ODE\_ACCURACY & $reltol$ and $abstol$ were not satisfied by the ODE solver for a given solution step. \\
ODE\_BAD\_INPUT & Invalid input to ODE solver \\
ODE\_MAXSTEP & ODE solver took $MaxStep$ steps and did not find solution \\
warnLength & Warning: It is recommended that 0.1 $<$= L $<$= 50 \\
warnDiam & Warning: It is recommended that 0.002 $<$= D/L $<$= 200 \\
warnPCMVol & Warning: It is recommended that Vp be $>$= 0.0001\% of Vt \\
warnVolArea & Warning: It is recommended that Vp $<$= Ap $<$= (2/0.001) * Vp \\
warnPCMDensity & Warning: It is recommended that 500 $<$ rho\_p $<$ 20000 \\
warnPCMHeatCapSolid & Warning: It is recommended that 100 $<$ C\_ps $<$ 4000 \\
warnPCMHeatCapLiquid & Warning: It is recommended that 100 $<$ C\_pl $<$ 5000 \\
warnCoilArea & Warning: It is recommended that Ac $<$= pi * (D/2) $\wedge$ 2 \\
warnWaterDensity & Warning: It is recommended that 950 $<$ rho\_w $<$= 1000 \\
warnWaterHeatCap & Warning: It is recommended that 4170 $<$ C\_w $<$ 4210 \\
warnCoilCoeff & Warning: It is recommended that 10 $<$ hc $<$ 10000 \\
warnPCMCoeff & Warning: It is recommended that 10 $<$ hp $<$ 10000 \\
warnFinalTime & Warning: It is recommended that 0 $<$ tfinal $<$ 86400 \\
warnWaterError & Warning: There is greater than $x$\% relative error between the energy in the water output and the expected output based on the law of conservation of energy. (Where $x$ is the value of $ConsTol$) \\
warnPCMError & Warning: There is greater than $x$\% relative error between the energy in the PCM output and the expected output based on the law of conservation of energy. (Where $x$ is the value of $ConsTol$) \\
\bottomrule
\end{longtable}

\end{document}