\chapter{Information Visualization}
\label{chap:InfoVis}

Information visualization seeks to use interactive graphics to assist
in the analysis and presentation of abstract information. Information
visualization builds on capabilities of human visual perception,
including the rapid scanning, recognition, and recall of visual
information, as well as the automatic detection of visual patterns. In
contrast to textual representations of data, the processing of
well-designed visualizations requires less cognitive effort,
because it leverages features of the human visual processing
system. One of these features is \emph{preattentive processing},
whereby certain visual attributes can be processed very quickly and
without conscious effort \parencite{PreattentiveProcessing}.
% KA give an example of a pre-attentive feature

In addition to visuals being easier to assimilate by humans, a purely
textual and statistical view of data can also lead to erroneous
assumptions. This is demonstrated in Anscombe's famous example of four
completely different datasets (variables in $x$ and $y$) having
identical summary statistics (mean and standard deviation), called
Anscombe's Quartet \parencite{AnscombesQuartet}, shown in
Table~\ref{tab:AnscombeTable}. An observer trying to understand these
datasets from their summary statistics alone might mistakenly deem
them to be identical. Their inequality only becomes obvious after
carefully examining and comparing the individual entries in the
datasets themselves.
%
However, the differences in the four datasets are immediately obvious
when plotted graphically, as can be seen in
Figure~\ref{fig:AnscombePlot}. Even though Anscombe's Quartet is
likely the most famous example demonstrating this characteristic, it
is certainly not the only example, as has been shown by
\textcite{GenDataIdenticalStatisticsDissimilarGraphics}.

\begin{table}[tp]
\centering
\tablestretch
\rowcolors{3}{tablerowcolour}{}
\begin{small}
\begin{tabular}{>{\kern-\tabcolsep}rcrrcrrcrrcrr<{\kern-\tabcolsep}}
\toprule
\hiderowcolors
  & \phantom{i} &
  \multicolumn{2}{c}{$\mathbf{v_1}$} & \phantom{a} &
  \multicolumn{2}{c}{$\mathbf{v_2}$} & \phantom{a} &
  \multicolumn{2}{c}{$\mathbf{v_3}$} & \phantom{a} &
  \multicolumn{2}{c}{$\mathbf{v_4}$} \\
\cmidrule(l{1em}r){3-4}\cmidrule(l{1em}r){6-7}\cmidrule(l{1em}r){9-10}\cmidrule(l{1em}r){12-13}
  & & $x_1$ &  $y_1$ & &  $x_2$ & $y_2$ & & $x_3$ &  $y_3$ & &  $x_4$ &  $y_4$ \\
\midrule
\showrowcolors
  & & 10.00 &   8.04 & &  10.00 &  9.14 & &  10.00 &   7.46 & &   8.00 &   6.58 \\
  & &  8.00 &   6.95 & &   8.00 &  8.14 & &   8.00 &   6.77 & &   8.00 &   5.76 \\
  & & 13.00 &   7.58 & &  13.00 &  8.74 & &  13.00 &  12.74 & &   8.00 &   7.71 \\
  & &  9.00 &   8.81 & &   9.00 &  8.77 & &   9.00 &   7.11 & &   8.00 &   8.84 \\
  & & 11.00 &   8.33 & &  11.00 &  9.26 & &  11.00 &   7.81 & &   8.00 &   8.47 \\
  & & 14.00 &   9.96 & &  14.00 &  8.10 & &  14.00 &   8.84 & &   8.00 &   7.04 \\
  & &  6.00 &   7.24 & &   6.00 &  6.13 & &   6.00 &   6.08 & &   8.00 &   5.25 \\
  & &  4.00 &   4.26 & &   4.00 &  3.10 & &   4.00 &   5.39 & &  19.00 &  12.50 \\
  & & 12.00 &  10.84 & &  12.00 &  9.13 & &  12.00 &   8.15 & &   8.00 &   5.56 \\
  & &  7.00 &   4.82 & &   7.00 &  7.26 & &   7.00 &   6.42 & &   8.00 &   7.91 \\
  & &  5.00 &   5.68 & &   5.00 &  4.74 & &   5.00 &   5.73 & &   8.00 &   6.89 \\
\hiderowcolors
\addlinespace[0.5em]
\textbf{mean} & &
  \textbf{9.00} & \textbf{7.50} & &
  \textbf{9.00} & \textbf{7.50} & &
  \textbf{9.00} & \textbf{7.50} & &
  \textbf{9.00} & \textbf{7.50} \\
\textbf{sd} & &
  \textbf{3.3166} & \textbf{2.0316} & &
  \textbf{3.3166} & \textbf{2.0317} & &
  \textbf{3.3166} & \textbf{2.0304} & &
  \textbf{3.3166} & \textbf{2.0306} \\
\bottomrule
\end{tabular}
\end{small}

\caption[Anscombe's Quartet in Tabular Form]
{
The four datasets (variables) in Anscombe's Quartet look identical if
only standard summary statistics like mean and standard deviation are
considered. The difference between the datasets is only apparent after
careful examination of the numbers.
}
\label{tab:AnscombeTable}
\end{table}

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\halfh]
{diagrams/anscombe.pdf}
\caption[Anscombe's Quartet]{
When plotted graphically, it is immediately apparent that
the four datasets in Anscombe's Quartet are very different.
\imgcredit{Image extracted from \textcite{IVISCourseNotes}.
Used with kind permission by Keith Andrews.}
}
\label{fig:AnscombePlot}
\end{figure}

This thesis adheres to the characterization of the field of
visualization as having three main subfields, as defined by
\textcite{IVISCourseNotes}:
\begin{enumerate}
\item \liintro{Information Visualization (InfoVis)}: Deals with
  abstract data, which has no inherent geometry or visual form and for
  which a suitable type of visualization has to be chosen.

\item \liintro{Geographic Visualization (GeoVis)}: Deals with
  map-based data which has inherent 2d or 3d spatial geometry.

\item \liintro{Scientific Visualization (SciVis)}: Deals with
  real-world objects having inherent 2d or 3d geometry, which
  is used as the basis for visualization.
\end{enumerate}
The often-used term \enquote{data visualization} (\emph{DataVis}) is
defined as the combination (union) of information visualization and
geographic visualization.

Visualizations presented in an interactive medium do not merely
consist of visual representations. It is equally important to provide
means for interacting with these representations to analyze more
complex datasets. Without interactions, a visualization is just a
static image and has only very limited use when dealing with large and
multidimensional datasets. Even though the majority of attention in
the field of information visualization has been directed towards the
presentational aspect of visualizations, research has also been done
on their interactive aspects. Numerous taxonomies have been formulated
with the goal of defining the design space of interactions to support
analytic reasoning, but they vary greatly depending on the concepts
they are focusing on. Some taxonomies have been defined on the concept
of low-level interaction techniques
\parencite{TheEyesHaveIt,GrammarOfGraphics}, providing a very
system-centric view on interaction. Other taxonomies focus on user
tasks \parencite{LowLevelComponentsOfAnalyticActivity}, which are not
necessarily strongly related to interacting with visualizations.
\textcite{RoleOfInteractionInInformationVisualization} aims to provide
a view in between the purely system-centric and purely user-centric
extremes by defining a taxonomy based on what a user wants to achieve,
also known as \emph{user intent}. The categories of this taxonomy are
shown in Table~\ref{tab:UserIntentCategories}. They provide a good
framework for the discussion of interactivity in the context of
information visualization.

\begin{table}[tp]
\tablestretch
\rowcolors{2}{}{tablerowcolour}
\centering
\begin{small}
\begin{tabularx}{\linewidth}{>{\kern-\tabcolsep}lL{0.35\linewidth}X<{\kern-\tabcolsep}}
\toprule
Category & Description & Examples \\
\midrule
Select &
  Mark something as interesting. &
  Highlighted selections, placemarks, assigning classes. \\
Explore &
  Show me something else. &
  Different subset of data, panning, direct-walk. \\
Reconfigure &
  Show me a different arrangement. &
  Sorting, rearranging columns, plotting different dimensions, using an alternative projection. \\
Encode &
  Show me a different representation. &
  Changing visual encoding (color, size, shape), or even chart type. \\
Abstract / Elaborate &
  Show me more or less detail. &
  Details-on-demand, drill-down and roll-up, tooltips, zooming in and out. \\
Filter &
  Show me something conditionally. &
  Dynamic queries, range sliders, toggle buttons, query by example. \\
Connect &
  Show me related items. &
  Brushing across views, highlighting connected items on mouseover. \\
\bottomrule
\end{tabularx}
\end{small}
\caption[Categories of Interaction Based on User Intent]{
Categories of interaction with visualizations based on what
a user wants to achieve (user intent).
\imgcredit{From \textcite{RoleOfInteractionInInformationVisualization}}
}
\label{tab:UserIntentCategories}
\end{table}

\section{History of Information Visualization}

The history of information visualization goes back a long time. One of
its earliest examples dates back to the \nth{10} Century, when an
unknown astronomer created the chart about the movement of prominent
planets \parencite{CommentariiInSomniumScipionis} shown in
Figure~\ref{fig:PlanetaryMovements}.
% KA: 1175 is the 12th Century not the 10th
Other noteworthy early visualizations include the first occurrence of
the principle which \textcite{VisualDisplayOfQuantitativeInformation}
later called \enquote{small multiples} in the 1626 chart by
\textcite{RosaUrsina} demonstrating sunspot changes shown in
Figure~\ref{fig:SunspotChanges}, and the 1644 chart displaying
longitudinal distance determinations between Toledo and Rome by
Michael Florent van Langren shown in
Figure~\ref{fig:RomeToledoLongitude}.

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/planetary-movements.png}
\caption[Chart of Planetary Movements from the \nth{10} Century]{%
A line chart created by an unknown astronomer in the \nth{10} Century,
depicting the movements of seven prominent planets.
\imgcredit{Image extracted from \textcite{BriefHistoryOfDataVis}.
Original appearance in \textcite{CommentariiInSomniumScipionis}.}
}
\label{fig:PlanetaryMovements}
\end{figure}
% KA Original appearance in Macrobius [1175] ??
% Funkhouser 1936 says 10th or 11th Century

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/sunspot-changes.png}
\caption[Chart of Changes in Sunspots from 1626]{%
The observed changes in sunspots based on recordings
of two months of data from 1611. It is the first occurrence of the
principle later called \enquote{small multiples} by
\textcite{VisualDisplayOfQuantitativeInformation}.
\imgcredit{Image extracted from \textcite{BriefHistoryOfDataVis}.
Original appearance in \textcite{RosaUrsina}.}
}
\label{fig:SunspotChanges}
\end{figure}

% Tufte, Edward R. and Peter R. Graves-Morris [1983].
% The Visual Display of Quantitative Information.
% Graphics Press, 1983. ISBN 1930824130 (cited on pages 19–20).
% KA: who is Graves-Morris ?

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/rome-toledo-longitude.png}
\caption[Chart of Longitudinal Distance Determinations Between Toledo and Rome From 1644]{%
A comparison of the twelve known estimates in longitudinal
distance between Rome and Toledo by various astronomers. The correct
distance is marked by the arrow beneath. It is considered to be the
first visual representation of statistical data.
\imgcredit{Image extracted from \textcite{BriefHistoryOfDataVis}.
Original appearance in \textcite{VisualExplanations}.}
}
\label{fig:RomeToledoLongitude}
\end{figure}

