%###############################################################
%\section{Theory of Globally Controlled Polyomino Assembly}\label{sec:Theory}
\section{Theory: Polyomino Assembly by Global Control}\label{sec:Theory}
%###############################################################

This section explains how to design factories that build arbitrary-shaped 2D polyominoes.
 We first assign species to individual tiles of the polyomino, second discover a build path, and finally build an assembly line of factory components that each add one tile to a partially assembled polyomino and pass the polyomino to the next component.

\subsection{Model}\label{subsec:model}
Assume the following rules:
%\begin{enumerate}
1.) A planar  grid \emph{workspace} $W$ is filled with a number of unit-square particles (each occupying one cell of the grid)  and some fixed unit-square blocks.  Each unit square in the workspace is either  \emph{free}, which a particle may occupy or \emph{obstacle} which a particle may not occupy.  Each square in the grid can be referenced by its Cartesian coordinates $\bm{x}=(x,y)$.
2.) All particles are commanded in unison: the valid commands are  ``Go Up" ($u$), ``Go Right" ($r$), ``Go Down" ($d$), or ``Go Left" ($l$).
3.) Particles all move until they  hit an obstacle, hit a stationary particle, or share an edge with a compatible particle.
	%\begin{enumerate}
%		\item hit an obstacle
%		\item hit a stationary particle
%		\item share an edge with a compatible particle
%	\end{enumerate}
If a particle shares an edge with a compatible particle the two particles bond and from then on move as a unit.
This letter uses \emph{cycles} of movement commands in the order $\langle r,d,l,u \rangle$. We assume the area of $W$ is finite and issue each command long enough for the particles to reach their maximum extent.
%\end{enumerate}

%###############################################################
\subsection{Arbitrary 2D shapes require two particle species}\label{subsec:RobotSpecies}
%###############################################################
Polyominoes have \emph{four-point connectivity}: a 4-connected square is a neighbor to every square that shares an edge with it.

\begin{lemma}
  Any polyomino can be constructed using just two species
  \end{lemma}
\begin{proof}
Label a grid with an alternating pattern like a checkerboard.  Any desired polyomino can be constructed on this checkerboard, and all joints are between dissimilar species.
  An example shape is shown in Fig.~\ref{fig:Grid}. Red and blue colors are used to indicate particles of different species.
  \end{proof}

   \begin{figure}
   \centering
   \vspace{0.2em}
\begin{overpic}[width =.8\columnwidth]{Grid2.pdf}
\end{overpic}
\caption{\label{fig:Grid}Any polyomino can be constructed with two compatible robot species, shown here with red and blue tiles.
}
\end{figure}

  The sufficiency of two species to construct any shape gives many options for implementation.  The two species could correspond to any gendered connection,
including ionic charge, magnetic polarity, or hook-and-loop type fasteners. Large populations of these two species can then be stored in separate hoppers and, like two-part epoxy,  only assemble when dissimilar particles come in contact.

%###############################################################
\subsection{Complexity Handled in This Letter}\label{sec:ComplexityHandled}
%###############################################################

2D part geometries vary in difficulty.  Fig.~\ref{fig:IncreasingDifficulty} shows parts with increasing  complexity.

   \begin{figure}
   \centering
