\chapter{Lecture 30 Jun 13th 2018}%
\label{chp:lecture_30_jun_13th_2018}
% chapter lecture_30_jun_13th_2018

\section{Polynomial Ring (Continued 3)}%
\label{sec:polynomial_ring_continued_3}
% section polynomial_ring_continued_3

\subsection{Quotient Rings of Polynomials (Continued)}%
\label{sub:quotient_rings_of_polynomials_continued}
% subsection quotient_rings_of_polynomials_continued

Let $A$ be a non-zero ideal in $F[x]$. By \cref{propo:ideals_of_f_x_are_principal_ideals}, we know that $A$ is a principal ideal\index{Principal Ideal} and can be written as $A = \lra{h(x)}$, for a unique polynomial $h(x) \in F[x]$.

Suppose that $\deg h = m \geq 1$. Consider the quotient ring $R = \faktor{F[x]}{A}$, and so we have
\begin{equation*}
  R = \left\{ \bar{f(x)} : f(x) + A, f(x) \in F[x] \right\}.
\end{equation*}
Write $t = \bar{x} = x + A$. Then by the \hlnoteb{Division Algorithm}\sidenote{This entire part until Proposition 89 might need to be rewritten since I am a little lost as to some of the details regarding the discussion.}, we have
\begin{equation*}
  R = \{ \bar{a_0} + \bar{a_1} t + \hdots + \bar{a_{m - 1}} t^{m - 1} : a_i \in F \}.
\end{equation*}
The map $\theta : F \to R$, given by $a \mapsto \bar{a}$, is an injective homomorphism, since $\theta$ is not a zero map and $\ker \theta$ is an ideal of $F$ \sidenote{Note that a field $F$ has only 2 ideals: $\{0\}$ and $F$ itself. Since $\ker \theta \neq F$, we have that $\ker \theta = \{0\}$ and so $\theta$ is injective.}. Since we have $F \cong \theta(F)$ by the \hyperref[thm:first_isomorphism_theorem_for_rings]{First Isomorphism Theorem for Rings}, by identifying $F$ with $\theta(F)$, we can write
\begin{equation*}
  R = \{ a_0 + a_1 t + \hdots a_{m - 1} t^{m - 1} : a_i \in F \}.
\end{equation*}

It is clear that, in $R$, we have
\begin{gather*}
  a_0 + a_1 t + \hdots + a_{m - 1} t^{m - 1} = b_0 + b_1 t + \hdots + b_{m - 1} t^{m - 1} \\
  \iff \\
  \forall i \in \mathbb{Z} \enspace 0 \leq i \leq m - 1 \quad a_i = b_i
\end{gather*}

Finally, in the ring $R$, we have $h(t) = 0$.

The following proposition follows from the above discussion.

\begin{propo}
\label{propo:remainder_ring}
Let $F$ be a field and let $h(x), f(x) \in F[x]$ be monic with $( \deg h, \, \deg f \geq 1 )$. Then the quotient ring $R = F[x] / A$ is given by
\begin{equation*}
  R = \{ a_0 + a_1 t + \hdots + a_{m - 1} t^{m - 1} : a_i \in F, \, h(t) = 0 \}
\end{equation*}
in which each element of $R$ can be uniquely represented in the above form.
\end{propo}

\begin{note}
  In $\mathbb{Z}$, we have that $\mathbb{Z} / \lra{n} = \mathbb{Z}_n = \{ [0], [1], ..., [n-1] \}$ which is analogous to our statement in \cref{propo:remainder_ring} for the case of integers.
\end{note}

\begin{eg}
  Consider $\mathbb{R}[x]$ and let $h(x) = x^2 + 1 \in \mathbb{R}[x]$. Then
  \begin{equation*}
    \mathbb{R}[x] = \{a + bt : a, b \in \mathbb{R}, \, t^2 + 1 = 0 \} \cong \{ a + bi : a, b \in \mathbb{R}, \, i^2 = -1 \} = \mathbb{C}
  \end{equation*}
\end{eg}

\begin{note}
  Recall that $\mathbb{Z}_n$ is a field (or an integral domain) if and only if $n$ is prime.
\end{note}

\begin{propo}
\label{propo:principal_ideals_of_polyms_as_fields}
  Let $F$ be a field nad $h(x) \in F[x]$ be a monic polynomial with $\deg h \geq 1$. TFAE:
  \begin{enumerate}
    \item $F[x] \big/ \lra{h(x)}$ is a field;
    \item $F[x] \big/ \lra{h(x)}$ is an integral domain;
    \item $h(x)$ is irreducible in $F[x]$.
  \end{enumerate}
\end{propo}

\begin{proof}
  $(1) \implies (2)$ since a field is an integral domain (see \cref{propo:fields_are_integral_domains}).

  \noindent $(2) \implies (3)$: Write $A = \lra{h(x)}$, If $h(x) = f(x) g(x)$ for $f(x), \, g(x) \in F[x]$, then
  \begin{align*}
    [ f(x) + A ] [ g(x) + A ] &= f(x) g(x) + A \quad \because A \text{ is an ideal } \\
                              &= h(x) + A = 0 \in F[x] \big/ A.
  \end{align*}
  Then by $(2)$, either $f(x) + A = 0$ or $g(x) + A = 0$, i.e. either $f(x) \in A$ or $g(x) \in A$. But if $f(x) \in A = \lra{h(x)}$, then $f(x) = q(x) h(x)$ for some $q(x) \in F[x]$. Then $h(x) = f(x) g(x) = q(x) h(x) g(x)$, which then implies that $0 = h(x) [ 1 - q(x) g(x) ] \implies q(x) g(x) = 1$ since $F[x]$ is an integral domain. Then we have that $\deg g = 0$. Similarly, if $g(x) \in A$, then we have $\deg f = 0$. Therefore, $h(x)$ is irreducible in $F[x]$ by definition.

  \noindent $(3) \implies (1)$: Note that $F[x] \big/ \lra{h(x)}$ is a commutative ring. To show that it is a field, it suffices to show that every non-zero element of $F[x] \big/ \lra{h(x)}$ has an inverse. Let $f(x) + A \neq 0 \in F[x] \big/ \lra{h(x)}$ with $f(x) \in F[x]$. Then $f(x) \notin A$, and so $h(x) \not| \, f(x)$. Since $h(x)$ is irreducible by $(3)$, we have that
  \begin{equation*}
    d(x) = \gcd[ f(x), h(x) ] = 1.
  \end{equation*}
  Then by \cref{propo:properties_of_the_greatest_common_divisor}, $\exists u(x), v(x) \in F[x]$ such that
  \begin{equation*}
    1 = u(x) h(x) + v(x) f(x).
  \end{equation*}
  Since $h(x) u(x) \in A$, we have that
  \begin{equation*}
    [v(x) + A] [f(x) + A] = 1 + A.
  \end{equation*}
  It follows that $f(x) + A$ has an inverse in $F[x] \big/ \lra{h(x)}$ and thus $F[x] \big/ \lra{h(x)}$ is a field. \qed
\end{proof}

% subsection quotient_rings_of_polynomials_continued (end)

% section polynomial_ring_continued_3 (end)

\section{Factorizations in Integral Domains}%
\label{sec:factorizations_in_integral_domains}
% section factorizations_in_integral_domains

\subsection{Irreducibles and Primes}%
\label{sub:irreducibles_and_primes}
% subsection irreducibles_and_primes

We have discussed much about the similarities between $\mathbb{Z}$ and $F[x]$, and in this chapter, we wish to abstract these similarties and study them in a more general manner to see if other sets that share the same kind of properties. For example, if a set has a \hlnoteb{unique factorization} for elements and the \hlnoteb{principal ideal} being the only ideal of the set, then do we still see the same analogy playing out?

\begin{defn}[Division]\index{Division}
\label{defn:division}
  Let $R$ be an integral domain and $a, \, b \in R$. We say that $a \, | \, b$ if $b = ca$ for some $c \in R$.
\end{defn}

\begin{note}
  Recall that in $\mathbb{Z}$, if $n \, | \, m$ and $m \, | \, n$, then $n = \pm m$, and the ideal generated by them are the same, i.e. $\lra{n} = \lra{m}$.

  Similarly so in $F[x]$< if $f(x) \, | \, g(x)$ and $g(x) \, | \, f(x)$, then $f(x) = cg(x)$ for some $x \in F[x]^* = F^*$, and $\lra{f(x)} = \lra{g(x)}$.
\end{note}

\begin{propo}[Division in an Integral Domain]
\label{propo:division_in_an_integral_domain}
Let $R$ be an integral domain. Then $\forall a, b \in R$, TFAE:\marginnote{This should be an easy exercise.
\begin{ex}
  Prove \cref{propo:division_in_an_integral_domain}.
\end{ex}
}
  \begin{enumerate}
    \item $a \, | \, b$ and $b \, | \, a$;
    \item $a = ub$ for some unit $u \in R$;
    \item $\lra{a} = \lra{b}$.
  \end{enumerate}
\end{propo}

\begin{defn}[Association]\index{Association}
\label{defn:association}
  Let $R$ be an integral domain. $\forall a, b \in R$, we say that $a$ is \hldefn{associated to} $b$, denoted by $a \sim b$, if $a \, | \, b$ and $b \, | \, a$.
\end{defn}

\begin{note}
  By \cref{propo:division_in_an_integral_domain}, we have that $a \sim a$ for any $a \in R$.

  \noindent Also, $a \sim b \iff b \sim a$.

  \noindent We also have $a \sim b \, \land \, b \sim c \implies a \sim c$.

  In other words, $\sim$ is an equivalence relation\index{Equivalence Relation} in $R$. Also, it can be shown that\sidenote{More exercise is always good.
  \begin{ex}
    Prove that the two statements following this is true.
  \end{ex}
  }
  \begin{enumerate}
    \item $a \sim a' \, \land \, b \sim b' \implies ab \sim a' b'$.
    \item $a \sim a' \, \land \, b \sim b' \implies ( a \, | \, b \iff b \, | \, a )$
  \end{enumerate}
\end{note}

