\lab{Regular Expressions}{Regular Expressions}
\objective{Cleaning and formatting data are fundamental problems in data science.
Regular expressions are an important tool for working with text carefully and efficiently, and are useful for both gathering and cleaning data.
This lab introduces regular expression syntax and common practices, including an application to a data cleaning problem.
}

% TODO: Important links!
% \url{https://docs.python.org/3/howto/regex.html}
% \url{https://docs.python.org/3/library/re.html}

A \emph{regular expression} or \emph{regex} is a string of characters that follows a certain syntax to specify a pattern.
Strings that follow the pattern are said to \emph{match} the expression (and vice versa).
A single regular expression can match a large set of strings, such as the set of all valid email addresses.

\begin{warn}
There are some universal standards for regular expression syntax, but the exact syntax varies slightly depending on the program or language.
However, the syntax presented in this lab (for Python) is sufficiently similar to any other regex system.
Consider learning to use regular expressions in Vim or your favorite text editor, keeping in mind that there will be slight syntactic differences from what is presented here.
\end{warn}

\section*{Regular Expression Syntax in Python} % ==============================

The \li{re} module implements regular expressions in Python.
The function \li{re.<<compile>>()} takes in a regular expression string and returns a corresponding \emph{pattern} object, which has methods for determining if and how other strings match the pattern.
For example, the \li{search()} method returns \li{None} for a string that doesn't match, and a \emph{match} object for a string that does.

Note the \li{match()} method for pattern objects only matches strings that satisfy the pattern \textbf{at the beginning} of the string.
To answer the question ``does any part of my target string match this regular expression?'' always use the \li{search()} method.

\begin{lstlisting}
>>> import re
>>> pattern = re.<<compile>>("cat")     # Make a pattern for finding 'cat'.
>>> bool(pattern.search("cat"))     # 'cat' matches 'cat', of course.
<<True>>
>>> bool(pattern.match("catfish"))  # 'catfish' starts with 'cat'.
<<True>>
>>> bool(pattern.match("fishcat"))  # 'fishcat' doesn't start with 'cat'.
<<False>>
>>> bool(pattern.search("fishcat")) # but it does contain 'cat'.
<<True>>
>>> bool(pattern.search("hat"))     # 'hat' does not contain 'cat'.
<<False>>
\end{lstlisting}

Most of the functions in the \li{re} module are shortcuts for compiling a pattern object and calling one of its methods.
Using \li{re.<<compile>>()} is good practice because the resulting object is reusable, while each call to \li{re.search()} compiles a new (but redundant) pattern object.
For example, the following lines of code are equivalent.
\begin{lstlisting}
>>> bool(re.<<compile>>("cat").search("catfish"))
<<True>>
>>> bool(re.search("cat", "catfish"))
<<True>>
\end{lstlisting}

\begin{problem} % Easy regular expression, construct test cases.
Write a function that compiles and returns a regular expression pattern object with the pattern string \li{"python"}.
\label{prob:regex-superbasic}
\end{problem}

\subsection*{Literal Characters and Metacharacters} % -------------------------

The following string characters (separated by spaces) are \emph{metacharacters} in Python's regular expressions, meaning they have special significance in a pattern string:
\li{. ^ \$ * + ? \{ \} [ ] \\ | ( )}.

A regular expression that matches strings with one or more metacharacters  requires two things.
\begin{enumerate}
    \item Use \emph{raw strings} instead of regular Python strings by prefacing the string with an \li{r}, such as \li{r"cat"}.
The resulting string interprets backslashes as actual backslash characters, rather than the start of an escape sequence like \li{\\n} or \li{\\t}.
    \item Preface any metacharacters with a backslash to indicate a literal character.
For example, to match the string \li{"\$3.99? Thanks."}, use \li{r"\\\$3\\.99\\? Thanks\\."}.

\end{enumerate}
Without raw strings, every backslash in has to be written as a double backslash, which makes many regular expression patterns hard to read (\li{"\\\\\$3\\\\.99\\\\? Thanks\\\\."}).

\begin{problem}
Write a function that compiles and returns a regular expression pattern object that matches the string \li{"^\{@\}(?)[\%]\{.\}(*)[_]\{&\}\$"}.
\label{prob:regex-metacharacter-literals}
\end{problem}

The regular expressions of Problems \ref{prob:regex-superbasic} and \ref{prob:regex-metacharacter-literals} only match strings that are or include the exact pattern.
The metacharacters allow regular expressions to have much more flexibility and control so that a single pattern can match a wide variety of strings, or a very specific set of strings.
The \emph{line anchor} metacharacters \li{^} and \li{\$} are used to match the \textbf{start} and the \textbf{end} of a line of text, respectively.
This shrinks the matching set, even when using the \li{search()} method instead of the \li{match()} method.
For example, the only single-line string that the expression \li{'^x\\\$'} matches is \li{'x'}, whereas the expression \li{'x'} can match any string with an \li{'x'} in it.

The \emph{pipe} character \li{|} is a logical \li{OR} in a regular expression: \li{A|B} matches \li{A} or \li{B}.
The parentheses \li{()} create a \emph{group} in a regular expression.
A group establishes an order of operations in an expression.
For example, in the regex \li{"^one|two fish\$"}, precedence is given to the invisible string concatenation between \li{"two"} and \li{"fish"}, while \li{"^(one|two) fish\$"} gives precedence to the \li{'\|'} metacharacter.

\begin{lstlisting}
>>> fish = re.<<compile>>(r"^(one|two) fish$")
>>> for test in ["one fish", "two fish", "red fish", "one two fish"]:
...     print(test + ':', bool(fish.search(test)))
...
<<one fish: True
two fish: True
red fish: False
one two fish: False>>
\end{lstlisting}

\begin{problem}
Write a function that compiles and returns a regular expression pattern object that matches the following strings, and no other strings, even with \li{re.search()}.

\centering
\begin{tabular}{lll}
\li{"Book store"} & \li{"Mattress store"} & \li{"Grocery store"} \\
\li{"Book supplier"} & \li{"Mattress supplier"} & \li{"Grocery supplier"} \\
\end{tabular}
\end{problem}

\subsection*{Character Classes} % ---------------------------------------------

The hard bracket metacharacters \li{[} and \li{]} are used to create \emph{character classes}, a part of a regular expression that can match a variety of characters.
For example, the pattern \li{[abc]} matches any of the characters \li{a}, \li{b}, or \li{c}.
This is different than a group delimited by parentheses: a group can match multiple characters, while a character class matches only one character.
For instance, \li{[abc]} does not match \li{ab} or \li{abc}, and \li{(abc)} matches \li{abc} but not \li{ab} or even \li{a}.

Within character classes, there are two additional metacharacters.
When \li{^} appears \textbf{as the first character} in a character class, right after the opening bracket \li{[}, the character class matches anything \textbf{not} specified instead.
In other words, \li{^} is the set complement operation on the character class.
Additionally, the dash \li{-} specifies a range of values.
For instance, \li{[0-9]} matches any digit, and \li{[a-z]} matches any lowercase letter.
Thus \li{[^0-9]} matches any character \textbf{except} for a digit, and \li{[^a-z]} matches any character \textbf{except} for lowercase letters. Keep in mind that the dash \li{-}, when at the beginning or end of the character class, will match the literal \li{'-'}.

\begin{lstlisting}
>>> p1, p2 = re.<<compile>>(r"^[a-z][^0-7]$"), re.<<compile>>(r"^[^abcA-C][0-27-9]$")
>>> for test in ["d8", "aa", "E9", "EE", "d88"]:
...     print(test + ':', bool(p1.search(test)), bool(p2.search(test)))
...
<<d8: True True>>
<<aa: True False>>                      # a is not in [^abcA-C] or [0-27-9].
<<E9: False True>>                      # E is not in [a-z].
<<EE: False False>>                     # E is not in [a-z] or [0-27-9].
<<d88: False False>>                    # Too many characters.
\end{lstlisting}

Note that \li{[0-27-9]} acts like \li{[(0-2)|(7-9)]}.

There are also a variety of shortcuts that represent common character classes, listed in Table \ref{table:regex-character-class-shortcuts}.
Familiarity with these shortcuts makes some regular expressions significantly more readable.

\begin{table}[H]
\begin{tabular}{c|l}
Character & Description \\ \hline
% \li{\\number} & Matches the contents of the group of the same number. \\
\li{\\b} & Matches the empty string, but only at the start or end of a word. \\
\li{\\s} & Matches any whitespace character; equivalent to \li{[ \\t\\n\\r\\f\\v]}. \\
\li{\\S} & Matches any non-whitespace character; equivalent to \li{[^\\s]}. \\
\li{\\d} & Matches any decimal digit; equivalent to \li{[0-9]}. \\
\li{\\D} & Matches any non-digit character; equivalent to \li{[^\\d]}. \\
\li{\\w} & Matches any alphanumeric character; equivalent to \li{[a-zA-Z0-9_]}. \\
\li{\\W} & Matches any non-alphanumeric character; equivalent to \li{[^\\w]}. \\
% \li{\\\\} & Matches a literal backslash. \\
\end{tabular}
\caption{Character class shortcuts.}
\label{table:regex-character-class-shortcuts}
\end{table}

Any of the character class shortcuts can be used within other custom character classes.
For example, \li{[\_A-Z\\s]} matches an underscore, capital letter, or whitespace character.

Finally, a period \li{.} matches \textbf{any} character except for a line break.
This is a very powerful metacharacter; be careful to only use it when part of the regular expression really should match \textbf{any} character.

\begin{lstlisting}
# Match any three-character string with a digit in the middle.
>>> pattern = re.<<compile>>(r"^.\d.$")
>>> for test in ["a0b", "888", "n2%", "abc", "cat"]:
...     print(test + ':', bool(pattern.search(test)))
...
<<a0b: True
888: True
n2%: True
abc: False
cat: False>>

# Match two letters followed by a number and two non-newline characters.
>>> pattern = re.<<compile>>(r"^[a-zA-Z][a-zA-Z]\d..$")
>>> for test in ["tk421", "bb8!?", "JB007", "Boba?"]:
...     print(test + ':', bool(pattern.search(test)))
..
<<tk421: True
bb8!?: True
JB007: True
Boba?: False>>
\end{lstlisting}

The following table is a useful recap of some common regular expression metacharacters.

\begin{table}[H]
\begin{tabular}{c|l}
Character & Description \\ \hline
\li{.}    & Matches any character except a newline. \\
\li{^}    & Matches the start of the string. \\
\li{\$}   & Matches the end of the string or just before the newline at the end of the string. \\
% \li{\\\\}   & Either escapes special characters or signals a special sequence. \\
\li{|}    & \li{A|B} creates an regular expression that will match either \li{A} or \li{B}. \\
\li{[...]}     & Indicates a set of characters. A \li{^} as the first character indicates a complementing set. \\
\li{(...)}  & Matches the regular expression inside the parentheses.\\ & The contents can be retrieved or matched later in the string. \\
\end{tabular}
\caption{Standard regular expression metacharacters in Python.}
\label{table:regex-special-characters}
\end{table}

% TODO: shorten this section.

\subsection*{Repetition} % ----------------------------------------------------

The remaining metacharacters are for matching a specified number of characters.
This allows a single regular expression to match strings of varying lengths.

\begin{table}[H]
\begin{tabular}{c|l}
Character & Description \\ \hline
\li{*}    & Matches 0 or more repetitions of the preceding regular expression. \\
\li{+}    & Matches 1 or more repetitions of the preceding regular expression. \\
\li{?}    & Matches 0 or 1 of the preceding regular expression. \\
\li{\{m,n\}}  & Matches from m to n repetitions of the preceding regular expression. \\
\li{*?}, \li{+?}, \li{??}, \li{\{m,n\}?} & Non-greedy versions of the previous four special characters.
\end{tabular}
\caption{Repetition metacharacters for regular expressions in Python.}
\label{table:regex-special-characters2}
\end{table}

Each of the repetition operators acts on the expression immediately preceding it.
This could be a single character, a group, or a character class.
For instance, \li{(abc)+} matches \li{abc}, \li{abcabc}, \li{abcabcabc}, and so on, but not \li{aba} or \li{cba}.
On the other hand, \li{[abc]*} matches any sequence of \li{a}, \li{b}, and \li{c}, including \li{abcabc} and \li{aabbcc}.

The curly braces \li{\{\}} specify a custom number of repetitions allowed.
\li{\{,n\}} matches \textbf{up to} $n$ instances, \li{\{m,\}} matches \textbf{at least} $m$ instances, \li{\{k\}} matches \textbf{exactly} $k$ instances, and \li{\{m,n\}} matches from $m$ to $n$ instances.
Thus the \li{?} operator is equivalent to \li{\{,1\}} and \li{+} is equivalent to \li{\{1,\}}.

\begin{lstlisting}
# Match exactly 3 'a' characters.
>>> pattern = re.<<compile>>(r"^a{3}$")
>>> for test in ["aa", "aaa", "aaaa", "aba"]:
...     print(test + ':', bool(pattern.search(test)))
...
<<aa: False>>                           # Too few.
<<aaa: True
aaaa: False>>                         # Too many.
<<aba: False>>
\end{lstlisting}

Be aware that line anchors are especially important when using repetition operators.
Consider the following (bad) example and compare it to the previous example.

\begin{lstlisting}
# Match exactly 3 'a' characters, hopefully.
>>> pattern = re.<<compile>>(r"a{3}")
>>> for test in ["aaa", "aaaa", "aaaaa", "aaaab"]:
...     print(test + ':', bool(pattern.search(test)))
...
<<aaa: True
aaaa: True>>                          # Should be too many!
<<aaaaa: True>>                         # Should be too many!
<<aaaab: True>>                         # Too many, and even with the 'b'?
\end{lstlisting}
The unexpected matches occur because \li{"aaa"} is at the beginning of each of the test strings.
With the line anchors \li{^} and \li{\$}, the search truly only matches the exact string \li{"aaa"}.

\begin{problem}
A \emph{valid Python identifier} (a valid variable name) is any string starting with an alphabetic character or an underscore, followed by any (possibly empty) sequence of alphanumeric characters and underscores.

A \emph{valid python parameter definition} is defined as the concatenation of the following strings:
\begin{itemize}
    \item any valid python identifier
    \item any number of spaces
    \item (optional) an equals sign followed by any number of spaces and ending with one of the following: any real number, a single quote followed by any number of non-single-quote characters followed by a single quote, or any valid python identifier
\end{itemize}

Define a function that compiles and returns a regular expression pattern object that matches any valid Python parameter definition.
\\(Hint: Use the \li{\\w} character class shortcut to keep your regular expression clean.)

To help in debugging, the following examples may be useful.
These test cases are a good start, but are not exhaustive.
The first table  should match valid Python identifiers.
The second should match a valid python parameter definition, as defined in this problem.
Note that some strings which would be valid in python will not be for this problem.

\centering
\begin{tabular}{c|lllll}
Matches: & \li{"Mouse"} & \li{"compile"} & \li{"_123456789"} & \li{"__x__"} & \li{"while"} \\ \hline
Non-matches: & \li{"3rats"} & \li{"err*r"} & \li{"sq(x)"} & \li{"sleep()"} & \li{"     x"}
\end{tabular}

\centering
\begin{tabular}{c|lllll}
Matches: & \li{"max=4.2"} & \li{"string= ''"} & \li{"num_guesses"} \\ \hline
Non-matches: & \li{"300"} & \li{"is_4=(value==4)"} & \li{"pattern = r'^one|two fish\$'"}
\end{tabular}
\end{problem}

\section*{Manipulating Text with Regular Expressions} % ======================

So far we have been solely concerned with whether or not a regular expression and a string match, but the power of regular expressions comes with what can be done with a match.
In addition to the \li{search()} method, regular expression pattern objects have the following useful methods.

\begin{table}[H]
\begin{tabular}{r|l}
Method & Description \\ \hline
\li{match()}     & Match a regular expression pattern to the beginning of a string. \\
\li{fullmatch()} & Match a regular expression pattern to all of a string. \\
\li{search()}    & Search a string for the presence of a pattern. \\
\li{sub()}       & Substitute occurrences of a pattern found in a string. \\
\li{subn()}      & Same as sub, but also return the number of substitutions made. \\
\li{split()}     & Split a string by the occurrences of a pattern. \\
\li{findall()}   & Find all occurrences of a pattern in a string. \\
\li{finditer()}  & Return an iterator yielding a match object for each match.
\end{tabular}
\caption{Methods of regular expression pattern objects.}
\end{table}

Some substitutions require remembering part of the text that the regular expression matches.
Groups are useful here: each group in the regular expression can be represented in the substitution string by \li{\\n}, where $n$ is an integer (starting at 1) specifying which group to use.

\begin{lstlisting}
# Find words that start with 'cat', remembering what comes after the 'cat'.
>>> pig_latin = re.compile(r"\bcat(\w*)")
>>> target = "Let's catch some catfish for the cat"

>>> pig_latin.sub(r"at\1clay", target)  # \1 = (\w*) from the expression.
<<"Let's atchclay some atfishclay for the atclay">>
\end{lstlisting}

The repetition operators \li{?}, \li{+}, \li{*}, and \li{\{m,n\}} are \emph{greedy}, meaning that they match the largest string possible.
On the other hand, the operators \li{??}, \li{+?}, \li{*?}, and \li{\{m,n\}?} are \emph{non-greedy}, meaning they match the smallest strings possible.
This is very often the desired behavior for a regular expression.

\begin{lstlisting}
>>> target = "<abc> <def> <ghi>"

# Match angle brackets and anything in between.
>>> greedy = re.<<compile>>(r"^<.*>$")  # Greedy *
>>> greedy.findall(target)
<<['<abc> <def> <ghi>']>>               # The entire string matched!

# Try again, using the non-greedy version.
>>> nongreedy = re.<<compile>>(r"<.*?>")# Non-greedy *?
>>> nongreedy.findall(target)
<<['<abc>', '<def>', '<ghi>']>>         # Each <> set is an individual match.
\end{lstlisting}

Finally, there are a few customizations that make searching larger texts manageable.
Each of these \emph{flags} can be used as keyword arguments to \li{re.<<compile>>()}.

\begin{table}[H]
\begin{tabular}{c|l}
Flag & Description \\ \hline
\li{re.DOTALL}     & \li{.} matches any character at all, including the newline. \\
\li{re.IGNORECASE} & Perform case-insensitive matching. \\
\li{re.MULTILINE}  & \li{^} matches the beginning of lines (after a newline)
               as well as the string; \\ & \li{\$} matches the end of lines (before a newline) as well as the end of the string.
\end{tabular}
\caption{Regular expression flags.}
\end{table}

A benefit of using \li{'^'} and \li{'\$'} is that they allow you to search across multiple lines.
For example, how would we match \li{"World"} in the string \mbox{\li{"Hello\\nWorld"}}?
Using \li{re.MULTILINE} in the \li{re.search} function will allow us to match at the beginning of each new line, instead of just the beginning of the string.
The following shows how to implement multiline searching:

\begin{lstlisting}
>>>pattern1 = re<<.compile>>("^W")
>>>pattern2 = re<<.compile>>("^W", re.MULTILINE)
>>>bool(pattern1.search("Hello\nWorld"))
<<False>>
>>>bool(pattern2.search("Hello\nWorld"))
<<True>>
\end{lstlisting}

\begin{problem}
A Python \emph{block} is composed of several lines of code with the same indentation level.
Blocks are delimited by key words and expressions, followed by a colon.
Possible key words are \li{if}, \li{elif}, \li{else}, \li{for}, \li{while}, \li{try}, \li{except}, \li{finally}, \li{with}, \li{def}, and \li{class}.
Some of these keywords require an expression to precede the colon (\li{if}, \li{elif}, \li{for}, etc.
Some require no expressions to precede the colon (\li{else}, \li{finally}), and \li{except} may or may not have an expression before the colon.

Write a function that accepts a string of Python code and uses regular expressions to place colons in the appropriate spots.
Assume that every colon is missing in the input string.

\begin{lstlisting}
"""
k, i, p = 999, 1, 0
while k > i
    i *= 2
    p += 1
    if k != 999
        print("k should not have changed")
    else
        pass
print(p)
"""

# The string given above should become this string.
"""
k, i, p = 999, 1, 0
while k > i:
    i *= 2
    p += 1
    if k != 999:
        print("k should not have changed")
    else:
        pass
print(p)
"""
\end{lstlisting}
\end{problem}

\begin{problem}
The file \texttt{fake\_contacts.txt} contains poorly formatted contact data for 2000 fictitious individuals.
Each line of the file contains data for one person, including their name and possibly their birthday, email address, and/or phone number.
The formatting of the data is not consistent, and much of it is missing.
For example, not everyone has their birthday listed, and those who do may have it listed in the form \li{1/1/11}, \li{1/01/2011}, or some other format.

Use regular expressions to parse the data and format it uniformly, writing birthdays as \li{mm/dd/yyyy} and phone numbers as \li{(xxx)xxx-xxxx}.
Return a dictionary where the key is the name of an individual and the value is another dictionary containing their information.
Each of these inner dictionaries should have the keys \li{"birthday"}, \li{"email"}, and \li{"phone"}.
In the case of missing data, map the key to \li{None}.
The first two entries of the completed dictionary are given below.

\begin{lstlisting}
{
    "John Doe": {
        "birthday": "01/01/1990",
        "email": "john_doe90@hopefullynotarealaddress.com",
        "phone": "(123)456-7890"
        },
    "Jane Smith": {
        "birthday": None,
        "email": None,
        "phone": "(222)111-3333"
        },
# ...
}
\end{lstlisting}
\end{problem}

\newpage

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

\section*{Regular Expressions in the Unix Shell}
As we have seen,, regular expressions are very useful when we want to match patterns.
Regular expressions can be used when matching patterns in the Unix Shell.
Though there are many Unix commands that take advantage of regular expressions, we will focus on \li{grep} and \li{awk}.

\subsection*{Regular Expressions and grep}
Recall from Lab 1 that \li{grep} is used to match patterns in files or output.
It turns out we can use regular expressions to define the pattern we wish to match.

In general, we use the following syntax:
\begin{lstlisting}
$ grep 'regexp' filename
\end{lstlisting}
%$

We can also use regular expressions when piping output to \li{grep}.
\begin{lstlisting}
# List details of directories within current directory.
$ ls -l | grep ^d
\end{lstlisting}
%$

\subsection*{Regular Expressions and awk}
By incorporating regular expressions, the \li{awk} command becomes much more robust.
Before GUI spreedsheet programs like Microsoft Excel, \li{awk} was commonly used to visualize and query data from a file.

Including \li{if} statements inside \li{awk} commands gives us the ability to perform actions on lines that match a given pattern.
The following example prints the filenames of all files that are owned by \li{freddy}.
\begin{lstlisting}
$ ls -l | awk ' {if ($3 ~ /freddy/) print $9} '
\end{lstlisting}
%$

Because there is a lot going on in this command, we will break it down piece-by-piece.
The output of \li{ls -l} is getting piped to \li{awk}. Then we have an \li{if} statement.
The syntax here means if the condition inside the parenthesis holds, print field $9$ (the field with the filename). The condition is where we use regular expressions.
The \li{\~} checks to see if the contents of field $3$ (the field with the username) matches the regular expression found inside the forward slashes.
To clarify, \li{freddy} is the regular expression in this example and the expression must be surrounded by forward slashes.

Consider a similar example.
In this example, we will list the names of the directories inside the current directory.
(This replicates the behavior of the Unix command \li{ls -d */})

\begin{lstlisting}
$ ls -l | awk ' {if ($1 ~ /^d/) print $9} '
\end{lstlisting}
%$

Notice in this example, we printed the names of the directories, whereas in one of the example using \li{grep}, we printed all the details of the directories as well.

\begin{warn}
Some of the definitions for character classes we used earlier in this lab will not work in the Unix Shell. For example, \li{\\w} and \li{\\d} are not defined. Instead of \li{\\w}, use \li{[[:alnum:]]}. Instead of \li{\\d}, use \li{[[:digit:]]}. For a complete list of similar character classes, search the internet for \emph{POSIX Character Classes} or \emph{Bracket Character Classes.}
\end{warn}

% TODO: deterministic finite state automata.


\documentclass{article}

\usepackage{fancyhdr}
\usepackage{extramarks}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{tikz}
\usepackage{physics}
\usepackage[plain]{algorithm}
\usepackage{algpseudocode}
\usepackage{graphicx,wrapfig,lipsum}
\usetikzlibrary{automata,positioning}

%
% Basic Document Settings
%

\topmargin=-0.45in
\evensidemargin=0in
\oddsidemargin=0in
\textwidth=6.5in
\textheight=9.0in
\headsep=0.25in

\linespread{1.1}

\pagestyle{fancy}
\lhead{\hmwkAuthorName}
\chead{\hmwkClass\ : \hmwkTitle}
\rhead{\firstxmark}
\lfoot{\lastxmark}
\cfoot{\thepage}

\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

\setlength\parindent{0pt}

%
% Create Problem Sections
%
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}
\newcommand{\bes}{\begin{equation*}}
\newcommand{\ees}{\end{equation*}}
\newcommand{\bea}{\begin{flalign*}}
\newcommand{\eea}{\end{flalign*}}

\newcommand{\enterProblemHeader}[1]{
    \nobreak\extramarks{}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
}

\newcommand{\exitProblemHeader}[1]{
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \stepcounter{#1}
    \nobreak\extramarks{Problem \arabic{#1}}{}\nobreak{}
}

\setcounter{secnumdepth}{0}
\newcounter{partCounter}
\newcounter{homeworkProblemCounter}
\setcounter{homeworkProblemCounter}{1}
\nobreak\extramarks{Problem \arabic{homeworkProblemCounter}}{}\nobreak{}

%
% Homework Problem Environment
%
% This environment takes an optional argument. When given, it will adjust the
% problem counter. This is useful for when the problems given for your
% assignment aren't sequential. See the last 3 problems of this template for an
% example.
%
\newenvironment{homeworkProblem}[1][-1]{
    \ifnum#1>0
        \setcounter{homeworkProblemCounter}{#1}
    \fi
    \section{Problem \arabic{homeworkProblemCounter}}
    \setcounter{partCounter}{1}
    \enterProblemHeader{homeworkProblemCounter}
}{
    \exitProblemHeader{homeworkProblemCounter}
}

%
% Homework Details
%   - Title
%   - Due date
%   - Class
%   - Section/Time
%   - Instructor
%   - Author
%

\newcommand{\hmwkTitle}{Assignment\ \#2}
\newcommand{\hmwkDueDate}{Due on 11th September, 2018}
\newcommand{\hmwkClass}{Fluid Mechanics}
\newcommand{\hmwkClassTime}{}
\newcommand{\hmwkClassInstructor}{}
\newcommand{\hmwkAuthorName}{\textbf{Aditya Vijaykumar}}

%
% Title Page
%

\title{
    %\vspace{2in}
    \textmd{\textbf{\hmwkClass:\ \hmwkTitle}}\\
    \normalsize\vspace{0.1in}\small{\hmwkDueDate\ }\\
%    \vspace{3in}
}

\author{\hmwkAuthorName}
\date{}

\renewcommand{\part}[1]{\textbf{\large Part \Alph{partCounter}}\stepcounter{partCounter}\\}

%
% Various Helper Commands
%

% Useful for algorithms
\newcommand{\alg}[1]{\textsc{\bfseries \footnotesize #1}}

% For derivatives
\newcommand{\deriv}[1]{\frac{\mathrm{d}}{\mathrm{d}x} (#1)}

% For partial derivatives
\newcommand{\pderiv}[2]{\frac{\partial}{\partial #1} (#2)}

% Integral dx
\newcommand{\dx}{\mathrm{d}x}

% Alias for the Solution section header
\newcommand{\solution}{\textbf{\large Solution}}

% Probability commands: Expectation, Variance, Covariance, Bias
\newcommand{\E}{\mathrm{E}}
\newcommand{\Var}{\mathrm{Var}}
\newcommand{\Cov}{\mathrm{Cov}}
\newcommand{\Bias}{\mathrm{Bias}}

\begin{document}

\maketitle
\textbf{Acknowledgements} -
I would like to thank Junaid, Aditya Sharma and Chandramouli for discussions in this assignment.

%\pagebreak

\begin{homeworkProblem}
    \textbf{Part (a)}\\
   	Given the assumptions, we can effectively consider the two volcanoes as sources/sinks in 2 dimensions. At some height $ h $, this then makes $ mh $ and $ nh $ the strength of the sources respectively. Consider the volcano at $ (0,0) $ to have strength $ m/h $ and the one at $ (d,0) $ to have $ n/h $. At some point $ (x,y) $, the velocity purely due to each of the volcanoes is given by,
   	\begin{equation*}
   	\vb{v}_1 = \frac{m}{2\pi h(x^2 + y^2)}(x\vu{x} + y \vu{y}) \qq{and} \vb{v}_2 = \frac{n}{2\pi h((x-d)^2 + y^2)}((x-d)\vu{x} + y \vu{y})
   	\end{equation*}
   	The final velocity field is just the vector addition,
   	\begin{equation*}
   	\vb{v} = \vb{v}_1 + \vb{v}_2= \frac{1}{2\pi h}\qty[\qty(\frac{mx}{x^2+y^2} +\frac{n(x-d)}{(x-d)^2 + y^2})\vu{x} + \qty(\frac{my}{x^2+y^2} +\frac{ny}{(x-d)^2 + y^2})\vu{y} ]
   	\end{equation*}

   	\textbf{Part (b)}\\
   	Obviously, $ h $ is not truly constant. There will be some additional force generated due to the pressure difference, which will then require us to solve the full Navier-Stokes equation to find the velocity field.
   	\\

   	\textbf{Part (c)}\\
   	If $ n<0 $, the second volcano is basically sucking in ash, and hence will act as a sink. The field sketches for both parts is given below

   	\begin{figure}[!h]
   		\caption{Figures - L: Part (a) and R: Part (c)}
   		\centering
   		\includegraphics[scale=0.26]{source.png}
   		\hspace{0.1in}
   		\includegraphics[scale=0.26]{sink.png}
   	\end{figure}
\end{homeworkProblem}

\begin{homeworkProblem}
	\textbf{Part (a)}\\
	\begin{wrapfigure}{l}{0.5\textwidth}
		\begin{center}
			\includegraphics[scale=0.08]{1a.jpg}
		\end{center}
	\end{wrapfigure}
	For a regular polygon with $ N $ sides, each side will subtend an angle $ \dfrac{2\pi}{N} $ at the centre. As the problem is symmetric, it is enough to solve for the motion of one point vortex.

	Considering a single vertex of the polygon, we can see that the motion will have contributions from the other $ N-1 $ vertices. As shown in the figure, only the horizontal components of these contributions will survive. Hence resultant tangential velocity will be given by,
	\begin{equation*}
	v = \sum_{k = 1}^{N-1} \dfrac{\Gamma}{2\pi a_k }\cos \theta_k
	\end{equation*}
	where $ k $ is the serial number of vertices starting anticlockwise from the vertex under consideration. It is evident from the figure that,
	\begin{equation*}
	\theta_k = \dfrac{\pi}{2} - \dfrac{k\pi}{N} \qq{and} a_k = 2 R \sin \dfrac{k\pi}{N}
	\end{equation*}
	where $ R $ is the distance of each vertex from the centre. Substituting this in the expression for velocity, and noting that $ \l = 2R \sin \dfrac{\pi}{N} $ where $ l $ is side length
	\begin{equation*}
	v = \dfrac{(N-1)\Gamma}{4\pi R} = \dfrac{(N-1)\Gamma  \sin \dfrac{\pi}{N} }{2\pi l}
	\end{equation*}
	The time period $ T $ is given by,
	\begin{equation*}
	\boxed{T = \dfrac{2\pi R}{v} = \dfrac{8 \pi^2 R^2}{(N-1)\Gamma} = \dfrac{2 \pi^2 l^2}{(N-1)\Gamma \sin^2 \dfrac{\pi}{N}}}
	\end{equation*}

	\textbf{Part (b)}\\
	As the expression for time period we have got is pretty simple, there is no need to solve this problem on the computer.

	\begin{equation*}
	\boxed{\qq{For $ N=4 $;} T = \dfrac{8 \pi^2 R^2}{3 \Gamma}}
	\end{equation*}
	\begin{equation*}
	\boxed{\qq{For $ N=10 $;} T = \dfrac{8 \pi^2 R^2}{9 \Gamma}}
	\end{equation*}

	\textbf{Part (c)}\\
	For a non-identical polygon, the flow will not be circular, and could follow some chaotic trajectory.
\end{homeworkProblem}
\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Template for AIMS Rwanda Assignments         %%%              %%%
%%% Author:   AIMS Rwanda tutors                             %%%   ###        %%%
%%% Email: tutors2017-18@aims.ac.rw                               %%%   ###        %%%
%%% Copyright: This template was designed to be used for    %%% #######      %%%
%%% the assignments at AIMS Rwanda during the academic year %%%   ###        %%%
%%% 2017-2018.                                              %%%   #########  %%%
%%% You are free to alter any part of this document for     %%%   ###   ###  %%%
%%% yourself and for distribution.                          %%%   ###   ###  %%%
%%%                                                         %%%              %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%% Ensure that you do not write the questions before each of the solutions because it is not necessary. %%%%%%

\documentclass[11pt,a4paper]{article}

%%%%%%%%%%%%%%%%%%%%%%%%% packages %%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{graphicx}
\usepackage[all]{xy}
\usepackage{tikz}
\usepackage{verbatim}
\usepackage[left=2cm,right=2cm,top=3cm,bottom=2.5cm]{geometry}
\usepackage{hyperref}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{psfrag}
\usepackage{float}

%%%%%%%%%%%%%%%%%%%%% students data %%%%%%%%%%%%%%%%%%%%%%%%
\newcommand{\student}{Louis Mozart Kamdem}
\newcommand{\course}{LaTex}
\newcommand{\assignment}{1}

%%%%%%%%%%%%%%%%%%% using theorem style %%%%%%%%%%%%%%%%%%%%
\newtheorem{thm}{Theorem}
\newtheorem{lem}[thm]{Lemma}
\newtheorem{defn}[thm]{Definition}
\newtheorem{exa}[thm]{Example}
\newtheorem{rem}[thm]{Remark}
\newtheorem{coro}[thm]{Corollary}
\newtheorem{quest}{Question}[section]

%%%%%%%%%%%%%%  Shortcut for usual set of numbers  %%%%%%%%%%%

\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\C}{\mathbb{C}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%555
\begin{document}

	%%%%%%%%%%%%%%%%%%%%%%% title page %%%%%%%%%%%%%%%%%%%%%%%%%%
	\thispagestyle{empty}
	\begin{center}
		\textbf{AFRICAN INSTITUTE FOR MATHEMATICAL SCIENCES \\[0.5cm]
			(AIMS RWANDA, KIGALI)}
		\vspace{1.0cm}
	\end{center}

	%%%%%%%%%%%%%%%%%%%%% assignment information %%%%%%%%%%%%%%%%
	\noindent
	\rule{17cm}{0.2cm}\\[0.3cm]
	Name:\student \hfill Assignment Number: \assignment\\[0.1cm]
	Course:\course \hfill Date: \today\\
	\rule{17cm}{0.05cm}
	\vspace{1.0cm}

\section*{Task 1:}

1) Build of the linear regression model:\\
\\To construct our model we will first takes all the variables (unless $User_{-}Id$) as explanatory variable and we will perform it as we go along. Let call this first model the model 1. We have in the table below the summary of model1
% latex table generated in R 4.1.2 by xtable 1.8-4 package
% Wed Dec  8 20:24:16 2021
\begin{table}[ht]
	\caption{Summary model1}
	\centering
	\begin{tabular}{rrrrr}
		\hline
		& Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\
		\hline
		(Intercept) & 8275.0003 & 51.3159 & 161.26 & 2e-16  \\
		Age\_num & 3.8340 & 1.1270 & 3.40 & 0.0007 \\
		GenderM & 707.5733 & 29.0924 & 24.32 & 2e-16  \\
		Marital\_Status & -44.7599 & 26.7599 & -1.67 & 0.0944 \\
		City\_CategoryB & 232.8961 & 31.1291 & 7.48 & 7.38e-14 \\
		City\_CategoryC & 816.1364 & 33.3939 & 24.44 & 2e-16  \\
		Stay\_In\_Current\_City\_Years & -2.4060 & 9.7449 & -0.25 & 0.8050 \\
		\hline
	\end{tabular}
\end{table}
\\We can see in the table above that p-value of all the variables are significantly close to 0 unless $Marital_{-}Status$ and $Stay_{-}In_{-}Current_{-}City_{-}Years$. And then to perform this model, we can build another model(model2) who doesn't contain does variables. We have in the table below the summary of model2.

% latex table generated in R 4.1.2 by xtable 1.8-4 package
% Wed Dec  8 20:33:21 2021
\begin{table}[ht]
	\caption{Summary Model2}
	\centering
	\begin{tabular}{rrrrr}
		\hline
		& Estimate & Std. Error & t value & Pr($>$$|$t$|$) \\
		\hline
		(Intercept) & 8271.6583 & 48.2288 & 171.51 &  2e-16 \\
		\hline
		Age\_num & 3.2739 & 1.0757 & 3.04 & 0.0023 \\
		\hline
		GenderM & 708.0186 & 29.0878 & 24.34 &  2e-16 \\
		\hline
		City\_CategoryB & 232.3207 & 31.1195 & 7.47 & 8.34e-14 \\
		\hline
		City\_CategoryC & 815.7573 & 33.3829 & 24.44 &  2e-16 \\
		\hline
	\end{tabular}
\end{table}
In this second model, all the p-values of the variables are significantly close to 0. Now let compare the two model with anova and AIC

\begin{table}[H]
	\caption{Comparaison table}
	\begin{subtable}{.5\linewidth}
		\centering
		\caption{AIC}
		 \begin{tabular}[t]{rrr}
		 	\hline
		 	& df & AIC \\
		 	\hline
		 	model2 & 6.00 & 3160097.61 \\
		 	model1 & 8.00 & 3160098.77 \\
		 	\hline
		 \end{tabular}
	\end{subtable} %
	\begin{subtable}{.5\linewidth}
		\centering
		\caption{ANOVA}
		\scalebox{0.8}{
		\begin{tabular}{lrrrrrr}
			\hline
			& Res.Df & RSS & Df & Sum of Sq & F & Pr($>$F) \\
			\hline
			1 & 158995 & 3984905477192.59 &  &  &  &  \\
			2 & 158993 & 3984834089188.59 & 2 & 71388004.00 & 1.42 & 0.2407 \\
			\hline
		\end{tabular}}
	\end{subtable}
\end{table}
We can see in the two table above that model2 has the smallest AIC and also the p-value in the ANOVA table is not very small this mean that there is no way to choose the most complicate model then model2 is better than model1.\\
\\
2) Interpretation of the model.

\begin{itemize}
	\item For every unit increase of Age, the purchase amount is expected to increases by about 3.27
	\item The standard error around the fitted intercept is quite small (48).
	\item Clients from the city category C are expected to buy 708 more than clients from the category A and client from category B are expected to buy 232 more than clients from category A
	\item Men are expected to buy 708 more than women
\end{itemize}
3) Let check if all the assumption about the model met

\begin{figure}[H]
	\centering
	\scalebox{0.5}{
		\begin{subfigure}[b]{0.4\textwidth}
			\includegraphics[width=\textwidth]{linearity}
			\caption{linearity}
			\label{fig:trapez1}
		\end{subfigure}
		~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc.
		%(or a blank line to force the subfigure onto a new line)
		\begin{subfigure}[b]{0.4\textwidth}
			\includegraphics[width=\textwidth]{normality}
			\caption{normality}
			\label{fig:trapez2}
		\end{subfigure}
		\begin{subfigure}[b]{0.4\textwidth}
			\includegraphics[width=\textwidth]{homos}
			\caption{homoskedasticity}
			\label{fig:trapez2}
		\end{subfigure}
		\begin{subfigure}[b]{0.4\textwidth}
			\includegraphics[width=\textwidth]{outliers}
			\caption{outliers}
			\label{fig:trapez2}
		\end{subfigure}	}

	\caption{Plot of different accuracy}\label{fig:trapez}
\end{figure}

\begin{itemize}
	\item Linearity:  With this model, the linearity is there but it is not very good
	\item Normality: We can see in subfigure (b) that the normality of our model is not to bad
	\item homoskedasticity: We can see that our model doesn't fit the assumption of homoskedasticity very well but it is not very bad
	\item Outliers: From the plot of the outliers in the subfigure (d), we can see some which can be removed to improve the model
\end{itemize}
4) Help the company to improve their sales

\begin{itemize}
	\item The company should do more advertising in the city category C to attract more clients from that city also clients from category B
	\item The company should go through to more old client because when the age of clients because if the age of the clients increase from one unit, we the purchase amount which increase from around 3
	\item The company should attract more men than women
\end{itemize}
5) Possible ways to improve the model:
\begin{itemize}
	\item We can investigate a non linear structure
	\item As indicate by the outliers, we can remove to our the observation from row 24859, 52407, 140019
\end{itemize}
6) Comparison of the final model with the model built on gender and age only.\\
\\We define the model built on age and Gender only as model3. We have the table of comparison below
% latex table generated in R 4.1.2 by xtable 1.8-4 package
% Sat Dec 11 14:34:33 2021
\begin{table}[H]
	\caption{Comparison between model2 and model3}
	\begin{subtable}{.5\linewidth}
		\centering
		\caption{AIC}
		 \begin{tabular}{rrr}
		 		\hline
		 		& df & AIC \\
		 		\hline
		 		model2 & 6.00 & 3160097.61 \\
		 		model3 & 4.00 & 3160755.17 \\
		 		\hline
		 	\end{tabular}
	\end{subtable} %
	\begin{subtable}{.5\linewidth}
		\centering
		\caption{ANOVA}
		\scalebox{0.7}{ \begin{tabular}{lrrrrrr}
				\hline
				& Res.Df & RSS & Df & Sum of Sq & F & Pr($>$F) \\
				\hline
				1 & 158995 & 3984905477192.59 &  &  &  &  \\
				2 & 158997 & 4001520005780.22 & -2 & -16614528587.63 & 331.45 & 2.2e-16 \\
				\hline
			\end{tabular}}
	 	\end{subtable}
\end{table}
We can see inside the table of AIC above that model2 have the smallest AIC and we have in the table of anova that the p-value is significantly close to 0 which mean that the most complicated model is the better one. We conclude that model2 is better than model3

\section*{Task2}

Show that the poisson distribution is a member of the exponential family\\
\\$X$ follow a poisson distribution of parameter $\lambda$ if $P(X = n)= \frac{\lambda^{n}}{n!}e^{-\lambda}$ $\forall n \in\mathbb{N}$\\0
  We want to write $P(X=n)$ on the form $$\displaystyle \exp(\frac{n\theta-b(\theta)}{a(\phi)}+c(n,\theta))$$\\
We  have:
\begin{align*}
	P(X = n, \theta,\phi )& = \frac{\lambda^{n}}{n!}e^{-\lambda}
	=e^{-\lambda}e^{\ln(\frac{\lambda^{n}}{n!})}
	=e^{n\ln(\lambda)-\ln(n!)-\lambda}
	=e^{n\ln(\lambda)-\lambda-\ln(n!)}
	\end{align*}
From this last inequality we can deduce : $\theta=\ln(\lambda)$, $b(\theta)=\lambda$, $a(\phi)=1$ and $c(n,\lambda)=-\ln(n!)$ which yield:   $b(\theta)=e^{\theta}$\\
\\This permit us to conclude that Poisson distribution is member of the exponential family

\section*{Task 3}
We have the model:
\begin{align*}
	\mu_{i}=\mathbb{E}[Y_{i}]=\frac{\alpha x_{i}}{\gamma+x_{i}}
\end{align*}
1) Let set the model as a GLM.
\begin{align*}
\mu_{i}=\frac{\alpha x_{i}}{\gamma+x_{i}}&\implies \frac{1}{\mu_{i}}=\frac{\gamma+x_{i}}{\alpha x_{i}}\\
&\implies g(\mu_{i})=\frac{1}{\alpha}+\frac{\gamma}{\alpha}\times \frac{1}{x_{i}}\quad \text{we know that $g(\mu_{i})=\eta_{i}$}\\
&\implies \eta_{i}=\frac{1}{\alpha}+\frac{\gamma}{\alpha}\times \frac{1}{x_{i}}\\
&\implies \eta_{i}=\beta_{0}+\beta_{1}X_{i}\quad\text{where $\beta_{0}=\frac{1}{\alpha}$, $\beta_{1}=\frac{\gamma}{\alpha}$, and $X_{i}=\frac{1}{x_{i}}$}
\end{align*}
Then, we have the linear form of the model.\\
\\2) Let write the regression parameter vector and the design matrix in terms of $\alpha$ and $\gamma$\\
\\We assume our sample is a sample of size $n$ then we have:
\begin{align*}
	\eta_{i}=\beta_{0}+\beta_{1}X_{i}\quad\forall i=1,2,\dots,n&\implies \begin{pmatrix}
	\eta_{1}	\\
	\eta_{2}	\\
	\vdots\\
	\eta_{n}
	\end{pmatrix}=\begin{pmatrix}{}
1	& X_{1} \\
1	& X_{2} \\
\vdots	&\vdots  \\
1	& X_{n}
\end{pmatrix}\times\begin{pmatrix}
\beta_{0}\\
\beta_{1}
\end{pmatrix}\\
&\implies \eta=X\beta
\end{align*}
Where $\eta=\begin{pmatrix}
	\eta_{1}	\\
	\eta_{2}	\\
	\vdots\\
	\eta_{n}
\end{pmatrix}$, The design matrix is $X=\begin{pmatrix}{}
1	& X_{1} \\
1	& X_{2} \\
\vdots	&\vdots  \\
1	& X_{n}
\end{pmatrix}=\begin{pmatrix}{}
1	&  \frac{1}{x_{1}} \\
1	&  \frac{1}{x_{2}} \\
\vdots	&\vdots  \\
1	&  \frac{1}{x_{n}}
\end{pmatrix}$ and the regression parameter vector is $\beta=\begin{pmatrix}
\beta_{0}\\
\beta_{1}
\end{pmatrix}=\begin{pmatrix}
 \frac{1}{\alpha}\\
 \frac{\gamma}{\alpha}
\end{pmatrix}$
\end{document}


\newcommand{\TeamNo}{31}

\newcommand{\HWno}{04}

\newcommand{\AuthorOneName}{Merve Nur Öztürk}
\newcommand{\AuthorOneID}{2311322}

\newcommand{\AuthorTwoName}{Atakan Süslü}
\newcommand{\AuthorTwoID}{2311371}

\newcommand{\AuthorThreeName}{Betül Rana Kuran}
\newcommand{\AuthorThreeID}{2311173}

\documentclass[letterpaper,12pt]{article}
\usepackage{tabularx} % extra features for tabular environment
\usepackage{amsmath}  % improve math presentation
\usepackage{amssymb}
\usepackage{xcolor}
\usepackage{float}
\usepackage[export]{adjustbox}
\usepackage{graphicx} % takes care of graphic including machinery
\usepackage[margin=1in,letterpaper]{geometry} % decreases margins
\usepackage{cite} % takes care of citations

\begin{document}
\begin{center}
AE 305, 2020-21 Fall \hfill \textbf{HW \HWno} \hfill \textbf{Team \TeamNo} \\
\noindent\rule{\textwidth}{0.4pt}
\begin{tabular}{p{0.33\textwidth} | p{0.33\textwidth} | p{0.33\textwidth} }
	\AuthorOneName&\AuthorTwoName&\AuthorThreeName\\
	\textit{\AuthorOneID}&\textit{\AuthorTwoID}&\textit{\AuthorThreeID}
\end{tabular}
\noindent\rule{\textwidth}{0.4pt}
\end{center}

%Report start

\section{Introduction}
Finite Difference Method uses finite-difference relations which are obtained from Taylor
series expansions in order to approximate the partial derivatives in a partial differential
equation. The equations representing the partial differentials are called Finite Difference
Equations. In this homework, given a convection-diffusion wave equation:

\begin{equation}
	\frac{\partial \omega}{\partial t} + V\frac{\partial \omega}{\partial x} = \nu\frac{\partial^2 \omega}{\partial x^2}
	\label{eqn:gaussian}
\end{equation}

where V is the constant convection velocity, $\nu$ is the diffusion (viscosity) coefficient,
and $\omega$ is distributed initially as follows:
\begin{equation}
	\omega(x,t=0) = exp(-b ln2(x/\Delta x)^2)
\end{equation}

where $\Delta x = 0.1$, and $b = 0.025$, it is requested to solve Equation \ref{eqn:gaussian} by modifying the given fortran code and
using forward-time central-space FDE, and prove that the equation is conditionally stable by
using different $\sigma$ (Courant number) and d values where $\sigma$ and d values are as the following:

\begin{eqnarray}
	\sigma &=& \frac{V\Delta t}{\Delta x} \nonumber \\
	d &=& \frac{\nu\Delta t}{\Delta x^2}
\end{eqnarray}
It is also asked to solve both Equation \ref{eqn:gaussian} and convection equation, where d equals
zero, by forward-time backward-space FDE and compare the solutions. Afterwards, given a high order
accuracy FDE, first, it is requested to perform consistency analysis on it and then solving
Equation \ref{eqn:gaussian} by using this FDE:

\begin{eqnarray}
\frac{-\omega^{n+1}_{i}+4\omega^{n}_{i}-3\omega^{n-1}_{i}}{2\Delta t} + V\frac{\omega^{n}_{i+1}-\omega^{n}_{i-1}}{2\Delta x} = \nu\frac{\omega^{n}_{i+1}-2\omega^{n}_{i}+\omega^{n}_{i-1}}{\Delta x^2}
\end{eqnarray}

Finally, implicit FDE (backward-time central-space) is used to solve Equation \ref{eqn:gaussian}.
In all solutions the range of x is such that -L/2$\leq$x$\leq$L/2 where L=40.

\newpage

\section{Method}
\subsection{Finite Difference Method}
Finite Difference method is used to solve partial differential equations by
approximating partial derivatives in these equations with finite difference relations.
In this homework, 1-D, linear, convection-diffusion equation and convection equation are solved
with a combination of finite difference approximations.
\begin{equation}
	\frac{\partial w}{\partial t} + V\frac{\partial w}{\partial x}=\nu\frac{\partial^2 w}{\partial x^2}
	\label{eqn:cde}
\end{equation}
is convective diffusion equation and
\begin{equation}
	\frac{\partial w}{\partial t} + V\frac{\partial w}{\partial x}=0
	\label{eqn:ce}
\end{equation}
is convective equation.\\
Two different derivations are used for the explicit finite difference equation of
Equation \ref{eqn:cde} in this homework.The first derivation of FDE is also used for the explicit
FDE of Equation \ref{eqn:ce}. In both derivations, the first term of
the equation forward time approximation is used.
\begin{equation}
	\frac{\partial w}{\partial t}\vert^{n}=\frac{w^{n+1}-{w^n}}{\Delta t}+O(\Delta t)
	\label{eqn:ft}
\end{equation}
In the first derivation, for second and third terms of the Equation \ref{eqn:cde},
central space approximations of
$\frac{\partial w}{\partial x}\vert_{i}$ of order ($\Delta x^2$) and
$\frac{\partial^2 w}{\partial x^2}\vert_{i}$ of order ($\Delta x^2$), respectively, are used.
\begin{equation}
	\frac{\partial w}{\partial x}\vert_{i}=\frac{w_{i+1}-w_{i-1}}{2\Delta x}+O(\Delta x^2)
	\label{eqn:cs1}
\end{equation}
\begin{equation}
	\frac{\partial^2 w}{\partial x^2}\vert_{i}=\frac{w_{i+1}-2w_i+w_{i-1}}{\Delta x^2}+O(\Delta x^2)
	\label{eqn:cs2}
\end{equation}
By substituting Equation \ref{eqn:ft}, \ref{eqn:cs1}, and \ref{eqn:cs2} into Equation \ref{eqn:cde}, it becomes:
\begin{equation}
	\frac{w_{i}^{n+1}-{w_{i}^{n}}}{\Delta t}+\frac{w_{i+1}^{n}-w_{i-1}^{n}}{2\Delta x}
	=\frac{w_{i+1}^{n}-2w_{i}^{n}+w_{i-1}^{n}}{\Delta x^2}+O(\Delta x^2, \Delta t)
\end{equation}
The explicit FDE of Equation \ref{eqn:cde} based on forward time and central spatial differences (FTCS) is obtained:
\begin{equation}
	w_{i}^{n+1}= w_{i}^{n}-\frac{\sigma}{2}(w_{i+1}^{n}-w_{i-1}^{n})+d(w_{i+1}^{n}-2w_{i}^{n}+w_{i-1}^{n})+O(\Delta x^2,\Delta t)
	\label{eqn:FTCS}
\end{equation}
where $\sigma = \frac{V\Delta t}{\Delta x }$ and $d = \frac{\nu\Delta t}{\Delta x^2 }$.
\\To derive the explicit FDE of Equation \ref{eqn:ce}, Equation \ref{eqn:ft} and \ref{eqn:cs1} are
substituted into Equation \ref{eqn:ce}:
\begin{equation}
	\frac{w_{i}^{n+1}-{w_{i}^{n}}}{\Delta t}+\frac{w_{i+1}^{n}-w_{i-1}^{n}}{2\Delta x}
	=0+O(\Delta x^2, \Delta t)
\end{equation}
The explicit FDE of Equation \ref{eqn:ce} based on forward time and central spatial differences (FTCS) is obtained:
\begin{equation}
	w_{i}^{n+1}= w_{i}^{n}-\frac{\sigma}{2}w_{i+1}^{n}-w_{i-1}^{n}+O(\Delta x^2, \Delta t)
\end{equation}
where $\sigma = \frac{V\Delta t}{\Delta x }$.
\\In the second derivation, instead of central space approximation, backward space approximation is used.
Backward space approximation of $\frac{\partial w}{\partial x}\vert$ of order ($\Delta x$):
\begin{equation}
	\frac{\partial w}{\partial x}\vert_{i}=\frac{w_{i}-w_{i-1}}{\Delta x}+O(\Delta x)
	\label{eqn:bs1}
\end{equation}
Backward space approximation of $\frac{\partial^2 w}{\partial x^2}\vert$ of order ($\Delta x$):
\begin{equation}
	\frac{\partial^2 w}{\partial x^2}\vert_{i}=\frac{w_{i}-2w_{i-1}+w_{i-2}}{\Delta x^2}+O(\Delta x)
	\label{eqn:bs2}
\end{equation}
By substituting Equation \ref{eqn:ft}, \ref{eqn:bs1}, and \ref{eqn:bs2} into Equation \ref{eqn:cde}:
\begin{equation}
	\frac{w_{i}^{n+1}-{w_{i}^{n}}}{\Delta t}+\frac{w_{i}^{n}-w_{i-1}^{n}}{\Delta x}
	=\frac{w_{i}^{n}-2w_{i-1}^{n}+w_{i-2}^{n}}{\Delta x^2}+O(\Delta x,\Delta t)
\end{equation}
The explicit FDE of Equation \ref{eqn:cde} based on forward time and backward spatial
differences (FTBS) is obtained:
\begin{equation}
	w_{i}^{n+1}= w_{i}^{n}-\sigma(w_{i+1}^{n}-w_{i-1}^{n})+d(w_{i}^{n}-2w_{i-1}^{n}+w_{i-2}^{n})+O(\Delta x,\Delta t)
\end{equation}
where $\sigma = \frac{V\Delta t}{\Delta x }$ and $d = \frac{\nu\Delta t}{\Delta x^2 }$.
\\ To obtain the implicit FDE of Equation \ref{eqn:cde}, backward time central space method is used.
Backward time difference is used for the first term of Equation \ref{eqn:cde}:
\begin{equation}
	\frac{\partial w}{\partial t}\vert^{n}=\frac{w^{n}-w^{n-1}}{\Delta x}+O(\Delta t)
	\label{eqn:bt}
\end{equation}
Equation \ref{eqn:cs1} and \ref{eqn:cs2} are used to approximate the second and third
terms of Equation \ref{eqn:cde}, respectively. Equation \ref{eqn:bt}, \ref{eqn:cs1}
and \ref{eqn:cs2} are inserted in the Equation \ref{eqn:cde}:
\begin{equation}
	\frac{w_{i}^{n}-{w_{i}^{n-1}}}{\Delta t}+\frac{w_{i+1}^{n-1}-w_{i-1}^{n-1}}{2\Delta x}
	=\frac{w_{i+1}^{n-1}-2w_{i}^{n-1}+w_{i-1}^{n-1}}{\Delta x^2}+O(\Delta x^2, \Delta t)
\end{equation}
To define a PDE as implicit, it should be discretized at time level $n+1$. So, equation becomes:
\begin{equation}
	\frac{w_{i}^{n+1}-{w_{i}^{n}}}{\Delta t}+\frac{w_{i+1}^{n+1}-w_{i-1}^{n+1}}{2\Delta x}
	=\frac{w_{i+1}^{n+1}-2w_{i}^{n+1}+w_{i-1}^{n+1}}{\Delta x^2}+O(\Delta x^2, \Delta t)
\end{equation}
The implicit FDE of Equation \ref{eqn:cde} based on BTCS Euler Implicit method is obtained:
\begin{equation}
	-(\frac{\sigma}{2}+d)w_{i-1}^{n+1}+(2d+1)w_{i}^{n+1}+(\frac{\sigma}{2}-d)w_{i+1}^{n+1} = w_{i}^{n}
	\label{eqn:implicit}
\end{equation}
where $\sigma = \frac{V\Delta t}{\Delta x }$ and $d = \frac{\nu\Delta t}{\Delta x^2 }$.
\newpage
\subsection{Thomas Algorithm}
As a consequence of the usage of the BTCS Euler Implicit method to solve the convection-diffusion
equation, the tridiagonal system of equations is obtained. The general form of the tridiagonal system
equation with k unknowns:
\begin{equation}
	a_i x_{i-1}+b_i x_i+c_i x_{i+1}=f_i
\end{equation}
where $a_1$ and $c_k$ is not used.\\System of equations can be written as following form
\begin{equation}
	\begin{bmatrix}
		b_1 & c_1    & 0      &\dots    &0   \\
		a_2 & b_2    & c_2    &\dots    &\vdots\\
		0   & \ddots & \ddots & \ddots	& 0    \\
		\vdots& \dots&a_{k-1} & b_{k-1} & c_{k-1}\\
		0   & \dots  & 0      & a_k     & b_k
		\end{bmatrix}
	\begin{Bmatrix}
		x_1\\
		x_2\\
		\vdots\\
		x_{k-1}\\
		x_k
		\end{Bmatrix}
	=
	\begin{Bmatrix}
		f_1\\
		f_2\\
		\vdots\\
		f_{k-1}\\
		f_k
	\end{Bmatrix}
	\label{eqn:matrx}
\end{equation}
The first term of Equation \ref{eqn:matrx} has 3 non-zero diagonals so
it is a tridiagonal matrix. Equation \ref{eqn:matrx} can be solved with Thomas
Algorihtm.

\subsection{Consistency Analysis of the Given FDE}
\label{sub:cons}
Consistency is one of the conditions to be able to approximate the PDE. What is meant by consistency is
that as the step sizes go to zero, FDE should converge to the PDE. For a given FDE written at a point
(i,n), consistency analysis is to expand the discrete values with Taylor series expansions and leaving
the original PDE terms on the left-hand-side and all the other terms on the right-hand side. If the right
hand side goes to zero as the step sizes go to zero, the FDE is consistent. This procedure is carried
out for the following FDE:

\begin{equation}
	\frac{-\omega^{n+1}_{i}+4\omega^{n}_{i}-3\omega^{n-1}_{i}}{2\Delta t} + V\frac{\omega^{n}_{i+1}-\omega^{n}_{i-1}}{2\Delta x} = \nu\frac{\omega^{n}_{i+1}-2\omega^{n}_{i}+\omega^{n}_{i-1}}{\Delta x^2}
	\label{equation:q4}
\end{equation}

First, all terms except the $\omega^{n}_{i}$ term, are expanded aorund $\omega^{n}_{i}$ with TSE:

\begin{eqnarray}
	\omega^{n+1}_i &=& w^n_i + \Delta t \omega_t|^n_i + \frac{\Delta t^2}{2} \omega_{tt}|^n_i + \frac{\Delta t^3}{6} \omega_{ttt}|^n_i ... \nonumber \\
	\omega^{n-1}_i &=& w^n_i - \Delta t \omega_t|^n_i + \frac{\Delta t^2}{2} \omega_{tt}|^n_i - \frac{\Delta t^3}{6} \omega_{ttt}|^n_i ... \nonumber \\
	\omega^n_{i+1} &=& w^n_i + \Delta x \omega_x|^n_i + \frac{\Delta x^2}{2} \omega_{xx}|^n_i + \frac{\Delta x^3}{6} \omega_{xxx}|^n_i ... \nonumber \\
	\omega^n_{i-1} &=& w^n_i - \Delta x \omega_x|^n_i + \frac{\Delta x^2}{2} \omega_{xx}|^n_i - \frac{\Delta x^3}{6} \omega_{xxx}|^n_i ...
\end{eqnarray}

Then the above relations are substituted into Equation \ref{equation:q4}:

\begin{equation}
	\omega_t|^n_i - \Delta t \omega_{tt}|^n_i + \frac{\Delta t^2}{6} \omega_{ttt}|^n_i + V\omega_x|^n_i + V\frac{\Delta x^2}{6}\omega_{xxx}|^n_i = \nu\omega_{xx}|^n_i + O(\Delta t^4,\Delta x^4)
\end{equation}

Collecting the original PDE terms to the RHS:

\begin{equation}
	[\omega_t + V\omega_x - \nu\omega_{xx}]|^n_i = \Delta t \omega_{tt}|^n_i - \frac{\Delta t^2}{6} \omega_{ttt}|^n_i - V\frac{\Delta x^2}{6}\omega_{xxx}|^n_i + O(\Delta t^4,\Delta x^4)
	\label{equation:consistency}
\end{equation}

Since the right-hand-side terms go to zero as $\Delta t$ and $\Delta x$ approach to zero, the FDE given
in Equation \ref{equation:q4} is consistent.

In order to understand the effect of the leading error term on the right-hand side the leading term's time
derivatives are converted to spatial derivatives using the Equation \ref{eqn:cde} as follows:

\begin{equation}
	\frac{\partial \omega}{\partial t} = \nu\frac{\partial^2 \omega}{\partial x^2} - V\frac{\partial \omega}{\partial x}
\end{equation}

Differentiating with respect to time:

\begin{eqnarray}
	\frac{\partial^2 \omega}{\partial t^2} &=& \nu\frac{\partial^2}{\partial x^2}(\frac{\partial \omega}{\partial t}) - V\frac{\partial}{\partial x}(\frac{\partial \omega}{\partial t}) \nonumber \\
	\frac{\partial^2 \omega}{\partial t^2} &=& \nu\frac{\partial^2}{\partial x^2}(\nu\frac{\partial^2 \omega}{\partial x^2} - V\frac{\partial \omega}{\partial x}) - V\frac{\partial}{\partial x}(\nu\frac{\partial^2 \omega}{\partial x^2} - V\frac{\partial \omega}{\partial x}) \nonumber \\
	\frac{\partial^2 \omega}{\partial t^2} &=& \nu^2\frac{\partial^4 \omega}{\partial x^4} - 2V\nu\frac{\partial^3 \omega}{\partial x^3} + V^2\frac{\partial^2 \omega}{\partial x^2}
	\label{eqnarray:t2}
\end{eqnarray}

Differentiating the last equation one more time:

\begin{eqnarray}
	\frac{\partial^3 \omega}{\partial t^3} &=& \nu^2\frac{\partial^4}{\partial x^4}(\frac{\partial \omega}{\partial t}) - 2V\nu\frac{\partial^3}{\partial x^3}(\frac{\partial \omega}{\partial t}) + V^2\frac{\partial^2}{\partial x^2}(\frac{\partial \omega}{\partial t}) \nonumber \\
	\frac{\partial^3 \omega}{\partial t^3} &=& \nu^2\frac{\partial^4}{\partial x^4}(\nu\frac{\partial^2 \omega}{\partial x^2} - V\frac{\partial \omega}{\partial x}) - 2V\nu\frac{\partial^3}{\partial x^3}(\nu\frac{\partial^2 \omega}{\partial x^2} - V\frac{\partial \omega}{\partial x}) + V^2\frac{\partial^2}{\partial x^2}(\nu\frac{\partial^2 \omega}{\partial x^2} - V\frac{\partial \omega}{\partial x}) \nonumber \\
	\frac{\partial^3 \omega}{\partial t^3} &=& \nu^3\frac{\partial^6}{\partial x^6} - 3\nu^2V\frac{\partial^5}{\partial x^5} + 3V^2\nu\frac{\partial^4}{\partial x^4} - V^3\frac{\partial^3}{\partial x^3}
	\label{eqnarray:t3}
\end{eqnarray}

Plugging Equations \ref{eqnarray:t2} and \ref{eqnarray:t3} into Equation \ref{equation:consistency} the
right hand side becomes:

\begin{eqnarray}
	V^2\Delta t \frac{\partial^2 \omega}{\partial x^2} - (2V\nu\Delta t &-&V^3\frac{\Delta t^2}{6} + V\frac{\Delta x^2}{6})\frac{\partial^3 \omega}{\partial x^3} + (\nu^2\Delta t -V^2\nu\frac{\Delta t^2}{2})\frac{\partial^4 \omega}{\partial x^4} \nonumber \\
	&+& \nu^2V\frac{\Delta t^2}{2}\frac{\partial^5 \omega}{\partial x^5} - \nu^3\frac{\Delta t^2}{6}\frac{\partial^6 \omega}{\partial x^6}
	\label{eqnarray:leading}
\end{eqnarray}

It can be concluded from Equation \ref{eqnarray:leading} that the $2^{nd}$, $4^{th}$, and $6^{th}$ derivatives are dissipation errors
and the $3^{rd}$ and $5^{th}$ derivatives are dispersion errors.

\newpage

\section{Results and Discussion}
\subsection{Stability of the Solution of the Explicit FDE of Convection Diffusion Equation}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTCS/ConvectionDiffusion/sigma05d05.eps}
	\caption{Convection diffusion solution by the explicit FTCS method with $\sigma= 0.5$ and $d=0.5$ at different time steps.}
 	\label{fig:FTCSsigma05d05}
\end{figure}
Figure \ref{fig:FTCSsigma05d05} shows the solution of the explicit FTCS
method for Equation \ref{eqn:cde} with $\sigma= 0.5$ and $d=0.5$ at various time steps.
Figure \ref{fig:FTCSsigma05d025} shows the solution of the same explicit FDE but with
different d value ($d=0.25$) at various time steps. As can be seen from the Figures \ref{fig:FTCSsigma05d05}
and \ref{fig:FTCSsigma05d025}, as time step increases, both curves continue to oscillate with a decrease in their
amplitudes. It can be seen that the solution of the explicit FDE is convergent for $d=0.5$
and $d=0.25$ while keeping $\sigma$ constant and equal to 0.5. Since the stability is a condition
to be satisfied for convergence, it can be understood that both solutions are stable. \\
\indent Figure \ref{fig:FTCSsigma05d075} shows the solution of the explicit FTCS
method for Equation \ref{eqn:cde} with $\sigma= 0.5$ and $d=0.75$ at the initial condition
and $25^{th}$ time step. The curve in the graph has some deterioration at $nt = 25$. Therefore,
the explicit FDE is unstable for $\sigma= 0.5$ and $d=0.75$.
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTCS/ConvectionDiffusion/sigma05d025.eps}
	\caption{Convection diffusion solution by the explicit FTCS method with $\sigma= 0.5$ and $d=0.25$ at different time steps.}
	 \label{fig:FTCSsigma05d025}
\end{figure}
\vspace{1cm}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTCS/ConvectionDiffusion/sigma05d075.eps}
	\caption{Convection diffusion solution by the explicit FTCS method with $\sigma= 0.5$ and $d=0.75$ at $nt=0$ and $nt=25$.}
	 \label{fig:FTCSsigma05d075}
\end{figure}

\newpage

\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTCS/ConvectionDiffusion/sigma025d05.eps}
	\caption{Convection diffusion solution by the explicit FTCS method with $\sigma= 0.25$ and $d=0.5$ at different time steps.}
	 \label{fig:FTCSsigma025d05}
\end{figure}

Figure \ref{fig:FTCSsigma025d05} and Figure \ref{fig:FTCSsigma075d05} illustrates the solutions of the explicit FTCS
method for Equation \ref{eqn:cde} for $d=0.5$ with different sigma values, $\sigma= 0.25$ and $\sigma=0.75$,
respectively, at various time steps. In both Figure \ref{fig:FTCSsigma025d05}
and \ref{fig:FTCSsigma075d05}, the wave lengths of curves increases and the amplitudes of the waves are reduced
with increasing time steps. Overall, it can be said that the solution of the explicit FDE is convergent, hence stable
for $d=0.5$ with $\sigma = 0.25$, and $\sigma = 0.75$ since there is no distortion observed.
\vspace{1em}

Figure \ref{fig:FTCSsigma12d05} demonstrates the solution of the explicit FTCS
method for Equation \ref{eqn:cde} with $\sigma= 1.2$ and $d=0.5$ at various time steps. For the curve in the
Figure \ref{fig:FTCSsigma12d05}, the amplitude of the wave increases, and the wave becomes disrupted with
increasing time step. Consequently, the solution of the explicit FDE is unstable for $\sigma=1.2$ and $d=0.5$\\
\indent To conclude this subsection since the explicit FDE of the convection-diffusion equation is stable for some $d$
and $\sigma$ values whereas it can be unstable for some other combinations of $d$ and $\sigma$ values, it is conditionally stable.

\newpage

\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTCS/ConvectionDiffusion/sigma075d05.eps}
	\caption{Convection diffusion solution by the explicit FTCS method with $\sigma= 0.75$ and $d=0.5$ at different time steps.}
	 \label{fig:FTCSsigma075d05}
\end{figure}
\vspace{1cm}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTCS/ConvectionDiffusion/sigma12d05.eps}
	\caption{Convection diffusion solution by the explicit FTCS method with $\sigma= 1.2$ and $d=0.5$ at different time steps.}
	 \label{fig:FTCSsigma12d05}
