\documentclass[paper=a4, fontsize=11pt]{scrartcl} % A4 paper and 11pt font size
\usepackage{physics}
\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs
\usepackage{fourier} % Use the Adobe Utopia font for the document - comment this line to return to the LaTeX default
\usepackage[english]{babel} % English language/hyphenation
\usepackage{amsmath,amsfonts,amsthm} % Math packages
\usepackage{braket}
\usepackage{lipsum} % Used for inserting dummy 'Lorem ipsum' text into the template
\usepackage{tikz}
\usepackage{amsmath}
\usepackage{sectsty} % Allows customizing section commands
\allsectionsfont{\centering \normalfont\scshape} % Make all sections centered, the default font and small caps

\usepackage{fancyhdr} % Custom headers and footers
\pagestyle{fancyplain} % Makes all pages in the document conform to the custom headers and footers
\fancyhead{} % No page header - if you want one, create it in the same way as the footers below
\fancyfoot[L]{} % Empty left footer
\fancyfoot[C]{} % Empty center footer
\fancyfoot[R]{\thepage} % Page numbering for right footer
\renewcommand{\headrulewidth}{0pt} % Remove header underlines
\renewcommand{\footrulewidth}{0pt} % Remove footer underlines
\setlength{\headheight}{13.6pt} % Customize the height of the header
\usepackage{float}
\numberwithin{equation}{section} % Number equations within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
\numberwithin{figure}{section} % Number figures within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)

\setlength\parindent{0pt} % Removes all indentation from paragraphs - comment this line for an assignment with lots of text

%----------------------------------------------------------------------------------------
%	TITLE SECTION
%----------------------------------------------------------------------------------------

\newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height

\title{
\normalfont \normalsize
\textsc{California State University San Marcos \\ Dr. Dominguez, Physics 490} \\ [25pt] % Your university, school and/or department name(s)
\horrule{0.5pt} \\[0.4cm] % Thin top horizontal rule
\huge Astrophysics H.W. I \\ % The assignment title
\horrule{2pt} \\[0.5cm] % Thick bottom horizontal rule
}

\author{Josh Lucas} % Your name

\date{\normalsize\today} % Today's date or a custom date

\begin{document}

\maketitle % Print the title

%----------------------------------------------------------------------------------------
%	PROBLEM 1
%----------------------------------------------------------------------------------------

\section{Weighing the Earth and the Sun}
\begin{equation}
\vec{F}= \frac{GMm}{r^2}\hat{r}
\end{equation}
\textbf{a) What are the units of the universal gravitational constant G?}\\
\\
We can find the units of the Universal Gravitaional constant by solving for G and analyzing the coresponding units.
\begin{equation*}
m\vec{a} = \frac{GMm}{r^2}\hat{r} \rightarrow G = \frac{m\vec{a} r^2}{Mm} = \frac{\vec{a}r^2}{M} = \frac{meters^3}{kilograms\ * seconds^2}
\end{equation*}
\textbf{(b) Using the radius of the earth,($R_E$), and empirical observations that the acceleration of an object near the Earth is g ($9.8ms^-2$)  and G is Newton's  Universal gravitational constant, find an expression for the mass of the Earth and use it to estimate the Earth's mass.}\\
\\
We know that the acceleration of an object near the Earth is $\vec{a} = 9.8\tfrac{m}{s^2}$, the force of the Earth's gravity on an object is equal to the mass of the ogbject multiplied by the acceleration,  $ \vec{F_g} = m\vec{a}$. Using the radius of the earth and Newton's Universal gravitation constant we can solve for the mass of the earth.
\begin{equation*}
m\vec{a} = G\frac{M_E m}{R_E^2}\hat{r} \rightarrow M_E = \frac{\vec{a}R_E^2}{G} = \frac{(9.8\tfrac{m}{s^2})\ 6.378\times 10^6m}{6.674\times 10^-11 \tfrac{m^3}{kg*s^2}} = 5.97\times 10^{24}
\end{equation*}
\section{Weighing the Sun}

\textbf{(a) An astronomical unit (AU) is defined as the average distance between the Earth and the
center of the Sun. Assuming that it take about 8.5 minutes for light from the Sun to reach the
Earth, derive an expression using the speed of light that represents 1 AU.}\\
\\
Distance is equal to velocity multiplied by time
\begin{equation*}
C * t = d \rightarrow 2.99\times 10^8 \tfrac{m}{s} * 8.5min \big(\frac{60sec}{1min}\big) = 1.5\times 10^8 km\approx1 AU
\end{equation*}
Velocity has units of meters per second which if multiplied by time and we get a distance.

We can use a slightly closer approximation by using 500 seconds multiplied by the speed of light for 1 AU\\

\textbf{(b)Using the fact that it takes 1 year for the Earth to complete one revolution around
the Sun, please derive an expression for the mass of the Sun and calculate this mass.}\\

The average distance of the radius of the Earth orbit is one astronomical unit which it completes in one years time. From this relation we can find the velocity of the earth and the force holding the earth in orbit.
The Earth's velocity is equal to the circumference of the orbit over the time,
\begin{equation*}
circumfrence = \int rd\theta = 2\pi r = 2\pi (1AU)
\end{equation*}
\begin{equation*}
\frac{distance}{time}= velocity =\frac{2\pi (1AU)}{\pi \times 10^7 sec} = 30000\tfrac{m}{s}
\end{equation*}
We can now solve for the center force on the earth tethering it to the sun,
\begin{equation*}
\vec{F_c} = m\frac{v^2}{r} =  5.97\times 10^24 kg \frac{(30000\tfrac{m}{s})^2}{6.378\times 10^6} = 8.434\times 10^{26} joules
\end{equation*}
We can now relate the center force to the Newtons equation for gravity,
\begin{equation*}
\frac{mv^2}{r} = G\frac{Mm}{r^2}\hat{r} \rightarrow M = \frac{v^2r}{G} = \frac{(30000\tfrac{m}{s})^26.378\times 10^6}{1.5\times 10^{11}\tfrac{m^3}{kg*s^2} } \approx 2\times 10^{30}kg
\end{equation*}