% KA  how can it be the "first visual representation of statistical data"  ?

% Tufte, Visual Explanations, 1997, page 15

William Playfair (1759--1823) is considered by many to be one of the
forefathers of modern information visualization. His published works
contain the first occurrences of many graphical forms still widely
used today. In one of his earlier works
\parencite{CommercialAndPoliticalAtlas}, he introduced the concepts of
line charts (Figure~\ref{fig:PlayfairLineChart}), bar charts
(Figure~\ref{fig:PlayfairBarChart}), and area charts
(Figure~\ref{fig:PlayfairAreaChart}) to communicate economic factors
of England during the eighteenth century. In a related later work
\parencite{StatisticalBreviary}, he used the first ever published pie
and circle charts to show and compare the resources of states and
kingdoms in Europe. The charts he created are very similar to modern
ones, containing familiar concepts such as labeled axes, grids,
titles, and color-coding.

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/playfair-line-chart.png}
\caption[Line Chart by William Playfair from 1786]{%
Line chart of the expenditure of the British Navy during the \nth{18}
Century. It was published in 1786 and is considered to be one of the
first occurrences of a line chart containing components found in
modern visualizations.
\imgcredit{Image extracted from Schoenberg Center for
Electronic Text and Image (SCETI).
Used under the terms of Creative Commons CC BY 2.5.}
}
\label{fig:PlayfairLineChart}
\end{figure}

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/playfair-bar-chart.png}
\caption[Bar Chart by William Playfair from 1786]{%
Bar chart of England's exports and imports to and from Scotland in
1781. Published in 1786, it is considered to be one of the
first occurrences of a bar chart containing most components found in
modern visualizations.
\imgcredit{Image extracted from Schoenberg Center
for Electronic Text and Image (SCETI).
Used under the terms of Creative Commons CC BY 2.5.}
}
\label{fig:PlayfairBarChart}
\end{figure}

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/playfair-area-chart.png}
\caption[Area Chart by William Playfair from 1786]{%
Area chart of annual revenues of England and France between
1550 and 1800. Published in 1786, it is considered to be one of
the first occurrences of an area chart
containing most components found in modern visualizations.
\imgcredit{Image extracted from Schoenberg Center
for Electronic Text and Image (SCETI).
Used under the terms of Creative Commons CC BY 2.5.}
}
\label{fig:PlayfairAreaChart}
\end{figure}

%% The dot map created by \textcite{ModeOfCommunicationOfCholera} in 1855
%% to trace cholera outbreaks in London (Figure~\ref{fig:CholeraDotMap})
%% is undoubtedly one of the most famous and influential visualizations
%% in history.  Even though it is not directly an information
%% visualization but rather a geographic one, it has been included here
%% because of its historic relevance.  This iconic dot map was used to
%% identify a cluster of cholera-related deaths near a contaminated water
%% pump on Broad Street, leading to the recognition of cholera as a
%% waterborne disease.
%%
%%
%% \begin{figure}[tp]
%% \centering
%% \includegraphics[keepaspectratio,width=\linewidth,height=\fullh / 3]{images/cholera-dot-map.png}
%% \caption[Dot Map Plotting Cholera Deaths in London From 1855]{%
%% This iconic chart was created by Dr. John Snow in 1855 to identify a
%% clustering of cholera-related deaths near Broad Street in London.  It
%% was used to identify a contaminated water pump and to illustrate the
%% waterborne nature of the disease.  Since the data is map-based, this
%% chart is an example of a geographic visualization rather than an
%% information visualization.
%% \imgcredit{Image extracted from \textcite{IVISCourseNotes}.
%% Original appearance in \textcite{ModeOfCommunicationOfCholera}.}
%% }
%% \label{fig:CholeraDotMap}
%% \end{figure}

It would be amiss not to mention Florence Nightingale (1820--1910)
\parencite{FlorenceNightingale} when talking about the history of
information visualization. She was a British statistician, social
reformer, and the founder of modern nursing and might be the first
person who used visualizations to persuade others of a need for
change. During her service as a superintendent of nurses in the
Crimean War, she realized that a large number of deaths in hospitals
resulted from preventable diseases which originated in poor sanitary
conditions. One of her contributions to the field of information
visualization was the creation of a new type of diagram, called a rose
diagram or polar-area chart, shown in
Figure~\ref{fig:NightingalePolarAreaChart}. She used these charts to
communicate data she collected on the mortality of soldiers during the
war and to grab the attention of politicians and the public.

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/nightingale.png}
\caption[Polar-Area Chart by Florence Nightingale from 1859]{%
One of the polar-area charts created by Florence Nightingale in 1859
to convince people of a need for more sanitary conditions in
hospitals. It visualizes the causes of mortality for soldiers during
the Crimean War and demonstrates that a large percentage of patients
died from preventable diseases linked to unsanitary environments.
\imgcredit{Image extracted from Harvard Library.
Used under the terms of Creative Commons Attribution 4.0.}
}
\label{fig:NightingalePolarAreaChart}
\end{figure}

Modern visualizations benefit from the interactive nature of the
devices used to consume them. They can be more complex than static
visualizations, because various interaction techniques enable users to
navigate large amounts of data and make sense of it. High-D by
Macrofocus \parencite{HighD} is a representative example of a modern
interactive visual analytics tool, and is shown in
Figure~\ref{fig:HighD}.

\begin{figure}[tp]
\centering
\includegraphics[keepaspectratio,width=\linewidth,height=\thirdh]
{images/high-d.png}
\caption[High-D]{
High-D by Macrofocus is a visual analytics tool
specialized in analyzing multidimensional data.
\imgcredit{Screenshot of High-D \parencite{HighD} taken by the author of this work.}
}
\label{fig:HighD}
\end{figure}

It is out of the scope of this work to provide a full account of the
long and eventful history of information visualization. This section
only provides a brief and very selective view of the topic.  More
comprehensive works for further reading include
\textcite{BriefHistoryOfDataVis}, \textcite{Meirelles-2013},
\textcite{HistoryOfInformationGraphics}, and
\textcite{HistoryOfDataVisAndGraphicCommunication}.

\section{Information Visualization Libraries for the Web}

There are many web-based libraries which simplify the rendering of
interactive visualizations. The approaches used to create and update a
visualization differ widely between libraries. D3 is a low-level
library which enables data-driven transformations of documents. Vega
and Vega-Lite provide a declarative grammar to express the visual and
interactive characteristics of a visualization. Template-based
visualization libraries provide a higher-level template-based
interface which can easily be configured.

\subsection{Data-Driven Documents (D3)}

D3 \parencite{D3} is a free, open-source document manipulation library
built in JavaScript by Mike Bostock and actively maintained by him and
a community on GitHub \parencite{D3JS}. Mike Bostock is also the
creator of Observable \parencite{Observable} and was one of the authors of
the deprecated Protovis visualization library \parencite{Protovis}.

D3 enables data-driven document transformations to allow developers to
describe documents as functions of data.  As an example, developers
can define transformations which receive a dataset and transform it
into a basic HTML table or into a more sophisticated visualization as
an SVG chart.  This focus on explicitly defining transformations is
better suited for dynamic visualizations because developers have
complete control over the creation, modification and removal of
elements.  It also sets D3 apart from other visualization libraries
where developers usually define the desired state of a representation
using a declarative domain specific language.

In contrast to other visualization libraries, D3 contains no
proprietary visual primitives and relies on well established web
standards like HTML, SVG and CSS to provide visual representations.
This yields great flexibility because developers work directly with
web standards that are implemented by their browsers and do not need
to wait for D3 to implement support for new features as standards
evolve.  If developers chose to switch to a different library, the
knowledge of web standards they gained during their work with D3 might
be applicable in their future work.  The reliance on web standards
also makes it possible to use debugging tools which are already
natively implemented in browsers.

Other important aspects of D3's design include immediate evaluation,
the principle of parsimony, and support for method chaining.
Immediately evaluating functions means that operations, such as
modifying attributes, are applied instantaneously at the time of
calling the respective functions.  This achieves a reduction in
internal complexity by handing control flow decisions over to invoking
code.  It also avoids common errors related to missing state changes
when state is being modified multiple times between rendering in
libraries that build on delayed evaluation.  The principle of
parsimony, also referred to as Occam's razor, is a problem-solving
principle which stems from the field of philosophy
\parencite{PrincipleOfParsimony}.  It is frequently paraphrased as
"entities should not be multiplied beyond necessity" and when applied
to API design it means that superfluous functions in an API should be
avoided.  As an example, the background color of a circle element can
already be set with the generic \lstinline{Selection.attr} method to
set the \attrname{background-color} attribute of all elements in a
Selection.  Adding an additional \lstinline{backgroundColor} method
would violate the principle of parsimony because it would introduce a
special method to achieve something that was already achievable.
Method chaining is a popular syntax which allows functions to be
chained after one another.  The use of method chaining avoids having
to store intermediate method results into variables which would
otherwise not be needed.  It is implemented in D3 by returning the
\lstinline{Selection} on which a modifying method is called as a
result of that method.  Methods that insert new elements into the DOM,
such as \lstinline{Selection.append} and \lstinline{Selection.insert},
return a Selection of the newly added elements to enable the creation
of nested structures.  This method chaining syntax is further aided by
the \lstinline{Selection.call} method, which invokes a callback
receiving the current Selection as a parameter and returns the
original Selection to further chain methods on it after the callback
has been executed.  The \lstinline{Selection.call} method enables the
creation of complex method chaining structures and is widely used by
developers.  A simple example of method chaining in D3 and the
application of the \lstinline{Selection.call} method can be seen in
Listing~\ref{list:D3MethodChaining}.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  language=JavaScript,
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:D3MethodChaining,
  caption={[D3 Method Chaining]
    A simple example of method chaining in D3 which creates an \elname{h1} and \elname{p} element inside a \elname{body}.
  },
]{listings/d3-method-chaining.js}
\end{samepage}

Selections have already been mentioned in the previous paragraphs.
They are the atomic building blocks of D3 and are used to access
almost any functionality.  Selections are created using the
\lstinline{d3.select} or \lstinline{d3.selectAll} methods.  These
methods are built on the DOM Selectors API, namely the
\lstinline{querySelector} and \lstinline{querySelectorAll} methods,
which allow the selection of elements via CSS selectors (see
Section~\ref{sec:CSS}).  The \lstinline{d3.select} and
\lstinline{d3.selectAll} methods respectively create a Selection
containing either a single element matching the provided selector, or
multiple elements matching it.  A Selection acts as a wrapper
container around selected elements to perform frequently performed DOM
operations on them.  Among others, the element operations provided by
a Selection include the setting and getting of: Attributes using the
\lstinline{Selection.attr} method, styles using the
\lstinline{Selection.style} method, properties using the
\lstinline{Selection.property} method, text or HTML content using the
\lstinline{Selection.text} or \lstinline{Selection.html} methods, and
event listeners using the \lstinline{Selection.on} method.  Selections
also provide wrapper methods to insert additional elements using the
\lstinline{Selection.append} or \lstinline{Selection.insert} methods
as well as to remove them using the \lstinline{Selection.remove}
method.  Accessing the DOM via this wrapper is less tedious than
accessing it directly because the native DOM API is very verbose, and
also because the method chaining API provided by D3 does not require
the storage of unnecessary intermediate variables.