\end{figure}

\newpage

\subsection{Comparison of convective eqution with FTBS}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/Convection/sigma025d0.eps}
	\caption{Convection solution by the explicit FTBS method with $\sigma= 0.25$ at different time steps.}
	 \label{fig:FTBSsigma025d0}
\end{figure}

Figures \ref{fig:FTBSsigma025d0}, \ref{fig:FTBSsigma05d0}, \ref{fig:FTBSsigma075d0}, and \ref{fig:FTBSsigma12d0}
demonstrate solutions of convection equation using FTBS with different $\sigma$ values at various time
steps. It can be observed that for $\sigma$ values less than 1.2, the solutions obtained are convergent.
However, for $\sigma = 1.2$, wave curve is distorted and the solution is divergent. Besides, comparing Figures
\ref{fig:FTBSsigma025d0}, \ref{fig:FTBSsigma05d0}, and \ref{fig:FTBSsigma075d0}, it can be seen that the
amplitudes of the wave curves decrease faster, whereas the wave lengths of the curves experience a more rapid
increase for smaller $\sigma$ values.

\newpage

\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/Convection/sigma05d0.eps}
	\caption{Convection solution by the explicit FTBS method with $\sigma= 0.5$ at different time steps.}
	 \label{fig:FTBSsigma05d0}
