%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Higher-Rank Polymorphism with the Application Mode}
\label{chap:BiDirectional}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

We have seen in \Cref{sec:DK} that bidirectional type checking is a useful and
versatile tool for type checking and type inference. In traditional
bidirectional type-checking, type information flows from functions to arguments
(e.g., \rref{dk-in-app} in \Cref{sec:DK:declarative}). In this section, we
present a novel variant of bidirectional type checking where the type
information flows from arguments to functions. This variant retains the
inference mode, but adds a so-called \textit{\mode} mode. Such design can remove
annotations that basic bidirectional type checking cannot, and is useful when
type information from arguments is required to type-check the functions being
applied.

We illustrate our novel design of bidirectional type-checking using System \ap,
a lambda calculus with implicit higher-rank polymorphism. This section first
presents the declarative, syntax-directed type system of System \ap
in \Cref{sec:AP:declarative}. The interesting aspects about the new type system
are: 1) the typing rules, which employ a combination of the inference mode and
the \textit{\mode} mode; 2) the novel subtyping relation under an application
context. Later, we prove our type system is type-safe by a type-directed
translation to System F in \Cref{sec:AP:translation}. An algorithmic type system
is discussed in \Cref{sec:AP:algorithm}.

\input{Gen/BiDirectional/introduction}
\input{Gen/BiDirectional/typesystem}
\input{Gen/BiDirectional/translation}
\input{Gen/BiDirectional/algorithm}
\input{Gen/BiDirectional/discussion}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../Thesis"
%%% org-ref-default-bibliography: "../Thesis.bib"
%%% End:


\documentclass[a0]{tumposter}

\usepackage[english]{babel}

\usepackage{blindtext}

\usepackage{multicol}
\usepackage{amsmath}
\usepackage{graphicx}

% for printing fontsizes
\usepackage{printlen}
\uselengthunit{mm}

\input{preamble.tex}

\usepackage[utf8]{inputenc}

\title{
	Early Classification for Agricultural Monitoring \\ from Satellite Time Series
	}

\author{
	Marc Rußwurm,\footnotemark[1] Romain Tavenard,\footnotemark[2] Sébastien Lefèvre,\footnotemark[2] Marco Körner\footnotemark[1]
	}

\header{
	Remote Sensing Technology \\
	TUM Department of Civil, Geo and Environmental Engineering \\
	Technical University of Munich
	}

\begin{document}
\maketitle

