\documentclass{article}

\usepackage{epsfig}
\usepackage[export]{adjustbox}% http://ctan.org/pkg/adjustbox
\usepackage{caption}
\usepackage{subcaption}
\usepackage{fullpage}
\usepackage{commath}
\usepackage{amssymb}
\usepackage[space]{grffile}
\usepackage{float}
\usepackage{float}

\def\E{\mathbb{E}}
\def\R{\mathbb{R}}
\def\bin{\text{bin}}
\def\bet{\text{beta}}
\def\Bin{\text{Binom}}
\def\diag{\text{diag}}

\title{Single Sequence HMM in DNA Methylation Problem}
\author{Chicheng Zhang}

\begin{document}
\maketitle

\section{The Model}

In the problem of DNA methylation, we are given a sequence $\cbr{x_t = (c_t, \mu_t)}_{t=1}^l$, where at each time $t$, the coverage is an nonnegative integer $c_t \in \cbr{0,1,\ldots,N}$ and the methylation count is $\mu_t \in \cbr{0,1,\ldots,c_t}$. We model the data using a hidden Markov model, that is, the underlying dynamics of the hidden states is driven by a Markov chain $\cbr{h_t}$, where $h_t \in [m]$. We leave the consideration of context information to the next stage.

The HMM can be summarized by parameters $(\pi, T, O)$, where $\pi \in \R^m$ is the initial probability distribution $\Pr(h_1)$ and $T \in \R^{m \times m}$ is the transition matrix of the Markov chain $\Pr(h_{t+1} | h_t)$, $O$ is the observation matrix, namely the conditional probability of methylation and coverage, given hidden state $\Pr(c_t, \mu_t | h_t)$. To avoid notation clutter, we drop the time indices $t$ if they are the same among all the variables appeared in a formula.

We assume the $\mu_t$ given $c_t$ and $h_t$ is drawn from a binomial distribution, and for each hidden state $h \in [m]$ there is a methylation probability $p_h \in [0,1]$ associated with it. Formally,
\[ \mu_t | c_t, h_t \sim \Bin(c_t, p_{h_t}) \]

\section{Algorithm based on Method of Moments}

Given an observation $(c, \mu)$, we map it to a $n$-dimensional vector using feature mapping $\phi$. Generally speaking, different feature mappings have different properties.

For mapping $\phi$, we define the corresponding observation matrices as follows:
\[ O_{\phi}^s := \E[\phi(c_s,\mu_s) | h_2] \]
for $s = 1,2,3$, where $h_2$ is the hidden state at time 2. It is worth pointing out that $O_\phi$ contains information to recover the $p_h$'s, and since
\[ O_{\phi}^3 = O_{\phi}^2 T, \qquad O_{\phi}^1 = O_{\phi}^2 \diag(\pi) T^T \diag(T\pi)^{-1}\]
if we can recover $O_{\phi}^s$, $s = 1,2,3$, then we can recover $T$ and $\pi$ by algebra.

Conditional independence of $(c_1, \mu_1)$, $(c_2, \mu_2)$, $(c_3, \mu_3)$ given $h_2$ implies that
\[ \E[\phi(c_1, \mu_1) \otimes \phi(c_2, \mu_2) \otimes \phi(c_3, \mu_3)] = \sum_{i=1}^m w_i (O_{\phi}^1)_i \otimes (O_{\phi}^2)_i \otimes (O_{\phi}^3)_i \]
where $w_i = \Pr[h_2 = i] = (T\pi)_i$.
This tensor has a low rank structure.

Its empirical version can be computed by summing the outer products of mapped observation over training data; suppose the training data contains triples $\cbr{((c_{t,1}, \mu_{t,1}), (c_{t,2}, \mu_{t,2}), (c_{t,3}, \mu_{t,3}))}_{t=1}^{l}$, then
\[ \hat{\E}[\phi(c_1, \mu_1) \otimes \phi(c_2, \mu_2) \otimes \phi(c_3, \mu_3)] = \frac{1}{l} \sum_{t=1}^l \phi(c_{t,1}, \mu_{t,1}) \otimes \phi(c_{t,2}, \mu_{t,2}) \otimes \phi(c_{t,3}, \mu_{t,3}) \to \E[\phi(c_1, \mu_1) \otimes \phi(c_2, \mu_2) \otimes \phi(c_3, \mu_3)] \]

Therefore, applying CP-tensor decomposition on the empirical tensor gives an estimate of $O_{\phi}^s$, $s = 1,2,3$.

\section{Feature Maps}
Some examples of feature maps are given as follows.

\paragraph{Binning mapping} Given observation $(c, \mu)$, $\phi_{\bin, n}(c, \mu)$ is a $n$-dimensional vector, with its entries as follows:
\[ (\phi_{\bin, n}(c, \mu))_i = \begin{cases} I(\frac{\mu}{c} \in (\frac{i-1}{n}, \frac{i}{n}]) & c \neq 0 \\ 0 & c = 0 \end{cases} \]
where $n$ is a hyperparameter controlling the number of the bins, and the width of the bins is $\frac{1}{n}$.

\paragraph{Beta mapping} Given observation $(c, \mu)$, $\phi_{\bet, n}(c, \mu)$ is a $n$-dimensional vector, with its entries as follows:
\[ (\phi_{\bet, n}(c, \mu))_i = \frac{1}{B(\mu+1, c-\mu+1)} (\frac{i}{n})^\mu (1-\frac{i}{n})^{c-\mu} \]

\section{Experiment Results}
\subsection{Setting}
In this set of experiments, we focus on the methylation data in cell type E1 and chromosome 1.

Let $s$ be the number of base segments merged to a single segment. Specifically, we aggregate every $s$ observations to a single one. Namely, for all integers $k \geq 0$, we merge obervations $(c_{ks+1}, \mu_{ks+1})$, $(c_{ks+2}, \mu_{ks+2})$, \ldots, $(c_{ks+s}, \mu_{ks+s})$ to a single $(\tilde{c}_k, \tilde{\mu}_k)$, where
\[ \tilde{c}_k = \sum_{i=1}^k c_{ks+i}, \quad \tilde{\mu}_k = \sum_{i=1}^k \mu_{ks+i}\]
Note that the segments merged are non-overlapping.

Let $l$ be the length of the input sequence, that is, we draw $l$ 3-consecutive observations with replacement from the (merged) sequence $\cbr{(c_t, \mu_t)}_{t=1}^{L}$, forming a new dataset containing triples $\cbr{((\tilde{c}_{t,1}, \tilde{\mu}_{t,1}), (\tilde{c}_{t,2}, \tilde{\mu}_{t,2}), (\tilde{c}_{t,3}, \tilde{\mu}_{t,3}))}_{t=1}^{l}$.

Let $n$, the dimensionality of the feature mapping, be 30.

Let $m$ be the number of hidden states assumed. For example if $m = 4$, then the estimated matrix $O^2_{\phi} = \E[\phi(x)|h]$ has 4 columns.

%At this point we do not take into account the contexts, and we further assume that the coverage in different segments are non-uniform.

Although our ultimate goal is to recover the transition matrix and observation matrix of the hidden Markov model, at the current stage, we recover $\E[\phi(x)|h]$ for each value of $h$. Recall that $x = (c, \mu)$ is the (coverage, methylation) count pair in each segment. In the figures, the x-axis $t$ corresponds to the $i = (tn)^{\text{th}}$ coordinate of vector $\phi$. The $y$ axis corresponds to the values of $(\E[\phi(x)|h])_i$.

The value of $p_h$ for each $h$ can be straightforwardly extracted from $\E[\phi(x)|h]$. The transition matrix can also be computed subsequently. We leave the full recovery of the parameters to the next stage.