\textbf{(c) Using your expression for Problem 1 part (b) and your answer from part (b) of this
problem, derive an expression for the ratio of Earth's mass to that of the Sun.}\\
\\
\section{Escape Velocities}
\textbf{The escape velocity is defined as the velocity initially needed by an object to permanently
leave the gravitational pull of a planet, star, etc.
(a) Derive a general expression for the escape velocity for an object of mass m leaving
the gravitational in
influence of a more massive object with mass M.}\\
\textbf{
(b) Using your expressions from the previous problems, derive an escape velocity for (1)
Earth and (2) The Sun. You can assume that for Earth, the initial position is RE and for
the Sun the initial position is at 1 AU.}\\
\textbf{(c) Provide numerical answers to part (b) in units of (1) meter and seconds (2) miles and
hours.}\\
\textbf{(d)Imagine an object with Earth's mass (mE) what is so compact that the escape velocity
is equal to the speed of light c. Derive an expression, using your answer from part (a), for
the radius of this object. What is this value numerically?}

\section{Keppler Orbits 1/2}
\textbf{(a) Derive an expression for the orbital velocity of Earth assuming it has a circular orbit of
radius $r_{E-S}$.}\\
\begin{equation}
\vec{V_{orbit}} = \frac{\text{circumfrence of orbit}}{time of one revolution} = \frac{2\pi 1.5\times 10^{8}km}{\pi \times 10^7 sec} \approx
\end{equation}
We can also use the relation of the center force and gravitational force and solve for velocity
\begin{equation*}
\frac{mv^2}{r} = G\frac{Mm}{r^2 } \rightarrow v^2 = \frac{GM}{r}
\end{equation*}
\textbf{(b) Using your expression from part (a), derive an expression for the total energy of Earth
(= KE + PE) and comment on whether it is less than or greater than zero.}

\begin{equation*}
T = \frac{1}{2}mv^2
\end{equation*}
replacing v for terms of gravitational force,
\begin{equation*}
T= \frac{1}{2}m(\frac{GM}{r})
\end{equation*}
\begin{equation*}
U = -\int \vec{F}\cdot d\vec{r} \rightarrow U = - \int -GMm \frac{1}{r^2} d\vec{r} = -GMm\frac{1}{2r}
\end{equation*}
%----------------------------------------------------------------------------------------
\section{Keppler Orbits 2/2}

\textbf{(a) Run the Matlab code and make sure that it works. If it doesn't, you might have to
modify the code to dene the mass of the Sun. You should not need to dene the mass of
the object (Why?). What is the shape of the orbit?}\\
\textbf{(b) increase the initial velocity of the satellite by 10%. What happens to the shape of
the orbit?}\\
\textbf{(c) increase the initial velocity of the object by 20%. What happens to the shape of the
orbit?}\\
\textbf{(d) Decrease the  velocity by 20$\%$. What happens to the shape of the orbit?}\\
\textbf{(e) Set the magnitude of the satellite's initial velocity equal to the escape velocity. Comment and sketch the shape of the orbit.}

\section{Free Falling}
\textbf{(a)Consider a mass m initially at a distance R from a much more massive mass M. Derive
an expression for the time it would take for this mass to crash into the much more massive mass. You can assume that the radius of both masses if much smaller than R. Check the
units of your answer.}\\
\textbf{(b) Calculate what this free-fall timescale is if R is 1 AU.}\\
\textbf{(c) Extra-credit: Check your answer in part (b) by using the numerical orbit simulator
(or write your own code) used in our previous problem.}
\end{document}


\section{Syntax}

\begin{table}[!htb]
    \centering\sl
    \begin{tabular}{lcl}
        firstletter
            &$\Coloneqq$&\keyword{a..z} $\mid$ \keyword{A..Z}\\
        letter
            &$\Coloneqq$&\keyword{a..z} $\mid$ \keyword{A..Z} $\mid$ \keyword{\_}\\
        ident
            &$\Coloneqq$&firstletter \{letter\}\\
        term
            &$\Coloneqq$&\fforall{} binder \{binder\}, term\\
            &$\mid$&\ffun{} \{binder\} \darrow{} term\\
            &$\mid$&\ffix{} ident binder \{binder\} \scolon{} term \scoloneq{} term\\
            &$\mid$&\flet{} ident \{binder\} \scolon{}term \scoloneq{} term \fin{} term\\
            &$\mid$&term \sarrow{} term\\
            &$\mid$&term arg \{arg\}\\
            &$\mid$&\fmatch{} term \fas{} ident \fin{} ident \{ident\} \freturn{} term \fwith{}\\
            &      &~~~~\{~$\mid$ equation\}\\
            &      &\fend{}\\
            &$\mid$&\fType{}\\
            &$\mid$&(term)\\
        arg
            &$\Coloneqq$&term\\
        binder
            &$\Coloneqq$&(ident \scolon{} term)\\
        equation
            &$\Coloneqq$&pattern \darrow{} term\\
        pattern
            &$\Coloneqq$&ident \{ident\}\\\\\\
        sentence
            &$\Coloneqq$&axiom\\
            &$\mid$&definition\\
            &$\mid$&inductive\\
            &$\mid$&fixpoint\\
            &$\mid$&assertion proof\\
        axiom
            &$\Coloneqq$&\fAxiom{} ident \scolon{} term .\\
        definition
            &$\Coloneqq$&\fDefinition{} ident \{binder\} \scolon{} term \scoloneq{} term .\\
        inductive
            &$\Coloneqq$&\fInductive{} ident \{binder\} \scolon{} term \scoloneq{}\\
            &&~~~~\{~$\mid$ ident \scolon{} term\} .\\
        fixpoint
            &$\Coloneqq$&\fFixpoint{} ident \{binder\} \scolon{} term \scoloneq{} term .\\
        assertion
            &$\Coloneqq$&\fTheorem{} ident \{binder\} \scolon{} term .\\
        proof
            &$\Coloneqq$&\fProof{} . \{tactic .\} \fQed{} .\\
        helper
            &$\Coloneqq$&printing\\
            &$\mid$&proof\_handling\\
        printing
            &$\Coloneqq$&\fPrint{} ident .\\
            &$\mid$&\fCheck{} term .\\
        proof\_handling
            &$\Coloneqq$&\fUndo{} .\\
            &$\mid$&\fRestart{} .\\
            &$\mid$&\fAdmitted{} .\\
            &$\mid$&\fAbort{} .\\
    \end{tabular}
\end{table}
\newpage
\begin{table}[!htb]
    \centering\sl
    \begin{tabular}{lcl}
        tactic
            &$\Coloneqq$&applying\\
            &$\mid$&context\_managing\\
            &$\mid$&case\_analyzing\\
            &$\mid$&rewriting\\
            &$\mid$&computing\\
            &$\mid$&equality\\
        applying
            &$\Coloneqq$&\fexact{} term\\
            &$\mid$&\fapply{} term [\fin{} ident]\\
            &$\mid$&\fleft{}\\
            &$\mid$&\fright{}\\
            &$\mid$&\fsplit{}\\
            &$\mid$&\fexists{}\\
        context\_managing
            &$\Coloneqq$&\fintro{} \{ident\}\\
            &$\mid$&\fintros{}\\
        case\_analyzing
            &$\Coloneqq$&\fdestruct{} term\\
            &$\mid$&\finduction{} term\\
        rewriting
            &$\Coloneqq$&\frewrite{} [~\larrow{} $\mid$ \sarrow{}] term [~\fin{} term]\qquad\qquad\qquad\qquad\qquad\qquad\quad\\
        computing
            &$\Coloneqq$&\fsimpl{} [\fin{} ident]\\
            &$\Coloneqq$&\funfold{} [\fin{} ident]\\
        equality
            &$\Coloneqq$&\freflexivity{}\\
            &$\mid$&\fsymmetry{}\\\\\\
    \end{tabular}
\end{table}


%auto-ignore
\providecommand{\MainFolder}{..}
\documentclass[\MainFolder/Text.tex]{subfiles}
\begin{document}

\section{BV-formulation for dIBL-algebra on cyclic cochains}\label{Sec:BVAction}

In the setting of Section~\ref{BV:Summary}, we define
$$ \CycB(V) := \BCyc V [3-n]\quad\text{and}\quad \Fun(\CycB(V)) := \hat{\Ext} \CycC(V) ((\hbar)) = \Ext \CycC(V) \COtimes \K((\hbar)). $$
We call $\Fun(\CycB(V))$ the \emph{space of functions on $\CycB(V)$}. This makes sense because $\CycC(V) \subset (\BCyc V [2-n])^{\GD}$, $\Ext \CycC(V) = \Sym(\CycC(V)[1])$ and the symmetric algebra of the dual can be viewed as polynomial functions.
In contrast to \cite{Doubek2018}, we do not have any canonical odd symplectic\Correct[noline,caption={Graded symplectic form}]{Define and use graded symplectic form and $dg$-symplectic vector space.} form on $B(V)$, and hence there is no Schwarz's $\BV$-operator on $\Fun(B(V))$.
However, we have the following $\BV$-operators from~\cite{Cieliebak2015}:
\begin{align*}
 \BVOp_0 & \coloneqq \hat{\OPQ}_{120} + \hbar \hat{\OPQ}_{210}, \\
 \BVOp &\coloneqq \hat{\OPQ}_{110} + \BVOp_0, \\
 \BVOp^\MC & \coloneqq \reallywidehat{\OPQ_{210}\circ_1 \MC_{10}} + \BVOp.
\end{align*}
The first $\BV$-operator is canonical for an odd symplectic vector space $(V,\Pair)$, and we call it the \emph{string $\BV$-operator.}
It is a $\BV$-operator because $\hat{\OPQ}_{120}$ is a derivative of order $1$, $\hat{\OPQ}_{210}$ a derivative of order $2$, and it holds $\BVOp_0\circ\BVOp_0 = 0$.
The second $\BV$-operator is canonical for a cyclic cochain complex $(V,\Pair,m_1)$ and the third for a cyclic $\DGA$ $(V,\Pair,m_1,m_2)$ (in both cases, $(V,\Pair)$ is an odd symplectic vector space).
Note that the perturbations $\hat{\OPQ}_{110}$, resp.~$\reallywidehat{\OPQ_{210}\circ_1\MC_{10}}$ are first order differential operators.

For $\BVOp$, we consider the associated Gerstenhaber bracket $\{\cdot,\cdot\}: \Fun(\CycB(V))^{\otimes 2} \rightarrow \Fun(\CycB(V))$, which is for all $\Psi_1$, $\Psi_2\in \Fun(\CycB(V))$ given by
$$ \{\Psi_1, \Psi_2\} := (-1)^{\Abs{\Psi_1}}\bigl(\BVOp(\Psi_1 \Psi_2)- \BVOp(\Psi_1)\Psi_2 - (-1)^{\Abs{\Psi_1}}\Psi_1\BVOp(\Psi_2)\bigr). $$
It is easy to see that
$$ \{\Psi_1,\Psi_2\} = (-1)^{1 + (\Abs{\Psi_1} + 1)(\Abs{\Psi_2}+1)}\{\Psi_2,\Psi_1\}. $$
If $\{\cdot,\cdot\}_0$ and $\{\cdot,\cdot\}^\MC$ are the Gerstenhaber brackets for $\BVOp_0$ and $\BVOp^\MC$, respectively, then it holds
$$ \{\cdot,\cdot\}_0 = \{\cdot,\cdot\}^\MC = \{\cdot,\cdot\} $$
because $\BVOp$, $\BVOp_0$ and $\BVOp^\MC$ differ only by differential operators of order $\le 1$.

Consider the cyclizations $m^+_1$, $m^+_2: \BCyc V \rightarrow \R$ defined for all $v_1$, $v_2$, $v_3 \in V[1]$ by
$$ m_1^+(v_1,v_2)\coloneqq \Pair(m_1(v_1),v_2)\quad\text{and}\quad m^+_2(v_1,v_2,v_3)\coloneqq \Pair(m_2(v_1,v_2),v_3). $$
They have degree $3-n$ as maps, thus degree $n-3$ as elements of $\DBCyc V$ with the cohomological grading, and thus $\Susp m^+_1$, $\Susp m^+_2\in \Fun(\CycB(V))$ have degree $2(n-3)$.
They are ``linear functions'' in the sense that $\Susp m^+_1$, $\Susp m^+_2 \in \hat{\Ext}_1\CycC(V)$.
We define the \emph{total action}
%\footnote{The sign $(-1)^{n-2}$ is added because of \eqref{Eq:TerribleComputationProblem}.}
\begin{equation}\label{Eq:Action}
 \Action \coloneqq \underbrace{(-1)^{n-2}(\Susp m_1^+)\hbar^{-1}}_{\displaystyle\eqqcolon \FreeAction} + \underbrace{(-1)^{n-2}(\Susp m_2^+)\hbar^{-1}}_{\displaystyle \eqqcolon \IntAction}\in \Fun(\CycB(V))
\end{equation}
and call $\FreeAction$ the \emph{free action} and $\IntAction$ the \emph{interaction.} The total action is linear and has degree $0$.
As a function, we can write
$$ S(\Susp b) = (-1)^{n-2}m_1^+(b) \hbar^{-1} + (-1)^{n-2} m_2^+(b) \hbar^{-1}\quad\text{for }b\in \BCyc V.$$
Recall that $\MC_{10} = (-1)^{n-2}\Susp m_2^+$ is the canonical Maurer-Cartan element.

\begin{Proposition}[$\BV$-action for canonical Maurer-Cartan element]\label{Prop:BVActForCanMC}
Let $(V,\Pair,m_1,m_2)$ be a cyclic $\DGA$ of degree $n$ of finite type, and let $\BVOp_0 = \hat{\OPQ}_{120} + \hbar \hat{\OPQ}_{210}$ be the string $\BV$-operator on $\Fun(\CycB(V))$.
The total action $S\in \Fun(\CycB(V))$ from \eqref{Eq:Action} satisfies the \emph{quantum master equation}
\begin{equation}\label{Eq:QME}
 \BVOp_0 S + \frac{1}{2}\{S,S\}_0 = 0,
\end{equation}
and it holds
\begin{equation}\label{Eq:Twist}
 \BVOp^\MC(f)= \BVOp_0(f) + \{S,f\}_0\quad\text{for all }f\in \Fun(\CycC(V)),
\end{equation}
where $\BVOp^\MC = \hat{\OPQ}_{110}^\MC + \hat{\OPQ}_{120} + \hbar \hat{\OPQ}_{210}$ is the $\BV$-operator associated to the twisted $\dIBL$-algebra $\dIBL^\MC(\CycC(V))$.
\end{Proposition}

\begin{proof}
Let $f\in \Fun(\CycB(V))$, and consider the left multiplication $L_f: \Fun(\CycB(V)) \rightarrow \Fun(\CycB(V))$ given by  $g\mapsto fg$.
If we view $f$ as a linear map $\Fun(\CycB(V)) \rightarrow \Fun(\CycB(V))$ which maps the constant $1$ to $f$ and vanishes on the reduced part, then we can write $L_f  = f\odot \Id$, where~$\odot$ is the convolution product on the symmetric algebra (see Appendix~\ref{App:IBLMV}
).
Using formulas from Proposition~\ref{Prop:PartCompositions}, we compute
\begin{align*}
\hat{\OPQ}_{210} \circ L_f &= \hat{\OPQ}_{210}(f\odot \Id) \\
&= \OPQ_{210}\circ_{0,2}(f,\Id) + \OPQ_{210}\circ_{1,1}(f,\Id) + \OPQ_{210}\circ_{2,0}(f,\Id) \\
&=(-1)^{\Abs{f}} L_f \circ \hat{\OPQ}_{210} + \reallywidehat{\OPQ_{210}\circ_1 f} + L_{\hat{\OPQ}_{210}(f)}.
\end{align*}
Therefore, it holds
\begin{align*}
 \{f,\cdot\}_0 & = \hbar\bigl(\hat{\OPQ}_{210} \circ L_f - L_{\hat{\OPQ}_{210}(f)} - (-1)^{\Abs{f}} L_f \circ \hat{\OPQ}_{210}\bigr)  \\
 & =  \hbar\reallywidehat{\OPQ_{210}\circ_1 f}.
\end{align*}
We compute
\begin{align}\label{Eq:TerribleComputationProblem}
&\bigl(\OPQ_{210}\circ_1 (\Susp m_1^+)\bigr)(\Susp\psi)(\omega) \nonumber\\
&\qquad= \OPQ_{210}(\Susp m_1^+, \Susp \psi)(\omega) \nonumber\\
&\qquad= (-1)^{\Abs{\Susp}} \OPQ_{210}(\Susp^2 m_1^+, \psi) \nonumber\\
&\qquad \underset{\mathclap{\substack{\uparrow\rule{0pt}{1.5ex} \\ T^{ij} = (-1)^{\Abs{s} + \Abs{e_i}\Abs{e_j}} T^{ji} \\
T^{ji} = (-1)^{\Abs{e_j}}\Pair(e^j,e^i) \\
\Pair(e^j,e^i)\neq 0\ \Implies\ \Abs{e_j} + \Abs{e_i} = \Abs{s} + 1}}}{=}
(-1)^{\Abs{\Susp}} \sum \varepsilon(\omega\to\omega^1\omega^2)(-1)^{\Abs{e_j}\Abs{\omega^1}}T^{ij} m_1^+(e_i \omega^1)\psi(e_j\omega^2)\nonumber\\
&\qquad \underset{\mathclap{\substack{\uparrow\rule{0pt}{1.5ex} \\ \sum_i \Pair(v,e^i)e_i = v\\
m_1^+(e^j \omega^1) = (-1)^{\Abs{e^j}\Abs{\omega^1}}m_1^+(\omega^1 e^j) \\
}}}{=} \sum \varepsilon(\omega\to\omega^1\omega^2)(-1)^{\Abs{e_j}(\Abs{\Susp}+1 + \Abs{\omega^1}) + \Abs{e^j}\Abs{\omega^1}} \Pair(m_1(\omega^1),e^j)\psi(e_j\omega^2) \nonumber\\
&\qquad\underset{\mathclap{\substack{\uparrow\rule{0pt}{1.5ex} \\ \hspace{1cm}\Pair(m_1(\omega^1),e^j)\neq 0\ \Implies\ 1 + \Abs{\omega^1} + \Abs{e^j} = \Abs{\Susp} + 1 \\
\Abs{e^j} + \Abs{e_j} = \Abs{\Susp} + 1
}}}{=} (-1)^{\Abs{\Susp} + 1} \sum \varepsilon(\omega^1 \omega^2) \psi(m_1(\omega^1)\omega^2) \nonumber\\
&\qquad = (-1)^{\Abs{\Susp} + 1} \sum_{i=1}^k (-1)^{\Abs{\omega_1} + \dotsb + \Abs{\omega_{i-1}}} \psi(\omega_1 \dotsb m_1(\omega_i) \dotsb \omega_k) \nonumber\\
&\qquad = (-1)^{\Abs{\Susp} + 1}\OPQ_{110}(\Susp \psi)(\Susp \omega).
\end{align}
Therefore, we have
\begin{equation}\label{Eq:FreeActionBracket}
 \{\FreeAction,\cdot\}_0 = \hat{\OPQ}_{110}.
\end{equation}
Since $m_1 \circ m_1 = 0$ and since $m_1^+$ is cyclically symmetric, it holds
\begin{equation*}
\{\FreeAction,\FreeAction\}_0 = (-1)^{n-2}\hbar^{-1}\OPQ_{110}(\Susp m_1^+) = 0.
\end{equation*}
Because $m_1^+ \in \DBCyc V$ has weight $2$, i.e., it vanishes on words of length $3$ and more, $\OPQ_{120}$ decreases the weight by $2$, and $\DBCyc V$ is reduced, i.e., its weight-$0$ part is $0$, we have
\begin{equation*}
\BVOp_0 \FreeAction = (-1)^{n-2}\OPQ_{120}(\Susp m_1^+) = 0.
\end{equation*}
We now compute
\begin{equation}\label{Eq:SSBracket}\begin{aligned}
\{\Action,\Action\}_0 &= \{\FreeAction,\FreeAction\}_0 + 2 \{\FreeAction,\IntAction\}_0 + \{\IntAction,\IntAction\}_0 \\
& = 2 \{\FreeAction,\IntAction\}_0 + \{\IntAction,\IntAction\}_0  \\
& = 2\hbar^{-1}\Bigl(\OPQ_{110}(\MC_{10}) + \frac{1}{2}\OPQ_{210}(\MC_{10},\MC_{10})\Bigr)
\end{aligned}\end{equation}
and
\begin{equation}\label{Eq:SBVOp}
 \BVOp_0 \Action = \hbar^{-1}\OPQ_{120}(\MC_{10}).
\end{equation}
The right-hand side of \eqref{Eq:SSBracket} vanishes due to \cite[Proposition~12.3]{Cieliebak2015}, and the right-hand side of \eqref{Eq:SBVOp} vanishes by the discussion preceding \cite[Proposition 12.5]{Cieliebak2015} (for degree reasons). Therefore, $\Action$ satisfies the quantum master equation \eqref{Eq:QME}.
The twisting equation~\eqref{Eq:Twist} is also clear.
\end{proof}

The inclusion of $\hbar^{-1}$ into $S$ is the convention from \cite{Cieliebak2015}.
After the transformation $\BVOp_0 \to \BVOp_0' = \BVOp_0$, $\Action\to\Action' = \hbar \Action$, we get the well-known equations
\begin{equation*}
 \hbar \BVOp_0' \Action' + \frac{1}{2} \{\Action',\Action'\}_0' = 0\quad\text{and}\quad \hbar {\BVOp'}^\MC= \hbar \BVOp_0' + \{\Action',\cdot\}_0'.
\end{equation*}

