\nwfilename{_src/2021/day/01.nw}\nwbegindocs{0}\newpage% ===> this file was generated automatically by noweave --- better not edit it
\section{Day 1: Sonar Sweep}
\todoo{Copy description}
\marginnote{\url{https://adventofcode.com/2021/day/1}}
\nwenddocs{}\nwfilename{_src/2021/haskell/01.nw}\nwbegindocs{0}\subsection{Haskell solution}

\newthought{The input} is just a list of natural numbers.

\nwenddocs{}\nwbegincode{1}\sublabel{NW2fQ2fr-2S9BvQ-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2fQ2fr-2S9BvQ-1}}}\moddef{Parse the input.~{\nwtagstyle{}\subpageref{NW2fQ2fr-2S9BvQ-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2fQ2fr-12NRmi-1}}\nwenddeflinemarkup
\nwlinkedidentc{getInput}{NW2dtzue-2ga90v-1} :: IO [Integer]
\nwlinkedidentc{getInput}{NW2dtzue-2ga90v-1} = parseInput (some natural) $(inputFilePath)
\nwused{\\{NW2fQ2fr-12NRmi-1}}\nwidentuses{\\{{\nwixident{getInput}}{getInput}}}\nwindexuse{\nwixident{getInput}}{getInput}{NW2fQ2fr-2S9BvQ-1}\nwendcode{}\nwbegindocs{2}\nwdocspar

\newthought{The general solution} is to count pairwise increases.

\nwenddocs{}\nwbegincode{3}\sublabel{NW2fQ2fr-1DYA9Y-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2fQ2fr-1DYA9Y-1}}}\moddef{Count pairwise increases.~{\nwtagstyle{}\subpageref{NW2fQ2fr-1DYA9Y-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2fQ2fr-12NRmi-1}}\nwenddeflinemarkup
countPairwiseIncreases :: Ord a => Int -> [a] -> Int
countPairwiseIncreases n =
  count (== LT)
    . uncurry (zipWith compare)
    . (id &&& drop n)
\nwused{\\{NW2fQ2fr-12NRmi-1}}\nwendcode{}\nwbegindocs{4}\nwdocspar

\newthought{For example,} in the following list there are seven pairwise increases.

\nwenddocs{}\nwbegincode{5}\sublabel{NW2fQ2fr-23nbvF-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2fQ2fr-23nbvF-1}}}\moddef{Example~{\nwtagstyle{}\subpageref{NW2fQ2fr-23nbvF-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2fQ2fr-12NRmi-1}}\nwenddeflinemarkup
example :: [Integer]
example = [199, 200, 208, 210, 200, 207, 240, 269, 260, 263]
\nwused{\\{NW2fQ2fr-12NRmi-1}}\nwendcode{}\nwbegindocs{6}\nwdocspar

\begin{minted}{haskell}
  λ> countPairwiseIncreases 1 example
  7
\end{minted}

The seven pairwise increases are as follows:

\begin{minted}{haskell}
  [(199,200), (200, 208), (208, 210), (200, 207), (207, 240), (240, 269), (260, 263)]
\end{minted}

\newthought{For Part One}, simply count pairwise increases.

\nwenddocs{}\nwbegincode{7}\sublabel{NW2fQ2fr-3ajnFh-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2fQ2fr-3ajnFh-1}}}\moddef{Solve Part One.~{\nwtagstyle{}\subpageref{NW2fQ2fr-3ajnFh-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2fQ2fr-12NRmi-1}}\nwenddeflinemarkup
\nwlinkedidentc{partOne}{NW2dtzue-4G9gVP-1} :: [Integer] -> Int
\nwlinkedidentc{partOne}{NW2dtzue-4G9gVP-1} = countPairwiseIncreases 1
\nwused{\\{NW2fQ2fr-12NRmi-1}}\nwidentuses{\\{{\nwixident{partOne}}{partOne}}}\nwindexuse{\nwixident{partOne}}{partOne}{NW2fQ2fr-3ajnFh-1}\nwendcode{}\nwbegindocs{8}\nwdocspar

\newthought{For Part Two}, count pairwise increases with an offset of \hs{3}.

\nwenddocs{}\nwbegincode{9}\sublabel{NW2fQ2fr-3nTTD5-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2fQ2fr-3nTTD5-1}}}\moddef{Solve Part Two.~{\nwtagstyle{}\subpageref{NW2fQ2fr-3nTTD5-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2fQ2fr-12NRmi-1}}\nwenddeflinemarkup
\nwlinkedidentc{partTwo}{NW2dtzue-2ZOhXn-1} :: [Integer] -> Int
\nwlinkedidentc{partTwo}{NW2dtzue-2ZOhXn-1} = countPairwiseIncreases 3
\nwused{\\{NW2fQ2fr-12NRmi-1}}\nwidentuses{\\{{\nwixident{partTwo}}{partTwo}}}\nwindexuse{\nwixident{partTwo}}{partTwo}{NW2fQ2fr-3nTTD5-1}\nwendcode{}\nwbegindocs{10}\nwdocspar

\newthought{Bring it} all together.

\nwenddocs{}\nwbegincode{11}\sublabel{NW2fQ2fr-12NRmi-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2fQ2fr-12NRmi-1}}}\moddef{Day01.hs~{\nwtagstyle{}\subpageref{NW2fQ2fr-12NRmi-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup
module AdventOfCode.Year2021.Day01 where

import AdventOfCode.Input (parseInput)
import AdventOfCode.TH (defaultMain, inputFilePath)
import AdventOfCode.Util (count)
import Control.Arrow ((&&&))
import Text.Trifecta (natural, some)

main :: IO ()
main = $(defaultMain)

\LA{}Parse the input.~{\nwtagstyle{}\subpageref{NW2fQ2fr-2S9BvQ-1}}\RA{}

\LA{}Example~{\nwtagstyle{}\subpageref{NW2fQ2fr-23nbvF-1}}\RA{}

\LA{}Solve Part One.~{\nwtagstyle{}\subpageref{NW2fQ2fr-3ajnFh-1}}\RA{}

\LA{}Solve Part Two.~{\nwtagstyle{}\subpageref{NW2fQ2fr-3nTTD5-1}}\RA{}

\LA{}Count pairwise increases.~{\nwtagstyle{}\subpageref{NW2fQ2fr-1DYA9Y-1}}\RA{}
\nwnotused{Day01.hs}\nwendcode{}\nwbegindocs{12}\nwdocspar
\nwenddocs{}\nwfilename{_src/2021/day/02.nw}\nwbegindocs{0}\newpage
\section{Day 2: Dive!}
\marginnote{\url{https://adventofcode.com/2021/day/2}}

Now, you need to figure out how to pilot this thing.

It seems like the submarine can take a series of commands like {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 1}, {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ 2}, or {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}\hs{ 3}:
\begin{itemize}
\item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ x} increases the horizontal position by \hs{x} units.
\item {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ x} increases the depth by \hs{x} units.
\item {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}\hs{ x} decreases the depth by \hs{x} units.
\end{itemize}

Note that since you're on a submarine, {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote} and {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote} affect your \textbf{depth}, and so they have the opposite result of what you might expect.

The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example:
\begin{minted}{text}
  forward 5
  down 5
  forward 8
  up 3
  down 8
  forward 2
\end{minted}

Your horizontal position and depth both start at \hs{0}. The steps above would then modify them as follows:
\begin{itemize}
  \item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 5} adds \hs{5} to your horizontal position, a total of \hs{5}.
  \item {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ 5} adds \hs{5} to your depth, resulting in a value of \hs{5}.
  \item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 8} adds \hs{8} to your horizontal position, a total of \hs{13}.
  \item {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}\hs{ 3} decreases your depth by \hs{3}, resulting in a value of \hs{2}.
  \item {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ 8} adds \hs{8} to your depth, resulting in a value of \hs{10}.
  \item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 2} adds \hs{2} to your horizontal position, a total of \hs{15}.
\end{itemize}

After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces \hs{150}.)

Calculate the horizontal position and depth you would have after following the planned course. \textbf{What do you get if you multiply your final horizontal position by your final depth?}

\newthought{Part Two}

Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated.

In addition to horizontal position and depth, you'll also need to track a third value, \textbf{aim}, which also starts at \hs{0}. The commands also mean something entirely different than you first thought:

\begin{itemize}
\item {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ x} increases your aim by \hs{x} units.
\item {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}\hs{ x} decreases your aim by \hs{x} units.
\item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ x} does two things:
  \begin{itemize}
  \item It increases your horizontal position by \hs{x} units.
  \item It increases your depth by your aim \textbf{multiplied by} \hs{x}.
  \end{itemize}
\end{itemize}

Again note that since you're on a submarine, {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote} and {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote} do the opposite of what you might expect: ``down'' means aiming in the positive direction.

Now, the above example does something different:
\begin{itemize}
\item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 5} adds \hs{5} to your horizontal position, a total of \hs{5}. Because your aim is \hs{0}, your depth does not change.
\item {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ 5} adds \hs{5} to your aim, resulting in a value of \hs{5}.
\item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 8} adds \hs{8} to your horizontal position, a total of \hs{13}. Because your aim is \hs{5}, your depth increases by $8*5=40$.
\item {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}\hs{ 3} decreases your aim by \hs{3}, resulting in a value of \hs{2}.
\item {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ 8} adds \hs{8} to your aim, resulting in a value of \hs{10}.
\item {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ 2} adds \hs{2} to your horizontal position, a total of \hs{15}. Because your aim is \hs{10}, your depth increases by $2*10=20$ to a total of \hs{60}.
\end{itemize}

After following these new instructions, you would have a horizontal position of \hs{15} and a depth of \hs{60}. (Multiplying these produces \hs{900}.)

Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. \textbf{What do you get if you multiply your final horizontal position by your final depth?}
\nwenddocs{}\nwfilename{_src/2021/haskell/02.nw}\nwbegindocs{0}\newpage
\subsection{Haskell solution}

A {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} is a change in horizontal position and a change in depth,
represented by \hrefootnote{https://hackage.haskell.org/package/linear/docs/Linear-V2.html\#t:V2}{a 2-dimensional vector}, \hrefootnote{https://hackage.haskell.org/package/base/docs/Data-Monoid.html\#t:Sum}{monoidal under addition}.

\nwenddocs{}\nwbegincode{1}\sublabel{NW2dtzue-1OzTRH-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-1}}}\moddef{Define some data types~{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwprevnextdefs{\relax}{NW2dtzue-1OzTRH-2}\nwenddeflinemarkup
newtype \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} = \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} \{unDirection :: V2 Int\}
  deriving stock (Eq, Show)
  deriving
    (Semigroup, Monoid)
    via (Sum (V2 Int))

\nwindexdefn{\nwixident{Direction}}{Direction}{NW2dtzue-1OzTRH-1}\eatline
\nwalsodefined{\\{NW2dtzue-1OzTRH-2}\\{NW2dtzue-1OzTRH-3}}\nwused{\\{NW2dtzue-1375sF-1}}\nwidentdefs{\\{{\nwixident{Direction}}{Direction}}}\nwendcode{}\nwbegindocs{2}\nwdocspar
The {\Tt{}\LA{}known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}\RA{}\nwendquote} are {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}, {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}, and {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}.

\nwenddocs{}\nwbegincode{3}\sublabel{NW2dtzue-38STh2-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}}\moddef{known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1r7xob-1}}\nwprevnextdefs{\relax}{NW2dtzue-38STh2-2}\nwenddeflinemarkup
\nwlinkedidentc{forward}{NW2dtzue-38STh2-2}, \nwlinkedidentc{down}{NW2dtzue-38STh2-3}, \nwlinkedidentc{up}{NW2dtzue-38STh2-4} :: Int -> \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}
\nwalsodefined{\\{NW2dtzue-38STh2-2}\\{NW2dtzue-38STh2-3}\\{NW2dtzue-38STh2-4}}\nwused{\\{NW2dtzue-1r7xob-1}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{down}}{down}}\\{{\nwixident{forward}}{forward}}\\{{\nwixident{up}}{up}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-38STh2-1}\nwindexuse{\nwixident{down}}{down}{NW2dtzue-38STh2-1}\nwindexuse{\nwixident{forward}}{forward}{NW2dtzue-38STh2-1}\nwindexuse{\nwixident{up}}{up}{NW2dtzue-38STh2-1}\nwendcode{}\nwbegindocs{4}\nwdocspar

{\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ x} increases the horizontal position by \hs{x} units.

\nwenddocs{}\nwbegincode{5}\sublabel{NW2dtzue-38STh2-2}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-2}}}\moddef{known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1r7xob-1}}\nwprevnextdefs{NW2dtzue-38STh2-1}{NW2dtzue-38STh2-3}\nwenddeflinemarkup
\nwlinkedidentc{forward}{NW2dtzue-38STh2-2} = \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} . flip V2 0
\nwindexdefn{\nwixident{forward}}{forward}{NW2dtzue-38STh2-2}\eatline
\nwused{\\{NW2dtzue-1r7xob-1}}\nwidentdefs{\\{{\nwixident{forward}}{forward}}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-38STh2-2}\nwendcode{}\nwbegindocs{6}\nwdocspar
{\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}\hs{ x} increases the depth by \hs{x} units.

\nwenddocs{}\nwbegincode{7}\sublabel{NW2dtzue-38STh2-3}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-3}}}\moddef{known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1r7xob-1}}\nwprevnextdefs{NW2dtzue-38STh2-2}{NW2dtzue-38STh2-4}\nwenddeflinemarkup
\nwlinkedidentc{down}{NW2dtzue-38STh2-3} = \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} . V2 0
\nwindexdefn{\nwixident{down}}{down}{NW2dtzue-38STh2-3}\eatline
\nwused{\\{NW2dtzue-1r7xob-1}}\nwidentdefs{\\{{\nwixident{down}}{down}}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-38STh2-3}\nwendcode{}\nwbegindocs{8}\nwdocspar
{\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote}\hs{ x} decreases the depth by \hs{x} units, i.e. {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote} with a \hs{negate}d \hs{x}.

\nwenddocs{}\nwbegincode{9}\sublabel{NW2dtzue-38STh2-4}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-4}}}\moddef{known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1r7xob-1}}\nwprevnextdefs{NW2dtzue-38STh2-3}{\relax}\nwenddeflinemarkup
\nwlinkedidentc{up}{NW2dtzue-38STh2-4} = \nwlinkedidentc{down}{NW2dtzue-38STh2-3} . negate
\nwindexdefn{\nwixident{up}}{up}{NW2dtzue-38STh2-4}\eatline
\nwused{\\{NW2dtzue-1r7xob-1}}\nwidentdefs{\\{{\nwixident{up}}{up}}}\nwidentuses{\\{{\nwixident{down}}{down}}}\nwindexuse{\nwixident{down}}{down}{NW2dtzue-38STh2-4}\nwendcode{}\nwbegindocs{10}\nwdocspar
Define a {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} parser using the {\Tt{}\LA{}known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}\RA{}\nwendquote}.