An additional feature that D3 adds is the ability to bind data to
elements using the \lstinline{Selection.data} and
\lstinline{Selection.datum} methods.  The \lstinline{Selection.datum}
method binds a single provided data record to all elements in the
Selection, whereas the \lstinline{Selection.data} method receives an
array of data records and binds each individual data record to exactly
one element.  The \lstinline{Selection.data} method performs a join
operation between data and elements to ensure that exactly one element
per data record exists.  This data join results in three separate
Selections: the enter Selection, containing the elements which were
newly created, the update Selection, containing the elements which
merely receive new data, and the exit Selection, containing the
elements which are being removed.  Each of these Selections can be
individually transformed using the \lstinline{Selection.join} method,
which can receive three callbacks each being respectively invoked with
the enter, update and exit Selections of the data join.  This ability
of individually controlling updates of entering, updating and exiting
elements is being referred to as the general update pattern in D3 and
a simple demonstration of how it is used can be seen in
Figure~\ref{list:D3GeneralUpdatePattern}.  All the previously
mentioned DOM wrapper methods can receive either constant values or
dynamic ones, which are defined as functions.  These functions receive
the bound element data, the element's index in the group of nodes
represented by the Selection, and the group of nodes themselves as
input and calculate a dynamic value based on these parameters, which
is then forwarded to the corresponding DOM methods.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:D3GeneralUpdatePattern,
  caption={[D3 General Update Pattern]
    A demonstration of D3's general update pattern and how it can be used to specify different transformations for entering, updating and exiting elements.
    This code is merely meant as an example of how the join selections can be transformed.
    The full utility of this pattern will only be appearant in more complex scenarios that involve transitions.
  },
]{listings/d3-join.js}
\end{samepage}

D3 also offers a convenient and optional API to perform
JavaScript-based animations via Transitions, which wrap a Selection
and allow the animation of various element characteristics.
Transitions are created using the \lstinline{Selection.transition}
method which creates a Transition wrapping the Selection on which it
has been called.  The duration of a Transition is defined using the
\lstinline{Transition.duration} method and its easing can be
configured using the \lstinline{Transition.ease} method.  There is
also the possibility of interrupting and chaining transitions, but
explaining these things would be to go into too many details.
Transitions provide an almost identical API to Selections.  The major
change is that the wrapping methods interpolate towards their target
values using the set easing function over the set duration instead of
setting the target value directly.  Using D3 Transitions is completely
optional and users can also choose to instead use other animation
technologies, like CSS transitions and animations.

At the core, D3 is simply a low-level library to perform data-driven
document transformations.  Even though this generic core technology is
applicable to a wide range of use cases, D3 has been created with a
focus on creating visualizations.  There are many additional modules
which simplify performing the higher-level tasks necessary for the
rendering of visualizations.  All modules follow the same patterns
inherent to D3, like method chaining and configurable functions.
Therefore, despite these higher-level functionalities being split on
multiple modules, a consistent experience is provided to developers.
Listing all available modules here would be out of the scope of this
work, but some noteworthy and characteristic ones include:
\modname{d3-shape} to create visual primitives like lines and areas,
\modname{d3-scale} to encode abstract data dimensions,
\modname{d3-axis} to render scales as human-readable axes, and many
more such as \modname{d3-array}, \modname{d3-layout} and
\modname{d3-zoom}.

\subsection{Vega and Vega-Lite}

Vega \parencite{Vega} is a library which consists of a grammar to
describe interactive graphics and a parser which translates
specifications written in this grammar into static images or web-based
views built on SVG documents or the Canvas Web API.  An interactive
visualization in Vega is fully described by a specification written in
Vega's grammar.  This grammar is essentially a domain specific
language designed for the declarative denotation of interactive
graphics.  Its syntax is based on the easy-to-read JavaScript Object
Notation (JSON), which is among the most frequently used textual
serialization formats.  Vega builds on previous research in the field
of declarative visualization design \parencite{GrammarOfGraphics}.
Compared to previous works, it contains powerful capabilities to
declaratively describe interactions \parencite{ReactiveVega} in
addition to describing visual appearances.

The visual aspects of a visualization are described in a grammar
similar to the one defined by \textcite{GrammarOfGraphics}.  At its
top level, a Vega specification contains properties to configure
sizing and padding of the container of a visualization.  Every
specification will also contain a data section which either defines
data or specifies where to load it from.  The Vega grammar also
supports various forms of data transformation which can successively
be applied to a dataset to perform various transformations like
filtering, deriving additional fields or deriving additional datasets.
In a majority of cases, the defined data will consist of abstract
information that requires being mapped to visual properties.  This
mapping is configured and performed using scales.  Vega already
contains a variety of scales to help with mapping abstract values to
visual properties.  They can broadly be categorized into quantitative
scales which map quantitative inputs to quantitative outputs, discrete
scales which map discrete inputs to discrete outputs, and discretizing
scales which map quantitative inputs to discrete outputs.  For
spatially encoded dimensions, these scales can be visualized as axes,
whereas non-spatial encodings such as encodings as colors, sizes or
shapes can be visualized as legends.  At the core of every
visualization lies the encoding of data as visual primitives, which is
achieved in Vega via marks.  Marks use scales to encode data fields as
properties of their shapes.  Based on the general update pattern of
the underlying D3 library, the encoding of marks can be separately
controlled for newly created (entering) marks, existing and not
exiting (updating) marks, and to-be-removed (exiting) marks.  In
addition to these basic visualization components, the Vega grammar
contains further capabilities to describe interactions (via signals,
triggers and event streams), cartographic projections, sequential or
layered views (via mark groups), layouts and color schemes.  To
demonstrate how the various aspects of a Vega specification are
defined, an example which represents a static bar chart can be seen in
Listing~\ref{list:VegaStaticBarChart}.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:VegaStaticBarChart,
  caption={[Static Bar Chart in Vega]
    The Vega specification of a static bar chart.
    Demonstrates the principle of data, scales, axes and marks.
  },
]{listings/vega-static-bar-chart.json}
\end{samepage}

In template-based visualization libraries, interactions are typically
defined by configuring premade interaction templates, which is easy
but limiting, or by manually modifying the visualization in various
callbacks, which is flexible but tedious and not serializable.  The
ability to describe custom interactions using a serializable,
data-driven grammar is what sets Vega apart from other declarative
visualization libraries.  This approach offers a comparable
flexibility to callback-driven interactions while still remaining
fully serializable and declarative.  The grammar to define
interactions is based on the syntax of event-driven functional
reactive programming \parencite{EventDrivenFRP}, a high-level grammar
which resembles mathematical equations to describe reactive systems.
In Vega, the primitives to express interactions are called signals.
Signals can be seen as dynamic variables which change their values
based on input events or other signals.  These signals and the way
their values change are declaratively defined, and they can be used as
dynamic variables throughout most places in a Vega specification to
change various characteristics of a visualization dynamically.  An
example of how the previously demonstrated static bar chart
specification can be extended with signals to display a tooltip when
hovering over bars can be seen in Listing~\ref{list:VegaBarChart}.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:VegaBarChart,
  caption={[Bar Chart with Tooltip in Vega]
    The necessary additions to the static bar chart specification in Listing~\ref{list:VegaStaticBarChart} to display a tooltip when hovering over bars.
    It demonstrates the basic functionality of signals in Vega.
    When the mouse hovers over a rect mark, the tooltip signal will receive the value of the rect's bound data record.
    The tooltip signal will be reset to an empty object when the mouse leaves the rect mark.
    It is then used in the newly added text mark section of the specification to define the position, text and visibility of it whenever an update occurs.
  },
]{listings/vega-bar-chart.json}
\end{samepage}

Visualizations created with Vega closely follow their specifications
and minimal assumptions are being made in the compilation process.
This results in very verbose specifications because all configurations
for all parts of the visualization need to be explicitly defined in
them.  It also means that specification authors have full control over
the resulting graphics, making Vega a good base on which to build
further libraries and tools.  Many tools
\parencite{Voyager,Lyra,CompassQL} have already been built on top of
Vega.  The tool worth mentioning most is Vega-Lite
\parencite{VegaLite}.  Vega-Lite is described as a "high-level grammar
of interactive graphics", which summarizes its difference to Vega
fairly well.  Vega-Lite is a higher-level grammar than Vega, which
allows authors to write specifications for common visualizations in a
much more concise form.  Specifications written in Vega-Lite are
compiled into Vega specifications.  During compilation, the compiler
automatically derives default configurations for axes, legends and
scales from a set of carefully designed rules.  This makes Vega-Lite
more convenient to use for quick authoring of visualizations because
many details which need to be explicitly stated in a Vega
specification can be omitted.  In those cases where the derived
default configurations are not suitable, Vega-Lite also offers the
possibility to override them.  Since Vega-Lite specifications are
simply being compiled into Vega ones, it is a sensible choice to use
Vega-Lite as a primary tool to describe visualizations, and switch to
Vega for more exotic cases which are not easily achievable in
Vega-Lite.  To properly compare the difference between Vega and
Vega-Lite specifications, a Vega-Lite version of the Vega bar chart
specification seen in Listing~\ref{list:VegaStaticBarChart} combined
with Listing~\ref{list:VegaBarChart} can be seen in
Listing~\ref{list:VegaLiteBarChart}.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:VegaLiteBarChart,
  caption={[Bar Chart with Tooltip in Vega-Lite]
    This is a Vega-Lite specification of the Vega bar chart specification seen in Listing~\ref{list:VegaStaticBarChart} combined with Listing~\ref{list:VegaBarChart}.
  },
]{listings/vega-lite-bar-chart.json}
\end{samepage}

\subsection{Template-Based Visualization Libraries}

Template-based visualization libraries work by providing templates for
possible types of visualizations and allowing users to customize them.
These types of visualization libraries are easier to use than D3 or
Vega because they offer a concise form of configuration which does not
require users to have detailed knowledge over the underlying rendering
technology or complex, non-standardized domain specific languages.
Even though these types of libraries are usually flexible enough to
create a huge range of visualizations, at one point users may run into
limitations.  Some of these limitations can not be worked around and
require the writing of custom source code which requires a deep
understanding of the underlying library.  This effectively eliminates
the ease-of-use benefit of these types of libraries for users that run
into these limitations.