\begin{Proposition}[$\BV$-action for general Maurer-Cartan element]\label{Prop:BVActForAnyMCElement}
Let $(V,\Pair,m_1,m_2)$ be a cyclic $\DGA$ of degree $n$ of finite type, and let $\BVOp_0 = \hat{\OPQ}_{120} + \hbar \hat{\OPQ}_{210}$ be the string $\BV$-operator on $\Fun(\CycB(V))$.
Let $\MC_{lg}\in \hat{\Ext}_l \CycC(V)$ for all $l$, $g\ge 0$ satisfy the degree and filtration degree conditions of a Maurer-Cartan element for an $\IBLInfty$-algebra of bidegree $(n-3,2)$.%(see Definition~\ref{} for the original and Proposition~\ref{} for the filtered $\MV$-version).
Then $\MC = (\MC_{lg})$ satisfies the Maurer-Cartan equation for $\dIBL(\CycC(V))$ if and only if the total action
\begin{equation}\label{Eq:MyAction}
 \Action := \FreeAction + \sum_{l,g\ge 0} \MC_{lg} \hbar^{g-1}  \in \Fun(\CycB(V))
\end{equation}
satisfies the quantum master equation \eqref{Eq:QME}.
The $\BVInfty$-operator $\BVOp^\MC$ of the twisted $\IBLInfty$-algebra $\dIBL^\MC(\CycC(V))$ is given by \eqref{Eq:Twist}.
The elements $\MC_{0g}$ appear neither in \eqref{Eq:QME} nor in~\eqref{Eq:Twist}.
\end{Proposition}
\begin{proof}
Using $\BVOp_0 \FreeAction = \{\FreeAction,\FreeAction\}_0 = 0$, we compute
\begin{align*}
\BVOp_0 \Action + \frac{1}{2}\{\Action,\Action\}_0 &= \BVOp_0 \IntAction + \{\FreeAction,\IntAction\}_0 + \frac{1}{2}\{\IntAction,\IntAction\}_0 \\
& = \begin{multlined}[t]\sum_{l,g\ge 0}\bigl(\hat{\OPQ}_{120}(\MC_{lg})\hbar^{g-1} + \hat{\OPQ}_{210}(\MC_{lg})\hbar^g + \hat{\OPQ}_{110}(\MC_{lg})\hbar^{g-1}\bigr) \\
{}+ \frac{1}{2} \sum_{l_1,l_2,g_1,g_2\ge 0} \reallywidehat{\OPQ_{210}\circ_1\MC_{l_1 g_1}}(\MC_{l_2 g_2})\hbar^{g_1 + g_2 - 1}\end{multlined}\\
& = \begin{multlined}[t]\sum_{l,g\ge 0} (\iota_l \pi_l)\Bigl(\OPQ_{120}\circ_1 \MC_{l-1, g} + \OPQ_{210}\circ_2\MC_{l+1,g-1} + \OPQ_{110}\circ_1\MC_{lg} \\
{}+ \frac{1}{2} \sum_{\substack{l_1,l_2,g_1,g_2\ge 0 \\
l_1 + l_2 - 1 = l\\
g_1 + g_2 = g}} \OPQ_{210}\circ_{1,1}(\MC_{l_1 g_1},\MC_{l_2 g_2})\Bigr)\hbar^{g-1}.\end{multlined}
\end{align*}
Comparing to Proposition~\ref{Prop:dIBL}, we see that the $(l,g)$-components for $l\ge 1$, $g\ge 0$ give precisely the Maurer-Cartan equation in $\dIBL(\CycC(V))$.
We compute
\begin{align*}
\BVOp_0 + \{S,\cdot\}_0 &= \hat{\OPQ}_{120} + \hbar\hat{\OPQ}_{210} + \hat{\OPQ}_{110} + \sum_{l,g\ge 0}\reallywidehat{\OPQ_{210}\circ_1 \MC_{lg}} \hbar^g \\
&=\begin{aligned}[t]
&(\hat{\OPQ}_{110} + \reallywidehat{\OPQ_{210}\circ_1 \MC_{10}}) + (\hat{\OPQ}_{120} + \reallywidehat{\OPQ_{210}\circ_1 \MC_{20}}) + (\reallywidehat{\OPQ_{210}\circ_1 \MC_{30}}) + \dotsb \\
&{}+\bigl[(\hat{\OPQ}_{210}) + (\reallywidehat{\OPQ_{210}\circ_1 \MC_{11}}) + (\reallywidehat{\OPQ_{210}\circ_1 \MC_{21}})+\dotsb\bigr]\hbar\\
&{}+\sum_{l\ge 0, g\ge 2} (\reallywidehat{\OPQ_{210}\circ_1 \MC_{lg}})\hbar^g
\end{aligned} \\
&=\begin{aligned}[t]&(\hat{\OPQ}_{110}^\MC) + (\hat{\OPQ}_{120}^\MC) + (\hat{\OPQ}_{130}^\MC) + \dotsb \\
&{}+\bigl[(\hat{\OPQ}_{210}^\MC) + (\hat{\OPQ}_{111}^\MC) + (\hat{\OPQ}_{121}^\MC) + \dotsb\bigr]\hbar \\
&{}+\sum_{\substack{l\ge 0, g\ge 2}}(\hat{\OPQ}_{1lg}^\MC) \hbar^g
\end{aligned}
\end{align*}
and see that this is indeed the $\BVInfty$-operator $\BVOp^\MC$ of $\dIBL^\MC(\CycC(V))$.
\end{proof}
\end{document}


\documentclass[a4paper,pdftex]{article}

\usepackage{array}
%\usepackage{mathtools}
\usepackage{hopsantut}
\usepackage{listings}
\usepackage{todonotes}
\usepackage[fleqn]{amsmath}
\usepackage{tikz}

\hypersetup{pdfauthor={Robert Braun and Peter Nordin}, pdftitle={Hopsan Tutorial - Writing Advanced Components}, pdfsubject={Hopsan Tutorial}}

\lstset{ %
  numbers			=	left,
  numberstyle		=	\scriptsize, % the style that is used for the line-numbers
  backgroundcolor	=\color{yellow!10}
}

\begin{document}
\maketitle{Writing Advanced Components}

\section*{Introduction}
This tutorial is a continuation of the \textit{Writing Component Libraries} tutorial. It explains how to write more advanced components based on acausal equations and physical connections. It also covers how to re-write the equations for the impedance variables, which are a consequence of the transmission line element method.

Two components are explained; a variable pump component with linear equations, and a translational mass component with second order dynamics.

\section*{Requirements}
It is necessary to know how to write and compile components for Hopsan, either using HoLC or a third-party tool. This is covered by the \textit{Writing Component Libraries} tutorial.

\section*{Hydraulic Pump}
A hydraulic pump is a component that transforms an angular velocity on a shaft into hydraulic flow. In this case we will use a simple model with no dynamics, where the angular velocity is assumed to be constant at all time. This is similar to the Q-Type Variable Displacement Pump component in the Hopsan default library.

The component is shown in the figure below. It consists of two hydraulic ports for inlet and outlet, respectively. It also has four input variables; displacement ($D$), displacement setting ($\varepsilon$), angular velocity ($\omega$) and leakage coefficient ($c_{leak}$). All of these

\begin{tikzpicture}
\node[] () {\includegraphics{gfx/writingadvancedcomponents/variablepump.pdf}};
\node[yshift=5pt] () {$D$};
\node[yshift=-20pt, xshift=3pt] () {$C_{leak}$};
\node[yshift=33pt, xshift=40pt] () {$\varepsilon$};
\node[yshift=50pt, xshift=1pt] () {$n$};
\node[yshift=-7pt, xshift=-60pt] () {$p_{1}$};
\node[yshift=-7pt, xshift=60pt] () {$p_{2}$};
\node[xshift=36pt] () {$q$};
\draw[very thick, ->] (25pt,-7pt) -> (44pt,-7pt);
\end{tikzpicture}

\subsection*{Equations}
The flow from a hydraulic pump can be modelled with the following equations:

\begin{equation*}
\begin{cases}
q - q_{leak} = \varepsilon D \omega/2\pi \\
q_{leak} = C_{leak}\Delta p
\end{cases}
\end{equation*}

\noindent Here $q$ is the generated flow and $q_{leak}$ the leakage flow. $\Delta p$ is the pressure difference over the pump. In Hopsan we will have one flow and pressure at each port. Thus, we need to introduce the variables $p_{1}$ and $q_{1}$ for the inlet port, and $p_{2}$ and $q_{2}$ for the outlet. Flow is always defined as positive outwards from Q-type components. Therefore, the inlet flow will be the same as the outlet flow but negative. The equations now become:

\begin{equation*}
\begin{cases}
q_{2} - C_{leak}(p_{1}-p_{2}) = \varepsilon D \omega/2\pi \\
q_{1} = -q_{2}
\end{cases}
\end{equation*}

\noindent However, Hopsan uses the transmission line element method. For this reason we will not get the pressure variables as explicit input variables. Instead, we get a \textit{wave variable} and an \textit{impedance}. The TLM equations are then used to calculate the pressures from the flow variables, according to the two new equations below:

\begin{equation*}
\begin{cases}
q_{2} - C_{leak}(p_{1}-p_{2}) = \varepsilon D \omega/2\pi \\
q_{1} = -q_{2}\\
p_{1} = c_{1} + q_{1}Z_{c,1}\\
p_{2} = c_{2} + q_{2}Z_{c,2}
\end{cases}
\end{equation*}

\noindent It is now possible to rearrange the equations so that the can be solved analytically. First we replace the pressure variables in the first equation with the TLM equations:

\begin{equation*}
\begin{cases}
q_{2} - C_{leak}(c_{1} - q_{2}Z_{c,1}-c_{2} - q_{2}Z_{c,2}) = \varepsilon D \omega/2\pi \\
q_{1} = -q_{2}\\
p_{1} = c_{1} + q_{1}Z_{c,1}\\
p_{2} = c_{2} + q_{2}Z_{c,2}
\end{cases}
\end{equation*}

\noindent Finally, we rearrange the first equation to break out the flow variable:

\begin{equation*}
\begin{cases}
q_{2} = (\varepsilon D \omega/2\pi - C_{leak}(c_{1} -c_{2})) / (1-C_{leak}(Z_{c,1}-Z_{c,2}))\\
q_{1} = -q_{2}\\
p_{1} = c_{1} + q_{1}Z_{c,1}\\
p_{2} = c_{2} + q_{2}Z_{c,2}
\end{cases}
\end{equation*}

\noindent We now have a linear equation system that can be solved step-by-step.

\subsection*{C++ Code}
First, we create the skeleton for the new component, as described in the previous tutorial. We need two hydraulic ports and four input variables ($\omega$, $D_{p}$, $C_{leak}$ and $\varepsilon$). The resulting code for the class members and the creator functions is shown below:

\noindent
\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
#include "ComponentEssentials.h"

namespace hopsan {

class HydraulicFixedDisplacementPump : public ComponentQ
{
private:
    double *mpND_p1, *mpND_q1, *mpND_c1, *mpND_Zc1;
    double *mpND_p2, *mpND_q2, *mpND_c2, *mpND_Zc2;
    double *mpW, *mpDp, *mpCleak, *mpEps;
    Port *mpP1, *mpP2;

public:
    static Component *Creator()
    {
        return new HydraulicFixedDisplacementPump();
    }
\end{lstlisting}
\end{minipage}

\noindent The only thing needed in the \texttt{configuration()} function is to create ports and input variables:

\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
void configure()
{
    mpP1 = addPowerPort("P1", "NodeHydraulic");
    mpP2 = addPowerPort("P2", "NodeHydraulic");

	addInputVariable("eps", "Displacement setting", "", 1.0, &mpEps);
    addInputVariable("w_p", "Angular Velocity", "rad/s", 250.0, &mpW);
    addInputVariable("D_p", "Displacement", "m^3/rev", 0.00005, &mpDp);
    addInputVariable("C_leak", "Leakage Coeff.", "(m^3/s)/Pa", 0.0, &mpCleak);
}
\end{lstlisting}
\end{minipage}

\noindent The \texttt{initialize()} function will only need the \texttt{getSafeDataNodePtr()} function calls:

\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
void initialize()
{
    mpND_p1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::Pressure);
    mpND_q1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::Flow);
    mpND_c1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WaveVariable);
    mpND_Zc1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CharImpedance);

    mpND_p2 = getSafeNodeDataPtr(mpP2, NodeHydraulic::Pressure);
    mpND_q2 = getSafeNodeDataPtr(mpP2, NodeHydraulic::Flow);
    mpND_c2 = getSafeNodeDataPtr(mpP2, NodeHydraulic::WaveVariable);
    mpND_Zc2 = getSafeNodeDataPtr(mpP2, NodeHydraulic::CharImpedance);
}
\end{lstlisting}
\end{minipage}

\noindent Now it is time for the interesting part, to write the actual equations in the \texttt{simulateOneTimestep()} function. The final code is presented below. Some of the steps below will already be done if you used HoLC to generate the code.

\begin{tutenumerate}
\tutitem{Create local variables}
We begin with creating local variables for the port variables (line 3-4 below).

\tutitem{Read input variables}
Assign all input variables them with their corresponding pointers (line 6-16).

\tutitem{Write the pump equations}
The equations must be converted to C++ syntax (line 18-22).

\tutitem{Check for cavitation}
In order to make the model physically correct, we must make sure that negative pressures are not allowed. For this we create a boolean variable for cavitation and assign it with false (line 25). Then we check if pressure $p_{1}$ or $p_{2}$ is smaller than zero. If they are, we set the cavitation boolean to true and assign $c_{1}$ and $Z_{c,1}$ with zero (line 26-37).

\tutitem{Handle the cavitation}
If the cavitation boolean is true, at least one of the pressures was negative. In this case we need to recalculate the flow and the pressure variables (line 39-46).

\tutitem{Write output variables}
Finally, the output variables must be written to the nodes (line 48-52).

\end{tutenumerate}

