% !Mode:: "TeX:UTF-8"
% !TEX program  = xelatex
\title{Assignment 7}

\section{Question 1}
\begin{statebox}{Timescale Invariance}{question-1}
    \begin{align*}
        d_1 &= \frac{\log(S/E)+(r+\sigma^2/2)(T-t)}{\sigma\sqrt{T-t}} \\
        d_2 &= \frac{\log(S/E)+(r-\sigma^2/2)(T-t)}{\sigma\sqrt{T-t}}
    \end{align*}
    Prove the following identity:
    \[
    	d_2 = d_1 - \sigma\sqrt{T-t}
    \]
\end{statebox}

\Python{}{code/7-a.py}

\section{Question 2}
\begin{statebox}{Put-Call Parity}{question-2}
    With $t=0$, $S_0=5$, $E=4$, $T=1$, $\sigma=0.3$ and $r=0.05$, find the option values and verify the put-call parity.
\end{statebox}

\Python{}{code/7-b.py}

\section{Question 3}
\begin{statebox}{Study Note}{question-3}
    \begin{enumerate}
    	\item Write a study note of Black-Scholes' 73 paper.
    	\item Find a sequence of works following this paper and sort out hot topics nowadays.
    \end{enumerate}
\end{statebox}

\subsection{The Black-Scholes World}
The Black–Scholes model assumes that the market consists of at least one risky asset, usually called the stock, and one riskless asset, usually called the money market, cash, or bond. Now we make assumptions on the assets (which explain their names):
\begin{itemize}
    \item (riskless rate) The rate of return on the riskless asset is constant and thus called the \href{https://en.wikipedia.org/wiki/Risk-free_interest_rate}{risk-free interest rate}.
    \item (random walk) The instantaneous log return of stock price is an infinitesimal \href{https://en.wikipedia.org/wiki/Random_walk}{random walk} with drift; more precisely, the stock price follows a \href{https://en.wikipedia.org/wiki/Geometric_Brownian_motion}{geometric Brownian motion}, and we will assume its drift and volatility are constant (if they are time-varying, we can deduce a suitably modified Black–Scholes formula quite simply, as long as the volatility is not random).
    \item The stock does not pay a \href{https://en.wikipedia.org/wiki/Dividend}{dividend}.
\end{itemize}

Assumptions on the market:
\begin{itemize}
    \item There is no \href{https://en.wikipedia.org/wiki/Arbitrage}{arbitrage} opportunity (i.e., there is no way to make a riskless profit).
    \item It is possible to borrow and lend any amount, even fractional, of cash at the riskless rate.
    \item It is possible to buy and sell any amount, even fractional, of the stock (this includes \href{https://en.wikipedia.org/wiki/Short_selling}{short selling}).
    \item The above transactions do not incur any fees or costs (i.e., \href{https://en.wikipedia.org/wiki/Frictionless_market}{frictionless market}).
\end{itemize}

\subsection{Black–Scholes Equation}
As above, the \textbf{Black–Scholes equation} is a \href{https://en.wikipedia.org/wiki/Partial_differential_equation}{partial differential equation}, which describes the price of the option over time. The equation is:
\begin{equation}\label{F:black-scholes}
    \frac{\partial V}{\partial t} + \frac{1}{2}\sigma^2S^2\frac{\partial^2V}{\partial S^2} + rS\frac{\partial V}{\partial S} - rV = 0.
\end{equation}

\subsection{Black–Scholes Formula}
The value of a call option for a non-dividend-paying underlying stock in terms of the Black–Scholes parameters is:
\begin{equation}\label{F:black-scholes-2}
    \begin{aligned}
        C(S_t,t) &= N(d_1)S_t - N(d_2)PV(K) \\
        d_1 &= \frac{1}{\sigma\sqrt{T-t}}\left[\ln\left(\frac{S_t}{K}\right)+\left(r+\frac{\sigma^2}{2}\right)(T-t)\right] \\
        d_2 &= d_1 - \sigma\sqrt{T-t} \\
        PV(K) &= K\exp{(-r(T-t))}
    \end{aligned}
\end{equation}

The price of a corresponding put option based on put–call parity is:
\begin{equation}\label{F:black-scholes-3}
    \begin{aligned}
        P(S_t,t) &= K\exp{(-r(T-t))} - S_t + C(S_t,t) \\
        &= N(-d_2)K\exp{(-r(T-t))} - N(-d_1)S_t.
    \end{aligned}
\end{equation}
\begin{figure}[H]
    \centering
    \includegraphics[width=.5\textwidth]{figures/2019-11-13-black-scholes-6}
    \caption{A European call valued using the Black-Scholes pricing equation for varying asset price $S$ and time-to-expiry $T$}\label{F:black-scholes-6}
\end{figure}

\begin{figure}[H]
    \centering
    \includegraphics[width=.7\textwidth]{figures/2019-11-13-black-scholes-1}
    \caption{Simulated geometric Brownian motions with parameters from market data}\label{F:black-scholes-1}
\end{figure}

\begin{figure}[H]
    \centering
    \includegraphics[width=.7\textwidth]{figures/2019-11-13-black-scholes-2}
\end{figure}

\begin{figure}[H]
    \centering
    \includegraphics[width=.7\textwidth]{figures/2019-11-13-black-scholes-3}
\end{figure}

\begin{figure}[H]
    \centering
    \includegraphics[width=\textwidth]{figures/2019-11-13-black-scholes-4}
    \caption{Bolling graph}\label{F:black-scholes-4}
\end{figure}

\begin{figure}[H]
    \centering
    \includegraphics[width=\textwidth]{figures/2019-11-13-black-scholes-5}
    \caption{Candle graph}\label{F:black-scholes-5}
\end{figure}

\appendix
    \section{Simulation Program}
        \Python{simulation.py}{code/simulation.py}
    \section{Plot Function}
        \Python{bolling.py}{code/plot/bolling.py}
        \Python{candle.py}{code/plot/candle.py}


\lab{Introduction to Python}{Introduction to Python}
\label{lab:Python_Intro}
\objective{Python is a powerful general-purpose programming language.
It can also be used interactively, allowing for very rapid development.
Python has many powerful scientific computing tools, making it an ideal language for applied and computational mathematics.
\\ \indent
In this introductory lab we introduce Python syntax, data types, functions, and control flow tools.
These Python basics are an essential part of almost every problem you will solve and almost every program you will write.
}

% FUTURE EDITS
%  - transition from Python 2.7 to Python 3.5
%     - Use parenthesis with all print statements, as print is now a function.

\section*{Getting Started} % ==================================================

% TODO: Update to Python 3
Python is quickly gaining momentum as a fundamental tool in scientific computing.
It is simple, readable, and easy to learn.
\emph{Anaconda} is a free distribution service by Continuum Analytics, Inc., that includes the cross-platform Python \emph{interpreter} (the software that actually executes Python code) and many Python libraries that are commonly used for applied and computational mathematics.
To install Python via Anaconda, go to \url{http://continuum.io/downloads}, download the installer corresponding to your operating system, and follow the on-screen instructions.

% TODO: Change this for Python 3
Use the installer corresponding to \textbf{Python 2.7}.
Although later versions of Python are available, they do not yet have many of the libraries and features that we require in this curriculum.
For more information on installing Python and various libraries, see Appendices \ref{pythoninstall} and \ref{updateinstall}.

\subsection*{Running Python} % ------------------------------------------------

Python files are saved with a \texttt{.py} extension.
For beginners, we strongly recommend using a simple text editor\footnote{Some of the more popular text editors are described in Appendix \ref{pythoninstall}.} for writing Python files, though many free IDEs (Integrated Development Environments---large applications that facilitate code development with some sophisticated tools) are also compatible with Python.
For now, the simpler the coding environment, the better.

A plain Python file looks similar to the code on the following page:

\begin{lstlisting}
# filename.py
"""This is the file header.
The header contains basic information about the file.
"""

if __name__ == "__main__":
    pass                            # 'pass' is a temporary placeholder.
\end{lstlisting}

The \li{#} character creates a single-line \emph{comment}.
Comments are ignored by the interpreter and serve as annotations for the accompanying source code.
A pair of three quotes, \li{""" """} or \li{''' '''}, creates a multi-line string literal, which may be used as a multi-line comment.
% Comments on the very first line can be used to give the interpreter special instructions, which we will discuss briefly in Volume III.
% For now, we put the name of the file on the first line.

A triple-quoted string literal at the top of the file serves as the \emph{header} for the file.
The header typically includes the author, instructions on how to use the file, and so on.
Executable Python code comes after the header.

Finally, each statement under the \li{if __name__ == "__main__"} clause is executed when the file is run.
Any ``orphan'' statements that are not placed under this clause are also executed when the file is run, but it is generally considered bad practice to leave any statements outside of function definitions or under the clause.

\begin{problem} % Problem: Run a file that prints "Hello, world!"
Create a new Python file and save it to your file system.
Write the file name and a brief header at the top, then add the following code:

\begin{lstlisting}
if __name__ == "__main__":
    print("Hello, world!")
\end{lstlisting}

Open a Unix shell (often called a \emph{terminal} or a \emph{command line}) and navigate to the directory where the new file is saved.
Use the command \li{ls} to list the files in the current directory, \li{pwd} to print the working directory, and \li{cd} to change directories.
Below, the \li{\$} character indicates that the command is being run from the shell.

\begin{lstlisting}[language=bash]
$ pwd
/Users/Guest
$ ls
Desktop     Documents       Downloads       Pictures        Music
$ cd Documents
$ pwd
/Users/Guest/Documents
$ ls
python_intro.py
\end{lstlisting}

Now that we are in the same directory as the Python file, we can execute it using the following command:

\begin{lstlisting}
$ python python_intro.py
\end{lstlisting}

If ``Hello, world!'' is displayed on the screen, you have just successfully executed your first Python program!
\label{prob:helloWorld}
\end{problem}

\subsection*{IPython} % -------------------------------------------------------

Python can be run interactively using several interfaces.
The most basic of these is the Python interpreter.
In this and subsequent labs, the triple brackets \li{>>>} indicate that the given code is being executed one line at a time via the Python interpreter.

\begin{lstlisting}
$ python                            # Start the Python interpreter.
>>> print("This is plain Python.")  # Execute some code.
<<This is plain Python.>>
\end{lstlisting}

There are, however, more useful interfaces.
Chief among these is \emph{IPython}.
To execute a script in IPython, use the \li{run} command.

\begin{lstlisting}
>>> quit()                          # Exit the Python interpreter.
$ ipython                           # Start IPython.

In [1]: print("This is IPython!")   # Execute some code.
<<This is IPython!>>

In [2]: run python_intro.py         # Run a particular Python script.
Hello, world!
\end{lstlisting}

One of the biggest advantages of IPython is that it supports \emph{object introspection}, whereas the regular Python interpreter does not.
Object introspection allows you to quickly see all methods and attributes associated with an object.
IPython also has a built-in \li{help()} function that provides interactive help.

\begin{lstlisting}
# A list is a basic Python data structure. To see the methods associated with
# a list, type the object name (list), followed by a period, and press tab.
In [1]: list.   # Press 'tab'.
<<list.append   list.extend   list.insert   list.remove      list.sort
list.count    list.index    list.pop      list.reverse>>

# To learn more about a specific method, use "?".
In [1]: list.append?
<<Docstring:    L.append(object) -- append object to end
Type:         method_descriptor>>

In [2]: help()                      # Start IPython's interactive help utility.

<<help>>> list                          # Get documentation on the list class.
<<Help on class list in module __builtin__:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  ...>>                             # Press 'q' to exit the info screen.

<<help>>> quit                          # End the interactive help session.
\end{lstlisting}

Use IPython side-by-side with a text editor to test syntax and small code snippets.
Testing code in IPython \emph{before} putting it into a program helps you catch errors beforehand and greatly speeds up the coding process.

If you cannot answer a coding question using these strategies, search the Internet.
In particular, \href{http://stackoverflow.com/}{stackoverflow.com} is often a valuable resource for answering common programming questions.

\section*{Python Basics} % ====================================================

\subsection*{Arithmetic} % ----------------------------------------------------

We can now dive into the particulars of Python syntax.
To begin, Python can be used as a calculator.
Use \li{**} for exponentiation and \li{\%} for modular division.

\begin{lstlisting}
>>> 3**2 + 2*5                      # Python obeys the order of operations.
19

>>> 13 % 3                          # The modulo operator % calculates the
1                                   # remainder: 13 = (3*4) + 1.
\end{lstlisting}

In most Python interpreters, the underscore character \li{\_} is a variable with the value of the previous command's output, like the ANS button on many calculators.

\begin{lstlisting}
>>> 12 * 3
36
>>> _ / 4
9
\end{lstlisting}

Data comparisons like \li{<} and \li{>} act as expected.
The \li{==} operator checks for numerical equality and the \li{<=} and \li{>=} operators correspond to $\le$ and $\ge$, respectively.

To connect multiple boolean expressions, use the operators \li{and}, \li{or}, and \li{not}.\footnote{In many other programming languages, the \li{and}, \li{or}, and \li{not} operators are written as \li{&&}, \li{||}, and \li{!}, respectively. Python's convention is much more readable and does not require parentheses.}

\begin{lstlisting}
>>> 3 > 2
True
>>> 4 < 4
False
>>> 1 <= 1 or 2 > 3
True
>>> 7 == 7 and not 4 < 4
True
\end{lstlisting}

\subsection*{Variables} % -----------------------------------------------------

Variables are used to temporarily store data.
A \emph{single} equals sign assigns one or more values (on the right) to one or more variable names (on the left).
A \emph{double} equals sign is a comparison operator, as in the previous code block.

Unlike many programming languages, Python does not require a variable's data type to be specified upon initialization.

\begin{lstlisting}
>>> x = 12                          # Initialize x with the integer 12.
>>> y = 2 * 6                       # Initialize y with the integer 2*6 = 12.
>>> x == y                          # Compare the two variable values.
True

>>> x, y = 2, 4                     # Give both x and y new values in one line.
>>> x == y
False
\end{lstlisting}

\subsection*{Functions} % -----------------------------------------------------

To define a function, use the \li{def} keyword followed by the function name, a parenthesized list of formal parameters, and a colon.
Then indent the function body using exactly \textbf{four} spaces.

\begin{lstlisting}
# Indent the lines of a function with four spaces.
>>> def add(x, y):
...    result = x + y
...    return result
\end{lstlisting}

\begin{warn} % Python is picky about whitespace.
Many other languages use curly braces to delimit blocks, but Python uses whitespace indentation.
Mixing tabs and spaces confuses the interpreter and causes problems.
Most text editors will allow you to set the indentation type to spaces so you can use the tab key on your keyboard to insert four spaces.
\end{warn}

Functions are defined with \emph{parameters} and called with \emph{arguments}, though the terms are often used interchangeably.
Below, \li{width} and \li{height} are parameters for the function \li{area()}.
The values \li{2} and \li{5} are the arguments that are passed when calling the function.

\begin{lstlisting}
>>> def area(width, height):
...     return width * height
...
>>> area(2, 5)
10
\end{lstlisting}

It is also possible to specify default values for a function's formal parameters.
In the following example, the function \li{printer()} has three formal parameters, and the value of \li{c} defaults to 0.
That is, if it is not specified in the function call, the variable \li{c} will contain the value 0 when the function is executed.

\begin{lstlisting}
>>> def printer(a, b, c=0):
...    print a, b, c
...
>>> printer(1, 2, 3)                # Specify each parameter.
1 2 3
>>> printer(1, 2)                   # Specify only non-default parameters.
1 2 0
\end{lstlisting} % TODO Python 3: give the print statement parentheses

Arguments are passed to functions based on position or name, and positional arguments must be defined before named arguments.
For example, \li{a} and \li{b} must come before \li{c} in the function definition of \li{printer()}.
Examine the following code blocks demonstrating how positional and named arguments are used to call a function.

\begin{lstlisting}
# Try defining printer with a named argument before a positional argument.
>>> def printer(c=0, a, b):
...    print a, b, c
...
SyntaxError: non-default argument follows default argument
\end{lstlisting}

\begin{lstlisting}
# Correctly define printer() with the named argument after positional arguments.
>>> def printer(a, b, c=0):
...    print a, b, c
...

# Call printer() with 3 positional arguments.
>>> printer(2, 4, 6)
2 4 6

# Call printer() with 3 named arguments. Note the change in order.
>>> printer(b=3, c=5, a=7)
7 3 5

# Call printer() with 2 named arguments, excluding c.
>>> printer(b=1, a=2)
2 1 0

# Call printer() with 1 positional argument and 2 named arguments.
>>> printer(1, c=2, b=3)
1 3 2
\end{lstlisting}

Python functions can return more than one value.
Simply separate the values by commas after the \li{return} statement.

\begin{lstlisting}
>>> def arithmetic(a, b):
...     difference = a - b
...     product = a * b
...     return difference, product
...
>>> x, y = arithmetic(5, 2)         # x is the difference, y is the product.
>>> print x, y
3 10
\end{lstlisting}

\begin{info} % Note on the difference between print and return.
The functions \li{area()} and \li{printer()} defined above have an important difference: \li{area()} ends with a \li{return} statement, but \li{printer()} lacks a \li{return} statement.

The \li{return} statement instantly ends the function call and passes the return value to the function caller.
The \li{print} statement does nothing more than display the value of a given object (or objects) in the terminal.
% TODO: print is a function in Python 3.
A function without a return statement implicitly returns the Python constant \li{None}, which is similar to the special value \li{null} of many other languages.

\begin{lstlisting}
>>> x = area(2, 4)              # Calling area() doesn't print anything,
>>> y = printer(1, 2, 3)        # but calling printer() does.
1 2 3

>>> print(x)                    # However, x now contains a value,
8
>>> print(y)                    # whereas y only contains 'None'.
None
\end{lstlisting}
%
% If you have any intention of using the results of a function, always use a \li{return} statement.
% The returned value or values can then be stored in variables for later use.
\end{info}

\begin{problem} % Problem: write a very basic function.
In your Python file from Problem \ref{prob:helloWorld}, define a function called \li{sphere_volume()}.
This function should accept a single parameter \li{r} and return (not print) the volume of the sphere of radius \li{r}.
For now, use $3.14159$ as an approximation for $\pi$.

To test your function, call it under the \li{if __name__ == "__main__"} clause and print the returned value.
Run your file to see if your answer is what you expect it to be.
\end{problem}

\section*{Data Types} % =======================================================

\subsection*{Numerical Types} % -----------------------------------------------

Python has four numerical data types: \li{int}, \li{long},
\li{float}, and \li{complex}.
Each stores a different kind of number.
The built-in function \li{type()} identifies an object's data type.

\begin{lstlisting}
>>> type(3)                         # Numbers without periods are integers.
<<int>>

>>> type(3.0)                       # Floats have periods (3. is also a float).
<<float>>
\end{lstlisting}

% TODO: Update this section for Python 3.
Python has two types of division: integer and float.
% The \li{/} operator performs float division (fractional division), and the \li{//} operator performs integer division.
% Integer division rounds the result down to the next integer.
Integer division rounds the the result down to the next integer, and float division performs true, fractional division.
Both are executed  with the \li{/} operator.
When one or both of the operands are non-integers, \li{/} performs float division.
If both operands are integers, integer division is performed.

% TODO: for Python 3, change all operands to ints and use // for the second one
\begin{lstlisting}
>>> 15.0 / 4.0                      # Float division performs as expected.
3.75
>>> 15 / 4                          # Integer division rounds the result to 3.
3
\end{lstlisting}

\begin{warn} % TODO: This warning can be deleted for Python 3.
Using integer division unintentionally is an incredibly common programming mistake.
To avoid this, cast at least one operand as a float before dividing.
\begin{lstlisting}
>>> x, y = 7, 5
>>> x / y
1
>>> float(x) / y
1.4
>>> x / float(y)
1.4
\end{lstlisting}
\end{warn}

Python also supports complex number computations.
Use the letter $j$, not $i$, for the imaginary part.
\begin{lstlisting}
>>> x = complex(2,3)                # Create a complex number this way...
>>> y = 4 + 5j	                    # ...or this way, using j (not i).
>>> x.real                          # Access the real part of x.
2
>>> y.imag                          # Access the imaginary part of y.
5
\end{lstlisting}

\subsection*{Strings} % -------------------------------------------------------

In Python, strings are created with either single or double quotes.
To concatenate two or more strings, use the \li{+} operator between string variables or literals.
\begin{lstlisting}
>>> str1 = "Hello"
>>> str2 = 'world'
>>> my_string = str1 + " " + str2 + '!'
>>> my_string
<<'Hello world!'>>
\end{lstlisting}

We can access parts of a string using \emph{slicing}, indicated by square brackets \li{[ ]}.
Slicing syntax is \li{[start:stop:step]}.
The parameters \li{start} and \li{stop} default to the beginning and end of the string, respectively.
The parameter \li{step} defaults to 1.

\begin{lstlisting}
>>> my_string = "Hello world!"
>>> my_string[4]                # Indexing begins at 0.
<<'o'>>
>>> my_string[-1]               # Negative indices count backward from the end.
<<'!'>>

# Slice from the 0th to the 5th character (not including the 5th character).
>>> my_string[:5]
<<'Hello'>>

# Slice from the 6th character to the end.
>>> my_string[6:]
<<'world!'>>

# Slice from the 3rd to the 8th character (not including the 8th character).
>>> my_string[3:8]
<<'lo wo'>>

# Get every other character in the string.
>>> my_string[::2]
<<'Hlowrd'>>
\end{lstlisting}

\begin{problem} % Problem: Slicing with strings.
Write two new functions, called \li{first_half()} and \li{backward()}.
\begin{enumerate}
\item \li{first_half()} should accept a parameter and return the first half of it, excluding the middle character if there is an odd number of characters.
\\
(Hint: the built-in function \li{len()} returns the length of the input.)
\item The \li{backward()} function should accept a parameter and reverse the order of its characters using slicing, then return the reversed string.
\\
(Hint: The \li{step} parameter used in slicing can be negative.)
\end{enumerate}
Use IPython to quickly test your syntax for each function.
\end{problem}

\subsection*{Lists} % ---------------------------------------------------------

A Python \li{list} is created by enclosing comma-separated values with square brackets \li{[ ]}.
Entries of a list do \emph{not} have to be of the same type.
Access entries in a list with the same indexing or slicing operations used with strings.

\begin{lstlisting}
>>> my_list = ["Hello", 93.8, "world", 10]
>>> my_list
<<['Hello', 93.8, 'world!', 10]>>
>>> my_list[0]
<<'Hello'>>
>>> my_list[-2]
<<'world!'>>
>>> my_list[:2]
<<['Hello', 93.8]>>
\end{lstlisting}

Common list methods (functions) include \li{append()}, \li{insert()}, \li{remove()}, and \li{pop()}.
Consult IPython for details on each of these methods using object introspection.
\begin{lstlisting}
>>> my_list = [1, 2]                # Create a simple list of two integers.
>>> my_list.append(4)               # Append the integer 4 to the end.
>>> my_list.insert(2, 3)            # Insert 3 at location 2.
>>> my_list
[1, 2, 3, 4]
>>> my_list.remove(3)               # Remove 3 from the list.
>>> my_list.pop()                   # Remove (and return) the last entry.
4
>>> my_list
[1, 2]
\end{lstlisting}

Slicing is also very useful for replacing values in a list.

\begin{lstlisting}
>>> my_list = [10, 20, 30, 40, 50]
>>> my_list[0] = -1
>>> my_list[3:] = [8, 9]
[-1, 20, 30, 8, 9]
\end{lstlisting}

The \li{in} operator quickly checks if a given value is in a list (or a string).

\begin{lstlisting}
>>> my_list = [1, 2, 3, 4, 5]
>>> 2 in my_list
True
>>> 6 in my_list
False
\end{lstlisting}

\subsection*{Tuples} % --------------------------------------------------------

A Python \li{tuple} is an ordered collection of elements, created by enclosing comma-separated values with parentheses \li{(} and \li{)}.
Tuples are similar to lists, but they are much more rigid, have less built-in operations, and cannot be altered after creation.
Lists are therefore preferable for managing dynamic ordered collections of objects.

When multiple objects are returned in by a function, they are returned as a tuple.
For example, recall that the \li{arithmetic()} function returns two values.

\begin{lstlisting}
>>> x, y = arithmetic(5,2)                      # Get each value individually,
>>> print x, y
3 10
>>> both = arithmetic(5,2)                      # or get them both as a tuple.
>>> print(both)
(3, 10)
\end{lstlisting}

\begin{problem} % Problem: Simple list operations.
Write a function called \li{list_ops()}.
Define a list with the entries \li{"bear"}, \li{"ant"}, \li{"dog"}, and \li{"cat"}, in that order.
Then perform the following operations on the list:
\begin{enumerate}
\item Append \li{"eagle"}.
\item Replace the entry at index 2 with \li{"fox"}.
\item Remove the entry at index 1.
\item Sort the list in reverse alphabetical order.
\end{enumerate}
Return the resulting list.
\end{problem}

\subsection*{Sets} % ----------------------------------------------------------

A Python \li{set} is an unordered collection of distinct objects.
Objects can be added to or removed from a set after its creation.
Initialize a set with curly braces \li{\{ \}}, separating the values by commas, or use \li{set()} to create an empty set.

\begin{lstlisting}
# Initialize some sets. Note that repeats are not added.
>>> gym_members = {"Doe, John", "Doe, John", "Smith, Jane", "Brown, Bob"}
>>> print(gym_members)
<<set(['Smith, Jane', 'Brown, Bob', 'Doe, John'])>>

>>> gym_members.add("Lytle, Josh")      # Add an object to the set.
>>> gym_members.discard("Doe, John")    # Delete an object from the set.
>>> print(gym_members)
<<set(['Lytle, Josh', 'Smith, Jane', 'Brown, Bob'])>>
\end{lstlisting}

Like mathematical sets, Python sets have operations like union and intersection.
% difference, and symmetric difference.

\begin{lstlisting}
>>> gym_members.intersection({"Lytle, Josh", "Henriksen, Amelia" "Webb, Jared"})
<<set(['Lytle, Josh'])>>
\end{lstlisting}

\subsection*{Dictionaries} % --------------------------------------------------

% TODO: Dictionaries are a little weirder in Python 3. For example,
%   the keys() and values() methods are generators.
Like a set, a Python \li{dict} (dictionary) is an unordered data type.
A dictionary stores key-value pairs, called \emph{items}.
The values of a dictionary are indexed by its keys.
Dictionaries are initialized with curly braces, colons, and commas.
Use \li{dict()} or \li{\{\}} to create an empty dictionary.

\begin{lstlisting}
>>> my_dictionary = {"business": 4121, "math": 2061, "visual arts": 7321}
>>> print(my_dictionary["math"])
2061

# Add a value indexed by 'science' and delete the 'business' keypair.
>>> my_dictionary["science"] = 6284
>>> my_dictionary.pop("business")       # Use 'pop' or 'popitem' to remove.
4121
>>> print(my_dictionary)
<<{'visual arts': 7321, 'math': 2016, 'science': 6284}>>

# Display the keys and values.
>>> my_dictionary.keys()
<<['visual arts', 'math', 'science']>>
>>> my_dictionary.values()
<<[7321, 2016, 6284]>>
\end{lstlisting}

The keys of a dictionary must be \emph{immutable}, which means that they must be objects that cannot be modified after creation.
We will discuss mutability more thoroughly in the next lab.
% TODO: Reference the Standard Library lab.

\subsection*{Type Casting} % --------------------------------------------------

The names of each of Python's data types can be used as functions to cast a value as that type.
This is particularly useful with integers and floats.

\begin{lstlisting}
# Cast numerical values as different kinds of numerical values.
>>> x = int(3.0)
>>> y = float(3)
>>> z = complex(3)
>>> print x, y, z
3, 3.0, (3+0j)

# Cast a list as a set and vice versa.
>>> a = set([1, 2, 3, 4, 4])
>>> b = list({'a', 'a', 'b', 'b', 'c'})
>>> print(a)
<<set([1, 2, 3, 4])>>
>>> print(b)
<<['a', 'b', 'c']>>

# Cast other objects as strings.
>>> s = str(['a', str(1), 'b', float(2)])
>>> t = str(list(set([complex(float(3))]))
>>> s
<<"['a', '1', 'b', 2.0]">>
>>> t
<<'[(3+0j)]'>>

\end{lstlisting}

\section*{Control Flow Tools} % ===============================================

Control flow blocks dictate the order in which code is executed.
Python supports the usual control flow statements including \li{if} statements, \li{while} loops and \li{for} loops.

\subsection*{The If Statement} % ----------------------------------------------

An \li{if} statement executes the indented code \emph{if} (and only if) the given condition holds.
The \li{elif} statement is short for ``else if'' and can be used multiple times following an if statement, or not at all.
The \li{else} keyword may be used at most once at the end of a series of \li{if}/\li{elif} statements.

\begin{lstlisting}
>>> food = "bagel"
>>> if food == "apple":             # As with functions, the colon denotes
...     print("72 calories")        # the start of each code block.
... elif food == "banana" or food == "carrot":
...     print("105 calories")
... else:
...     print("calorie count unavailable")
...
calorie count unavailable
\end{lstlisting}

\begin{problem} % Problem: If statements and Pig Latin.
Write a function called \li{pig_latin()}.
Accept a parameter \li{word}, translate it into Pig Latin, then return the translation.
Specifically, if \li{word} starts with a vowel, add ``hay'' to the end; if \li{word} starts with a consonant, take the first character of \li{word}, move it to the end, and add ``ay''.
\\
(Hint: use the \li{in} operator to check if the first letter is a vowel.)
\end{problem}

\subsection*{The While Loop} % ------------------------------------------------

A \li{while} loop executes an indented block of code \emph{while} the given condition holds.

\begin{lstlisting}
>>> i = 0
>>> while i < 10:
...     print(i),
...     i = i+1
...
0 1 2 3 4 5 6 7 8 9
\end{lstlisting}

There are two additional useful statements to use inside of loops:
\begin{enumerate}
\item The \li{break} statement manually exits the loop, regardless of which iteration the loop is on or if the termination condition is met.
\item The \li{continue} statement skips the current iteration and returns to the top of the loop block if the termination condition is still not met.
\end{enumerate}

\begin{lstlisting}
>>> i = 0
>>> while True:
...    print(i),
...    i += 1
...    if i >= 10:
...        break                    # Exit the loop.
...
0 1 2 3 4 5 6 7 8 9

>>> i = 0
>>> while i < 10:
...     i += 1
...     if i % 3 == 0:
...         continue                # Skip multiples of 3.
...     print(i),
1 2 4 5 7 8 10
\end{lstlisting}

\subsection*{The For Loop} % --------------------------------------------------

A \li{for} loop iterates over the items in any \emph{iterable}.
Iterables include (but are not limited to) strings, lists, sets, and dictionaries.

\begin{lstlisting}
>>> colors = ["red", "green", "blue", "yellow"]
>>> for entry in colors:
...    print(entry + "!")
...
red!
green!
blue!
yellow!
\end{lstlisting}

The \li{break} and \li{continue} statements also work in for loops, but a \li{continue} in a for loop will automatically increment the index or item, whereas a \li{continue} in a while loop makes no automatic changes to any variable.

In addition, Python has some very useful built-in functions that can be used in conjunction with the \li{for} statement:
\begin{enumerate}
\item \li{range(start, stop, step)}: Produces a list of integers, following slicing syntax. If only one argument is specified, it produces a list of integers from 0 to the argument, incrementing by one.
In Python 2.7, we use \li{xrange()} more often because it is faster than \li{range()} and does not explicitly create a list in memory.
\item \li{zip()}: Joins multiple sequences so they can be iterated over simultaneously.
\item \li{enumerate()}: Yields both a count and a value from the sequence. Typically used to get both the index of an item and the actual item simultaneously.
\item \li{sorted()}: Returns a new list of sorted items that can then be used for iteration.
\item \li{reversed()}: Reverses the order of the iteration.
\end{enumerate}
% TODO: get rid of the xrange() note for Python 3.

\begin{lstlisting}
>>> vowels = "aeiou"
>>> colors = ["red", "yellow", "white", "blue", "purple"]
>>> for i in xrange(5):
...     print i, vowels[i], colors[i]
...
0 a red
1 e yellow
2 i white
3 o blue
4 u purple

>>> for letter, word in zip(vowels, colors):
...     print letter, word
...
a red
e yellow
i white
o blue
u purple

>>> for i, color in enumerate(colors):
...     print i, color
...
0 red
1 yellow
2 white
3 blue
4 purple

>>> for item in sorted(colors):
...     print item,
...
blue purple red white yellow

>>> for item in reversed(colors):
...     print item,
...
yellow white red purple blue

# Range arguments follow slicing syntax.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(4, 8)
[4, 5, 6, 7]
>>> range(2, 20, 3)
[2, 5, 8, 11, 14, 17]
\end{lstlisting}

\begin{problem} % Problem: large palindromic number (Project Euler #4)
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is $9009 = 91 \times 99.$\\
Write a function called \li{palindrome()} that finds and returns the largest palindromic number made from the product of two 3-digit numbers.

This problem originates from \url{https://projecteuler.net}, an excellent resource for math-related coding problems.
\end{problem}

\subsection*{List Comprehension} % --------------------------------------------

A \emph{list comprehension} uses for loop syntax between square brackets to create a list.
This is a powerful, efficient way to build lists.
The code is concise and runs quickly.

\begin{lstlisting}
>>> [float(n) for n in range(5)]
[0.0, 1.0, 2.0, 3.0, 4.0]
\end{lstlisting}

List comprehensions can be thought of as ``inverted loops'', meaning that the body of the loop comes before the looping condition.
The following loop and list comprehension produce the same list, but the list comprehension takes only about two-thirds the time to execute.

\begin{lstlisting}
>>> loop_output = []
>>> for i in range(5):
...    loop_output.append(i**2)
...
>>> list_output = [i**2 for i in range(5)]
\end{lstlisting}

Tuple, set, and dictionary comprehensions can be done in the same way as list comprehensions by using the appropriate style of brackets on the end.

\begin{lstlisting}
>>> colors = ["red", "blue", "yellow"]
>>> {c[0]:c for c in colors}
<<{'y': 'yellow', 'r': 'red', 'b': 'blue'}>>

>>> {"bright " + c for c in colors}
<<set(['bright blue', 'bright red', 'bright yellow'])>>
\end{lstlisting}

\begin{problem} % Problem: the alternating harmonic series.
The alternating harmonic series is given by the following:
\[\sum_{n=1}^\infty \frac{(-1)^{(n+1)}}{n} = 1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} + \frac{1}{5} - \ldots = \ln(2)\]

Write a function called \li{alt_harmonic()}.
Use a list comprehension to quickly compute the first $n$ terms of this series, given the parameter \li{n}.
The sum of the first 500,000 terms of this series approximates $\ln(2)$ to five decimal places.
\\
(Hint: consider using Python's built-in \li{sum()} function.)
\end{problem}

% \section*{Conclusion}
Refer back to this and other introductory labs often as you continue getting used to Python syntax and data types.
As you continue your study of Python, we strongly recommend the following readings:
\begin{enumerate}
\item Chapters 3, 4, and 5 of the Official Python Tutorial \\
        (\url{http://docs.python.org/2.7/tutorial/introduction.html}).
\item Section 1.2 of the SciPy Lecture Notes\\
        (\url{http://scipy-lectures.github.io/}).
\item PEP8 - Python Style Guide \\
        (\url{http://www.python.org/dev/peps/pep-0008/}).
\end{enumerate}

\newpage

\section*{Additional Material} % ==============================================

\subsection*{Lambda Functions} % ----------------------------------------------

The keyword \li{lambda} is a shortcut for creating one-line functions.
For example, we can create Python functions for the polynomials $f(x) = 6x^3 + 4x^2 - x + 3$ and $g(x,y,z) = x + y^2 - z^3$ using only a single line for each definition.

\begin{lstlisting}
>>> f = lambda x: 6*x**3 + 4*x**2 - x + 3
>>> g = lambda x, y, z: x + y**2 - z**3
\end{lstlisting}

\subsection*{Generalized Function Input} % ------------------------------------

On rare occasion, it is necessary to define a function without knowing exactly what the parameters will be like or how many there will be.
This is usually done by defining the function with the parameters \li{*args} and \li{**kwargs}.
Here \li{*args} is a list of the positional arguments and \li{**kwargs} is a dictionary mapping the keywords to their argument.
This is the most general form of a function definition.

\begin{lstlisting}
>>> def report(*args, **kwargs):
...     for i, arg in enumerate(args):
...         print "Argument " + str(i) + ":", arg
...     for key in kwargs:
...         print "Keyword", key, "->", kwargs[key]
...
>>> report("TK", 421, exceptional=False, missing=True)
Argument 0: TK
Argument 1: 421
Keyword missing -> True
Keyword exceptional -> False

>>> average = lambda *args: sum(args) / float(len(args))
>>> average(4, 5, 6)
5.0
>>> average(1, 2, 3, 4, 5, 6, 7, 8, 9)
5.0
\end{lstlisting}

See \url{https://docs.python.org/2.7/tutorial/controlflow.html} for more on this topic.

\subsection*{Function Decorators} % -------------------------------------------

A \emph{function decorator} is a special function that ``wraps'' other functions.
It takes in a function as input, then usually pre-processes its inputs or post-processes its outputs.

\begin{lstlisting}
>>> def typewriter(func):
...     """Decorator for printing the type of output a function returns"""
...     def wrapper(*args, **kwargs):
...         output = func(*args, **kwargs)      # Call the decorated function.
...         print "output type:", type(output)  # Do something before finishing.
...         return output                       # Return the function output.
...     return wrapper
\end{lstlisting}

The outer function, \li{typewriter()}, returns the new function \li{wrapper()}.
Since \li{wrapper()} accepts \li{*args} and \li{**kwargs} as arguments, the input function \li{func()} could accepts any number of positional or keyword arguments.

Apply a decorator to a function by tagging the function's definition with an \textbf{@} symbol and the decorator name.

\begin{lstlisting}
>>> @typewriter
... def combine(a, b, c):
...     return a*b/float(c)
...
\end{lstlisting}

Placing the \textbf{@} tag above the definition is equivalent to adding the following line of code after the function definition:

\begin{lstlisting}
>>> combine = typewriter(combine)
\end{lstlisting}

Now when we call \li{combine()}, we are really calling \li{wrapper()}, which then calls the originally defined \li{combine()}.

\begin{lstlisting}
>>> combine(3, 4, 6)
<<output type: <type 'float'>>>
2.0
\end{lstlisting}

Function decorators can also accept arguments.
This requires another level of nesting: the outermost function must define and return a decorator that defines and returns a wrapper.

\begin{lstlisting}
>>> def repeat(times=2):
...     """Decorator for calling a function several times."""
...     def decorator(func):
...         def wrapper(*args, **kwargs):
...             for _ in xrange(times):
...                 output = func(*args, **kwargs)
...             return output
...         return wrapper
...     return decorator
...
>>> @repeat(times=3)
... def hello_world():
...     print "Hello, world!"
...
>>> hello_world()
Hello, world!
Hello, world!
Hello, world!
\end{lstlisting}

See \url{https://www.python.org/dev/peps/pep-0318/} for more details.

\begin{comment} % Overkill, since they don't know how to import yet.
Decorating a function can overwrite the original function's \emph{docstring}, the string directly below the \li{def} statement that gives a description of the function.
To remedy this problem, the \li{functools} module includes a decorator for wrappers.

\begin{lstlisting}
>>> from functools import wraps

>>> def typewriter(func):
...     """Decorator for printing the type of output a function returns"""
...     @wraps(func)                            # Add the @wraps tag.
...     def wrapper(*args, **kwargs):
...         output = func(*args, **kwargs)
...         print "output type:", type(output)
...         return output
...     return wrapper
...
>>> def repeat(times=2):
...     """Decorator for calling a function several times."""
...     def decorator(func):
...         @wraps(func)                        # Add the @wraps tag.
...         def wrapper(*args, **kwargs):
...             for _ in xrange(times):
...                 output = func(*args, **kwargs)
...             return output
...         return wrapper
...     return decorator
\end{lstlisting}
\end{comment}


\section{Conclusion}
In this research, our team explored the intuition, implementation, and evaluation of three search strategies for agents in partially-observable (specifically eight-connected) environments. These search strategies were integrated with the Pacman domain, which is a representative application for robot navigation search tasks.
%The metrics for evaluation were the final path length, number of nodes expanded from the search queue, memory use, and runtime.
After evaluating the three search strategies (in addition to A*), the group confirmed that the D* Lite strategy is the optimal re-planning strategy. The D* Lite builds off the theoretical foundation of LPA*, but makes signification optimizations to the implementation that allow it to dominate in terms of performance. The NRA* strategy is competitive in terms of path length, but its simple strategy hurts its performance in all other categories. When a totally observable environment is not practical, D* Lite is the best search strategy of the assessed algorithms.


\documentclass{article}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{verbatim}
\usepackage{enumerate}
\usepackage{comment}

\newtheorem{thm}{Theorem}[section]
\newtheorem{lem}[thm]{Lemma}

\newtheorem{defn}[thm]{Definition}
\newtheorem{ex}[thm]{Example}
\newtheorem{xca}[thm]{Exercise}

\newcommand{\sii} {\sigma_{-1}}

\title%[Prime Factors of an Odd Perfect Number]
    {New techniques for bounds on the total number of Prime Factors of an
     Odd Perfect Number}
\author{Kevin G. Hare
\footnote{Department of Pure Mathematics, University of Waterloo, Waterloo,
    Ontario, Canada,  N2L 3G1, kghare@math.uwaterloo.ca}}

%\email{kghare@math.uwaterloo.ca}

%\subjclass{Primary 11A25, 11Y70}

%\keywords{Perfect Numbers, Divisor function, Prime numbers}

\date{April 12, 2006}

\begin{document}
\maketitle
\thanks{Research of K.G. Hare supported, in part by NSERC of Canada.}

\begin{abstract}
Let $\sigma(n)$ denote the sum of the positive divisors of $n$.
We say that $n$ is perfect if $\sigma(n) = 2 n$.
Currently there are no known odd perfect numbers.
It is known that if an odd perfect number exists, then it must be
    of the form $N = p^\alpha \prod_{j=1}^k q_j^{2 \beta_j}$, where
    $p, q_1, \cdots, q_k$ are distinct primes and
    $p \equiv \alpha\equiv 1 \pmod{4}$.
Define the total number of prime factors of $N$ as
    $\Omega(N) := \alpha + 2 \sum_{j=1}^k \beta_j$.
Sayers showed that $\Omega(N) \geq 29$.
This was later extended by Iannucci and Sorli to show that $\Omega(N) \geq 37$.
This was extended by the author to show that $\Omega(N) \geq 47$.
Using an idea of Carl Pomerance this paper extends these results.
The current new bound is $\Omega(N) \geq 75$.
\end{abstract}

\section{Introduction}

Here and throughout, $n$ is any natural number, and $N$ is a hypothetical
    odd perfect number.
Let $\sigma(n)$ denote the sum of the positive divisors of $n$.
We say that $n$ is perfect if $\sigma(n) = 2 n$.
It is known that if $\sigma(n) = 2n $ and $n$ is even, then
    $n = 2^{k-1} (2^k-1)$ where $2^k-1$ is a Mersenne prime.
Currently there are no known odd perfect numbers.
First shown by Euler, it is well known that if
    an odd perfect number exists, then it must be
    of the form
\begin{eqnarray}
N = p^\alpha \prod_{j=1}^k q_j^{2 \beta_j},
\label{eq:odd}
\end{eqnarray} where
    $p, q_1, \cdots, q_k$ are distinct primes and
    $p \equiv \alpha\equiv 1 \pmod{4}$.

Based on (\ref{eq:odd}) we define the total number of prime factors
    of an odd perfect number as
\begin{eqnarray}
\Omega(N) := \alpha + 2 \sum_{j=1}^k \beta_j,
\label{eq:Omega}
\end{eqnarray}
and we define the total number of distinct prime factors of $N$ as
    \begin{eqnarray} \omega(N) := 1 + k. \label{eq:omega} \end{eqnarray}
A number of bounds have been derived for $\Omega(N)$.
Cohen showed that $\Omega(N) \geq 23$ \cite{Cohen82}.
Sayers showed that $\Omega(N) \geq 29$ \cite{Sayers86}.
Iannucci and Sorli showed that $\Omega(N) \geq 37$ \cite{IannucciSorli03}.
The author extended this to give $\Omega(N) \geq 47$ \cite{Hare05a}.
This paper extends this result to give

\begin{thm} If $N$ is an odd perfect number, then $\Omega(N) \geq 75$.
\label{thm:main}
\end{thm}

In proving these results, the methods of \cite{Hare05a} were modified and
    applied.
For an introduction and explanation of the algorithm we refer the
    interested reader there.

To some extent, with the modification of the algorithm given here,
    the calculation becomes a matter of book-keeping.
In \cite{Hare05a} there was a specific road-block which prevented any
    further calculation.
This is no longer the case.
With enough computational power, we could get to any number, although the
    amount of time required appears to be exponential, more than
    doubling every time we increase the bound by 4 (see Table \ref{tab:times}).
So it is just a matter of how much computer power to dedicate
    towards the problem.
The choice of 75 in the theorem was motiviated by the fact that
    it was sufficiently large to demonstrate
    the improvement in the algorithm while still remaining reasonable
    with respect to computation time.
\begin{table}
\caption{Timing results for algorithm}
\label{tab:times}
\begin{tabular}{|l|l|l|}
\hline
Result & Time to Prove result & Lines to Prove result\\
\hline
$\Omega(N) \geq 69$ &
%                      185 hours, 23 minutes 40 seconds \\
                      7 days, 17 hours, 23 minutes, 50 seconds &
%92:52:18.43 + 92:31:21.93  %%% ALTERED FOR 11
%92+1/60*52+1/60^2*18.43 + 92+1/60*31+1/60^2*21.93
%185.3945445
25,234,392 lines \\  %% ALTERED FOR 11
$\Omega(N) \geq 71$ &
%                      262 hours, 17 minutes, 58 seconds  \\
                      10 days, 22 hours, 18 minutes, 4 seconds &
%131:23:12.35 + 130:54:45.66            %% ALTERED FOR 11
%131+1/60*23+1/60^2*12.35 + 130+1/60*54+1/60^2*45.66;
% 262.2994472
37,752,127 lines \\  %% ALTERED FOR 11
$\Omega(N) \geq 73$ &
%                     409 hours, 28 minutes, 28 seconds \\
                       17 days, 1 hour, 28 minutes, 36 seconds &
%148:10:52.41 + 150:33:25.34a + 2:30:02.21 + 1:57:45.35   %% ALTERED FOR 11
%+ 51:51:06.36 + 45:08:04.90 + 4:19:32.38 + 4:57:39.10
% 409.4744445 total
56,352,999 lines \\   %% ALTERED FOR 11
$\Omega(N) \geq 75$ &
%
                       25 days, 3 hours, 17 minutes, 35 seconds &  %% ALTERED 11
% 603.290811
83,902,264 lines \\    %% ALTERED 11
%Time.out1
%455.276u 566.316s 42:12:24.80 0.6%      0+0k 0+0io 3pf+0w
%Time.out2
%1637.643u 2082.795s 152:23:21.91 0.6%   0+0k 0+0io 0pf+0w
%Time.out3
%906.597u 1191.579s 79:33:00.86 0.7%     0+0k 0+0io 0pf+0w
%Time.out4
%809.237u 1013.459s 74:05:35.76 0.6%     0+0k 0+0io 2pf+0w
%Time.out5
%927.325u 1160.900s 75:26:58.77 0.7%     0+0k 0+0io 0pf+0w
%Time.out6
%1234.393u 1549.627s 90:21:22.59 0.8%    0+0k 0+0io 5pf+0w
%Time.out7
%1172.815u 1461.271s 89:14:42.23 0.8%    0+0k 0+0io 0pf+0w

%42 + 1/60.*12+1/60.^2*24.80 +
%152 + 1/60.*23+1/60.^2*21.91+
%79 + 1/60.*33+1/60.^2*00.86 +
%74 + 1/60.*05+1/60.^2*35.76 +
%75 + 1/60.*26+1/60.^2*58.77 +
%90 + 1/60*21+1/60^2*22.59 +
%89 + 1/60*14+1/60^2*42.23;

\hline
\end{tabular}
\end{table}

%Between 69 and 71, there is an increase by a factor of about 1.414.
%Between 71 and 73, there is an increase by a factor of about 1.561.
%Between 73 and 75, there is an increase by a factor of about 1.473.
%
%Based on these numbers, we could estimate that the amount of time to compute
%    up to 101 would be over 11 years of CPU time.
%100243.3726

\section{Definitions and Notation}

For any prime $p$, by $p^a\parallel N$ we mean $p^a |N$ and $p^{a+1}\nmid N$.
By $p^a\nparallel N$ we mean either $p^{a+1}| N$ or $p^a \nmid N$.
We define the function $\sii(n)$ as
\begin{eqnarray}
\sii(n) := \sum_{d|n}d^{-1} = \frac{\sigma(n)}{n}.
\label{eq:sii}
\end{eqnarray}

A number of simple results concerning $\sii(n)$ are summarized below.
\begin{lem}
\label{lem:sii}
Let $n$ be any natural number.
Then
\begin{itemize}
\item $\sii(n)$ is a multiplicative function,
    i.e. if $(n, m) = 1$ then $\sii(n\cdot m) = \sii(n) \sii(m)$,
\item $\sii(n) > 1$ for all $n > 1$,
\item $\sii(n) = 2$ if and only if $n$ is perfect,
\item $\frac{p+1}{p} \leq \sii(p^a) < \sii(p^{a+1}) < \frac{p}{p-1}$
    for all primes $p$ and integers $a \geq 1$.
\end{itemize}
\end{lem}

There are a number of useful results concerning $\omega(N)$, the total number
    of distinct prime factors.
\begin{lem}
\label{lem:exclude}
Let $N$ be an odd perfect number.
Then
\begin{itemize}
\item $\omega(N) \geq 8$ \cite{Chein79, Hagis80}.
\item If $3 \nmid N$ then $\omega(N) \geq 11$ \cite{Hagis83, Kishore83}.
\item If $3 \nmid N$ and $5 \nmid N$ then $\omega(N) \geq 15$ \cite{Norton61}.
\item If $3 \nmid N$, $5 \nmid N$ and $7 \nmid N$ then
    $\omega(N) \geq 27$ \cite{Norton61}.
\item If $3 \nmid N$, $5 \nmid N$, $7 \nmid N$, and $11 \nmid N$,
    then $\omega(N) \geq 41$ and hence $\Omega(N) \geq 81$.
\end{itemize}
\end{lem}

The last result is probably not the tightest possible, but it is sufficient
    for our purposes.
It follows immediately by noticing that the product $\prod \frac{p_i}{p_i-1}$
    for the first 40 primes strictly greater than 11 is less than 2.
So, for our purposes it suffices to assume that $\Omega(N) \leq 73$ and
    show as a result that $3\nmid N$, $5\nmid N$, $7\nmid N$ and
    $11 \nmid N$, which gives the desired contradiction.

This last result is well known in the literature.
We use the version given in \cite{CohenSorli03}.  \nocite{Pomerance74}

\begin{lem}[Cohen, Sorli \cite{CohenSorli03}] \label{lem:Carl}
    Let
    \[N = p_1^{\alpha_1} p_2^{\alpha_2} \cdots p_k^{\alpha_k}
          q_1^{\beta_1} q_2^{\beta_2} \cdots q_r^{\beta_r} \]
    be an odd perfect number, where the $p_i$ and $q_j$ are distinct primes with
    the $p_i$ and $\alpha_i$ known.
    Define \[ S := \sii\left(p_1^{\alpha_1} \cdots p_k^{\alpha_k}\right). \]

    Then we have,
    \[ \min q_i < \frac{2 + S (r-1)}{2-S}\]
    moreover, if $r \geq 3$ we have the tighter bound
    \[ \min q_i < \frac{8 + 2 S^2 (r-1)}{4 - S^2}. \]
    Furthermore we have the lower bound
    \[ \min q_i \geq \max\left(3, \frac{S}{2 - S}\right). \]
\end{lem}

\begin{proof}
Taking $h = \sii$, $\mu = 1$, $h(\lambda) = S$ and $w = r$, this follows
    directly from equations (2.3), (4.1) and (2.4) of \cite{CohenSorli03}.
\end{proof}

\begin{ex}
Assume that
    $N = 3^2\cdot 13^4\cdot 30941 \cdot q_1^{\beta_1} \cdot q_2^{\beta_2}$
    is an odd perfect number.
Then by Lemma \ref{lem:Carl} we can assume that $3.5962 < q_1 < 8.1924$.
So in, particular we can assume that $q_1 = 5$ or $7$.
\end{ex}

\section{The Algorithm and Proof of Theorem \ref{thm:main}}%and \ref{thm:equiv}}

Suppose $N = p^{\alpha}\prod q_i^{2 \beta_i}$, as before.
To prove that $\Omega(N) \geq K$, we assume that $\Omega(N) =
    \alpha + \sum 2 \beta_i \leq K-2$ and obtain a contradiction
    for every combination of $\alpha$ and $\beta_i$.
As mentioned above, it suffices to assume that $\Omega(N) \leq 73$ and
    show as a result that $3\nmid N$, $5\nmid N$, $7\nmid N$ and
    $11 \nmid N$ to obtain our contradiction.

There are two main modifications to the algorithm in \cite{Hare05a}.
First, as opposed to doing every individual case of $[\alpha, \beta_1, \cdots
    \beta_k]$ where $\Omega(N) = \alpha + 2 \sum \beta_i$, we combine them into
    one test.
For example, if we want to prove $3 \nmid N$, where $\Omega(N) \leq 57$,
    we look at the possibilities
    $3^2\parallel N, 3^4 \parallel N, \cdots, 3^{56}\parallel N$, and recurse.
(Actually, for any power $\beta \geq 46$, we have that $3^\beta\parallel N$
    will give
    rise to a contradiction as $\omega(N) \geq 8$.)
This was done because the original method of looking at every possible
    partition of $N$ caused a large amount of duplicated effort in the
    automated proofs.
By combining these tests together we speed up the calculation, and
    significantly reduce the storage space requirements.

It should be pointed out that this modification introduced a new means of
    obtaining a contradiction,
    which in \cite{Hare05a} was taken care of in the choice of
    partitions.
This is listed as contradiction (\ref{cont:omega}) below.

The second modification to the algorithm is the use of Lemma \ref{lem:Carl}.
If the algorithm finds itself in a situation where previously it could not
    continue, because it did not know the factorization of some very
    large number, we then compute
    $\frac{2 + S (r-1)}{2-S}$ or $\frac{8 + 2 S^2 (r-1)}{4 - S^2}$
    as approriate, from Lemma \ref{lem:Carl}.
If this upper bound is reasonably small, then we run though all of the
    possibilities of $q_i$ prime less than this upper bound,
   (and greater than the lower bound),
    as a means of continuing the calculation.
Here ``small'' was defined as anything less than 100000.
This was sufficient for these calculations.
It should also be noted that the primes are checked in order.
After proving that a particular prime (say $p$) causes a contradiction,
    it is assumed that it cannot occur as a factor for the next cases
    being checked, within the same sub-branch.
(For example, with an abuse of notation, we assume $p^0 \parallel N$, and
    would arrive at contradiction (\ref{cont:xs=p}) if a factor of $p$
    occurs.)

There are five contradictions that we test for.
The first four are from the original algorithm, or the equivalent variation
    needed to combine all tests into one test.
The last contradiction is commented on above.
\begin{enumerate}
\item Excess of a given prime: \label{cont:xs=p}

    By assuming $p^k \parallel N $ we derive the contradiction that
     $p^{k+1} | N$.
    This is denoted in the output by ``xs=$p$'' where $p$ is the prime in
    question.

    For example, if we wish to show that $269 \nparallel N$ assuming
        that $3^2 \parallel N$, we first assume that $269 \parallel N$.
    Then we see that $3^3$ and $5$ must divide $N$ (the factors of
        $\sigma(269)$), which contradicts $3^2 \parallel N$.
    In this case, this would be denoted in the output by ``xs=3''.

\item Excess of the number of primes: \label{cont:xs=prime}

    We have more primes than we are allowed, given the restrictions on
    $\Omega(N)$ and the fact that only one prime can have an exponent of 1.
    This is denoted in the output by ``xs=prime''.
    Incompletely factored numbers are counted as contributing
    two primes, even though this may be too low.
    Incompletely factors numbers are known not to be perfect powers.
    Furthermore, incompletely factored numbers are checked to ensure that
    they are co-prime with each other, as well as other primes within
    the relevant branch.

    For example, if we wish to show that $26881^{14} \nparallel N$
    when $\Omega(N) \leq 19$, we would start with the
    assumption that $26881^{14} \parallel N$.
    This would imply that
    3, 5, 31, 43, 3368729516337631, 6717545999551, 5601667,
    8265157321, 18691, 145861 and 1801 must all divide $N$, as they
    are the factors of $\sigma(26881^{14})$.
    We see that the factorization of $N$ that would maximize the number of prime
        factors would be $N = 26881^{14} \cdot p_1 \cdot p_2^2 \cdot p_3^2$.
    As this has at most 3 primes unassigned, and there are 11 unassigned prime
        factors of $\sigma(26881^{14})$, we get a contradiction.

\item Partition cannot be satisfied: \label{cont:part}

    The factors that must divide $N$, along with their powers, cannot satisfy
        the partition.
    In the original algorithm there were a number of different ways that
        this contradiction could occur.
    Given that in this implementation, there are not specific exponent
        bounds assigned before starting to recurse, this can only
        occur in one way.
    This is if, of the remaining primes, one of them has to be the special
        prime (with an exponent $a \equiv 1 \pmod{4}$), and
        of all of the remaining primes, all of them are such that
        $p \not\equiv 1 \pmod{4}$.
    This is denoted in the output by ``exponent bounds exceeded''.

    For example, if we wished to show that $3^{10} \nparallel N$ when
         $\Omega(N) \leq 13$, we would start by assuming that
         $3^{10} \parallel N$.
    This implies that $23$ and $3851$ both must divide $N$, (the
         two factors of $\sigma(3^{10})$).
    At this point, as $\Omega(N) \leq 13$, we must have one of these
        two primes being the special prime to get either
        $N = 3^{10} \cdot 23 \cdot 3851^2$ or
        $N = 3^{10} \cdot 23^2 \cdot 3851$.
    But we notice that $23 \equiv 3851 \equiv 3 \pmod{4}$, hence
        we see that neither of 23 or 3851 could be the special prime,
        hence a contradiction.

\item Excess of $\sii$:

    A lower bound for $\sii(N)$ using known factors gives
    $\sii(N) > 2$.
    This is denoted in the code by ``S= number'', giving a floating
        point approximation for a lower bound of $\sii(N)$.
    (The code uses exact rational arithmetic to check the inequality.)

    For example, if we wished to show that $90089 \nparallel N$ we would
        start by assuming that $90089 \parallel N$.
    This implies that $3^2, 5, 7, 11$ and $13$ all divide $N$
        (the factors of $\sigma(90089)$).
    This implies that
        \begin{eqnarray*}
      \sii(N) &\geq & \frac{\sigma(3^2)}{3^2}\times
                         \frac{\sigma(5)}{5}\times
                         \frac{\sigma(7)}{7}\times
                         \frac{\sigma(11)}{11}\times
                         \frac{\sigma(13)}{13}\times
                         \frac{\sigma(90089)}{90089} \\
                  & \approx& 2.327298560 \\ &>& 2
        \end{eqnarray*}
        which is the desired contradiction.
    This is denoted in the output as ``S=2.327298560''.

\item $\omega$-bound exceeded. \label{cont:omega}

    Given the choices of primes and exponents made so far, it is not
        possible to satisfy Lemma \ref{lem:exclude}.

    For example, if we were trying to prove that $3^{46}\nparallel N$ where
        $\Omega(N) \leq 57$ we would start by assuming that
        $3^{46} \parallel N$.
    We notice that $\omega(N)$ is maximized by writting
        $N = 3^{46}\cdot p_1 \cdot p_2^2 \cdot p_3^2
                   \cdot p_4^2\cdot p_5^2$, and hence
        $\omega(N) \leq 7$.
    This contradicts $\omega(N) \geq 8$ from Lemma \ref{lem:exclude}.
    This is denoted as ``violate omega bound''.
\end{enumerate}

In Table \ref{tab:ex} an example of running this code is given, and
    the five possible exceptions.
These exceptions are indicated by the numbers (1) through (5) on the
    left hand side of the page.
The use of Lemma \ref{lem:Carl} is indicated with a star, $(*)$, on the
    left hand side of the page.
Minor formatting has been done to the output, to avoid lines with more
    than 80 characters.
(The output of the actual code would have put the line starting with
    ``It would be nice to know'' all on one line.)

As was done in \cite{Hare05a}, numbers were factored using the
    ifactor command in MAPLE, with the easy option specified.
If easy factors were not found, then the number was checked in a
    hints database (which currently contains over 700 completely, or
    partially factored numbers).

\begin{table}
\caption{Parts of the proof that $\Omega(N) \geq 75$}
\label{tab:ex}
%\verbatiminput{OUTPUT}
\begin{verbatim}
3^6  => 1093
  1093  => 2 547
    547^2  => 3 163 613
      163^2  => 3 7 19 67
        7^2  => 3 19
          19^2  => 3 127
(1)         67^2  => 3 7^2 31  xs=7
    ....
    547^18  => 19256021298645399074821884828797791764310604858317
      19256021298645399074821884828797791764310604858317^2  => 3
                  3081128010533825683 143739375561423904832226409
                  279078490021828554466220167808251320188667868911072727
      ....
      19256021298645399074821884828797791764310604858317^36  => c_1775
        It would be nice to know more factors of
                   sigma(19256021298645399074821884828797791764310604858317^36)
(*)     By Cohen/Sorli's argument, N has a prime factor between 3 and 18
        Trying each one in turn
        Next prime to try is 5
        5^2  => 31
        ....
(5)     17^8  => 19 307 1270657  violate omega bound
        Finished Cohen/Sorli's argument
  ....
  1093^2  => 3 398581
    398581  => 2 17 19 617
    ....
    398581^4  => 5 1866871 2703853428809791
      5  => 2 3
      ....
      5^10  => 12207031
        1866871^2  => 3 19 331 184725139
(4)       19^2  => 3 127  S=2.001549342
          ....
          19^16  => 3044803 99995282631947
            331^2  => 3 7 5233  S=2.310779791
            ...
            331^18  => 282349518620419 8080363351283173500917653281271
(3)           3044803^2  => 3 3090276117871   exponent bounds exceeded
(2)           3044803^4  => 11 631 12382686952067349629581  xs=prime
....
\end{verbatim}
\end{table}

\section{Comments and Acknowledgments}

In \cite{Hare05a} it was said that there were three numbers
    that needed to be factored, without which the algorithm in
    \cite{Hare05a} could not be continued.
Using the methods of Carl Pomerance, this problem was avoided.
At this point, the calculation was terminated not by a particular
    obstruction, but instead because 75 was esthetically pleasing.
Further, 75 was sufficiently large to demonstrate
    the improvement in the algorithm while still remaining reasonable
    with respect to computation time.
The purpose of this paper was to demonstrate a new technique to
    extend this bound, and not necessarily to extend this bound to the
    farthest extent possible.

I would like to thank Phil Carmody, Christophe Clavier, Don Leclair
    Paul Leyland, Tom Womack, Paul Zimmermann, and the people at
    {\tt http://mersenneforum.org} who helped provide factorizations
    for the numbers
    \begin{itemize}
      \item $\sigma(\sigma(547^{18})^{16})$,  a 789-digit number,
      with a factor of: \[ 1520135498523547561326750429418247. \]
      \item $\sigma(\sigma(3221^{12})^{22})$, a 927-digit number,
      with a factor of: \[ 46973400441039677515399714233826061. \]
    \end{itemize}
    which I had listed in \cite{Hare05a} as obstructions to my
    calculations.
This information was included in the hints database used by the code.

I am also indebted to Carl Pomerance for bringing a weaker form of
    Lemma \ref{lem:Carl} to my attention \cite{Pomerance74},
    and more importantly how this could be applied to
    improve the existing bound.
I would also like to thank the unknown referee for the reference
    \cite{CohenSorli03}, which replaced Lemma 2.3, as well as many other
    useful suggestions and comments.

Also, I would like to acknowledge William Lipp, the creator of
   www.oddperfect.org, for providing some additional factorizations.
(The website www.oddperfect.org is a website, which when complete, will
    co-ordinate an attack to improve the lower bound on odd perfect numbers,
    of $N \geq 10^{300}$,
    given by \cite{BrentCohenTeRiele91}.)

%\bibliographystyle{amsplain}
%\bibliography{paper}

\providecommand{\bysame}{\leavevmode\hbox to3em{\hrulefill}\thinspace}
\providecommand{\MR}{\relax\ifhmode\unskip\space\fi MR }
% \MRhref is called by the amsart/book/proc definition of \MR.
\providecommand{\MRhref}[2]{%
  \href{http://www.ams.org/mathscinet-getitem?mr=#1}{#2}
}
\providecommand{\href}[2]{#2}
\begin{thebibliography}{10}

\bibitem{BrentCohenTeRiele91}
R.~P. Brent, G.~L. Cohen, and H.~J.~J. te~Riele, \emph{Improved techniques for
  lower bounds for odd perfect numbers}, Math. Comp. \textbf{57} (1991),
  no.~196, 857--868. \MR{1094940}

\bibitem{Chein79}
E.~Z. Chein, \emph{An odd perfect number has at least 8 prime factors}, Ph.D.
  thesis, Pennsylvania State University, 1979.

\bibitem{Cohen82}
Graeme~L. Cohen, \emph{Generalised quasiperfect numbers}, Ph.D. thesis,
  University of New South Wales, 1982.

\bibitem{CohenSorli03}
Graeme~L. Cohen and Ronald~M. Sorli, \emph{On the number of distinct prime
  factors of an odd perfect number}, J. Discrete Algorithms \textbf{1} (2003),
  no.~1, 21--35, Combinatorial algorithms. \MR{2016472}

\bibitem{Hagis80}
Peter Hagis, Jr., \emph{Outline of a proof that every odd perfect number has at
  least eight prime factors}, Math. Comp. \textbf{35} (1980), no.~151,
  1027--1032. \MR{81k:10004}

\bibitem{Hagis83}
\bysame, \emph{Sketch of a proof that an odd perfect number relatively prime to
  {$3$} has at least eleven prime factors}, Math. Comp. \textbf{40} (1983),
  no.~161, 399--404. \MR{85b:11004}

\bibitem{Hare05a}
Kevin~G. Hare, \emph{More on the total number of prime factors of an odd
  perfect number}, Math. Comp. \textbf{74} (2005), no.~250, 1003--1008
  (electronic). \MR{2114661}

\bibitem{IannucciSorli03}
D.~E. Iannucci and M.~Sorli, \emph{On the total number of prime factors of an
  odd perfect number}, Math. Comp. \textbf{72} (2003), no.~244, 2077--2084.

\bibitem{Kishore83}
Masao Kishore, \emph{Odd perfect numbers not divisible by {$3$}. {II}}, Math.
  Comp. \textbf{40} (1983), no.~161, 405--411. \MR{84d:10009}

\bibitem{Norton61}
Karl~K. Norton, \emph{Remarks on the number of factors of an odd perfect
  number}, Acta Arith. \textbf{6} (1960/1961), 365--374. \MR{26 \#4950}

\bibitem{Pomerance74}
Carl Pomerance, \emph{Odd perfect numbers are divisible by at least seven
  distinct primes}, Acta Arith. \textbf{25} (1973/74), 265--300.
  \MR{0340169}

\bibitem{Sayers86}
M.~Sayers, \emph{An improved lower bound for the total number of prime factors
  of an odd perfect number}, Master's thesis, New South Wales Institute of
  Technology, 1986.

\end{thebibliography}

\end{document}


\section{Boost Attribute}\label{spell:boostAttribute}
\textbf{Cost:} 500 CP\\
\textbf{Requirements:}~\nameref{rune:arcana} I, one other level I rune (see below)\\
\textbf{Spell, Active, Repeatable, Source(200 Gold), Memory}\\
You cast a spell for 10 Mana and 6 AP and target a creature you can see in a range of \passus{6}, increasing one of their Ability values by 2 for an amount of minutes equals to your IN.
One creature can only benefit from one attribute boost per attribute at a time, and it doesn't stack with other temporary attribute increases, neither from Items, Perks nor Equipment.
You can temporarily increase an attribute to a maximum of more than 12 with this spell.\\
When using this spell, the type of attribute you can boost depends on the runes that you know.
In order to learn the spell, you only need to know one of these runes.\\
\begin{itemize}
    \item Strength: "\nameref{rune:heat} I"
    \item Vitality: "\nameref{rune:earth} I"
    \item Agility: "\nameref{rune:water} I"
    \item Dexterity: "\nameref{rune:air} I"
    \item Intellect: "\nameref{rune:nil} I"
    \item Perception: "\nameref{rune:light} I"
    \item Empathy: "\nameref{rune:dark} I"
\end{itemize}
Level Progression:\\
II: 1,000 CP, increase by 3 for 25 Mana\\
III: 2,000 CP, increase by 4 for 50 Mana\\
IV: 5,000 CP, increase by 5 for 80 Mana\\
V: 10,000 CP, increase by 6 for 120 Mana\\


\section{Serialization}
\label{sec:serialization}

This section defines a binary format, which is used to store \langname
contracts in persistent stores, to transfer them over wire and to enable
cross-platform interoperation.

Terms of the language described in Section~\ref{sec:language} can be
serialized to array of bytes to be stored in Ergo blockchain (e.g. as
Box.propositionBytes).

When the guarding script of an input box of a transaction is validated the
\lst{propositionBytes} array is deserialized to an \langname IR (called \ASDag), which can
be evaluated as it is specified in Section~\ref{sec:evaluation}.

Here we specify the serialization procedure in general. The serialization
format of \langname terms and types is specified in
Appendix~\ref{sec:appendix:ergotree_serialization} and
~\ref{sec:appendix:type_serialization} correspondingly.

Table~\ref{table:ser:formats} shows size limits which are checked during
contract deserialization.

\begin{table}[h]
    \footnotesize
\(\begin{tabularx}{\textwidth}{| l | p{2cm} | X |}
    \hline
    \bf{Name}   & \bf{Value} & \bf{Description} \\
    \hline
    $\MaxVlqSize$  & $10$ & Maximum size of VLQ encoded byte sequence (See VLQ formats)  \\
    \hline
    $\MaxTypeSize$ & $100$ & Maximum size of serialized type term (see Type format) \\
    \hline
    $\MaxDataSize$ & $10Kb$ & Maximum size of serialized data instance (see Data format) \\
    \hline
    $\MaxConstSize$ & $=\MaxTypeSize + \MaxDataSize$  & Maximum size of serialized data instance (see Const format) \\
    \hline
    $\MaxExprSize$ & $1Kb$ & Maximum size of serialized \langname term (see Expr format) \\
    \hline
    $\MaxErgoTreeSize$ & $24Kb$ & Maximum size of serialized \langname contract (see ErgoTree format) \\
    \hline
\end{tabularx}\)
\caption{Serialization limits}
\label{table:ser:formats}
\end{table}

All serialization formats which are uses and defined thoughout this
section are listed in Table~\ref{table:ser:formats}.

\begin{table}[h]
    \footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | X |}
    \hline
    \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
    \lst{Byte} & $1$ & 8-bit signed two's-complement integer \\
    \hline
    \lst{Short} & $2$ & 16-bit signed two's-complement integer (big-endian) \\
    \hline
    \lst{Int} & $4$ & 32-bit signed two's-complement integer (big-endian) \\
    \hline
    \lst{Long} & $8$ & 64-bit signed two's-complement integer (big-endian) \\
    \hline
    \lst{UByte} & $1$ & 8-bit unsigned integer \\
    \hline
    \lst{UShort} & $2$ & 16-bit unsigned integer (big-endian) \\
    \hline
    \lst{UInt} & $4$ & 32-bit unsigned integer (big-endian) \\
    \hline
    \lst{ULong} & $8$ & 64-bit unsigned integer (big-endian) \\

    \hline
    \lst{VLQ(UShort)} & $[1..3]$ & Encoded unsigned \lst{Short} value using VLQ. See~\cite{VLQWikipedia,VLQRosetta} and~\ref{sec:vlq-encoding} \\
    \hline
    \lst{VLQ(UInt)} & $[1..5]$ & Encoded unsigned 32-bit integer using VLQ. \\
    \hline
    \lst{VLQ(ULong)} & $[1..\MaxVlqSize]$ & Encoded unsigned 64-bit integer using VLQ. \\

    \hline
    \lst{Bits} & $[1..\MaxBits]$ & A collection of bits packed in a sequence of bytes. \\
    \hline
    \lst{Bytes} & $[1..\MaxBytes]$ & A sequence (block) of bytes.
    The size of the block should either stored elsewhere or wellknown. \\

    \hline
    \lst{Type} & $[1..\MaxTypeSize]$ & Serialized type terms of \langname. See~\ref{sec:ser:type} \\
    \hline
    \lst{Data} & $[1..\MaxDataSize]$ & Serialized \langname values. See~\ref{sec:ser:data} \\
    \hline
    \lst{GroupElement} & $33$ & Serialized elements of eliptic curve group. See~\ref{sec:ser:data:groupelement} \\
    \hline
    \lst{SigmaProp} & $[1..\MaxSigmaProp]$ & Serialized sigma propositions. See~\ref{sec:ser:data:sigmaprop} \\
    \hline
    \lst{Box} & $[1..\MaxBox]$ & Serialized box data. See~\ref{sec:ser:data:box} \\
    \hline
    \lst{AvlTree} & $44$ & Serialized dynamic dictionary digest. See~\ref{sec:ser:data:avltree} \\
    \hline
    \lst{Const} & $[1..\MaxConstSize]$ & Serialized \langname constants (values with types). See~\ref{sec:ser:const} \\
    \hline
    \lst{Expr} & $[1..\MaxExprSize]$ & Serialized expression terms of \langname. See~\ref{sec:ser:expr} \\
    \hline
    \lst{ErgoTree} & $[1..\MaxErgoTreeSize]$ & Serialized instances of \langname contracts. See~\ref{sec:ser:ergotree} \\
    \hline
\end{tabularx}\)
\caption{Serialization formats}
\label{table:ser:formats}
\end{table}

Table~\ref{table:ser:formats} introduce a name for each format and also shows
the number of bytes each format may occupy in the byte stream. We use $[1..n]$
notation when serialization may produce from 1 to n bytes depending of actual
data instance.

Serialization format of \ASDag is optimized for compact storage. In many
cases serialization procedure is data dependent and thus have branching
logic. To express this complex serialization logic we use
\emph{pseudo-language operators} like \lst{for, match, if, optional} which
allow to specify a \emph{structure} on \emph{simple serialization slots}.
Each \emph{slot} specifies a fragment of serialized stream of bytes, whereas
\emph{operators} specifiy how the slots are combined together to form the
stream of bytes.

\input{type_serialization.tex}

\subsection{Data Serialization}
\label{sec:ser:data}

In \langname all runtime data values have an associated type also available
at runtime (this is called \emph{type reification}\cite{Reification}).
However serialization format separates data values from its type descriptors.
This allows to save space when for example a collection of items is serialized.

The contents of a typed data structure can be fully described by a type tree.
For example having a typed data object \lst{d: (Int, Coll[Byte], Boolean)} we can
tell that \lst{d} has 3 items, the first item contain 32-bit integer, the second
- collection of bytes, and the third - logical true/false value.

To serialize/deserialize typed data we need to know its type descriptor (type
tree). Serialization procedure is recursive over type tree and the
corresponding subcomponents of an object. For primitive types (the leaves of
the type tree) the format is fixed. The data values of \langname types are
serialized using predefined function shown in Figure~\ref{fig:ser:data}.

\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
    \hline
    \multicolumn{4}{l}{\lst{def serializeData(}$t, v$\lst{)}} \\
    \multicolumn{4}{l}{~~\lst{match} $(t, v)$ } \\

    \multicolumn{4}{l}{~~~~\lst{with} $(Unit, v \in \Denot{Unit})$~~~// nothing serialized } \\
    \multicolumn{4}{l}{~~~~\lst{with} $(Boolean, v \in \Denot{Boolean})$} \\
    \hline
    $~~~~~~v$ & \lst{Byte} & 1 & 0 or 1 in a single byte \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(Byte, v \in \Denot{Byte})$} \\
    \hline
    $~~~~~~v$  & \lst{Byte} & 1 &  in a single byte \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(N, v \in \Denot{Short}), N \in {Short, Int, Long}$} \\
    \hline
    $~~~~~~v$  & \lst{VLQ(ZigZag($$N$$))} & [1..3] &
      16,32,64-bit signed integer encoded using \hyperref[sec:zigzag-encoding]{ZigZag}
      and then using \hyperref[sec:vlq-encoding]{VLQ} \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(BigInt, v \in \Denot{BigInt})$} \\
    \multicolumn{4}{l}{~~~~~~$bytes = v$\lst{.toByteArray} } \\
    \hline
    $~~~~~~numBytes$  & \lst{VLQ(UInt)} &  & number of bytes in $bytes$ array \\
    \hline
    $~~~~~~bytes$  & \lst{Bytes} &  & serialized $bytes$ array \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(GroupElement, v \in \Denot{GroupElement})$} \\
    \hline
    ~~~~~~$v$  & \lst{GroupElement} &  & serialization of GroupElement data. See~\ref{sec:ser:data:groupelement} \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(SigmaProp, v \in \Denot{SigmaProp})$} \\
    \hline
    ~~~~~~$v$  & \lst{SigmaProp} &  & serialization of SigmaProp data. See~\ref{sec:ser:data:sigmaprop} \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(Box, v \in \Denot{Box})$} \\
    \hline
    ~~~~~~$v$  & \lst{Box} &  & serialization of Box data. See~\ref{sec:ser:data:box} \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(AvlTree, v \in \Denot{AvlTree})$} \\
    \hline
    ~~~~~~$v$  & \lst{AvlTree} &  & serialization of AvlTree data. See~\ref{sec:ser:data:avltree} \\

    \hline
    \multicolumn{4}{l}{~~~~\lst{with} $(Coll[T], v \in \Denot{Coll[T]})$} \\
    \hline
    $~~~~~~len$  & \lst{VLQ(UShort)} & [1..3] & length of the collection \\
    \hline
    \multicolumn{4}{l}{~~~~~~\lst{match} $(T, v)$ } \\

    \multicolumn{4}{l}{~~~~~~~~\lst{with} $(Boolean, v \in \Denot{Coll[Boolean]})$} \\
    \hline
    $~~~~~~~~~~items$  & \lst{Bits} & [1..1024] & boolean values packed in bits \\
    \hline

    \multicolumn{4}{l}{~~~~~~~~\lst{with} $(Byte, v \in \Denot{Coll[Byte]})$} \\
    \hline
    $~~~~~~~~~~items$  & \lst{Bytes} & $[1..len]$ & items of the collection  \\
    \hline
    \multicolumn{4}{l}{~~~~~~~~\lst{otherwise} } \\
    \multicolumn{4}{l}{~~~~~~~~~~\lst{for}~$i=1$~\lst{to}~$len$} \\
    \multicolumn{4}{l}{~~~~~~~~~~~~\lst{serializeData(}$T, v_i$\lst{)}} \\
    \multicolumn{4}{l}{~~~~~~~~~~\lst{end for}} \\
    \multicolumn{4}{l}{~~~~~~\lst{end match}} \\

    \multicolumn{4}{l}{~~\lst{end match}} \\
    \multicolumn{4}{l}{\lst{end serializeData}} \\
    \hline
    \hline
\end{tabularx}\)
\caption{Data serialization format}
\label{fig:ser:data}
\end{figure}

\subsubsection{GroupElement serialization}
\label{sec:ser:data:groupelement}

\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
    \multicolumn{4}{l}{\lst{def serialize(}$ge$\lst{)}} \\
    \multicolumn{4}{l}{~~\lst{if} $ge.isIdentity$ \lst{then}} \\
    \hline
    ~~~~$ $  & \lst{Const} & $ $ &  \\
    \hline
    \multicolumn{4}{l}{~~\lst{else}} \\
    \hline
    ~~~~$ $  &  & $ $ &  \\
    \hline
    \multicolumn{4}{l}{~~\lst{end if}} \\
    \multicolumn{4}{l}{\lst{end def}} \\
\end{tabularx}\)
\caption{GroupElement serialization format}
\label{fig:ser:data:groupelement}
\end{figure}

\subsubsection{SigmaProp serialization}
\label{sec:ser:data:sigmaprop}
\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
\end{tabularx}\)
\caption{SigmaProp serialization format}
\label{fig:ser:data:sigmaprop}
\end{figure}

\subsubsection{Box serialization}
\label{sec:ser:data:box}
\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
\end{tabularx}\)
\caption{Box serialization format}
\label{fig:ser:data:box}
\end{figure}

\subsubsection{AvlTree serialization}
\label{sec:ser:data:avltree}
\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
\end{tabularx}\)
\caption{AvlTree serialization format}
\label{fig:ser:data:avltree}
\end{figure}

\subsection{Constant Serialization}
\label{sec:ser:const}

\lst{Constant} format is simple and self sufficient to represent any data value in
\langname. Every data block of \lst{Constant} format contains both type and
data, such it can be stored or wire transfered and then later unambiguously
interpreted. The format is shown in Figure~\ref{fig:ser:const}

\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
    $type$  & \lst{Type} & $[1..\MaxTypeSize]$ & type of the data instance (see~\ref{sec:ser:type}) \\
    \hline
    $value$  & \lst{Data} & $[1..\MaxDataSize]$ & serialized data instance (see~\ref{sec:ser:data}) \\
    \hline
\end{tabularx}\)
\caption{Constant serialization format}
\label{fig:ser:const}
\end{figure}

\subsection{Expression Serialization}
\label{sec:ser:expr}

Expressions of \langname are serialized as tree data structure using
recursive procedure described here.

\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
    \hline
    \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
    \hline
    \multicolumn{4}{l}{\lst{def serializeExpr(}$e$\lst{)}} \\
    \hline
    ~~$e.opCode$  & \lst{Byte} & $1$ & opcode of ErgoTree node,
    used for selection of an appropriate node serializer from Appendix~\ref{sec:appendix:ergotree_serialization} \\
    \hline
    \multicolumn{4}{l}{~~\lst{if} $opCode <= LastConstantCode$ \lst{then}} \\
    \hline
    ~~~~$c$  & \lst{Const} & $[1..\MaxConstSize]$ & Constant serializaton slot \\
    \hline
    \multicolumn{4}{l}{~~\lst{else}} \\
    \hline
    ~~~~$body$  & Op & $[1..\MaxExprSize]$ & serialization of operation arguments
    depending on $e.opCode$ as defined in Appendix~\ref{sec:appendix:ergotree_serialization} \\
    \hline
    \multicolumn{4}{l}{~~\lst{end if}} \\
    \multicolumn{4}{l}{\lst{end serializeExpr}} \\
    \hline
\end{tabularx}\)
\caption{Expression serialization format}
\label{fig:ser:expr}
\end{figure}

\subsection{\ASDag~serialization}
\label{sec:ser:ergotree}

The root of a serializable \langname term is a data structure called \ASDag
which serialization format shown in Figure~\ref{fig:ergotree}

\begin{figure}[h]
\footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | l | X |}
  \hline
  \bf{Slot} & \bf{Format} & \bf{\#bytes} & \bf{Description} \\
  \hline
  $ header $ & \lst{VLQ(UInt)} & [1, *] & the first bytes of serialized byte array which
  determines interpretation of the rest of the array \\
  \hline
  $numConstants$ & \lst{VLQ(UInt)} & [1, *] & size of $constants$ array \\
  \hline
  \multicolumn{4}{l}{\lst{for}~$i=1$~\lst{to}~$numConstants$} \\
  \hline
      ~~ $ const_i $ & \lst{Const} & [1, *] & constant in i-th position \\
  \hline
  \multicolumn{4}{l}{\lst{end for}} \\
  \hline
  $ root $ & \lst{Expr} & [1, *] & If constantSegregationFlag is true, the  contains ConstantPlaceholder instead of some Constant nodes.
                       Otherwise may not contain placeholders.
                       It is possible to have both constants and placeholders in the tree, but for every placeholder
                       there should be a constant in $constants$ array. \\
  \hline
\end{tabularx}\)
\caption{\ASDag serialization format}
\label{fig:ser:ergotree}
\end{figure}

Serialized instances of \ASDag are self sufficient and can be stored and passed around.
\ASDag format defines top-level serialization format of \langname scripts.
The interpretation of the byte array depend on the first $header$ bytes, which uses VLQ encoding up to 30 bits.
Currently we define meaning for only first byte, which may be extended in future versions.

\begin{figure}[h]
    \footnotesize
\(\begin{tabularx}{\textwidth}{| l | l | X |}
    \hline
    \bf{Bits} & \bf{Default Value} & \bf{Description} \\
    \hline
    Bits 0-2 & 0 & language version (current version == 0) \\
    \hline
    Bit 3 & 0 & reserved (should be 0) \\
    \hline
    Bit 4 & 0 & == 1 if constant segregation is used for this ErgoTree (see~ Section~\ref{sec:ser:constant_segregation}\\
    \hline
    Bit 5 & 0 & == 1 - reserved for context dependent costing (should be = 0) \\
    \hline
    Bit 6 & 0 & reserved for GZIP compression (should be 0) \\
    \hline
    Bit 7 & 0 & == 1 if the header contains more than 1 byte (should be 0) \\
    \hline
\end{tabularx}\)
\caption{\ASDag $header$ bits}
\label{fig:ergotree:header}
\end{figure}

Currently we don't specify interpretation for the second and other bytes of
the header. We reserve the possibility to extend header by using Bit 7 == 1
and chain additional bytes as in VLQ. Once the new bytes are required, a new
version of the language should be created and implemented via
soft-forkability. That new language will give an interpretation for the new
bytes.

The default behavior of ErgoTreeSerializer is to preserve original structure
of \ASDag and check consistency. In case of any inconsistency the
serializer throws exception.

If constant segregation bit is set to 1 then $constants$ collection contains
the constants for which there may be \lst{ConstantPlaceholder} nodes in the
tree. If is however constant segregation bit is 0, then \lst{constants}
collection should be empty and any placeholder in the tree will lead to
exception.

\subsection{Constant Segregation}
\label{sec:ser:constant_segregation}