\section{Conclusion} \label{conclusion}

In this project, we implement a real-roots isolation program based on
Budan’s theorem and continued fraction. Besides that, we also use several
methods to optimize the program, like Taylor Expansion for polynomial shift and
interval arithmetic for error control.

Then we compare the running time of these two algorithms. It is noticeable that
when there are conjugate complex roots, Budan’s theorem will take longer. And
continued fraction methods perform worse when polynomials have several large
real roots due to slow shifts of polynomials. This can be optimized in the
future.

With the application of interval arithmetic, our program becomes more robust to
the errors from inexact computation and representation, although it is not
perfect for all of the cases. We analyze the conditions that might
cause failure of the program. We find that after square-free decomposition,
every factors has error in express of coefficients. It is hard to isolate close
real roots with this expression since small change of coefficients might causes
large change the property of these roots.


In this Section we introduce the Parametric Hypercubes abstract domain \adomain.

Intuitively, an abstract state of our domain tracks disjunctive information relying on floating-point intervals of fixed width. A state of \adomain\ is made by a set of hypercubes of dimension $|\variables|$. Each hypercube has $|\variables|$ sides, one for each variable, and each side contains an abstract non-relational value for the corresponding variable. Each hypercube represents a set of admissible combinations of values for all variables.

The name Hypercubes comes from the geometric interpretation of the elements of \adomain . The concrete state of a program with variables in $\variables$ is an environment in $\funzione{\variables}{\real}$. This can be isomorphically represented by a tuple of values where each item of the tuple represents a program variable. Seen in this way, the concrete state corresponds, geometrically, to \emph{a point} in the $|\variables|$-dimensional space. Each dimension of the space represents the possible values that the corresponding variable of the program can assume. The concrete trace of a program is a sequence of points in such space (one for each state of the trace). The hypercubes of our \adomain\ domain are \emph{volumes} in the same $|\variables|$-dimensional space. Each side of the hypercube is the concretization of the abstract value of the corresponding variable, and thus it corresponds to a set of values in that dimension of the space. The concretization of an hypercube is the set of all the points contained in its volume. A state in \adomain\ is composed by a set of hypercubes: its concretization is the union of all the volumes of its hypercubes.  In this way we track disjunctive information.

\subsection{Lattice structure}
An abstract state of \adomain\ is made by a \emph{set} of hypercubes. Each hypercube is represented by a tuple of abstract values. The dimension of these tuples is equal to the number of program variables: this means that each variable is associated to a given item of the tuple (i.e., to a specific side of the hypercube).
Consider for instance a program in which $\variables = \{x_1, x_2\}$. In this case, the hypercubes of \adomain\ are 2D-rectangles. In particular, the two sides of a single hypercube are two abstract values, one for $x_1$ and one for $x_2$.

A priori, our approach is modular w.r.t. the non-relational abstract domain we adopt to approximate the values of single variables inside an hypercube. We abstract floating-point variables through intervals of real values. We adopt set of hypercubes to improve the precision of the analysis and to track disjunctive information. This is useful, for instance, when the values of a variable are clustered in different ranges: instead of having a very big interval to cover them all (and which would cover also a lot of invalid values), we use two (or more) smaller intervals. Since it would be particularly expensive to perform all the lattice operators pointwisely, we partition the possible values into intervals of fixed width. As an example, suppose that the initial vertical velocity of the balls of our case study ranges between $50.0$ and $60.0$ or between $-60.0$ and $-50.0$. A single interval would approximate these values with $[-60.0,60.0]$, while with our approach we track two intervals, $[-60.0,-50.0]$ and $[50.0,60.0]$ (with fixed width $10.0$), which distinguish between balls thrown downwards and balls thrown upwards. The performance of this domain, though, becomes a crucial point, because the number of possible hypercubes in the space is potentially exponential with respect to the number of partitions along each spatial axis. The complexity is lightened by the use of a \emph{fixed} width for each variable, by partitioning the possible intervals, and by the efficiency of set operators on tuples.

Since a single hypercube is a tuple of intervals (one for each side), another performance booster is the use of a smart representation for intervals. In order to store the specific interval range we just use a single integer representing it. Each variable $x_i$ is associated to an interval width (specific only for that variable), which we call $w_i$ and which is a parameter of the analysis. In Section \ref{sec:tuning} we will present a variation of our analysis which computes automatically the widths, adapting them recursively and freeing the user from the need to specify values for them. For now, just notice that the smaller the width associated to a variable, the more granular and precise the analysis on that variable (and the heavier computationally the analysis). Each width $w_i$ is a floating point number that represents the width of all the possible abstract intervals associated to $x_i$. More precisely, given a width $w_i$ and an integer index $m$, the interval uniquely associated to the variable $x_i$ is $[m \times w_i, (m+1) \times w_i]$.

\textbf{Example:} Consider the case study of Section \ref{sec:case_study} and in particular the two variables \statement{px} and \statement{py}. Suppose that the widths associated to such variables are $w_1 = 10.0, w_2 = 25.0$. The hypercubes in this case are 2D-rectangles. The area of each rectangle is $10.0 \times 25.0 = 250.0$. We can draw such rectangles on the Cartesian plan, where the horizontal axis represents the values which \statement{px} can assume, and the vertical axis represents those of \statement{py}. Each side of a hypercube is identified by an integer index, representing the interval of values associated to that side. A 2D hypercube is then uniquely identified by a pair of integers. For instance, the hypercube $h_1 = ( 0, 1 )$ says that $\statement{px} \in [0.0, 10.0]$ and $\statement{py} \in [25.0, 50.0]$, while the hypercube $h_2 = ( 0, 0 )$  associates $\statement{px}$ to $[0.0, 10.0]$ and $\statement{py}$ to $[0.0, 25.0]$. In Figure \ref{fig:hcExample} we can see the graphical representation of the two hypercubes associated to the initialization of the case study (i.e., $h_1$ and $h_2$). The two axes of the Cartesian plan are split in correspondence of multiples of $10.0$ ($x$-axis) and $25.0$ ($y$-axis). In Figure \ref{fig:hcExample2}, instead, we depict the hypercubes obtained after executing the first iteration of the \statement{while} loop. Note that the hypercubes are now six. The ball is moving towards the right of the screen and is going downwards: this is coherent with the fact that the horizontal velocity is certainly positive (between $0.0$ and $60.0$), while the vertical velocity is certainly negative (between $-30.0$ and $-25.0$).

\begin{figure}[ht]
\begin{centering}
\includegraphics[scale=0.35]{Pics/example_hc_2d.png}
\caption{The abstract state of the case study after the initialization of the variables (focusing the attention only on \statement{px,py}, when their widths are, respectively, $10.0$ and $25.0$)}
\label{fig:hcExample}
\end{centering}
\end{figure}

\begin{figure}[ht]
\begin{centering}
\includegraphics[scale=0.35]{Pics/example_hc_2d_2.png}
\caption{The abstract state of the case study after the first iteration of the loop (focusing the attention only on \statement{px,py}, when their widths are, respectively, $10.0$ and $25.0$)}
\label{fig:hcExample2}
\end{centering}
\end{figure}

We now define formally our abstract domain. Each abstract state is a set of hypercubes, where each hypercube is composed by $|\variables|$ integer numbers. The abstract domain is then defined by $\adomain = \wp(\integer^n)$ where $n = |\variables|$.

The definition of lattice operators relies on set operators: the partial order is defined through set inclusion, the lub and glb are set union and set intersection, respectively, while bottom and top are the empty set and the set containing all possible $n$-dimensional hypercubes, respectively. Formally, the lattice definition is $\langle\wp(\integer^n), \subseteq, \cup, \cap, \emptyset, \integer^n\rangle$.

\begin{lemma}
$\langle\wp(\integer^n), \subseteq, \cup, \cap, \emptyset, \integer^n\rangle$ is a complete lattice.
%\begin{proof}
%The proof follows immediately by basic properties of set operators.
%\end{proof}
\end{lemma}

\subsection{Concretization function}
We denote by $\ael{A}$ the non-relational abstract domain on which our analysis is parameterized, and by $n$ the number of variables of the program, where $n = | \variables |$.

$$
\begin{array}{l}
\gamma_{\aval} : \funzione{\wp(\integer^n)}{\wp(\real^\variables)}\\
\gamma_{\aval}(\ael{V}) = \{\sigma : \exists v \in \ael{V} : \forall i \in [1..n] : \sigma_i \in \gamma_\ael{A}(\afunction{getAbsValue}_v(i)) \}
\end{array}
$$

where: (i) $\sigma \in \real^\variables$ and $\sigma_i \in \real$ denotes the $i$-th element of the tuple $\sigma$, (ii) $\gamma_\ael{A} : \funzione{\ael{A}}{\wp(\real)}$ is the concretization function of abstract values of the non-relational abstract domain on which our analysis is parameterized, and (iii)  $\afunction{getAbsValue}_v : \funzione{\naturals}{\ael{A}}$ is the function that, given an integer index, returns the abstract value (in the domain $\ael{A}$) which corresponds to that index inside the tuple $v$.

$\gamma_{\aval}$ concretizes a set of hypercubes to a set of vectors of $n$ floating point values.

$$
\begin{array}{l}
\gamma_{\adomain} : \funzione{\wp(\integer^n)}{\wp(\funzione{\variables}{\real})}\\
\gamma_{\adomain}(\ael{V}) = \{[\statement{x} \mapsto \cel{r}(\avariableindex{\statement{x}}) : \statement{x} \in \variables] : \cel{r} \in \gamma_{\aval}(\ael{V})\}
\end{array}
$$

$\gamma_{\adomain}$ simply transforms the vectors returned by $\gamma_{\aval}$ into concrete environments relying on the function $\avariableindexname : \funzione{\variables}{\naturals}$, that, given a variable, returns its index in the elements of \adomain.

%Intuitively, we represent a concrete value as a tuple of real values (one for each variable of the program). The concretization of an abstract state $h \in \adomain$ is then a set of tuples. The concretization of $h$ is the union of all the concretizations of its hypercubes, i.e., all the points belonging to the volumes of its hypercubes. Each tuple of the concretization of $h$, then, is a point belonging to one hypercube of $h$.