For this thesis, a total of 20 template-based JavaScript visualization
libraries have been collected and compared by different factors such
as their rendering technology, usage popularity, open-source
popularity, license, and recent development activity.  In terms of
rendering technology, most libraries render visualizations as either
SVG documents or canvas elements, though some implement a hybrid
renderer which can be configured to render as either one of them.
Usage popularity has been measured by the cumulative package downloads
from the npm package manager over the last twelve months.  This has
been deemed one of the most relevant metrics for the comparison
because it reflects actual user behavior and gives an indication on
how widespread a library is used in practice.  The 20 libraries found
in the initial collection phase were filtered by their usage
popularity and recent development activity to remove those which were
not sufficiently used or maintained anymore.  This filtering step
yielded the following ten libraries: (1) ChartJS \parencite{ChartJS},
(2) Highcharts \parencite{Highcharts}, (3) ECharts
\parencite{ECharts}, (4) ApexCharts \parencite{ApexCharts}, (5)
PlotlyJS \parencite{PlotlyJS}, (6) C3JS \parencite{C3JS}, (7) Chartist
\parencite{Chartist}, (8) amCharts \parencite{amCharts}, (9)
billboardJS \parencite{billboardJS}, and (10) D3FC \parencite{D3FC}.
These libraries have been selected for deeper evaluation because they
are heavily used and, for the most part, still actively maintained.
The focus of this more detailed analysis is on summarizing these
libraries based on high-level features and responsive capabilities.

Eight of those ten libraries are completely free to use without
restrictions, amCharts has a free license for users who are
comfortable with an attribution logo on their visualizations, and
Highcharts offers a free license option for non-profit, educational
and personal applications.  Nine libraries implement an SVG-based
renderer, two of which (ECharts, D3FC) offer alternative rendering to
canvas elements for high-performance scenarios, and only ChartJS
purely targets canvas-based rendering.  Eight libraries are very
actively maintained with most of them showing development activity
within the last month.  Only C3JS and Chartist do not seem to be
actively maintained anymore, but they nonetheless have been included
in the deeper evaluation because of their historic and thematic
relevance and because they are still widely used.

Template-based visualization libraries have a strong inclination
towards designing their APIs according to principles of declarative
programming.  APIs following these principles allow users to describe
a desired state they want the underlying system to be in.  This is in
strong contrast to the typical imperative way of designing APIs in
which users are instead given a set of tools to query and modify a
system's state.  The difference can be summarized in simple terms as:
Using declarative APIs, users specify what state shall be achieved,
whereas when using imperative APIs, users specify how a certain state
is achieved.  Declarative APIs are typically built on top of
lower-level imperative APIs and can therefore be seen as a higher
level of abstraction over them.  They are popular among developers
because they are expressive, easy to use and effectively encapsulate
complexity which would otherwise have to be handled by users.  An
often overlooked disadvantage of declarative APIs is that they
frequently only provide high-level access to a system and that more
specific use cases might not be achievable if they can not be
expressed in the domain specific language defined by the API.  In many
cases it makes sense to provide additional imperative APIs for users
which require a lower level of access to the system to implement
functionality not achievable via the declarative parts of the
interface.

All evaluated libraries, except D3FC, expose declarative interfaces in
the form of nested configuration objects which are used to specify the
characteristics of individual visualizations.  Apart from Chartist,
all those libraries feature generic high-level creation functions.
These functions create charts from declarative configuration objects,
which allow the specification of different forms of visualization for
different data dimensions.  This type of interface is demonstrated by
the Highcharts code seen in Listing~\ref{list:Highcharts}.  Generic
chart creation functions seem to be correlated with the ability of
dynamically changing the type of visualization.  In Chartist, for
instance, which provides separate chart creation functions for each
type of chart, it is not possible to alter the type of chart after it
has been created.  Another limitation which may originate in this
interface partitioning via chart types is that mixed charts which
combine multiple forms of visualization in one composite visualization
can not be expressed.  The only library in the deeper evaluation which
does not provide a high-level declarative configuration API is D3FC.
The design philosophy of D3FC is based on the idea of "unboxing" D3.
Even though many visualization libraries are implemented on top of D3,
it is usually hidden behind public APIs which are easier to work with
but do not provide the full flexibility of D3.  D3FC exposes a
component-based interface which closely follows design patterns
frequently encountered when working with D3.  These components form
higher-level building blocks on which advanced visualizations can be
built.  They are also highly configurable and in those cases where the
options for configuration are not sufficient, a decorator pattern is
used to allow users to hook into the underlying D3 functionality and
inject custom code into the various stages of the general update
pattern at the core of D3.  Code which demonstrates the usage of D3FC
can be seen in Listing~\ref{list:D3FC}.  The only evaluated library
which exposes a hybrid API with the possibility of configuring
visualizations using both declarative configuration objects and
manually composing higher-level visualizations from lower-level
components, such as axes and series, is amCharts.  Its component-based
interface is still rather declarative, with most options being
configurable by modifying certain properties on the components.
However, modifying only the properties which require changing instead
of processing a full configuration object and figuring out the
necessary changes from it is less costly in terms of performance.  In
addition to these performance benefits, the components provide
additional functions to perform operations which would not be
available using a purely declarative API.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:Highcharts,
  caption={[Bar Chart in Highcharts]
    This example demonstrates how a basic column (vertical bar) chart is defined using the generic chart creation API provided by Highcharts.
  },
]{listings/highcharts.js}
\end{samepage}

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:D3FC,
  caption={[Bar Chart in D3FC]
    This example demonstrates how a basic bar chart is defined using the component-based API provided by D3FC.
  },
]{listings/d3fc.js}
\end{samepage}

When comparing the evaluated libraries by their responsive
configurability, most libraries offer similar capabilities albeit in
slightly different ways.  Six libraries (Highcharts, C3JS, Chartist,
amCharts, billboardJS, D3FC) support the styling of elements in their
created visualizations with CSS, which requires rendering as SVG
documents because only document-based visualizations can be affected
by CSS.  The styling of visualizations with CSS is powerful because it
leads to a separation of concerns and designers can make use of
CSS-inherent mechanisms to configure responsive styles.
Unfortunately, CSS-based styling is only of limited applicability
because not all CSS properties affect SVG elements, which has already
been described in Section~\ref{sec:SVG}.  To responsively configure
other visualization characteristics, such as their type, data, and
layout, designers have to resort to configuration mechanisms offered
by the libraries.  Four libraries (Highcharts, ApexCharts, Chartist,
amCharts) provide the possibility to specify rule-based responsive
configurations as part of their declarative interfaces, demonstrated
in the Highcharts example in Listing~\ref{list:HighchartsResponsive}.
These declarative rules consist of a condition part which specifies
when to apply the rule, and a configuration part which specifies the
configuration options which should be set when applying the rule.
Even though this is a convenient form of responsive configuration, if
the desired conditions can not be expressed via the provided
declarative properties, designers have to fall back to more generic
mechanisms which are also applicable to other libraries.  The
mechanisms for responsive configuration in the other libraries are
more generic because they do not offer these configurations as part of
their declarative interfaces.  This means that developers need to
trigger responsive configurations themselves by manually reconfiguring
visualizations via their APIs in custom resize or media query event
listeners.  Nearly all libraries provide means to dynamically resize
visualizations and update their data, type and options.  The
exceptions from this are C3JS, which only supports dynamic changes of
some options, and Chartist, which does not support changing of a
visualization's type.

\begin{samepage}
\lstinputlisting[%
  float=tp,
  aboveskip=\floatsep,
  belowskip=\floatsep,
  xleftmargin=0cm,              % no extra margins for floats
  xrightmargin=0cm,             % no extra margins for floats
  %
  basicstyle=\footnotesize\ttfamily,
  frame=shadowbox,
  numbers=left,
  label=list:HighchartsResponsive,
  caption={[Responsive Rules in Highcharts]
    This example demonstrates how responsive rules can be declared to configure various aspects of a visualization in relation to the size of the viewport.
  },
]{listings/highcharts-responsive.js}
\end{samepage}


\documentclass[12pt,letterpaper]{article}

%Packages
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amscd}
\usepackage{dsfont}
\usepackage{enumerate}
\usepackage{fancyhdr}
\usepackage{mathrsfs}
\usepackage{bbm}
\usepackage{framed}
\usepackage{mdframed}
\usepackage{cancel}
\usepackage{float}
\usepackage{mathtools}
%\usepackage[]{mcode}
\usepackage{graphicx}
\usepackage{tikz}

%Page formatting
\usepackage[letterpaper,voffset=-.5in,bmargin=3cm,footskip=1cm]{geometry}
\setlength{\parindent}{0.0in}
\setlength{\parskip}{0.1in}
\allowdisplaybreaks
\headheight 15pt
\headsep 10pt