\begin{eg}
  Let $R = \mathbb{Z}[\sqrt{3}] = \{ m + n \sqrt{3} : m, n \in \mathbb{Z} \}$. Note that this is an integral domain\sidenote{For $(a + b\sqrt{3}), \, (c + d\sqrt{3}) \in R$ such that
  \begin{equation*}
    (a + b \sqrt{3})(c + d \sqrt{3}) = 0
  \end{equation*}
  we would have that
  \begin{gather*}
    (a + b\sqrt{3})(a - b \sqrt{3})(c + d\sqrt{3})(c - d\sqrt{3}) = 0 \\
    ( a^2 - 3b^2 )( c^2 - 3d^2 ) = 0.
  \end{gather*}
  Since $\mathbb{Z}$ is an integral domain, suppose $a^2 - 3b^2 = 0$. If $b = 0$, then $a = 0$ and we are done. If $b \neq 0$, then we have $3 = \left( \frac{a}{b} \right)^2$, and we notice that $\sqrt{3}$ is irrational. Thus it can only be that $b = 0$. Therefore, $a + b\sqrt{3} = 0$, implying that there are no zero divisors in $R = \mathbb{Z}[\sqrt{3}]$.
  }. Observe that
  \begin{equation*}
    (2 + \sqrt{3})(2 - \sqrt{3}) = 1 \implies 2 + \sqrt{3} \text{ is a unit in } R.
  \end{equation*}
  Then we would have
  \begin{equation*}
    3 + 2 \sqrt{3} = (2 + \sqrt{3}) \sqrt{3}
  \end{equation*}
  and so by \cref{propo:division_in_an_integral_domain}, we have
  \begin{equation*}
    3 + 2 \sqrt{3} \sim \sqrt{3} \in \mathbb{Z}[\sqrt{3}].
  \end{equation*}
\end{eg}

% subsection irreducibles_and_primes (end)

% section factorizations_in_integral_domains (end)

% chapter lecture_30_jun_13th_2018 (end)


\documentclass[12]{scrartcl}
\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}
\makeatletter
\newcommand\Aboxed[1]{
   \@Aboxed#1\ENDDNE}
\def\@Aboxed#1&#2\ENDDNE{%
   &
   \settowidth\@tempdima{$\displaystyle#1{}$}
   \setlength\@tempdima{\@tempdima+\fboxsep+\fboxrule}
   \kern-\@tempdima
   \boxed{#1#2}
}
\makeatother

\begin{document}

\title{Homework 21, Section 4.5: 2, 6, 11, 14}
\author{Alex Gordon}
\date{\today}
\maketitle
\section*{Homework}
\subsection*{2. A)}
$R_1$ is symmetric
\subsection*{2. B)}
$R_2$ is symmetric
\subsection*{2. C)}
$R_3$ is not symmetric
\subsection*{6.}
\{\{ACBD, CBDA, BDAC, DACB\}, \{ADBC, DBCA, BCAD, CADB\}, \{ABCD,BCDA,CDAB,DABC\},\{ADCB, DCBA, CBAD, BADC\},\{ABDC,BDCA,DCAB,CABD\}, \{ACDB, CDBA, DBAC, BACD\}\}

\subsection*{11. A)}
Let $a \in \mathds{Z} $ since $a - a = 0$ and a is divisible by $n$, $(a,a) \in \mathds{R}$. This means R is reflexive.
\subsection*{11. B)}
Let $a, b \in \mathds{Z}$ so that $(a,b) \in \mathds{R}$. Since $a - b$ is divisible by $n$, which in turn means that $a - b= kn$ and $b-a= -kn$. Since $-k$ is an integer it means that $b -a$ is divisible by $n$, which means that R is symmetric.
\subsection*{11. C)}
\subsection*{11. D)}

\subsection*{14. A)}
\{(1,1),(2,2),(3,3),(3,2),(1,3),(1,2)\}
\subsection*{14. B)}
\{(1,1),(2,2),(3,3),(3,2),(1,3),(3,1),(2,3)\}
\subsection*{14. C)}
\{(1,1),(1,2),(2,1),(2,2)\}

\end{document}


% Custom environments

\theoremstyle{plain}
\newtheorem{theorem}{Theorem}[section]
\newtheorem*{theorem*}{Theorem}
\newtheorem{lemma}{Lemma}[section]
\newtheorem*{lemma*}{Lemma}
\newtheorem{prop}{Proposition}[section]
\newtheorem{cor}{Corollary}[section]

\theoremstyle{definition}
\newtheorem{definition}{Definition}
\newtheorem{remark}{Remark}
%\newtheorem{think}{Gedankenexperiment}
%\newtheorem*{think}{Think about it \faLightbulbO}

\newtheorem{example}{Example}

\newenvironment{think}
	{
		\bigskip
		\begin{tcolorbox}
		\paragraph{Think about it.}
	}{
		\end{tcolorbox}
}

\newenvironment{extra}
{
	\bigskip
	\begin{tcolorbox}
		\paragraph{Extra Information.}
	}{
	\end{tcolorbox}
}

% Custom commands