\subsection{Widening operator}
The domain described so far does not ensure the convergence of the analysis. In fact, a \statement{while} loop may add new hypercubes with increased indices at each iteration, and the dimension of the abstract state (i.e., the hypercubes set) would increase at each iteration without converging. Thus, we need a way to force the convergence of the analysis. Given our abstract state representation, we fix for each variable of the program a maximum integer index $n_i$ such that $n_i$ represents the interval $[n_i \times w_i, +\infty]$. The same happens symmetrically for negative values. In this way, the set of indices of a given variable is finite, and the resulting domain has finite height. Thus, in this scenario, the widening operator coincides with the lub operator, i.e., set union.

This approach may seem too rough since we establish the bounds of intervals before running the analysis. However, this allows us to control the number of possible intervals in our hypercubes, and this is particularly important for the efficiency of the overall analysis. In addition, when analysing physics simulations we can use the initialization of variables and the property we want to check in order to establish convenient bounds for the intervals. For instance, in the case study presented in Section \ref{sec:case_study} we are interested in checking if a ball stays in the screen, that is, if \statement{px} is greater than zero and less than a given value \statement{w} representing the width of the screen.

Observe that more sophisticated widening operators could be used as an alternative to the adopted solution described above, but this could affect the performance of the resulting analysis.