\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
void simulateOneTimestep()
{
    //Declare local variables
    double p1, q1, c1, Zc1, p2, q2, c2, Zc2, w, dp, Cleak, eps;

    //Read input variables
    w = (*mpW);
    dp = (*mpDp);
    Cleak = (*mpCleak);
    eps = (*mpEps);

    //Get variable values from nodes
    c1 = (*mpND_c1);
    Zc1 = (*mpND_Zc1);
    c2 = (*mpND_c2);
    Zc2 = (*mpND_Zc2);

    //Fixed Displacement Pump equations
    q2 = ( dp*eps*w/(2.0*pi) + Cleak*(c1-c2) ) / ( (Zc1+Zc2)*Cleak+1 );
    q1 = -q2;
    p1 = c1 + Zc1*q1;
    p2 = c2 + Zc2*q2;

    //Check for cavitation
    bool cav = false;
    if (p1 < 0.0)
    {
        c1 = 0.0;
        Zc1 = 0.0;
        cav = true;
    }
    if (p2 < 0.0)
    {
        c2 = 0.0;
        Zc2 = 0.0;
        cav = true;
    }

    //Handle cavitation
    if (cav)
    {
        q2 = ( dp*eps*w/(2.0*pi) + Cleak*(c1-c2) ) / ( (Zc1+Zc2)*Cleak+1 );
		q1 = -q2;
        p1 = c1 + Zc1 * q1;
        p2 = c2 + Zc2 * q2;
    }

    //Write new values to nodes
    (*mpND_p1) = p1;
    (*mpND_q1) = q1;
    (*mpND_p2) = p2;
    (*mpND_q2) = q2;
}
\end{lstlisting}
\end{minipage}

\vfill

\section*{Translational Mass}
This part of the tutorial will explain how to write a translational mass component with second order dynamics. It will contain a mass and a damping coefficient, as shown in the figure below. We leave out dry friction and spring coefficient for simplicity.

\begin{tikzpicture}
\node[] () {\includegraphics[width=6cm]{gfx/writingadvancedcomponents/mass.pdf}};
\node[yshift=-10pt, xshift=0pt] () {$M$};
\node[yshift=-3pt, xshift=-70pt] () {$F_{1}$};
\node[yshift=-3pt, xshift=70pt] () {$F_{2}$};
\node[yshift=36pt, xshift=55pt] () {$B$};
\end{tikzpicture}

\subsection*{Equations}

The fundamental equation in the component will be Newton's second law of motion:

\begin{equation*}
M\ddot{x} + B\dot{x} = \sum{F}
\end{equation*}

\noindent The Hopsan component will have two ports, which will be defined in opposite directions. It is also necessary to provide equivalent mass variables, which are required by some other components in Hopsan:

\begin{equation*}
\begin{cases}
M\ddot{x_{2}} + B\dot{x_{2}} = F_{1} - F_{2}\\
x_{1} = -x_{2} \\
\dot{x}_{1} = -\dot{x}_{2} \\
m_{e,1} = M \\
m_{e,2} = M
\end{cases}
\end{equation*}

\noindent Finally, we must add the TLM equations in order to calculate the force from the wave variables and impedances:

\begin{equation*}
\begin{cases}
M\ddot{x_{2}} + B\dot{x_{2}} = F_{1} - F_{2}\\
x_{1} = -x_{2} \\
\dot{x}_{1} = -\dot{x}_{2} \\
m_{e,1} = M \\
m_{e,2} = M \\
F_{1} = c_{1} + Z_{c,1}\dot{x}_{1} \\
F_{2} = c_{2} + Z_{c,2}\dot{x}_{2}
\end{cases}
\end{equation*}

\noindent The equations of the mass is more complicated than the ones for the pump, since it contains time derivatives ($\ddot{x}$ and $\dot{x}$). Hopsan uses bilinear transforms to solve such equations. In order to use these, we must convert the first equation into a Laplace transform. We use a first order transform to calculate the velocity. Then the position can be obtained by integrating the velocity. By adding the impedance directly to the damping, we can use the wave variables as the external force. In this way we can calculate $x$ and $v$ without first calculating the forces.

\begin{equation*}
\begin{cases}
v_{2} = \dfrac{1}{M s + B}(F_{1}-F_{2}) = \dfrac{1}{M s + (B+Z_{c,1}+Z_{c,2})}(c_{1}-c_{2}) \\
\dot{x}_{2} = v_{2} \\
v_{1} = -v_{2} \\
x_{1} = -x_{2} \\
F_{1} = c_{1} + Z_{c,1}v_{1} \\
F_{2} = c_{2} + Z_{c,2}v_{2}
\end{cases}
\end{equation*}

\subsection*{C++ Code}
As with the previous component, we begin by creating a code skeleton. We want two mechanical ports, a constant parameter for the mass and input variables for damping and minimum and maximum position. Note that we also need to include the file \texttt{ComponentUtilities.h}, which contain classes for the transfer function and the integration.

\noindent
\begin{minipage}{\linewidth}
\begin{lstlisting}[language=c++, basicstyle=\footnotesize\ttfamily]
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"

namespace hopsan {

class MechanicTranslationalMass : public ComponentQ
{
private:
    Port *mpP1, *mpP2;
    double *mpP1_f, *mpP1_x, *mpP1_v, *mpP1_c, *mpP1_Zc, *mpP1_me;
    double *mpP2_f, *mpP2_x, *mpP2_v, *mpP2_c, *mpP2_Zc, *mpP2_me;
    double *mpB, *mpXMin, *mpXMax;
    double mMass;