\begin{overpic}[width =\columnwidth]{IncreasingDifficulty3.pdf}
\end{overpic}\vspace{-2em}
\caption{\label{fig:IncreasingDifficulty}Polyomino parts. Assembly difficulty increases from left to right.
}
\end{figure}
Label the first particle in the assembly process the \emph{seed particle}.
 Part 1 is shaped as a `\#' symbol.  Though it has an interior hole, any of the 16 particles could serve as the seed particle, and the shape could be constructed around it.  The second shape is a spiral, and must be constructed from the inside-out.  If the outer spiral was completed first, there would be no path to add particles to finish the interior because added particles would have to slide past compatible particles.  Increasing the number of species would not solve this problem, because there is a narrow passage through the spiral that forces incoming parts to slide past the edges of all the bonded particles.
The third shape contains a loop, and the interior must be finished before the loop is closed.
Shape 4 is the combination of a left-handed and a right-handed spiral.
Adding one particle at a time in 2D cannot assemble this part, because each spiral must be constructed from the inside-out.
 Instead, this part must be divided into sub-assemblies that are each constructed, and then combined.
 Shape 5 contains compound overhangs, and may be impossible to construct with additive 2D manufacturing using only two species.
 The algorithms in this letter detect if the desired shape can be constructed one particle at a time.
 If so, a build order is provided, and a factory layout is designed.

% A polyomino is said to be \emph{column convex} if each column has no holes. Similarly, a polyomino is said to be row convex if each row has no holes. A polyomino is said to be \emph{convex} if it is row and column convex.
%
%\begin{lemma}\label{lemma:convexonjectsCanbeConstructedAdditively}
%Any convex polyomino can be constructed by adding one particle at a time
%\end{lemma}
%\begin{proof}
%Select any pixel as the \emph{seed block}, or root node.  Perform a breadth-first search starting at the seed block, labelling each block in the order they are expanded.  Constructing the shape according to the ordering ensures that the polyomino is convex at every step of construction.
%\end{proof}

%The proof of \ref{lemma:convexonjectsCanbeConstructedAdditively} assumes the existence of fixtures for assembly.
%\todo{describe fixtures for adding one particle at a time}

%Some non-convex polynominos cannot be constructed one particle at a time, as illustrated in Fig. ~\ref{fig:IncreasingDifficulty}.    For instance, a polynomino consisting of a clockwise and a counterclockwise square spiral, joined at the ends with a gap of one unit between the spirals must be constructed by first assembling each spiral, and then combining the sub assemblies.

%###############################################################
\subsection{Discovering a Build Path}
%###############################################################

Given a polyomino, Alg.~\ref{alg:FindBuildPath} determines if the polyomino can be built by adding one component at a time.
 The  problem of determining a build order is difficult because there are $O(n!)$ possible build orders, and many of them may  violate the constraints given in Section \ref{subsec:model}.
 Each new tile must have a straight-line path to its goal position in the polyomino that does not collide with any other tile, does not slide past an opposite specie tile, and terminates in a mating configuration with an opposite specie tile.
However, as in many robotics problems, the inverse problem of deconstruction is easier than the forward problem of construction.

\begin{algorithm}
\newcommand\algotext[1]{\end{algorithmic}#1\begin{algorithmic}[1]}
%\begin{algorithmic}[1]
%\scriptsize
\caption{\sc {FindBuildPath}($\mathbf{P})$   \label{alg:FindBuildPath}}
$\mathbf{P}$ is the $x,y$ coordinates of a 4-connected polyomino. % that has at least a 1-tile empty border.
Returns $ \mathbf{C} $, $ \mathbf{c} $ and $\mathbf{m}$ where $ \mathbf{C} $ contains sequence of polyomino coordinates, $ \mathbf{c} $ is a vector of color labels, and $\mathbf{m}$ is a vector of directions for assembly.
\begin{algorithmic}[1]

\State\hbox{$ \mathbf{c}\leftarrow${\sc{LabelColor}}($\mathbf{P}$)}
\State $\{\mathbf{C},\mathbf{m} \}= ${\sc {Decompose}}$(\mathbf{P},\mathbf{c})$
\State \Return $\{ \mathbf{C},\mathbf{c}, \mathbf{m} \} $
\end{algorithmic}
\end{algorithm}

   \begin{figure}
   \centering
\begin{overpic}[width =\columnwidth]{DeconstructionOrderMattersSlide.pdf}
\end{overpic}\vspace{-2em}
\caption{\label{fig:DeconstructionOrderMatters} Deconstruction order matters if loops are present.  Loops occur when the 8-connected freespace has more than one connected component.  In the top row the green tile is removed first, resulting in a polyomino that cannot be decomposed. However, if the bottom right tile is removed first, deconstruction is possible.
}
\end{figure}

Alg.~\ref{alg:FindBuildPath}  first assigns each tile in the polyomino a color, then calls the recursive function {\sc {Decompose}}, which returns either a build order of polyomino coordinates and the directions to build, or an empty list if the part cannot be constructed.
{\sc {Decompose}} starts by calling the function {\sc {Erode}}.  {\sc {Erode}} first counts the number of components in the 8-connected freespace. An 8-connected square is a neighbor to every square that shares an edge or vertex with it. If there is more than one connected component, the polyomino contains loops.
 {\sc {Erode}} maintains an array of the remaining tiles in the polyomino $\mathbf{R}$.
 In the inner \textit{for loop} at line  \ref{alg:line:forloopTotryremovinEachTileERODE}, a temporary array $\mathbf{T}$ is generated that contains all but the $j$th tile in $\mathbf{R}$ sorted by the number of neighbors so a tile with one neighbor is checked before tiles with two or three.
This \textit{for loop} simply checks (1) if the $j$th tile can be removed along a straight-line path without  colliding with any other particle or sliding past an opposite specie tile in line \ref{alg:line:checkpathtileERODE},  (2) that its removal does not fragment the remaining polyomino into more than one piece in line \ref{alg:line:NumConnectedCompERODE}, and (3) that its removal does not break a loop in line \ref{alg:line:Num8ConnectedCompERODE}.
If no loops are present, this algorithm requires at most  $n/2 (1 + n)$ iterations, because there are $n$ particles to remove, and each iteration considers one less particle than the previous iteration.

Polyominoes with loops require care, because decomposing them in the wrong order can make disassembly impossible, as shown in Fig.~\ref{fig:DeconstructionOrderMatters}.
If loops exist then  {\sc {Erode}} may return only a partial decomposition, so {\sc {Decompose}} must then try every possible break point and recursively call {\sc {Decompose}} until either a solution is found, or all possible decomposition orders have been tested.  The worst-case number of function calls of  {\sc {Decompose}}  are proportional to the factorial of the number of loops, $O( |\text{\sc 8-ConnComp}(\neg\mathbf{P})| !)$. Though large, this is much less than $O(n!)$.

\begin{algorithm}
\newcommand\algotext[1]{\end{algorithmic}#1\begin{algorithmic}[1]}
%\scriptsize
\caption{\sc {Erode}($\mathbf{P},\mathbf{c})$   \label{alg:Erode}}
$\mathbf{P}$ is the $x,y$ coordinates of a 4-connected polyomino  and $ \mathbf{c} $ is a vector of color labels.
Returns $ \mathbf{R} $, $ \mathbf{C} $, $\mathbf{m}$, and $\mathbf{\ell}$ where $ \mathbf{R} $  is a list of coordinates of the remaining polyomino, $ \mathbf{C} $ contains sequence of tile coordinates that were removed,   $\mathbf{m}$ is a vector of directions for assembly, and $\mathbf{\ell}$ if loops were encountered. $\mathbf{d} \gets\{r,d,l,u\}$
\begin{algorithmic}[1]
%\State\hbox{$ \mathbf{c}\leftarrow${\sc{LabelColor}}($\mathbf{P}$)}
%\State $ \{ \mathbf{R},\mathbf{C}, \mathbf{m}, \ell \} \gets ${\sc {Erode}}$(\mathbf{P},\mathbf{c})$
\State\hbox{$\mathbf{C} \leftarrow \{\}, \mathbf{m} \leftarrow \{\}, \mathbf{\ell} \gets \textrm{\sc False},  \mathbf{R}\leftarrow \mathbf{P}$}
\State $w \gets |\text{\sc 8-ConnComp}(\neg\mathbf{R})|$

\While{$1 <  |\mathbf{R}|  $}
\State  \emph{successRemove} $\gets$ {\sc False}
\State\hbox{$ \mathbf{R}\leftarrow${\sc{Sort}}($\mathbf{R}$)} \Comment{sort by number of neighbors}
\For{$j\leftarrow 1, j \le  |\mathbf{R}| $}
\State $\mathbf{p} \gets \mathbf{R}_j,  \mathbf{T} \gets  \mathbf{R}  \backslash   \mathbf{R}_j$

\For{$ k \leftarrow 1, k \le  4$   \label{alg:line:forloopTotryremovinEachTileERODE} }
\If{{\sc CheckPathTile}($\mathbf{T},\mathbf{p}, \mathbf{d}_k, \mathbf{c}$) \label{alg:line:checkpathtileERODE} \textbf{and}
\\ \textbf{~~~~~~~~~~~~~~}
$1 = |\text{\sc 4-ConnComp}(\mathbf{T})|$  \label{alg:line:NumConnectedCompERODE}}
\If{$w = |\text{\sc 8-ConnComp}(\neg\mathbf{T})|$  \label{alg:line:Num8ConnectedCompERODE}}
\State $ \mathbf{R}\leftarrow   \mathbf{T}$, \emph{successRemove} $\gets$ {\sc True}
\State  $\mathbf{C}_{ 1+|\mathbf{R}|} \gets \mathbf{p},  \mathbf{m}_{ |\mathbf{R}|}  \gets \mathbf{d}_k$
\Else { $  \mathbf{\ell} \gets \textrm{\sc True}$}
\EndIf
\State \textbf{break}
\EndIf
\EndFor
\EndFor
\If {  \emph{successRemove} $=$ {\sc False}}
\State  \hbox{$\mathbf{C} \leftarrow \{\}, \mathbf{m} \leftarrow \{\}$}
\State \textbf{break}
\EndIf
\EndWhile
\If {$ |\mathbf{R}| = 1$}
\State  $\mathbf{C}_{ 1} \gets \mathbf{R}_1 $
\EndIf
\State \Return $\{ \mathbf{R},\mathbf{C}, \mathbf{m}, \ell \}$
\end{algorithmic}
\end{algorithm}

\vspace{10em}
\begin{algorithm}
\newcommand\algotext[1]{\end{algorithmic}#1\begin{algorithmic}[1]}
%\scriptsize
\caption{\sc {Decompose}($\mathbf{P},\mathbf{c})$   \label{alg:Decompose}}
$\mathbf{P}$ is the $x,y$ coordinates of a 4-connected polyomino and $ \mathbf{c} $ is a vector of color labels.
Returns $ \mathbf{C} $ and $\mathbf{m}$ where $ \mathbf{C} $ contains sequence of polyomino coordinates and $\mathbf{m}$ is a vector of directions for assembly. $\mathbf{d} \gets\{u,d,l,r\}$
\begin{algorithmic}[1]
\State $ \{ \mathbf{R},\mathbf{C}, \mathbf{m}, \ell \} \gets ${\sc {Erode}}$(\mathbf{P},\mathbf{c})$
\If {$|  \mathbf{R} | = 0 \textbf{ or } \neg \ell$}
\State \Return $\{ \mathbf{C},\mathbf{m} \}$
\EndIf
\For{$j\leftarrow 1, j \le  |\mathbf{R}| $}
\State $\mathbf{p} \gets \mathbf{R}_j,  \mathbf{T} \gets  \mathbf{R}  \backslash   \mathbf{R}_j$
\For{$ k \leftarrow 1, k \le  4$   \label{alg:line:forloopTotryremovinEachTileDecompose} }
\If{{ ( \sc CheckPathTile}($\mathbf{T},\mathbf{p}, \mathbf{d}_k, \mathbf{c}$) \label{alg:line:checkpathtileDecompose} \textbf{and }
\\ \textbf{~~~~~~~~~~~~ }
$1 = |\text{\sc 4-ConnComp}(\mathbf{T})|$)  \label{alg:line:NumConnectedCompDecompose}}
\State $\{\mathbf{C2},\mathbf{m2} \}\gets ${\sc {Decompose}}$(\mathbf{T},\mathbf{c})$
\If {$\mathbf{C2}  \ne \{\}$}
%\State  $\mathbf{C}_{ 1+|\mathbf{R}|} \gets \mathbf{p},  \mathbf{m}_{ |\mathbf{R}|}  \gets \mathbf{d}_k$
\State $\mathbf{C}_{1:|\mathbf{C2}|+1} \gets \{\mathbf{C2},\mathbf{p}\}$
\State $ \mathbf{m}_{1:|\mathbf{m2}|+1} \gets \{\mathbf{m2},\mathbf{d}_k\}$
\State \Return $\{ \mathbf{C}, \mathbf{m} \}$
\EndIf
\State \textbf{break}
\EndIf
%\EndIf
\EndFor
\EndFor
%\State $\mathbf{C} \gets \{\}, \mathbf{m} \gets \{\}$
\State \Return $\{ \mathbf{C}\gets \{\}, \mathbf{m}\gets \{\} \}$
\end{algorithmic}
\end{algorithm}

%###############################################################
%\subsection{Assembling Tiles}
%###############################################################

%###############################################################
\subsection{Hopper Construction}\label{subsec:HopperConstruction}
%###############################################################
Two-part adhesives react when components mix.  Placing components in separate containers prevents mixing.  Similarly, storing many particles of a single specie in separate containers allows controlled mixing.
%WIKI: harden by mixing two or more components which chemically react.

We can design \emph{part hoppers}, containers that store similarly labelled particles.  These particles will not bond with each other.  The hopper shown in Fig.~\ref{fig:HopperCW} releases one particle every cycle. Delay blocks are used to ensure the $n$th part hopper does not start releasing particles until cycle $n$. For ease of exposition, this letter has a unique hopper for each tile position. This enables precise positioning of different materials, but a particle logic system could use just two hoppers, similar to our particle logic systems in [9].

   \begin{figure}
  %  \vspace{-1em}
   \centering
\begin{overpic}[width =\columnwidth]{hopperV4.pdf}
\end{overpic}\\ \vspace{-1em}
\caption{\label{fig:HopperCW}Hopper with five delays. The hopper is filled with similarly-labelled robots that will not combine.  Every clockwise command cycle releases one robot from the hopper.  %\textcolor{red}{replace with new hopper design}
}
\end{figure}

\begin{figure}
   \centering
\begin{overpic}[width =\columnwidth]{24tilefactory.pdf}
\end{overpic}
\begin{overpic}[width =\columnwidth]{Spiraltilefactory.pdf}
\end{overpic}\\ \vspace{-1em}
\caption{\label{fig:24Tilefactory}A twenty-four tile factory, step 82 for a `\#' shape and a twenty-one tile factory, step 66 for a spiral (zoom in for details in this vector graphic).
}
\end{figure}

%###############################################################
\subsection{Part Assembly Jigs}\label{subsec:PartAssemblyJigs}
%###############################################################

Assembly is an iterative procedure.
A factory layout is generated by  {\sc{BuildFactory}}($\mathbf{P}, n_c$), described in Alg.~\ref{alg:BuildFactory}. This function takes a 2D polyomino $\mathbf{P}$ and, if $\mathbf{P}$ has a valid build path, designs an obstacle layout to generate $n_c$ copies of the polyomino. A polyomino is composed of $|\mathbf{P}| = n$ tiles.

For each tile, the function
 {\sc{FactoryAddTile}} $(n_c,\mathbf{b}, m,C, c,w)$
  described in  Alg.~\ref{alg:FactoryAddTile}
is called to generate an obstacle configuration $\mathbf{A}$.
$\mathbf{A}$  forms a hopper that releases a particle each iteration and a chamber that temporarily holds the partially-assembled polyomino $\mathbf{b}$ and guides the new particle $C$ to the correct mating position. A 24-tile factory is shown in  Fig.~\ref{fig:24Tilefactory}.

%\todo{Sheryl, add the algorithmic environment for Build Factory}
\begin{algorithm}
\newcommand\algotext[1]{\end{algorithmic}#1\begin{algorithmic}[1]}
%\scriptsize
\caption{ \sc{BuildFactory}($\mathbf{P}, n_c$)\label{alg:BuildFactory}}
$\mathbf{P}$ is the $x,y$ coordinates of a 4-connected polyomino.  $n_c$ is the number of parts desired.
Returns a two dimensional array $ \mathbf{F} $ containing the factory obstacles and filled hoppers.
\begin{algorithmic}[1]
\State$\mathbf{F} \leftarrow \{\}$ \Comment{the factory obstacle array}

\State \{$\mathbf{C},\mathbf{c}, \mathbf{m}$\} $  \leftarrow$ {\sc{FindBuildPath}}($\mathbf{P}$)
 \If{$ \{\} = \mathbf{m}$}
 \State \Return  $ \mathbf{F} $
 \EndIf
 \State$\{ \mathbf{A}, \mathbf{b} \}\leftarrow${\sc{FactoryFirstTile}}$(n_c, \mathbf{c}_i,w)$
 \For{$i\leftarrow 2, i \le  |\mathbf{c}| )$}
 \State$\{\mathbf{A},\mathbf{b}\}\leftarrow${\sc{FactoryAddTile}}$(n_c,\mathbf{b}, \mathbf{m}_{i-1},\mathbf{C}_i, \mathbf{c}_i,w)$
 \State$ \mathbf{F} \leftarrow${\sc{ConcatFactories}}$(\mathbf{F},\mathbf{A})$