\end{figure}
\vspace{1cm}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/Convection/sigma075d0.eps}
	\caption{Convection solution by the explicit FTBS method with $\sigma= 0.75$ at different time steps.}
	 \label{fig:FTBSsigma075d0}
\end{figure}

\newpage

\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/Convection/sigma12d0.eps}
	\caption{Convection solution by the explicit FTBS method with $\sigma= 1.2$ at $nt=0$ and $nt=55$.}
	 \label{fig:FTBSsigma12d0}
\end{figure}

Figures \ref{fig:FTBSsigma025d05}, \ref{fig:FTBSsigma05d05}, \ref{fig:FTBSsigma075d05}, and \ref{fig:FTBSsigma12d05}
illustrate the solutions of convection diffusion equation using FTBS with various $\sigma$ values at different time
steps while keeping d value constant. As can be seen from these figures, for $\sigma = 1.2$, a convergent solution
is obtained for the convection diffusion equation. Nonetheless, for $\sigma$ values smaller than 1.2, calculations
gave divergent solutions.
\vspace{1em}

Figures \ref{fig:FTBSsigma12d05}, \ref{fig:FTBSsigma12d025}, and \ref{fig:FTBSsigma12d075} monitor the
solutions of convection diffusion equation using FTBS with various d values at different time steps
while keeping $\sigma$ value constant. When the d value is decreased to 0.25 from 0.5, the solution remains
convergent. Nevertheless, if the d value is increased, such as 0.75, distortion in wave curve is observed and
the solution obtained is divergent. Comparing Figures \ref{fig:FTBSsigma12d05} and \ref{fig:FTBSsigma12d025},
it is observed that the decrease in the amplitude of the waves is more significant for higher d values. In addition,
the wave length increases faster for d = 0.5 compared to the increase in the wave length for d = 0.25.

