%\documentclass{article}
%\usepackage{fancyvrb}
%\usepackage{perltex}
%\usepackage{xcolor}
%\usepackage{listings}
%\usepackage{longtable}
%\usepackage{multirow}
%\input{src/cmd}
%\begin{document}

\index{vecsol!application writeup}

\section{\emph{vecsol}}
\subsection{Overview}
The application computes a 3D vector solution using dual-frequency carrier phases. A double difference
algorithm is applied with properly computed weights (elevation sine weighting) and correlations. The program
iterates to convergence and attempts to resolve ambiguities to integer values if close enough. Crude outlier rejection
is provided based on a triple-difference test. Ephemerides used are either broadcast or precise (SP3).

Alternatively, P code processing is additionally provided.
The solution is computed using either the ionosphere-free linear
combination, or the average of L1 and L2. The ionospheric model included
in broadcast ephemeris may be used. A standard tropospheric correction
is applied, or tropospheric parameters (zenith delays) may be estimated
for the first station (vector mode) or both.

\subsection{Usage}
\subsubsection{\emph{vecsol}}
\begin{\outputsize}
vecsol usage: vecsol $<$RINEX Obs file 1$>$ $<$RINEX Obs file 2$>$
\end{\outputsize}

\subsubsection{RINEX Observation Files}
The two arguments are names of RINEX observation files. They contain the observations collected at the two end points 1 and 2 of the baseline.
They must contain a sufficient set of simultaneous observations to the same satellites.

If no separate station coordinate files are provided, the initial
station coordinates are taken from the RINEX headers. Upon finishing,
vecsol creates or updates the coordinate file of the first station
(vector mode) or both.

\subsubsection{Configuration File vecsol.conf}
The file vecsol.conf contains the input options for the program, one per line.

\begin{\outputsize}

\begin{longtable}{lll}
\entry{Options}{Value}{Meaning}{1}
\entry{obsMode}{3/2/1/0}{If 1 or 3, process carrier phase data (instead of P
code data). If 0 or 1, iterate on ionosphere-free vector (not L1 + L2).}{3}
\entry{truecov}{1/0}{If 1, use true double difference covariances. If 0, ignore any possible correlations.}{2}
\entry{precise}{1/0}{If 1, use precise ephemeris, if 0, use broadcast ephemeris.}{2}
\entry{iono}{1/0}{If 1, use the 8-parameter ionospheric model that comes with the broadcast ephemeris (.nav) files.}{2}
\entry{tropo}{1/0}{If 1, estimate troposphere parameters (zenith delays relative to the standard value, which is always applied).}{3}
\entry{vecmode}{1/0}{If 1, solve the vector, i.e. the three coordinate differences between the  baseline end points. If 0, solve for the absolute coordinates of both end points.}{4}
\entry{debug}{1/0}{If 1, produce lots of gory debugging output. See the source for what it all means.}{2}
\entry{refsat elev}{number}{Minimum elevation (degs) of the reference satellite used for computing inter-satellite differences.  Good initial choice: 30.0.}{3}
\entry{cutoff elev}{number}{Cut-off elevation (degs). Good initial choice: 10.0 - 20.0.}{2}
\entry{rej TP, rej TC}{two numbers}{Phase, code triple differences rejection limit (m).}{1}
\entry{reduce}{1/0}{Apply post-reduction to combine dependent unknowns.}{2}

\end{longtable}
\end{\outputsize}