%\subsection{Other data types or non-relational abstractions}
%\todogiulia{Secondo me questa subsection si puo' cancellare}
%As suggested before, for now we focus the application of our abstract domain to physics simulations, and for this reason we abstract floating point variables through intervals of fixed width. However, we may apply other kind of abstractions (e.g., the Sign domain) to our framework to consider other types of variables (integer, boolean, etc.). We will sketch other possible applications of our framework in Section \ref{sec:otherapplications}.

12. Hypercubes Domain/HC/Sections/versione SAS2013/3a_hypercubes_domain.tex

12. Hypercubes Domain/Sections/versione SAS2013/3a_hypercubes_domain.tex


\input{../header_function}

%---------- start document ---------- %
\section{arith1 - miscellaneous arithmetic functions}\linkedzero{arith1}

\subsection{floorsqrt -- floor of square root}\linkedone{arith1}{floorsqrt}
\func{floorsqrt}{\hiki{a}{integer/\linkingone{rational}{Rational}}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return the floor of square root of \param{a}.\\
%\spacing
% input, output document
%\quad Input number \param{a} must be integer or \linkingone{rational}{Rational}.\\
%
\subsection{floorpowerroot -- floor of some power root}\linkedone{arith1}{floorpowerroot}
\func{floorpowerroot}{\hiki{n}{integer},\ \hiki{k}{integer}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return the floor of \param{k}-th power root of \param{n}.\\
%\spacing
% input, output document
%\quad Input numbers \param{n}, \param{k} must be integer.\\
%
\subsection{legendre - Legendre(Jacobi) Symbol}\linkedone{arith1}{legendre}
\func{legendre}{\hiki{a}{integer},\ \hiki{m}{integer}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return the Legendre symbol or Jacobi symbol $\DS \Bigl(\frac{\param{a}}{\param{m}}\Bigr)$.\\
%\spacing
% input, output document
%\quad Input numbers \param{a}, \param{m} must be integer.\\
%
\subsection{modsqrt -- square root of $a$ for modulo $p$}\linkedone{arith1}{modsqrt}
\func{modsqrt}{\hiki{a}{integer}, \, \hiki{p}{integer}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return one of the square roots of \param{a} for modulo \param{p} if square roots exist, raise ValueError otherwise.\\
\spacing
% add document
%\spacing
% input, output ducument
\quad \param{p} must be a prime number.\\
%
\subsection{expand -- $m$-adic expansion}\linkedone{arith1}{expand}
\func{expand}{\hiki{n}{integer}, \, \hiki{m}{integer}}{\out{list}}\\
\spacing
% document of basi document
\quad Return the \param{m}-adic expansion of \param{n}.\\
\spacing
% input, output document
\quad \param{n} must be nonnegative integer. \param{m} must be greater than or equal to $2$.  The output is a list of expansion coefficients in ascending order.\\
%
\subsection{inverse -- inverse}\linkedone{arith1}{inverse}
\func{inverse}{\hiki{x}{integer}, \, \hiki{n}{integer}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return the inverse of \param{x} for modulo \param{n}.\\
\spacing
% input, output document
\quad \param{n} must be coprime to \param{x}.\\
%
\subsection{CRT -- Chinese Reminder Theorem}\linkedone{arith1}{CRT}
\func{CRT}{\hiki{nlist}{list}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return the uniquely determined integer satisfying all modulus
conditions given by \param{nlist}.\\
\spacing
% input, output document
\quad Input list \param{nlist} must be the list of lists each consisting of two elements.
The first element is remainder and the second is divisor.
They must be integer.\\
%
\subsection{AGM -- Arithmetic Geometric Mean}\linkedone{arith1}{AGM}
\func{AGM}{\hiki{a}{integer},\ \hiki{b}{integer}}{\out{float}}\\
\spacing
% document of basi document
\quad Return the Arithmetic-Geometric Mean of \param{a} and \param{b}.\\
%\spacing
% input, output document
%\quad Input number \param{a}, \param{b} must be integer.\\
%
%\subsection{\_BhaskaraBrouncker}\linkedone{arith1}{\_BhaskaraBrouncker}
%\func{\_BhaskaraBrouncker}{\hiki{n}{integer}}{\out{integer}}\\
%\spacing
% document of basi document
%\quad Return the minimum tuple \param{p}, \param{q} such that, $\param{p}^2
%- \param{n} \param{q}^2 = \pm 1$.\\
%\spacing
% input, output document
%\quad Input number \param{n} must be positive integer.
%
\subsection{vp -- $p$-adic valuation}\linkedone{arith1}{vp}
\func{vp}{\hiki{n}{integer},\ \hiki{p}{integer}, \hikiopt{k}{integer}{0}}{\out{tuple}}\\
\spacing
% document of basi document
\quad Return the \param{p}-adic valuation and other part for \param{n}.\\
\spacing
% added document
\quad \negok If $k$ is given, return the valuation and the other part for $\param{n}p^\param{k}$.\\
% input, output document
%\quad Input number \param{n}, \param{p} must be int, long or \linkingone{rational}{Integer}.
%
\subsection{issquare - Is it square?}\linkedone{arith1}{issquare}
\func{issquare}{\hiki{n}{integer}}{\out{integer}}\\
\spacing
% document of basi document
\quad Check if \param{n} is a square number and return square root
of \param{n} if \param{n} is a square.
Otherwise, return \(0\).\\
%\spacing
% input, output document
%\quad Input number \param{n} must be int, long or \linkingone{rational}{Integer}.
%
\subsection{log -- integer part of logarithm}\linkedone{arith1}{log}
\func{log}{\hiki{n}{integer},\ \hikiopt{base}{integer}{2}}{\out{integer}}\\
\spacing
% document of basi document
\quad Return the integer part of logarithm of \param{n} to the \param{base}.\\
%\spacing
% input, output document
%\quad Input number \param{n}, \param{base} must be int, long or \linkingone{rational}{Integer}.
%
\subsection{product -- product of some numbers}\linkedone{arith1}{product}
\func{product}{\hiki{iterable}{list},\ \hikiopt{init}{object}{None}}{\out{\hiki{prod}{object}}}\\
\spacing
% document of basic document
\quad Return the products of all elements in \param{iterable}. \\
\spacing
% added document
\quad If \param{init} is given, the multiplication starts with \param{init} instead of the first element in \param{iterable}.\\
\spacing
% input, output document
\quad Input list \param{iterable} must be list of mathematical objects which support multiplication.\\
The type of output \param{prod} is determined by the types of elements of \param{iterable} and \param{init}.\\
If the \param{iterable} is empty, then \param{init} (if given) or \(1\) (otherwise) will be returned.\\
%
\begin{ex}
>>> arith1.AGM(10, 15)
12.373402181181522
>>> arith1.CRT([[2, 5], [3, 7]])
17
>>> arith1.CRT([[2, 5], [3, 7], [5, 11]])
192
>>> arith1.expand(194, 5)
[4, 3, 2, 1]
>>> arith1.vp(54, 3)
(3, 2)
>>> arith1.product([1.5, 2, 2.5])
7.5
>>> arith1.product([3, 4], 2)
24
>>> arith1.product([])
1
\end{ex}

%---------- end document ---------- %

\input{../footer}


\subsection{Matrices over fields}\label{subsec:matrices_over_fields}

We will assume that all matrices have entries from some fixed \hyperref[def:field]{field} \( \BbbK \). We will later on need to distinguish between real and complex matrices, but the theory built here holds more generally than that, and we choose to postulate it for arbitrary fields.

The definitions of \hyperref[def:triangular_matrix]{triangular} and \hyperref[def:triangular_matrix]{elementary matrices} make sense over more general rings, however we introduce them because of \fullref{alg:plu_decomposition}, which has no direct generalization.

\begin{definition}\label{def:triangular_matrix}
  An \term{upper triangular matrix} is one with zeros below its \hyperref[def:matrix_diagonal]{main diagonal}. More precisely, \( U = \seq{ u_{i,j} }_{i,j=1}^{m,n} \) is an upper triangular matrix if \( u_{i,j} = 0 \) when \( i > j \).

  Similarly, a \term{lower triangular matrix} is one with zeros above its main diagonal.

  A matrix that is either upper or lower triangular is simply referred to as \enquote{triangular}.
\end{definition}

\begin{proposition}\label{thm:def:triangular_matrix}
  \hyperref[def:triangular_matrix]{Triangular matrices} have the following basic properties:
  \begin{thmenum}
    \thmitem{thm:def:triangular_matrix/diagonal} A matrix that is both upper and lower triangular is a \hyperref[def:matrix_diagonal]{diagonal matrix}.

    \thmitem{thm:def:triangular_matrix/product} The \hyperref[def:matrix_algebra/matrix_multiplication]{product} of upper (resp. lower) triangular matrices is upper (resp. lower).

    Consequently, the product of diagonal matrices is a diagonal matrix.

    \thmitem{thm:def:triangular_matrix/determinant} The \hyperref[thm:def:triangular_matrix/determinant]{determinant} of a triangular matrix is the product of (the entries on) its main diagonal.

    \thmitem{thm:def:triangular_matrix/invertible} A triangular matrix is \hyperref[def:inverse_matrix]{invertible} if and only if its main diagonal has no zero entries.

    Here, the assumption that \( \BbbK \) is a field is essential.
  \end{thmenum}
\end{proposition}
\begin{proof}
  \SubProofOf{thm:def:triangular_matrix/diagonal} Trivial.

  \SubProofOf{thm:def:triangular_matrix/product} Let \( A \) be an \( m \times k \) upper triangular matrix and \( B \) be a \( k \times n \) upper triangular matrix. The \( (i, j) \)-th element of \( C = AB \) is
  \begin{equation*}
    \sum_{l=1}^k a_{i,l} b_{l,j}.
  \end{equation*}

  Since \( A \) and \( B \) are upper triangular, we have \( b_{l,j} = 0 \) whenever \( l > j \) and \( a_{i,l} = 0 \) whenever \( l < i \). Thus, \( a_{i,l} b_{l,j} = 0 \) if either condition holds. If \( i > j \), then either \( l > j \) or \( l < j < i \), implying that \( a_{i,l} b_{l,j} = 0 \). Therefore, \( AB \) is also upper triangular.

  The proof for lower triangular matrices is analogous.

  \SubProofOf{thm:def:triangular_matrix/determinant} Let \( A \) be an \( n \times n \) upper triangular matrix. Let \( \sigma \in S_n \) be any permutation. Then \( a_{i,\sigma(i)} = 0 \) when \( i > \sigma(i) \). Hence, the only permutation for which the product \( \prod_{i=1}^n a_{i,\sigma(i)} \) is nonzero is the identity permutation. Therefore,
  \begin{equation*}
    \det(A) = \prod_{i=1}^n a_{i,i}.
  \end{equation*}

  \SubProofOf{thm:def:triangular_matrix/invertible} Follows from \fullref{thm:def:triangular_matrix/determinant} and \fullref{thm:matrix_invertibility} by noting that \( 0 \) is the only non-invertible element in a field.
\end{proof}

\begin{definition}\label{def:elementary_matrix}
  We introduce the following three types of \hyperref[def:inverse_matrix]{invertible} \( n \times n \) matrices, collectively known as \term{elementary matrices}:
  \begin{thmenum}
    \thmitem{def:elementary_matrix/permutation} For a \hyperref[def:symmetric_group/permutation]{permutation} \( \sigma \in S_n \), the \term{permutation matrix} \( P_\sigma \) is obtained by permuting the columns \( e_1, \ldots, e_n \) of the identity matrix \( I_n \) in accordance with \( \sigma \). The permutation matrix
    \begin{equation*}
      P_\sigma = \parens*
      {
        \begin{array}{c|c|c}
          e_{\sigma(1)} & \cdots & e_{\sigma(n)}
        \end{array}
      }
    \end{equation*}
    acts on the \( n \times m \) matrix \( B = \seq{ b_{i,j} }_{i,j=1}^{m,n} \) by permuting the \hi{rows} of \( B \), i.e.
    \begin{equation*}
      P_\sigma B
      =
      \parens*
      {
        \begin{array}{c|c|c}
          e_{\sigma(1)} & \cdots & e_{\sigma(n)}
        \end{array}
      }
      \cdot
      \begin{pmatrix}
        b_{1,1} & b_{1,2} & \cdots & b_{1,m} \\
        \vdots  & \vdots  & \ddots & \vdots \\
        b_{n,1} & b_{n,2} & \cdots & b_{n,m}
      \end{pmatrix}
      =
      \begin{pmatrix}
        b_{\sigma(1),1} & b_{\sigma(1),2} & \cdots & b_{\sigma(1),m} \\
        \vdots          & \vdots          & \ddots & \vdots \\
        b_{\sigma(n),1} & b_{\sigma(n),2} & \cdots & b_{\sigma(n),m}
      \end{pmatrix}.
    \end{equation*}

    The inverse is the matrix corresponding to its inverse permutation.

    \thmitem{def:elementary_matrix/scaling} For a nonzero element \( a \) and index \( i \), the \( n \times n \) \term{scaling matrix} \( S_{i \mapsto a} \) is a \hyperref[def:matrix_diagonal]{diagonal matrix} that differs from the identity by replacing \( 1 \) with \( a \) instead of \( 1 \) in the \( (i, i) \)-th place. The scaling matrix
    \begin{equation*}
      S_{i \mapsto a}
      \coloneqq
      \begin{blockarray}{cccccccc}
      1      & \cdots & {i-1}   & i      & {i+1}  & \cdots & n      &        \\
      \begin{block}{(ccccccc)c}
      1      & \cdots & 0       & 0      & 0      & \cdots & 0      & 1      \\
      \vdots & \ddots &         & \vdots &        &        & \vdots & \vdots \\
      0      &        & 1       & 0      &        &        & 0      & {i-1}  \\
      0      & \cdots & 0       & a      & 0      & \cdots & 0      & i      \\
      0      &        &         & 0      & 1      &        & 0      & {i+1}  \\
      \vdots &        &         & \vdots &        & \ddots & \vdots & \vdots \\
      0      & \cdots & 0       & 0      & 0      & \cdots & 1      & n      \\
      \end{block}
      \end{blockarray}
    \end{equation*}
    acts on the \( n \times m \) matrix \( B \) by scaling the \( i \)-th row of \( B \) by \( a \).

    The inverse is the same matrix with \( a \) replaced by its multiplicative inverse \( a^{-1} \).

    \thmitem{def:elementary_matrix/transvection} For any element \( a \) and indices \( i \) and \( j \), the \term{transvection matrix} \( T_{i \reloset a \to j} \) is obtained from the identity matrix \( I_n \) by placing \( a \) on the \( (j, i) \)-th place. The transvection matrix
    \begin{equation*}
      T_{i \reloset a \to j}
      \coloneqq
      \begin{blockarray}{cccccccc}
        1      & \cdots & i       &        &        &        & n      &        \\
      \begin{block}{(ccccccc)c}
        1      & \cdots & 0       & \cdots & 0      & \cdots & 0      & 1      \\
        \vdots & \ddots &         &        &        &        & \vdots &        \\
        0      &        & 1       & 0      &        & \cdots & 0      &        \\
        \vdots &        &         & \ddots & 0      &        & \vdots &        \\
        0      & \cdots & a       &        & 1      & \cdots & 0      & j      \\
        \vdots &        & \vdots  &        &        & \ddots & \vdots & \vdots \\
        0      & \cdots & 0       & \cdots & 0      & \cdots & 1      & n      \\
      \end{block}
      \end{blockarray}
    \end{equation*}
    acts on the \( n \times m \) matrix \( B \) by adding the \( i \)-th row of \( B \) scaled by \( a \) to the \( j \)-th row.

    The order of indices is important --- if the \( (j, i) \)-th entry is nonzero, the scaled \( i \)-th row gets added to the \( j \)-th.

    The inverse is the same matrix with \( a \) replaced by its additive inverse \( -a \).
  \end{thmenum}
\end{definition}

\begin{proposition}\label{thm:def:elementary_matrix}
  \hyperref[def:elementary_matrix]{Elementary matrices} have the following basic properties:
  \begin{thmenum}
    \thmitem{thm:def:elementary_matrix/permutation_product} The product of \hyperref[def:elementary_matrix/permutation]{permutation matrices} is a permutation matrix.

    \thmitem{thm:def:elementary_matrix/permutation_determinant} The \hyperref[def:matrix_determinant]{determinant} of a permutation matrix is the \hyperref[def:permutation_parity]{sign} of the \hyperref[def:symmetric_group/permutation]{permutation}.

    \thmitem{thm:def:elementary_matrix/transvection_product_same} The product of the \hyperref[def:elementary_matrix/transvection]{transvection matrices} \( T_{i \reloset \alpha \to j} \) and \( T_{i \reloset \beta \to j} \) is the transvection matrix \( T_{i \reloset {\alpha + \beta} \to j} \).

    \thmitem{thm:def:elementary_matrix/transvection_product} The product of the \hyperref[def:elementary_matrix/transvection]{transvection matrices} \( A = T_{i_A \reloset \alpha \to j_A} \) and \( B = T_{i_B \reloset \beta \to j_B} \) with \( i_A \neq i_B \) or \( j_A \neq j_B \) is the identity matrix \( I_n \) modified with \( \alpha \) in the \( (j_A, i_A) \)-th place and \( \beta \) in the \( (j_B, i_B) \)-th.
  \end{thmenum}
\end{proposition}
\begin{proof}
  \SubProofOf{thm:def:elementary_matrix/permutation_product} Trivial.

  \SubProofOf{thm:def:elementary_matrix/permutation_determinant} As discussed in the proof of \fullref{thm:determinant_on_columns}, the determinant of any permutation of the vectors of the standard basis is the sign of the permutation.

  \SubProofOf{thm:def:elementary_matrix/transvection_product} The \( (i, j) \)-th entry of the product \( C = AB \) is
  \begin{equation*}
    c_{i,j} = \sum_{k=1}^n a_{i,k} b_{k,j}.
  \end{equation*}

  \begin{itemize}
    \item If \( i = j \), \( c_{i,j} \) is clearly \( 1 \).
    \item If \( i = i_A \) and \( j = j_A \), then
    \begin{equation*}
      a_{i_A,k} b_{k,j_A} = \begin{cases}
        a_{i_A,j_A}, &i_A = j_A \\
        0,           &i_A \neq j_A
      \end{cases}.
    \end{equation*}

    Thus, \( c_{i_A,j_A} = a_{i_A,j_A} \).

    \item Analogously, \( c_{i_B,j_B} = b_{i_B,j_B} \).
    \item Otherwise, for \( k = 1, \ldots, n \), either \( a_{i,k} \) or \( b_{k,j} \) is zero, hence \( c_{i,j} \) also is.
  \end{itemize}

  \SubProofOf{thm:def:elementary_matrix/transvection_product_same} This proof only requires a slight modification to the proof of \fullref{thm:def:elementary_matrix/transvection_product}.
\end{proof}

\begin{algorithm}[PLU decomposition]\label{alg:plu_decomposition}
  Fix an \( n \times n \) matrix \( A \). We will build a \hyperref[def:triangular_matrix]{lower triangular matrix} \( L \), \hyperref[def:triangular_matrix]{upper triangular matrix} \( U \) and a \hyperref[def:elementary_matrix/permutation]{permutation matrix} \( P \) such that \( A = PLU \).

  The algorithm itself is also called \term{Gaussian elimination} and \( U \) is said to be a \term{row-echelon form} of \( A \), although both terms may have different meanings depending on the context.

  We will proceed via \hyperref[thm:bounded_transfinite_recursion]{bounded recursion} on \( n \). After the \( k \)-th step, for \( k = 1, \ldots, n - 1 \), we will have built a lower triangular matrix \( L_k \) and a permutation matrix \( P_k \) such that for \( i > k \), \( (i, k) \)-th entry of \( L_k P_k A \) is zero.

  Furthermore, we will obtain \( L_k \) as a product of \hyperref[def:elementary_matrix/transvection]{transvection} and permutation matrices. Therefore, at each step, both \( P_k \) and \( L_k \) will be \hyperref[def:inverse_matrix]{invertible} as products of invertible matrices.

  The matrix \( U \coloneqq L_{n-1} P_{n-1} A \) will be upper triangular, and hence, putting \( P \coloneqq P_{n-1}^{-1} \) and \( L \coloneqq L_{n-1}^{-1} \), we obtain
  \begin{equation*}
    A = PLU.
  \end{equation*}

  \begin{thmenum}
    \thmitem{alg:plu_decomposition/initialization} As an initial condition, put \( L_0 \coloneqq I_n \) and \( P_0 \coloneqq I_n \) as identity matrices.

    \thmitem{alg:plu_decomposition/step} Suppose that we have already built \( L_{k-1} \) and \( P_{k-1} \). Let \( U_{k-1} \coloneqq L_{k-1} P_{k-1} A \). We will describe step \( k \) of the algorithm.

    If the \( (k, j) \)-th entry of \( U_{k-1} \) is zero for all \( j > k \), put \( P_k = P_{k-1} \) and \( L_k = L_{k-1} \).

    Otherwise, let \( j_0 \) be the first row index of \( L_{k-1} P_{k-1} A \) for which the \( k \)-th entry is nonzero. Let \( P_{k \to j_0} \) be the permutation matrix exchanging the \( k \)-th and \( j_0 \)-th column of the identity and put
    \begin{equation*}
      P_k \coloneqq P_{k \to j_0} P_{k-1}.
    \end{equation*}

    Then, since \( P_{k \to j_0} \) is its own inverse,
    \begin{equation*}
      \widehat{U}_{k-1} \coloneqq P_{k \to j_0} U_{k-1} = P_{k \to j_0} L_{k-1} (\smash{ \overbrace{P_{k \to j_0} P_{k \to j_0}}^{I_n} P_{k-1}) A = (P_{k \to j_0} L_{k-1} P_{k \to j_0}) } P_k A.
    \end{equation*}

    Denote by \( u_{i,j} \) the entries of \( \widehat{U}_{k-1} \).

    Also put \( \widehat{L}_{k-1} \coloneqq P_{k \to j_0} L_{k-1} P_{k \to j_0} \). This is again a lower triangular matrix since we only swap columns below the main diagonal.

    For each row \( j > k \), define \( \upsilon_j \coloneqq - \ifrac {(u_{k,j})} {(u_{k,k})} \) consider the transvection matrix \( T_{k \reloset {\upsilon_j} \to j} \). When multiplied by \( \widehat{U}_{k-1} \) from the right, it adds the \( k \)-th row of \( \widehat{U}_{k-1} \) to the \( j \)-th after multiplying it by \( \upsilon_j \). Hence, \( T_{k \reloset {\upsilon_j} \to j} \widehat{U}_{k-1} \) has zero at as its \( (i, j) \)-th entry.

    Finally, put
    \begin{equation*}
      L_k \coloneqq \parens*{ \prod_{j=k}^n T_{k \reloset {\upsilon_j} \to j} } \widehat{L}_{k-1}.
    \end{equation*}

    By \fullref{thm:def:elementary_matrix/transvection_product}, \( L_k \) adds nonzero entries to \( \widehat{L}_{k-1} \) only below the main diagonal. Since \( \widehat{L}_{k-1} \) is lower triangular, so is \( L_k \). Furthermore, for \( j > k \), the coefficient \( \upsilon_j \) is chosen so that the \( (k, j) \)-th entry of \( L_k P_k A \) of zero, which ensures that the latter matrix will be upper triangular when \( k = n - 1 \).
  \end{thmenum}
\end{algorithm}

\begin{proposition}\label{thm:alg:plu_decomposition}
  Let \( A = PLU \) be the decomposition of some matrix \( A \) obtained via \fullref{alg:plu_decomposition}.

  \begin{thmenum}
    \thmitem{thm:alg:plu_decomposition/upper_triangular} If \( A \) is upper triangular, then \( P = L = I_n \) and \( A = U \).

    \thmitem{thm:alg:plu_decomposition/nonsingular} \( A \) is \hyperref[def:inverse_matrix]{nonsingular} if and only if \( U \) is nonsingular.
  \end{thmenum}
\end{proposition}
\begin{proof}
  \SubProofOf{thm:alg:plu_decomposition/upper_triangular} Suppose that \( A \) is upper triangular. Then, at step \( k \) of the algorithm:
  \begin{itemize}
     \item If \( u_{k,k} \) is zero, then all entries below it are also zero, and hence we directly continue to the next step.
     \item If \( u_{k,k} \) is not zero, then the transvection matrices \( T_{k \reloset 0 \to j} \) for \( j > k \) are all identity matrices, and hence \( L_k \) is also the identity.
  \end{itemize}

  In both cases, \( L_k = P_k = I_n \).

  \SubProofOf{thm:alg:plu_decomposition/nonsingular} By \fullref{thm:def:matrix_determinant/homomorphism},
  \begin{equation*}
    \det(A) = \det(P) \det(L) \det(U).
  \end{equation*}

  Since \( P \) and \( L \) are products of permutation and transvection matrices, by \fullref{thm:def:elementary_matrix/permut ation_determinant} and \fullref{thm:def:elementary_matrix/transvection_product}, their determinants are either \( 1 \) or \( -1 \). Hence,
  \begin{equation*}
    \abs{\det(A)} = \abs{\det(U)}.
  \end{equation*}

  It follows from \fullref{thm:def:elementary_matrix/transvection_product} that \( A \) is nonsingular if and only if \( U \) is.
\end{proof}

\begin{algorithm}[Elementary matrix decomposition]\label{alg:elementary_matrix_decomposition}
  Fix a \hyperref[def:inverse_matrix]{nonsingular} \( n \times n \) matrix \( A \). Let \( A = PLU \) be the decomposition obtained via \fullref{alg:plu_decomposition}. By \fullref{thm:alg:plu_decomposition/nonsingular}, \( U \) is a nonsingular matrix. Both \( P \) and \( L \) are products of elementary matrices, hence it suffices to show that \( U \) is a product of elementary matrices in order to show that \( A \) is a product of elementary matrices.

  The algorithm is complementary to \fullref{alg:plu_decomposition}, although with noticeable differences. We will assume that \( k = 2, \ldots, n \). At each step, we will build a matrix \( U_k \) whose first \( k \) columns match those of \( U \). Then \( U_n \) must equal \( U \).

  Denote by \( u_{i,j} \) the entries of \( U \).

  \begin{thmenum}
    \thmitem{alg:elementary_matrix_decomposition/initialization} We will define the initial condition \( U_1 \) to be he diagonal matrix whose main diagonal matches that of \( U \). This can be achieved via \hyperref[def:elementary_matrix/scaling]{scaling matrices}:
    \begin{equation*}
      U_1 \coloneqq \prod_{i=1}^n S_{i \mapsto u_{i,i}}.
    \end{equation*}

    \thmitem{alg:elementary_matrix_decomposition/step} At step \( k \), given \( U_{k-1} \), for \( j < k \) define \( \upsilon_j \coloneqq \ifrac {(u_{k,j})} {(u_{k,k})} \). It is important that here, unlike in \fullref{alg:plu_decomposition}, we put no minus sign in \( \upsilon_j \) since we are building the matrix \( U \) directly rather than building an intermediate matrix that we will later invert. Put
    \begin{equation*}
      U_k \coloneqq \parens*{ \prod_{j=k}^n T_{k \reloset {\upsilon_j} \to j} } U_{k-1}.
    \end{equation*}

    Since \( U \) is nonsingular, by \fullref{thm:def:triangular_matrix/determinant}, \( u_{k,k} \) must be nonzero. Hence, we can divide by it.

    As a product of scaling and \hyperref[def:elementary_matrix/transvection]{transvection matrices} with nonzero entries above the main diagonal, \( U_k \) is an upper diagonal matrix. Furthermore, the scaling matrices neutralize the division done by the transvection matrices, so the \( k \)-th column of \( U_k \) and \( U \) must match.
  \end{thmenum}
\end{algorithm}

\begin{proposition}\label{thm:product_of_elementary_matrices_iff_invertible}
  The square matrix over a field is \hyperref[def:inverse_matrix]{invertible} if and only if it is a product of \hyperref[def:elementary_matrix]{elementary matrices}.
\end{proposition}
\begin{proof}
  \SufficiencySubProof Follows from \fullref{alg:elementary_matrix_decomposition}.
  \NecessitySubProof Follows from \fullref{thm:def:matrix_determinant/homomorphism}.
\end{proof}

\begin{example}\label{ex:vandermonde_matrix}\mcite[corr. 2.37]{Knapp2016BasicAlgebra}
  Given elements \( r_0, r_1, \ldots, r_n \) of some commutative ring, we define their \term{Vandermonde matrix} as
  \begin{equation*}
    \RenewDocumentCommand \arraystretch {} {1.3}
    V_n(r_0, r_1, \ldots, r_n)
    \coloneqq
    \begin{pmatrix}
      r_0^0  & r_0^1  & r_0^2  & \cdots & r_0^n  \\
      r_1^0  & r_1^1  & r_1^2  & \cdots & r_1^n  \\
      \vdots & \vdots & \vdots & \ddots & \vdots \\
      r_n^0  & r_n^1  & r_n^2  & \cdots & r_n^n
    \end{pmatrix}.
  \end{equation*}

  Having in mind that, by \fullref{thm:def:triangular_matrix/determinant}, transvection matrices have determinant \( 1 \), subtracting the \( k \)-th row multiplied by \( r_0 \) from the \( (k + 1) \)-th does not change the determinant. We thus have
  \begin{balign*}
    \det V_n
    =
    \det V_n^T
    &=
    \det
    \begin{pmatrix}
      1         & 1                     & 1                     & \cdots & 1                     \\
      0         & r_1 - r_0             & r_2 - r_0             & \cdots & r_n - r_0             \\
      0         & r_1 (r_1 - r_0)       & r_2 (r_2 - r_0)       & \cdots & r_n (r_n - r_0)       \\
      \vdots    & \vdots                & \vdots                & \ddots & \vdots                \\
      0         & r_1^{k-1} (r_1 - r_0) & r_2^{k-1} (r_2 - r_0) & \cdots & r_n^{k-1} (r_n - r_0) \\
      \vdots    & \vdots                & \vdots                & \ddots & \vdots                \\
      0         & r_1^{n-1} (r_1 - r_0) & r_2^{n-1} (r_2 - r_0) & \cdots & r_n^{n-1} (r_n - r_0) \\
    \end{pmatrix}
    \reloset {\ref{thm:laplace_expansion}} = \\ &=
    \det
    \begin{pmatrix}
      r_1 - r_0             & r_2 - r_0             & \cdots & r_n - r_0             \\
      r_1 (r_1 - r_0)       & r_2 (r_2 - r_0)       & \cdots & r_n (r_n - r_0)       \\
      \vdots                & \vdots                & \ddots & \vdots                \\
      r_1^{k-1} (r_1 - r_0) & r_2^{k-1} (r_2 - r_0) & \cdots & r_n^{k-1} (r_n - r_0) \\
      \vdots                & \vdots                & \ddots & \vdots                \\
      r_1^{n-1} (r_1 - r_0) & r_2^{n-1} (r_2 - r_0) & \cdots & r_n^{n-1} (r_n - r_0) \\
    \end{pmatrix}
    = \\ &=
    (r_1 - r_0) (r_2 - r_0) \cdots (r_n - r_0)
    \det
    \begin{pmatrix}
      1         & 1         & \cdots & 1         \\
      r_1       & r_2       & \cdots & r_n       \\
      \vdots    & \vdots    & \ddots & \vdots    \\
      r_1^{k-1} & r_2^{k-1} & \cdots & r_n^{k-1} \\
      \vdots    & \vdots    & \ddots & \vdots    \\
      r_1^{n-1} & r_2^{n-1} & \cdots & r_n^{n-1}
    \end{pmatrix}.
  \end{balign*}

  Proceeding by induction, we conclude that
  \begin{equation}\label{eq:ex:vandermonde_matrix/determinant}
    \det V_n = \prod_{i < j} (r_j - r_i).
  \end{equation}

  Hence, the determinant is nonzero if and only if all of \( r_0, \ldots, r_n \) are distinct.
\end{example}

\begin{definition}\label{def:column_and_row_spaces}
  The \term{column space} of the \( m \times n \) matrix \( A \) is the \hyperref[def:module/submodel]{linear span} of the columns vectors of \( A \), regarded as a subspace of \( R^n \). It is precisely the image of \( A \) regarded as a linear operator.

  Analogously, the \term{row space} is the span of the row vectors, regarded as a subspace of \( R^m \). It is the image of \( A^T \) regarded as a linear operator.
\end{definition}

\begin{proposition}\label{thm:def:column_and_row_spaces}
  \hyperref[def:column_and_row_spaces]{Column and row spaces} have the following basic properties:
  \begin{thmenum}
    \thmitem{thm:def:column_and_row_spaces/isomorphism} The matrix \( A \) as a linear map from the row space to the column space an isomorphism.
  \end{thmenum}
\end{proposition}
\begin{proof}
  \SubProofOf{thm:def:column_and_row_spaces/isomorphism} We will show that the image of \( A \) and \( A^T \) are isomorphic.

  Let \( x \in \BbbK^m \) and \( y \in \BbbK^n \). Then
  \begin{equation*}
    x^T A y = y^T A^T x.
  \end{equation*}

  If \( y \) is in the kernel of \( A \), then
  \begin{equation*}
    x^T A y = 0 = y^T A^T x
  \end{equation*}

  By \fullref{thm:rank_nullity_theorem},
  \begin{equation*}
    n = \dim \ker A + \dim \img A.
  \end{equation*}
  and
  \begin{equation*}
    m = \dim \ker A^T + \dim \img A^T.
  \end{equation*}
\end{proof}

\begin{definition}\label{def:matrix_rank}
  We define the \term{rank} of an \( m \times n \) matrix \( A \) in the following equivalent ways:
  \begin{thmenum}
    \thmitem{def:matrix_rank/independent_columns} \( \rank(A) \) is the number of \hyperref[def:linear_dependence]{linearly independent} columns of \( A \).
    \thmitem{def:matrix_rank/image_dimension} \( \rank(A) \) is the \hyperref[thm:vector_space_dimension]{dimension} of the image of \( A \) (when regarded as a linear operator; see \fullref{rem:matrices_as_functions}).
    \thmitem{def:matrix_rank/image_dimension} \( \rank(A) \) is the \hyperref[thm:vector_space_dimension]{dimension} of the image of the transpose matrix \( A^T \).
    \thmitem{def:matrix_rank/independent_rows} \( \rank(A) \) is the number of linearly independent rows of \( A \).
  \end{thmenum}
\end{definition}
\begin{defproof}
  \SubProofOf{def:matrix_rank/independent_columns} Suppose that the columns \( v_1, \ldots, v_k \) of \( A \) are linearly independent.

  By \fullref{thm:rank_nullity_theorem},
  \begin{equation*}
    n = \dim \ker A + \dim \img A.
  \end{equation*}

   \( n - k \).

  \SubProofOf{def:matrix_rank/image_dimension}

  Also,
  \begin{equation*}
    m = \dim \ker A^T + \dim \img A^T.
  \end{equation*}

  This is the same as
  \begin{equation*}
    (Ax)^T = x^T A^T = 0.
  \end{equation*}
\end{defproof}

\begin{remark}\label{rem:system_of_linear_equation}
  Given an \( m \times n \) matrix \( A \) and an \( m \)-dimensional column vector \( b \), we consider the \term{system of linear equations}
  \begin{equation}\label{eq:rem:system_of_linear_equation/matrix_form}
    Ax = b.
  \end{equation}

  This is often written in scalar form as
  \begin{equation}\label{eq:rem:system_of_linear_equation/scalar_form}
    \begin{array}{ccccccc}
      a_{1,1} x_1 & +      & \cdots & +      & a_{m,1} x_m & =      & b_1 \\
      \vdots      &        &        & \vdots &             &        & \vdots \\
      a_{1,n} x_1 & +      & \cdots & +      & a_{m,n} x_m & =      & b_m.
    \end{array}
  \end{equation}
\end{remark}


    \documentclass{article}
    \usepackage[utf8]{inputenc}
    \usepackage{amsmath}
    \begin{document}
 %Title
 \section{Collatz Sequence for \(n=112233\) }
    %Collatz Function
    \[
        f(n)=
        \begin{cases}
        \frac{n}{2}, & n \mod 2=0
        \\
        3n+1, &n \mod 2=1
        \end{cases} \\
    \]
    % Path for given N
    \(\textbf{Path for f(112233)}\\[3mm]f(n), n=112233
 \\
 \Rightarrow 3(112233) + 1
 \\
 \Rightarrow n=336700
 \\[3mm]
f(n), n=336700
 \\
 \Rightarrow \frac{336700}{2}
 \\
 \Rightarrow n=168350
 \\[3mm]
f(n), n=168350
 \\
 \Rightarrow \frac{168350}{2}
 \\
 \Rightarrow n=84175
 \\[3mm]
f(n), n=84175
 \\
 \Rightarrow 3(84175) + 1
 \\
 \Rightarrow n=252526
 \\[3mm]
f(n), n=252526
 \\
 \Rightarrow \frac{252526}{2}
 \\
 \Rightarrow n=126263
 \\[3mm]
f(n), n=126263
 \\
 \Rightarrow 3(126263) + 1
 \\
 \Rightarrow n=378790
 \\[3mm]
f(n), n=378790
 \\
 \Rightarrow \frac{378790}{2}
 \\
 \Rightarrow n=189395
 \\[3mm]
f(n), n=189395
 \\
 \Rightarrow 3(189395) + 1
 \\
 \Rightarrow n=568186
 \\[3mm]
f(n), n=568186
 \\
 \Rightarrow \frac{568186}{2}
 \\
 \Rightarrow n=284093
 \\[3mm]
f(n), n=284093
 \\
 \Rightarrow 3(284093) + 1
 \\
 \Rightarrow n=852280
 \\[3mm]
f(n), n=852280
 \\
 \Rightarrow \frac{852280}{2}
 \\
 \Rightarrow n=426140
 \\[3mm]
f(n), n=426140
 \\
 \Rightarrow \frac{426140}{2}
 \\
 \Rightarrow n=213070
 \\[3mm]
f(n), n=213070
 \\
 \Rightarrow \frac{213070}{2}
 \\
 \Rightarrow n=106535
 \\[3mm]
f(n), n=106535
 \\
 \Rightarrow 3(106535) + 1
 \\
 \Rightarrow n=319606
 \\[3mm]
f(n), n=319606
 \\
 \Rightarrow \frac{319606}{2}
 \\
 \Rightarrow n=159803
 \\[3mm]
f(n), n=159803
 \\
 \Rightarrow 3(159803) + 1
 \\
 \Rightarrow n=479410
 \\[3mm]
f(n), n=479410
 \\
 \Rightarrow \frac{479410}{2}
 \\
 \Rightarrow n=239705
 \\[3mm]
f(n), n=239705
 \\
 \Rightarrow 3(239705) + 1
 \\
 \Rightarrow n=719116
 \\[3mm]
f(n), n=719116
 \\
 \Rightarrow \frac{719116}{2}
 \\
 \Rightarrow n=359558
 \\[3mm]
f(n), n=359558
 \\
 \Rightarrow \frac{359558}{2}
 \\
 \Rightarrow n=179779
 \\[3mm]
f(n), n=179779
 \\
 \Rightarrow 3(179779) + 1
 \\
 \Rightarrow n=539338
 \\[3mm]
f(n), n=539338
 \\
 \Rightarrow \frac{539338}{2}
 \\
 \Rightarrow n=269669
 \\[3mm]
f(n), n=269669
 \\
 \Rightarrow 3(269669) + 1
 \\
 \Rightarrow n=809008
 \\[3mm]
f(n), n=809008
 \\
 \Rightarrow \frac{809008}{2}
 \\
 \Rightarrow n=404504
 \\[3mm]
f(n), n=404504
 \\
 \Rightarrow \frac{404504}{2}
 \\
 \Rightarrow n=202252
 \\[3mm]
f(n), n=202252
 \\
 \Rightarrow \frac{202252}{2}
 \\
 \Rightarrow n=101126
 \\[3mm]
f(n), n=101126
 \\
 \Rightarrow \frac{101126}{2}
 \\
 \Rightarrow n=50563
 \\[3mm]
f(n), n=50563
 \\
 \Rightarrow 3(50563) + 1
 \\
 \Rightarrow n=151690
 \\[3mm]
f(n), n=151690
 \\
 \Rightarrow \frac{151690}{2}
 \\
 \Rightarrow n=75845
 \\[3mm]
f(n), n=75845
 \\
 \Rightarrow 3(75845) + 1
 \\
 \Rightarrow n=227536
 \\[3mm]
f(n), n=227536
 \\
 \Rightarrow \frac{227536}{2}
 \\
 \Rightarrow n=113768
 \\[3mm]
f(n), n=113768
 \\
 \Rightarrow \frac{113768}{2}
 \\
 \Rightarrow n=56884
 \\[3mm]
f(n), n=56884
 \\
 \Rightarrow \frac{56884}{2}
 \\
 \Rightarrow n=28442
 \\[3mm]
f(n), n=28442
 \\
 \Rightarrow \frac{28442}{2}
 \\
 \Rightarrow n=14221
 \\[3mm]
f(n), n=14221
 \\
 \Rightarrow 3(14221) + 1
 \\
 \Rightarrow n=42664
 \\[3mm]
f(n), n=42664
 \\
 \Rightarrow \frac{42664}{2}
 \\
 \Rightarrow n=21332
 \\[3mm]
f(n), n=21332
 \\
 \Rightarrow \frac{21332}{2}
 \\
 \Rightarrow n=10666
 \\[3mm]
f(n), n=10666
 \\
 \Rightarrow \frac{10666}{2}
 \\
 \Rightarrow n=5333
 \\[3mm]
f(n), n=5333
 \\
 \Rightarrow 3(5333) + 1
 \\
 \Rightarrow n=16000
 \\[3mm]
f(n), n=16000
 \\
 \Rightarrow \frac{16000}{2}
 \\
 \Rightarrow n=8000
 \\[3mm]
f(n), n=8000
 \\
 \Rightarrow \frac{8000}{2}
 \\
 \Rightarrow n=4000
 \\[3mm]
f(n), n=4000
 \\
 \Rightarrow \frac{4000}{2}
 \\
 \Rightarrow n=2000
 \\[3mm]
f(n), n=2000
 \\
 \Rightarrow \frac{2000}{2}
 \\
 \Rightarrow n=1000
 \\[3mm]
f(n), n=1000
 \\
 \Rightarrow \frac{1000}{2}
 \\
 \Rightarrow n=500
 \\[3mm]
f(n), n=500
 \\
 \Rightarrow \frac{500}{2}
 \\
 \Rightarrow n=250
 \\[3mm]
f(n), n=250
 \\
 \Rightarrow \frac{250}{2}
 \\
 \Rightarrow n=125
 \\[3mm]
f(n), n=125
 \\
 \Rightarrow 3(125) + 1
 \\
 \Rightarrow n=376
 \\[3mm]
f(n), n=376
 \\
 \Rightarrow \frac{376}{2}
 \\
 \Rightarrow n=188
 \\[3mm]
f(n), n=188
 \\
 \Rightarrow \frac{188}{2}
 \\
 \Rightarrow n=94
 \\[3mm]
f(n), n=94
 \\
 \Rightarrow \frac{94}{2}
 \\
 \Rightarrow n=47
 \\[3mm]
f(n), n=47
 \\
 \Rightarrow 3(47) + 1
 \\
 \Rightarrow n=142
 \\[3mm]
f(n), n=142
 \\
 \Rightarrow \frac{142}{2}
 \\
 \Rightarrow n=71
 \\[3mm]
f(n), n=71
 \\
 \Rightarrow 3(71) + 1
 \\
 \Rightarrow n=214
 \\[3mm]
f(n), n=214
 \\
 \Rightarrow \frac{214}{2}
 \\
 \Rightarrow n=107
 \\[3mm]
f(n), n=107
 \\
 \Rightarrow 3(107) + 1
 \\
 \Rightarrow n=322
 \\[3mm]
f(n), n=322
 \\
 \Rightarrow \frac{322}{2}
 \\
 \Rightarrow n=161
 \\[3mm]
f(n), n=161
 \\
 \Rightarrow 3(161) + 1
 \\
 \Rightarrow n=484
 \\[3mm]
f(n), n=484
 \\
 \Rightarrow \frac{484}{2}
 \\
 \Rightarrow n=242
 \\[3mm]
f(n), n=242
 \\
 \Rightarrow \frac{242}{2}
 \\
 \Rightarrow n=121
 \\[3mm]
f(n), n=121
 \\
 \Rightarrow 3(121) + 1
 \\
 \Rightarrow n=364
 \\[3mm]
f(n), n=364
 \\
 \Rightarrow \frac{364}{2}
 \\
 \Rightarrow n=182
 \\[3mm]
f(n), n=182
 \\
 \Rightarrow \frac{182}{2}
 \\
 \Rightarrow n=91
 \\[3mm]
f(n), n=91
 \\
 \Rightarrow 3(91) + 1
 \\
 \Rightarrow n=274
 \\[3mm]
f(n), n=274
 \\
 \Rightarrow \frac{274}{2}
 \\
 \Rightarrow n=137
 \\[3mm]
f(n), n=137
 \\
 \Rightarrow 3(137) + 1
 \\
 \Rightarrow n=412
 \\[3mm]
f(n), n=412
 \\
 \Rightarrow \frac{412}{2}
 \\
 \Rightarrow n=206
 \\[3mm]
f(n), n=206
 \\
 \Rightarrow \frac{206}{2}
 \\
 \Rightarrow n=103
 \\[3mm]
f(n), n=103
 \\
 \Rightarrow 3(103) + 1
 \\
 \Rightarrow n=310
 \\[3mm]
f(n), n=310
 \\
 \Rightarrow \frac{310}{2}
 \\
 \Rightarrow n=155
 \\[3mm]
f(n), n=155
 \\
 \Rightarrow 3(155) + 1
 \\
 \Rightarrow n=466
 \\[3mm]
f(n), n=466
 \\
 \Rightarrow \frac{466}{2}
 \\
 \Rightarrow n=233
 \\[3mm]
f(n), n=233
 \\
 \Rightarrow 3(233) + 1
 \\
 \Rightarrow n=700
 \\[3mm]
f(n), n=700
 \\
 \Rightarrow \frac{700}{2}
 \\
 \Rightarrow n=350
 \\[3mm]
f(n), n=350
 \\
 \Rightarrow \frac{350}{2}
 \\
 \Rightarrow n=175
 \\[3mm]
f(n), n=175
 \\
 \Rightarrow 3(175) + 1
 \\
 \Rightarrow n=526
 \\[3mm]
f(n), n=526
 \\
 \Rightarrow \frac{526}{2}
 \\
 \Rightarrow n=263
 \\[3mm]
f(n), n=263
 \\
 \Rightarrow 3(263) + 1
 \\
 \Rightarrow n=790
 \\[3mm]
f(n), n=790
 \\
 \Rightarrow \frac{790}{2}
 \\
 \Rightarrow n=395
 \\[3mm]
f(n), n=395
 \\
 \Rightarrow 3(395) + 1
 \\
 \Rightarrow n=1186
 \\[3mm]
f(n), n=1186
 \\
 \Rightarrow \frac{1186}{2}
 \\
 \Rightarrow n=593
 \\[3mm]
f(n), n=593
 \\
 \Rightarrow 3(593) + 1
 \\
 \Rightarrow n=1780
 \\[3mm]
f(n), n=1780
 \\
 \Rightarrow \frac{1780}{2}
 \\
 \Rightarrow n=890
 \\[3mm]
f(n), n=890
 \\
 \Rightarrow \frac{890}{2}
 \\
 \Rightarrow n=445
 \\[3mm]
f(n), n=445
 \\
 \Rightarrow 3(445) + 1
 \\
 \Rightarrow n=1336
 \\[3mm]
f(n), n=1336
 \\
 \Rightarrow \frac{1336}{2}
 \\
 \Rightarrow n=668
 \\[3mm]
f(n), n=668
 \\
 \Rightarrow \frac{668}{2}
 \\
 \Rightarrow n=334
 \\[3mm]
f(n), n=334
 \\
 \Rightarrow \frac{334}{2}
 \\
 \Rightarrow n=167
 \\[3mm]
f(n), n=167
 \\
 \Rightarrow 3(167) + 1
 \\
 \Rightarrow n=502
 \\[3mm]
f(n), n=502
 \\
 \Rightarrow \frac{502}{2}
 \\
 \Rightarrow n=251
 \\[3mm]
f(n), n=251
 \\
 \Rightarrow 3(251) + 1
 \\
 \Rightarrow n=754
 \\[3mm]
f(n), n=754
 \\
 \Rightarrow \frac{754}{2}
 \\
 \Rightarrow n=377
 \\[3mm]
f(n), n=377
 \\
 \Rightarrow 3(377) + 1
 \\
 \Rightarrow n=1132
 \\[3mm]
f(n), n=1132
 \\
 \Rightarrow \frac{1132}{2}
 \\
 \Rightarrow n=566
 \\[3mm]
f(n), n=566
 \\
 \Rightarrow \frac{566}{2}
 \\
 \Rightarrow n=283
 \\[3mm]
f(n), n=283
 \\
 \Rightarrow 3(283) + 1
 \\
 \Rightarrow n=850
 \\[3mm]
f(n), n=850
 \\
 \Rightarrow \frac{850}{2}
 \\
 \Rightarrow n=425
 \\[3mm]
f(n), n=425
 \\
 \Rightarrow 3(425) + 1
 \\
 \Rightarrow n=1276
 \\[3mm]
f(n), n=1276
 \\
 \Rightarrow \frac{1276}{2}
 \\
 \Rightarrow n=638
 \\[3mm]
f(n), n=638
 \\
 \Rightarrow \frac{638}{2}
 \\
 \Rightarrow n=319
 \\[3mm]
f(n), n=319
 \\
 \Rightarrow 3(319) + 1
 \\
 \Rightarrow n=958
 \\[3mm]
f(n), n=958
 \\
 \Rightarrow \frac{958}{2}
 \\
 \Rightarrow n=479
 \\[3mm]
f(n), n=479
 \\
 \Rightarrow 3(479) + 1
 \\
 \Rightarrow n=1438
 \\[3mm]
f(n), n=1438
 \\
 \Rightarrow \frac{1438}{2}
 \\
 \Rightarrow n=719
 \\[3mm]
f(n), n=719
 \\
 \Rightarrow 3(719) + 1
 \\
 \Rightarrow n=2158
 \\[3mm]
f(n), n=2158
 \\
 \Rightarrow \frac{2158}{2}
 \\
 \Rightarrow n=1079
 \\[3mm]
f(n), n=1079
 \\
 \Rightarrow 3(1079) + 1
 \\
 \Rightarrow n=3238
 \\[3mm]
f(n), n=3238
 \\
 \Rightarrow \frac{3238}{2}
 \\
 \Rightarrow n=1619
 \\[3mm]
f(n), n=1619
 \\
 \Rightarrow 3(1619) + 1
 \\
 \Rightarrow n=4858
 \\[3mm]
f(n), n=4858
 \\
 \Rightarrow \frac{4858}{2}
 \\
 \Rightarrow n=2429
 \\[3mm]
f(n), n=2429
 \\
 \Rightarrow 3(2429) + 1
 \\
 \Rightarrow n=7288
 \\[3mm]
f(n), n=7288
 \\
 \Rightarrow \frac{7288}{2}
 \\
 \Rightarrow n=3644
 \\[3mm]
f(n), n=3644
 \\
 \Rightarrow \frac{3644}{2}
 \\
 \Rightarrow n=1822
 \\[3mm]
f(n), n=1822
 \\
 \Rightarrow \frac{1822}{2}
 \\
 \Rightarrow n=911
 \\[3mm]
f(n), n=911
 \\
 \Rightarrow 3(911) + 1
 \\
 \Rightarrow n=2734
 \\[3mm]
f(n), n=2734
 \\
 \Rightarrow \frac{2734}{2}
 \\
 \Rightarrow n=1367
 \\[3mm]
f(n), n=1367
 \\
 \Rightarrow 3(1367) + 1
 \\
 \Rightarrow n=4102
 \\[3mm]
f(n), n=4102
 \\
 \Rightarrow \frac{4102}{2}
 \\
 \Rightarrow n=2051
 \\[3mm]
f(n), n=2051
 \\
 \Rightarrow 3(2051) + 1
 \\
 \Rightarrow n=6154
 \\[3mm]
f(n), n=6154
 \\
 \Rightarrow \frac{6154}{2}
 \\
 \Rightarrow n=3077
 \\[3mm]
f(n), n=3077
 \\
 \Rightarrow 3(3077) + 1
 \\
 \Rightarrow n=9232
 \\[3mm]
f(n), n=9232
 \\
 \Rightarrow \frac{9232}{2}
 \\
 \Rightarrow n=4616
 \\[3mm]
f(n), n=4616
 \\
 \Rightarrow \frac{4616}{2}
 \\
 \Rightarrow n=2308
 \\[3mm]
f(n), n=2308
 \\
 \Rightarrow \frac{2308}{2}
 \\
 \Rightarrow n=1154
 \\[3mm]
f(n), n=1154
 \\
 \Rightarrow \frac{1154}{2}
 \\
 \Rightarrow n=577
 \\[3mm]
f(n), n=577
 \\
 \Rightarrow 3(577) + 1
 \\
 \Rightarrow n=1732
 \\[3mm]
f(n), n=1732
 \\
 \Rightarrow \frac{1732}{2}
 \\
 \Rightarrow n=866
 \\[3mm]
f(n), n=866
 \\
 \Rightarrow \frac{866}{2}
 \\
 \Rightarrow n=433
 \\[3mm]
f(n), n=433
 \\
 \Rightarrow 3(433) + 1
 \\
 \Rightarrow n=1300
 \\[3mm]
f(n), n=1300
 \\
 \Rightarrow \frac{1300}{2}
 \\
 \Rightarrow n=650
 \\[3mm]
f(n), n=650
 \\
 \Rightarrow \frac{650}{2}
 \\
 \Rightarrow n=325
 \\[3mm]
f(n), n=325
 \\
 \Rightarrow 3(325) + 1
 \\
 \Rightarrow n=976
 \\[3mm]
f(n), n=976
 \\
 \Rightarrow \frac{976}{2}
 \\
 \Rightarrow n=488
 \\[3mm]
f(n), n=488
 \\
 \Rightarrow \frac{488}{2}
 \\
 \Rightarrow n=244
 \\[3mm]
f(n), n=244
 \\
 \Rightarrow \frac{244}{2}
 \\
 \Rightarrow n=122
 \\[3mm]
f(n), n=122
 \\
 \Rightarrow \frac{122}{2}
 \\
 \Rightarrow n=61
 \\[3mm]
f(n), n=61
 \\
 \Rightarrow 3(61) + 1
 \\
 \Rightarrow n=184
 \\[3mm]
f(n), n=184
 \\
 \Rightarrow \frac{184}{2}
 \\
 \Rightarrow n=92
 \\[3mm]
f(n), n=92
 \\
 \Rightarrow \frac{92}{2}
 \\
 \Rightarrow n=46
 \\[3mm]
f(n), n=46
 \\
 \Rightarrow \frac{46}{2}
 \\
 \Rightarrow n=23
 \\[3mm]
f(n), n=23
 \\
 \Rightarrow 3(23) + 1
 \\
 \Rightarrow n=70
 \\[3mm]
f(n), n=70
 \\
 \Rightarrow \frac{70}{2}
 \\
 \Rightarrow n=35
 \\[3mm]
f(n), n=35
 \\
 \Rightarrow 3(35) + 1
 \\
 \Rightarrow n=106
 \\[3mm]
f(n), n=106
 \\
 \Rightarrow \frac{106}{2}
 \\
 \Rightarrow n=53
 \\[3mm]
f(n), n=53
 \\
 \Rightarrow 3(53) + 1
 \\
 \Rightarrow n=160
 \\[3mm]
f(n), n=160
 \\
 \Rightarrow \frac{160}{2}
 \\
 \Rightarrow n=80
 \\[3mm]
f(n), n=80
 \\
 \Rightarrow \frac{80}{2}
 \\
 \Rightarrow n=40
 \\[3mm]
f(n), n=40
 \\
 \Rightarrow \frac{40}{2}
 \\
 \Rightarrow n=20
 \\[3mm]
f(n), n=20
 \\
 \Rightarrow \frac{20}{2}
 \\
 \Rightarrow n=10
 \\[3mm]
f(n), n=10
 \\
 \Rightarrow \frac{10}{2}
 \\
 \Rightarrow n=5
 \\[3mm]
f(n), n=5
 \\
 \Rightarrow 3(5) + 1
 \\
 \Rightarrow n=16
 \\[3mm]
f(n), n=16
 \\
 \Rightarrow \frac{16}{2}
 \\
 \Rightarrow n=8
 \\[3mm]
f(n), n=8
 \\
 \Rightarrow \frac{8}{2}
 \\
 \Rightarrow n=4
 \\[3mm]
f(n), n=4
 \\
 \Rightarrow \frac{4}{2}
 \\
 \Rightarrow n=2
 \\[3mm]
f(n), n=2
 \\
 \Rightarrow \frac{2}{2}
 \\
 \Rightarrow n=1
 \\[3mm]

    \section{Credits}
    %Maybe add link to gitrepo and other shit, idk
    This is created using Collatzer (https://github.com/Z1aaan/Collatzer).
    Created By: Z1aaan

    README:
    A program created to visualize and simulate a user-given value for \textit{N}
    and see what happens when it is put under the Collatz function.
    \end{document}


\documentclass[12pt]{article}
\usepackage{amsmath, mathtools}

\begin{document}

\begin{center}
{\Large Sample swap}

\medskip
Jonathan Bloom \texttt{jbloom@broadinstitute.org}\\
and \\
Yossi Farjoun \texttt{farjoun@broadinstitute.org} \\

June 20, 2014
\end{center}

Let $\theta$ and $\varphi$ denote the diploid haplotypes (that is AA, AB or BB) of samples from which sequencing data sets $x$ and $y$, respectively, have been generated.
Let $s$ be a Bernoulli random variable with $s=1$ if these samples are from distinct individuals.
We call the event $s=1$ a {\em swap}, and in this note we compute its posterior probability $p(s = 1 \, | \, x, y)$.
In the context of sample validation, $x$ is sequencing data from a sample of interest and $y$ is micro-array or sequencing data from a sample intended to be from the same individual.
If $p(s = 1 \, | \, x, y)$ is non-trivial, then one should flag the suspect data and investigate.

By Bayes' Rule, the posterior probability of a swap is given by
\begin{align}
\label{prob_swap}
p(s = 1 \, | \, x,y) = \frac{p(x,y \, | \, s = 1) \, p(s=1)}{p(x,y \, | \, s = 1) \, p(s = 1) + p(x,y \, | \, s = 0) \, p(s =0)}
\end{align}
Equivalently, the posterior odds of a swap is the product of the Bayes factor (likelihood ratio) and prior odds:
\begin{align}
\label{odds_swap}
\frac{p(s = 1 \, | \, x,y)}{p(s = 0 \, | \, x,y)} = \frac{p(x,y \, | \, s = 1) \, p(s = 1)}{p(x,y \, | \, s = 0) \, p(s = 0)}
\end{align}
In particular, if a sample swap rarely occurs then the posterior log odds of a swap is well-approximated by
\[
\log(L_1) - \log(L_0) + \log(S)
\]
where $L_i = p(x,y \, | \, s=i)$ and $S$ is the prior probability of a swap.

To compute these, the following functions must be empirically estimated:
\begin{itemize}
\item the prior $p(s)$, or equivalently the prior probability of a swap.
\item the haplotype distribution $p(\theta)$ in the source population.
\item the likelihood function $p(x \, | \, \theta)$ up to a scaling factor $c(x)$.
\item the likelihood function $p(y \, | \, \varphi)$ up to a scaling factor $c(y)$.
\end{itemize}
Then by \eqref{prob_swap}, it suffices to express $p(x,y \, | \, s)$ in terms of $p(\theta)$, $p(x \, | \, \theta)$, and $p( y \, | \, \varphi)$.  To do this, we assume that distinct individuals are independently drawn from the population and that samples from the same individual have the same haplotype:
\begin{equation}
\label{theta_phi_cond_indep}
p(\theta, \varphi \, | \, s) =
  \begin{cases}
   p(\theta) \, p(\varphi) & \text{if } s = 1, \\
   p(\theta) & \text{if } \theta = \varphi, \\
   0 & \text{otherwise.}
  \end{cases}
\end{equation}
Next we have
\begin{align}
p(x,y \, | \, \theta, \varphi)
&= \frac{p(x,y \, | \, \theta, \varphi)}{p(y \, | \, \theta, \varphi)} p(y \, | \, \theta, \varphi) \notag \\
\label{def_cond_prob}
&= p(x \, | \, \theta, \varphi, y) \, p(y \, |  \, \theta, \varphi) \\
\label{xy_cond_indep}
&= p(x \, | \, \theta) \, p(y \, | \, \varphi).
\end{align}
where \eqref{def_cond_prob} applies the definition of conditional probability and \eqref{xy_cond_indep} uses that $x$ is conditionally independent of $\varphi$ and $y$ given $\theta$, and $y$ is conditionally independent of $\theta$ given $\varphi$. Therefore
\begin{align}
\label{total_prob}
p(x,y \, | \, s)
&=  \textstyle\sum\limits_{\theta,\varphi} p(x, y \, | \, \theta, \varphi, s) \, p(\theta, \varphi \, | \, s) \\
\label{xy_cond_indep_s}
&= \textstyle\sum\limits_{\theta, \varphi} p(x, y \, | \, \theta, \varphi) \, p(\theta, \varphi \, | \, s) \\
\label{apply_xy_cond_indep}
&= \textstyle\sum\limits_{\theta, \varphi} p(x \, | \, \theta) \, p(y \, | \, \varphi) \, p(\theta, \varphi \, | \, s) \\
\label{apply_theta_phi_cond_indep}
&=
  \begin{dcases}
   \textstyle\sum\limits_{\theta} p(x \, | \, \theta) \, p(\theta) \, \textstyle\sum\limits_{\varphi} p(y \, | \, \varphi) \, p(\varphi) & \text{if } s = 1, \\
   \textstyle\sum\limits_{\theta = \varphi}  \, p(x\,|\,\theta)  \, p(y \, | \, \varphi) \, p(\theta) & \text{if } s = 0. \\
  \end{dcases}
\end{align}
Here \eqref{total_prob} is the law of total probability, \eqref{xy_cond_indep_s} uses that $x$ and $y$ are conditionally independent of $s$ given $\theta$ and $\varphi$, \eqref{apply_xy_cond_indep} applies \eqref{xy_cond_indep}, and \eqref{apply_theta_phi_cond_indep} applies \eqref{theta_phi_cond_indep}.  Substituting \eqref{apply_theta_phi_cond_indep} into \eqref{odds_swap}, we conclude that the posterior odds of a swap is:
\begin{equation}
\label{odds}
\boxed{\frac{\sum_\theta p(x \, | \, \theta) \, p(\theta) \, \sum_{\varphi} p(y \, | \, \varphi) \, p(\varphi)}{\sum_{\theta = \varphi} p(x \, | \, \theta) \, p(y \, | \, \varphi) \, p(\theta)} \cdot \frac{p(s=1)}{p(s=0)}}
\end{equation}

Computing \eqref{odds_swap} is easiest when $\theta$, $\varphi$, $x$, and $y$ are understood as tuples indexed by loci such that:
\begin{itemize}
\item The haplotypes at distinct loci are independent, i.e. $p(\theta) = \prod_i p(\theta_i)$.
\item $x_i$ and $\theta_j$ are independent for $i \neq j$, i.e. $p(x_i \, | \, \theta) = p(x_i \, | \, \theta_i)$.
\item $y_i$ and $\varphi_j$ are independent for $i \neq j$, i.e. $p(y_i \, | \, \varphi) = p(y_i \, | \, \varphi_i)$.
\end{itemize}
In this case, by a generalization of the argument in \eqref{xy_cond_indep} we have
\begin{align*}
p(x \, | \, \theta) &= \textstyle\prod\limits_i p(x_i \, | \, \theta_i) \\
p(y \, | \, \varphi) &= \textstyle\prod\limits_i p(y_i \, | \, \varphi_i).
\end{align*}
Substituting these expressions into \eqref{odds} and re-distributing yields
\begin{equation}
\boxed{\prod_i \left(\frac{\sum_{\theta_i} p(x_i \, | \, \theta_i) \, p(\theta_i) \, \sum_{\varphi_i} p(y_i \, | \, \varphi_i) \, p(\varphi_i)}{\sum_{\theta_i = \varphi_i} p(x_i \, | \, \theta_i) \, p(y_i \, | \, \varphi_i) \, p(\theta_i)}\right) \cdot \frac{p(s=1)}{p(s=0)}}
\label{odds_many}
\end{equation}

\section{Haplotype Likelihoods}
In this section we describe how the haplotype likelihood $p(x|\theta)$ can be computed for various kinds of data.
\subsection{Sequence data}
For sequence data, we assume that the data come from a single individual (i.e. not contaminated, see subsection below) and that there is no reference bias (can correct for that, but it's rarely needed).
Sequence data arrives in the form of reads.
We assume that evidence for haplotype $h_i\in\{A,B\}$ with probability of error $e_i\in(0,1)$ are given at a certain haplotype block.
We further assume that said evidence is independent, for example, reads have been duplicate marked, and close SNPs from the same read-pair are not used twice.
Then we can write:
\begin{equation}
p(h,e|\theta)=\prod_{i=0}^n p(h_i,e_i|\theta)
\end{equation}
The likelihood of a single datum $p(h_i,e_i|\theta)$ is expressed by
\begin{equation}
p(h_i,e_i|\theta)=\begin{cases}
I_B(h_i)e_i + I_A(h_i)(1-e_i) & \theta=AA\\
0.5 & \theta=AB\\
I_A(h_i)e_i + I_B(h_i)(1-e_i) &  \theta=BB
\end{cases}
\end{equation}
Where $I_x$ is the indicator function of $x$ and the assumption is that an error will cause a switch in the interpretation of the haplotype between $A$ and $B$.
This assumes that we throw away non-conformant haplotypes, and ignores the possibility of a non-conformant haplotype erroneously looking conformant.
(By conformant we mean either $A$ or $B$.)

This LOD calculation is implemented in Picard's CheckFingerprints and CrosscheckFingerprints.

\subsection{Contaminated Samples}
At times, one knows that data from a particular sample is contaminated at a known level (that level can be estimated using VarifyBamID, or ContEst, for example).
However, the identity of the contaminator is unknown.
In this section we describe how the diploid Haplotype likelihood of the contaminator can be (sometimes) extracted from the data.
For the calculation we will need the prior on the haplotypes, $p(\theta)$, which can be calculated from the haplotype frequency by assuming Hardy-Weinberg equilibrium.

We assume that the underlying samples have (unknown) haplotypes $\theta$ and $\phi$, mixed with proportion $1-c$ and $c$, respectively.
The data collected from this mixture, is $x$.
Then we can write:
\begin{equation}
p(x|c,\theta)=\sum_\phi p(x|c,\theta,\phi)p(\phi)
\end{equation}

This enables us to discover (and thus extract) $p(x|c,\theta)$ which can then be used in \eqref{odds_many}.

Picard's ExtractContaminantFingerprint implements this and writes a new VCF with the likelihoods of the contaminant.
This VCF can then be further used to compare the contaminant (or the contaminated sample) to another sample.

\subsection{LoH samples}
When a sample comes from a tumor there is the possibility that it has undergone a loss of heterozygosity (LoH) where large sections of chromosomes are lost (whole arms, and sometimes one copy of a whole chromosome can be lost).
This makes all the heterozygous haplotypes (from the germline) in that region of the chromosome seem homozygous since the only evidence comes from the remaining copy.
In this case, the standard calculation of $p(x|\theta)$ will yield an incorrect likelihood for the genotypes of the normal sample. Furthermore, since the LoH event is correlated among the different sites, our assumption of independence is incorrect.
We need to be able to infer the genotype posterior of the normal sample given the data from the tumor, $p(G_n|D_t)$,  so that we can compare genotypes of the individual.

We assume that a heterozygous site can become homozygous at a probability $p_{loh}$. Thus we can write a transition probability:
\begin{equation}
T= \begin{pmatrix}
1 & 0 & 0 \\
p_{loh}/2 & 1-p_{loh} & p_{loh}/2\\
0 & 0 & 1
\end{pmatrix}
\end{equation}
and now
\begin{equation}
p(g_t=j|g_n=i) = T^i_j
\end{equation}
where $g_t$ is the tumor's genotype and $g_n$ is the normal's genotype.

We are looking for $p(G_n|D_t)$ and so we observe:
\begin{align*}
p(D_t|g_n)&=\sum_{g_t}p(D_t,g_t|g_n)\\
&=\sum_{g_t}p(D_t|g_n,g_t)p(g_t|g_n)\\
&=\sum_{g_t}p(D_t|g_t) T^{g_t}_{g_n}\\
\end{align*}
Which gives us the likelihood of the tumor's data in the context of the normal's genotype.

Thus, in \eqref{odds} above, if $x'$ is data from the tumor with genotype $\theta'$ and whose normal has genotype $\theta$, we get that the posterior odds of a swap is:
\begin{equation}
\boxed{\frac{\sum_\theta \sum_{\theta'} p(x' \, | \, \theta')T_{\theta}^{\theta'} \, p(\theta) \, \sum_{\varphi} p(y \, | \, \varphi) \, p(\varphi)}{\sum_{\theta = \varphi}  \sum_{\theta'} p(x' \, | \, \theta')T_{\theta}^{\theta'} \, p(y \, | \, \varphi) \, p(\theta)} \cdot \frac{p(s=1)}{p(s=0)}}
\end{equation}

This is implemented in CrosscheckFingerprints and emitted in the TUMOR\_NORMAL\_LOD and NORMAL\_TUMOR\_LOD columns in the fingerprinting report.

\end{document}