\documentclass[12pt]{amsart}
\usepackage{geometry} % see geometry.pdf on how to lay out the page. There's lots.
\usepackage{bsymb}
\usepackage{unitb}
\usepackage{calculational}
\usepackage{ulem}
\usepackage{hyperref}
\normalem
\geometry{a4paper} % or letter or a5paper or ... etc
% \geometry{landscape} % rotated page geometry

% See the ``Article customise'' template for some common customisations

\title{}
\author{}
\date{} % delete this line to display the current date

%%% BEGIN DOCUMENT
\setcounter{tocdepth}{4}
\begin{document}

\maketitle
\tableofcontents

\newcommand{\G}{\text{G}}
\renewcommand{\H}{\text{H}}

\section{Initial model}
\begin{machine}{m0}

\with{functions}
\with{sets}
\with{intervals}
\newset{\G}

\begin{align*}
\variable{p,q : \Int } \\
\variable{qe : \Int \pfun \G }
\end{align*}

\begin{align*}
\invariant{m0:inv0}{ qe &\1\in \intervalR{p}{q} \tfun \G }
% \invariant{m0:inv0}{ \dom.qe = \intervalR{p}{q} }
\\ \invariant{m0:inv1}{ p &\1\le q }
\end{align*}

\begin{align*}
\initialization{m0:init0}{p = 0 \land q = 0 \land qe = \emptyfun }
\end{align*}

\newevent{m0:push:left}{push\_left}
\param{m0:push:left}{x : \G}

