\documentclass[12pt]{article}
\usepackage{a4wide}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{commath}
\usepackage{listings}
\usepackage{epic}
\usepackage{graphicx}
\usepackage{float}
\usepackage{hyperref}
\usepackage{algorithm,algorithmic}
%\pagestyle{empty}
\newcommand{\tr}{\mbox{\sf true}}
\newcommand{\fa}{\mbox{\sf false}}
\usepackage[toc,page]{appendix}
\newcommand{\bimp}{\leftrightarrow}
\usepackage{enumitem}
% \renewcommand{\algorithmicrequire}{\textbf{Input:}}
% \renewcommand{\algorithmicensure}{\textbf{Output:}}

\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}

\usepackage{changepage}
\newcommand\sdent{\begin{adjustwidth}{2.5em}{0pt}}
\newcommand\edent{\end{adjustwidth}}

\begin{document}

\lstset{
    frame=tb,
    aboveskip=3mm,
    belowskip=3mm,
    showstringspaces=false,
    columns=flexible,
    basicstyle={\small\ttfamily},
    numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
    numbersep=5pt,                   % how far the line-numbers are from the code
    numberstyle=\footnotesize,
    postbreak=\mbox{$\hookrightarrow$\space},
    breaklines=true,
    breakatwhitespace=false,
    tabsize=3,
    frame=shadowbox,
}

\begin{center}
    \font\myfont=cmr12 at 30pt
    \title*{\myfont Polygon intersection algorithm}
\end{center}

\begin{center}
    Tar van Krieken
\end{center}

\vspace{8mm}

\section*{Introduction}
This document describes an algorithm I came up with while following the Geometric Algorithms course (2IMA15) at Eindhoven University of Technology.

The algorithm calculates the faces that are formed adding multiple simple polygons to the same plane. An example of what separated faces are formed and calculated by the algorithm can be seen in Figure \ref{fig:intersectionExample}

\begin{figure}[!htb]
    \includegraphics[width=\linewidth]{Images/intersectionExample.jpg}
    \caption{Face separation example}
    \label{fig:intersectionExample}
\end{figure}

The algorithm unfortunately suffers from some robustness issues. An attempt was made to resolve these but without success. A redesign is probably required to fix these issues instead of only applying patches within the implementation.

\newpage
\section*{Approach}

The algorithm is based on a vertical \href{https://en.wikipedia.org/wiki/Sweep_line_algorithm}{line sweep}. The scanline tracks all separate x-intervals formed by segments that intersect the scanline as illustrated in Figure \ref{fig:intersectionScanline}. The intervals hold the following information:
\begin{itemize}
    \item The left boundary (if any)
    \item The right boundary (if any)
    \item The output shape
\end{itemize}
\begin{figure}[!htb]
    \includegraphics[width=\linewidth]{Images/intersection_scanline.png}
    \caption{The scanline and the intervals it stores}
    \label{fig:intersectionScanline}
\end{figure}

These output shapes are y-monotone polygon sections. Each section contains the following data:
\begin{itemize}
    \item The left walls (A list of points sorted in increasing y-value)
    \item The right walls (A list of points sorted in increasing y-value)
    \item The top left section (if any)
    \item The top right section (if any)
    \item The bottom left section (if any)
    \item The bottom right section (if any)
    \item The source polygons that are part of this section
\end{itemize}
These section references establish a bi-direction relation between multiple sections, such that at the end of the algorithm a simple polygon can be generated by performing a search on a root section. Additionally any two linked sections will contain the same list of source polygons.
In Figure \ref{fig:intersectionExamplePolygon} a polygon is shown that could be dissected into these y-monotone sections. This results in the sections shown in Figure \ref{fig:intersectionPolygonSections}. The individual sections and their points on the left and right walls can be seen in Figures \ref{fig:intersectionPolygonSection1} to \ref{fig:intersectionPolygonSection5}. Figure  \ref{fig:intersectionPolygonSection3} highlights that polygons formed by connecting the left and right walls of a y-monotone section are not necessarily part of the original polygon, but the left and right walls are always part of the resulting polygon.

\begin{figure}[H]
    \minipage{0.48\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_polygon.png}
    \caption{A polygon that could be dissected}
    \label{fig:intersectionExamplePolygon}
    \endminipage\hfill
    \minipage{0.48\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_yMonotoneSections.png}
    \caption{y-monotone sections of a polygon}
    \label{fig:intersectionPolygonSections}
    \endminipage
\end{figure}

\begin{figure}[H]
    \minipage{0.2\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_yMonotoneSection1.png}
    \caption{}
    \label{fig:intersectionPolygonSection1}
    \endminipage\hfill
    \minipage{0.2\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_yMonotoneSection2.png}
    \caption{}
    \label{fig:intersectionPolygonSection2}
    \endminipage\hfill
    \minipage{0.2\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_yMonotoneSection3.png}
    \caption{}
    \label{fig:intersectionPolygonSection3}
    \endminipage\hfill
    \minipage{0.2\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_yMonotoneSection4.png}
    \caption{}
    \label{fig:intersectionPolygonSection4}
    \endminipage\hfill
    \minipage{0.2\textwidth}
    \includegraphics[width=\linewidth]{Images/intersection_yMonotoneSection5.png}
    \caption{}
    \label{fig:intersectionPolygonSection5}
    \endminipage
\end{figure}

There are 7 different event types that of relevance when progressing the scanline. 6 of these can be calculated ahead of time for each input polygon individually, but the last one - intersection events - will be calculated at scantime. Below is a list of all event types and their colors withing Figure \ref{fig:intersectionEventTypes}.
\begin{itemize}
    \item Interval start (light-green)
    \item Interval end (light-red)
    \item Interval split (dark-green)
    \item Interval merge (dark-red)
    \item Interval left wall replacement (light-blue)
    \item Interval right wall replacement (dark-blue)
    \item Interval boundaries intersection
\end{itemize}
The first 6 event types can be identified by walking the boundaries of the simple polygon and analyzing the relative positions of 3 consecutive points at a time to determine the even type corresponding to the middle of the three points.
Here an important edge case shows up, because determining the event types when dealing with horizontal lines is not very straight forward. We however managed to simplify this situation by imagining a symbolic left-rotation of the whole polygon that is small enough to not mess with the y-order of points (apart from points with the same y-value) in a similar fashion as was done in the vertical decomposition construction algorithm. An example of this is illustrated in Figures \ref{fig:intersectionHorizontalLines} and \ref{fig:intersectionHorizontalLinesRotated}. We also have to mirror this symbolic rotation in our event queue by having a lexicographical ordering which first sorts the events in increasing y-value followed by increasing x-value.

\begin{figure}[H]
    \centering
    \includegraphics[width=0.5\linewidth]{Images/intersection_eventAssignment.png}
    \caption{The polygon event types}
    \label{fig:intersectionEventTypes}
\end{figure}
\begin{figure}[H]
    \minipage{0.48\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_eventAssignmentEdgeCase.png}
    \caption{Horizontal lines edge case}
    \label{fig:intersectionHorizontalLines}
    \endminipage\hfill
    \minipage{0.48\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_eventAssignmentEdgeCaseRotated.png}
    \caption{Symbolic left rotation edge case fix}
    \label{fig:intersectionHorizontalLinesRotated}
    \endminipage
\end{figure}

As stated before, the algorithm computes the intersections at runtime. Whenever a new interval is added to the scanline (or the boundary of an interval is altered) the interval will check whether its boundaries will intersect in the future. If they do intersect in the future, this intersection is added to the event queue. When an interval is removed from the scanline and its boundaries were going to intersect in the future, this intersection event is removed from the event queue. This can for instance happen if another line happened to intersect the boundary of an interval before the interval's boundaries intersected.

Intersection events are handled completely separately from the other 6 event types. Moreover one has to be careful and consider that multiple events can take place in the same point. In this scenario where general position is not assumed the lexicographical event ordering has to be extended to prioritise intersection events over the other event types, the reason for which will become apparent later. Whenever an intersection event occurs interval $x$ whose boundaries intersected is retrieved, as well as interval $l$ that is to the left of $x$ and interval $r$ that is to the right of $x$. Now $x$'s boundaries are replaced together with the shared boundaries with $l$ and $r$ by new boundaries that stop at the intersection point. In Figure \ref{fig:intersectionIntersection} an intersection event is shown and the state after replacing the boundaries is highlighted in Figure \ref{fig:intersectionIntersectionOldBoundary}. Next a simple trick is used to offload all the other relevant logic to the normal event handling code. A new start event is created at the intersection point. This event stores the continuation of the left and right boundaries that we cut in two. Handling this even will take care of removing the stopped interval, updating its shape, updating $l$ and $r$'s shapes, and creating the new interval that was started. The creation of this even is illustrated in Figure \ref{fig:intersectionIntersectionNewStartEvent}

\begin{figure}[H]
    \minipage{0.3\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_intersect.png}
    \caption{An intersection situation}
    \label{fig:intersectionIntersection}
    \endminipage\hfill
    \minipage{0.3\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_intersectOldBoundaryCut.png}
    \caption{Intersection boundary replacement}
    \label{fig:intersectionIntersectionOldBoundary}
    \endminipage\hfill
    \minipage{0.3\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_intersectNewStartEvent.png}
    \caption{Intersection fake start event}
    \label{fig:intersectionIntersectionNewStartEvent}
    \endminipage
\end{figure}

Handling all other 6 events is quite tricky at first glance, especially when considering multiple of these events can happen at the same point once again. They can however be generalized to simplify everything quite a bit: all that's important at a given point is knowing what new segments have started. So we will collect all non-intersection-events that start at the same point and handle them simultaneously. First off the scanline is queried for all intervals that contain the event point. Next we obtain all new boundaries (segments) of the events that occurred and sort them from left to right. Now using this data a couple of useful observations can be made: \begin{itemize}
    \item If there is more than 1 new boundary, new intervals should be created. More precisely, given $x$ new segments, there will be $x-1$ new intervals. This is illustrated in Figure \ref{fig:intersectionNewIntervals}.
    \item If there are more than 2 intervals that the event point lied in, there are intervals ending at this point. More precisely, given $n$ intervals containing the event point, there will be $n-2$ intervals that end. This is illustrated in Figure \ref{fig:intersectionOldIntervals}.
\end{itemize}

\begin{figure}[H]
    \minipage{0.48\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_newIntervals.png}
    \caption{Newly formed intervals}
    \label{fig:intersectionNewIntervals}
    \endminipage\hfill
    \minipage{0.48\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_oldIntervals.png}
    \caption{Old ended intervals (scanline moved down for clarity)}
    \label{fig:intersectionOldIntervals}
    \endminipage
\end{figure}

This information can be exploited in the algorithm. One can quite easily cross the new boundaries from left to right and create the new intervals to add to the scanline. While crossing these boundaries the list of source polygons that are part of the interval can be tracked. Every segment of the event will store whether it was a left or right wall of a polygon, as well as the polygon itself. Thus when crossing a boundary one can add or remove the polygon from a list of sources, depending on whether it was a left or right wall.

Similarly all internal intervals (all intervals but the first and last) can be iterated over to remove them from the scanline, as well as add the event point to the shape's left and right walls.
Having taken care of these stopped and started intervals, only handling the outermost intervals remains. 3 different cases can be recognized here as illustrated in Figures \ref{fig:intersectionIntervalCase1} to \ref{fig:intersecionIntervalCase3}. Here the black triangles represent an unknown number of old/new boundaries, but there is at least 1 boundary such that the left and right parts of this triangle are separated. Each of these cases can be handled independently and are rather straight forward to handle. Case 1 and 3 will require new intervals to be created (with new y-monotone shapes), and case 2 only requires shapes and boundaries to be appropriately updated. Special care should be taken to properly link the new y-monotone sections with each other. Additionally all of these cases will check for new possible intersections.

\begin{figure}[H]
    \minipage{0.3\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_case1.png}
    \caption{Shape linking case 1}
    \label{fig:intersectionIntervalCase1}
    \endminipage\hfill
    \minipage{0.3\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_case2.png}
    \caption{Shape linking case 2}
    \label{fig:intersecionIntervalCase2}
    \endminipage\hfill
    \minipage{0.3\textwidth}
    \centering
    \includegraphics[height=5cm]{Images/intersection_case3.png}
    \caption{Shape linking case 3}
    \label{fig:intersecionIntervalCase3}
    \endminipage
\end{figure}

This discussed approach still misses out on one significant edge case, but this is fortunately easy to handle: an event point may lie on a segment as illustrated in Figure \ref{fig:eventPointOnSegment}. This means that no pure intersection occurs, thus it would not be observed. When all intervals with the event point are retrieved this includes intervals with this segment as its boundary. Now one can easily iterate over all found intervals and if the event point lies on the boundary $b$ without being its endpoint, a new segment $s$ can be created starting at the event point and ending at the endpoint of $b$. These created segment are then added to the list of new boundaries starting at this event point. This ensures that the lines going through the point are properly considered in the rest of the calculation. This also handles the situation of multiple intersections occurring in the same point. If it were not for rounding errors this approach could take care of all intersection events, such that those would not have to be handled separately. It however is very plausible and not unlikely that a calculated intersection point does not lie exactly on both segments, which would make this approach fail in practice. But it is known that for a set of closed polygons that partially overlap either the segments will cross somewhere or a point will lie on a segment. Therefore the combination of the intersection approach and point on the segment approach will take care of all situations.
\begin{figure}[H]
    \centering
    \includegraphics[width=10cm]{Images/intersection_pointOnSegment.png}
    \caption{Point lies on segment, but does not cross it}
    \label{fig:intersectionScanline}
\end{figure}

Now that events are handled in batches of the same point, this nuanced view of 7 different event types is excessive. Therefore in practice when the first 6 event types are identified, one can simply encode them within the 3 generalized virtual event types that the scanline later deals with:
\begin{itemize}
    \item Segment (start (2 instances), left wall, right wall, split)
    \item End (stop, merge)
    \item Intersection
\end{itemize}

\end{document}


\documentclass[12pt, a4paper]{article}
\usepackage[UKenglish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{mathtools} % an extension of amsmath
\usepackage{amsthm, amssymb, amsfonts, amstext}
\usepackage{longtable}
\usepackage{tocloft}
\usepackage{geometry}
\usepackage{algpseudocode}
\usepackage{multicol}
\geometry{margin=27mm}
\usepackage{listings}
\usepackage{xcolor,colortbl}
\usepackage{wrapfig}
\usepackage{graphicx}
\usepackage{array}
\usepackage{tabularx}
\usepackage{makecell}
\usepackage{ulem}
\usepackage{enumitem}
\usepackage[many]{tcolorbox}
\newtcolorbox{mybox}[3][] {
  colframe = #2!25,
  colback  = #2!10,
  coltitle = #2!20!black,
  title    = {#3},
  #1,
}
\renewcommand\theadalign{bc} % to leave lines inside a table
\renewcommand\theadgape{\Gape[4pt]}
\renewcommand\cellgape{\Gape[4pt]}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0,0,0}
\definecolor{pageBG}{rgb}{0,0,0}
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,
    urlcolor=cyan,
}
\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},
    commentstyle=\color{yellow},
    keywordstyle=\color{red},
    numberstyle=\color{red},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\footnotesize\color{codegreen},
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=4
}
\lstset{style=mystyle}
\urlstyle{same}
\usepackage{cleveref}
\usepackage{bm}
\newcommand{\bs}{\boldsymbol}
\newcommand{\ora}{\overrightarrow}