% Common Commands
\newcommand\N{\mathbb N}
\newcommand\Z{\mathbb Z}
\newcommand\R{\mathbb R}
\newcommand\Q{\mathbb Q}
\newcommand\lcm{\operatorname{lcm}}
\newcommand\setbuilder[2]{\ensuremath{\left\{#1\;\middle|\;#2\right\}}}
\newcommand\E{\operatorname{E}}
\newcommand\V{\operatorname{V}}
\newcommand\Pow{\ensuremath{\operatorname{\mathcal{P}}}}

\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}

% 22 style
\newcommand\hint[1]{\textbf{Hint}: #1}
\newcommand\note[1]{\textbf{Note}: #1}
\newenvironment{22enumerate}{\begin{enumerate}[a.]\itemsep0em}{\end{enumerate}}
\newenvironment{22itemize}{\begin{itemize}\itemsep0em}{\end{itemize}}
\fancypagestyle{firstpagestyle} {
  \renewcommand{\headrulewidth}{0pt}%
  \lhead{\textbf{CSCI 0220}}%
  \chead{\textbf{Discrete Structures and Probability}}%
  \rhead{Klivans}%
}

\pagestyle{fancyplain}

\newcommand\EX{\mathds{E}}
\newcommand\PR{\mathds{P}}
\newcommand\zlam{Z_\lambda}
\DeclareMathOperator*{\argmin}{arg\,min}

%%%%%%%%%%%%%%%% COMPILE WITH \soltrue or \solfalse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newif\ifsol
\soltrue  % SOLUTIONS
\solfalse % NO SOLUTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%% solution help %%%%%%%%%%%%%%%%%%%%%
\newcommand{\solu}[2]{ \begin{mdframed} \ifsol #2 \else \vspace{#1} \fi \end{mdframed} }
\newcommand{\solt}{ \ifsol (T) \fi }
\newcommand{\solf}{ \ifsol (F) \fi }
\newcommand{\solm}[1]{\ifsol \textit{(#1)} \fi}

\begin{document}
  \thispagestyle{firstpagestyle}
  \begin{center}
    {\large \textbf{Recitation 4}}

    {\large Induction and Algorithms}
  \end{center}

 \section*{Review}

      We will review the template for an inductive proof.

      For example, say we are trying to prove that $\sum_{i=0}^n i = \frac{n(n+1)}{2}$ is true for all $n \in \N$.

      \begin{enumerate}
        \item Define the predicate $P(n)$.

        \textit{Let $P(n)$ be the predicate that $\sum_{i=0}^n i = \frac{n(n+1)}{2}$.}

        \item Show that the base case is true.

        \textit{We will first show $P(0)$ is true. $\sum_{i=0}^0 i = 0$ and $\frac{0(0+1)}{2} = 0$ so they are equal as needed.}

        \item Assume the inductive hypothesis is true. If you are using stardard induction then you will assume
			$P(k)$ is true for some integer $k$. If you are using strong induction then you will assume $P(i)$ is true for all $i \leq k$.

        \textit{Assume $P(k)$ is true for some integer $k$.}

        \item Show that $P(k+1)$ is true given the inductive hypothesis.

		\textit{We will now show that  $\sum_{i=0}^{k+1} i = \frac{(k+1)(k+2)}{2}$}.

       	\textit{We know that $\sum_{i=0}^{k+1} i = \left( \sum_{i=0}^{k} i \right)+ (k+1)$.}

		\textit{By our inductive hypothesis $\sum_{i=0}^k i = \frac{k(k+1)}{2}$.}

         \textit{Therefore}
		\begin{align*}
			\sum_{i=0}^{k+1} i &= \left( \sum_{i=0}^{k} i \right)+ (k+1) \\
			&=  \frac{k(k+1)}{2} + (k+1) \\
			&= \frac{k(k+1) + 2(k+1)}{2} \\
			&= \frac{(k+1)(k+2)}{2}
		\end{align*}
		\textit{as needed.}\qed

	\subsection*{Warm-up}

      \begin{22enumerate}

      \item
      Prove by induction that for all positive integers $n$, there exists a
      positive integer $m$ such that:
      \[m^2 \leq n < (m + 1)^2\]

	\hint{The inductive step may contain two cases.}

	\solu{17cm}{ Let $P(k)$ denote the property that there exists a positive integer
        $m$ such that $m^2 \leq k < (m + 1)^2$.

        Construct a proof by induction.

        \textbf{Base Case:} Consider $k = 1$.

        Let $m = 1$. Then $m^2 = 1$ and $(m + 1)^2 = 4$, so
        $m^2 \leq k <(m + 1)^2$. Thus $P(1)$ holds.

        \textbf{Inductive Hypothesis:}

        Assume $P(k)$ is true for some positive integer $k$.

        \textbf{Inductive Step:} Consider $n = k+1$.

        By the inductive hypothesis, there exists a positive integer $m$
        such that $m^2 \leq k < (m + 1)^2$.

        There are two cases:
        \begin{22enumerate}

        \item \textbf{Case 1:} $k + 1 < (m + 1)^2$. Then we can define
        $m_* = m$, and it holds that $m_*^2 \leq k + 1 < (m_* + 1)^2$.

        \item \textbf{Case 2:} $k + 1 = (m + 1)^2$. Then we can define
        $m_* = m + 1$. Then $k + 1 = (m + 1)^2 < ((m + 1) + 1)^2$, so
        $k + 1 < (m_* + 1)^2$.
        Since $k + 1 = (m + 1)^2$, $k + 1 = m_*^2$, so it is true that
        $m_*^2 \leq k + 1 < (m_* + 1)^2$.

        \end{22enumerate}

        Because $k < (m + 1)^2$ and $k$ and $m$ are integers, then
        $k + 1 \ngtr (m + 1)^2$, so these are the only two cases.

        In either case, we found an integer $m_*$ such that
        $m_*^2 \leq k + 1 < (m_* + 1)^2$. Thus $P(k + 1)$ is correct.

        Thus $P(k)$ implies $P(k + 1)$.

        Since $P(1)$ is true, and since for all positive integers $k$,
        $P(k)$ implies $P(k+1)$, then by standard induction, $P(n)$ is true for
        all positive integers $n$.

        Thus, for all positive integers $n$, there exists a positive integer
        $m$ such that $m^2 \leq n < (m + 1)^2$.}

		\pagebreak

      \item
      Prove by contradiction that there exists a \textbf{unique} such $m$.

	 \solu{17cm}{        We prove by contradiction. Assume that for some positive integer
        $n$, there exist two unique positive integer solutions
        $m_1 \neq m_2$ such that $m^2 \leq n < (m + 1)^2$. Without loss
        of generality, assume $m_2 > m_1$. Then $m_2 \geq m_1 + 1$.
        Because both sides of the equation are non-negative, we can square
        both sides of this equation to get $m_2^2 \geq (m_1 + 1)^2$.

        By our assumption, we also know that $m_2^2 \leq n$ and that
        $n < (m_1 + 1)^2$. $m_2^2 \leq n < (m_1 + 1)^2$, so
        $m_2^2 < (m_1 + 1)^2$.

        But this is a contradiction, because $m_2^2 \geq (m_1 + 1)^2$. Thus
        our assumption was false.

        Thus, for all positive integers $n$, there can exist only one unique
        integer $m$ such that $m^2 \leq n < (m + 1)^2$.

        From part a, we know that a solution exists for all positive
        integers $n$. Thus, for all positive integers $n$, there exists
        exactly one unique integer $m$ such that $m^2 \leq n < (m + 1)^2$.}

      \end{22enumerate}

	\textbf{Checkpoint - Call a  TA over}

    \end{enumerate}

	\section*{Section Lesson - Algorithms}

	\subsection*{Why does induction work?}

	You can think of induction as a ladder. We want to prove that we can reach every step of the ladder.

	The base case says that we can reach the first step of the ladder.

	The inductive hypothesis says that we can get to the $k^{\text{th}}$ step of the ladder.

	The inductive step says that if we can get to the $k^{\text{th}}$ step of the ladder, then we can get to step $k+1$.

	Therefore, once we get to step 1, we can get to step 2. Once we get to step 2, we can get to step 3. And so on for all steps of the ladder.

	\subsection*{Induction for algorithms}

	Induction can also be used to prove the correctness of algorithms. An algorithm is simply a series of steps.

	Consider the following $SORT$ algorithm which operates on a list of length $n$.
	\begin{enumerate}
		\item If $n=1$ do nothing as the list is already sorted.
		\item Find the smallest element in the list and remove it.
		\item Run the $SORT$ algorithm on the remaining $n-1$ elements.
		\item Put the smallest element at the begining of the list.
	\end{enumerate}

	We can now prove that $SORT$ correctly sorts a list of size $n$ for $n \geq 1$.

        \textit{Base case: $SORT$ does nothing on a list of size 1, which is already sorted.}

        \textit{Inductive hypothesis: Assume $SORT$ correctly sorts a list of size $k$.}

	   \textit{Inductive step: We will now show that $SORT$ correctly sorts a list of size $k+1$. In step 3, we are left with a list of size $k$. By our inductive hypothesis, $SORT$ correctly sorts this sublist. Therefore, when we put the smallest element (which we have removed) at the begining, our list is completely sorted as needed.}\qed

Your turn.

\textbf{Given a stack of pancakes, you can stick your spatula in between any two
pancakes, and flip the stack of pancakes above the spatula upside-down. Find an algorithm
to sort $n$ pancakes from largest to smallest, using at most $2n$ flips. Prove it is correct.}

\solu{18cm}{The algorithm is to always find the largest pancake, flip it to the top, then flip the whole stack so the largest pancake is on the bottom. After this proceed recursively on all but the largest pancake. The proof for why this is correct is identical to the proof for $SORT$ given above.}

\textbf{Checkpoint - Call a TA over}

\pagebreak

\textbf{Consider the following inductive proof}

Claim: All $n$ people in the room have the same eye color.
\begin{proof}

Base case: When $n=1$ clearly everyone in the room has the same eye color as there is only one person in the room.

Inductive Hypothesis: Assume that in a room of $k$ people, everyone in the room has the same eye color.

Inductive Step: We will now show that in a room of $k+1$ people everyone has the same eye color.

We know from our inductive step that the first $k$ people in the room have the same eye color, and that the last $k$ people in the room have the same eye color. Since there is some overlap between the first $k$ people and the last $k$ people, everyone in the room must have the same eye color.
\end{proof}

\textbf{Can you find the flaw in this proof?}

\solu{10cm}{The inductive step does not work for 2 people.}

\pagebreak

\textbf{Challlenge 1:}
100 dragons are sitting in a circle so that every dragon can see every other dragon.

Every dragon has green eyes, but the dragons don't know this. No dragon knows its own eye color, and the dragons cannot talk.

Ben comes and tells the circle of dragons that at least one of them has green eyes.

If a dragon knows it has green eyes, it will turn into a human at midnight.

Prove that on night 100, all dragons will turn into humans at once.

\hint{Use induction! What is the base case? Ignore the number 100 and instead consider $n$ dragons and show they turn into humans on the $n^{\text{th}}$ night.}

\solm{If there is only one dragon, it takes her one night to turn into a human. Now assume it takes $k$ nights for $k$ dragons. Consider the case where there is $k+1$ dragons and consider what one individual dragon is thinking. This one dragon sees $k$ dragons with green eyes. Therefore, if this dragon does not have green eyes, she would expect the other dragons to turn into humans after $k$ night since they can see her. Since they don't, this dragon realizes that she also has green and turns into a dragon on night $k+1$.}

\vspace{6cm}
\textbf{Challenge 2:}
We say that an infinite set $S$ is countable if there exists a bijection from $\N$ to $S$. Giventhat $\N \times \N$ is countable, prove by induction that $\N^k$ is countable where $k \in \N$.

\solm{$\N^k$ is countable so there exists a bijection $f_k$. We can now make a bijection $g_{k+1}$ from $\N^{k+1}$ to $\N \times \N$. $g_{k+1} ((x_1,...,x_{k+1})) = (f_k(x_1,...,x_k),x_{k+1})$.}

\end{document}


%\subsection{DFT-based transfer integrals using DIPRO}
\label{sec:dft}
\index{electronic coupling!DFT}
% While the use of the semiempirical ZINDO method provides an efficient on-the-fly technique to determine electronic coupling elements, it is not generally applicable to all systems. For instance, its predictive capacity with regards to atomic composition and localization behavior of orbitals within more complex structures is reduced. Moreover, transition- or semi-metals are often not even parametrized. In this case, {\it ab-initio} based approaches, e.g., density-functional theory can remedy the situation~\cite{huang_intermolecular_2004,huang_validation_2005,valeev_effect_2006,yin_balanced_2006,yang_theoretical_2007,baumeier_density-functional_2010}.

The calculation of one electronic coupling element requires the overlap matrix of atomic orbitals $\matr{\mathcal{S}}$, the expansion coefficients for monomer $\vctr{\boldsymbol{\lambda}}_{(k)} = \{ \lambda_\alpha^{(k)}\}$ and dimer orbitals $\vctr{D}_{(n)} = \{ D^{(n)}_{\alpha} \}$, as well as the orbital energies $E_{n}$ of the dimer are required as input. In practical situations, performing self-consistent quantum-chemical calculations for each individual monomer and one for the dimer to obtain this input data is extremely demanding. Several simplifications can be made to reduce the computational effort, such as using non-Counterpoise basis sets for the monomers (thereby decoupling the monomer calculations from the dimer run) and performing only a single SCF step in a dimer calculation starting from an initial guess formed from a superposition of monomer orbitals. This ''noCP+noSCF'' variant of \dipro is shown in \fig{dipro_scheme}(a) and recommended for production runs.
A detailed comparative study of the different variants can be found in~\cite{baumeier_density-functional_2010}.

The code currently contains supports evaluation of transfer integrals from quantum-chemical calculations performed with the \gaussian, \turbomole, and \nwchem packages. The interfacing procedure consists of three main steps: generation of input files for monomers and dimers, performing the actual quantum-chemical calculations, and calculating the transfer integrals.

\subsubsection{Monomer calculations}
\label{sec:edft}
First, \slink{sec:segments}{hopping sites} and a \slink{sec:neighborlist}{neighbor list} need to be generated from the atomistic topology and trajectory and written to the \sqlstate file. Then the parallel \calc{edft} \calculator manages the calculation of the monomer properties required for the determination of electronic coupling elements. Specifically, the individual steps it performs are:
%
\begin{enumerate}
\item Creation of a job file containing the list of molecules to be calculated with DFT
\votcacommand{Writing job file for \calc{edft}}{\ctpparallel \opt \xmloptions \sql \sqlstate \exe \calc{edft} \job \wrt }
\item Running of all jobs in job file
\votcacommand{Running all \calc{edft} jobs}{\ctpparallel \opt \xmloptions \sql \sqlstate \exe \calc{edft} \job \run }
which includes
\begin{itemize}
\item creating the input files for the DFT calculation (using the package specified in \xmloptions) in the directory
\begin{verbatim}
OR_FILES/package/frame_F/mol_M
\end{verbatim}
where {\tt F} is the index of the frame in the trajectory, {\tt M} is the index of a molecule in this frame,
\item executing the DFT run, and
\item after completion of this run, parsing the output (number of electrons, basis set, molecular orbital expansion coefficients), and saving it in compressed form to
\begin{verbatim}
 OR_FILES/molecules/frame_F/molecule_M.orb
\end{verbatim}
\end{itemize}
\end{enumerate}

\subsubsection{Calculating the transfer integrals}
\label{sec:idft}
After the momomer calculations have been completed successfully, the respective runs for dimers from the neighborlist can be performed using the parallel \calc{idft} \calculator, which manages the DFT runs for the hopping pairs and determines the coupling element using \dipro. Again, several steps are required:
\begin{enumerate}
\item Creation of a job file containing the list of pairs to be calculated with DFT
\votcacommand{Writing job file for \calc{idft}}{\ctpparallel \opt \xmloptions \sql \sqlstate \exe \calc{idft} \job \wrt }
\item Running of all jobs in job file
\votcacommand{Running all \calc{idft} jobs}{\ctpparallel \opt \xmloptions \sql \sqlstate \exe \calc{idft} \job \run }
which includes
\begin{itemize}
\item creating the input files (including the merged guess for a noSCF calculation, if requested) for the DFT calculation (using the package specified in \xmloptions) in the directory
\begin{verbatim}
OR_FILES/package/frame_F/pair_M_N
\end{verbatim}
where {\tt M} and {\tt N} are the indices of the molecules in this pair,
\item executing the DFT run, and
\item after completion of this run, parsing the output (number of electrons, basis set, molecular orbital expansion coefficients and energies, atomic orbital overlap matrix), and saving the pair information in compressed form to
\begin{verbatim}
 OR_FILES/pairs/frame_F/pair_M_N.orb
\end{verbatim}
\item loading the monomer orbitals from the previously saved {\tt *.orb files}.
\item calculating the coupling elements and write them to the job file
\end{itemize}
\item Reading the coupling elements from the job file and saving them to the \sqlstate file
\votcacommand{Saving \calc{idft} results from job file to \sqlstate}{\ctpparallel \opt \xmloptions \sql \sqlstate \exe \calc{idft} \job \rd }
\end{enumerate}


% Define document class
\documentclass[twocolumn]{aastex63}
\DeclareRobustCommand{\Eqref}[1]{Eq.~\ref{#1}}
\DeclareRobustCommand{\Figref}[1]{Fig.~\ref{#1}}
\DeclareRobustCommand{\Tabref}[1]{Tab.~\ref{#1}}
\DeclareRobustCommand{\Secref}[1]{Sec.~\ref{#1}}
\newcommand{\todo}[1]{{\large $\blacksquare$~\textbf{\color{red}[#1]}}~$\blacksquare$}
% \usepackage{cuted}
\usepackage{flushend}
\usepackage{amsmath}
\graphicspath{{./figures/}}

\begin{document}

% Title
\title{Pair-instability mass loss for top-down compact object mass calculations}

\author[0000-0002-6718-9472]{M.~Renzo}
\affiliation{Center for Computational Astrophysics, Flatiron Institute, New York, NY 10010, USA}
\affiliation{Department of Physics, Columbia University, New York, NY 10027, USA}

\author[0000-0002-8717-6046]{D.~D.~Hendriks}
\affiliation{Department of Physics, University of Surrey, Guildford, GU2 7XH, Surrey, UK}

\author[0000-0001-5484-4987]{L.~A.~C.~van~Son}
\affiliation{Center for Astrophysics $|$ Harvard $\&$ Smithsonian,60 Garden St., Cambridge, MA 02138, USA}
\affiliation{Anton Pannekoek Institute for Astronomy, University of Amsterdam, Science Park 904, 1098XH Amsterdam, The Netherlands}
\affiliation{Max-Planck-Institut für Astrophysik, Karl-Schwarzschild-Straße 1, 85741 Garching, Germany}

\author[0000-0003-3441-7624]{R.~Farmer}
\affiliation{Max-Planck-Institut für Astrophysik, Karl-Schwarzschild-Straße 1, 85741 Garching, Germany}

\begin{abstract}
  \noindent
  Population synthesis relies on semi-analytic formulae to determine
  masses of compact objects from the (helium or carbon-oxygen) cores
  of collapsing stars. Such formulae are combined across mass ranges
  that span different explosion mechanisms, potentialy introducing
  artificial features in the compact object mass distribution. Such
  artifacts impair the interpretation of gravitational-wave
  observations. We propose a ``top-down'' remnant mass prescription
  where we remove mass from the star for each possible mass-loss
  mechanism, instead of relying on the fallback onto a
  ``proto-compact-object'' to get the final mass. For one of these
  mass-loss mechanisms, we fit the metallicity-dependent mass lost to
  pulsational-pair instability supernovae from numerical
  simulations. By imposing no mass loss in the absence of pulses, our
  approach recovers the existing compact object masses at the low mass
  end and ensures continuity across the
  core-collapse/pulsational-pair-instability regime. % Our remnant mass
  % prescription can be extended
  % to include other mass-loss mechanisms at the final collapse.\\
\end{abstract}

\section{Introduction}

Stellar and binary population synthesis calculations are necessary to
predict event rates and population statistics of astrophysical
phenomena, including those involving neutron stars (NS) and
black holes (BH). Typically, at the end of the evolution (carbon
depletion) the mass of the core is mapped to a compact object mass, using a
$M_\mathrm{comp.\ obj}\equiv M_\mathrm{comp.\ obj}(M_\mathrm{core})$
informed by core-collapse (CC) simulations (e.g., \citealt{fryer:12,
  spera:15, mandel:20, couch:20}, see also \citealt{zapartas:21,
  patton:21}) and/or (pulsational) pair instability (PPI) simulations
(e.g., \citealt{belczynski:16, woosley:17, spera:17, stevenson:19,
  marchant:19, farmer:19, breivik:20, renzo:20csm, costa:21}).

The most commonly adopted algorithms to obtain compact object masses
in the CC regime are the ``rapid'' and ``delayed'' prescriptions of
\cite{fryer:12}. In both cases, the compact object is built from the
``bottom-up'', starting from a proto-NS mass and adding the amount of
fallback expected in the (possibly failed) explosion. However, the
proto-NS mass and information about the core structure relevant to
calculate the fallback are usually not available
\citep[e.g.,][]{patton:20}. Instead, the total final mass of the star
is arguably easier to constrain in population synthesis models.

At the transition between CC and PPI (roughly at carbon-oxygen cores
of $\sim{}35\,M_\odot$, \citealt{woosley:17, marchant:19, farmer:19,
  renzo:20csm, costa:21}), a mismatch between commonly adopted fitting
formulae exists, and impairs the
interpretation of gravitational-wave data \citep[as pointed out in
Fig.~5 of][]{vanson:21}. While it is possible that the BH mass
function is discontinuous at the onset of the PPI regime (e.g.,
\citealt{renzo:20conv,costa:21}, Hendriks et al., in prep.), the
location and amplitude of a putative discontinuity should not be
governed by a mismatch between the fitting formulae.

\section{Top-down compact object masses}

In contrast with the ``bottom up'' approach of \cite{fryer:12}, we
propose a ``top-down'' compact object mass calculation. Starting from
the total stellar mass, we remove the amount of mass lost due to all
of the processes associated with the (possibly failed) explosion:

\begin{widetext}
  \begin{equation}
    \label{eq:mass}
      M_\mathrm{comp.\ obj} =
      M_\mathrm{pre-CC} - \left(\Delta M_\mathrm{SN} + \Delta M_{\nu, \mathrm{core}} + \Delta M_\mathrm{env} + \Delta M_\mathrm{PPI} + \cdots \right)
  \end{equation}
\end{widetext}

% where all masses are in $M_\odot$,
where $M_\mathrm{pre-CC}$ is the total mass at the onset of CC, and
each term in parenthesis corresponds to a potential mass-loss
mechanism: $\Delta M_\mathrm{SN}$ for the CC ejecta,
$\Delta M_{\nu, \mathrm{core}}$ the change in gravitational mass of
the core due to the neutrino losses, $\Delta M_\mathrm{env}$ the loss
of the envelope that can occur even in red supergiant ``failed''
core-collapse due to % the change in
% gravitational mass corresponding to
$\Delta M_{\nu, \mathrm{core}}$
\citep{nadezhin:80, lovegrove:13, piro:13, fernandez:18, ivanov:21},
and $\Delta M_\mathrm{PPI}$ the pulsational mass loss due to
pair-instability. Each term may be a function of the progenitor
properties, and may be theoretically or observationally informed
(e.g., $\Delta M_\mathrm{SN}$ could be derived from the light curves of a
large sample of observed SNe). \Eqref{eq:mass} can be extended by
adding additional mass-loss mechanisms in the parenthesis (e.g., disk
winds).

In the CC regime, the previous approach from \cite{fryer:12} can be recovered by setting
$\Delta M_\mathrm{SN} + \Delta M_{\nu, \mathrm{core}} = M_\mathrm{pre-CC} - M_\mathrm{comp.\ obj}^\mathrm{Fryer+12}$,
where the last term is the compact object mass as predicted by
\cite{fryer:12} and ignoring the other mass loss terms,
such as $\Delta M_\mathrm{PPI}$ and $\Delta M_\mathrm{env}$.

\begin{figure}[tbp]
    \begin{centering}
      \includegraphics[width=0.75\linewidth]{fit_DM_PPI.pdf}
      \caption{Each panel shows our fitting formula \Eqref{eq:fit} for
        the PPI induced mass-loss as a function of carbon-oxygen core
        mass at each metallicity $Z$. The crosses show the values from
        Tab.~1 \cite{farmer:19}.}
        % This label tells showyourwork that the script `figures/fit_DM_PPI.py'
        % generates the PDF included above
        \label{fig:fit_DM_PPI}
    \end{centering}
\end{figure}

\section{New fit for PPI ejecta}

Imposing $\Delta M_\mathrm{PPI}=0$ at the edge of the PPI regime,
\Eqref{eq:mass} produces a smooth BH mass distribution.
\Eqref{eq:fit} provides a fit (in $M_\odot$ units) to naked helium
star models from \cite{farmer:19} for
$\Delta M_\mathrm{PPI} \equiv \Delta M_\mathrm{PPI}(M_\mathrm{CO},Z)$.
While the fit of \cite{farmer:19} provides the BH mass after PPI, this
is only an estimate because of other mass loss processes that might
occur at CC \citep[e.g.,][]{renzo:20csm, powell:21, rahman:22}. Here,
we fit the mass removed by PPI (crosses in \Figref{fig:fit_DM_PPI}),
which is what is directly computed in \cite{farmer:19}.

% Each panel of \Figref{fig:fit_DM_PPI} shows
% % The dashed curves in each panel of \Figref{fig:fit_DM_PPI} show the
% % fit \Eqref{eq:fit} for each
% one metallicity computed in
% \cite{farmer:19}.
We neglect the (weak) metallicity dependence of the minimum core mass
for PPI, and we fit the data for initial helium core masses between
$38-60\,M_\odot$.  We emphasize that \cite{farmer:19} only simulated
helium cores. In the presence of a H-rich envelope at the onset of
PPI, if it is extended and red it can be easily removed by the first
pulse \citep[][]{woosley:17,renzo:20csm}. Thus the H-rich mass of red
supergiants should be added to the $\Delta M_\mathrm{PPI}$ provided
here. It is unclear what occurs in cases when the envelope is compact
and blue \citep[e.g.,][]{dicarlo:19, renzo:20merger, costa:21}.

\input{fit_DM_PPI.tex} %% generated by src/figures/fit_DM_PPI.py

The mass lost in PPI is sensitive to convection
\citep{renzo:20conv} and nuclear physics \citep{farmer:19,
  farmer:20, costa:21, woosley:21, mehta:21}, which can introduce
uncertainties up to $\sim{}20\%$ on the maximum BH mass. The accuracy
of our fit is comparable to these uncertainties.

\vspace*{-10pt}

% \section*{Acknowledgements}
% MR is grateful to R.~Luger for help with showyourwork
% \citep{luger:21}. The code associated to this paper is publicly
% available at
% \url{https://github.com/mathren/top_down_compact_obj_mass} and the
% input data are loaded from \url{https://zenodo.org/record/3346593}.  LvS
% acknowledges partial financial support from the National Science
% Foundation under Grant No. (NSF grant number 2009131), the Netherlands
% Organisation for Scientific Research (NWO) as part of the Vidi
% research program BinWaves with project number 639.042.728 and the
% European Union’s Horizon 2020 research and innovation program from the
% European Research Council (ERC, Grant agreement No. 715063).

\newpage
\bibliography{./top_down_comp_obj_mass.bib}
\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:


% !TEX TS-program = pdflatex
% !TEX encoding = UTF-8 Unicode

% This is a simple template for a LaTeX document using the "article" class.
% See "book", "report", "letter" for other types of document.

\documentclass[11pt]{article} % use larger type; default would be 10pt

\usepackage[utf8]{inputenc} % set input encoding (not needed with XeLaTeX)

%%% Examples of Article customizations
% These packages are optional, depending whether you want the features they provide.
% See the LaTeX Companion or other references for full information.

%%% PAGE DIMENSIONS
\usepackage{geometry} % to change the page dimensions
\geometry{a4paper} % or letterpaper (US) or a5paper or....
\geometry{margin=1in} % for example, change the margins to 2 inches all round
% \geometry{landscape} % set up the page for landscape
%   read geometry.pdf for detailed page layout information

\usepackage{graphicx} % support the \includegraphics command and options
\usepackage{amsmath}
\usepackage{amsfonts}
% \usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent

%%% PACKAGES
\usepackage{booktabs} % for much better looking tables
\usepackage{array} % for better arrays (eg matrices) in maths
\usepackage{paralist} % very flexible & customisable lists (eg. enumerate/itemize, etc.)
\usepackage{verbatim} % adds environment for commenting out blocks of text & for better verbatim
\usepackage{subfig} % make it possible to include more than one captioned figure/table in a single float
% These packages are all incorporated in the memoir class to one degree or another...

%%% HEADERS & FOOTERS
\usepackage{fancyhdr} % This should be set AFTER setting up the page geometry
\pagestyle{fancy} % options: empty , plain , fancy
\renewcommand{\headrulewidth}{0pt} % customise the layout...
\lhead{}\chead{}\rhead{}
\lfoot{}\cfoot{\thepage}\rfoot{}

%%% SECTION TITLE APPEARANCE
\usepackage{sectsty}
\allsectionsfont{\sffamily\mdseries\upshape} % (See the fntguide.pdf for font help)
% (This matches ConTeXt defaults)

%%% ToC (table of contents) APPEARANCE
\usepackage[nottoc,notlof,notlot]{tocbibind} % Put the bibliography in the ToC
\usepackage[titles,subfigure]{tocloft} % Alter the style of the Table of Contents
\renewcommand{\cftsecfont}{\rmfamily\mdseries\upshape}
\renewcommand{\cftsecpagefont}{\rmfamily\mdseries\upshape} % No bold!

%%% END Article customizations

%%% The "real" document content comes below...

\title{Homework 2}
\author{Alireza Shafaei\\78428133}
%\date{} % Activate to display a given date or no date (if empty),
         % otherwise the current date is printed

\begin{document}
\maketitle

\section*{Problem 1}
Let G(X) be the woman that is paired with man X by the Gale-Shapley proposal algorithm. Prove that there is no stable pairing P such that X prefers P(X) (his partner in pairing P) to G(X).\\
\textbf{Proof.}
Let's say there's a stable pairing $P$ such that $X$ prefers $P(X)$ to $G(X)$. This means $P(X)$ has to appear before $G(X)$ in $X$'s preference list. If so, according to the Gale-Shapley proposal algorithm, $X$ must've proposed to $P(X)$ before $G(X)$. Given that the final stable marriage of $X$ is $G(X)$, then there must exist a $Y$ such that $P(X)$ preferes to $X$, and $P(X)$ is the first available preference in $Y$'s list, resulting in a break up of $X$ and $P(X)$; thus no such stable marriage $P$ can exist.

\section*{Problem 2}
Prove that the expectation of a sum of random variables is the sum of the expectation of these random variables.\\
\textbf{Proof.} I demonstrate this feature using two random variables. Through induction, it could be generalized for $n$ random variables.

\begin{gather}
\mathbb{E}[X+Y] = \sum_{\omega_1 \in \Omega} \sum_{\omega_2 \in \Omega} (X(\omega_1)+Y(\omega_2))\mathbb{P}(\omega_1,\omega_2) \\
\Rightarrow \mathbb{E}[X+Y] = 	\sum_{\omega_1 \in \Omega}X(\omega_1) \sum_{\omega_2 \in \Omega}\mathbb{P}(\omega_1,\omega_2) +
					\sum_{\omega_2 \in \Omega}Y(\omega_2) \sum_{\omega_1 \in \Omega}\mathbb{P}(\omega_1,\omega_2) \\
\Rightarrow \mathbb{E}[X+Y] = 	\sum_{\omega_1 \in \Omega}X(\omega_1) \sum_{\omega_2 \in \Omega}\mathbb{P}(\omega_1|\omega_2)\mathbb{P}(\omega_2) +
					\sum_{\omega_2 \in \Omega}Y(\omega_2) \sum_{\omega_1 \in \Omega}\mathbb{P}(\omega_2|\omega_1)\mathbb{P}(\omega_1)\\
\Rightarrow \mathbb{E}[X+Y] = 	\sum_{\omega_1 \in \Omega}X(\omega_1) \mathbb{P}(\omega_1)+
					\sum_{\omega_2 \in \Omega}Y(\omega_2) \mathbb{P}(\omega_2)\\
\Rightarrow \mathbb{E}[X+Y] = 	\mathbb{E}[X]+\mathbb{E}[Y]
\end{gather}

\section*{Problem 3}
 Prove that the expectation of a product of independent random variables is the product of the expectation of these random variables.\\
\textbf{Proof.} I demonstrate this feature using two independent random variables. Through induction, it could be generalized for $n$ independent random variables.
\begin{gather}
\mathbb{E}[XY] = \sum_{\omega_1 \in \Omega} \sum_{\omega_2 \in \Omega} X(\omega_1)Y(\omega_2)\mathbb{P}(\omega_1,\omega_2) \\
X \perp Y \Rightarrow \mathbb{E}[XY] = \sum_{\omega_1 \in \Omega} \sum_{\omega_2 \in \Omega} X(\omega_1)Y(\omega_2)\mathbb{P}(\omega_1)\mathbb{P}(\omega_2) \\
\Rightarrow \mathbb{E}[XY] = \sum_{\omega_1 \in \Omega} X(\omega_1)\mathbb{P}(\omega_1)\sum_{\omega_2 \in \Omega} Y(\omega_2)\mathbb{P}(\omega_2) \\
\Rightarrow \mathbb{E}[XY] = \mathbb{E}[X]\mathbb{E}[Y]
\end{gather}

\section*{Problem 4}
Use the previous two results to prove that the variance of a sum of pairwise independent random variables is the sum of the variances of these random variables.\\
\textbf{Proof.} I demonstrate this feature using two independent random variables. Through induction, it could be generalized for $n$ pairwise independent random variables.
\begin{gather}
Var[X+Y] = \mathbb{E}[(X+Y)^2] - (\mathbb{E}[X+Y])^2\\
\Rightarrow Var[X+Y] = \mathbb{E}[X^2+Y^2+2YX] - (\mathbb{E}[X]+\mathbb{E}[Y])^2\\
\Rightarrow Var[X+Y] = \mathbb{E}[X^2]+\mathbb{E}[Y^2]+\mathbb{E}[2YX] - (\mathbb{E}[X])^2-(\mathbb{E}[Y])^2-(2\mathbb{E}[X]\mathbb{E}[Y])\\
\Rightarrow Var[X+Y] = \mathbb{E}[X^2]+\mathbb{E}[Y^2]+2\mathbb{E}[Y]\mathbb{E}[X] - (\mathbb{E}[X])^2-(\mathbb{E}[Y])^2-(2\mathbb{E}[X]\mathbb{E}[Y])\\
\Rightarrow Var[X+Y] = \mathbb{E}[X^2]- (\mathbb{E}[X])^2+\mathbb{E}[Y^2]-(\mathbb{E}[Y])^2\\
\Rightarrow Var[X+Y] = Var[X]+Var[Y]
\end{gather}

\section*{Problem 4}
Suppose I have a sequence of $n$ different numbers. I reorder the sequence randomly (each ordering equally likely) and give you the numbers one at a time in this random order. You are interested in determining the maximum number in the sequence.

\begin{itemize}
	\item An obvious approach is to keep the maximum of the numbers given so far, updating this maximum as needed. What is the expected number of times you update the maximum (as a function of $n$)?\\
\textbf{Answer.} Let's say we have seen $i$ numbers so far, the probability that $(i+1)_{th}$ number is the biggest in a series of $i+1$ numbers will be $\frac{1}{i+1}$, since the biggest number could be any of $i+1$ numbers. Let $X_i$ denote whether we updated upon seeing $i_{th}$ number. The expected value of updates will be calculated as follows:

\begin{gather}
\mathbb{E}[X_i] = 1.\frac{1}{i}+0.\frac{i-1}{i}=\frac{1}{i}\\
Y = X_1+X_2+X_3+\ldots+X_n\\
\mathbb{E}[Y]=\sum_{i=1}^{n}\mathbb{E}[X_i] = \sum_{i=1}^{n}\frac{1}{i} = H_n
\end{gather}
So the answer will be $H_n$.

\item Suppose after you see each number, I ask ``Is this the maximum of all n numbers?'' If you say ``no'' then I give you the next number. If you say ``yes'' then you win if the number truly is the maximum number in the sequence, otherwise you lose.\\
Describe an algorithm for you to follow that results in a probability of winning that is at least 1/4. Note that your algorithm knows n from the start.\\
\textbf{Answer.} If we have seen $i$ numbers so far, it means there are $n-i$ numbers that we haven't seen. On updating max with $i_{th}$ number, the probability of $i_{th}$ number being  the biggest number will be $\frac{i}{n}$. Let's call probability of wining after update on $i_{th}$ number, $P_{i}$, we'd have:

\begin{gather}
	P_{i} = \frac{i}{n}\\
	P_i \geq \frac{1}{4} \Rightarrow \frac{i}{n} \geq \frac{1}{4}\\
	\Rightarrow i \geq \frac{n}{4}
\end{gather}
Meaning that after seeing at least $n/4$ numbers, if the maximum was updated, we should say yes. In other words, if an update on max occured after seeing at least $n/4$ numbers, we're at least $1/4$ sure that this is the biggest number.
\end{itemize}

\end{document}


\section{Reaction initial state simulation.}

\subsection{Allowed projectiles and bombarding energy range for interaction
with nucleon and nuclear targets.}
\hspace{1.0em}
The GEANT4 kinetic model is capable to predict final states (produced
hadrons
which belong to the pseudoscalar meson nonet and the baryon (antibaryon)
octet) of reactions on nucleon and nuclear targets
with a large variety of hadron (the same types as final state hadrons) and
nuclear projectiles. The allowed bombarding kinetic energy in
the hadron--nucleon,
  hadron--nucleus and nucleus--nucleus collisions
 is recommended to be more than
 20 MeV in the laboratory frame.
  The upper limit of initial
  kinetic energy is approximately $10$ GeV per initial particle.

  This model is also able to predict
final states in the photon--nucleon and photon--nucleus inelastic
collisions  as well as the nuclear absorption of the
stopping $\pi^{-}$, $K^{-}$ and $\bar{p}$.
 The last cases are described in the
separate chapters.

  There are also needs
 to simulate hadron
kinetics after the "parton string" stage of nuclear interaction, taking
account secondary hadron rescatterings.

\subsection{MC initialization procedure for a nucleus}
\hspace{1.0em}The initialization of each nucleus, consisting from $A$
nucleons and $Z$ protons ($N=A-Z$ neutrons)
with coordinates $\mathbf{r}_i$ and momenta
$\mathbf{p}_i$, where $i = 1,2,...,A$ is performed.
For the hadron kinetic model the MC initialization procedure for a nucleus is
similar as for the
parton string model except of some peculiarities, which are taken into
account:
\begin{itemize}
\item Nucleon radii $r_i$ are selected randomly in the rest of nucleus according
to proton or neutron density $\rho(r_i)$.
For heavy nuclei with $A > 16$ \cite{GLMP91} normalized on unity
nucleon density is
\begin{equation}
\label{KNIS1}\rho(r_i) =
 \frac{\rho_0}{1 + \exp{[(r_i - R)/a]}}
\end{equation}
where
\begin{equation}
\label{KNIS2}\rho_0 \approx \frac{3}{4\pi R^3}(1+\frac{a^2\pi^2}{R^2})^{-1}.
\end{equation}
Here $R=r_0 A^{1/3}$ \ fm and $r_0=1.16(1-1.16A^{-2/3})$ \ fm and $a
\approx 0.545$ fm.  For light nuclei with $A < 17$ normalized on unity
nucleon density is
given by a harmonic oscillator shell model \cite{Elton61}, e. g.
\begin{equation}
\label{KNIS3} \rho(r_i) = (\pi R^2)^{-3/2}\exp{(-r_i^2/R^2)},
\end{equation}
where $R^2 = 2/3<r^2> = 0.8133 A^{2/3}$ \ fm$^2$ or
\begin{equation}
\label{KNIS4} \rho(r_i) =
\frac{4}{\pi^{3/2}R^3}[1+\frac{A-4}{6}(\frac{r_i}{R})^2]
\exp{(-r_i^2/R^2)},
\end{equation}
where
\begin{equation}
\label{KNIS5} R^2=(\frac{5}{2}-\frac{4}{A})^{-1}(<r^2_{ch}>_{A}-
<r^2_{ch}>_{p})
\end{equation}
The mean squared charge radii of the nucleus $<r^2_{ch}>_{A}$ and proton
$<r^2_{ch}>_{p}$ are taken from the measurements of lepton-nucleus
scattering experiments \cite{BJ77}.  To take into account nucleon
repulsive core it is assumed that internucleon distance $d > 0.8$ \ fm;

\item The initial momenta of the nucleons are randomly choosen between $0$ and
$p^{max}_F$, where
the maximal momenta of nucleons (in the local Thomas-Fermi
approximation \cite{DF74}) depends from
the proton or neutron density $\rho_{Z,N}$ according to
\begin{equation}
\label{KNIS6} p^{max}_F = \hbar c(3\pi^2 \rho_{Z,N})^{1/3}
\end{equation}
with $\hbar c = 197.327$ MeVfm.

\item To obtain coordinate and momentum components, it
 is assumed that nucleons are distributed isotropicaly in configuration
 and momentum spaces;

We assume \cite{URQMD97}
that nucleons are not points in configuration space
and they are represented by Gaussian shaped density distributions (c = 1):
\begin{equation}
\label{KNIS7}\phi({\bf x_i}, t) = (\frac{2\alpha}{\pi})^{3/4}
\exp{\{-\alpha ({\bf x_i}
- {\bf r_i} (t))^2 + \frac{i}{\hbar}{\bf p_i} (t) {\bf x_i}\}},
\end{equation}
where $\alpha=0.25$ \ fm$^{-2}$ is a model parameter.
It gives us a possibility to take into account
the Pauli blocking (the Pauli blocking procedure is decsribed below),
i. e. if the phase space of $i$-th nucleon is already occupied by other
nucleons, its sampling is deserted;

\item Then perform shifts of nucleon coordinates ${\bf r_i^{\prime}}
= {\bf r_i} - 1/A \sum_i {\bf r_i}$ and momenta ${\bf p_i^{\prime}}
= {\bf p_i} - 1/A \sum_i {\bf p_i}$
of nucleon momenta. The nucleus must be centered in configuration space around
$\mathbf{0}$, \textit{i. e.} $\sum_i {\mathbf{r}_i} = \mathbf{0}$ and
 the nucleus must be at rest, i. e. $\sum_i {\bf p_i} = \bf 0$ and
$\sum_i {\bf r_i} \times {\bf p_i}={\bf 0}$;

\item We compute energy per nucleon $e = E/A = m_{N} + B(A,Z)/A$,
where $m_N$ is nucleon mass and the nucleus binding energy $B(A,Z)$ is given
by the Bethe-Weizs\"acker formula\cite{BM69}:
\begin{equation}
\begin{array}{c}
\label{KNIS8} B(A,Z) = \\
= -0.01587A + 0.01834A^{2/3} + 0.09286(Z- \frac{A}{2})^2 +
0.00071 Z^2/A^{1/3},
\end{array}
\end{equation}
 and find the effective mass of each nucleon $m^{eff}_i =
\sqrt{(E/A)^2 - p^{2\prime}_i}$.
\end{itemize}

\subsection{Lorentz boost of nucleon longitudinal momenta and energies.}

\hspace{1.0em}In the case of fast moving nucleus with initial momentum
per nucleon ${\bf P_0}= \{0, 0, P_{z0}\}$ one should perform Lorentz
transformation of the nucleon longitudinal momenta
\begin{equation}
\label{KNIS9}  p_{zi} \rightarrow \gamma_i (p_{zi} - \beta_i e_{i})
\end{equation}
and the nucleon energies
\begin{equation}
\label{KNIS10} e_{i} \rightarrow \gamma_i (e_{i} - \beta_i p_{zi}),
\end{equation}
where $\beta_{i}$ is defined as
\begin{equation}
\label{KNIS11} \beta_{i} = \frac{P_{z0}}{\sqrt{P_{z0}^2 + m^{eff2}_i}}
\end{equation}
and $\gamma_i$ is given by
\begin{equation}
\label{KNIS12}\gamma_i = \frac{1}{\sqrt{1 - \beta_i^2}}.
\end{equation}

\subsection{Lorentz contraction of the fast moving nucleus.}
\hspace{1.0em}For this case one need also to perform the Lorentz
contraction of the nucleus, \textit{i. e.}
\begin{equation}
\label{KNIS13} r_{zi} \rightarrow r_{zi}/ \gamma_{i}.
\end{equation}
\subsection{Random choice of the impact parameter.}

\hspace{1.0em}The impact parameter $0 \leq b \leq R_p + R_t$ is randomly
selected according to the probability:
\begin{equation}
\label{KNIS14}P({\bf b})d{\bf b} = b d{\bf b},
\end{equation}
where $R_p$ and $R_t$ are the target and projectile radius,
respectively. In the case of nuclear projectile or target the nuclear radius is
determined from condition:
\begin{equation}
\label{KNIS15}\frac{\rho(R)}{\rho(0)} = 0.01.
\end{equation}
 Then one should update the transversal components of
nucleon coordinates:
\begin{equation}
\label{KNIS16} r_{xi} \rightarrow r_{xi} + b_x
\end{equation}
and
\begin{equation}
\label{KNIS17} r_{yi} \rightarrow r_{yi} + b_y.
\end{equation}
Finaly, for target nucleus, if a projectile is centered around $0$, one
should perform a shift of the nucleon longitudinal coordinates:
\begin{equation}
\label{KNIS18} r_{zi} \rightarrow r_{zi} + \Delta r_z/\gamma_{i},
\end{equation}
where $\Delta r_z = R_p + 1.5 \ fm + R_t + 1.5 \ fm$ is taken.

In the case of hadron--nucleus collision we determine the initial
angular momentum
of target nucleus:
\begin{equation}
\label{KNIS19} \vec{L}_0= \vec{p}_0 \times \vec{r}_0,
\end{equation}
where $\vec{p}_0$ and $\vec{r}_0$ are initial momentum and  radius vector
of incoming hadron enter point in the target nucleus rest frame.