\EndFor
\State \Return  $ \mathbf{F} $
%\State{\sc{DisplayFactory}}($factoryLayout$)
\end{algorithmic}
\end{algorithm}

\begin{algorithm}
\newcommand\algotext[1]{\end{algorithmic}#1\begin{algorithmic}[1]}
%\scriptsize
\caption{\sc {FactoryAddTile}$(n_c,\mathbf{b}, m,C, c,w)$ \label{alg:FactoryAddTile}}
\begin{algorithmic}[1]
\State$
\{ \mathbf{hopper}\}\leftarrow${\sc{Hopper}}$(c,n_c,w)$
\If{ $m = d \textbf{ and } \left(     C_x  \le \max \mathbf{b}_x
                         \textbf{ or }  C_y     < \min \mathbf{b}_y \right)  }$

\State$\{\mathbf{A},\mathbf{b}\}\leftarrow${\sc{downdir}}$(\mathbf{hopper},\mathbf{b},\mathbf{C})$

\ElsIf{ $m = l \textbf{ and} \left(     C_y  \le \max \mathbf{b}_y
                         \textbf{ or }  C_x     > \max \mathbf{b}_x \right)  }$

\State$\{\mathbf{A},\mathbf{b}\}\leftarrow${\sc{leftdir}}$(\mathbf{hopper},\mathbf{b},\mathbf{C})$
\ElsIf{ $m = l \textbf{ and} \left(     C_x  \ge \max \mathbf{b}_x
                         \textbf{ or }  C_y     > \max \mathbf{b}_y \right)  }$

\State$\{\mathbf{A},\mathbf{b}\}\leftarrow${\sc{updir}}$(\mathbf{hopper},\mathbf{b},\mathbf{C})$
\ElsIf{ $m = r \textbf{ and } \left(     C_y     \ge \min \mathbf{b}_y
                       \textbf{ or }  C_x  < \min \mathbf{b}_x   \right)  }$
\State$\{\mathbf{A},\mathbf{b}\}\leftarrow${\sc{rightdir}}$(\mathbf{hopper},\mathbf{b},\mathbf{C})$

\EndIf

\State \Return $\{ \mathbf{A}, \mathbf{b} \}$

\end{algorithmic}
\end{algorithm}


\section{Introduction}

OpenMath~\cite {BusCapCar:oms04} is a semantic representation format of mathematical objects and formulae.
In a nutshell, OpenMath standardizes six basic object types (symbols, variables, numbers, strings, and foreign objects), three ways of building complex objects: (function) application, binding, and management facilities like structure sharing and error reporting.
The OpenMath object model underlies Content MathML~\cite{CarlisleEd:MathML3:on}, making it well-integrated with MathML presentation.

There are several encodings of OpenMath Objects, most notably the XML and Binary encodings.
In this paper we propose another one based on JSON, a lightweight data-interchange format that used heavily in the Web Applications area.

JSON~\cite{JSON:web}, short for \textbf{J}ava\textbf{S}cript \textbf{O}bject \textbf{N}otation, is a lightweight data-interchange format.
While being a subset of JavaScript, it is defined independently.
JSON can represent both primitive types and composite types.

Primitive JSON data types are strings (e.g. \lstinline{"Hello world"}), Numbers (e.g. \lstinline{42} or \lstinline{3.14159265}), Booleans (\lstinline{true} and \lstinline{false}) and \lstinline{null}.
Composite JSON types are either (non-homogeneous) arrays (e.g. \lstinline{[1, "two", false]}) or key-value pairs called objects (e.g. \lstinline|{"foo": "bar", "answer": 42}|).

Constructs corresponding to JSON objects are found in most programming languages.
Furthermore, the syntax is very simple; hence many languages have built-in facilities for translating their existing data structures to and from JSON.
The use for an OpenMath JSON encoding is clear: It would enable easy use of OpenMath across many languages.

In the next Section we survey two existing OpenMath JSON encodings.
Section~\ref{sec:encoding} proposes a new encoding that combines the advantages and alleviates their disadvantages.
We give a thorough specification of the encoding, present a JSON schema implemented in TypeScript, and provide a web service that validates JSON-encoded OpenMath and transforms OpenMath objects between XML and JSON encodings.
Section~\ref{sec:concl} concludes the paper.

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "paper"
%%% End:

%  LocalWords:  standardizes textbf textbf cript textbf bject otation sec:concl


\section{Introduction}

Community detection is an essential task for cyberspace mining, which has been successfully employed to explore users’ resemblance for retrieval/recommendation enhancement and user behavior analysis. Taking social media and e-commerce as examples, the complex, and often heterogeneous, relations among users and other objects, e.g., products, reviews, and messages, can be encapsulated as bipartite graphs, and the topology can help to synthesize and represent users with a coarser and broader view.

While a graph is well-connected, conventional methods, e.g., modularity-based approach \cite{newman2004fast}, spectral approach \cite{nascimento2011spectral}, dynamic approach \cite{peixoto2017modelling} and deep learning approach \cite{chiang2019cluster}, are able to estimate the internal/external connectivity and generate high-quality communities directly on nodes \cite{fortunato2016community}.

For sparse graphs, as mentioned in the Chapter \ref{ch:intro}, to deal with the lack-of-connection problem, I propose  a novel research task – Cross-Graph Community Detection. The idea is based on the fact that an increasing number of small apps are utilizing the user identity information inherited from giant providers, i.e., users can easily login a large number of new apps by using Facebook and Google ID. In such ecosystem, the main large graph can provide critical information to enlighten the community detection on many small sparse graphs. Note that, in spit of the small sparse graphs can engage with a specific field, the main graph is quite comprehensive and noisy. As Figure \ref{fig:c4_example} shows, not all the connections in Amazon (shopping graph) can be equally important for the two candidate app graphs. In the example, three mutual users are selected where $u_1$ and $u_2$ mainly share similar shopping interests on cosmetics and $u_1$ and $u_3$ mainly share similar shopping interests on food products in Amazon. Then, with deliberate propagation from main graph, in the Cosmetic graph, $u_1$ and $u_2$ have a better chance to be grouped together, while $u_1$ and $u_3$ are more likely to be assigned the same community ID in the Cooking graph. Therefore, the proposed model should be able to differentiate various kinds of information from the main graph for each candidate sparse graph to enhance its local community detection performance.

As another challenge, small sparse graphs often suffer from training data insufficiency, e.g., the limited connections in these graphs can hardly tell the community residency information. In this study, I employed a novel data augmentation approach - cross-graph pairwise learning. Given a candidate user and an associated user triplet, the proposed model can detection the community closeness superiority by leveraging main graph and the sparse graph simultaneously. Moreover, the proposed pairwise learning method can cope with the main graph heterogeneity issue and reduce noisy information by taking care of graph local structure. Theoretically, I can offer at most $\mathcal{O}(N^{3})$ user triplets to learn graph community structure while conventional community detection methods by default can only be applied on $\mathcal{O}(N)$ users  ($N$ is the number of users in the sparse graph).

Therefore, I propose an innovative \textit{Pairwise Cross-graph Community Detection} (PCCD) model for enhanced sparse graph user community detection. Specifically, given user $u_i$ and its associated triplet $\langle u_{i},u_{j},u_{k}\rangle$, I aim to predict their pairwise community relationship, e.g., compared with user $u_{k}$, user $u_{j}$ should have closer, similar or farther community closeness to user $u_i$.


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{indentfirst}

\title{CS131 B1: HW 3}
\author{Duy Nguyen}
\date{2 October 2016}

\begin{document}

\maketitle

\section*{Question 1}
\subsection*{a.}
\begin{tabular}{l|l}
    The program has bugs or works correctly. & $B \lor C$ \\
    The program is bug-free or needs debugging. & $\neg B \lor N$ \\ \hline
    the program works correctly or needs debugging.&$C \lor N$.
\end{tabular}

This argument is valid since it follows the valid argument form of \textit{resolution}.
\subsection*{b.}
\begin{tabular}{l|l}
    The error is in function A or B. & $A \lor B$ \\ \hline
    I need to debug function A & $A$
\end{tabular}

We construct a truth table:

\begin{tabular}{cc|cc}
    $A$&$B$&$A \lor B$&$A$ \\ \hline
    T&T&T&T\\
    T&F&T&T\\
    \textbf{F}&\textbf{T}&\textbf{T}&\textbf{F}\\
    F&F&F&F
\end{tabular}

We note that there is one case where a true premise leads to a false conclusion. Thus this argument is invalid.

\subsection*{c.}
\begin{tabular}{l}
    All integers are rational numbers. \\
    All rational numbers can be represented as $p/q$, \\
    where
p and q are integers. \\
    There are no such p and q which satisfy $x=p/q$. \\ \hline
    x is irrational and x is not an integer.
\end{tabular}

 We have: ``all integers are rational numbers" and ``all rational numbers can be represent as $p/q$" are both true since this is the definition of rational number. So if the third premise ``there are no such p and q which satisfy $x=p/q$" is true, then x is not an rational number. And since integers are subset of rational numbers, x is not an integer. Therefore, this argument is valid.

 \subsection*{d.}
 \begin{tabular}{l}
     All the planets of the solar system orbit the Sun. \\
     Pluto orbits the Sun. \\ \hline
     Pluto is a planet of
the solar system.
 \end{tabular}

Both of the premises are true. However, the conclusion is false. Therefore, this is not a valid argument.

\section*{Question 2}
\subsection*{a. Every CS student knows Python and Java.}
$\forall x (C(x) \rightarrow (P(x) \land J(x)))$

\begin{tabular}{ll}
    Where: & \textbf{x} are all people. \\
    & \textbf{C(x)} are those who are a CS student. \\
    & \textbf{P(x)} is a person who knows Python.\\
    & \textbf{J(x)} is a person who knows Java.
\end{tabular}

\subsection*{b. Some CS students know C++ or C\#.}
$\exists x (C(x) \land (P(x) \lor S(x))$

\begin{tabular}{ll}
    Where: & \textbf{x} are all people. \\
    & \textbf{C(x)} are those who are a CS student. \\
    & \textbf{P(x)} is a person who knows C++.\\
    & \textbf{S(x)} is a person who knows C\#.
\end{tabular}

\subsection*{c. For every successful person there is someone even more successful, for every unhappy person there is someone more unhappy.}

$\forall x \exists y P(x,y)$

\begin{tabular}{ll}
    Where: & \textbf{x} is a successful/unhappy person. \\
    & \textbf{P(x,y)} is where y is more successful/unhappy than x
\end{tabular}

\subsection*{d. If y=f(x) is a function, then for every x there exists only one y.}
$ y = f(x) \rightarrow \forall x \exists y $

\section*{Question 3}
\subsection*{2a.}
$\neg \forall x (C(x) \rightarrow (P(x) \land J(x)))$

$\exists x \neg (C(x) \rightarrow (P(x) \land J(x)))$

$\exists x (C(x) \land \neg (P(x) \land J(x)))$

$\exists x (C(x) \land (\neg P(x) \lor \neg J(x)))$

There exists a person who is a CS student and does not know Python nor Java.

\subsection*{2b.}
$\neg \exists x (C(x) \land (P(x) \lor S(x))$

$\forall x \neg (C(x) \land (P(x) \lor S(x))$

$\forall x (\neg C(x) \lor \neg (P(x) \lor S(x))$

$\forall x (\neg C(x) \lor (\neg P(x) \land \neg S(x))$

For all people, there is not a CS student or there is not a person who know both C++ and C\#.

\end{document}


\documentclass{subfile}

\begin{document}
	\section{BuNO}\label{sec:buno}

		\begin{problem}[$2020$ Day $1$, problem $2$]
			Let $b_{1},\ldots,b_{n}$ be non-negative integers and $a_{0},a_{1},\ldots,a_{n}$ be real numbers such that $b_{1}+\ldots+b_{n}=2$ and $a_{0}=a_{n}=0,|a_{i}-a_{i-1}|\leq b_{i}$ for $1\leq i\leq n$. Prove that
				\begin{align*}
					\sum_{i=1}^{n}(a_{i}+a_{i-1})b_{i}
						& \leq 2
				\end{align*}
		\end{problem}

		\begin{problem}[$2018$, problem $3$]
			Prove that
				\begin{align*}
					\left(\dfrac{6}{5}\right)^{\sqrt{3}}
						& > \left(\dfrac{5}{4}\right)^{\sqrt{2}}
				\end{align*}
		\end{problem}

		\begin{problem}[$2016$, problem $3$]
			For positive real numbers $a,b,c$ and $d$, prove that
				\begin{align*}
					\dfrac{a+\sqrt{ab}+\sqrt[3]{abc}+\sqrt[4]{abcd}}{4}
						& \leq \sqrt[4]{a\cdot\dfrac{a+b}{2}\cdot\dfrac{a+b+c}{3}\cdot\dfrac{a+b+c+d}{4}}
				\end{align*}
		\end{problem}

		\begin{problem}[$2009$, problem $6$]
			Let $a_{1},\ldots,a_{n},b_{1},\ldots,b_{n}$ be arbitrarily taken real numbers and $c_{1},\ldots,c_{n}$ be positive real numbers, then
				\begin{align*}
					\left(\sum_{i,j=1}^{n}\dfrac{a_{i}a_{j}}{c_{i}+c_{j}}\right)\left(\sum_{i,j=1}^{n}\dfrac{b_{i}b_{j}}{c_{i}+c_{j}}\right)
						& \geq \left(\sum_{i,j=1}^{n}\dfrac{a_{i}b_{j}}{c_{i}+c_{j}}\right)^{2}
				\end{align*}
		\end{problem}

		\begin{problem}[$2008$, problem $3$]
			Let $n$ be a natural number and $a_{1},\ldots,a_{n},b_{1},\ldots,b_{n}$ be real positive numbers such that $0\leq a_{1}\leq\ldots\leq a_{n}\leq\pi$ and
				\begin{align*}
					\left|\sum_{i=1}^{n}b_{i}\cos{ka_{i}}\right|
						& < \dfrac{1}{k}
				\end{align*}
			for all positive integer $k$. Prove that $b_{1}=\ldots=b_{n}=0$.
		\end{problem}

		\begin{problem}[$2007$ Team Selection Test, problem $3$]
			Let $n\geq2$ be a positive integer. Find the best constant $C(n)$ such that
				\begin{align*}
					\sum_{i=1}^{n}x_{i}
						& \geq C(n)\sum_{1\leq j<i\leq n}(2x_{i}x_{j}+\sqrt{x_{i}x_{j}})
				\end{align*}
			is true for all $x_i\in(0,1)$ such that
				\begin{align*}
					(1-x_{i})(1-x_{j})
						& \geq \dfrac{1}{4}
				\end{align*}
			for $1\leq i<j\leq n$.
		\end{problem}

		\begin{problem}[$1997$, problem $1$]
			Let $a,b,c$ be positive real numbers such that $abc=1$. Prove that
				\begin{align*}
					\dfrac{1}{1+b+c}+\dfrac{1}{1+c+b}+\dfrac{1}{1+a+b}
						& \leq \dfrac{1}{2+a}+\dfrac{1}{2+b}+\dfrac{1}{2+c}
				\end{align*}
		\end{problem}
\end{document}


\section{Task 6}
% Given a n-by-n tori and an n-dimensional hypercube decide things for node
% count 4, 16, 64, 256

% N   | tori n | cube k
% 4       2        2
% 16      4        4
% 64      8        6
% 256    16        8
\subsection{Task 6.a}
% At what scale does the hypercube provide (strictly) higher bisection width than the torus?

Table \ref{tab:task6a1} shows the different dimensions of the two patterns for
the specified networks sizes, this is used to calculate the bisection widths
which can be seen in Table \ref{tab:task6a2}. We can see that at $N=64$ the
hypercube provides a strictly greater bisection width.

\begin{table}[H]
    \centering
    \begin{tabular}{|r|r|r|}
        \hline
        $N$ & Tori $n$ & Cube $k$ \\\hline
          4 &  2       & 2        \\
         16 &  4       & 4        \\
         64 &  8       & 6        \\
        256 & 16       & 8        \\\hline
    \end{tabular}
    \caption{The different variables needed for calculating the dimensions of
        the two patterns.}
    \label{tab:task6a1}
\end{table}

\begin{table}[H]
    \centering
    \begin{tabular}{|l|l|l|}
        \hline
        $N$     & Tori & HyperCube \\ \hline
        Formula & $2n$ & $2^{k-1}$ \\
        4       &  4   &   2       \\
        16      &  8   &   8       \\
        64      & 16   &  32       \\
        256     & 32   & 128       \\ \hline
    \end{tabular}
    \caption{My caption}
    \label{tab:task6a2}
\end{table}

\subsection{Task 6.b}
% Determine the network diameter and the switch degree for the scale at which the hypercube
% provides a higher bisection width than the torus.

% Scale: N=64.
% n/k = 8/6
% Network Diameter: 8/6
% Switch degree: 4/6

Using the formulas from \cite[slide 38]{l7Interconnect} for scale $N=64$ as
calculated in the previus sub task, we have a $8$-by-$8$ tori and a
$6$-dimensional hypercube, so we have $n=8$ and $k=6$. This gives the tori a
network diameter of $8$ and the hypercube a network diameter of $6$. The switch
degree for the tori is $4$ regardless of the size of the tori, and for the
hypercube it is $6$.

\subsection{Task 6.c}
% What can you say about the relative merits of the two topologies?
\begin{itemize}
    \item[Hyper-cybe] The high bisection width allows for potential high
    bandwidth through the many links, however this also comes with a high
    switching degree, and for higher dimensions hyper-cubes, they layout of the
    cube itself becomes highly complicated, which makes the hyper-cube a very
    costly interconnection pattern.

    \item[Torus] A constant switching degree means that nodes can be added
    without adding complexity to the rest of the system. The slower growing
    bisection width means that potential bandwidth doesn't increase as fast as
    with the hyper-cube.
\end{itemize}


\subsection{Type graphs}
\label{subsec:formalisations:groove_formalisation:type_graphs}

In GROOVE, type graphs are used to constrain the valid instance graphs within the grammar. From a type graph follows a set of valid instance graphs that can be used for verification.

\begin{defin}[Type graph]
\label{defin:formalisations:groove_formalisation:type_graphs:type_graph}
A type graph is modeled as tuple $TG$:
\begin{equation}
    TG = \langle NT, ET, \sqsubseteq, abs, \mathrm{mult}, contains \rangle
\end{equation}
with
\begin{itemize}
    \item $NT \subseteq Lab_t \cup Lab_{prim}$ is the set of nodes in the type graph. The nodes can consist of type labels (see \cref{defin:formalisations:groove_formalisation:definitions:labels}) or primitive type labels (see \cref{defin:formalisations:groove_formalisation:definitions:primitive_type_labels}).

    \item $ET \subseteq NT \times (Lab_e \cup Lab_f) \times NT$ is the set of (directed) edges in the type graph, which is a set of triples containing the source and target node, as well as the edge label or flag label (see \cref{defin:formalisations:groove_formalisation:definitions:labels}) used to identify the edge.

    \item $\sqsubseteq\ \subseteq NT \times NT$ is the inheritance relation, the set of tuples of nodes between which an inheritance relation exists.

    \item $abs \subseteq NT$ is the (possibly empty) subset of nodes in the type graph which are considered abstract. An instance graph cannot instantiate abstract nodes.

    \item $\mathrm{mult}: ET \Rightarrow \mathbb{M} \times \mathbb{M}$ is the function which maps edges to their multiplicity pair. See \cref{defin:formalisations:groove_formalisation:type_graphs:multiplicity_pair} for the definition.

    \item $contains \subseteq ET$ is the set of edges which identify an containment relation.
\end{itemize}

\isabellelref{type_graph}{GROOVE.Type_Graph}
\end{defin}

\begin{figure}[p]
    \centering
    \begin{subfigure}{\textwidth}
        \centering
        \input{images/03_formalisations/03_groove_formalisation/type_graph_example.tikz}
        \caption{Type graph in GROOVEs visual notation. Multiplicities are omitted for clarity.}
    \end{subfigure}

    \begin{subfigure}{\textwidth}
        \centering
        \begin{align*}
            NT_{TG} =\ & \{
                \type{House},
                \type{PaymentInterval},
                \type{PaymentInterval\$MONTH},\\&
                \type{PaymentInterval\$QUARTER},
                \type{Person},
                \type{Renter},
                \type{Room},
                \type{int},
                \type{string}
            \}\\
            ET_{TG} =\ & \{
                ( \type{House}, \type{name}, \type{string} ),
                ( \type{House}, \type{rooms}, \type{Room} ),\\&
                ( \type{Person}, \type{age}, \type{int} ),
                ( \type{Person}, \type{name}, \type{string} ),\\&
                ( \type{Renter}, \type{payment\_interval}, \type{PaymentInterval} ),
                ( \type{Renter}, \type{rents}, \type{Room} ),\\&
                ( \type{Room}, \type{number}, \type{int} ),
                ( \type{Room}, \type{renter}, \type{Renter} )
            \}\\
            \sqsubseteq_{TG}\: =\ & \{
                ( \type{House}, \type{House} ),
                ( \type{PaymentInterval}, \type{PaymentInterval} ),\\&
                ( \type{PaymentInterval\$MONTH}, \type{PaymentInterval} ),\\&
                ( \type{PaymentInterval\$MONTH}, \type{PaymentInterval\$MONTH} ),\\&
                ( \type{PaymentInterval\$QUARTER}, \type{PaymentInterval} ),\\&
                ( \type{PaymentInterval\$QUARTER}, \type{PaymentInterval\$QUARTER} ),\\&
                ( \type{Person}, \type{Person} ),
                ( \type{Renter}, \type{Person} ),
                ( \type{Renter}, \type{Renter} ),
                ( \type{Room}, \type{Room} ),
                ( \type{int}, \type{int} ),
                ( \type{string}, \type{string} )
            \}\\
            abs_{TG} =\ & \{
                \type{PaymentInterval}, \type{Person}
            \}\\
            \mathrm{mult}_{TG} =\ & \big\{
                \big( ( \type{House}, \type{name}, \type{string} ), ( 0..*, 1..1 ) \big),
                \big( ( \type{House}, \type{rooms}, \type{Room} ), ( 1..1, 1..* ) \big),\\&
                \big( ( \type{Person}, \type{age}, \type{int} ), ( 0..*, 1..1 ) \big),
                \big( ( \type{Person}, \type{name}, \type{string} ), ( 0..*, 1..1 ) \big),\\&
                \big( ( \type{Renter}, \type{payment\_interval}, \type{PaymentInterval} ), ( 0..*, 1..1 ) \big),\\&
                \big( ( \type{Renter}, \type{rents}, \type{Room} ), ( 0..*, 0..* ) \big),\\&
                \big( ( \type{Room}, \type{number}, \type{int} ), ( 0..*, 1..1 ) \big),
                \big( ( \type{Room}, \type{renter}, \type{Renter} ), ( 0..*, 0..1 ) \big)
            \big\}\\
            contains_{TG} =\ & \{
                ( \type{House}, \type{rooms}, \type{Room} )
            \}
        \end{align*}
        \caption{Formal definition of the type graph}
    \end{subfigure}
    \caption{Example of a type graph corresponding with \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph}}
    \label{fig:formalisations:groove_formalisation:type_graphs:type_graph_example}
\end{figure}

An example of a type graph is given in \cref{fig:formalisations:groove_formalisation:type_graphs:type_graph_example}. This example is similar to the type model example discussed in \cref{subsec:formalisations:ecore_formalisation:type_models}. There is a node $\type{House}$ which contains $\type{Room}$s. A $\type{House}$ also has an edge to a primitive type label $\type{string}$ under edge label $\type{name}$ which represents the name of the house. Please note that in the visual representation, syntactic sugar is used to represent this edge. Instead of an extra node and edge, it is represented as part of the $\type{House}$ node. This syntactic sugar can be used for edges to primitive types and are in reality still treated as an edge to a separate node type. A $\type{Room}$ has an edge $\type{number}$, targeting the primitive type label $\type{int}$, which represents the number of the room within the house. A $\type{Room}$ can be rented by a $\type{Renter}$. The $\type{Renter}$s have edges to the $\type{Room}$s they rented under the edge label $\type{rents}$, while a $\type{Room}$ can access its $\type{Renter}$ through the edge with edge label $\type{renter}$. A $\type{Renter}$ extends the abstract $\type{Person}$ node type, which has 2 edges $\type{age}$ and $\type{name}$, targeting the primitive type labels $\type{int}$ and $\type{string}$ respectively. These edges represent the age and the name of the $\type{Person}$. Finally, a $\type{Renter}$ has an edge under the edge label $\type{payment\_interval}$, which points to a $\type{PaymentInterval}$ node type. This node type is abstract and the edge should therefore point to one of its subtypes, $\type{PaymentInterval\$MONTH}$ or $\type{PaymentInterval\$QUARTER}$. This represents the interval in which the $\type{Renter}$ pays the rent.
Notable from the definition is that the nodes set $N$ can contain primitive type labels. As a consequence, primitive type labels need to be added explicitly to a type graph in order to use primitive type values in an instance graph.

Furthermore, each edge has a multiplicity pair tied to it, which is defined as the $\mathrm{mult}$ function in the type graph definition. The multiplicity pair consists of an incoming multiplicity and an outgoing multiplicity. The incoming multiplicity determines the allowed amount of nodes that share the same target node with this edge type. On the other hand, the outgoing multiplicity determines the number of edges a single source node may have to its target nodes.

\begin{defin}[Multiplicity pair]
\label{defin:formalisations:groove_formalisation:type_graphs:multiplicity_pair}
A multiplicity pair is defined as a tuple of two multiplicities, $\mathbb{M} \times \mathbb{M}$, in which the first value denotes the incoming multiplicity and the second value the outgoing multiplicity.

For any multiplicity pair, we define two functions:
\begin{align*}
    \mathrm{in}\!:&\: \mathbb{M} \times \mathbb{M} \Rightarrow \mathbb{M} \\
    \mathrm{out}\!:&\: \mathbb{M} \times \mathbb{M} \Rightarrow \mathbb{M}
\end{align*}
The $\mathrm{in}$ function being the function which from a multiplicity pair returns the incoming multiplicity and the $\mathrm{out}$ function being the function that returns the outgoing multiplicity, so:
\begin{equation*}
\forall m = (m_{in}, m_{out}) \in \mathrm{mult}_{TG}: \mathrm{in}(m) = m_{in} \land \mathrm{out}(m) = m_{out}
\end{equation*}

\isabellelref{multiplicity_pair}{GROOVE.Multiplicity_Pair}
\end{defin}

With all definitions in place, it is possible to define a valid type graph.
The definition of a valid type graph introduces some new constraint that should hold for a type graph to be valid.

\begin{defin}[Type graph validity]
\label{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity}
For a type graph to be valid, the following properties must hold:
\begin{enumerate}
    \item There may not be any ambiguity in the use of edges: $\forall (s_1, l, t_1) \in ET_{TG}\,\land\, (s_2, l, t_2) \in ET_{TG}\!: \big((s_1, s_2) \in\ \sqsubseteq_{TG} \lor\ (s_2, s_1) \in\ \sqsubseteq_{TG}\!\!\big) \land \big((t_1, t_2) \in\ \sqsubseteq_{TG} \lor\ (t_2, t_1) \in\ \sqsubseteq_{TG}\!\!\big) \Longrightarrow s_1 = s_2 \land t_1 = t_2$.
    \item Flags should have the same source and target node: $\forall (s, l, t) \in ET_{TG}: l \in Lab_f \Longrightarrow s = t$.
    \item $\sqsubseteq_{TG}$ is a partial order ($\sqsubseteq_{TG}$ is reflexive, transitive and anti-symmetric on $N\!$).
    \item The incoming multiplicities of edges that identify a containment relation are valid: $\forall e \in contains_{TG}: \mathrm{in}(\mathrm{mult}_{TG}(e)) = (0, 1) \lor \mathrm{in}(\mathrm{mult}_{TG}(e)) = (1, 1)$.
\end{enumerate}

\isabellelref{type_graph}{GROOVE.Type_Graph}
\end{defin}

\begin{figure}
    \centering
    \begin{subfigure}{0.45\textwidth}
        \centering
        \input{images/03_formalisations/03_groove_formalisation/edge_ambiguity_example_valid.tikz}
        \caption{Valid type graph without ambiguity}
        \label{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example:valid}
    \end{subfigure}
    \begin{subfigure}{0.45\textwidth}
        \centering
        \input{images/03_formalisations/03_groove_formalisation/edge_ambiguity_example_invalid.tikz}
        \caption{Invalid type graph with an ambiguous edge type labelled $\type{f}$}
        \label{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example:invalid}
    \end{subfigure}
    \caption{Example of ambiguity within edge types}
    \label{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example}
\end{figure}

The last 3 properties presented here are mostly self-explanatory. The first property might be unclear at first. This property prevents type graphs from having ambiguous edge types. \cref{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example} shows an example of such an ambiguity. In essence, when creating edges within an instance graph, there should be an unique solution for typing the edge. In \cref{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example:valid}, this is always the case, even though both edges are labelled $\type{f}$. If an edge labelled $\type{f}$ references a node of type $\type{B}$, then the edge type should be $( \type{Y}, \type{f}, \type{B} )$. When an edge labelled $\type{f}$ references a node of type $\type{A}$, the edge type should be $( \type{X}, \type{f}, \type{A} )$. There is no ambiguity possible.

\cref{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example:invalid} shows an example of a type graph where ambiguity is possible. When a node of type $\type{Y}$ references a node of $\type{B}$ using an edge labelled $\type{f}$, it is unclear which edge type was meant. Both $( \type{Y}, \type{f}, \type{B} )$ and $( \type{X}, \type{f}, \type{A} )$ would be valid edge types here. This means there is ambiguity in how edges are typed. The first property of \cref{defin:formalisations:groove_formalisation:type_graphs:type_graph_validity} excludes this case, since $( \type{Y}, \type{f}, \type{B} )$ and $( \type{X}, \type{f}, \type{A} )$ are both edge types, while $(\type{Y}, \type{X}) \in\ \sqsubseteq_{TG}$ and $(\type{B}, \type{A}) \in\ \sqsubseteq_{TG}$. Then according to the first property, $\type{Y}$ should be equal to $\type{X}$ and $\type{B}$ should be equal to $\type{A}$, which is not the case, so \cref{fig:formalisations:groove_formalisation:type_graphs:ambiguous_edges_example:invalid} violates the first property, hence the example is invalid.


%%
%% This is file `./samples/shortsample.tex',
%% generated with the docstrip utility.
%%
%% The original source files were:
%%
%% apa6.dtx  (with options: `shortsample')
%% ----------------------------------------------------------------------
%%
%% apa6 - A LaTeX class for formatting documents in compliance with the
%% American Psychological Association's Publication Manual, 6th edition
%%
%% Copyright (C) 2011-2017 by Brian D. Beitzel <brian at beitzel.com>
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License (LPPL), either
%% version 1.3c of this license or (at your option) any later
%% version.  The latest version of this license is in the file:
%%
%% http://www.latex-project.org/lppl.txt
%%
%% Users may freely modify these files without permission, as long as the
%% copyright line and this statement are maintained intact.
%%
%% This work is not endorsed by, affiliated with, or probably even known
%% by, the American Psychological Association.
%%
%% ----------------------------------------------------------------------
%%
\documentclass[jou]{apa6}

\usepackage[american]{babel}

\usepackage{csquotes}
\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{bibliography.bib}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Discrete Structures
%% The start of RBS stuff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Working internal and external links in PDF
\usepackage{hyperref}
% Extra math symbols in LaTeX
\usepackage{amsmath}
\usepackage{gensymb}
\usepackage{amssymb}
% Enumerations with (a), (b), etc.
\usepackage{enumerate}

\let\OLDitemize\itemize
\renewcommand\itemize{\OLDitemize\addtolength{\itemsep}{-6pt}}

\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=3pt \partopsep=3pt }
\makeatother

% These sizes redefine APA for A4 paper size
\oddsidemargin 0.0in
\evensidemargin 0.0in
\textwidth 6.27in
\headheight 1.0in
\topmargin -24pt
\headheight 12pt
\headsep 12pt
\textheight 9.19in

\title{Sample Quiz for Week02}
\author{Discrete Structures, Fall 2020}
\affiliation{RBS}

\leftheader{Discrete Structures (W2): Sample Quiz}

\abstract{%
}

%\keywords{}

\begin{document}

\twocolumn

\section{Worksheet 2: Predicates}

{\bf Question 1.} Let $a,b \in \mathbb{Z}^{+}$ be two positive integers.
Translate into predicate logic: ``$d$ is the greatest common divisor
of $a,b$.'' (That is,
the greatest number that divides both $a$ and $b$).\\
{\em Note 1.} "Translate into predicate logic" means - use
predicates and quantifiers to express that statement.
{\em Note 2.} Use ``infix'' notation for common predicates: write
$a\,\mid\,b$ whenever $a$ divides $b$; write $x < y$, if $x$ is less than $y$. For example, $3\,|\,6$ \hspace{1ex}
($3$ divides $6$) is preferred compared to
``$\mathtt{divides}(3,6)$''. Also \hspace{1ex}
$10 < 17$ is more readable than
``$\mathtt{lessThan(10,17)}$''.

\vspace{10pt}
{\bf Question 2.} Use quantifiers to write a
statement to tell that a quadratic
function $f(x) = ax^2 +bx+c$
has two different integer roots.

\vspace{10pt}
{\bf Question 3.} Assume that for some argument {\tt x},
Python functions {\tt a(x)} and {\tt b(x)}
return value {\tt True}, but other two functions
{\tt c(x)} and {\tt d(x)} return value {\tt False}.
Which functions are called and evaluated, if you run the following conditional statement:
\begin{verbatim}
if (a(x) or b(x)) and (c(x) & d(x)):
    ## ... some Python code ...
\end{verbatim}
{\em Note.} Note that Boolean operators {\tt and}, {\tt or}
use {\em short-circuit
evaluation}, but operators {\tt \&}, {\tt |} do not.

\vspace{10pt}
{\bf Question 4.} There is a set $C$ of several children and a
set $H$ of several hats. There is a predicate $W(c,h)$ which is {\tt True}
iff the child $c \in C$ has ever worn the hat $h \in H$.\\
{\bf (a)} Write the domain set and the range set of the predicate function $W$. \\
{\bf (b)} Use quantifiers to write a statement: ``Every two
children have at least one hat in common (that is, both of
them have worn it).''

\vspace{10pt}
{\bf Question 5.}
Let $\mathcal{H}$ be the set of all humans, and the predicate $F(x,y)$ is
true iff $x$ is the father of $y$. Express these sentences in plain English:\\
{\bf (a)} $\forall y \in \mathcal{H}\;\exists x \in \mathcal{H},\;F(x,y)$.\\
{\bf (b)} $\exists x \in \mathcal{H}\;\forall y \in \mathcal{H},\;F(x,y)$.\\
{\bf (c)} Which of the two statements {\bf (a)}, {\bf (b)} (if any)
is true, if we replace the non-empty domain of all humans $\mathcal{H}$ by an
empty domain $\mathcal{Z} = \emptyset$ of all zombies?

\vspace{10pt}
{\bf Question 6.} We define predicates $P(x,y)$,
$Q(x,y)$ with two arguments,
where $x,y$ can be any of the three letters:
$\mathtt{a},\mathtt{b},\mathtt{c}$.
(The type for all these predicates is
$\{ \mathtt{a},\mathtt{b},\mathtt{c} \}^2
\rightarrow \{ \mathtt{T},\mathtt{F} \}$.)

They have these following truth tables:
\begin{center}
\begin{tabular}{c|ccc}
$P$ & $a$ & $b$ & $c$ \\ \hline
$a$ & $\mathtt{T}$ & $\mathtt{F}$ & $\mathtt{T}$ \\
$b$ & $\mathtt{F}$ & $\mathtt{F}$ & $\mathtt{F}$ \\
$c$ & $\mathtt{T}$ & $\mathtt{T}$ & $\mathtt{T}$
\end{tabular}
\hspace{2ex}
\begin{tabular}{c|ccc}
$Q$ & $a$ & $b$ & $c$ \\ \hline
$a$ & $\mathtt{F}$ & $\mathtt{T}$ & $\mathtt{F}$ \\
$b$ & $\mathtt{F}$ & $\mathtt{F}$ & $\mathtt{T}$ \\
$c$ & $\mathtt{T}$ & $\mathtt{F}$ & $\mathtt{F}$
\end{tabular}
\end{center}
Find the truth values of these statements:\\
{\bf (a)} $\exists x \forall y, P(y,x)$\\
{\bf (b)} $\exists x \forall y, P(x,y)$\\
{\bf (c)} $\exists x \exists y, Q(x,y)$\\
{\bf (d)} $\forall x \exists y, Q(x,y)$\\
{\em Note.} In all truth tables the first argument is
represented by row, the second is represented by column.
For example $P(\mathtt{b}, \mathtt{c}) = \mathtt{F}$ (2nd row
and 3rd column). Meanwhile
$P(\mathtt{c}, \mathtt{b}) = \mathtt{T}$ (3rd row and 2nd column).

\vspace{10pt}
{\bf Question 7.}
For a real number $x$ we know that $\lfloor x \rfloor \neq
\lfloor x + 0.5 \rfloor$. Write this statement in
predicate logic without using any $\lfloor \ldots \rfloor$
notation. (Write instead that $x$ and $x+0.5$ have some integer number
betwen $x$  and $x+0.5$.)\\
{\em Note.} By $\lfloor x \rfloor$ we denote the
largest integer number that does not exceed $x$.
For example $\lfloor 3.14 \rfloor = 3$, $\lfloor 17 \rfloor = 17$,
$\lfloor -4.5 \rfloor = -5$.

\newpage

\subsection{Answers}

{\bf Question 1.} Answer:
$$\boxed{\forall k \in \mathbb{Z}^{+},\;\left(k\,\mid\,a \wedge
k\,\mid\,b\right)\,\rightarrow\,k \leq d.}$$
{\em Recite:} ``For all positive integers $k$, if $k$ divides
both $a$ and $b$, then $k$ does not exceed
$d = \operatorname{gcd}(a,b)$.''\\
This also means that $d$ is the largest number among all
common divisors of $a,b$ ({\em greatest common divisor}, GCD).\\
{\em Note:} In the above formula $a,b,d$ are ``free variables''
(they need to be assigned independently; and if
$d \neq \operatorname{gcd}(a,b)$, then the statement is false).
On the other hand, $k$ is a ``bound variable''. You can rename
$k$ into $x$ \textendash{} and nothing will change.

\vspace{10pt}
{\bf Question 2.} Answer:
\begin{align}
 & \exists x_1 \in \mathbb{Z}^{+}\,\exists x_2 \in \mathbb{Z}^{+}\,
\forall x_3 \in \mathbb{Z}^{+}, \nonumber \\
 & \left( x_1 \neq x_2 \wedge f(x_1)=0 \wedge f(x_2) = 0 \right) \wedge \nonumber \\
\wedge & \left( f(x_3) = 0 \rightarrow x_3 = x_1 \vee x_3 = x_2 \right).
\nonumber
\end{align}
{\em Recite:} ``There exist two positive integers $x_1,x_2$
such that they are different and
both of them are roots of $f(x)=0$ and,
furthermore, for any other root $x_3$, it
equals either $x_1$ or $x_2$.''\\
{\em Note:} The above statement says that there are {\em exactly}
two roots $x_1$ and $x_2$. You can easily write a modified statement
saying that the equation $f(x)=0$ has {\em at least} two roots \textendash{}
in this case you can skip the $x_3$ part. For quadratic equations it
is the same (since no equation has more than $2$ roots), but
the idea expressed here is slightly different:
\begin{align}
 & \exists x_1 \in \mathbb{Z}^{+}\,\exists x_2 \in \mathbb{Z}^{+} \nonumber \\
 & \left( x_1 \neq x_2 \wedge f(x_1)=0 \wedge f(x_2) = 0 \right). \nonumber
\end{align}

\vspace{10pt}
{\bf Question 3.} Answer:\\
\underline{The following functions are called: {\tt a(x)},
{\tt c(x)}, {\tt d(x)}.}\\
Function {\tt b(x)} is not called, because
short-circuit operator {\bf or}
skips the second argument in ``{\tt a(x) or b(x)}'',
if the first argument is {\tt True}.

\vspace{10pt}
{\bf Question 4.} Answer: {\bf (a)}
$$\boxed{W\,:\,C \times H \rightarrow \{ \mathtt{T}, \mathtt{F} \}.}$$
{\em Note.} In Coq the set of ``True'' and ``False''
is denoted by {\tt Prop} or $\{ \mathtt{T}, \mathtt{F} \}$.\\
{\bf (b)}
$$\boxed{\forall c_1 \in C \; \forall c_2 \in C \; \exists h \in H,
W(c_1,h) \wedge W(c_2,h).}$$
Every two
children have at least one hat in common (that is, both
of them have worn it).

\vspace{10pt}
{\bf Question 5.} Answers:\\
{\bf (a)} \underline{Every human has a father.}\\
{\bf (b)} \underline{There exists someone, who is the father of everyone.}\\
{\bf (c)} \underline{Both (a) and (b) are false for empty sets.}\\
Every time we write $\exists x \in \mathcal{Z}$
regarding anything (where $\mathcal{Z} = \emptyset$ \textendash{}
an empty set) it is false.

On the other hand, this statement is {\tt True}:
$$\forall x \in \mathcal{Z} \; \forall y \in \mathcal{Z},\; F(x,y) \equiv \mathtt{True}.$$
{\em Recite:} ``In the (empty) set $\mathcal{Z}$ of all
zombies, any zomby is a father of any other zomby.''\\
{\em Note.} For empty domains we do not need to know anything
about the predicate values, because their truth tables have
zero rows and zero columns. You can also safely state the negation:
``No zomby is a father of another zomby.''
$$\forall x \in \mathcal{Z} \; \forall y \in \mathcal{Z},\; \neg F(x,y) \equiv \mathtt{True}.$$

\vspace{10pt}
{\bf Question 6.} Answers:\\
{\bf (a)} False. In the truth table of $P$, there is NO
column (denoted by $x$) containing $\mathtt{T}$ in
every row.\\
{\bf (b)} True. In the truth table of $P$ there is a row $x$
(it is the last row $x = \mathtt{c}$), containing
$\mathtt{T}$ in every column.\\
{\bf (c)} True. We can indeed make $Q(x,y)$ true, if we pick
row and column. For example $Q(\mathtt{c},\mathtt{a}) = \mathtt{T}$.\\
{\bf (d)} True. For any row in the truth table of $Q$,
we can find at least one $\mathtt{T}$ in some column.

\vspace{10pt}
{\bf Question 7.} Answer:\\
$$\exists k \in \mathbb{Z}, x < k \wedge x+0.5 \geq k.$$
In this example $\lfloor x \rfloor = k-1$, but
$\lfloor x+0.5 \rfloor = k$, so they are different.

\end{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% End of RBS stuff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%
%% Copyright (C) 2011-2017 by Brian D. Beitzel <brian at beitzel.com>
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License (LPPL), either
%% version 1.3c of this license or (at your option) any later
%% version.  The latest version of this license is in the file:
%%
%% http://www.latex-project.org/lppl.txt
%%
%% Users may freely modify these files without permission, as long as the
%% copyright line and this statement are maintained intact.
%%
%% This work is not endorsed by, affiliated with, or probably even known
%% by, the American Psychological Association.
%%
%%
%% This work is "maintained" (as per LPPL maintenance status) by
%% Brian D. Beitzel.
%%
%% This work consists of the file  apa6.dtx
%% and the derived files           apa6.ins,
%%                                 apa6.cls,
%%                                 apa6.pdf,
%%                                 README,
%%                                 APAamerican.txt,
%%                                 APAbritish.txt,
%%                                 APAdutch.txt,
%%                                 APAenglish.txt,
%%                                 APAgerman.txt,
%%                                 APAngerman.txt,
%%                                 APAgreek.txt,
%%                                 APAczech.txt,
%%                                 APAturkish.txt,
%%                                 APAendfloat.cfg,
%%                                 apa6.ptex,
%%                                 TeX2WordForapa6.bas,
%%                                 Figure1.pdf,
%%                                 shortsample.tex,
%%                                 longsample.tex, and
%%                                 bibliography.bib.
%%
%%
%% End of file `./samples/shortsample.tex'.


% !TEX root = ../zeth-protocol-specification.tex

\section{Ethereum}\label{preliminaries:ethereum}

In a nutshell, \ethereum~is a distributed deterministic state machine, consisting of a globally accessible singleton state (``the World state'') and a virtual machine that applies changes to that state~\cite{mastering-eth}.
State transitions in the state machine are represented by transactions on the system. As such, each transaction represents a change in the global state represented as a Merkle Patricia Tree~\cite{patricia-tree} whose nodes are objects called ``accounts'' (\cref{preliminaries:ethereum:eth-account}). The Ethereum Virtual Machine (\evm) allows state transitions to be specified by creating a type of accounts which are associated with a piece of code (smart-contracts). The code of such accounts, and so, the corresponding state transitions, can be executed to transition to another state in the automata, by creating a transaction that calls the given piece of code (\cref{preliminaries:ethereum:eth-tx}).

To prevent unbounded state transitions in the state machine, each instruction executed by the \evm~is associated with a cost in \wei, referred to as ``the gas necessary to run the operation''. The ``gas cost'' of a transaction needs to be paid by the transaction originator (deduced from their account balance), and is awarded to the miner (added to their account balance) who successfully mines the block containing the transaction.
In addition to the cost of every instruction executed as part of a state transition, every transaction has an intrinsic cost of $\txDefaultGas$ gas~\cite[Appendix G]{ethyellowpaper}. Bounding modifications to the $\ethereum{}$ state by the amount of \wei~held in the transaction originator's account allows the system to avoid the Halting problem\footnote{\url{https://en.wikipedia.org/wiki/Halting\_problem}} and protects against a range of Denial of Service (\dos) attacks.

\subsection{Ethereum account}\label{preliminaries:ethereum:eth-account}

An \ethereum~account~\cite[Section 4.1]{ethyellowpaper} is an object containing 4 attributes, as represented~\cref{preliminaries:tab:eth-account}.
We distinguish two types of accounts:
\begin{itemize}
    \item ``Externally Owned Accounts'' (\eoa), that are created by derivation of an \ecdsa~secret key; and
    \item Smart-contract accounts, that are derived from \evm~code specifying a state transition on the state machine.
\end{itemize}

Each account object is accessible in the Merkle Patricia Tree representing the ``World state'' by a unique $\addressLen$-bit long identifier called the address.
In the context of \eoa, the address is obtained by generating a new \ecdsa~\cite{johnson2001elliptic} key pair $\smalltuple{\sk, \vk}$ over curve \secpCurve~\cite{qu1999sec} and taking the rightmost $\addressLen$ bits of the \keccak{256} hash of the verification key $\vk$.

\begin{table}[H]
    \centering
    \begin{tabular}{cp{25em}c}
        Field           & Description & Data type\\ \toprule
        $\nonce$        & The nonce of an account is a scalar value representing the number of transactions that have originated from the account, starting at 0. & $\NN_\ethWordLen$ \\ \midrule
        $\balance$      & The balance of an account is a scalar value representing the amount of \wei~in the account. & $\NN_\ethWordLen$\\ \midrule
        $\sroot$        & The storage root is the \keccak{256} hash representing the storage of the account. & $\BB^{\keccakTwoDigestLen}$\\ \midrule
        $\codeh$        & The code hash is the hash of the \evm~code governing the account. If this field is the \keccak{256} hash of the empty string, then the account is said to be an ``Externally owned Account'' (\eoa), and is controlled by the corresponding \ecdsa~private key. If, however, this field is not the \keccak{256} hash of the empty string, the account represents a smart contract whose interactions are governed by its \evm~code. & $\BB^{\keccakTwoDigestLen}$\\ \bottomrule
    \end{tabular}
    \caption{Ethereum Account structure}\label{preliminaries:tab:eth-account}
\end{table}

\begin{notebox}
In the rest of this document, we will refer to an \emph{Ethereum user} $\eparty{U}$ as a person, modeled as an object, holding \emph{one}\footnote{The same physical person may correspond to multiple ``$\ethereum{}$ users'' and thus control multiple accounts in the Merkle Patricia Tree.} secret key, $\sk$ (object attribute), associated with an existing \eoa~in the ``World state''. We denote by $\eparty{U}.\addr$ the \ethereum~address of $\eparty{U}$ derived from $\eparty{U}.\sk$, and which allows $\eparty{U}$ to access the state of their account $\wstate[\eparty{U}.\addr]$.

We denote by $\contractstyle{SmartC}$ a smart-contract instance/object (i.e.~deployed smart-contract with an address,~\cref{preliminaries:ethereum:eth-tx}), and denote by $\contractstyle{SmartC}.\addr$ its address.
\end{notebox}

\subsection{Ethereum transaction}\label{preliminaries:ethereum:eth-tx}

We now briefly mention what \ethereum~transactions~\cite[Section 4.2]{ethyellowpaper} are, and how they are created, signed and validated. Once more, the reader is highly encouraged to refer to~\cite{ethyellowpaper} for a detailed presentation.
%\subsubsection{Transaction}
Informally, a transaction object ($\tx$) is a signed message originating from an \ethereum~user $\eparty{U}$ (the \emph{transaction originator}, or simply \emph{sender}) that represents a state transition on the distributed state machine (i.e.~a change in the ``World state'' $\wstate$).

\subsubsection{Raw transaction}\label{preliminaries:ethereum:eth-tx:raw}
In the following, we define a raw transaction as an unsigned transaction (\cref{preliminaries:tab:eth-unsigned}).

\begin{table}[H]
    \centering
    \begin{tabular}{ccc}
        Field			    & Description & Data type \\\toprule
        $\nonce$            & Transaction nonce & $\NN_{\ethWordLen}$\\\midrule
        $\gasp$		        & gasPrice & $\NN_{\ethWordLen}$\\\midrule
        $\gasl$		        & gasLimit & $\NN_{\ethWordLen}$\\\midrule
        $\tto$		        & Recipient's address & $\BB^{\addressLen}$\\\midrule
        $\val$		        & Value of the transaction in $\wei$ & $\NN_{\ethWordLen}$\\\midrule
        $\init$ / $\data$	& \begin{tabular}{@{}c@{}}Contract Creation data $\init$ \\ Message call data $\data$\end{tabular} & $\BB^{*}$\\\bottomrule
    \end{tabular}
    \caption{Structure of a \emph{raw transaction data type} $\txRawDType$}\label{preliminaries:tab:eth-unsigned}
\end{table}

\subsubsection{Finalizing raw transactions}\label{preliminaries:ethereum:eth-tx:final}
A raw transaction needs to be finalized to be accepted. In the context of this document, ``finalizing a raw transaction'' will be a synonym of ``signing a raw transaction''. The transaction structure is represented in~\cref{preliminaries:tab:eth-signed}.

\begin{table}[H]
    \centering
    \begin{tabular}{ccc}
        Field           & Description & Data type \\ \toprule
        $\rawTx$      & Raw transaction object & $\txRawDType$ \\ \midrule
        $\sigv$         & Field $\sigv$ of $\ecdsa$ signature used for public key recovery & $\BB^{\byteLen}$\\ \midrule
        $\sigr$         & Field $\sigr$ of $\ecdsa$ signature~\cite{rfc6979} & $\FFx{\rSecp}$\\ \midrule
        $\sigs$         & Field $\sigs$ of $\ecdsa$ signature~\cite{rfc6979} & $\FFx{\rSecp}$\\ \bottomrule
    \end{tabular}
    \caption{Structure of a (finalized) \emph{transaction data type} $\txDType$}\label{preliminaries:tab:eth-signed}
\end{table}

We define the transaction generation function, cf.~\cref{preliminaries:fig:txgen}, as the function taking the sender's \ecdsa~signing key and the components of a raw transaction as arguments, and returning a signed (or finalized) transaction ($\finalTx$ or $\tx$ for short).
\begin{align*}
    \finalTx &= \txgen(\sk_{\ecdsa}, \inp{\nonce}, \inp{\gasp}, \inp{\gasl}, \inp{\tto}, \inp{\val}, \inp{\init}, \inp{\data})\\
    \finalTx &= \{ \\
                & \left.
                \begin{array}{l@{}l}
                    \nonce & {}: \inp{\nonce},\\
                    \gasp & {}: \inp{\gasp},\\
                    \gasl & {}: \inp{\gasl},\\
                    \tto & {}: \inp{\tto},\\
                    \val & {}: \inp{\val},\\
                    \init/\data & {}: \inp{\init}/\inp{\data},
                \end{array}
                \right\rbrace~\rawTx\\
                & \left.
                \begin{array}{l@{}l}
                    \sigv & {}: \sigma_\ecdsa.\sigv,\\
                    \sigr & {}: \sigma_\ecdsa.\sigr,\\
                    \sigs & {}: \sigma_\ecdsa.\sigs \\
                \end{array}
                \right\rbrace~\sigma_\ecdsa\\
                \}
\end{align*}

To sign a transaction, the sender first computes the hash of the raw transaction using $\keccak{256}$, cf.~\cref{preliminaries:eq:tx-sig-hash}, and then uses their \ecdsa~signing key, $\sk_\ecdsa$, to sign the obtained digest. cf.~\cref{preliminaries:eq:tx-sig-sig}. The signature is then appended to the raw transaction to obtain a finalized transaction, cf.~\cref{preliminaries:fig:txgen}.

\begin{align}
    \digest_\ecdsa &= \keccak{256}(\inp{\nonce}, \inp{\gasp}, \inp{\gasl}, \inp{\tto}, \inp{\val}, \inp{\init}/\inp{\data}) \label{preliminaries:eq:tx-sig-hash} \\
    \sigma_{\ecdsa} &= \ecdsasigscheme.\sig(\sk_\ecdsa, \digest_\ecdsa)\ (= \smalltuple{\sigv, \sigr, \sigs}) \label{preliminaries:eq:tx-sig-sig}
\end{align}

\begin{figure}[H]
    \centering
    \procedure[linenumbering]{$\txgen(\sk_\ecdsa, \inp{\nonce}, \inp{\gasp}, \inp{\gasl}, \inp{\tto}, \inp{\val}, \inp{\init}, \inp{\data})$}{%
    \pcif \inp{\tto} = \emptyset \pcdo\\
    \t \rawTx \gets \{\nonce: \inp{\nonce}, \gasp: \inp{\gasp}, \gasl: \inp{\gasl}, \tto: \inp{\tto}, \val: \inp{\val}, \init: \inp{\init}\}; \\
    \pcelse \\
    \t \rawTx \gets \{\nonce: \inp{\nonce}, \gasp: \inp{\gasp}, \gasl: \inp{\gasl}, \tto: \inp{\tto}, \val: \inp{\val}, \data: \inp{\data}\}; \\
    \pcendif \\
    \sigma_\ecdsa \gets \ecdsasigscheme.\sig(\sk_{\ecdsa}, \keccak{256}(\rawTx)); \\
    \finalTx \gets \{ \rawTx, \sigv: \sigma_\ecdsa.\sigv, \sigr: \sigma_\ecdsa.\sigr, \sigs: \sigma_\ecdsa.\sigs \}; \\
    \pcreturn\ \finalTx;
}
    \caption{Transaction generation function \txgen}\label{preliminaries:fig:txgen}
\end{figure}

\begin{remark}\label{preliminaries:recovering-msg-sender}
    As one can see, there is no ``from'' attribute in a transaction. The sender's \ethereum~address can be recovered from the \ecdsa~signature. This method is defined in the \ethereum~yellow paper as a ``sender function'' $S$~\cite[Appendix F]{ethyellowpaper} which maps each transaction to its sender.
\end{remark}

\subsubsection{Types of transactions}\label{preliminaries:ethereum:eth-tx:tx-types}

While only two types of transactions are described in~\cite[Section 4.2]{ethyellowpaper}; namely those which result in message calls and those which result in the creation of new accounts with associated code, we will instead differentiate the types of transactions based on their purpose. The reader is encouraged to read~\cite{ethyellowpaper} for a formal discussion.

\medskip

Informally, a transaction can be used to achieve three things: transferring \wei~from an \eoa~to another \eoa, creating a new account with associated code (i.e.~``deploying a smart-contract''), and calling a function of a smart-contract. We will detail here the differences between these usages.
\begin{description}
    \item[Creating a contract] The $\tx.\tto$ address is set to $\emptyset$ in the transaction. The contract creation data ($\tx.\init$) includes the new contract's code. The contract address is computed as the rightmost $\addressLen$ bits of the \keccak{256} hash of the \rlp~encoding~\cite{ethrlp} of the transaction originator's address and account nonce~\cite[Section 6]{ethyellowpaper}.
    \item[Calling a contract function] The $\tx.\tto$ address is set to the address of the contract. The message call data byte array ($\tx.\data$) is set to the contract's function address (or \emph{``Function Selector''}~\cite{abi-function-selector}) which are the first 4 bytes of the \keccak{256} hash of the function signature, and the function input arguments ($\ethWordLen$ bits per input)~\cite[Section 8]{ethyellowpaper}.
    \item[Transferring \wei~from an \eoa~to another \eoa] This corresponds to a ``plain transaction'' spending \wei~from an address to send them to another. In that case the $\tx.\tto$ address corresponds to the recipient's address while the transaction data is left empty.
\end{description}

\begin{notebox}
    In order to keep notations simple, we assume, in the rest of the document, that smart-contract functions are uniquely determined by their name. As such, we denote by $\funcSelec{\cdot} \colon \BB^{*} \to \BB^{4 \cdot \byteLen}$ the function that takes a function name as input and returns its function selector.
\end{notebox}

\subsubsection{Transaction validity}\label{preliminaries:ethereum:eth-tx:tx-validity}

Importantly, not all finalized transactions constitute valid state transitions on the state machine~\cite[Section 6]{ethyellowpaper}.
We denote by \ethVerifyTx~the function that takes an \ethereum~transaction object $\tx$ as input and return $\true$ (resp.~$\false$) if $\tx$ is valid (resp.~invalid). To be deemed valid, a transaction $\MUST$ satisfy \emph{all} the following conditions:
\begin{enumerate}
    \item The transaction is correctly \rlp~encoded, with no additional trailing bytes;
    \item the transaction signature $\smalltuple{\sigv, \sigr, \sigs}$ is valid;
    \item the transaction nonce ($\tx.\nonce$) is valid, i.e.~it is equal to the account nonce of the transaction originator;
    \item the gas limit is no smaller than the gas used by the transaction;
    \item the transactor has enough funds on his account balance to cover at least the cost $\tx.\val + \tx.\gasp \cdot \tx.\gasl$.
\end{enumerate}

\subsubsection{Lifecyle of a transaction, and miners' incentives}\label{preliminaries:ethereum:eth-tx:tx-life}

After the creation of an \ethereum~transaction \tx~by a user from an \ethereum~client (machine running a piece of software that enables to be connected to the \ethereum~network), the transaction is broadcasted to the network and received by a set of peers/nodes.

The transaction is then stored in each node's transaction pool, which is a data structure containing all transactions that should be validated (pending transactions) by the node and mined. To maximize miners' returns, the transaction pools are ordered according to the gas price of the transactions. As such, transactions with the highest $\tx.\gasp$ are subject to be validated and included into a block first.
Once \tx~is selected from the transaction pool, it is validated (fed into \ethVerifyTx), executed, and included into a block (i.e.~``mined''). The block is then broadcasted to all the nodes of the network and is used as the predecessor for the next block to be mined on the network (i.e.~``it is added to the chain'').

\subsection{Ethereum events and Bloom filters}\label{sssec:ethereum-events}

The \evm~contains the set of ``LOGX'' instructions enabling smart-contract functions to ``emit events'' (i.e.~log data) when they are executed\footnote{see~\url{https://ethgastable.info/}}

As such, when a block is generated by a miner or verified by the rest of the network, the address of any logging contract, and all the indexed fields from the logs generated by executing those transactions are added to a Bloom filter~\cite{DBLP:journals/cacm/Bloom70}, which is included in the block header~\cite[Section 4.3]{ethyellowpaper}. Importantly, the actual logs \emph{are not included in the block data} in order to save space.
    As such, when an application wants to find (``consume'') all the log entries from a given contract, or with specific indexed fields (or both), the node can quickly scan over the header of each block, checking the Bloom filter to see if it may contain relevant logs. If it does, \emph{the node re-executes the transactions from that block, regenerating the logs, and returning the relevant ones to the application}~\cite{eth-bloom-filters}.

\begin{notebox}
    The ability for a smart-contract function to ``emit'' some pieces of data when executed, and for an application to ``consume'' such pieces of data, is used in \zeth~in order to construct a \emph{confidential receiver-anonymous channel}~\cite{DBLP:conf/pet/KohlweissMOTV13}.
\end{notebox}