\paragraph{Recovery of $p_h$ from Expected Beta feature mapping}
Recall that
\[ \int_0^1 \frac{t t^{m}t^{c-m}}{B(m+1,c-m+1)} dt = \int_0^1 \frac{t t^{(m+1)-1}t^{(c-m+1)-1}}{B(m+1,c-m+1)} dt = \frac{m+1}{c+2} \]
Therefore,
\[ \int_0^1 \E[\phi(x,t) | h] dt = \E[\frac{m+1}{c+2} | h] = \E[\frac{cp_h + 1}{c + 2} | h] = \E[\frac{c}{c+2}] p_h + \E[\frac{1}{c+2}] \]
assuming independence between $h$ and $c$.
Let $a = \E[\frac{1}{c+2}]$. Then, $\int_0^1 \E[\phi(x,t) | h] dt = (1 - 2a) p_h + a$.
Hence,
\[ p_h = \frac{\int_0^1 \E[\phi(x,t) | h] dt - a}{1 - 2 a}. \]

%In subsequent results, we show the entire $\E[\phi(x)|h]$, as opposed to a single number $p_h \in [0,1]$. The reason is that we wish to recover more information about the hidden states learned, to get a better understanding of the HMM model.

%-- what features $\phi$ are you looking at?
%-- why are you showing the entire $\phi$ vector and not a single number?
%We focus on two types of feature mappings $\phi$, the first one is binning mapping:
%\[ \phi_{\bin}(x,y) = \begin{cases} {I(\frac{\mu}{c} \in (y,y+h])} & c \neq 0 \\ 0 & c = 0\end{cases} \]
%where $h$ is the width of the bins.

%The second one is Beta map:
%\[ \phi(x,y) = \frac{1}{B(\mu+1, c-\mu+1)}y^\mu (1-y)^{c-\mu} \]
%In this mapping there is no explicit notion of ``bin width", but the value of $c$ can be thought of as a parameter controlling it: if the coverage $c$ is large, then the bin width is small, and vice versa.

%In experiments, since it is impossible to write down $\E[\phi(x_1, \cdot) \otimes \phi(x_2, \cdot) \otimes \phi(x_3, \cdot)]$ and perform tensor decomposition, we use discretization: compute an empirical version of $\E[\phi(x_1, y_1) \otimes \phi(x_2, y_2) \otimes \phi(x_3, y_3)]$, where $y_1, y_2, y_3$ is in $\cbr{0,h,2h,\ldots,1}$. By decomposing this tensor we are able to recover $\E[\phi(x, y) | h]$, where $y$ is in $\cbr{0,h,2h,\ldots,1}$. By mild regularity assumption on the distribution of $x$, this can give a fairly accurate estimate of $\E[\phi(x, y) | h]$ where $y$ ranges in the $[0,1]$ interval.

\subsection{Effect of Sample Size $l$}
We fix $m = 4$, $s = 1$, and vary the sample size (number of triples collected) $l =$ 1000, 10000, 20000, 40000, 80000, 160000, 320000. The samples are drawn without replacement from the original dataset. Figure~\ref{fig:varyl} shows the result. Recall that the value of $m$ is the number of hidden states assumed; We observe that the output of the algorithm stablizes when $l \geq 80000$. \footnote{For the last few figures, although the colors of the lines in all subfigures are diffent, we observe that they have the same pattern.}

\begin{figure}[H]

    \begin{tabular}{cc}
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 10000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$l = 10000$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 20000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$l = 20000$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 40000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$l = 40000$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 80000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$l = 80000$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 160000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$l = 160000$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$l = 320000$}
    \end{subfigure}
    \\
    \end{tabular}

    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for varying sample size $l$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varyl}
\end{figure}

\subsection{Effect of Specifying the Number of States}

We fix $l = 320000$, $s = 1$, and vary the number of states $m = 2,3,4,5,6,7,8,9$. Figure~\ref{fig:varym} shows the columns of $\E[\phi(x)|h]$ recovered. The spectral algorithm provides reasonable results when $m \leq 4$; when $m \geq 5$, the algorithm started to recover observation columns that has a lot of negative entries.

\begin{figure}[H]

    \begin{tabular}{cc}
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 320000_s = 1_m = 1_n = 30_phi = beta_full.pdf}
        \caption{$m = 1$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 320000_s = 1_m = 2_n = 30_phi = beta_full.pdf}
        \caption{$m = 2$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 320000_s = 1_m = 3_n = 30_phi = beta_full.pdf}
        \caption{$m = 3$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$m = 4$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_l/cell = E1_chr = 1_l = 320000_s = 1_m = 5_n = 30_phi = beta_full.pdf}
        \caption{$m = 5$}
    \end{subfigure}
    \end{tabular}

    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for varying number of states $m$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varym}
\end{figure}

\subsection{Binning Feature vs. Beta Feature}

We compare the experimental results using two types of feature maps $\phi_{\bin, n}$ and $\phi_{\bet, n}$. Although the two mappings are substantially different, their respective $\E[\phi(x)|h]$ have some similarities. In some sense, the beta mapping is performing a ``soft'' binning which takes into account the number count $c$ in $x$: fixing the value of methylation probability $m/c$, if $c$ is larger, then the beta mapping is closer to a binning mapping with smaller bin size. Figure~\ref{fig:varyphi} shows the columns of the recovered $\E[\phi(x)|h]$ recovered. Generally, $\phi_{\bet, n}$ produces smoother observation columns, and the results are stabler than $\phi_{\bin, n}$.

%-- double check this one experiment -- typo in file naming?

\begin{figure}[H]
    \begin{tabular}{cc}
        \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_phi/cell = E1_chr = 1_l = 320000_s = 1_m = 3_n = 30_phi = beta_full.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 3$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_phi/cell = E1_chr = 1_l = 320000_s = 1_m = 3_n = 30_phi = binning_igz.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 3$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_phi/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 4$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_phi/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 30_phi = binning_igz.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 4$}
    \end{subfigure}
    \end{tabular}

    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for $m = 3,4$ and two types of feature map $\phi$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varyphi}
\end{figure}

\subsection{Effect of Number of Segments Combined}
We fix $l = 320000$, $m = 4$, and vary the number of merged segments $s = 1,2,3,4,5,6,7,8$. Figure~\ref{fig:varys} shows the columns of the recovered $\E[\phi(x)|h]$. It can be seen that the recovered result is fairly insensitive to the choice of $s$.

\begin{figure}[H]
    \begin{tabular}{cc}
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_s/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$s = 1$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_s/cell = E1_chr = 1_l = 320000_s = 2_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$s = 2$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_s/cell = E1_chr = 1_l = 320000_s = 3_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$s = 3$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_s/cell = E1_chr = 1_l = 320000_s = 4_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$s = 4$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[width=\textwidth]{figs/vary_s/cell = E1_chr = 1_l = 320000_s = 5_m = 4_n = 30_phi = beta_full.pdf}
        \caption{$s = 5$}
    \end{subfigure}
    \end{tabular}

    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for $m = 4$ and beta feature map $\phi$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varys}
\end{figure}

\section{Experiments with CG methylations}
It is previously known that CG sites has different methylation behavior
compared to non-CG sites. We conduct experiments by merging the coverages and
the methylation counts only in contexts CGA, CGT, CGC, CGG (rows 13 to 16 of
the data).

\subsection{Effect of Number of Hidden States}
Our first set of experiments is on investigating the effect of $m$, the number of hidden
states. We vary $m$ from 1 to 8, and plot the observation matrices in
Figure~\ref{fig:varymcg}.