\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/ConvectionDiffusion/sigma025d05.eps}
	\caption{Convection diffusion solution by the explicit FTBS method with $\sigma= 0.25$ and $d=0.5$ at $nt=0$ and $nt=20$.}
	 \label{fig:FTBSsigma025d05}
\end{figure}
\vspace{1cm}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/ConvectionDiffusion/sigma05d05.eps}
	\caption{Convection diffusion solution by the explicit FTBS method with $\sigma= 0.5$ and $d=0.5$ at $nt=0$ and $nt=25$.}
	 \label{fig:FTBSsigma05d05}
\end{figure}
\newpage
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/ConvectionDiffusion/sigma075d05.eps}
	\caption{Convection diffusion solution by the explicit FTBS method with $\sigma= 0.75$ and $d=0.5$ at $nt=0$ and $nt=55$.}
	 \label{fig:FTBSsigma075d05}
\end{figure}
\vspace{1cm}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/ConvectionDiffusion/sigma12d05.eps}
	\caption{Convection diffusion solution by the explicit FTBS method with $\sigma= 1.2$ and $d=0.5$ at different time steps.}
	 \label{fig:FTBSsigma12d05}
\end{figure}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/ConvectionDiffusion/sigma12d025.eps}
	\caption{Convection diffusion solution by the explicit FTBS method with $\sigma= 1.2$ and $d=0.25$ at different time steps.}
	 \label{fig:FTBSsigma12d025}