\newcommand{\naive}{na\"{\i}ve }
\newcommand{\Naive}{Na\"{\i}ve }
\newcommand{\andor}{and\textbackslash or }
\newcommand{\erdos}{Erd\H{o}s }
\newcommand{\renyi}{R\`enyi }

\newcommand{\al}{\alpha}
\newcommand{\be}{\beta}
\newcommand{\si}{\sigma}

\newcommand{\set}[1]{\{ #1 \}} % A set
\newcommand{\setII}[1]{\left\{ #1 \right\}} % A set
\newcommand{\rv}[1]{\mathbf{#1}} % A random variable
\newcommand{\x}{\rv x} % The random variable x
\newcommand{\y}{\rv y} % The random variable x
\newcommand{\U}{\rv u} % The random variable x
\newcommand{\T}{\rv t} % The random variable x
\newcommand{\X}{\rv X} % The random variable x
\newcommand{\Y}{\rv Y} % The random variable y
\newcommand{\expect}[1]{\mathbf{E}\left[ #1 \right]} % The expectation operator
\newcommand{\expectg}[2]{\mathbf{E}_{\rv{#1}}\left[ \rv{#2} \right]} % An expectation w.r.t. a particular random variable.
\newcommand{\expectn}[1]{\mathbb{E}\left[#1\right]} % The empirical expectation
\newcommand{\cov}[1]{\mathbf{Cov} \left[ #1 \right]} % The expectation operator
\newcommand{\var}[1]{\mathop{Var} \left[ #1 \right]} % The expectation operator
\newcommand{\covn}[1]{\mathbb{Cov} \left[ #1 \right]} % The expectation operator
\newcommand{\gauss}[1]{\mathcal{N}\left(#1\right)} % The gaussian distribution
\newcommand{\cdf}[2]{F_{#1} (#2)} % The CDF function
\newcommand{\survive}[2]{S_{#1} (#2)} % The survival function
\newcommand{\surviven}[2]{\hat{S}_{#1} (#2)} % The survival function
\newcommand{\hazard}[2]{h_{#1} (#2)} % The survival function
\newcommand{\hazardn}[2]{\hat{h}_{#1} (#2)} % The survival function
\newcommand{\cuhazard}[2]{H_{#1} (#2)} % The survival function
\newcommand{\cdfn}[2]{\mathbb{F}_{#1}(#2)} % The empirical CDF function
\newcommand{\icdf}[2]{F_\rv{#1}^{-1} (#2)} % The invecrse CDF function
\newcommand{\icdfn}[2]{\mathbb{F}^{-1}_{#1}(#2)} % The inverse empirical CDF function
\newcommand{\pdf}[2]{p_{#1} (#2)} % The CDF function
\newcommand{\prob}[1]{P\left( #1 \right)} % the probability of an event
\newcommand{\dist}{P} % The proabaiblity distribution
\newcommand{\density}{p}
\newcommand{\entropy}{H} % entropy
\newcommand{\mutual}[2]{I\left(#1;#2\right)} % mutual information

\newcommand{\estim}[1]{\widehat{#1}} % An estimator
\newcommand{\estimII}[1]{\tilde{#1}} % Some other estimator

\newcommand{\norm}[1]{\Vert #1 \Vert} % The norm operator
\newcommand{\normII}[1]{\norm{#1}_2} % The norm operator
\newcommand{\normI}[1]{\norm{#1}_1} % The norm operator
\newcommand{\normF}[1]{\norm{#1}_{Frob}} % The Frobenius matrix norm
\newcommand{\ones}{\textbf{1}} % Vector of ones.
\newcommand{\lik}{\mathcal{L}} % The likelihood function
\newcommand{\loglik}{L} % The log likelihood function
\newcommand{\loss}{l} % A loss function
\newcommand{\lossII}{\prescript{}{2}{l}} % A loss function
\newcommand{\risk}{R} % The risk function
\newcommand{\riskn}{\mathbb{R}} % The empirical risk
\newcommand{\riskII}{\prescript{}{2}{R}} % The empirical risk
\newcommand{\risknII}{\prescript{}{2}{\mathbb{R}} } % The empirical risk
\newcommand{\noisen}{\mathbb{G}} % The empirical noise process
\newcommand{\deriv}[2]{\frac{\partial #1}{\partial #2}} % A derivative
\newcommand{\argmin}[2]{\textstyle{\mathop{argmin}_{#1}}\set{#2}} % The argmin operator
\newcommand{\argmax}[2]{\textstyle{\mathop{argmax}_{#1}}\set{#2}} % The argmin operator
\newcommand{\hyp}{f} % A hypothesis
\newcommand{\hypclass}{\mathcal{F}} % A hypothesis class
\newcommand{\hilbert}{\mathcal{H}}
\newcommand{\rkhs}{\hilbert_\kernel} % A hypothesis class
\newcommand{\normrkhs}[1]{\norm{#1}_{\rkhs}} % the RKHS function norm

\newcommand{\plane}{\mathbb{L}} % A hypoerplane
\newcommand{\categories}{\mathcal{G}} % The categories set.
\newcommand{\positive}[1]{\left[ #1 \right]_+} % The positive part function
\newcommand{\kernel}{\mathcal{K}} % A kernel function
\newcommand{\featureS}{\mathcal{X}} % The feature space
\newcommand{\outcomeS}{\mathcal{Y}} % The feature space
\newcommand{\indicator}[1]{I_{\set{#1}}} % The indicator function.
\newcommand{\reals}{\mathbb{R}} % the set of real numbers

\newcommand{\latent}{\rv{s}} % latent variables matrix
\newcommand{\latentn}{S} % latent variables matrix
\newcommand{\loadings}{A} % factor loadings matrix
\newcommand{\rotation}{R}  % rotation matrix
\newcommand{\similaritys}{\mathfrak{S}} % a similarity graph
\newcommand{\similarity}{s} % A similarity measure.
\newcommand{\dissimilarity}{d} % A dissimilarity measure.
\newcommand{\dissimilaritys}{\mathfrak{D}} % a dissimilarity graph
\newcommand{\scalar}[2]{\left< #1,#2 \right>} % a scalar product

\newcommand{\manifold}{\mathcal{M}} % A manifold.
\newcommand{\project}{\hookrightarrow} % The orthogonal projection operator.
\newcommand{\projectMat}{H} % A projection matrix.
\newcommand{\rank}{q} % A subspace rank.
\newcommand{\dimy}{K} % The dimension of the output.
\newcommand{\encode}{E} % a linear encoding matrix
\newcommand{\decode}{D} % a linear decoding matrix
\DeclareMathOperator{\Tr}{Tr}
\newcommand{\ensembleSize}{M} % Size of a hypothesis ensemble.
\newcommand{\ensembleInd}{m} % Index of a hypothesis in an ensemble.

\newcommand{\sample}{\mathcal{S}} % A data sample.
\newcommand{\test}{\risk(\hyp)} % The test error (risk)
\newcommand{\train}{\riskn(\hyp)} % The train error (empirical risk)
\newcommand{\insample}{\bar{\risk}(\hyp)} % The in-sample test error.
\newcommand{\EPE}{\risk(\hat{\hyp}_n)} % The out-of-sample test error.
\newcommand{\folds}{K} % Cross validation folds
\newcommand{\fold}{k} % Index of a fold
\newcommand{\bootstraps}{B} % Bootstrap samples
\newcommand{\bootstrap}{{b^*}} % Index of a bootstrap replication

\newcommand{\rankings}{\mathcal{R}} % Rankings, for colaborative filtering.
\newcommand{\ranking}{\mathcal{R}} % Rankings, for colaborative filtering.
\newcommand{\KL}[2]{D_{KL}\left(#1 \Vert #2 \right)}
\newcommand{\ortho}{\mathbb{O}} % space of orthogonal matrices

\newcommand{\id}[6]{
	\begin{tabular}{|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|}
	\hline Task & Type & Input & Output & Concept & Remark \\
	\hline
	\hline #1 & #2 & #3 & #4 & #5 & #6 \\
	\hline
	\end{tabular}
	\newline
	\newline
}

\newcommand{\union}{\cup}
\newcommand{\intersect}{\cap}
\newcommand{\supp}[1]{\mathop{support}(#1)}
\newcommand{\conf}[2]{\mathop{confidence}(#1 \Rightarrow #2)}
\newcommand{\lift}[2]{\mathop{lift}(#1 \Rightarrow #2)}
\newcommand{\convic}[2]{\mathop{conviction}(#1 \Rightarrow #2)}

\newcommand{\machine}[1]{\estim{\theta}_n^{(#1)}}
\newcommand{\minimizer}{\theta^*}
\newcommand{\generative}{\theta_0}
\newcommand{\parallelized}{\bar{\theta}_{N,m}}
\newcommand{\parallelizedII}{\mathring{\theta}_{N,m}}
\newcommand{\parallelizedIII}{\prescript{}{2}{\widehat{\theta}}_{N,m}}
\newcommand{\centralized}{\estim{\theta}_N}
\newcommand{\parallelKL}{\estim{\theta}_{KL}}
\newcommand{\penalize}{J}
\newcommand{\bigO}{\mathcal{O}}
\newcommand{\bigOprob}{\mathcal{O}_P}
\newcommand{\smallO}{o}
\newcommand{\smallOprob}{o_P}

\newcommand{\citeJR}[1]{\citeauthor{#1} \citep{#1}}
\newcommand{\citeJRfull}[1]{\citeauthor*{#1} \citep{#1}}
\newcommand{\error}{\mathcal{E}}

\newcommand{\M}{$M$}
\newcommand{\MII}{$\prescript{}{2}{M}$}

\newcommand{\biasSecond}[1]{B_2(#1)}
\newcommand{\MSESecond}[1]{M_2(#1)}

\newcommand{\rate}{r}

\newcommand{\emptyfigure}[1]{\missingfigure[figwidth=6cm]{#1}}

% % Time line
%\usepackage[paperwidth=210mm,%
%    paperheight=297mm,%
%    tmargin=7.5mm,%
%    rmargin=7.5mm,%
%    bmargin=7.5mm,%
%    lmargin=7.5mm,
%    vscale=1,%
%    hscale=1]{geometry}
%
%\usepackage[utf8]{inputenc}
%\usepackage[T1]{fontenc}

\usepackage{tikz}
\usetikzlibrary{arrows, calc, decorations.markings, positioning}

\makeatletter
\newenvironment{timeline}[6]{%
    % #1 is startyear
    % #2 is tlendyear
    % #3 is yearcolumnwidth
    % #4 is rulecolumnwidth
    % #5 is entrycolumnwidth
    % #6 is timelineheight

    \newcommand{\startyear}{#1}
    \newcommand{\tlendyear}{#2}

    \newcommand{\yearcolumnwidth}{#3}
    \newcommand{\rulecolumnwidth}{#4}
    \newcommand{\entrycolumnwidth}{#5}
    \newcommand{\timelineheight}{#6}

    \newcommand{\templength}{}

    \newcommand{\entrycounter}{0}

    % http://tex.stackexchange.com/questions/85528/checking-whether-or-not-a-node-has-been-previously-defined
    % http://tex.stackexchange.com/questions/37709/how-can-i-know-if-a-node-is-already-defined
    \long\def\ifnodedefined##1##2##3{%
        \@ifundefined{pgf@sh@ns@##1}{##3}{##2}%
    }

    \newcommand{\ifnodeundefined}[2]{%
        \ifnodedefined{##1}{}{##2}
    }

    \newcommand{\drawtimeline}{%
        \draw[timelinerule] (\yearcolumnwidth+5pt, 0pt) -- (\yearcolumnwidth+5pt, -\timelineheight);
        \draw (\yearcolumnwidth+0pt, -10pt) -- (\yearcolumnwidth+10pt, -10pt);
        \draw (\yearcolumnwidth+0pt, -\timelineheight+15pt) -- (\yearcolumnwidth+10pt, -\timelineheight+15pt);

        \pgfmathsetlengthmacro{\templength}{neg(add(multiply(subtract(\startyear, \startyear), divide(subtract(\timelineheight, 25), subtract(\tlendyear, \startyear))), 10))}
        \node[year] (year-\startyear) at (\yearcolumnwidth, \templength) {\startyear};

        \pgfmathsetlengthmacro{\templength}{neg(add(multiply(subtract(\tlendyear, \startyear), divide(subtract(\timelineheight, 25), subtract(\tlendyear, \startyear))), 10))}
        \node[year] (year-\tlendyear) at (\yearcolumnwidth, \templength) {\tlendyear};
    }

    \newcommand{\entry}[2]{%
        % #1 is the year
        % #2 is the entry text

        \pgfmathtruncatemacro{\lastentrycount}{\entrycounter}
        \pgfmathtruncatemacro{\entrycounter}{\entrycounter + 1}

        \ifdim \lastentrycount pt > 0 pt%
            \node[entry] (entry-\entrycounter) [below of=entry-\lastentrycount] {##2};
        \else%
            \pgfmathsetlengthmacro{\templength}{neg(add(multiply(subtract(\startyear, \startyear), divide(subtract(\timelineheight, 25), subtract(\tlendyear, \startyear))), 10))}
            \node[entry] (entry-\entrycounter) at (\yearcolumnwidth+\rulecolumnwidth+10pt, \templength) {##2};
        \fi

        \ifnodeundefined{year-##1}{%
            \pgfmathsetlengthmacro{\templength}{neg(add(multiply(subtract(##1, \startyear), divide(subtract(\timelineheight, 25), subtract(\tlendyear, \startyear))), 10))}
            \draw (\yearcolumnwidth+2.5pt, \templength) -- (\yearcolumnwidth+7.5pt, \templength);
            \node[year] (year-##1) at (\yearcolumnwidth, \templength) {##1};
        }

        \draw ($(year-##1.east)+(2.5pt, 0pt)$) -- ($(year-##1.east)+(7.5pt, 0pt)$) -- ($(entry-\entrycounter.west)-(5pt,0)$) -- (entry-\entrycounter.west);
    }

    \newcommand{\plainentry}[2]{% plainentry won't print date in the timeline
        % #1 is the year
        % #2 is the entry text

        \pgfmathtruncatemacro{\lastentrycount}{\entrycounter}
        \pgfmathtruncatemacro{\entrycounter}{\entrycounter + 1}

        \ifdim \lastentrycount pt > 0 pt%
            \node[entry] (entry-\entrycounter) [below of=entry-\lastentrycount] {##2};
        \else%
            \pgfmathsetlengthmacro{\templength}{neg(add(multiply(subtract(\startyear, \startyear), divide(subtract(\timelineheight, 25), subtract(\tlendyear, \startyear))), 10))}
            \node[entry] (entry-\entrycounter) at (\yearcolumnwidth+\rulecolumnwidth+10pt, \templength) {##2};
        \fi

        \ifnodeundefined{invisible-year-##1}{%
            \pgfmathsetlengthmacro{\templength}{neg(add(multiply(subtract(##1, \startyear), divide(subtract(\timelineheight, 25), subtract(\tlendyear, \startyear))), 10))}
            \draw (\yearcolumnwidth+2.5pt, \templength) -- (\yearcolumnwidth+7.5pt, \templength);
            \node[year] (invisible-year-##1) at (\yearcolumnwidth, \templength) {};
        }

        \draw ($(invisible-year-##1.east)+(2.5pt, 0pt)$) -- ($(invisible-year-##1.east)+(7.5pt, 0pt)$) -- ($(entry-\entrycounter.west)-(5pt,0)$) -- (entry-\entrycounter.west);
    }

    \begin{tikzpicture}
        \tikzstyle{entry} = [%
            align=left,%
            text width=\entrycolumnwidth,%
            node distance=10mm,%
            anchor=west]
        \tikzstyle{year} = [anchor=east]
        \tikzstyle{timelinerule} = [%
            draw,%
            decoration={markings, mark=at position 1 with {\arrow[scale=1.5]{latex'}}},%
            postaction={decorate},%
            shorten >=0.4pt]

        \drawtimeline
}
{
    \end{tikzpicture}
    \let\startyear\@undefined
    \let\tlendyear\@undefined
    \let\yearcolumnwidth\@undefined
    \let\rulecolumnwidth\@undefined
    \let\entrycolumnwidth\@undefined
    \let\timelineheight\@undefined
    \let\entrycounter\@undefined
    \let\ifnodedefined\@undefined
    \let\ifnodeundefined\@undefined
    \let\drawtimeline\@undefined
    \let\entry\@undefined
}
\makeatother
% % % % %

\newcommand{\R}{\textnormal{\sffamily\bfseries R }}

% Process capability notation
\newcommand{\targetValue}{T}% target value
\newcommand{\cp}{C_p}% c_p
\newcommand{\cpHat}{\hat{C}_p}% c_p
\newcommand{\ctqExpect}{\mu}
\newcommand{\pnc}{p_{NC}}
\newcommand{\cpu}{C_{pu}}
\newcommand{\cpl}{C_{pl}}
\newcommand{\cpk}{C_{pk}}
\newcommand{\cpkHat}{\hat{C}_{pk}}
\newcommand{\cpm}{C_{pm}}
\newcommand{\cpmHat}{\hat{C}_{pm}}
\newcommand{\cpq}{C_p(q)}
\newcommand{\pp}{P_{p}}
\newcommand{\ppk}{P_{pk}}

\newcommand{\barxChart}{$\bar{x}$-chart}
\newcommand{\sigmabar}{\sigma_{\bar{x}}}
\newcommand{\aka}{{a.k.a.\ }}
\newcommand{\Aka}{{A.k.a.\ }}
\newcommand{\rcode}[1]{\texttt{#1}}
\newcommand{\arm}{L}

\newcommand{\tsq}{$T^2$ }
\newcommand{\struct}{\Phi}
\newcommand{\exppdf}[2]{#1 e^{-#1 #2}}
\newcommand{\expcdf}[2]{e^{-#1 #2}}

\newcommand{\conv}{\ast}
\newcommand{\range}[1]{Range(#1)}

\newcommand{\dif}{\mathrm{d}}


\section{Simulation extractability of $\plonk$, omitted proofs}
\label{sec:plonkse_proofs}

%\oursubsub{Proof of \cref{lem:plonkprot_ur}}

\begin{lemma}[\cref{lem:plonkprot_ur} restated]
	\label{lem:app:plonkprot_ur}
	Let $\PCOMp$ be a polynomial commitment that is $\epsbind(\secpar)$-binding and has unique opening property with loss $\epsop (\secpar)$, let $(\noofc + 5, 1)$-$\udlog$ problem be $\epsudlog (\secpar)$ hard. Then $\plonkprotfs$ is $\ur{3}$ against algebraic adversaries, who makes up to $q$ random oracle queries, with security loss $8  \cdot \epsbinding (\secpar) + \epsudlog (\secpar) + 2 \infrac{q}{p}$.
\end{lemma}

\begin{proof}
    Let $\adv$ be an algebraic adversary tasked to break the $\ur{3}$-ness of
      $\plonkprotfs$. We show that the first three prover's messages determine, along with 	the verifiers challenges, the rest of it. We denote by $\zkproof^0$ and $\zkproof^1$ the two proofs that the adversary outputs. To distinguish polynomials and commitments which an honest prover would send in the proof from the polynomials and commitments computed by the adversary we write the latter using indices $0$ and $1$ (two indices as we have two transcripts), e.g.~to describe the quotient polynomial provided by the adversary we write $\p{t}^0$ and $\p{t}^1$ instead of $\p{t}$ as in the description of the protocol.

    We note that since the unique response property requires from $\zkproof^{0}$ and $\zkproof^{1}$ that the first place they possibly differ is the $4$-th prover's message, then the challenge $\chz$, that is picked by the adversary after the $3$-rd message is the same in both transcripts. This challenge determines the evaluation point of polynomials $\p{a}(X), \p{b}(X), \p{c}(X), \p{t}(X), \p{z}(X)$ which commitments are already sent.

    In its fourth message, the prover provides evaluations of the aforementioned polynomials, along with evaluations of publicly known polynomials $
    \p{S_{\sigma 1}} (\chz), \p{S_{\sigma 2}} (\chz)$, and evaluation of a linearization polynomial $\p{r}(\chz)$.

    Note that the adversary can output two accepting proofs that differ on their fourth message only if it either manages to break evaluation binding of one of the opening, or provides an incorrect opening which is accepted due to a batching error. Since the commitment scheme is evaluation binding with security loss $\epsbinding (\secpar)$, %and the batched verification equation accepts an incorrect opening with probability at most $\infrac{q}{p}$, cf.~\cite{EPRINT:GabWilCio19},
	the adversary can make $\zkproof^{0}$ and $\zkproof^{1}$ differ on the fourth message with the same probability. % at most $8  \cdot \epsbinding (\secpar) + \infrac{q}{p}$.

    Next, assume that the transcripts are the same up to the fourth message, but differ at the fifth. In that message, the adversary provides openings of the evaluations. Since the unique opening property, the adversary can open the valid evaluation of a polynomial to two different values with probability at most $\epsop (\secpar)$. (We note that for the KZG polynomial commitment scheme, as used in \cite{EPRINT:GabWilCio19}, $\epsop (\secpar) \leq \epsudlog (\secpar) + \infrac{q}{p}$, cf.~\cref{lem:pcomp_op}.)
    % , which is upper-bounded by $\epsudlog (\secpar) + \infrac{q}{p}$, cf.~\cref{lem:pcomp_op}.

    By the union bound, the adversary is able to break the unique response property with probability upper bounded by $\epsbinding (\secpar) + \epsop (\secpar)$.
    \qed
    \end{proof}

%\oursubsub{Proof of \cref{lem:plonkprot_ss}}

\begin{lemma}[\cref{lem:plonkprot_ss} restated]
	\label{lem:app:plonkprot_ss}
	$\plonkprotfs$ is $(3, 3 \noofc + 6)$-rewinding-based knowledge sound against algebraic adversaries who make up to $q$ random oracle queries with security loss
	\[
	\epscss(\secpar,\accProb, q) \leq \left(1 - \frac{\accProb - (q + 1) \left(\frac{3 \noofc + 5}{p} \right)}{1 - \frac{3 \noofc + 5}{p}}\right) + (3 \noofc + 6) \cdot \epsudlog (\secpar)\,,
	\]

	Here $\accProb$ is a probability that the adversary outputs an accepting proof, and $\epsudlog(\secpar)$ is security of $(\numberofconstrains + 5, 1)$-$\udlog$.
\end{lemma}

\begin{proof}
	Let $\adv^{\ro, \initU}(\secparam; r)$ be the adversary who outputs $(\inp, \zkproof)$ such that $\plonkprotfs.\verifier$ accepts the proof. Let $\tdv$ be a tree-building algorithm of \cref{lem:attema} that outputs a tree $\tree$, and let $\extcss$ be an extractor that given the tree output by $\tdv$ reveals the witness for $\inp$. The main idea of the proof is to show that an adversary who breaks rewinding-based knowledge soundness can be used to break a $\udlog$-problem instance. The proof goes by game hops. Note that since the tree branches after $\adv$'s $3$-rd message, the instance $\inp$, commitments $\gone{\p{a} (\chi), \p{b} (\chi), \p{c} (\chi), \p{z} (\chi), \p{t_{lo}} (\chi), \p{t_{mid}} (\chi), \p{t_{hi}} (\chi)}$, and challenges $\alpha, \beta, \gamma$ are the same in all the transcripts. Also, the tree branches after the third adversary's message where the challenge $\chz$ is presented, thus tree $\tree$ is built using different values of $\chz$.	We consider the following games.

  \ncase{Game 0} %
  In this game the adversary wins if it outputs a valid instance--proof pair $(\inp, \zkproof)$, and the extractor $\extcss$ does not manage to output a witness $\wit$ such that $\REL (\inp, \wit)$ holds.

  \ncase{Game 1} %
  In this game the environment aborts the game if the tree building algorithm $\tdv$ fails in building a tree of accepting transcripts $\tree$.

  \ncase{Game 0 to Game 1} %
  By \cref{lem:attema} probability that Game 1 is aborted, while Game 0 is not, is at most
  %\hamid{2.5}{Should this not be "1 minus the following"?}
  \[
    1 - \frac{\accProb - (q + 1) \left(\frac{3 \noofc + 5}{p} \right)} {1 - \frac{3 \noofc + 5}{p}} \,.
  \]

  \ncase{Game 2} %
  In this game the environment additionally aborts if at least one of its proofs in $\tree$ is not accepting by an ideal verifier.

  \ncase{Game 1 to Game 2} %
  As usual, we show a reduction that breaks an instance of a $\udlog$ assumption when Game 2 is aborted, while Game 1 is not.

  Let $\rdvudlog$ be a reduction that gets as input an $(\noofc + 5, 1)$-$\udlog$ instance $\gone{1, \ldots, \chi^{\noofc + 5}}, \gtwo{\chi}$. Then it can update the instance to another one $\gone{1, \ldots, {\chi'}^{\noofc + 5}}, \gtwo{\chi'}$. Eventually, the reduction outputs $\chi'$.
	%
	The reduction $\rdvudlog$ proceeds as follows.
	First, it builds $\adv$'s SRS $\srs$ using the input $\udlog$ instance. Then it processes the adversary's update query by adding it to the list $\Qsrs$ and passing it to its own update oracle getting instance $\gone{1, \ldots, {\chi'}^{\noofc + 5}}, \gtwo{\chi'}$. The updated SRS $\srs'$ is then computed and given to $\adv$. $\rdvdulog$ also takes care of the random oracle queries made by $\adv$. It picks their answers honestly and write them in $\Qro$. The reduction then starts $\tdv(\srs, \adv, r, \Qro, \Qsrs)$.

  Let $(1, \tree)$ be the output returned by $\tdv$. Let $\inp$ be a relation proven in $\tree$.  Consider a transcript $\zkproof \in \tree$ such that $\vereq_{\inp, \zkproof}(X) \neq 0$, but $\vereq_{\inp, \zkproof}(\chi') = 0$. Since $\adv$ is algebraic, all group elements included in $\tree$ are extended by their representation as a combination of the input $\GRP_1$-elements. Hence, all coefficients of the verification equation polynomial $\vereq_{\inp, \zkproof}(X)$ are known.
  Eventually, the reduction finds $\vereq_{\inp, \zkproof}(X)$ zero points and returns $\chi'$ which is one of them.

  Hence, the probability that the adversary wins in Game 2 but does not win in Game 1 is upper-bounded by $(3 \noofc + 6) \cdot \epsudlog (\secpar)$.

  \ncase{Conclusion}

  Note that the adversary can win in Game 2 only if $\tdv$ manages to produce a tree of accepting transcripts $\tree$, such that each of the transcripts in $\tree$ is accepting by an ideal verifier. Note that since $\tdv$ produces $(3 \noofc + 6)$ accepting transcripts for different challenges $\chz$, it obtains the same number of different evaluations of polynomials $\p{a} (X), \p{b} (X), \p{c} (X), \p{z} (X), \p{t} (X)$. Since all the transcripts are accepting by an idealized verifier, the equality between polynomial $\p{t} (X)$ and combination of polynomials $\p{a} (X), \p{b} (X), \p{c} (X), \p{z} (X)$ defined in prover's $3$-rd message description holds. Hence, $\p{a} (X), \p{b} (X), \p{c} (X)$ encodes the valid witness for the proven statement. $\extcss$ can recreate polynomials' coefficients by interpolation and reveal the witness given $(3 \noofc + 6)$ evaluations.
  % Thus, the probability that extraction fails in that case is upper-bounded by $(3 \noofc + 6) \cdot \epsid(\secpar)$.

  Hence, the probability that the adversary wins in Game 0 is upper-bounded by
  \[
    \epscss(\secpar,\accProb, q) \leq \left(1 - \frac{\accProb - (q + 1) \left(\frac{3 \noofc + 5}{p} \right)}{1 - \frac{3 \noofc + 5}{p}}\right) + (3 \noofc + 6) \cdot \epsudlog (\secpar)\,.
  \]
  \qed
 \end{proof}

%\oursubsub{Proof of \cref{lem:plonk_tlzk}}
\begin{lemma}[\cref{lem:plonk_tlzk} restated]
	\label{lem:app:plonk_tlzk}
	$\plonkprotfs$ is 3-programmable trapdoor-less zero-knowledge.
\end{lemma}

\begin{proof}
    As noted in \cref{def:upd-scheme}, subvertible zero-knowledge implies updatable zero-knowledge. Hence, here we show that Plonk is TLZK even against adversaries who picks
    the SRS on its own.

  The adversary $\adv(\secparam)$ picks an SRS $\srs$ and instance--witness pair
  $(\inp, \wit)$ and gets a proof $\zkproof$ simulated by the simulator
  $\simulator$ which proceeds as follows.

  For its $1$-st message the simulator  picks randomly both the randomizers $b_1, \ldots, b_6$ and
  sets $\wit_i = 0$ for $i \in \range{1}{3\noofc}$. Then $\simulator$
  outputs $\gone{\p{a}(\chi), \p{b}(\chi), \p{c}(\chi)}$. For the first
  challenge, the simulator picks permutation argument challenges $\beta, \gamma$
  randomly.

  For its $2$-nd message, the simulator computes $\p{z}(X)$ from
  the newly picked randomizers $b_7, b_8, b_9$ and coefficients of polynomials
  $\p{a}(X), \p{b}(X), \p{c}(X)$. Then it evaluates $\p{z}(X)$ honestly and outputs
  $\gone{\p{z}(\chi)}$. Challenge $\alpha$ that should be sent by the verifier
  after the simulator's $2$ message is picked by the simulator at random.

  In its $3$-rd message the simulator starts by picking at random a challenge $\chz$, which
  in the real proof comes as a challenge from the verifier sent \emph{after} the prover
  sends its $3$-rd message. Then $\simulator$ computes evaluations
  \(\p{a}(\chz), \p{b}(\chz), \p{c}(\chz), \p{S_{\sigma 1}}(\chz), \p{S_{\sigma
      2}}(\chz), \pubinppoly(\chz), \lag_1(\chz), \p{Z_H}(\chz),\allowbreak
  \p{z}(\chz\omega)\) and computes $\p{t}(X)$ honestly. Since for a random
  $\p{a}(X), \p{b}(X), \p{c}(X), \p{z}(X)$ the constraint system is (with
  overwhelming probability) not satisfied and the constraints-related polynomials
  are not divisible by $\p{Z_H}(X)$, hence $\p{t}(X)$ is a rational function
  rather than a polynomial. Then, the simulator evaluates $\p{t}(X)$ at $\chz$ and
  picks randomly a degree-$(3 \noofc + 15)$ polynomial $\p{\tilde{t}}(X)$ such that
  $\p{t}(\chz) = \p{\tilde{t}}(\chz)$ and publishes a commitment
  $\gone{\p{\tilde{t}_{lo}}(\chi), \p{\tilde{t}_{mid}}(\chi),
    \p{\tilde{t}_{hi}}(\chi)}$. After that the simulator outputs $\chz$ as a
  challenge.

  For the next message, the simulator computes polynomial $\p{r}(X)$ as an honest
  prover would, cf.~\cref{sec:plonk_explained} and evaluates $\p{r}(X)$ at $\chz$.

  The rest of the evaluations are already computed, thus $\simulator$ simply outputs
  \( \p{a}(\chz), \p{b}(\chz), \p{c}(\chz), \p{S_{\sigma 1}}(\chz), \p{S_{\sigma
      2}}(\chz), \p{t}(\chz), \p{z}(\chz \omega)\,.  \) After that it picks randomly
  the challenge $v$, and prepares the the last message as an honest prover
  would. Eventually, $\simulator$ and outputs the final challenge, $u$, by picking it
  at random as well.

  We argue about zero-knowledge as usual. The property holds since the polynomials that has witness elements at their coefficients are randomized by at least two randomizers and are evaluated at at most two points; and the simulator computes all polynomials as an honest prover would.
  \qed
  \end{proof}


%This is test for LaTeX syntax
\documentclass[a4paper,12pt]{article}
\begin{document}

%Title
\title{My First Document}
\author{My Name}
\date{\today}
\maketitle

%Sections
\section{Introduction}
This is the introduction.

%Labelling
Referring to section \ref{sec1} on page \pageref{sec1}

%Table of Contents
\pagenumbering{roman}
\tableofcontents
\newpage
\pagenumbering{arabic}

%Font Effects
\textit{words in italics}
\textsl{words slanted}
\textsc{words in smallcaps}
\textbf{words in bold}
\texttt{words in teletype}
\textsf{sans serif words}
\textrm{roman words}
\underline{underlined words}

%Coloured Text
{\color{colour_name}text}

%Font Sizes
{\tiny tiny words}
{\scriptsize scriptsize words}
{\footnotesize footnotesize words}
{\small small words}
{\normalsize normalsize words}
{\large large words}
{\Large Large words}
{\LARGE LARGE words}
{\huge huge words}

%Lists
\begin{itemize}
\item[-] First thing
\item[+] Second thing
\begin{itemize}
\item[Fish] A sub-thing
\item[Plants] Another sub-thing
\end{itemize}
\item[Q] Third thing
\end{itemize}

%Tables
\begin{tabular}{|l|l|}
Apples & Green \\
Strawberries & Red \\
Oranges & Orange \\
\end{tabular}

%Figures
\begin{figure}[h]
\centering
\includegraphics[width=1\textwidth]{image}
\caption{Here is image}
\label{image}
\end{figure}

%Mathematical
$\sin(x)$
$$\sin(x)$$
\[\sin(x)\]
\(\sin(x)\)

\begin{equation}1+2=3\end{equation}
\begin{eqnarray}
  a & = & b + c \\
    & = & y - z
\end{eqnarray}
$\alpha$ = α
$\beta$ = β
$\delta, \Delta$ = δ, ∆
$\theta, \Theta$ = θ, Θ

%Comments
\begin{comment}
This is a comment.
\end{comment}

%Lstlistings|Minted
\lstdefinelanguage{JavaScript}{
    morestring=[b]`
}

\lstset{language=JavaScript}
\begin{lstlisting}
    let x = `this is a ${string}`
\end{lstlisting}

\begin{minted}{python}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1
                VT[(i)*n + c[k]] = 1
                VT[(j)*n + r[k]] = 1
                VT[(j)*n + c[k]] = 1

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{minted}

\begin{VerbatimOut}{ex-scala-logstage.tmp}
    class ExampleService(log: IzLogger) {
      val justAnArg = "example"
      val justAList = List[Any](10, "green", "bottles")
      val msec = Random.nextInt(1000)
      log.trace(s"Argument: $justAnArg, another arg: $justAList")
      log.info(s"Expr: ${Random.nextInt() -> "number"}")
      log.warn(s"Hidden: ${Random.nextInt() -> "number" -> null}")
      val ctxLog = log("userId" -> "user@google.com"
        , "company" -> "acme")
      ctxLog.info(s"Processing time: $msec")
    }
\end{VerbatimOut}

\end{document}
\documentclass{article}


\chapter*{Resonators}
<<<<<<< HEAD
Though the physical models described in the previous part are also considered resonators, they are \textit{ideal} cases. In other words, you would not be able to find these ``in the wild'' as they do not includes effects such as losses or frequency dispersion.

This part presents the different resonators used over the course of the project and is structured as follows: Chapter \ref{ch:stiffString} introduces the stiff string, a model which has been used a lot over the course of this project, Chapter \ref{ch:brass} talks about brass instruments, or more generally, 1D systems of varying geometry along their spatial dimension. Finally, Chapter \ref{ch:2Dsyst} will introduces 2D systems which, in this project, have been used to simulate (simplified) instrument bodies.
=======
Although the physical models described in the previous part -- the simple mass-spring system and the 1D wave equation -- are also considered resonators, they are \textit{ideal} cases. In other words, these can not be found in the real world as effects such as losses or frequency dispersion are not included.

This part presents the different resonators used over the course of the project that better include these non-ideal physical processes and is structured as follows: Chapter \ref{ch:stiffString} introduces the stiff string, an extension of the 1D wave equation, % and is the single most-used model in this project.
Chapter \ref{ch:brass} introduces acoustic tubes, used to model brass instruments, and finally, Chapter \ref{ch:2Dsyst} introduces 2D systems which, in this project, have been used to simulate (simplified) instrument bodies. The analysis techniques introduced in the previous part will be applied to all models and described in detail.
>>>>>>> master


% Part: first-order-logic
% Chapter: sequent-calculus
% Section: propositional-rules

\documentclass[../../../include/open-logic-section]{subfiles}

\begin{document}

\olfileid{mvl}{seq}{prl}

\olsection{Propositional Rules for Selected Logics}

The inference rules for a connective in an $n$-sided sequent calculus
only depend on the characteristic truth function for the connective.
Thus, if some connective is defined by the same truth function in
different logics, these $n$-sided sequent rules for the connective are
the same in those logics.

\subsection{Rules for $\lnot$}

The following rules for $\lnot$ apply to \L ukasiewicz and Kleene
logics, and their variants.

\begin{defish}
  \begin{center}
\AxiomC{$ \Gamma \nSequent \Pi \nSequent \Delta, !A $}
\RightLabel{\iR{\lnot}{\False}}
\UnaryInfC{$ \lnot !A, \Gamma \nSequent \Pi \nSequent \Delta$}
\DisplayProof
\\[2ex]
\AxiomC{$ \Gamma \nSequent !A, \Pi \nSequent \Delta $}
\RightLabel{\iR{\lnot}{\Undef}}
\UnaryInfC{$\Gamma \nSequent \lnot !A, \Pi \nSequent \Delta$}
\DisplayProof
\\[2ex]
\AxiomC{$!A, \Gamma \nSequent \Pi \nSequent \Delta$}
\RightLabel{\iR{\lnot}{\True}}
\UnaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta,  \lnot !A$}
\DisplayProof
  \end{center}
\end{defish}

The following rules for $\lnot$ apply to G\"odel logic.

\begin{defish}
\AxiomC{$ \Gamma \nSequent !A, \Pi \nSequent \Delta, !A $}
\RightLabel{\iR{\lnot}{\False}[\LogGod]}
\UnaryInfC{$ \lnot !A, \Gamma \nSequent \Pi \nSequent \Delta$}
\DisplayProof
\hfill
\AxiomC{$!A, \Gamma \nSequent \Pi \nSequent \Delta$}
\RightLabel{\iR{\lnot}{\True}[\LogGod]}
\UnaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta,  \lnot !A$}
\DisplayProof
\hfill
\end{defish}