\renewcommand{\subsection}[1]{\textbf{#1}}

\begin{minipage}[t]{.65\textwidth}

	\section{Objective}

	\begin{tikzpicture}[scale=16.8]
	\node[label={[name=sat,text height=1.5ex,text depth=.25ex]Satellite Data}, anchor=north](x) at (-1,0){$\M{X} = (\V{x}_0, \V{x}_1, \dots , \V{x}_T)$};
	\node[below=of x, label={[yshift=1.3em, xshift=1.8em, font=\tiny, text=white]below:ESA Sentinel 2 Satellite}](s2){\includegraphics[width=11cm]{images/sentinel2}};

	\node[below=0em of s2, text width=11cm](eqbox){
		\small
		\begin{itemize}
			\item collected at regular temporal intervals of 2-3 days
			\item measurements of 13 spectral bands
			\item data available globalls
		\end{itemize}
	};

	\node[label={[name=cm,text height=1.5ex,text depth=.25ex]{Early} {Classification} Model}, anchor=north](f) at (0,0){ $\yhat_t, {\deltat} = f(\xuptot)$};
	\node[below=0em of f, text width=13cm, font=\small](info){
		\begin{description}

		\item[$\xuptot$] observation until $t$  \\
		\item[$\yhat_t$] class prediction scores \\
		\item[$\deltat$] probability of stopping.

		\end{description}

	};
%	\node[below=of f](example){\input{images/example.tikz}};
	\node[circle, below=of info, text width=11cm, fill=tumbluedark, text=white](example){Classifying a \\ satellite time series \\ {\color{tumbluelight}\textbf{accurately}} \color{white} as {\color{ecolor}\textbf{early}} \color{white} as possible};

	\node[label={[name=ctm,text height=1.5ex,text depth=.25ex]Crop Type Labels}, anchor=north](y) at (1,0){
		$\V{y} = \small (y_\text{corn}, y_\text{barley}, \dots) \in \mathbb{R}^{13}$
	};
	\node[below=of y, label=below:crop type labels](labels){\includegraphics[width=11cm]{images/parcels}};
	\node[below=of labels, text width=11cm](lbls){
		\small
		\begin{itemize}\setlength\itemsep{.1em}
		\item European Common Agricultural Policy (CAP)
		\item collected yearly in entire Europe
%		\item slowly made publicly available
%		\item today, gathered on a national basis
%		\item in future harmonized within Europe's INSPIRE directive
		\end{itemize}
	};

	\draw[very thick, -{Stealth[scale=.5]}, tumblue] (x) -- (f);
	\draw[very thick, -{Stealth[scale=.5]}, tumblue] (f) -- (y);

	\coordinate(bottomleftcolumn) at (example.south -| s2);
	\coordinate(bottomrightcolumn) at (example.south -| lbls);

	\scoped[on background layer]
	{
		\node[fit=(ctm)(lbls)(bottomrightcolumn), fill=tumbluelight!20, inner sep=1em, rounded corners]{};
		\node[fit=(f)(example)(cm), fill=tumorange!20, inner sep=1em, rounded corners]{};
		\node[fit=(sat)(eqbox)(bottomleftcolumn), fill=tumbluelight!20, inner sep=1em, rounded corners]{};
	}

	\end{tikzpicture}

	\section{Method}

	Based on previous work (Rußwurm et al., 2019) applied to crop type mapping from remote sensing data.

	%A network output to indicate a probability of stopping $\deltat$

	\begin{minipage}[t]{.49\textwidth}
		\subsection{Mechanism}

		\input{images/backprop_stopping_rule.tikz}
		\backpropstoppingrulefull

%	\begin{tikzpicture}
%		\node[fill=tumbluelight!20, rounded corners](a) at (0,0){
%						\input{images/backprop_stopping_rule.tikz}
%						\backpropstoppingrulefull
%					};
%		\node[right=of a]{\input{images/qualitative_example.tikz}};
%	\end{tikzpicture}
%	\vspace{-10em}

%	probability of not having classified before (known at training time)
%	$$P(t) = \deltat \cdot \prod_{\tau=0}^{t-1} 1 - p_\tau$$

	\end{minipage}
	\begin{minipage}[t]{.49\textwidth}

	\subsection{Loss function}

	composite loss function
	$$\mathcal{L}(\V{x}, \V{y}) = \sum_{t=0}^T P(t;\deltauptot) \mathcal{L}_t(\xuptot, \V{y})$$

	A Loss function including accuracy and earliness

	\begin{tikzpicture}[node distance=-.5em, draw=tumbluelight, rounded corners]

	%	\node(allloss){$\mathcal{L}(\V{x}, \V{y}) = \sum_{t=0}^T P(t;\deltauptot) \mathcal{L}_t(\xuptot, \V{y})$};
	%
	\node(loss){$\mathcal{L}_t(\xuptot, \V{y})$};
	\node[right=of loss](equals){$=$};
	\node[right=of equals, fill=accuracycolor!20, rounded corners, label={[font=\small]Classification Loss}](classificationloss){$\alpha \mathcal{L}_c (\xuptot, \V{y})$};
	\node[right=of classificationloss](minus){$-$};
	\node[right=of minus, fill=earlinesscolor!20, rounded corners, label={[font=\small]Earliness Reward}](earlinessreward){$(1 - \alpha)\mathcal{R}_e(t, \ycorrect_t)$};

	\node[below=1em of classificationloss, text width=10cm, xshift=-4em](clossexp){$\mathcal{L}_c = -\log(\ycorrect_t)$ \\
		\vspace{.5em}
		\tiny
		cross entropy loss for accurate classifications \par};

	\node[below=1em of earlinessreward, text width=13cm, xshift=-2em](erewardexp){$\mathcal{R}_e(t, \ycorrect_t) = \ycorrect_t \left(1 - \frac{t}{T}\right)$ \\
		\vspace{.5em}
		\tiny
		reduces loss for earlier classifications $1-\frac{t}{T}$ if the correct class $\ycorrect_t$ has been predicted \par};

	\draw[thick] (classificationloss) -- (clossexp);
	\draw[thick] (earlinessreward) -- (erewardexp);
	\end{tikzpicture}

	\end{minipage}

	{\tiny
	Rußwurm, M., Lefèvre, S., Courty, N., Emonet, R., Körner, M., and Tavenard, R. End-to-end learning for early classification of time series. arXiv preprint arXiv:1901.10681, 2019.
	\par
	}

	\vspace{-1em}
	\section{Application}

	\begin{minipage}[t]{.5\textwidth}
	\subsection{Agriculture}

	\small

	\vspace{1em}

		\textbf{Early Crop Detection}
		\begin{itemize}
			\item early assessment of cultivated crops
			\item basis for early crop yield estimation
		\end{itemize}
		\vspace{.3em}

		\textbf{Extraction of Crop Phenology}
		\begin{itemize}
			\item extraction of vegetation specific events
			\item monitoring time of classification
			\item regional or temporal variations
		\end{itemize}
		\vspace{.3em}

		\textbf{Generalization}
		\begin{itemize}
			\item end-to-end trainable
			\item no region-specific expert knowledge
			\item applicable globally
		\end{itemize}

	\end{minipage}
	\begin{minipage}[t]{.49\textwidth}
	\subsection{Dataset and Area of Interest} \par
	\begin{minipage}{.6\textwidth}
		\small
		\vspace{1em}
		Hollfeld region Bavaria
		\begin{itemize}
			\item 49k field parcels
			\item 6 main crop types
			\item covering 40km by 30 km
			\item central Germany
		\end{itemize}

		\vspace{1em}

		\tiny Challenge: Class imbalance \par
		\input{images/partition_histograms.tikz}
%		\vspace{-4em}\includegraphics[width=.3\textwidth]{images/holl.pdf}
	\end{minipage}
	\begin{minipage}{.35\textwidth}
%		\input{images/partition_histograms.tikz}
		\tiny {\color{tumblue}regions with labels} and \\ {\color{tumorange} location of dataset. \par} \par
		\includegraphics[width=.9\textwidth]{images/oberfrankenineurope.pdf}

		 \tiny partition in {\color{traincolor} train}, {\color{validcolor} validation}, and {\color{evalcolor} evaluation} \par
		\includegraphics[width=.9\textwidth]{images/holl.pdf}
	\end{minipage}

	\end{minipage}

\end{minipage}
\hfill
\begin{minipage}[t]{.32\textwidth}
	\section{Results}

	\subsection{Qualitative Example} \par
	{\footnotesize Single example showing reflectance data $\M{x}$ and predictions $\yhat$ along with the stopping time $\tstop \sim \text{Ber}(\deltat)$. \par}

	\vspace{.5em}
	\input{images/example.tikz}
	\vspace{-.5em}

	\subsection{Losses during Training} \par
	{\footnotesize The combined loss $L_t$, as well as earliness $L_e$ and accuracy $L_e$ losses during training. \par}

	\vspace{.5em}
	\input{images/loss-accuracyplots.tikz}
	\vspace{-1em}

	\subsection{Stopping Condition Parameterization} \par
	{\footnotesize Stopping times throughout the training grouped by crop category. The parameterization of early classification is learned for different crop types at different times during training. \par}

	\input{images/trainingstoppingclasses.tikz}

	\subsection{Balancing Earliness and Accuracy} \par
	{\footnotesize Evaluting the effect of the trade-off parameter $\alpha$ on the accuracy and earliness ($\tstop$). Runs repeated three times to evaluated the sability of the results. \par}

	\begin{table}

		\scriptsize
		\hspace{0em}\begin{tabular}{lcccccc}
			\toprule\small
			\textbf{$\alpha$} & accuracy & $\meantstop$  & precision & recall & $f_1$ & $\kappa$ \\
			\cmidrule(lr){0-0}\cmidrule(lr){1-1}\cmidrule(lr){2-2}\cmidrule(lr){3-3}\cmidrule(lr){4-4}\cmidrule(lr){5-5}\cmidrule(lr){6-6}\cmidrule(lr){7-7}
			.0 & .25 $\pm$ .22 & .10 $\pm$ .17 & .19 $\pm$ .20 & .25 $\pm$ .17 & .16 $\pm$ .20 & .12 $\pm$ .19 \\
			.2 & .81 $\pm$ .03 & .40 $\pm$ .02 & .70 $\pm$ .01 & .74 $\pm$ .01 & .71 $\pm$ .01 & .71 $\pm$ .04 \\
			.4 & .80 $\pm$ .09 & .47 $\pm$ .03 & .71 $\pm$ .02 & .74 $\pm$ .01 & .71 $\pm$ .02 & .71 $\pm$ .10 \\
			.6 & .85 $\pm$ .02 & .88 $\pm$ .07 & .73 $\pm$ .04 & .74 $\pm$ .03 & .73 $\pm$ .03 & .77 $\pm$ .03 \\
			.8 & .84 $\pm$ .01 & .93 $\pm$ .05 & .72 $\pm$ .02 & .75 $\pm$ .01 & .73 $\pm$ .02 & .76 $\pm$ .02 \\
			1.0 & .83 $\pm$ .03 & 1.00 $\pm$ .00 & .72 $\pm$ .03 & .75 $\pm$ .01 & .72 $\pm$ .03 & .75 $\pm$ .04 \\
			\bottomrule
		\end{tabular}

		%	\caption{Varying the weighting factor $\alpha$ for \emph{early reward} loss formulation (\cref{sec:earlynessreward}).}
		%	\label{tab:alpha}

	\end{table}

	\subsection{Extracting Vegetation Characteristics} \par

	{\footnotesize Stopping time per crop category reveals characteristic variations in type of vegetation confirmed by date of harvest (\druschdatum) from local authorities. \par}
	\vspace{.5em}
	\input{images/classboxplots.tikz}

\end{minipage}

%\frame{
\begin{footer}
	\begin{minipage}{.15\textwidth}
		\textbf{ICML Workshop}\\
		\includegraphics[width=5cm]{images/AI4SG}
	\end{minipage}
	\begin{minipage}{.275\textwidth}
		\textbf{Technical University of Munich}\footnotemark[1]\\
		TUM Department of Civil, Geo and Env. \\
		Remote Sensing Technology \\
		Arcisstr. 21, 80333 Munich, Germany
	\end{minipage}
	\begin{minipage}{.275\textwidth}
		\textbf{IRISA-Obelix}\footnotemark[2]\\
		Université Bretagne Sud \\
		IRISA, UMR 6074 CNRS \\
		Campus de Tohannic, 56000 Vannes, France

	\end{minipage}
	\begin{minipage}{.2\textwidth}
		\textbf{Data \& Code} \\
		%		\vspace{1em}
		{github.com/rtavenar/early\_rnn} \\
		{twitter.com/MarcCoru} \\
		www.lmf.bgu.tum.de/vision
	\end{minipage}
	\begin{minipage}{.05\textwidth}
		\hfill\includegraphics[width=5cm]{images/qr-code}\\

	\end{minipage}

\end{footer}
%}

\end{document}


\chapter{Discussion}
\label{chapter:conclusion}

    %% TODO
    %% - SimGrid suppose que les consommations réseau et cpu sont linéaires
    %%   et indépendantes. Ce n'est pas si simple. Tension entre
    %%   mesurer/injecter et modéliser/prédire.
    %% - Ça marche mais niveau d'expertise encore assez démentiel
    %% - Résolution/automatisation de pas mal de choses en terme de
    %%   modélisation de plate-forme mais il y a encore beaucoup de
    %%   travail. LibSimBLAS ?

    \section{Contribution}%

        This thesis has contributed to the improvement of experimental reproducibility in high performance computing.

        In Part~\ref{part:prediction}, we described a method for predicting the performance of MPI applications through
        simulation. Using Simgrid/SMPI simulator, we managed to emulate the High Performance Linpack benchmark at scale
        by applying only a few modifications to its source code. We compared several computation and communication
        models and showed the importance of modeling both the temporal and spatial variability of the platform. In a
        thorough comparison of the simulations with real executions, we show that the prediction error remains very low,
        only a few percent, thereby demonstrating the faithfulness of this approach. Several sensibility analyses are
        then performed to quantify the effect of platform variability and showcase an important use case of simulation.

        The lessons learned during this work are then presented in Part~\ref{part:experiment}. We start by describing the
        experiment engine we developed and that was used throughout this thesis. Then, we present an in-depth report of
        the many experimental biases we faced, including very unsettling phenomenons we did not anticipate. While some
        of these biases can be desirable if they are also occurring in the simulated application, most of them had to be
        suppressed through randomization. Finally, we showcase the performance non-regression test we implemented. While
        not a statistical novelty, they allowed us to detect many changes on Grid'5000 platform that affected
        significantly the performance and could harm experiments if gone unnoticed. We believe the HPC community could
        greatly benefit of such tests.

    \section{Trusting our predictions}%
    \label{sec:prediction_trust}

        Unlike mathematical theorems or algorithms, the correctness of a model like those of Part~\ref{part:prediction}
        cannot be formally proven. The only sound method for validating its faithfulness is to thoroughly try to break
        it, by comparing predictions to reality while methodically changing the configurations. As presented in
        Chapter~\ref{chapter:prediction:validation}, we did cover an extensive range of configurations in our
        validation. Before managing to systematically obtain accurate predictions, we stumbled on many problems which
        caused our predictions to be unrealistic. We had to investigate, understand and overcome these multiple
        obstacles, as reported in Part~\ref{part:experiment}.

        A few weeks before the defense of this thesis, we decided to repeat the whole simulation study from scratch on
        another Grid'5000 cluster named \gros, using 60 of its nodes. This cluster has different nodes (one Intel Xeon
        Gold 5220 processor per node with \NSI{96}{\giga\byte} of memory), a different network (with
        \NSI{25}{\giga\bit/\second} Ethernet) and we used a more recent version of OpenBLAS (resulting in the use of
        AVX512 instructions by the \dgemm function instead of AVX2). Over the course of a weekend, we calibrated the
        platform by measuring the \dgemm and MPI durations. Then, we performed real and simulated HPL executions. At
        first, the predicted performance was too low by one order of magnitude. This was due to a mistake we made: we
        computed the linear regression of the \dgemm model using all the terms of the polynomial, even those of degree
        one (\ie \(M\), \(N\) and \(K\)) which were not statistically significant. This resulted in an overfitted model
        with spurious predictions.  After fixing this issue by only considering the significant terms, we obtained
        extremely accurate predictions of HPL performance for various matrix sizes (see
        Figure~\ref{fig:conclusion:gros_study}).

        \begin{figure}[htpb]
            \centering
            \includegraphics[width=\linewidth]{img/conclusion/validation_gros.pdf}
            \caption{HPL performance: prediction vs. reality for various matrix ranks, using 60 nodes of the \gros
            cluster.}%
            \label{fig:conclusion:gros_study}
        \end{figure}

        Similarly to what we observed in Chapter~\ref{chapter:prediction:validation}, the predictions are more accurate
        with a complex \dgemm model (\ie heterogeneous, stochastic and polynomial)  than with a simpler model (\ie
        homogeneous, deterministic and linear). However, the simpler model still makes reasonably low prediction errors
        here as the \gros cluster has less variability than the \dahu cluster.

        This small additional study demonstrates clearly the level of trust we can now have in our model, but also its
        fragility, as seemingly inoffensive changes in the approach can lead to widely inaccurate predictions.

    \section{Future work}%

        Besides the next steps already discussed in Chapter~\ref{chapter:prediction:conclusion} and
        Section~\ref{sec:test:conclusion}, there also remains a unification work. By going a step further in the
        automation, we could use the data produced by the non-regression tests to generate new model instances for
        Simgrid. It would then be possible to make new simulations with a platform model that reflects the latest
        changes of the real platform. Then, by implementing the same statistical test on the performance predicted by
        the simulation, we should be able to detect whether a platform change has affected the application
        performance and quantify this effect. A minor performance drop of the computation kernels could be amplified by
        the synchronization phases of the application and become very concerning at a larger scale. Conversely, it could
        also be attenuated by the global noise and go completely unnoticed.

        We believe that our predictions could be extremely valuable to the whole life cycle of supercomputers:
        \begin{description}
            \item[Design] Using simulations, manufacturers could apply co-design techniques to construct the most
                performant machines for a given set of target applications and within a given budget. This could help
                achieve more faithful results than the current techniques relying on less accurate simulations or even
                guesswork.
            \item[Development] Simulations could also largely benefit software developers. Both debugging and tuning the
                application are more convenient and less expensive in simulation than in reality, especially if large
                scale runs are required.
            \item[Maintenance] Whenever the platform employees need to perform some maintenance, there is a
                non-negligible risk of affecting the machine performance, as we illustrated in
                Chapter~\ref{chapter:experiment:tests}. To verify that the performance did not change, the usual method
                is to perform large-scale runs of a benchmark such as HPL, which can largely lengthen the maintenance
                duration. A more convenient alternative would be to (1) carry small but carefully designed performance
                tests as those described in Chapter~\ref{chapter:experiment:tests} to check if there is anything
                obviously wrong, and (2) perform large-scale simulations with the updated model and compare the new
                predictions with the previous ones.
        \end{description}


\documentclass{report}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,mathpazo,siunitx,xparse,tikz,enumitem,fancyhdr,pgfplots}