\end{figure}
\vspace{1cm}
\begin{figure}[H]
	\centering
	\includegraphics[max height=8.5cm]{graphs/FTBS/ConvectionDiffusion/sigma12d075.eps}
	\caption{Convection diffusion solution by the explicit FTBS method with $\sigma= 1.2$ and $d=0.75$ at different time steps.}
	 \label{fig:FTBSsigma12d075}
\end{figure}

\newpage

Overall, if the solutions of the convection-diffusion equation and the convection equation are
compared, it can be denoted that for $\sigma$ values lower than 1.2 the FTBS equation gives convergent
solutions for the convection equation whereas for the convection-diffusion equation the solutions
obtained by FTBS equation is divergent.

\subsection{Solution of the given FDE}

\begin{figure}[!h]
	\centering
	\includegraphics[max height=8.5cm]{graphs/Question4/sigma03d05.eps}
	\caption{Solution of given FDE with $\sigma= 0.3$ and $d=0.5$ at different time steps.}
	\label{fig:Q4_1}
\end{figure}

 \vspace{1cm}

 Stability of given FDE is numerically experimented for $\sigma$ and $d$ values between 0 and 2 with 0.05 spacing.
 Some of the results this experimentation is given in Figures \ref{fig:Q4_1}, \ref{fig:Q4_2} and \ref{fig:Q4_3}.
 As a result, it is concluded that given FDE is unconditionally unstable. Although given FDE is found consistent
 in Section \ref{sub:cons}, as FDE is found to be unstable, numerical solution does not converge.