    FirstOrderTransferFunction mTF;
    Integrator mIntegrator;
    double mNum[2], mDen[2];

public:
    static Component *Creator()
    {
        return new MechanicTranslationalMass();
    }
\end{lstlisting}
\end{minipage}

\noindent There is nothing special with the \texttt{configure()} function. All we need to do here is to create the ports, the constant and the input variables.

\noindent
\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
void configure()
{
    mpP1 = addPowerPort("P1", "NodeMechanic");
    mpP2 = addPowerPort("P2", "NodeMechanic");

    addConstant("m",          "Mass",               "kg",   100.0, mMass);

    addInputVariable("B",     "Viscous Friction",   "Ns/m", 10.0,  &mpB);
    addInputVariable("x_min", "Minimum Position",   "m",    0.0,   &mpXMin);
    addInputVariable("x_max", "Maximum Position",   "m",    1.0,   &mpXMax);
}
\end{lstlisting}
\end{minipage}

\noindent The \texttt{initialize()} function is a little more advanced than for the pump. We need to initialize the transfer function and the integrator with start values for $f$, $v$ and $x$. We also need to define the coefficients for the transfer function. This is done with two arrays called \texttt{mDen} and \texttt{mNum}, according to this:\\

$\dfrac{mNum[1] s + mNum[0]}{mDen[1] s + mNum[0]}$\\

\noindent Finally, we also need to initialize the equivalent mass variables in the nodes.

\noindent
\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
void initialize()
{
    mpP1_f = getSafeNodeDataPtr(mpP1, NodeMechanic::Force);
    mpP1_x = getSafeNodeDataPtr(mpP1, NodeMechanic::Position);
    mpP1_v = getSafeNodeDataPtr(mpP1, NodeMechanic::Velocity);
    mpP1_c = getSafeNodeDataPtr(mpP1, NodeMechanic::WaveVariable);
    mpP1_Zc = getSafeNodeDataPtr(mpP1, NodeMechanic::CharImpedance);
    mpP1_me = getSafeNodeDataPtr(mpP1, NodeMechanic::EquivalentMass);

    mpP2_f = getSafeNodeDataPtr(mpP2, NodeMechanic::Force);
    mpP2_x = getSafeNodeDataPtr(mpP2, NodeMechanic::Position);
    mpP2_v = getSafeNodeDataPtr(mpP2, NodeMechanic::Velocity);
    mpP2_c = getSafeNodeDataPtr(mpP2, NodeMechanic::WaveVariable);
    mpP2_Zc = getSafeNodeDataPtr(mpP2, NodeMechanic::CharImpedance);
    mpP2_me = getSafeNodeDataPtr(mpP2, NodeMechanic::EquivalentMass);

    //Read node variables
    double f1, f2, x2, v2;
    f1 = (*mpP1_f);
    f2 = (*mpP2_f);
    x2 = (*mpP2_x);
    v2 = (*mpP2_v);

    //Initialization code
    mNum[0] = 1.0;
    mNum[1] = 0.0;
    mDen[0] = (*mpB);
    mDen[1] = mMass;

    mTF.initialize(mTimestep, mNum, mDen, f1-f2, v2);
    mIntegrator.initialize(mTimestep, x2, v2);

    //Write values to nodes
    (*mpP1_me) = mMass;
    (*mpP2_me) = mMass;
}
\end{lstlisting}
\end{minipage}

\noindent Last but not least, we need to write the \texttt{simulateOneTimeStep()} function. This is explained step-by-step:
\begin{tutenumerate}
\tutitem{Define local variables}
Define local variables for input variables and node values (line 3-4)
\tutitem{Read from input variables}
Assign input variables to local variables (line 6-9)
\tutitem{Read from nodes}
Assign node variables to local variables (line 11-15)
\tutitem{Update the damping coefficient}
Update the coefficient in the transfer function by adding the impedance variables to the damping factor (line 17-19)
\tutitem{Calculate velocity}
Use the transfer function to calculate $v_{2}$ from $c_{1}-c_{2}$ (line 21-22)
\tutitem{Calculate position}
Use the integrator to calculate $x_{2}$ as a function of $v_{2}$ (line 24-25)
\tutitem{Handle limitations}
Reset variables and re-initialize the transfer function and the integrator if $x_{2}$ is outside limits (line 27-41)
\tutitem{Calculate the remaining variables}
Calulate velocity and position for node 1 ($v_{1}$, $x_{1}$), and then calculate, $F_{1}$ and $F_{2}$ using the TLM equations (line 43-47)
\tutitem{Write values to the nodes}
Write back the values of the local variables to the node variables (line 49-57)
\end{tutenumerate}

\noindent
\begin{minipage}{\linewidth}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
void simulateOneTimestep()
{
    //Declare local variables
    double f1, x1, v1, c1, Zc1, f2, x2, v2, c2, Zc2, B, xmin, xmax;

    //Read input variables
    B = (*mpB);
    xmin = (*mpXMin);
    xmax = (*mpXMax);

    //Get variable values from nodes
    c1 = (*mpP1_c);
    Zc1 = (*mpP1_Zc);
    c2 = (*mpP2_c);
    Zc2 = (*mpP2_Zc);

    //Mass equations
    mDen[0] = B+Zc1+Zc2;
    mTF.setDen(mDen);

    //Calculate velocity
    v2 = mTF.update(c1-c2);

    //Calculate position
    x2 = mIntegrator.update(v2);

    //Handle position limits
    if(x2<xmin)
    {
        x2=xmin;
        v2=0.0;
        mTF.initializeValues(c1-c2, v2);
        mIntegrator.initializeValues(v2, xmin);
    }
    if(x2>xmax)
    {
        x2=xmax;
        v2=0.0;
        mTF.initializeValues(c1-c2, v2);
        mIntegrator.initializeValues(v2, xmax);
    }

    //Calculate remainig varaibles
    v1 = -v2;
    x1 = -x2;
    f1 = c1 + Zc1*v1;
    f2 = c2 + Zc2*v2;

    //Write new values to nodes
    (*mpP1_f) = f1;
    (*mpP1_x) = x1;
    (*mpP1_v) = v1;
    (*mpP2_f) = f2;
    (*mpP2_x) = x2;
    (*mpP2_v) = v2;
    (*mpP1_me) = mMass;
    (*mpP2_me) = mMass;
}
\end{lstlisting}
\end{minipage}

\end{document}


\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage{amsmath}%
\usepackage{hyperref}%
%
\title{2020 AIME II Problems}%
\author{MAA}%
\date{\today}%
%
\begin{document}%
\normalsize%
\maketitle%
\section{Acknowledgement}%
\label{sec:Acknowledgement}%
All the following problems are copyrighted by the \href{https://www.maa.org/}{Mathematical Association of America}'s \href{https://www.maa.org/math-competitions}{American Mathematics Competitions}.

%
\section{Problems}%
\label{sec:Problems}%
\begin{enumerate}%
\item%
[\textbf{Problem 1}]Find the number of ordered pairs of positive integers $(m,n)$ such that ${m^2n = 20 ^{20}}$.
%
\item%
[\textbf{Problem 2}]Let $P$ be a point chosen uniformly at random in the interior of the unit square with vertices at $(0,0), (1,0), (1,1)$, and $(0,1)$. The probability that the slope of the line determined by $P$ and the point $\left(\frac58, \frac38 \right)$ is greater than $\frac12$ can be written as $\frac{m}{n}$, where $m$ and $n$ are relatively prime positive integers. Find $m+n$.
%
\item%
[\textbf{Problem 3}]The value of $x$ that satisfies $\log_{2^x} 3^{20} = \log_{2^{x+3}} 3^{2020}$ can be written as $\frac{m}{n}$, where $m$ and $n$ are relatively prime positive integers. Find $m+n$.
%
\item%
[\textbf{Problem 4}]Triangles $\triangle ABC$ and $\triangle A'B'C'$ lie in the coordinate plane with vertices $A(0,0)$, $B(0,12)$, $C(16,0)$, $A'(24,18)$, $B'(36,18)$, $C'(24,2)$. A rotation of $m$ degrees clockwise around the point $(x,y)$ where $0<m<180$, will transform $\triangle ABC$ to $\triangle A'B'C'$. Find $m+x+y$.
%
\item%
[\textbf{Problem 5}]For each positive integer $n$, let $f(n)$ be the sum of the digits in the base-four representation of $n$ and let $g(n)$ be the sum of the digits in the base-eight representation of $f(n)$. For example, $f(2020) = f(133210_{\text{four}}) = 10 = 12_{\text{eight}}$, and $g(2020) = \text{the digit sum of }12_{\text{eight}} = 3$. Let $N$ be the least value of $n$ such that the base-sixteen representation of $g(n)$ cannot be expressed using only the digits $0$ through $9$. Find the remainder when $N$ is divided by $1000$.
%
\item%
[\textbf{Problem 6}]Define a sequence recursively by $t_1 = 20$, $t_2 = 21$, and\[t_n = \frac{5t_{n-1}+1}{25t_{n-2}}\]for all $n \ge 3$. Then $t_{2020}$ can be written as $\frac{p}{q}$, where $p$ and $q$ are relatively prime positive integers. Find $p+q$.
%
\item%
[\textbf{Problem 7}]Two congruent right circular cones each with base radius $3$ and height $8$ have the axes of symmetry that intersect at right angles at a point in the interior of the cones a distance $3$ from the base of each cone. A sphere with radius $r$ lies withing both cones. The maximum possible value of $r^2$ is $\frac{m}{n}$, where $m$ and $n$ are relatively prime positive integers. Find $m+n$.
%
\item%
[\textbf{Problem 8}]Define a sequence recursively by $f_1(x)=|x-1|$ and $f_n(x)=f_{n-1}(|x-n|)$ for integers $n>1$. Find the least value of $n$ such that the sum of the zeros of $f_n$ exceeds $500,000$.
%
\item%
[\textbf{Problem 9}]While watching a show, Ayako, Billy, Carlos, Dahlia, Ehuang, and Frank sat in that order in a row of six chairs. During the break, they went to the kitchen for a snack. When they came back, they sat on those six chairs in such a way that if two of them sat next to each other before the break, then they did not sit next to each other after the break. Find the number of possible seating orders they could have chosen after the break.
%
\item%
[\textbf{Problem 10}]Find the sum of all positive integers $n$ such that when $1^3+2^3+3^3+\cdots +n^3$ is divided by $n+5$, the remainder is $17$.
%
\item%
[\textbf{Problem 11}]Let $P(x) = x^2 - 3x - 7$, and let $Q(x)$ and $R(x)$ be two quadratic polynomials also with the coefficient of $x^2$ equal to $1$. David computes each of the three sums $P + Q$, $P + R$, and $Q + R$ and is surprised to find that each pair of these sums has a common root, and these three common roots are distinct. If $Q(0) = 2$, then $R(0) = \frac{m}{n}$, where $m$ and $n$ are relatively prime positive integers. Find $m + n$.
%
\item%
[\textbf{Problem 12}]Let $m$ and $n$ be odd integers greater than $1.$ An $m\times n$ rectangle is made up of unit squares where the squares in the top row are numbered left to right with the integers $1$ through $n$, those in the second row are numbered left to right with the integers $n + 1$ through $2n$, and so on. Square $200$ is in the top row, and square $2000$ is in the bottom row. Find the number of ordered pairs $(m,n)$ of odd integers greater than $1$ with the property that, in the $m\times n$ rectangle, the line through the centers of squares $200$ and $2000$ intersects the interior of square $1099$.
%
\item%
[\textbf{Problem 13}]Convex pentagon $ABCDE$ has side lengths $AB=5$, $BC=CD=DE=6$, and $EA=7$. Moreover, the pentagon has an inscribed circle (a circle tangent to each side of the pentagon). Find the area of $ABCDE$.
%
\item%
[\textbf{Problem 14}]For real number $x$ let $\lfloor x\rfloor$ be the greatest integer less than or equal to $x$, and define $\{x\} = x - \lfloor x \rfloor$ to be the fractional part of $x$. For example, $\{3\} = 0$ and $\{4.56\} = 0.56$. Define $f(x)=x\{x\}$, and let $N$ be the number of real-valued solutions to the equation $f(f(f(x)))=17$ for $0\leq x\leq 2020$. Find the remainder when $N$ is divided by $1000$.
%
\item%
[\textbf{Problem 15}]Let $\triangle ABC$ be an acute scalene triangle with circumcircle $\omega$. The tangents to $\omega$ at $B$ and $C$ intersect at $T$. Let $X$ and $Y$ be the projections of $T$ onto lines $AB$ and $AC$, respectively. Suppose $BT = CT = 16$, $BC = 22$, and $TX^2 + TY^2 + XY^2 = 1143$. Find $XY^2$.
%
\end{enumerate}

%
\end{document}


\chapter{Convergence of funcoids}

\section{Convergence}

The following generalizes the well-known notion of a filter convergent
to a point or to a set:
\begin{defn}
\index{converges!regarding funcoid}A filter $\mathcal{F}\in\mathscr{F}(\Dst\mu)$
\emph{converges} to a filter $\mathcal{A}\in\mathscr{F}(\Src\mu)$
regarding a funcoid $\mu$ ($\mathcal{F}\overset{\mu}{\rightarrow}\mathcal{A}$)
iff $\mathcal{F}\sqsubseteq\supfun{\mu}\mathcal{A}$.
\end{defn}

\begin{defn}
\index{converges!regarding funcoid}A funcoid $f$ \emph{converges}
to a filter $\mathcal{A}\in\mathscr{F}(\Src\mu)$ regarding a funcoid
$\mu$ where $\Dst f=\Dst\mu$ (denoted $f\overset{\mu}{\rightarrow}\mathcal{A}$)
iff $\im f\sqsubseteq\supfun{\mu}\mathcal{A}$ that is iff $\im f\overset{\mu}{\rightarrow}\mathcal{A}$.
\end{defn}

\begin{defn}
\index{converges!regarding funcoid}A funcoid $f$ \emph{converges}
to a filter $\mathcal{A}\in\mathscr{F}(\Src\mu)$ on a filter $\mathcal{B}\in\mathscr{F}(\Src f)$
regarding a funcoid $\mu$ where $\Dst f=\Dst\mu$ iff $f|_{\mathcal{B}}\overset{\mu}{\rightarrow}\mathcal{A}$.\end{defn}
\begin{obvious}
A funcoid $f$ converges to a filter
$\mathcal{A}\in\mathscr{F}(\Src\mu)$ on a filter
$\mathcal{B}\in\mathscr{F}(\Src f)$ regarding a funcoid $\mu$ iff
$\supfun{f}\mathcal{B}\sqsubseteq\supfun{\mu}\mathcal{A}$.
\end{obvious}

\begin{rem}
We can define also convergence for a reloid $f$: $f\overset{\mu}{\rightarrow}\mathcal{A}\Leftrightarrow\im f\sqsubseteq\supfun{\mu}\mathcal{A}$
or what is the same $f\overset{\mu}{\rightarrow}\mathcal{A}\Leftrightarrow\tofcd f\overset{\mu}{\rightarrow}\mathcal{A}$.\end{rem}
\begin{thm}
Let $f$, $g$ be funcoids, $\mu$, $\nu$ be endofuncoids, $\Dst f=\Src g=\Ob\mu$,
$\Dst g=\Ob\nu$, $\mathcal{A}\in\mathscr{F}(\Ob\mu)$. If $f\overset{\mu}{\rightarrow}\mathcal{A}$,
\[
g|_{\supfun{\mu}\mathcal{A}}\in\continuous(\mu\sqcap(\supfun{\mu}\mathcal{A}\times^{\mathsf{FCD}}\supfun{\mu}\mathcal{A}),\nu),
\]
and $\supfun{\mu}\mathcal{A}\sqsupseteq\mathcal{A}$, then $g\circ f\overset{\nu}{\rightarrow}\supfun g\mathcal{A}$.\end{thm}
\begin{proof}
~
\begin{gather*}
\im f\sqsubseteq\supfun{\mu}\mathcal{A};\\
\supfun g\im f\sqsubseteq\supfun g\supfun{\mu}\mathcal{A};\\
\im(g\circ f)\sqsubseteq\supfun{g|_{\supfun{\mu}\mathcal{A}}}\supfun{\mu}\mathcal{A};\\
\im(g\circ f)\sqsubseteq\supfun{g|_{\supfun{\mu}\mathcal{A}}}\supfun{\mu\sqcap(\supfun{\mu}\mathcal{A}\times^{\mathsf{FCD}}\supfun{\mu}\mathcal{A})}\mathcal{A};\\
\im(g\circ f)\sqsubseteq\supfun{g|_{\supfun{\mu}\mathcal{A}}\circ(\mu\sqcap(\supfun{\mu}\mathcal{A}\times^{\mathsf{FCD}}\supfun{\mu}\mathcal{A}))}\mathcal{A};\\
\im(g\circ f)\sqsubseteq\supfun{\nu\circ g|_{\supfun{\mu}\mathcal{A}}}\mathcal{A};\\
\im(g\circ f)\sqsubseteq\supfun{\nu\circ g}\mathcal{A};\\
g\circ f\overset{\nu}{\rightarrow}\supfun g\mathcal{A}.
\end{gather*}
\end{proof}
\begin{cor}
Let $f$, $g$ be funcoids, $\mu$, $\nu$ be endofuncoids, $\Dst f=\Src g=\Ob\mu$,
$\Dst g=\Ob\nu$, $\mathcal{A}\in\mathscr{F}(\Ob\mu)$. If $f\overset{\mu}{\rightarrow}\mathcal{A}$,
$g\in\continuous(\mu,\nu)$, and $\supfun{\mu}\mathcal{A}\sqsupseteq\mathcal{A}$
then $g\circ f\overset{\nu}{\rightarrow}\supfun g\mathcal{A}$.\end{cor}
\begin{proof}
From the last theorem and theorem \ref{rect-cont}.
\end{proof}

\section{Relationships between convergence and continuity}
\begin{lem}
Let $\mu$, $\nu$ be endofuncoids, $f\in\mathsf{FCD}(\Ob\mu,\Ob\nu)$,
$\mathcal{A}\in\mathscr{F}(\Ob\mu)$, $\Src f=\Ob\mu$, $\Dst f=\Ob\nu$.
If $f\in\continuous(\mu|_{\mathcal{A}},\nu)$ then
\[
f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}\Leftrightarrow\supfun{f\circ\mu|_{\mathcal{A}}}\mathcal{A}\sqsubseteq\supfun{\nu\circ f}\mathcal{A}.
\]
\end{lem}
\begin{proof}
~
\begin{multline*}
f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}\Leftrightarrow\im f|_{\supfun{\mu}\mathcal{A}}\sqsubseteq\supfun{\nu}\supfun f\mathcal{A}\Leftrightarrow\\
\supfun f\supfun{\mu}\mathcal{A}\sqsubseteq\supfun{\nu}\supfun f\mathcal{A}\Leftrightarrow\supfun{f\circ\mu}\mathcal{A}\sqsubseteq\supfun{\nu\circ f}\mathcal{A}\Leftrightarrow\supfun{f\circ\mu|_{\mathcal{A}}}\mathcal{A}\sqsubseteq\supfun{\nu\circ f}\mathcal{A}.
\end{multline*}
\end{proof}
\begin{thm}
Let $\mu$, $\nu$ be endofuncoids, $f\in\mathsf{FCD}(\Ob\mu,\Ob\nu)$,
$\mathcal{A}\in\mathscr{F}(\Ob\mu)$, $\Src f=\Ob\mu$, $\Dst f=\Ob\nu$.
If $f\in\continuous(\mu|_{\mathcal{A}},\nu)$ then $f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}$.\end{thm}
\begin{proof}
~
\begin{multline*}
f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}\Leftrightarrow\text{(by the lemma)}\Leftrightarrow\supfun{f\circ\mu|_{\mathcal{A}}}\mathcal{A}\sqsubseteq\supfun{\nu\circ f}\mathcal{A}\Leftarrow\\
f\circ\mu|_{\mathcal{A}}\sqsubseteq\nu\circ f\Leftrightarrow f\in\continuous(\mu|_{\mathcal{A}},\nu).
\end{multline*}
\end{proof}
\begin{cor}
Let $\mu$, $\nu$ be endofuncoids, $f\in\mathsf{FCD}(\Ob\mu,\Ob\nu)$,
$\mathcal{A}\in\mathscr{F}(\Ob\mu)$, $\Src f=\Ob\mu$, $\Dst f=\Ob\nu$.
If $f\in\continuous(\mu,\nu)$ then $f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}$.\end{cor}
\begin{thm}
Let $\mu$, $\nu$ be endofuncoids, $f\in\mathsf{FCD}(\Ob\mu,\Ob\nu)$,
$\mathcal{A}\in\mathscr{F}(\Ob\mu)$ be an ultrafilter, $\Src f=\Ob\mu$,
$\Dst f=\Ob\nu$. $f\in\continuous(\mu|_{\mathcal{A}},\nu)$ iff $f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}$.\end{thm}
\begin{proof}
~
\begin{multline*}
f|_{\supfun{\mu}\mathcal{A}}\overset{\nu}{\rightarrow}\supfun f\mathcal{A}\Leftrightarrow\text{(by the lemma)}\Leftrightarrow\supfun{f\circ\mu|_{\mathcal{A}}}\mathcal{A}\sqsubseteq\supfun{\nu\circ f}\mathcal{A}\Leftrightarrow\\
\text{(used the fact that \ensuremath{\mathcal{A}} is an ultrafilter)}\\
f\circ\mu|_{\mathcal{A}}\sqsubseteq\nu\circ f|_{\mathcal{A}}\Leftrightarrow f\circ\mu|_{\mathcal{A}}\sqsubseteq\nu\circ f\Leftrightarrow f\in\continuous(\mu|_{\mathcal{A}},\nu).
\end{multline*}

\end{proof}

\section{Convergence of join}

\begin{prop}
$\bigsqcup S\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow \forall\mathcal{F}\in S:\mathcal{F}\overset{\mu}{\rightarrow}\mathcal{A}$
for every collection~$S$ of filters on~$\Dst\mu$ and filter~$\mathcal{A}$ on~$\Src\mu$, for every funcoid~$\mu$.
\end{prop}

\begin{proof}
~
\[\bigsqcup S\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow \bigsqcup S\sqsubseteq\supfun{\mu}\mathcal{A} \Leftrightarrow
\forall\mathcal{F}\in S:\mathcal{F}\sqsubseteq\supfun{\mu}\mathcal{A} \Leftrightarrow \forall\mathcal{F}\in S:\mathcal{F}\overset{\mu}{\rightarrow}\mathcal{A}.\]
\end{proof}

\begin{cor}
$\bigsqcup F\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow \forall f\in F:f\overset{\mu}{\rightarrow}\mathcal{A}$
for every collection~$F$ of funcoids~$f$ such that $\Dst f=\Dst\mu$ and filter~$\mathcal{A}$ on~$\Src\mu$, for every funcoid~$\mu$.
\end{cor}