\nwenddocs{}\nwbegincode{11}\sublabel{NW2dtzue-1r7xob-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-1r7xob-1}}}\moddef{Define a Direction parser~{\nwtagstyle{}\subpageref{NW2dtzue-1r7xob-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwenddeflinemarkup
\nwlinkedidentc{direction}{NW2dtzue-1r7xob-1} :: Parser \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}
\nwlinkedidentc{direction}{NW2dtzue-1r7xob-1} = dir <*> (fromInteger <$> natural)
  where
    dir =
      symbol "\nwlinkedidentc{forward}{NW2dtzue-38STh2-2}" $> \nwlinkedidentc{forward}{NW2dtzue-38STh2-2}
        <|> symbol "\nwlinkedidentc{down}{NW2dtzue-38STh2-3}" $> \nwlinkedidentc{down}{NW2dtzue-38STh2-3}
        <|> symbol "\nwlinkedidentc{up}{NW2dtzue-38STh2-4}" $> \nwlinkedidentc{up}{NW2dtzue-38STh2-4}

\LA{}known directions~{\nwtagstyle{}\subpageref{NW2dtzue-38STh2-1}}\RA{}
\nwindexdefn{\nwixident{direction}}{direction}{NW2dtzue-1r7xob-1}\eatline
\nwused{\\{NW2dtzue-1375sF-1}}\nwidentdefs{\\{{\nwixident{direction}}{direction}}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{down}}{down}}\\{{\nwixident{forward}}{forward}}\\{{\nwixident{up}}{up}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-1r7xob-1}\nwindexuse{\nwixident{down}}{down}{NW2dtzue-1r7xob-1}\nwindexuse{\nwixident{forward}}{forward}{NW2dtzue-1r7xob-1}\nwindexuse{\nwixident{up}}{up}{NW2dtzue-1r7xob-1}\nwendcode{}\nwbegindocs{12}\nwdocspar
The puzzle input is a list of {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote}s.

\nwenddocs{}\nwbegincode{13}\sublabel{NW2dtzue-2ga90v-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-2ga90v-1}}}\moddef{Parse the input~{\nwtagstyle{}\subpageref{NW2dtzue-2ga90v-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup
\nwlinkedidentc{getInput}{NW2dtzue-2ga90v-1} :: IO [\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}]
\nwlinkedidentc{getInput}{NW2dtzue-2ga90v-1} = parseInput (some \nwlinkedidentc{direction}{NW2dtzue-1r7xob-1}) $(inputFilePath)
\nwindexdefn{\nwixident{getInput}}{getInput}{NW2dtzue-2ga90v-1}\eatline
\nwnotused{Parse the input}\nwidentdefs{\\{{\nwixident{getInput}}{getInput}}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{direction}}{direction}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-2ga90v-1}\nwindexuse{\nwixident{direction}}{direction}{NW2dtzue-2ga90v-1}\nwendcode{}\nwbegindocs{14}\nwdocspar

\newthought{The general solution} of the puzzle is to sum a list of additive monoids, extract the final position, and compute the \hs{product} of the horizontal position and depth.

\nwenddocs{}\nwbegincode{15}\sublabel{NW2dtzue-1ULoeY-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-1ULoeY-1}}}\moddef{Solve the puzzle~{\nwtagstyle{}\subpageref{NW2dtzue-1ULoeY-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwenddeflinemarkup
\nwlinkedidentc{solve}{NW2dtzue-1ULoeY-1} :: Monoid m => (m -> V2 Int) -> [m] -> Int
\nwlinkedidentc{solve}{NW2dtzue-1ULoeY-1} extract = product . extract . mconcat
\nwindexdefn{\nwixident{solve}}{solve}{NW2dtzue-1ULoeY-1}\eatline
\nwused{\\{NW2dtzue-1375sF-1}}\nwidentdefs{\\{{\nwixident{solve}}{solve}}}\nwendcode{}\nwbegindocs{16}\nwdocspar

\newthought{For Part One,} the additive monoid is {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote}.

\nwenddocs{}\nwbegincode{17}\sublabel{NW2dtzue-4G9gVP-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-4G9gVP-1}}}\moddef{Solve Part One~{\nwtagstyle{}\subpageref{NW2dtzue-4G9gVP-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwenddeflinemarkup
\nwlinkedidentc{partOne}{NW2dtzue-4G9gVP-1} :: [\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}] -> Int
\nwlinkedidentc{partOne}{NW2dtzue-4G9gVP-1} = \nwlinkedidentc{solve}{NW2dtzue-1ULoeY-1} unDirection
\nwindexdefn{\nwixident{partOne}}{partOne}{NW2dtzue-4G9gVP-1}\eatline
\nwused{\\{NW2dtzue-1375sF-1}}\nwidentdefs{\\{{\nwixident{partOne}}{partOne}}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{solve}}{solve}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-4G9gVP-1}\nwindexuse{\nwixident{solve}}{solve}{NW2dtzue-4G9gVP-1}\nwendcode{}\nwbegindocs{18}\nwdocspar

\newthought{For Part Two,} the additive monoid is {\Tt{}\nwlinkedidentq{Aim}{NW2dtzue-1OzTRH-2}\nwendquote}, i.e. an integer.

\nwenddocs{}\nwbegincode{19}\sublabel{NW2dtzue-1OzTRH-2}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-2}}}\moddef{Define some data types~{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwprevnextdefs{NW2dtzue-1OzTRH-1}{NW2dtzue-1OzTRH-3}\nwenddeflinemarkup
newtype \nwlinkedidentc{Aim}{NW2dtzue-1OzTRH-2} = \nwlinkedidentc{Aim}{NW2dtzue-1OzTRH-2} Int
  deriving stock (Eq, Show)
  deriving
    (Semigroup, Monoid)
    via (Sum Int)

\nwindexdefn{\nwixident{Aim}}{Aim}{NW2dtzue-1OzTRH-2}\eatline
\nwused{\\{NW2dtzue-1375sF-1}}\nwidentdefs{\\{{\nwixident{Aim}}{Aim}}}\nwendcode{}\nwbegindocs{20}\nwdocspar
{\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}\hs{ x} increases the horizontal position by \hs{x} units and increases the depth by the aim multiplied by \hs{x}, forming a \hrefootnote{https://hackage.haskell.org/package/monoid-extras/docs/Data-Monoid-SemiDirectProduct.html\#t:Semi}{semi-direct product} of {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} (the sub-monoid) and {\Tt{}\nwlinkedidentq{Aim}{NW2dtzue-1OzTRH-2}\nwendquote} (the quotient monoid).

Define how {\Tt{}\nwlinkedidentq{Aim}{NW2dtzue-1OzTRH-2}\nwendquote} acts on {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote}.

\nwenddocs{}\nwbegincode{21}\sublabel{NW2dtzue-1OzTRH-3}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-3}}}\moddef{Define some data types~{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwprevnextdefs{NW2dtzue-1OzTRH-2}{\relax}\nwenddeflinemarkup
instance Action \nwlinkedidentc{Aim}{NW2dtzue-1OzTRH-2} \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} where
  act (\nwlinkedidentc{Aim}{NW2dtzue-1OzTRH-2} a) (\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} (V2 x y)) = \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} (V2 x (y + a * x))
\nwused{\\{NW2dtzue-1375sF-1}}\nwidentuses{\\{{\nwixident{Aim}}{Aim}}\\{{\nwixident{Direction}}{Direction}}}\nwindexuse{\nwixident{Aim}}{Aim}{NW2dtzue-1OzTRH-3}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-1OzTRH-3}\nwendcode{}\nwbegindocs{22}\nwdocspar

Use the \hs{Action} to construct the semi-direct product {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote}$\ \rtimes\ ${\Tt{}\nwlinkedidentq{Aim}{NW2dtzue-1OzTRH-2}\nwendquote}.

\nwenddocs{}\nwbegincode{23}\sublabel{NW2dtzue-4XKPl9-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-1}}}\moddef{Define the semi-direct product~{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-2ZOhXn-1}}\nwprevnextdefs{\relax}{NW2dtzue-4XKPl9-2}\nwenddeflinemarkup
\nwlinkedidentc{lift}{NW2dtzue-4XKPl9-1} :: \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} -> Semi \nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} \nwlinkedidentc{Aim}{NW2dtzue-1OzTRH-2}
\nwindexdefn{\nwixident{lift}}{lift}{NW2dtzue-4XKPl9-1}\eatline
\nwalsodefined{\\{NW2dtzue-4XKPl9-2}\\{NW2dtzue-4XKPl9-3}\\{NW2dtzue-4XKPl9-4}}\nwused{\\{NW2dtzue-2ZOhXn-1}}\nwidentdefs{\\{{\nwixident{lift}}{lift}}}\nwidentuses{\\{{\nwixident{Aim}}{Aim}}\\{{\nwixident{Direction}}{Direction}}}\nwindexuse{\nwixident{Aim}}{Aim}{NW2dtzue-4XKPl9-1}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-4XKPl9-1}\nwendcode{}\nwbegindocs{24}\nwdocspar

{\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote}, i.e. a {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} with a depth change of \hs{0}, doesn't affect the aim.

\nwenddocs{}\nwbegincode{25}\sublabel{NW2dtzue-4XKPl9-2}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-2}}}\moddef{Define the semi-direct product~{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-2ZOhXn-1}}\nwprevnextdefs{NW2dtzue-4XKPl9-1}{NW2dtzue-4XKPl9-3}\nwenddeflinemarkup
\nwlinkedidentc{lift}{NW2dtzue-4XKPl9-1} dir@(\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} (V2 _ 0)) = inject dir
\nwused{\\{NW2dtzue-2ZOhXn-1}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{lift}}{lift}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-4XKPl9-2}\nwindexuse{\nwixident{lift}}{lift}{NW2dtzue-4XKPl9-2}\nwendcode{}\nwbegindocs{26}\nwdocspar

{\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote} or {\Tt{}\nwlinkedidentq{down}{NW2dtzue-38STh2-3}\nwendquote}, i.e. a {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} with a horizontal change of \hs{0} and a non-zero depth change \hs{y}, results in an aim change of \hs{y} units.

\nwenddocs{}\nwbegincode{27}\sublabel{NW2dtzue-4XKPl9-3}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-3}}}\moddef{Define the semi-direct product~{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-2ZOhXn-1}}\nwprevnextdefs{NW2dtzue-4XKPl9-2}{NW2dtzue-4XKPl9-4}\nwenddeflinemarkup
\nwlinkedidentc{lift}{NW2dtzue-4XKPl9-1} (\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1} (V2 0 y)) = embed (\nwlinkedidentc{Aim}{NW2dtzue-1OzTRH-2} y)
\nwused{\\{NW2dtzue-2ZOhXn-1}}\nwidentuses{\\{{\nwixident{Aim}}{Aim}}\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{lift}}{lift}}}\nwindexuse{\nwixident{Aim}}{Aim}{NW2dtzue-4XKPl9-3}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-4XKPl9-3}\nwindexuse{\nwixident{lift}}{lift}{NW2dtzue-4XKPl9-3}\nwendcode{}\nwbegindocs{28}\nwdocspar

Since {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} is not specific enough to prevent them, add a catch-all clause to handle invalid directions, e.g. {\Tt{}\nwlinkedidentq{forward}{NW2dtzue-38STh2-2}\nwendquote} and {\Tt{}\nwlinkedidentq{up}{NW2dtzue-38STh2-4}\nwendquote} simultaneously.

\nwenddocs{}\nwbegincode{29}\sublabel{NW2dtzue-4XKPl9-4}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-4}}}\moddef{Define the semi-direct product~{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-1}}}\plusendmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-2ZOhXn-1}}\nwprevnextdefs{NW2dtzue-4XKPl9-3}{\relax}\nwenddeflinemarkup
\nwlinkedidentc{lift}{NW2dtzue-4XKPl9-1} _ = error "Invalid \nwlinkedidentc{direction}{NW2dtzue-1r7xob-1}"
\nwused{\\{NW2dtzue-2ZOhXn-1}}\nwidentuses{\\{{\nwixident{direction}}{direction}}\\{{\nwixident{lift}}{lift}}}\nwindexuse{\nwixident{direction}}{direction}{NW2dtzue-4XKPl9-4}\nwindexuse{\nwixident{lift}}{lift}{NW2dtzue-4XKPl9-4}\nwendcode{}\nwbegindocs{30}\nwdocspar

To solve Part Two, {\Tt{}\nwlinkedidentq{lift}{NW2dtzue-4XKPl9-1}\nwendquote} each {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote} in the input to {\Tt{}\nwlinkedidentq{Direction}{NW2dtzue-1OzTRH-1}\nwendquote}$\ \rtimes\ ${\Tt{}\nwlinkedidentq{Aim}{NW2dtzue-1OzTRH-2}\nwendquote}, forgetting the {\Tt{}\nwlinkedidentq{Aim}{NW2dtzue-1OzTRH-2}\nwendquote} tag to extract the final position.

\nwenddocs{}\nwbegincode{31}\sublabel{NW2dtzue-2ZOhXn-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-2ZOhXn-1}}}\moddef{Solve Part Two~{\nwtagstyle{}\subpageref{NW2dtzue-2ZOhXn-1}}}\endmoddef\nwstartdeflinemarkup\nwusesondefline{\\{NW2dtzue-1375sF-1}}\nwenddeflinemarkup
\nwlinkedidentc{partTwo}{NW2dtzue-2ZOhXn-1} :: [\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}] -> Int
\nwlinkedidentc{partTwo}{NW2dtzue-2ZOhXn-1} = \nwlinkedidentc{solve}{NW2dtzue-1ULoeY-1} (unDirection . untag) . map \nwlinkedidentc{lift}{NW2dtzue-4XKPl9-1}
  where
    \LA{}Define the semi-direct product~{\nwtagstyle{}\subpageref{NW2dtzue-4XKPl9-1}}\RA{}
\nwindexdefn{\nwixident{partTwo}}{partTwo}{NW2dtzue-2ZOhXn-1}\eatline
\nwused{\\{NW2dtzue-1375sF-1}}\nwidentdefs{\\{{\nwixident{partTwo}}{partTwo}}}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{lift}}{lift}}\\{{\nwixident{solve}}{solve}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-2ZOhXn-1}\nwindexuse{\nwixident{lift}}{lift}{NW2dtzue-2ZOhXn-1}\nwindexuse{\nwixident{solve}}{solve}{NW2dtzue-2ZOhXn-1}\nwendcode{}\nwbegindocs{32}\nwdocspar

\newthought{Bring it} all together.