\newpage

\begin{figure}[!h]
	\centering
	\includegraphics[max height=8.5cm]{graphs/Question4/sigma08d08.eps}
	\caption{Solution of given FDE with $\sigma= 0.8$ and $d=0.8$ at different time steps.}
	\label{fig:Q4_2}
\end{figure}

\begin{figure}[!h]
	\centering
	\includegraphics[max height=8.5cm]{graphs/Question4/sigma12d06.eps}
	\caption{Solution of given FDE with $\sigma= 1.2$ and $d=0.6$ at different time steps.}
	\label{fig:Q4_3}
\end{figure}

\newpage

\subsection{Bonus: Implicit Solution}

\begin{figure}[!h]
	\centering
	\includegraphics[max height=8.5cm]{graphs/Bonus/sigma05d05.eps}
	\caption{Implicit Solution of Convection diffusion equation with $\sigma= 0.5$ and $d=0.5$}
	\label{fig:b_1}
\end{figure}

\vspace{1cm}

Implicit FDE derived in Equation \ref{eqn:implicit} is solved for various $\sigma$ and $d$ values.
It is found that solution converges for every $\sigma$ and $d$ combination. Therefore implicit method
is unconditionally stable. Figures \ref{fig:b_1}, \ref{fig:b_2} and \ref{fig:b_3} shows some of the solutions.
As this method is unconditionally stable, a larger timestep can be used for calculations. But it should be noted that the
accuracy of the solution decreases as timestep increases. Because of that, the time step size is still limited if one wants
an accurate solution.