\begin{proof}
By corollary~\ref{fcd-dom-join} we have
\begin{multline*}
\bigsqcup F\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow \im\bigsqcup F\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow
\bigsqcup\rsupfun{\im}F\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow \\
\forall f\in\rsupfun{\im}F:\mathcal{F}\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow
\forall f\in F:\im f\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow
\forall f\in F:f\overset{\mu}{\rightarrow}\mathcal{A}.
\end{multline*}
\end{proof}

\begin{thm}
$f|_{\mathcal{B}_0\sqcup\mathcal{B}_1}\overset{\mu}{\rightarrow}\mathcal{A} \Leftrightarrow
f|_{\mathcal{B}_0}\overset{\mu}{\rightarrow}\mathcal{A} \land f|_{\mathcal{B}_1}\overset{\mu}{\rightarrow}\mathcal{A}$.
for all filters~$\mathcal{A}$, $\mathcal{B}_0$, $\mathcal{B}_1$ and funcoids~$\mu$, $f$ and~$g$ on suitable sets.
\end{thm}

\begin{proof}
As easily follows from distributivity of the lattices of funcoids we have
$f|_{\mathcal{B}_0\sqcup\mathcal{B}_1} = f|_{\mathcal{B}_0}\sqcup f|_{\mathcal{B}_1}$.
Thus our theorem follows from the previous corollary.
\end{proof}

\section{Limit}
\begin{defn}
\index{limit}$\lim^{\mu}f=a$ iff $f\overset{\mu}{\rightarrow}\uparrow^{\Src\mu}\{a\}$
for a $T_{2}$-separable funcoid $\mu$ and a non-empty funcoid $f$
such that $\Dst f=\Dst\mu$.
\end{defn}
It is defined correctly, that is $f$ has no more than one limit.
\begin{proof}
Let $\lim^{\mu}f=a$ and $\lim^{\mu}f=b$. Then $\im f\sqsubseteq\rsupfun{\mu}@\{a\}$
and $\im f\sqsubseteq\rsupfun{\mu}@\{b\}$.

Because $f\ne\bot^{\mathsf{FCD}(\Src f,\Dst f)}$ we have $\im f\ne\bot^{\mathscr{F}(\Dst f)}$;
$\rsupfun{\mu}@\{a\}\sqcap\rsupfun{\mu}@\{b\}\ne\bot^{\mathscr{F}(\Dst f)}$;
$\uparrow^{\Src\mu}\{b\}\sqcap\supfun{\mu^{-1}}\rsupfun{\mu}@\{a\}\ne\bot^{\mathscr{F}(\Src\mu)}$;
$\uparrow^{\Src\mu}\{b\}\sqcap\supfun{\mu^{-1}\circ\mu}@\{a\}\ne\bot^{\mathscr{F}(\Src\mu)}$;
$@\{a\}\suprel{\mu^{-1}\circ\mu}@\{b\}$.
Because $\mu$ is $T_{2}$-separable we have $a=b$.\end{proof}
\begin{defn}
$\lim_{\mathcal{B}}^{\mu}f=\lim^{\mu}(f|_{\mathcal{B}})$.\end{defn}
\begin{rem}
We can also in an obvious way define limit of a reloid.
\end{rem}

\section{Generalized limit}

\subsection{\index{limit!generalized}Definition}

Let $\mu$ and $\nu$ be endofuncoids. Let $G$ be a transitive permutation
group on $\Ob\mu$.

For an element $r\in G$ we will denote $\uparrow r=\uparrow^{\mathsf{FCD}(\Ob\mu,\Ob\mu)}r$.

We require that $\mu$ and every $r\in G$ commute, that is
\[
\mu\circ\uparrow r=\uparrow r\circ\mu.
\]

We require for every $y\in\Ob\nu$
\begin{equation}
\nu\sqsupseteq\rsupfun{\nu}@\{y\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}.\label{lim-squares}
\end{equation}

\begin{prop}
Formula (\ref{lim-squares}) follows from $\nu\sqsupseteq\nu\circ\nu^{-1}$.\end{prop}
\begin{proof}
Let $\nu\sqsupseteq\nu\circ\nu^{-1}$. Then
\begin{align*}
\rsupfun{\nu}@\{y\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & =\\
\supfun{\nu}@\{y\}\times^{\mathsf{FCD}}\supfun{\nu}@\{y\} & =\\
\nu\circ(\uparrow^{\Ob\nu}\{y\}\times^{\mathsf{FCD}}\uparrow^{\Ob\nu}\{y\})\circ\nu^{-1} & =\\
\nu\circ\uparrow^{\mathsf{FCD}(\Ob\nu,\Ob\nu)}(\{y\}\times\{y\})\circ\nu^{-1} & \sqsubseteq\\
\nu\circ1_{\Ob\nu}^{\mathsf{FCD}}\circ\nu^{-1} & =\\
\nu\circ\nu^{-1} & \sqsubseteq\nu.
\end{align*}
\end{proof}
\begin{rem}
The formula (\ref{lim-squares}) usually works if $\nu$ is a proximity.
It does not work if $\mu$ is a pretopology or preclosure.
\end{rem}
We are going to consider (generalized) limits of arbitrary functions
acting from $\Ob\mu$ to $\Ob\nu$. (The functions in consideration
are not required to be continuous.)
\begin{rem}
Most typically $G$ is the group of translations of some topological
vector space.
\end{rem}
\emph{Generalized limit} is defined by the following formula:
\begin{defn}
\index{limit!generalized}$\xlim f\eqdef\setcond{\nu\circ f\circ\uparrow r}{r\in G}$
for any funcoid $f$.\end{defn}
\begin{rem}
Generalized limit technically is a set of funcoids.
\end{rem}
We will assume that $\dom f\sqsupseteq\rsupfun{\mu}@\{x\}$.
\begin{defn}
$\xlim_{x}f=\xlim f|_{\rsupfun{\mu}@\{x\}}$.\end{defn}
\begin{obvious}
$\xlim_{x}f=\setcond{\nu\circ f|_{\rsupfun{\mu}@\{x\}}\circ\uparrow r}{r\in G}$.\end{obvious}
\begin{rem}
$\xlim_{x}f$ is the same for funcoids $\mu$ and $\Compl\mu$.
\end{rem}
The function $\tau$ will define an injection from the set of points
of the space $\nu$ (``numbers'', ``points'', or ``vectors'')
to the set of all (generalized) limits (i.e. values which $\xlim_{x}f$
may take).
\begin{defn}
$\tau(y)\eqdef\setcond{\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}}{x\in D}$.\end{defn}
\begin{prop}
$\tau(y)=\setcond{(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\})\circ\uparrow r}{r\in G}$
for every (fixed) $x\in D$.\end{prop}
\begin{proof}
~
\begin{align*}
(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\})\circ\uparrow r & =\\
\supfun{\uparrow r^{-1}}\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & =\\
\supfun{\mu}\rsupfun{\uparrow r^{-1}}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & =\\
\rsupfun{\mu}@\{r^{-1}x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & \in \setcond{\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}}{x\in D}.
\end{align*}

Reversely $\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}=(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\})\circ\uparrow e$
where $e$ is the identify element of $G$.\end{proof}
\begin{prop}
$\tau(y)=\xlim(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\uparrow^{\Base(\Ob\nu)}\{y\})$
(for every $x$). Informally: Every $\tau(y)$ is a generalized limit
of a constant funcoid.\end{prop}
\begin{proof}
~
\begin{align*}
\xlim(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\uparrow^{\Base(\Ob\nu)}\{y\}) & =\\
\setcond{\nu\circ(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\uparrow^{\Base(\Ob\nu)}\{y\})\circ\uparrow r}{r\in G} & =\\
\setcond{(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\})\circ\uparrow r}{r\in G} & =\tau(y).
\end{align*}
\end{proof}
\begin{thm}
If $f$ is a function and $f|_{\rsupfun{\mu}@\{x\}}\in\continuous(\mu,\nu)$
and $\rsupfun{\mu}@\{x\}\sqsupseteq\uparrow^{\Ob\mu}\{x\}$
then $\xlim_{x}f=\tau(fx)$.\end{thm}
\begin{proof}
$f|_{\rsupfun{\mu}@\{x\}}\circ\mu\sqsubseteq\nu\circ f|_{\rsupfun{\mu}@\{x\}}\sqsubseteq\nu\circ f$;
thus $\langle f\rangle\rsupfun{\mu}@\{x\}\sqsubseteq\supfun{\nu}\rsupfun{f}@\{x\}$;
consequently we have
\begin{gather*}
\nu\sqsupseteq\supfun{\nu}\rsupfun{f}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\}\sqsupseteq\supfun f\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\}.\\
\begin{aligned}\nu\circ f|_{\rsupfun{\mu}@\{x\}} & \sqsupseteq\\
(\supfun f\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\})\circ f|_{\rsupfun{\mu}@\{x\}} & =\\
(f|_{\rsupfun{\mu}\{x\}})^{-1}\supfun f\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\} & \sqsupseteq\\
\supfun{\id_{\dom f|_{\rsupfun{\mu}\{x\}}}^{\mathsf{FCD}}}\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\} & \sqsupseteq\\
\dom f|_{\rsupfun{\mu}@\{x\}}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\} & =\\
\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\}.
\end{aligned}
\end{gather*}

$\im(\nu\circ f|_{\rsupfun{\mu}@\{x\}})=\supfun{\nu}\rsupfun{f}@\{x\}$;
\begin{align*}
\nu\circ f|_{\rsupfun{\mu}@\{x\}} & \sqsubseteq\\
\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\im(\nu\circ f|_{\rsupfun{\mu}@\{x\}}) & =\\
\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\}.
\end{align*}
So $\nu\circ f|_{\rsupfun{\mu}@\{x\}}=\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\}$.

Thus $\xlim_{x}f=\setcond{(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{f}@\{x\})\circ\uparrow r}{r\in G}=\tau(fx)$.\end{proof}
\begin{rem}
Without the requirement of $\rsupfun{\mu}@\{x\}\sqsupseteq\uparrow^{\Ob\mu}\{x\}$
the last theorem would not work in the case of removable singularity.\end{rem}
\begin{thm}
Let $\nu\sqsubseteq\nu\circ\nu$. If $f|_{\rsupfun{\mu}@\{x\}}\overset{\nu}{\rightarrow}\uparrow^{\Ob\mu}\{y\}$
then $\xlim_{x}f=\tau(y)$.\end{thm}
\begin{proof}
$\im f|_{\rsupfun{\mu}@\{x\}}\sqsubseteq\rsupfun{\nu}@\{y\}$;
$\supfun f\rsupfun{\mu}@\{x\}\sqsubseteq\rsupfun{\nu}@\{y\}$;
\begin{align*}
\nu\circ f|_{\rsupfun{\mu}@\{x\}} & \sqsupseteq\\
(\rsupfun{\nu}@\{y\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\})\circ f|_{\rsupfun{\mu}@\{x\}} & =\\
\supfun{(f|_{\rsupfun{\mu}@\{x\}})^{-1}}\rsupfun{\nu}@\{y\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & =\\
\supfun{\id_{\rsupfun{\mu}\{x\}}^{\mathsf{FCD}}\circ f^{-1}}\rsupfun{\nu}@\{y\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & \sqsupseteq\\
\supfun{\id_{\rsupfun{\mu}\{x\}}^{\mathsf{FCD}}\circ f^{-1}}\supfun f\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & =\\
\supfun{\id_{\rsupfun{\mu}\{x\}}^{\mathsf{FCD}}}\supfun{f^{-1}\circ f}\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & \sqsupseteq\\
\supfun{\id_{\rsupfun{\mu}\{x\}}^{\mathsf{FCD}}}\supfun{\id_{\rsupfun{\mu}\{x\}}^{\mathsf{FCD}}}\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\} & =\\
\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}.
\end{align*}

On the other hand, $f|_{\rsupfun{\mu}@\{x\}}\sqsubseteq\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}$;

$\nu\circ f|_{\rsupfun{\mu}@\{x\}}\sqsubseteq\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\supfun{\nu}\rsupfun{\nu}@\{y\}\sqsubseteq\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}$.

So $\nu\circ f|_{\rsupfun{\mu}@\{x\}}=\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\}$.

$\xlim_{x}f=\setcond{\nu\circ f|_{\rsupfun{\mu}@\{x\}}\circ\uparrow r}{r\in G}=\setcond{(\rsupfun{\mu}@\{x\}\times^{\mathsf{FCD}}\rsupfun{\nu}@\{y\})\circ\uparrow r}{r\in G}=\tau(y)$.\end{proof}
\begin{cor}
If $\lim_{\rsupfun{\mu}@\{x\}}^{\nu}f=y$ then $\xlim_{x}f=\tau(y)$ (provided that $\nu\sqsubseteq\nu\circ\nu$).
\end{cor}
We have injective $\tau$ if $\rsupfun{\nu}@\{y_{1}\}\sqcap\rsupfun{\nu}@\{y_{2}\}=\bot^{\mathscr{F}(\Ob\mu)}$
for every distinct $y_{1},y_{2}\in\Ob\nu$ that is if $\nu$ is $T_{2}$-separable.

\section{Expressing limits as implications}

When you studied limits in the school, you was told that
$\lim_{x\to\alpha} f(x) = \beta$ when $x\to\alpha$ implies
$f(x) \to \beta$. Now let us formalize this.

\begin{prop}
  The following are pairwise equivalent for funcoids $\mu$, $\nu$, $f$ of
  suitable (``compatible'') sources and destinations:
  \begin{enumerate}
    \item\label{implim-one} $f|_{\langle \mu \rangle^{\ast} \{ \alpha \}}
    \overset{\nu}{\rightarrow} \beta$;

    \item\label{implim-f} $\forall x \in \mathscr{F} (\Ob \mu) : \left( x
    \overset{\mu}{\rightarrow} \alpha \Rightarrow \supfun{f} x
    \overset{\nu}{\rightarrow} \beta \right)$;

    \item\label{implim-a} $\forall x \in \atoms^{\mathscr{F} (\Ob \mu)} : \left( x
    \overset{\mu}{\rightarrow} \alpha \Rightarrow \supfun{f} x
    \overset{\nu}{\rightarrow} \beta \right)$.
  \end{enumerate}