%%Needed to properly display graphs
\pgfplotsset{width=10cm,compat=1.9}

\pagestyle{fancy}
\fancyhf{}
\lhead{Steven Glasford}
\chead{Homework 2}
\rhead{Page \thepage}

\title{Homework 2}
\author{Steven Glasford}
\date{\parbox{\linewidth}{\centering%
    %%Adds the last compiled date
    \today\endgraf\medskip
    Math-451-M001}}

%%Creates a new symbol for plus and minus together
\newcommand{\rpm}{\sbox0{$1$}\sbox2{$\scriptstyle\pm$}
  \raise\dimexpr(\ht0-\ht2)/2\relax\box2 }

%%Creates a nice format for displaying the steps taken
\newlist{steps}{enumerate}{1}
\setlist[steps, 1]{label = Step \arabic*:}

\ExplSyntaxOn
%%new command to round numbers
\newcommand*{\prlen}[1]{%
   % round to 1 digit:
    \pgfmathparse{round(10)/10.0}%
    %\pgfkeys{/pgf/number format/precision=1}
    %\pgfmathresult
    \pgfmathprintnumber[fixed, precision=2]{\pgfmathresult}
}
\ExplSyntaxOff

\begin{document}
%% adds the title to the document
\maketitle
%% adds the table of contents to the document
\tableofcontents