It can be seen from the figures below that the range of plausible $m$'s are broader:
unlike the full dataset where the observation columns start to have
large negative entries starting from $m \geq 4$, the CG subset still produces
palusible output when $m = 5,6$. In addition, some hidden states recovered
has a large methylation probability, which is not observed in the full dataset
(see e.g. Figure~\ref{fig:varym}.)

\begin{figure}[H]

    \begin{tabular}{cc}
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 1_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 1$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 2_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 2$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 3_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 3$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 4$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 5_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 5$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 6_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 6$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 7_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 7$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 8_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$m = 8$}
    \end{subfigure}

    \end{tabular}

    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for varying number of states $m$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varymcg}
\end{figure}

\subsection{Effects of Feature Maps}
We next conduct a set of comparisons between the beta feature map and the binning
feature map, setting the dimension of feature maps $n = 50$.
It can be seen that overall, binning features produce ``rougher''
observation columns. As with the range of plausible $m$'s, binning feature performs
badly when $m \geq 5$, while beta feature consistently produces reasonable result
even if $m = 5,6$. Both approaches output nonsensical observation matrices when
$m = 7, 8$.

In addition, algorithm using the binning features cannot capture hidden states that has
low methylation probability (for all the hidden states, the conditional
methylation frequency histograms skew towards right).

\begin{figure}[H]
    \begin{tabular}{cc}
    \begin{subfigure}[t]{0.4\textwidth}
      \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 2_n = 50_phi = beta_full_ctxt = 12131415.pdf}
      \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 2$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
      \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 2_n = 50_phi = binning_ctxt = 12131415.pdf}
      \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 2$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 3_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 3$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 3_n = 50_phi = binning_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 3$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 4$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 4_n = 50_phi = binning_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 4$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 5_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 5$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 5_n = 50_phi = binning_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 5$}
    \end{subfigure}
    \end{tabular}
    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for $m = 2,3,4,5$ and two types of feature map $\phi$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varyphicg}
\end{figure}

\begin{figure}[H]
    \begin{tabular}{cc}
    \begin{subfigure}[t]{0.4\textwidth}
      \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 6_n = 50_phi = beta_full_ctxt = 12131415.pdf}
      \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 6$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
      \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 6_n = 50_phi = binning_ctxt = 12131415.pdf}
      \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 6$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 7_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 7$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 7_n = 50_phi = binning_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 7$}
    \end{subfigure}
    \\
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 8_n = 50_phi = beta_full_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bet, n}$ is beta mapping, $m = 8$}
    \end{subfigure}
    &
    \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/cg/cell = E1_chr = 1_l = 320000_s = 1_m = 8_n = 50_phi = binning_ctxt = 12131415.pdf}
        \caption{$\phi = \phi_{\bin, n}$ is binning mapping, $m = 8$}
    \end{subfigure}
    \end{tabular}
    \caption{The observation columns of $\E[\phi(x)|h]$recovered, for $m = 6,7,8$ and two types of feature map $\phi$. The $x$-axis is the value of $t = i/n$, the $y$-axis is the value of $(\E[\phi(x)|h])_i$.}
    \label{fig:varyphicg2}
\end{figure}

\section{Experiments with Posterior Decoding}

With the observation matrix $\E[\phi(x)|h]$, transition matrix $T$, and initial probability $\pi$ recovered,
we apply posterior decoding to the original sequence to get estimates of hidden states in each position (every 100 base pairs).

Empirically we see the result of posterior decoding is similar to that of Viterbi decoding, therefore we present here only the results
for posterior decoding. For illustration purposes, we set the length of our test sequence to 100000; in principle it can be set arbitrarily long.
We set the size of our training set to be 320000.

Below we visualize the recovered hidden states using horizontal bar plots of different colors, each color represents a different outcome
of hidden state. On the right panel, we plot the corresponding expected feature maps of hidden states, and the colors of feature map
curves are consistent with those in the bar plot.

It can be concluded from the plots that all the sequences we are working with are dominated by a certain hidden states. We observe that the
observation matrices recovered in the CG contexts are significantly different from that of CC, CT, CA contexts. In particular, the red hidden
state in the results of CC, CT, CA contexts represents one with a low methylation probability, whereas the red hidden state in the result of CG
represents one whose methlation probablity is high.

\subsection{CC Context}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
  \end{figure}

    \begin{figure}[H]
        \begin{tabular}{cc}
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123l_test = 320000_posterior.pdf}
            \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
          \end{subfigure}
          &
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123_feature_map.pdf}
            \caption{Expected Feature map given the hidden states}
          \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
\end{figure}

\subsection{CT Context}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |4567l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |4567_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |4567l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |4567_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |4567l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |4567_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
  \end{figure}

    \begin{figure}[H]
        \begin{tabular}{cc}
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |4567l_test = 320000_posterior.pdf}
            \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
          \end{subfigure}
          &
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |4567_feature_map.pdf}
            \caption{Expected Feature map given the hidden states}
          \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |4567l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |4567_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
\end{figure}

\subsection{CA Context}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |891011l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |891011_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |891011l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |891011_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |891011l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |891011_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
  \end{figure}

    \begin{figure}[H]
        \begin{tabular}{cc}
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |891011l_test = 320000_posterior.pdf}
            \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
          \end{subfigure}
          &
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |891011_feature_map.pdf}
            \caption{Expected Feature map given the hidden states}
          \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |891011l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |891011_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
\end{figure}

\subsection{CG Context}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
  \end{figure}

    \begin{figure}[H]
        \begin{tabular}{cc}
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |12131415l_test = 320000_posterior.pdf}
            \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
          \end{subfigure}
          &
          \begin{subfigure}[t]{0.4\textwidth}
            \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |12131415_feature_map.pdf}
            \caption{Expected Feature map given the hidden states}
          \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
\end{figure}

\subsection{All Contexts}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123456789101112131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123456789101112131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123456789101112131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123456789101112131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123456789101112131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123456789101112131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

  \begin{figure}[H]
      \begin{tabular}{cc}
        \begin{subfigure}[t]{0.4\textwidth}
          \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123456789101112131415l_test = 320000_posterior.pdf}
          \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
        \end{subfigure}
        &
        \begin{subfigure}[t]{0.4\textwidth}
          \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123456789101112131415_feature_map.pdf}
          \caption{Expected Feature map given the hidden states}
        \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123456789101112131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123456789101112131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
    \end{tabular}
\end{figure}

\section{Merging the Contexts using Conditional Independence}

We concatenate the feature representations in constexts CC, CA, CT and CG. For each
context, the dimension is 10; hence in total the feature map is of 40 dimensions.
Moreover, when performing posterior decoding, we assume the the observations are
conditionally independent, that is, for all $i$, the observation probabililty satisfies
\begin{eqnarray*}
  &&\Pr[(m_t^{CC}, m_t^{CA}, m_t^{CT}, m_t^{CG}) | c_t^{CC}, c_t^{CA}, c_t^{CT}, c_t^{CG}, h_t = i] \\
  &=&
  \Pr[m_t^{CC} | c_t^{CC}, h_t = i] \Pr[m_t^{CA} | c_t^{CA}, h_t = i] \Pr[m_t^{CT} | c_t^{CT}, h_t = i] \Pr[m_t^{CG} | c_t^{CG}, h_t = i]
\end{eqnarray*}

From the experiments below, we can see that the recovered hidden states are diverse,
and corresponds to different methylation behaviors in different contexts.

\subsection{Cell type E sequences(E1 and E2)}
\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell E, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = E_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

\subsection{Cell type V (sequences V8 and V9)}
\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell V, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell V, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell V, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell V, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell V, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = V_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