\begin{align*}
\evassignment{m0:push:left}{m0:act0}{ qe' &\2= qe \2| p\0-1 \fun x }
\\ \evassignment{m0:push:left}{m0:act1}{ p' &\1= p-1 }
\\ \evassignment{m0:push:left}{m0:act2}{ q' &\1= q }
\end{align*}

\newevent{m0:push:right}{push\_right}
\param{m0:push:right}{ x : \G }

\begin{align*}
\evassignment{m0:push:right}{m0:act0}{ qe' &\2= qe \2| q \fun x }
\\ \evassignment{m0:push:right}{m0:act1}{ p' & \1= p }
\\ \evassignment{m0:push:right}{m0:act2}{ q' & \1= q+1 }
\\ \evguard{m0:push:right}{m0:grd1}{ qe.p = x }
\end{align*}

\newevent{m0:pop:left}{pop\_left}
\param{m0:pop:left}{x : \G}

\begin{align*}
\evassignment{m0:pop:left}{m0:act0}{ qe' &\1= \{ p \} \domsub qe }
\\ \evassignment{m0:pop:left}{m0:act1}{ p' &\1= p+1 }
\\ \evassignment{m0:pop:left}{m0:act2}{ q' &\1= q }
\\ \evguard{m0:pop:left}{m0:grd0}{ p < q }
\\ \evguard{m0:pop:left}{m0:grd1}{ qe.(p-1) = x }
\end{align*}

\newevent{m0:pop:right}{pop\_right}
\param{m0:pop:right}{ x : \G }

\begin{align*}
\evassignment{m0:pop:right}{m0:act0}{ qe' &\1= \{ q-1 \} \domsub qe }
\\ \evassignment{m0:pop:right}{m0:act1}{ p' &\1= p }
\\ \evassignment{m0:pop:right}{m0:act2}{ q' &\1= q-1 }
\\ \evguard{m0:pop:right}{m0:grd0}{ p < q }
\\ \evguard{m0:pop:right}{m0:grd1}{ qe.p = x }
\end{align*}

\end{machine}

\end{document}


\documentclass[a4paper,12pt]{article}

\usepackage{amsmath,amssymb,amsthm,tikz}
\usetikzlibrary{calc,arrows.meta}
\usepackage[margin=20mm]{geometry}
\usepackage{hyperref}

\setlength{\parindent}{0pt}
\setlength{\columnsep}{1cm}

\begin{document}

\twocolumn

\thispagestyle{empty}

\begin{center}
{\Large Assignment 11}\\
{\Large Published on 2020-12-05,}\\
{\em Estimated Time: 30 minutes,}\\
{\em Max.grade 10\textperthousand}
\end{center}

\section{Introduction}

If you know how to do topological sorting using
the DFS traversal (recording their
discovery and final visit times), you can immediately
start with the items in Section 2.
You can also read an inspirational slide deck on TOpological Sorting
from University of California, Davis:\\
\url{https://www.cs.ucdavis.edu/~bai/ECS122A/Notes/DFSapps.pdf}.
Or (Goodrich2011, p.633),
{\em Section 13.4.3 Directed Acyclic Graphs}.

In the example below we show the following:
\begin{itemize}
\item Draw the visual representation from its adjancency list
representation.
\item Add two more edges to the graph.
\item Run the DFS to check, if it is still a DAG (directed acyclic graph).
We do that DFS in a repeatable order (always pick the lexicographically smallest
vertex, if there is a choice).
\item Use the DFS visiting order (``final'' timestamp) to
create the topological sorting.
\end{itemize}

\subsection{Sample DAG}

Mr.\ Bunbury dresses every morning according to
certain rules: He always puts on his Trousers
after Underpants, his Sweater after his Belt.
He also puts on his Face-mask after the Sweater
(otherwise it would displace the Face-mask
as it is pulled over the head),
glasses are put on after the Face-mask,
since otherwise they get foggy, and so on.

\begin{figure}[!htb]
\center{\includegraphics[width=3in]{assignment11-topological-sort/clothing-adjacent.png}}
\caption{\label{fig:clothing-adjacent} Adjacency List Representation}
\end{figure}

All the rules are shown in graph $G$ Figure~\ref{fig:clothing-adjacent}
(it is also the adjecency list representation;
it shows all the before-after binary relationships). Square cells
that are crossed diagonally show null-pointers (i.e.\ they denote
where the adjacency lists end).
Mr.\ Bunbury has figured how he can get dressed according to these rules.
To make it even more intuitive, he made a visual
representation of the rules as in Figure~\ref{fig:clothing-dag}.

Somebody tells Mr.\ Bunbury that his Coat and Boots may be contaminated
with viruses, but hands should be clean as he applies the Face-mask
(this adds two red arrows to the diagram in Figure~\ref{fig:clothing-dag}).
At this point Mr.\ Bunbury needs advice \textendash{} one
feasible way to get dressed
by {\em topologically sorting} the clothing items
(or an evidence of a contradiction: a loop of arrows that prove
that the updated graph is not a
{\em Directed Acyclic Graph} anymore and it cannot be sorted).

\begin{figure}[!htb]
\center{\includegraphics[width=3in]{assignment11-topological-sort/clothing-dag.png}}
\caption{\label{fig:clothing-dag} Graph $G$ visualized}
\end{figure}

\subsection{DFS Traversal Example}

The Depth-First-Search traversal is described by a
recursive algorithm having this pseudocode:

$$\begin{array}{rl}
 & \text{\sc DFS}(G)\\
1 & \text{\bf for each}\;\text{vertex}\;u \in G.V:\\
2 & \hspace{.5cm} u.\text{\em color} = \text{\sc white}\\
3 & \hspace{.5cm} u.\text{\em parent} = \text{\sc nil}\\
4 & \text{\em time} = 0\\
5 & \text{\bf for each}\;\text{vertex}\;u \in G.V:\\
6 & \hspace{.5cm} \text{\bf if}\;u.\text{\em color} == \text{\sc white}:\\
7 & \hspace{1cm} \text{\sc DFS\textunderscore{}Visit}(G,u)\\
\end{array}$$

The loop on Line 5 (see the pseudocode of
$\text{\sc DFS}(G)$ above) visits vertices $u \in G.V$
in the lexicographic order. (It may also happen that
$\text{\sc DFS\textunderscore{}Visit}(G,u)$ is invoked just once, if
a single DFS call is enough to visit every vertex and to turn it black.

Here is the code of $\text{\sc DFS\textunderscore{}Visit}(G,u)$ (the DFS-visit
for vertex $u \in G.V$). Please pay attention to the two parameters
$\text{\em u.d}$ (discovery time \textendash{} when the DFS
traversal enters $u$ for the first time) and $\text{\em u.d}$ (finish time \textendash{}
when the DFS traversal leaves $u$ forever, since $u$ is visited along with all
its freshly discovered child vertices).

$$\begin{array}{rl}
  & \text{\sc DFS\textunderscore{}Visit}(G,u)\\
1 & \text{\em time} = \text{\em time} + 1 \\
  & \textcolor{teal}{\small \text{\em (white vertex $u$ was just discovered)}}\\
2 & u.d = \text{\em time}\\
3 & u.\text{\em color} = \text{\sc gray}\\
  & \textcolor{teal}{\small \text{\em (explore $(u,v_1)$, $(u,v_2)$, $\ldots$)}}\\
4 & \text{\bf for each}\;v \in G.Adj[u]: \\
5 & \hspace{0.5cm} \text{\bf if}\;v.\text{\em color} == \text{\sc white}:\\
6 & \hspace{1cm} v.\text{\em parent} = u\\
7 & \hspace{1cm} \text{\sc DFS\textunderscore{}Visit}(G,u)\\
  & \textcolor{teal}{\small \text{\em (vertex u now fully processed)}}\\
8 & u.\text{\em color} = \text{\sc black}\\
9 & \text{\em time} = \text{\em time} + 1\\
10 & u.f = \text{\em time}\\
\end{array}$$

Once again, we assume that the white neighbors of $u$ (for example,
$v_1$, $v_2$) are visited in their lexicographic order.
These assumptions make DFS traversal repeatable (without such assumption there
are typically multiple ways how to do DFS-style visits).

Let us run this DFS pseudocode on the clothing graph.
We start by visiting the vertex ``Belt'' (as it is alphabetically first),
so its discovery time $u.d = 1$. After that we visit all its neighbors (in their
alphabetical order, if there are several).
When we finish processing ``Belt'', we find the next vertex
(alphabetically first among those unvisited or having color {\sc white}), and so on.
The result of these activities is shown in Figure~\ref{fig:clothing-dfs}
(each vertex in $G$ has a green pair $(d/f)$ that shows the discovery/finish
time).

\begin{figure}[!htb]
\center{\includegraphics[width=3in]{assignment11-topological-sort/clothing-dfs.png}}
\caption{\label{fig:clothing-dfs} Graph $G$ with DFS discovery/finish}
\end{figure}

\subsection{Getting Topological Sorting}

$$\begin{array}{rl}
  & \text{\sc Topological\textunderscore{}Sort}(G)\\
  & \textcolor{teal}{\small \text{\em (result accumulates in reverse order)}}\\
1 & S = \text{\sc Stack.Empty()}\\
2 & \text{call}\;\text{\sc DFS}(G)\\
3 & \text{\bf for each}\;u \in G.V:\\
4 & \hspace{0.5cm} \text{as soon as $u.f$ (finish time) is assigned}:\\
5 & \hspace{0.5cm} S.\text{\em push}(u)\\
6 & \text{\bf return}\;S\\
\end{array}$$

We can look at Figure~\ref{fig:clothing-dfs} and list all the nodes in the
reverse order of their finish times (their values are $20,18,16,14,12,11,10,9,7,4$),
we would get the following topological order (one feasible way how
Mr.\ Bunbury can dress himself). For every clothing item we
also specify the time value when that vertex was finished (painted black).

\begin{quote}
(20) Underpants; (18) Trousers;\\
(16) Socks; (14) Shirt;\\
(12) Belt; (11) Sweater;\\
(10) Face mask; (9) Glasses;\\
(7) Boots; (4) Coat.
\end{quote}

The sequence shows that DFS (and the formal rule that always
picks the lexicographically smallest item) causes a reasonable
advice to get dressed.

\subsection{Graphs that are Not DAGs}

Topological sorting is not always doable \textendash{} if there
is any loop in the graph, it is no longer a DAG
(a directed acyclical graph).
During the DFS traversal it is possible to verify,
if a graph is a DAG or not.

Let us remember, how all directed edges fall into 4 categories as we
perform DFS:
\begin{description}
\item[Tree/Discovery edges] \hfill \\
All the edges $(u,v)$ visited by DFS as the depth-first forest is built (see Line 4
in pseudocode $\text{\sc DFS\textunderscore{}Visit}(G,u)$).
\item[Back edges] \hfill \\
Edges connecting a vertex $u$ with its ancestor $v$ in some DFS tree.
(If a cyclical graph contains a loop $(v,v)$ from a vertex to itself,
it is considered a back edge as well.)
\item[Forward edges] \hfill\\
Non-tree edges $(u,v)$ connecting $u$ to a descendant $v$ in some DFS tree.
\item[Cross edges] \hfill\\
All the other edges \textendash{} a cross edge connects a vertex to a vertex
that is neither its ancestor nor its descendent
\end{description}

{\bf Statement.} A graph is a DAG iff there is no
back edge: all edges during the DFS traversal are either
discovery edges, forward edges or cross edges.

{\bf Example.} Consider the graph in Figure~\ref{fig:cyclical-graph}.
It has a back-edge $(D,A)$ which completes a cycle
(in this example it is made from $3$ edges: $(A,B)$, $(B,D)$, $(D,A)$)

\begin{figure}[!htb]
\center{\includegraphics[width=3in]{assignment11-topological-sort/cyclical-graph.png}}
\caption{\label{fig:cyclical-graph} A graph with a cycle}
\end{figure}

To identify directed graphs that are not acyclical,
modify Line 4 in the pseudocode of\\
$\text{\sc DFS\textunderscore{}Visit}(G,u)$:
Before adding the new discovery/tree edge $(u,v)$, check,
if $u$ has any neighbor $v^{\ast}$ that currently has color {\sc gray};
this would mean that $v^{\ast}$ is an ancestor of $u$ and
$(u,v^{\ast})$ is a back-edge, which is forbidden.
(Even in case when $v^{\ast} = u$, and the edge $(u,v^{\ast})$ is
a loop to itself, the check would reveal that $u$ has color {\sc gray}.)

\section{Problem}

We start with the graph shown in Figure~\ref{fig:problem-adjacent}.

\begin{figure}[!htb]
\center{\includegraphics[width=3in]{assignment11-topological-sort/problem-adjacent.png}}
\caption{\label{fig:problem-adjacent} Adjacency list representation}
\end{figure}

\vspace{10pt}
{\bf (A)} Draw the visual representation of the graph,
each vertex is a circle (with string values {\tt "0"} to {\tt "9"})
inside. If there is a directed edge from one vertex to another,
draw it as an arrow.\\
(Figures \ref{fig:clothing-adjacent} and \ref{fig:clothing-dag} show
how this transformation was made for the clothing graph.)

\vspace{10pt}
{\bf (B)} Compute the following $4$ numbers from $a,b,c$ (your last
Student ID numbers):
$$\left\{ \begin{array}{l}
T = 3 \cdot ((a+b)\;\text{mod}\;4)\\
U = 3 \cdot ((b+c)\;\text{mod}\;3)+1\\
V = 3 \cdot ((c+a)\;\text{mod}\;3)+1\\
W = 3 \cdot ((a+b+c)\;\text{mod}\;3)+2\\
\end{array} \right.$$

By $(x\;\text{mod}\;y)$ we denote the remainder as $x$ is divided by $y$.
Add to the original graph two new directed edges $(T,U)$ and $(V,W)$.
(For example, if $T = 5$ and $U = 7$, then there should be an arrow from
vertex {\tt "5"} to vertext {\tt "7"}. If such an edge already exists, do
not add anything.)

Draw the new graph; show the newly added edges in bold or colored differently.

\vspace{10pt}
{\bf (C)} Run the DFS traversal algorithm on the graph just obtained in (B), mark each vertex
with the pair of numbers {\tt d/f}, where the first number {\tt d} is the
discovery time, and the second number {\tt f} is the finishing time.
(You will use all the numbers from $1$ to $20$: every number will be used
exactly once.) It should take exactly $20$ steps to do DFS enters/exits in
a directed graph with $10$ vertices.

If there are multiple ways how to pick a vertex to visit next, always
pick the vertex with the smallest number. (Otherwise your results cannot be
properly verified.)

\vspace{10pt}
{\bf (D)} If the graph you got in (B) after adding new edges is not a DAG anymore,
please say so in your answer; indicate what vertex you visited as you discovered
that a back edge exists. And also show which is the cycle.

If the graph is a DAG, produce a topological sorting of its vertices
(the algorithm is explained in Section 1.4 above).

\vspace{10pt}
{\em Note.} Your solution should contain two directed graphs ((A) and (B)), one
directed graph with vertices anotated with {\tt d/f} (in (C)) and
EITHER information on the back edge+cycle OR topological sorting of the vertices.

\end{document}


\documentclass{article}

%-------------------------------------------------

\usepackage{fullpage}
\usepackage{setspace}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\usepackage{color}

%------------------------

%-------------------------------------------------
\begin{document}

\title{
Upon constraining the spatial distribution of transient gravitational-wave sources
}

\author{
Reed Essick
}

\maketitle

%------------------------

\doublespace

We begin by asserting that graviational waves (GWs) are interesting and therefore their sources are interesting.
Furthermore, we assert that the spacetime distribution of sources is also interesting and set out to measure that distribution using transient GW signals.
A bit of nomenclature

\vspace{0.5cm}
\begin{tabular}{p{3cm}p{12cm}}
    $R(m_1, m_2, z, \Omega)$ & the rate of signals from a direction in the sky ($\Omega$) at redshift $z$ with masses $m_1$, $m_2$, etc, measured with respect to detector-frame time. \\
    $dV_c/d\Omega dz$ & the differntial sensitive co-moving volume observed by our detectors as a function of time, position on the sky, and $z$, which depends on the detector sensitivity. \\
    $p(\mathrm{noise})$ & the probability of observing a particular noise realization. This is usually Gaussian in a frequency series or a non-central $\chi^2$-distribution with 2 degrees of freedom for the signal-to-noise ratio. \\
    $\mathcal{F}(m_1,m_2,z,\Omega;t) $ & the probability of detecting a signal with these parameters at this time (related to probabilities of specific noise realizations and the associated signal-to-noise ratios); in most cases this may be treated approximately as a step function.
\end{tabular}
We note that
\begin{equation}
    \mathcal{F} = \int \mathcal{D}\mathrm{noise}\, \left(p(\mathrm{noise}) R\frac{dV_c}{d\Omega dz}\right) \Theta\left(\mathrm{noise}+h(m_1, m_2, \Omega, z)\geq \mathrm{thr}\right)
\end{equation}
where $\Theta$ is the heaviside function and $h$ is the modeled strain in the detector associated with $m_1$, $m_2$, $\Omega$, and $z$.

\vspace{0.5cm}
\noindent
We also assume that reasonable priors for our Bayesian inference on a per-event basis follow the modeled astrophysical distribution so that
\begin{equation}
    \frac{p(m_1, m_2, z, \Omega|t,R)}{p(m_1^\prime, m_2^\prime, z^\prime, \Omega^\prime|t^\prime,R)} = \frac{R(m_1, m_2, z, \Omega) \left.(dV_c/d\Omega dz)\right|_{\Omega, z}}{R(m_1^\prime, m_2^\prime, z^\prime, \Omega^\prime) \left.(dV_c/d\Omega dz)\right|_{\Omega^\prime, z^\prime}}
\end{equation}
This means that the expected number of signals with masses $m_1$, $m_2$, etc. coming from $\Omega$ at $z$ coincident with $t$ will be something like
\begin{equation}
    N_\mathrm{astro} = \left[ R(m_1, m_2, \Omega, z) \frac{dV_c}{d\Omega dz} \Delta\Omega \Delta z \Delta m_1 \Delta m_2 \right] \Delta t
\end{equation}
and we expect to detect
\begin{equation}
    N_\mathrm{detect} = N_\mathrm{astro} \mathcal{F}(m_1, m_2, z, \Omega; t)
\end{equation}

Now, we consider rates that are low enough so that only one type of signal ($m_1$, $m_2$, $z$, $\Omega$) is detectable at a time and further model each type of signal as an independent Poisson process.
We then marginalize over all possible signal parameters, which we approximate by a set of discrete bins indexed by $k$, and noise realizations, which we approximate by an indepdendent set of discrete bins indexed by $\alpha$.
For each combination of $k$ and $\alpha$, we expect the rate of detectable signals in the detectors to be $\mathrm{rate} = R_k dV_k p(n_\alpha) \Theta_{k,\alpha}$, where we've abbreviated some of the terms from above.
This is because there will be an overall rate of $R_k dV_k$ astrophysical events in our detectors, and the relative frequency with which each of these events will have noise realization $n_\alpha$ is $p(n_\alpha)$.
Finally, if the signal and noise are not above threshold, then the rate of signals above threshold vanishes and this is captured by $\Theta_{k,\alpha}$.
Thus, we expect
\begin{align}
    p(\mathrm{data}=d|\mathrm{signal}; R, t)p(\mathrm{signal}|R, t) & = \left. \sum_{k,\alpha} \right[ p(N_{k,\alpha}=1|R_k dV_k p(n_\alpha)\Theta_{k,\alpha} \Delta t) \prod\limits_{j \neq k, \beta \neq \alpha} p(N_{j,\beta}=0|R_j dV_j p(n_\beta)\Theta_{j,\beta} \Delta t) \nonumber \\
                                                                  & \quad\quad\quad\quad \left. \times p\left(d\left|n_\alpha, m_1^{(k)}, m_2^{(k)}, \Omega^{(k)}, z^{(k)}\right)\right. \right] \nonumber \\
                                                                  & = \left. \sum_{k,\alpha} \right[ \left(R_k dV_k p(n_\alpha)\Theta_{k,\alpha} \Delta t\right) e^{-R_k dV_k p(n_\alpha)\Theta_{k,\alpha} \Delta t} \prod\limits_{j \neq k, \beta \neq \alpha} e^{-R_j dV_j p(n_\beta)\Theta_{j,\beta} \Delta t} \nonumber \\
                                                                  & \quad\quad\quad\quad \left. \times \delta\left(d - n_\alpha+h^{(k)}\right) \right] \nonumber \\
                                                                  & = \left[\sum_{k} \left(R_k dV_k p\left(n=d-h^{(k)}\right) \Delta t\right) \right] e^{-\sum\limits_{j, \beta} R_j dV_j p(n_\beta)\Theta_{j,\beta} \Delta t} \nonumber \\
                                                                  & = \Delta t \left[ \int dm_1 dm_2 dz d\Omega \left(R \frac{dV_c}{d\Omega dz} \right) p\left(d|m_1, m_2, \Omega, z\right) \right] e^{-\left[\int dm_1 dm_2 dz d\Omega \left(R \frac{dV_c}{d\Omega dz} \mathcal{F}\right)\right] \Delta t}
\end{align}
where in the second-to-last line we use the fact that $(d\geq\mathrm{thr})$ to drop the factor of $\Theta_{k,\alpha}$ because there is a detectable signal in the data, and in the last line we've assumed the standard notation $p(d|m_1,m_2,\Omega,z)=p(n=d-h(m_1,m_2,\Omega,z)$.
Similarly, we obtain
\begin{align}
    p(\mathrm{data}=d|\mathrm{noise}; R, t)p(\mathrm{noise}|R, t) & = p(n=d) \prod\limits_{j,\beta} p(N_{j,\beta}=0|R_jdV_j p_\beta(\mathrm{noise})\Theta_{j,\beta} \Delta t) \nonumber \\
                                                                & = p(d|\mathrm{noise}) e^{-\left[\int dm_1 dm_2 dz d\Omega \left(R \frac{dV_c}{d\Omega dz} \mathcal{F}\right)\right] \Delta t}
\end{align}
where I've again switched to more standard notation in the last line: $p(d|\mathrm{noise}) = p(n=d)$.
These define the relevant likelihoods for each small time segment.
We assume many time segments are independent and then stack everything together.
This give an overall joint likelihood of observing the set of detections we actually observed, conditioned on a Rate distribution: $R(m_1, m_2, z, \Omega)$.
Following Messenger+Veitch (2013), we obtain
\begin{align}
    p(\mathrm{data}|R) = & \prod\limits_{i|d_i\geq\mathrm{thr}} \left[ p(d_i|\mathrm{noise}) + \int dm_1 dm_2 dz d\Omega \left( R\frac{dV_c}{d\Omega dz} \Delta t \right) p(d_i|m_1, m_2, z, \Omega) \right] e^{-\int dm_1 dm_2 dz d\Omega R\frac{dV_c}{d\Omega dz} \mathcal{F}_i \Delta t} \nonumber \\
                         & \quad\quad\quad\quad \times \prod\limits_{j|d_j<\mathrm{thr}} p(d_i<\mathrm{thr}|\mathrm{noise}) e^{-\int dm_1 dm_2 dz d\Omega R\frac{dV_c}{d\Omega dz} \mathcal{F}_j \Delta t}
\end{align}
which we simplify by assuming $p(d_i<\mathrm{thr}|\mathrm{noise}) =1$.
This is equivalent to normalizing the likelihood appropriately to assume we only see signals above our threshold.
In reality, we should be able to extract more information by lowering the threshold to include marginal events, but the associated benefits are expected to be realtively small with a significant computational overhead.
With our simplifying assumptions, we obtain
\begin{multline}
    \log p(\mathrm{data}|R) = - \int dt dm_1 dm_2 dz d\Omega \left(R \frac{dV_c}{d\Omega dz} \mathcal{F}\right) \\
         + \sum\limits_{i|d_i\geq\mathrm{thr}} \log \left[ \Delta t \int dm_1 dm_2 dz d\Omega \left(R \frac{dV_c}{d\Omega dz} \right) p(d_i|m_1, m_2, \Omega, z) \right] \\
         + \text{terms independent of }R
\end{multline}
This looks something like a Poisson factor for the overall rate along with the evidence for each individual event.
We can use this marginal likelihood for the Rate distribution to make inferences about the rate.
Several approaches for sampling $p(R|\mathrm{data})$ have been proposed
\begin{itemize}
    \item bin the sky into separate voxels and run an MCMC direcly over the rate in each voxel. This can be expensive if there are a lot of voxels. We note that sampling can be done in ``pixel-space'' or in spherical harmonics, although care is needed to guarantee $R(\Omega) \geq 0\ \forall\ \Omega$.
    \item assume the deviations from isotropy are small and attempt to infer the posterior of the deviations analytically (see below).
\end{itemize}
along with several sanity checks and/or back-of-the-envelop estimates
\begin{itemize}
    \item divide the sky into hemispheres and count the posterior weight in each hemisphere as a statistic looking for a dipole. We note that because ground-based detectors' antenna patterns are quadropoles, there manifestly must be equal exposures in any hemisphere and it's complement, meaning a counting experiment is justified without additional weighting by exposure.
    \item compute the 2-point auto-correlation function with stacked posteriors to look for preferred length scales. This may have to deal with complicated ``point-spread functions'' associated with the posterior distributions of each event.
\end{itemize}

%------------------------

\subsection*{Marginal likelihood for $R_\Omega$}

We assume a separation of the rate distribition: $R = p_{m,z}(m_1, m_2, z) R_\Omega(\Omega)$.
We have adopted a separation of variables in which the mass and redshift distribution integrates to one and the units are carried by the angular dependence.
Thus,
\begin{align}
    \mathcal{N} p_\Omega & = \int dm_1 dm_2 dz\, \left(p_{m,z} \frac{dV_c}{d\Omega dz} \right) \\
    \int d\Omega p_\Omega & = 1
\end{align}
so that
\begin{equation}
    \int dm_1 dm_2 dz \left( p_{m,z}\frac{dV_c}{d\Omega dz} \right) p(d_i|m_1, m_2, z, \Omega) = \mathcal{N} p(\Omega|d_i)
\end{equation}
where $p(\Omega|d_i)\propto p(d_i|\Omega)p_\Omega$ is the a posteriori skymap for event $i$.
We find
\begin{align}
    \log p(\mathrm{data}|R) \supset & - \int d\Omega\, R_\Omega \int dt \mathcal{N} p_\Omega + \sum\limits_{i|d_i\geq\mathrm{thr}} \left[ \log\left(\int d\Omega\, R_\Omega p(\Omega|d_i)\right) + \log\left(\Delta t \mathcal{N}\right) \right]
\end{align}
We note that $R_o = \int d\Omega R_\Omega$ sets the overall rate of signals detectable in our detectors.
This also shows that inference about $R_\Omega$ can be performed with knowledge of the a posteriori skymaps from each detection ($p(\Omega|d_i)$) and overall measures of the exposure as a function of $\Omega$ integrated over time ($\int dt \mathcal{N} p_\Omega$).
If we assume an isotropic distribution ($R_\Omega = \text{constant}$), we obtain the expected inference for the overall rate of signals $R_o$.

We also note that, because $R_\Omega$ only appears within inner products (integrals over $\Omega$), we can replace it by sums over spherical harmonics such that $R_\Omega = \sum\limits_{l,m} a_{lm} Y_{lm}(\Omega)$.
Thus,
\begin{equation}
    \log p(\mathrm{data}|a_{lm}) \supset - \sum\limits_{l,m} a_{lm} E_{lm} + \sum\limits_{i|d_i\geq\mathrm{thr}} \log\left(\sum\limits_{lm} a_{lm} P_{lm}^{(i)} \right)
\end{equation}
where $E_{lm}$ are the spherical harmonic coefficients corresponding to the exposure and $P_{lm}^{(i)}$ are the spherical harmonic coefficients corresponding to each event's posterior distribution.
Special care must be taken to guarantee that $R(\Omega)\geq0\ \forall\ \Omega$, which can place complicated joint restrictions on the $a_{lm}$.

%------------------------

\subsection*{Analytic regression of small (perturbative) anisotropies}

Let us assume that $R_\Omega$ is well described by a simple model $R_o(\Omega)$, perhaps containing only a few spherical harmonics or otherwise describing only large-scale features.
We then consider small perturbations to the simple model so that
\begin{equation}
    \left. R_\Omega = R_o(\Omega)\left(1+\varepsilon(\Omega)\right) \ \right| \ \varepsilon \ll 1 \ \forall \ \Omega
\end{equation}
This yields
\begin{align}
    \log p(\mathrm{data}|R) \supset & \left( - \int d\Omega R_o \int dt \mathcal{N}p_\Omega + \sum\limits_{i|d_i\geq\mathrm{thr}} \left( \log\left[ \int d\Omega R_o \mathcal{N}p_\Omega \Delta t \right] \right) \right) \nonumber \\
                                    & \quad \quad \quad \quad + \left( \int d\Omega\, \varepsilon R_o \left[ - \int dt \mathcal{N} p_\Omega + \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i) \right] \right) \nonumber \\
                                    & \quad \quad \quad \quad \quad \quad \quad \quad - \left( \frac{1}{2}\int d\Omega d\Omega^\prime \varepsilon(\Omega) \left[ R_o(\Omega) R_o(\Omega^\prime) \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i) p(\Omega^\prime|d_i) \right] \varepsilon(\Omega^\prime) \right) \nonumber \\
                                    & \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad + O\left(\varepsilon^3\right)
\end{align}
We note that, in this approximation, the likelihood is a well-behaved Gaussian in $\varepsilon$ and therefore amenable to analytic priors.
Specifically,
\begin{align}
    0 & \leq \left[\int d\Omega \varepsilon R_o \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i)\right]^2 \nonumber \\
      & = \int d\Omega d\Omega^\prime \varepsilon(\Omega) \varepsilon(\Omega^\prime) \left[ R_o(\Omega) R_o(\Omega^\prime) \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i) p(\Omega^\prime|d_i \right] \\
      & = \int d\Omega d\Omega^\prime \varepsilon(\Omega) \varepsilon(\Omega^\prime) P(\Omega, \Omega^\prime)
\end{align}
which implies that $P(\Omega, \Omega^\prime)$ is positive semi-definite and therefore $P^{-1} = \mathrm{cov}\left(\varepsilon(\Omega), \varepsilon(\Omega^\prime)\right)$ is also positive semi-definie.

As a purely pedagogical note, we examine the linear cofactor for $\varepsilon$
\begin{equation}\label{eq:linear cofactor}
    R_o \left( - \int dt \mathcal{N} p_\Omega + \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i)\right)
\end{equation}
The first term is the Poisson factor accounting for how much exposure we have in any particular direction.
All else being equal, if the exposure increases in a direction without more associated detections, the anisotropy is infered to be negative ($\varepsilon < 0$).
Similarly, if there is an excess of detections infered from a certain direction without an increased exposure, the anisotropy is infered to be positive ($\varepsilon > 0$).
We also note that the intuitive notion of simply ``adding posteriors'' to look for excesses emerges naturally in the linear approximaiton, although it is too naive for the more general inference.

To infer the posterior process for $\varepsilon$, we can assume a Guassian Process (GP) prior for $\varepsilon$ with some covariance: $\varepsilon \sim \mathcal{N}\left(\mathrm{mean}=0;\ \mathrm{cov}=\Xi\right)$.
A common choice might be the squared-exponential covariance kernel such that
\begin{equation}
    \left. \text{cov}(\varepsilon, \varepsilon^\prime) = \sigma^2 \exp \left[ -\frac{\left(\Delta \theta\right)^2}{2l^2}\right] \quad  \right| \ \Delta \theta = \cos^{-1}\left(\cos\theta\cos\theta^\prime + \sin\theta\sin\theta^\prime\cos(\phi-\phi^\prime)\right)
\end{equation}
If we wish to avoid introducing a length scale in our prior (i.e.: we're interested in measureing clustering), we can take the limit $l \rightarrow 0$ to obtain a ``white noise'' prior instead.
However, maximizing the associated posterior as a function of $l$ may be a natural way to infer length scales in the data.

Assuming the GP prior and completing the square yields analytic inferences for $\epsilon$ at whatever resolution is desired along with error estimates.
Furthermore, because we assume $\varepsilon \ll 1 \ \forall \ \Omega$, zero-mean Gaussian priors on $\varepsilon$ are not unreasonable.
To wit, we obtain
\begin{equation}
    p(\varepsilon|\mathrm{data}, R_o) \sim \mathcal{N}\left( \mathrm{mean}=\int d\Omega^\prime \Gamma(\Omega, \Omega^\prime) A(\Omega^\prime);\ \mathrm{cov}=\Gamma^{-1}\right)
\end{equation}
where
\begin{align}
    A(\Omega) & = R_o\left( -\int dt\mathcal{N}p_\Omega + \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i) \right) \\
    \Gamma(\Omega, \Omega^\prime) & = \Xi^{-1} + R_o(\Omega) R_o(\Omega^\prime) \sum\limits_{i|d_i\geq\mathrm{thr}} p(\Omega|d_i)p(\Omega^\prime|d_i)
\end{align}
and the posterior's normalization depends on $R_o$.

Furthermore, because $\varepsilon\ll1$, we should be able to infer $R_o$ independently of $\varepsilon$ and then simply marginalize over it here.
\begin{equation}
    p(\varepsilon|\mathrm{data}) = \int dR_o\, p(\varepsilon|\mathrm{data},R_o)p(R_o|\mathrm{data}) \propto p(\varepsilon) \int dR_o\, p(\mathrm{data}|R_o, \varepsilon)p(R_o)
\end{equation}
Alternatively, we can analytically marginalize over $\varepsilon$ to derive a likelihood for $R_o$ alone, from which we can sample $R_o$ and then use that empirical distribution to make inferences about $\varepsilon$.
\begin{equation}
    p(R_o|\mathrm{data}) \propto p(R_o) \int \mathcal{D}\varepsilon\, p(\mathrm{data}|R_o, \varepsilon)p(\varepsilon)
\end{equation}
This has the advantage of letting us quickly, and quasi-analytically, obtain posterior processes for $\varepsilon$ using already published estimates of $R_o$, exposure estimates, and posterior skymaps for individual detections alone.

We also note that we can examine how informative the data is by investigating the covariance matrix for $\varepsilon$.
For instance, we note that the covariance matrix is inversely proportional to the number of detected events (roughly), meaning the side of confidence regions should scale as $\propto 1/\sqrt{N_\mathrm{events}}$.
This will immediately tell us whether our approximation $\varepsilon\ll1\ \forall\ \Omega$ can be justified by the likelihood, or whether the uncertainties are large enough that any constraints will come from the prior alone.

\subsubsection*{model complexity and null eigenvectors}

To determine how informative the data can be in our perturbative analysis, we examine the eigenvalues of $P(\Omega, \Omega^\prime) = R_o(\Omega) R_o(\Omega^\prime) \sum\limits_i p(\Omega|d_i) p(\Omega^\prime|d_i)$.
Indeed, this matrix appears to have an extremely large number of null eigenvectors.
Although this has not been demonstrated rigorously, it seems like the number of non-zero eigenvalues is approximately equal to the number of events included in the sum.
This means that we cannot constrain arbitrarily complex models with finite amounds of data.
It also tells us which particular correlations between different $\varepsilon(\Omega)$ can be constrained with existing data; if one allows oneself to gerrymander ``model bins'' according to the non-null eigenvectors one can define something like the ``smallest possible data-informed model.''

Again, because all our inference is based on inner products, we can alternatively specify $\varepsilon_{lm}$ and a poserteriori distributions for sets of these coefficients.
However, we expect that there will continue to be many null-eigenvectors in this representation as well.

We note that applying a non-trivial prior ($\Xi$), such as the squared-exponential Gaussian Process prior we suggested, can break these degeneracies and allow one to compute a posteriori processes for arbitrarily complicated $\varepsilon$.
However, the vast majority of ``measurements'' will be prior dominated in that case.

\subsubsection*{implications for CMB analysis}

This perturbative approach may be naturally applicable to CMB analyses looking for anisotropies.
Indeed, it may provide an analytic estimate of the a posteriori joint distribution for the $a_{lm}$, which in turn can produce a posteriori joint distributions for the $C_{lm}$.
This is particularly attractive because the observed CMB signal is dominated by a monopole and dipole with much smaller additional anisotropies; this is exactly the case we consider with a ``known model'' $R_o$ and small perturbations $\varepsilon$.

However, before claiming a perfect match we should read instrument paper describing how the CMB detectors actually record data and what it means to have ``events'' in that context.
Furthermore, the notion of $p(\Omega|d_i)$ will likely be somewhat complicated, although it may be reasonable to assume a fixed point-spread-function for each pixel.
Out likelihood also assumes that rates are low enough that the expected count above threshold in our detectors within some small time window is much less than 1.
Depending on how CMB detectors read out their data, this may be violated and we may need a more complicated likelihood that more accurately describes the detector response.

%-------------------------------------------------
\end{document}


\documentclass{article}
\usepackage{packages}
\usepackage{commands}
\graphicspath{{img/}}

%*************************************************************
\title{Explanation of "On Two Minimax Theorems in Graph"}
\author{Daniel Blévin\\George Apaaboah}
\date\today

%*************************************************************
\begin{document}
\maketitle
%\newpage
\tableofcontents
%\newpage
%************************************************************* THEOREM
\newtheorem{edmonds_theorem}{THEOREM}

%************************************************************* 1
\section{Theorems}

\begin{edmonds_theorem}[Edmonds]
The maximum number of edge-disjoint branchings (rooted at $a$)
equals the minimum number of edges in $a-$cuts.
\end{edmonds_theorem}

%************************************************************* 2
\section{Definitions}

\subsection*{Edge-disjoint branchings}
Two branching are edge-disjoint if they do not have any internal edge in common.

\subsection*{Branching :}

% todo : merge in one definition (later)

\paragraph{Branching One}
In a directed graph $D = (V, A)$ a branching is a set of arcs not containing
circuits s.t. each node of $D$ is entered at most by one arc in $A'$.
(So the arc in $A'$ make up a forest). % A or A' ???

\paragraph{Branching Two} {
A branching $B$ is an arc set in a digraph $D$ that is a forest such that every node of $D$
is the head of at most one arc of $B$.
A branching that is a tree is called an arborescence.
A branching that is a spanning tree of $D$ is called a spanning arborescence of $D$.
Clearly, in a spanning arborescence B of $D$ every node of $D$ is the head of one arc of $B$
except for one node.
This node is called the root of $B$.
If $r$ is the root of arborescence $B$ we also say that $B$ is rooted at $r$ or $r-$rooted.
}

\paragraph{R-branching}
For a subset $R \subset V$, an $R-$branching in $G$ is a spanning forest $B \subset G$ in
which all vertices of $V - R$ have outdegree precisely $1$.

\paragraph{r-branching}
When $R$ just consists of a single vertex $r$, we refer to $B$ as an $r-$branching.

\subsection*{k-connected}
A graph $G$ (digraph $D$) is called $k-$connected ($k-$diconnected) if every pair
s, t of nodes is connected by at least $k$ $[s, t]-$paths ($(s, t)-$dipaths) whose sets of
internal nodes are mutually disjoint.

\subsection*{a-cut}
A $a-$cut of $G$ determined by a set $S \subset V(G)$ is the set of
edges going from $S$ to $V(G) - S$.
It will be denoted by $\Delta_G(S)$.
We also set that $\delta_G(S) = |\Delta_G(S)|$.

\subsection*{r-Cuts and r-Arborescences}

Consider a connected digraph $(N, A)$ with $r \in N$ and nonnegative
integer arc lengths $l_a$ for $a \in A$. An $r-$arborescence is a minimal arc
set that contains an $rv-$dipath for every $v \in N$.
It follows that an $r-$arborescence contains $|N| - 1$ arcs forming a spanning tree and each
node of $N - {r}$ is entered by exactly one arc.
The minimal transversals of the clutter of r-arborescences are called $r-$cuts.

~

We define a clutter C to be a family $E(C)$ of subsets of a finite ground
set $V(C)$ with the property that $S_1 \nsubseteq S_2$ for all distinct $S_1, S_2 \in E(C)$.
$V(C)$ is called the set of vertices and $E(C)$ the set of edges of $C$.

\subsection*{r-cut 2}

An r-cut in a digraph is an edge set $\delta^+(X)$ for some $X \subset V(G)$ with $r \in X$.

\subsection*{r-arborescence 2}

an Arborescence in a digraph $D = (V, A)$ is a set $A'$ of arcs making up a spanning tree
such that each node of $D$ is entered by at most one arc in $A'$.
It follows that there is exactly one node r that is not
entered by any arc of $A'$. This node is called the root of $A'$, and $A'$ is called
rooted in $r$, or an $r-$arborescence.

\subsection*{A note on orientation}
A rooted tree is a tree in which one vertex has been designated the root.
The edges of a rooted tree can be assigned a natural orientation, either away from
or towards the root, in which case the structure becomes a directed rooted tree.
When a directed rooted tree has an orientation away from the root,
it is called an arborescence, branching, or out-tree;
when it has an orientation towards the root,
it is called an anti-arborescence or in-tree.

%************************************************************* 2
\section{Examples}

\subsubsection*{Simple branching}

\insertTikzFigure{1}{branchingExemple_base}
{A digraph $G=(A, V)$}
{tikz:branchingExemple_base}

\insertTikzFigure{1}{branchingExemple_simple}
{A branching of $G$ routed at $a$.}
{tikz:branchingExemple_simple}

\subsubsection*{Edge disjoint branching}

\insertTikzFigure{1}{branchingExemple_disjoint}
{Two edge-disjoint branching routed respectively at $a$ and $d$.}
{tikz:branchingExemple_disjoint}

\subsubsection*{Edge disjoint a-routed branching}

\insertTikzFigure{1}{branchingExemple_arouted}
{Two edge-disjoint $a$-routed branching.}
{tikz:branchingExemple_arouted}

\subsubsection*{a-cut}

\end{document}


\documentclass[12pt]{article}
\usepackage{graphicx}
\usepackage{enumerate}

\author{Aaron Song s267807}
\title{CW2}
\date{\today}

\begin{document}
\maketitle

\section{Task 1}

1. An entry of data in this problem is defined as $(x,y,label)$, where $x$ and $y$ is the inputs and $label$ is the output. Define:
\begin{description}
    \item[data] Data: x:number, y:number, label: number
    \item[neural network] A neural network in this task is an object with a function that takes a pair of numbers of outputs a number, so functionally define Apply: number->number->number and NeuralNetwork: { Apply }.
    \item[loss function] Loss(nn: NeuralNetwork, d: Data) = $((\textrm{Apply d.x d.y)-d.error)}^2$
    \item[fitness functtion] The fitness of a neural network is the average loss on the specific dataset. $$Ftiness(nn: NeuralNetwork, ds: Data[]) = \frac{\sum_{i=1}^{\textrm{ds.Length}}Loss(nn, ds[i])}{ds.Length}$$
\end{description}

\noindent 2. A [-10, 10] is enough for this question.

\noindent 3. Two hidden layers are used, with the first 5~7 neurons and the second 2 neurons. If only one hidden layer is permitted, 7 neurons are prefered to get a better result, as shown in \ref{7n}.
\begin{figure}[!ht]
    \centering
    \includegraphics[width=\textwidth]{1.jpg}
    \caption{A hidden layer with 7 neurons}
    \label{7n}
\end{figure}

\noindent 4.
The learning result is much better when non-linear input are involved. For this question specifically, a spiral data is generated by a formula $r=k\theta$ where $k>0, \theta>0$. When translating the polar coordinate into a Cartisean coordinate, it's
\begin{equation}
\label{equ:task1-target-func}
\sqrt{x^2+y^2}=k(2n\pi+\textrm{atan2}(x,y))
\end{equation}
, where $n\in Z$ and atan2 is the arctan function defined by most common programming language where the range is $[0,2\pi)$. In order to expand the aforementioned equation into a plain form, atan2 can be approximately translated into $\arctan$, and according to Tylor expansion,
\begin{equation}
    \frac{\textrm{d}\arctan x}{\textrm{d}x}=\frac{1}{x+1}\\
\arctan x=x-\frac{1}{3}x^3+\frac{1}{5}x^5-\ldots
\end{equation}
. Curtailling high order terms,
$$
\arctan x=x-\frac{1}{3}x^3\\
x^2+y^2=an+b(x-\frac{1}{3}x^3)^2
$$
where $a=\frac{4k^2}{\pi^2},b=k^2$. Curtailling high order terms again,
$$
x^2+y^2=an+bx
$$
We can see that $x^2$, $y^2$, terms are presented here. To fully simulate the spiral data generation function \ref{equ:task1-target-func}, $\sin x$ and $\sin y$ may also be included given the Tylor expansion:
$$
\sin x=x-\frac{1}{3!}x^3+\frac{1}{5!}x^5-\ldots
$$

\noindent 5. Many PSO parameters have an effect to this particular problem.
\begin{description}
    \item[learning rate] The learning rate decides how fast the weights and biases of the neural network changes. A moderate value (0.03 or 0.1) yields good output, otherwise if it's too high ($\geq 1$) the training loss and the test lost will fluctuate too fast and fail to converge to a proper local best. If too small ($\leq 0.0003$), the weights and the biases barely change. A global best may still present itself after enough long time, but that may take too many epochs.
    \item[activation function] Activation function is used to discretse the floating-number output of the neural network into a number. The default activation tanh in this problem suits very well, and sigmoid also fits good despite longer training time may be required. RBF and ReLU are also acceptable. Sin doesn't fit well since the radius is not constant, and linear doesn't work at all.
    \item[regularisation]
    \item[feature] The features in this problem are the soul source of non-linear input and decide the form of the neural network; the number of layers and the number of neurons on each layer depend only the linear combination of the input features. As memtioned in the previous question, $x_1^2$ and $\sin x$ improve the learning result a lot compared to a purely linear model. I also tried $x_1^3$ and $x_2^3$, but the result is not satisfying.
    \item[nn shape] Every neural node blends all inputs linearly and yields one single value. Mathematically, suppose there are $x$ layers (including the input layer) of nodes in the neural network and on layer $i$ there are $k[i]$ nodes ($0\leq i<x$), then node $b$ on layer $0<a\leq x$ $n_{a,b}$ takes a vector
    $X=(x_0,x_1,\ldots,x_{k[a-1]})$ as input and output $A\cdot X+B$, where $A$ stands for the weight between $a-1$ layer and node $n_{a,b}$ and $B$ represents the bias of node $n_{a,b}$.\\
    In other words, the input layer is defined by some common function $y=x$, $y=x^2$, $y=\sin x$, and nodes in a following layers form a linear combination of the last layer.

\end{description}

\section{Task 2}
1. There're seven input nodes so the encoding of the input layer would be a binary string with a length of 7; the maximum number of layers is 6 and on each layer the limit of the number of neurons is 8, so a layer can be encoded in a binary string with a length of 3. In the first layer (also the input layer), every node is different because each one represents a different input function (it is however possible to have to input nodes with the same function, but it would be meaningless); for other layers, every node (neuron) is the same. So the neural network can be represented as:
$$
{i_0i_1\ldots i_7,\ l_{1_0}l_{1_1}l_{1_2},\ l_{5_0}l_{5_1}l_{5_2},\ \ldots,\ l_{6_0}l_{6_1}l_{6_2}}
$$
.

\end{document}


% !TeX encoding = UTF-8
% !TeX spellcheck = LaTeX
% !TeX program = XeLaTeX
%

% Please compile by 'xelatex -shell-escape pre.tex'

\documentclass[UTF-8]{beamer}

\makeatletter
\let\@@magyar@captionfix\relax
\makeatother

\usepackage{graphicx}
\usepackage{tikz}
\usepackage{amsmath,amssymb}
\usepackage{bm}
\usepackage{extarrows}
\usepackage{newtxtext}
\usepackage{minted}
\undef\checkmark
\usepackage{dingbat}
\usepackage{listings}
\usepackage{caption}
\usepackage{xcolor}

\usetheme{CambridgeUS}
\usecolortheme{crane}
\usefonttheme{professionalfonts}
\setbeamertemplate{footjoline}[frame number]
\useoutertheme{infolines}

\definecolor{bg}{rgb}{0.95,0.95,0.95}
\renewcommand{\listingscaption}[1]{\begin{center}CODE: #1\end{center}\vspace{-20pt}}
\setminted{
    fontsize=\small,
    bgcolor=bg, frame=lines,
    mathescape, breaklines, breakanywhere,
    breaksymbolleft=\raisebox{0.8ex}{\small\reflectbox{\carriagereturn}},
    breaksymbolright=\small\carriagereturn
}

\setbeamercolor{thxcolor}{fg=white,bg=darkred}

\usetikzlibrary{shapes.geometric, arrows}
\tikzstyle{startstop} = [rectangle, rounded corners, minimum width=2.5cm, minimum height=1cm, text centered,
draw=black, fill=red!30, font=\bf]
\tikzstyle{io} = [trapezium, trapezium left angle=70, trapezium right angle=110, minimum width=2.5cm, minimum height=1cm,
text centered, draw=black, fill=blue!30, font=\bf]
\tikzstyle{process} = [rectangle, minimum width=2.5cm, minimum height=1cm, text centered,
draw=black, fill=orange!30, font=\bf]
\tikzstyle{decision} = [diamond, minimum width=2.5cm, minimum height=1cm, text centered,
draw=black, fill=green!30, font=\bf]
\tikzstyle{arrow} = [thick, ->, >= stealth]
\tikzstyle{line} = [thick]

\title{MiniProver}
\subtitle{A coq-like proof assistant}
\institute{Peking University}
\author{Zhenwen Li, Sirui Lu, Kewen Wu}
\date{\today}

\begin{document}
\frame{\titlepage}

\section{Type System}
\subsection{Calculus of Inductive Constructions}
\begin{frame}{$\lambda$-cube}
    \centering
\begin{tikzpicture}[node distance=4.5cm]
    \node (la) {$\lambda\!\to$};
    \node (l2) [above of=la] {$\lambda 2$};
    \node (lp) [right of=la] {$\lambda P$};
    \node (lw') [right of=la, xshift=-1cm, yshift=1.5cm] {$\lambda \underline{\omega}$};
    \node (lw) [above of=lw'] {$\lambda \omega$};
    \node (lc) [right of=lw] {$\lambda C$};
    \node (lpw) [right of=lw'] {$\lambda P\underline{\omega}$};
    \node (lp2) [above of=lp] {$\lambda P2$};

    \footnotesize

    \path[->, thick, >=stealth] (lw') edge (lw) edge (lpw);
    \node[fill=white, minimum size=6mm] at (3.5,4.5) {};
    \node[fill=white, minimum size=6mm] at (4.5,1.5) {};
    \path[->, thick, >=stealth]
        (la) edge node[below] {Type depends on Term} (lp)
            edge node[sloped,yshift=2mm] {Term depends on Type} (l2)
            edge node[sloped,yshift=2mm] {Type depends on Type} (lw')
        (lp) edge (lpw) edge (lp2)
        (l2) edge (lp2) edge (lw)
        (lw) edge (lc)
        (lp2) edge (lc)
        (lpw) edge (lc);
\end{tikzpicture}
\end{frame}

\begin{frame}{Example and \textbf{CIC}}
\begin{itemize}
\item Term depends on Type\\
    $\tt\lambda T:Type.\ \lambda x:T.\ x\quad :\quad \Pi T:Type.\ T\to T$
\item Type depends on Type\\
    $\tt\lambda T:Type.\ T\to T\quad :\quad Type\to Type$
\item Type depends on Term\\
    $\tt\lambda n:nat.\ S\ n\quad :\quad nat\to Type$
        \vspace{10pt}
\item $\lambda C$ + \textit{Definition} $\Rightarrow$ $\lambda D$.\\
\item $\lambda D$ + \textit{Inductive Type} $\Rightarrow$ \textbf{CIC}.
\end{itemize}
\end{frame}

\subsection{Key Typing Rule}
\begin{frame}[fragile]{Inductive Type}
$$
\tt Ind\ [{\it p}]\ (\Gamma_I:=\Gamma_C)
$$
\vspace{-10pt}
\begin{itemize}
\item $\it p$ : Number of parameters.
\item $\tt \Gamma_I$ : Inductive type.
\item $\tt \Gamma_C$ : Constructors of the inductive type.
\end{itemize}
\vspace{10pt}
\begin{minted}{coq}
Inductive lst (T : Type) : Type :=
    | nil : lst T
    | cons : T -> lst T -> lst T
\end{minted}
$$
\small
\tt Ind\ [1]\left([lst:Type\to Type]:=
\begin{bmatrix}
\tt nil:\Pi T:Type,\ lst\ T\\
\tt cons:\Pi T:Type,\ T\to lst\ T\to lst\ T
\end{bmatrix}\right)
$$
\end{frame}

\begin{frame}[fragile]{Match}
$$\tt match\ {\it t}\ as\ {\it x_0}\ in\ {\it namelist}\ return\ {\it returntype}\ with\ [{\it equation}]$$
\begin{itemize}
    \item $\it t$ : A term of inductive type.
    \item $\it namelist$ : Arguments of the inductive type.
    \item $\it equation$ : Different constructors of the inductive type.
\end{itemize}

\begin{minted}{coq}
Inductive eq (T : Type) (x : T) : T -> Type :=
    | eq_refl : eq T x x

fun (n : nat) (m : nat) (e : eq nat n m) =>
    match e in (eq _ _ y) return (eq nat y n) with
    | eq_refl _ _ => ...
\end{minted}
\end{frame}

\subsection{Termination}
\begin{frame}[fragile]{Termination Check}
\begin{minted}[escapeinside=<>]{coq}
Fixpoint plus (<\colorbox{green}{n}> m : nat) : nat :=
    match <\colorbox{green}{n}> with
    | O => m
    | S p => S (plus <\colorbox{green}{p}> m)

Fixpoint plus' (<\colorbox{green}{n}> <\colorbox{red}{m}> : nat) : nat :=
    match <\colorbox{green}{n}> with
    | O => m
    | S p => S (plus <\colorbox{red}{m}> <\colorbox{green}{p}>)
\end{minted}
\begin{alertblock}{Criterion}
    Descending on at least one variable.
\end{alertblock}
\end{frame}

\subsection{Inductive Positivity}
\begin{frame}[fragile]{Positivity Check}
\begin{minted}[escapeinside=<>]{coq}
Inductive ill : Type :=
    | malf : (ill -> ill) -> ill

Definition extract (t : ill) : ill :=
    match t with
    | malf f => f t

    extract (malf extract)  (* not terminating *)
\end{minted}
\begin{alertblock}{Criterion}
    Types of constructors satisfy \textbf{positivity condition} for name of inductive type.
\end{alertblock}
\end{frame}

\section{Top Level}
\begin{frame}[fragile]{Build Term and Type for Inductive Definition}
\begin{exampleblock}{Intuition}
    View mathematical induction as building a term for inductive definition.
\end{exampleblock}

\begin{minted}[escapeinside=<>]{coq}
Inductive nat : Type := O : nat | S : nat -> nat

fun (P : nat -> Type) (f : P O)
        (f0 : forall n : nat, P n -> P (S n))
    fix F (n : nat) : P n :=
        match n as n0 in (nat) return (P n0) with
        | O => f
        | S n0 => f0 n0 (F n0)
:
forall P : nat -> Type, P O ->
    (forall n : nat, P n -> P (S n)) ->
        forall n: nat, P n
\end{minted}
\end{frame}

\section{Evaluation}
\begin{frame}{Evaluation (Conversion)}
\begin{itemize}
    \item $\beta$-reduction : Reduce \textit{application}
    \item $\iota$-reduction : Reduce {\tt match}
    \item $\delta$-reduction : $\tt Definition\ x\ :=\ u$ \quad $\Rightarrow$\quad $\tt x\to u$
    \item $\zeta$-reduction : $\tt let\ x\ :=\ u\ in\ t$ \quad $\Rightarrow$\quad $\tt [x\to u]t$
    \item $\eta$-expansion : $\tt t:\forall x:T,U$ \quad $\Rightarrow$\quad $\tt \lambda x:T.\ (t\ x)$
\end{itemize}
\end{frame}

\section{Proof Handling}
\begin{frame}{Proof Handling}
\begin{itemize}
\item Build proof object.
\item Navigate : Undo.
\item Switch mode : Proof, Qed, Abort.
\item Request info : Print.
\end{itemize}
\end{frame}

\section{Tactic}
\begin{frame}{Tactics}
\begin{itemize}
\item Intro, Intros : $\tt \vdash A\to B$ $\Rightarrow$ $\tt A\vdash B$
\item Apply : $\tt A\to B\vdash B$ $\Rightarrow$ $\tt A\to B\vdash A$
\item Exact : Construct the term manually
\item Reflexivity : $\tt eq\ T\ x\ y$ $\Rightarrow$ check if $\tt x=_{\beta\delta\iota\eta\zeta}y$
\item Split : $\tt \vdash P_1\wedge P_2$ $\Rightarrow$ $\tt \vdash P_1,P_2$
\item Induction : Classified sub-proofs with induction hypothesis
\item Equivalence : Build equivalence relations inside inductive term
\end{itemize}
\end{frame}

\begin{frame}{Tactics}
\begin{itemize}
\item Simpl : Simplify into human-readable goal
\item Destruct : Classified sub-proofs without induction hypothesis
\item Left, Right : $\tt \vdash P_1\vee P_2$ $\Rightarrow$ $\tt \vdash P_1$ or $\tt\vdash P_2$
\item Symmetry : $\tt eq\ T\ x\ y\vdash eq\ T\ y\ x$
\item Rewrite : $\tt eq\ T\ x\ y$ $\Rightarrow$ $\tt x\to y$ or $\tt y\to x$
\item Unfold : Replace term with $\beta\iota$-normal form
\item Exists : $\tt \vdash\exists x,\ P\ x$ $\Rightarrow$ $\tt x_0\wedge(P\ x_0)$
\end{itemize}
\end{frame}

\section*{Thanks}
\begin{frame}
\LARGE
\begin{beamercolorbox}[center,ht=3em]{thxcolor}
\vspace{1em}
\Huge Thanks!
\end{beamercolorbox}
\end{frame}\end{document}


\input{"/Users/brandonwilliams/Documents/LaTeX Includes/hwpreamble.tex"}
\input{"/Users/brandonwilliams/Documents/LaTeX Includes/extrapackages.tex"}
\input{"/Users/brandonwilliams/Documents/LaTeX Includes/extracommands.tex"}

\begin{document}

\title{\Large Lee's Variant of Khovanov Homology}
\author{\large Brandon Williams}

\maketitle

\section{Construction of Khovanov Homology}

Let $V$ be the graded $\mathbb Q$-vector space generated by two elements $v_\pm$ with gradings $p(v_\pm) = \pm 1$. We define a $(1+1)$-TQFT $\mathcal A$ by defining it on the set of generators of cobordisms
\[
\mathcal A \left( \smallcircle \right) = V
\]
\[
\mathcal A\left( \smallpairofpants \right) = m : V \otimes V \longrightarrow V  \ \ \ \ \ \ \ \mathcal A \left( \smallupsidedownpairofpants \right) = \Delta : V \longrightarrow V \otimes V
\]
\[
\mathcal A \left( \smallcap \right) = i : \mathbb Q \longrightarrow V  \ \ \ \ \ \ \ \mathcal A \left( \smallcup \right) = \epsilon : V \longrightarrow \mathbb Q
\]
where the maps $m,\Delta,\epsilon,i$ are given by
\begin{align}
\label{mdei}
\begin{array}{lcclcclcclcc}
	m(v_+ \otimes v_+)     = v_+ & & & \Delta(v_+) = v_+ \otimes v_- + v_- \otimes v_+ & & &  i(1) = v_+ & & & \epsilon(v_+) = 0 \\
	m(v_\pm \otimes v_\mp) = v_- & & &  \Delta(v_-) = v_- \otimes v_-                  & & &             & & & \epsilon(v_-) = 1 \\
	m(v_- \otimes v_-)     = 0
\end{array}
\end{align}
The maps $m$ and $\Delta$ are commutative and cocommutative, and $i$ and $\epsilon$ satisfy the relations of a unit and counit. It is also easy to see that
\begin{equation}
\label{frobenius condition}
\Delta \circ m = (m \otimes \id) \circ (\id \otimes \Delta) = (\id \otimes m) \circ (\Delta \otimes \id)
\end{equation}
so these maps make $V$ into a commutative and cocommutative Frobenius algebra, which implies that $\mathcal A$ is well-defined.

Let $L$ be a link diagram with $k$ crossings, and fix a labeling of the crossings by numbers 1 through $k$. Each vector $v \in [0,1]^k$ consisting of only 1's and 0's (i.e. vertices of the $k$-dimensional cube) determine a resolution of $L$ by resolving the $i$-th crossing according to the $i$-th component of $v$ (see Figure~\ref{crossing resolution}). Let $L_v$ denote the associated resolution of $L$, which is just some disjoint collection of circles.
\begin{figure}[t]
\centering
\[
\xy0;/r0.5pc/:
(-6,6)*{}="tl";
(6,6)*{}="tr";
(-6,-6)*{}="bl";
(6,-6)*{}="br";
"tl";"tr" **\crv{(0,1)};
"bl";"br" **\crv{(0,-1)};
(0,-10)*{\text{0-resolution}};
\endxy
\qquad \qquad
\xy0;/r0.5pc/:
(6,6)*{}="tl";
(-6,6)*{}="tr";
(6,-6)*{}="bl";
(-6,-6)*{}="br";
{\ar@{-}|{\hole \; \hole \; \hole \; \hole \; \hole \; \hole } "bl";"tr"};
{\ar@{-} "br";"tl"};
(0,-10)*{\text{crossing}};
\endxy
\qquad \qquad
\xy0;/r0.5pc/:
(-6,6)*{}="tl";
(6,6)*{}="tr";
(-6,-6)*{}="bl";
(6,-6)*{}="br";
"bl";"tl" **\crv{(-1,0)};
"br";"tr" **\crv{(1,0)};
(0,-10)*{\text{1-resolution}};
\endxy
\]
\caption{Ways to resolve a crossing}
\label{crossing resolution}
\end{figure}

If two vertices $v$ and $w$ of the cube $[0,1]^k$ share an edge, then their coordinates differ in precisely one place, say the $i$-th coordinate, and we can suppose $v_i=0$ and $w_i=1$. In this case we will say the edge of $[0,1]^k$ which contains these vertices is directed from $v$ to $w$. If $e$ is the edge from $v$ to $w$, we will let $C_e : L_v \rightarrow L_w$ denote the standard cobordism by taking the identity cobordism outside some small neighborhood of $i$-th crossing and taking the appropriate saddle cobordism from the 0-resolution to the 1-resolution around the $i$-th crossing (see Figure~\ref{saddle cobordism}).

\begin{figure}[t]
\centering
\[ \saddlecobordism \]
\caption{Saddle cobordism between 0- and 1-resolutions}
\label{saddle cobordism}
\end{figure}

We can now define the Khovanov complex of the link $L$ as the vector space
\[ \CKh(L) = \bigoplus_{v \in \lcb 0,1 \rcb^k} \mathcal A(L_v) \]
There is another way of interpreting $\CKh(L)$. Let us write $V = \mathbb Q v_+ \oplus \mathbb Q v_+$, then $V^{\otimes n}$ is the direct sum of all vector spaces of the form $\mathbb Q v_1 \otimes \cdots \otimes \mathbb Q v_n$ where $v_i = v_\pm$. On the other hand, given a resolution $L_v$ of $L$ consisting of $n$ circles, we can decorate each circle with either $v_i = v_+$ or $v_i = v_-$, and associate to this decoration the vector space $\mathbb Q v_1 \otimes \cdots \otimes \mathbb Q v_n$. Therefore $\CKh(L)$ can be thought of as the direct sum of the vector spaces associated to all possible decorations of all possible resolutions of $L$.

For a vector $v \in \lcb 0,1 \rcb^k$, let $c_0(v)$ and $c_1(v)$ denote the number of 0's and 1's in $v$ respectively. It is clear that there are exactly $c_0(v)$ edges of $[0,1]^k$ directed from $v$, so for each $1 \leq i \leq c_0(v)$ let $C_{e_i}$ denote the cobordism associated to the edge that changes the $i$-th zero in $v$ to a one. Then we can define the differential $d : \CKh(L) \rightarrow \CKh(L)$ for $x \in \mathcal A(L_v)$ by
\begin{equation}
\label{khovanov d}
d(x) = \sum_{i=1}^{c_0(v)} (-1)^{\sum_{j<i} v(i)} \mathcal A(C_{e_i})(x)
\end{equation}
In the exponent of $-1$ we are using the notation $v(i)$ to denote the $i$-th coordinate of $v$.

\begin{prop}
\label{khovanov d^2 = 0}
$d^2 = 0$.
\end{prop}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\comment{
\begin{proof}
\comment{
Let $x \in \mathcal A(L_v)$ for some $v \in \lcb 0,1 \rcb^k$, and let $x_i = \mathcal A(C_{e_i})(x)$, where $C_{e_i}$ are the cobordisms discussed in the definition of \eqref{khovanov d}, so that $d(x) = \sum_i \pm \, x_i$. Each $x_i$ lies in $\mathcal A(L_{w_i})$, where $w_i$ is obtained from $v$ by changing the $i$-th zero to a one. Similarly $d(x_i) = \sum_j \pm \, y_{ij}$, where $y_{ij}$ lies in $\mathcal A(L_{z_{ij}})$ and $z_{ij}$ is obtained from $w_i$ by changing the $j$-th zero to a one. We now have that $d^2(x) = \sum_{i,j} \pm \, y_{ij}$.

We claim that $y_{ij} = y_{ji}$.

Finally we claim that $y_{ij}$ and $y_{ji}$ appear in $d^2(x)$ with opposite signs.

\todo{finish}
}
\end{proof}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

The proof of \ref{khovanov d^2 = 0} is completely based on the fact that the maps $m$ and $\Delta$ are (co)associative and (co)commutative, and satisfied the Frobenius condition \eqref{frobenius condition}. If our TQFT $\mathcal A$ had been defined with other multiplication and comultiplication maps that satisfied these properties, we could still define a map $d$ and find that $d^2 = 0$.

We define the Khovanov homology vector space to be $\Kh(L) = \ker d / \image d$. Right now $\CKh$ is graded by elements of $\lcb 0,1 \rcb^k$, so we introduce some numerical degrees by defining the homological degree of $x \in \mathcal A(L_v)$ to be $\gr(x) = c_1(v) - n_-$, where $n_-$ is the number of negative crossings in the link diagram.

\begin{prop}
\label{d raises hom degree}
The Khovanov differential raises the homological degree by one.
\end{prop}
\begin{proof}
In the definition of the differential \eqref{khovanov d} we see that $\mathcal A(C_{e_i})(x) \in \mathcal A(L_w)$, where $w$ is obtained from $v$ by changing the $i$-th zero to a one. So, $d(x)$ is a sum of elements of degree $c_1(w)-n_- = c_1(v)+1-n_- = \gr(x)+1$, hence $d$ raises the homological degree by one.
\end{proof}

Recall that $V$ is generated by two elements $v_\pm$ of degrees $p(v_\pm) = \pm 1$. We can extend this grading to $V^{\otimes n}$ by $p(v_1 \otimes \cdots \otimes v_n) = \sum p(v_i)$.

\begin{prop}
\label{d lowers p degree}
If $e$ is an edge of $[0,1]^k$, $C_e$ the associated cobordism, and $v \in V^{\otimes n}$ is of homogeneous $p$-degree, then $p(\mathcal A(C_e)(v)) = p(v) - 1$.
\end{prop}
\begin{proof}
First we note that the maps $m,\Delta$ in \eqref{mdei} lower the $p$-grading by 1. Suppose $v = v_1 \otimes \cdots \otimes v_n$. Then for some $i$ we have that $\mathcal A(S_e)(v)$ is in two possible forms:
\[
\mathcal A(S_e)(v_1 \otimes \cdots \otimes v_n) = \begin{cases}
																										 v_1 \otimes \cdots \otimes v_{i-1} \otimes \Delta(v_i) \otimes v_{i+1} \otimes \cdots \otimes v_n \\
																										 v_1 \otimes \cdots \otimes m(v_i \otimes v_j) \otimes \cdots \otimes v_n
																									\end{cases}
\]
In both cases the overall $p$-degree lowers by one since $\Delta$ and $m$ lower the degree by 1.
\end{proof}

There is another grading we can introduce in $\CKh(L)$. If $x \in \mathcal A(L_v)$ for some $v \in \lcb 0,1 \rcb^k$, then we define the quantum degree of $x$ by
\begin{equation}
\label{q grading}
q(x) = p(x) + \gr(x) + n_+ - n_-
\end{equation}
This makes $\CKh$ and $\Kh$ into a bigraded vector spaces. If we write $\CKh^{r,s}$ we will mean that $r$ is the homological grading and $s$ is the quantum grading, and if we write only one superscript $\CKh^r$ we will mean that $r$ is the homological grading.

\begin{cor}
\label{d preserves q}
The Khovanov differential preserves the $q$-grading, i.e. if $x \in \mathcal A(L_v)$, then $q(d(x)) = q(x)$.
\end{cor}
\begin{proof}
By \ref{d lowers p degree} $d$ lowers the $p$-grading, and by \ref{d raises hom degree} $d$ raises the homological grading, so it is clear from \eqref{q grading} that $d$ preserves the $q$-grading.
\end{proof}

Therefore $\CKh(L)$ splits as a direct sum of chain complexes.

\section{Lee's Spectral Sequence}

We will now define a new $(1+1)$-TQFT $\mathcal A'$, which in turn defines a new complex $\CKh'$ and homology vector space $\Kh'$. The new functor $\mathcal A'$ still maps a circle to $V$ and the disjoint union of circles to tensor products of $V$, and $\mathcal A'$ of a cup and cap are still given by $\epsilon$ and $i$ from \eqref{mdei}. However, we change our multiplication and comultiplication induced by pairs of pants by
\[
\mathcal A\left( \smallpairofpants \right) = m' : V \otimes V \longrightarrow V  \ \ \ \ \ \ \ \mathcal A \left( \smallupsidedownpairofpants \right) = \Delta' : V \longrightarrow V \otimes V
\]
where
\begin{align}
\label{deformed md}
\begin{array}{lcclcclcclcc}
	m'(v_\pm \otimes v_\pm) = v_+ & & & \Delta'(v_+) = v_+ \otimes v_- + v_- \otimes v_+ \\
	m'(v_\pm \otimes v_\mp) = v_- & & & \Delta'(v_-) = v_- \otimes v_- + v_+ \otimes v_+
\end{array}
\end{align}
It is easy to see that these maps make $V$ into a commutative and cocommutative Frobenius algebra as before. Using $\mathcal A'$ we can define the vector space $\CKh'(L)$ and map $d' : \CKh'(L) \rightarrow \CKh'(L)$ in the same way as before
\[ CKh'(L) = \bigoplus_{v \in \lcb 0,1 \rcb^k} \mathcal A'(L_v) \]
\begin{equation}
\label{dprime}
d'(x) = \sum_{i=1}^{c_0(v)} (-1)^{\sum_{j<i} v(i)} \mathcal A'(C_{e_i})(x)
\end{equation}
Let $\Kh'(L)$ denote the homology. Since $\CKh'(L)$ is the same underlying vector spaces as $\CKh(L)$ we can define the homological grading and $q$-grading in the same way as before. Just as in \ref{d raises hom degree} we have that $d'$ raises the homological degree by one. Unfortunately $d'$ does not preserve the $q$-grading like last time (actually this turns out to be a very useful outcome).

\begin{prop}
\label{dprime respects filtration}
Let $x \in \CKh'$ be of homogeneous $q$-grading, then each term of \eqref{dprime} in $d'(x)$ has $q$-grading greater than or equal to $q(x)$.
\end{prop}
\begin{proof}
First let us take note of the behavior of $p$-gradings under $m'$ and $\Delta'$ in \eqref{deformed md}. By examination of the $p$-gradings of elements we are plugging into $m'$ and $\Delta'$, and the terms in their outputs we see that $m'$ and $\Delta'$ lowers the $p$-grading of elements by at most one.

Suppose $x = v_1 \otimes \cdots \otimes v_n \in \mathcal A'(L_v)$, where $v_i = v_\pm$. Then $d'(x)$ is a sum of terms of the form
\begin{align*}
&v_1 \otimes \cdots \otimes m'(v_i \otimes v_j) \otimes \cdots \otimes v_n \\
&v_1 \otimes \cdots \otimes \Delta'(v_i) \otimes \cdots \otimes v_n
\end{align*}
So it suffices to look at the special case of $x = v_1 \otimes v_2$. We have the following formulas for $q$-gradings
\begin{align}
\label{q-grading line 1}
q(v_1 \otimes v_2) &= p(v_1 \otimes v_2) + c_1(v) + n_+ - 2n_- \\
\label{q-grading line 2}
q(m'(v_1 \otimes v_2)) &= p(m'(v_1 \otimes v_2)) + c_1(v) + 1 + n_+ - 2n_-
\end{align}
In \eqref{q-grading line 2} we see that $p(m'(v_1\otimes v_2))$ is at most one less than $q(v_1\otimes v_2)$, but then we have added one to $c_1(v)$ since we have increased the number of 1-resolutions. Therefore the difference between \eqref{q-grading line 2} and \eqref{q-grading line 1} is greater than or equal to zero. The same argument holds for $\Delta'$, therefore each term in $d'(x)$ has $q$-grading greater than or equal to $q(x)$.
\end{proof}

That fact that $d'$ either raises the $q$-grading of elements or preserves the $q$-grading allows us to define a filtration on $\CKh'$ that is respected by $d'$. We define a filtration $F$ on $\CKh'$ by
\begin{equation}
\label{filtration}
F^s \CKh' = \bigoplus_{v \in \lcb 0,1 \rcb^k} \lcb x \in \mathcal A'(L_v) \st q(x) \geq s \rcb
\end{equation}
Clearly this is a decreasing filtration, as $F^s \CKh' \subset F^{s-1} \CKh'$, and the filtration is finite and exhaustive. By \ref{dprime respects filtration} $d'$ respects the filtration, i.e. $d'(F^s \CKh') \subset F^s \CKh'$. The filtration also respects the homological grading, i.e. $F^s \CKh'^r \subset F^{s-1} \CKh'^r$.  A ``basic principle'' of spectral sequences tells us that a graded object equipped with a differential and a filtration (such that everything is compatible) leads to a spectral sequence, as spelled out in the following theorem:

\begin{thm}
\label{Lee's spectral sequence}
There is a spectral sequence with $E_0 = \CKh$ and $E_1 = \Kh$, and the spectral sequence converges to $\Kh'$.
\end{thm}
\begin{proof}
The fact that there is a spectral sequence converging to $\Kh'$ is apparent from the ``basic principle.'' We will identify the $E_0$ and $E_1$ pages of this spectral sequence.

The $E_0$ page is simply the bigraded vector space associated to our filtered, graded object:
\begin{equation}
\label{associated bigraded vector space}
E_0^{r,s} = F^s \CKh'^r / F^{s+1} \CKh'^r
\end{equation}
Since we are dealing with vector spaces it is easy to see that
\begin{align*}
	F^s \CKh'^r / F^{s+1} \CKh'^r &= \bigoplus_v \lcb x \in \mathcal A(L_v) \st \gr(x)=r, q(x) = s \rcb \\
	                              &= \CKh'^{r,s} \\
	                              &= \CKh^{r,s}
\end{align*}
where the last equality follows since the underlying vector spaces for both complexes is the same. The map $d'$ induces a map on $E_0$ such that $d' : E_0^{r,s} \rightarrow E_0^{r+1,s}$, which can be thought of as the part of $d'$ that preserves the $q$-grading rather than raising it. Since $d'$ is expressed in terms of $m'$ and $\Delta'$, the part of $d'$ that preserves $q$-grading is determined by the parts of $m'$ and $\Delta'$ that preserves the $q$-grading. Let us determine what part of $m'$ preserves the $q$-grading.

Suppose $v_1 \otimes v_2 \in \mathcal A(L_v)$, then
\begin{align*}
q(v_1 \otimes v_2) &= p(v_1 \otimes v_2) + c_1(v) + n_+ - 2n_- \\
q(m'(v_1 \otimes v_2)) &= p(m'(v_1 \otimes v_2)) + c_1(v) + 1 + n_+ - 2n_-
\end{align*}
The part of $m'$ and $\Delta'$ that preserves $q$-grading is the part that lowers the $p$-grading by 1. Upon examination of \eqref{deformed md} we see that these parts are precisely $m$ and $\Delta$, therefore the differential on the $E_0$ page is the Khovanov differential on $\CKh$, hence $E_1 = \Kh$.
\end{proof}

The convention we used for the associated bigraded vector space \eqref{associated bigraded vector space} is not the one usually used. It is more common to use
\[ E_0^{s,r} = F^s \CKh'^{r+s} / F^{s+1} \CKh'^{r+s} \]
Notice that the indices in $E_0$ have been switched, and we are using $r+s$ for the homological grading. With this convention the bidegree of $d_r$ is $(r,1-r)$. This convention is used because with the other convention many popular spectral sequences (like the Leray-Serre spectral sequence) will live in a half-wedge in the first quadrant, which is awkward. By making this index transformation we get a spectral sequence living in the full first quadrant for those spectral sequences. However, Khovanov homology can be supported in any region in the bigraded vector space, so we do not adopt this convention. With our indices we have that the bidegree of $d_r$ is $(1,r)$.

It turns out that pretty much the entire spectral sequence is an invariant of the link.

\begin{thm}
The $E_1$ and higher pages of the spectral sequence in \ref{Lee's spectral sequence} are invariants of the link $L$.
\end{thm}

The proof of this theorem constructs a map $\rho_i' : \CKh'(L) \rightarrow \CKh'(\tilde{L})$ for links $L$ and $\tilde{L}$ that are related by the $i$-th Reidemeister move. It is then shown that $\rho_i'$ induces a map on the spectral sequence which is an isomorphism on the $E_1$ page, and by principles of spectral sequence it follows that the induced maps on the higher pages are also isomorphisms.

\section{Rasmussen's $s$-invariant}

It turns out that Lee's homology is quite simple:

\begin{thm}
If $L$ is a link with $n$ component, then $\Kh'(L) \cong \mathbb Q^{2^n}$.
\end{thm}

Now let us apply Lee's homology and the associated spectral sequence to a knot $K$. The filtration \eqref{filtration} on $\CKh'$ induces a filtration on $\Kh'$, which we will also denote by $F$, and we will denote its associated graded vector space by $\Gr^{**} \Kh'$. Since $K$ has only one component we have that $\Kh' \cong \mathbb Q \oplus \mathbb Q$, and so also $\Gr^{**} \Kh' \cong \mathbb Q \oplus \mathbb Q$. Let $s_{\max}(K)$ and $s_{\min}(K)$ be the maximum and minimum indices $s$ such that $\Gr^{*s} \Kh' \neq 0$. One can prove that the two copies of $\mathbb Q$ in $\Kh'$ are situated in a very specific way.

\begin{prop}
For any knot $K$, $s_{\max}(K) = s_{\min}(K) + 2$.
\end{prop}

So, we define $s(K)$ to be $s_{\max}(K)-1 = s_{\min}(K)+1$. Since the spectral sequence is an invariant of the knot, we have that $s_{\max},s_{\min},s$ are invariants of the knot.

%define induced filtration on $\Kh'$ and use to define $s_\min$ and $s_\max$ .....

\end{document}


% ..............................................................................
% Homomorphe Chiffren
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

\newpage
\hypertarget{homciph}{}
\chapter{Homomorphic Ciphers}
\label{Chapter_HomomorphicCiphers}
\index{homomorphic ciphers}\index{encryption!homomorphic}
(Martin Franz, January 2013)

% -----------------------------------------------------------------------------
\section{Introduction}

Homomorphic ciphers are public-key cryptosystems with special properties. They allow performing certain arithmetic operations on encrypted ciphertexts, without knowing the corresponding plaintexts and without having to decrypt the ciphertexts first. These special properties have led to a huge amount of applications for homomorphic ciphers, e.g. in the domain of cloud computing. A very famous and relatively new cryptosystem with homomorphic properties is the Paillier cryptosystem. But also some of the older and well established cryptosystems, such as ElGamal or RSA, have homomorphic properties.

% -----------------------------------------------------------------------------
\section{Origin of the term ``homomorphic''}

We first clarify the meaning and the origin of the term ``homomorphic''. This term in cryptography is derived from its counterpart in mathematics: in mathematics, a homomorphism is a structure-preserving map between two algebraic structures. In the common sense this means, that a homomorphism $f: X \to Y$ maps the structure of $X$ to the structure of $Y$. Using an example, this can be easily illustrated: Let $(X,+)$ and $(Y,*)$ two algebraic groups with group operations $+$ and $*$, respectively. A homomorphism $f: X \to Y$ maps any given $x \in X$ to a value $y \in Y$, in a way that it holds:
%
$$f(x_1 + x_2) = f(x_1) * f(x_2)$$
%
for any two $x_1, x_2$ in $X$. This means, that for any two values $x_1, x_2$ it does not matter whether we first compute their sum (group operation of $X$) and then apply $f$ (this is the left side of the above given equation); or, whether we first apply $f$ to the values $x_1, x_2$, and then compute their product in $Y$, thus apply the group operation of $Y$. Please note that the operations $+$ and $*$ were chosen here only as an example, they always depend on the algebraic group they belong to. Naturally, the same relation holds for homomorphisms between groups with the same group operation.

\begin{example}{:} Let $X = \mathbb{Z}$ be the set of integer values. The set $\mathbb{Z}$ together with the addition operation forms an algebraic group $G_1 = (\mathbb{Z}, +)$. Similarly, the real values $\mathbb{R}$ without the value zero together with the multiplication operation form a group $G_2 = (\mathbb{R}\backslash\{0\}, *)$. The function $f:\mathbb{Z}{\to}\mathbb{R}\backslash\{0\},z {\to}e^z$ is a homomorphism, since for all $z_1,z_2 \in \mathbb{Z}$ it holds: $f(z_1+ z_2) = e^{(z_1+ z_2 )} = f(z_1 )* f(z_2)$. On the contrary, $f:\mathbb{Z} \to \mathbb{R}\backslash\{0\}, z \to z^2$ is an example for a function which is not a homomorphism.
\end{example}

% -----------------------------------------------------------------------------
\section{Decryption function is a homomorphism}

In the remainder of this chapter we will consider public-key cryptosystems with a special property, namely that its decryption function is a homomorphism. A public-key cryptosystem with this property will be called homomorphic.

Let us for now assume, the above described homomorphism $f$ is the decryption function of a known cryptosystem. This means that we can perform certain algebraic operations in the ciphertext space, knowing which effects this will have on their plaintexts. Following the above given example:

$Y$ corresponds to the set of cipher texts, $X$ is the set of plaintexts. For two plaintexts $x_1, x_2$ with corresponding ciphertexts $y_1, y_2$ it holds:
%
$$f(y_1  * y_2) = f(y_1) + f(y_2) = x_1  + x_2$$
%
This equation can be interpreted as follows: If we multiply two ciphertexts $y_1, y_2$ with each other and subsequently decrypt their product, then we will obtain the sum of the originally encrypted values $x_1$ and $x_2$. Everybody can -- without knowledge of the plaintexts, without having to decrypt and even without knowing the private decryption key -- compute a product of the two ciphertexts and knows that upon decryption the owner of the private key will obtain the sum of the two originally encrypted plaintexts.

% -----------------------------------------------------------------------------
\section{Examples of homomorphic ciphers}

\subsection{Paillier cryptosystem}

The most famous cryptosystem with homomorphic properties is the one by Paillier \cite{hc:Paillier}. First we will see how the Paillier key generation process works. After that, we will show that the Paillier cryptosystem indeed has homomorphic properties.

\subsubsection{Key generation}

First, we generate two random prime numbers $p,q$ in a way that their product $n=pq$ forms  a valid RSA modulus. As for common RSA, the value $n$ should have a bit length of at least 1024 bits.

Using the prime values $p$ and $q$, we can compute the value $\lambda = \textit{lcm}(p-1,q-1)$. $\textit{lcm}$ here denotes the least common multiple. The RSA modulus $n$ will now be the public key, while the private key is the value $\lambda$.

\subsubsection{Encryption}

Let $m$ be the message which will be encrypted, where $m$ is taken from the plaintext space $\mathbb{Z}_n$. For each encryption, we first choose a random element $r$ from the plaintext space $\mathbb{Z}_n$. Subsequently, using the public key, we compute the ciphertext $n$ as:
%
$$c = E(m,r) = (n+1)^m  * r^n  \bmod n^2$$
%
\subsubsection{Decryption}

Given the private key $\lambda$ and a ciphertext $c \in \mathbb{Z}_{n^2}^*$, we first compute $S = c^\lambda \bmod n^2$ and subsequently $T = \phi(n)^{(-1)} \bmod n^2$, where $\phi$ denotes the Euler function.

Finally, we compute the plaintext $m = D(c) = (S-1)/n * T \bmod n$.

\subsubsection{Homomorphic property}

We will now show that the Paillier cryptosystem has the homomorphic property as described above. For this, we will use $E$ to denote the encryption and $D$ to denote the decryption function of the Paillier cryptosystem. For simplicity, we set $g:= n+1$.  For any two plaintexts $m_1,m_2$ and random values $r_1, r_2$ we obtain ciphertexts $c_1, c_2$ as
%
$$c_1 = g^{m_1} *  {r_1}^n \bmod n^2 \mbox{ and } c_2 = g^{m_2} * {r_2}^n \bmod n^2,$$
%
respectively. Now it is easy to see that for the product $c_3 = c_1 * c_2$ it holds
%
$$c_3 = (g^{m_1} * {r_1}^n \bmod n^2) * (g^{m_2} * {r_2}^n \bmod n^2) = g^{m_1+m_2} * (r_1*r_2 )^n \bmod n^2 = E(m_1 + m_2, r_1*r_2)$$
%
Thus, the product of two given ciphertexts is in fact a valid ciphertext, namely the encryption of the sum of the originally encrypted messages. Now it is straightforward to see that the decryption function is a homomorphism. Given two plaintexts $m_1, m_2$ it holds
%
$$D( E(m_1,r_1) * E(m_2,r_2)) = D( E(m_1+m_2, r_1 r_2)) = m_1  + m_2 = D(E(m_1,r_1)) + D(E(m_2,r_2))$$

\subsection{Other cryptosystems}

Also older public-key cryptosystems can have homomorphic properties. Both the ElGamal cryptosystem and RSA constitute famous examples. We will show their homomorphic properties by means of some easy examples.

\subsubsection{RSA}

Let $(e,n)$ be the public RSA key ($e$ the public encryption exponent, $n$ the RSA modulus). For any two messages $m_1, m_2$ we obtain encryptions $c_1 = {m_1}^e \bmod n$ and $c_2 = {m_2}^e \bmod n$. Now for the product of these two encryptions it holds: $c_1*c_2={m_1}^e * {m_2}^e \bmod n=(m_1*m_2)^e \bmod n$. Thus, we obtain an encryption of the product of the two messages $m_1$ and $m_2$. As it is straightforward to see, this property holds for any two plaintexts $m_1, m_2$ and similar as for Paillier, the decryption function is a homomorphism. As we have seen here, RSA is an example for a homomorphism, where both groups have the same group operation.

\subsubsection{ElGamal}

Similar to RSA we can also show the homomorphic properties of the ElGamal cryptosystem. Let $(p,g,K)$ the public key while the private key is $k$ (thus, it holds $g^k \bmod p = K$). For any two messages $m_1, m_2$ and random values $r, s$ we obtain encryptions $(R, c_1) = (K^r \bmod p, m_1*g^r \bmod p)$ and $(S,c_2) = (K^s \bmod p, m_2 * g^s \bmod p)$. As for RSA, we verify that their product $(R*S, c_1*c_2)$ is an encryption of $m_1*m_2$. Again it is straightforward to see that the decryption function is a homomorphism.

% -----------------------------------------------------------------------------
\section{Applications}
The homomorphic property of the Paillier cryptosystem can be used to add two encrypted values or to multiply any value under encryption with a known constant (note that the multiplication corresponds to the repeated application of the addition operation). This makes homomorphic ciphers to important and easy to use base primitives in cryptographic applications.

\begin{enumerate}
\item One of these applications is the so called ``Electronic Voting''. Electronic voting allows a large number of voters to submit their ballots in an encrypted form. This is important in situations, where the voters cannot come together to the same location. This happens, for example, if the voters can only communicate over the internet via email. If the voting behavior of the single parties should remain secret, then the use of homomorphic ciphers is a good solution to this problem. The main principle of electronic voting using homomorphic ciphers is as follows.

All voters encrypt their ballots, using homomorphic encryption (see at the left site of the screenshot). The screenshot depicts the next steps (1 to 3):

\begin{itemize}
\item All voters (on the left in the figure \ref{CT2-PaillierVoting}) encrypt the value 1 if they opt positive and the value 0, if opposed to the decision.
\item Using the homomorphic property, one can compute the sum of all encrypted ballots. Since this happens on encrypted values, the voting behavior of all participants remains secret.
\item At the end, the result of the election is determined and published, this happens by decrypting the sum which was computed using the homomorphic property.
\end{itemize}

\begin{figure}[ht]
\begin{center}
\includegraphics[scale=0.4]{figures/CT2-PaillierVoting.png}
\caption{Voting example for Paillier}
\label{CT2-PaillierVoting}
\end{center}
\end{figure}

\item A second application of homomorphic ciphers is ``Secure Multiparty Computation''. Here, two or more parties can compute any commonly known function. Each of the parties provides one or more of the inputs for the function to be computed. The goal of the secure computations is to keep all private inputs secret, while only the result of the function is revealed. The use of homomorphic encryption helps to perform these computations on encrypted data. However, since the Paillier encryption only allows to compute additions of encrypted values (and, e.g. no multiplications can be performed), a number of additional methods and techniques have to be applied. The Wikipedia page \cite{hc:SMC} offers a great start for reading more about this topic and more advanced techniques for Secure Multiparty Computation.

\item Furthermore it is expected, that homomorphic encryption will provide great advantages in the areas of ``Cloud Computing''. Using so called ``fully-homomorphic encryption'' \cite{hc:HomEnc} it will be possible to run large applications on external servers only on encrypted data. For this, necessarily one needs to be able to perform both arithmetic operations, the addition and the multiplication, on encrypted data (in contrast to Paillier encryption, which only allows performing additions). Such a crypto system was first presented in 2009 \cite{hc:Gentry2009}.
\end{enumerate}

% -----------------------------------------------------------------------------
\section{Homomorphic ciphers in CrypTool}

\subsection{CrypTool 2}

In CrypTool 2 you will find an implementation of the Paillier cryptosystem. Among the available components, there are components for key generation (Paillier Key Generator), an example for encryption and decryption with Paillier (called Paillier Text), as well as examples which illustrate the homomorphic properties of the cryptosystem (Paillier Addition, Paillier Blinding and Paillier Voting).

\begin{figure}[ht]
\begin{center}
\includegraphics[scale=0.8]{figures/CT2-Paillier.png}
\caption{Paillier cryptosystem in CrypTool 2}
\label{CT2-Paillier}
\end{center}
\end{figure}

\newpage
\subsection{JCrypTool}

In JCrypTool there is an implementation (see Figure \ref{JCT-HomEnc}), which visualizes the homomorphic properties of various cryptosystem. For RSA and Paillier it shows, that multiplications, for RSA, and additions for Paillier, respectively, can be performed on encrypted values. For the fully-homomorphic cryptosystem by Gentry it is possible to perform both multiplications, as well as additions on encrypted values.

\begin{figure}[ht]
\begin{center}
\includegraphics[scale=0.4]{figures/JCT-HomEnc.PNG}
\caption{Visualization of homomorphic properties in JCrypTool}
\label{JCT-HomEnc}
\end{center}
\end{figure}

%------------------------------------------------------------------------------
\newpage
\begin{thebibliography}{99999}
\addcontentsline{toc}{section}{Bibliography}

\bibitem[Paillier1999]{hc:Paillier} \index{Paillier 1999}
   Pascal Paillier, \\
   {\em Public-Key Cryptosystems Based on Composite Degree Residuosity Classes},\\
	 Advances in Cryptology -- EUROCRYPT'99, 1999.

\bibitem[SMC]{hc:SMC} \index{SMC}
   Wikipedia, \\
   {\em Secure Multiparty Computation}.\\
   \url{http://en.wikipedia.org/wiki/Secure_multi-party_computation}

\bibitem[HomEnc]{hc:HomEnc}
   Wikipedia, \\
   {\em Homomorphic Encryption}\\
   \url{https://en.wikipedia.org/wiki/Homomorphic_encryption}\\
   {\em Homomorphism}\\
   \url{https://en.wikipedia.org/wiki/Homomorphism}

\bibitem[Gentry2009]{hc:Gentry2009} \index{Gentry 2009}
   Craig Gentry, \\
   {\em Fully Homomorphic Encryption Using Ideal Lattices},\\
	In the 41st ACM Symposium on Theory of Computing (STOC), 2009.

\end{thebibliography}  % German

% Local Variables:
% TeX-master: "../script-de.tex"
% End:


\subsection{Belief states}

Inc initial knowledge of environment, page on storing observations

eg if position is right or left, at start belief state is both, if we try to move right, we are definitely right.

what if actions differ between states? can consider only actions available to all states if cost of illegal action is high

goal test: need to test all belief states


% dcs.tex

\section*{Document Control System}

Here we model a simple document control system in Z.
People who work together need to share their work, but there are many
opportunities for misunderstandings and confusion.  Errors can be
introduced when two people working on the same thing --- a file of
program code, for example --- make changes that conflict with each
other.  We can enlist the computer to help prevent such errors: this
is the purpose of a document control system.  Real examples include
SCCS (source code control system) and RCS (revision control
system).

Here is an excerpt from the informal description:

\begin{quote}
    If a user wants to check out a document in order to change
    the document and the user  has the permission to change it,
    and nobody else is changing it at the moment, then that user
    may check the document out.

    As soon as a user has checked out a document for editing
    everyone else is disallowed from checking it out (of course people with
    read permission can read it).

    When the user is done editing the document, it should be
    checked in, allowing another user to check it out.
\end{quote}

Here is the Z model.  We begin by introducing two basic sets that
hold everything of interest in this universe, namely people and
documents:

\begin{zed} [PERSON, DOCUMENT] \end{zed}
Some people have permission to change particular documents.  We can model
that as a relation on documents and people:

\begin{axdef}
	permission: DOCUMENT \rel PERSON
\end{axdef}
This relation is just a set of pairs of the form $(document, person)$.
For example, Doug can change the specification, Aki and Doug can
change the design, and Aki and Phil can change the code.

\begin{axdef}
	doug, aki, phil: PERSON \\
	spec, design, code: DOCUMENT
\end{axdef}
\begin{zed}
	permission = \{ (spec, doug), (design, doug), (design, aki), (code, aki), (code, phil) \}
\end{zed}
The state of the system is merely another relation of the same type,
this one saying which documents are actually checked out to whom.   The
central requirement is that a document can only be checked out to
one person at a time, so in this case the relation is a function:
it associates each object in the domain with a single
object in the range.

\begin{schema}{Documents}
	checked\_out: DOCUMENT \pfun PERSON
\where
	checked\_out \subseteq permission
\end{schema}
Note that $checked\_out$ is a partial function, indicated by the stroke
through the arrow $\pfun$.  This means that some documents might not be
checked out to anybody.  The predicate says that documents can only be
checked out to people who have permission to change them.

A possible state of our system occurs when Doug has checked out the
specification and design, and Phil has checked out the code.

\begin{zed}
	checked\_out = \{ (design, doug), (spec, doug), (code, phil) \}
\end{zed}

We need two operations that change the state, $CheckOut$ and $CheckIn$.
Here is $CheckOut$.  It has two input parameters, the person $p?$ and the document $d?$.

\begin{schema}{CheckOut}
	\Delta Documents \\
	p?: PERSON \\
	d?: DOCUMENT
\where
	d? \notin \dom checked\_out \\
	(d?, p?) \in permission \\
	checked\_out' = checked\_out \cup \{(d?, p?)\}
\end{schema}
$CheckOut$ has two preconditions.  They are the predicates that contain
no primed ``after'' variables.  First, document $d?$ can't already be checked
out: it can't be in the domain of $checked\_out$.  Moreover, the person
doing the checking out needs permission:  $(d?, p?)$ must belong to
$permission$.  If the preconditions are satisfied we add the pair $(d?,p?)$
to $checked\_out$; this prevents anyone else from checking out $d?$.

We must account for cases where the preconditions are not satisfied.
There are two preconditions, so there must be two such cases.
$CheckedOut$ says that the document is already checked out: $d? \in
\dom checked\_out$.  $Unauthorized$ expresses that the person does not
have permission: $(d?,p?) \notin permission$.  In both cases nothing
gets checked out and the state of the system does not change:
$\Xi~Documents$.

\begin{zed}
CheckedOut \defs [~ \Xi Documents; d?: DOCUMENT | d? \in \dom checked\_out ~]
\end{zed}

\begin{schema}{Unauthorized}
	\Xi Documents \\
	p?: PERSON \\
 	d?: DOCUMENT
\where
	(d?,p?) \notin permission
\end{schema}
The total operation $T\_CheckOut$ covers all three possibilities.

\begin{zed}
	T\_CheckOut \defs CheckOut \lor CheckedOut \lor Unauthorized
\end{zed}
This concludes our presentation.  This little study illustrates some
typical features of Z models:

You can ignore details in order to focus on the aspects of the problem
you are interested in.  Here we concentrated on permissions and
keeping track of who has checked out what.  We did not model actually
copying documents back and forth between the central repository and
users' local directories.  We modelled the collections of documents
and users as fixed sets, and the permissions as a constant.  A real
document control system would have to provide some way to enter new
documents into the system and delete old ones, and there would also
have to be a way to assign and change permissions.  If we wished to
model all that in Z we could represent people, documents, and
permissions as variables in the state schema instead of basic types
and global constants.

Models should be simple.  If you find yourself writing complicated functions
and quantified predicates, it is usually a sign that you are on the wrong
track.  Let the basic properties of sets, relations and functions do the
work for you.  The requirement that only one person at a time can check out
a document can be neatly expressed by a function.

The requirements about permissions can be represented by letting the
$checked\_out$ function be a subset of the $permission$ relation.  In
Z, functions are relations and relations are sets, so operators
defined for sets also apply to relations and functions, and you can
put them all together in the same expressions.  This is an advantage
of Z that you don't find in every formal notation.


\documentclass{article}
\usepackage{tocloft}
\include{common_symbols_and_format}
\renewcommand{\cfttoctitlefont}{\Large\bfseries}

\begin{document}
\logo
\rulename{Exponential Moving Average Trading Rule} %Argument is name of rule
\tblofcontents

\ruledescription{Gives a buy signal when the asset price closed above the EMA($\lookbacklength$) and gives a sell signal when the asset price closed below or lower than EMA($\lookbacklength$). The lookback length, $\lookbacklength$, determines how far back the rule looks.}

\section{Equation}
\begin{equation}
    EMA_{\currenttime} = \Big(V_{\currenttime} * \Big(\frac{S}{1 + \lookbacklength}\Big)\Big) + EMA_{\currenttime-1} * \Big(1-\frac{S}{1 + \lookbacklength}\Big)
\end{equation}
\\

where: \\

$EMA$ is exponentially weighted moving average. \\

$V_{\currenttime}$ is current stock value. \\

$\lookbacklength$ \ is look back length. \\

$S$ is the smoothing factor.

\ruleparameters
{Window size}{50}{This is the number of time steps over which exponential contributions are sourced.}{$\lookbacklength$}
{Smoothing Factor}{2}{Smoothing factor represents the weighting applied to the most recent period’s value.}{$S$}
\stoptable

\keyterms
\furtherlinks

\end{document}