%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                              %
%   PAW   - Reference Manual -- LaTeX Source                                   %
%                                                                              %
%   Chapter 5: Vectors                                                         %
%                                                                              %
%   EPS file      : none
%                                                                              %
%   Editor: Michel Goossens / IT-AS                                            %
%   Last Mod.: 29 July 1998 Olivier Couet                                      %
%                                                                              %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\chapter{Vectors}
\label{sec:H1PVECT}
\index{vector}
\index{array}
\index{SIGMA}
\index{COMIS}

Vectors are named arrays of numerical data, memory resident, which can be
created during a session, loaded from HBOOK objects, typed in by hand, read
from disk files, operated upon using the full functionality of SIGMA or COMIS.
Vectors can be used to produce graphics output, and, if necessary, stored away
on disk files for further usage. Vectors provide a very convenient mechanism to
transport numerical information between different PAW objects, and to
manipulate mathematically their content. At the end of an interactive session,
they are lost, unless previously saved onto disk files.

Vectors can have up to 3 dimensions (in fact they are ``arrays'',
called ``vectors'' for historical reasons).  They can be handled
by using \PAWcind{VECTOR}\texttt{/... } commands.

Simple arithmetic operations can be applied to vectors.
In addition, as SIGMA is part of PAW,
powerful array manipulation operations are available,
through the SIGMA, \texttt{\$SIGMA}
and \Cind{APPLICATION} \texttt{SIGMA} commands
(see section \ref{sec:H2SIGMA} on page~\pageref{sec:H2SIGMA}).

\section{Vector creation and filling}
\index{create!vector}
\index{vector!create}
\index{fill!vector}
\index{vector!fill}

A vector is {\bf created} either by the {\bf PAW command}
\texttt{VECTOR/CREATE}, by the {\bf SIGMA function} \PAWcind{ARRAY}.
or by the {\bf COMIS statement} \PAWcind{VECTOR}.