\newtheorem{theorem}{Theorem}[section]
\theoremstyle{definition}
\newtheorem{definition}{Definition}[section]
\newtheorem*{claim}{Claim}
\theoremstyle{remark}
\newtheorem*{remark}{Remark}
% \numberwithin{equation}{section}
\newcommand{\textsb}{\textsubscript}

\title{Computer Graphics Notes\\Lecture 3}
\author{Aditya Harikrish\\2020111009}
\date{}

\begin{document}
\maketitle
\tableofcontents

\begin{definition}[Modelling Matrix]
    The matrix which defines the transformation of the world origin to the object origin is called the modelling matrix of the object.
    The modelling matrix rotates the object axes and translates them from $(0,0,0)$.
\end{definition}

\section{Rotation About an Arbitrary Axis}

\subsection{Rotation About an Axis Parallel to \texorpdfstring{\bs{$x$}}{x}-axis}
To rotate a point about an axis parallel to the $x$-axis passing through $(0,y,z)$, first translate the point by $(k,-y,-z)$, rotate it around the $x$-axis and then translate it by $(-k,y,z)$. Here, $k$ can be anything we want and its value doesn't make a difference to the end result. So,
\begin{equation*}
    M = T(-k,y,z) R_X (\theta) T(k, -y, -z)
\end{equation*}

\subsection{Rotation About Any Axis}
Let $\alpha$ be the axis of rotation. Let $\alpha$ pass through the origin. If $\alpha$ does not pass through the origin, all we'll need to do is add a translation step before and after our procedure. Our task is to find $R_{\alpha}(\theta)$. Let $\alpha = (\alpha_1, \alpha_2, \alpha_3)$.
We follow the following steps:
\begin{enumerate}
    \item Apply $R_{\alpha x}$ to align $\alpha$ with the $x$-axis.
    \item Rotate the object about the $x$-axis by $\theta$.
    \item Apply $R_{\alpha x}^{-1}$ to align the axis of rotation back with $\alpha$.
\end{enumerate}
\begin{equation}
    R_{\alpha}(\theta) = R_{\alpha x}^{-1} R_X (\theta) R_{\alpha x}
\end{equation}

\subsubsection{Finding \texorpdfstring{\bs{$R_{\alpha x}$}}{x}: Method 1 (Harder)}
\begin{enumerate}
    \item Rotate $\alpha$ about the $x$-axis until it lies on the $xy$-plane. Let the angle needed to make this rotation be $\beta$. $\beta$ happens to be the angle made by the projection of $\alpha$ on the $yz$-plane with the $y$-axis.
          \begin{equation}
              \beta = -\tan^{-1} \frac{\alpha_3}{\alpha_2}
          \end{equation}
          The tip of the vector is now at $P' = (\alpha_1, \sqrt{\alpha_1^2 + \alpha_2^2},0)$
    \item Now, rotate it about the $z$-axis until it coincides with the $x$-axis. Let the angle needed to make this rotation be $\gamma$.
          \begin{equation}
              \gamma = - \tan^{-1} \frac{\sqrt{\alpha_1^2 + \alpha_2^2}}{\alpha_1}
          \end{equation}
\end{enumerate}
Thus,
\begin{align}
    R_{\alpha x}      & = R_z(-\gamma) R_x(-\beta)\text{, and} \\
    R_{\alpha x}^{-1} & = R_x(\beta) R_z(\gamma).
\end{align}

\subsubsection{Finding \texorpdfstring{\bs{$R_{\alpha x}$}}{x}: Method 2 (Easier)}
We know that the rows of the rotation matrix are the coordinates that rotate into the $(1,0,0)$, $(0,1,0)$ and$(0,0,1)$ and the columns are what these points rotate into.
\begin{enumerate}
    \item Our rotation matrix rotates $\ora{\alpha} / |\ora{\alpha}|$ into $(1,0,0)$. Hence, the first row of the rotation matrix, $\ora{r_1}$, is given by
          \begin{equation}
              \ora{r_1} = \frac{\ora{\alpha}}{|\ora{\alpha}|}.
          \end{equation}
    \item $\ora{r_2}$ and $\ora{r_3}$ are generated to be perpendicular with each other and with $\ora{r_1}$. $\ora{r_2}$ can be any unit vector orthogonal to $\ora{r_1}$, i.e. orthogonal to $\ora{\alpha_1}$. Choose any vector $\ora{v}$ not parallel to $\ora{\alpha}$. Then,
          \begin{equation}
              \ora{r_2} = \ora{\alpha} \times \ora{v}.
          \end{equation}
    \item \begin{equation}
              \ora{r_3} = \ora{r_1} \times \ora{r_2}
          \end{equation}
\end{enumerate}

\begin{equation}
    R_{\alpha x \, (4 \times 4)} = \begin{bmatrix}
        \ora{\alpha}                & 0 \\
        \ora{\alpha} \times \ora{v} & 0 \\
        \ora{r_1} \times \ora{r_2}  & 0 \\
        \ora{0}                     & 1
    \end{bmatrix}
\end{equation}

There are multiple possible solutions for $R_{\alpha x}$.

\begin{mybox}[breakable]{red}{General Rotation Matrix}
    Let $\ora{\alpha}$ be a vector along the direction of the axis of rotation, $L$. Let $T$ be a translation matrix that translates $L$ so that it passes through the origin.
    \begin{equation}
        \begin{split}
            R_L (\theta) &= T^{-1} R_{\alpha}(\theta) T \\
            &= T^{-1} R_{\alpha x}^{-1} R_x(\theta) R_{\alpha x} T
        \end{split}
    \end{equation}
\end{mybox}

\section{Transforming Planes}
Consider a plane $P$ given by
\begin{equation*}
    n^T p = 0,
\end{equation*}
where $n$ is the normal vector with its base at the origin (need not be the origin, just has to be some known point to ensure uniqueness of the plane) and $p$ is any point.

Let $Q$ transform $n$ when the points on the plane are transformed by $M$. Coplanarity of the points is preserved after the transformation, i.e.
\begin{equation*}
    (Qn)^T Mp = 0 = n^T Q^T M p
\end{equation*}
But as $n^T p = 0$, $Q^T M = I$ or $Q = (M^{-1})^T$. When $M^{-1}$ doesn't exist, $Q$ is the cofactor matrix of $M$.
\end{document}


%% LyX 2.0.3 created this file.  For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{color}
\usepackage{amsmath}
\usepackage{esint}

\makeatletter

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
%% Because html converters don't know tabularnewline
\providecommand{\tabularnewline}{\\}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\usepackage{amsthm}
\usepackage{amsfonts}

\usepackage{algorithm}
\usepackage{algpseudocode}

\makeatother

\usepackage{babel}
\begin{document}

\title{Summary for Hybrid Stochastic Simulation}

\maketitle

\section{Theory}

Here we summarize some thoretical results from the literature about
Hybrid Stochastic Systems and approximation schemes for such systems.
We mostly follow the notation in \cite{crudu2012convergence} and
\cite{kang2013separation}.

\subsection{Description of a biochemical stochastic reaction network}

We assume a stochastic reaction network consisting of
\begin{itemize}
\item $s_{0}$ species $S_{i}$ with copy numbers $x_{i}$, with $i=1,...,s_{0}$
\item $r_{0}$ reactions with corresponding stochiometry vectors $\xi_{k}=\nu'_{k}-\nu{}_{k}$
and reaction rates $\lambda_{k}\left(x\right)$ with $k=1,...,r_{0}$
\end{itemize}
This network can be written as a Markov Jump Process in the random-time-change
representation