\end{prop}

\begin{proof}
  ~
  \begin{description}
    \item[\ref{implim-one}$\Leftrightarrow$\ref{implim-f}]
    \begin{multline*}
    \forall x \in \mathscr{F} (\Ob \mu) :
    \left( x \overset{\mu}{\rightarrow} \alpha \Rightarrow \supfun{f} x
    \overset{\nu}{\rightarrow} \beta \right) \Leftrightarrow \\ \forall x \in
    \mathscr{F} (\Ob \mu) : (x \sqsubseteq \langle \mu \rangle \alpha
    \Rightarrow \\ \supfun{f} x \sqsubseteq \supfun{\nu} \beta)
    \Leftrightarrow \supfun{f} \langle \mu \rangle \alpha \sqsubseteq
    \supfun{\nu} \beta \Leftrightarrow f|_{\langle \mu \rangle^{\ast}
    \{ \alpha \}} \overset{\nu}{\rightarrow} \beta.
    \end{multline*}

    \item[\ref{implim-f}$\Rightarrow$\ref{implim-a}] Obvious.

    \item[\ref{implim-a}$\Rightarrow$\ref{implim-f}] Let \ref{implim-a} hold. Then for $x \in \mathscr{F}
    (\Ob \mu)$ we have $x \overset{\mu}{\rightarrow} \alpha
    \Leftrightarrow x \sqsubseteq \langle \mu \rangle \alpha \Leftrightarrow
    \forall x' \in \atoms x : x' \sqsubseteq \langle \mu \rangle \alpha
    \Leftrightarrow \forall x' \in \atoms x : x'
    \overset{\mu}{\rightarrow} \alpha \Rightarrow \forall x' \in \atoms
    x : \supfun{f} x' \overset{\nu}{\rightarrow} \beta \Leftrightarrow
    \forall x' \in \atoms x : \left\langle f \right\rangle x'
    \sqsubseteq \supfun{\nu} \beta \Leftrightarrow \bigsqcup_{x' \in
    \atoms x} \supfun{f} x' \sqsubseteq \supfun{\nu} \beta
    \Leftrightarrow \supfun{f} x \sqsubseteq \supfun{\nu} \beta
    \Leftrightarrow \supfun{f} x \overset{\nu}{\rightarrow} \beta$.
  \end{description}
\end{proof}

\begin{lem}
  If $f$ is an enterely defined monovalued funcoid and $x$ is an ultrafilter,
  $y$ is a filter, then $\supfun{f} x \sqsubseteq y \Leftrightarrow x
  \sqsubseteq \langle f^{- 1} \rangle y$.
\end{lem}

\begin{proof}
  $\supfun{f} x$ is an ultrafilter. $\supfun{f} x \sqsubseteq y
  \Leftrightarrow \supfun{f} x \nasymp y \Leftrightarrow x \nasymp
  \langle f^{- 1} \rangle y \Leftrightarrow x \sqsubseteq \langle f^{- 1}
  \rangle y$.
\end{proof}

\begin{prop}
  The following are pairwise equivalent for funcoids $\mu$, $\nu$, $f$, $g$ of
  suitable (``compatible'') sources and destinations provided that $g$ is
  entirely defined and monovalued:
  \begin{enumerate}
    \item\label{limback-one} $(f \circ g^{- 1}) |_{\langle \mu \rangle^{\ast} \{ \alpha \}}
    \overset{\nu}{\rightarrow} \beta$;

    \item\label{limback-f} $\forall x \in \mathscr{F} (\Ob \mu) : \left( \langle g
    \rangle x \overset{\mu}{\rightarrow} \alpha \Rightarrow \supfun{f}
    x \overset{\nu}{\rightarrow} \beta \right)$;

    \item\label{limback-a} $\forall x \in \atoms^{\mathscr{F} (\Ob \mu)} : \left(
    \supfun{g} x \overset{\mu}{\rightarrow} \alpha \Rightarrow \langle
    f \rangle x \overset{\nu}{\rightarrow} \beta \right)$.
  \end{enumerate}
\end{prop}

