\label{chapter:bdp}

Scheduling an event for a group of invitees is a frustrating task; it tends to be tedious and time consuming.
A typical scheduling process can be described as iterative approval voting:
An event organizer selects a candidate set of date/time options, and asks invitees to respond with their availability.
Given the responses, the organizer chooses an agreeable option and announces it, or she may repeat the process by proposing another set of options if no feasible option is found.
Naturally the organizer and her invitees wish to reach an agreement within a small number of iterations and proposed options -- the more iterations and proposed options there are, the more laborious a scheduling process becomes.

There exist several software tools that are designed to help an event organizer handle a scheduling process more efficiently -- one of the most well-known tools is Doodle~\footnote{http://www.doodle.com}.
In Doodle, an organizer can simply list as many date/time options as she likes,
and each invitee is asked to respond with her availability.
Essentially, invitees participate in approval voting upon all proposed options.
Hence if too many options are proposed, then invitees are given the burden of answering them all.
This often leads to undesired behaviors of invitees such as herding or procrastination, instead of honest, quick responses~\cite{zou2015strategic}.
On the other hand, if the organizer proposes only few options, there may not exist an agreeable outcome after all, which may result in another iteration of proposals and responses.
In fact, surveys find that the most challenging part of group scheduling is due to ``chasing people who do not answer'' and ``finding a suitable time.''~\footnote{http://en.blog.doodle.com/2012/07/26/new-findings-a-small-number-of-initiators-organize-most-of-the-meetings/}

Doodle has many practical advantages.
One of them is its simplicity -- invitees simply need to approve a subset of options based on their availability.
Another is a short duration of scheduling process -- the duration it takes until
the last invitee responds and the meeting time is settled. Each invitee
needs to respond only once, which limits the degree to which the
process is hijacked by invitees' delayed responses. But Doodle has many
drawbacks, even in this idealized setting. In particular, Doodle
forces the invitees to examine many potential date/time options. This can be
inconvenient not so much due to the effort involved (though that is a
factor), but mostly because invitees need to block their available slots
off until a option is announced. We use the expected number of time
slots floated by the organizer as a proxy for this inconvenience.

To avoid incurring much inconvenience, the organizer can select only a few options,
and poll the invitees about those. If a feasible option is not found
among them, then repeat with another batch of date/time options.
We call this broad class of mechanisms \emph{B-Doodle} (for ``Batched Doodle").
Clearly, Doodle is a special case with one batch consisting of all
options. Another extreme case is the OAAT (one-at-a-time)
mechanism, in which the organizer tests a single option at each
iteration. Doodle minimizes the total number of iterations, whereas
OAAT minimizes (expected) inconvenience caused by the scheduling process.
In-between lie many other mechanisms, with different
batching schemes, that trade off time against inconvenience
differently.

Figure~\ref{fig:bdp:Pareto_scatter} illustrates this via a simple example.
In this scenario there are six options, four invitees, each of whom
is available at each option independently with probability $.8$.
The figure depicts a scatter plot of all 32 different B-Doodle mechanisms,
including Doodle and OAAT. The vertical axis depicts the expected
number of rounds to determine the option, and the horizontal axis
the expected inconvenience.

\begin{figure}[h!] \small
\centering
\includegraphics[scale=0.45]{plots/pareto_scatter_fin.eps}
\caption{A scatter plot of B-Doodle Mechanisms.}
\label{fig:bdp:Pareto_scatter}
\end{figure}

We can clearly observe a time-inconvenience Pareto frontier in this
plot. If in addition there is an overall cost function combining time
and inconvenience, one can identify an optimal B-Doodle mechanism
along this frontier as illustrated in
Figure~\ref{fig:bdp:Pareto_objective}. In this example, if the overall
cost is the linear function 3$\cdot$\Time+\Inconvenience, the optimal
mechanism happens to be the ``Half-n-half" mechanism; this mechanism
sends out $3$ options in the first batch, and if no feasible time
slot is found then sends out the remaining $3$ options in the next
batch.

\begin{figure}[h!] \small
\centering
\includegraphics[scale=0.45]{plots/pareto_objective_fin.eps}
\caption{Pareto-frontier and objective function.}
\label{fig:bdp:Pareto_objective}
\end{figure}

In this chapter we will investigate the difficulty of determining the
optimal B-Doodle mechanism, and to what degree it improves on the
simple Doodle in realistic scenarios.
Under the assumption that the set of events in which an invitee is available for a particular option is mutually independent, we provide an efficient recursive algorithm for computing the
optimal batching scheme, for a broad class of objective functions of
time and inconvenience, including the linear combination as in the
above example.\footnote{As another, more minor generalization of the
problem, we will allow that the organizer is content with only a
fraction of the invitees attending, not necessarily requiring everyone be
available. This fraction will be a part of input to the problem; of
course, as a special case, 1 implies full attendance.}

Lastly, we assume that the event organizer is given probability estimates on availability of agents, but it is not clear how one can obtain such probabilities.
 Probability estimation is an interesting and challenging research question on its own, and we do not attempt to solve the question in this work. However, we provide several plausible methods for estimating the probabilities in the context of group scheduling, which can enable our model and algorithm to be deployed as a real-world application in the future.
 In the psychology literature, Mann et al. found that cultural differences between the Western, individualistic countries (such as the United States) and the Eastern, collectivistic countries (such as China and Japan) lead to different behaviors of respondents when it comes to a group-decision making process~\cite{mann1998cross}.
 More recently, Reinecke et al. analyzed more than 1.5 million Doodle date/time polls from 211 countries, and confirmed similar findings regarding time perception and group's behavior~\cite{reinecke2013doodle}. Among others, they found that ``in comparison to predominantly individualist societies, poll participants from collectivist countries respond earlier, agree to fewer options but find more consensus,'' which agrees with the findings of Mann et al.
 Besides the cultural differences, Doodle's own surveys on event scheduling found that people tend to respond to the scheduling surveys on Mondays, while Monday is the least popular day for having a meeting.~\footnote{http://en.blog.doodle.com/2012/05/23/mondays-for-planning-busy-weekends/}
 We believe that these studies and findings can be used to design a reasonable estimator for availability of agents, by utilizing the features that are known to be crucial -- such as demographics of the group and purpose of the event being scheduled.
 Recent work by Zou et al. analyzed over 340,000 Doodle polls data to study behavioral patterns of the users, and they were able to identify response functions that match the response patterns observed in the real data~\cite{zou2015strategic}. We believe that a similar approach can be taken to tackle the problem of probability estimation in the context of group scheduling.

\section{Notation and Definitions}

% \subsection{Problem Setting}
We mentioned two dimensions of optimality in the scheduling process: \Time\ and \Inconvenience.
\Time\ captures the duration of the scheduling process and \Inconvenience\ measures how much inconvenience is caused for each invitee during the scheduling process.
In this section we formally define the class of B-Doodle mechanisms and the Batched Doodle Problem (\BDP).

Consider a setting where there are $n$ invitees and $s$ date/time options from which the organizer can choose to propose. The organizer wishes to find a {\em feasible} date/time option that works for at least $\lceil f \cdot n \rceil$ invitees (we call $f\in [0,1]$ the {\em feasibility threshold}) or determines that there is no feasible option.
We model the uncertainty of availability of invitees as a random matrix as follows.
Consider a matrix of mutually independent Bernoulli random variables where rows represent invitees and columns represent a set of date/time options.
Given probability of success for each Bernoulli random variable, the organizer can ``inspect'' a batch of columns at once to know of the realization of those entries. This corresponds to polling invitees' availability for a batch of date/time options. The organizer wishes to determine with certainty whether the matrix contains a feasible column or it does not. Using the random matrix model, we first investigate interesting properties of an optimal solution, and then discuss how it performs better than the classic Doodle under various settings.

 \begin{definition}[Feasibility]
 Let $A$ be a matrix whose entries are from $\{0,1\}$, and refer to the entry of $A$ at row $r$ and column $c$ as $a_{r,c}$.
 We say that a column $c$ of $A$ is {\em feasible} if it consists only of 1's (otherwise it is {\em infeasible}).
 We say that $A$ is {\em feasible} if it contains at least one feasible column (otherwise it is {\em infeasible}).
 \end{definition}

The organizer iteratively sends out a batch of options until a feasible option is found. In our setting \Time\ spent by the scheduling process is measured by the number of iterations and \Inconvenience\ caused is measured by the number of options that have been sent out by the organizer.
Let us define a class of B-Doodle mechanisms that describe how the organizer sends out options in each iteration.
\begin{definition}[B-Doodle Mechanism]\label{def:bdp:BDoodleMechanism}
Let $S = \{1, 2, \dots, s\}$ be a set of $s$ options.
We define a B-Doodle mechanism for $S$ as an ordered partition of $S$.
Let $B = \langle S_1, S_2, \dots, S_m \rangle$ be a partition of $S$ into $m$ subsets such that $S_j \neq\emptyset$, $S_j \cap S_k = \emptyset$ for $j \neq k$, and $\cup_{l=1}^{m} S_l = S$ where $1 \leq j,k \leq m$.
We define $b_j = |S_j|$ for all $j \leq m$ and call $b_j$ the size of the $j$-th batch.
We write $B_m$ to emphasize that $B$ has $m$ batches.
\end{definition}

We interpret a B-Doodle mechanism $B$ as follows: the organizer sends out options in $S_1$ during the first iteration. If a feasible option is found, the process ends. Otherwise she sends out the next batch, $S_2$, and so on.
Note that there exist exponentially many B-Doodle mechanisms for any a given $S$ (exponential in cardinality of $S$).

The goal is to find a B-Doodle mechanism that minimizes the expected cost of scheduling process, given an objective function of \Time\ and \Inconvenience.
Earlier we considered a simple cost function that is a linear combination of the two.
While this cost function fits in many realistic situations, we want to explore a larger class of cost functions.
We define a class of cost functions that depend only on the number of iterations and batch sizes.
\begin{definition}[Cost function] \label{def:bdp:CostFunction}
	A cost function $c$ takes two integers $j$ and $b$ as arguments, and $c(j, b) > 0$ describes the aggregate cost of \Time\ and \Inconvenience\ that is incurred by sending out a batch of $b$ options during the $j$-th iteration. We assume that cost is additive so that the overall cost of executing the first $j$ iterations of ${B}_m = \langle S_1, S_2, \dots, S_m \rangle$ is simply the sum, $\sum_{k=1}^{j} c(k, b_k)$, which we denote by $C(j, {B}_m)$; recall that $b_k = |S_k|$.
A cost function $c$ is said to be $\theta$-\emph{simple} if there exists some constant $\theta>0$ such that $c(j, b) = \theta \cdot c(j-1, b)$ for all $j > 1$ and for all $b \geq 1$.
We often drop $\theta$ and just state that a cost function is \emph{simple}, for brevity.
\end{definition}
It is reasonable to assume that cost is additive (with respect to iterations) because an additional iteration adds the time spent and inconvenience caused for the invitees.

Note that $C(j, B_{m})$ is strictly increasing in $j$ for any fixed $B_{m}$ because $c(j, b) > 0$ for any $j$ and $b$. While the class of simple cost functions may seem too restrictive, we present a few natural choices of cost functions that belong to the class of simple cost functions. In this work we assume that the underlying cost function is simple; further we assume that $c(j, b)$ for all $1 \leq j, b \leq s$ can be computed in polynomial time with respect to $s$.
\begin{example}[Examples of simple cost functions] \label{exmp:bdp:CostFunctions}
	The simplest choice of a cost function is a linear combination of \Time\ and \Inconvenience, parameterized by some constant $\alpha > 0$; we call this a \emph{linear} cost function. This cost function is $1$-simple. Notice that the first term captures \Time\ and the second captures \Inconvenience\ in both expressions.
	\begin{eqnarray*} \label{eqn:linear_cost_function}
	&&	c_{\alpha}(j, b_j) = \alpha + b_j \\
	&&	C_{\alpha}(j, {B}_m) = \left(\alpha \cdot j\right) + \left(\sum_{k=1}^{j} b_k\right)
	\end{eqnarray*}
	In some cases the organizer may want to penalize the mechanism for executing too many iterations by making later iterations to cost more than earlier iterations. The following describes such cost function, parameterized by some constant $\beta > 1$; we call this a \emph{time-averse} cost function. Notice that the term $\beta^j$ is strictly increasing as $j$ increases (recall $\beta > 1$). This cost function is $\beta$-simple.
	\begin{eqnarray*} \label{eqn:time_averse_cost_function}
	&&	c_{\beta}(j, b_j) = \beta^j \cdot b_j \\
	&&	C_{\beta}(j, {B}_m) = \left(\sum_{k=1}^{j} \beta^k \cdot b_k \right)
	\end{eqnarray*}
	In contrast if the organizer is interested in reducing the size of each batch because it may cause too much inconvenience, then the following cost function could be used, which is parameterized by some constant $\gamma > 1$; we call this an \emph{inconvenience-averse} cost function which is $1$-simple.
	\begin{eqnarray*} \label{eqn:inconvenience_averse_cost_function}
	&&	c_{\gamma}(j, b_j) = \gamma^{b_j} \\
	&&	C_{\gamma}(j, {B}_m) = \left(\sum_{k=1}^{j} \gamma^{b_k} \right)
	\end{eqnarray*}
\end{example}

We now formally define the Batched Doodle Problem.
\begin{definition}[Batched Doodle Problem] \label{def:bdp:Problem} % \label{Def:GSP}
	An instance of the Batched Doodle Problem (\BDP) is a tuple $(A, P_A, f, c)$
	where $A$ is a matrix of Bernoulli random variables,
	$P_A$ is the probability matrix associated with it,
	$f$ is the feasibility threshold with $f \in [0,1]$,
	and $c$ is a cost function.

	The objective in \BDP\ is to find an optimal B-Doodle mechanism $B^*$ such that $B^*$ minimizes the expected cost of the scheduling process (expectation with respect to $P_A$), given $(A, P_A, f, c)$.
\end{definition}

Since there are exponentially many B-Doodle mechanisms, it is impractical to enumerate each B-Doodle and compute its expected cost in order to find an optimal one. In what follows we make some simplifying assumptions that are assumed throughout this paper, and we present an efficient algorithm to solve \BDP\ in next section.

% TODO: To change 'invitees' to 'rows' and 'options' to 'columns' and 'availability' to 'entries in A'

\section{Efficient Algorithm for Finding Optimal B-Doodle}

\subsection{Preliminaries}
	Intuitively, if the organizer knows the probability distribution of availability of invitees, then he should inspect the columns that are more likely to be feasible first. We will prove this claim using the following lemma.
	\begin{lemma} \label{lemma:bdp:q_t_polytime}
	Given $(A, P_A, f, c)$, let $q_t$ for each column $t$ be the probability that column $t$ is $f$-feasible.
	We can compute $q_t$ in polynomial time.
	\end{lemma}
	\begin{proof}
	For any fixed $t$, let us define $V_t(i, z)$ to be the probability that among the column $t$ of $A$, exactly $z$ entries out of the first $i$ entries (in their row indices) are 1's. $V_t(i, z)$ is well-defined where $1 \leq i \leq n$ and $0 \leq z \leq i$. We further define $V_t(i, z)$ for the following degenerate cases:
	\begin{equation*}
	V_t(i, z) =
	\begin{cases}
		1 & \mbox{if~} i = z = 0 \\
		0 & \mbox{if~} z = -1 \mbox{~or~} (i = 0 \land z > 0)
	\end{cases}
	\end{equation*}
	Then we can compute $V_t(i, z)$ using a simple dynamic programming algorithm according to the following recurrence relation where $1 \leq i \leq n$ and $0 \leq z \leq i$:
	\begin{equation} \label{eqn:vt_precompute}
	V_t(i, z) = V_t(i-1, z-1) \cdot p_{i,t} + V_t(i-1, z) \cdot (1- p_{i,t})
	\end{equation}
	It is easy to verify that the recurrence relation is correct.
	For the degenerate cases (or base cases) when $i = z = 0$, no entries (out of $0$ entries) in column $t$ are equal to 1, and thus $V_t(i, z) = 1$ in this case. When $(z = -1)$ or $(i=0 \land z>0)$, $V_t(i, z) = 0$ because it is impossible to have $z$ entries out of $i$ entries.

	For the main recurrence relation, the entry $a_{r, t}$ is either 1 or 0, and we compute $V_t(i, z)$ by considering both cases. For each fixed $t$, there are $O(n^2)$ entries of $V_t$ to be computed, and computing each entry takes $O(1)$; therefore it takes $O(sn^2)$ time to compute $V_t(i, z)$ for all $t, i, z$.

	Finally we can compute $q_t$ after we compute $V_t(i, z)$ for all $i,z$, as follows:

	$$q_t = \sum_{z = \lceil f \cdot n \rceil}^{n} V_t(n, z).$$
	\end{proof}

	Lemma~\ref{lemma:bdp:q_t_polytime} allows us to describe a B-Doodle mechanism in a simpler form, along with the following theorem because an optimal B-Doodle mechanism must inspect the columns in non-increasing order of $q_t$.
	\begin{theorem} \label{thm:bdp:exchange_argument}
	Consider a B-Doodle mechanism $B$ described by $\langle S_1, S_2, \dots, S_m \rangle$. Suppose that there is some option $t \in S_l$ and $t'\in S_{l'}$ with $q_t < q_{t'}$ and $l < l'$. Then $B$ is not an optimal in the sense that we can find another mechanism $B^*$ whose expected cost is strictly less than the expected cost of $B$.
	\end{theorem}
	\begin{proof}
	Given $B$, let us construct $B^* = \langle S^*_1, S^*_2, \dots, S^*_m \rangle$ that is the same as $B$ except that we swap $t$ and $t'$. That is, $S^*_i = S_i$ for all $i \neq l$ and $i\neq l'$, and $S^*_{l} = (S_l \cup t') \setminus t$ and $S^*_{l'} = (S_{l'} \cup t) \setminus t'$. Note that the two mechanisms have the same batch sizes ($b_j = b^*_j$ for all $j$). \\

	Let $w_j$ be the probability that the scheduling process ends after the $j$-th iteration if we use $B$, and $w_j^*$ if we use $B^*$. Then $w_j = w_j^*$ for all $j < l$ because $S_j = S^*_j$ for all $j$ with $1 \leq j < l$. Clearly it holds that $w_l < w_l^*$ because of the swap of $t$ and $t'$. For $j$ with $l < j \leq l'$, it holds that $w_j > w_j^*$; this is not obvious, but the intuition is that if $w_l^*$ increases then the subsequent $w_j^*$'s with $l < j \leq l'$ must decrease as they depend on $1-w_l^*$, until this effect is canceled out in the $l'$-th batch. Since the probability of finding no feasible options during $l'$ iterations is the same in both cases (because $\cup_{i=1}^{l'} S_i = \cup_{i=1}^{l'}S^*_i$) it holds that $w_j = w_j^*$ for all $j > l'$. \\

	Let $E_B$ be the expected cost of $B$ and $E_{B^*}$ of $B^*$. Since $b_j = b^*_j$ for all $j$, it holds that $C(j, B) = C(j, B^*)$ for all $j$, and we have:
	\begin{eqnarray*}
		E_B - E_{B^*}
		&=& (w_l - w_l^*)C(l, B) + \sum_{j=l+1}^{l'} (w_j - w_j^*)C(j, B) \\
		&=& \sum_{j=l+1}^{l'} (w_j - w_j^*)(C(j, B) - C(l, B))
	\end{eqnarray*}
	The first inequality holds by definition of the expected cost and canceling out some terms; the second inequality holds because $(w_l - w_l^*) + \sum_{j=l+1}^{l'} (w_j - w_j^*) = 0$ (as probabilities must add up to one). Since $w_j > w_j^*$ and $C(j, B) > C(l, B)$ for all $j$ (because $C(j, B)$ is an increasing function in $j$ for fixed $B$), we conclude that $E_{B} > E_{B^*}$.
	\end{proof}
	Theorem~\ref{thm:bdp:exchange_argument} implies that an optimal B-Doodle that minimizes the expected cost must have the following property: for any two batches $S_j$ and $S_k$ with $j < k$, it must hold that $q_t \geq q_{t'}$ for all $t\in S_j$ and $t' \in S_k$ (otherwise we can apply the theorem and swap the two options to obtain a mechanism with smaller expected cost).
	Therefore we can limit our attention to the sub-class of B-Doodle mechanisms that only describe batch sizes, but not explicitly which options in each batch. Due to Lemma~\ref{lemma:bdp:q_t_polytime} we can compute $q_t$ for each $t$ in polynomial time, and thus we can simply sort options by $q_t$ in non-increasing order as a pre-processing step.

	Therefore we can focus on the following sub-class of \emph{simplified} B-Doodle mechanisms when we seek an optimal B-Doodle mechanism.
	\begin{definition}[Simplified B-Doodle Mechanism]
	Let $S = \{1, 2, \dots, s\}$ be a set of $s$ options.
	A simplified B-Doodle mechanism $B$ for $S$ is a vector of integers, described as $B = \langle b_1, b_2, \dots, b_m\rangle$ where $(b_j \geq 1$ for all $j \leq m)$ and $(\sum_{k=1}^{m} b_k = s)$.
	We write $B_m$ to emphasize that $B$ has $m$ batches. It is assumed that $B_m$ partitions $S$ into $m$ batches according to $b_j$'s where options (or columns) are sorted by $q_t$ in non-increasing order.
	\end{definition}
	From now on we use the definition of a simplified B-Doodle, and simply write a B-Doodle mechanism to mean a simplified B-Doodle mechanism but this should cause no confusion.

\subsection{Optimal Algorithm} \label{sec:Algorithm}

	In this section we present an algorithm that finds an optimal B-Doodle mechanism that minimizes the expected cost, given an instance of \BDP.
	Let us first describe how one can express the expected cost of a B-Doodle mechanism.

	Given an instance $(A, P_A, f, c)$, consider some B-Doodle mechanism $B_{m} = \langle b_1, b_2, \dots, b_m \rangle$ with $\sum_{k=1}^{m} b_k = |S|$. Let $\Pr(j)$ be the probability that the scheduling process ends after $j$-th iteration. Let us denote the expected cost of $B_{m}$ by $\Exp_c[B_{m}]$, which can be expressed in terms of $\Pr(\cdot)$ and the cost function $c$:
	\begin{equation} \label{eqn:expCost}
		\Exp_c[B_{m}] = \sum_{j=1}^{m} \Pr(j) \cdot C(j, B_{m})  =  \sum_{j=1}^{m} \Pr(j) \cdot \left(\sum_{k=1}^{j} c(k, b_k)\right)
	\end{equation}%

	While one can compute $\Pr(j)$ in polynomial time, it is not necessary for our algorithm. Instead we present an important lemma that leads us to an efficient algorithm. The following lemma states that if $c$ is simple, then we can compute $\Exp_c[B_{m}]$ in a recursive manner.
	\begin{lemma} \label{lemma:recurrence}
		Consider any mechanism $B_m = \langle b_1, b_2, \dots, b_m \rangle$. Let us denote another mechanism that is obtained after removing the first batch ($b_1$) from $B_m$, as $\hat{B}_{m-1}$ (i.e. $\hat{B}_{m-1} = \langle b_2, b_3, \dots, b_m \rangle$). For each option $t \in S$, let $q_t$ be the probability that $t$ is $f$-feasible.

	If $c$ is a $\theta$-simple cost function with with $\theta > 0$, the following equality holds:
	\begin{equation} \label{eqn:recurrence}
	\Exp_c[B_{m}] = c(1, b_1) +  \left(\prod_{t=1}^{b_1} \left(1 - q_t\right)\right) \cdot \theta \cdot \Exp_c[\hat{B}_{m-1}]
	\end{equation}
	\end{lemma}
	\begin{proof}
	Let us first provide an intuitive way to understand the recurrence relation given by Equation~\ref{eqn:recurrence}. The first term $c(1, b_1)$ captures the cost of sending out the first batch; regardless of when the scheduling process ends, this cost incurs with probability of $1$. If it turns out that the first batch does not contain a feasible option with probability of $(1 - \Pr(1))$, then the organizer must send out the remaining batches, which is precisely $\hat{B}_{m-1}$. It is easy to verify that the product term in the equation is equal to $(1 - \Pr(1))$. The expected cost of $\hat{B}_{m-1}$ is adjusted by a factor of $\theta$ in the equation because the cost function is $\theta$-simple. \\

	We now formally prove the claim. Given $B_{m}$ as described above, for each batch $j \in \{1, 2, \dots, m\}$, let $r_j$ be the probability that the $j$-th batch has at least one $f$-feasible option. Let us define $v_0 = 0$ and $v_j = \sum_{k=1}^{j} b_k$ (i.e. $v_j$ is the number of options in batches $1$ through $j$).
	We can express $r_j$ as:
	\begin{equation} \label{eqn:r_j}
	r_j = 1 - \prod_{t=v_{j-1} + 1}^{v_j} (1 - q_t)
	\end{equation}
	$\Pr(j)$ is the probability that the scheduling process ends after $j$-th iteration (with $\Pr(m) = 1 - \sum_{k=1}^{m-1} \Pr(k)$). For $1 \leq j < m$, $\Pr(j)$ is given by:
	\begin{equation} \label{eqn:Pr_j}
	\Pr(j) =  r_j  \prod_{k=1}^{j-1} (1 - r_k)
	\end{equation}
	It is understood that $\prod_{k=x}^{y} (\cdot)$ is equal to $1$ when $x > y$. \\

	Recall that $\hat{B}_{m-1} = \langle b_2, b_3, \dots, b_{m} \rangle$.
	Not to be confused, let us express it as $\hat{B}_{m-1} = \langle \hat{b}_1, \hat{b}_2, \dots, \hat{b}_{m-1}\rangle$ with $\hat{b}_j = b_{j+1}$ for all $j\geq 1$. Let $\hat{r}_j$ be the probability that a feasible option exists in $j$-th batch of $\hat{B}_{m-1}$, which is equal to $r_{j+1}$ for all $j \geq 1$. Let $\hat{Pr}(j)$ be the probability that scheduling ends after the $j$-th iteration of $\hat{B}_{m-1}$:
	\begin{equation}
		\hat{Pr}(j)
		= \hat{r}_j \prod_{k=1}^{j-1} (1 - \hat{r}_k)
		= r_{j+1} \prod_{k=2}^{j} (1 - r_{k})  \label{eqn:pr_hat_b}
	\end{equation}
	We can express $\Exp_c[\hat{B}_{m-1}]$ as follows:
	\begin{eqnarray*}
	\Exp_c[\hat{B}_{m-1}]
	&=& \sum_{j=1}^{m-1} \hat{Pr}(j) \left( \sum_{k=1}^{j} c(k, \hat{b}_k) \right) \\
	&=& \sum_{j=1}^{m-1} r_{j+1} \left(\prod_{k=2}^{j} (1 - r_{k})\right) \left(\sum_{k=2}^{j+1} c(k-1, b_{k+1})\right) \\
	&=& \sum_{j=2}^{m} r_{j} \left(\prod_{k=2}^{j-1} (1 - r_{k})\right) \left(\sum_{k=2}^{j} c(k-1, b_{k+1})\right)
	\end{eqnarray*}
	The first equality holds by definition. The second equality is due to Equation~\ref{eqn:pr_hat_b} and because $\hat{b}_k = b_{k+1}$. The third equality is by changing the range of $j$ in the summation. \\

	If we multiply $\Exp_c[\hat{B}_{m-1}]$ by $(1 - r_1)\theta$, we get the following:
	\begin{equation} \label{eqn:ExpCost_Bhat}
	(1-r_1)\theta \Exp_c[\hat{B}_{m-1}] = \sum_{j=2}^{m} r_{j} \left(\prod_{k=1}^{j-1} (1 - r_{k})\right) \left(\sum_{k=2}^{j} c(k, b_{k+1})\right)
	\end{equation}
	Notice that the product term now runs from $k = 1$ to $j-1$ as we multiply by $(1-r_1)$ and the inner-most summation has $c(k, b_{k+1})$ as we multiply by $\theta$ (recall that $c$ is $\theta$-simple).

	Finally we can express $\Exp_c[B_m]$ in terms of $\Exp_c[\hat{B}_{m-1}]$ as follows (where $c_1 = c(1, b_1)$ for brevity):
	\begin{eqnarray*}
	\Exp_c[B_{m}]
	&=& \sum_{j=1}^{m} \Pr(j) \left(\sum_{k=1}^{j} c(k, b_k)\right) \\
	&=& c_1 + \left(\sum_{j=2}^{m} r_j \left(\prod_{k=1}^{j-1} (1 - r_k)\right) \left(\sum_{k=2}^{j} c(k, b_k)\right) \right) \\
	&=& c_1 + (1-r_1)\theta \Exp_c[\hat{B}_{m-1}] \\
	&=& c(1, b_1) + \left(\prod_{t=1}^{b_1} (1-q_t) \right)\cdot \theta \cdot \Exp_c[\hat{B}_{m-1}]
	\end{eqnarray*}
	The first equality holds by definition of $\Exp_c[B_{m}]$. The second equality is obtained by taking $c(1, b_1)$ out from the summation (and note that $\Pr(j)$ adds up to 1) first and then applying Equation~\ref{eqn:Pr_j}. The last two inequalities hold due to Equation~\ref{eqn:ExpCost_Bhat} and \ref{eqn:r_j}, respectively.
	The last expression exactly  matches Equation~\ref{eqn:recurrence} in the lemma.
	\end{proof}

	Using the recurrence relation in Lemma~\ref{lemma:recurrence} and the computing method in Lemma~\ref{lemma:bdp:q_t_polytime}, we can now design an efficient recursive algorithm finds the optimal B-Doodle mechanism. Our algorithm is presented in Algorithm~\ref{alg:recursive} as a recursive method $Rec(x)$. We assume that the values of $q_t$ have been computed as a pre-processing step prior to running our algorithm, using the method in Lemma~\ref{lemma:bdp:q_t_polytime}. We further assume that options are sorted in decreasing order of $q_t$ (i.e. $q_1 \geq q_2 \geq \dots \geq q_{s}$); therefore we simply refer to the option by its index (i.e. $t = 3$ refers to the third option in the sorted list of options).

	Given $1 \leq x \leq s$, $Rec(x)$ returns optimal B-Doodle ($B^*$) that consists of options $\{x, x+1, \dots, s\}$ and its expected cost ($EC^*$). To solve for a given instance of the problem, we simply call the method $Rec(x)$ with $x = 1$.

	\begin{algorithm}
	\caption{Recursive Algorithm: $Rec(x)$}
	\label{alg:recursive}
	\begin{algorithmic}[1]
		\State ${B}^* \gets \langle s-x+1 \rangle$, $EC^* \gets c(1, s-x+1)$
		\For{$b := 1, 2, \dots, s-x$}
			\State $({B}, EC) \gets Rec( x+b )$
			\State $EC_b \gets c(1, b) + \left(\prod_{t=x}^{x+b-1} (1 - q_t)\right)\cdot \theta \cdot EC$
			\If {$EC^* > EC_b$}
				\State $EC^* \gets EC_b$
				\State $B^* \gets \langle b, {B} \rangle$
			\EndIf
		\EndFor
		\State \textbf{return} $({B}^*, EC^*)$
	\end{algorithmic}
	\end{algorithm}

	\begin{theorem} \label{thm:recursive_algo}
	Algorithm~\ref{alg:recursive} runs in polynomial time, and returns an optimal B-Doodle mechanism that minimizes the expected cost, given an instance $(N, S, f, c, P)$ of \BDP\ when $c$ is $\theta$-simple.
	\end{theorem}
	\begin{proof}
	Our recursive method is very simple: given options $\{x, x+1, \dots, s\}$, it iteratively considers the case of sending out $b$ options in the first iteration, and computes the expected cost $EC_b$ of doing so, for each $b$ with $1 \leq b \leq s-x+1$.  In line 1, our method checks for the trivial case when $b = s-x+1$ (i.e. all options are sent in a single batch); we store this mechanism in $B^*$ and its expected cost in $EC^*$. Then we iterate $b$ from $1$ to $s-x$ and compute the expected cost $EC_b$, and compare with the optimal expected cost found so far (lines 2-9). For each $b$, we first recursively compute the expected cost for the remaining options (namely, $\{x+b, x+b+1, \dots, s\}$) by calling our method $Rec(x+b)$, and store the expected cost in $EC$ (line 3). Using Lemma~\ref{lemma:recurrence} we can compute $EC_b$ as in line 4 (note that the first batch contains $b$ options from $x$ to $x+b-1$). In lines 5-8, we simply compare $EC_b$ with the current optimal, $EC^*$, and update if necessary; $\langle b, B \rangle$ should be interpreted as the concatenation of $b$ and $B$ into a single vector of integers. Finally in line 10, our method returns the optimal B-Doodle found, $B^*$ and its expected cost $EC^*$. \\

	We prove correctness of the algorithm by induction on $x$ (from $x = s$ to $x = 1$). The base case is trivial: if $x = s$ the only B-Doodle mechanism is $\langle 1 \rangle$ and our method finds it in line $1$ and returns it in line $10$. Suppose our method correctly returns the optimal B-Doodle mechanism (and its expected cost) for all $x > k$ for some $k$ (the inductive hypothesis), and we prove for the case of $x = k$. When $x = k$, there are precisely $(s-k+1)$ options that are to be sent, and the first batch can contain any number of options between $1$ and $(s-k+1)$, inclusive. In lines 1-9 our method considers all such cases, and for each case it computes the expected cost correctly (in line 4) due to our inductive hypothesis and Lemma~\ref{lemma:recurrence}. Therefore our method finds the optimal B-Doodle for all $x$ with $1 \leq x \leq s$; in particular when $x = 1$, it returns the desired optimal B-Doodle mechanism for the given problem instance.\\

	Our recursive method runs in polynomial time when we use memoization on $Rec(x)$ with respect to $x$; that is, for each $x$ we cache what $Rec(x)$ returns for the first time, and for any subsequence calls to $Rec(x)$ we simply return the cached values. Therefore lines 1-9 are executed at most once for each $x$ with $1 \leq x \leq s$. Also note that $Rec(x)$ makes a call to $Rec(x + b)$ with $b \geq 1$ and $x+b \leq s$, which means there are no infinite loops. Once $Rec(x)$ is computed for all $x > k$, it takes $O(|S|^2)$ time to compute $Rec(k)$, and thus the overall running time of our algorithm is $O(|S|^3)$ when we start with $Rec(1)$. Pre-processing steps (of computing $q_t$) also run in polynomial time due to Lemma~\ref{lemma:bdp:q_t_polytime}.
	\end{proof}

\section{Experimental Results with Synthetic Data}

We showed that we can find an optimal B-Doodle mechanism that minimizes the expected cost. But a very important question remains: Is our optimal B-Doodle substantially better than Doodle in realistic settings? If the answer is no, we do not have much incentive to discard the simplest mechanism, Doodle, over using our sophisticated algorithm. Intuitively we expect Doodle to be inefficient if there are many options (i.e., $s$ is large) because it causes much inconvenience for invitees to examine the options. Reasoning further, we can also see that inefficiency of Doodle depends on the probability of each option being feasible (i.e. $q_t$ values), which in turn depends on $p_{i, t}$ values. If invitees are relatively free, then a small number of options would be sufficient for finding a feasible option, which makes Doodle inefficient. Last but not least, the underlying cost function plays an important role as well. These all sound plausible, and we validate our intuition with simulation results.

In our setting there are many experimental choices one can choose from. In what follows we look at a representative example in which each invitee is available for each option with the same probability of $p$; that is, $p_{i, t} = p$ for some constant $p$. (While in realistic situations the $p_{i, t}$'s may all differ, we  note that in our simulations  our results seem to carry over to these more general settings as well.) We present experimental results for each of the three cost functions discussed in Example~\ref{exmp:bdp:CostFunctions}: The linear cost function, the time-averse cost function, and the inconvenience-averse function.

% ===================== Linear Cost Function (Below)

\subsection{Case of Linear Cost Function} \label{sec:result_linear_cost}
Recall that the linear cost function is parameterized by some constant $\alpha>0$ and that $c_{\alpha}(j, b) = \alpha + b$. We used $\alpha = 2$ as an experimental choice, and we later discuss what we observed for different values of $\alpha$.

We reasoned that Doodle becomes suboptimal if the number of options, $s$, is large. Therefore it is interesting to know for what ranges of $s$, Doodle is suboptimal. For some fixed $(n, s, p)$, let $C^D(n, s, p)$ be the cost of Doodle and $C^*(n, s, p)$ be the expected cost of $B^*$. We want to find the smallest critical point $S^*(n, p)$ such that for any $s \geq S^*(n, p)$ we have $C^D(n, s, p) > C^*(n, s, p)$.

In Table~\ref{table:bdp:DoodleSuboptimal}, we show $S^*$ for various $(n, p)$ when $f = 1$ (i.e. the organizer requires everyone be available). For instance we find $S^*(6, .8) = 5$, which implies that Doodle is suboptimal for all $s \geq 5$ given that $n=6$ and $p=.8$. The smaller $S^*$ is, the less practical Doodle is for the corresponding $(n, p)$.
Across the table we can observe that $S^*$ is small when $n$ is small and/or when $p$ is high -- this agrees with our intuition.
We highlighted $8$ entries in boldface to emphasize that $S^* \leq 15$; for the corresponding $(n, p)$ values, Doodle is suboptimal if there are $15$ or more options being considered.
\begin{table}[h!]  % \small
\centering
\begin{tabular}{|c|c|c|c|c|c|}
	\hline
	$S^*$ & $n = 2$ & $n = 4$ & $n = 6$ & $ n = 10 $ & $n = 15$ \\ \hline
	$p = .8$ & \textbf{3} & \textbf{4} & \textbf{5} & \textbf{8} & \textbf{15} \\ \hline
	$p = .5$ & \textbf{5} & \textbf{11} & 22 & 90 & $>300$\\ \hline
	$p = .2$ & \textbf{14} & 70 & $>300$ & $>300$ & $>300$ \\ \hline
\end{tabular}
\caption{Critical point $S^*$ for various $(n, p)$ when $f = 1, \alpha = 2$.
Entries in boldface emphasize that $S^* \leq 15$.
} \label{table:bdp:DoodleSuboptimal}
\end{table}

Not only do we want to know when Doodle is suboptimal, but we also want to know how inefficient Doodle is in realistic situations. For some fixed $(n, s, p)$, we define the efficiency of Doodle, $e_{D}(n,s,p)$, as the ratio of the optimal expected cost to the cost of Doodle: $e_{D}(n,s,p) = C^*(n, s, p) / C^D(n, s, p)$.

In Table~\ref{table:bdp:DoodleEfficiency} we show $e_{D}$ for the same settings of $(n, p)$ we used in Table~\ref{table:bdp:DoodleSuboptimal}. For this experiment we used $s = 15$ and $f = 1$. If $e_{D} = 1$ Doodle is optimal, and if $e_{D}$ is close to zero then Doodle is very inefficient. We find that $e_{D}(2, .8) = .270$, which implies that Doodle is very inefficient in this case; on the other hand $e_{D}(10, .5) = 1$, in which case Doodle is optimal. Across the table we observe the same pattern we observed before -- for small $n$ and high $p$, Doodle is substantially inefficient.
\begin{table}[h]  % \small
\centering
\begin{tabular}{|c|c|c|c|c|c|c|}
	\hline
	$e_{D}$ & $n = 2$ & $n = 4$ & $n = 6$ & $ n = 10 $ & $n = 15$ \\ \hline
	$p = .8$ & \textbf{.270} & \textbf{.361} & \textbf{.486} & .777 & .986 \\ \hline
	$p = .5$ & \textbf{.502} & .904 & 1 & 1 & 1  \\ \hline
	$p = .2$ & .970 & 1 & 1 & 1 & 1\\ \hline
\end{tabular}
\caption{Efficiency of Doodle $e_{D}$ for various $(n, p)$ when $f = 1, \alpha=2, s = 15$.
Entries in boldface emphasize that $e_{D} < .750$.
} \label{table:bdp:DoodleEfficiency}
\end{table}

Inefficiency of Doodle is more pronounced when the organizer has a lower feasibility threshold such as $f = .7$; in such case, only a fraction of invitees need to be available.
We can clearly observe the worsened inefficiency of Doodle in Table~\ref{table:bdp:DoodleEfficiency-lower-attendance}.
Here we show $e_{D}$ values for the same set of $(n, p)$ as in Table~\ref{table:bdp:DoodleEfficiency} but with $f = .7$.
Previously we highlighted four entries with $e_{D} < .750$ when $f = 1$ in Table~~\ref{table:bdp:DoodleEfficiency}; when $f = .7$ the number of entires with $e_{D} < .750$ doubled to eight.
Note that the first column is identical between the two tables; this is because $f = .7$ still requires both invitees to be available when $n = 2$.
Also notice that $e_{D}$ is surprisingly low in the first row of Table~\ref{table:bdp:DoodleEfficiency-lower-attendance} across all columns. This shows that regardless of the number of invitees, Doodle is significantly inefficient when the invitees are highly available ($p \geq .8$) and the organizer has a relaxed feasibility threshold.
\begin{table}[h]  % \small
\centering
\begin{tabular}{|c|c|c|c|c|c|c|}
	\hline
	$e_{D}$ & $n = 2$ & $n = 4$ & $n = 6$ & $ n = 10 $ & $n = 15$ \\ \hline
	$p = .8$ & \textbf{.270} & \textbf{.215} & \textbf{.267} & \textbf{.201} & \textbf{.211} \\ \hline
	$p = .5$ & \textbf{.502} & \textbf{.434} & .772 & \textbf{.628} & .913  \\ \hline
	$p = .2$ & .970 & 1 & 1 & 1 & 1\\ \hline
\end{tabular}
\caption{Efficiency of Doodle $e_{D}$ for various $(n, p)$ when $f = .7, \alpha=2, s = 15$.
Entries in boldface emphasize that $e_{D} < .750$.
} \label{table:bdp:DoodleEfficiency-lower-attendance}
\end{table}

We ran experiments with different values of $(n, s, p, f, \alpha)$, and observed the same  trends that are presented here.

% ===================== Other Cost Functions (Below)

%\balancecolumns
\subsection{Case of Other Cost Functions}
We present some of the experimental results we obtained with different cost functions, namely the time-averse cost function and the inconvenience-averse cost function. As the names suggest, the former places more weight on optimizing \Time, while the latter on optimizing \Inconvenience. \\

For the time-averse cost function (recall $c_{\beta}(j, b) = \beta^j \cdot b$), we chose $\beta = 2$ as an experimental choice. Notice that the cost increases exponentially for later iterations, which forces the organizer to send out a small number of batches (as in Doodle). We ran the same set of experiments as before to measure efficient of Doodle, $e_{D}$.

The result is summarized in Table~\ref{table:bdp:DoodleEfficiency-lower-attendance_time_averse}, which shows the same trends as we observed in previous experiments. Notice that in the first row ($p = .8$), as $n$ increases we expect $e_{D}$ to decrease, but $e_{D}$ fluctuates while decreasing in general. The fluctuation is due to the rounding of attendance requirement ($\lceil a \cdot n \rceil$). For instance when $n = 4$, $\lceil a \cdot n \rceil$ = 3 which effectively requires 75\% of attendees be available.
\begin{table}[h]  % \small
\centering
\begin{tabular}{|c|c|c|c|c|c|c|}
	\hline
	$e_{D}$ & $n = 2$ & $n = 4$ & $n = 6$ & $ n = 10 $ & $n = 15$ \\ \hline
	$p = .8$ & \textbf{.180} & \textbf{.104} & \textbf{.175} & \textbf{.088} & \textbf{.099} \\ \hline
	$p = .5$ & \textbf{.561} & \textbf{.457} & .876 & \textbf{.726} & .987  \\ \hline
	$p = .2$ & 1 & 1 & 1 & 1 & 1\\ \hline
\end{tabular}
\caption{Efficiency of Doodle $e_{D}$ for various $(n, p)$ when $f = .7, \beta=2, s = 15$.
Entries in boldface emphasize that $e_{D} < .750$.
} \label{table:bdp:DoodleEfficiency-lower-attendance_time_averse}
\end{table}

For the inconvenience-averse cost function (recall $c_{\gamma}(j, b) = \gamma^{b}$), we chose $\gamma = 1.1$ as an experimental choice. While $\gamma$ is fairly small, because the cost function is an exponential function of $b$, an optimal B-Doodle must send out small-size batches. This cost function optimizes \Inconvenience\ primarily. We ran the same set of experiments as before to measure efficiency of Doodle, $e_{D}$.

The result is summarized in Table~\ref{table:bdp:DoodleEfficiency-lower-attendance_inconvenience_averse}. Notice that $e_{D}$ is not equal to $1$ even when $p = .2$ in this setting, which we did not observe with the other cost functions previously. Due to integer-rounding, we again observe some fluctuations in $e_{D}$ across columns within the same row, but the general trend is that $e_{D}$ decreases as $n$ increases.
\begin{table}[h]  % \small
\centering
\begin{tabular}{|c|c|c|c|c|c|c|}
	\hline
	$e_{D}$ & $n = 2$ & $n = 4$ & $n = 6$ & $ n = 10 $ & $n = 15$ \\ \hline
	$p = .8$ & \textbf{.333} & \textbf{.299} & \textbf{.329} & \textbf{.294} & \textbf{.298} \\ \hline
	$p = .5$ & \textbf{.499} & \textbf{.450} & \textbf{.695} & \textbf{.592} & .799  \\ \hline
	$p = .2$ & .850 & .887 & .974 & .976 & .980 \\ \hline
\end{tabular}
\caption{Efficiency of Doodle $e_{D}$ for various $(n, p)$ when $f = .7, \gamma=1.1, s = 15$.
Entries in boldface emphasize that $e_{D} < .750$.
} \label{table:bdp:DoodleEfficiency-lower-attendance_inconvenience_averse}
\end{table}

%\balancecolumns

\subsection{Summary of Experiments}
While we only presented experimental results with specific values of $(n, s, p, f)$ and parameters $(\alpha, \beta, \gamma)$, we observed that Doodle is in general substantially inefficient, including (but not limited to) when one or more of the following conditions hold:
\begin{itemize}
	\item There is a relatively small number of invitees ($n \leq 10$).
	\item There is a large number of options ($s \geq 15$).
	\item invitees are relatively free ($p > .5$).
	\item Feasibility threshold is relaxed ($f < .8$).
	\item The cost function places more weight on \Inconvenience\ than \Time\ ($\alpha < 20$, $\beta < 5$, or $\gamma > 1.05$).
\end{itemize}
Intuitively the first four conditions affect $q_t$ (the probability that option $t$ is feasible) in the same way, and if $q_t$'s are high then Doodle is more likely to be inefficient because a few options may be sufficient for finding a feasible one. While the last condition is independent of $q_t$, the cost function determines what is being optimized, and Doodle becomes more inefficient if $c$ favors reducing \Inconvenience\ over reducing \Time.

\section{Discussion}

In this chapter we identified two important dimensions of optimality in
group scheduling: \Time\ and \Inconvenience. We generalized the popular
Doodle mechanism to a class of B-Doodle mechanisms that partition date/time
options into batches. We showed an example of the Pareto-frontier of
B-Doodle mechanisms on the \Time-\Inconvenience\ dimensions. We then
described an efficient algorithm for finding an optimal B-Doodle
mechanisms, given a simple cost function that aggregates \Time\ and
\Inconvenience, assuming probabilistic independence among availability
of invitees. We showed in simulations that optimal B-Doodle mechanism
is superior to Doodle in realistic situations, sometimes greatly so.

% TODO: Move to next chapter?
% While useful in and of itself, this work leaves open many questions.
% Here we focused on a sub-class of the Single-proposer mechanisms in
% which there is a sole organizer who is trying to find an agreeable
% schedule. In realistic situations a group of invitees often negotiate
% among themselves or respond with counter-offers. It will be
% interesting to extend our B-Doodle mechanisms to the Multi-proposer
% mechanisms. Another obvious extension of our work is to relax the
% independence assumption and develop an adaptive mechanism that infers
% availability of invitees based on their responses. In addition, we
% implicitly assumed that invitees prefer all options equally (by
% allowing invitees to specify their availability but not preferences),
% but people often have specific preferences. Thus it will be important
% to study the trade-off between optimizing the cost of scheduling
% process and finding a `good' schedule.
% Finally, we assumed honesty, promptness, and trust of invitees, but
% these are strong assumptions. In particular, promptness assumes that
% invitees do not procrastinate and do not deliberately delay responses.
% It is arguably true that if the scheduling process is efficient then
% it will indeed reduce the procrastination of invitees. However in
% practice an invitee may have an incentive to delay her response or to
% lie about her availability or preferences. Practical mechanisms should
% not be vulnerable to such strategic behavior of invitees, and this is
% yet another direction for future work.
%


% --------------------------------------------------------------
% This is all preamble stuff that you don't have to worry about.
% Head down to where it says "Start here"
% --------------------------------------------------------------

\documentclass[12pt]{article}

\usepackage[margin=1in]{geometry}
\usepackage{amsmath,amsthm,amssymb}
\usepackage{tikz}
\usepackage{listings}
\usepackage{subfig}
\usepackage{float}

\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}

\newenvironment{theorem}[2][Theorem]{\begin{trivlist}
\item[\hskip \labelsep {\bfseries #1}\hskip \labelsep {\bfseries #2.}]}{\end{trivlist}}
\newenvironment{lemma}[2][Lemma]{\begin{trivlist}
\item[\hskip \labelsep {\bfseries #1}\hskip \labelsep {\bfseries #2.}]}{\end{trivlist}}
\newenvironment{exercise}[2][Exercise]{\begin{trivlist}
\item[\hskip \labelsep {\bfseries #1}\hskip \labelsep {\bfseries #2.}]}{\end{trivlist}}
\newenvironment{reflection}[2][Reflection]{\begin{trivlist}
\item[\hskip \labelsep {\bfseries #1}\hskip \labelsep {\bfseries #2.}]}{\end{trivlist}}
\newenvironment{proposition}[2][Proposition]{\begin{trivlist}
\item[\hskip \labelsep {\bfseries #1}\hskip \labelsep {\bfseries #2.}]}{\end{trivlist}}
\newenvironment{corollary}[2][Corollary]{\begin{trivlist}
\item[\hskip \labelsep {\bfseries #1}\hskip \labelsep {\bfseries #2.}]}{\end{trivlist}}

\lstdefinestyle{CStyle}{
    basicstyle=\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=4,
    language=C
}

\begin{document}
%\setcounter{secnumdepth}{0}
% --------------------------------------------------------------
%                         Start here
% --------------------------------------------------------------

%\renewcommand{\qedsymbol}{\filledbox}

\title{Lab1 deliverable}%replace X with the appropriate number
\author{Daniel Sattler and Cristina Raluca Vijulie\and par1207} %if necessary, replace with your course title

\maketitle
\begin{enumerate}
\section*{Node architecture and memory}

\item[] 1. Draw and briefly describe the architecture of the computer in which you are doing this lab session (number of sockets, cores per socket, threads per core, cache hierarchy size and sharing, and amount of main memory).

\begin{enumerate}
\item sockets: 2
\item cores/socket: 6
\item threads: 2
\end{enumerate}

\begin{center}
\includegraphics[width=14cm]{fig1.png}
\end{center}

\section*{Timing sequential and parallel executions}

\item[] 2. Describe what do you need to add to your program to measure the elapsed execution time between a pair of points in the program, clearly indicating the library header file that needs to be included, the library functions that need to be invoked, the data structure and its fields.

\begin{itemize}

\item[] To measure the time we need to get a timestamp with the time of the day when the execution starts and subtract that value to the time of day when the program ends. To do so we use the following:

\item The library:
\begin{lstlisting}[style=CStyle]
	#include <sys/time.h>
\end{lstlisting}

\item The function:
\begin{lstlisting}[style=CStyle]
	int  gettimeofday(struct timeval *, void *);
\end{lstlisting}

\item The data structure \textbf{timeval}, which includes the following fields:

\begin{lstlisting}[style=CStyle]
	time_t         tv_sec      seconds
	suseconds_t    tv_usec     microseconds
\end{lstlisting}

\end{itemize}

\item[] 3. Plot the speed–up obtained when varying the number of threads (strong scalability) and problemsize (weak scalability) for pi omp.c. Reason about how the scalability of the program.

\begin{figure}[H]%
\centering
\subfloat{{\includegraphics[width=6cm]{weak.png} }}%
\qquad
\subfloat{{\includegraphics[width=6cm]{strong.png} }}%
\end{figure}
\begin{itemize}
\item[] When we are in weak scalability, the speedup does not change so much, it means the scalability is good and we can keep increasing the problem size while increasing the threads and the execution time will not be much greater. In the case of strong scalability, we can see that more than 11 threads start to decrease the speed-up, so it does not have a great strong scalability, with 11 as the optimal number of threads.
\end{itemize}

\section*{Visualizing the task graph and data dependences}

\item[] 4. Include the source code for function dot product in which you show the Tareador instrumentation that has been added to study the potential parallelism in the code. This instrumentation has to appropriately define tasks and filter the analysis of variable(s) that cause the dependence(s).

%this is too long, better include the code to the archive
%\lstinputlisting[caption=Scheduler, style=CStyle]{dot_product.c}
\begin{itemize}
	\item[] The source code has been added to the archive and is named dot\_product.c
\end{itemize}

\item[] 5. Capture the task dependence graph for that task decomposition and the execution timelines (for 8 processors) that allow you to understand the potential parallelism attainable. Briefly comment the relevant information that is reported by the tools.

\begin{figure}[H]%
\centering
\subfloat{{\includegraphics[width=18cm]{graph.png} }}%
\label{fig:test}%
\end{figure}
\begin{figure}[H]%
\centering
\subfloat{{\includegraphics[width=18cm]{timelines.png} }}%
\end{figure}

\section*{Analysis of task decompositions}

\item[] 6. Complete the following table for the initial and different versions generated for 3dfft\_seq.c, briefly
commenting the evolution of the metrics with the different versions.
\begin{center}
\begin{tabular}{| c || c | c | c | }
  \hline
  \textbf{Version} & $T_1$ & $T_{\infty}$ & \textbf{Parallelism}\\ \hline \hline
  seq & 593772 & 593758 & 1.000\\ \hline
  v1 & 593772 & 593758 & 1.000\\ \hline
  v2  & 594054 & 315537 & 1.883 \\ \hline
  v3  &  594054 & 108701 & 5.465\\ \hline
  v4  & 594054 & 59694 & 9.952 \\
  \hline

\end{tabular}
\end{center}

\item[] 7. With the results from the parallel simulation with 2, 4, 8, 16 and 32 processors, draw the execution
time and speedup plots for version v4 with respect to the sequential execution (that you can
estimate from the simulation of the initial task decomposition that we provided in 3dfft seq.c,
using just 1 processor). Briefly comment the scalability behaviour shown on these two plots.

\begin{figure}[H]%
\centering
\includegraphics[width=12cm]{plotTimeCores.png}
\caption{Execution time in ns }
\label{fig:test}%
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=12cm]{plotSpeedup.png}
\caption{Speedup v4 vs. seq}
\label{fig:Speedup plot}%
\end{figure}

\begin{itemize}
	\item[] As we can see in the plots, the scalability is bad. The maximum number of cores we can use at the same time are 16, more than that do not help the execution time.
\end{itemize}

\section* {Tracing sequential and parallel executions}

\item[] 8. From the instrumented version of pi seq.c, and using the appropriate Paraver configuration
file, obtain the value of the parallel fraction φ for this program when executed with 100.000.000
iterations, showing the steps you followed to obtain it. Clearly indicate which Paraver configuration
file(s) did you use.

\begin{figure}[H]
\centering
\includegraphics[width=12cm]{ex8.png}
\caption{Parallel fraction of the code}
\label{fig:Parallel duration}%
\end{figure}

\begin{itemize}
	\item[] The parallel fraction of this program is the parallel duration * 100 / the total duration. The value of the fraction is: 58.4\% This was obtained using the APP\_userevents configuration.
\end{itemize}

\item[] 9. From the instrumented version of pi omp.c, and using the appropriate Paraver configuration file,
show a profile of the \% of time spent in the different OpenMP states when using 8 threads and for
100.000.000 iterations. Clearly indicate which Paraver configuration file(s) did you use and your
own conclusions from that profile.

\begin{figure}[H]
\centering
\includegraphics[width=15cm]{ex9.png}
\caption{Time spent in the different states of OMP}
\label{fig:Parallel duration}%
\end{figure}

\begin{itemize}
	\item[] This was obtained using the OMP\_state\_profile configuration.
\end{itemize}

\end{enumerate}
\end{document}


\documentclass[twocolumn,prl,nobalancelastpage,aps,10pt]{revtex4-1}
%\documentclass[rmp,preprint]{revtex4-1}
\usepackage{graphicx,bm,times,notoccite}
\graphicspath{{figures/}}

\usepackage{float} %useful to structure the figures if they're not going where you'd like them to. When beginning a figure environment with "\begin{figure}" add An H to the end to make the placement more forceful like "\begin{figure}[H]"

\usepackage{gensymb} %has some extra symbols like the degree symbol

\begin{document}

\title{Investigating the motion of a body in free-fall experiencing drag}

\author{Francis Taylor}

\affiliation{Department of Physics, University of Bristol}

\begin{abstract}The motion of a body in free-fall experiencing fixed and varying drag was modelled using the Euler method for solving ordinary differential equations. The effect of varying the mass, $m$, of the body and time step, $\Delta t$, was investigated, and it was found that at higher $\Delta t$ the model produced better approximations for higher masses. This model was applied to Felix Baumgartner's free-fall jump from the edge of space. It was concluded that the Euler model with varying drag gives the best approximation to Baumgartner's actual jump.
\end{abstract}
\date{\today}

\maketitle

\section{INTRODUCTION AND THEORY}

For a body in free-fall, i.e. with no initial acceleration, only two forces act on it: weight and drag. As it begins to fall, it will have an initial acceleration due to gravity. While falling, the frictional force from the air increases, decreasing the downwards acceleration. This is due to Isaac Newton's third law of motion, as every action has an equal and opposite reaction \cite{Newton1846}. At some point during the free-fall, the force due to gravity will balance with the force from air resistance, and the body will stop accelerating - it has reached its terminal velocity, and will fall with constant speed. In a uniform gravitational field with air resistance, the equation of motion will be
\begin{equation}\label{eq-motion}
m\frac{dv}{dt} = mg - \frac{1}{2}\rho C_{D}Av^{2},
\end{equation}
where $m$ is the mass of the object, $v$ is the velocity of the object, $t$ is time, $g$ is the acceleration due to gravity, $\rho$ is the density of the air, $C_{D}$ is the drag coefficient and $A$ is the cross-sectional area. Integrating this gives
\begin{equation}\label{eq-v}
v(t) = v_{\infty}\tanh(\frac{gt}{v_{\infty}}),
\end{equation}
where $v_{\infty}$ is
\begin{equation}\label{eq-terminal-v}
v_{\infty} = \sqrt{\frac{2mg}{\rho C_{D} A}}.
\end{equation}

\subsection{Euler's Method}
Euler's method is an iterative numerical method for solving first order ordinary differential equations (ODEs), and is an example of a Runge-Kutta method \cite{Butcher2003}. Consider an unknown curve, that we wish to calculate the shape of, which starts at a known point, $A_{0}$ and satisfies a differential equation. We can break the curve into small steps $\delta x$, and calculate the slope of the curve at the start of the step, $A_{n}$, and thus we get a tangent line. This can be repeated for the length of the unknown curve to form a polygonal approximation. The error between this line and the curve is proportional to $(\delta x)^{2}$. By decreasing $\delta x$, the slope at $A_{n}$ will be closer to the unknown curve, and thus for $\delta x$ small enough, we get a good approximation of the unknown curve \cite{Butcher2003,Atkinson1989}. Figure \ref{Euler-method} shows an Euler approximation in comparison to the unknown curve.

\begin{figure}[H]
\includegraphics*[width=0.96\linewidth,clip]{Euler_method}
\caption{Illustration of the Euler method. The unknown curve is in blue, and its polygonal approximation is in red. Figure from \cite{Alexandrov2007}.}\label{Euler-method}
\end{figure}

Given a differential equation
\begin{equation}
\frac{dy}{dt} = f(y,t),
\end{equation}
where $y$ is vertical height and $t$ is time, Euler's method can be summarised by
\begin{equation}
y_{n+1} = y_{n} + \Delta t.f(y_{n},t_{n})\quad;\quad t_{n+1} = t_{n} +\Delta t,
\end{equation}
where $\Delta t$ is the chosen time interval.
By applying this method to equation \ref{eq-v}, we get
\begin{equation}\label{eq-iterative-v}
v_{n+1} = v_{n} - \Delta t(g+\frac{k}{m}|v_{n}|v_{n}),
\end{equation}
where k is the drag factor, given by
\begin{equation}
k = \frac{C_{D}\rho A}{2}.
\end{equation}
If the air density isn't constant \cite{Mohazzabi1996},
\begin{equation}\label{eq-va-air-dens}
\rho(y)=\rho_{0}exp(-y/h),
\end{equation}
where $y$ is the height and $h$ is a scaling constant (7640m on Earth). The height, $y$, is given by
\begin{equation}\label{eq-iterative-y}
y_{n+1} = y_{n}+\Delta t.v_{n}.
\end{equation}
By inputting initial values of $v_{0}$, $y_{0}$, and $t_{0}$, all values of $v_{n}$, $y_{n}$ and $t_{n}$ could be calculated.
\subsection{Analytical Method}
The Euler method was used to approximate the trajectory of a body in free-fall experiencing a force due to drag. In order to check the accuracy of the Euler approximation, it was compared to an analytical approximation. The analytical prediction for height was given by
\begin{equation}
y = y_{0}-\frac{m}{k}\ln(\cosh(\sqrt{\frac{kg}{m}}t)),
\end{equation}
and for velocity,
\begin{equation}
v = -\sqrt{\frac{mg}{k}}\tanh(\sqrt{\frac{kg}{m}}t),
\end{equation}
\subsection{Speed of Sound}
The speed of sound is the distance travelled per unit time by a sound wave. At 20\degree C, it is about 343ms$^{-1}$, however this is variable, and depends on the temperature of the air,
\begin{equation}
v_{sound} = \sqrt{\frac{\gamma RT}{M}},
\end{equation}
where $\gamma$ is the adiabatic constant of the medium, $R$ is the gas constant, $M$ is the molecular mass of the gas, and $T$ is the absolute temperature. $\gamma$, $R$ and $M$ are all constant, so at higher altitudes where the temperature decreases, the speed of sound decreases \cite{Everest2001}.
\section{RESULTS AND DISCUSSION}

The vertical velocity and height of a body in free-fall from a height of 1 kilometre was modelled using Euler's method. The body had a cross-sectional area of 0.95m$^{2}$, which was kept constant, and the time step, $\Delta t$, was varied, and the Euler approximation compared with an analytical prediction. Figures \ref{ana-fig-ht-t=0.25} and \ref{ana-fig-vt-t=0.25} show the height and vertical velocity of a body plotted against time. Both plots follow the analytical approximation almost exactly. This shows that a small time step in Euler's approximation gives a very accurate prediction of the motion of a body.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-ht-t=025}
	\caption{Height-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  0.1s.}\label{ana-fig-ht-t=0.25}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-vt-t=025}
	\caption{Vertical velocity-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  0.1s.}\label{ana-fig-vt-t=0.25}
\end{figure}
As $\Delta t$ increases, the Euler approximation becomes increasingly less accurate, as seen in figures \ref{ana-fig-ht-t=2.0} and \ref{ana-fig-vt-t=2.0} (with $\Delta t$ equalling 2s), with a noticeable deviation from the analytical solution for the height-time graph, and a poorly defined curve for the velocity-time graph.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-ht-t=20}
	\caption{Height-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  2.0s.}\label{ana-fig-ht-t=2.0}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-vt-t=20}
	\caption{Vertical velocity-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  2.0s.}\label{ana-fig-vt-t=2.0}
\end{figure}
Increasing $\Delta t$ further causes the Euler approximation to break down, with the height-time graph becoming two straight lines at $t<5$s in figure \ref{ana-fig-ht-t=4.0}, compared to the smooth curve of the analytical solution, and the velocity-time graph becoming jagged in figure \ref{ana-fig-vt-t=4.0}.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-ht-t=40}
	\caption{Height-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  4.0s.}\label{ana-fig-ht-t=4.0}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-vt-t=40}
	\caption{Vertical velocity-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  4.0s.}\label{ana-fig-vt-t=4.0}
\end{figure}
As the mass of the body decreases, the Euler approximation becomes less accurate at larger time steps. Figures \ref{ana-fig-htm-t=2.0} and \ref{ana-fig-vtm-t=2.0} show the height-time and velocity-time graphs for a body of mass $m=25$kg and $\Delta t=2.0$s. Compared to figures \ref{ana-fig-ht-t=2.0} and \ref{ana-fig-vt-t=2.0}, there is a clear difference; the height-time graph is similar in shape to that in figure \ref{ana-fig-ht-t=4.0} ($\Delta t =4.0$s, $m=100$kg), but lying closer to the analytical solution, and the velocity-time is jagged like in figure \ref{ana-fig-vt-t=4.0} ($\Delta t =4.0$s, $m=100$kg), but with a smaller period of oscillation.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-htm-t=20}
	\caption{Height-time graph for a body of mass 25kg approximated using a time step $\Delta t$ of  2.0s.}\label{ana-fig-htm-t=2.0}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{ana-fig-vtm-t=20}
	\caption{Vertical velocity-time graph for a body of mass 25kg approximated using a time step $\Delta t$ of  2.0s.}\label{ana-fig-vtm-t=2.0}
\end{figure}

The Euler method was then compared with the modified Euler method, which accounted for a varying drag factor. For small $\Delta t$, both approximations have similar shapes, with the modified Euler method (varying drag) lying below the normal Euler method (fixed drag) for both height-time and velocity-time, as seen in figures \ref{euler-fig-ht-t=0.25} and \ref{euler-fig-vt-t=0.25}. The velocity curve is more pronounced in the modified Euler method, and it rises to meet the Euler method curve as $t$ increases.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{euler-fig-ht-t=025}
	\caption{Height-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  0.1s with varying drag.}\label{euler-fig-ht-t=0.25}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{euler-fig-vt-t=025}
	\caption{Vertical velocity-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  0.1s with varying drag.}\label{euler-fig-vt-t=0.25}
\end{figure}
As $\Delta t$ increases, both approximations behave similarly, however the gap between them increases slightly. This can be seen in figures \ref{euler-fig-ht-t=2.0} and \ref{euler-fig-vt-t=2.0}.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{euler-fig-ht-t=20}
	\caption{Height-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  2.0s with varying drag.}\label{euler-fig-ht-t=2.0}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{euler-fig-vt-t=20}
	\caption{Vertical velocity-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  2.0s with varying drag.}\label{euler-fig-vt-t=2.0}
\end{figure}
Once again, as $\Delta t$ is increased further, the height-time graph behaves as with the normal Euler method, and the velocity-time graph become quite jagged, with the modified method having a greater deviation from what it should be. This is seen in figures \ref{euler-fig-ht-t=4.0} and \ref{euler-fig-vt-t=4.0}.
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{euler-fig-ht-t=40}
	\caption{Height-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  4.0s with varying drag.}\label{euler-fig-ht-t=4.0}
\end{figure}
\begin{figure}
	\includegraphics*[width=0.96\linewidth,clip]{euler-fig-vt-t=40}
	\caption{Vertical velocity-time graph for a body of mass 100kg approximated using a time step $\Delta t$ of  4.0s with varying drag.}\label{euler-fig-vt-t=4.0}
\end{figure}

\subsection{Modelling Baumgartner's Jump}

An approximation of Felix Baumgartner's jump was simulated using the modified Euler method. Baumgartner was taken to have a mass of 64kg, jumping from  a height of 39045m. He jumped head-first, so the cross-sectional area was taken to be that of his shoulders (approximately $0.5$m$\times0.1$m), and $\Delta t=0.25$s. The scaling height in equation \ref{eq-va-air-dens} was taken as 7460m. The drag coefficient could be varied by the user, however it was set as 1.3 for this problem. With these parameters, the maximum speed reached by Baumgartner in this simulation was over 500ms$^{-1}$ at $t=65$s, and he broke the sound barrier at a speed of 312.7ms$^{-1}$ at roughly $t=35$s, and a height of 33938m above ground. The orange line on figure \ref{Baumgartner-vt} shows the sound barrier for the speed at which Baumgartner broke it, as this varies depending on the temperature of the air, and thus height of the body falling. According to the simulation, Baumgartner completed his jump in 125 seconds. However, in Baumgartner's jump, he took at least double this time to complete his jump, suggesting the values used for cross-sectional area and drag coefficient were incorrect.
\begin{figure}[H]
	\includegraphics*[width=0.96\linewidth,clip]{Baumgartner-ht}
	\caption{Height-time graph for Baumgartner's free-fall jump, approximated using a time step $\Delta t$ of 0.25s with varying drag.}\label{Baumgartner-ht}
\end{figure}
\begin{figure}[H]
	\includegraphics*[width=0.96\linewidth,clip]{Baumgartner-vt}
	\caption{Vertical velocity-time graph for Baumgartner's free-fall jump, approximated using a time step $\Delta t$ of 0.25s with varying drag.}\label{Baumgartner-vt}
\end{figure}
By adjusting these values, a much closer approximation to his jump was obtained. This is seen in figures \ref{Baumgartner-ht2} and \ref{Baumgartner-vt2}. The drag coefficient was reduced to 1.08, and the cross-sectional area and mass increased to 0.28m$^{2}$ and 70kg respectively to account for extra equipment he was carrying. With this new simulation, the maximum speed was much more realistic, at approximately 370ms$^{-1}$ at $t=50$s. Baumgartner broke the sound barrier at a speed of 311.5ms$^{-1}$ and a height of 33316m, and had a much longer flight time of 245s.
\begin{figure}[H]
	\includegraphics*[width=0.96\linewidth,clip]{Baumgartner-ht2}
	\caption{Height-time graph for Baumgartner's free-fall jump, approximated using a time step $\Delta t$ of 0.25s with varying drag and improved parameters.}\label{Baumgartner-ht2}
\end{figure}
\begin{figure}[H]
	\includegraphics*[width=0.96\linewidth,clip]{Baumgartner-vt2}
	\caption{Vertical velocity-time graph for Baumgartner's free-fall jump, approximated using a time step $\Delta t$ of 0.25s with varying drag and improved parameters.}\label{Baumgartner-vt2}
\end{figure}

\section{IMPROVEMENTS TO CODE}

The program could have been improved by extending the approximations to include a different, more accurate Runge-Kutta approximation for the differential equation. The simulation could have been extended by simulating a parachute after a certain height had been reached. Better validation could have been added to the custom values section, instead of defaulting to a hard-programmed value, as well as restricting $\Delta t$ and $v_{0}$ values to prevent unexpected behaviour. During the jump, the drag coefficient would not have remained constant, as it is dependent on $v$, so corrections could be added to the code to account for this. As well as this, Baumgartner did not remain rotationally stationary during his jump, so his cross-sectional area may have changed, and corrections could be made for this by randomly varying the cross-sectional area within a small range to simulate this behaviour. The code could be made more concise by moving some re-used sections of code into their own function, and while attempts were made to do this, there are several other areas where this could have been done, especially with the calculation of the sound barrier.

\section{CONCLUSIONS}

The Euler model has been shown to be valuable in approximating ordinary differential equations and modelling an object in free-fall. It could be made better by reducing $\Delta t$, however this change would be negligible below $\Delta t = 0.2$s, and so this may be unnecessary. To improve on the model, a different Runge-Kutta method of solving an ODE could be used, allowing a larger $\Delta t$ to be used while giving the same error, significantly reducing the computational load and making the program more efficient.

\section{REFERENCES}
%Do not include material in your reference list that is not specifically referred to in the text.  It is not a list of
%things you have read but rather a list of things you refer to in the text. Only refer to web based material if
%absolutely necessary. You should refer, where ever possible, to the original material in a textbook or academic
%journal.   A good report should have many references - showing that the subject has been widely researched.  The style
%to be used for the references is shown below.

\bibliographystyle{unsrt}
\bibliography{C:/Users/Francis/Documents/Bibtex/Coding-Report-2}

\end{document}


\section{Overview}
\label{section1}
\begin{frame}{Overview}
\begin{itemize}[<+->]
 \item The trivial Set Cover algorithm has running time of ${\cal O}(2^n)$.
 \item bla, bla, bla\ldots
\end{itemize}

\end{frame}


\section{Assembling Multiple Insert Length Libraries}

\begin{note}
Like the previous examples, the data you will examine in this exercise is again
from Staphylococcus aureus which still has a genome of around 3MB. The reads are
Illumina paired end with an insert size of 170 bp and 350 bp.

You already downloaded the required reads from the SRA in previous exercises.
Specifically, the run data (SRR022863, SRR022852) from the SRA Study SRP001086.

\center{\url{http://www.ebi.ac.uk/ena/data/view/SRP001086}}
\end{note}

\begin{information}
The following exercise focuses on handing two insert length libraries with
velvet and the changes you have to look out for.
\end{information}

\begin{steps}
First move to the directory you made for this exercise, make a suitable named
directory for the exercise and check if all the files are in place:
\begin{lstlisting}
cd ~/NGS/velvet/part3
mkdir SRP001086
cd SRP001086
ln -s ~/NGS/Data/SRR022863_?.fastq.gz ./
ln -s ~/NGS/Data/SRR022852_?.fastq.gz ./
\end{lstlisting}

Now run \texttt{velveth} and \texttt{velvetg} using the appropriate command line
options by typing:
\begin{lstlisting}
time velveth run_25 25 -fmtAuto -create_binary -shortPaired -separate SRR022863_1.fastq.gz SRR022863_2.fastq.gz -shortPaired2 -separate SRR022852_1.fastq.gz SRR022852_2.fastq.gz
time velvetg run_25
\end{lstlisting}

The right thing to do is to run velvetg setting the cut-offs. To investigate
with R, as you did in the previous exercises, start up R and produce the
weighted histogram using the columns \texttt{short1\_cov} and
\texttt{short2\_cov} by typing:
\begin{lstlisting}[style=R]
R --no-save
library(plotrix)
data <- read.table("run_25/stats.txt", header=TRUE)
weighted.hist(data$short1_cov+data$short2_cov, data$lgth, breaks=0:70)
\end{lstlisting}

\begin{figure}[H]
\centering
\includegraphics[width=0.8\textwidth]{de_novo/velvet/velvet_Rplot004.png}
\caption{\label{fig:velvet_Rplot004}}
\end{figure}

For me the histogram suggests a coverage cut-off of around 28
with an expected coverage of about 36. If you disagree, feel free to try
different settings, but first leave R before running \texttt{velvetg} with the coverage
parameters typing:
\begin{lstlisting}[style=R]
q()
\end{lstlisting}

\begin{lstlisting}
cp run_25/contigs.fa run_25/contigs.fa.0

time velvetg run_25 -cov_cutoff 28
cp run_25/contigs.fa run_25/contigs.fa.1

time velvetg run_25 -cov_cutoff 28 -exp_cov 36
cp run_25/contigs.fa run_25/contigs.fa.2

time velvetg run_25 -cov_cutoff 28 -exp_cov 36 -ins_length 170 -ins_length2 350
cp run_25/contigs.fa run_25/contigs.fa.3

gnx -min 100 -nx 25,50,75 run_25/contigs.fa*
\end{lstlisting}

\end{steps}

\begin{questions}
What was the best N50 you got?
\begin{answer}
62,741 bp
\end{answer}

How did the runtime/results compare to a run with a single paired-end library?
\begin{answer}
More memory, longer runtime, (in this case) similar results
\end{answer}

How many different libraries would you be able to run with this velvet version?
\begin{answer}
2 paired-end (or mate-pair) + one single end
\end{answer}

Would you be able to add a single-end library as well with this velvet version?
\begin{answer}
Yes
\end{answer}
\end{questions}

\begin{bonus}
Output an AMOS message file, convert it into an AMOS bank, update the
estimations for the insert size distributions and view the assembly with
Hawkeye.

\begin{lstlisting}
time velvetg run_25 -cov_cutoff 28 -exp_cov 36 -ins_length 170 -ins_length2 350 -amos_file yes -read_trkg yes
cp run_25/contigs.fa run_25/contigs.fa.4
gnx -min 100 -nx 25,50,75 run_25/contigs.fa.4

bank-transact -c -b run_25/velvet_asm.bnk -m run_25/velvet_asm.afg
asmQC -b run_25/velvet_asm.bnk -scaff -recompute -update -numsd 2
hawkeye run_25/velvet_asm.bnk
\end{lstlisting}

\begin{questions}
What are the mean and SD for the insert size distributions for the two libraries
used in the assembly?
\begin{answer}
Mean: 129; SD:31
Mean: 227; SD:19
\end{answer}
\end{questions}

\end{bonus}

% \begin{bonus}
% Find and download a different insert length library
% % TODO: \footnote affects the width of the shaded box - \renewcommand{\footnote}?
% \footnotemark[1]
% from the
% study SRP001086 and recompile velvet to allow the use of three insert length
% libraries. Maybe you could use the library you trimmed during previous
% exercises. You should be able to find these files here:
% \texttt{~/NGS/velvet/part2/SRX008042/SRR023408\_trim?.fastq}. If you don't still
% have these files, you can find a copy of them here:
% \texttt{~/NGS/Data/SRR023408\_trim?.fastq}.
% Use the fresh compiled Velvet version with the three (two provided and one
% downloaded library) to assemble the genome.
% \begin{questions}
% Does the extra library make any difference?
% \begin{answer}
% % TODO
% \end{answer}
%
% How does the overall coverage change?
% \begin{answer}
% % TODO
% \end{answer}
%
% Any other comments?
% \begin{answer}
% % TODO
% \end{answer}
% \end{questions}
% \footnotetext[1]{Paired insert
% lengths can be found on the NCBI SRA page in the library section (Nominal
% length) e.g. \url{http://www.ncbi.nlm.nih.gov/sra?term=SRR022866}}
% \end{bonus}


\documentclass[12pt]{article}
\input{physics1}
\begin{document}

\section*{NYU Physics I---Problem Set 13}

Due Thursday 2018 December 6 at the beginning of lecture.

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
Get a sense of the speed of light by computing two things:

\textsl{(a)} How many times could light go around the equator of the Earth
in a time interval of $1\,\s$?

\textsl{(b)} How long (in ns) does it take light to go $1\,\ft$?

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
From the notes at \url{http://cosmo.nyu.edu/hogg/sr/},
Problem 3--4. Note that there is a typo in this part \textsl{(d)} of this
problem: It is the Earth that replies, not the station.

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
From the notes at \url{http://cosmo.nyu.edu/hogg/sr/},
Problem 2--14.

\paragraph{\problemname~\theproblem:}\refstepcounter{problem}%
\textsl{(a)} What is $\gamma$ to first order in $\beta^2$ for $\beta
<< 1$? That is, construct a Taylor Series for $\gamma$ in terms of
$\beta^2$ and give the zeroth-order term (1) and then the first-order
term.

\textsl{(b)} What are $\beta$ and $\gamma$ for a person walking
(relative to the sidewalk), a driver on the freeway (relative to the
road), a commercial jet (relative to the air), and an astronaut in the
ISS (relative to the center of mass of the Earth)? Use the first-order
expression from part \textsl{(a)} to compute the $\gamma$ values.

\textsl{(c)} Computing the full time dilation effect in gravity is
complicated! However, the pure kinematic part of the time dilation
only depends on $\gamma$. Two twins part. One gets on the ISS for a
year, and one stays on Earth. When they are reunited in a year, how
much younger is the astronaut than the homebody?

\paragraph{Extra Problem (will not be graded for credit):}%
If the total energy (rest mass plus kinetic) of a point particle is
$\gamma\,m\,c^2$, use the result from \problemname~3 above to get an
approximate expression for the kinetic energy at low speeds.

\end{document}


\documentclass[11pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
%\usepackage[ddmmyyyy]{datetime}
\usepackage[short,nodayofweek,level,12hr]{datetime}
%\usepackage{cite}
%\usepackage{wrapfig}
%\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}

\newcommand{\e}{\epsilon}
\newcommand{\dl}{\delta}
\newcommand{\pd}[2]{\frac{\partial #1}{\partial #2}}
\newcommand{\describe}[2]{\underbrace{#2}_{\text{#1}}}% \describe{}{} - First bracket is for description
%\describe{$\substack{this \ is \ substacking}$}{b} - To split the description over multiple lines
\newcommand{\vect}[1]{\underline{#1}}
\newcommand{\uvect}[1]{\hat{#1}}
\newcommand{\1}{\vect{1}}
\newcommand{\grad}{\nabla}
\newcommand{\ux}{u_x}
\newcommand{\uy}{u_y}
\newcommand{\RA}{\Rightarrow}

\title{Kinematics: Surface Gravity Waves}
\date{\displaydate{date}}
\newdate{date}{03}{10}{2018}
\author{}

\begin{document}
\maketitle

\section{Overview}

We want to observe the flow induced due to a propagating surface gravity wave in the ground frame and in the comoving frame using the dispersion relation derived earlier.

\section{Streamlines due to surface gravity waves}

The relation between frequency ($\omega$) and wavenumber ($k$) of a surface gravity wave, as derived before is
\begin{align*}
&\omega^2(k) = \tanh(kH)\bigg(gk + \frac{\Gamma k^3}{\rho} \bigg) \tag{dispersion relation}
\end{align*}
where  $H$ is the depth of the basin and $\Gamma$ is the surface tension. To obtain the flow field, we used the irrotational flow approximation and obtained the velocity potential $\phi(x,y)$ as
\begin{align*}
&\phi(x,y) =
\end{align*}
Using the velocity ptential we can evaluate the velocity fields
\begin{align*}
&\ux = \pd \phi x = \\
&\uy = \pd \phi y =
\end{align*}
We can now analyze the streamlines, starting with the comoving frame.

\subsection{Analysis in the comoving frame}

This is the case where fluid sweeps past us with a velocity $c$ but crest and troughs of the wave do not change postion. Note that the time dependence of velocity and potential fields comes in via the term $\cos(k x - \omega t) = \cos(k(x-ct))$, which indicates that the waveform is travelling to the right with a velocity $c$. If we change our frame of reference to one which moves with $c$ to the right, i.e. $\hat x = x- ct$, then we have $\cos(k(x-ct)) = \cos(k\hat x)$. Hence in the comoving frame, the velocity is not time dependent. The flow becomes steady and hence the streamlines and pathlines are identical.
The coordinate transformation is
\begin{align*}
&\hat x = x-ct\\
&\hat y = y
\end{align*}
The velocities are given by
\begin{align*}
&\ux = \\
&\uy =
\end{align*}
The equation for streamlines is given by
\begin{align*}
&\frac{d\hat x}{\ux} = \frac{d\hat y}{\uy}\\
\RA&\frac{d\hat x}{d\hat y} = \frac{\ux}{\uy} =
\end{align*}
In this expression, note the term proportional to $c/A\omega$ in the denominator. We know that
\begin{align*}
&\frac{c}{A\omega} = \frac{\omega}{k A \omega} \sim \frac{\lambda}{A} \gg 1
\end{align*}
since amplitube is much smaller than any other length scale in the problem and hence much smaller than the wavelength of perturbation $\lambda$. Therefore we neglect the other term in the denominator in favour of this term and obtain
\begin{align*}
&\frac{d\hat y}{d\hat x} =
\end{align*}
This integration is over both $y$ and $x$, but if note that $\hat y + H \sim \hat y_0 + H$ where $\hat y_0$ is the mean ordinate of the fluid element about which it oscillates. Then the integration only needs to be performed over $x$. This gives
\begin{align*}
&\hat y = \hat y_0 + A\bigg( \frac{\sinh(k(y_0+H))}{\sinh(kH)}\bigg)\sin(k\hat x)
\end{align*}
which is the equation relating $\hat x$ and $\hat y$- the equation for the pathlines (and for this case, streamlines as well). If we assume that the basin depth is large compared to the wavelength ($\lim kH \to \infty$), then we get the streamlines for the deep water limit case as
\begin{align*}
&y= y_0 + Ae^{ky}\sin kx
\end{align*}

\subsection{Analysis in the lab frame}

In this case, the fluid doesn't sweep past us, but the crests and troughs travel at speed $c$. The flow pattern will be unsteady and so pathlines will not be the same as streamlines. The derivation is straightforward.
As before, we write down the velocities (in lab frame)
\begin{align*}
&\ux = \frac{dx}{dt} = \\
&\uy = \frac{dy}{dt} = \\
\RA& \frac{dy}{dx} = \\
\RA& \sinh(k(y+H))\sin(k x - \omega t) = c
\end{align*}
which is the equation for the streamlines. We can draw the pattern at $t=0$ and just translate it to the right for $t>0$. The streamlines in this case look markedly different from the those in the comoving frame.	Especially we see that there is vertical motion of the order of depth of the basin (or wavelength; whichever is larger).

In order to obtain the pathlines, we need an equation relating $y$ and $x$. As before we obtain it from a ratio of $dx/dt$ and $dy/dt$. This gives
\begin{align*}
&\frac{dy}{dx} =
\end{align*}
This just gives us a point, indicating that particles just stay where they are. To investigate their motion, we need to go to next higher order approximation. Let
\begin{align*}
&x = x_0 + \dl x_1\\
&y = y_0 + \dl y_1
\end{align*}
where $\dl x^1$ and $\dl y^1$ are $O(A)$. We can substitute this ansatz in equations for $dx/dt$ and $dy/dt$ and seperate out terms of zeroth order and terms of $O(A)$. The $O(A)$ equation gives
\begin{align*}
&\frac{d\dl x}{dt} = \\
&\frac{d\dl y}{dt} = \\
\RA& \dl x = \\
& \dl y = \\
\RA& \frac{\dl x^2}{\hat A^2 \cosh^2(kH)} + \frac{\dl y^2}{\hat A^2 \sinh^2(kH)} = 1
\end{align*}
and therefore, pathlines are ellipses with centers at $(x_0,y_0)$. In the deep water limit, these become circles. If we consider the approximation to the next order, we observe that particles in-fact do not trace closed curves and experience a net drift in the direction of the wave velocity. This is known as the Stokes' Drift.

\subsection{Stokes Drift}

We write a perturbation expansion for the the $x$ and $y$ coordinates of the particles
\begin{align*}
&x = x_0 + \dl x_1 + \dl x_2\\
&y = y_0 + \dl y_1 + \dl y_2\\
\end{align*}
where the first terms are $O(H)$, the second terms are $O(A)$, third are $O(A^2)$ and so on (In non-dimensional terms, the ordering would be $O(1)$, $O(A/H)$, $O((A/H)^2)$ and so on). Substitute this ansatz in the governing equations for $\dl x$ and $\dl y$
\begin{align*}
&\frac{d\dl x}{dt} = \frac{d\dl x_1}{dt} + \frac{d\dl x_2}{dt} = \\
&\frac{d\dl y}{dt} = \frac{d\dl y_1}{dt} + \frac{d\dl y_2}{dt} =
\end{align*}

Taylor expand the RHS about ($x_0 + \dl x_1, y_0 + \dl y_1$). Cancelling off the first order solution and ignoring terms of third order, gives us the governing equation for second order perturbations - ($\dl x_2, \dl y_2$)
\begin{align*}
&\frac{d\dl x_2}{dt} = \\
&\frac{d\dl y_2}{dt} =
\end{align*}
The equation for $\dl x_1$ gives us the mean drift if we take an average of $\dl x_1$ over an interval of $2\pi/\omega$ i.e. the mean drift ($D$) is given by
\begin{align*}
&D = \int_0^{2\pi/\omega}\dl x^1 dt
\end{align*}
For the deep water limit, we get a simplified expression
\begin{align*}
&D = k\omega A^2 e^{2ky_0}
\end{align*}

\end{document}


% !TEX root = cs1textbook.tex

\chapter{Mutators and Parameterized Constructors}
\label{chapter:mutators}

\minitoc

In Chapters \ref{chapter:classes} and \ref{chapter:default-constructors} we developed enough of a \texttt{Point} class to be able to instantiate \texttt{Point} objects and see what they store.  But right now, all they can store is $(0,0)$.  In this chapter, we see how to customize the values stored in the object.

\section{Mutators}

Once an object has been created, the secure way to allow an outside class to change the values stored in the instance variables is to write a \mintinline{java}{public} \textit{mutator} method.

\begin{defn}{Mutator}
    A \textbf{mutator method}\index{Methods!Mutators} is a method that grants public privileges to change private data.
\end{defn}

Mutator conventions are very similar to accessor conventions:

\bi
\item Write one mutator per instance variable (or fewer -- you might not want to grant edit access to every instance variable)
\item Begin the method's identifier with \texttt{set}
\item Finish the method's identifier with the name of the instance variable, capitalizing the first letter
\item The return type of the method should be \mintinline{java}{void}
\item The method should have one formal parameter, of the same data type as the instance variable whose value is getting changed
\ei

With that being said, a naive programmer might initially write a mutator like this:

\begin{trap}{Mutator}
    Don't just store data from the caller without validating it, like this:
    \begin{minted}{java}
    public void setX( int newXVal ) {
        x = newXVal;
    }
    \end{minted}
\end{trap}

The code in that Trap will store any value sent to it from the caller as the $x$ portion of our ordered pair -- even a negative value, which we decided is not valid for the \texttt{Point} class.  We must \textit{validate} any value that comes in from the mutator before using it.  For this class, it means only storing non-negative numbers.  Here's a better mutator:

\begin{minted}{java}
    /**
     * Change the value of the x coordinate
     * @param newXVal  the proposed new x coordinate (must be non-negative)
     */
    public void setX( int newXVal ) {
        if( newXVal >= 0 )
            x = newXVal;
    }
\end{minted}

\begin{tip}{Data Validation}
    Only you can ensure that your instance variables always contain valid data.  When writing a method like a mutator -- one that changes instance variables based on external values -- always validate those external values.  Never trust the caller to have sent in proper data.
\end{tip}

\subsection{Testing}

Remember to test your code every time you add a method!

\begin{minted}{java}
public class TestPoint {
    public static void main( String args[] ) {
        Point p1 = new Point();

        // Test the default constructor
        System.out.println( "p1's x value should be 0 and is " + p1.getX() );
        System.out.println( "p1's x value should be 0 and is " + p1.getX() );

        // Test the mutators with valid requests
        p1.setX( 5 );
        System.out.println( "p1's x value should be 5 and is " + p1.getX() );
        p1.setY( 16 );
        System.out.println( "p1's y value should be 16 and is " + p1.getX() );

        // Be sure to test edge cases!  0 should be considered valid
        p1.setX( 0 );
        System.out.println( "p1's x value should be 0 and is " + p1.getX() );
        p1.setY( 0 );
        System.out.println( "p1's y value should be 0 and is " + p1.getY() );

        // Test the mutators with invalid requests
        p1.setX( -1 );
        System.out.println( "p1's x value should be 0 and is " + p1.getX() );
        p1.setY( -1 );
        System.out.println( "p1's x value should be 0 and is " + p1.getX() );
    }
}
\end{minted}

\section{Scope}

This code might not do what you think it does:

\begin{trap}{Scope}
    The instance variable is named \texttt{x}.  What if the parameter is also named \texttt{x}?
    \begin{minted}{java}
    public void setX( int x ) {
        x = x;
    }
    \end{minted}
\end{trap}

When this method runs, there exist two completely different variables called \texttt{x}: the instance variable that's declared near the top of the class definition, and the formal parameter declared in the mutator's header.  While these variables have the same name, they exist in different places in memory, and changes made to one have no effect on the other.

Programmers use the word \textit{scope} to describe the parts of code in which a variable exists or doesn't exist.  A formal parameter has the same scope as a \textit{local variable} declared within the body of a method; both of these are scoped only within the method.  Instance variables, on the other hand, exist in \textit{class scope}; that is, you can type the name of an instance variable anywhere within the definition of a class and refer to that variable -- with one big exception.  A closer, or more local, scope always supercedes a larger scope.

\begin{defn}{Scope}
    Every variable has a \textbf{scope}\index{Scope}, which is the portion of code in which that variable exists.  As a general rule, the scope of a variable is bounded by the closest set of curly braces.  (The exception to this is formal parameters, which are defined in a method's header, but scoped within the method's body.)  A class, a method, and a compound statement like a conditional or a loop can all serve as a variable's scope.
\end{defn}

In the case of the preceding code trap, the formal parameter is what's referred to by every occurrence of the mane \texttt{x}.  There are no references to the instance variable.  The assignment statement, then, sets the formal parameter equal to itself.  When this method ends, the instance variable will still have the value it had when the method began.

\subsection{Resolving Scope with \texttt{this}}

The keyword \texttt{this}\index{this()@\mintinline{java}{this}} has a couple of uses in the Java language.  The one that's most relevant here is that it can be used like an object's identifier to mean ``the present instance'', to resolve the scope of an otherwise ambiguous identifer.  For example, in the \texttt{setX} mutator, the identifier \mintinline{java}{this.x} would mean ``the instance variable called x'', whereas \texttt{x} by itself would still mean the formal parameter, which is the variable called \texttt{x} that was declared most locally.  We can therefore use \texttt{this} to fix the bug in the code trap:

\begin{minted}{java}
    // Alternate definition of setX, using this for scope resolution
    public void setX( int x ) {
        this.x = x;
    }
\end{minted}

It is the author's opinion that code like this should be avoided, since it's easy to accidentally add ambiguity.  However, the author will concede that on rare occassions, there really is no better name for a mutator's parameter than the one used already for the instance variable.

\section{Parameterized Constructors}
\label{section:parameterized-constructors}

As our code currently stands, if we want to make a \texttt{Point} to represent the point $(5, 16)$, we have to construct a \texttt{Point} at $(0,0)$ and then call two mutators to change the coordinates.  It would save us some steps if we could customize the object while we instantiate it.  This is why programmers write \textit{parameterized constructors.}

A \textbf{parameterized constructor}\index{Methods!Constructors!Parameterized constructor}, as the name implies, is a constructor that has one or more parameters.  While every class needs to have a default constructor, not every class needs a parameterized one.  Or, if you find that it's appropriate to do so, you can provide more than one parameterized constructor in a class.  Whether you provide any is your choice, but parameterized constructors can make it easier for programmers to instantiate your class the way they want to.

When writing a parameterized constructor, it is essential to remember these two things that we've learned in recent chapters:

\bi
\item A constructor must initialize all instance variables with valid data values
\item A method that changes instance variables based on external values must validate those external values
\ei

A parameterized constructor must do both of these things.  Our \texttt{Point} class constructor, then, should probably examine each parameter, use it if it's valid, and use the default value instead if it isn't.  Here's a first attempt:

\begin{minted}{java}
    // A first attempt at a parameterized constructor
    public Point( int xVal, int yVal ) {
        if( xVal >= 0 )
            x = xVal;
        else
            x = 0;

        if( yVal >= 0 )
            y = yVal;
        else
            y = 0;
    }
\end{minted}

We can make this code a little bit shorter if we set the instance variables to their default values, and then use simple if statements to change the values if appropriate.

\begin{minted}{java}
    // A second, slightly shorter, version of the parameterized constructor
    public Point( int xVal, int yVal ) {
        // Set instance variables to default values
        x = 0;
        y = 0;

        // Use parameters if their values are valid
        if( xVal >= 0 )
            x = xVal;

        if( yVal >= 0 )
            y = yVal;
    }
\end{minted}

\subsection{Avoid Repeated Work}

The code above does what we want it to.  It allows the caller to decide on a point's values at the time the object is created, and it validates those values, making sure that only valid values are stored in the object.

However, just because the code \textit{works}, doesn't mean it's \textit{right}.

All of the logic in that constructor exists in another part of the code, also -- the default values are set in the default constructor, and the validation occurs in the mutators.  It's easy to see that re-typing the same code could lead to a typo - for instance, pressing the 9 key instead of the 0 key when entering the default value for $y$.  But there also exist more compelling reasons to avoid repeated code.  What would happen if we decided to change the default values?  We would now have to make that change in two different parts of the code.  What would happen if we changed the specification so that $x$ and $y$ could only be even numbers?  We would also need to make these changes in multiple places.  Further, time is a non-renewable resource, and we shouldn't spend it re-solving solved problems.

All this leads to the old adage ``DRY'' -- \textbf{don't repeat yourself}.

\begin{tip}{Don't Repeat Yourself}
    Repeating code wastes your time, can lead to copy-and-paste errors, and can cause logical decisions to be handled in different ways when code changes aren't correctly propagated.  Solve each problem once, and reuse that code when needed.
\end{tip}

Since all the logic in the parameterized constructor above exists in other places, the best solution is to call it when needed.

\subsection{Calling Constructors with \texttt{this()}}

The right way to set the instance variables to their default values from within the parameterized constructor is to use the default constructor.  We can call one constructor from another by using the keyword \mintinline{java}{this} with parentheses, so that it looks like a method call: \mintinline{java}{this();}\index{this()@\mintinline{java}{this()}}.  When using \mintinline{java}{this()} in this way, it must be the first statement in the constructor.

The next iteration of the parameterized constructor reuses the code from the default constructor and the mutators to get the same job done, while ensuring that the logic for each decision only exists in one place:

\begin{minted}{java}
    // A parameterized constructor free of repeated logic
    public Point( int xVal, int yVal ) {
        // Set instance variables to default values
        this();

        // Use parameters if their values are valid
        setX( xVal );
        setY( yVal );
    }
\end{minted}

To review:
\bi
\item Default values for instance variables are defined in the default constructor
\item The logic concerning acceptable changes to instance variables is defined in the accessors
\item Any other code that assigns default values, or changes values, should use those methods
\ei

This will ensure that decisions about your instance variables are only made in one place.