%%Add everything about the first problem here
\chapter{Hydro-Turbine Optimization}
\section{Introduction}
A paper company in Maine operates a hydroelectric generating station on the Penobscot River. Water is piped through from a dam to the power station. The rate at which the water flows through the pipe varies, depending on external conditions. The power station has three different hydroelectric turbine, each with a known (and unique) power function that gives the amount of electric generated as a function of the water flow arriving at the turbine. The incoming water can be apportioned in different volumes to each turbine, so the goal is to determine how to distribute water among the turbines to give the maximum total energy production for any rate of flow. Using experimental evidence and Bernoulli's equation, the following quadratic models were determined for the power output of each turbine, along with the allowable flows of operation:
\begin{align*}
    KW_1 &= (-18.89+0.1277Q_1-\num{4.08e-5}Q_1^2)(170-\num{1.6e-6}Q_T^2)\\
    KW_2 &= (-24.5+0.1358Q_2-\num{4.69e-5}Q_2^2)(170-\num{1.6e-6}Q_T^2)\\
    KW_3 &= (-27.02+0.1380Q_3-\num{3.84e-5}Q_3^2)(170-\num{1.6e-6}Q_T^2)
\end{align*}
$$250 \leq Q_1 \leq 1110, 250 \leq Q_2 \leq 1110, 250 \leq Q_3 \leq 1225$$
where

$Q_i = $ flow through turbine $i$ in cubic feet per second

$KW_i = $ power generated by turbine $i$ in kilowatts

$Q_T = $ total flow through the station in cubic feet per second

\section{Presentation of the Model}
\subsection{Objective}
\hspace{10mm} The objective of this problem is to determine the flow through each turbine needed to create the maximum amount of power.
\subsection{Variables and Constants}

\begin{center}
\begin{tabular}{c c c}
$KW_i$ &$=$ & power generated by turbine $i$ in kilowatts.\\
$Q_i$ & $=$ & flow through turbine $i$ in cubic feet per second.\\
$Q_T$ & $=$ & total flow through the station in cubic feet per second.\\
$P$ & $=$ & total power generated.

\end{tabular}
\end{center}

\subsection{Assumptions}
\begin{align*}
    KW_1 &= (-18.89+0.1277Q_1-\num{4.08e-5}Q_1^2)(170-\num{1.6e-6}Q_T^2)\\
    KW_2 &= (-24.5+0.1358Q_2-\num{4.69e-5}Q_2^2)(170-\num{1.6e-6}Q_T^2)\\
    KW_3 &= (-27.02+0.1380Q_3-\num{3.84e-5}Q_3^2)(170-\num{1.6e-6}Q_T^2)
\end{align*}
\begin{align*}
    250 &\leq Q_1 \leq 1110\\
    250 &\leq Q_2 \leq 1110\\
    250 &\leq Q_3 \leq 1225
\end{align*}
$$Q_T=Q_1+Q_2+Q_3$$
$$P = KW_1+KW_2+KW_3$$

\section{Solving the Model}
We will be using Lagrange Multipliers to find the values for the individual flow (as functions of $Q_T$) that maximize the total energy production $KW_1+KW_2+KW_3$ subject to the constraints $Q_1+Q_2+Q_3=Q_T$ and the domain restrictions on each $Q_i$.