\nwenddocs{}\nwbegincode{33}\sublabel{NW2dtzue-1375sF-1}\nwmargintag{{\nwtagstyle{}\subpageref{NW2dtzue-1375sF-1}}}\moddef{Day02.hs~{\nwtagstyle{}\subpageref{NW2dtzue-1375sF-1}}}\endmoddef\nwstartdeflinemarkup\nwenddeflinemarkup
\{-# LANGUAGE DerivingVia #-\}
\{-# LANGUAGE MultiParamTypeClasses #-\}

module AdventOfCode.Year2021.Day02 where

import AdventOfCode.Input (parseInput)
import AdventOfCode.TH (defaultMain, inputFilePath)
import Control.Applicative ((<|>))
import Data.Functor (($>))
import Data.Monoid.Action (Action (..))
import Data.Monoid.SemiDirectProduct.Strict (Semi, embed, inject, untag)
import Data.Semigroup (Sum (..))
import Linear (V2 (..))
import Text.Trifecta (Parser, natural, some, symbol)

\LA{}Define some data types~{\nwtagstyle{}\subpageref{NW2dtzue-1OzTRH-1}}\RA{}

main :: IO ()
main = $(defaultMain)

\nwlinkedidentc{getInput}{NW2dtzue-2ga90v-1} :: IO [\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}]
\nwlinkedidentc{getInput}{NW2dtzue-2ga90v-1} = parseInput (some \nwlinkedidentc{direction}{NW2dtzue-1r7xob-1}) $(inputFilePath)

example :: [\nwlinkedidentc{Direction}{NW2dtzue-1OzTRH-1}]
example =
  [ \nwlinkedidentc{forward}{NW2dtzue-38STh2-2} 5,
    \nwlinkedidentc{down}{NW2dtzue-38STh2-3} 5,
    \nwlinkedidentc{forward}{NW2dtzue-38STh2-2} 8,
    \nwlinkedidentc{up}{NW2dtzue-38STh2-4} 3,
    \nwlinkedidentc{down}{NW2dtzue-38STh2-3} 8,
    \nwlinkedidentc{forward}{NW2dtzue-38STh2-2} 2
  ]

\LA{}Solve Part One~{\nwtagstyle{}\subpageref{NW2dtzue-4G9gVP-1}}\RA{}

\LA{}Solve Part Two~{\nwtagstyle{}\subpageref{NW2dtzue-2ZOhXn-1}}\RA{}

\LA{}Solve the puzzle~{\nwtagstyle{}\subpageref{NW2dtzue-1ULoeY-1}}\RA{}

\LA{}Define a Direction parser~{\nwtagstyle{}\subpageref{NW2dtzue-1r7xob-1}}\RA{}
\nwnotused{Day02.hs}\nwidentuses{\\{{\nwixident{Direction}}{Direction}}\\{{\nwixident{direction}}{direction}}\\{{\nwixident{down}}{down}}\\{{\nwixident{forward}}{forward}}\\{{\nwixident{getInput}}{getInput}}\\{{\nwixident{up}}{up}}}\nwindexuse{\nwixident{Direction}}{Direction}{NW2dtzue-1375sF-1}\nwindexuse{\nwixident{direction}}{direction}{NW2dtzue-1375sF-1}\nwindexuse{\nwixident{down}}{down}{NW2dtzue-1375sF-1}\nwindexuse{\nwixident{forward}}{forward}{NW2dtzue-1375sF-1}\nwindexuse{\nwixident{getInput}}{getInput}{NW2dtzue-1375sF-1}\nwindexuse{\nwixident{up}}{up}{NW2dtzue-1375sF-1}\nwendcode{}\nwbegindocs{34}\nwdocspar
\nwenddocs{}

\nwixlogsorted{c}{{Count pairwise increases.}{NW2fQ2fr-1DYA9Y-1}{\nwixd{NW2fQ2fr-1DYA9Y-1}\nwixu{NW2fQ2fr-12NRmi-1}}}%
\nwixlogsorted{c}{{Day01.hs}{NW2fQ2fr-12NRmi-1}{\nwixd{NW2fQ2fr-12NRmi-1}}}%
\nwixlogsorted{c}{{Day02.hs}{NW2dtzue-1375sF-1}{\nwixd{NW2dtzue-1375sF-1}}}%
\nwixlogsorted{c}{{Define a Direction parser}{NW2dtzue-1r7xob-1}{\nwixd{NW2dtzue-1r7xob-1}\nwixu{NW2dtzue-1375sF-1}}}%
\nwixlogsorted{c}{{Define some data types}{NW2dtzue-1OzTRH-1}{\nwixd{NW2dtzue-1OzTRH-1}\nwixd{NW2dtzue-1OzTRH-2}\nwixd{NW2dtzue-1OzTRH-3}\nwixu{NW2dtzue-1375sF-1}}}%
\nwixlogsorted{c}{{Define the semi-direct product}{NW2dtzue-4XKPl9-1}{\nwixd{NW2dtzue-4XKPl9-1}\nwixd{NW2dtzue-4XKPl9-2}\nwixd{NW2dtzue-4XKPl9-3}\nwixd{NW2dtzue-4XKPl9-4}\nwixu{NW2dtzue-2ZOhXn-1}}}%
\nwixlogsorted{c}{{Example}{NW2fQ2fr-23nbvF-1}{\nwixd{NW2fQ2fr-23nbvF-1}\nwixu{NW2fQ2fr-12NRmi-1}}}%
\nwixlogsorted{c}{{known directions}{NW2dtzue-38STh2-1}{\nwixd{NW2dtzue-38STh2-1}\nwixd{NW2dtzue-38STh2-2}\nwixd{NW2dtzue-38STh2-3}\nwixd{NW2dtzue-38STh2-4}\nwixu{NW2dtzue-1r7xob-1}}}%
\nwixlogsorted{c}{{Parse the input}{NW2dtzue-2ga90v-1}{\nwixd{NW2dtzue-2ga90v-1}}}%
\nwixlogsorted{c}{{Parse the input.}{NW2fQ2fr-2S9BvQ-1}{\nwixd{NW2fQ2fr-2S9BvQ-1}\nwixu{NW2fQ2fr-12NRmi-1}}}%
\nwixlogsorted{c}{{Solve Part One}{NW2dtzue-4G9gVP-1}{\nwixd{NW2dtzue-4G9gVP-1}\nwixu{NW2dtzue-1375sF-1}}}%
\nwixlogsorted{c}{{Solve Part One.}{NW2fQ2fr-3ajnFh-1}{\nwixd{NW2fQ2fr-3ajnFh-1}\nwixu{NW2fQ2fr-12NRmi-1}}}%
\nwixlogsorted{c}{{Solve Part Two}{NW2dtzue-2ZOhXn-1}{\nwixd{NW2dtzue-2ZOhXn-1}\nwixu{NW2dtzue-1375sF-1}}}%
\nwixlogsorted{c}{{Solve Part Two.}{NW2fQ2fr-3nTTD5-1}{\nwixd{NW2fQ2fr-3nTTD5-1}\nwixu{NW2fQ2fr-12NRmi-1}}}%
\nwixlogsorted{c}{{Solve the puzzle}{NW2dtzue-1ULoeY-1}{\nwixd{NW2dtzue-1ULoeY-1}\nwixu{NW2dtzue-1375sF-1}}}%
\nwixlogsorted{i}{{\nwixident{Aim}}{Aim}}%
\nwixlogsorted{i}{{\nwixident{Direction}}{Direction}}%
\nwixlogsorted{i}{{\nwixident{direction}}{direction}}%
\nwixlogsorted{i}{{\nwixident{down}}{down}}%
\nwixlogsorted{i}{{\nwixident{forward}}{forward}}%
\nwixlogsorted{i}{{\nwixident{getInput}}{getInput}}%
\nwixlogsorted{i}{{\nwixident{lift}}{lift}}%
\nwixlogsorted{i}{{\nwixident{partOne}}{partOne}}%
\nwixlogsorted{i}{{\nwixident{partTwo}}{partTwo}}%
\nwixlogsorted{i}{{\nwixident{solve}}{solve}}%
\nwixlogsorted{i}{{\nwixident{up}}{up}}%


%\vspace{-5pt}
\section{Memoryless Methods}
\label{sec:memoryless}

\noindent
In this model, we simply take the set of $K+W$ positional and key tokens, and
the set of $K+W+1$ output tokens, and fit a model similar to word
vectors~\cite{ref:mikolov:wvec}. The details of the model are described below.

We first assign a $D$ dimensional vector to each one of $K+W$ different key
tokens and positional tokens. We denote such token-vectors by $v_i$, where $1
\leq i \leq K+W$. Next, given a fixed size window of tokens $[t_1, t_2, \ldots,
t_W]$, we compute a score for each possible output $j$, $s_j$ as a function of
the token-vectors of the tokens in the window, i.e.,
\[
s_j = f_j\left(v_{t_1}, v_{t_2}, \ldots v_{t_W}\right)
\]
The final loss function for this particular example is given by
\[
L = \log\left(\frac{e^{s_{t_o}}}{\sum_j{e^{s_j}}}\right)
\]
where $t_o$ is the output token. This is the cross-entropy loss
between softmax based probabilities for each output and the actual observed
output. According to the actual form of the function $f_j$, we get different
models. A few of these models are described below.

For each model, we use {\sc AdaGrad} optimizer to minimize the total loss
function with respect to the parameters of that model. {\sc AdaGrad} was chosen
because it gave the best performance in our case among other alternatives such
as vanilla SGD and momentum based SGD.

\subsection{Fixed Window Weight Model}
In the spirit of continuous bag-of-word (CBOW) model~\cite{ref:mikolov:wvec}, in
this model we assume that a token at position $i$ has a ``weight'' of $w_i$, and
combine the token-vectors of the window according to these weights. The final
score is assumed to be a linear function of this weighted token-vectors. Thus,
the overall model is
\begin{align}
u &= \sum_{i=1}^{W}{w_i v_{t_i}}\\
s_j &= p_j^Tu\\
L &= \log\left(\frac{e^{s_{t_o}}}{\sum_j{e^{s_j}}}\right)
\end{align}
The parameters in this model are the weights $w_i$, and the ``prediction''
vectors $p_j$. The gradients of the loss w.r.t. the parameters are obtained by
backpropagation, the details of which are omitted here for space.

\subsection{Matrix Vector Model}
In this case, we do not introduce any averaging as in the case of CBOW, but
instead simply concatenate the token-vectors to create a larger vector which is
then used to create the scores. Formally, the model is
\begin{align}
u &= [v_{t_1}; v_{t_2}; v_{t_3}; \ldots; v_{t_W}]\\
s_j &= p_j^Tu\\
L &= \log\left(\frac{e^{s_{t_o}}}{\sum_j{e^{s_j}}}\right)
\end{align}
Note that since here $u$ is $DW$ dimensional instead of being $D$ dimensional as
in the case of Fixed Window Weight Model. Thus, the prediction vectors $p_j$ are
much higher dimensional as well, which means this model has a higher number
of parameters as compared to Fixed Window Weight Model.

\subsection{Non-Linear Matrix Vector Model}
This case differs from the Matrix Vector Model by addition of an extra
non-linear transformation between the concatenated token-vectors and the final
scores. In this model, we assume
\begin{align}
u &= [v_{t_1}; v_{t_2}; v_{t_3}; \ldots; v_{t_W}]\\
y &= Qu\\
z &= \text{relu}(y)\\
s_j &= p_j^Tz\\
L &= \log\left(\frac{e^{s_{t_o}}}{\sum_j{e^{s_j}}}\right)
\end{align}
Here $\text{relu}(.)$ is the rectified linear unit, i.e., $\text{relu}(x) = x$
if $x \geq 0$, and $0$ otherwise.


%\documentclass[UTF8]{ctexart} % use larger type; default would be 10pt
\documentclass[a4paper]{article}
\usepackage{../mqc}

\title{\textbf{Modern Quantum Chemistry, Szabo \& Ostlund}\\HW}
\author{wsr
\vspace{5pt}\\
}
\date{\today} % Activate to display a given date or no date (if empty),
         % otherwise the current date is printed

\begin{document}
% \boldmath

\maketitle

\tableofcontents

\newpage

%\setcounter{section}{1}
\section{Mathematical Review}
\subsection{Linear Algebra}
\subsubsection{3-D Vector Algebra}
\ex{1.1}
\subex{a)}
\begin{equation}\label{key}
\mathcal{O}\vb{e}_j = \sum_{i=1}^3 \vb{e}_i O_{ij}
\end{equation}
\begin{equation}\label{key}
\vb{e}_i \cdot \mathcal{O}\vb{e}_j = \vb{e}_i \cdot \sum_{i=1}^3 \vb{e}_i O_{ij} = O_{ij}
\end{equation}
\subex{b)}
\begin{equation}\label{key}
\begin{aligned}
\vb{b} &= \mathcal{O}\vb{a} = \sum_{i=1}^3 a_i\sum_{j=1}^3 \vb{e}_jO_{ji}\\
&=\sum_{j=1}^3 a_j\sum_{i=1}^3 \vb{e}_iO_{ij} = \sum_{i=1}^3 \vb{e}_i\sum_{j=1}^3 a_jO_{ij}
\end{aligned}
\end{equation}
thus
\begin{equation}\label{key}
\vb{b}_i = \sum_{j=1}^3 a_jO_{ij}
\end{equation}

%.
\ex{1.2}
\begin{equation}\label{key}
[\vb{A},\vb{B}] = \mqty[0& -2& 4\\2& 0& 3\\-4& -3& 0]
\end{equation}
\begin{equation}\label{key}
\{\vb{A},\vb{B}\} = \mqty[0& 0& -2\\0& -2& 3\\-2& 3& -2]
\end{equation}

\subsubsection{Matrices}
\ex{1.3}
\begin{equation}\label{key}
(AB)_{nk} = \sum_m^M A_{nm}B_{mk}
\end{equation}
\begin{equation}\label{key}
(AB)^\dagger_{kn} = (AB)_{nk}^* = \sum_m^M A_{nm}^*B_{mk}^* = \sum_m^M B^\dagger_{km} A^\dagger_{mn} = (B^\dagger A^\dagger)_{kn}
\end{equation}
thus
\begin{equation}\label{key}
(\vb{A}\vb{B})^\dagger = \vb{B}^\dagger \vb{A}^\dagger
\end{equation}