\newpage

\begin{figure}[!h]
	\centering
	\includegraphics[max height=8.5cm]{graphs/Bonus/sigma12d05.eps}
	\caption{Implicit Solution of Convection diffusion equation with $\sigma= 1.2$ and $d=0.5$}
	\label{fig:b_2}
\end{figure}

\begin{figure}[!h]
	\centering
	\includegraphics[max height=8.5cm]{graphs/Bonus/sigma05d12.eps}
	\caption{Implicit Solution of Convection diffusion equation with $\sigma= 0.5$ and $d=1.2$}
	\label{fig:b_3}
\end{figure}

\newpage

\section{Conclusion}
In this homework, the convection-diffusion equation was solved by using different
finite-difference equations and convection equation was solved with the explicit
FTBS equation. First, in the solution of the convection-diffusion equation,
the explicit FTCS equation was used and it was shown that the solution was
conditionally stable. The reason of is that for some combination of $\sigma$ and $d$ values,
convergent, hence stable solutions were determined whereas solutions were unstable
for other combinations, such as $\sigma =1.2$ and $d=0.5$ or  $\sigma =0.5$ and $d=0.75$.
Then, the explicit FTBS equation was used to solve the convection equation. The results showed
that as the value of $\sigma$ increased up to some value, the solutions were stable and
the shrinkage in the waves of solution curves is less significant. Also, the solution
was distorted and unstable for $\sigma=1.2$. Afterwards, the solution of the convection-diffusion equation was calculated with the explicit FTBS method. It was seen that
with constant d value ($d=0.5$), unstable and disrupted solution curves were observed
for some $\sigma$ values such as 0.25, 0.5, and 0.75. On the other hand, for constant
$\sigma=1.2$, with increased d value up to some value, the change in the waves of solutions,
which were convergent, became more insignificant. When $d$ were increased to 0.75, a divergent
solution was observed. At the next part of the homework, consistency analysis was made,
and it was determined that Equation \ref{equation:q4} is consistent. However, it was seen that
from the solutions of the Equation \ref{equation:q4} with different $\sigma$ and d values,
it is divergent and unstable. In the last part of the homework, the solution of the convection-diffusion equation was calculated with the BTCS Euler implicit method. All solutions obtained in
Subsection 3.6 were convergent with different $\sigma$ and d values. Therefore, it may be more
reasonable to solve the convection-diffusion equation with the implicit FDE since it provided convergent
solutions in a more large range of $\sigma$ and d values than the explicit FDEs.
\end{document}


\chapter{Modeling and Model Validation}
\label{modeling}

\begin{figure}[thpb]
      \centering
      \includegraphics[width=0.8\columnwidth]{tex/img/superball_roverscape2_cropped.jpg}
      \caption{SUPERball, fully assembled, in the NASA Ames Research Center Roverscape.}
      \label{fig:SB}
\end{figure}

As part of our research for the NASA Innovative Advanced
Concepts  (NIAC)  program,  we  are  developing  the \SB{} (Spherical Underactuated Planetary Exploration Robot),
which is a compliant icosahedron tensegrity robot designed
for   planetary   landing   and   exploration, seen in figure \ref{fig:SB}.   Tensegrity   robots
are  soft  machines  which  are  uniquely  able  to  compliantly
absorb  forces  and  interact  with  unstructured  environments.
However, instead of engineering a single new robot, we have
chosen  to  develop  a  fundamentally  reusable  component  for
tensegrity  robots  by  creating  a  modular  robotic  tensegrity
strut which contains an integrated system of power, sensing,
actuation, and communications. The purpose is to enable the
exploration of the wide range of possible tensegrity robotic
morphologies  by  simply  combining  the  robotic  struts  into
new systems.

Though there is much prior work in a variety of theoretical
areas for tensegrities, engineering knowledge of constructing
practical  tensegrity  robots  is  limited.  Since  a  staggering
variety  of  different  tensegrity  structures  can  be  constructed
from  collections  of  simple  sticks  and  strings, we have made it a priority
to develop self-contained robotic tensegrity struts which can
be  used  to  explore  and  build  a  wide  range  of  tensegrity
robots  simply  by  combining  them  into  novel  structures.
Our  designs  are  driven  by  experimental  results  obtained
from  a  previous  prototype,  ReCTeR  (Reservoir  Compliant
Tensegrity Robot) in combination with simulation results of
our validated tensegrity simulator NTRT (NASA Tensegrity
Robotics Toolkit)~\cite{2917079}\cite{Caluwaerts2013rsif}.

In  order  to  develop  SUPERball  from  ReCTeR's  design
limitations as well as our lab’s need for rapid experimentation
of  various  tensegrity  configurations  and  morphologies,  we
came  up  with  a  modular  tensegrity  platform  to  research
large  scale  robotic  tasks;  e.g.  a  tensegrity  planetary  probe
to explore Saturn's moon Titan.
%Our lab obtained design requirements through an iterative
%approach  involving  NTRT  and  ReCTeR.  As  we  validated  our  NTRT  simulator  by  experimental  validation
%with  ReCTeR~\cite{Caluwaerts2013rsif} and can  now  quickly  evaluate  various
Our lab obtained design requirements through an iterative approach with validated our NTRT simulator by experimental comparison with ReCTeR~\cite{Caluwaerts2013rsif}.
We now can quickly  evaluate  various
tensegrity  configurations  in  simulation  to  find  optimal  mechanical  design  goals.  In conjunction with the  NTRT  solver,  we  also
incorporated  results  obtained  with  our  (open  source)  Euler
Lagrange solver based on Skelton's work~\cite{Skelton2009} and measurements on ReCTeR.
The initial design requirements obtained from the NTRT simulations, refined designs after a first prototype build, and how these compare to other tensegrity robotic systems are given in Table \ref{design_req}.