But first we must find the objective function, which is the function we are trying to optimize. In this case it is the function $P$.
$$P = KW_1+KW_2+KW_3$$
Then we must populate this function using the data we are concerned about, we are not concerned with the optimum power generated with respect to the total power outputs of each individual turbine, instead we want to optimize with respect to the flow rates to each individual turbine. This makes the power function look more like this

\begin{multiline}
$P = (-18.89+0.1277Q_1-\num{4.08e-5}Q_1^2)(170-\num{1.6e-6}Q_T^2) + (-24.5+0.1358Q_2-\num{4.69e-5}Q_2^2)(170-\num{1.6e-6}Q_T^2) + (-27.02+0.1380Q_3-\num{3.84e-5}Q_3^2)(170-\num{1.6e-6}Q_T^2)$
\end{multiline}

Lagrange Multipliers have the form:
$$\nabla f = \lambda \nabla g,$$

where $f$ is our objective function and $g$ is the constraint equation. In this problem our constraint equation is $$Q_T = Q_1 + Q_2 + Q_3$$ and $$f = P,$$ but before we continue we must replace the all of the $Q_T$ in the objective equation with the variable $Q_1, Q_2, Q_3$ which isn't difficult since the constraint equation already does this step for us.

\vspace{5mm}

\begin{tabular}{c c}
$P =& (-18.89+0.1277Q_1-\num{4.08e-5}Q_1^2)(170-\num{1.6e-6}* \\
&(Q_T)^2)+ (-24.5+0.1358Q_2-\num{4.69e-5}Q_2^2)* \\
&(170-\num{1.6e-6}(Q_T)^2) \\
&+ (-27.02+0.1380Q_3-\num{3.84e-5}Q_3^2)*\\
&(170-\num{1.6e-6}(Q_T)^2)$
\end{tabular}

%(170-w^2/625000)*(-(51*x^2)/1250000+(1277*x)/10000-1889/100)+(170-w^2/625000)*(-(3*z^2)/78125+(69*z)/500-1351/50)+(170-w^2/625000)*(-(469*y^2)/10000000+(679*y)/5000-49/2)

\vspace{5mm}

We shall try to find the extrema for P the old fashion way, by simply finding the gradient of P, then setting the gradient to 0 and finding min and maxes. To make our lives easier we will assume that $Q_T$ is a constant, which will end up making life much, much easier in the long run.
$$\nabla P = \left\langle\frac{\partial P}{\partial Q_1},\frac{\partial P}{\partial Q_2},\frac{\partial P}{\partial Q_3}\right\rangle$$

Now we must find the partials:

$$\frac{\partial P}{\partial Q_1} = \dfrac{\left(Q_T^2-106250000\right)\left(102Q_1-159625\right)}{781250000000}$$

$$\frac{\partial P}{\partial Q_2}=\dfrac{7\left(Q_T^2-106250000\right)\left(67Q_2-97000\right)}{3125000000000}$$

$$\frac{\partial P}{\partial Q_3} = \dfrac{3\left(Q_T^2-106250000\right)\left(8Q_3-14375\right)}{195312500000}$$

\vspace{5mm}

The roots of P:
$$\nabla P = \left\langle \dfrac{159625}{102},\dfrac{97000}{67},\dfrac{14375}{8}\right\rangle$$
Or more approximately:
$$\nabla P \approx \left\langle1564.95098,1447.76119,1796.875\right\rangle$$

However, this extrema is outside our bounds for all of the variables so we cannot use this method of finding the gradient and the roots of the gradient. So we must now use Lagrange multipliers.

\vspace{5mm}
Lagrange multipliers are in the form $$\nabla f = \lambda \nabla g,$$ where $f$ is our objective equation ($P$) and $g$ ($Q_T$) is out constraint equation and $\lambda$ is our Lagrange multiplier.

We have already found $\nabla P$ so we must now find the gradient of $Q_T$ The gradient of $Q_T$
$$\nabla Q_T = \left\langle\frac{\partial Q_T}{\partial Q_1},\frac{\partial Q_T}{\partial Q_2},\frac{\partial Q_T}{\partial Q_3}\right\rangle$$ which boils down to $$\nabla Q_T = \left\langle1,1,1\right\rangle$$

Now we can set the two equations equal to each other:

$$\frac{\partial P}{\partial Q_1} = \dfrac{\left(Q_T^2-106250000\right)\left(102Q_1-159625\right)}{781250000000}=\lambda$$
$$\frac{\partial P}{\partial Q_2}=\dfrac{7\left(Q_T^2-106250000\right)\left(67Q_2-97000\right)}{3125000000000}=\lambda$$
$$\frac{\partial P}{\partial Q_3} = \dfrac{3\left(Q_T^2-106250000\right)\left(8Q_3-14375\right)}{195312500000} = \lambda$$

and $$Q_T=Q_1+Q_2+Q_3$$

Now we want to solve for $\lambda$

$$Q_1 = \frac{15925Q_T+781250000000\lambda -1692031250000}{102Q_T-10837500000}$$
$$Q_2 = \frac{679000Q_T + 3125000000000\lambda - 72143750000000}{469Q_T^2-49831250000}$$
$$Q_3 = \frac{43125Q_t^2+195312500000\lambda - 4582031250000}{24Q_T^2-2550000000}$$

Put these equations into the original $Q_T$ equation and solve for $\lambda$

$$\lambda = \frac{7\left(2733Q_T-92963275\right)\left(Q_T^2-106250000\right)}{4297851562500000}$$

Plugging $\lambda$ back into the original $Q_i$ equations and then simplifying we get:

$$Q_1 = \frac{7501Q_T}{22005}-\frac{26500495}{26406}$$

$$Q_2=\frac{2176Q_T}{7335}+\frac{1931560}{4401}$$

$$Q_3=\frac{7973Q_T}{22005}+\frac{14911135}{26406}$$

Now we graph the function between the bounds of each variable and try to find some intersection points between the $Q_i$ functions:

\begin{tikzpicture}
        \begin{axis}[
            axis lines = left,
            ylabel = Flow,
        ]

        \addplot[
            domain=225:1225,
            samples=100,
            color=green,
        ]{abs(-.3408770734*x+1003.57854276)};
        \addlegendentry{$\left|Q_1\right|$}
        \addplot [
            domain=225:1225,
            samples=100,
            color=red,
        ]{(.29665985003)*x+438.8911611};
        \addlegendentry{$Q_2$}

        \addplot[
            domain=225:1225,
            samples=100,
            color=blue,
        ]{(.36232674392)*x+564.687381656};
        \addlegendentry{$Q_3$}

        \end{axis}
    \end{tikzpicture}

 %   Then the optimized version of this model should be at $$790.827$$ $$Q_2=701.653$$ $$Q_3=746.24$$ for a total power generation of 16622.69864 Kilowatts.

  %  But then I started to think about it. Logically if you have a turbine, that turbine should generate the most amount of power when it is doing the most amount of work, which would logically place the max value at the max boundary for each individual turbine, which means the max values should be at $$Q_1=1110$$ $$Q_1=1110$$ $$Q_3=1225$$ and if you put those values into the calculator you get an even higher value than you would get from the the other values. In particular you get a total power generation of 23155.92823 kilowatts, which is obviously greater than 16622.69864, so this is a bigger maximum, and a very obvious maximum.