\subsection{Cell type P (sequences P13P14 and P15P16)}
\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell P, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 2_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell P, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 3_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell P, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 4_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

\begin{figure}[H]
    \begin{tabular}{cc}
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell P, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 5_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
      \\
      \begin{subfigure}[t]{0.4\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415l_test = 320000_posterior.pdf}
        \caption{Posterior Decoding for a substring of methylation of cell P, chromosome 1.}
      \end{subfigure}
      &
      \begin{subfigure}[t]{0.6\textwidth}
        \includegraphics[width=\textwidth]{figs/merge_ctxts/cell = P_chr = 1_l = 320000_s = 1_m = 6_n = 40_phi = beta_full_ctxt = |0123|4567|891011|12131415_feature_map.pdf}
        \caption{Expected Feature map given the hidden states}
      \end{subfigure}
  \end{tabular}
\end{figure}

\end{document}


\section{Bubble Sort}

%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Bubble Sort: Basic Idea}
  Basic idea: to eliminate all adjacent inversions
  \pause

  \input{algs/bubble-sort-basic-idea-overlay}

  \vspace{0.30cm}
  \uncover<5->{
    \begin{center}
	  Finiteness $\implies$ \textcolor{red}{Correctness}.\\[8pt]
	  \fbox{\textcolor{blue}{Theorem:} $A$ is sorted $\iff$ $A$ has no adjacent inversions.}
    \end{center}
  }
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Bubble Sort: Definiteness}
  \input{algs/bubble-sort-alg-overlay}
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Bubble Sort: Example}
  % \begin{center}
  %   \scalebox{0.50}{
  %     \begin{minipage}{0.70\linewidth}
  %   	\input{algs/bubble-sort-alg}
  %     \end{minipage}
  %   }
  % \end{center}

  \begin{center}
	\input{tikz/bubble-sort-example-overlay}
  \end{center}

  \uncover<13->{
	After each ``{\bf for}'' loop, one more element is bubbled up to its final position.
  }
  % \[
  %   5\quad 3\quad 1\quad 6\quad 7\quad 2\quad 4\quad 8
  % \]
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Optimizing Bubble Sort (I)\footnote{See Appendix for ``Optimizing Bubble Sort (II)''.}}
  After each ``{\bf for}'' loop, one more element is bubbled up to its final position.

  \input{algs/bubble-sort-alg-mfp}
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Bubble Sort: Finiteness}
  \begin{center}
	\scalebox{0.75}{
	  \begin{minipage}{0.70\linewidth}
		\input{algs/bubble-sort-alg}
	  \end{minipage}
	}
  \end{center}

  The inner ``{\bf for}'' loops:
  \begin{enumerate}[1)]
	\item \textcolor{blue}{$\exists$ loop : no swaps} $\implies$ swapped = false $\implies$ terminates
	  \pause
	\item \textcolor{red}{$\forall$ loop : has swaps} \pause \qquad \textcolor{red}{\bf \textsc{Impossible}!}
  \end{enumerate}