\ex{1.4}
\subex{a.}
suppose $ \vb{A} $ is $ N\cross M $ and $ \vb{B} $ is $ M\cross N $
\begin{equation}\label{key}
\tr \vb{A}\vb{B} = \sum_n^N (AB)_{nn} = \sum_n^N \sum_m^M A_{nm}B_{mn} = \sum_m^M\sum_n^N  B_{mn}A_{nm} = \sum_m^M (BA)_{mm} = \tr \vb{B}\vb{A}
\end{equation}
\subex{b.}
\begin{equation}\label{key}
\vb{AB}(\vb{AB})^{-1} = \iden
\end{equation}
\begin{equation}\label{key}
\vb{B}^{-1}\vb{A}^{-1}\vb{A}\vb{B}(\vb{AB})^{-1} = \vb{B}^{-1}\vb{A}^{-1}\iden
\end{equation}
\begin{equation}\label{key}
\vb{B}^{-1}(\vb{A}^{-1}\vb{A})\vb{B}(\vb{AB})^{-1} = \vb{B}^{-1}\vb{A}^{-1}
\end{equation}
\begin{equation}\label{key}
\vb{B}^{-1} \iden \vb{B}(\vb{AB})^{-1} = \vb{B}^{-1}\vb{A}^{-1}
\end{equation}
thus
\begin{equation}\label{key}
(\vb{AB})^{-1} = \vb{B}^{-1}\vb{A}^{-1}
\end{equation}
\subex{c.}
\begin{equation}\label{key}
\vb{B} = \vb{U}^\dagger \vb{A} \vb{U}
\end{equation}huhhj
\begin{equation}\label{key}
\vb{U} \vb{B} \vb{U}^\dagger = \vb{U} \vb{U}^\dagger \vb{A} \vb{U} \vb{U}^\dagger = \iden \vb{A} \iden = \vb{A}
\end{equation}
\subex{d.}
$ \because \vb{C}$ is Hermitian, $ \therefore $
\begin{equation}\label{key}
\vb{C} = \vb{C}^\dagger
\end{equation}
\begin{equation}\label{key}
\vb{A}\vb{B} = (\vb{A}\vb{B})^\dagger = \vb{B}^\dagger \vb{A}^\dagger
\end{equation}
Since $ \vb{A} $, $ \vb{B} $ are Hermitian,
\begin{equation}\label{key}
\vb{A}\vb{B} = \vb{B}^\dagger \vb{A}^\dagger = \vb{B}\vb{A}
\end{equation}
$ \therefore $
\begin{equation}\label{key}
[\vb{A}, \vb{B}] = \vb{A}\vb{B} - \vb{B}\vb{A} = 0
\end{equation}
i.e. $ \vb{A} $, $ \vb{B} $ commute
\subex{e.}
Since $ \vb{A} $ is Hermitian,
\begin{equation}\label{key}
\vb{A} = \vb{A}^\dagger
\end{equation}
thus
\begin{equation}\label{key}
(\vb{A}^{1-})^\dagger \vb{A} = (\vb{A}^{1-})^\dagger \vb{A}^\dagger = (\vb{A}\vb{A}^{-1})^\dagger = \iden^\dagger = \iden
\end{equation}
thus
\begin{equation}\label{key}
(\vb{A}^{1-})^\dagger \vb{A} \vb{A}^{-1} = \vb{A}^{-1}
\end{equation}
\begin{equation}\label{key}
(\vb{A}^{1-})^\dagger = \vb{A}^{-1}
\end{equation}
i.e. $ \vb{A}^{-1} $, if it exists, is Hermitian.
\subex{f.}
Suppose
\begin{equation}\label{key}
\vb{A}^{-1} = \mqty(x & y\\z & w)
\end{equation}
thus
\begin{equation}\label{key}
\mqty(A_{11} & A_{12}\\A_{21} & A_{22})\mqty(x & y\\z & w) = \mqty(1 & 0\\0 & 1)
\end{equation}
the solution is
\begin{equation}\label{key}
\mqty{
	&x = \dfrac{A_{22}}{A_{11}A_{22} - A_{12}A_{21}}\\
	&y = \dfrac{-A_{12}}{A_{11}A_{22} - A_{12}A_{21}}\\
	&z = \dfrac{-A_{21}}{A_{11}A_{22} - A_{12}A_{21}}\\
	&w = \dfrac{A_{11}}{A_{11}A_{22} - A_{12}A_{21}}\\
}
\end{equation}
thus
\begin{equation}\label{key}
\vb{A}^{-1} = \dfrac{1}{\det(\vb{A})} \mqty(A_{22} & -A_{12}\\ -A_{21} & A_{11})
\end{equation}

\subsubsection{Determinants}
%.
\ex{1.5}
Suppose
\begin{equation}\label{key}
\vb{A} = \mqty(A_{11} & A_{12}\\A_{21} & A_{22})
\end{equation}
\subex{1.}
\begin{equation}\label{key}
\mqty|0 & 0\\A_{21} & A_{22}| = 0\cdot A_{22} - 0\cdot A_{21} = 0
\end{equation}
\begin{equation}\label{key}
\mqty|0 & A_{12}\\0 & A_{22}| = 0\cdot A_{22} - 0\cdot A_{12} = 0
\end{equation}
\subex{2.}
\begin{equation}\label{key}
\det(\vb{A}) = A_{11}A_{22} -  0\cdot 0 = A_{11}A_{22}
\end{equation}
\subex{3.}
\begin{equation}\label{key}
\det(\vb{A}) = A_{11}A_{22} -  A_{12}A_{21}
\end{equation}
\begin{equation}\label{key}
\mqty| A_{21} & A_{22}\\A_{11} & A_{12} | = A_{21}A_{12} - A_{22}A_{11} = -\det(\vb{A})
\end{equation}
\subex{4.}
\begin{equation}\label{key}
\det(\vb{A}^\dagger)^* = \mqty|A_{11}^* & A_{21}^*\\A_{12}^* & A_{22}^*|^* = (A_{11}^*A_{22}^* - A_{21}^*A_{12}^*)^* = A_{11}A_{22} -  A_{12}A_{21} = \det(\vb{A})
\end{equation}
\subex{5.}
Suppose $ \vb{B} = \mqty(B_{11} & B_{12}\\B_{21} & B_{22}) $
\begin{equation}\label{key}
\begin{aligned}
\det(\vb{A}\vb{B}) &=
\mqty|A_{11}B_{11}+A_{12}B_{21} & A_{11}B_{12}+A_{12}B_{22}\\
A_{21}B_{11}+A_{22}B_{21} & A_{21}B_{12}+A_{22}B_{22}|\\
&= (A_{11}B_{11}+A_{12}B_{21})(A_{21}B_{12}+A_{22}B_{22}) - (A_{11}B_{12}+A_{12}B_{22})(A_{21}B_{11}+A_{22}B_{21})\\
&= A_{11}B_{11}A_{21}B_{12} + A_{11}B_{11}A_{22}B_{22} + A_{12}B_{21}A_{21}B_{12} + A_{12}B_{21}A_{22}B_{22}\\
&\quad - (A_{11}B_{12}A_{21}B_{11} +  A_{11}B_{12}A_{22}B_{21} + A_{12}B_{22}A_{21}B_{11} + A_{12}B_{22}A_{22}B_{21})\\
&= A_{11}B_{11}A_{22}B_{22} + A_{12}B_{21}A_{21}B_{12} - A_{11}B_{12}A_{22}B_{21} - A_{12}B_{22}A_{21}B_{11}
\end{aligned}
\end{equation}
\begin{equation}\label{key}
\begin{aligned}
\det(\vb{A})\det(\vb{B}) &= (A_{11}A_{22} -  A_{12}A_{21})(B_{11}B_{22} -  B_{12}B_{21})\\
&= A_{11}A_{22}B_{11}B_{22} - A_{11}A_{22}B_{12}B_{21} - A_{12}A_{21}B_{11}B_{22} + A_{12}A_{21}B_{12}B_{21}\\
&= A_{11}B_{11}A_{22}B_{22} + A_{12}B_{21}A_{21}B_{12}- A_{11}B_{12}A_{22}B_{21} - A_{12}B_{22}A_{21}B_{11} \\
\end{aligned}
\end{equation}
$ \therefore $
\begin{equation}\label{key}
\det(\vb{A})\det(\vb{B}) = \det(\vb{A}\vb{B})
\end{equation}

\ex{1.6}
%.
\subex{6.}
If two rows (e.g. $ i $th and $ j $th) are equal
\begin{equation}\label{key}
\det(\vb{A}) = \mqty|  & ... & ... & \\
      A_{i1} & A_{i2} & ... & A_{in}\\
        & ... & ... & \\
      A_{j1} & A_{j2} & ... & A_{jn}\\
        & ... & ... & \\|
\xlongequal{1.5.3} -\mqty|  & ... & ... & \\
A_{j1} & A_{j2} & ... & A_{jn}\\
& ... & ... & \\
A_{i1} & A_{i2} & ... & A_{in}\\
& ... & ... & \\|
= - \mqty|  & ... & ... & \\
A_{i1} & A_{i2} & ... & A_{in}\\
& ... & ... & \\
A_{j1} & A_{j2} & ... & A_{jn}\\
& ... & ... & \\|
\end{equation}
i.e.
\begin{equation}\label{key}
\det(\vb{A}) = -\det(\vb{A})
\end{equation}
thus
\begin{equation}\label{key}
\det(\vb{A}) = 0
\end{equation}
\subex{7.}
From Ex 1.5.5, we have
\begin{equation}\label{key}
\det(\vb{A})\det(\vb{A}^{-1}) = \det(\iden) = 1
\end{equation}
thus
\begin{equation}\label{key}
\det(\vb{A}^{-1}) = \det(\vb{A})^{-1}
\end{equation}
\subex{8.}
\begin{equation}\label{key}
\vb{A}\vb{A}^\dagger = \iden \;\dra\; \det(\vb{A})\det(\vb{A}^\dagger) = \det(\iden) = 1
\end{equation}
From Ex 1.5.4, we have
\begin{equation}\label{key}
\det(\vb{A})\det(\vb{A})^* = 1
\end{equation}
\subex{9.}
From Ex 1.5.5, we get
\begin{equation}\label{key}
\det(\vb{U}^\dagger)\det(\vb{O})\det(\vb{U}) = \det(\bm\Omega)
\end{equation}
and
\begin{equation}\label{key}
\det(\vb{U}^\dagger)\det(\vb{U}) = \det(\iden) = 1
\end{equation}
$ \therefore $
\begin{equation}\label{key}
\det(\vb{O}) = \det(\bm\Omega)
\end{equation}

%.
\ex{1.7}
If $ \det(\vb{A}) \neq 0 $, thus $ \vb{A}^{-1} $ exists, we have
\begin{equation}\label{key}
\vb{A}^{-1}\vb{A}\vb{c} = \bm{0} \;\dra\; \vb{c} = \bm{0}
\end{equation}
$  \square $

\subsubsection{N-D Complex Vector Spaces}

\subsubsection{Change of Basis}
\ex{1.8}
\begin{equation}\label{key}
\Omega_{\alpha\beta} = \sum_{ij} U_{\alpha i}^\dagger O_{ij} U_{j\beta}
\end{equation}
gives
\begin{equation}\label{key}
\begin{aligned}
\tr\bm\Omega &= \sum_\alpha \Omega_{\alpha\alpha} = \sum_\alpha \sum_{ij} U_{\alpha i}^\dagger O_{ij} U_{j\alpha}\\
&= \sum_{ij} O_{ij} \sum_\alpha U_{j\alpha} U_{\alpha i}^\dagger = \sum_{ij} O_{ij} \delta_{ji} = \tr\vb{O}
\end{aligned}
\end{equation}
%while
%\begin{equation}\label{key}
%O_{ij} = \sum_{\alpha\beta} U_{i\alpha} \Omega_{\alpha\beta} U_{\beta j}^\dagger
%\end{equation}
%gives
%\begin{equation}\label{key}
%\tr \vb{O} = \sum_{i} O_{ii} = \sum_{\alpha\beta} U_{i\alpha} \Omega_{\alpha\beta} U_{i\beta}^*
%\end{equation}

\subsubsection{The Eigenvalue Problem}
%.
\ex{1.9}
\begin{equation}\label{key}
\vb{O}\vb{U} = \vb{U}\bm\omega \;\dra\; \vb{O}\mqty(\vb{c}^1 & \vb{c}^2 & \cdots & \vb{c}^N) = \mqty(\omega_1\vb{c}_1 & \omega_2\vb{c}_2 & \cdots & \omega_N\vb{c}_N)
\end{equation}
thus
\begin{equation}\label{key}
\vb{O}\vb{c}^\alpha = \omega_\alpha \vb{c}^\alpha
\end{equation}
\ex{1.10}
\begin{equation}\label{key}
\left\{
\begin{aligned}
&O_{11}-\omega + O_{12}c = 0\\
&O_{21} + (O_{22}-\omega)c = 0
\end{aligned}\right.
\end{equation}
\begin{equation}\label{key}
(O_{11}-\omega)(O_{22}-\omega) - O_{21}O_{12} = 0
\end{equation}
\begin{equation}\label{key}
\omega^2 - (O_{11}+O_{22})\omega + O_{11}O_{22} - O_{21}O_{12} = 0
\end{equation}
\begin{equation}\label{key}
\left\{\begin{aligned}
&\omega_1 = \dfrac{1}{2}\qty(O_{11}+O_{22} - \sqrt{(O_{11}-O_{22})^2 + 4O_{21}O_{12}})\\
&\omega_2 = \dfrac{1}{2}\qty(O_{11}+O_{22} + \sqrt{(O_{11}-O_{22})^2 + 4O_{21}O_{12}})
\end{aligned}\right.
\end{equation}

%.
\ex{1.11}
\subex{a)}
\begin{equation}\label{key}
\mqty| 3-\omega & 1\\1 & 3-\omega| = 0 \;\dra\; (3-\omega)^2 - 1 = 0
\end{equation}
Eigenvalues
\begin{equation}\label{key}
\omega_1 = 2 \quad \omega_2 = 4
\end{equation}
Eigenvectors
\begin{equation}\label{key}
\vb{c}^1 = \mqty(1\\-1) \quad \vb{c}^2 = \mqty(1\\1)
\end{equation}
\begin{equation}\label{key}
\mqty|3-\omega & 1\\1 & 2-\omega| = 0 \;\dra\; (3-\omega)(2-\omega) - 1 = 0
\end{equation}
Eigenvalues
\begin{equation}\label{key}
\omega_1 = \dfrac{5+\sqrt{5}}{2} \quad \omega_2 = \dfrac{5-\sqrt{5}}{2}
\end{equation}
Eigenvectors
\begin{equation}\label{key}
\vb{c}^1 = \mqty(\dfrac{1}{2}(1+\sqrt{5})\\1) \quad \vb{c}^2 = \mqty(\dfrac{1}{2}(1-\sqrt{5})\\1)
\end{equation}
\subex{b)}
\begin{equation}\label{key}
\theta_0 = \dfrac{1}{2}\tan^{-1}\dfrac{2O_{12}}{O_{11}-O_{12}}
\end{equation}
for $ \vb{A} $
\begin{equation}\label{key}
\theta_0 = \dfrac{1}{2}\tan^{-1}\dfrac{2\cross 1}{3-3} = \dfrac{\pi}{4}
\end{equation}
Eigenvalues
\begin{equation}\label{key}
\omega_1 = 2 \quad \omega_2 = 4
\end{equation}
Eigenvectors
\begin{equation}\label{key}
\vb{c}^1 = \mqty(\sqrt{2}/2\\-\sqrt{2}/2) \quad \vb{c}^2 = \mqty(\sqrt{2}/2\\ \sqrt{2}/2)
\end{equation}
for $ \vb{B} $
\begin{equation}\label{key}
\theta_0 = \dfrac{1}{2}\tan^{-1}\dfrac{2\cross 1}{3-2} = \dfrac{1}{2}\tan^{-1}2
\end{equation}
Eigenvalues
\begin{equation}\label{key}
\omega_1 = \dfrac{10}{5+\sqrt{5}} = \dfrac{5-\sqrt{5}}{2} \quad \omega_2 = \dfrac{10}{5-\sqrt{5}} = \dfrac{5+\sqrt{5}}{2}
\end{equation}
Eigenvectors
\begin{equation}\label{key}
\vb{c}^1
= \mqty(\sqrt{\dfrac{\sqrt{5}+5}{10}}\vspace{5pt}\\ \sqrt{\dfrac{2}{\sqrt{5}+5}})
= \sqrt{\dfrac{2}{\sqrt{5}+5}}
\mqty(\dfrac{1+\sqrt{5}}{2} \vspace{5pt}\\1)
\end{equation}
\begin{equation}\label{key}
\vb{c}^2
= \mqty(\sqrt{\dfrac{2}{\sqrt{5}+5}}\vspace{5pt}\\ -\sqrt{\dfrac{\sqrt{5}+5}{10}})
= -\sqrt{\dfrac{\sqrt{5}+5}{10}}
\mqty(\dfrac{1-\sqrt{5}}{2} \vspace{5pt}\\1)
\end{equation}
Details are in \code{1-1.nb}