\begin{proof}
  ~
  \begin{description}
    \item[\ref{limback-one}$\Leftrightarrow$\ref{limback-a}] Equivalently transforming: $(f \circ g^{- 1})
    |_{\langle \mu \rangle^{\ast} \{ \alpha \}} \overset{\nu}{\rightarrow}
    \beta$; $\supfun{f} \langle g^{- 1} \rangle^{\ast} \langle \mu
    \rangle^{\ast} \{ \alpha \} \sqsubseteq \supfun{\nu}^{\ast} \{
    \beta \}$; for every $x \in \atoms^{\mathscr{F} (\Ob \mu)}$ we
    have $x \sqsubseteq \langle g^{- 1} \rangle \langle \mu \rangle^{\ast} \{
    \alpha \} \Rightarrow \supfun{f} x \sqsubseteq \langle \nu
    \rangle^{\ast} \{ \beta \}$; what by the lemma is equivalent to $\langle g
    \rangle x \sqsubseteq \langle \mu \rangle^{\ast} \{ \alpha \} \Rightarrow
    \supfun{f} x \sqsubseteq \supfun{\nu}^{\ast} \{ \beta \}$
    that is $\supfun{g} x \overset{\mu}{\rightarrow} \alpha \Rightarrow
    \supfun{f} x \overset{\nu}{\rightarrow} \beta$.

    \item[\ref{limback-a}$\Leftrightarrow$\ref{limback-f}] Let $x \in \mathscr{F} (\Ob \mu)$ and~\ref{limback-a}
    holds. Let $\supfun{g} x \overset{\mu}{\rightarrow} \alpha$. Then
    $\forall x' \in \atoms x : \supfun{g} x'
    \overset{\mu}{\rightarrow} \alpha$ and thus $\supfun{f} x'
    \overset{\nu}{\rightarrow} \beta$ that is $\supfun{f} x'
    \sqsubseteq \supfun{\nu} \beta$. $\supfun{f} x =
    \bigsqcup_{x' \in \atoms x} \supfun{f} x' \sqsubseteq \langle
    \nu \rangle \beta$ that is $\supfun{f} x \overset{\nu}{\rightarrow}
    \beta$.
  \end{description}
\end{proof}

\begin{problem}
  Can the theorem be strenhtened for: a. non-monovalued; b. not entirely defined $g$?
  (The problem seems easy but I have not checked it.)
\end{problem}


\documentclass[12pt]{article}
\usepackage[a4paper, bindingoffset=0.2in, %
							left=0.5in,right=0.5in,top=0.5in,bottom=0.5in,%
							footskip=.25in]{geometry}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{amssymb}
\usepackage{hyperref}

\title{PSet1 Report}
\author{Ali Abolhassanzadeh Mahani}
\date{Sep. 28}

\begin{document}
    \maketitle
    \section{Problem 1}
    \subsection{Creations and the loops}
    For starters, since I know how many steps I'm going to have and the size of the row,
    I allocate a table of that size in memory using \texttt{np.ndarray} with \texttt{int} as my data type; This will be my canvas.

    Now,  I do a nested for loop for each \textit{round} and each \textit{element} in the row
    to find their situation and decide their next state. Here, some people use
    \texttt{(index) \% len(row)} to set the boundary condition, but with this setup, we are doing a \texttt{mod operation} per element and it makes it a little inefficient. I used the fact that Python \texttt{ndarray}s support \emph{negative indexing} and just set the upper boundary condition with an if statement.

    \subsection{The rule}
    Our rule is as follows: \emph{``If \underline{only one} of my neighbors is 1 (i.e. Has a hat), I become 1 (i.e. put on the hat), otherwise, I become 0."}

    The mathematical interpretation of \emph{``If only 1 neighbor is 1"} is that the sum of the neighbors equals to 1. Hence the \texttt{if} statement in our code.

    \subsection{Fancy}
    The style of which I have written this code is to be able to import the functions, if I
    need them in the future. All that the last \texttt{if} statement does, is to see if we are executing this file, and then, execute the \texttt{main()} function.

    \subsection{Analysis} \label{sec:analysis}
    The main part of the code is the \texttt{put\_hat()} function, which consists mainly of two
    nested \texttt{for} loops. taking one to have $m$ iterations and the other, $n$, we can see
    that the runtime complexity of this code is $\mathcal{O}(m.n)$.
    In order to analyze this code, one can run a profiler on it as follows:
    \begin{lstlisting}[language=bash]
    	python -m cProfile -s time Hats.py
    \end{lstlisting}
	Note that this profiler lists all the modules that are being called, so due to our use of \texttt{numpy} and \texttt{matplotlib.pyplot}, it will show a lot of things, but the main
	function \texttt{put\_hats} will be at the top few.

	\subsection{Results}
	I used the \texttt{pcolormesh()} module from the \texttt{matplotlib.pyplot} library to
	export my canvas into a file. The resulting image is identical to rule 18, 26 or 90. (Figure \ref{fig:hats200})
	\begin{figure}[h!]
		\includegraphics[width=\linewidth]{../P1/Hats200.jpg}
		\label{fig:hats200}
		\caption{The evolution of the hats for 200 steps using the rule that if only one of
							my neighbors has a hat, I put on a hat, otherwise, I put down my hat. The yellow cells have a hat on and the purple ones don't.
							\emph{Note that this rule is independent of the item in question.}}
	\end{figure}

	\section{Problem 2}
	\subsection{The Code}
	This project consists of 3 files. \texttt{256rules.py} which is the main file to be run,
	\texttt{cells.py} which contains the creation and evolution of cells, and finally, \texttt{graphics.py} which contains the modules to make the image files.

	As for analysis, one can use the code used in section\ref{sec:analysis} to run a profiler on the main functions. But the algorithm used is the same as the one before.

	\subsection{Results}
	Using the \texttt{graphics.py} module we output the file with its rule number in binary as its name. The result are included in Fig \ref{fig:2rules}.   As one can see, the CA rule 75 makes a chaotic-looking pattern meaning that
	it's classified in \textbf{Class 3} in Wolfram, while rule 110 leads to a comples pattern that seems to repeat itself locally, hence in \textbf{Class 4} in Wolfram.
	\begin{figure}[h!]
		\includegraphics[width=0.45\linewidth]{../P2/Hats01001011.jpg}
		\includegraphics[width=0.45\linewidth]{../P2/Hats01101110.jpg}
		\label{fig:2rules}
		\caption{These images where created using rules 110 (on the right) and 75 (on the left)
							 of the 256 Elementary Cellular Automata Rules. Color yellow means the
							 cell is \emph{on} and purple means that it's \emph{off}. }
	\end{figure}

	\section{Problem 3}
	\subsection{The Code}
	This project is almost identical to the previous one. The only difference is the main file
	\texttt{iteration\_bitflip.py}. This time we take rule 110 and iterate over its digits and do a
	bit flip for each one. Then we make the CA for that rule and output it as before.
	\subsection{Results}
	The result are the same as the ones in question in the assignment.
	(Figure \ref{fig:bitflip}) As one can see, rules \texttt{00101110}, \texttt{01101010}, \texttt{01101100} are Class 2 CAs and  rules \texttt{01001110}, \texttt{11101110}, \texttt{01100110}
	are class 4 CAs, while \texttt{01101111}, \texttt{01111110} seem chaotic and are classified as Class 3 CAs.

	\begin{figure}[h!]
		\includegraphics[width=0.4\linewidth]{../P3/Hats00101110.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats01001110.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats01100110.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats01101010.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats01101100.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats01101111.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats01111110.jpg}
		\includegraphics[width=0.4\linewidth]{../P3/Hats11101110.jpg}
		\label{fig:bitflip}
		\caption{This collections of images is created by performing bitflips on every binary
		digit of rule 110. The yellow cells are \emph{on} and the purple ones are \emph{off}.}
	\end{figure}

	\section{Problem 4}
	\subsection{The Code}
	Here we have the main file \texttt{gol.py} which stands for Game of Life (GoL).
	In the subfolder \texttt{classes}, we have \texttt{types.py} which contains a set initializers for our 4 models, \texttt{operations.py} which is contains everything
	we need to make decisions for the model, and \texttt{graphics.py} which consists of
	the module \texttt{animate}. This module takes an array, makes a new one and initializes
	it with the input, and prints an image of it. Then, it decides the next frame and saves the
	new array to \texttt{canvas}, and prints it, and so on the loop goes. I chose 20 frames to be the default. (Let's be honest, I just hard coded it! ;-P)
	\subsection{Results}
	At last, I took the frames and made a gif with them using \href{https://ezgif.com/maker}{this GIF Maker}. The files are available at the
	 corresponding subdirectories. I checked them with
	  \href{https://www.conwaylife.com/wiki/Main_Page}{this source} and
	 they are spot on! Yay!

	 \section{Conclution}
	 I Hate \texttt{matplotlib.animation.FuncAnimation} soooo much!

\end{document}


\documentclass{article}

\usepackage{amsmath, amsthm, amssymb}
\usepackage{fullpage}
\usepackage{url}

\begin{document}
\title{SIGVISA Processing}
\author{Dave Moore}
\date{}

This document describes the models algorithms used in SIGVISA's data processing.

\section{Envelope Model}

\section{Observation Model}

\subsection{Model}
We model the observation at a three-component station by the following generative process. Each arriving phase $p$ generates an {\em abstract log-envelope} $\ell^{(p)}(t)$ according to the envelope model given above; the parameters of this envelope depend on the arriving amplitude, azimuth, angle of incidence, etc. (which in turn depend stochastically on the generating event). This abstract log-envelope is perturbed by an autoregressive process $w^{(p)}(t)$, given by
\begin{align*}
w^{(p)}(t) &= \sum_{i=1}^{n_0} \alpha_i w^{(p)}(t-i) + \epsilon^{(p)}(t)\\
\epsilon^{(p)}(t) &\sim \mathcal{N}(0, \sigma_{(p)}^2)
\end{align*}
where $\alpha_1, \cdots, \alpha_{n_0}$ and $\sigma_{(p)}^2$ denote the weights and noise variance respectively of an order-$n_w$ autoregressive process (the ``wiggle process'' associated with this phase). The full abstract log-envelope $a^{(p)}(t)$ is thus given by
\[a^{(p)}(t) = \ell^{(p)}(t) + w^{(p)}(t)\]

A three-component station measures waveform energy along the east-west, north-south, and vertical axes. The energy of each arriving phase is projected onto those three components according to its arriving azimuth $\theta^{(p)}$ and angle of incidence $\phi^{(p)}$. If the abstract log-envelope of an arriving P wave is $a^{(p)}(t)$, then the projection onto component $k$ is given by $\log(\tau_k) + a^{(p)}$, where $\tau_k$ is a scaling factor given by
\begin{align*}
\tau^{(p)}_E &= |\tan \phi^{(p)} \cos\theta^{(p)}|\\
\tau^{(p)}_N &= |\tan \phi^{(p)} \sin\theta^{(p)}|\\
\tau^{(p)}_Z &=|\cos \phi^{(p)}|.
\end{align*}
For an S wave, {\bf I don't know what to do} since we know which direction the motion {\em isn't} in, but there are two ``transverse'' directions and I don't know how to distinguish between them. Maybe ignore this for the moment and pretend that S waves are like P waves (though they aren't,  of course).

Finally, the observed envelope at component $k$ is generated by the sum of all projected arriving phase envelopes $\sum_{p\in \mathcal{P}} \exp(a^{(p)}(t))$, along with a component-specific {\em background noise process} $b^{(k)}(t)$, the log of which is again specified by an AR model with parameters $\beta^{(k)}_1, \cdots, \beta^{(k)}_{n_k}, \sigma_{(k)}^2$. So our final observed log-envelope is given by
\[h_k(t) = \log \left(\sum_{p\in\mathcal{P}} \exp(a^{(p)}(t)) + \exp(b^{(k)}(t))\right).\]

\subsection{Inference}

It turns out that the observation model described above is almost exactly a linear Gaussian model, suggesting a Kalman filter for state estimation and likelihood computation (recall that our main task is to compute the likelihood of the observed signal under a particular event hypothesis). Our state vector includes the current and previous values of the ``wiggle process'' for each currently arriving phase (up to the order of the AR model) along with the current and previous values of the noise processes for the three components. Considering for simplicity a single arriving phase $p$ and a single component noise process $k$, this is
\[\mathbf{x}(t) = \left(w^{(p)}(t), w^{(p)}(t-1), \cdots, w^{(p)}(t-n_0), b^{(k)}(t), b^{(k)}(t-1), \cdots, b^{(k)}(t-n_k)\right)^T.\]
The transition model is linear Gaussian, since the current value of each process is updated according to the AR model (which is just a linear combination of the previous values, plus Gaussian noise), and the previous values are just propogated along. That is, the transition model is given by
\[\mathbf{x}(t+1) = \mathbf{F}\mathbf{x}(t) + \mathbf{w}(t)\]
where $\mathbf{F}$ is a transition matrix which contains the AR weights and propagates the previous process values backwards in time:
\[\mathbf{F} = \left(\begin{array}{cccccccccc} \alpha_1 & \alpha_2 & \cdots & \alpha_{n_0-1} & \alpha_{n_0} & 0 & 0 & \cdots & 0 & 0 \\
1 & 0 & \cdots & 0 & 0 & 0 & 0 & \cdots & 0 & 0 \\
0 & 1 & \cdots & 0 & 0 & 0 & 0 & \cdots & 0 & 0 \\
\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots\\
0 & 0 & \cdots & 1 & 0 & 0 & 0 & \cdots & 0 & 0 \\
0 & 0 & \cdots & 0 & 0 & \beta^{(k)}_1 & \beta^{(k)}_2 & \cdots & \beta^{(k)}_{n_k-1} & \beta^{(k)}_{n_k}\\
0 & 0 & \cdots & 0 & 0 & 1 & 0 & \cdots & 0 & 0 \\
0 & 0 & \cdots & 0 & 0 & 0 & 1 & \cdots & 0 & 0 \\
\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots\\
0 & 0 & \cdots & 0 & 0 & 0 & 0 & \cdots & 1 & 0
\end{array}\right)\]
and $\mathbf{w}(t) \sim \mathcal{N}(0, \mathbf{Q})$ is a Gaussian noise vector with covariance $\mathbf{Q}$, where $\mathbf{Q}$ is a diagonal matrix whose only nonzero entries are $Q_{11} = \sigma_{(p)}^2$ and $Q_{(n_0+1)(n_0+1)} = \sigma_{(k)}^2$, i.e. the variances of the autoregressive processes being modeled.

Unfortunately the observation model is {\em not} linear since we are modeling the envelopes in the log scale. Now if we let $\mathcal{P}$ be the set of currently arriving phases (assumed above to contain just a single element $p$, but now allowed to be arbitrary), we have
\[\mathbf{z}(t) = \mathbf{h}(\mathbf{x}(t)) + \mathbf{v}(t)\]
where
\[\mathbf{h}(\mathbf{x}(t)) = \left(\begin{array}{c}\log\left(\sum_{p\in\mathcal{P}} \tau^{(p)}_E \exp\left(a^{(p)}(t)\right) + \exp(b^{(E)}(t)) \right)\\
\log\left(\sum_{p\in\mathcal{P}} \tau^{(p)}_N \exp\left(a^{(p)}(t)\right) + \exp(b^{(N)}(t)) \right)\\
\log\left(\sum_{p\in\mathcal{P}} \tau^{(p)}_Z \exp\left(a^{(p)}(t)\right) + \exp(b^{(Z)}(t)) \right)
\end{array}\right)\]
is our (nonlinear) measurement function and
\[\mathbf{v}(t) = \mathbf{0},\]
i.e. we assume no additional measurement noise (recall that we already include AR noise processes for each component as part of our state vector). ({\bf is this tenable? do we need some noise just for numerical stability?}) Since $\mathbf{h}$ is nonlinear we cannot use a traditional Kalman filter to compue the likelihood. Since $\mathbf{h}$ is differentiable we could linearize it around the current state estimate $\mathbf{\hat{x}(t)}$, i.e. an extended Kalman filter (EKF), but instead we opt to use an unscented Kalman filter (UKF). While the EKF uses an approximation of $\mathbf{h}$ to compute an exact (Gaussian) posterior distribution, the UKF uses the true $\mathbf{h}$ applied to a set of deterministic sample points to compute an approximation of the posterior distribution.

Further details on the UKF can be found on Wikipedia (and at \url{stomach.v2.nl/Docs/TechPubs/Tracking_and_AR/wan01unscented.pdf}), but for clarity we derive here the likelihood function $p(\mathbf{z}_1, \cdots, \mathbf{z}_t)$. The chain rule allows us to write this as a recursive update:
\[\log p(\mathbf{z}_1, \cdots, \mathbf{z}_t) = \log p(\mathbf{z}_t | \mathbf{z}_1, \cdots, \mathbf{z}_{T-1}) + \log p(\mathbf{z}_1, \cdots, \mathbf{z}_{t-1})\]
and so we just need to derive the update factor
\begin{align*}
p(\mathbf{z}_t | \mathbf{z}_1, \cdots, \mathbf{z}_{t-1}) &= \int p(\mathbf{z}_t | \mathbf{x}_t) p(\mathbf{x}_t | \mathbf{z}_1, \cdots, \mathbf{z}_{t-1})d\mathbf{x}_t
\end{align*}
where \[p(\mathbf{x}_t | \mathbf{z}_1, \cdots, \mathbf{z}_{t-1}) \sim \mathcal{N}\left(\hat{\mathbf{x}}_{t|t-1}, \mathbf{P}_{t|t-1}\right)\]
 is the Gaussian distribution predicted by the Kalman filter. In a standard KF the observation model $p(\mathbf{z}_t | \mathbf{x}_t)$ is also linear Gaussian:
\[p(\mathbf{z}_t | \mathbf{x}_t) \sim \mathcal{N}\left( \mathbf{H}\mathbf{x}_t, \mathbf{R} \right)\]
and the integral gives a Gaussian density \[p(\mathbf{z}_t | \mathbf{z}_1, \cdots, \mathbf{z}_{t-1}) \sim \mathcal{N}\left( \mathbf{H} \hat{\mathbf{x}}_{t|t-1}, \mathbf{R} + \mathbf{H}\mathbf{P}_{t|t-1}\mathbf{H}^T\right)\]
(see identity 35 in \url{http://userpage.fu-berlin.de/mtoussai/notes/gaussians.pdf}), so our update factor is just a Gaussian likelihood. Now in our case, we have $\mathbf{R}=\mathbf{0}$ since we assume no additional measurement noise, but more importantly our measurements are no longer linear. In an EKF we would just take $\mathbf{H}$ to be the linear approximation of $\mathbf{h}$ around $\hat{\mathbf{x}}_{t|t-1}$.

Note that what we just derived is just the ``innovation covariance'' $\mathbf{S}$ from wikipedia.

problems:

- the idea of an abstract wiggle process means that wiggles in all channels have to look almost exactly the same. is this the case in real wiggles? I'm guessing not... so I either focus on real data, or add iid observation noise... but that sort of defeats the point of AR noise in the first place.
-- I could also add separate wiggle processes for each channel, but then there'd be no correlation between the channels at all (except the envelope, which I guess counts for something...)
-- separate wiggle processes is actually the only way I can think of to legitimately learn a wiggle model (without crazy Kalman stuff...)

-- another thought: instead of having an elephant model, just learn a separate AR noise variance for the first few seconds of the signal...

-- steps:
-- when this is working: integrate into fit_envelope!
-- hook in Min's code to learn AR noise params
-- once this is all good and working, go back to (iteratively) learning signal AR params
-- keep in mind the whole time that we will need to do this for lots of frequency bands...
- once this is all working, go back and try to figure out how P/S projection coeffs should work (learn a model...)

- mystery segfault/stack corruption when I remove the canary

issues w/ integration:
- need to decide when to have obs noise and when not to (or, whether to just have indep wiggle models for each channel...)

problems:
- costs are barely changing?
- fix horiz_avg ( or just work with bhz...)

again, the optimizer isn't even TRYING
further, there's an issue with big negative costs (enormous lls) for some params ... is this OK?

let's try what I think are the ``true'' params, compare to what the optimizer finds

if we have an arrival at zero height, then suddenly we get twice the variance to explain the same noise signal?
if we think of adding things in real space, we have an exp-AR noise process, plus a peak-height-'e' exponentially-decaying envelope being multiplied by an exp-AR process.
under this model a logamp-0 arrival will almost always make a signal more plausible (which makes a weird sort of sense...)
this will be solved by a prior on event sizes, and then on the amplitudes created by event sizes...

fixed the not adding zero events, but haven't fixed the outcome.

I don't believe that my sigma is correct ... the noise residuals I'm seeing are ALL like .01, but my stddev is apparently .07? (var .005)
the stddev of residuals from the first 1000 datapoints is 0.0233

so maybe the noise variance just isn't representative?

even with low noise variance, the ``best params'' are getting lower costs (higher ll) than the ``true params''.
the variances shouldn't be too different: they both have mixtures of the same AR processes (but how do variances work with the mixed processes?)
next step: extract residuals and variances from the lls logs for ``true'' vs. ``best''

one issue: we start by predicting the mean, and charging enormously in ll for any deviation from it. we should probably just fix the initial state to the first observation?

also:
``true'' has high residuals throughout the arrivals. ``best'' has a couple of big ones but then it adjusts, to having mostly smaller residuals.
``true'' has variances matchine the shape of the signal. ``best'' has big variances at the time of each arrival, but then mostly small again.

I don't understand how ``best'' doesn't have GIANT residuals.

it makes sense that the variances should follow the envelope outlines: the bigger the envelope, the greater the ability of the wiggle process to influence the outcome.
I suppose it's possible that high variances could cause lower likelihoods, so this would be effectively saying that we don't *need* the wiggle process to understand the variation taking place.

the problem:  by effectively not having an event, we are forcing the noise process to explain the arrival. this is really expensive, once. (at the time of the arrival). but just half a second later, the noise process has jumped up, and is now doing fine. and it now constitutes a better explanation than the actual wiggle process, because the variance on the wiggle process is way too high?

solutions:
a) lower the variance on the wiggle process.
b) run the noise process in the original scale, not the log scale. the chance of getting a series of jumps up to the level of a phase arrival, just by random chance, ought to be essentially zero.

the residuals are still waaay off. and now we pay more for them.
I think the issue is that we're not properly tracking the wiggle process -- or maybe we don't have the right params for the wiggle process.
the Kalman gain controls how much of the adjustment goes into which hidden state

I should build proper debugging tools for this, since I imagine it will come up a lot.

need a DEBUG flag which causes dumping to a new dir everytime likelihood is called.
in this dir are files for the residual, output variance, predicted mean, and Kalman gain.
then I have a matlab script which, given the dir name, loads these files and plots stuff.

okay, now I have the gain and state logs

the major issue is the residuals. why are residuals larger under the ``true'' params than under the ``best'' params? it seems to be yo-yoing back and forth constantly
meanwhile, the ``best'' params should have constantly negative residuals during the time of the signal spike, since the arrival energy has been decaying.
yet they don't!

just to be absolutely sure about the stats, maybe I should go ahead and write a subtract-envelope function. what I want:
- give it a trace, and a set of envelope params
- return the trace with that envelope subtracted
- be able to use this to learn AR wiggle models. (so I should be ignoring the noise level... how does this work? exponentiate the signal,and the envelope. subtract the envelope, then take the log.

the confusing thing here is that if I exponentiate a nonzero-mean AR noise process, then subtract the mean, then take the log, this will stretch the process in a weird way.
this isn't an issue for the noise process param estimates, because I'm subtracting the mean in the log domain
but even focusing solely on the wiggle process, say I have exp(template + wiggleAR) and exp(template). to get wiggleAR I would actually just subtract the log-template from the log-obs. this is the right thing as long as the signal level is actually several orders of magnitude above the noise. (e.g. from looking at the envelope it should be clear that the noise could *never* reach up to the signal level).

my assumption had been that the signal is exp(mean + noiseAR) + exp(template + wiggleAR)

)

\end{document}