(In G\"odel logic, $\lnot !A$ can never take the value~$\Undef$, so
there is no rule for the middle position.)

\subsection{Rules for $\land$}

These are the rules for $\land$ in \L ukasiewicz, strong Kleene, and
G\"odel logic.

\begin{defish}
\begin{center}
  \AxiomC{$!A, !B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \RightLabel{$\iR{\land}{\False}$}
  \UnaryInfC{$!A \land !B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \DisplayProof
\\[2ex]
  \AxiomC{$\Gamma \nSequent !A, \Pi \nSequent !A, \Delta$}
  \AxiomC{$\Gamma \nSequent !B, \Pi \nSequent !B, \Delta$}
  \AxiomC{$\Gamma \nSequent !A, !B, \Pi \nSequent \Delta$}
  \RightLabel{$\iR\land\Undef$}
  \TrinaryInfC{$\Gamma \nSequent !A \land !B, \Pi \nSequent \Delta$}
  \DisplayProof
  \\[2ex]
  \AxiomC{$\Gamma \nSequent \Pi \nSequent \Delta, !A$}
  \AxiomC{$\Gamma \nSequent \Pi \nSequent \Delta, !B$}
  \RightLabel{$\iR\land\True$}
  \BinaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta, !A \land !B$}
  \DisplayProof
\end{center}
\end{defish}

\subsection{Rules for $\lor$}

These are the rules for $\lor$ in \L ukasiewicz, strong Kleene, and
G\"odel logic.

\begin{defish}
\begin{center}
 \AxiomC{$!A, \Gamma \nSequent \Pi \nSequent \Delta$}
  \AxiomC{$!B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \RightLabel{$\iR\lor\False$}
  \BinaryInfC{$!A \lor !B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \DisplayProof
\\[2ex]
  \AxiomC{$!A, \Gamma \nSequent !A, \Pi \nSequent \Delta$}
  \AxiomC{$!B, \Gamma \nSequent !B, \Pi \nSequent \Delta$}
  \AxiomC{$\Gamma \nSequent !A, !B, \Pi \nSequent \Delta$}
  \RightLabel{$\iR\lor\Undef$}
  \TrinaryInfC{$\Gamma \nSequent !A \lor !B, \Pi \nSequent \Delta$}
  \DisplayProof
  \\[2ex]
  \AxiomC{$\Gamma \nSequent \Pi \nSequent \Delta, !A, !B$}
  \RightLabel{$\iR\lor\True$}
  \UnaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta, !A \lor !B$}
  \DisplayProof
\end{center}
\end{defish}

\subsection{Rules for $\lif$}

These are the rules for $\lif$ in \L ukasiewicz logic.

\begin{defish}
\begin{center}
  \AxiomC{$\Gamma \nSequent \Pi \nSequent \Delta, !A$}
  \AxiomC{$!B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \RightLabel{$\iR\lif\False[\LogLuk[3]]$}
  \BinaryInfC{$!A \lif !B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \DisplayProof
  \\[2ex]
  \AxiomC{$\Gamma \nSequent !A, !B, \Pi \nSequent \Delta$}
  \AxiomC{$!B, \Gamma \nSequent \Pi \nSequent \Delta, !A$}
  \RightLabel{$\iR\lif\Undef[\LogLuk[3]]$}
  \BinaryInfC{$\Gamma \nSequent !A \lif !B, \Pi \nSequent \Delta$}
  \DisplayProof
\\[2ex]
  \AxiomC{$!A, \Gamma \nSequent !B, \Pi \nSequent \Delta, !B$}
  \AxiomC{$!A, \Gamma \nSequent !A, \Pi \nSequent \Delta, !B$}
  \RightLabel{$\iR{\lif}{\True}[\LogLuk[3]]$}
  \BinaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta, !A \lif !B$}
  \DisplayProof
\end{center}
\end{defish}

These are the rules for $\lif$ in strong Kleene logic.

\begin{defish}
\begin{center}
  \AxiomC{$\Gamma \nSequent \Pi \nSequent \Delta, !A$}
  \AxiomC{$!B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \RightLabel{$\iR\lif\False[\LogKs]$}
  \BinaryInfC{$!A \lif !B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \DisplayProof
  \\[2ex]
  \AxiomC{$!B, \Gamma \nSequent !B, \Pi \nSequent \Delta$}
  \AxiomC{$\Gamma \nSequent !A, !B, \Pi \nSequent \Delta$}
  \AxiomC{$\Gamma \nSequent !A, \Pi \nSequent \Delta, !A$}
  \RightLabel{$\iR\lif\Undef[\LogKs]$}
  \TrinaryInfC{$\Gamma \nSequent !A \lif !B, \Pi \nSequent \Delta$}
  \DisplayProof
\\[2ex]
  \AxiomC{$!A, \Gamma \nSequent \Pi \nSequent \Delta, !B$}
  \RightLabel{$\iR{\lif}{\True}[\LogKs]$}
  \UnaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta, !A \lif !B$}
  \DisplayProof
\end{center}
\end{defish}

These are the rules for $\lif$ in G\"odel logic.

\begin{defish}
\begin{center}
  \AxiomC{$\Gamma \nSequent !A, \Pi \nSequent \Delta, !A$}
  \AxiomC{$!B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \RightLabel{$\iR\lif\False[\LogGod[3]]$}
  \BinaryInfC{$!A \lif !B, \Gamma \nSequent \Pi \nSequent \Delta$}
  \DisplayProof
  \\[2ex]
  \AxiomC{$\Gamma \nSequent !B, \Pi \nSequent \Delta$}
  \AxiomC{$\Gamma \nSequent \Pi \nSequent \Delta, !A$}
  \RightLabel{$\iR\lif\Undef[\LogGod[3]]$}
  \BinaryInfC{$\Gamma \nSequent !A \lif !B, \Pi \nSequent \Delta$}
  \DisplayProof
\\[2ex]
  \AxiomC{$!A, \Gamma \nSequent !B, \Pi \nSequent \Delta, !B$}
  \AxiomC{$!A, \Gamma \nSequent !A, \Pi \nSequent \Delta, !B$}
  \RightLabel{$\iR{\lif}{\True}[\LogGod[3]]$}
  \BinaryInfC{$\Gamma \nSequent \Pi \nSequent \Delta, !A \lif !B$}
  \DisplayProof
\end{center}
\end{defish}

\begin{sidewaysfigure}
  \begin{center}
  \AxiomC{$A \nSequent A \nSequent A$}
  \RightLabel{\iR \Weakening \True}
  \UnaryInfC{$A \nSequent A \nSequent B, A$}
  \RightLabel{\iR \Weakening \Undef}
  \UnaryInfC{$A \nSequent B, A \nSequent B, A$}
  \RightLabel{\iR \Weakening \Undef}
  \UnaryInfC{$A \nSequent A, B, A \nSequent B, A$}
  \AxiomC{$A \nSequent A \nSequent A$}
  \RightLabel{\iR \Weakening \True}
  \UnaryInfC{$A \nSequent A \nSequent A, A$}
  \RightLabel{\iR \Weakening \True}
  \UnaryInfC{$A \nSequent A \nSequent B, A, A$}
  \RightLabel{\iR \Weakening \False}
  \UnaryInfC{$B, A \nSequent A \nSequent B, A, A$}
  \RightLabel{$\iR\lif\Undef$}
  \BinaryInfC{$A \nSequent A \lif B, A \nSequent B, A$}
  \AxiomC{$B \nSequent B \nSequent B$}
  \RightLabel{\iR \Weakening \Undef}
  \UnaryInfC{$B \nSequent A, B \nSequent B$}
  \RightLabel{\iR \Exchange \Undef}
  \UnaryInfC{$B \nSequent B, A \nSequent B$}
  \RightLabel{\iR \Weakening \Undef}
  \UnaryInfC{$B \nSequent A, B, A \nSequent B$}
  \RightLabel{\iR \Weakening \False}
  \UnaryInfC{$A, B \nSequent A, B, A \nSequent B$}
  \RightLabel{\iR \Exchange \False}
  \UnaryInfC{$B, A \nSequent A, B, A \nSequent B$}
  \AxiomC{$A \nSequent A \nSequent A$}
  \RightLabel{\iR \Weakening \True}
  \UnaryInfC{$A \nSequent A \nSequent B, A$}
  \RightLabel{\iR \Weakening \False}
  \UnaryInfC{$B, A \nSequent A \nSequent B, A$}
  \RightLabel{\iR \Weakening \False}
  \UnaryInfC{$B, B, A \nSequent A \nSequent B, A$}
  \RightLabel{$\iR\lif\Undef$}
  \BinaryInfC{$B, A \nSequent A \lif B, A \nSequent B$}
  \RightLabel{$\iR\lif\False$}
  \BinaryInfC{$A \lif B, A \nSequent A \lif B, A \nSequent B$}
  \DisplayProof
  \end{center}
  \caption{Example !!{derivation} in~$\LogLuk[3]$}
\end{sidewaysfigure}

\end{document}


\ignore{
\documentstyle[11pt]{report}
\textwidth 13.7cm
\textheight 21.5cm
\newcommand{\myimp}{\verb+ :- +}
\newcommand{\ignore}[1]{}
\def\definitionname{Definition}

\makeindex
\begin{document}

}
\chapter{\label{chapter:predicates}Predicates and Functions}
In Picat, predicates\index{predicate} and functions\index{function} are defined with pattern-matching rules. Picat has two types of rules: the \emph{non-backtrackable} rule\index{non-backtrackable rule}
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $Head, Cond\ $\verb+=>+$\ Body$.
\end{tabbing}
and the \emph{backtrackable} rule\index{backtrackable rule}
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> $Head, Cond\ $\verb+?=>+$\ Body$.
\end{tabbing}
Each rule is terminated by a dot (\verb+.+) followed by a white space.

\section{Predicates}
A \emph{predicate}\index{predicate} defines a relation, and can have zero, one, or multiple answers. Within a predicate\index{predicate}, the $Head$ is a \emph{pattern} in the form $p(t_1,\ldots,t_n)$, where $p$ is called the predicate\index{predicate} \emph{name}, and $n$ is called the \emph{arity}\index{arity}. When $n=0$, the parentheses can be omitted. The condition $Cond$, which is an optional goal\index{goal}, specifies a condition under which the rule is applicable. $Cond$ cannot succeed more than once. The compiler converts $Cond$ to \texttt{once $Cond$}\index{\texttt{once}} if would otherwise be possible for $Cond$ to succeed more than once.

For a call $C$, if $C$ matches the pattern $p(t_1,\ldots,t_n)$ and $Cond$ is true, then the rule is said to be \emph{applicable} to $C$. When applying a rule to call $C$, Picat rewrites $C$ into $Body$. If the used rule is non-backtrackable\index{non-backtrackable rule}, then the rewriting is a commitment, and the program can never backtrack to $C$. However, if the used rule is backtrackable\index{backtrackable rule}, then the program will backtrack to $C$ once $Body$ fails, meaning that $Body$ will be rewritten back to $C$, and the next applicable rule will be tried on $C$.

A predicate\index{predicate} is said to be \emph{deterministic} if it is defined with non-backtrackable rules\index{non-backtrackable rule} only, \emph{non-deterministic} if at least one of its rules is backtrackable\index{backtrackable rule}, and \emph{globally deterministic} if it is deterministic and all of the predicates\index{predicate} in the bodies of the predicate's\index{predicate} rules are also globally deterministic. A deterministic predicate\index{predicate} that is not globally deterministic can still have more than one answer.

\subsection*{Example}
\begin{verbatim}
    append(Xs,Ys,Zs) ?=> Xs=[], Ys=Zs.
    append(Xs,Ys,Zs) => Xs=[X|XsR], append(XsR,Ys,Zs).

    min_max([H],Min,Max) => Min=H, Max=H.
    min_max([H|T],Min,Max) =>
        min_max(T,MinT,MaxT),
        Min=min(MinT,H),
        Max=max(MaxT,H).
\end{verbatim}
The predicate \texttt{append(Xs,Ys,Zs)}\index{\texttt{append/3}} is true if the concatenation of \texttt{Xs} and \texttt{Ys} is \texttt{Zs}. It defines a relation among the three arguments, and does not assume directionality of any of the arguments. For example, this predicate can be used to concatenate two lists, as in the call
\begin{verbatim}
    append([a,b],[c,d],L)
\end{verbatim}
this predicate can also be used to split a list nondeterministically into two sublists, as in the call \texttt{append(L1,L2,[a,b,c,d])}\index{\texttt{append/3}}; this predicate can even be called with three free variables, as in the call \texttt{append(L1,L2,L3)}\index{\texttt{append/3}}.

The predicate \texttt{min\_max(L,Min,Max)} returns two answers through its arguments.  It binds \texttt{Min} to the minimum of list \texttt{L}, and binds \texttt{Max} to the maximum of list \texttt{L}. This predicate does not backtrack. Note that a call fails if the first argument is not a list. Also note that this predicate consumes linear space. A tail-recursive\index{tail recursion} version of this predicate that consumes constant space will be given below.

\section{Functions}
A \emph{function}\index{function} is a special kind of a predicate\index{predicate} that always succeeds with \emph{one} answer. Within a function\index{function}, the $Head$ is an equation $p(t_1,\ldots, t_n)$\verb+=+$X$, where $p$ is called the function\index{function} \emph{name}, and $X$ is an \emph{expression} that gives the return value. Functions\index{function} are defined with non-backtrackable rules\index{non-backtrackable rule} only.

For a call $C$, if $C$ matches the pattern $p(t_1,\ldots,t_n)$ and $Cond$ is true, then the rule is said to be \emph{applicable} to $C$. When applying a rule to call $C$, Picat rewrites the equation $C$\verb+=+$X'$ into \texttt{($Body$, $X'$=$X$)}, where $X'$ is a newly introduced variable that holds the return value of $C$.

Picat allows inclusion of \emph{function facts}\index{function fact} in the form {\tt $p$($t_1$,$\ldots$,$t_n$)\verb+=+$Exp$} in function\index{function} definitions. The function fact\index{function fact} {\tt $p$($t_1$,$\ldots$,$t_n$)\verb+=+$Exp$} is shorthand for the rule:
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> {\tt $p$($t_1$,$\ldots$,$t_n$)\verb+=+$X$ \verb+=>+ $X\verb+=+Exp$.}
\end{tabbing}
where $X$ is a new variable.

Although all functions\index{function} can be defined as predicates\index{predicate}, it is preferable to define them as functions\index{function} for two reasons.  Firstly, functions\index{function} often lead to more compact expressions than predicates\index{predicate}, because arguments of function\index{function} calls can be other function\index{function} calls.  Secondly, functions\index{function} are easier to debug than predicates\index{predicate}, because functions\index{function} never fail and never return more than one answer.

\subsection*{Example}
\begin{verbatim}
    qequation(A,B,C) = (R1,R2),
        D = B*B-4*A*C,
        D >= 0
    =>
        NTwoC = -2*C,
        R1 = NTwoC/(B+sqrt(D)),
        R2 = NTwoC/(B-sqrt(D)).

    rev([]) = [].
    rev([X|Xs]) = rev(Xs)++[X].
\end{verbatim}
The function \texttt{qequation(A,B,C)} returns the pair of roots of \texttt{A*X$^2$+B*X+C=0}. If the discriminant \texttt{B*B-4*A*C} is negative, then an exception will be thrown.

The function \texttt{rev(L)} returns the reversed list of \texttt{L}. Note that the function \texttt{rev(L)} takes quadratic time and space in the length of \texttt{L}. A tail-recursive\index{tail recursion} version that consumes linear time and space will be given below.

\section{Patterns and Pattern-Matching}
The pattern $p(t_1,\ldots,t_n)$ in the head of a rule takes the same form as a structure. Function\index{function} calls are not allowed in patterns. Also, patterns cannot contain index notations, dot notations, ranges, array comprehensions, or list comprehensions. Pattern matching is used to decide whether a rule is applicable to a call. For a pattern $P$ and a term $T$, term $T$ matches pattern $P$ if $P$ is identical to $T$, or if $P$ can be made identical to $T$ by instantiating $P$'s variables. Note that variables in the term do not get instantiated after the pattern matching. If term $T$ is more general than pattern $P$, then the pattern matching can never succeed.

Unlike calls in many committed-choice languages, calls in Picat are never suspended if they are more general than the head patterns of the rules. A predicate\index{predicate} call fails if it does not match the head pattern of any of the rules in the predicate\index{predicate}. A function\index{function} call throws an exception if it does not match the head pattern of any of the rules in the function\index{function}. For example, for the function call \texttt{rev(L)}, where \texttt{L} is a variable, Picat will throw the following exception:

\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \> \texttt{unresolved\_function\_call(rev(L))}.
\end{tabbing}

A pattern can contain \emph{as-patterns}\index{as-pattern} in the form \texttt{$V$@$Pattern$}, where $V$ is a new variable in the rule, and $Pattern$ is a non-variable term. The as-pattern\index{as-pattern} \texttt{$V$@$Pattern$} is the same as \texttt{$Pattern$} in pattern matching, but after pattern matching succeeds, $V$ is made to reference the term that matched $Pattern$. As-patterns\index{as-pattern} can avoid re-constructing existing terms.

\subsection*{Example}
\begin{verbatim}
    merge([],Ys) = Ys.
    merge(Xs,[]) = Xs.
    merge([X|Xs],Ys@[Y|_]) = [X|Zs], X<Y => Zs=merge(Xs,Ys).
    merge(Xs,[Y|Ys]) = [Y|merge(Xs,Ys)].
\end{verbatim}
In the third rule, the as-pattern\index{as-pattern} \texttt{Ys@[Y|\_]} binds two variables: \texttt{Ys} references the second argument, and \texttt{Y} references the car\index{car} of the argument. The rule can be rewritten as follows without using any as-pattern\index{as-pattern}:
\begin{verbatim}
    merge([X|Xs],[Y|Ys]) = [X|Zs], X<Y => Zs=merge(Xs,[Y|Ys]).
\end{verbatim}
Nevertheless, this version is less efficient, because the cons\index{cons} \texttt{[Y|Ys]} needs to be re-constructed.

\section{Goals}
In a rule, both the condition and the body are \emph{goals}\index{goal}. Queries that the users give to the interpreter are also goals\index{goal}. A goal\index{goal} can take one of the following forms:
\begin{itemize}
\item \texttt{true}\index{\texttt{true}}: This goal\index{goal} is always true.
\item \texttt{fail}\index{\texttt{fail}}: This goal\index{goal} is always false. When \texttt{fail}\index{\texttt{fail}} occurs in a condition, the condition is false, and the rule is never applicable. When \texttt{fail}\index{\texttt{fail}} occurs in a body, it causes execution to backtrack.
\item \texttt{false}\index{\texttt{false}}: This goal is the same as \texttt{fail}.
\item $p(t_1, \ldots, t_n)$: This goal\index{goal} is a predicate call. The arguments $t_1, \ldots, t_n$ are evaluated in the given order, and the resulting call is resolved using the rules in the predicate $p/n$. If the call succeeds, then variables in the call may get instantiated. Many built-in predicates\index{predicate} are written in infix notation. For example, \texttt{X=Y} is the same as \texttt{'='(X,Y)}.
\item \texttt{$P$, $Q$}: This goal\index{goal} is a conjunction of goal\index{goal} $P$ and goal\index{goal} $Q$. It is resolved by first resolving $P$, and then resolving $Q$. The goal\index{goal} is true if both $P$ and $Q$ are true. Note that the order is important: ($P$, $Q$) is in general not the same as ($Q$, $P$).
\item \texttt{$P$ $\&\&$ $Q$}: This is the same as \texttt{($P$, $Q$)}.
\item \texttt{$P$; $Q$}: This goal\index{goal} is a disjunction of goal\index{goal} $P$ and goal\index{goal} $Q$. It is resolved by first resolving $P$. If $P$ is true, then the disjunction is true. If $P$ is false, then $Q$ is resolved. The disjunction is true if $Q$ is true. The disjunction is false if both $P$ and $Q$ are false. Note that a disjunction can succeed more than once. Note also that the order is important: ($P$; $Q$) is generally not the same as ($Q$; $P$).
\item \texttt{$P$ $|$$|$ $Q$}: This is the same as \texttt{($P$; $Q$)}.
\item \texttt{not $P$}\index{\texttt{not}}: This goal\index{goal} is the negation of $P$. It is false if $P$ is true, and true if $P$ is false.  Note a negation goal\index{goal} can never succeed more than once.  Also note that no variables can get instantiated, no matter whether the goal\index{goal} is true or false.
\item \texttt{once $P$}\index{\texttt{once}}: This goal\index{goal} is the same as $P$, but can never succeed more than once.
\item \texttt{repeat}\index{\texttt{repeat/0}}: This predicate is defined as follows:
\begin{verbatim}
    repeat ?=> true.
    repeat => repeat.
\end{verbatim}
The \texttt{repeat}\index{\texttt{repeat/0}} predicate is often used to describe failure-driven loops\index{failure-driven loop}. For example, the query
\begin{verbatim}
      repeat,writeln(a),fail
\end{verbatim}
repeatedly outputs \texttt{'a'} until \texttt{ctrl-c} is typed.
\item \texttt{if-then}\index{if statement}: An if-then statement takes the form
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{if $Cond_1$ then} \\
\> \> $Goal_1$ \\
\> \texttt{elseif $Cond_2$ then} \\
\> \> $Goal_2$ \\
\> \> $\vdots$ \\
\> \texttt{elseif $Cond_{n}$ then} \\
\> \> $Goal_{n}$ \\
\> \texttt{else} \\
\> \> $Goal_{else}$ \\
\> \texttt{end}
\end{tabbing}
where the \texttt{elseif} and \texttt{else} clauses are optional. If the \texttt{else} clause is missing, then the else goal\index{goal} is assumed to be \texttt{true}. For the if-then statement, Picat finds the first condition $Cond_i$ that is true. If such a condition is found, then the truth value of the if-then statement is the same as $Goal_i$. If none of the conditions is true, then the truth value of the if-then statement is the same as $Goal_{else}$. Note that no condition can succeed more than once.
\ignore{
\item \texttt{try-catch}\index{\texttt{try}}: A \texttt{try-catch}\index{\texttt{try}} statement specifies a goal\index{goal} to try, the exceptions that need to be handled when they occur during the execution of the goal\index{goal}, and a clean-up goal\index{goal} that is executed no matter whether the goal\index{goal} succeeds, fails, or is terminated by an exception. The detailed syntax and semantics of the \texttt{try-catch}\index{\texttt{try}} statement will be given in Chapter \ref{chapter:exception} on Exceptions.
}
\item \texttt{throw $Exception$}\index{\texttt{throw}}: This predicate throws the term $Exception$. This predicate will be detailed in Chapter \ref{chapter:exception} on Exceptions.
\item Loops: Picat has three types of loop statements: foreach, while, and do-while.  A loop statement is true if and only if every iteration of the loop is true. The details of loops are given in Chapter \ref{chapter:loops}.
\end{itemize}

\section{Predicate Facts}
For an extensional relation that contains a large number of tuples, it is tedious to define such a relation as a predicate\index{predicate} with pattern-matching rules. It is worse if the relation has multiple keys. In order to facilitate the definition of extensional relations, Picat allows the inclusion of \emph{predicate facts}\index{predicate fact} in the form \texttt{$p$($t_1$,$\ldots$,$t_n$)} in predicate\index{predicate} definitions. Facts and rules cannot co-exist in predicate definitions and facts must be ground. A predicate\index{predicate} definition that consists of facts can be preceded by an \emph{index declaration}\index{index declaration} in the form
\begin{tabbing}
aa \= aaa \= aaa \= aaa \= aaa \= aaa \= aaa \kill
\> \texttt{index ($M_{11},M_{12},\ldots,M_{1n}$) $\ldots$ ($M_{m1},M_{m2},\ldots,M_{mn}$)}\index{\texttt{index}}
\end{tabbing}
where each $M_{ij}$ is either $+$ (meaning indexed) or $-$ (meaning not indexed). If no index declaration is given, then Picat assumes that no arguments are indexed. Facts are translated into pattern-matching rules before they are compiled.

\subsection*{Example}
\begin{verbatim}
    index (+,-) (-,+)
    edge(a,b).
    edge(a,c).
    edge(b,c).
    edge(c,b).
\end{verbatim}
The predicate \texttt{edge} is translated into the following rules:
\begin{verbatim}
    edge(a,Y) ?=> Y=b.
    edge(a,Y) =>  Y=c.
    edge(b,Y) =>  Y=c.
    edge(c,Y) =>  Y=b.
    edge(X,b) ?=> X=a.
    edge(X,c) ?=> X=a.
    edge(X,c) =>  X=b.
    edge(X,b) =>  X=c.
\end{verbatim}

\section{Tail Recursion}
A rule is said to be \emph{tail-recursive}\index{tail recursion} if the last call of the body is the same predicate\index{predicate} as the head. The \emph{last-call optimization}\index{last-call optimization} enables last calls to reuse the stack frame of the head predicate\index{predicate} if the frame is not protected by any choice points. This optimization is especially effective for tail recursion\index{tail recursion}, because it converts recursion into iteration. Tail recursion\index{tail recursion} runs faster and consumes less memory than non-tail recursion.

The trick to convert a predicate\index{predicate} (or a function\index{function}) into tail recursion\index{tail recursion} is to define a helper that uses an \emph{accumulator}\index{accumulator} parameter to accumulate\index{accumulator} the result. When the base case is reached, the accumulator\index{accumulator} is returned. At each iteration, the accumulator\index{accumulator} is updated. Initially, the original predicate\index{predicate} (or function\index{function}) calls the helper with an initial value for the accumulator\index{accumulator} parameter.

\subsection*{Example}
\begin{verbatim}
    min_max([H|T],Min,Max) =>
        min_max_helper([H|T],H,Min,H,Max).

    min_max_helper([],CMin,Min,CMax,Max) => Min=CMin, Max=CMax.
    min_max_helper([H|T],CMin,Min,CMax,Max) =>
        min_max_helper(T,min(CMin,H),Min,max(CMax,H),Max).

    rev([]) = [].
    rev([X|Xs]) = rev_helper(Xs,[X]).

    rev_helper([],R) = R.
    rev_helper([X|Xs],R) = rev_helper(Xs,[X|R]).
\end{verbatim}
In the helper predicate \texttt{min\_max\_helper(L,CMin,Min,CMax,Max)}, \texttt{CMin} and \texttt{CMax} are accumulators\index{accumulator}: \texttt{CMin} is the current minimum value, and \texttt{CMax} is the current maximum value. When \texttt{L} is empty, the accumulators\index{accumulator} are returned by the unification calls \texttt{Min=CMin} and \texttt{Max=CMax}. When \texttt{L} is a cons\index{cons} \texttt{[H|T]}, the accumulators\index{accumulator} are updated: \texttt{CMin} changes to \texttt{min(CMin,H)}\index{\texttt{min/2}}, and \texttt{CMax} changes to \texttt{max(CMax,H)}\index{\texttt{max/2}}. The helper function \texttt{rev\_helper(L,R)} follows the same idea: it uses an accumulator\index{accumulator} list to hold, in reverse order, the elements that have been scanned. When \texttt{L} is empty, the accumulator\index{accumulator} is returned. When \texttt{L} is the cons\index{cons} \texttt{[X|Xs]}, the accumulator\index{accumulator} \texttt{R} changes to \texttt{[X|R]}.
\ignore{
\end{document}
}