\subsubsection{Ephemeris File Lists}
The file vecsol.nav contains the names of the navigation RINEX files (``nav files", extension). Good navigation RINEX files that are globally valid can be found  from  the  CORS  website  at http://www.ngs.noaa.gov/CORS/.

The file vecsol.eph contains  the  names  of  the  precise ephemeris SP3 files (extension .sp3) to be used. These should cover the time span of the observations, with time to spare on both  ends. Note  that the date in the filenames of the SP3 files is given as GPS week + weekday, not year + day of year, as in the observation and nav files.

In the .nav and .eph files, comment lines have \# in the first position.
\subsection{Examples}
\begin{verbatim}
> vecsol bell0300.02o bell030a.02o

Configuration data from vecsol.conf
-----------------------------------
Use carrier phases:             1
Compute ionosphere-free:        1
Use true correlations:          1
Use precise ephemeris:          1
Use broadcast iono model:       0
Use tropospheric est.:          1
Vector mode:                    1
Debugging mode:                 1
Ref sat elevation limit:        30
Cut-off elevation:              20
TD rej. limits (phase, code):   0.1 0.1
Reduce out DD dependencies:     1

Eph file: # skipped
Eph file: igs12851.sp3
Eph file: igs12852.sp3
Eph file: igs12853.sp3
Dump SP3EphemerisStore:
 Reject bad positions.
 Reject bad clocks.
 Do not reject predicted positions.
 Do not reject predicted clocks.
Dump of FileStore
 File  1: igs12851.sp3 (header for this file follows)
SP3 Header: version SP3a containing positions only.
 Time tag : 2004/08/23  0:00:00
 Timespacing is 900 sec, and the number of epochs is 96
 Data used as input : ORBIT
 Coordinate system : IGb00
 Orbit estimate type : HLM
 Agency :  IGS
 List of satellite PRN/accuracy (29 total) :
 G01/3 G03/3 G04/3 G05/3 G06/3 G07/3 G08/3 G09/3
 G10/3 G11/4 G13/4 G14/4 G15/3 G16/3 G17/3 G18/4
 G19/4 G20/4 G21/3 G22/3 G23/4 G24/3 G25/3 G26/3
 G27/3 G28/4 G29/3 G30/3 G31/3
 Comments:
    FINAL ORBIT COMBINATION FROM WEIGHTED AVERAGE OF:
    cod emr esa gfz jpl mit ngs sio
    REFERENCED TO IGS TIME AND TO WEIGHTED MEAN POLE:
    CLK ANT Z-OFFSET (M): II/IIA 1.023; IIR 0.000
End of SP3 header
 File  2: igs12852.sp3 (header for this file follows)
SP3 Header: version SP3a containing positions only.
 Time tag : 2004/08/24  0:00:00
 Timespacing is 900 sec, and the number of epochs is 96
 Data used as input : ORBIT
 Coordinate system : IGb00
 Orbit estimate type : HLM
 Agency :  IGS
 List of satellite PRN/accuracy (29 total) :
 G01/3 G03/3 G04/3 G05/3 G06/3 G07/3 G08/3 G09/3
 G10/3 G11/4 G13/4 G14/4 G15/3 G16/3 G17/3 G18/3
 G19/4 G20/4 G21/3 G22/3 G23/4 G24/3 G25/3 G26/3
 G27/3 G28/4 G29/3 G30/3 G31/3
 Comments:
    FINAL ORBIT COMBINATION FROM WEIGHTED AVERAGE OF:
    cod emr esa gfz jpl mit ngs sio
    REFERENCED TO IGS TIME AND TO WEIGHTED MEAN POLE:
    CLK ANT Z-OFFSET (M): II/IIA 1.023; IIR 0.000
End of SP3 header
 File  3: igs12853.sp3 (header for this file follows)
SP3 Header: version SP3a containing positions only.
 Time tag : 2004/08/25  0:00:00
 Timespacing is 900 sec, and the number of epochs is 96
 Data used as input : ORBIT
 Coordinate system : IGb00
 Orbit estimate type : HLM
 Agency :  IGS
 List of satellite PRN/accuracy (29 total) :
 G01/3 G03/3 G04/3 G05/3 G06/3 G07/3 G08/3 G09/3
 G10/3 G11/4 G13/3 G14/3 G15/3 G16/3 G17/3 G18/3
 G19/3 G20/4 G21/3 G22/3 G23/4 G24/3 G25/3 G26/3
 G27/3 G28/4 G29/3 G30/3 G31/3
 Comments:
    FINAL ORBIT COMBINATION FROM WEIGHTED AVERAGE OF:
    cod emr esa gfz jpl mit ngs sio
    REFERENCED TO IGS TIME AND TO WEIGHTED MEAN POLE:
    CLK ANT Z-OFFSET (M): II/IIA 1.023; IIR 0.000
End of SP3 header
End dump of FileStore
Dump of PositionSatStore(1):
 This store does not contain acceleration data.
 Interpolation is Lagrange, of order 10 (5 points on each side)
 Dump of TabularSatStore(1):
  Data stored for 29 satellites
  Time span of data:  FROM 1285 1  86400.000 2004/08/23  0:00:00 Any
		      TO 1285 3 344700.000 2004/08/25 23:45:00 Any
  This store contains: position, not velocity, not clock bias, and not clock drift data.
  Checking for data gaps? no
  Checking data interval? no
   Sat GPS 1 : 288 records.
   Sat GPS 3 : 288 records.
   Sat GPS 4 : 288 records.
   Sat GPS 5 : 288 records.
   Sat GPS 6 : 288 records.
   Sat GPS 7 : 288 records.
   Sat GPS 8 : 288 records.
   Sat GPS 9 : 288 records.
   Sat GPS 10 : 276 records.
   Sat GPS 11 : 288 records.
   Sat GPS 13 : 288 records.
   Sat GPS 14 : 288 records.
   Sat GPS 15 : 288 records.
   Sat GPS 16 : 288 records.
   Sat GPS 17 : 288 records.
   Sat GPS 18 : 288 records.
   Sat GPS 19 : 288 records.
   Sat GPS 20 : 288 records.
   Sat GPS 21 : 288 records.
   Sat GPS 22 : 288 records.
   Sat GPS 23 : 288 records.
   Sat GPS 24 : 288 records.
   Sat GPS 25 : 288 records.
   Sat GPS 26 : 288 records.
   Sat GPS 27 : 288 records.
   Sat GPS 28 : 288 records.
   Sat GPS 29 : 288 records.
   Sat GPS 30 : 288 records.
   Sat GPS 31 : 288 records.
 End dump of TabularSatStore.
End dump of PositionSatStore.
Dump of ClockSatStore(1):
 This store  does not contain clock acceleration data.
 Interpolation is Lagrange, of order 10 (5 points on each side)
 Dump of TabularSatStore(1):
  Data stored for 29 satellites
  Time span of data:  FROM 1285 1  86400.000 2004/08/23  0:00:00 Any
		      TO 1285 3 344700.000 2004/08/25 23:45:00 Any
  This store contains: not position, not velocity, clock bias, and not clock drift data.
  Checking for data gaps? no
  Checking data interval? no
   Sat GPS 1 : 288 records.
   Sat GPS 3 : 288 records.
   Sat GPS 4 : 288 records.
   Sat GPS 5 : 288 records.
   Sat GPS 6 : 288 records.
   Sat GPS 7 : 288 records.
   Sat GPS 8 : 288 records.
   Sat GPS 9 : 288 records.
   Sat GPS 10 : 276 records.
   Sat GPS 11 : 288 records.
   Sat GPS 13 : 288 records.
   Sat GPS 14 : 288 records.
   Sat GPS 15 : 288 records.
   Sat GPS 16 : 288 records.
   Sat GPS 17 : 288 records.
   Sat GPS 18 : 288 records.
   Sat GPS 19 : 288 records.
   Sat GPS 20 : 288 records.
   Sat GPS 21 : 288 records.
   Sat GPS 22 : 288 records.
   Sat GPS 23 : 288 records.
   Sat GPS 24 : 288 records.
   Sat GPS 25 : 288 records.
   Sat GPS 26 : 288 records.
   Sat GPS 27 : 288 records.
   Sat GPS 28 : 288 records.
   Sat GPS 29 : 288 records.
   Sat GPS 30 : 288 records.
   Sat GPS 31 : 288 records.
 End dump of TabularSatStore.
End dump of ClockSatStore.
End dump SP3EphemerisStore.
\end{verbatim}

\subsection{Notes}
Currently, vecsol does not recover from cycle slips, so the RINEX observation files used have to be fairly clean.

%\end{document}


\def\DevnagVersion{2.13}% Assignment 2 for CMSC723
% Finite State Machines

\documentclass[11pt]{article}
\usepackage{latexsym}
\usepackage{listings}
\usepackage[usenames,dvipsnames]{color}
\usepackage[pdftex]{graphicx}
\usepackage{url}
\usepackage{hyperref}

%@modernhindi

% \date{}
\begin{document}
\begin{center}
{\Large{\textbf{ Natural Language Processing:  }}}\\
\mbox{}\\
{\Large{Assignment 2: Finite State Adventures\\Census Nomenclature \& Number Translation}}\\
% \mbox{}\\
% (\textsc{Not For Credit})\\
\mbox{}\\
{\large{Jordan Boyd-Graber}}\\
\mbox{}\\
{\large{Out: \textbf{25. August 2014}\\Due: \textbf{19. September 2014}}}\\
\end{center}

% \maketitle
\lstset{stringstyle=\ttfamily,language=Python,showstringspaces=False,tabsize=8,frameround=tttt,
		,keywordstyle=\color{Orange}\bfseries, stringstyle=\ttfamily\color{Green}
		,columns=fullflexible,identifierstyle=\ttfamily
		% , commentstyle=\itshape\color{Red}
}

\section*{Introduction} % (fold)
\label{sec:introduction}

This assignment is on finite state automata and will require you to
create automata in python. There are a total of three problems, and we
have provided some code to get you started, as well as a few utilities
that will make it easier for you to debug and test your code.  \\

We've provided an a \textsc{fst} implementation from \textsc{nltk}.
However, the documentation is less than perfect. Therefore, in this
section, we will give you a brief introduction to everything that you
will need to understand how to build finite state transducers in Python.
\\

To start building \textsc{fst}s, you need to first import the
\texttt{fst} module into your program's namespace. Then, you need to
instantiate an \texttt{FST} object. Once you have such an object, you
can start adding states and arcs to it. Listing~\ref{example} shows
how to build a very simple finite state transducer---one that removes
all vowels from any given word.

\begin{lstlisting}[float, label=example,caption=A 1-state transducer that deletes vowels, frame=trBL,escapechar=*, numbers=left, numberstyle=\tiny, numberblanklines=false]
# import the fst module
import fst

# import the string module
import string

# Define a list of all vowels for convenience
vowels = *\texttt{[}*'a', 'e', 'i', 'o', 'u'*\texttt{]}*

# Instantiate an FST object with some name
f = fst.FST('devowelizer')

# All we need is a single state ...
f.add_state('1')

# and this same state is the initial and the final state
f.initial_state = '1'
f.set_final('1')

# Now, we need to add an arc for each letter; if the letter is a vowel
# then then transition outputs nothing but otherwise it outputs the same
# letter that it consumed.
for letter in string.ascii_lowercase:
*\qquad*if letter in vowels:
*\qquad**\qquad*f.add_arc('1', '1', (letter), ())
*\qquad*else:
*\qquad**\qquad*f.add_arc('1', '1', (letter), (letter))

# Evaluate it on some example words
print ''.join(f.transduce(*\texttt{[}*'v', 'o', 'w', 'e', 'l'*\texttt{]}*))
print ''.join(f.transduce('e x c e p t i o n'.split()))
print ''.join(f.transduce('c o n s o n a n t'.split()))

\end{lstlisting}
\mbox{}\\
 Feel free to try out the example to see how it works on some of your
 own input. There are a few points worth mentioning:
\begin{enumerate}
	\item The Python \texttt{string} module comes with a few
          built-in strings that you might be able to use in this
          assignment for purposes of iteration as used in the example
          on line $23$. These are:
	\begin{itemize}
		\item \texttt{string.letters} : All letters, upppercased and lowercased
		\item \texttt{string.ascii\_lowercase} : All lowercased letters
		\item \texttt{string.ascii\_uppercase} : All uppercased letters
	\end{itemize}
	\item States can be added to an FST object by using its
          \texttt{add\_state()} method. This method takes a single
          argument: a unique string identifier for the state. Our
          example has only one state (line $13$). Furthermore, there
          can only be \textbf{one} initial state and this is indicated
          by assigning the state identifier to the FST object's
          \texttt{initial\_state} field (line $17$). However, there
          may be multiple final states in an FST. In fact, it is
          almost always necessary to have multiple final states when
          working with transducers. All final states may be so
          indicated by using the FST object's \texttt{set\_final()}
          method (line $18$).
	\item Arcs can be added between the states of an FST object by
          using its \texttt{add\_arc()} method. This method takes the
          following arguments (in order): the starting state, the
          ending state, the input symbol and, finally, the output
          symbol. If you wish to use single characters as input or
          output symbols, you must enclose them in parentheses (lines
          $25$ and $27$).  \\

	 However, if you wish to use entire words as input or output
         symbols, you must enclose the word in \textbf{square
           brackets} (not in parentheses). For example, if you wish to
         add an arc that takes the string \emph{ten} as input and
         returns the number string \emph{10} when going from state 1
         to 2, you should use:
	\begin{lstlisting}[label=foo1, frame=trBL,escapechar=*]
	f.add_arc('1', '2', *\texttt{[}*'ten'*\texttt{]}*, *\texttt{[}*'10'*\texttt{]}*)
	\end{lstlisting}
	 $\epsilon$'s may be indicated by an empty set of parentheses
         or square brackets, depending on the context. (line $25$).
	 \item An FST object can be evaluated against any input string
           by using its \texttt{transduce()} method. Here's how:
	\begin{enumerate}
		\item If your transducer uses \textbf{characters} as
                  input/output symbols, then the input to
                  \texttt{transduce()} must be a \textbf{list of
                    characters}. You may either directly input a list
                  of characters (line $30$) or you may convert a
                  string to a list of characters by spacing out its
                  characters and calling its \texttt{split()} method
                  (lines $31$ and $32$).
		\item If your transducer uses \textbf{words} as
                  input/output symbols, then the input to
                  \texttt{transduce()} should be a \textbf{list of
                    words}. Again, you can either explicitly use a
                  list of words or call the split method on a string
                  of words separated by whitespace. For example, say
                  your FST maps from strings like \emph{ten} and
                  \emph{twenty} to number strings \emph{10} and
                  \emph{20}, then to evaluate it on the input string
                  \emph{ten twenty}, you should use either:
		\begin{lstlisting}[label=foo2, frame=trBL,escapechar=*]
		f.transduce('ten twenty'.split())
		\end{lstlisting}
		\begin{center}{OR}\end{center}
		\begin{lstlisting}[label=foo3, frame=trBL,escapechar=*]
		f.transduce(*\texttt{[}*'ten', 'twenty'*\texttt{]}*)
		\end{lstlisting}
	\end{enumerate}
\end{enumerate}
% section introduction (end)

\section*{Provided Utilities}
To make it easier for you to solve the two programming problems below,
we have provided $3$ handy utilities in the included python file
\texttt{fsmutils.py}. These utility functions will help you to test
each transducer that you build and compose multiple transducers
together.  \\

 The first is \texttt{composechars()}, which allows you to compose any
 number of transducers (that use single characters as input strings)
 and evaluate it on any input string\footnote{Note that this function
   only performs composition in a practical sense and does not
   actually create a single composed transducer. However, for this
   assignment, the former is more than sufficient.}. For example, if
 you have created three transducers \texttt{f1}, \texttt{f2} and
 \texttt{f3} and you wish to evaluate their composition on the input
 string \texttt{S}, then you should use the following code:
	\begin{lstlisting}[label=composechars, frame=trBL,escapechar=*]
	from fsmutils import composechars
	output = composechars(S, f1, f2, f3)
	\end{lstlisting}
	The above function call computes (\texttt{f3} $\circ$
        \texttt{f2} $\circ$ \texttt{f1})(\texttt{S}). i.e., it will
        first apply transducer \texttt{f1} to the given input
        \texttt{S}, use the output of this transduction as input to
        transducer \texttt{f2} and so on and so forth. It will raise a
        generic exception if one or more input transducers do not work
        correctly. Note that since all transducers for this function
        use single characters as the input symbols, \texttt{S} must be
        a list of characters. \\

 The second utility function is \texttt{composewords()} which allows
 you to compose transducers that use words as input symbols, instead
 of single characters. The usage is similar to \texttt{composechars()}
 but the input string \texttt{S} must be a list of words in order to
 be used with this function. \\

 The final utility function is \texttt{trace()}. Given any single
 transducer \texttt{f} and a string \texttt{S}, this function will
 print the entire path taken through \texttt{f} when using \texttt{S}
 as the input. This can prove extremely invaluable for debugging any
 transducer. It may be used as follows:
	\begin{lstlisting}[label=trace, frame=trBL,escapechar=*]
	from fsmutils import trace
	trace(f, S)
	\end{lstlisting}

\section*{Problem 1: Soundex (35 points)} % (fold)
\label{sec:problem_2}
\textbf{Background}: The Soundex algorithm is a phonetic algorithm
commonly used by libraries and the Census Bureau to represent people's
names as they are pronounced in English. It has the advantage that
name variations with minor spelling differences will map to the same
representation, as long as they have the same pronunciation in
English. Here is how the algorithm works:
\begin{description}
	\item[Step 1:] Retain the first letter of the name. This may
          be uppercased or lowercased.
	\item[Step 2:] Remove all \textbf{non-initial} occurrences of
          the following letters: \texttt{a, e, h, i, o, u, w, y}. (To
          clarify, this step removes all occurrences of the given
          characters \emph{except} when they occur in the first
          position.)
	\item[Step 3:] Replace the remaining letters (except the
          first) with numbers:
	\begin{itemize}
		\item \texttt{b, f, p, v} $\rightarrow 1$
		\item \texttt{c, g, j, k, q, s, x, z} $\rightarrow 2$
		\item \texttt{d, t} $\rightarrow 3$
		\item \texttt{l} $\rightarrow 4$
		\item \texttt{m, n} $\rightarrow 5$
		\item \texttt{r} $\rightarrow 6$
	\end{itemize}
 	If two or more letters from the same number group were
        adjacent in the \emph{original} name, then \emph{only} replace
        the first of those letters with the corresponding number and
        ignore the others.
 	\item[Step 4:] If there are more than $3$ digits in the
          resulting output, then drop the extra ones.
 	\item[Step 5:] If there are less than $3$ digits, then pad at
          the end with the required number of trailing zeros.
\end{description}

 The final output of applying Soundex algorithm to any input string
 should be of the form \texttt{Letter Digit Digit
   Digit}. Table~\ref{tbl:soundex} shows the output of the Soundex
 algorithm for some example names.  \\

\begin{table}[htbp]
	\begin{center}
		\begin{tabular}{|c|c|}
			\hline
			\textbf{Input} & \textbf{Output} \\ \hline \hline
			Jurafsky & J$612$ \\ \hline
			Jarovski & J$612$ \\ \hline
			Resnik & R$252$ \\ \hline
			Reznick & R$252$ \\ \hline
			Euler & E$460$ \\ \hline
			Peterson & P$362$ \\ \hline
			\end{tabular}
		\caption{Example outputs for the Soundex algorithm.}\label{tbl:soundex}
\end{center}
\end{table}

 Construct an \textsc{fst} that implements the Soundex
 algorithm. Obviously, it is non-trivial to implement a single
 transducer for the entire algorithm. Therefore, the strategy we will
 adopt is a bottom-up one: implement multiple transducers, each
 performing a simpler task, and then compose them together to get the
 final output. One possibility is to partition the algorithm across
 three transducers:
\begin{enumerate}
	\item \textbf{Transducer 1}: Performs steps $1$-$3$ of the
          algorithm, i.e, retaining the first letter, removing letters
          and replacing letters with numbers.
	\item \textbf{Transducer 2}: Performs step $4$ of the
          algorithm, i.e., truncating extra digits.
	\item \textbf{Transducer 3}: Performs step $5$ of the
          algorithm, i.e., padding with zeros if required. \\
\end{enumerate}

 Note that each of these three transducers will have characters as
 input/output symbols.  \\

 To make things easier for you, we have provided the file
 \texttt{soundex.py} which is where you will write your code. It
 already imports all needed modules and functions (including
 \texttt{fsmutils.py}). It also creates three transducer objects---as
 dictated by the bottom-up strategy outlined above---such that all you
 should have to do is to figure out the states and arcs required by
 each transducer. It also contains code that allows you to input a
 single name on the command line to get the output.

\noindent \textbf{Notes}:
\begin{enumerate}
	\item[(i)] Your grade will only be evaluated on the command
          line.  You do not have to factor the code in the same way as
          the unit tests; however, the unit tests will no longer
          work.

          \item[(ii)] While we have provided you with sample unit
          tests containing some names, it might be very useful to test
          your code on other names. For comparison purposes, you may
          use one of the many Soundex calculators available online.
\end{enumerate}
% section problem_2 (end)

\section*{Problem 2 (55 points)} % (fold)
\label{sec:problem_3}
\textbf{Background}: In the French language, Arabic numerals that we
use in everyday can be spelled out just like they can in English. For
example, the numeral 175 is written as \texttt{one hundred seventy
  five} in English and \textit{cent soixante quinze} in French.

French is interesting becuase they have a mixture of a deximal (base
10) and vegesimal (base 20) system, created by committee to placate
two different regions of Franch that used different systems.  Thus,
for example, you have: \\
\begin{tabular}{|l|l|l|}
\hline
Arabic & French & English Gloss \\
\hline
4 & quatre & four \\
6 & six & six \\
16 & seize & sixteen \\
20 & vingt & twenty \\
26 & vingt six & twenty six \\
56 & cinquante six & fifty six \\
66 & soixante six & sixty six \\
76 & soixante seize & sixty sixteen  \\
80 & quatre vingt & four twenty \\
86 & quatre vingt six & four twenty six \\
96 & quatre ving seize & four twenty sixteen \\
996 & neuf cent quatre ving seize & nine hundred four twenty sixteen
\\
\hline
\end{tabular}

\noindent To summarize:
\begin{itemize}
\item Between 70--79 and 90--99, French numbers use a
vegesimal base system.  For everything else, it is base 10.
\item Numbers congruent to 1 mod 10 in the decimal reange have an ``and''.  For example, 21
  is \textit{vingt et un} (``twenty and one'')
\item Numbers larger than 100 are written as $x$ hundred.  For
  example, 600 becomes \textit{six cent} (``six hundred'').
\item To make things simpler, we'll say that 80 is \textit{quatre vingt} (without an ``s'').
\end{itemize}

You may want to consult an online reference, such
as \url{https://www.udemy.com/blog/french-numbers-1-1000/}.

Construct an \textsc{fst} in \textsc{nltk} that can translate any
given Arabic numeral into its corresponding French string. For the
sake of convenience, you will only be given integer input less than
1000.

\noindent \textbf{Notes}:
\begin{itemize}
	\item[(i)]  Just like for the Soundex problem, we have provided a file
          called \texttt{french\_count.py} with boilerplate code. You
          should add your code to this file, having the
          \texttt{french\_count} function return a transducer that
          produces the correct output.
	\item[(ii)] You should not type any French string into this
          file.  All necessary French strings are in a dictionary
          called \texttt{kFRENCH\_TRANS}.  Adding additional French
          strings will cause you to lose points.
\end{itemize}
% section problem_3 (end)

\section*{English Morphology (10 points)}

English is one of the least interesting languages morphologically, but
it's a good warm up (Chinese, Vietnamese are even less
interesting). If you take a look at \texttt{tests.py}, you can see
some of the words we're going to working with: pack, ice, frolic,
pace, ace, traffic, lilac, lick.  Our goal is to be able to generate
things like "spruced" (from "spruce+d") and "picnicking" (from
"picnic+ed") using regular expressions (which are magically tranformed
into finite state machines\footnote{How this happens is outside the
  scope of the course.}).

The shell for this part of the assignment is in
\texttt{morphology.py}. Essentially all you need to do is implement an
additional regular expression rule that will correctly handle c/ck
alternations. Before doing this, you should be able to execute
\texttt{tests.py} to see the tests failing.

\section*{Turning in Your Assignment}

As usual, submit your completed code to
\href{https://moodle.cs.colorado.edu/course/view.php?id=161}{Moodle}.
Make sure:
\begin{itemize}
  \item You do not change filenames or function names
  \item Turn in all the files you modified individually (do not zip or
    combine them)
  \item You do not change the \textsc{api} of the functions
  \item Do not add \texttt{print} statements to the code you turn in
  \item Add your name as a comment to all files you turn in
\end{itemize}

\end{document}


\chapter{Immersion Grating Design Considerations}

\section{Blaze angle and choice of R}
Blaze angle choice is an important early design consideration for Si immersion gratings.  There is a dichotomy in choice- R1.4 or anything else\footnote{The R-number is the tangent of the blaze angle, and is often used for specifying the blaze angle of echelles for example ranges R1-R10  correspond to $\delta= 45-84.2\deg$}.  The choice of R1.4 simplifies the substrate preparation process because R1.4 ($\delta=54.7$) is the natural blazing provided by the Si (111) crystal plane (see Figure \ref{fig:Rnum}).  One can simply cut Si pucks from conventionally prepared Si boules, with the cuts on parallel planes to the top (100) surface of the Si boule.  Different blaze angles require an additional sample preparation step of x-ray orienting and precision cutting substrates at finite angles from the conventional (100) Si boule surface.  For example, an R3 grating has $\delta=71.6 \deg=54.7\deg+16.9$.  So, cutting the Si boule at 16.9$\deg$ will yield R3 blazed facets.  The cutting plane is normal to the major flat plane.  The middle pane of Figure \ref{fig:IGdesignplot} shows the cutting angle as a function of the blaze angle, with the width of the line equal to the uncertainty of the cutting angle associated with finite etching into the (111) Si crystal plane.

\begin{figure}[h!]
\begin{center}
\ \psfig{file=chGratingDesign/Rnum,height=4.25in,width=5.5in}
\caption[Illustration of Si gratings of different blaze angles]{Illustration of Si gratings of different blaze angles, and the concomitant microscopic Si V-groove cross section.  The grooves are symmetric for R1.4, and increasingly asymmetric for larger blaze angles.  The apex angle of the cross section is 70.5$\deg$ in all cases; it is set by the Si crystal structure and is minutely increased by the finite anisotropic etch ratio.}
\label{fig:Rnum}
\end{center}
\end{figure}

\section{Groove top fill factor and geometric shadowing}
The groove top size has an allowable range.  The small size limit on the groove top is set by KOH under-etching, specifically the tops must be wide enough to hold up against the finite amount of under-etching.  Under-etching limits the groove top to a few percent of the groove width.  The large size limit for the groove top is set by geometric shadowing of the groove facets in a delivered device.  The geometric shadowing is illustrated schematically in Figure \ref{fig:groovetop}.  We derived the geometrical maximum groove top width above which the efficiency is degraded, described below.  We assumed for our derivation that light is incident normal to the groove facets, i.e. the Littrow configuration, which is a good assumption in immersion because of Snell's law.  The maximum allowable ratio of $t/\sigma$ is:

\begin{equation*}
t/\sigma < \frac{1}{1 + \frac{\tan(a)}{\tan(\delta)}}
\end{equation*}
Where $a$ is the Si Apex angle, and $\delta$ is the blaze angle.  For an R3 echelle we must have $t/\sigma < 0.51$.  For the LM module of iShell we elected to use a groove top $t=30 \; \mu$m, which is $t/\sigma=0.375$, so the groove tops will be safely shadowed in this device.  It makes sense that higher R-number gratings can tolerate larger groove tops, as can be surmised from the schematic Figure \ref{fig:groovetop} and the top pane of Figure \ref{fig:IGdesignplot}.

\begin{figure}[h!]
\begin{center}
\ \psfig{file=chGratingDesign/gt_geom_blockage.pdf,height=3in,width=6.4in}
\caption[Schematic of groove top geometry]{Schematic of groove top geometry.  The cartoon gratings have the same blaze angle and period, but different groove top widths (fill factors).  There is a critical groove top width to period ratio below which the groove tops are completely shadowed and no geometric blockage occurs.  For an R3 grating as used in iSHELL, the critical fraction is $t/\sigma < 0.51$.  The delivered devices have $t/\sigma = 0.375$, which is similar to the schematic on the right side.}
\label{fig:groovetop}
\end{center}
\end{figure}

\begin{figure}[h!]
\begin{center}
\ \psfig{file=chGratingDesign/IG_blaze_design.pdf,height=6.5in,width=3.25in}
\caption[Grating design considerations that depend on the choice of blaze angle]{Three paneled plot showing three grating design considerations that depend on the choice of blaze angle.  The top pane shows the range of groove top to grating period ratios that result in shadowed groove tops, or efficiency loss from exposed groove tops.  The middle pane shows the angle at which a Si boule must be cut to produce Si V groove facets at the given blaze angle.  The thickness of the line in the middle pane is equal to the range in cutting angle depending on the degree of anisotropic etching into the (111) Si crystal plane (and concomitant widening of the Si V-groove apex angle).  The width corresponds to $<0.8\deg$.  The bottom pane shows the maximum beam size possible on a 30 mm thick, 100 mm diameter Si substrate, as a function of blaze angle.  The solid line is the beam size, the dashed line is the substrate thickness as measured perpendicular to the grating surface.  These figures are all for Si immersion gratings in Littrow autocollimation.}
\label{fig:IGdesignplot}
\end{center}
\end{figure}

\subsection{Scarp face size in optical reflection measurements}
The proposed GMTNIRS grating LM module will require a larger beam size and a larger illuminated length than the IGRINS or iSHELL immersion gratings.  The strawman design requires an 8 inch substrate, which seems daunting given the challenges of immersion grating production on smaller 4 inch substrates.  Alternative designs employing an R4.5, rather than R3, grating are being considered.  High-R gratings have the limitation that the scarp facet length shrinks for larger blaze angles, until some threshold at which the scarp face is obscured.  The most important diagnostics for evaluating the performance of prototype immersion gratings require the scarp face to be visible.

\begin{figure}[h!]
\begin{center}
\ \psfig{file=chGratingDesign/scarp_reflect.pdf,height=2.0in,width=6.3in}
\caption[Scarp facet in reflection]{A diagram illustrating the lengths used to define the scarp face geometry when illuminated in back surface reflection.  The scarp face length $s$ is labelled and shown in the vertical short solid yellow line.  The blaze angle is the enclosed angle of line $s$ and $h$.  The hypotenuse of the right triangle is label $h$ in the long dashed red line.  The short blue dashed line is perpendicular to the scarp face and parallel to the incoming beam.  }
\label{fig:scarpface}
\end{center}
\end{figure}

Equipped with the geometrical definitions of \ref{fig:scarpface} we can determine $s$:
 \begin{eqnarray}
h=\sigma-t \nonumber \\
\cos{\delta}=s/h \nonumber \\
s=(\sigma-t)\cos{\delta}
 \end{eqnarray}

For an R4.5 grating, $\delta=77.5^\circ$, so the scarp facet $s$ is 20\% of the length $h=\sigma-t$.  There is no angle for which the scarp facet is completely shadowed, although it is true $s$ shrinks for large blaze angles.  Optical tests performed in reflection on higher blaze gratings will have a smaller scarp facet to probe, and the concomitant broad blaze envelope associated with convolving orders with the transform of narrow slit functions.


\documentclass[sigconf]{acmart}

\usepackage{amsmath}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\usepackage{tikz}
\usepackage{pgfplots}

\graphicspath{ {images/} }

\setcopyright{none}
\acmConference[ICPP'19]{ICPP 2019}{August 2019}{Kyoto, Japan}
\acmYear{2019}
\copyrightyear{2019}

\begin{document}

	\title{A Framework for Solving Fractional Laplacian Problems using Eigenfunction Expansion}

	\author{<Author 1>}
	\affiliation{%
		\institution{<Institution 1>}
		\city{<City 1>}
		\state{<State 1>}
	}
	\email{<E-mail 1>}

	\author{<Author 2>}
	\affiliation{%
		\institution{<Institution 1>}
		\city{<City 1>}
		\state{<State 1>}
	}
	\email{<E-mail 2>}

	\author{<Author 3>}
	\affiliation{%
		\institution{<Institution 1>}
		\city{<City 1>}
		\state{<State 1>}
	}
	\email{<E-mail 3>}

	\begin{abstract}
		In order to study the non-local diffusion operator known as the fractional laplacian, we have developed a framework to solve a simple fractional poisson problem using the spectral expansion method. This framework requires computation of a set of eigenpairs for the given problem geometry. For analytical purposes, we compute the entire eigenbasis in order to explore the impact of the non-local nature of the fractional laplacian on the convergence of the spectral expansion. Additionally, we employ the zfp compression library to reduce the amount of data required to store the full eigenbasis. Using this compression library, we explore strategies for balancing data reduction and performance impact in addition to leveraging any aspect of the non-local operator to improve either data reduction or performance.
	\end{abstract}

	\maketitle

	\section{Introduction}
	\input{intro}

	\section{Fractional Laplacian}
	\input{flaplacian}

	\section{Eigenbasis Computation}
	\input{eigenbasis}

	\section{Eigenbasis Storage and Compression}
	\input{compression}

	\section{Results}
	\input{results}

	\section{Conclusion}
	\input{conclusion}

	\bibliographystyle{unsrt}
	\bibliography{refs}

\end{document}


\section{Equation of State}

\subsection{Standard \castro\ EOSes}

\castro\ is written in a modular fashion so that the EOS and network
burning routines can be supplied by the user. However, for the
examples presented later we use several EOS and network routines
that come with the \microphysics\ distribution.

\castro\ relies on routines to calculate the equation of state (EOS)
of a fluid, as well as a species network to define the components of
the fluid. The network optionally has the ability to do nuclear burning,
but for this section its main purpose is in defining the species so that
the EOS can calculate fluid properties that depend on composition, such
as electron fraction.

By default, \castro\ comes with the {\tt gamma\_law}
EOS. This represents a gamma law gas, with equation of state:
\begin{equation}
  P = (\gamma - 1) \rho e.
\end{equation}
The gas is currently assumed to be monatomic and ideal. (Only a
restricted set of thermodynamic variables are actually calculated,
the minimum necessary for the hydrodynamics. A fuller set of
thermodynamic variables, for example the entropy from the
Sackur-Tetrode equation, are calculated in the {\tt gamma\_law\_general}
EOS inside the \microphysics\ repository.)

\subsection{EOS Interfaces and Parameters}

Each EOS should have two main routines by which it interfaces to the
rest of \castro.  At the beginning of the simulation, {\tt eos\_init}
will perform any initialization steps and save EOS variables (mainly
\texttt{smallt}, the temperature floor, and \texttt{smalld}, the
density floor). Then, whenever you want to call the EOS, use
\[
  {\tt call\ eos (eos\_input, eos\_state)}.
\]
The first argument specifies the inputs to the EOS. The options
that are currently available are stored in
{\tt EOS/eos\_data.F90}, and are always a combination of two
thermodynamic quantities. For example, {\tt eos\_input\_rt} means
that we call the EOS with {\tt rho} (density) and {\tt T} (temperature)
and we expect the EOS to return the associated thermodynamic
quantities such as internal energy {\tt e} and entropy {\tt s}.

We note that for real (non-analytic) equations of state
in which $\rho$, $T$ and species are the independent variables, such
as the Helmholtz EOS, {\tt eos\_input\_rt} directly calls the EOS
and obtains the other thermodynamic variables. But for other inputs,
e.g. {\tt eos\_input\_re}, a Newton-Raphson iteration is performed
to find the density or temperature that corresponds to the given
input.

The {\tt eos\_state} variable is a Fortran derived type (similar to
a \cpp\ struct). It stores a complete set of thermodynamic
variables. When calling the EOS, you should first fill the variables
that are the inputs, for example with
\begin{verbatim}
  use eos_type_module
  ...
  type (eos_t) :: eos_state
  ...
  eos_state % rho = state(i,j,k,URHO)
  eos_state % T   = state(i,j,k,UTEMP)
  eos_state % e   = state(i,j,k,UEINT) / state(i,j,k,URHO)
  eos_state % xn  = state(i,j,k,UFS:UFS+nspec-1) / state(i,j,k,URHO)
  eos_state % aux = state(i,j,k,UFX:UFX+naux-1) / state(i,j,k,URHO)
\end{verbatim}
Whenever the \texttt{eos\_state} type is initialized, the
thermodynamic state variables are filled with unphysical numbers. If
you do not input the correct arguments to match your input quantities,
the EOS will call an error. This means that it is good
practice to fill the quantities that will be iterated over with an
initial guess. Indeed, this initial guess is typically required for
equations of state that iterate over this variable, as the values
they are initialized with will likely not
converge. Usually a prior value of the temperature or density suffices
if it's available, but if not then use \texttt{small\_temp} or
\texttt{small\_dens}.

If you are interested in using more realistic and sophisticated equations of
state, you should download the \href{https://github.com/starkiller-astro/Microphysics}{\microphysics}
repository. This is a collection of microphysics routines that are compatible with the
\boxlib\ codes. We refer you to the documentation in that repository for how to set it up
and for information on the equations of state provided. That documentation
also goes into more detail about the details of the EOS code, in case you are interested in
how it works (and in case you want to develop your own EOS).

\section{Nuclear Network}

The nuclear network serves two purposes: it defines the fluid components used
in both the equation of state and the hydrodynamics, and it evolves those
components through a nuclear burning step. \castro\ comes with a {\tt general\_null}
network (which lives in the {\tt Networks/} directory). This is a bare interface for a
nuclear reaction network. No reactions are enabled, and no auxiliary variables
are accepted. It contains several sets of isotopes; for example,
{\tt Networks/general\_null/triple\_alpha\_plus\_o.net} would describe the
isotopes needed to represent the triple-$\alpha$ reaction converting
helium into carbon, as well as oxygen and iron.

The main interface file, {\tt network.f90}, is a wrapper function. The
actual network details are defined in {\tt actual\_network.f90}, a
file which is automatically generated in your work directory when you compile.
It supplies the number and names of species and auxiliary variables, as
well as other initializing data, such as their mass numbers, proton numbers,
and the binding energies.

The burning front-end interface, {\tt Networks/burner.f90}, accepts a different
derived type called the {\tt burn\_t} type. Like the {\tt eos\_t}, it has entries
for the basic thermodynamic quantities:
\begin{verbatim}
  use burn_type_module
  ...
  type (burn_t) :: burn_state
  ...
  burn_state % rho = state(i,j,k,URHO)
  burn_state % T   = state(i,j,k,UTEMP)
  burn_state % e   = state(i,j,k,UEINT) / state(i,j,k,URHO)
  burn_state % xn  = state(i,j,k,UFS:UFS+nspec-1) / state(i,j,k,URHO)
\end{verbatim}
It takes in an input {\tt burn\_t} and returns an output {\tt burn\_t} after
the burning has completed. The nuclear energy release can be computed by
taking the difference of {\tt burn\_state\_out \% e} and
{\tt burn\_state\_in \% e}. The species change can be computed analogously.
In normal operation in \castro\, the integration occurs over a time interval
of $\Delta t/2$, where $\Delta t$ is the hydrodynamics timestep.

If you are interested in using actual nuclear burning networks,
you should download the \href{https://github.com/starkiller-astro/Microphysics}{\tt Microphysics}
repository. This is a collection of microphysics routines that are compatible with the
\boxlib\ codes. We refer you to the documentation in that repository for how to set it up
and for information on the networks provided. That documentation
also goes into more detail about the details of the network code, in case you are interested in
how it works (and in case you want to develop your own network).

\subsection{Required Thermodynamics Quantities}

Three input modes are required of any EOS:
\begin{itemize}
\item {\tt eos\_input\_re}: $\rho$, $e$, and $X_k$ are input
\item {\tt eos\_input\_rt}: $\rho$, $T$, and $X_k$ are input
\item {\tt eos\_input\_rp}: $\rho$, $P$, and $X_k$ are input
\end{itemize}

The {\tt eos\_t} derived type holds a large number of thermodynamics
quantities, but not all of these are needed for basic
\castro\ operation.  The main quantities that any EOS in any mode needs to
supply, if they are not input, are:
\begin{itemize}
  \item {\tt eos\_state \% T}: the temperature
  \item {\tt eos\_state \% P}: total pressure
  \item {\tt eos\_state \% e}: the specific energy
  \item {\tt eos\_state \% gam1}: the first adiabatic index,
       $\Gamma_1 = d\log P / d\log \rho |_s$
\end{itemize}

Additionally the {\tt eos\_input\_re} mode also needs to supply:
\begin{itemize}
  \item {\tt eos\_state \% cs}: the adiabatic sound speed
  \item {\tt eos\_state \% dpdr\_e}: the derivative, $\partial
    p/\partial \rho |_e$---note that the specific internal energy, $e$
    is held constant here.
  \item {\tt eos\_state \% dpde}: the derivative, $\partial p /
    \partial e |_\rho$
\end{itemize}

For radiation hydro, the {\tt eos\_input\_rt} model needs to supply:
\begin{itemize}
  \item {\tt eos\_state \% cv}: the specific heat capacity.
\end{itemize}
Other quantities (e.g., entropy) might be needed for the derived
variables that are optional output into the plotfiles.

For burning, when the temperature equation is evolved, the EOS
needs to supply:
\begin{itemize}
\item {\tt eos\_state \% dhdX(nspec)}: the derivative of the
  specific enthalpy with respect to mass fraction at constant
  $T$ and $p$.  This is commonly computed as:
  \begin{equation}
    \xi_k = e_{X_k} + \frac{1}{p_\rho} \left (\frac{p}{\rho^2} - e_\rho \right ) p_{X_k}\enskip .
  \end{equation}
  with
  \begin{eqnarray}
p_{X_k} &=& \left .\frac{\partial p}{\partial \bar{A}} \right |_{\rho, T, \bar{Z}}
          \frac{\partial \bar{A}}{\partial X_k} +
          \left . \frac{\partial p}{\partial \bar{Z}} \right |_{\rho, T, \bar{A}}
          \frac{\partial \bar{Z}}{\partial X_k} \nonumber \\
        &=& -\frac{\bar{A}^2}{A_k}
          \left .\frac{\partial p}{\partial \bar{A}} \right |_{\rho, T, \bar{Z}} +
          \frac{\bar{A}}{A_k} \left (Z_k - \bar{Z} \right )
          \left . \frac{\partial p}{\partial \bar{Z}} \right |_{\rho, T, \bar{A}}\enskip,
\end{eqnarray}
\begin{eqnarray}
e_{X_k} &=& \left . \frac{\partial e }{\partial \bar{A}} \right |_{\rho, T, \bar{Z}}
        \frac{\partial \bar{A}}{\partial X_k} +
        \left .\frac{\partial e}{\partial \bar{Z}} \right |_{\rho, T, \bar{A}}
        \frac{\partial \bar{Z}}{\partial X_k} \nonumber \\
        &=& -\frac{\bar{A}^2}{A_k}
        \left . \frac{\partial e }{\partial \bar{A}} \right |_{\rho, T, \bar{Z}} +
        \frac{\bar{A}}{A_k} \left (Z_k - \bar{Z}\right )
        \left .\frac{\partial e}{\partial \bar{Z}} \right |_{\rho, T, \bar{A}}\enskip.
\end{eqnarray}
\end{itemize}
(see \cite{maestro:III}, Appendix A).


% 202010??
\documentclass[env.tex]{subfiles}
\begin{document}

Engineering with bio-components have less potential to harm nature than geo-engineering proposals.  This is because the former can be installed in cities and on rooftops; the device is isolated from natural communities.  Geo-engineering proposals however directly perturbing nature; there are risks of unintended consequences.  This study proposes a new model incorporating artificial and life history trait constraints with applications in designing an effective carbon capture device.  The model incorporates \phy\ in a system with the option to add \bac\ and harvest.  The results show the importance of optimising \phy, \bac\ and harvest parameters for maximum carbon harvest efficiency.  The results also show there is a trade-off between feasibility and efficiency; \phy\ cultures have high feasibility but low efficiency while a \pbs\ have low feasibility but high efficiency when optimised.  The choice of system is dependent on the goals of the users and whether the life history traits of \phy\ and \bac\ are controllable.

\subsection{Feasibility of \pbs s}
My model shows \bac\ lowers feasibility of \pbs s (0.3\% \PBH, 97.2\% \PBN) compare with \phy-only systems (100\% \PoH\ \& \PoN; Table \ref{t:feasDist}).  This means a random choice of \phy-\bac\ pair has a lower chance of system establishment.  Substantial work has suggested the importance of chemical mediators in establishment of a high carbon yield co-culture (also known as consortia) and about culture medium optimisations \autocite{rivas2010interactions,amin2009photolysis,fuentes2016impact}.  This study suggests an alternative view on optimising bio-mediators (life history traits).  The results show life history trait values are at least as important as (if not more) environmental factors leading to an establishment of a high carbon yield co-culture; bio-mediators have not been studied in the context of carbon capture yet.  The small feasibility (0.3\%) may explain the few success cases in the experimental tests of high carbon yield \phy-\bac\ pairs \autocite{fuentes2016impact}.  Unfortunately those experiments do not measure life history traits of their organisms of choice; the measurements count on future work for confirmation on whether the experimental life history trait values are those predicted by this model (Fig. \ref{f:harvPB}).

\subsection{Optimal harvest of \phy\ and \phy-\bac\ \pbs s}
Previous work has mixed views on whether destructive or continuous harvest is a better carbon capture approach.  Destructive harvest is proposed by many aquaculture and geo-engineering projects \autocite{lawrence2014efficiency,krause2016substantial}.  Co-culture experiments often adopt continuous harvest methods without considering destructive harvest as an alternative \autocite{kim2008anaerobic,kazamia2012mutualistic}.  My model incorporates both continuous and destructive harvest options which enables direct comparison of the two harvest methods.

The results show there is no optimal harvest for \phy-only systems (Fig. \ref{f:ydDaily}).  This is because \phy\ captures carbon at a constant speed regardless of the carbon density in the model after the system stabilizes (Fig. \ref{f:destCarbon}).  The density-independent carbon capture feature from \phy\ causes a linear accumulation of organic carbon independent from time (Fig. \ref{f:ydDaily}A).  Hence carbon yield for \phy-only systems at equivalent harvest interval/rate have almost the same numerical value; any numerical difference is likely explained by the technical error of the computational methods I used.  The results agree with geo-engineering proposals that adopting destructive harvest by convention is an effective carbon capture method because the alternative harvest method does not have significant carbon yield advantages (Fig. \ref{f:harvPo}).

Continuous harvest is the optimal harvest for \pbs s within feasibility limits (Fig. \ref{f:harvPB}).  This is because \bac\ stabilizes equilibrium carbon densities during development of \pbs s (Fig. \ref{f:destCarbon}A).  As a result longer harvest intervals in destructive harvest have no effect on the carbon content accumulation in the systems; longer waiting time lowers the average carbon yield instead (Fig. \ref{f:ydDaily}A).  Continuous harvest consistently extracts organic carbon out from the system without altering biomass content.  Thus the carbon capture ability from \phy\ is not affected by the harvest.  On the other hand, \bac l growth is limited by the availability of organic carbon; future carbon consumption from \bac\ is also limited.  With smaller \bac l biomass, more carbon can be retained as organic carbon and benefit future harvest of carbon yield.  So a high harvest rate benefits carbon yield from \pbs s (Fig. \ref{f:ydDaily}B).  The results agree with experimental observations of continuous harvest enhances carbon/product yield from \pbs s \autocite{kim2008anaerobic,choix2012enhanced1,choix2012enhanced2,leyva2014accumulation} by providing a mechanistic explanation using ecological interactions between \phy\ and \bac.

\subsection{Importance of life history traits for the organic carbon yield}
Experiments on co-cultures focus on chemical and genetic features of \phy\ and \bac\ bringing the enhanced organic carbon yield effect \autocite{seyedsayamdost2011roseobacticides,durham2015cryptic,amin2009photolysis}.  They used various \phy-\bac\ pairs with different chemical mediators to achieve the enhancement, yet there is not a general explanation on what mechanism causes the enhancement effect.  This model uses a new approach to address effect through bio-mediator (life history traits); the results show trait values are as important (if not more) as chemical ones repeatedly emphasized for the carbon yield enhancement \autocite{fuentes2016impact}.  In the model, carbon yield enhancement can be achieved by expanding the organic carbon pool.  The expansion is maximising the supply and/or minimising the consumption of organic carbon (Fig. \ref{f:harvPB}).

Maximising the carbon supply is maximising \phy\ carbon-use efficiency.  This includes increasing the \phy\ non-respired carbon fraction (increasing $\ePR$; Fig. \ref{f:harvPB}A), increasing the \phy\ carbon leakages (increasing $\eP$; Fig. \ref{f:harvPB}B) and decreasing the \phy\ density-dependent death rate (decreasing $\aP$; Fig. \ref{f:harvPB}D).  Increasing $\ePR$ and $\eP$ increases the amount of carbon leaked into the organic carbon pool and directly benefiting the carbon yield in the short-term.  Decreasing $\aP$ benefits the organic carbon pool in the long-term instead of short-term.  This is because a low $\aP$ keep more carbon as \phy\ biomass.  A high \phy\ biomass enhances photosynthesis rate (Fig. \ref{f:model}) and increases the amount of carbon available for all three processes: respiration, leakage and biomass incorporation.  An enhanced \phy\ respiration is not a concern in this study because the external carbon dioxide pool is always unlimited.  The enhanced carbon leakage from \phy\ directly benefits the organic carbon pool.  The increased carbon incorporated into biomass then forms a positive feedback loop as a long-term enhancement of carbon yield.  Thus \phy\ biomass is functionally more important than its literal carbon content in carbon capture devices.  The results provide a direction for future experimental work to confirm whether the bio-mechanisms of these \phy\ carbon-use efficiencies perform in this logic.

Minimising the carbon consumption is minimising \bac\ carbon-use efficiency.  This includes increasing \bac l respired carbon fraction (decreasing $\eBR$; Fig. \ref{f:harvPB}E), decreasing \bac l leakage carbon fraction (decreasing $\eB$; Fig. \ref{f:harvPB}F) and increasing the \bac l density-independent death rate (increasing $\mB$; Fig. \ref{f:harvPB}H).  Decreasing $\eBR$ and $\eB$ raises the carbon requirements of \bac, which suppress the maximum capacity of \bac.  Decreasing $\eBR$ means more carbon has to be released as carbon dioxide.  Decreasing $\eB$ means more carbon has to be released as organic carbon.  So less carbon can be incorporated into the \bac l biomass, and the maximum capacity of \bac\ decreased.  With less \bac, less carbon will be consumed in the long-term and relatively more carbon can be retained in the organic carbon pool for harvest.  The logic is similar to $\aP$ but in reverse.  Increasing $\mB$ has a short-term effect of increasing the organic carbon pool as well as a long-term effect of suppressing \bac l consumption of organic carbon.  Hence more carbon can be retained for harvest.  The results agree with experimental co-cultures on enhancing product yield by the use of \bac\ \autocite{fuentes2016impact,santos2014microalgal}.  It also simultaneously suggests the biological reasons leading to the enhancement of carbon yield.  The results provide a direction for future experimental confirmation on why a \bacm\ is needed for yield enhancement but the \bacm\ has to be suppressed to the maximum extent.

Two life history traits, \phy\ growth rate ($\gP$; Fig. \ref{f:harvPB}C) and \bac l clearance rate ($\gB$; Fig. \ref{f:harvPB}G), have a peak carbon yield within the range of trait values.  This shows increasing those trait values are beneficial to carbon yield enhancement until their optima; further increasing the trait values recede the carbon benefit.  Increasing $\gP$ and decreasing $\gB$ enhance carbon yields agree with the same logic above: increasing the \phy\ biomass density and/or decreasing the \bac l biomass density benefits the long-term organic carbon accumulation.

The model suggests a high $\gP$ beyond the optimal value also recede carbon yield.  This effect may be brought by the limiting living space for \phy; extremely high \phy\ growth rate would make some fraction of \phy\ biomass non-functional but also non-harvestable.  The redundant \phy\ biomass cannot expand further the organic carbon pool due to space limitations but also cannot be harvested because it is not in the organic carbon pool.  This situation may provide a reason for a lower-than-expected yield in ocean fertilisation geo-engineering proposals \autocite{boyd2008implications,gnanadesikan2008export,oschlies2010side}, where fertilisers only cause a localised algal bloom \autocite{gnanadesikan2008export,lawrence2014efficiency,trick2010iron,kwiatkowski2015atmospheric,lovelock2007ocean}.  In those areas, \phy\ are growing so fast that they cannot disperse to other areas where living space can be a limiting factor.  The results provide a direction for experimental confirmation on the mechanism behind receding yield benefit.

The model suggests that a $\gB$ lower than optimal value benefits carbon yield.  This effect is caused by the trade-off between \bac l consumption and death.  In a low $\gB$ situation, \bac l consumption ($\gB CB$) is small, so as the \bac l death ($\mB$; Eq. \ref{eq:PBH}).  An increase of $\gB$ provides more \bac l biomass to enhance future carbon yield through higher amounts of \bac l death with a minor fraction of respiration (leakage does not matter as carbon flow back to the organic carbon pool).  The increase of \bac l biomass hence is a benefit to future carbon harvest.  The benefit recedes when $\gB$ rises beyond the optimal value, which \bac l respiration is a considerable loss of carbon from the \pbs\ and hinders the yield from organic carbon pool.  The results may reinforce the experimental observations on \bac\ enhancing carbon yield in \pbs s \autocite{fuentes2016impact,santos2014microalgal} by providing a mechanistic explanation.  The results provide a direction for future ground-truthing with experimental measurements.

\subsection{Strengths and Constraints}

\begin{center}\begin{minipage}[H]{.97\linewidth}
\noindent\rule{3.5cm}{1pt}
RENAME \& REWRITE
\noindent\rule{3.5cm}{1pt}
\begin{itemize}
    \item brief linking the model with practicality
    \item focus on C-footprint, experimental trait values search
    \item future direction on practical harvest methods (and respective C-footprints)
\end{itemize}\noindent\rule{10cm}{1pt}
\end{minipage}\end{center}

\noindent\rule{10cm}{4pt}

This model is spatial, temporal independent and ignores temperature variation; it can be applied across latitudes and longitudes where \phy\ and \bac\ can thrive.  The results provide a general overview on the carbon capture ability of \pbs s within feasibility limitations.  This provides a framework on how the model data can be interpreted and suggests potential criteria on selecting the optimal harvest parameters and life history trait values of \phy\ and \bac.

Enhanced co-cultures were reported resilient towards \bac l invasion experimentally \autocite{fuentes2016impact,seyedsayamdost2011roseobacticides}.  The model in this study may have implications on invasion tolerance for \pbs s; the low feasibility (0.3\%) may indicate but not directly address this issue.  An invasion analysis is needed for confirmation of this \pbs\ property.

The model can be engineered as a panel of co-culture with an optimal \phy-\bacm\ pair; this design is applicable in urban area and on rooftops as a carbon capture device.  A life cycle assessment (LCA) should be needed to test whether the design is environmentally-friendly.  Important factors in the LCA should include resource footprints of materials, logistics, construction, maintenance and disposal.  Carbon debt of the panel includes the logistics for raw materials (\phy, \bac, chemicals and disposable laboratory apparatus), genetic modification materials and power used (if needed), co-culture assembly, device manufacture, delivery of the device to the installation location, installing the device, consistence use of machinery and maintenance for carbon harvest and finally the disposal of the device.  It is worth noting that using \bac\ in the design has a minor impact on the overall carbon footprint but a huge benefit on the carbon yield (Fig. \ref{f:ydDaily}).  Carbon benefit includes the total carbon yield harvest from the system during the service life of the device and the internal carbon content when disposed.  However organic carbon can be consumed and respired by decomposers in nature and release back to the atmosphere.  Only carbon that are not easily consumable by organisms is the ``carbon benefit" of the device.

Method of carbon harvest is an important factor contributing to the carbon footprint \autocite{fuentes2016impact}.  Continuous harvest can reduce as much as a quarter of the carbon benefit from a feasible co-culture \autocite{mata2010microalgae}.  Current harvesting methods include ultrafiltration membranes \autocite{zhang2010harvesting}, electrocoagulation and centrifugation (currently not deployable at large scale) \autocite{wijffels2010outlook} and carbon adsorption \autocite{mata2010microalgae,wang2012novel,lee2014repeated}.  These methods should be incorporated in an LCA and a cost-benefit analysis.  Automated harvesting may be costly in expenses and carbon footprint, so harvesting by hand should be considered in the design.  Harvesting by hand can reduce both harvest costs to zero (because human effort is neglected); the only requirement is to construct an invasion-resistant co-culture which would not genetically pollute the environment.  This is because the hand-held harvesting tools is likely to be contaminated by environmental microorganisms.  Co-culture resistance to invasion is a key to preserve the expected carbon yield; some co-cultures might already have this ecological property \autocite{fuentes2016impact,seyedsayamdost2011roseobacticides}.  Handling the co-culture by hand will also bring genetic materials out of the device.  If non-native genetic material is leaked, native microorganisms may have access to recombine with these DNAs.  Native microbiome may change and affect the ecosystems.  This potential risk is an important concern if genetic modified \phy\ or \bac\ is used.

Broad assumptions are the main constraints for this model.  For example, unlimited nutrient may not always be a valid assumption because some \phy\ have specific nutrient requirements \autocite{kazamia2012mutualistic}.  Nutrient specificity of a \phy\ may require specific \bac\ or artificial fertilisers.  These additional criteria may cause the use of sub-optimal \bac, or even lowers the overall carbon yield from the \pbs\ because production of artificial fertilisers require energy (hence translate to carbon footprints in an LCA analysis if the energy is generated from fossil fuels).  Genetic modification may provide a solution but there is a practical risk to the native environment.

\end{document}


%% LyX 2.3.6 created this file.  For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage[a4paper]{geometry}
\geometry{verbose}
\usepackage{babel}
\usepackage{amsmath}
\usepackage{hyperref}
% algorithms
\usepackage[ruled,vlined]{algorithm2e}

\begin{document}

\section{Echo Chamber Problem}

 (``Echo Chamber Problem'' might not be the best name, but I did
 not come up with another one.)

We propose to use our data to find echo chambers inside social networks.
The general idea is that some content is controversially discussed
inside a social network, but that inside echo chambers we do not see
this controversy. Thus, the general idea is as follows: Look at contents
in social networks that are controversially discussed \emph{globally}
and then find subgraphs in which the same contents are discussed non-controversially.
These subgraphs are the echo chambers.

We will now make this notion more formal, but it requires a few definitions.
\begin{itemize}
	\item Suppose there is a signed, directed, multi-graph $G=(V,E^{+},E^{-})$.
	      In the graph, the vertices correspond to users of a social network and
	      the edges correspond to positive/negative interactions of the different
	      users. We will call \emph{G} the \emph{interaction graph}.
	\item Consider a set of contents $\mathcal{C}$, e.g., newspaper articles
	      that are shared on a social network.
	\item For each content $C\in\mathcal{{C}}$, there exists a set of threads
	      $\mathcal{{T}}_{C}.$ Each thread is $T\in\mathcal{{T}}_{C}$ is a
	      subgraph of $G$, i.e., $T\subseteq G,$ such that in the initial post of
	      the thread a user shared the content $C$ and then other users replied
	      to this post. The edges are directed outwards from the replying user;
	      the edges have signs based on whether the interaction was
	      positive/negative.  Furthermore, we assume that the whole graph is the
	      union of the threads, i.e.,
	      $G=\bigcup_{C\in\mathcal{{C}}}\bigcup_{T\in\mathcal{{T}}_{C}}T$.
	\item Fix some $\alpha\in[0,1]$. We denote the fraction of negative edges
	      of a content $C$ and thread $T$ as $\eta(C)$ and $\eta(T)$,
	      respectively. We now define \emph{(non-)controversial}
	      threads and contents:
	      \begin{itemize}
		      \item Intuitively, a thread is controversial if there are many
		            negative interactions. Formally, we say that a thread $T$ is
		            \emph{controversial} if $\eta(T) \in [\alpha,1]$.
		            Otherwise, the thread is
		            \emph{non-controversial} (in this case, the thread contains
		            mostly positive edges).
		      \item Intuitively, a content is controversial if it triggers a
		            lot of negative interactions in the whole network. Formally,
		            we say that a content $C$ is \emph{controversial} if the
		            fraction of negative edges in
		            $\bigcup_{T\in\mathcal{{T}_{C}}}T$ is in the interval
		            $[\alpha,1]$, i.e. $\eta(C) \in [\alpha,1]$.  Otherwise,
		            the content is \emph{non-controversial}. We write
		            $\hat{\mathcal{C}} \subseteq \mathcal{C}$ to denote the set
		            of controversial contents.
	      \end{itemize}
	\item Now our intuition is that inside \emph{echo chambers} there should be
	      little controversy because users have similar opinions and there is
	      little rebuttal. In particular, echo chambers should satisfy that
	      content is which is \emph{globally} controversial is discussed in a
	      non-controversial way \emph{inside} the echo chamber.
	\item We will now formalize this notion. We will use the following
	      notation, where $U\subseteq V$ is a set of vertices:
	      \begin{itemize}
		      \item For a thread $T$, we write $T[U]$ to denote the induced subgraph
		            of $T$ only containing vertices in $U$. As above, we say
		            that $T[U]$ is \emph{controversial} if the fraction of
		            negative edges in $T[U]$ is in the interval $[\alpha,1]$.
		      \item We write $|T(U)|$ to denote the number of edges in $T(U)$
		            (irrespective of their sign).
		      \item For a controversial
		            content $C\in\hat\mathcal{{C}}$ and a set of users
		            $U\subseteq V$, we write $\mathcal{{S}}_{C}(U)$ to denote
		            all threads $T[U]$ such that $T\in\mathcal{{T}}_{C}$ and
		            $T[U]$ is non-controversial. Note that, as desired,
		            $\mathcal{{S}}_{C}(U)$ contains only threads are
		            \emph{locally} non-controversial and that
		            $\mathcal{{S}}_{C}(U)$ is only defined for contents which
		            are \emph{globally} controversial.
		      \item For a set of users $U\subseteq V$, we say that its
		            \emph{echo chamber score} $\xi(U)$ is defined as \[
			            \xi(U)=\sum_{C\in\hat{\mathcal{{C}}}}\sum_{T[U]\in\mathcal{{S}}_{C}(U)}|T[U]|.
		            \] Note that in the first sum we only take into account contents
		            that are globally controversial; this choice was made to ensure
		            that ``wholesome'' content has no effect on the echo chamber
		            score.
	      \end{itemize}
	\item We can now define the \textbf{Echo Chamber Problem}:
	      \begin{itemize}
		      \item \emph{Input:} An interaction graph $G=(V,E^{+},E^{-})$, a set of
		            contents $\mathcal{{C}}$, a set of threads
		            $\mathcal{{T}}_{C}$ for each $C\in\mathcal{{C}}$ and a
		            parameter $\alpha\in[0,1]$.
		      \item \emph{Goal:} Find a set of users $U\subseteq V$ that
		            maximizes the echo chamber score $\xi(U)$.
	      \end{itemize}
\end{itemize}
%

\section{Comments}
\begin{itemize}
	\item I do not insist that this is the perfect problem formulation that we
	      should study. I just think that it might be a starting point for a
	      discussion.
	\item In the echo chamber score, we could as well say that we only count
	      the number of positive edges in $T[U]$.
	\item The problem formulation has the benefit that we do not have to try to
	      infer the leaning of users towards contents.
	\item We could assume that we also have access to the \emph{follow graph},
	      i.e., the graph that encodes which user follows which other user.  In
	      that case, we could define communities based on the follow graph and
	      then check which of the communities has the highest echo chamber score.
	      We could find the communities inside the follow graph by simply using
	      existing community detection algorithms. This would also allow us to
	      check whether the echo chamber score is useful in practice without
	      having to solve the optimization problem.
	\item A problem with the above definition of the echo chamber problem that
	      it does not take into account the follow graph at all. For example,
	      suppose that in a graph all users interact with each other and half
	      them is left-wing and the other one is right-wing. Then the above
	      problem could simply pick one of the two communities (inside which
	      should be mostly positive interactions) and claim that it is an echo
	      chamber. But that is not really true because (by assumption) all users
	      interact and debate with each other regularly.
	\item We could also extend the definition of \emph{controversial} and
	      \emph{non-controversial} to the interval $[\alpha,1-\alpha]$ instead of
	      $[0,1-\alpha]$.  This would resemble the fact that there might be
	      threads such that all users from an echo chamber reply negatively. In
	      other words, there is still a clear ``majority'' reaction. This might,
	      however, come at the risk of finding opposing groups which contain a
	      lot of negative edges; this would not really go too well with the usual
	      notion of an echo chamber.
\end{itemize}

\section{Approaches}%
\label{sec:approaches}

For a graph $G$ we denote with $\xi(G)$ the maximum echo chamber score, and
$\hat U$ the corresponding set of users.

\subsection{Greedy algorithm}%
\label{sub:greedy_algorithm}

The behaviour of the algorithm depends on the choice of $\beta$, regulating
the density of the resulting set of users (for smaller values an higher density
is to be expected, generally)

\begin{algorithm}[H]
	\SetAlgoLined
	% \KwResult{Write here the result }
	$U = \{$ random node $\}$\;
	\While{$\xi(U)$ can be increased by adding a node}{
		With probability $\beta $  {
				add to $U$ the node increasing the score $\xi(U)$ the most\;
			}
		With probability $(1 - \beta )$ remove from $U$ the node contributing
		less to the score $\xi(U)$. This node will be ignored in the next iteration\;
	}
	\caption{Greedy algorithm}
\end{algorithm}

The process is repeated with different starting nodes.

A variant takes into a account the fraction of positive edges of a vertex in
sampling the initial node (the higher the fraction, the more likely it is to be
sampled).

\subsection{Integer Linear Programming model}%
\label{sub:integer_linear_programming_model}

We define the following ILP model to compute exactly the maximing score for a
graph $G$.

We denote as $E(\hat{\mathcal{C}} )$ the set of edges associated to
controversial contents.

\begin{gather}
	\begin{align}
		\label{eq:ilp-model-obj}
		maximize\; \sum^{}_{ij \in E(\hat{\mathcal{C}})} x _{ij}
	\end{align} \\
	\begin{align}
		\label{eq:ilp-model-edge1}
		x _{ij} \leq y_i \quad \forall ij \in E(\hat{\mathcal{C}})
	\end{align} \\
	\begin{align}
		\label{eq:ilp-model-edge2}
		x _{ij} \leq y_j \quad \forall ij \in E(\hat{\mathcal{C}})
	\end{align} \\
	\begin{align}
		\label{eq:ilp-model-nct1}
		\sum^{}_{ij \in E^{-} (T_k)} x_{ij} - \alpha \sum^{}_{ij \in E(T_k)} x_{ij}
		\leq M_k(1 -z_{k} ) \quad \forall T_{k} \in \mathcal{T} _{C}, C \in
		\mathcal{C}
	\end{align} \\
	\begin{align}
		\label{eq:ilp-model-nct2}
		\sum^{}_{ij \in E(T_{k} )} x_{ij} \leq N_{k} z_{k}
	\end{align} \\
	\begin{align}
		\label{eq:ilp-model-d1}
		x _{ij} \in \{0, 1\} \quad \forall ij \in E(\hat{\mathcal{C}})
	\end{align} \\
	\label{eq:ilp-model-d2}
	y _{i} \in  \{0, 1\} \quad \forall i \in V                     \\
	\label{eq:ilp-model-d3}
	z _{k} \in  \{0, 1\} \quad \forall T_{k} \in \mathcal{T} _{C}, C \in
	\mathcal{C}
\end{gather}

The model associates to each vertex a variable $y_i$, to each edge a
variable $x _{ij} $ and to each thread associated to a controversial content a
variable $z_k$.
If the variable associated to a vertex is 1 then it belongs to the set of users
U considered for the current solution; similarly, if the variable associated
to an edge is 1 it is counted in the score (= objective function): This happens
only for links induced by the chosen vertices (due to \ref{eq:ilp-model-edge1}
and \ref{eq:ilp-model-edge2}).

Constraints \ref{eq:ilp-model-nct1} and \ref{eq:ilp-model-nct2} exclude edges associated to controversial threads from
contributing to the objective: for a controversial thread $T_k$ by
definition it will be $\eta(T) > \alpha $, i.e.

\begin{equation}
	\frac{\sum^{}_{ij \in E^{-} (T_{k} )} x_{ij} }
	{\sum^{}_{ij \in E^ (T_{k} )} x_{ij} } > \alpha
\end{equation}
which can be written as
\begin{equation}
	\sum^{}_{ij \in E^{-} (T_{k} )} x_{ij} -
	\alpha {\sum^{}_{ij \in E^ (T_{k} )} x_{ij} } > 0
\end{equation}

So, considering again \autoref{eq:ilp-model-nct1}, for a controversial thread
it will necessarily be $z_{k} = 0$.
But, because of constraint \autoref{eq:ilp-model-nct2}, all the edges
associated to that thread $T_{k} $ needs to be 0, making that an invalid
solution.
This means that a solution in which edges associated to a controversial thread
are set to $1$ is an invalid solution.

The model finds a solution whose value of the objective function corresponds to $\xi(G)$ and the
corresponding set of users is the set of vertices whose $y_i = 1$.

The choice of $M_k$ and $N_k$ can simply be $m$ (the number of edges of the
graph $G$) to produce a valid formulation.

\end{document}


\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{natbib}
\bibliographystyle{plain}

\newtheorem{theorem}{Theorem}
\newtheorem{corollary}{Corollary}
\newtheorem{lemma}{Lemma}

\title{paxos-algorithm}
\author{Khanh Nguyen}
\date{January 2022}

\begin{document}

\maketitle

\section{The Paxos Algorithm}

    In Paxos algorithm, there are two type of machines: $proposer$ and $acceptor$ where each $proposer$ holds a $value$ and the goal of Paxos algorithm is to reach a consensus in the set of $acceptor$ on a single $value$.

    Let assign a partition of natural numbers to each $proposer$ (each partition is a disjoint subset of natural numbers).

    The algorithm below describes the simple version of Paxos algorithm \cite{lamport2001paxos}

    \subsection{$proposer$}
    \label{algorithm:proposer}

    \subsubsection{phase 1: prepare}
    \label{algorithm:proposer:prepare}

        \fbox{\begin{minipage}{30em}

        \textbf{input:} a $value$ the $proposer$ intended to propose

        \textbf{1} choose a number from its partition, namely $proposal\_number$

        \textbf{2} broadcast the prepare message to all $acceptor$

            \begin{center}
                PREPARE\_REQUEST \{$proposal\_number$\}
            \end{center}

        \textbf{3} if it receives responses from a majority of $acceptor$, do \textbf{phase 2}

        \end{minipage}}

    \subsubsection{phase 2: accept}
    \label{algorithm:proposer:accept}

        \fbox{\begin{minipage}{30em}

        \textbf{4} receives

            \begin{center}
                PREPARE\_RESPONSE \{\{$proposal\_number$, $value$\} or $Null$\}
            \end{center}

        \textbf{5} if all PREPARE\_RESPONSE contain $Null$, pick the input $value$ the $proposer$ intended to propose. Else, pick the $value$ corresponding to the highest $proposer\_number$.

        \textbf{6} broadcast the accept message to all $acceptor$

            \begin{center}
                ACCEPT\_REQUEST \{$proposal\_number$, $value$\}
            \end{center}

        \end{minipage}}

    \subsection{$acceptor$}
    \label{algorithm:acceptor}

    an $acceptor$ holds an accepted proposal \{$proposal\_number$, $value$\} in its stable storage.

    \subsubsection{on receiving prepare request}
    \label{algorithm:acceptor:prepare}

        \fbox{\begin{minipage}{30em}

        \textbf{input:} PREPARE\_REQUEST \{$proposal\_number$\}

        \textbf{1} if the accepted proposal is not set or $proposal\_number$ is greater than the accepted proposal, reply with the accepted proposal, namely $promise$

            \begin{center}
                PREPARE\_RESPONSE \{\{$proposal\_number$, $value$\} or $Null$\}
            \end{center}

        \end{minipage}}

    \subsubsection{on receiving accept request}
    \label{algorithm:acceptor:accept}

        \fbox{\begin{minipage}{30em}

        \textbf{input:} ACCEPT\_REQUEST \{$proposal\_number$, $value$\}

        \textbf{1} if the accepted proposal is not set or $proposal\_number$ is greater than the accepted proposal, set the accepted proposal with the input, namely $accept$

        \end{minipage}}

\section{The Proof of Correctness}

    If the proposal \{$m$, $u$\} is accepted by majority of $acceptor$, the algorithm reaches the consensus on value $u$.

    \begin{theorem}
    \label{theorem:1}
    If the proposal \{$m$, $u$\} is accepted by majority of $acceptor$, any issued proposal \{$n$, $v$\} with $m < n$ has $v = u$
    \end{theorem}

    Since all proposals accepted by majority of $acceptor$ must be issued at some point, there cannot be any two proposals accepted by majority of $acceptor$ with two different values. A straight forward corollary of theorem \ref{theorem:1}

    \begin{corollary}
    \label{corollary:1}
    All proposals accepted by majority of $acceptor$ has the same value.
    \end{corollary}

    By guaranteeing corollary \ref{corollary:1}, $acceptor$ can notify the consensus to $proposer$ by replying if they accept the accept request. If $proposer$ receives accept responses from the majority of $acceptor$, it can confirm the consensus.

    \subsection{The proof the theorem \ref{theorem:1}}

    The theorem \ref{theorem:1} can be proved by induction.

    \begin{lemma}[induction step]
    Let \{$m$, $u$\} be the first proposal accepted by majority of $acceptor$.
    Let \{$n$, $v$\} be an issued proposal with $m < n$.
    Suppose that, for all $k \in [m, n)$, the proposal with $k$ has value $u$, then $v = u$
    \end{lemma}

    Let $M_1$ be the set of $acceptor$ that accepted \{$m$, $u$\}, proposal \{$n$, $v$\} is issued by some $proposer$ $p$ hence its prepare request must be replied from some majority set of $acceptor$, namely $M_2$.

    Let an $acceptor$ $q \in M_1 \cap M_2$, since $m < n$, from step 1 of \ref{algorithm:acceptor:prepare}, we know that $acceptor$ $q$ must accept \{$m$, $u$\} before receiving prepare request of $n$.

    Furthermore, $acceptor$ $q$ returns to the prepare request with the proposal \{$k$, $u^*$\} where it is the latest proposal $acceptor$ $q$ accepts.

    We can establish the relation among $m$, $k$, and $n$. By step 1 of \ref{algorithm:acceptor:accept},  $m \leq k < n$, from the induction step assumption, we can conclude that $u^* = u$

    From the perspective of $proposal$ $p$, it receives responses from $M_2$ where there is at least one non-$Null$ proposal. The maximum $proposal\_number$ from the responses set is greater than or equal to $k$, one of the responses, namely $k^*$.

    We can further establish the relation between $k^*$ and $n$. Since, $proposer$ $p$ receives $k^*$ from an $acceptor$ that accepted a proposal with $proposal\_number$ $k^*$, from step 1 of \ref{algorithm:acceptor:prepare}, $k^* < n$

    Therefore, $m \leq k \leq k^* < n$, that implies $proposer$ $p$ picks the $value$ corresponding to the highest $proposer\_number$ $k^*$ which is $u$. Or, $v = u$

\bibliography{references}

\end{document}