\subsubsection{Functions of Matrices}
\ex{1.12}
\subex{a.}
\begin{equation}\label{key}
\vb{A}^n = \vb{U}\vb{a}^n\vb{U}^\dagger
\end{equation}
\begin{equation}\label{key}
\det(\vb{A}^n) = \det(\vb{U})\det(\vb{a}^n)\det(\vb{U}^\dagger) =  \det(\vb{U})\det(\vb{U}^\dagger)
\mqty|a_1^n & & & \\
      & a_2^n & & \\
      & & \ddots & \\
      & & & a_N^n | = a_1^n a_2^n \cdots a_N^n
\end{equation}
\subex{b.}
From 1.4.a, we have
\begin{equation}\label{key}
\tr \vb{A}^n = \tr(\vb{U}\vb{a}^n\vb{U}^\dagger) = \tr(\vb{U}\vb{U}^\dagger\vb{a}^n) = \tr(\vb{a}^n) = \sum_{\alpha=1}^N a_\alpha^n
\end{equation}
\subex{c.}
\begin{equation}\label{key}
\vb{U}^\dagger(\omega\iden - \vb{A})\vb{U} = \omega\iden - \vb{a}
\end{equation}
\begin{equation}\label{key}
(\omega\iden - \vb{A})^{-1} = [(\vb{U}(\omega\iden - \vb{a})\vb{U}^\dagger]^{-1} = \vb{U}(\omega\iden - \vb{a})^{-1}\vb{U}^\dagger
\end{equation}
while
\begin{equation}\label{key}
(\omega\iden - \vb{a})^{-1} =
\mqty(\omega-a_{1} & & & \\
      & \omega-a_{2} & & \\
      & & \ddots & \\
      & & & \omega-a_{N} )^{-1}
= \mqty(\dfrac{1}{\omega-a_{1}} & & & \\
        & \dfrac{1}{\omega-a_{2}} & & \\
        & & \ddots & \\
        & & & \dfrac{1}{\omega-a_{N}} )
\end{equation}
thus
\begin{equation}\label{key}
\vb{G}(\omega) = (\omega\iden - \vb{A})^{-1} = \vb{U}
\mqty(\dfrac{1}{\omega-a_{1}} & & & \\
& \dfrac{1}{\omega-a_{2}} & & \\
& & \ddots & \\
& & & \dfrac{1}{\omega-a_{N}} )
\vb{U}^\dagger
\end{equation}
\begin{equation}\label{key}
\vb{G}(\omega)_{ij} = \sum_\alpha U_{i\alpha}\dfrac{1}{\omega-a_\alpha}U^\dagger_{\alpha j} = \sum_\alpha \dfrac{U_{i\alpha}U_{j\alpha}^*}{\omega-a_\alpha}
\end{equation}
Since $U_{i\alpha} = \Braket{i | \alpha}  $, $ U^\dagger_{\alpha j} = U_{j\alpha}^* = \Braket{\alpha | j} $
\begin{equation}\label{key}
\vb{G}(\omega)_{ij} = \sum_\alpha \dfrac{\Braket{i | \alpha} \Braket{\alpha | j}}{\omega-a_\alpha}
\end{equation}
\ex{1.13}
The eigenvalues and eigenvectors of $ \vb{A} $ are
\begin{equation}\label{key}
\omega_1 = a-b \quad \omega_2 = a+b
\end{equation}
\begin{equation}\label{key}
\vb{c}^1 = \mqty(1\\ -1) \quad \vb{c}^2 = \mqty(1\\ 1)
\end{equation}
\begin{equation}\label{key}
\vb{A} = \vb{U}\vb{a}\vb{U}^\dagger
=\dfrac{\sqrt{2}}{2}\mqty(1 & 1\\1 & -1)\mqty(a+b & 0\\0 & a-b) \dfrac{\sqrt{2}}{2}\mqty(1 & 1\\1 & -1)
\end{equation}
\begin{equation}\label{key}
\begin{aligned}
f(\vb{A}) &= \vb{U}f(\vb{a})\vb{U}^\dagger = \dfrac{1}{2}\mqty(1 & 1\\1 & -1) \mqty(f(a+b) & 0\\0 & f(a-b)) \mqty(1 & 1\\1 & -1)\\
&= \dfrac{1}{2}\mqty(f(a+b) & f(a-b)\\ f(a+b) & -f(a-b)) \mqty(1 & 1\\1 & -1)\\
&= \dfrac{1}{2}\mqty(f(a+b)+f(a-b) & f(a+b)-f(a-b) \\ f(a+b)-f(a-b) & f(a+b)+f(a-b) )
\end{aligned}
\end{equation}

\subsection{Orthogonal Functions, Eigenfunctions, and Operators}
\ex{1.14}
\begin{equation}\label{key}
\intdinf \dd x a(x)\delta(x) = \lim_{\varepsilon\ra 0} \int_{-\varepsilon}^\varepsilon \dd x a(x)\dfrac{1}{2\varepsilon} = \lim_{\varepsilon\ra 0} \dfrac{1}{2\varepsilon} \int_{-\varepsilon}^\varepsilon \dd x a(x)
\xlongequal{\text{L'H\^opital}} \lim_{\varepsilon\ra 0} \dfrac{a(\varepsilon) - [-a(-\varepsilon)]}{2} = a(0)
\end{equation}
\ex{1.15}
\begin{equation}\label{key}
\begin{aligned}
\int \dd x \psi_j^*(x)\mathcal{O}\psi_i(x) &= \int\dd x \psi_j^*(x)\sum_k\psi_k(x)O_{ki} = \sum_k O_{ki}\int\dd x \psi_j^*(x)\psi_k(x)\\
&= \sum_k O_{ki}\delta_{jk} =  O_{ji}
\end{aligned}
\end{equation}
In bra-ket notation, (1) becomes
\begin{equation}\label{key}
\mathcal{O}\ket{i} = \sum_j \ket{j} \Braket{j | \mathcal{O} | i}
\end{equation}
which is identical to Eq.(1.55) in the textbook.
\ex{1.16}
With bra-ket notation,
\begin{equation}\label{key}
\mathcal{O}\sumiinf c_i\ket{i} = \omega\sumiinf c_i\ket{i}
\end{equation}
Multiply by $ \bra{j} $
\begin{equation}\label{key}
\sumiinf c_i \Braket{j | \mathcal{O} | i} = \omega\sumiinf c_i \Braket{j | i} = \omega c_j
\end{equation}
i.e.
\begin{equation}\label{key}
\sumiinf O_{ji} c_i = \omega c_j
\end{equation}
\begin{equation}\label{key}
\vb{O}\vb{c} = \omega\vb{c}
\end{equation}
It's similar to prove that without bra-ket notation.

\ex{1.17}
\subex{a.}
\begin{equation}\label{key}
\int\dd x \Bra{i|x}\Braket{x|j} = \Braket{i|j} = \delta_{ij}
\end{equation}
i.e.
\begin{equation}\label{key}
\int\dd x \psi_i^*(x)\Psi_j(x) = \delta_{ij}
\end{equation}
\subex{b.}
\begin{equation}\label{key}
\sumiinf \Braket{x|i}\Braket{i|x'} = \Braket{x|x'} = \delta(x-x')
\end{equation}
thus
\begin{equation}\label{key}
 \sumiinf \psi_i^*(x)\psi_i(x') = \sumiinf \Braket{x|i}\Braket{i|x'} = \delta(x-x')
\end{equation}
\subex{c.}
\begin{equation}\label{key}
\int\dd x \Braket{x'|x}\Braket{x|a} = \Braket{x'|a}
\end{equation}
thus
\begin{equation}\label{key}
\int\dd x \delta(x' - x) a(x) = a(x')
\end{equation}
i.e.
\begin{equation}\label{key}
\int\dd x' \delta(x-x')a(x') = a(x)
\end{equation}
\subex{d.}
\begin{equation}\label{key}
\Braket{x' | \mathcal{O} | a} = \int\dd x \Braket{x' | \mathcal{O} | x} \Braket{x|a} = \Braket{x'|b}
\end{equation}
$ \therefore $
\begin{equation}\label{key}
\mathcal{O}a(x') = \int\dd x O(x',x)a(x) = b(x')
\end{equation}
i.e.
\begin{equation}\label{key}
b(x) = \mathcal{O}a(x) = \int\dd x' O(x,x')a(x')
\end{equation}
\subex{e.}
\begin{equation}\label{key}
\begin{aligned}
O(x,x') &= \Braket{x | \mathcal{O} | x'} = \bra{x} \qty(\sum_i \ket{i}\bra{i}) \mathcal{O} \qty(\sum_j\ket{j}\bra{j}) \ket{x'}\\
&= \sum_{ij} \Braket{x|i}\Braket{i | \mathcal{O} | j} \Braket{j|x'}\\
&= \sum_{ij} \psi_i(x) O_{ij} \psi_j^*(x')
\end{aligned}
\end{equation}

\subsection{The Variation Method}
\subsubsection{The Variation Principle}
\ex{1.18}
\begin{equation}\label{key}
\begin{aligned}
\mathscr{E} &= \dfrac{\Braket{\tilde{\Phi} | -\tfrac{1}{2}\dv[2]{x}-\delta(x) | \tilde{\Phi}}}{\Braket{\tilde{\Phi} | \tilde{\Phi}}} = \dfrac{N^2 \intdinf\dd x \e^{-\alpha x^2}\qty[-\dfrac{1}{2}(-2\alpha+4\alpha^2 x^2) - \delta(x)]\e^{-\alpha x^2}}{N^2\intdinf\dd x \e^{-2\alpha x^2}}\\
&= \dfrac{\alpha\dfrac{\pi^{1/2}}{(2\alpha)^{1/2}} - 2\alpha^2\dfrac{2\pi^{1/2}}{4(2\alpha)^{3/2}} - 1}{\dfrac{\pi^{1/2}}{(2\alpha)^{1/2}}}\\
&= \dfrac{\alpha \pi^{1/2} - \alpha^2\dfrac{\pi^{1/2}}{(2\alpha)} - (2\alpha)^{1/2}}{\pi^{1/2}}\\
&= \alpha - \dfrac{1}{2}\alpha - \dfrac{(2\alpha)^{1/2}}{\pi^{1/2}}\\
&= \dfrac{1}{2}\alpha - \dfrac{(2\alpha)^{1/2}}{\pi^{1/2}}
\end{aligned}
\end{equation}
Let $ \dv{\mathscr{E}}{\alpha} = 0 $, we have
\begin{equation}\label{key}
\dfrac{1}{2} - \dfrac{1}{(2\pi\alpha)^{1/2}} = 0 \;\dra\; \alpha = \dfrac{2}{\pi}
\end{equation}
thus
\begin{equation}\label{key}
\mathscr{E}_{min} = -\dfrac{1}{\pi}
\end{equation}

\ex{1.19}
\begin{equation}\label{key}
\begin{aligned}
\mathscr{E} &= \dfrac{\Braket{\tilde{\Phi} | -\dfrac{1}{2}\nabla^2 - \dfrac{1}{r} | \tilde{\Phi}}}{\Braket{\tilde{\Phi} | \tilde{\Phi}}} = \dfrac{N^2 \cdot 4\pi \intdinf r^2\dd r \e^{-\alpha r^2}\qty[-\dfrac{1}{2}(4 \alpha^2 r^2 - 6\alpha ) - \dfrac{1}{r}]\e^{-\alpha r^2}}{N^2\cdot 4\pi \intdinf r^2\dd r \e^{-2\alpha r^2}}\\
&= \dfrac{-2\alpha^2\dfrac{24\pi^{1/2}}{64(2\alpha)^{5/2}} + 3\alpha\dfrac{2\pi^{1/2}}{8(2\alpha)^{3/2}} - \dfrac{1}{2(2\alpha)} }{\dfrac{2\pi^{1/2}}{8(2\alpha)^{3/2}}}\\
&= -2\alpha^2\dfrac{12}{8(2\alpha)} + 3\alpha - \dfrac{2(2\alpha)^{1/2}}{\pi^{1/2} } \\
&= \dfrac{3}{2}\alpha - \dfrac{2(2\alpha)^{1/2}}{\pi^{1/2} }
\end{aligned}
\end{equation}
Let $ \dv{\mathscr{E}}{r} = 0 $,
\begin{equation}\label{key}
\dfrac{3}{2} - \dfrac{2}{\sqrt{2\pi\alpha}} = 0 \;\dra\; \alpha = \dfrac{8}{9\pi}
\end{equation}
\begin{equation}\label{key}
\mathscr{E}_{min} = \dfrac{4}{3\pi} - \dfrac{8}{3\pi} = -\dfrac{4}{3\pi}
\end{equation}

\ex{1.20}
\begin{equation}\label{key}
\begin{aligned}
\omega(\theta) &= \vb{c}^\dagger \vb{O} \vb{c} = \mqty(\cos\theta & \sin\theta) \mqty(O_{11}\cos\theta + O_{12}\sin\theta\\ O_{12}\cos\theta + O_{22}\sin\theta)\\
&= O_{11}\cos^2\theta + 2O_{12}\cos\theta\sin\theta + O_{22}\sin^2\theta\\
\end{aligned}
\end{equation}
Let $ \dv{\omega}{\theta} = 0 $, thus
\begin{equation}\label{key}
O_{11} (-2\cos\theta\sin\theta) + O_{12}\cdot 2\cos 2\theta + O_{22}\cdot 2\sin\theta\cos\theta = 0
\end{equation}
\begin{equation}\label{key}
(O_{22}-O_{11})\sin 2\theta + 2O_{12}\cos 2\theta = 0
\end{equation}
\begin{equation}\label{key}
\theta = \dfrac{1}{2}\arctan\dfrac{2O_{12}}{O_{11}-O_{22}}
\end{equation}
%\begin{equation}\label{key}
%\omega_{min} = \dfrac{1}{2}\qty(O_{11}+O_{22} \pm \sqrt{(O_{11}-O_{22})^2 + 4O_{12}^2})
%\end{equation}
\begin{equation}\label{key}
\omega = O_{11}\cos^2\theta + O_{12}\sin 2\theta + O_{22}\sin^2\theta
\end{equation}
which are exactly the results in Eq. (1.105) and Eq. (1.106a) in the textbook. We get the result because the trial vector $ \vb{c} $ is the exact eigenvector of $ \vb{O} $.

\subsubsection{The Linear Variational Problem}
\ex{1.21}
\subex{a.}
\begin{equation}\label{key}
\Braket{\tPhi' | \tPhi'} = 1 = \sum_{\alpha\beta} \Braket{\tPhi' | \Phi_\alpha} \Braket{\Phi_\alpha | \Phi_\beta} \Braket{\Phi_\beta | \tPhi'}
\end{equation}
Since $ \Braket{\tPhi' | \Phi_0} = 0 $, we have
\begin{equation}\label{key}
\sum_{\alpha=1}^\infty \sum_{\beta=1}^\infty \Braket{\tPhi' | \Phi_\alpha} \Braket{\Phi_\alpha | \Phi_\beta} \Braket{\Phi_\beta | \tPhi'} = 1
\end{equation}
thus
\begin{equation}\label{key}
\sum_{\alpha=1}^\infty \sum_{\beta=1}^\infty \Braket{\tPhi' | \Phi_\alpha} \delta_{\alpha\beta} \Braket{\Phi_\beta | \tPhi'} = 1
\end{equation}
\begin{equation}\label{key}
\sum_{\alpha=1}^\infty \Braket{\tPhi' | \Phi_\alpha} \Braket{\Phi_\alpha | \tPhi'} = 1
\end{equation}
\begin{equation}\label{key}
\sum_{\alpha=1}^\infty \abs{\Braket{\Phi_\alpha | \tPhi'}}^2 = 1
\end{equation}
Similarly,
\begin{equation}\label{key}
\Braket{\tPhi' | \mathscr{H} | \tPhi'} = \sum_{\alpha\beta} \Braket{\tPhi' | \Phi_\alpha} \Braket{\Phi_\alpha | \mathscr{H} | \Phi_\beta} \Braket{\Phi_\beta | \tPhi'} = \sum_{\alpha=1}^\infty \sum_{\beta=1}^\infty \Braket{\tPhi' | \Phi_\alpha} \Braket{\Phi_\alpha | \mathscr{H} | \Phi_\beta} \Braket{\Phi_\beta | \tPhi'}
\end{equation}
From Eq. (1.170) from the textbook, we get
\begin{equation}\label{key}
\Braket{\Phi_\alpha | \mathscr{H} | \Phi_\beta} = \mathscr{E}_\alpha \delta_{\alpha\beta}
\end{equation}
thus
\begin{equation}\label{key}
\Braket{\tPhi' | \mathscr{H} | \tPhi'} =\sum_{\alpha=1}^\infty \abs{\Braket{\Phi_\alpha | \tPhi'}}^2 \mathscr{E}_\alpha \geq \sum_{\alpha=1}^\infty \abs{\Braket{\Phi_\alpha | \tPhi'}}^2 \mathscr{E}_1 = \mathscr{E}_1
\end{equation}
\subex{b.}
\begin{equation}\label{key}
\Braket{\tPhi' | \tPhi'} = 1 = \qty(x^* \bra{\tPhi_0} + y^*\bra{\tPhi_1}) \qty(x\ket{\tPhi_0} + y\ket{\tPhi_1}) = \abs{x}^2 + \abs{y}^2
\end{equation}
\subex{c.}
\begin{equation}\label{key}
\begin{aligned}
\Braket{\tPhi' | \mathscr{H} | \tPhi'} &= \abs{x}^2 \Braket{\tPhi_0 | \mathscr{H} | \tPhi_0} + \abs{y}^2 \Braket{\tPhi_1 | \mathscr{H} | \tPhi_1} + x^* y \Braket{\tPhi_0 | \mathscr{H} | \tPhi_1} + x y^* \Braket{\tPhi_1 | \mathscr{H} | \tPhi_0}\\
&= E_1 - \abs{x}^2(E_1 - E_0)
\end{aligned}
\end{equation}
thus
\begin{equation}\label{key}
\mathscr{E}_1 \leq \Braket{\tPhi' | \mathscr{H} | \tPhi'} \leq E_1 - \abs{x}^2(E_1-E_1) = E_1
\end{equation}

\ex{1.22}
\begin{equation}\label{key}
\begin{aligned}
H_{11} &= \Braket{1s | \mathscr{H} | 1s} = -\dfrac{1}{2} + F\Braket{1s| r\cos\theta | 1s} = -\dfrac{1}{2}\\
H_{12} &= H_{21} = \Braket{1s | \mathscr{H} | 2p_z} = 0 + F\Braket{1s| r\cos\theta | 2p_z} = \dfrac{512 \sqrt{2} \pi }{243}F\\
H_{22} &= \Braket{2p_z | \mathscr{H} | 2p_z} = -\dfrac{1}{8} + F\Braket{2p_z| r\cos\theta | 2p_z} = -\dfrac{1}{8}
\end{aligned}
\end{equation}
Suppose $ \vb{c} = \mqty(\cos p\\ \sin p) $,
\begin{equation}\label{key}
p = \dfrac{1}{2}\arctan\dfrac{2H_{12}}{H_{11} - H_{22}} = -\dfrac{1}{2} \tan ^{-1}\qty(\dfrac{2048 \sqrt{2} F}{729})
\end{equation}
thus
\begin{equation}\label{key}
\mathscr{E}(F) = H_{11}\cos^2 p + H_{12}\sin 2p + H_{22}\sin^2 p = -\dfrac{1}{2}-\dfrac{262144}{177147}F^2+\mathcal{O}(F^3)
\end{equation}
$ \therefore $
\begin{equation}\label{key}
\alpha = 2\cross\dfrac{262144}{177147} = 2.96
\end{equation}

\end{document}


\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%    CALCULUS OF VARIATIONS APPENDIX    %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Calculus of Variations}
\index{Calculus of Variations}
\label{app:calcvar}

\section{Variational Formalism}
Here we briefly review some key aspects of the calculus of variations, with an emphasis on Euler's equations and common notations used in physics texts. The basic problem is to determine the function $y$ such that the integral $J$ given by Eq \ref{eq:app-cov:j} (properly called a functional\footnote{A functional is is a generalization of a function that depends on infinitely many parameters. In this case, $J$ depends on the value of $y$ at \textit{every} point between $x_1$ and $x_2$, so we could also write $J\big(\{y_i\}\big)$ where $\{y_i\}=\{y(x_i):x_i\in[x_1, x_2]\}$. Note that this set $\{y_i\}$ contains an uncountably infinite number of elements, hence the "functional" $J$ has infinite degrees of freedom.}) is an extremum (maximum or minimum). Physics is often concerned with the minimum case, in accordance with Hamilton's Principle. Also, when the $x$ variable is replaced with time $t$, $J$ is called the \textit{action}\index{Action}.

\eqn[eq:app-cov:j]{J = \int_{x_1}^{x_2}f\big\{y(x), y'(x); x\big\}dx}

For $J$ to be a minimum given $Y(x)$, that means that \textit{any neighboring function}, no matter how close, must make $J$ increase. We construct the notion of "neighboring" function by adding a  second function $\eta(x)$ to $y(x)$, scaled by $\alpha$, as in Eq. \ref{eq:app-cov:add-alpha}. Once the new parameter $\alpha$, which controls the "deviation" along $\eta(x)$ from the original function $y(x)$, has been propagated to $J(\alpha)$, we can formally state a necessary condition for an minimum in \ref{eq:app-cov:ex-cond}.

\begin{equation}
	\label{eq:app-cov:add-alpha}
	\begin{split}
		y(x) & \rightarrow y(\alpha, x) = y(x) + \alpha\eta(x) \\
		J & \rightarrow J(\alpha) = \int_{x_1}^{x_2}f\big\{y(\alpha, x), y'(\alpha, x); x\big\}dx \\
	\end{split}
\end{equation}

\eqn[eq:app-cov:ex-cond]{\pd{J}{\alpha}\bigg\rvert_{\alpha=0}=0}\

Note that this condition isn't sufficient, we'd also need to show the second-order partial derivative to be positive; fortunately in most physics applications this isn't required. %The familiar Lagrangian equation from Sec. \ref{sec:cm-lagrangian} is the special case of $f=\Lag$, though the variable $x$ from Eq. \ref{eq:app-cov:j} shouldn't be taken to mean the "x-coordinate," rather, it represents the familiar, generalized coordinates $q$ we're used to seeing in the Lagrangian.

\section{$\delta$ Notation}
Also worth noting, we often use a shorthand by representing the variation with a $\delta$ symbol in place of the partial derivatives of the parameter $\alpha$. This gives a shorthand notation for the extremum condition, as in Eq. \ref{eq:app-cov:short}:
\eqn{\delta J \equiv \pd{J}{\alpha}d\alpha,\quad \delta y \equiv \pd{y}{\alpha}d\alpha,\quad ...}
\eqn[eq:app-cov:short]{\delta J = \delta\int_{x_1}^{x_2}f\left\{y, y'; x\right\}dx = 0}

% Euler's Equation Derivation
\section{Euler's Equation}
Euler's equation, the more general form of the familiar Euler-Lagrange equation, can be derived from the above extremum condition for $J$. The below derivation of the Euler equation begins by computing the partial derivatives of $f$ of the new parameter $\alpha$, and then substitutes known quantities from Eq. \ref{eq:app-cov:add-alpha}:

\eqn{\pd{J}{\alpha} = \pd{}{\alpha}\int_{x_1}^{x_2}f\big\{y(x), y'(x); x\big\}dx = \int_{x_1}^{x_2}\left(\pd{f}{y}\pd{y}{\alpha} + \pd{f}{y'}\pd{y'}{\alpha}\right)dx}

\eqn{\pd{J}{\alpha} = \int_{x_1}^{x_2}\left(\pd{f}{y}\eta(x) + \pd{f}{y'}\frac{d\eta}{dx}\right)dx\where \pd{y}{\alpha} = \eta(x),\quad \pd{y'}{\alpha}=\frac{d\eta}{dx}}\

The latter term in the above can be integrated by parts:

\eqn{\int_{x_1}^{x_2}\pd{f}{y'}\frac{d\eta}{dx}dx = \pd{f}{y'}\eta(x)\bigg\rvert_{x_1}^{x_2} - \int_{x_1}^{x_2}\frac{d}{dx}\left(\pd{f}{y'}\right)\eta(x)dx\where \pd{f}{y'}\eta(x)\bigg\rvert_{x_1}^{x_2} = 0}

Factoring out a common term of $\eta(x)$ gives the succinct:

\eqn{\pd{J}{\alpha} = \int_{x_1}^{x_2} \left(\pd{f}{y} - \frac{d}{dx}\pd{f}{y'}\right)\eta(x)dx}

In order for the above to be equal to zero, the first term must vanish since $\eta(x)$ can be an arbitrary, non-zero function. This last implication gives the Euler equation:

\eqn{\boxed{\pd{f}{y} - \frac{d}{dx}\pd{f}{y'} = 0}\quad\quad\quad \text{Euler's Equation}}\

% Constraints
\section{Adding Constraints}
It is also possible to add constraints to the Euler equation; we discuss two types of constraints. The simpler type, \textit{function} constraint takes the form of a second function $g$. In such a case, the Euler equation is modified by the inclusion of an \textit{undetermined Lagrangian multiplier} $\lambda$ scaled by partial derivatives of $g$. The general case of $n$ variables and $m$ constraints is given by Eq. \ref{eq:app-cov:euler-f-const} where $i = 1, 2, ..., n$ and $j = 1, 2, ..., m$.

\eqn{\pd{f}{y} - \frac{d}{dx}\pd{f}{y'} + \lambda(x)\pd{g}{y}= 0\where g\{y, y'; x\} = 0}

This gives the form of Euler's Equation with a function constraint:

\eqn[eq:app-cov:euler-f-const]{\boxed{\pd{f}{y_i} - \frac{d}{dx}\pd{f}{y'_i} + \sum\limits_{j}\lambda_j(x)\pd{g_j}{y_i} = 0}\quad \text{Euler's Equation with function constraint}}\

A constraint may also be added in the form of an integral equation (or additional functional) $K$. In this case, $y$ must be the extremum of $\int(f + \lambda g)dx$, which gives a new form of Euler's equation as expressed in Eq \ref{eq:app-cov:euler-i-const}:
\eqn{K[y] = \int_{x_1}^{x_2}g\left\{y(x), y'(x); x\right\}dx}

\eqn[eq:app-cov:euler-i-const]{\boxed{\pd{f}{y} - \frac{d}{dx}\pd{f}{y'} + \lambda \left(\pd{g}{y} - \frac{d}{dx}\pd{g}{y'}\right) = 0}\quad \text{Euler's Equation with integral constraint}}\

% Legendre Transformation
\section{Legendre Transformation}
\label{sec:app-calc-var-legendre}
The Legendre transformation takes a convex function $f(x)$, $f''(x) > 0$, and turns it into a new function $g$ of a new variable $p$ under an extremal condition \cite{arnoldMathematicalMethodsClassical1997}. Given an arbitrary number $p$, there exists a unique point $x(p)$ such that the function $F(p, x) = px - f(x)$ has a maximum at the point $x = x(p)$. Note that $x(p)$ is therefore defined by the extremal condition $\pd{F}{x}=0$.
\eqn[eq:app-calc-var-legendre]{g(p) = F(p, x(p)) = px(p) - f(x)}
As a geometric interpretation, the line defined by $y=px$ will be maximally greater than $f(x)$ at the point $x=x(p)$, where the slope of $f(x) = p$ (depicted below):

\texfig[0.35]{app-calc-var-legendre}{Legendre Transformation, adapted from Arnold \cite{arnoldMathematicalMethodsClassical1997}.}

The Legendre transform is \textit{involutive}, meaning that its square is the identity, e.g. $L(L(f))\equiv f$. Due to this duality, we call $f$ the \textit{Young dual} of $g$, and vice versa. This relates to Young's inequality: $px <f(x) + g(p)$ for any $x$ and $p$. Note that in general $p$ is a free variable, not a strict function of $x$; rather, $p$ determines $x(p)$. Since $f(x(p)) = g(p)$, $p$ is often called the \textit{conjugate} variable to $x$. Small note: this "conjugation" refers to Young duality, not complex conjugation of $\mathbb{C}$ (which is another involution itself).


\section{A Refined IO Monad}\label{sec:state}

Next, we illustrate the expressiveness of Bounded Refinements by
showing how they enable the specification and verification of
stateful computations. We show how to
%
(1)~implement a refined \emph{state transformer}
    (\RIO) monad, where the transformer is indexed by refinements
    corresponding to \emph{pre}- and \emph{post}-conditions
    on the state~(\S~\ref{subsec:state:definition}),
%
(2)~extend \RIO with a set of combinators for
    \emph{imperative} programming, \ie whose types
    precisely encode Floyd-Hoare style program
    logics~(\S~\ref{subsec:state:examples}), and
%
(3)~use the \RIO monad to write \emph{safe scripts}
    where the type system precisely tracks capabilities
    and statically ensures that functions only access
    specific resources~(\S~\ref{subsec:state:files}).

\subsection{The RIO Monad}
\label{subsec:state:definition}

\mypara{The RIO data type} describes stateful computations.
Intuitively, a value of type @RIO a@ denotes a computation
that, when evaluated in an input @World@ produces a value
of type @a@ (or diverges) and a potentially transformed
output @World@. We implement @RIO a@ as an abstractly
refined type (as described in ~\citep{vazou13})
%%(cf. \S~\ref{sec:overview:data})
%%\nv{TODO: compare with Vac from ART}
%
%  data World
%
\begin{code}
  type Pre    = World -> Bool
  type Post a = World -> a -> World -> Bool

  data RIO a <p :: Pre, q :: Post a> = RIO {
    runState :: w:World <p> -> (x:a, World <q w x>)
  }
\end{code}
%
That is, @RIO a@ is a function @World-> (a, World)@, where
@World@ is a primitive type that represents the state of
the machine \ie the console, file system, \etc
%
This indexing notion is directly inspired by the method
of~\citep{Filliatre98} (also used in \cite{ynot}).

\mypara{Our Post-conditions are Two-State Predicates}
that relate the input- and output- world (as in~\cite{ynot}).
%
Classical Floyd-Hoare logic, in contrast,
uses assertions which are single-state
predicates.
%
We use two-states to smoothly account for
specifications for stateful procedures.
This increased expressiveness makes the
types slightly more complex than a direct
one-state encoding which is, of course
also possible with bounded refinements.

\mypara{An {RIO} computation is parameterized} by two
abstract refinements:
%
\begin{inparaenum}[(1)]
\item @p :: Pre@, which is a predicate over the \emph{input}
   world, \ie the input world @w@ satisfies the refinement
   @p w@; and
%
\item @q :: Post a@, which is a predicate relating the
   \emph{output} world with the input world and the
   value returned by the computation, \ie the output
   world @w'@ satisfies the refinement @q w x w'@ where
   @x@ is the value returned by the computation.
\end{inparaenum}
%
Next, to use @RIO@ as a monad, we define @bind@ and
@return@ functions for it, that satisfy the monad laws.
%%like the ones defined
%%for Haskell's state monad.

\mypara{The return operator} yields a pair of the
supplied value @z@ and the input world unchanged:
%
\begin{code}
  return   :: z:a -> RIO <p, ret z> a
  return z = RIO $ \w -> (z, w)

  ret z    = \w x w' -> w' == w && x == z
\end{code}
% $
The type of \return states that for any
precondition @p@ and any supplied value
@z@ of type @a@, the expression @return z@
is an \RIO computation with precondition
@p@ and a post-condition @ret z@.
The postcondition states that:
%
(1)~the output @World@ is the same as the input, and
%
(2)~the result equals to the supplied value @z@.
%
Note that as a consequence of the equality of the two worlds
and congruence, the output world @w'@ trivially satisfies @p w'@.
%
%% CHECK (3)~the result world satisfies the precondition @p@.

\mypara{The bind Operator} is defined in the usual way.
However, to type it precisely, we require bounded refinements.
%
\begin{code}
  (>>=) :: (Ret q1 r, Seq r q1 p2, Trans q1 q2 q)
        => m:RIO <p, q1> a
        -> k:(x:a<r> -> RIO <p2 x, q2 x> b)
        -> RIO <p, q> b

  (RIO g) >>= f = RIO $ \x ->
    case g x of { (y, s) -> runState (f y) s }
\end{code} %$
%
The bounds capture various sequencing requirements
(c.f. the Floyd-Hoare rules of consequence).
%
First, the output of the first action @m@,
satisfies the refinement required by the
continuation @k@;
%
\begin{code}
  bound Ret q1 r = \w x w' -> q1 w x w' => r x
\end{code}
%
Second, the computations may be sequenced,
\ie the postcondition of the first action
@m@ implies the precondition of the
continuation @k@ (which may be dependent
upon the supplied value @x@):
%
\begin{code}
  bound Seq q1 p2 = \w x w' -> q1 w x w' => p2 x w'
\end{code}%
%
Third, the transitive composition of the two
computations, implies the final postcondition:
%
\begin{code}
  bound Trans q1 q2 q = \w x w' y w'' ->
        q1 w x w' => q2 x w' y w'' => q w y w''
\end{code}

%%% \toolname verifies that the implementation of
%%% @return@ and @>>=@ satisfy their refined type
%%% signatures.
%$
Both type signatures would be impossible
to use if the programmer had to manually
instantiate the abstract refinements
(\ie pre- and post-conditions).
%
Fortunately, Liquid Type inference % automatically
generates the instantiations making it practical
to use \toolname to verify stateful computations
written using @do@-notation.

\subsection{Floyd-Hoare Logic in the RIO Monad}
\label{subsec:state:examples}

Next, we use bounded refinements to derive an
encoding of Floyd-Hoare logic, by showing how to
read and write (mutable) variables and
typing higher order
@ifM@ and @whileM@ combinators.

\mypara{We Encode Mutable Variables} as fields of
the @World@ type. For example, we might encode
a global counter as a field:
%
\begin{code}
  data World = { ... , ctr :: Int, ... }
\end{code}
%
We encode mutable variables in the refinement logic
using McCarthy's @select@ and @update@ operators
for finite maps and the associated axiom:
%
\begin{code}
  select :: Map k v -> k -> v
  update :: Map k v -> k -> v -> Map k v

  forall m, k1, k2, v.
       select (update m k1 v) k2
    == (if k1 == k2 then v else select m k2 v)
\end{code}
%
The quantifier free theory of @select@ and @update@ is decidable
and implemented in modern SMT solvers~\cite{SMTLIB2}.

\mypara{We Read and Write Mutable Variables} via
suitable ``get'' and ``set'' actions. For example,
we can read and write @ctr@ via:
%
\begin{code}
  getCtr   :: RIO <pTrue, rdCtr> Int
  getCtr   = RIO $ \w -> (ctr w, w)

  setCtr   :: Int -> RIO <pTrue, wrCtr n> ()
  setCtr n = RIO $ \w -> ((), w { ctr = n })
\end{code}
%$
Here, the refinements are defined as:
%
\begin{code}
  pTrue = \w -> True
  rdCtr = \w x w' -> w' == w && x == select w ctr
  wrCtr n = \w _ w' -> w' == update w ctr n
\end{code}
%
Hence, the post-condition of @getCtr@ states
that it returns the current value of @ctr@,
encoded in the refinement logic with McCarthy's
@select@ operator while leaving the world unchanged.
%
The post-condition of @setCtr@ states that @World@
is updated at the address corresponding to @ctr@,
encoded via McCarthy's @update@ operator.

\mypara{The {ifM} combinator}
takes as input a @cond@ action that returns a @Bool@ and,
depending upon the result, executes either
the @then@ or @else@ actions. We type it as:
%
%% name the return state v to fit it in one line
\begin{code}
  bound Pure g    = \w x v -> (g w x v => v == w)
  bound Then g p1 = \w v   -> (g w True  v => p1 v)
  bound Else g p2 = \w v   -> (g w False v => p2 v)

  ifM :: (Pure g, Then g p1, Else g p2)
      => RIO <p , g> Bool       -- cond
      -> RIO <p1, q> a          -- then
      -> RIO <p2, q> a          -- else
      -> RIO <p , q> a
\end{code}
%
The abstract refinements and bounds
correspond exactly to the hypotheses in the
Floyd-Hoare rule for the @if@ statement.
%
The bound @Pure g@ states that the @cond@
action may access but does not \emph{modify}
the @World@, \ie the output is the same
as the input @World@. (In classical Floyd-Hoare
formulations this is done by syntactically
separating terms into pure \emph{expressions}
and side effecting \emph{statements}).
%
The bound @Then g p1@ and @Else g p2@ respectively
state that the preconditions of the @then@ and @else@
actions are established when the @cond@ returns @True@
and @False@ respectively.

\mypara{We can use {ifM}} to implement a stateful
computation that performs a division, after checking
the divisor is non-zero.
%
We specify that @div@ should not be called with a zero divisor.
Then, \toolname verifies that @div@ is called safely:
%
\begin{code}
  div :: Int -> {v:Int | v != 0} -> Int

  ifTest :: RIO Int
  ifTest = ifM nonZero divX (return 10)
    where nonZero = getCtr >>= return . (!= 0)
          divX    = getCtr >>= return . (div 42)
\end{code}
%
Verification succeeds as the post-condition of @nonZero@
is instantiated to
{@\_ b w -> b <=>@ @select w ctr != 0@}
and the pre-condition of @divX@'s is instantiated to
{@\w -> select w ctr != 0@}, which suffices to
prove that @div@ is only called with non-zero values.

\mypara{The {whileM} combinator}
formalizes loops as @RIO@ computations:
%
\begin{code}
  whileM :: (OneState q, Inv p g b, Exit p g q)
         => RIO <p, g> Bool      -- cond
         -> RIO <pTrue, b> ()    -- body
         -> RIO <p, q> ()
\end{code}
%
As with @ifM@, the hypotheses of the Floyd-Hoare derivation rule
become bounds for the signature.
%
Given a @cond@ition with pre-condition @p@ and
post-condition @g@ and @body@ with a true
precondition and post-condition @b@, the computation
@whileM cond body@ has precondition @p@ and post-condition
@q@ as long as the bounds (corresponding to the Hypotheses
in the Floyd-Hoare derivation rule) hold.
%
First, @p@ should be a loop invariant; \ie when
the @cond@ition returns @True@ the post-condition
of the body @b@ must imply the @p@:
%
\begin{code}
  bound Inv p g b = \w w' w'' ->
      p w => g w True w' => b w' () w'' => p w''
\end{code}
%
Second, when the @cond@ition returns @False@ the invariant @p@
should imply the loop's post-condition @q@:
%
\begin{code}
  bound Exit p g q = \w w' ->
        p w => g w False w' => q w () w'
\end{code}
%
Third, to avoid having to transitively connect the guard and the body,
we require that the loop post-condition be a one-state predicate,
independent of the input world (as in Floyd-Hoare logic):
%
\begin{code}
  bound OneState q = \w w' w'' ->
        q w () w'' => q w' () w''
\end{code}

\mypara{We can use {whileM}} to implement a loop that repeatedly
decrements a counter while it is positive, and to then verify that
if it was initially non-negative, then
at the end the counter is equal to @0@.
%
\begin{code}
  whileTest   :: RIO <posCtr, zeroCtr> ()
  whileTest = whileM gtZeroX decr
    where gtZeroX = getCtr >>= return . (> 0)

  posCtr  = \w -> 0 <= select w ctr
  zeroCtr = \_ _ w' -> 0 == select w ctr
\end{code}
%
Where the decrement is implemented by @decr@ with type:
%
\begin{code}
  decr :: RIO <pTrue, decCtr> ()

  decCtr = \w _ w' -> w' == update w ctr ((select ctr w) - 1)
\end{code}
% $
\toolname verifies that at the end of @whileTest@
the counter is zero (\ie the post-condition @zeroCtr@)
by instantiating suitable (\ie inductive) refinements
for this particular use of @whileM@.


\section{Figures}

\begin{figure}[!hbtp]
    \centering
    \includegraphics[width=\textwidth]{../src/lab_08_figure_01.pdf}
    \caption{Polynomial Interpolation using different routines}
    \label{fig:my_label}
\end{figure}

\begin{figure}[!hbtp]
    \centering
    \includegraphics[width=\textwidth]{../src/lab_08_figure_02.pdf}
    \caption{Derivatives of Interpolation Polynomials}
    \label{fig:my_label}
\end{figure}
\newpage
\section{Script}
\subsection{Script file: \lstinline[style=Plain]{lab_08_script.m}}
\lstinputlisting[style=MATLAB]{../src/lab_08_script.m}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Written By Michael Brodskiy
% Class: Analytic Geometry & Calculus III (Math-292)
% Professor: V. Cherkassky
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[12pt]{article}
\usepackage{alphalph}
\usepackage[utf8]{inputenc}
\usepackage[russian,english]{babel}
\usepackage{titling}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{enumitem}
\usepackage{amssymb}
\usepackage[super]{nth}
\usepackage{everysel}
\usepackage{ragged2e}
\usepackage{geometry}
\usepackage{fancyhdr}
\geometry{top=1.0in,bottom=1.0in,left=1.0in,right=1.0in}
\newcommand{\subtitle}[1]{%
  \posttitle{%
    \par\end{center}
    \begin{center}\large#1\end{center}
    \vskip0.5em}%

}
\usepackage{hyperref}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=blue,
citecolor=blue,
}

\urlstyle{same}

\title{Lecture XIII Notes}
\date{\today}
\author{Michael Brodskiy\\ \small Professor: V. Cherkassky}

% Mathematical Operations:

% Sum: $$\sum_{n=a}^{b} f(x) $$
% Integral: $$\int_{lower}^{upper} f(x) dx$$
% Limit: $$\lim_{x\to\infty} f(x)$$

\begin{document}

\maketitle

\section{Maxima and Minima $-$ 14.7}

In three dimensions, a point is determined to be critical if:
$$\frac{\partial f}{\partial x}(a,b)=0,DNE\text{ and } \frac{\partial f}{\partial y}(a,b)=0,DNE$$

From here, it needs to be determined whether or not there is an extrema at point $(a,b)$, and whether it is a minima or maxima.

\subsection{The Second Derivative Test}

First, $\frac{\partial^2f}{\partial x^2}\text{, } \frac{\partial^2f}{\partial x \partial y}\text{, } \frac{\partial^2f}{\partial y \partial x}\text{ and } \frac{\partial^2f}{\partial y^2}$ must be found. Then the determinant, $D$, of these must be found:
\begin{center}
  \begin{tabular}{|c c|}
    $f_{xx}$ & $f_{xy}$ \\
    $f_{yx}$ & $f_{yy}$ \\

  \end{tabular}
\end{center}

$$f_{xx}f_{yy}-(f_{xy})^2$$

\begin{enumerate}

  \item If $D > 0$, and $f_{xx}(a,b)>0$, then $f(a,b)$ is a local minimum

  \item If $D > 0$, and $f_{xx}(a,b)<0$, then $f(a,b)$ is a local maximum

  \item If $D < 0$, then $f(a,b)$ is not a local maximum or minimum (saddle point)

\subsection{Bounded Sets}

In a closed, bounded set, $f$ attains a maximum at $(x_1,y_1)$, and a minimum at $(x_2,y_2)$

\end{enumerate}

\end{document}


\documentclass[modern]{aastex62}

\usepackage{amsmath}
\usepackage{amssymb}

\newcommand{\dd}{\mathrm{d}}
\newcommand{\diff}[2]{\frac{\dd #1}{\dd #2}}

\begin{document}

\title{Notes on the Model}
\author[0000-0003-1540-8562]{Will M. Farr}
\affiliation{Department of Physics and Astronomy, Stony Brook University, Stony Brook NY 11794, USA}
\affiliation{Center for Computational Astronomy, Flatiron Institute, 162 5th Ave., New York NY 10010, USA}
\email{will.farr@stonybrook.edu}

\begin{abstract}
  I discuss the contaminated mixture model that we are using.
\end{abstract}

\section{Hierarchical Likelihood}

We assume, following \citet{Foreman-Mackey2014}, that the occurrence rate of
planets is constant in some set of bins in the period-radius plane, $R_i \leq R
< R_{i+1}$, $P_i \leq P \leq P_{i+1}$, $i = 1, \ldots, N_\mathrm{bin}$:
%
\begin{equation}
  \diff{N}{\ln P \dd \ln R} = \begin{cases}
  n_i & R_i \leq R < R_{i+1} \textnormal{ and } P_i \leq P \leq P_{i+1} \\
  \tilde{n} & \textnormal{otherwise}
\end{cases}.
\end{equation}
%
We include a ``catch all'' bin, where the rate density is $\tilde{n}$ to avoid
issues at the edges of the set of bins; with the catch-all bin, we can cut the
data set several ``sigma'' outside the region of interest with bins, and objects
that land on the edges will be distributed between the bins and the
``catch-all'' bin.  Note that, for all practical purposes, Kepler measures the
period perfectly, so the only uncertainty in any of the measurements is the
radius.

We also assume that the contaminated background follows a similar
constant-in-bin model,
%
\begin{equation}
  \diff{N_{\mathrm{bg}}}{\ln P \dd \ln R} = b_i \quad R_i \leq R < R_{i+1} \textnormal{ and } P_i \leq P \leq P_{i+1},
\end{equation}
%
but here we do not include the extra bin (since we don't care about the
background-foreground distinction in that bin).

Let us assume that the likelihood is well-approximated by a delta function in
period and a log-normal distribution for the radius for each planet detection:
%
\begin{equation}
    p\left( d \mid \ln P, \ln R \right) \propto \delta\left( \ln P_\mathrm{obs} - \ln P \right) \frac{1}{\sqrt{2\pi} \sigma_{\ln R}} \exp\left[ \frac{\left( \ln R_\mathrm{obs} - \ln R \right)^2}{2 \sigma_{\ln R}^2} \right].
\end{equation}
%
Then the hierarchical likelihood for a set of planet candidates can be obtained
by integrating out the ``nuisance'' parameters giving the true period and radius
of each planet \citep{Mandel2018,Loredo2004}:
%
\begin{multline}
  \label{eq:hier-likelihood}
  p\left( \left\{ d_j \right\} \mid \left\{ n_i \right\}, \tilde{n}, \left\{b_i \right\} \right) \propto  \left[ \prod_{j = 1}^{N} \int \dd \ln P_j \, \dd \ln R_j \, p\left( d_j \mid \ln P_j, \ln R_j \right) \right. \\ \times \left. \left( \diff{N}{\ln P_j \dd \ln R_j} + \diff{N_\mathrm{bg}}{\ln P_j \dd \ln R_j} \right) \right] \exp\left[ - N_\mathrm{ex} - N_\mathrm{bg} - \tilde{N} \right];
\end{multline}
%
where $N_\mathrm{ex}$ is the expected number of true planet detections within the
grid of cells,
%
\begin{equation}
  N_\mathrm{ex} = \sum_{i=1}^{N_\mathrm{bin}} n_i \Delta \ln P_i \Delta \ln R_i \sum_{k = 1}^{N_\mathrm{stars}}  \left\langle P_\mathrm{det}^{(k)} \right\rangle_i,
\end{equation}
%
where $\left\langle P_\mathrm{det}^{(k)} \right\rangle_i$ is the detection
probability for a planet around star $k$ averaged over cell $i$ for a flat
population in $\ln P$ and $\ln R$; $N_\mathrm{bg}$ is the expected number of
background observations
%
\begin{equation}
  N_\mathrm{bg} = \sum_{i=1}^{N_\mathrm{bin}} b_i \Delta \ln P_i \Delta \ln R_i;
\end{equation}
%
and $\tilde{N}$ is the expected number of detections in the ``catch all'' bin
%
\begin{equation}
  \tilde{N} = \tilde{n} \tilde{V},
\end{equation}
%
where $\tilde{V}$ is the volume of the catch-all in $\ln P$-$\ln R$ space.
Because the population is assumed to be constant in bins, the integrals in Eq.
\eqref{eq:hier-likelihood} reduce to
%
\begin{equation}
  \label{eq:reduced-likelihood}
  p\left( \left\{ d_j \right\} \mid \left\{ n_i \right\}, \tilde{n}, \left\{b_i \right\} \right) \propto  \left[ \prod_{j = 1}^{N} \tilde{w}_j \tilde{n} + \sum_{i=1}^{N_\mathrm{bin}} w_{ji} \left( n_i + b_i \right) \right] \exp\left[ - N_\mathrm{ex} - N_\mathrm{bg} - \tilde{N} \right],
\end{equation}
%
where
%
\begin{equation}
  w_{ji} = \int_{R_i \leq R_j < R_{i+1} \cap P_i \leq P_j < P_{i+1}} \dd \ln P_j \, \dd \ln R_j \, p\left( d_j \mid \ln P_j, \ln R_j \right),
\end{equation}
%
are weights assigned to each bin (similarly for $\tilde{w}_j$ for the catch-all
bin).  The $w_{ji}$ can be pre-computed, as they depend only on the bin
boundaries and the observed periods, radii, and radius uncertainties.

\section{Prior}

The foreground and background per-bin rates, $n_i$ and $b_i$, are degenerate in
the likelihood in Eq.\ \eqref{eq:reduced-likelihood}.  We can break the
degeneracy using an informative prior on one or both rate distributions.  Here
we will assume that we have \emph{measured} the background contamination rate
(perhaps imperfectly) through some independent process, and incorporate this
through an informative prior on the background rate densities $b_i$.

Following \citet{Formean-Mackey2014}, we choose to estimate the background $b_i$
by using the results of a search over \emph{inverted} Kepler lightcurves using
the same pipelines used to produce the catalog \citep{Coughlin2017}.  TODO: more
details here.  We supply a log-normal prior on $b_i$ based on the observed count
of non \texttt{FP} inverted-lightcurve candidate events and a relative
uncertainty of $1/\sqrt{N}$.

We choose to implement a Gaussian process prior on the (log of the) $n_i$.  We
choose a constant-mean, squared exponential covariance GP on the log-rates:
%
\begin{equation}
  \ln \vec{n} \sim N\left( \mu \vec{1} , \mathbf{\Sigma} \right),
\end{equation}
%
with
%
\begin{equation}
  \Sigma_{ij} = \sigma^2 \left( 1 + \epsilon \delta_{ij} \right) \exp\left[ -\frac{\left| \Delta \vec{x}_{ij} \right|^2}{2 \lambda^2} \right].
\end{equation}
%
The single-bin variance is $\sigma^2 \left( 1 + \epsilon \right)$, $\epsilon \ll
1$ is a fractional white-noise component added to the diagonal terms of the
matrix for stability, $\Delta \vec{x}_{ij}$ is the displacement vector between
the centers of bin $i$ and bin $j$ in the $\ln P$-$\ln R$ plane, and $\lambda$
is a correlation length scale in this plane\footnote{A natural extension would
be to allow the $\ln P$ and $\ln R$ dimensions to have \emph{independent} length
scales; or even to impose an arbitrary \emph{metric} matrix that would allow for
arbitrary anisotropy in the correlations.}.

\section{Correlations in Planet Detection}

The model currently assumes that the detection probability for each planet is
independent of all the other planets in the same system.  This will
over-estimate the number of planets per star (since it almost certainly makes
second and subsequent planets seem harder to detect than they should be---at
least if there are \emph{any} planetary disks out there).  I will think about
how to modify the detection probability calculation to better reflect the fact
that planets occur in disks.  That, in itself, would be worth another paper; and
a particularly exciting one if we could find evidence for small disk opening
angles (i.e.\ once one planet transits, all the planets transit).

\section{Actual Data}

Plots of the actual data go here.

\bibliography{mixture_notes}

\end{document}


\section{Use of Recursive Functions}

\begin{lstlisting}[language=Haskell]
module ProgExercises.FS_2019_ProgExer03Prob_V01 where

  -- Develop some functions using recursion over lists.
  -- Higher-order functions are not required yet.

toBeImplemented = undefined

--delDups deletes duplicates from a list
testDelDups =
  delDups [1,2,3,4,5] == [1,2,3,4,5] &&
  delDups [1,1,1,1,1] == [1] &&
  (delDups [1,2,2,4,1] == [1,2,4] || delDups [1,2,2,4,1] == [2,4,1]) &&
  delDups []          == ([] :: [Int])

delDups :: Eq a => [a] -> [a]
delDups [] = []
delDups (x : xs)
  | x `elem` xs = delDups xs
  | otherwise   = x : delDups xs

-- removeEachSnd removes each second element from a list.
testRemoveEachSnd =
  removeEachSnd [1,2,3,4,5,6,7,8] == [1,3,5,7] &&
  removeEachSnd [1,2,3,4,5,6,7]   == [1,3,5,7] &&
  removeEachSnd [1]               == [1] &&
  removeEachSnd []                == ([] :: [Int])

removeEachSnd :: [a] -> [a]
removeEachSnd [] = []
removeEachSnd (a : []) = [a]
removeEachSnd (x : xs : xz) = x : removeEachSnd xz

-- makePairs pairs adjacent elements of a list
testMakePairs =
  makePairs [1,2,3,4,5,6,7,8] == [(1,2),(3,4),(5,6),(7,8)] &&
  makePairs [1,2,3,4,5,6,7]   == [(1,2),(3,4),(5,6)] &&
  makePairs [1,2]             == [(1,2)] &&
  makePairs [1]               == [] &&
  makePairs []                == ([] :: [(Int,Int)])

makePairs :: [a] -> [(a, a)]
makePairs [] = []
makePairs (a : []) = []
makePairs (x : xs : xz) = (x, xs) : makePairs xz

testMakePairsV2 =
  makePairsV2 [1,2,3,4,5,6,7,8] == [(1,2),(3,4),(5,6),(7,8)] &&
  makePairsV2 [1,2,3,4,5,6,7]   == [(1,2),(3,4),(5,6)] &&
  makePairsV2 [1,2]             == [(1,2)] &&
  makePairsV2 [1]               == [] &&
  makePairsV2 []                == ([] :: [(Int,Int)])

makePairsV2 :: [a] -> [(a, a)]
makePairsV2 []          = []
makePairsV2 xs@(_ : ys) = removeEachSnd (zip xs ys)

-- halve divides a list into two lists containing each second element,
-- the first list beginning with the first,
-- the second list beginning with the second
testHalve =
  halve [1,2,3,4,5,6] == ([1,3,5], [2,4,6]) &&
  halve [1,2,3,4,5]   == ([1,3,5], [2,4]) &&
  halve [1]           == ([1], []) &&
  halve []            == ([], [] :: [Int])

halve :: [a] -> ([a], [a])
halve xs = h xs [] []
  where
    h (x1 : x2 : xs) accu1 accu2 = h xs (x1 : accu1) (x2 : accu2)
    h [x]            accu1 accu2 = h [] (x : accu1) accu2
    h []             accu1 accu2 = (reverse accu1, reverse accu2)

-- divideList divides a list into chunks of length n each, except
-- of the last chunk, which might be shorter
-- Precondition:
--   n > 0
-- Theorem:
--   For all n > 0 and all xs: concat (divideList n xs) == xs
testDivideList =
  divideList 3 [1 .. 10] == [[1,2,3],[4,5,6],[7,8,9],[10]] &&
  divideList 3 [1 .. 9] == [[1,2,3],[4,5,6],[7,8,9]] &&
  divideList 3 [1] == [[1]] &&
  divideList 3 [] == ([] :: [[Int]])

divideList :: Int -> [a] -> [[a]]
divideList _ [] = []
divideList n xs = take n xs : divideList n (drop n xs)
\end{lstlisting}

\clearpage


\documentclass[11pt,a4paper]{report}
\usepackage{amsmath,amsfonts,amssymb,amsthm,epsfig,epstopdf,titling,url,array}
\usepackage{enumitem}
\usepackage{changepage}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{listings}
\usepackage{color}
\theoremstyle{plain}
\newtheorem{thm}{Theorem}[section]
\newtheorem{lem}[thm]{Lemma}
\newtheorem{prop}[thm]{Proposition}
\newtheorem*{cor}{Corollary}
\theoremstyle{definition}
\newtheorem{defn}{Definition}[section]
\newtheorem{conj}{Conjecture}[section]
\newtheorem{exmp}{Example}[section]
\newtheorem{exercise}{Exercise}[section]
\theoremstyle{remark}
\newtheorem*{rem}{Remark}
\newtheorem*{note}{Note}
\def\changemargin#1#2{\list{}{\rightmargin#2\leftmargin#1}\item[]}
\let\endchangemargin=\endlist

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
	backgroundcolor=\color{backcolour},
	commentstyle=\color{codegreen},
	keywordstyle=\color{magenta},
	numberstyle=\tiny\color{codegray},
	stringstyle=\color{codepurple},
	basicstyle=\footnotesize,
	breakatwhitespace=false,
	breaklines=true,
	captionpos=b,
	keepspaces=true,
	numbers=left,
	numbersep=5pt,
	showspaces=false,
	showstringspaces=false,
	showtabs=false,
	tabsize=2
}

\lstset{style=mystyle}
\begin{document}

\section*{Problem}
Moe's revolutionary ``oreo design" hotel has become so successful that his VBA-powered MSFT Access CRS is having trouble handling the transaction volume coming at it when both of his room service / sales agents (Huey and Looey) take calls at the same time.  The system doesn't have any logging and doesn't store enough info to count transactions, but Joe found a way to sample counts of transactions per hour throughout the day.  Using his Colorado City HS AP Stats training, Joe estimated a polynomial regression model from the data and came up with the following model for the rate of incoming transactions per hour (in thousands) as a function of time over the period when Huey and Looey answer the phone (between 2 and 6 in the afternoon):
$$r(t) = -t^2 +8t - 12$$
where t is measured in hours starting at $t = 2$ and ending at $t = 6$.  How many total transactions should Moe expect to receive between 2 and 6?

\section*{Solution}
$\int_{2}^{6}{-t^2 + 8t - 12}dt = \left[x^3/3 + 4x^2 - 12x\right]_2^6 = 32/3$ thousand transactions.

\end{document}