%$$Q_1 = -z-y \pm %2500\cdot\sqrt{17}$$

%and
%$$Q_1 = \dfrac{\sqrt{2}\sqrt{-19584Q_3^2+70380000Q_3-23919Q_2^2+69258000Q_2+15051181250} \pm 319250}{204}$$

%$$Q_2 = -Q_3-Q_1 \pm 2500\cdot\sqrt{17}$$
%and
%$$Q_2 = \dfrac{2\cdot\sqrt{14}\sqrt{-3216Q_3^2+11557500Q_3-3417Q_1^2+10694875Q_1+2336037500} \pm 679000}{469}$$

%$$Q_3 = -Q_2-Q_1 \pm 2500\cdot\sqrt{17}$$
%and
%$$Q_3 = \dfrac{\sqrt{6}\sqrt{-469Q_2^2+1358000Q_2-408Q_1^2+1277000Q_1+535743750}\pm 86250}{48}$$

%As you may have noticed, each axis has a root something with $\pm 2500\cdot\sqrt{17}$, these would be nice to use if they pass all of the constraints of the problem, however, they fail $Q_T=Q_1+Q_2+Q_3$ since you can rearrange any of those equations to be in the form $$\pm 2500\cdot\sqrt{17} = Q_1 + Q_2 + Q_3$$ So these equations cannot be used if you consider that $750 \leq Q_T \leq 3445$, which are the combined bounds of $Q_1,Q_2,Q_3$ and $\pm 2500\cdot\sqrt{17}$ is far from being in that bound.

%%$$P = (-18.89+0.1277Q_1-\num{4.08e-5}Q_1^2)(170-\num{1.6e-6}Q_T^2) + (-24.5+0.1358Q_2-\num{4.69e-5}Q_2^2)(170-\num{1.6e-6}Q_T^2) + (-27.02+0.1380Q_3-\num{3.84e-5}Q_3^2)(170-\num{1.6e-6}Q_T^2)$$

%%$$P = (-18.89+0.1277x-4.08*10^-5*x^2)(170-1.6*10^-6*(x+y+z)^2) + (-24.5+0.1358y-4.69*10^-5*y^2)(170-1.6*10^-6*(x+y+z)^2) + (-27.02+0.1380z-3.84*10^-5*z^2)(170-1.6*10^-6*(x+y+z)^2)$$

%\section{Discussion of Results}
%\subsection{Verification}
%To verify that this is in fact the optimal flow rate to each turbine we will try some nearby distributions.

%If we try the points (1110,1110,1224), (1109,1110,1225), (1110,1109,1225), (1109,1109,1224) which are all points a little less than the max we get the following distributions

%\begin{center}
%\begin{tabular}{c c}
%     $P(1110,1110,1224)=$& 23150.97440\\
%%     $P(1109,1110,1225)=$& 23157.57594\\
%     $P(1110,1109,1225)=$& 23152.82133\\
%     $P(1109,1109,1224)=$& 23149.51208
%\end{tabular}
%\end{center}

%all of these points are less than the max, making the (1110,1110,1225) a max

\section{More Information}

\subsection{Turbine Distribution for a Predetermined Max Flow Rate}
If the incoming flow never goes beyond 2500 cubic feet per second, the flow must be distributed accordingly to maximize the power generated. As shown in the graph, $Q_2$ maxes at 701.653 and $Q_3$ at 74.24, we then allow the remaining water to flow through $Q_1$ this will result in the max for the situation.

\subsection{More Information}

\hspace{10mm} \emph{Turbines to be used if only two are allowed to operate}

If we were to have 1500 cubic feet per second, I would recommend using the $Q_2$ and $Q_3$ due to these ones generating the most amount of power individually.

\subsection{Recomendation of When the Flow Rate is Near the Hypothetical Maximum Flow Rate of Each Turbine}

If there was an incoming flow rate of 3400 cubic feet per second I would recommend allowing the maximum allowed flow through both $Q_2$ and $Q_3$, and then allowing the rest of the water to go through $Q_1$, this would generate the greatest amount of power for the situation.

\section{Conclusion}
Overall, the best point for the water distribution is when $Q_1 \approx 790.827$, $Q_2 \approx 701.53$ and $Q_3 = 24.24$ for $\approx$ of 16622.984 kilowatts.

\vspace{5mm}

\hspace{5mm} Let's say that the company discovers that it is sometimes advantageous to only use two turbines, and the incoming flow is 1500 cubic feet per second, the company should use the turbine x and turbine y to generate the most power
\vspace{5mm}

\hspace{5mm} If the incoming flow is 3400 cubic feet per second, the company should take the following action.

%%Add everything about the second problem here
\chapter{Advertising Budget Analysis for a Personal Computer Manufacturer}
\section{Introduction}
\emph{This is a problem can be found on page 52 number 6 of \textit{Mathematical Modeling, Fourth Edition} by Mark M. Meerschaert.}

\vspace{5mm}
A manufacturer of personal computers currently sells 10,000 units per month of a basic model. The cost of manufacture is \$700/unit, and the wholesale price is \$950. During the last quarter the manufacturer lowered the price \$100 in a few test markets, and the result was a 50\% increase in sales. The company has been advertising its product nationwide at a cost of \$50,000 per month. The advertising agency claims that increasing the advertising budget by \$10,000/month would result in a sales increase of 200 units/month. Management has agreed to consider an increase in the advertising budget to no more than \$100,000/month.

\section{Presentation of the Model}
\subsection{Objective}
Will try to find a price and the advertising budget size that will maximize the total revenue for this manufacturing company.

\subsection{Variables and Constants}
\begin{tabular}{c c}
    $R= $ & revenue (\$)\\
    $P= $ & profit (\$)\\
    $C= $ & costs (\$)\\
    $U= $ & units of personal computers\\
    $B= $ & advertising budget (\$/month)\\
    $S= $ & selling wholesale price per unit\\
    $D = $& price drop\\
    $B_i = $& budget increase\\
    $C_m=700=$ & cost to manufacture per unit (in dollars)  \\
    $B_0=50000=$ & initial advertising budget size\\
    $B_m=100000=$ & max advertising budget\\
    $U_0 = 10000=$ & initial number of units sold\\
    $S_0 = 950=$ &initial wholesale price