\[
X(t)=x(0)+\sum_{k=1}^{r_{0}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\nu'_{k}-\nu_{k}\right)
\]

whereas the $Y_{k}$ are independent unit Poisson processes.

For the following we assume a decomposition $\left(x_{C},x_{D}\right)$
of the $s_{0}$ species, such that $x_{C}$ represents species that
are large, scaling with a parameter $N$, and $x_{D}$ represents
species that are of order $O(1)$. We define $\psi_{i}^{C}=\frac{1}{N}x_{i}^{C}$.

Additionally we partition the $r_{0}$ reactions into $\mathcal{R}_{C},\mathcal{R}_{DC},\mathcal{R}_{D}$,
such that
\begin{itemize}
\item $\mathcal{R}_{C}$ corresponds to reactions that involve only species
from $x_{C}$ and whose reaction rate only depends on $x_{C}$
\item $\mathcal{R}_{D}$ corresponds to reactions that involve only species
from $x_{D}$ and whose reaction rate only depends on $x_{D}$
\item $\mathcal{R}_{DC}$ corresponds to reactions not belonging to $\mathcal{R}_{C}$
or $\mathcal{R}_{D}$
\end{itemize}

\subsection{Convergence of Markov Jump Processes to Piecewise Deterministic Markov
Processes}

\label{sub:PDMP_convergence}

The following theorem states the convergence of a partially scaled
Markov Jump Process into a PDMP (Piecewise Deterministic Markov Process)
\cite{davis1984piecewise}.

For $r\in\mathcal{R}_{C}$ define $\tilde{\lambda}_{r}=\frac{1}{N}\lambda_{r}$
(we can implicitely assume that $\lambda_{r}$ is large and scales
with $N$ for $r\in\mathcal{R}_{C}$ because otherwise these reactions
will not appear in the limit process anyway).

Define $S_{1}\subseteq\mathcal{R}_{DC}$ such that for a reaction
$r\in S_{1}$ the rate $\lambda_{r}$ is large and scales with $N$
and $\xi_{r}^{D}=0$. For each $r\in S_{1}$ define $\tilde{\lambda}_{r}=\frac{1}{N}\lambda_{r}$.

Define $S_{2}\subseteq\mathcal{R}_{DC}$ such that for a reaction
$r\in S_{2}$ the stochiometry $\xi_{r}^{C}$ is large and scales
with $N$. For each $r\in S_{1}$ define $\tilde{\xi}_{r}^{C}=\frac{1}{N}\xi_{r}^{C}$.

Define $S=S_{1}\cup S_{2}$.

Then we can write the random-time-change representation of the stochastic
process corresponding to this reaction network as

\begin{align*}
X^{N}(t)=\left(\Psi_{C}^{N},X_{D}^{N}\right)(t) & =x(0)\\
 & +\sum_{k\in\mathcal{R}_{C}}Y_{k}\left(\int_{0}^{t}\tilde{\lambda}_{k}\left(\Psi_{C}(s)\right)ds\right)\left(\frac{1}{N}\xi{}_{k}^{C},0\right)\\
 & +\sum_{k\in S_{1}}Y_{k}\left(\int_{0}^{t}N\tilde{\lambda}_{k}\left(X(s)\right)ds\right)\left(\frac{1}{N}\xi{}_{k}^{C},0\right)\\
 & +\sum_{k\in S_{2}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\tilde{\xi}_{k}^{C},\xi_{k}^{D}\right)\\
 & +\sum_{k\in\mathcal{R}_{DC\backslash S}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\frac{1}{N}\xi{}_{k}^{C},\xi{}_{k}^{D}\right)\\
 & +\sum_{k\in\mathcal{R}_{D}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi{}_{k}^{D}\right)
\end{align*}

\newtheorem{theorem}{Theorem}

\begin{theorem}
\label{theo:theorem_convergence}
The limit process of $X^{N}(t)$ for $N\rightarrow\infty$ is
\begin{align*}
	X(t) &
		\equiv\underset{N\rightarrow\infty}{\lim}X^{N}(t) = \left(\Psi_{C}(t),X_{D}(t)\right) \\
	& = x(0) \\
	& + \sum_{k\in\mathcal{R}_{C}}\int_{0}^{t}\tilde{\lambda}_{k}\left(\Psi_{C}(s)\right)ds\left(\xi{}_{k}^{C},0\right) \\
	& + \sum_{k\in S_{1}}\int_{0}^{t}\tilde{\lambda}_{k}\left(X(s)\right)ds\left(\xi{}_{k}^{C},0\right) \\
	& + \sum_{k\in S_{2}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\tilde{\xi}_{k}^{C},\xi_{k}^{D}\right) \\
	& + \sum_{k\in\mathcal{R}_{DC\backslash S}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi{}_{k}^{D}\right) \\
	& + \sum_{k\in\mathcal{R}_{D}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi{}_{k}^{D}\right)
\end{align*}
which is equivalent to a PDMP.
\end{theorem}

See \cite{crudu2012convergence} for a rigerous proof.

One should note that the distinction between $\mathcal{R}_{C}$ and
$S_{1}$ is just a formality (the dependence of the $\tilde{\lambda}_{r}$)
so we can define $S_{3}=\mathcal{R}_{C}\cup S_{1}$ and similarly
$S_{4}=\mathcal{R}_{D}\cup(\mathcal{R}_{DC}\backslash S)$ and write
the limit process as

\begin{align*}
X(t) & \equiv\underset{N\rightarrow\infty}{\lim}X^{N}(t)=\left(\Psi_{C}(t),X_{D}(t)\right)\\
 & =x(0)\\
 & +\sum_{k\in S_{3}}\int_{0}^{t}\tilde{\lambda}_{k}\left(X(s)\right)ds\left(\xi{}_{k}^{C},0\right)\\
 & +\sum_{k\in S_{2}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\tilde{\xi}_{k}^{C},\xi_{k}^{D}\right)\\
 & +\sum_{k\in S_{4}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi{}_{k}^{D}\right)
\end{align*}

\subsection{Averaging of some discrete variables}

\label{sub:PDMP_averaging}

Define $S_{5}\subseteq\mathcal{R}_{DC}$ such that for a reaction
$r\in S_{1}$ the rate $\lambda_{r}$ is large and scales with $N$
and $\xi_{r}^{D}\neq0$. For each $r\in S_{5}$ define $\tilde{\lambda}_{r}=\frac{1}{N}\lambda_{r}$.
Assume a decomposition $\left(x_{D}^{1},x_{D}^{2}\right)$ of the
$x_{D}$ such that $\xi_{r}^{D,1}=0$ and $\xi_{r}^{D,2}\neq0$ ($x_{D}^{1}$
could be empty).

Define $S=S_{1}\cup S_{2}\cup S_{5}$.

Then the random-time-change representation of the stochastic process
can be written as

\begin{align*}
X^{N}(t)=\left(\Psi_{C}^{N},X_{D}^{N}\right)(t) & =x(0)\\
 & +\sum_{k\in\mathcal{R}_{C}}Y_{k}\left(\int_{0}^{t}\tilde{\lambda}_{k}\left(\Psi_{C}(s)\right)ds\right)\left(\frac{1}{N}\xi{}_{k}^{C},0,0\right)\\
 & +\sum_{k\in S_{1}}Y_{k}\left(\int_{0}^{t}N\tilde{\lambda}_{k}\left(X(s)\right)ds\right)\left(\frac{1}{N}\xi{}_{k}^{C},0,0\right)\\
 & +\sum_{k\in S_{5}}Y_{k}\left(\int_{0}^{t}N\tilde{\lambda}_{k}\left(X(s)\right)ds\right)\left(\tilde{\xi}_{k}^{C},0,\xi_{k}^{D,2}\right)\\
 & +\sum_{k\in S_{2}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\tilde{\xi}_{k}^{C},\xi_{k}^{D,1},\xi_{k}^{D,2}\right)\\
 & +\sum_{k\in\mathcal{R}_{DC\backslash S}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\frac{1}{N}\xi{}_{k}^{C},\xi_{k}^{D,1},\xi_{k}^{D,2}\right)\\
 & +\sum_{k\in\mathcal{R}_{D}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi_{k}^{D,1},\xi_{k}^{D,2}\right)
\end{align*}

If $x_{D}^{2}$ only takes a finite number of values (i.e. there exists
a finite set $K$ such that $X_{D}^{2}\in K$) then the process $X_{D}^{2}$
given $\psi_{C},x_{D}^{1}$ is ergodic (every state can be reached
from a given state).

Define $\bar{\lambda}_{r}\left(\psi_{C},x_{D}^{1}\right)=\int_{K}\tilde{\lambda}_{r}\left(\psi_{C},x_{D}^{1},x_{D}^{2}\right)\nu_{\Psi_{C},x_{D}^{1}}\left(dx_{D}^{2}\right)$
for $r\in S_{5}$ where $\nu_{\Psi_{C},x_{D}^{1}}$ is the unique
invariant measure of the ergodic process $X_{D}^{2}$ given $\psi_{C},x_{D}^{1}$.

\begin{theorem}
\label{theo:theorem_convergence_averaging}
The limit process of $X^{N}(t)$ for $N\rightarrow\infty$ is
\begin{align*}
	X(t) &
		\equiv\underset{N\rightarrow\infty}{\lim}X^{N}(t) = \left(\Psi_{C}(t),X_{D}(t)\right) \\
	& = x(0) \\
	& + \sum_{k\in\mathcal{R}_{C}}\int_{0}^{t}\tilde{\lambda}_{k}\left(\Psi_{C}(s)\right)ds\left(\xi{}_{k}^{C},0,0\right) \\
	& + \sum_{k\in S_{1}}\int_{0}^{t}\tilde{\lambda}_{k}\left(X(s)\right)ds\left(\xi{}_{k}^{C},0,0\right) \\
	& + \sum_{k\in S_{5}}\int_{0}^{t}\bar{\lambda}_{k}\left(X(s)\right)ds\left(\xi{}_{k}^{C},0,0\right) \\
	& + \sum_{k\in S_{2}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(\tilde{\xi}_{k}^{C},\xi_{k}^{D,1},\xi_{k}^{D,2}\right) \\
	& + \sum_{k\in\mathcal{R}_{DC\backslash S}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi_{k}^{D,1},\xi_{k}^{D,2}\right) \\
	& + \sum_{k\in\mathcal{R}_{D}}Y_{k}\left(\int_{0}^{t}\lambda_{k}\left(X(s)\right)ds\right)\left(0,\xi_{k}^{D,1},\xi_{k}^{D,2}\right)
\end{align*}
which is again equivalent to a PDMP.
\end{theorem}

\subsection{Multiscale approximations of stochastic reaction networks}

For the following we limit ourselves to four types of reactions

\medskip{}

\begin{tabular}{|c|c|c|}
\hline
$\lambda_{k}$ & Reaction & $\nu_{k}$\tabularnewline
\hline
\hline
$\kappa'_{k}$ & $\emptyset\rightarrow stuff$ & $0$\tabularnewline
\hline
$\kappa'_{k}x_{i}$ & $S_{i}\rightarrow stuff$ & $e_{i}$\tabularnewline
\hline
$\kappa'_{k}V^{-1}x_{i}(x_{i}-1)$ & $2S_{i}\rightarrow stuff$ & $2e_{i}$\tabularnewline
\hline
$\kappa'_{k}V^{-1}x_{i}x_{j}$ & $S_{i}+S_{j}\rightarrow stuff$ & $e_{i}+e_{j}$\tabularnewline
\hline
\end{tabular}

\bigskip{}

whereas $V$ corresponds to the volume of the system and the $\kappa'_{k}$
correspond to molecular reaction rates.

Define
\begin{itemize}
\item $z_{i}^{N}(t)=N^{-\alpha_{i}}x_{i}^{N}(t)$ with $\alpha_{i}\geq0$
for $i=1,...,s_{0}$
\item $\kappa_{k}=N^{-\beta_{k}}\kappa'_{k}$ for $k=1,...,r_{0}$
\end{itemize}
with a parameter $N$ that is assumed to be large.

The rates of the four types of reactions can now be written as

\medskip{}

\begin{tabular}{|c|c|}
\hline
Reaction & $\lambda_{k}^{N}$\tabularnewline
\hline
\hline
$\emptyset\rightarrow stuff$ & $N^{\beta_{k}}\kappa_{k}$\tabularnewline
\hline
$S_{i}\rightarrow stuff$ & $N^{\beta_{k}+\alpha_{i}}\kappa_{k}z_{i}$\tabularnewline
\hline
$2S_{i}\rightarrow stuff$ & $N^{\beta_{k}+2\alpha_{i}}\kappa_{k}V^{-1}z_{i}(z_{i}-N^{-\alpha_{i}})$\tabularnewline
\hline
$S_{i}+S_{j}\rightarrow stuff$ & $N^{\beta_{k}+\alpha_{i}+\alpha_{j}}\kappa_{k}V^{-1}z_{i}z_{j}$\tabularnewline
\hline
\end{tabular}

\bigskip{}

So we have
\[
\lambda_{k}(x)\left(\nu'_{k}-\nu_{k}\right)=N^{\beta_{k}+\nu_{k}\cdot\alpha}\lambda_{k}^{N}(z)\left(\nu'_{k}-\nu_{k}\right)
\]
 whereas $\alpha=\left(\alpha_{1},...,\alpha_{s_{0}}\right)^{T}$
. With this we can write the corresponding multiscale Markov Jump
Process as

\[
Z_{i}^{N}(t)=z(0)+\sum_{k=1}^{r_{0}}N^{-\alpha_{i}}Y_{k}\left(\int_{0}^{t}N^{\beta_{k}+\nu_{k}\cdot\alpha}\lambda_{k}^{N}\left(Z_{i}^{N}(s)\right)ds\right)\left(\nu'_{ik}-\nu_{ik}\right)
\]

The $\alpha_{i}$ and $\beta_{i}$ should be choosen in such a way,
that the $z_{i}$ and $\kappa_{k}$ are of order 1 in a loose sense.

In addition we introduce a further scaling parameter $\gamma$ for
the time-scale of the process and write

\[
Z_{i}^{N,\gamma}(t)=Z_{i}^{N}(N^{\gamma}t)=z(0)+\sum_{k=1}^{r_{0}}N^{-\alpha_{i}}Y_{k}\left(\int_{0}^{t}N^{\gamma+\beta_{k}+\nu_{k}\cdot\alpha}\lambda_{k}^{N}\left(Z_{i}^{N,\gamma}(s)\right)ds\right)\left(\nu'_{ik}-\nu_{ik}\right)
\]

See \cite{kang2013separation} for a more elaborate discussion.

\subsection{Constraints for selection of the scaling parameters}

\label{sec:multiscale_parametrization_constraints}

In \cite{kang2013separation} Kang et al. derive constraints for the
selection of the scaling parameters $\alpha_{i},\beta_{i},\gamma$
that we recapitulate here.

\newtheorem{condition}{Condition}

\begin{condition}
Define $\Gamma_{i}^{+}=\{k:\nu'_{ik}>\nu_{ik}\}$ and $\Gamma_{i}^{-}=\{k:\nu'_{ik}<\nu_{ik}\}$. Then the condition
\[ 	\underset{k\in\Gamma_{i}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)=\underset{k\in\Gamma_{i}^{+}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
\]
or
\[
	\gamma\leq\alpha_{i}-\underset{k\in\Gamma_{i}^{+}\cup\Gamma_{i}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
\]
is called the \textbf{species balance condition} and ensures that no species explodes or is driven to zero.
\end{condition}

We can generalize this condition to linear combinations $\Theta\cdot z$
of species with $\Theta\in[0,\infty)^{s_{0}}$.

\begin{condition}
\label{cond:coll_species_balance}
Define $\Gamma_{\Theta}^{+}=\{k:\Theta\cdot\xi_{k}>0\}$ and $\Gamma_{\Theta}^{-}=\{k:\Theta\cdot\xi_{k}<0\}$. Then the condition
\begin{equation}
	\label{cond:coll_species_balance1}
	\underset{k\in\Gamma_{\Theta}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)=\underset{k\in\Gamma_{\Theta}^{+}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
\end{equation}
or
\begin{equation}
	\label{cond:coll_species_balance2} 	\gamma\leq\gamma_{i}\equiv\underset{i:\Theta_{i}>0}{\max}\alpha_{i}-\underset{k\in\Gamma_{\Theta}^{+}\cup\Gamma_{\Theta}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
\end{equation}
is called the \textbf{collective species balance condition}. It ensures that no linear combination of species explodes or is driven to zero.
\end{condition}

Checking this condition is not trivial but in \cite{kang2013separation}
Kang et al. show a significant simplification to check for the \textbf{collective
species balance condition}:

\newtheorem{lemma}{Lemma}
\label{lemma:coll_species_balance_graph}

\begin{lemma}
Let $G$ be a directed graph where the nodes correspond to the species and a directed edge from $S_{i}\rightarrow S_{j}$ is drawn
if there is a reaction consuming $S_{i}$ and producing $S_{j}$.

Let $G_{j}$ be maximal strongly connected subgraphs such that $G=\cup_{j}G_{j}$ (this decomposition is unique).

Let $\gamma \in \mathbb{R}$ be fixed. If Condition \ref{cond:coll_species_balance} holds for each $\Theta \in [0,\infty)^{s_0}$ with
$\mbox{supp} \left(\Theta\right) \subset G_j$ for all maximal strongly connected subgraphs $G_j$, then Condition \ref{cond:coll_species_balance}
holds for all $\Theta \in [0,\infty)^{s_0}$.
\end{lemma}

This reduces checking Condition \ref{cond:coll_species_balance} for
all $\Theta\in[0,\infty)^{s_{0}}$ to checking Condition \ref{cond:coll_species_balance}
for all $\Theta$ with $\mbox{supp}\left(\Theta\right)\subset G_{j}$
for each of the subgraphs $G_{j}$ separately.

\begin{lemma}
\label{lemma:coll_species_balance_special_case1}
Kang et al. continue to show that Condition \ref{cond:coll_species_balance} also holds for $c_{1}\Theta^{1}+c_{2}\Theta^{2}$ for all $c_{1},c_{2} > 0$ if either

\[
	\mbox{(\ref{cond:coll_species_balance2}) holds for $\Theta^1$ or $\Theta^2$}
\]

or

\begin{align*}
	& \underset{k\in\Gamma_{\Theta^{1}}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
		= \underset{k\in\Gamma_{\Theta^{1}}^{+}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)\nonumber \\
	\neq & \underset{k\in\Gamma_{\Theta^{2}}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
		= \underset{k\in\Gamma_{\Theta^{2}}^{+}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
\end{align*}
\end{lemma}

\begin{lemma}
\label{lemma:coll_species_balance_special_case2}
If Lemma \ref{lemma:coll_species_balance_special_case1} does not apply but
\[
	\Gamma_{\Theta^{1}}^{+}\cap\Gamma_{\Theta^{2}}^{-} = \emptyset
\]
or
\[
	\Gamma_{\Theta^{1}}^{-}\cap\Gamma_{\Theta^{2}}^{+} = \emptyset
\]
(i.e. the support of $\Theta^{1}$ produces no species that are consumed in the support of $\Theta^{2}$ and vice versa),
then Condition \ref{cond:coll_species_balance} holds for
$c_{1}\Theta^{1}+c_{2}\Theta^{2}$ for all $c_{1},c_{2} > 0$.
\end{lemma}

\begin{lemma}
\label{lemma:coll_species_balance_special_case3}
If Lemma \ref{lemma:coll_species_balance_special_case1} does not apply and
$\Gamma_{\Theta^{1}}^{+}\cap\Gamma_{\Theta^{2}}^{-} \neq \emptyset$
and $\Gamma_{\Theta^{1}}^{-}\cap\Gamma_{\Theta^{2}}^{+} \neq \emptyset$
suppose that Condition \ref{cond:coll_species_balance} also holds for $\Theta^1 - \frac{\Theta^1 \cdot \xi_k}{\Theta^2 \cdot \xi_k} \Theta^2$
for all $k \in \left( \Gamma_{\Theta^1}^+ \cap \Gamma_{\Theta^2}^- \right) \cup \left(\Gamma_{\Theta^1}^- \cap \Gamma_{\Theta^2}^{+} \right)$.
Then Condition \ref{cond:coll_species_balance} also holds for $c_1 \Theta^1 + c_2 \Theta^2$ for all $c_1, c_2 > 0$.
\end{lemma}

The only case that is left now is that

(\ref{cond:coll_species_balance2}) doesn't hold for both $\Theta^{1}$
and $\Theta^{2}$ and $\Gamma_{\Theta^{1}}^{+}\cap\Gamma_{\Theta^{2}}^{-}\neq\emptyset$
and $\Gamma_{\Theta^{1}}^{-}\cap\Gamma_{\Theta^{2}}^{+}\neq\emptyset$
and Condition \ref{cond:coll_species_balance} doesn't hold for $\Theta^{1}-\frac{\Theta^{1}\cdot\xi_{k}}{\Theta^{2}\cdot\xi_{k}}\Theta^{2}$
and

\begin{align*}
 & \underset{k\in\Gamma_{\Theta^{1}}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)=\underset{k\in\Gamma_{\Theta^{1}}^{+}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)\\
= & \underset{k\in\Gamma_{\Theta^{2}}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)=\underset{k\in\Gamma_{\Theta^{2}}^{+}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)
\end{align*}

all hold. We call this case \emph{non-reducable collective species
balance.} In this case Condition \ref{cond:coll_species_balance}
has to be checked directly (of course this only needs to be done for
all $\Theta\in[0,\infty)^{s_{0}}$ with support in the subgraphs $G_{j}$
with a \emph{non-reducable collective species balance}).

In all other cases it is now sufficient to check Condition \ref{cond:coll_species_balance}
on a set $\Theta^{j,k}$ spanning the subgraph $G_{j}$ for all $j$.

\begin{theorem}
For completeness we state that if
\[ 	\gamma=\underset{i}{\min}\gamma_{i}=\underset{i}{\min}\left(\alpha_{i}-\underset{k\in\Gamma_{\Theta}^{+}\cup\Gamma_{\Theta}^{-}}{\max}\left(\beta_{k}+\nu_{k}\cdot\alpha\right)\right)
\]
then each term
\[
	N^{-\alpha_{i}}Y_{k}\left(\int_{0}^{t}N^{\gamma+\beta_{k}+\nu_{k}\cdot\alpha}\lambda_{k}^{N}\left(Z_{i}^{N,\gamma}(s)\right)ds\right)
\]
converges to
\[
\begin{cases}
	0 &
		\mbox{for }\alpha_{i}>\gamma+\beta_{k}+\nu_{k}\cdot\alpha \\
	Y_{k}\left(\int_{0}^{t}\lambda_{k}^{N}\left(Z_{i}^{N,\gamma}(s)\right)ds\right) &
		\mbox{for }\alpha_{i}=\gamma+\beta_{k}+\nu_{k}\cdot\alpha=0 \\
	\int_{0}^{t}\lambda_{k}^{N}\left(Z_{i}^{N,\gamma}(s)\right)ds &
		\mbox{for }\alpha_{i}=\gamma+\beta_{k}+\nu_{k}\cdot\alpha
\end{cases}
\]
for $N\rightarrow\infty$ which represents a PDMP of the multiscale network.
\end{theorem}

\subsection{Combination of convergence results and multiscale parametrization}

To combine the convergence results from \ref{sub:PDMP_convergence}
with the multiscale Parametrization we note that the membership of
a species $x_{i}$ in $x_{C},x_{D}$ depends on $\alpha_{i}$:

$\begin{cases}
x_{i}\mbox{ belongs to }x_{C} & \mbox{ for }\alpha_{i}>0\\
x_{i}\mbox{ belongs to }x_{D} & \mbox{ for }\alpha_{i}=0
\end{cases}$

We also note that $r\in S_{1}$ if $\gamma+\beta_{r}+\nu_{r}\cdot\alpha>0$
and $\xi_{r}^{D}=0$ (if $\xi_{r}^{D}\neq0$ one can still take the
approach in \ref{sub:PDMP_averaging}).

We can then use Theorem \ref{theo:theorem_convergence} or Theorem
\ref{theo:theorem_convergence_averaging} to derive the PDMP that
corresponds to the limiting process of the multiscale network.

\section{Implementation}

Here we summarize how the adaptive multiscale network is implemented
as a PDMP, how to simulate the PDMP and then go into more details
about the steps of the adaptation.

\subsection{Adaptive Multiscale Network as a PDMP}

To distinguish between stochastic and deterministic reactions we follow
the theoretical foundation stated further up with an additional threshold
parameter $\delta\geq0$

\[
\begin{cases}
Y_{k}\left(\int_{0}^{t}\lambda_{k}^{N}\left(Z_{i}^{N,\gamma}(s)\right)ds\right) & \mbox{for }\alpha_{i}<\delta\\
\int_{0}^{t}\lambda_{k}^{N}\left(Z_{i}^{N,\gamma}(s)\right)ds & \mbox{for }\alpha_{i}\geq\delta
\end{cases}
\]

If any term of a reaction is stochastic by the previous definition,
then the whole reaction is treated stochastically, as we have to simulate
the stochastic event anyway.

The $\alpha_{i}$ and $\beta_{k}$ are computed by solving the following
linear program:

\begin{center}
\begin{equation}
\begin{array}{ccc}
\mbox{maximize } & \sum_{i=1}^{Q}\frac{\alpha_{i}}{A_{i}}+\sum_{i=1}^{W}\frac{\beta_{k}}{B_{k}}\\
\\
\mbox{subject to } & 0\leq\alpha_{i}\leq A_{i} & \mbox{ for each \ensuremath{i\in\{1,...,Q\}}}\\
\mbox{and } & \beta_{k}\leq B_{k} & \mbox{for each }k\in\{1,...,W\}\\
\mbox{and } & \alpha_{i}\geq\beta_{k}+\alpha\cdot\nu_{k} & \mbox{ for each \ensuremath{i\in\{1,...,Q\},\ k\in\{1,...,W\}}}
\end{array}\label{eq:linear_program_alpha_beta}
\end{equation}

\par\end{center}

whereas $A_{i}=\frac{\log(x_{i})}{\log(N)}{\color{green}+1}$ and
$B_{i}=\frac{log(\kappa'_{k})}{\log(N)}{\color{green}+1}$.

If a species $i$ has $\alpha_{i}\geq\delta$ it is a scaled species,
otherwise it is an unscaled species.

In the next step the reaction graph is searched for subnetworks that
can be averaged (see section \ref{subsection:averaging}).

\subsection{Simulation of a PDMP with adaptation}

{\footnotesize \begin{algorithm}
\label{PDMP_algorithm}
\algblock[evolve]{evolve}{until}
\algblockdefx[evolve]{Evolve}{EndEvolve}%
	{\textbf{evolve}}%
	{\textbf{until }}
\begin{algorithmic}
\State $t\gets t_0$
\State $X\gets x_0$
\State $i\gets 0$
\State $Y\gets [\mbox{exprnd}\left(1\right), 0]$
\While {$t_0 \leq t_1$}
	\Evolve
		\State $X$ according to $X'(t) = \sum_{M_D} \lambda_k\left(X(t)\right) \left(\nu'_k - \nu_k\right)$
		\State $Y$ according to $Y'(t) = [0, \sum_{M_S} \lambda_k\left(X(t)\right)]$
	\EndEvolve {either $t=t_1$ or $Y_1 = Y_2$ or \textit{copy number bounds have been crossed}}
	\If {\textit{copy number bounds have been crossed}}
		\State Adapt scaling parameters and update scaled copy numbers
	\ElsIf {$Y_1=Y_2$}
		\State $Y\gets [\mbox{exprnd}\left(1\right), 0]$
		\State $r\gets k \mbox{ with probability } p_k\propto \lambda_k\left(X\right)$
		\State $X\gets X + \nu'_k - \nu_k$
	\EndIf
\EndWhile
\end{algorithmic}
\end{algorithm}}{\footnotesize \par}

\subsection{Copy number bounds}

As stated in the algorithm \ref{PDMP_algorithm} an adaptation procedure
is performed whenever the copy number bounds are crossed. These bounds
are defined by two parameters $\delta\geq0$ and $\eta>0$. The copy
number bounds for an unscaled species $i$ are $0\leq x_{i}<N^{\delta}$
and the bounds for a scaled species $j$ are $N^{-\eta}<z_{j}=N^{-\alpha_{j}}x_{j}<N^{\eta}$.

An unscaled species $i$ that crosses it's upper copy number bound
$N^{\delta}$ can be a scaled species after the adaptation. Only when
the copy number of the scaled species crosses it's lower bound $N^{-\eta}$
will the species revert to an unscaled species. This means that there
is a hysteresis-like effect for the switching between unscaled and
scaled copy numbers for a species. In the range $(N^{-\eta}N^{\delta},N^{\delta})$
of real copy numbers a species can be either scaled or unscaled depending
on whether the species was unscaled or scaled before the switching.
This might seem like an inconvenience of the implementation but actually
this is necessary to prevent endless adaptation and thus a high performance
penalty due to numerical errors and small changes in the copy numbers
and also to enable the detection of crossings of copy number bounds
by root finding during the ODE integration in the first place.

\subsection{Averaging}

\label{subsection:averaging}

After the $\alpha_{i}$ and $\beta_{k}$ have been computed a timescale
$\tau_{i}$ is computed for each species as follows:

\[
\tau_{i}:=\frac{q_{i}}{\sum_{k\ s.t.\ v'_{ik}\neq0}\sum_{j}|q\nu_{jk}|}
\]

whereas $q_{i}=\max(x_{i},1)$.

Now for each possible subset $S$ of species we compute the timescale
of the subset $\tau_{S}$ and the timescale of the outside network
$\tau_{\bar{S}}$ as follows:

\[
\tau_{S}=max_{i\in S}(\tau_{i})
\]

\[
\tau_{\bar{S}}=min_{i\in\bar{S}}(\tau_{i})
\]

whereas $\bar{S}$ is the set of species $j$ that are directly involved
in reactions with species $i\in S$. That is either

\[
\bar{S}=\bar{S}_{1}\cup\bar{S}_{2}
\]

\[
\bar{S}_{1}=\{j:\nu'_{kj}\neq0\mbox{ and }\nu_{ki}\neq0\mbox{ for some }i\in S\mbox{ and }k\}
\]

\[
\bar{S}_{2}=\{j:\nu{}_{kj}\neq0\mbox{ and }\nu'_{ki}\neq0\mbox{ and }l\mbox{ is connected to }j\mbox{ for some }i,l\in S\mbox{ and }k\}
\]

If $\frac{\tau_{\bar{S}}}{\tau_{S}}\geq\theta$ and for all reactions
$k$ there is no $i\in S$ s.t. $\nu_{ki}>1$ and no $i,j\in S$ s.t.
$\nu_{ki}>0$ and $\nu_{kj}>0$ then we remember $S$ as a candidate
subnetwork for averaging.

Finally we start with an empty list $L_{A}$ of species to average
and an empty list $L$ of subnetworks to average and iterate in order
of decreasing number of species over the candidate subnetworks. If
$L_{A}\cap S=\emptyset$ we add all the species from $S$ to $L_{A}$
and add $S$ to $L$. After the iteration $L$ contains all the subnetworks
to average so we treat the copy numbers of all species of those subnetworks
as continuous and all the reactions within those subnetwork as deterministic.

\bibliographystyle{plain}
\bibliography{/home/bhepp/Documents/papers}

\end{document}


%
%==> Section: TikZ libraries
%
\section{
  Ti$k$Z libraries
}
%
%==> TikZ libraries
%
\begin{frame}
  \frametitle{
    Ti$k$Z libraries
  }
  \begin{itemize}
  \item
    To provide simpler methods to create complex structures
    libraries for Ti$k$Z has \textcolor{purple}{\tt $\backslash$usetikzlibary}
  \item
    Different examples are: \textcolor{blue}{ \tt decorations.fractals},  \textcolor{blue}{ \tt arrows}, \textcolor{blue}{ \tt backgrounds}, \textcolor{blue}{ \tt intersections}, and \textcolor{blue}{ \tt shapes.geometric}.
  \end{itemize}
\end{frame}

%
%==> Examples
%
\begin{frame}[fragile]
  \frametitle{
    And now for some examples
  }

  First you must add

  \begin{lstlisting}
    \usetikzlibrary{backgrounds}
  \end{lstlisting}

  to your preamble

  \begin{center}
    \input{./tex/src/tikz_lib_backgrounds_example.tex}
  \end{center}

  \lstinputlisting{./tex/src/tikz_lib_backgrounds_example.tex}

\end{frame}

%
%==> Koch snowflake
%
\begin{frame}[fragile]
  \begin{itemize}
  \item
    For the Koch snowflake, first you must add

    \begin{lstlisting}
      \usetikzlibrary{decorations.fractals}
    \end{lstlisting}

    to your preamble

    % Generate image
    \begin{center}
      \begin{tikzpicture}[decoration=Koch
          snowflake,draw=blue,fill=green!20,thick]
        \filldraw decorate{ decorate{ (0,0) --
            ++(60:1) -- ++(-60:1) -- cycle}};
      \end{tikzpicture}
    \end{center}

    % Source file
    \begin{lstlisting}
      \begin{tikzpicture}[decoration=Koch
          snowflake,draw=blue,fill=green!20,thick]
        \filldraw decorate{ decorate{ (0,0) --
            ++(60:1) -- ++(-60:1) -- cycle}};
      \end{tikzpicture}
    \end{lstlisting}

  \item
    Don't forget to put the correct Ti$k$Z library in your preamble.

  \end{itemize}

\end{frame}


The \mEdhoc{} \mSpec{} \cite{our-analysis-selander-lake-edhoc-00} claims
that \mEdhoc{} satisfies many security properties, but these are imprecisely
expressed and motivated.
%
In particular, there is no coherent adversary model.
%
It is therefore not clear in which context properties should be verified.
%
We resolve this by clearly specifying an adversary model, in which we can verify
properties.
%

\subsection{Adversary Model}\label{sec:threat-model}
We verify \mEdhoc{} in the symbolic Dolev-Yao model, with idealized
cryptographic primitives, e.g, encrypted messages can only be
decrypted using the key, no hash collisions exist etc.
%
The adversary controls the
communication channel, and can interact with an unbounded number of sessions
of the protocol, dropping, injecting and modifying messages at their liking.
%

In addition to the basic Dolev-Yao model, we also consider two more adversary
capabilities, namely long-term key reveal and ephemeral key reveal.
%
Long-term key reveal models an adversary compromising a party $A$'s
long-term private key \mPriv{A} at time $t$, and we denote this event by
$\mRevLTK^t(A)$.
%
The event $\mRevEph^t(A, k)$ represents that the adversary learns
the ephemeral private key \mPrivE{A} used by party $A$ at time $t$ in a session
establishing key material $k$.
%
These two capabilities model the possibility to store and operate on
long-term keys in a secure module, whereas ephemeral keys
may be stored in a less secure part of a device.
%
This is more granular and realistic than assuming an adversary have equal
opportunity to access both types of keys.
%

We now define and formalize the security properties we are interested in, and
then describe how we encode them into \mTamarin{}-tool.
%
The adversary model becomes part of the security properties themselves.
%

\subsection{Formalization of Properties}
\label{sec:desired-properties}
We use the \mTamarin{} verification
tool~\cite{DBLP:conf/cav/MeierSCB13} to encode the model and verify properties.
%
This tool uses a fragment of temporal first order logic to reason about
events and knowledge of the parties and of the adversary.
%
For conciseness we use a slightly different syntax than
that used by \mTamarin{}, but which has a direct mapping to \mTamarin{}'s logic.
%

Event types are predicates over global states of system execution.
%
Let $E$ be an event type and let $t$ be a timestamp associated with a point in a
trace.
%
Then $E^{t}(p_i)_{i\in\mathbb{N}}$ denotes an event of type $E$ associated with
a sequence of parameters $(p_i)_{i\in\mathbb{N}}$ at time $t$ in that trace.
%
In general, more than one event may have the same timestamp and hence
timestamps form a quasi order, which we denote by $t_1 \lessdot t_2$ when $t_1$
is before $t_2$ in a trace.
%
We define $\doteq$ analogously.
%
However, two events of the same type cannot have the same timestamp, so
$t_1 \doteq t_2$ implies $E^{t_1} = E^{t_2}$.
%
Two events having the same timestamp does not imply the there is a fork in the
trace, only that the two events happen simultaneously and that comparing their
timestamps results in that they are equal.
%
This notation corresponds to \mTamarin{}'s use of action facts
$E(p_i)_{i\in\mathbb{N}}@t$.
%

The event $\mK^t(p)$ denotes that the adversary knows a parameter $p$ at
time $t$.
%
Parameters are terms in a term algebra of protocol specific operations and
generic operations, e.g., tuples $\langle\cdot\rangle$.
%
Intuitively, $\mK^t(p)$ evaluates to true when $p$ is in
the closure of the
parameters the adversary observed from interacting with parties using the
protocol, under the Dolev-Yao message deduction operations and
the advanced adversary capabilities up until time $t$.
%
For a more precise definition of knowledge management, we refer to~\cite{DBLP:conf/cav/MeierSCB13}.
%
An example of a formula is
\[
    \forall t, k, k'\mLogicDot \mK^{t}(\langle k, k'\rangle)\ \rightarrow\
\mK^{t}(k) \land \mK^{t}(k'),
\]
expressing that if there is a time $t$ when the adversary knows the tuple
$\langle k, k'\rangle$, then the adversary knows both
$k$ and $k'$ at the same point in time.
%

An initiator $I$ considers the
protocol run started when it sends a message \mMsgone{} (event type \mIStart)
and the run completed after sending a message \mMsgthree{} (event type
\mIComplete).
%
Similarly, a responder $R$ considers the run started upon receiving
a \mMsgone{} (event type \mRStart), and completed upon receiving a \mMsgthree{}
(event type \mRComplete).
%

%----------------------------------------------------------------------- PFS
\subsubsection{Perfect Forward Secrecy (PFS)}
\label{sec:secrecy}
Informally, PFS captures the idea that session key material remains secret
even if a long-term key leaks in the future.
%
We define PFS for session key material \mSessKey{} as \mPredPfs{} in
Figure~\ref{fig:props}.
%

\begin{figure*}
\begin{align*}
    \mPredPfs \triangleq\ & \forall I, R, \mSessKey, t_2, t_3\mLogicDot
    \mK^{t_3}(\mSessKey)\  \land\
    (\mIComplete^{t_2}(I, R, \mSessKey)\, \lor\, \mRComplete^{t_2}(I, R, \mSessKey))
    \rightarrow\\
    &(\exists t_1\mLogicDot \mRevLTK^{t_1}(I) \land t_1 \lessdot t_2)
    \ \lor\ (\exists t_1\mLogicDot \mRevLTK^{t_1}(R) \land t_1 \lessdot t_2)
    \ \lor\ (\exists t_1\mLogicDot \mRevEph^{t_1}(R, \mSessKey))
    \ \lor\ (\exists t_1\mLogicDot \mRevEph^{t_1}(I, \mSessKey))
\end{align*}
\begin{align*}
    \mPredInjI \triangleq\ &
    \forall I, R, \mSessKey, S, t_2\mLogicDot \mIComplete^{t_2}(I, R, \mSessKey, S)
    \rightarrow\\
    &(\exists t_1\mLogicDot \mRStart^{t_1}(R, \mSessKey, S) \land t_1 \lessdot t_2)
    \land (\forall I' R' t_1' \mLogicDot \mIComplete^{t_1'}(I' , R', \mSessKey, S)
        \rightarrow t_1' \doteq t_1)
    \ \ \lor\ \ (\exists t_1\mLogicDot \mRevLTK^{t_1}(R) \land t_1 \lessdot t_2)
\end{align*}
\begin{align*}
    \mPredInjR \triangleq\ &
    \forall I, R, \mSessKey, S, t_2\mLogicDot \mRComplete^{t_2}(I, R, \mSessKey, S)
    \rightarrow\\
    &(\exists t_1\mLogicDot \mIStart^{t_1}(I, R, \mSessKey, S) \land t_1 \lessdot t_2)
    \land (\forall I' R' t_1' \mLogicDot \mRComplete^{t_1'}(I' , R', \mSessKey, S)
        \rightarrow t_1' \doteq t_1)
    \ \ \lor\ \ (\exists t_1\mLogicDot \mRevLTK^{t_1}(I) \land t_1 \lessdot t_2).
\end{align*}
\begin{align*}
    \mPredImpI \triangleq\ &
    \forall I, R, \mSessKey, S, t_1\mLogicDot \mIComplete^{t_1}(I, R, \mSessKey, S)
    \rightarrow\\
      &(\forall I', R', S', t_2\mLogicDot \mRComplete^{t_2}(I', R', \mSessKey, S') \rightarrow
             (I=I' \land R=R' \land S=S'))\\
      &\land (\forall I', R', S', t_1'\mLogicDot
        (\mIComplete^{t_1'}(I', R', \mSessKey, S') \rightarrow t_1' \doteq t_1
        )\\
      &\ \ \ \lor(\exists t_0\mLogicDot \mRevLTK^{t_0}(R) \land t_0 \lessdot t_1)
    \lor(\exists t_0\mLogicDot \mRevEph^{t_0}(R, \mSessKey))
    \lor(\exists t_0\mLogicDot \mRevEph^{t_0}(I, \mSessKey)).
\end{align*}
%
\caption{Formalization of security properties and adversary model.}
\label{fig:props}
\end{figure*}

The first parameter $I$ of the \mIComplete{} event represents the
initiator's identity,
and the second, $R$, represents that $I$ believes $R$ to be playing
the responder role.
%
The third parameter, \mSessKey{}, is the established session key material.
%
The parameters of the \mRComplete{} event are defined analogously.
%
Specifically, the first parameter of \mRComplete{} represents the identity of
whom $R$ believes is playing the initiator role.
%
The essence of the definition is that an adversary only knows \mSessKey{} if they
compromised one of the
parties long-term keys before that party completed the run, or if the adversary
compromised any of the ephemeral keys at any time after a party starts
its protocol run.
%
One way the definition slightly differs from the corresponding \mTamarin{} lemma
is that \mTamarin{} does not allow a disjunction on the left-hand side of an
implication in a universally quantified formula.
%
In the lemma, therefore, instead of the disjunction
$\mIComplete^{t_2}(I, R, \mSessKey)\, \lor\,  \mRComplete^{t_2}(I, R, \mSessKey)$,
we use a single action parametrized by $I$, $R$, and \mSessKey{} to signify that
\emph{either} party has completed their role.
%

%-------------------------------------------------------------------- InjAgree
\subsubsection{Authentication}
\label{sec:authenticationDef}
We prove two different flavors of authentication, the first being classical
\emph{injective agreement} following Lowe~\cite{DBLP:conf/csfw/Lowe97a}, and
the second being an implicit agreement property.
%
Informally, injective agreement guarantees to an initiator $I$ that whenever
$I$ completes a run ostensibly with a responder $R$,
then $R$ has been engaged in the protocol as a responder,
and this run of $I$ corresponds to a unique run of $R$.
%
In addition, the property guarantees to $I$ that the two parties agree on a set
$S$ of parameters associated with the run, including, in particular, the
session key material \mSessKey{}.
%
However, we will treat \mSessKey{} separately for clarity.
%
On completion, $I$ knows that $R$ has access to the session key material.
%
The corresponding property for $R$ is analogous.
%

Traditionally, the event types used to describe injective agreement are called
\emph{Running} and \emph{Commit}, but to harmonize the presentations of
authentication and PFS in this section, we refer to these event types as
\mIStart{} and \mIComplete{} respectively for the initiator, and
\mRStart{} and \mRComplete{} for the responder.
%
For the initiator role we define injective agreement by
\mPredInjI{} in Figure~\ref{fig:props}.

%
The property captures that for an initiator $I$, either the injective agreement
property as described above holds, or the long-term key of the believed
responder $R$ has been compromised before $I$ completed its role.
%
Had the adversary compromised $R$'s long-term key, they could have generated a
message of their liking (different to what $R$ agreed on), and signed this or
computed a $\mathit{MAC}_R$ based on \mPubE{I}, \mPriv{R} and their own chosen
ephemeral key pair $\langle\mPrivE{R},\ \mPubE{R}\rangle$.
%
This places no restrictions on the ephemeral
key reveals, or on the reveal of the initiator's long-term key.
%
For the responder we define the property \mPredInjR{} as in
Figure~\ref{fig:props}.
%

%------------------------------------------------------------- Implicit auth
Unlike PFS, not all \mEdhoc{} methods enjoy the injective agreement property.
%
Hence, we show for all methods a form of \emph{implicit agreement} on all the
parameters mentioned above.
%
We take inspiration from the computational model definitions of implicit
authentication, proposed by Guilhem~et~al.~\cite{DBLP:conf/csfw/GuilhemFW20}, to
modify classical injective agreement into an implicit property.
%
A small but important difference between our definition and theirs, is that
they focus on
authenticating a key and related identities, whereas we extend the more general
concept of agreeing on a set of parameters, starting from the idea of injective
agreement~\cite{DBLP:conf/csfw/Lowe97a}.
%
We use the term \emph{implicit} in this context to denote that a party $A$
assumes that any other party $B$ who knows the session key material \mSessKey{} must
be the intended party, and that $B$ (if honest) will also agree on a set
$S$ of parameters computed by the protocol, one of which is \mSessKey{}.
%
When implicit agreement holds for both roles, upon completion, $A$ is guaranteed
that $A$ has been or is engaged in exactly one protocol run with $B$ in the
opposite role, and that $B$ has been or will be able to agree on $S$.
%
The main difference to injective agreement is that $A$ concludes that if
$A$ sends the last message and this reaches $B$, then $A$ and $B$ have agreed
on $I$, $R$ and $S$.
%
While almost full explicit key authentication, as defined by
Guilhem~et~al.~\cite{DBLP:conf/csfw/GuilhemFW20}, is a similar property, our
definition does not require key confirmation, so our definition is closer to
their definition of implicit authentication.
%
In the \mTamarin{} model we split the property into one lemma for
$I$ (\mPredImpI{}) and one for $R$ (\mPredImpR{}) to save memory during
verification.
%
We show only the definition for $I$ in Figure~\ref{fig:props}, because it is
symmetric to the one for $R$.
%

For implicit agreement to hold for the initiator $I$, the ephemeral keys
can never be revealed.
%
Intuitively, the reason for this is that the implicit agreement relies on that
whomever knows the session key material is the intended responder.
%
An adversary with access to the ephemeral keys and the public keys of
both parties can compute the session key material produced by all methods.
%
However, the responder $R$'s long-term key can be revealed after $I$ completes
its run, because the adversary is still unable to compute $P_e$.
%
The initiator's long-term key can also be revealed at any time without affecting
$I$'s guarantee for the same reason.
%

%------------------------------------------------------- Agreed parameters
\subsubsection{Agreed Parameters}
\label{sec:agreedParams}
The initiator $I$ gets injective and implicit agreement guarantees on the
following partial set $S_P$ of parameters:
\begin{itemize}
    \item the roles played by itself and its peer,
    \item responder identity,
    \item session key material (which varies depending on \mEdhoc{} method),
    \item context identifiers \mCi{} and \mCr{}, and
    \item cipher suites \mSuites{}.
\end{itemize}
%
Because \mEdhoc{} aims to provide identity protection for $I$, there is no
injective agreement guarantee for $I$ that $R$ agrees on the initiator's
identity.
%
For the same reason, there is no such guarantee for $I$ with respect to
the $P_I$ part of the session key material when $I$ uses the \mStat{}
authentication method.
%
There is, however, an implicit agreement guarantee for $I$ that $R$ agrees on
$I$'s identity and the full session key material.
%
Since $R$ completes after $I$, $R$ can get injective agreement guarantees on
more parameters, namely also the initiator's identity and the full session key
material for all methods.
%
The full set of agreed parameters $S_F$ is $S_P \cup \{I, P_I\}$
when $P_I$ is
part of the session key material, and $S_P \cup \{I\}$ otherwise.
%

%------------------------------------------------------- Implied properties
\subsubsection{Inferred Properties}
From the above, other properties can be inferred to hold in our adversary model.
%
Protocols where a party does not get confirmation that their peer knows the
session key material may be susceptible to
\emph{Key-Compromise Impersonation (KCI)}
attacks~\cite{DBLP:conf/ima/Blake-WilsonJM97}.
%
Attacks in this class allow an adversary in possession of a party $A$'s secret
long-term key to coerce $A$ to complete a
protocol run believing it authenticated a certain peer $B$, but where $B$ did
not engage with $A$ at all in a run.
%
Because both our notions of agreement above ensure agreement on identities,
roles and session key material, all methods passing verification of those are
also resistant to KCI attacks.
%

If a party $A$ can be coerced into believing it completed a run with $B$, but
where the session key material is actually shared with $C$ instead, the
protocol is vulnerable to an \emph{Unknown Key-Share (UKS)}
attack~\cite{DBLP:conf/ima/Blake-WilsonJM97}.
%
For the same reason as for KCI, any method for which our agreement
properties hold is also resistant to UKS attacks.
%

From the injective agreement properties it follows that each party is assured
the identity of its peer upon completion.
%
Therefore, the agreement properties also capture \emph{entity authentication}.
%

%---------------------------------------------------------------------------
\subsection{\mTamarin{}}
\label{sec:tamarin}
We chose \mTamarin{} to model and verify \mEdhoc{} in the symbolic model.
%
\mTamarin{} is an interactive verification tool in which models are specified
as multi-set rewrite rules that define a transition relation.
%
The elements of the multi-sets are called facts and represent the global system
state.
%
Rules are equipped with event annotations called actions.
%
Sequences of actions make up the execution trace, over which
logic formulas are defined and verified.
%

Multi-set rewrite rules with actions are written\\ $ l \ifarrow[e] r $,
where $l$ and $r$ are multi-sets of facts, and $e$ is a multi-set of actions.
%
Facts and actions are $n$-ary predicates over a term algebra, which defines a
set of function symbols, variables and names.
%
\mTamarin{} checks equality of these terms under an equational theory $E$.
%
For example, one can write $ dec(enc(x,y),y) =_E x $
to denote that symmetric decryption reverses the encryption operation under $E$.
%
The equational theory $E$ is fixed per model, and hence we omit the subscript.
%
\mTamarin{} supports let-bindings and tuples as syntactic sugar to simplify
model definitions.
%
It also provides built-in rules for Dolev-Yao adversaries and for
managing their knowledge.
%
We implement events using actions, and parameters associated with events using
terms of the algebra.
%

\subsubsection{Protocol Rules and Equations}
\mTamarin{} allows users to define new function symbols and equational theories.
rules, which are added to the set of considered rules during verification.
For example, in our model we have a symbol to denote authenticated encryption,
for which \mTamarin{} produces a rule of the following form:
%
\begin{small}
\begin{verbatim}
[!KU(k), !KU(m), !KU(ad), !KU(ai)] --[]->
    [!KU(aeadEncrypt(k, m, ad, ai))]
\end{verbatim}
\end{small}
%
to denote that if the adversary knows a key \mT{k}, a message \mT{m}, the
authenticated data \mT{ad}, and an algorithm \mT{ai}, then they can construct
the encryption, and thus get to know the message
\mT{aeadEncrypt(k, m, ad, ai)}.
%

%-------------------------------------------------------------------------- sub
\subsection{\mTamarin{} Encoding of \mEdhoc{}}
\label{sec:modeling}
%
We model all four methods of \mEdhoc{}, namely
\mSigSig, \mSigStat, \mStatSig{} and \mStatStat.
%
Because the methods share a lot of common structure, we derive
their \mTamarin-models from a single specification written with the aid of the
M4 macro language.
%
To keep the presentation brief, we only present the \mStatSig{} metohod, as it
illustrates the use of two different asymmetric authentication methods
simultaneously.
%
The full \mTamarin{} code for all models can be found at~\cite{edhocTamarinRepo}.
%
Variable names used in the code excerpts here are sometimes shortened compared
to the model itself to fit the paper format.
%

\subsubsection{Primitive Operations}
Our model uses the built-in theories of exclusive-or and DH operations, as
in~\cite{DBLP:conf/csfw/DreierHRS18,DBLP:conf/csfw/SchmidtMCB12}.
%
Hashing is modeled via the built-in hashing function symbol augmented
with a public constant as additional input, modelling different
hash functions.
%
The HKDF interface is represented by \mT{expa} for the
expansion operation and \mT{extr} for the extraction operation.
%
Signatures use \mTamarin's built-in theory for \mT{sign} and \mT{verify}
operations.
%
For \mAead{} operations on key \mT{k}, message \mbox{\mT{m}}, additional data \mT{ad}
and algorithm identifier \mT{ai}, we use \mT{aeadEncrypt(m, k, ad, ai)}
for encryption.
%
Decryption with verification of the integrity is defined via the equation
\begin{small}\begin{verbatim}
aeadDecrypt(aeadEncrypt(m, k, ad, ai),
    k, ad, ai) = m.
\end{verbatim}\end{small}
%
The integrity protection of AEAD covers \mT{ad}, and this equation hence requires
an adversary to know \mT{ad} even if they only wish to decrypt the data.
%
To enable the adversary to decrypt without needing to verify the integrity
we add the equation
\begin{small}\begin{verbatim}
decrypt(aeadEncrypt(m, k, ad, ai), k, ai) = m.
\end{verbatim}\end{small}
%
The latter equation is not used by honest parties.
%

\subsubsection{Protocol Environment and Adversary Model}
We model the binding between a party's identity and their long-term
key pairs using the following rules.
%
\begin{small}
\begin{verbatim}
rule registerLTK_SIG:
    [Fr(~ltk)] --[UniqLTK($A, ~ltk)]->
        [!LTK_SIG($A, ~ltk),
         !PK_SIG($A, pk(~ltk)),
         Out(<$A, pk(~ltk)>)]
rule registerLTK_STAT:
    [Fr(~ltk)] --[UniqLTK($A, ~ltk)]->
        [!LTK_STAT($A, ~ltk),
         !PK_STAT($A, 'g'^~ltk),
         Out(<$A, 'g'^~ltk>)]
\end{verbatim}
\end{small}
%
The two rules register long-term
key pairs for the \mSig{}- and \mStat{}-based methods respectively.
%
The fact \verb|Fr(~ltk)| creates a fresh term \mT{ltk}, representing a long-term
secret key, not known to the adversary.
%
The fact \verb|Out(<$A, pk(~ltk)>)| sends the identity of the party
owning the long-term key and the corresponding public key to the adversary.
%
The event \mT{UniqLTK} together with a corresponding restriction models the fact
that the each party is associated with exactly one long-term key.
%
Consequently, an adversary cannot register additional long-term keys for an
identity.
%
In line with the \mEdhoc{} \mSpec{}, this models an external mechanism
ensuring that long term keys are bound to correct identities, e.g.,
a certificate authority.
%

We rely on \mTamarin's{} built-in message deduction rules for a Dolev-Yao adversary.
%
To model an adversary compromising long-term keys, i.e., events of type
\mRevLTK{}, and revealing ephemeral keys, i.e., events of type
\mRevEph{}, we use standard reveal rules.
%
The timing of reveals as modelled by these events is important.
%
The long-term keys can be revealed on registration, before protocol execution.
%
The ephemeral key of a party can be revealed when the party completes,
i.e., at events of type \mIComplete{} and \mRComplete.~\footnote{A stronger, and perhaps more realistic, model would reveal ephemeral keys upon
creation at the start of the run, but we failed to get \mTamarin{} to
terminate on this.}
%

\subsubsection{Protocol Roles}
We model each method of the protocol with four rules: \mT{I1}, \mT{R2}, \mT{I3}
and \mT{R4} (with the method suffixed to the rule name).
%
Each of these represent one step of the protocol as run by the initiator $I$
or the responder $R$.
%
The rules correspond to the event types \mIStart, \mRStart, \mIComplete,  and
\mRComplete, respectively.
%
Facts prefixed with \mT{StI} carry state information between \mT{I1} and \mT{I3}.
%
A term unique to the current thread, \mT{tid}, links two rules to a given state fact.
%
Similarly, facts prefixed with \mT{StR} carry state information between the
responder role's rules.
%
Line 28 in the \mT{R2\_STAT\_SIG} rule shown below illustrate one such use of state
facts.
%

We do not model the error message that $R$ can send in response to message
\mMsgone, and hence our model does not
capture the possibility for $R$ to reject $I$'s offer.
%

We model the XOR encryption of \mT{CIPHERTEXT\_2} with the key \mT{K\_2e} using
\mTamarin{}'s built in theory for XOR, and allow each term of the encrypted
element to be attacked individually.
%
That is, we first expand \mT{K\_2e} to as many key-stream terms as there are
terms in the plaintext tuple by applying the \mHkdfExpand{} function to unique
inputs per term.
%
We then XOR each term in the plaintext with its own key-stream term.
%
This models the \mSpec{} closer than if we would have XORed \mT{K\_2e} as a
single term onto the plaintext tuple.
%
The XOR encryption can be seen in lines 19--22 in the listing of
\mT{R2\_STAT\_SIG} below.
%
\begin{small}
\begin{verbatim}
1 rule R2_STAT_SIG:
2 let
3    agreed = <CS0, CI, ~CR>
4    gx = 'g'^xx
5    data_2 = <'g'^~yy, CI, ~CR>
6    m1 = <'STAT', 'SIG', CS0, CI, gx>
7    TH_2 = h(<$H0, m1, data_2>)
8    prk_2e = extr('e', gx^~yy)
9    prk_3e2m = prk_2e
10   K_2m = expa(<$cAEAD0, TH_2, 'K_2m'>,
11               prk_3e2m)
12   protected2 = $V // ID_CRED_V
13   CRED_V = pkV
14   extAad2 = <TH_2, CRED_V>
15   assocData2 = <protected2, extAad2>
16   MAC_2 = aead('e', K_2m, assocData2,
                  $cAEAD0)
17   authV = sign(<assocData2, MAC_2>, ~ltk)
18   plainText2 = <$V, authV>
19   K_2e = expa(<$cAEAD0, TH_2,
                 'K_2e'>, prk_2e)
20   K_2e_1 = expa(<$cAEAD0, TH_2,
                   'K_2e', '1'>, prk_2e)
21   K_2e_2 = expa(<$cAEAD0, TH_2,
                   'K_2e', '2'>, prk_2e)
22   CIPHERTEXT_2 = <$V XOR K_2e_1,
                     authV XOR K_2e_2>
23   m2 = <data_2, CIPHERTEXT_2>
24   exp_sk = <gx^~yy>
25 in
26   [!LTK_SIG($V, ~ltk), !PK_SIG($V, pkV),
      In(m1), Fr(~CR), Fr(~yy), Fr(~tid)]
27   --[ExpRunningR(~tid, $V, exp_sk, agreed),
        R2(~tid, $V, m1, m2)]->
28   [StR2_STAT_SIG($V, ~ltk, ~yy, prk_3e2m,
              TH_2, CIPHERTEXT_2, gx^~yy,
              ~tid, m1, m2, agreed),
29    Out(m2)]
\end{verbatim}
\end{small}
%

To implement events and
to bind them to parameters, we use actions.
%
For example, the action \verb|ExpRunningR(~tid, $V, exp_sk, agreed)| in line 27
above implements binding of an event of type \mRStart{} to the parameters and session key
material.
%

As explained in Section~\ref{sec:agreedParams}, it is not possible to show
injective agreement on session key material when it includes
$P_I$ (not visible in the rule \mT{R2\_STAT\_SIG}).
%
Therefore, we use certain actions to implement events that include $P_I$ in the
session key material and other actions that do not.
%
Session key material which includes (resp. does not include) $P_I$ is referred
to as \mT{imp\_sk} (resp. \mT{exp\_sk}) in the
\mTamarin{} model.
%
In the case of \mSigSig{} and \mSigStat, therefore, \mT{imp\_sk} is the same as
\mT{exp\_sk}.
%

%-------------------------------------------------------------------------- sub
\subsection{\mTamarin{} Encoding of Properties}
\label{sec:propertyFormalization}
The properties and adversary model we defined in
Section~\ref{sec:desired-properties} translate directly into \mTamarin's logic,
using the straightforward mapping of events to the actions emitted from the model.
%
As an example, we show the lemma for verifying the property \mPredPfs.
%
\begin{small}
\begin{verbatim}
1 lemma secrecyPFS:
2 all-traces
3  "All u v sk #t3 #t2.
4   (K(sk)@t3 & CompletedRun(u, v, sk)@t2) ==>
5       ( (Ex #t1. LTKRev(u)@t1 & #t1 < #t2)
6       | (Ex #t1. LTKRev(v)@t1 & #t1 < #t2)
7       | (Ex #t1. EphKeyRev(sk)@t1))"
\end{verbatim}
\end{small}
%
As mentioned earlier, the action \mT{CompletedRun(u, v, sk)} in line 4 is
emitted by both the rules \mT{I3} and \mT{R4}, and corresponds
to the disjunction of events $\mIComplete^{t_2} \lor \mRComplete^{t_2}$ in the
definition of \mPredPfs{} in Section~\ref{sec:secrecy}.
%
Similarly, \mT{EphKeyRev(sk)} in line 7 models that the ephemeral
key is revealed for either $I$ or $R$, or both.
%


% \documentclass[a4paper, 10px]{ctexart}
\documentclass{ctexart}
\usepackage[left=1in, right=1in, top=1.2in, bottom=1.2in]{geometry}
\usepackage{ctex}
\usepackage[utf8]{inputenc}
\usepackage{boxproof}
\usepackage{fontspec}
\usepackage{a4wide}
% \setmainfont[Scale = 1]{Palatino}
% \setCJKmainfont{Songti SC}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancypagestyle{plain}{
    \fancyhead[L]{East China Normal University}
    \fancyhead[R]{}
    \fancyfoot[C]{\thepage}
}
\def\premise{\mathrm{premise}}
\def\assumption{\mathrm{assumption}}
\def\MT{\mathrm{MT\ }}
\def\LEM{\mathrm{LEM}}
\def\PBC{\mathrm{PBC\ }}
\def\intro{\mathrm{i\ }}
\def\elim{\mathrm{e\ }}
\def\introa{\mathrm{i_1\ }}
\def\elima{\mathrm{e_1\ }}
\def\introb{\mathrm{i_2\ }}
\def\elimb{\mathrm{e_2\ }}

\def\n{\neg}
\def\d{\vee}
\def\c{\wedge}
\def\a{\forall}
\def\e{\exists}

\title{Logic in Computer Science Assignment 3}
\author{10185101210 陈俊潼}
\date{November 2020}

\begin{document}

\maketitle

\section{Prove}
Prove the following theorems with deduction rules.

\subsection{$\forall x(P(x) \rightarrow \neg Q(x)) \vdash \neg(\exists x(P(x) \wedge Q(x)))$}

Proof:

$$
\begin{proofbox}
    \: \a x (P(x) \to \n Q(x)) \= \premise\\
    \[
        \: \e x(P(x) \c Q(x)) \= \assumption\\
        \[
            x_0 \: P(x_0) \c Q(x_0) \= \assumption \\
            \: P(x_0) \= \c \elima 3 \\
            \[
                \: Q(x_0) \= \c \elimb 3\\
                \: P(x_0) \to \n Q(x_0) \= \a \elim 1 \\
                \: \n Q(x_0) \= \to \elim 6\\
            \]
            \: \bot \= \n \intro 5,7 \\
        \]
        \: \bot \= \e \elim 2, 3-8\\
    \]
    \: \n(\e x(P(x) \c Q(x))) \= \n \intro 2,9
\end{proofbox}
$$

\newpage

\subsection{$\forall x(P(x) \leftrightarrow x=b) \vdash P(b) \wedge \forall x \forall y(P(x) \wedge P(y) \rightarrow x=y)$}

Proof:
$$
\begin{proofbox}
    \: \a (P(x) \to x = b) \= \premise \\
    \: \a (x = b \to P(x)) \= \premise \\
    \: b = b \= = \intro \\
    \: b = b \to P(b) \= \a \elim 2\\
    \: P(b) \= \to\elim 4\\
    \[
        x_0 \: P(x_0) \to x_0 = b \= \a\elim 1\\
        \[
            y_0 \: P(y_0) \to y_0 = b \= \a\elim 1\\
            \[
                \: P(x_0) \c P(y_0) \= \assumption \\
                \: P(x_0) \= \c\elima 8 \\
                \: x_0 = b \= \to\elim 6 \\
                \: P(y_0) \= \c\elimb 8 \\
                \: y_0 = b \= \to\elim 7 \\
                \: x_0 = y_0 \= =\elim 10, 12\\
            \]
            \: P(x_0) \c P(y_0) \to x_0 = y_0 \= \to\intro 8,9-13\\
        \]
        \: \a y (P(x_0) \c P(y) \to x_0 = y) \= \a \intro 7-14\\
    \]
    \: \a x \a y (P(x) \c P(y) \to x = y) \= \a \intro 6-15\\
    \: P(b) \c \a x \a y (P(x) \c P(y) \to x = y)\ \ \ \ \  \= \c\intro 5,16
\end{proofbox}$$

\end{document}


%!TEX root = ../notes.tex
\section{April 28, 2022}
\subsection{Dedekind-Kummer Theorem \emph{continued}}
\recall last time we
\begin{itemize}
    \item Briefly revisited proof that $p\mid \Disc(K)\Leftrightarrow p$ ramifies in $K$ in the monogenic case.
    \item Stated Dedekind-Kummer Theorem (\cref{thm:dk}), proved (albeit somewhat rapidly) the ``shape'' piece of the theorem.
    \item Unfinished business: $\frk{p}_i = (p, \pi_i(\theta))$ for $\pi_i$ any lift to $\ZZ[x]$ of the irreducible factor $\pi_i$ that corresponds to $\frk{p}_i$.
\end{itemize}
\begin{theorem*}[Dedekind-Kummer]
    Let $K = \QQ(\theta)$, $\theta \in \riO_K$, $f := \minpoly_\QQ(\theta$, $p\in\ZZ$ a prime.
    Suppose $p\nmid \big[\riO_K : \ZZ[\theta]\big]$. If
    \[\overline{f}(x) = \overline{\pi}_1(x)^{e_1}\overline{\pi}_2(x)^{e_2}\cdots \overline{\pi}_r(x)^{e_r}\]
    is the prime factorization of $f$ mod $p$, then
    \[p\riO_K = \frk{p}_1^{e_1}\frk{p_2}^{e_2}\cdots \frk{p}_r^{e_r}\]
    is the prime factorization of $p\riO_K$ ($\star$) where
    \[\frk{p}_i = (p, \pi_i(\theta))\]
    for any lift $\pi_i\in\ZZ[x]$ of $\overline{pi}_i$.
\end{theorem*}
Last time, we proved this theorem up to ($\star$), it remains to prove each of the $\frk{p}_i$'s specifically.
\begin{proof}[Proof so far]
    Defined homomorphism
    \begin{align*}
        \ZZ[\theta]/p\ZZ[\theta] & \overset{\phi}{\longrightarrow} \riO_K/p\riO_K \\
        x + p\ZZ[\theta]         & \overset{\phi}{\longmapsto} x + p\riO_K
    \end{align*}
    and we argued that $\phi$ is an isomorphism.

    Hence
    \begin{equation}\label{eqn:dk-long-cross}\tag{\textdagger}
        \underset{
        \substack{\text{\rotatebox[origin=c]{270}{$\cong$}} \\ \riO_K/\frk{p}_i^{e_i}\times \cdots \times \riO_K/\frk{p}_r^{e_r}}
        }{\riO_K / p\riO_K}
        \cong \quad \ZZ[\theta]/p\ZZ[\theta]\quad \cong\quad  \ZZ[x]/(p, f(x))\quad\cong \underset{
            \substack{\text{\rotatebox[origin=c]{270}{$\cong$}} \\ \FF_p[x]/\overline{\pi}_1(x)^{f_1}\times \cdots \times \FF_p[x]/\overline{\pi}_s(x)^{f_s}}
        }{\FF_p[x]/(\overline{f})}
    \end{equation}
    We can break this isomorphism up factor-by-factor (hitting with Sunzi's theorem).

    One argues that $r = s$ and after reordering, $e_i = f_i$ $\forall i$, and so in fact \emph{(aside)}
    \[\riO_K/\frk{p}_i\cong \FF_p[x]/(\overline{pi}_i(x))\]
    where $\riO_K/\frk{p}_i$ is a finite field of characteristic $p$ (extension of $\FF_p$, $f_i:=[\riO_K/\frk{p}_i : \FF_p]$).

    We have that $\FF_p[x]/(\overline{\pi}_i(x))$ has degree $\deg(\overline{\pi}_i(x))$ over $\FF_p$, so $f_i = \deg(\overline{\pi}_i(x))$. This $f_i$ is called the \emph{inertial degree} of $\frk{p}_i$ over $p$.

    Thus
    \[|\riO_K / \frk{p}_i| = p^{f_i} = p^{\deg \overline{\pi}_i}.\]
    \emph{end of aside}.

    \emph{The idea (from what I think I gathered from lecture) is to push something back through every isomorphism to get this result, applying the third isomorphism theorem. }

    The ideal $(\overline{\pi}_i(x))\subseteq \FF_p[x]/(\overline{f})$ corresponds via the isomorphisms in \cref{eqn:dk-long-cross} to the ideal $\frk{p}_i/p\riO_K$. The third isomorphism theorem then says that $(p, \pi_i(\theta))$ (for any lift $\pi_i$) is the \ul{only} lift of $\frk{p}_i/p\riO_K$ to $\riO_K$.
\end{proof}

\begin{example}
    \emph{Dedekind's Revenge}: what can happen when you don't take the $p\nmid \big[\riO_K : \ZZ[\theta]\big]$ into account?

    $K = \QQ(\sqrt{-3})$, $\riO_K = \ZZ\left[ \frac{1 + \sqrt{-3}}{2} \right] = \ZZ\left[ \frac{-1 + \sqrt{-3}}{2} \right] = \ZZ[\omega]$. Maybe you're silly and you let $\theta = \sqrt{-3}$ such that $\big[\riO_K : \ZZ[\theta]\big] = 2$. Argue that the $\disc(x^2 + 3) = -12$ while $\disc(K) = \disc(x^2 + x + 1) = -3$, so we cannot apply Dedekind-Kummer to $p = 2$.

    We get $(x^2 + 3) = x^2 - 1 = (x-1)^2\pmod{2}$. Incorrectly applying the conclusion of Dedekind-Kummer would give us the square of a prime ideal, so we conclude that $2$ ramifies in $\riO_K$.

    \otoh, if we take an actual generating element for $\riO_K$, say $\omega$ and take its minimum polynomial, factoring modulo $2$.
    \[(x^2 + x + 1)\pmod{2}\]
    is irreducible over $\FF_2$ since it has no roots mod $2$. So the correct conclusion is that $2$ is actually inert in $K = \QQ(\sqrt{-3})$.
\end{example}

\subsection{Ramification Degrees, Inertial Degrees, Primes Upstairs + Downstairs}
We start \emph{upstairs}. Let $\frk{p}$ be a nonzero prime ideal of $\riO_K$. We showed that $\riO_K/\frk{p}$ is a finite field. It has characteristic $p$ where $p\ZZ = \frk{p}\cap \ZZ$. Where $p\riO_K = \frk{p}^e(\text{stuff})$. So it corresponds to a maximal ideal \emph{downstairs}.

We already said that $f_i := \left[ \riO_K/\frk{p} : \ZZ/p\ZZ = \FF_p \right]$ is called the \ul{inertial degree}. We can think of $\riO_K / \frk{p}$ as an $\FF_p$-vector space too. It's a quotient of the $\ZZ/p\ZZ$ vector space by $\riO_K/(p)$.

But we had commented on the cardinality of this vector space: $\riO_K/(p)$ has order $p^n$, where $n = [K : \QQ]$ ($\riO_K$ is a free Abelian group of rank $n$, and take each basis vector modulo $p$). Thus we observe that $f\leq n$.

If $p\riO_K = \frk{p}^e\frk{p}_2^{e_2}\cdots \frk{p}_r^{e_r}$, then $e$ is called the \ul{ramification index} or the \ul{ramification degree} of $\frk{p}$ over $p$.

We write $e(\frk{p} | p)$ to be the ramidication index; $f(\frk{p} | p)$ to be the inertial degree.

We say that $\frk{p}$ \ul{lies above} $p$ in $K$, and that $p$ \ul{lies below} $\frk{p}$ in $\QQ$.

Colloquially, $\frk{p}$ is a ``prime upstairs'' and $p$ is a ``prime downstairs''.

\subsection{Fundamental Identity}

\begin{theorem}[Fundamental Identity]
    Let $p\in\ZZ$ be a rational prime, and suppose $[K : \QQ] = n$, and
    \[p\riO_K = \frk{p}_1^{e_1}\frk{p_2}^{e_2}\cdots \frk{p}_g^{e_g}\]
    is the prime factorization of $p\riO_K$, where $f_i := f(\frk{p}_i | p)$.

    Then
    \[\sum_{i = 1}^g e_i f_i = n.\]
    is called the \ul{fundamental identity}.
\end{theorem}
If a prime $p$ is totally split, this is a sum of $1$'s.

If $p$ is totally ramified, it corresponds to $g = 1$ and $e = n$, so the inertial degree is $1$.

If $p$ is inert, then the residual extension $f = [\riO_K/\frk{p_1} : \FF_p] = n$.

\begin{remark}
    When $K/\QQ$ is Galois, the $e_i$ for $1\leq i\leq g$ are all the same, and similarly for the $f_i$.
\end{remark}

\emph{What does this proof look like?} It's fairly involved in the general case, but it simplifies a lot in the monogenic case which becomes simple given what we've done.

\begin{proof}
    We had
    \[\riO_K / \frk{p}_i \cong \FF_p[x] / \overline{\pi}_i(x)\]
    and that
    \[\riO_K(p) \cong (\text{Sunzi})\cong \FF_p[x]/(\overline{f}) \cong (\text{Sunzi})\]
    so $\deg(\overline{f}) = n$ and
    \[\left\lvert\FF_p[x] / (\overline{\pi}_i^{e_i})\right\rvert = p^{e_i \deg \pi_i} = p^{e_i f_i}\]
    and we take products (so sums in the exponents).
\end{proof}


% -*-latex-*-

\title{Orbiter Technical Notes: Object lighting}
\author{Martin Schweiger}
\date{January 26, 2006}

\documentclass[a4paper]{article}
\usepackage[dvips]{graphicx}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{times}
\usepackage{cite}

\begin{document}
\bibliographystyle{unsrt}

%\renewcommand{\vec}[1]{\ensuremath{\mathbf{#1}}}

\newcommand{\vR}[1]{\ensuremath{\vec{R}_{#1}}}
\newcommand{\nR}[1]{\ensuremath{|\vR{#1}|}}
\newcommand{\mat}[1]{\ensuremath{\mathsf{#1}}}

\maketitle

\section{Introduction}
This note contains some implementation details of lighting objects such as spacecraft or buildings on planet surfaces in Orbiter.

\section{Planetary shadows}
Planets and moons cast shadows into space away from the central sun. An object entering that shadow (such as an orbiting spacecraft, or a surface building moving across the planet's terminator) need to modify their lighting parameters to simulate this. In general, the planet shadow reduces the direct (diffuse and specular) lighting component, $D_\text{RGB}$. If the planet also contains an atmosphere, this can lead to a spectral dispersion of the direct light distribution in the twilight zone (penumbra), as well as an increase in the ambient component, $A_\text{RGB}$, due to atmospheric scattering. In the following, subscript ``RGB'' denotes a colour value consisting of red, green and blue components.

\subsection{Planets without atmosphere}
We start with the simpler case of a planet without atmospheric layer. In this case the ambient component is assumed to be unaffected (backscattering from the planet surface is currently not considered). The change in the direct component is given by geometric considerations, due to the planet disc covering part or all of the sun's disc.

Given a point in space $\vec{r}$ at which the lighting parameters are to be evaluated (e.g. the current position of a spacecraft, let $\vec{s}$ be the position of the sun, and $\vec{p}$ the position of the shadowing planet, both relative to $\vec{r}$.

With distances $s = |\vec{s}|$ and $p = |\vec{p}|$, the angular separation $\theta$ between sun and planet, as seen from $\vec{r}$, is given by
\begin{equation}
\theta = \cos^{-1} \frac{\vec{s} \cdot \vec{p}}{sp}
\end{equation}
Let $a_s$ and $a_p$ be the mean radii of sun and planet, respectively. Then their apparent radii, as seen from $\vec{r}$ are given by
\begin{equation}
\alpha_s = \sin^{-1} \frac{a_s}{s}, \qquad \alpha_p = \sin^{-1} \frac{a_p}{p}
\end{equation}
It follows that shadowing at $\vec{r}$ will only occur if
\begin{equation}
p < s \quad \text{and} \quad \theta < \alpha_s + \alpha_p
\end{equation}
Depending on the distance $p$ from the planet, we can divide the shadow zone into two areas: the near-zone, in which totality can occur (the planet disc completely covers the sun's disc), and the far zone, in which annularity can occur (the planet disc is entirely within the sun's disc).
The relevant zone can simply be determined by comparing the relative disc sizes:\begin{equation}\label{eq:shadowzone}
\begin{array}{lcl}
\text{case 1:} & \alpha_p \geq \alpha_s: & \text{totality zone}\\
\text{case 2:} & \alpha_p < \alpha_s: & \text{annularity zone}
\end{array}
\end{equation}

\subsubsection{Case 1: totality zone}
If the object is within totality distance, we have to detemine if it is actually located within the cone of totality (umbra), or in the zone of partial shadow (penumbra):
\begin{equation}
\begin{array}{lcl}
\text{case 1a:} & \theta \leq \alpha_p-\alpha_s: & \text{totality}\\
\text{case 1b:} & \theta > \alpha_p-\alpha_s: & \text{partiality}
\end{array}
\end{equation}
In case 1a, direct lighting is eliminated. In case 1b, a linear propagation from full lighting to full shadow is assumed:
\begin{equation}\label{eq:partial1b}
\begin{array}{l}
D_\text{RGB}^{(\text{1a})} = (0,0,0)\\
D_\text{RGB}^{(\text{1b})} = (f,f,f) \quad\text{with}\quad f = \frac{\theta+\alpha_s-\alpha_p}{2 \alpha_s}
\end{array}
\end{equation}
The linear assumption is not correct, but probably not critical, and may partly be justifiable by physiological arguments (the eye is more sensitive at low light levels, therefore intensity should drop more gradually).
Note that in Eq.~\ref{eq:partial1b} the fully lit direct light level is assumed to be $D_\text{RGB}^{(0)} = (1,1,1)$, but different unperturbed base line levels can easily be multipled on.

\subsubsection{Case 2: annularity zone}\label{sec:noatm_annul}
If the object is too far from the planet to enter the totality zone, we need to determine if the planet disc is contained fully or partially in the sun's disc:
\begin{equation}
\begin{array}{lcl}
\text{case 2a:} & \theta \leq \alpha_s-\alpha_p: & \text{annularity}\\
\text{case 2b:} & \theta > \alpha_s-\alpha_p: & \text{partiality}
\end{array}
\end{equation}
In case 2a, the light level is reduced according to the ratio of the two disc areas, while in case 2b a linear transition is assumed:
\begin{equation}
\left.
\begin{array}{l}
D_\text{RGB}^{(\text{2a})} = (f_0,f_0,f_0)\\
D_\text{RGB}^{(\text{2b})} = (f,f,f)
\end{array}
\right\rbrace
\begin{array}{l}
\text{with}\; f_0 = 1-(\alpha_p/\alpha_s)^2\\
\text{and}\; f = 1-\frac{1-f_0}{2} (1+\frac{\alpha_s-\theta}{\alpha_p})
\end{array}
\end{equation}
Note that for large distances the effect of the planet disc becomes insignificant. Orbiter disregards shadowing at distances where $\alpha_p/\alpha_s < 0.1$.

\subsection{Planets with atmospheric layer}
In the presence of an atmosphere, additional effects such as spectral filtering of the direct component and ambient in-scattering must be taken into account.
At high altitudes $h=p-a_p$, we can describe the atmospheric layer as an increase of the planet disc's radius of influence:
\begin{equation}\label{eq:altmod1}
\alpha_p' = \alpha_p \frac{h_0 + a_p}{a_p},\qquad (h > h_0)
\end{equation}
where $h_0$ is the effective thickness of the atmospheric layer (in Orbiter given by the AtmAlt parameter).
At low altitudes, when the object is already within the atmosphere, this value is no longer adequate. We simply assume that at ground level the atmosphere affects the lighting parameters up to an elevation $\gamma$ of the sun of $\gamma_0=10$\,deg. above the horizon, and interpolate to the actual altitude:
\begin{equation}\label{eq:altmod2}
\alpha_p' \leftarrow \alpha_p' \frac{\alpha_0}{\alpha_p'+\frac{h}{h_0}(\alpha_0-\alpha_p')},\qquad (0 \leq h \leq h_0)
\end{equation}
where $\alpha_0 = \gamma_0+\pi/2$, and $\alpha_p'$ on the right-hand side of Eq.~\ref{eq:altmod2} is taken from Eq.~\ref{eq:altmod1}.
Now, lighting parameters will be modified if
\begin{equation}
p < s \quad\text{and}\quad \phi < \alpha_s + \alpha_p'
\end{equation}
Again we can distinguish the two cases of Eq.~\ref{eq:shadowzone}.

\subsubsection{Case 1: totality zone}
For totality, we set $D_\text{RGB}^{(\text{1a})} = (0,0,0)$ as before.
However, in the case of partial shadow, we now take into account that we lose more of the blue direct component due to scattering. The amount of spectral dispersion is linked to the atmospheric density $\rho_0$ at ground level, with the following ad-hoc formulae:
\begin{eqnarray}
\Delta &=& \ln (\rho_0+1),\quad\text{bounded at}\quad 0.02 \leq \Delta \leq 0.9\\
\Delta_\text{RGB} &=& 1-\left(
\begin{array}{c} 0.3 \\ 0.85 \\ 1 \end{array}
\right) \Delta
\end{eqnarray}
Now we use a piecewise linear transition:
\begin{equation}
D_\text{RGB}^{(\text{1b})} = \left\lbrace
\begin{array}{cll}
f (1-\Delta_\text{RGB}) + \Delta_\text{RGB} &\text{where}\; f = \frac{\theta-\alpha_s-\alpha_p}{\alpha_p'-\alpha_p} &\text{if}\; \theta > \alpha_s+\alpha_p \\
f \Delta_\text{RGB} & \text{where}\;f = \frac{\theta-\alpha_p+\alpha_s}{2\alpha_s} &\text{otherwise}
\end{array}
\right.
\end{equation}
Here, the top equation describes the case that the sun is fully above the horizon, and propagates from full lighting (1,1,1) to maximum dispersion. The bottom equation describes the case of the sun is partially covered by the horizon, and propagates from the dispersed state to darkness (0,0,0).

\subsubsection{Case 2: annularity zone}
At distances beyond the totality zone atmospheric effects are considered negligible. Lighting parameters are calculated as described in Section~\ref{sec:noatm_annul}.

\subsubsection{Ambient lighting}
In addition to changes to the direct light parameters, the atmosphere can also affect the ambient level due to atmospheric scattering, thereby increasing ambient light parameters during daytime.

Ambient lighting is considered to be affected when the sun's horizon elevation, $\gamma = \phi-\alpha_p$, is higher than a threshold level $\gamma_0$. In Orbiter, $\gamma_0 = -14$\,deg. universally. Ambient lighting is considered fully saturated for $\gamma > \gamma_1$ where $\gamma_1$ is another threshold value. In Orbiter, $\gamma_1 = +6$\,deg. universally.

The following ad-hoc formula is used to determine the ambient level $A$ as a functioion of atmospheric density at zero altitude, $\rho_0$:
\begin{equation}
\begin{array}{ll}
f = \frac{\gamma-\gamma_0}{\gamma_1-\gamma_0}, & \text{bounded at}\; f \leq 1\\
A_0 = 0.45 \ln(\rho_0+1), & \text{bounded at}\; A_0 \leq 0.7.\\
A = \frac{f A_0}{h/h_0 +1} &
\end{array}
\end{equation}
where $h$ is the altitude of the object, and $h_0$ is a reference altitude. In Orbiter, $h_0 = 2\cdot10^4$\,m universally. Thus, atmospheric effects are inversely proportional to altitude. Furthermore, ambient effects are not considered if $h$ is above the effective atmospheric layer defined by the AtmAlt parameter.

Ambient lighting modifications are non-dispersive, i.e. affect all channels equally: $A_\text{RGB} = (A,A,A)$.

Note that any user-defined ambient level is a universal additive component added to all objects at all times, on top of the individual atmospheric ambient effects described above. This will generally be used to increase the base line brightness of unlight surfaces.

\end{document}