\begin{table*}[ht]
%\begin{minipage}[t][\linewidth]{
\caption{\SB{} and Related Robots Design Overview.}
\label{design_req}

\begin{center}%
\resizebox{\columnwidth}{!}{%
\begin{tabular}{lrrrcrrrrrrr}
%\hline
&$\bm{l_{strut}}$ & $\bm{\Delta l_{act}}$ & $\bm{k_{passive}}$ & \bf{tethered?} & \bf{control} & $\bm{f_{act}}$ & \bf{\#act.} & \bf{mass} & \bf{sensors} &\bf{actuators} &\bf{ref.} \\ \hline \hline
\bf{Pneumatic}&\SI{.57}{m} & - & - & Y & open loop & \SI{800}{\newton} & \num{24} & \SI{3.3}{\kg}& none & McKibben& \cite{Koizumi2012b} \\
\bf{ReCTeR}&\SI{1}{m} & \SI{0.3}{\metre} & \SI{28.4}{\newton\per\metre} & N & closed loop & \SI{12}{\newton} & \num{6} & \SI{1.1}{\kg} & F, L, IMU & DC & \cite{Caluwaerts2013rsif} \\
\bf{Rapid Proto Kit}&\SI{.69}{m} & \SI{0.005}{\metre} & \SI{1193}{\newton\per\metre} & N & open loop  & $<$\SI{45}{\newton} & \num{24} & \SI{2.7}{\kg}& none & linear DC &\cite{kim2014rapid} \\
\bf{\SB{} 2014}&\SI{1.5}{m} & \SI{0.2}{\metre} & \SI{613}{\newton\per\metre} & N & closed loop & \SI{140}{\newton}  & \num{12} & \SI{12}{\kg}& F, L, $\tau$, IMU & BLDC& \\
\bf{\SB{} 2015}&\SI{1.7}{m} & \SI{0.42}{\metre} & \SI{998}{\newton\per\metre} & N & closed loop & \SI{250}{\newton} & \num{12} & \SI{21}{\kg} & F, L, $\tau$, IMU & BLDC&
%Tensegrity Kit
%\SB{} ICRA 2014 &$1.5\mbox{m}$ & $0.26 {\mbox{m}}/{\mbox{s}}$ & $500 \mbox{N}/\mbox{m}$ & $100\mbox{Hz}$ & $3 \mbox{Nm}$ \\
%\SB{} ICRA 2015
%\hline

\end{tabular}
}
\end{center}
\bigskip
\fontsize{10pt}{12pt}\selectfont
The variable $l_{strut}$ indicates the length of a strut, $\Delta l_{act}$ is the nominal spring-cable retraction length in tension, $k_{passive}$ is the linear stiffness coefficient of a passive spring-cable (or active spring-cable if fully actuated), tethered indicates if the robot is powered externally or by internal systems, control indicates whether sensor feedback is used, $f_{act}$ is the nominal actuated spring-cable tension and \#act. is the number of actuators. In the sensors column, F represents a linear force sensor (for cables), L is cable length sensor (in the form of motor encoders), $\tau$ represents a torque sensor for motors, and IMU represents an accelerometer/gyroscope inertial motion sensing unit. Actuators are specified as DC motors or brushless DC (BLDC) motors. The SUPERball 2014 values are revised original design requirements based on NTRT simulations, and changed to the 2015 values after additional detail design. %

\vspace{-0.2cm}

%\end{minipage}
\end{table*}

The work presented here is work verifying our in house tensegrity simulators.
In order to achieve this, the group decided to use a \SB{} like structure with a center payload.
This is believed to be closer to the proposed build profile of a real tensegrity probe, where the main science modules will be contained within the payload.
Protecting this science payload is the main goal for and EDL scenario.
Figure \ref{fig:NTRT_SB} shows a 3-D representation of \SB{} with a payload generated within NTRT.

\begin{figure}[thpb]
      \centering
      \includegraphics[width=0.8\columnwidth]{tex/img/1.png}
      \caption{SUPERball with a payload modeled within NTRT.}
      \label{fig:NTRT_SB}
\end{figure}

\section{Euler-Lagrange Model}
In order to verify the simulation results produced by our NTRT simulator, we decided to compare the behavior of the NTRT to a published analytic model for tensegrity systems.
We choose to use Skelton's dynamic equations because it is a well accepted and used model.
It may be found in his \emph{Tensegrity Systems} book \cite{skelton_tensegrity_2009} which is based on his work in \cite{skelton2005dynamics}.
In order to solve the dynamic equations with interactions with the environment, an Euler-Lagrange approach is used as well as Skelton's constrained class one structure.
The lagrange equation for a constrained rod is given by
\begin{equation}
\label{eq:lagrange}
L = T - V - c
\end{equation}
where
\begin{align}
\mathbf{b} &= l^{-1}(\mathbf{n}_{j}-\mathbf{n}_{i})\label{eq:normalizedVector}\\
c &= \frac{\mathbf{J}\xi}{2}(\mathbf{b}^{T}\mathbf{b}-1)\label{eq:constraint}
\end{align}
Equation \eqref{eq:normalizedVector} is the normalized vector of a rod with \(\mathbf{n}_{i,j}\) the nodal positions in \(R^3\), and equation \eqref{eq:constraint} contains the lagrange multiplier \(\xi\) to keep \eqref{eq:normalizedVector} constrained.
\(\mathbf{J}\) is also defined as the inertia matrix for a one dimensional rod in three dimensional space.
In order to define the system of \(k\) rods we need to define a combined Lagrangian as
\begin{equation}
\mathbf{L} = \sum_{i=1}^{k} L_{i}\label{eq:combinedLagrangian}
\end{equation}
where \(L_{i}\) is the Lagrange function for each rod.
Using the approach outlined in Skelton's book for deriving the equations of motion, we can then derive the configuration matrix
\begin{equation}
\mathbf{Q} = \begin{bmatrix}
	\mathbf{R} & \mathbf{B}
	\end{bmatrix}\label{eq:configMatrix}
\end{equation}
where \(\mathbf{R}\) and \(\mathbf{B}\) are matrices containing the translational and rotational vectors, respectively. They have the form
\begin{align}
\mathbf{R} &= \begin{bmatrix}
	\mathbf{r}_{1} & \cdots & \mathbf{r}_{k}
	\end{bmatrix}\label{eq:transR}\\
\mathbf{B} &= \begin{bmatrix}
	\mathbf{b}_{1} & \cdots & \mathbf{b}_{k}
	\end{bmatrix}\label{eq:rotB}
\end{align}
Also using the procedure to derive generalized forces within Skelton's book, the systems's generalized force equations are computed as
\begin{equation}
\mathbf{F}_{\mathbf{Q}} = \begin{bmatrix}
	\mathbf{F}_{\mathbf{R}} & \mathbf{F}_{\mathbf{B}}
	\end{bmatrix}\label{eq:generalizedForce}
\end{equation}
with
\begin{align}
\mathbf{F}_{\mathbf{R}} &= \begin{bmatrix}
	\mathbf{f}_{\mathbf{r}_{1}} & \cdots & \mathbf{f}_{\mathbf{r}_{k}}
	\end{bmatrix}\label{eq:gForceR}\\
\mathbf{F}_{\mathbf{B}} &= \begin{bmatrix}
	\mathbf{f}_{\mathbf{b}_{1}} & \cdots & \mathbf{f}_{\mathbf{b}_{k}}
	\end{bmatrix}\label{eq:gForceB}
\end{align}
Finally, we can define the resulting equations of motion in a compact form as
\begin{equation}
(\ddot{\mathbf{Q}} + \mathbf{Q}\mathbf{\Xi})\mathbf{M} = \mathbf{F}_{\mathbf{Q}}\label{eq:compactForm}
\end{equation}
where
\begin{align}
\mathbf{\Xi} &= diag\begin{bmatrix}
	0,\cdots,0,\xi_{1},\cdots,\xi_{k}
	\end{bmatrix}\label{eq:lagrangeMatrix}\\
\mathbf{M} &= diag\begin{bmatrix}
	m_{1},\cdots,m_{k},J_{1},\cdots,J_{k}
	\end{bmatrix}\label{massMatrix}
\end{align}
This approach was then implemented in Python utilizing a 4th order Runge-Kutta formula for solving the system of ordinary differential equations.
In order to implement a gravitational field, a force distribution function is applied along the length of each rod and calculated as a nodal force depending on the given density of the rod.
This external force is then applied to the nodes during each time step, simulating a gravitational field.

\section{Detailed Impact Simulations and Cross-Validation Using Two Simulators}
The NTRT simulator is the most general purpose, allowing us to explore control algorithms and complex environmental interactions, but it is an iterative discrete solver that we were concerned might not be providing accurate answers.  The E-L solver, on the other hand, has a much stronger analytical basis and should provide very accurate answers, but is limited because some of the nodes (rod ends) must be constrained and locked into place.  This is unrealistic for the deformation caused during landing, and makes it an inappropriate choice for mobility and controls research.
If ground contact forces are incorporated into the E-L solver and code optimization implemented, it could be used in conjunction with a unscented kalman filter for state estimation propogation.
This tool could then be used to develop online learning algorithms for mobility research.

In this section, we compare the NTRT simulator and E-L solver at the moment of impact with the ground.
The simulations are compared at the moment of impact with the ground because our implementation of the analytic E-L solver requires select nodes to be constrained.
We setup the structure so that it is barely in contact with the ground and is in balance at time equal to 0.
In both simulations, we add an initial velocity equal to the terminal velocity of Titan, and compared each vertical trajectory, vertical velocity, and vertical acceleration of the payload.
Since the structure's horizontal speed is zero at the beginning and the structure is symmetrical, the payload's horizontal components of position, velocity and acceleration are zero.
As it can be seen in the Figures \ref{fig:vsPosition} and \ref{fig:vsVelocity}, both simulators closely match and generate the same results for position and velocity with the error margin close to zero.
Comparing the accelerations generated by two simulators (Figure \ref{fig:vsAccelerations}), it can be seen that there is a bigger difference.
The reason behind this difference is the fact that NTRT uses Bullet, which is a discrete time simulator and accelerations are calculated using two point estimations from velocities at the timestep before.  Yet, even with these differences in accelerations, our conclusion at the end of the comparison is that both simulators showed the same basic dynamics and their results were close enough that we could move forward using the more general purpose NTRT Simulator for our controls, mobility, and landing experiments.

\begin{figure}[htb]
   \centering
   \includegraphics[width=0.8\columnwidth]{tex/images/landing/bulletVsEL/SimVsEL}
   \caption{NTRT vs EL: Vertical Position}
   \label{fig:vsPosition}
\end{figure}

\begin{figure}[htb]
   \centering
   \includegraphics[width=0.8\columnwidth]{tex/images/landing/bulletVsEL/Velocities}
   \caption{NTRT vs EL Vertical Velocity}
   \label{fig:vsVelocity}
\end{figure}
\begin{figure}[htb]
   \centering
   \includegraphics[width=0.8\columnwidth]{tex/images/landing/bulletVsEL/VelocityDerivatives_SimVsEL}
   \caption{NTRT vs EL Vertical Acceleration}
   \label{fig:vsAccelerations}
\end{figure}

\section{Simulated Drop Tests and Payload Protection}

Finally, we performed extensive analysis on drop tests and the protection provided to a payload.   As expected, we found that by varying the rod lengths, which impacts the stroke distance for the payload to decelerate, we could control the maximum deceleration experienced by the payload while ensuring that it did not collide with the ground or structure.  For example, with rods of 1.5 meters in length, our payload experienced a max deceleration of 21.4G when landing at 15 m/s. In figure \ref{fig:rodvsG} we show the results of a series of drop tests with different rod lengths and show the resulting maximum deceleration and forces experienced in the tension members.   As can be seen from these graphs, even for reasonable rod lengths, the maximum G's are acceptable for most instruments, and the maximum forces experienced by the cables are easily within ranges that can be engineered for.  In all tests we kept the total system mass constant, at 100kg (which is 70kg for the payload and 5kg per rod) in order to highlight the impact of structural geometry and rod length.  For the tension members we used spring constants of 44 kN/m for the cables around the perimeter and 10 kN/m for the cables attached to the payload.  Also, the results in Figure \ref{fig:rodvsG} were found using the landing orientation of 35 degrees around X axis and 45 degrees around Z axis, which we selected from our orientation studies discussed below.

\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\columnwidth]{tex/images/rodvsG_fixed2}
\caption{{\em {\bf Landing Forces Study}. This shows how rod length impacts maximum deceleration of the payload and  the maximum forces experienced by the tension cables.  All tests were conducted with a landing velocity of 15 m/s onto a hard surface.}}
\label{fig:rodvsG}
\end{figure}

A very interesting point to consider is that the mass of our system will grow in a linear fashion with the length in the rods, while providing increasing payload protection.  On the other hand, the mass of airbags increases with the square of the radius, which is one of the reasons that the MSL rover, with its increased size and mass, had to switch from the airbag approach to the more complex Sky Crane approach.  While this study has focused on small light-weight mission concepts, we expect that there are compelling advantages to scaling up to handle larger payloads and we look forward to studying this further in the future.

\section{Landing Orientation Studies}
In order to study how landing orientation affects payload decelerations and impact events, we conducted a systematic study of landing orientations.  Since we wanted to get meaningful data, even for bad orientations, we used a larger tensegrity with 4 meter rods so the data wouldn't saturate.  Our success criteria for this study was that the decelerations had to stay under an upper limit of 25G deceleration of the payload, and the payload had to avoid collision with the ground or parts of the tensegrity structure.  Figure \ref{fig:landingHeatMapRot} shows the orientations that were safely within these criteria (black) or failed one or both of the criteria (colored).  By using a simple trailing streamer during descent it would be possible to control landing at an optimal orientation and enable the use of smaller structures with shorter rods because the orientation control would maximize the available stroke for the payload to decelerate within the structure.  Conversely, we can use these studies to know what the worst possible landing scenario will be and choose a structure size which will allow safe landing at any orientation.

\begin{figure}[htbp]
   \centering
   \includegraphics[width=0.8\columnwidth]{tex/images/landing/landingHeatMapRot.png}
   \caption{\em Heat map of the maximum acceleration that the payload encounters for all possible landing orientations. Black areas are safe, colored areas are where the payload does not meet one or both success criteria.}
   \label{fig:landingHeatMapRot}
\end{figure}

\section{Conclusions from Simulation Experiments}
In our landing analysis we developed and cross-validated two different simulation methods that allowed us to explore the capabilities of a tensegrity structure to absorb the forces of landing and to simultaneously protect a delicate payload.  This analysis confirmed that indeed it is possible to do so using a 6-bar tensegrity probe while maintaining maximum decelerations experienced by the instrument-containing payload to forces less than 25G, despite the structure landing at 15 m/s (which is greater than terminal velocity on Titan).   Comparing this to the Huygens probe's landing acceleration of \(32G\) \cite{lorenz1994huygens}, the tensegrtiy probe will have a \(43\% \) reduction in \(G\) forces experienced by the scientific payload, despite the Huygens probe's use of parachutes to land at 1/3 of the speed of our tensegrity probe.


% Homework Template - myTemplate.tex
% Created by Minhduc Cao for ICS 6B (Gassko)
% ~ A general template for assignments in LaTeX
\documentclass[letterpaper]{article}
\usepackage[margin=1in]{geometry}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{times}
%\hbadness=99999
\renewcommand{\qedsymbol}{$\blacksquare$}
\begin{document}

\title{Homework \#}
\author{Name Here\\
        ICS 6B - Lecture A/B}
\date{\today}
\maketitle

% Copy-paste and edit parts as necessary
\section*{1.1.1}
\subsection*{a.}

\subsection*{b.}

\subsection*{c.}

\subsection*{d.}

\subsection*{e.}

\subsection*{f.}

\subsection*{g.}

\subsection*{h.}

\pagebreak

% 2 VARIABLE TRUTH TABLE
\begin{tabular}{|c|c|c|}
 \hline
 $p$ & $q$ & $final$\\
 \hline
 T & T & x\\
 T & F & x\\
 F & T & x\\
 F & F & x\\
 \hline
\end{tabular}

% 3 VARIABLE TRUTH TABLE
\begin{tabular}{|c|c|c|c|}
 \hline
 $p$ & $q$ & $r$ & $final$\\
 \hline
 T & T & T & x\\
 T & T & F & x\\
 T & F & T & x\\
 T & F & F & x\\
 F & T & T & x\\
 F & T & F & x\\
 F & F & T & x\\
 F & F & F & x\\
 \hline
\end{tabular}

% LOGICAL EQUIVALENCE PROOF TABLE
\begin{tabular}{|c|c|}
 \hline
 Expression & Law Applied\\
 \hline
 $.$ & Original expression\\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 $.$ & \\
 \hline
\end{tabular}

% PROOF
\begin{proof}
    ...
\end{proof}

\end{document}


% This is a sample documentation for Compass in the tex format.
% We restrict the use of tex to the following subset of commands:
%
% \section, \subsection, \subsubsection, \paragraph
% \begin{enumerate} (no-nesting), \begin{quote}, \item
% {\tt ... }, {\bf ...}, {\it ... }
% \htmladdnormallink{}{}
% \begin{verbatim}...\end{verbatim} is reserved for code segments
% ...''
%

\section{Right Shift Mask}
\label{RightShiftMask::overview}

% write your introduction
Do not assume that a right shift operation is implemented as either an
arithmetic (signed) shift or a logical (unsigned) shift. If E1 in the
expression E1 >> E2 has a signed type and a negative value, the
resulting value is implementation defined and may be either an
arithmetic shift or a logical shift. Also, be careful to avoid
undefined behavior while performing a bitwise shift.
\subsection{Parameter Requirements}

%Write the Parameter specification here.
No Parameter Required.

\subsection{Implementation}

%Details of the implementation go here.
Upon finding a right shift we trace parent pointers up until we find
a bit and operator.  If we find this bitwise and then we return.  If
we make it to the basic block node of the statement we raise an alert.

\subsection{Non-Compliant Code Example}

% write your non-compliant code subsection
For implementations in which an arithmetic shift is performed and the
sign bit can be propagated as the number is shifted.
\begin{verbatim}
int stringify;
char buf[sizeof("256")];
sprintf(buf, "%u", stringify >> 24);
% write your non-compliant code example

\end{verbatim}
If stringify has the value 0x80000000, stringify >> 24 evaluates to
0xFFFFFF80 and the subsequent call to sprintf() results in a buffer overflow.
\subsection{Compliant Solution}
For bit extraction, make sure to mask off the bits you are not
interested in.
% write your compliant code subsection

\begin{verbatim}
int stringify;
char buf[sizeof("256")];
sprintf(buf, "%u", ((number >> 24) & 0xff));
% write your compliant code example

\end{verbatim}

\subsection{Mitigation Strategies}
\subsubsection{Static Analysis}

Compliance with this rule can be checked using structural static analysis checkers using the following algorithm:

\begin{enumerate}
\item Find the bitwise and
\item climb parent tree
\item alert if parent null or basicblock found.
\end{enumerate}

\subsection{References}

% Write some references
\htmladdnormallink{ISO/IEC 9899-1999:TC2}{https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References}
[Dowd 06] Chapter 6, ``C Language Issues''
[ISO/IEC 9899-1999] Section 6.5.7, ``Bitwise shift operators''
[ISO/IEC 03] Section 6.5.7, ``Bitwise shift operators''