\end{tabular}

\subsection{Assumptions}
\begin{center}
\begin{tabular}{c}
    $P=R-C$   \\
    $p=S_0-D$\\
    $R = UP$\\
    $C= B + C_m*U$\\
    $B = B_0 + B_i$\\
    $U=U_0+(950-S)*50 + \frac{b-B_0}{U_0}*200$\\
    $B_0 \leq B \leq B_m$\\
    $700\leq P \leq 950$

\end{tabular}
\end{center}

\emph{objective:} Maximize Profits

%Notice how the equation for $U$ has two main components, the next component is the increase of sets sold as the budget for advertising increases which is a linear component since for every dollar increase the number of sets grows at a known amount, in this case by 200. Then there is a quadratic function with very interesting, seemingly random coefficients. This part of the equation was found using a calculator doing linear regressions on the points:
%\begin{center}
%\begin{tabular}{c}
 %   (950,10000)\\
  %  (850,15000)\\
   % (750,22500)
%\end{tabular}
%\end{center}

%I chose those points due to the 50\% increase of sets purchased as a \$100 decrease in price. I then put these points into the calculator to find a regression between all of them. I could have chosen to use a more exact regression and more points (this would also reduce the overall amount of error in the model, however I felt that this regressed version might be easier to have a calculator use later on in the problem. I chose to do a quadratic regression because the correlation between the points and the function is 1. I could have used a cubic or quadratic regression with added points, however I felt that those would have added too much complexity.

\section{Solution to Model}
In order to proceed we need to obtain our objective function

%We will model this as a constrained optimization problem, and solve it using the method of Lagrange multipliers.

%First we must make a uniform objective equation, which uses the variables $B$ and $S$:

$$P=R-C$$

$$\left(10000+(950-p)50+\frac{B-50000}{10000}\cdot200\right)p-\left(B-\left(10000+(950-p)50+\frac{B-50000}{10000}\cdot200\right)700\right)$$

which reduces to: $$P=\left(10000+(950-p)50+\frac{B-50000}{10000}\cdot 200\right)(p-700)-B$$

Without showing it, we have determined that this problem cannot be solved by setting the gradient to zero and solving for the roots, doing that just gives us values outside our bounds. So we shall use Lagrange Multipliers

$$\nabla P = \left\langle-100p+91500+.01B,.02p-15\right\rangle$$

We solve using Lagrange by $$\nabla f = \lambda \nabla g$$

where $\nabla f$ is our objective equation (which is $P$) and $\nabla g$ is our constraint value:

$$-100p+91500+.02B = 0$$
$$.02p-15 = \lambda$$

Solving this for when $B$ is at a minimum (10000)

$$p=935$$
$$\lambda = 3.7$$
and
$$P = 261250$$

Solving for when $B$ is at a maximum we get

$$B = 100000$$
$$P(950,10000) = 2650000$$

\section{Sensitivity Analysis}
%This is part 2 of the original problem
We will now determine the sensitivity of the decision variables (price and advertising) to price elasticity.

We will assume that $e$ is our price elasticity, we then obtain an equation $$P(p,B,e) = (10000 +e(950-p) + .02(B-50000))(p-700)-B$$

Now we take the corresponding partials from the equation above:

\begin{center}
    \begin{tabular}
    $\dfrac{\partial P}{\partial p}=-e(p-700)+9000+100e(950-p)+.02a$\\
    $\dfrac{\partial P}{\partial B}=.02p-15$
    \end{tabular}
\end{center}

Now we use Lagrange Multipliers method to obtain the equation:
$$\frac{\partial P}{\partial p} = 0$$
$$\frac{\partial P}{\partial B}=\lambda$$

by using $B=100000$ we get the values of $p$ and $\lambda$:

$$P = \dfrac{275(3D+20)}{e}$$
$$\lambda = \frac{1}{2}\left(\dfrac{3e+220}{e}\right)$$

Evaluating when $p=935$, $B=100000$ (our max point), $e=50$
$$S(p,e) = \dfrac{dp}{de}\cdot \dfrac{e}{p}=-.12$$

$$S(B,e)=\dfrac{dB}{de}\cdot \dfrac{e}{p}$$

What this means is that a 10\% increase in the price elasticity the company would notice a 1.2\% decrease in price but that the advertising budget would not be affected.

\vspace{5mm}
%This is part 3 of the original book problem
\emph{The advertising agency estimates that the company will gain 200 new sales each time the advertising budget is increased by \$10,000 per month. The sensitivity analysis is the following:}

This new assumption gives us the following equations:

$E = $ estimate of new sales per \$10,000 increase

\begin{center}
    \begin{tabular}{c}
        $P(p,B,E)=(10000+50(950-p) + \dfrac{E}{10000}(B-50000))(p-700)-B$\\
        $\dfrac{\partial P}{\partial p}=-100p+91500+\dfrac{E}{10000}(B-50000)$\\
        $\dfrac{\partial P}{\partial B} = \dfrac{E}{10000}(p-700)-1$
    \end{tabular}
\end{center}

By once again using the Lagrange multiplier method, we set the first partial to zero, and the second to 1; this gives us the following:

$$p = .25 +.05E$$
$$B=100000$$
$$\lambda = \dfrac{9E}{400}+\dfrac{E^2}{20000}-1$$

Using the max point $p=935$ and $B=100000$ as well as using the point $E=200$ we obtain:

$$S(p,e)=\dfrac{dp}{de}\cdot \dfrac{e}{p}=-.12$$

$$S(B,e)=\dfrac{dB}{de}\cdot \dfrac{e}{B}=0$$

What this means is that when a 10\% increase in the price elasticity would result in a 1.2\% decrease in the profit, and the advertising budget would remain.

\section{Conclusion}
%need to describe what \lambda is. This is part 4 of the original problem
In conclusion, the best price to sell the units are at \$935 and the best size for the advertising budget is \$100000, this would give the company a total profit of about \$2650000.

With or without the price elasticity we discovered that a 10\% increase in price would result in a 1.2\% decrease in price, with no affect on the advertising budget.

\end{document}


% !TeX spellcheck = en_US
% !TeX root = DynELA.tex
%
% LaTeX source file of DynELA FEM Code
%
% (c) by Olivier Pantalé 2020
%
\chapter{Theory}

\startcontents[chapters]
\printmyminitoc[1]\LETTRINE{T}he \DynELA~is an Explicit FEM code written in \Cpp~using a Python's interface for creating the Finite Element Models.

\section{Introduction}

\begin{tcolorbox}[width=0.95\textwidth,myTab,tabularx={l||C|C|C|C|C},title=Homogeneous system of units in mechanics]%,boxrule=0.5pt]
              & Dimension        & SI (MKS)   & SI (mm-s)  & SI (mm-kg)  & SI (mm-kg-s) \\\hline\hline