\end{frame}
%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Bubble Sort: Finiteness}
  \begin{center}
	\fbox{Fact: total \#inversions is finite.}
  \end{center}

  \pause
  Effects of \textsc{Swap}{($a_{i}, a_{i+1}$)} on \textcolor{red}{\#inversions}\footnote{Not on \textcolor{blue}{\#adjacent inversions}! Think about it.}:
  \fignocaption{width = 0.50\textwidth}{figs/swap-inversions.pdf}

  \pause
  \begin{center}
	\textcolor{blue}{$-1: (a_{i},a_{i+1})$}\\[3pt] \pause
	\textcolor{red}{${}+{}0:$} relative order between any other two elements does not change!\\[3pt]
	$\langle a_k, a_l \rangle, \langle a_m, a_n \rangle, \textcolor{red}{\langle a_k, a_i \rangle, \langle a_i, a_m \rangle}$
  \end{center}

  \pause
  \begin{center}
	\fbox{\textcolor{blue}{Lemma:} $\textsc{Swap}(a_{i}, a_{i+1}) \implies -1 \text{ inversion}$}
  \end{center}
\end{frame}
%%%%%%%%%%%%%%%%%%%%


%!TEX root = modelguide.tex

\chapter{Supporting classes}

ArtiSynth uses a large number of supporting classes, mostly defined in
the super package {\tt maspack}, for handling mathematical and
geometric quantities. Those that are referred to in this manual are
summarized in this section.

\section{Vectors and matrices}

Among the most basic classes are those used to implement vectors and
matrices, defined in {\tt maspack.matrix}. All vector classes implement
the interface \javaclass[maspack.matrix]{Vector} and all matrix
classes implement \javaclass[maspack.matrix]{Matrix}, which provide a
number of standard methods for setting and accessing values and
reading and writing from I/O streams.

General sized vectors and matrices are implemented by
\javaclass[maspack.matrix]{VectorNd} and
\javaclass[maspack.matrix]{MatrixNd}. These provide all the usual
methods for linear algebra operations such as addition, scaling, and
multiplication:
%
\begin{lstlisting}[]
  VectorNd v1 = new VectorNd (5);        // create a 5 element vector
  VectorNd v2 = new VectorNd (5);
  VectorNd vr = new VectorNd (5);
  MatrixNd M = new MatrixNd (5, 5);      // create a 5 x 5 matrix

  M.setIdentity();                       // M = I
  M.scale (4);                           // M = 4*M

  v1.set (new double[] {1, 2, 3, 4, 5}); // set values
  v2.set (new double[] {0, 1, 0, 2, 0});
  v1.add (v2);                           // v1 += v2
  M.mul (vr, v1);                        // vr = M*v1

  System.out.println ("result=" + vr.toString ("%8.3f"));
\end{lstlisting}
%
As illustrated in the above example, vectors and matrices both provide
a {\tt toString()} method that allows their elements to be formated
using a C-printf style format string. This is useful for providing
concise and uniformly formatted output, particularly for diagnostics.
The output from the above example is
%
\begin{verbatim}
  result=   4.000   12.000   12.000   24.000   20.000
\end{verbatim}
%
Detailed specifications for the format string are provided in the
documentation for \javamethod[maspack.util]{NumberFormat.set(String)}.
If either no format string, or the string {\tt "\%g"}, is specified,
{\tt toString()} formats all numbers using the full-precision output
provided by {\tt Double.toString(value)}.

For computational efficiency, a number of fixed-size vectors and
matrices are also provided. The most commonly used are those defined
for three dimensions, including \javaclass[maspack.matrix]{Vector3d}
and \javaclass[maspack.matrix]{Matrix3d}:
%
\begin{lstlisting}[]
  Vector3d v1 = new Vector3d (1, 2, 3);
  Vector3d v2 = new Vector3d (3, 4, 5);
  Vector3d vr = new Vector3d ();
  Matrix3d M = new Matrix3d();

  M.set (1, 2, 3,  4, 5, 6,  7, 8, 9);

  M.mul (vr, v1);        // vr = M * v1
  vr.scaledAdd (2, v2);  // vr += 2*v2;
  vr.normalize();        // normalize vr
  System.out.println ("result=" + vr.toString ("%8.3f"));
\end{lstlisting}
%

\section{Rotations and transformations}
\label{RigidTransform3d:sec}

{\tt maspack.matrix} contains a number classes that implement rotation
matrices, rigid transforms, and affine transforms.

Rotations (Section \ref{Rotations:sec}) are commonly described using a
\javaclass[maspack.matrix]{RotationMatrix3d}, which implements a
rotation matrix and contains numerous methods for setting rotation
values and transforming other quantities. Some of the more commonly
used methods are:
%
\begin{lstlisting}[]
   RotationMatrix3d();         // create and set to the identity
   RotationMatrix3d(u, angle); // create and set using an axis-angle

   setAxisAngle (u, ang);      // set using an axis-angle
   setRpy (roll, pitch, yaw);  // set using roll-pitch-yaw angles
   setEuler (phi, theta, psi); // set using Euler angles
   invert ();                  // invert this rotation
   mul (R)                     // post multiply this rotation by R
   mul (R1, R2);               // set this rotation to R1*R2
   mul (vr, v1);               // vr = R*v1, where R is this rotation
\end{lstlisting}
%
Rotations can also be described by
\javaclass[maspack.matrix]{AxisAngle}, which characterizes a rotation
as a single rotation about a specific axis.

Rigid transforms (Section \ref{RigidTransforms:sec}) are used by
ArtiSynth to describe a rigid body's pose, as well as its relative
position and orientation with respect to other bodies and coordinate
frames.  They are implemented by
\javaclass[maspack.matrix]{RigidTransform3d}, which exposes its
rotational and translational components directly through the fields
{\tt R} (a {\tt RotationMatrix3d}) and {\tt p} (a {\tt
Vector3d}). Rotational and translational values can be set and
accessed directly through these fields.  In addition, {\tt
RigidTransform3d} provides numerous methods, some of the more commonly
used of which include:
%
\begin{lstlisting}[]
   RigidTransform3d();         // create and set to the identity
   RigidTransfrom3d(x, y, z);  // create and set translation to x, y, z

   // create and set translation to x, y, z and rotation to roll-pitch-yaw
   RigidTransfrom3d(x, y, z, roll, pitch, yaw);

   invert ();                  // invert this transform
   mul (T)                     // post multiply this transform by T
   mul (T1, T2);               // set this transform to T1*T2
   mulLeftInverse (T1, T2);    // set this transform to inv(T1)*T2
\end{lstlisting}
%

Affine transforms (Section \ref{AffineTransforms:sec}) are used by
ArtiSynth to effect scaling and shearing transformations on
components. They are implemented by
\javaclass[maspack.matrix]{AffineTransform3d}.

Rigid transformations are actually a specialized form of affine
transformation in which the basic transform matrix equals a rotation.
{\tt RigidTransform3d} and {\tt AffineTransform3d} hence both derive
from the same base class
\javaclass[maspack.matrix]{AffineTransform3dBase}.

\section{Points and Vectors}

The rotations and transforms described above can be used to transform
both vectors and points in space.

Vectors are most commonly implemented using
\javaclass[maspack.matrix]{Vector3d}, while points can be implemented
using the subclass \javaclass[maspack.matrix]{Point3d}.  The only
difference between {\tt Vector3d} and {\tt Point3d} is that the former
ignores the translational component of rigid and affine transforms;
i.e., as described in Sections \ref{RigidTransforms:sec} and
\ref{AffineTransforms:sec}, a vector {\tt v} has
an implied homogeneous representation of
%
\begin{equation}
\v^* \equiv \matl \v \\ 0 \matr,
\end{equation}
%
while the representation for a point {\tt p} is
%
\begin{equation}
\p^* \equiv \matl \p \\ 1 \matr.
\end{equation}
%

Both classes provide a number of methods for applying rotational and
affine transforms. Those used for rotations are
%
\begin{lstlisting}[]
  void transform (R);             // this = R * this
  void transform (R, v1);         // this = R * v1
  void inverseTransform (R);      // this = inverse(R) * this
  void inverseTransform (R, v1);  // this = inverse(R) * v1
\end{lstlisting}
%
where {\tt R} is a rotation matrix and {\tt v1} is a vector (or a point
in the case of {\tt Point3d}).

The methods for applying rigid or affine transforms include:
\begin{lstlisting}[]
  void transform (X);             // transforms this by X
  void transform (X, v1);         // sets this to v1 transformed by X
  void inverseTransform (X);      // transforms this by the inverse of X
  void inverseTransform (X, v1);  // sets this to v1 transformed by inverse of X
\end{lstlisting}
where {\tt X} is a rigid or affine transform.
As described above, in the case of {\tt Vector3d}, these methods
ignore the translational part of the transform and apply only the
matrix component ({\tt R} for a {\tt RigidTransform3d} and {\tt A} for
an {\tt AffineTransform3d}).
In particular, that means that for a {\tt RigidTransform3d} given by {\tt X}
and a {\tt Vector3d} given by {\tt v},
the method calls
%
\begin{lstlisting}[]
  v.transform (X.R)
  v.transform (X)
\end{lstlisting}
%
produce the same result.

\section{Spatial vectors and inertias}
\label{SpatialVectors:sec}

The velocities, forces and inertias associated with 3D coordinate
frames and rigid bodies are represented using the 6 DOF spatial
quantities described in Sections \ref{SpatialVelocitiesAndForces:sec}
and \ref{SpatialInertia:sec}. These are implemented by classes in the
package {\tt maspack.spatialmotion}.

Spatial velocities (or twists) are implemented by
\javaclass[maspack.spatialmotion]{Twist}, which exposes its
translational and angular velocity components through the publicly
accessible fields {\tt v} and {\tt w}, while spatial forces (or
wrenches) are implemented by
\javaclass[maspack.spatialmotion]{Wrench}, which exposes its
translational force and moment components through the publicly
accessible fields {\tt f} and {\tt m}.

Both {\tt Twist} and {\tt Wrench} contain methods for algebraic
operations such as addition and scaling. They also contain {\tt
transform()} methods for applying rotational and rigid transforms.
The rotation methods simply transform each component by the supplied
rotation matrix. The rigid transform methods, on the other hand,
assume that the supplied argument represents a transform between two
frames fixed within a rigid body, and transform the twist or wrench
accordingly, using either (\ref{XvelAB:eqn}) or (\ref{XforceAB:eqn}).

The spatial inertia for a rigid body is implemented by
\javaclass[maspack.spatialmotion]{SpatialInertia}, which contains a
number of methods for setting its value given various mass, center of
mass, and inertia values, and querying the values of its components.
It also contains methods for scaling and adding, transforming between
coordinate systems, inversion, and multiplying by spatial vectors.

\section{Meshes}
\label{Meshes:sec}

ArtiSynth makes extensive use of 3D meshes, which are defined in {\tt
maspack.geometry}.  They are used for a variety of purposes, including
visualization, collision detection, and computing physical properties
(such as inertia or stiffness variation within a finite element
model).

A mesh is essentially a collection of vertices
(i.e., points) that are topologically connected in some way.  All
meshes extend the abstract base class
\javaclass[maspack.geometry]{MeshBase}, which supports the vertex
definitions, while subclasses provide the topology.

Through {\tt MeshBase}, all meshes provide methods for
adding and accessing vertices. Some of these include:
%
\begin{lstlisting}[]
  int numVertices();                 // return the number of vertices
  Vertex3d getVertex (int idx);      // return the idx-th vertex
  void addVertex (Vertex3d vtx);     // add vertex vtx to the mesh
  Vertex3d addVertex (Point3d p);    // create and return a vertex at position p
  void removeVertex (Vertex3d vtx);  // remove vertex vtx for the mesh
  ArrayList<Vertex3d> getVertices(); // return the list of vertices
\end{lstlisting}
%
Vertices are implemented by \javaclass[maspack.geometry]{Vertex3d},
which defines the position of the vertex (returned by the method
\javamethod*[maspack.geometry.Vertex3d]{getPosition()}), and also
contains support for topological connections. In addition, each vertex
maintains an index, obtainable via
\javamethod*[maspack.geometry.Vertex3d]{getIndex()}, that equals the
index of its location within the mesh's vertex list. This makes it
easy to set up parallel array structures for augmenting mesh vertex
properties.

Mesh subclasses currently include:

\begin{description}

\item[\protect{\javaclass[maspack.geometry]{PolygonalMesh}}]\mbox{}

Implements a 2D surface
mesh containing faces implemented using half-edges.

\item[\protect{\javaclass[maspack.geometry]{PolylineMesh}}]\mbox{}

Implements a mesh
consisting of connected line-segments (polylines).

\item[\protect{\javaclass[maspack.geometry]{PointMesh}}]\mbox{}

Implements a point cloud with
no topological connectivity.

\end{description}

\javaclass[maspack.geometry]{PolygonalMesh} is used quite extensively
and provides a number of methods for implementing faces, including:
%
\begin{lstlisting}[]
  int numFaces();                 // return the number of faces
  Face getFace (int idx);         // return the idx-th face
  Face addFace (int[] vidxs);     // create and add a face using vertex indices
  void removeFace (Face f);       // remove the face f
  ArrayList<Face> getFaces();     // return the list of faces
\end{lstlisting}
%
The class \javaclass[maspack.geometry]{Face} implements a face as a
counter-clockwise arrangement of vertices linked together by
half-edges (class \javaclass[maspack.geometry]{HalfEdge}).
{\tt Face} also supplies a face's (outward facing) normal
via
\javamethod[maspack.geometry.Face]{getNormal()}.

Some mesh uses within ArtiSynth, such as collision detection, require a
{\it triangular} mesh; i.e., one where all faces have three vertices.
The method \javamethod[maspack.geometry.PolygonalMesh]{isTriangular()}
can be used to check for this. Meshes that are not triangular can be
made triangular using
\javamethod[maspack.geometry.PolygonalMesh]{triangulate()}.

\subsection{Mesh creation}

It is possible to create a mesh by direct construction. For example,
the following code fragment creates a simple closed tetrahedral
surface:
%
\begin{lstlisting}[]
   // a simple four-faced tetrahedral mesh
   PolygonalMesh mesh = new PolygonalMesh();
   mesh.addVertex (0, 0, 0);
   mesh.addVertex (1, 0, 0);
   mesh.addVertex (0, 1, 0);
   mesh.addVertex (0, 0, 1);
   mesh.addFace (new int[] { 0, 2, 1 });
   mesh.addFace (new int[] { 0, 3, 2 });
   mesh.addFace (new int[] { 0, 1, 3 });
   mesh.addFace (new int[] { 1, 2, 3 });
\end{lstlisting}
%

However, meshes are more commonly created using either one of the
factory methods supplied by \javaclass[maspack.geometry]{MeshFactory},
or by reading a definition from a file (Section \ref{MeshFileIO:sec}).

Some of the more commonly used factory methods for creating polyhedral
meshes include:
%
\begin{lstlisting}[]
  MeshFactory.createSphere (radius, nslices, nlevels);
  MeshFactory.createBox (widthx, widthy, widthz);
  MeshFactory.createCylinder (radius, height, nslices);
  MeshFactory.createPrism (double[] xycoords, height);
  MeshFactory.createTorus (rmajor, rminor, nmajor, nminor);
\end{lstlisting}
%
Each factory method creates a mesh in some standard coordinate
frame. After creation, the mesh can be transformed using the
\javamethodAlt{maspack.geometry.MeshBase.transform(AffineTransform3dBase)}%
{transform(X)} method, where {\tt X} is either a rigid transform (
\javaclass[maspack.matrix]{RigidTransform3d}) or a more general affine
transform (\javaclass[maspack.matrix]{AffineTransform3d}).
For example, to create a rotated box centered on $(5, 6, 7)$,
one could do:
%
\begin{lstlisting}[]
  // create a box centered at the origin with widths 10, 20, 30:
  PolygonalMesh box = MeshFactor.createBox (10, 20, 20);

  // move the origin to 5, 6, 7 and rotate using roll-pitch-yaw
  // angles 0, 0, 45 degrees:
  box.transform (
     new RigidTransform3d (5, 6, 7,  0, 0, Math.toRadians(45)));
\end{lstlisting}
%
One can also scale a mesh using
\javamethodAlt{maspack.geometry.MeshBase.scale(double)}{scale(s)},
where {\tt s} is a single scale factor, or
\javamethodAlt{maspack.geometry.MeshBase.scale(double,double,double)}%
{scale(sx,sy,sz)}, where {\tt sx}, {\tt sy}, and {\tt sz} are separate
scale factors for the x, y and z axes. This provides a useful way to
create an ellipsoid:
%
\begin{lstlisting}[]
   // start with a unit sphere with 12 slices and 6 levels ...
  PolygonalMesh ellipsoid = MeshFactor.createSphere (1.0, 12, 6);

  // and then turn it into an ellipsoid by scaling about the axes:
  ellipsoid.scale (1.0, 2.0, 3.0);
\end{lstlisting}
%
\javaclass[maspack.geometry]{MeshFactory} can also be used to create
new meshes by performing boolean operations on existing ones:
%
\begin{lstlisting}[]
  MeshFactory.getIntersection (mesh1, mesh2);
  MeshFactory.getUnion (mesh1, mesh2);
  MeshFactory.getSubtraction (mesh1, mesh2);
\end{lstlisting}
%

\subsection{Setting normals, colors, and textures}

Meshes provide support for adding normal, color, and texture
information, with the exact interpretation of these quantities
depending upon the particular mesh subclass. Most commonly this
information is used simply for rendering, but in some cases normal
information might also be used for physical simulation.

\begin{sideblock}
For polygonal meshes, the normal information described here is used
only for smooth shading. When flat shading is requested, normals are
determined directly from the faces themselves.
\end{sideblock}

Normal information can be set and queried using
the following methods:
%
\begin{lstlisting}[]
  setNormals (
     List<Vector3d> nrmls, int[] indices);  // set all normals and indices

  ArrayList<Vector3d> getNormals();         // get all normals
  int[] getNormalIndices();                 // get all normal indices
  int numNormals();                         // return the number of normals
  Vector3d getNormal (int idx);             // get the normal at index idx

  setNormal (int idx, Vector3d nrml);       // set the normal at index idx
  clearNormals();                           // clear all normals and indices
\end{lstlisting}
%
The method \javamethod[maspack.geometry.MeshBase]{setNormals()} takes
two arguments: a set of normal vectors ({\tt nrmls}), along with a set
of index values ({\tt indices}) that map these normals onto the
vertices of each of the mesh's geometric features. Often, there will
be one unique normal per vertex, in which case {\tt nrmls} will have a
size equal to the number of vertices, but this is not always the case,
as described below.  Features for the different mesh subclasses are:
faces for {\tt PolygonalMesh}, polylines for {\tt PolylineMesh}, and
vertices for {\tt PointMesh}.  If {\tt indices} is specified as {\tt
null}, then {\tt normals} is assumed to have a size equal to the
number of vertices, and an appropriate index set is created
automatically using
\javamethod[maspack.geometry.MeshBase]{createVertexIndices()}
(described below). Otherwise, {\tt indices} should have a size of
equal to the number of features times the number of vertices per
feature. For example, consider a {\tt PolygonalMesh} consisting of two
triangles formed from vertex indices (0, 1, 2) and (2, 1, 3),
respectively. If normals are specified and there is one unique normal
per vertex, then the normal indices are likely to be
%
\begin{verbatim}
   [ 0 1 2  2 1 3 ]
\end{verbatim}
%
As mentioned above, sometimes there may be {\it more} than one normal
per vertex. This happens in cases when the same vertex uses different
normals for different faces. In such situations, the size of the {\tt
nrmls} argument will exceed the number of vertices.

The method {\tt setNormals()} makes internal copies of the specified
normal and index information, and this information can be
later read back using
\javamethod[maspack.geometry.MeshBase]{getNormals()}
and
\javamethod[maspack.geometry.MeshBase]{getNormalIndices()}.
The number of normals can be queried using
\javamethod[maspack.geometry.MeshBase]{numNormals()},
and individual normals can be queried or set using
\javamethodAlt{maspack.geometry.MeshBase.getNormal(int)}{getNormal(idx)}
and
\javamethodAlt{maspack.geometry.MeshBase.setNormal(,)}{setNormal(idx,nrml)}.
All normals and indices can be explicitly cleared using
\javamethod[maspack.geometry.MeshBase]{clearNormals()}.

Color and texture information can be set using analagous methods.
For colors, we have
%
\begin{lstlisting}[]
  setColors (
     List<float[]> colors, int[] indices);  // set all colors and indices

  ArrayList<float[]> getColors();           // get all colors
  int[] getColorIndices();                  // get all color indices
  int numColors();                          // return the number of colors
  float[] getColor (int idx);               // get the color at index idx

  setColor (int idx, float[] color);        // set the color at index idx
  setColor (int idx, Color color);          // set the color at index idx
  setColor (
     int idx, float r, float g, float b, float a); // set the color at index idx
  clearColors();                            // clear all colors and indices
\end{lstlisting}
%
When specified as {\tt float[]}, colors are given as RGB or
RGBA values, in the range $[0,1]$, with array lengths of 3 and 4,
respectively.  The colors returned by
\javamethod[maspack.geometry.MeshBase]{getColors()} are always RGBA
values.

%
With colors, there may often be {\it fewer} colors than the number of
vertices. For instance, we may have only two colors, indexed by 0 and
1, and want to use these to alternately color the mesh faces. Using
the two-triangle example above, the color indices might then look like
this:
%
\begin{verbatim}
   [ 0 0 0 1 1 1 ]
\end{verbatim}
%

Finally, for texture coordinates, we have
%
\begin{lstlisting}[]
  setTextureCoords (
     List<Vector3d> coords, int[] indices); // set all texture coords and indices

  ArrayList<Vector3d> getTextureCoords();   // get all texture coords
  int[] getTextureIndices();                // get all texture indices
  int numTextureCoords();                   // return the number of texture coords
  Vector3d getTextureCoords (int idx);      // get texture coords at index idx

  setTextureCoords (int idx, Vector3d coords);// set texture coords at index idx
  clearTextureCoords();                     // clear all texture coords and indices
\end{lstlisting}

When specifying indices using
\javamethodAlt{maspack.geometry.MeshBase.setNormals(,)}{setNormals},
\javamethodAlt{maspack.geometry.MeshBase.setColors(,)}{setColors}, or
\javamethodAlt{maspack.geometry.MeshBase.setTextureCoords(,)}{setTextureCoords},
it is common to use the same index set as that which
associates vertices with features. For convenience,
this index set can be created automatically using
%
\begin{lstlisting}[]
   int[] createVertexIndices();
\end{lstlisting}
%
Alternatively, we may sometimes want to create a index set
that assigns the same attribute to each feature vertex. If
there is one attribute per feature, the resulting
index set is called a {\it feature index} set, and
can be created using
%
\begin{lstlisting}[]
   int[] createFeatureIndices();
\end{lstlisting}
%
If we have a mesh with three triangles and one color per
triangle, the resulting feature index set would be
%
\begin{verbatim}
   [ 0 0 0 1 1 1 2 2 2 ]
\end{verbatim}
%

\begin{sideblock}
Note: when a mesh is modified by the {\it addition} of new features
(such as faces for \javaclass[maspack.geometry]{PolygonalMesh}), all
normal, color and texture information is cleared by default (with
normal information being automatically recomputed on demand if
automatic normal creation is enabled; see Section \ref{AutoNormalCreation:sec}).
When a mesh is modified by the {\it removal} of
features, the index sets for normals, colors and textures are adjusted
to account for the removal.

For colors, it is possible to request that a mesh explicitly maintain
colors for either its vertices or features (Section
\ref{vertexAndFeatureColoring:sec}). When this is done, colors will
persist when vertices or features are added or removed, with default
colors being automatically created as necessary.
\end{sideblock}

Once normals, colors, or textures have been set,
one may want to know which of these attributes are
associated with the vertices of a specific feature. To know this,
it is necessary to find that feature's offset into the
attribute's index set. This offset information can
be found using the array returned by
%
\begin{lstlisting}[]
  int[] getFeatureIndexOffsets()
\end{lstlisting}
%
For example, the three normals associated with a triangle at index
{\tt ti} can be obtained using
%
\begin{lstlisting}[]
   int[] indexOffs = mesh.getFeatureIndexOffsets();
   ArrayList<Vector3d> nrmls = mesh.getNormals();
   // get the three normals associated with the triangle at index ti:
   Vector3d n0 = nrmls.get (indexOffs[ti]);
   Vector3d n1 = nrmls.get (indexOffs[ti]+1);
   Vector3d n2 = nrmls.get (indexOffs[ti]+2);
\end{lstlisting}
%
Alternatively, one may use the convenience methods
%
\begin{lstlisting}[]
   Vector3d getFeatureNormal (int fidx, int k);
   float[] getFeatureColor (int fidx, int k);
   Vector3d getFeatureTextureCoords (int fidx, int k);
\end{lstlisting}
%
which return the attribute values for the $k$-th vertex of
the feature indexed by {\tt fidx}.

In general, the various {\tt get} methods return references to
internal storage information and so should
{\bf not} be modified. However, specific values within the lists
returned by
\javamethod[maspack.geometry.MeshBase]{getNormals()},
\javamethod[maspack.geometry.MeshBase]{getColors()}, or
\javamethod[maspack.geometry.MeshBase]{getTextureCoords()}
may be modified by the application.  This may be
necessary when attribute information changes as the simultion
proceeds. Alternatively, one may use methods such
as
\javamethodAlt{maspack.geometry.MeshBase.setNormal(,)}{setNormal(idx,nrml)}
\javamethodAlt{maspack.geometry.MeshBase.setColor(int,float)}%
{setColor(idx,color)}, or
\javamethodAlt{maspack.geometry.MeshBase.setTextureCoords(int,)}%
{setTextureCoords(idx,coords)}.

Also, in some situations, particularly with colors and textures, it
may be desirable to {\it not} have color or texture information
defined for certain features. In such cases, the corresponding index
information can be specified as -1, and the {\tt getNormal()}, {\tt
getColor()} and {\tt getTexture()} methods will return {\tt null} for
the features in question.

\subsection{Automatic creation of normals and hard edges}
\label{AutoNormalCreation:sec}

For some mesh subclasses, if normals are not explicitly set, they are
computed automatically whenever {\tt getNormals()} or {\tt
getNormalIndices()} is called. Whether or not this is true
for a particular mesh can be queried by the method
%
\begin{lstlisting}[]
   boolean hasAutoNormalCreation();
\end{lstlisting}
%
Setting normals explicitly, using a call to {\tt
setNormals(nrmls,indices)}, will overwrite any existing normal information,
automatically computed or otherwise. The method
%
\begin{lstlisting}[]
   boolean hasExplicitNormals();
\end{lstlisting}
%
will return {\tt true} if normals have been explicitly set, and {\tt
false} if they have been automatically computed or if there is
currently no normal information. To explicitly remove normals from a
mesh which has automatic normal generation, one may call {\tt
setNormals()} with the {\tt nrmls} argument set to {\tt null}.

More detailed control over how normals are automatically created may
be available for specific mesh subclasses. For example, {\tt
PolygonalMesh} allows normals to be created with multiple normals per
vertex, for vertices that are associated with either open or hard
edges. This ability can be controlled using the methods
%
\begin{lstlisting}[]
   boolean getMultipleAutoNormals();
   setMultipleAutoNormals (boolean enable);
\end{lstlisting}
%
Having multiple normals means that even with smooth shading, open or
hard edges will still appear sharp. To make an edge hard within
a {\tt PolygonalMesh}, one may use the methods
%
\begin{lstlisting}[]
   boolean setHardEdge (Vertex3d v0, Vertex3d v1);
   boolean setHardEdge (int vidx0, int vidx1);
   boolean hasHardEdge (Vertex3d v0, Vertex3d v1);
   boolean hasHardEdge (int vidx0, int vidx1);
   int numHardEdges();
   int clearHardEdges();
\end{lstlisting}
%
which control the hardness of edges between individual vertices,
specified either directly or using their indices.

\subsection{Vertex and feature coloring}
\label{vertexAndFeatureColoring:sec}

The method \javamethod[maspack.geometry.MeshBase]{setColors()} makes
it possible to assign any desired coloring scheme to a mesh. However,
it does require that the user explicity reset the color information
whenever new features are added.

For convenience, an application can also request that a mesh
explicitly maintain colors for either its vertices or features.  These
colors will then be maintained when vertices or features are added or
removed, with default colors being automatically created as necessary.

Vertex-based coloring can be requested with the method
%
\begin{lstlisting}[]
   setVertexColoringEnabled();
\end{lstlisting}
%
This will create a separate (default) color for each of the mesh's
vertices, and set the color indices to be equal to the vertex indices,
which is equivalent to the call
%
\begin{lstlisting}[]
   setColors (colors, createVertexIndices());
\end{lstlisting}
%
where {\tt colors} contains a default color for each
vertex. However, once vertex coloring is enabled, the color and index
sets will be updated whenever vertices or features are added or
removed. Meanwhile, applications can query or set the colors
for any vertex using {\tt getColor(idx)}, or any of the
various {\tt setColor} methods.
Whether or not vertex coloring
is enabled can be queried using
%
\begin{lstlisting}[]
   getVertexColoringEnabled();
\end{lstlisting}
%
Once vertex coloring is established, the application will typically
want to set the colors for all vertices, perhaps using a code fragment
like this:
%
\begin{lstlisting}[]
   mesh.setVertexColoringEnabled();
   for (int i=0; i<mesh.numVertices(); i++) {
      ... compute color for the vertex ...
      mesh.setColor (i, color);
   }
\end{lstlisting}
%

Similarly, feature-based coloring can be requested using the method
%
\begin{lstlisting}[]
   setFeatureColoringEnabled();
\end{lstlisting}
%
This will create a separate (default) color for each of the mesh's
features (faces for
\javaclass[maspack.geometry]{PolygonalMesh}, polylines for
\javaclass[maspack.geometry]{PolylineMesh}, etc.),
and set the color indices to equal the feature
index set, which is equivalent to the call
%
\begin{lstlisting}[]
   setColors (colors, createFeatureIndices());
\end{lstlisting}
%
where {\tt colors} contains a default color for each feature.
Applications can query or set the colors
for any vertex using {\tt getColor(idx)}, or any of the
various {\tt setColor} methods. Whether or not feature coloring
is enabled can be queried using
%
\begin{lstlisting}[]
   getFeatureColoringEnabled();
\end{lstlisting}
%

\subsection{Reading and writing mesh files}
\label{MeshFileIO:sec}

The package {\tt maspack.geometry.io} supplies a number of classes for
writing and reading meshes to and from files of different formats.

Some of the supported formats and their associated readers and writers
include:

\begin{tabular}{|lll|}
\hline
Extension & Format & Reader/writer classes \\
\hline
.obj & Alias Wavefront & \tt WavefrontReader, WavefrontWriter \\
.ply & Polygon file format & \tt PlyReader, PlyWriter \\
.stl & STereoLithography & \tt StlReader, StlWriter \\
.gts & GNU triangulated surface & \tt GtsReader, GtsWriter \\
.off & Object file format & \tt OffReader, OffWriter \\
\hline
\end{tabular}

The general usage pattern for these classes is to construct the
desired reader or writer with a path to the desired file, and then
call {\tt readMesh()} or {\tt writeMesh()} as appropriate:
%
\begin{lstlisting}[]
   // read a mesh from a .obj file:
   WavefrontReader reader = new WavefrontReader ("meshes/torus.obj");
   PolygonalMesh mesh = null;
   try {
      mesh = reader.readMesh();
   }
   catch (IOException e) {
      System.err.println ("Can't read mesh:");
      e.printStackTrace();
   }
\end{lstlisting}
%
Both {\tt readMesh()} and {\tt writeMesh()} may throw I/O exceptions,
which must be either caught, as in the example above, or
thrown out of the calling routine.

For convenience, one can also use the classes
\javaclass[maspack.geometry.io]{GenericMeshReader} or
\javaclass[maspack.geometry.io]{GenericMeshWriter}, which internally
create an appropriate reader or writer based on the file
extension. This enables the writing of code
that does not depend on the file format:
%
\begin{lstlisting}[]
   String fileName;
   ...
   PolygonalMesh mesh = null;
   try {
      mesh = (PolygonalMesh)GenericMeshReader.readMesh(fileName);
   }
   catch (IOException e) {
      System.err.println ("Can't read mesh:");
      e.printStackTrace();
   }
\end{lstlisting}
%
Here, {\tt fileName} can refer to a mesh of any format supported by
{\tt GenericMeshReader}. Note that the mesh returned by {\tt
readMesh()} is explicitly cast to {\tt PolygonalMesh}.  This is
because {\tt readMesh()} returns the superclass {\tt MeshBase}, since
the default mesh created for some file formats may be different from
{\tt PolygonalMesh}.

\subsection{Reading and writing normal and texture information}

When writing a mesh out to a file, normal and texture information are
also written if they have been explicitly set and the file format
supports it. In addition, by default, automatically generated normal
information will also be written if it relies on information (such as
hard edges) that can't be reconstructed from the stored file
information.

Whether or not normal information will be written is returned by the
method
%
\begin{lstlisting}[]
   boolean getWriteNormals();
\end{lstlisting}
%
This will always return {\tt true} if any of the conditions described
above have been met.  So for example, if a {\tt PolygonalMesh}
contains hard edges, and multiple automatic normals are enabled (i.e.,
{\tt getMultipleAutoNormals()} returns {\tt true}), then {\tt
getWriteNormals()} will return {\tt true}.

Default normal writing behavior can be overridden within
the \javaclass[maspack.geometry.io]{MeshWriter} classes
using the following methods:
%
\begin{lstlisting}[]
   int getWriteNormals()
   setWriteNormals (enable)
\end{lstlisting}
%
where {\tt enable} should be one of the following values:
\begin{description}
\item[ 0] normals will {\it never} be written;
\item[ 1] normals will {\it always} be written;
\item[-1] normals will written according to the default behavior
described above.
\end{description}

When reading a {\tt PolygonalMesh} from a file, if the file contains
normal information with multiple normals per vertex that suggests the
existence of hard edges, then the corresponding edges are set to be
hard within the mesh.