\subsection*{Example of vector creation}
\begin{alltt}
\Ucom{VECTOR/CREATE  X(100)}      will create a 100-components vector, values = 0.
\Ucom{SIGMA X=ARRAY(100,1#100)}   will create a 100-components vector and assign
                            to each element the values 1,2,...100
\Ucom{VECTOR X(100)}              in a COMIS routine creates a 100-components vector
                           and initialises each element to zero
\end{alltt}

Once the vector is created, it can be manipulated
using the following PAW commands:

\begin{DLtt}{12345678901234567890}
\item[\texttt{VECTOR/INPUT} vlist]
       Input from the terminal values into the vector
       elements specified by the list \texttt{vlist}.
\item[\texttt{VECTOR/READ} vlist]
       Values can be {\bf read in} from a file
       into the vector elements specified by the list vlist.
\item[\texttt{VECTOR/COPY} v1 v2]
       Values in \texttt{v1} are copied into \texttt{v2}.
\item[\texttt{VECTOR/WRITE} vlist]
       Values in the vector elements specified by the
       list vlist can be {\bf saved} on a file.
\item[\texttt{VECTOR/PRINT} vlist]
       Values of the vector elements specified in \texttt{vlist} will be
       {\bf printed} on the terminal.
\item[\texttt{VECTOR/LIST}]
       A {\bf list} of existing vectors and their
       {\bf characteristics} is printed on the terminal.
\item[\texttt{VECTOR/DELETE}]
       Allows global or selective deletion of vectors.
\end{DLtt}

\section{Vector addressing}
\index{vector!address}
\index{addressing of vectors}

Indexing of vectors is possible. The
indexing permitted in PAW can be considered as a superset
of that permitted by FORTRAN.

\subsection*{Example of vector indices}
\begin{alltt}
{\bf Vec}            for all elements
{\bf Vec(13)}        for element 13
{\bf Vec(12:)}       for elements 12 up to the last
{\bf Vec(:10)}       for elements 1 to 10
{\bf Vec(5:8)}       for elements 5 to 8
\end{alltt}

Sub-elements of the two-dimensional vector \texttt{Vec(3,100)}
(3 columns by 100 rows) may be addressed by:

\subsection*{Using two-dimensional vectors}
\begin{alltt}
{\bf Vec(2,5:8)}     for elements 5 to 8 in column 2
{\bf Vec(2:3,5:8)}   for elements 5 to 8 columns 2 to 3
{\bf Vec(2,5)}       for element 5 in column 2
{\bf Vec(:,3)}       for all elements in row 3
{\bf Vec(2)}         for all elements in the 2-nd column (SPECIAL CASE)
\end{alltt}

\section{Vector arithmetic operations}
\index{vector!arithmetic}
\index{operation on vectors}

A number of basic vector arithmetic operations is available:

\begin{DLtt}{1234567890123456789012}
\item[VBIAS     v1 bias v2]   \texttt{v2(I) = bias + v1(I)}
\item[VSCALE    v1 scale v2]  \texttt{v2(I) = scale * v1(I)}
\item[VADD      v1 v2 v3]     \texttt{v3(I) = v1(I) + v2(I)}
\item[VMULTI    v1 v2 v3]     \texttt{v3(I) = v1(I) * v2(I)}
\item[VSUBTR    v1 v2 v3]     \texttt{v3(I) = v1(I) - v2(I)}
\item[VDIVID    v1 v2 v3]     \texttt{v3(I) = v1(I) / v2(I), if v2(I)<>0}
\end{DLtt}

In all operations only the minimum vector length is considered,
i.e. an operation between a vector \texttt{A} of dimension 10 and a vector
\texttt{B} of dimension 5 will involve the first 5 elements for both vectors.
If the destination vector does not exist,
it is created with the same length as specified in the source vector.

\section{Vector arithmetic operations using SIGMA}
\index{SIGMA}

A more complete and convenient mechanism for the mathematical
manipulation of entire vectors is provided by SIGMA.
SIGMA-generated arrays are stored as
PAW vectors and therefore are accessible
to PAW commands, and PAW vectors are accessible to SIGMA.
The facilities available via SIGMA are described in the next chapter.

\section{Using vectors in a COMIS routine}
\index{COMIS}
\index{KUIP!vector}

The declaration \Ucom{VECTOR vector\_name}
may be used inside a COMIS routine to address a PAW vector.
If the vector does not exist, it is created with the specifications
provided by the declared dimension.

\section{Usage of vectors with other PAW objects}

Vectors can be used to transport
numerical information between different PAW objects, and
to manipulate mathematically their content.

\begin{DLtt}{1234567890123456789012345678901}
\item[\texttt{VECTOR/HFILL} VNAME ID]
     Each vector element of \texttt{VNAME}
     is used to fill the existing \mbox{histogram \texttt{ID}.}
\item[\texttt{HISTOGRAM/GET_VECTOR/CONTENT}]
     Provides an interface between vectors and histograms.
\item[\texttt{HISTOGRAM/PUT_VECTOR/CONTENT}]
     Provides an interface between histograms and vectors.
\end{DLtt}

\section{Graphical output of vectors}
\index{graphical!output}

\begin{DLtt}{123456789012345678901234}
\item[\texttt{VECTOR/DRAW} VNAME]
     Interprets the content of the vector \texttt{VNAME}
     as a histogram contents and draw a {\bf graph}.
\item[\texttt{VECTOR/PLOT} VNAME]
     Vector elements are considered as individual values
     to be entered into a histogram and a graph is produced.
     If \texttt{VNAME} is the name of a vector, then each vector element of
     \texttt{VNAME} is used to fill a histogram which is
     automatically booked with 100 channels and plotted.
     If \texttt{VNAME} has the form \texttt{VNAME1\%VNAME2}
     then a scatter-plot of vector \texttt{VNAME1}
     versus \texttt{VNAME2} is plotted.
\end{DLtt}

%See section~\ref{sec:vectordrawplot}
%in the tutorial section for an
%explanation of the difference between \texttt{VECTOR/DRAW}
%and \texttt{VECTOR/PLOT}.

A number of graphical primitives are available in PAW.
Those directly related to the graphical output of vectors are:

\begin{DLtt}{123456789012345678901234}
\Inref{GRAPH}
\item[GRAPH N X Y]
     Draw a curve through a set of points defined by arrays
     \texttt{X} and \texttt{Y}.
\Inref{HIST}
\item[HIST  N X Y]
     Draw an histogram defined by arrays \texttt{X} and \texttt{Y}.
\Inref{PIE}
\item[PIE   X0 Y0 RAD N VAL]
     Draw a pie chart, of \texttt{N} slices,
     with size of slices given in \texttt{VAL},
     of a radius \texttt{RAD}, centered at \texttt{X0}, \texttt{Y0}.
\end{DLtt}

\section{Fitting the contents of a vector}
\index{fit!vector}

A user defined (and parameter dependent) function
can be fitted to the points defined by the two vectors \texttt{X}
and \texttt{Y} and the vector of associated errors \texttt{EY}.
The general syntax of the command to fit vectors is:

\texttt{VECTOR/FIT} \texttt{x y ey func [ chopt np par step pmin pmax errpar ]}

For more information have a look at the online help of this command in PAW.


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

\chapter{Security proofs of Blake2}\label{appendix:blake}

This appendix proves the collision resistance, PRF-ness, binding and hiding properties of the \blake{2}{} hash function in the Weakly Ideal Cipher model (WICM, see~\cite{luykx2016security}). The proofs use definitions and results of Luykx et al.~\cite{luykx2016security}, regarding the indifferentiability of \blake{2}{} and a random oracle in the Weakly Ideal Cipher Model (WICM). In the following, we assume that the optimization of \blake{2}{} for 8- to 32-bit platforms is as secure as \blake{2}{} as described in~\cite{luykx2016security}.

\section{Security model of Blake2}\label{appendix:blake:secmod}

The security analysis treats \blake{2}{} as hash function built on top of a block-cipher-based compression function in the WICM (which derives from the Ideal Cipher Model). In this section, we present the WICM and prove that \blake{2}{} is a collision resistant PRF, and thus a commitment scheme.

\subsection{Weakly Ideal Cipher Model}\label{appendix:blake:secmod:WICM}

The research community believes that Blake’s underlying block cipher has no known weaknesses and could reasonably be modeled as an ideal cipher~\cite[Section 2.1]{luykx2016security}. However, \blake{2}{} admits weak keys with a specific structure~\cite[Section 2.1]{luykx2016security}. \blake{2}{} is therefore more appropriately analysed in the WICM, which is an extension of the Ideal Cipher Model that represents a block cipher as a set of independent random permutations~\cite{holenstein2011equivalence}. The WICM may also be viewed as a specialization for \blake{2}{} of the Weak Cipher Model~\cite{mennink2015impact}, which aims to be realistic by modeling particular characteristics, invariants or properties a block cipher may have.

A number of definitions in what follows are quoted directly from Luykx et al.~\cite{luykx2016security}.

\paragraph{The Weakly Ideal Cipher Model.}

Let \weakSet and \strongSet be the following partition of $\BB^{2 \cdot \ol}$ into weak and strong sets, where $w$ is the word length ($16 \cdot w = 2 \cdot \ol$):
\begin{align*}
    \weakSet &= \smallset{aaaabbbbccccdddd \in \BB^{2 \cdot \ol}\ |\ a, b, c, d \in \BB^w} \\
    \strongSet &= \BB^{2 \cdot \ol} \setminus \weakSet
\end{align*}

Let $\blockSet(2 \cdot \ol, 2 \cdot \ol)$ denote the set of all block ciphers $\Enc{}: \BB^{2 \cdot \ol}\times \BB^{2 \cdot \ol} \rightarrow \BB^{2 \cdot \ol}$. Define $\blockSet^{*}(2 \cdot \ol, 2 \cdot \ol)$ as the set of all block ciphers $\Enc \in \blockSet(2 \cdot \ol, 2 \cdot \ol)$ with the additional restriction that $\Enc(k_w,\cdot)$ is \weakSet- and \strongSet-subspace invariant for all keys $k_w \in \keyspace_{weak}$. That is, inputs in \weakSet map to \weakSet, and likewise for \strongSet. Here, $\keyspace_{weak}$ is the set of weak keys, defined as
\[
    \keyspace_{weak} = \smallset{ \key = kkkkkkkkkkkkkkkk \in \BB^{2 \cdot \ol}\ |\ k \in \BB^w }.
\]
A random $ \Enc \sample \blockSet^{*}(2 \cdot \ol, 2 \cdot \ol)$ can now be modeled as follows:
\begin{itemize}
    \item on input of $(\key, x) \in \keyspace_{weak} \times \weakSet$, $\Enc$ generates its response $y$ randomly from \weakSet up to repetition;
    \item on input of $(\key, x) \in \keyspace_{weak} \times \strongSet$, $\Enc$ generates its response $y$ randomly from \strongSet up to repetition.
\end{itemize}

For key values $\key \in \BB^{2 \cdot \ol} \setminus \keyspace_{weak}$, $\Enc$ behaves like an ideal cipher: it either outputs a new random value or if the key-message-image tuple has already been queried the tuple's image. The case of inverse queries is analogous.

\blake{2C}{} is defined over the following domains and codomain:
\[
    \blake{2C}{}: \blockSet^{*}(2 \cdot \ol, 2 \cdot \ol) \times \BB^{\ol} \times \BB^{2 \cdot \ol} \times \BB^{\ol/4} \times \BB^{\ol/4} \to \BB^{\ol}
\]
We write $\blake{2C}{}_\Enc(h, \msg, t, f)$ for the output of the \blake{2}{} compression function, defined over encryption scheme $\Enc$ on inputs $h$, $\msg$, $t$ and $f$. The compression function, in particular, computes the state $x = (h \concat \pad{0}{\ol/2} \concat t \concat f) \xor (\pad{0}{\ol} \concat \blakeIV{})$ for some $\blakeIV{}$. It then encrypts $x$ under $\msg$ (where $\msg$ is treated as a key for the encryption) and splits $\Enc(\msg, x)$ in two same size variables, the left part $l_\Enc$ and right part $r_\Enc$. It finally outputs $l_\Enc \xor r_\Enc \xor h$.\linebreak

\zeth{} uses the \blake{2}{} compression function with a fixed encryption scheme $\Enc^*$ based on \chacha{} stream cipher~\cite{bernstein2008chacha}. Thus, we write $\blake{2C}{h, \msg, t, f} = \blake{2C}{}_{\Enc^*}(h, \msg, t, f)$.
%
% \blake{2}{} is defined over the following domain and codomain:
% \[
%     \blake{2}{}: \BB^{\leq 2 \cdot \ol} \times \BB^{*} \to \BB^{\ol}
% \]

\paragraph{Indifferentiability.}

One way to measure the extent to which a certain cryptographic function behaves like a random function is via the indistinguishability framework  where a distinguisher is given oracle access to either the cryptographic function or the random function with the goal of determining which one it has access to.

\begin{definition}\label{appendix:blake:secmod:WICM:indiff}
    Let $\primC$ be a construction with oracle access to an ideal primitive $\primP$. Let $\primR$ be an ideal primitive with the same domain and codomain as $\primC$. Let $\simulator$ be a simulator with the same domain and codomain as $\primP$ with oracle access to $\primR$, and let $\distinguisher$ be a $\ppt$ distinguisher. The indifferentiability advantage of $\distinguisher$ is defined as:
    \[
        \indiff_{\primC^\primP, \simulator}(\distinguisher) = \abs*{\prob{\distinguisher^{\primC^\primP, \primP} = 1} - \prob{\distinguisher^{\primR, \simulator^\primR} = 1}}
    \]
\end{definition}

The distinguisher $\distinguisher$ can query both its left oracle (either $\primC$ or $\primR$) and its right oracle (either $\primP$ or \simulator). We refer to $\primC^\primP,\ \primP$ as the real world, and to $\primR,\ \simulator^\primR$ as the simulated world; the distinguisher $\distinguisher$ converses with either of these worlds and its goal is to tell both worlds apart.

\begin{theorem}[Indifferentiability of \blake{2}{}~\cite{luykx2016security}]
Let an encryption scheme $\Enc \sample \blockSet^*(2 \cdot \ol, 2 \cdot \ol)$ be a weakly ideal cipher, and consider the hash function $\blake{2}{}_\Enc$ that internally uses $\Enc$. There exists a simulator $\simulator$ such that for any distinguisher $\distinguisher$ with total complexity $\queryBound$, we have:
    \[
        \indiff_{\blake{2}{}_\Enc, \simulator}(\distinguisher) \leq \frac{\binom q 2}{2^{2\ol}} + \frac{2 \binom q 2}{2^{\ol}} + \frac{q}{2^{\ol/2}}
    \]
    where $\simulator$ makes at most $O(\queryBound^3)$ queries to a random function $\primR$.
\end{theorem}
\begin{proof}
    See~\cite[Corollary 1]{luykx2016security}.
\end{proof}

For asymptotic security, we assume the distinguisher to be \ppt{} and that the number of queries made is polynomial $q\leq \poly[\ol]$.

\paragraph{Additional remarks.}

Luykx et al.~\cite{luykx2016security} remark that, by resorting to the WICM, they do not make stronger assumptions than those used in previous results (ICM), and, despite the fact that they give distinguishers more power (by weakening the cipher), they are able to get similar results.

\section{Security proofs}\label{appendix:blake:proofs}

\subsection{Blake2 is a PRF}\label{appendix:blake:proofs:prf}

Luykx et al.~already prove the PRFness of \blake{2}{} \textit{keyed} hash function in the multi-key setting.

\begin{definition}[PRF in multi-key setting~\cite{mouha2015multi}]
	Let $\mu \geq 1$ and $k \sample \keyspace^\mu$. Let $\primC$ be a keyed construction with key space $\keyspace$ and with oracle access to an ideal primitive $\primP$. Let $\primR_1, \ldots, \primR_\mu$ be random functions with the same domains and ranges as $\primC_{\key_1}, \ldots, \primC_{\key_\mu}$. Let $\dist$ be a distinguisher. The PRF distinguishing advantage of $\dist$ is defined as,
\[
    \prf_{\primC^\primP}(\dist) = \abs*{\prob{\distinguisher^{\primC^\primP_{\key_1}, \ldots, \primC^\primP_{\key_\mu}, \primP} = 1} - \prob{\distinguisher^{\primR_1, \ldots, \primR_\mu, \primP} = 1}}
\]
\end{definition}

\blake{2}{} supports keyed hashing by simply prepending the key to the message:
\[
    \blake{2}{}_{\Enc,\key}(\msg) = \blake{2}{}_{\Enc}(\key \concat 0^{2\ol - \kl} \concat \msg)
\]
where $\kl \leq 2\ol$ denotes the key size. In other words, the key gets processed as other data and the $\haifa$ counter and flags are designated to the key in a similar fashion as if they were for normal data blocks.

\begin{theorem}[PRF-security of \blake{2}{} keyed mode~\cite{luykx2016security}]\label{appendix:th:kh-blake-prf}
Let $\mu \geq 1$ and let $\key \sample \left( \BB^\kl \right )^\mu$. Let an encryption scheme $\Enc \sample \blockSet^*(2 \cdot \ol, 2 \cdot \ol)$ be a weakly ideal cipher, and consider the keyed hash function $\blake{2}{}_{\Enc, \key}$ that internally uses $\blake{2C}{}_\Enc$ that internally uses $\Enc$. For any distinguisher $\distinguisher$ with total complexity $\queryBound$:
    \[
        \prf_{\blake{2}{}_{\Enc, \key}}(\distinguisher) \leq \frac{\binom q 2}{2^{2\ol}} + \frac{2 \binom q 2}{2^{\ol}} + \frac{q}{2^{\ol/2}} + \frac{\mu q}{2^\kl} + \frac{\binom \mu 2}{2^\kl}
    \]
\end{theorem}
\begin{proof}
    See~\cite[Corollary 3]{luykx2016security}.
\end{proof}

\begin{remark}\label{appendix:blake:proofs:kh-blake-remark}
We can note that in the case of keyed hashing, the key is padded only to be processed in a single block to differentiate the key from the message. The security proof of~\cref{appendix:th:kh-blake-prf} does not rely on this padding and as such also works with no padding.
\end{remark}

\begin{theorem}[PRF-security of \blake{2}{} with a single key~\cite{luykx2016security}]\label{appendix:th:blake-prf}
Let $\key \sample \BB^\kl$. Let an encryption scheme $\Enc \sample \blockSet^*(2 \cdot \ol, 2 \cdot \ol)$ be a weakly ideal cipher, and consider the keyed hash function $\blake{2}{}_{\Enc}(\key, \cdot) = \blake{2}{}_\Enc(\key \concat \cdot)$ that internally uses $\blake{2C}{}_\Enc$ that internally uses $\Enc$. For any distinguisher $\distinguisher$ with total complexity $\queryBound$:
    \[
        \prf_{\blake{2}{}_{\Enc}}(\distinguisher) \leq \frac{\binom q 2}{2^{2\ol}} + \frac{2 \binom q 2}{2^{\ol}} + \frac{q}{2^{\ol/2}} + \frac{q}{2^\kl}
    \]
\end{theorem}
\begin{proof}
    See~\cref{appendix:blake:proofs:kh-blake-remark} and~\cref{appendix:th:kh-blake-prf} with $\mu=1$.
\end{proof}

\begin{remark}
  Since we analyse the security of \blake{2}{} asymptotically, we assume that for a security parameter $\secpar$ holds $\ol = \bigO{\secpar}$, $\kl = \bigO{\secpar}$, and $q = \poly$.
\end{remark}

\subsection{Proof of Blake2 collision resistance}\label{appendix:blake:proofs:colres}

We want to prove here the collision resistance of \blake{2}{}. To do so, we are going to prove by contradiction that if \blake{2}{} is not collision resistant, it is not indifferentiable according to~\cref{appendix:blake:secmod:WICM:indiff}.

\begin{theorem}
    \blake{2}{} is collision resistant.
     % with a security parameter of $\secpar=\ol/2$.
\end{theorem}
\begin{proof}[Informal proof.]
    Let us assume that there exists a $\ppt$ adversary $\bdv$ which breaks the collision resistance of \blake{2}{}. We build an adversary $\adv$ that uses this adversary to differentiate between the real and simulated worlds. More particularly, $\adv$ gets left and right oracles (see~\cite[Figure 3]{luykx2016security}), which are either an oracle for a hash function and for a weakly ideal block cipher or a random oracle and an encryption simulator with oracle access to the random oracle.

    On each $\bdv$'s query $\msg_i$, $i \in \range{1}{\queryBound}$, $\adv$ passes them to his left oracle and returns the answer $h_i$ to $\bdv$.
    Eventually, if $\bdv$ finds a collision, that is a pair $(\msg_i, \msg_j)$ such that $\msg_i \neq \msg_j$ and $h_i = h_j$, $\adv$ guesses that his oracles were real; else $\adv$ returns a random guess. Otherwise $\adv$ guesses his oracles were simulated -- if the left oracle was a random oracle, the probability of finding a collision would be negligible for $\queryBound \leq \poly$\footnote{The probability would be $\frac{\queryBound^2}{2^{\ol}}$ which is negligible for a polynomial number of queries $\queryBound$. This is the sum of the probabilities of finding a collision when doing the $i^{th}$ query. Indeed, let us suppose the adversary has done $i-1$, $i>2$, queries without finding a collision, i.e.~he knows $i-1$ distinct tuples of input-output. When receiving the $i^{th}$ value, the adversary has thus $i-1$ chance to find a collision. The probability for the new output to be equal to any of the previous outputs is thus $(i-1) \cdot \frac{1}{2^{\ol}}$ (as we are in the random oracle model). Summing this probability over all queries, we find the probability of finding a collision after doing $\queryBound$ queries.}.

    On the other hand, $\bdv$ finds a collision with non-negligible probability if the oracles were real.
    Hence, $\adv$ wins the indifferentiability game with non-negligible advantage, which is a contradiction.
\end{proof}

\subsection{Blake2 as a commitment scheme}\label{appendix:blake:proofs:comm}

We prove here that $\blake{2}{}$ is a commitment scheme, i.e.~is binding and hiding. To do so we rely on the previous results that \blake{2}{} is collision resistant and a \prf.

\begin{theorem}
    Let $\Enc\sample \blockSet (2\ol, 2\ol) $ and for a message $x \in \BB^{*}$ and randomness $r \in \BB^{\rl}$ commitment to $x$ using $r$ be $\comm.\commit{x}{r} = \blake{2}{}_\Enc (r \concat x)$.
    Then $\comm$ is hiding and binding.

    % Then $\comm$ is hiding with security parameter $\rl/2$ and binding with security parameter $\rl/2$.

\end{theorem}
\begin{proof}[Informal proof.]
\emph{Hiding.}
    A commitment scheme $\comm$ is computationally hiding if, knowing two potential openings, a \ppt{} adversary cannot distinguish which was committed. Let us assume that there exists a $\ppt$ adversary $\bdv$ which breaks the hiding property of $\blake{2}{}$ with a non-negligible advantage $\eta$. We build an adversary $\adv$ that uses $\bdv$ to break the PRF property of $\blake{2}{}$ with advantage $\eta/2$.

    First, the \prf{} game is initiated, that is, the challenger chooses a random encryption scheme $\Enc$ and key $\key \in \BB^\rl$ and instantiates two oracles $\oracle{\blake{2}{}_k} = \blake{2}{}_{\Enc}(\key, \cdot)$ and $\oracle{R}$ a random function. The challenger picks an oracle randomly and gives $\adv$ access to it.
    $\bdv{}$ sends $\queryBound$ oracle queries $m_1, \ldots, m_q$ to $\adv{}$ (adaptively) who extends them with random $r_1, \ldots, r_q$ and sends $r_i \| \msg_i$ to his left oracle. Given the answer from the oracle, $\adv$  returns them to $\bdv$.
    Eventually, $\bdv{}$ then outputs two challenge messages $(\tilde{\msg}_0, \tilde{\msg}_1)$ and sends them to $\adv$ who randomly selects message $\tilde{\msg}_b$, extends it with $r$ and sends $r \| \tilde{\msg}_b$ to his left oracle.
    The oracle answers with $y_b$ which is also sent to \bdv{}.
    Finally, \bdv{} returns the decision bit $\tilde{b}$ to \adv. If $b = \tilde{b}$, \adv{} answers to the challenger that the oracle was instantiating the PRF. Otherwise, \adv{} answers with a random guess.
    The advantage of $\adv$ equals advantage of $\bdv$ if it interacts with a real hash function. The advantage of $\adv$ equals half the advantage of $\bdv$ when interacting with a random oracle and simulator.
    % $\adv$ wins when $\bdv$ does and wins with probability at least $1/2$ otherwise. Hence, \adv{} wins the PRF game with non-negligible advantage what gives a contradiction.

\emph{Binding.}
    A commitment scheme $\comm$ is said to be computationally binding if it is infeasible to find $x, x'$ and $r, r'$ such that $x \neq x'$ and $\commit{x}{r} = \commit{x'}{r'}$. This is implied by collision resistance of \blake{2}{}. Thus if $\bdv$ is an algorithm that breaks the biding property with advantage $\eta$, there is another algorithm $\adv$ that breaks \blake{2}{} collision resistance with the same advantage.
\end{proof}

Assuming that \blake{2s}{} is as secure as \blake{2}{}, a commitment scheme based on a \blake{2s}{}, i.e.~$\commit{x}{r} = \blake{2s}{}_{\Enc}(r \concat x)$ is hiding and binding.

\subsection{Proof of commitment scheme security}\label{appendix:blake:full-comm}

To prove the binding and hiding property of $\comm$ (see~\cref{instantiation:prf-comm-crh:comm}), we introduce the following commitment scheme $\comm^*$,
\begin{align*}
	\comm^*.\setup & : \smallset{\secparam\ \suchthat\ \secpar \in \NN} \to \BB^{*} \\
	\comm^*.\commit{}{} &: \blockSet^{*}(2 \cdot \blakeCompLen, 2 \cdot \blakeCompLen) \times \BB^{2 \cdot \blakeCompLen} \\
  & \times \left( \BB^\prfAddrOutLen \times \BB^\prfRhoOutLen \times \BB^\zvalueLen \right ) \times \BB^\noterLen \to \BB^\blakeCompLen
\end{align*}

The commitment scheme is defined as follows,
\begin{align*}
	& \comm^*.\setup(\secparam) = \pparams^* = \epsilon\\
	&\comm^*.\commit{\msg = (\apk, \rrho, \notev)}{\noter} = \cm{}\\
	&= \blake{2}{}_{\Enc^*} (\noter \concat \apk \concat \rrho \concat \notev)
\end{align*}

Given a commitment scheme $\comm^*$, the bijective function $\decode{\cdot}{\NN}$ and $p_\secpar{} \in \NN$, a prime which can be represented using $\secpar$ bits, we define the commitment scheme $\comm'$ as follows:
\begin{align*}
    & \comm'.\setup(\secparam{}) = (\comm^*.\setup(\secparam{}), p_\secpar{})\\
    & \comm'.\commit{\msg}{r} = \decode{\comm^*.\commit{\msg}{\noter}}{\NN} \pmod{p_{\secpar}}\ \text{for}\ \msg= (\apk \concat \rrho \concat \notev)
\end{align*}
Note that $\comm$ (see~\cref{instantiation:prf-comm-crh:comm}) is a particular instantiation of $\comm'$ where $\Enc^*$ is set as \chacha{} encryption scheme~\cite{bernstein2008chacha}, $k^*$ is a random key, and $p_\secpar{}$ is $\rCURVE$.

\begin{theorem}[Hiding]\label{instantiation:th:com-bin-field-hiding}
    If $\comm^*$ is hiding then $\comm'$ is hiding.
\end{theorem}
\begin{proof}
	We prove the theorem by contradiction i.e.~we assume that there exists an adversary $\bdv$ that breaks $\comm'$'s hiding property and construct an adversary $\adv$ that uses $\bdv$ to break $\comm^*$'s hiding property with non-negligible probability.

  Let $\cdv$ be a challenger that sets up the hiding game for $\comm^*$ and $\adv$.
	The adversary $\adv$, given public parameters $\pparams^*$ of $\comm^*$ and access to an oracle that runs the $\commit{}{}$ algorithm of $\comm^*$ scheme, simulates a hiding game for $\comm'$ for $\bdv$.
  The adversary $\adv$ starts by setting public parameters $\pparams'$ for $\comm'$ using public parameters $\pparams^*$ given by $\cdv$. Parameters $\pparams'$ are passed to $\bdv$ who outputs a pair of messages $\msg_0, \msg_1$.
  The adversary $\adv$ forwards them to the challenger who samples a bit $b$ at random and generates $\cm{}^*= \comm^*.\commit{\msg_b}{r}$ for some randomness $r$. The result is returned to \adv{} (see~\cref{preliminaries:definitions:commitment-hiding}).
	Then $\adv{}$ passes $\cm{}= \decode{\cm{}^*}{\NN} \pmod{p_\secpar{}}$ to $\bdv{}$ who returns his guess $b'$. The adversary $\adv$ returns the same $b'$ to the challenger.

	By construction, it is clear that $\adv$ wins the hiding game with the same probability that $\bdv$ wins the simulated hiding game. Since $\bdv$'s advantage is non-negligible, this means that $\adv$ wins the $\comm^*$ hiding game with non-negligible probability as well.
\end{proof}

\begin{theorem}[Binding]\label{instantiation:th:com-bin-field-binding}
    Let $\comm^*$ be a computationally binding commitment scheme and $\comm^*.\commit{}{}$ indifferentiable from a random oracle. Then $\comm'$ is also computationally binding if $l = \left \lceil 2^{\secpar} / p_\secpar \right\rceil$ is at most $\poly[\secpar]$.
\end{theorem}
\begin{proof}
	Assume that \adv{} asks the $\comm'$ commit and open oracles a total of $q_\secpar$ distinct queries. Let us denote the result of the $q_\secpar$ queries and output of the attacker (the candidate collision) as
  $\left ( ( \msg_1, \opening_1, y_1), \ldots , (\msg_{q_\secpar}, \opening_{q_\secpar}, y_{q_\secpar}), \text{out} \right )$.
  If \adv{} is successful it means that it outputs $(\msg, \opening)$, $(\msg', \opening')$ such that $(\msg, \opening) \neq (\msg', \opening')$ and $\comm'.\commit{\msg}{\opening} = \comm'.\commit{\msg'}{\opening'}$.

	By the definition of $\comm'$, we have that,
	\[
		\comm'.\commit{\msg}{\opening} = \decode{\comm^*.\commit{\msg}{\opening}}{\NN} \pmod{p_\secpar}
	\]
Hence, we have a collision in $\comm'$ if there exists $k \in [l]$, $l$ being the ratio of the codomains of $\comm^*.\commit{}{}$ and $\comm'.\commit{}{}$, such that,
	\[
		\abs*{\decode{\comm^*.\commit{\msg}{\opening}}{\NN} - \decode{\comm^*.\commit{\msg'}{\opening'}}{\NN}} = k \cdot p_{\secpar}.
	\]
	We show that this event is unlikely.

	% In fact, for each $i \in [q_\secpar]$, let $C_i$ be the event that the adversary wins at the $i^{th}$ query; i.e.~either the last commitment $y_i$, obtained by the adversary, is a $\comm^*$ collision with one of the previous or a $\comm'$ collision which is not a collision for $\comm^*$. That is, $\exists j\leq i, \exists k, 0\leq k < l,\ \suchthat\ y_i = y_j + k \cdot p_\secpar$. Hence, the adversary has $l$ ways to win.

  In fact, for each $i \in [q_{\secpar}]$, let $C_i$ be the event that the adversary wins at the $i$-th query. That is, the last commitment $y_i$ is a $\comm'$ collision with one of the previous $y_j$.  More precisely there exists $j \leq i$ and $k < l$ such that $y_i = y_j + k \cdot p_{\secpar}$.

	Since $\comm^*$ is a random oracle, $y_i$ is randomly selected from a set of at least $p_\secpar$ elements. As such, we have $\prob{C_i} \leq i \cdot l / p_\secpar$.

	Thus the probability of finding a collision after $q_\secpar$ queries is
  $\prob{C_1 \lor \ldots \lor C_{q_\secpar}} \leq \sum_{i = 1}^{q_\secpar} \prob{C_i} = l/p_\secpar \cdot \sum_{i=1}^{q_\secpar} i$.
  This probability is bounded by $l \cdot \frac{q_\secpar(q_\secpar+1)}{p_\secpar}$.
	However, we allow only polynomial number of queries. Thus for $q_\secpar = \poly$ this probability becomes,
		\[
			\frac{2^\secpar \cdot \poly}{p_\secpar^2},
		\]
	what is negligible for $2^\secpar / p_\secpar \leq \poly$.
\end{proof}

\begin{remark}\label{instantiation:remark:rbn-blackcomplen}
	Note that in \zeth's commitment scheme, we set $p_\secpar{} = \rCURVE$ and $2^\secpar = 2^\blakeCompLen$. Thus, for \BNCurve and \BLSCurve have $l = 6$ and $l = 14$, respectively. Therefore, the probability of an attacker breaking the binding property due to reduction modulo $\rCURVE$ increases approximately by these factors. This is still negligible.
\end{remark}

\begin{cor}
    Assume that \blake{2}{} is indifferentiable from a random oracle and a PRF, then $\comm^*$ is computationally binding and computationally hiding. Furthermore, the reduction is \emph{tight}. That is, the advantage of any \ppt{} adversary against the binding (resp.~hiding) property is the same as the advantage of an adversary against collision resistance and binding (resp.~hiding).
\end{cor}


\subsection{Word vs. Instance-Based Induction}
\label{sec:typevsinstance}

Table~\ref{tab:results} shows that the overall many-to-one accuracy of
our instance based induction system is comparable to
\cite{yatbaz-sert-yuret:2012:EMNLP-CoNLL}\footnote{The difference is
  not statistically significant at $p=0.05$.} and significantly higher
than the other published results on the Penn Treebank.  However
Figure~\ref{fig:perplexity} in the introduction suggests that this
summary hides the large difference in the answers given by the
different systems.  In this section we compare the performance of our
instance-based model to the word-based model of
\cite{yatbaz-sert-yuret:2012:EMNLP-CoNLL} on word types at different
levels of ambiguity using the English Penn Treebank results.

We propose the gold-tag perplexity of a word as a measure of its
degree of ambiguity defined as:
\begin{equation*} \label{eq:tag-perp}
GP(w) = 2^{H(p_w)} = 2^{-\sum_{t} p_w(t)log_2 p_w(t)}
\end{equation*}
\noindent where $w$ is a word, $t$ is a tag, $p_w$ is the gold POS tag
distribution of the word $w$ and $H(p_w)$ is the entropy of the $p_w$
distribution.  A $GP$ of 1 for a word $w$ indicates that $w$ is always
associated with the same POS tag.  A word with $N$ equally probable
tags would have a $GP$ of $N$.

Figure~\ref{fig:perplexity} plots the gold-tag perplexity versus the
smoothed \mto\ accuracy for the word-based and the instance-based POS
induction systems on the Penn Treebank.  To compose the plot, we found
the best mapping from the induced clusters to the gold-standard tags,
then we computed the \mto\ accuracy for each word using this mapping
and plotted the \mto\ as a function of the word's $GP$.  We used the
Nadaraya-Watson kernel regression estimate
\cite{nadaraya1964estimating,watson1964smooth} with normal kernel of
bandwidth 1.0 to obtain smooth regression lines.  The figure shows
that the performance of the instance-based induction model does not
degrade as much as the word-based model as the ambiguity of the words
increase.  However, only 14.94\% of the instances in the PTB consists
of words with GP greater than 1.5 and 45.71\% consists of words with
GP exactly 1.  Thus, the overall accuracy numbers do not adequately
reflect the improvement on highly ambiguous words.

%% In the next section we apply the instance based model on 19 corpora in 15
%% different languages.

%% Due to the one-tag-per-word nature of POS induction, the
%% type based model significantly outperforms the instance based one on the
%% unambiguous words.  Instance based model performs significantly better than the
%% type based model on the ambiguous words and assigns 1.34 tags per word.
%% \subsection{Clustering Concatenation of Word and Context Embeddings (${\bf W}\oplus{\bf S}$)}
%% \label{sec:clustering-c}
%% Two models presented in earlier sections perform POS induction either
%% by assuming (Section~\ref{sec:clustering-w}) or discarding
%% (Section~\ref{sec:clustering-c}) the one-tag-per-word assumption.  In
%% this section we define a sparse-instance based model which clusters the
%% concatenation of ${\bf W}$ and ${\bf S}$ embeddings.  This model not
%% only tends to put instances of a word into the same cluster but
%% also performs instance based clustering by incorporating the word
%% and context information together.
%%
%% Similar to the previous models, we generate ${\bf W}$ -- ${\bf S}$
%% pairs as the input to S-CODE.  For each observed ${\bf W}$ -- ${\bf
%%   S}$ pair in the S-CODE input, corresponding 25-dimensional $\phi_w$
%% and $\psi_c$ embeddings are concatenated to create a 50-dimensional
%% representation.  We used the same experimental setting of the previous
%% section and predict the instance clusters according to the majority
%% cluster-id of the corresponding pairs.  The many-to-one accuracy of
%% this model is \wsxymto\ and the V-measure is \wsxyvm\ .
%%
%% Table~\ref{tab:bins} presents the performance of the ${\bf
%%   W}\oplus{\bf S}$ based model over the subsets and it achieves
%% statistically better \mto\ than both of the ${\bf W}$ and ${\bf S}$
%% based models on ambiguous words.  Due to the bias towards to the
%% sparse clustering, sparse-instance based model statistically improves the
%% \mto\ accuracy on unambiguous words compared to the ${\bf S}$ based
%% model but it still can not achieve the performance of the ${\bf W}$
%% based model.  The ${\bf W}\oplus{\bf S}$ based model constructs instance
%% based clusters that tend to assign instances of a word into the
%% same cluster which leads to a smaller average $GP$ than the ${\bf S}$
%% based model as shown in Table~\ref{tab:bins}.
%%
%% We don't really need this part
%% \subsubsection{Paradigmatic vs Syntagmatic Representations of Word Context}
%% \label{sec:bigram-instance}
%% In order to compare the instance clustering performance of the
%% paradigmatic and the syntagmatic context representations we use the
%% same 4 models defined in Section~\ref{sec:bigram-type}.  Following the
%% previous section we concatenate the 25-dimensional $\phi_x$ and
%% $\psi_y$ ($\psi_{y_{1}}$ and $\psi_{y_{2}}$ in the fourth model)
%% embeddings of the corresponding observed pairs (tuples in the fourth
%% model) and represent the first three models outputs with a
%% 50-dimensional vectors (75-dimensional vectors in the fourth model).
%% The resulting vectors are clustered using k-means algorithm with 128
%% restarts.
%% \begin{table}[ht]
%% \centering
%% \small
%% \caption{Accuracies of the instance based S-CODE models on the gold-tag
%%   perplexity separated subsets.}
%% \begin{tabular}{|l|l|l|l|}
%% \hline
%% Model & \specialcell{$GP < 1.75$\\$89\%$} & \specialcell{$GP \ge 1.75$\\$11\%$} & \specialcell{$GP \ge 1.0$\\$100\%$}\\
%% \hline
%% $X$ (word) - $Y$ (left bigram) & .5950 (.0051) & .4783 (.0005) & .5821 (.0041)\\
%% $X$ (word) - $Y$ (right bigram) & .6239 (.0049) & .3075 (.0153) & .5891 (.0046)\\
%% $X$ (word) - $Y$ (left and right bigram concatenation) & .7523 (.0065) & .4492 (.0240) & .7190 (.0049)\\
%% $X$ (word) - $Y_1$, $Y_2$ (left and right bigrams) & .6697 (.0065) & .4579 (.0052) & .6464 (.0051)\\
%% $X$ (word) - $Y$ (random substitutes) & .7322 (.0079) & .4671 (.0174) & .7030 (.0073)\\
%% \hline
%% \end{tabular}
%% \label{tab:instances}
%% \end{table}


\documentclass[twocolumn]{article}
\usepackage[margin=1in]{geometry}
\usepackage{outlines}
\usepackage{amsmath}
\usepackage{gensymb}
\title{Ch. 20-21 Notes}
\author{John Yang}
\setcounter{section}{+19}

\begin{document}
\maketitle
\section{Magnetic Forces and the Magnetic Field}
\subsection{The Magnetic Field}
\begin{outline}
	\1 The end of a compass needle that points generally in a northerly direction at most places on earth is defined to be the North magnetic pole of the compass needle
	\1 The opposite end is defined to be its south pole.
	\1 Magnets always occur in dipoles. If you break a permanent magnet in half you get two magnets.
	\1 Like poles repel and unlike poles attract
	\1 Force on a charged particle moving through a uniform field: \[\vec{F}_{\text{magnet on q}}=q\vec{v}\times\vec{B}\]
	\1 Magnetic field $\vec{B}$ is in Teslas (T)
	\1 Use the pointing rhr for positive charges, where the index finger is the velocity, the thumb is the force, and the other fingers are the field. The left hand can be used for negative charges but do not get confused!
\end{outline}
\subsection{Applications}
\begin{outline}
	\1 Velocity selectors; charged particles are shot through perpendicular electric and magnetic fields; only those with a certain velocity make it through without being deflected due to imbalanced forces, given by \(v_0=\dfrac{E}{B}\)
	\1 Mass spectrometers: A charged particle is shot into a region of a uniform magnetic field at a known velocity. The semicircular radius it makes before hitting a plate depends on its mass and is given by \(R=\dfrac{mv}{|q|B}\)
		\2 Can be used to separate a compound into its constituent ions to find its composition.
	\1 Hall effect: charges moving through a magnetic field experience a force, but moving magnetic fields can also induce a current. Using semiconductors, the Hall effect can be used to measure the proximity of a moving magnet by measuring the way charges move in a semiconductor in response to the change in magnetic field.

\end{outline}
\subsection{Magnetic Forces on Currents}
\begin{outline}
	\1 Magnetic force on a current-carrying wire: \[\vec{F}_{\text{magnet}}=I\int_{\text{wire}}d\vec{\ell}\times\vec{B}\]

\end{outline}
\subsection{Work Done by Magnetic Forces}
\begin{outline}
	\1 Work done by magnetic forces is always 0 because it is perpendicular to the motion of the charge.
\end{outline}
\subsection{Torque on a Current Loop in a Magnetic Field}
\begin{outline}
	\1 Magnetic dipole moment: \[\vec{\mu}\equiv I\vec{A}\] where $\vec{A}$ is the area vector.
	\1 Torque on a current loop inside a uniform magnetic field: \[\vec{\tau}=\vec{\mu}\times\vec{B}=I\vec{A}\times\vec{B}\]
	\1 The current loop inside the magnetic field executes simple harmonic motion.
\end{outline}
\subsection{The Biot-Savart Law}
\begin{outline}
	\1 To find the magnetic field caused by the entire wire, \[\vec{B}=\dfrac{\mu_0}{4\pi}I\int_{\text{wire}}\dfrac{d\vec{\ell}\times\vec{r}}{r^2}\]
	\1 Some commonly used magnetic fields:
		\2 At the center of a circular loop of radius $R$ \[\vec{B}_{\text{center}}=\dfrac{\mu_0}{4\pi}\dfrac{2\pi I}{R}\hat{k}\]
		\2 On the axis of a circular current loop \[\vec{B}_{axis}=\dfrac{\mu_0}{4\pi}\dfrac{I(2\pi R)^2}{(R^2+z^2)^{3/2}}\hat{k}\]
		\2 For a circular coil of $n$ loops, all of the same radius, multiply the preceding results by $n$
		\2 A distance $d$ from an infinite wire \[B=\dfrac{\mu_0}{4\pi}\dfrac{2I}{d}\] use grabbing rhr for direction
		\2 Inside a long solenoid having $n$ turns per meter of its length, each carrying current $I$, far from its ends \[B=\mu_0nI\]
\end{outline}
\subsection{Forces of Parallel Currents on Each Other and the definition of the Ampere}
\begin{outline}
	\1 Forces on parallel wires - attractive if currents in the same direction, repulsive if currents are antiparallel
	\1 Two infinitely long parallel straight current carrying wires exert forces on a length $\ell$ of either wire of magnitude \[F=\dfrac{\mu_0}{4\pi}\dfrac{2I_1I_2}{d}\ell\]

\end{outline}
\subsection{Gauss' Law for the Magnetic Field}
\begin{outline}
	\1 The flux of the magnetic field through any closed surface must always be zero: \[\int_{\text{clsd surf}}\vec{B}\cdot d\vec{S}=0\text{ T}\cdot\text{m}^2\]

\end{outline}
\subsection{Magnetic Poles and current loops}
\begin{outline}
	\1 Magnetic field forms closed loops in accordance with Gauss's law for magnetic field
	\1 Field lines come out of the north pole and enter into the south pole
\end{outline}
\subsection{Ampere's Law}
\begin{outline}
	\1 Ampere's law is: \[\int_{\text{clsd path}}\vec{B}\cdot d\ell=\mu_0I\]
\end{outline}
\subsection{The Displacement Current and the Ampere-Maxwell Law}
\begin{outline}
	\1 Displacement current - current due to changing electric flux, where \[I_D\equiv\varepsilon_0\dfrac{d\Phi_{\text{elec}}}{dt}\]
	\1 Ampere-Maxwell law - right side of Ampere's law should include both displacement and conduction currents: \[\int_{\text{clsd path}}\vec{B}\cdot d\vec{r}=\mu_0(I+I_D)_{\text{threading the path}}\]
	\1 Makwell realized that magnetic fields are produced by:
		\2 Electric charges in motion (conduction current)
		\2 Time-varying electric fields (displacement current)
	\1 The magnetic field induced by the displacement current is perpendicular to the (changing) electric field that causes it

\end{outline}
\subsection{Magnetic Materials}
\begin{outline}
	\1 certain materials are naturally magnetic. It depends on the relative permeability of the substance: \[\kappa_m=\dfrac{\mu}{\mu_0}\]
		\2 Diamagnetic - $\kappa_m$ slightly less than 1
		\2 Paramagnetic - $\kappa_m$ slightly greater than 1
		\2 Ferromagnetic - $\kappa_m$ much greater than 1
\end{outline}
\subsection{The Magnetic Field of the Earth}
\begin{outline}
	\1 Earth has a permanent magnetic field.
	\1 Magnetic north pole is actually the geographic south pole
	\1 Magnetic declination - difference in angle between magnetic north and true north
\end{outline}
\section{Faraday's Law of Electromagnetic Induction}
\subsection{Faraday's Law of Electromagnetic Induction}
\begin{outline}
	\1 A changing magnetic flux through a loop induces an electric field, called an induced electric field
	\1 Faraday's law: \[\int_{\text{clsd path}}\vec{E}\cdot d\vec{\ell}=-\dfrac{d\Phi}{dt}\] where $\Phi$ is the magnetic flux through the enclosed area
	\1 Induced emf: \[\text{induced emf}\equiv\int_{\text{clsd path}}\vec{E}\cdot d\vec{\ell}\]
	\1 Faraday's law is commonly written as \[\text{induced emf}=-\dfrac{d\Phi}{dt}\]
	\1 The magnetic flux is: \[\Phi=\vec{B}\cdot\vec{A}\]
	\1 Changing magnetic fields give rise to induced electric fields via Faraday's law
	\1 Changing electric fields give rise to magnetic fields via the displacement current and the Ampere-Maxwell law.
	\1 the electric and magnetic fields are mutually perpendicular to each other
\end{outline}
\subsection{Lenz's Law}
\begin{outline}
	\1 The induced current always will be directed so as to oppose the change in the magnetic flux that is taking place.
\end{outline}
\subsection{An ac generator}
\begin{outline}
	\1 A coil of wire of $N$ loops (of identical area $A$) rotates in a uniform magnetic field at an angular frequency $\omega$:\[\text{induced emf}=NBA\omega\sin(\omega t)\]
		\2 The induced emf is sinusoidal
	\1 When associated with a generator, we call the induced emf the source voltage
\end{outline}
\subsection{Summary of the Maxwell Equations of Electromagnetism}
\begin{outline}
	\1 Gauss' law for electric field: \[\int_{\text{clsd srfc } S}\vec{E}\cdot d\vec{S}=\dfrac{Q_{\text{enc}}}{\varepsilon_0}\]
	\1 Gauss' law for magnetic field: \[\int_{\text{clsd srfc } S}\vec{B}\cdot d\vec{S}=0\text{ T}\cdot\text{m}^2\]
	\1 Ampere-maxwell law: \[\int_{\text{clsd path}}\vec{B}\cdot d\vec{\ell}=\mu_0(I+I_D)=\mu_0I+\mu_0\varepsilon_0\dfrac{d\Phi_{\text{elec}}}{dt}\]
	\1 Faraday's law: \[\int_{\text{clsd path}}\vec{E}\cdot d\vec{\ell}=-\dfrac{d\Phi}{dt}\]
	\1 Light is an electromagnetic wave with its speed given by: \[c=\dfrac{1}{\sqrt{\mu_0\varepsilon_0}}\]
\end{outline}
\subsection{Electromagnetic Waves}
\begin{outline}
	\1 electric field component: \[\dfrac{\partial^2E_y}{\partial x^2}-\mu_0\varepsilon_0\dfrac{\partial^2E_y}{\partial t^2}=0\text{ N}/(\text{C}\cdot\text{m}^2)\]
	\1 Magnetic field component: \[\dfrac{\partial^2B_z}{\partial x^2}-\mu_0\varepsilon_0\dfrac{\partial^2B_z}{\partial t^2}=0\text{ T}/\text{m}^2)\]
	\1 The electric field, magnetic field, and direction of propagation are all mutually orthogonal, therefore light is a transverse wave
	\1 Acceleration of charges is light
\end{outline}
\subsection{Self-Inductance}
\begin{outline}
	\1 Self inductance is: \[L\equiv\dfrac{\Phi}{I}\] which is the total magnetic flux over the current. Measured in Henrys $H$

\end{outline}
\subsection{Series and Parallel Combinations of Inductors}
\begin{outline}
	\1 Inductors add in series: \[L_{\text{eq}}=L_1+L_2+L_3+\cdots\]
	\1 Inverses of inductors add in parallel: \[\dfrac{1}{L_{\text{eq}}}=\dfrac{1}{L_1}+\dfrac{1}{L_2}+\dfrac{1}{L_3}+\cdots\]
\end{outline}
\subsection{A Series LR Circuit}
\begin{outline}
	\1 For a series LR Circuit, \[I(t)=\dfrac{V_0}{R}\left[1-e^{-(R/L)t}\right]\]
		\2 When I is constant, there is no voltage across the inductor. An Inductor only has an effect while the current is changing with time. For the steady-state situation, there is no potential difference across an inductor since the current no longer is changing with time. \[V=L\dfrac{dI}{dt}\]
	\1 Time constant of a LR circuit is \[\tau\equiv\dfrac{L}{R}\]
\end{outline}
\subsection{Energy stored in a magnetic field}
\begin{outline}
	\1 Potential energy stored by the inductor is: \[U=\dfrac{1}{2}LI^2\]
		\2 That is, the inductor stores energy even if the current is not changing.
	\1 Power absorbed by the inductor: \[P=\dfrac{dU}{dt}=IL\dfrac{dI}{dt}\]
	\1 Magnetic energy density is \[\dfrac{1}{2}\dfrac{B^2}{\mu_0}\]
\end{outline}
\subsection{A Parallel LC Circuit}
\begin{outline}
	\1 For a parallel LC circuit, \[\dfrac{d^2Q}{dt^2}+\dfrac{1}{LC}Q=0\text{ A}/\text{s}\]
		\2 Which is the equation for SHM
	\1 the charge oscillates between the inductor and the capacitor: \[Q(t)=Q_0\cos(\omega t+\phi)\]
	\1 The angular frequency of the charge oscillations is: \[\omega=\dfrac{1}{\sqrt{LC}}\]
\end{outline}
\subsection{Mutual Inductance}
\begin{outline}
	\1 an inductor near another inductor can induce a current there.
	\1 mutual inductance \[M_{21}\equiv\dfrac{\Phi_{21}}{I_1}\] \[V_2\equiv M_{21}\dfrac{dI_1}{dt}\] for a closed circuit near an open one \[V_1\equiv M_{21}\dfrac{dI_2}{dt}\] for a reciprocal arrangement \[M_{21}=M_{12}\]
	\1 If both circuits are closed, \[V_1=L_1\dfrac{dI_1}{dt}+M\dfrac{dI_2}{dt}\] \[V_2=L_2\dfrac{dI_2}{dt}+M\dfrac{dI_1}{dt}\]
\end{outline}
\subsection{An Ideal Transformer}
\begin{outline}
	\1 Transformers can change voltage of AC signals using mutual inductance.
\0 \[V_1=N_1\dfrac{d\Phi}{dt}\] \[V_2=N_2\dfrac{d\Phi}{dt}\] but since $\dfrac{d\Phi}{dt}$ is the same for all wires in the system, we can write this as \[\dfrac{V_1}{V_2}=\dfrac{N_1}{N_2}\]
	\1 Input coil is the primary coil, the output coil is the secondary
	\1 Step up transformers - \(V_2>V_1\) and \(N_2>N_1\)
	\1 Step down transformers - \(V_2<V_1\) and \(N_2<N_1\)
	\1 In a step up transformer, the output potential is greater than the input but the current is less
	\1 In a step down transformer, the output voltage is less than the input, and the current is greater
	\1 Transformers don't work with dc current.
\end{outline}
\end{document}


%!TEX root = ../thesis.tex
\chapter{Quad-tree mesh in 2D analysis}
\label{qdt_sec:main}
\section{Introduction}
\paragraph{}
The main objective of this chapter is to implement an adaptor that can parse the geometric information in CAD directly and to develop an automatic mesh generation algorithm based on it.
The IGES file introduced in Sec.~\ref{lr_sec:IGES} is used in the proposed method as the bridge between the CAD and the numerical analysis.
A quad-tree mesh generation algorithm described in \ref{qt_sc:quadtree} will be adopted to generate a high quality mesh.
Either the NURBS basis function or the traditional shape function can be used as the shape function of the SBFEM solver.
The geometric boundary will be translated into polylines before the meshing and the intersections are calculated based on them.
Intersecting points on these polylines are projected back to the NURBS surface after the meshing is generated to retain the exact geometry.
% We further extend the method to problems with singularities within the framework of linear elastic fracture mechanics.
The proposed method enhances the conventional SBFEM and the salient features of the method are:
    \begin{itemize}
        \item Direct using design file as geometric input
        \item No human effort involvement in mesh generation
        \item Retained exact geometry
        \item High quality mesh generated from the quad-tree algorithm
    \end{itemize}
\paragraph{}
This chapter is organized as follows.
The CAD output (iges file) will be introduced first.
After that, an overview of the algorithm that can generate quadtree mesh will be provided.
Furthermore, a point projection method for NURBS curve utilizing its strong convex hull property is presented.
The accuracy and the convergence properties of the proposed techniques are demonstrated with benchmark problems in the context of linear elasticity, followed by concluding remarks in the last section.

\section{CAD output in 2D}
\label{qt_sc:iges}
\input{quadtree/iges.tex}

\section{Quad-tree structure}
\label{qt_sc:quadtree}
\input{quadtree/quadtree.tex}

\section{Points projection}
\label{qt_sc:projection}
\input{quadtree/projection.tex}

\section{Numerical Examples}
\input{quadtree/ex_cantilever.tex}
\input{quadtree/ex_circular_hole_qdt.tex}
\input{quadtree/ex_bracket.tex}
% \input{quadtree/ex_dam.tex}
\input{quadtree/ex_building.tex}
\input{quadtree/ex_other_mesh.tex}

\section{Conclusions}
\paragraph{}
In this chapter, the IGES file is employed directly from the CAD output to represent the geometry during the preprocessing.
The proposed methods provides a systematic and automatic mesh generation algorithm where high quality mesh is produced efficiently.
The CAD design file can be used directly and the exact geometry can also be retained, which largely reduce the human efforts involved in numerical analysis.
Moreover, it helps to reduce the analytical error as the difference in the geometric representation is minimized.
Computational efficiency is improved via utilizing the pattern of the quadtree to prevent repeated calculation.
Points projection algorithm is accelerated using the strong convex hull property of the NURBS curve.
The accuracy, effectiveness and the convergence properties of the proposed method are demonstrated with benchmark problems in linear elasticity mechanics.
From the numerical studies, it can be observed that the quadtree mesh yield better accuracy when compared to uniform mesh with same degree of freedoms.


\documentclass[../templatetop.tex]{subfiles}

\swd{contents/02_literature_review}

\begin{document}

\section{Position estimation using parameters}

After estimating a  set of parameters form the received signals by one of techniques described in the previous section, the next step is to estimate the position from the obtained parameters.
Position estimation techniques can be divide into two category depending on the presence of a database that contain the signal measurements at known positions. A techniques that makes use of such a database which is usually obtain by training phase (off-line phase) before the real time positioning start, is called mapping (fingerprinting) technique. Other techniques that do not utilize such a database commonly employ \textit{geometric} and \textit{statistical} techniques to estimate the position using only parameters estimates form the first step.

\noindent In the absence of a database consisting of previous taken measurements at known positions, the position of the target node should be estimated directly from the available measurements obtained in the first step. Such position techniques can be considered in two groups, geometric and statistic techniques.

\subsection{Mapping techniques}
Mapping techniques use the available database in the system as training data and estimate the position of a target node by pattern-matching algorithms, such as \textit{K-nearest-neighbor (k-NN)}, \textit{support vector regression (SVR)} and \textit{neural networks}.

A mapping technique can be consider as a regression scheme that maps the input vector to an output vector by using a training set. Let the training set be represented by:
\begin{equation}
    \tau = \{(m_1, p_1), (m_1, p_1),..., (m_{N_t}, p_{N_t})\}
\end{equation}
where $m_i$ represents the measurement vector for $i$th position $p_i$ ($p_i=\begin{bmatrix} x_i & y_i \end{bmatrix}^T$ for two-dimensional positioning) and $N_t$ is the total number of training set (the size of the database). For

One of the simplest regression techniques is to estimate the position of the target node as the position vector in the training set $\tau$ corresponding to the measurement vector that has the shortest distance to the measurement vector $m$. In other words, the position is estimated as $p_j$, with:
\begin{equation}
    j = \argmin_{i \in \{1,..,N_t\}} \lVert m - m_i \rVert
\end{equation}
where $\lVert m - m_i \rVert$ represents the Euclidean distance between $m$ and $m_i$.

\subsection{Geometric approach}

A geometric positioning technique solve for the position of the target node as intersection of position lines obtained from set of measurements at a number if reference nodes. For example, the RSS and TOA give us an uncertainty in the shape of a circle while the A0A give us an uncertainty in the shape of a line. In geometric approach, the position of the target node is determined by the intersection of uncertainty regions computed on several nodes.

In case of RSS or TOA, we need to know the distance of target node and three source nodes with known position, $d_i$, as shown in figure \ref{fig:rss_toa_position_model}.

\begin{figure}[htbp]
    \centering
    \includegraphics[width=0.5\textwidth]{rss_toa_position_model}
    \caption{The reference (black) nodes measure their distances (via RSS or TOA estimation) from the target node (gray node), which results in three circles passing through the target node. The intersection of the three circles can be calculated to obtain the position of the target node, which is called trilateration}
    \label{fig:rss_toa_position_model}
\end{figure}

Let $d_1$, $d_2$, $d_3$ represent the range measurement obtained from three TOA and RSS measurements. Then, the following system of equations is solved in order to estimate the position of the target node via trilateration:
\begin{equation}
    d_i = \sqrt{(x_i -x)^2 + (y_i - y)^2}  \mbox{,i = 1,2,3}
    \label{eq:rss_toa_system_of_equations}
\end{equation}
where $(x_i, y_i)$ is the known position of the $i$th reference node, and $(x,y)$ is the position of the target node.
The position $(x,y)$ can be solved from \ref{eq:rss_toa_system_of_equations} as:
\begin{equation}
    x = \frac{(y_2-y_1)\gamma_1 + (y_2-y_3)\gamma_2}{2[(x_2-x_3)(y_2-y_1) + (x_1-x_2)(y_2-y_3)]}
\end{equation}
\begin{equation}
    y = \frac{(x_2-x_1)\gamma_1 + (x_2-x_3)\gamma_2}{2[(x_2-x_1)(y_2-y_3) + (x_2-x_3)(y_1-y_2)]}
\end{equation}
where
\begin{equation}
    \gamma_1 = x_2^2 - x_3^2 + y_2^2 - y_3^2 + d_3^2 - d_2^2;
\end{equation}
\begin{equation}
    \gamma_2 = x_1^2 - x_2^2 + y_1^2 - y_2^2 + d_2^2 - d_1^2;
\end{equation}

Using the AOA approach, we need only two source nodes (antenna arrays) to estimate the position of the target node. As depicted in figure \ref{fig:aoa_position_model}, each AOA gives us an uncertainty in the shape of a line; so, we can estimate the target node's position as the intersection of these two lines.

\begin{figure}[htbp]
    \centering
    \includegraphics[width=0.5\textwidth]{aoa_position_model}
    \caption{The angles measured by the reference (black) nodes determine two lines, the intersection of
    which yields the target position. This technique is called triangulation}
    \label{fig:aoa_position_model}
\end{figure}

Each line give us an equation like:
\begin{equation}
    \tan{\psi} = \frac{y-y_1}{x-x_1}, i = 1,2
\end{equation}
Solving the equation jointly, we have:
\begin{equation}
    x = \frac{x_2\tan{\psi_2} - x_1\tan{\psi_1} + y_1 - y_2}{\tan{\psi_2} - \tan{\psi_1}}
\end{equation}
\begin{equation}
    y = \frac{(x_2-x_1)\tan{\psi_2}\tan{\psi_1} + y_1\tan{\psi_2} - y_2\tan{\psi_1}}{\tan{\psi_2}-\tan{\psi_1}}
\end{equation}

In case of the TDOA, we need three source nodes with known positions to obtain two TDOAs. As explained in previous section, TDOA is time difference of arrival of transmitted signals from the target node, between two source nodes. On TDOA gives us an uncertainty region in the shape of a hyperbola.

\begin{figure}[htbp]
    \centering
    \includegraphics[width=0.5\textwidth]{tdoa_position_model}
    \caption{Each TDOA determines a hyperbola. The position of the target node is estimated by intersection of these two hyperbola}
    \label{fig:tdoa_position_model}
\end{figure}

The hyperbola region is described by the following equation:
\begin{equation}
    d_{i1} = d_i - d_1 = \sqrt{(x-x_i)^2 - (y-y_i)^2} - \sqrt{(x-x_1)^2+(y-y_1)^2}, i =2,3
    \label{eq:tdoa_position_model}
\end{equation}
where
\begin{equation}
    d_1 = \sqrt{(x-x_1)^2 - (y-y_1)^2}
\end{equation}
The position of the target node is estimated by solving the two equations of \ref{eq:tdoa_position_model} jointly.

Since geometric approaches cannot cope with practical noisy eviroments, usually statistical approaches are used in practice. In this noisy framework, we define a model for noisy measurement as:

\section{Statistic approach}
Since geometric approaches cannot cope with noisy environments, usually statistical approach are used in practice. In this noisy framework, we define a model for noisy measurement as:
\begin{equation}
    z = f(x,y) + \eta
\end{equation}
where $z$ is the results of a noisy measurement, $f(x,y)$ is the true value of this measurement which is the function of target node's position and $\eta$ is the noise of this measurement. For the techniques discussed in previous section, $f(x,y)$ is as follows:
\begin{equation}
    f(x,y) = \begin{cases} \sqrt{(x-x_s)^2 + (y-y_s)^2} & \mbox{TOA, RSS}
    \\ \arctan{\frac{y-y_s}{x-y_s}} & \mbox{AOA}
    \\ \sqrt{(x-x_s)^2 + (y-y_s)^2} - \sqrt{(x-x_{cs})^2 + (y-y_{cs}^2)} & \mbox{TDOA}
\end{cases}
\end{equation}
where $(x_s,y_s)$ is the known position of the source nodes, and $(x_{cs},y_{cs})$ is the position of common source node for the TDOA technique. In vector-space notation, the cited model is changed to:
\begin{equation}
    \mathbf{z} = \mathbf{f}(x,y) + \mathbf{\eta}
\end{equation}
where $\mathbf{z} = [z_1,...,z_{N_m}]^T$, $\mathbf{F}(x,y) = [f_1(x,y),...,f_{N_m}(x,y)]^T$ and $\mathbf{\eta}=[\eta_1,...,\eta_{N_m}]^T$. $N_m$ equal to the number if source node in TOA, RSS amd AOA approaches, and one less than the number of source nodes in the TDOA approach. Assume that the noise which affects our measurements is known except for a set of parameters, $\lambda$. So, we have a vector of unknown parameters, $\theta$, as:
\begin{equation}
    \mathbf{\theta} = [xy\mathbf{\lambda}^T]^T
\end{equation}
where $(x,y)$ is the position of the target node. In such problems, we can use parametric approaches to estimate the  true value of $\mathbf{\theta}$. Two prevalent parametric approaches are Bayesian and Maximum-Likelihood (ML). The Bayesian approach is usefull in case of prior information about $\mathbf{\theta}$ is available. The ML approach find $\mathbf{\theta}$ which gives the maximum probability for the observations. Formally, we can define $\mathbf{\theta}$ estimated by the ML $\hat{\mathbf{\theta}}$ as:
\begin{equation}
    \hat{\mathbf{\theta}}_{ML} = \argmax_{\theta}p(\mathbf{z}|\mathbf{\theta})
\end{equation}
Since the function of $f(x,y)$ is deterministic, we can express the likelihood function $p(\mathbf{z}|\mathbf{\theta})$ as:
\begin{equation}
    p(\mathbf{z}|\mathbf{\theta}) = p_{\eta}(\mathbf{z} - \mathbf{f}(x,y) | \mathbf{\theta})
    \label{eq:probability_density_function_of_the_noise}
\end{equation}
where $p(.|\mathbf{\theta})$ is the conditional probability density function of the noise given parameter vector $\mathbf{\theta}$.
\subsubsection*{Position in the presence of the independent noise}
In case of the independent noise for all measurement, we can express equation \ref{eq:probability_density_function_of_the_noise} as:
\begin{equation}
    p(\mathbf{z}|\mathbf{\theta}) = \prod_{i=1}^{N_m}p_{\eta_i}(z_i-f_i(x,y) | \mathbf{\theta})
\end{equation}
where $z_i$ is the $i$th measurement, $f_i(x,y)$ is the true value of the $i$th measurement and the $p_{\eta_i}$ is the conditional probability function of the $i$th measurement. The independent noise assumption is reasonable for the AOA, TOA and RSS approaches. However, in the case of TDOA, we have correlated noise for several source node's measurements due to the presence of the common source node. For system working under LOS conditions, the majority of the noise is thermal noise. We can model the noise of the environments as Gaussian zero mean random variable as:
\begin{equation}
    p_{\eta_i} = \frac{1}{\sqrt{2\pi}\sigma_i}\exp{-\frac{u^2}{2\sigma_i^2}}
\end{equation}
\end{document}


\documentclass[10pt, a4paper, twoside]{basestyle}
\usepackage{tkz-euclide}
\usetkzobj{all}
\usepackage[Mathematics]{semtex}
\usepackage{chngcntr}
\counterwithout{equation}{section}

%%%% Shorthands.

%%%% Title and authors.

\newcommand{\point}[1]{\mathrm{#1}}
\newcommand{\bipoint}[2]{\overrightarrow{\point #1 \point #2}}
\newcommand{\straightline}[2]{\point #1 \point #2}
\newcommand{\plane}[3]{\point #1 \point #2 \point #3}
\newcommand{\squarenorm}[1]{\scal{#1}{#1}}

\title{%
\textdisplay{%
Hiding Computations in Projection%
}%
}
\author{Pascal~Leroy (pleroy)}
\begin{document}
\maketitle
This document describes the computations that are performed by the method
\texttt{VisibleSegments} of class \texttt{Perspective} to determine the parts of
a segment that are hidden by a sphere when seen from a pinhole camera.

Figure~\ref{fig3d} illustrates an example of the problem.  The points drawn in
black define the problem: $\point A$ and $\point B$ are the extremities of the
segment; $\point C$ is the centre of the sphere; $R$ is the radius of the
sphere; and $\point K$ is the location of the camera.  The points drawn in red
will be computed as part of the resolution.  Of particular interest is the plane
$\plane KAB$, in which we willl do much of the analysis below.  The figure shows
the circle formed by the intersection of this plane with the sphere, as well as
$\point H$, the center of that circle and the projection of $\point C$ on
$\plane KAB$.
\begin{figure}[htb!]
\centering
\includegraphics[scale=0.35]{Perspective-hiding-3d}
\caption{A 3-dimensional example.  In this case, the only segment visible from
$\point K$ is the part of $\straightline AB$ between $\point B$ and the red
point immediately to its left.\label{fig3d}}
\end{figure}

\subsection*{Camera inside the sphere}
We start our analysis by eliminating a case that would cause anomalies in the
analysis below.  If\[
\scal{\bipoint KC}{\bipoint KC} < R^2
\]
then the camera is inside the sphere and the segment is hidden irrespective of
its position.

\subsection*{Sphere and segment in distinct half-spaces}
Consider the plane containing $\point K$ and orthogonal to $\straightline KC$;
it separates the entire space into two half-spaces.  If the segment
$\straightline AB$ is entirely within the half-space that does not contain
$\point C$ then the segment is not hidden (remember that $\point K$ is not
inside the sphere).  This is the case if the following inequalities are both
true:
\begin{align*}
\scal{\bipoint KA}{\bipoint KC} &< 0\\
\scal{\bipoint KB}{\bipoint KC} &< 0\text.
\end{align*}

\subsection*{Projection of $\point C$ on $\plane KAB$}
For simplicity we will do the rest of our analysis in the plane $\plane KAB$ and
we will often use $\tuple{\bipoint KA, \bipoint KB}$ as a basis of that plane.
Let $\point H$ be the orthogonal projection of $\point C$ on $\plane KAB$.
and define $\ga$, $\gb$ to be its coordinates in
$\tuple{\bipoint KA, \bipoint KB}$
\[
\bipoint KH = \ga \bipoint KA + \gb \bipoint KB\text.
\]
Note that $\bipoint KH = \bipoint KC + \bipoint CH$. By definition,
$\bipoint CH$ is orthogonal to both $\bipoint KA$ and $\bipoint KB$:
\begin{align*}
\scal{\bipoint KA}{\bipoint CH} &= 0\\
\scal{\bipoint KB}{\bipoint CH} &= 0\text.
\end{align*}
Decomposing $\bipoint CH$ we obtain:
\begin{align*}
\scal{\bipoint KA}{\bipoint KH} &= \scal{\bipoint KA}{\bipoint KC}\\
\scal{\bipoint KB}{\bipoint KH} &= \scal{\bipoint KB}{\bipoint KC}\text.
\end{align*}
Expanding $\bipoint KH$ on the basis $\tuple{\bipoint KA, \bipoint KB}$ gives a
linear system of two equations with two unknowns:
\begin{align*}
\ga \scal{\bipoint KA}{\bipoint KA} + \gb \scal{\bipoint KA}{\bipoint KB}
    &= \scal{\bipoint KA}{\bipoint KC}\\
\ga \scal{\bipoint KA}{\bipoint KB} + \ga \scal{\bipoint KB}{\bipoint KB}
    &= \scal{\bipoint KB}{\bipoint KC}\text.
\end{align*}
The determinant of this system is\[
D = \pascal{\squarenorm{\bipoint KA}} \pascal{\squarenorm{\bipoint KB}} -
    \pascal{\scal{\bipoint KA}{\bipoint KB}}^2\text,
\]
which is non-zero if and only if $\point A \neq \point B$. The solutions are
thus:
\begin{align*}
\ga &= \frac
  {\pascal{\squarenorm{\bipoint KB}} \pascal{\scal{\bipoint KA}{\bipoint KC}} -
   \pascal{\scal{\bipoint KA}{\bipoint KB}}
   \pascal{\scal{\bipoint KB}{\bipoint KC}}}
  {D}\\
\gb &= \frac
  {\pascal{\squarenorm{\bipoint KA}} \pascal{\scal{\bipoint KB}{\bipoint KC}} -
   \pascal{\scal{\bipoint KA}{\bipoint KB}}
   \pascal{\scal{\bipoint KA}{\bipoint KC}}}
  {D}\text.
\end{align*}
Once $\bipoint KH$ is determined we can compute $\bipoint CH =
\bipoint KH - \bipoint KC$.  If $\squarenorm{\bipoint CH} \geq R^2$, the sphere
is either tangent to the plane $\plane KAB$ or doesn't intersect it. In these
cases, there is no hiding.

If the sphere intersects $\plane KAB$, then the intersection is a circle whose
radius we denote by $r$ in the rest of this analysis.  The radius is such that
$r^2 = R^2 - \squarenorm{\bipoint CH}$.

\subsection*{An optimization where the circle is outside the wedge $\plane KAB$}
\marginfig[Circle lying outside the wedge $\plane KAB$ on the side of
$\straightline KB$.\label{figOutside}]{
\begin{tikzpicture}[scale=0.5]
\tkzInit[ymin=-7,ymax=8,xmin=-1,xmax=9]
\tkzClip
\tkzDefPoint(3,5){A}
\tkzDefPoint(8,0){B}
\tkzDefPoint(4,-3){H}
\tkzDefPoint(0,0){K}

\tkzDefLine[orthogonal=through H](K,B) \tkzGetPoint{h1}
\tkzInterLL(H,h1)(K,B) \tkzGetPoint{N}

\tkzDefLine[parallel=through H](K,A) \tkzGetPoint{h2}
\tkzInterLL(H,h2)(K,B) \tkzGetPoint{M}

\tkzDefPointWith[linear,K=2](H,M) \tkzGetPoint{m}

\tkzDefPointBy[rotation=center H angle -130](N) \tkzGetPoint{r}

\tkzDrawPoints(A,B,H,K,M,N)
\tkzLabelPoint[left](A){$\point A$}
\tkzLabelPoint[above](B){$\point B$}
\tkzLabelPoint[left](H){$\point H$}
\tkzLabelPoint[above left](K){$\point K$}
\tkzLabelPoint[below right](M){$\point M$}
\tkzLabelPoint[above left](N){$\point N$}

\tkzDrawLine(K,A)
\tkzDrawLine(K,B)
\tkzDrawLine(H,N)
\tkzDrawLine[add=0.2 and 0.5](H,M)

\tkzDrawSegment[style=dashed](H,r)
\tkzLabelSegment[above right](H,r){$r$}

\tkzDrawCircle[R](H,3cm)

\tkzMarkRightAngle[size=0.5](H,N,M)
\tkzMarkAngle[size=0.5](B,K,A)
\tkzLabelAngle(A,K,B){$\gq$}
\tkzMarkAngle[size=0.5](B,M,m)
\tkzLabelAngle(B,M,m){$\gq$}

\end{tikzpicture}
}
A useful optimization at this stage is to determine if the circle intersects the
wedge $\plane KAB$.  If it does not, then there is no hiding and the segment
$\straightline AB$ is entirely visible.  This can happen because the circle is
away from the wedge on the side of $\straightline KA$ or because it is away from
the wedge on the side of $\straightline KB$.  Figure~\ref{figOutside}
illustrates the latter case: note that the circle must not intersect
$\straightline KB$, so the distance between $\point H$ and $\straightline KB$
must be at least $r$; the figure shows the case where the circle is tangent to
$\straightline KB$ at $\point N$, which is the one that interests us in this
section.

Observe that, if $\gq$ is the angle between $\bipoint KA$ and $\bipoint KB$, we
have
\[
\scal{\bipoint KA}{\bipoint KB} = \norm{\bipoint KA} \norm{\bipoint KB}
                                  \cos \gq
\]
Let $\point M$ be the point where $\point H$ projects on $\straightline KB$
parallel to $\straightline KA$.  Since $\ga$ and $\gb$ are the coordinates of
$\bipoint KH$ in the basis $\tuple{\bipoint KA, \bipoint KB}$, we
have
\begin{equation}
{\bipoint HM} = \ga {\bipoint KA} \label{eqnhm1}\text,
\end{equation}
and elementary trigonometry in the triangle $\plane HNM$ yields
\begin{equation}
\scal{\bipoint HM}{\bipoint HM} = \frac{r^2} {\sin^2 \gq} =
                                  \frac{r^2} {1 - \cos^2 \gq}
                                  \label{eqnhm2}\text.
\end{equation}
Eliminating $\bipoint HM$ between equations (\ref{eqnhm1}) and (\ref{eqnhm2}) we
obtain the following conditions on $\ga$ for $\point H$ to be outside the wedge
$\plane KAB$ on the side of $\straightline KB$:
\begin{align*}
\ga &\leq 0\\
\ga^2 &\geq r^2 \frac{\squarenorm{\bipoint KB}}
                     {\pascal{\squarenorm{\bipoint KA}}
                      \pascal{\squarenorm{\bipoint KB}} -
                     {\pascal{\scal{\bipoint KA}{\bipoint KB}}}^2}\text.
\end{align*}
It's straightforward to prove similar conditions on $\gb$ for the circle to be
outside the wedge $\plane KAB$ on the side of $\straightline KA$.

\subsection*{Construction of the cone}
\marginfig[Construction of $\point P$ and $\point P'$ and of the cone.
\label{figP}]{
\begin{tikzpicture}[scale=0.5]
\tkzInit[ymin=-5,ymax=10,xmin=-4,xmax=6]
\tkzClip
\tkzDefPoint(-3,9){A}
\tkzDefPoint(5.5,9){B}
\tkzDefPoint(2,5){H}
\tkzDefPoint(0,-4){K}

\tkzTangent[from with R=K](H,3cm) \tkzGetPoints{P'}{P}
\tkzInterLL(K,P)(A,B) \tkzGetPoint{Q}

\tkzDefPointBy[rotation=center H angle -130](P) \tkzGetPoint{r}

\tkzDrawPoints(A,B,H,K,P,P',Q)
\tkzLabelPoint[below left](A){$\point A$}
\tkzLabelPoint[above left](B){$\point B$}
\tkzLabelPoint[below](H){$\point H$}
\tkzLabelPoint[left](K){$\point K$}
\tkzLabelPoint[above left](P){$\point P$}
\tkzLabelPoint[below right](P'){$\point P'$}
\tkzLabelPoint[above right](Q){$\point Q$}

\tkzDrawLine[add=0.05 and 0.05](A,B)
\tkzDrawLine(H,P)
\tkzDrawLine(K,A)
\tkzDrawLine(K,B)
\tkzDrawLine(K,P')
\tkzDrawLine(K,Q)

\tkzDrawSegment[style=dashed](H,r)
\tkzLabelSegment[left](H,r){$r$}

\tkzDrawCircle[R](H,3cm)

\tkzMarkRightAngle[size=0.5](K,P,H)

\end{tikzpicture}
}
Remember that the circle of centre $\point H$ and radius $r$ is the intersection
of the sphere with the plane $\plane KAB$.  As shown on figure~\ref{fig3d},
hiding is determined by the cone of apex $\point K$ tangent to the sphere.  This
cone intersects $\plane KAB$ in two straight lines that go through $\point K$
and are tangent to the circle at points $\point P$ and $\point P'$.  In this
section we are going to determine the coordinates of $\point P$ and $\point P'$
in the basis $\tuple{\bipoint KA, \bipoint KB}$.  Figure~\ref{figP} illustrates
the construction of these points.

$\point P$ is characterized by the two equations:
\begin{align}
\squarenorm{\bipoint PH} &= r^2 \label{eqnp1}\\
\scal{\bipoint PH}{\bipoint KP} &= 0 \label{eqnp2}\text.
\end{align}
Equation (\ref{eqnp2}) may be rewritten as
\[
\scal{\bipoint PH}{\pascal{\bipoint KH + \bipoint HP}} = 0\text,
\]
which yields, when combined with equation (\ref{eqnp1})
\begin{equation}
\scal{\bipoint PH}{\bipoint KH} = r^2 \label{eqnp3}\text.
\end{equation}
Define now $\gg$ and $\gd$ to be the coordinates of $\bipoint PH$ in
$\tuple{\bipoint KA, \bipoint KB}$\[
\bipoint PH = \gg {\bipoint KA} + \gd {\bipoint KB}\text.
\]
Equation (\ref{eqnp3}) is linear in the coordinates of $\point P$ and can be
rewritten as\[
\gg\scal{\bipoint KA}{\bipoint KH} + \gd\scal{\bipoint KB}{\bipoint KH} =
r^2\text.
\]
Note that $\scal{\bipoint KA}{\bipoint KH}$ and
$\scal{\bipoint KB}{\bipoint KH}$ cannot both be $0$ unless $\point K$ is on
$\straightline AB$, so we can either express $\gg$ as a function of $\gd$ or
vice-versa.  If we do the former we obtain\[
\gg = \frac{r^2 - \gd \scal{\bipoint KB}{\bipoint KH}}
           {\scal{\bipoint KA}{\bipoint KH}}\text.
\]
Equation (\ref{eqnp1}) is quadratic in the coordinates of $\point P$ and can be
rewritten as\[
\pa{\gg\bipoint KA + \gd \bipoint KB}^2 = r^2\text.
\]
Pluging the value of $\gg$ above we get
\begin{align*}
\gd^2\pa{
 \pascal{\squarenorm{\bipoint KB}} \pascal{\scal{\bipoint KA}{\bipoint KH}}^2 +
 2\pascal{\scal{\bipoint KA}{\bipoint KB}}
  \pascal{\scal{\bipoint KA}{\bipoint KH}}
  \pascal{\scal{\bipoint KB}{\bipoint KH}} +
 \squarenorm{\bipoint KA} \pascal{\scal{\bipoint KB}{\bipoint KH}}^2} +&\\
2\gd r^2\pa{
 \pascal{\scal{\bipoint KA}{\bipoint KB}}
 \pascal{\scal{\bipoint KA}{\bipoint KH}} -
 \pascal{\squarenorm{\bipoint KA}}
 \pascal{\scal{\bipoint KB}{\bipoint KH}}} +&\\
r^2\pa{
 r^2\pascal{\squarenorm{\bipoint KA}} -
 \pascal{\scal{\bipoint KA}{\bipoint KH}}^2} &= 0\text.
\end{align*}
This equation always has two solutions because the sphere intersects
$\plane KAB$.
\subsection*{Intersection of the cone and the line $\straightline AB$}
Having determined the location of points $\point P$ and $\point P'$ we need to
find the points $\point Q$ and $\point Q'$ where the lines $\straightline KP$
and $\straightline KP'$, respectively, intersect the line $\straightline AB$.
Since $\point Q$ is on $\straightline AB$ there is a $\gl$ such that\[
\bipoint AQ = \gl \bipoint AB\text,
\]
or equivalently
\begin{equation}
\bipoint KQ - \bipoint KA = \gl \bipoint AB \label{eqnq1}\text.
\end{equation}
We can take the scalar product of equation (\ref{eqnq1}) with $\bipoint PH$, and,
noting that $\bipoint KQ$ is orthogonal to $\bipoint PH$ we obtain\[
-\scal{\bipoint KA}{\bipoint PH} = \gl \scal{\bipoint AB}{\bipoint PH}
\text{, or, }
\gl = -\frac{\scal{\bipoint KA}{\bipoint PH}}{\scal{\bipoint AB}{\bipoint PH}}
\text.
\]
Obviously there is a similar equation with $\point P'$ which may be used to
compute $\gl'$, the position of $\point Q'$ on $\straightline AB$.

The point $\point Q$ is in the segment $\straightline AB$ if and only if
$0 \leq \gl \leq 1$.  This does not tell us, however, where $\point Q$ is
located with respect to the cone, to the sphere, or for that matter if it is
in front or behind the camera.  This is what we need to determine next.

\marginfig[Definition of $\point S$ and $\point T$.\label{figST}]{
\begin{tikzpicture}[scale=0.5]
\tkzInit[ymin=-5,ymax=12,xmin=-4,xmax=6]
\tkzClip
\tkzDefPoint(2,11){A}
\tkzDefPoint(5,-4){B}
\tkzDefPoint(0,0){H}
\tkzDefPoint(0,6){K}

\tkzTangent[from with R=K](H,3cm) \tkzGetPoints{P2}{P}

\tkzDefLine[orthogonal=through P](K,H) \tkzGetPoint{p}
\tkzInterLL(P,p)(A,B) \tkzGetPoint{T}
\tkzInterLL(P,p)(K,H) \tkzGetPoint{q}

\tkzDefLine[orthogonal=through K](K,H) \tkzGetPoint{k}
\tkzInterLL(K,k)(A,B) \tkzGetPoint{S}

\tkzInterLL(K,P)(A,B) \tkzGetPoint{Q}

\tkzDefPointBy[rotation=center H angle -80](P) \tkzGetPoint{r}

\tkzDrawPoints(A,B,H,K,P,Q,S,T)
\tkzLabelPoint[left](A){$\point A$}
\tkzLabelPoint[left](B){$\point B$}
\tkzLabelPoint[left](H){$\point H$}
\tkzLabelPoint[left](K){$\point K$}
\tkzLabelPoint[below left](P){$\point P$}
\tkzLabelPoint[left](Q){$\point Q$}
\tkzLabelPoint[above right](S){$\point S$}
\tkzLabelPoint[above right](T){$\point T$}

\tkzDrawLine[add=0.2 and 3](A,B)
\tkzDrawLine(H,K)
\tkzDrawLine[add=1 and 1](K,P)
\tkzDrawLine[add=1 and 1](K,P2)
\tkzDrawLine[add=0.05 and 0.2](K,S)
\tkzDrawLine[add=2.2 and 0.2](P,T)

\tkzDrawSegment[style=dashed](H,r)
\tkzLabelSegment[above right](H,r){$r$}

\tkzDrawCircle[R](H,3cm)

\tkzMarkRightAngle[size=0.5](S,K,H)
\tkzMarkRightAngle[size=0.5](P,q,H)

\end{tikzpicture}
}
\subsection*{Location of $\point Q$ and $\point Q'$}
Having computed the values of $\gl$ we need to determine where $\point Q$ is
located with respect to the cone, the sphere and the camera.  To do this we are
going to define two new points, $\point S$ and $\point T$, as shown on
figure~\ref{figST}.  $\point S$ is the intersection of $\straightline AB$ with
the line orthogonal to $\straightline KH$ at $\point K$.  $\point T$ is the
intersection of $\straightline AB$ with the line orthogonal to
$\straightline KH$ at $\point P$.  We are going to find the positions of
$\point S$ and $\point T$ on $\straightline AB$, and, by comparing then with
$\gl$, figure out the location of $\point Q$ with respect to $\point S$ and
$\point T$.

We locate $\point S$ on $\straightline AB$ as follows\[
\bipoint KS = \bipoint KA + \gs \bipoint AB\text.
\]
Taking the scalar product of this equation with $\bipoint KH$, and noting that
$\bipoint KS$ is orthogonal to $\bipoint KH$ we obtain\[
\gs = -\frac{\scal{\bipoint KA}{\bipoint KH}}
            {\scal{\bipoint AB}{\bipoint KH}}
\]
Similarly, we locate $\point T$ on $\straightline AB$ as\[
\bipoint KT = \bipoint KA + \gt \bipoint AB\text.
\]
Since $\bipoint KT = \bipoint KH + \bipoint HP + \bipoint PT$ this can be
written\[
\bipoint PT = \bipoint KA + \gt \bipoint AB - \bipoint KH + \bipoint PH
\]
Again, taking the scalar product of this equation with $\bipoint KH$, and noting
that $\bipoint KT$ is orthogonal to $\bipoint KH$ we obtain\[
\gt = \frac{\scal{\bipoint KH}{\bipoint KH} - \scal{\bipoint PH}{\bipoint KH} -
            \scal{\bipoint KA}{\bipoint KH}}
           {\scal{\bipoint AB}{\bipoint KH}}
\]
We can now determine if $\point Q$ (or alternatively, $\gl$) is an
``interesting'' intersection, i.e., one that intersects the cone behind the
sphere when seen from the camera.  That's because the location of $\point S$ let
us separate what is behind the camera from what is in front of the camera, and
the location of $\point T$ determines where the cone starts (points in front
of $\point T$ cannot be in the cone, although they can be in the sphere).

First, assume that $\point A$ and $\point B$ are in the same order as $\point S$
and $\point T$ on $\straightline AB$.  Then we have $\gs \leq \gt$ and the
intersection $\point Q$ is farther than $\point T$ (as seen from the camera) if
and only if $\gt < \gl$.  $\point Q$ is located on the cone and it is an
interesting intersection (and it participates in hiding) if it falls within the
segment $\straightline AB$.  This is the situation illustrated in
figure~\ref{figST}.

Conversely, if $\point A$ and $\point B$ are in the reverse order
as $\point S$ and $\point T$ on $\straightline AB$ we have $\gt \leq \gs$ and
the intersection is farther than $\point T$ if and only if $\gl < \gt$.

The same analysis must be performed for $\gl'$ corresponding to $\point Q'$.

\subsection*{Point at infinity}
There is another special case that requires some care: if the line
$\straightline AB$ is in ``hyperbolic'' position, i.e., intersects both halves
of the cone, then one of the values $\gl$, $\gl'$ is smaller than $\gs$ and the
other is greater than $\gs$ (this is the situation shown in figure~\ref{figST}).
Exactly one of $\gl$, $\gl'$ will be retained by the preceding analysis.  To
account for the fact that the points farther than $\point Q$ (such as $\point B$
in figure~\ref{figST}) are inside the cone, we need to add to our analysis an
extra value of $\gl$ equal to an infinity with the sign of $\gt - \gs$.

\marginfig[Intersection with the sphere.\label{figSphere}]{
\begin{tikzpicture}[scale=0.5]
\tkzInit[ymin=-5,ymax=10,xmin=-3.8,xmax=6.2]
\tkzClip
\tkzDefPoint(-3,5){A}
\tkzDefPoint(5.5,5){B}
\tkzDefPoint(2,7){H}
\tkzDefPoint(0,-4){K}

\tkzTangent[from with R=K](H,3cm) \tkzGetPoints{P'}{P}
\tkzInterLC[R](A,B)(H,3cm) \tkzGetPoints{Q'}{Q}

\tkzDefPointBy[rotation=center H angle 100](Q') \tkzGetPoint{r}

\tkzDrawPoints(A,B,H,K,P,P',Q,Q')
\tkzLabelPoint[below left](A){$\point A$}
\tkzLabelPoint[below right](B){$\point B$}
\tkzLabelPoint[left](H){$\point H$}
\tkzLabelPoint[left](K){$\point K$}
\tkzLabelPoint[left](P){$\point P$}
\tkzLabelPoint[right](P'){$\point P'$}
\tkzLabelPoint[below left](Q){$\point Q$}
\tkzLabelPoint[above left](Q'){$\point Q'$}

\tkzDrawLine[add=0.05 and 0.05](A,B)
\tkzDrawLine(K,A)
\tkzDrawLine(K,B)
\tkzDrawLine[add=-0.9 and 0.1](K,P)
\tkzDrawLine[add=-0.9 and 0.1](K,P')

\tkzDrawSegment[style=dashed](H,r)
\tkzLabelSegment[left](H,r){$r$}

\tkzDrawCircle[R](H,3cm)

\end{tikzpicture}
}
\subsection*{Intersection with the circle}
To complete the analysis we need to compute the intersection $\point Q$ of the
circle with the line $\straightline AB$. $\point Q$ is on the circle, thus
\begin{equation}
\squarenorm{\bipoint HQ} = r^2 \label{eqnq2}\text;
\end{equation}
it is also on the line $\straightline AB$ and therefore there is a $\gm$ such
that
\[
\bipoint KQ = \bipoint KA + \gm \bipoint AB\text.
\]
We can rewrite $\bipoint HQ$ as follows\[
\bipoint HQ = \bipoint KQ - \bipoint KH =
  \bipoint KA + \gm \bipoint AB - \bipoint KH =
  \bipoint HA + \gm \bipoint AB\text.
\]
Inserting this value in equation (\ref{eqnq2}) we obtain\[
r^2 = \pascal{\bipoint HA + \gm \bipoint AB}^2\text,
\]
meaning that $\gm$ is a solution of\[
\gm \squarenorm{\bipoint AB} + 2 \gm \scal{\bipoint HA}{\bipoint AB}
+ \squarenorm{\bipoint HA} - R^2 = 0\text.
\]
Depending on the location of $\straightline AB$ with respect to the circle,
there can be $0$, $1$, or $2$ intersections.

\subsection*{Concluding the analysis}
If we take the union of the values of $\gl$ and $\gm$ and order them, it is
straightforward to find the visible segments by remembering that
$0 \leq \gl,\gm \leq 1$ for the points that are in the segment
$\straightline AB$.
\end{document}