Length        & $L$              & $m$        & $mm$       & $mm$        & $mm$        \\\hline
Weight        & $M$              & $kg$       & $T$        & $kg$        & $kg$        \\\hline
Time          & $T$              & $s$        & $s$        & $ms$        & $s$         \\\hline
Stress        & $ML^{-1}T^{-2}$  & $Pa$       & $MPa$      & $GPa$       & $kPa$       \\\hline
Force         & $MLT^{-2}$       & $N$        & $N$        & $kN$        & $mN$        \\\hline
Energy        & $ML^{2}T^{-2}$   & $J$        & $mJ$       & $J$         & $MJ$        \\\hline
Density       & $ML^{-3}$        & $kg/m^{3}$ & $T/mm^{3}$ & $kg/mm^{3}$ & $kg/mm^{3}$ \\\hline
Speed         & $LT^{-1}$        & $m/s$      & $mm/s$     & $mm/ms$     & $mm/s$      \\\hline
Angular speed & $T^{-1}$         & $s^{-1}$   & $s^{-1}$   & $ms^{-1}$   & $s^{-1}$    \\\hline
Acceleration  & $LT^{-2}$        & $m/s^{2}$  & $mm/s^{2}$ & $mm/ms^{2}$ & $mm/s^{2}$  \\\hline
Couple        & $ML^{2}T^{-2}$   & $N.m$      & $N.mm$     & $kN.mm$     & $mN.mm$
\end{tcolorbox}


\section{FRP}

The most common solution for the construction of reactive systems in an imperative setting are call-back frameworks, embedded into a loop.
The call-backs are either used to query the state of variables, or to change them.
This imperative approach is well suited for rapid prototyping of small systems.
However, tracing behaviors over time quickly becomes unmanageably complex for larger systems.

Functional Reactive Programming instead introduces a concrete abstraction of time that allows the programmer to safely manipulate time-varying values.
The key abstraction is given by a \textit{signal}, providing the programmer with a simple type interface:

\begin{lstlisting}
  type Signal a = Time -> a
\end{lstlisting}

For example, the type \texttt{Signal Image} represents a video, while \texttt{Signal Steer} captures a steering wheel operated over time.
To better understand how our library works, we now introduce the basic concepts and terminology from FRP.

\subsection{Arrowized FRP}

There are many types of FRP based on different abstractions from type theory.
Expressive abstractions, such as monads, allow for complex manipulation of signal flows~\cite{van2014monadic}.
However, for most applications they are far too expressive.
We instead focus on an FRP library, Yampa, which uses the arrow abstraction, or so called Arrowized FRP~\cite{hudak2003arrows}.
Arrows generally run faster and with little need for manual optimization~\cite{yallop2016causal}, but are fundamentally less expressive than a monadic FRP~\cite{lindley2011idioms}.
This more restrictive language is in fact a benefit, as it makes it harder for the programmer to introduce errors.
As we will see in the sequel, Yampa is still powerful enough to write complex controllers to drive an autonomous vehicle, or even to communicate with other vehicles.
At the same time, the syntax is clear and accessible enough to make for an easy introduction to the FRP paradigm.

Along with signals, Yampa also introduces the abstraction of a \textit{signal function (SF)}.
This is a transformer from one signal to another.

\begin{lstlisting}
  type SF a b = Signal a -> Signal b
\end{lstlisting}

\noindent Using the previous signals, imagine a type for a steering function, which operates based on a video stream, such as

\begin{lstlisting}
  turn :: SF Image Steer
\end{lstlisting}

\noindent This function processes video and uses it to decide how to steer.
We omit an implementation, as the details of the data transformation are not relevant to the structure of the FRP code.

Haskell provides special syntax for Arrowized FRP, which mimics the structure of control flow charts.
The syntax provides a composition environment, in which the programmer just manages the composition of arrow functions.
Inputs are read in from the right hand side, and piped to the left hand side (\texttt{output <- function -< input}).
A demonstration is given in Listing~\ref{lst:arrows}.

The example introduces
%
\begin{lstlisting}
  avoid :: (Image, Steer) -> Steer
\end{lstlisting}
%
a pure function that adjusts the basic steering plan based on the image to avoid any obstacles.
In Listing~\ref{lst:arrows}, this \texttt{avoid} function is lifted to the signal level using:
%
\begin{lstlisting}
  arr :: (a -> b) -> SF a b
\end{lstlisting}
%
The function \texttt{turn} is already on the signal level (has an SF type). Hence, we do not need to lift it.

\begin{lstlisting}[float,floatplacement=h!,caption=Basic Arrowized FRP syntax,label=lst:arrows]
myDriver :: SF Image Steer
myDriver = proc image -> do
  basicSteer    <-     turn  -< image
  adjustedSteer <- arr avoid -< (image, basicSteer)
  returnA -< adjustedSteer
\end{lstlisting}

\subsection{Stateful FRP}

To avoid obstacles on the road, we might write an \texttt{avoid2} function as shown in Listing~\ref{lst:loop}, which requires two images to calculate the adjusted steering command.
For this, we need a mechanism to maintain state between each processing step.
Two images would be necessary to filter noise in the image, or calculates the velocity of an approaching obstacle.
To implement it, we use an abstraction called \texttt{ArrowLoop} to  save the previous state of the image for the next processing step.
The syntax is presented in Listing~\ref{lst:loop}.
Intuitively, \texttt{ArrowLoop} gives us a recursive computation, as also indicated by the \texttt{rec} keyword\footnote{We elide the technical details for the purposes of this presentation and refer the interested reader to~\cite{paterson2001icfp}.}.

\begin{lstlisting}[float,caption=Using ArrowLoop to send feedback,label=lst:loop]
myDriver :: SF Image Steer
myDriver = proc image -> do
  rec
    oldI          <- iPre null  -< image
    basicSteer    <-      turn  -< image
    adjustedSteer <- arr avoid2 -< (image, oldI, basicSteer)
  returnA -< adjustedSteer
\end{lstlisting}

The predefined function \texttt{iPre} takes an initial state, in our case an empty image, and saves images for one time step, each time it is processed.
This way, we create a feedback loop that is then used in the updated \texttt{avoid} function.
At the same time, the \texttt{rec} keyword is used to denote a section of arrow code with  mutual dependencies\footnote{Without the keyword, there is an unresolvable dependency loop.}.