%
% Chapter 4
%

\chapter{Monte Carlo event generation}
\label{event_sim}

\section{Introduction}

Accurate simulations for signal and backgrounds are needed for searches for new physics. The primary collision and the decay processes in an event can be described by perturbative QFT. However, perturbative QCD (pQCD) cannot describe the QCD bound states. Therefore phenomenological models are needed to describe hadronization.

Event generators are used for generating simulated particle physics events. Event generators factorize the full process of the event simulation into individual tasks. MC methods are used for the probabilistic branching between these individual problems. MC methods are a class of computational algorithms that rely on repeated random sampling to have the same average behavior in simulation as in collision data. Event signature beyond SM particles can be generated to compare its signature to one of the generated background processes.

General-purpose Monte Carlo (GPMC) generators, like PYTHIA~\cite{Sjostrand:2014zea}, provide fully exclusive simulations of high energy collisions. However, there are also event generators that are specialized in a certain aspect of the event simulation. Perturbative matrix elements for the scattering process are implemented in matrix element generators. Hadronic event generators simulate the initial and final state particle showers, hadronization, and soft hadron-hadron physics, including the initial state's composition and substructure. An overview of different steps in MC generation for \pp collision events can be seen in Figure~\ref{fig:simulation}.

\begin{figure}[htbp]
  \centering
  \includegraphics[width=0.8\textwidth]{plots/chapter4/simulation.png}
  \caption{MC simulation of an event in \pp collisions.}
  \label{fig:simulation}
\end{figure}

\section{Monte Carlo simulation}

The primary hard interaction process and the decay of short-lived particles happen at short distance scales. The QCD and QED radiation at a time scale much below $\frac{1}{\Lambda}$, where $\Lambda$ is a typical hadronic scale of a few hundred~\MeV, are also happening at short distance scales. Soft and collinear safe inclusive observables, such as total decay widths or inclusive cross-sections, can be computed with pQCD theory for momentum scales much larger than this scale. The final state collinear splittings and soft emissions give rise to large logarithmically divergent corrections, which cancel against virtual corrections in the total cross-section. Initial state collinear singularities are factorized into parton distribution functions (PDFs). Therefore, the cross-section remains accurate up to higher-order corrections if interpreted as an inclusive cross-section. If this is not the case, then the QCD singularities can lead to a non-convergence of the fixed order expansion.

\textbf{Matrix element generator:} Matrix element generators generate the exact matrix elements for the production of the process. They also produce a certain number of additional partons for hard, large-angle emissions. The radiation of extra partons is not included at the tree level accuracy of the hard process. The radiation of an extra parton with tree level accuracy can be included to provide next-to-leading-order (NLO) corrections along with all NLO virtual corrections. The parton shower algorithms use as input the final state partons of the hard process and their phase space.

\textbf{Parton shower algorithm:} The parton shower algorithm is used for computing the cross-section for a generic hard process. Parton level events are transferred from a hard process generator to a shower generator, containing a list of particles and the used free parameters, using the Les Houches Event File standard~\cite{Alwall:2006yp}. The kinematics of the basic process is first generated, followed by a sequence of independent shower splittings. The cross-section for the given final state is calculated by assigning a probability to each splitting vertex. Collinear emissions and soft gluon emissions at arbitrary angles are the two sources of infrared singularities in massless field theories like QCD. PYTHIA uses a $\text{p}_{\perp}$ ordered shower evolution for correctly describing both effects.

\textbf{Matching:} QCD color confinement restricts quarks and gluons from existing as isolated particles. The hadronization of a quark or a gluon gives rise to hadrons or their decay products. Jets are collimated bunches of these hadrons. The collinear/soft radiation of an appropriate (N + 1) parton final state, generated by a matrix element generator, can give rise to a (N + 1) jet event. A (N + 1) jet event can also be obtained from an N parton final state with hard, large-angle emission during shower evolution. A matching has to be done if different generators have been used to generate matrix elements and parton showers or extra partons generated by the hard process generator.

\textbf{Hadronization models:} The hadronization scale $\text{Q}_{\text{had}}$ is by construction equal to the infrared cut-off where the parton shower ends. Colored partons are transformed into a set of colorless hadrons by GPMCs. This happens at scales with low momentum transfers and at long distances, where non-perturbative effects become important. GPMCs use models that rely on the color flow information between partons as a starting point for hadronization.

\textbf{Soft hadron-hadron physics modeling :} Underlying-event is the additional activity beyond the basic process and its associated initial- and final-state radiation. The dominant part is coming from additional color exchanges between the beam remnants. Multiple parton-parton interactions (MPI) can produce two or more back-to-back jet pairs, with each pair having a small transverse momentum. Most MPI are soft, and they influence the color flow and the event's total scattered energy. This increases the particle multiplicity in the final state and affects the final state activity. Compared to events with no hard jets, the hard jets appear to sit on top of a higher ``pedestal'' of underlying activity. This comes from the impact parameter dependence since central collisions are more likely to contain at least one hard scattering due to the higher probability of interactions and is called the ``jet pedestal'' effect.

\textbf{Parameter Tuning:} The accuracy of the used models is very important for event simulation. The accuracy depends on the inclusiveness of the chosen observables and the sophistication of the simulation. The models can be improved by improving the theoretical calculations. The precision also depends on the constraints in the free parameters, and existing collision data constrains them and is referred to as generator tuning. MC generators are not tuned beyond the constraints in theoretical and experimental precision to avoid overfitting. The final state of the particles and their spectra are influenced by event modeling and generator tuning. Events generated with different generators or tunes can differ and might not describe the collision data in the entire phase space.

\section{Monte Carlo generators}

PYTHIA has been developed for multi-particle production in \pp collisions and simulation of jets. PYTHIA can generate hard subprocess, initial and final state parton showers, hadronization, decays, and the underlying-event. Many hard processes have been implemented for generating the matrix elements for final state and phase space calculation. PYTHIA can optimally generate $2 \to 1$ and $2 \to 2$ processes. Resonance decays with the resonance masses above the b quark system are implemented. Their branching fractions and partial width can be dynamically calculated as a function of their mass. If the spin information is available for resonance decays, it leads to angular correlations of the resonance decay products; otherwise, the resonance decays isotropically. GPMC generators like PYTHIA can simulate the full process. However, there are specialized generators that deal with a certain aspect of the event simulation.

\textbf{MadGraph:} MadGraph generates the matrix element with leading-order (LO) accuracy~\cite{Alwall:2011uj}. MadGraph is a matrix element generator for processes that involve final states with a large number of jets, heavy flavor quarks, leptons, and missing energy. Events from new physics models that are renormalizable or from an effective field theory written in a Lagrangian can be generated. The full amplitude is split into gauge invariant sub-amplitudes. The matrix element contains the full spin correlation and Breit-Wigner effects but is not valid far from the mass peak.

\textbf{POWHEG:} POWHEG is a framework for implementing NLO matrix element calculations~\cite{Alioli:2010xd}. It includes NLO virtual corrections and radiation of an extra parton in the matrix element. It needs the LO matrix elements and the finite part of the virtual corrections as input from which it finds all the singular regions. The singular regions are characterized by a final state parton becoming collinear or soft to either an initial state parton or a final state parton. The singular regions can be grouped according to their underlying LO diagram by replacing this parton pair with a single parton of appropriate flavor.

\textbf{aMC@NLO:} aMC@NLO implements all aspects of NLO computation and its matching with parton showers~\cite{Frederix:2011ss, Alwall:2014hca}. NLO calculations can be achieved by combining one-loop matrix elements and tree-level matrix elements. Tree level computations are performed using MadGraph, and one-loop amplitudes are evaluated with MadLoop~\cite{Hirschi:2011pa}. The matched samples which differ by their final state multiplicity can be merged using the FxFx merging scheme.

\textbf{MLM matching:} MLM matching scheme is a matching algorithm~\cite{Mangano:2001xp, Mangano:2002ea} that matches partons from matrix element calculations to jets reconstructed after shower generation. Parton level events are required to have a separation greater than a minimum value $\text{R}_{\text{jj}} > \text{R}_{\text{min}}$ between them and at least a minimum transverse energy $\text{E}^{\text{min}}_{\text{T}}$ for partons. The jet closest in $(\eta, \phi)$ to the hardest parton is selected, and both match if the distance is smaller than $\text{R}_{\text{min}}$. Once a match is found, the jet is removed, and matching is done with the next parton. If a match is not found, then the event is rejected. This is the case for collinear partons or soft partons, which do not lead to an independent jet or are too soft for jet reconstruction.

\textbf{FxFx merging:} FxFx merging scheme is an NLO merging procedure~\cite{Frederix:2012ps}. There can be NLO accuracy for exclusive events with J light jets by the computation based on matrix elements that have J and (J + 1) partons. NLO mergings are more complicated than LO ones. This is because the matrix elements are considered twice, as Born contribution for processes with J partons and as the real emission contribution, infrared subtraction terms, and the one-loop contributions to processes with (J - 1) partons. Events are reweighted, and a certain amount of events might carry negative weights.

\section{Detector simulation}

In detector simulation, the interactions of particles with the detector material and the detector response are simulated. These events can then be reconstructed and analyzed. Geant4~\cite{Agostinelli:2002hh} is used for detector simulation. It is a toolkit for simulating particles' passage through matter and for simulating particle interactions with matter across a very wide energy range. The user defines the detector geometry and materials. A large number of components with different shapes and materials can be included in the geometrical model. Sensitive elements can be defined, which record information in the form of hits. Hits are needed to simulate the detector responses called digitization. The detector's geometrical structure is divided into logical and physical volumes. Logical volumes contain the information of the material and the sensitive detector behavior. A mixture of different elements and isotopes can be used for the material. Physical volumes carry information about the spatial positioning or placement of the logical volumes.

Particles can interact with the detector material or can decay while they are transported through the geometry. A model can be implemented by electromagnetic and hadronic processes in Geant4 depending on the energy or particle type. Geant4 can handle ionization described by energy loss and range tables, bremsstrahlung, pair production of electron-positrons from photons, photoelectric effect, pair conversion, annihilation, synchrotron, and transition radiation, scintillation, refraction, reflection, absorption, the Cherenkov effect, and many other processes. Particles with their basic properties, like mass, charge, and sensitive processes, can be defined. Particles are transported in steps, and they are tracked through materials and external electromagnetic fields. Event data is generated during simulation. First, events contain primary vertices and primary particles before processing an event. After processing, hits and digitizations generated by simulation are added. Trajectories of simulated particles can be added optionally for the recording of ``simulation truth.''

\section{Monte Carlo samples}

MC simulated event samples are used to model signal and background contributions to all the analysis regions with several event generators. In all cases, parton showering, hadronization, and underlying-event properties are modeled using PYTHIA version 8.212. The PYTHIA parameters affecting the description of the underlying-event are set to the CUETP8M1 tune in 2016~\cite{Khachatryan:2015pea}, except for the \ttbar sample where the CP5 tune is used, which is also the tune in 2017 and 2018~\cite{CMS:2018zub}. The NNPDF3.0 PDF set is used for all 2016 samples, and the NNPDF3.1 PDF set is used for the 2017 and 2018 samples~\cite{Ball:2017nwa}.

Simulation of interactions between particles and the CMS detector is based on Geant4. The same reconstruction algorithms used for data are applied to simulated samples as well. The Higgs bosons are produced in \pp collisions predominantly by gluon gluon fusion (ggF)~\cite{Georgi:1977gs}, but also by vector boson fusion (VBF)~\cite{Cahn:1986zv}, and in association with a vector boson (W/Z)~\cite{Glashow:1978ab}. The ggF, VBF, and associated production Higgs boson samples are generated with POWHEG generator in the implementation described in Ref.~\cite{Heinrich:2017kxx, Buchalla:2018yce}. We only consider Higgs boson produced in ggF and VBF production mechanisms and do not use associated production Higgs boson samples for the signal.

Embedded samples are data samples with well-identified \Zmm events from which muons are removed, and simulated tau leptons are embedded with the same kinematics as the replaced muons. These samples are employed for the data-driven estimation of the \Ztt and some \ttbar/Diboson/Single Top background. The MadGraph generator is used to simulate the $\Zee/\Pgm{}\Pgm + \text{jets}$ process along with the \wjets background process. They are simulated at LO with MLM jet matching and merging schemes~\cite{Alwall:2007fs}.

Diboson production is simulated at NLO using aMC@NLO generator with FxFx jet matching and merging scheme. Top quark pair and single top quark production simulated samples are generated using POWHEG. Events have multiple \pp interactions per bunch crossing (pileup) because of the high instantaneous luminosities attained during data-taking period. The effect is taken into account in simulated samples by generating concurrent minimum bias events. All simulated samples are weighted to match the pileup distribution observed in the data.


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\title{First Document}
\author{Gubert Farnsworth}
\date{ }

\begin{document}

\maketitle

\tableofcontents

\part{First Part of this document}

\section{Introduction}

This is the first section.

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

\section{Introduction}
Theorems can easily be defined

\begin{theorem}
Let $f$ be a function whose derivative exists in every point, then $f$ is
a continuous function.
\end{theorem}

\begin{theorem}[Pythagorean theorem]
\label{pythagorean}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]
\end{theorem}

And a consequence of theorem \ref{pythagorean} is the statement in the next
corollary.

\begin{corollary}
There's no right rectangle whose sides measure 3cm, 4cm, and 6cm.
\end{corollary}

You can reference theorems such as \ref{pythagorean} when a label is assigned.

\begin{lemma}
Given two line segments whose lengths are $a$ and $b$ respectively there is a
real number $r$ such that $b=ra$.
\end{lemma}
\section{Second Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem.  Nullam nec mi et neque pharetra
sollicitudin.  Praesent imperdiet mi necante...

\subsection{First Subsection}
Praesent imperdietmi nec ante. Donec ullamcorper, felis non sodales...

\section*{Unnumbered Section}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem

\section{Introduction}

This is the first section.

Lorem  ipsum  dolor  sit  amet,  consectetuer  adipiscing
elit.   Etiam  lobortisfacilisis sem.  Nullam nec mi et
neque pharetra sollicitudin.  Praesent imperdietmi nec ante.
Donec ullamcorper, felis non sodales...

\section{Second Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem.  Nullam nec mi et neque pharetra
sollicitudin.  Praesent imperdiet mi necante...

\section{Third Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem.  Nullam nec mi et neque pharetra
sollicitudin.  Praesent imperdiet mi necante...

\end{document}


When source identification is performed following initial detection of a
contamination incident, it is likely that the identified set of
possible injection locations is fairly large due to the limited
measurement information available at the early stages of detection.
As time progresses, more measurements become available to help
decrease the number of possible injection locations. It is possible to
obtain additional measurements in the form of grab samples from
optimally selected locations that can help in quickly narrowing down
the set of likely incident locations when source inversion
calculations are performed again. The \code{grabsample} subcommand can be used to
identify optimal grab sample locations
that are likely to provide the most information in narrowing down the
list of possible injection locations identified from
the \code{inversion} subcommand.

A flowchart representation of the \code{grabsample} subcommand is
shown in Figure \ref{fig:grabsample_flowchart}. The required input
for the \code{grabsample} subcommand includes a utility network model
specified with an EPANET 2.00.12 compatible input file (INP) and a list of
likely injection scenarios.
%A flowchart representation of the \code{grabsample} subcommand, used in conjunction with the
%\code{inversion} subcommand, is shown in Figure \ref{fig:inversion_grabsample_flowchart}.

\begin{figure}[h]
  \centering
  \includegraphics[scale=0.75]{graphics/grabsample_flowchart.pdf}
  \caption{Grab sample flowchart.}
  \label{fig:grabsample_flowchart}
\end{figure}

\section{Grab Sample Formulations}
The \code{grabsample} subcommand contains three different grab sampling formulations,
the distinguishability formulation and two probability-based formulations.
The probability functions will likely be faster for larger problems (linear scaling), while the distinguishability formulation scales quadratically with the number of contamination scenarios.
The following subsections provide brief descriptions of these formulations.

\subsection{Distinguishability Formulation}
\label{grabsample_formulation}
Considering two possible contamination incidents $i$ and $j$, if a
particular sample location is impacted by incident $i$, but not
impacted by incident $j$, then this sample location is able to
distinguish between the two incidents. The \code{grabsample} subcommand
can be used to identify grab sample locations that maximize the number
of pairwise distinguishable incidents in a list of possible
contamination incidents. The <output prefix>profile.tsg obtained
from the \code{inversion} subcommand contains a list of possible injection
locations. The data sets required by the optimization formulation
below are obtained by simulating each possible incident using the
EPANET 2.00.12 hydraulics model and either the EPANET 2.00.12 water quality model or the Merlion water quality model \citep{Mann1},
which can be selected using the merlion option in the scenario block of the configuration file.

The distinguishability problem formulation is:
\begin{align}
\textrm{maximize}\qquad &\sum_{(i,j) \in PE} d_{ij}\label{eqn.grabsample_obj}\\
\textrm{subject to} \qquad &\sum_{n \in D_{ij}}s_n \geq d_{ij} &&\forall \left( i,j \right) \in PE \label{eqn.grabsample_cons1} \\
&\sum_{n \in G}s_n \leq S_{\max} + \left|F\right|\label{eqn.grabsample_cons2} \\
&s_n \in \lbrace 0,1 \rbrace &&\forall \; n \in G \label{eqn.grabsample_cons3}\\
&s_n = 1 &&\forall \; n \in F \label{eqn.grabsample_cons5}\\
&0 \leq d_{ij} \leq 1 &&\forall \left( i,j \right) \in PE \label{eqn.grabsample_cons4}
\end{align}

where $G$ is the set of all grab sample locations, $F$ is the set of
fixed sensor locations and $PE$ is the pairwise set of all candidate
incidents (i.e., possible contamination incidents). The variable $D_{ij}$ is
the set of sample locations that distinguish incident $i$ from
incident $j$; $S_{max}$ is the maximum number of samples that can be
taken at the same time (i.e., number of sampling teams); $s_n$ is a
binary variable that is 1 if node $n$ is a good sample and is 0 otherwise; and
$d_{ij}$ is a continuous variable that will be 1 if incident $i$ is
distinguishable from incident $j$ and is 0 otherwise.

Equation \ref{eqn.grabsample_obj} represents the mixed-integer programming (MIP) objective, which
maximizes the number of pairwise distinguishable incidents.
Equation \ref{eqn.grabsample_cons1} requires that at least one or more
sample locations be selected for a distinguishable incident.
Equation \ref{eqn.grabsample_cons2} limits the number of selected
locations to be less than or equal to the number of sampling teams (specified by the user).
Equation \ref{eqn.grabsample_cons3} defines $s_n$ as a binary variable.
Equation \ref{eqn.grabsample_cons5} ensures that the fixed sensor
locations are always sampled since measurements from these fixed sensors
are always available, which avoids double counting distinguished incidents. This formulation is the default formulation solved in the \code{grabsample} subcommand.

\subsection{Probability-based Formulations}
\label{probabilityFormulations}
From a source inversion perspective, the contamination incident that agrees with the largest number of measurements is the contamination incident with the higher probability of occurrence. Similarly, all contamination incidents that disagree with many of the measurements have a low probability of occurrence. Following this idea, two optimization formulations were implemented in the \code{grabsample} subcommand in order to determine optimal sampling locations that are intended to maximize the probability of identifying the true contamination incident (or minimizing the probability of incidents that did not occur).

\subsubsection{Maximization of expected number of scenarios that disagree with measurements}

Given a set of potential contamination incidents, a few scenarios will agree with all the measurements, while many more will disagree. For this reason, the formulations in this section aim to select locations that maximize the number of disagreements between incidents and measurements (quickly reduce the probabilities of the incidents that are not likely to be consistent with observations). The development of an MILP problem formulation that meets this goal is presented next.

\begin{align}
%& \underset{x, P_{s}^{\textrm{miss}}, P_{s}^{\textrm{match}}}{\textrm{max}}
\textrm{maximize} \qquad&\;\; \sum_{s\in S}P_{s}^{\textrm{miss}} &  \label{eqn.p1_obj}\\
\textrm{subject to} \qquad &P_{s}^{\textrm{miss}} = 1-P_{s}^{\textrm{match}} & \;\forall \; s \in S \label{eqn.p1_c1}\\
&P_{s}^{\textrm{match}} = \exp(\tilde{P}_{s}) & \forall \; s \in S \label{eqn.p1_c2}\\
&\tilde{P}_{s} = \sum_{n\in N} x_n \ln(\alpha_{s,n}) & \forall \; s \in S \label{eqn.p1_c3}\\
&\sum_{n\in N} x_n \le S_{\textrm{max}} & \label{eqn.p1_c4}\\
&x_{n} \in \{0,1\} & \forall \; n \in N  \label{eqn.p1_c5}
\end{align}

Here $P_{s}^{\textrm{miss}}$ is the probability that incident $s$ disagrees with the outcome of the measurements at the selected locations. $P_s^{\textrm{match}}$ (complement of  $P_{s}^{\textrm{miss}}$) is given by the product of the probabilities $\alpha_{s,n}$ over all selected sampling locations,

\begin{equation}
P_s^{\textrm{match}}= \prod_{n\in N} \alpha_{s,n}^{x_n}
\end{equation}

where $x_n$ is a binary variable that will be $1$ if location $n$ is selected for sampling, and is $0$ otherwise. In the formulation, this product is written in equations (\ref{eqn.p1_c2}) and (\ref{eqn.p1_c3}). The parameter $\alpha_{s,n}$ is the probability that incident $s$ disagrees with the outcome of a measurement taken at location $n$

\begin{equation}
\alpha_{s,n} = \left\{ \begin{array}{ll}
         \gamma_n & \mathrm{if }\ \delta_{s,n} = 1;\\
        1-\gamma_n & \mathrm{otherwise}.\end{array} \right.
\label{alphasn}
\end{equation}

where $\delta_{s,n}$ is a binary parameter that is $1$ if incident $s$ contaminates node $n$, and $0$ otherwise. The values of $\delta_{s,n}$ are determined from the simulations pre-computed over the full potential incident set. The parameter $\gamma_n$ is the probability that node $n$ is contaminated and can be computed from the probability of the contamination incidents

\begin{equation}
\gamma_n = \sum_{s \in S} \delta_{s,n}\beta_s,
\label{nodeprob}
\end{equation}

Here $\beta_s$ is the current estimate of the probability of contamination incident $s$. Finally, $S_{\textrm{max}}$ is the maximum number of samples to be taken. The formulation as written is an MINLP because of Equation (\ref{eqn.p1_c2}). However, it is easily made linear. Note that the equality in Equation (\ref{eqn.p1_c2}) can be replaced with a lower bounding inequality. Since the objective function is maximizing $P_{s}^{\textrm{miss}}$ (and pushing down on $P_{s}^{\textrm{match}}$), this inequality will always be satisfied with equality at the solution. Note also that this new inequality is convex and can be replaced with a set of linear under-estimators.

This new MILP formulation, referred to as problem Probability1, is shown below, where $v_{i}$ are tangent
points selected for the linear under-estimators of the exponential term and $L$ is the set of indices corresponding to each of the linear under-estimators:

\begin{align}
%& \underset{x, P_{s}^{\textrm{miss}}, P_{s}^{\textrm{match}}}{\textrm{max}}
\textrm{maximize}\qquad & \;\; \sum_{s\in S}P_{s}^{\textrm{miss}} &  \label{eqn.p1_obj1}\\
\textrm{subject to}\qquad &P_{s}^{\textrm{miss}} = 1-P_{s}^{\textrm{match}} & \forall \; s \in S \label{eqn.p1_c11}\\
&P_{s}^{\textrm{match}} \geq \exp(v_i) + \exp(v_i) \left( \tilde{P}_{s} - v_i \right) & \forall \; i \in L, \; s \in S \label{eqn.p1_c21} \\
&\tilde{P}_{s} =  \sum_{n\in N} x_n \ln(\alpha_{s,n}) & \forall \; s \in S \label{eqn.p1_c31}\\
&\sum_{n\in N} x_n \le S_{\textrm{max}}  & \label{eqn.p1_c41}\\
&x_{n} \in \{0,1\} & \forall \; n \in N ,\label{eqn.p1_c51}
\end{align}

\subsubsection{Maximization of scenario with least number of measurement disagreements}

A third formulation is also presented that maximizes the worst-case number of mismatches (instead of the expected value). This formulation does not contain the exponential term and is already an MILP without the need for any linear under-estimators, which avoids numerical issues that can occur when too many numerically similar
under-estimators are added. This produces the max-min formulation shown below:
\begin{align*}
\textrm{maximize} \qquad \underset{s}{\textrm{minimize}} \qquad & P_{s}^{\textrm{miss}} &  \label{eqn.p2_bi_obj}\\
\textrm{subject to} \qquad &P_{s}^{\textrm{miss}} = 1-P_{s}^{\textrm{match}} & \forall \; s \in S \label{eqn.p2_bi_c1}\\
&P_{s}^{\textrm{match}} = \exp(\tilde{P}_{s}) & \forall \; s \in S \label{eqn.p2_bi_c2}\\
&\tilde{P}_{s} =  \sum_{n\in N} x_n \ln(\alpha_{s,n}) & \forall \; s \in S \label{eqn.p2_bi_c3}\\
&\sum_{n\in N} x_n \le S_{\textrm{max}}  & \label{eqn.p2_bi_c4}\\
&x_{n} \in \{0,1\} & \forall \; n \in N, \label{eqn.p2_bi_c5}\
\end{align*}
Recognizing that
\[
\underset{s} \argmin \; P_{s}^{\textrm{miss}} = \underset{s}\argmin \;{-}P_{s}^{\textrm{match}} \label{eqn.p2_arg1}\\
\]
and that
\[
\underset{x} \argmin \; {-}x = \underset{x}\argmin \; {-}\exp(x), \label{eqn.p2_arg2}\\
\]
the prior bilevel optimization formulation is reformulated to a single level optimization formulation as,

\begin{align}
\textrm{maximize} \qquad & \;\; q &  \\
\textrm{subject to} \qquad & \;\;q \leq -\tilde{P}_{s} & \label{eqn.p2_obj}\\
&\;\; \tilde{P}_{s} =  \sum_{n\in N} x_n \ln(\alpha_{s,n}) & \forall \; s \in S \label{eqn.p2_c1}\\
&\;\; \sum_{n\in N} x_n \le S_{\textrm{max}}  & \label{eqn.p2_c2}\\
&\;\; x_{n} \in \{0,1\} & \forall \; n \in N, \label{eqn.p2_c3}
\end{align}

This formulation is referred to as Probability2, where q is an auxiliary variable that
supports the max-min reformulation to a single level optimization problem.

\section{Grab Sample Solvers}
The \code{grabsample} subcommand requires standard MIP solvers to
identify optimal grab sample locations. The solvers recognized by
the \code{grabsample} subcommand are the same as those recognized
by \code{booster\_mip} subcommand (See
Section \ref{booster_mip_solver} for more details).

\section{\code{grabsample} Subcommand}

The \code{grabsample} subcommand is executed using the following
command line:
\begin{unknownListing}
wst grabsample <configfile>
\end{unknownListing}
where \code{configfile} is a WST configuration file in the YAML format.

The \code{---help} option prints information about this subcommand:
\begin{unknownListing}
wst grabsample --help
\end{unknownListing}

\subsection{Configuration File}

The \code{grabsample} subcommand generates a template configuration
file using the following command line:

\begin{unknownListing}
wst grabsample --template <configfile>
\end{unknownListing}

The \code{grabsample} template configuration file is shown in
Figure \ref{fig:grabsample_template}. Brief descriptions of the
options are included in the template after the \# sign.

\begin{figure}[H]
  \unknownInputListing{examples/grabsample_config.yml}{}{1}{46}
  \caption{The \code{grabsample} configuration template file.}
  \label{fig:grabsample_template}
\end{figure}

The \code{grabsample} subcommand requires information about likely scenarios, which is set in the scenario block.
These scenarios must be defined using a TSG file or by specifying the scenario location, type,
strength, start and stop times (see Section \ref{sec:scenarios} for more information on defining scenarios).
In general, the TSG file created by the \code{inversion} subcommand will be used to define likely scenarios.
Either the EPANET option or the Merlion option can be used as the water quality model, although, the Merlion
water quality model is recommended for larger networks.

\subsection{Configuration Options}

Full descriptions of the WST configuration options used by
the \code{grabsample} subcommand are listed below.
\input{examples/grabsample_config}

\subsection{Subcommand Output}
The \code{grabsample} subcommand creates a YAML file called <output prefix>grabsample\_output.yml that contains
a list of node locations (EPANET node IDs) to
take manual grab samples, the objective function value (based on the particular formulation selected),
the run date and CPU time.
The log file named <output prefix>grabsample\_output.log contains basic debugging information.
A visualization YAML configuration file named <output prefix>grabsample\_output\_vis.yml is also created, and
following the execution of the \code{grabsample} subcommand,
the \code{visualization} subcommand is automatically run using this YAML file.

\section{Grab Sample Examples}
Two examples for the \code{grabsample} subcommand are provided. The first example uses the distinguishability
formulation, while the second uses the probability-based formulation, Probability1.

\subsection{Example 1}
An EPANET 2.00.12 network model (INP format) and a file containing a list of
possible injection scenarios (e.g., a TSG file, which is generated by
the \code{inversion} subcommand) are required to run the \code{grabsample} subcommand. The
configuration file for this example, grabsample\_ex1.yml, is shown in
Figure \ref{fig:sampling_ex1}. The EPANET Example Network 3 input file,
Net3.inp, is used for this example.
The \code{grabsample} subcommand is typically used to identify sampling location
after the results of the source identification calculation give a large list of
candidate injection nodes. The time line of using the \code{inversion} and \code{grabsample}
subcommand sequentially is provided in Figure \ref{fig:inversion_flowchart}.
The TSG file, Net3\_gs\_profile.tsg, which contains the possible contamination incidents, is created by the \code{inversion} subcommand using the measurement data created by the  \code{measuregen} executable (Executable Files Section \ref{measuregenExecutable}). For this example, the \code{measuregen} executable
is used to simulate and obtain the measurements from a contaminant injection at node 251 at 24 hours.
The injection is detected at 30.5 hours by using a set of fixed sensor
locations defined in the Net3\_fixed\_sensors file.
The list of eight equally likely
contamination injection locations as listed in the TSG file, Net3\_gs\_profile.tsg, produced by the \code{inversion} subcommand is used as input to the
\code{grabsample} subcommand along with the EPANET 2.00.12 network file.
The sample time is set to 1890
minutes (31.5 hours), since it is assumed that it takes 60 minutes to
perform source identification and obtain the manual grab samples (including travel time).
The maximum number of manual grab samples that can be taken is two.

\begin{figure}[H]
  \unknownInputListing{../../examples/grabsample_ex1.yml}{}{1}{32}
  \caption{The \code{grabsample} configuration file for example 1.}
  \label{fig:sampling_ex1}
\end{figure}

The example can be executed using the following command:
\begin{unknownListing}
wst grabsample grabsample_ex1.yml
\end{unknownListing}

The results are available in the {\outputprefix}grabsample\_output.yml, which
is shown in Figure \ref{fig:sampling_ex1_re}. The manual grab sample
locations identified are nodes 241 and 251. Twenty-three pairwise
incidents will be distinguished after taking the samples at these
locations. To reiterate the configuration parameters, the sampling
time is 1890 minutes and the maximum number of sampling locations is
two. The grab sample locations identified in Figure \ref{fig:sampling_ex1_re}
might be one of several solutions that produce the same objective value. If
multiple grab sample locations provide the same ability to distinguish the
contamination source, the solver will randomly pick a solution. Thus, the solution
identified in Figure \ref{fig:sampling_ex1_re} could be different for other users.

\begin{figure}[H]
  \unknownInputListing{examples/sampling/grabsample_ex1_output.yml}{}{1}{13}
  \caption{The \code{grabsample} YAML output for example 1.}
  \label{fig:sampling_ex1_re}
\end{figure}

Next, as shown in Figure \ref{fig:inversion_flowchart}, the
measurements from these selected grab sample locations (actual or
simulated using \code{measuregen} executable) can be used to again
perform source identification. Please refer to
Section \ref{chap:inversionCase} for a complete case study of how to
use the \code{inversion} and \code{grabsample} subcommands in tandem.

\subsection{Example 2}

In the second example, the probability-based formulation, Probability1, is used to select the optimal sampling locations, since the probability-based formulations are particularly efficient when the number of contamination scenarios is considerably large. The configuration file for this example, grabsample\_ex2.yml, is shown in
Figure \ref{fig:sampling_ex2}.

\begin{figure}[H]
  \unknownInputListing{../../examples/grabsample_ex2.yml}{}{1}{28}
  \caption{The \code{grabsample} configuration file for example 2.}
  \label{fig:sampling_ex2}
\end{figure}

The scenario information is provided with a list of pairs of INP-TSG files. This input allows the user to include different hydraulic and contamination in the set of potential scenarios. The list of potential scenarios used is shown in Figure \ref{fig:gs_scenarios}. Ten different INP files with variations in the demand patterns are specified in the list to account for uncertainty in the hydraulics of the system. For simplicity a single TSG file is specified to provide information about the contamination scenarios. However, each entry in the list of scenarios could have a different TSG file.

\begin{figure}[!ht]
  \unknownInputListing{../../examples/Net3/grabsample/list_scenarios.dat}{}{1}{10}
  \caption{List of scenarios example 2.}
  \label{fig:gs_scenarios}
\end{figure}

In addition, a list of the currently available measurements is provided in a measurement file with columns labeled as ``location, time and measurement value.'' The measurements are used to compute the probability of the scenarios following a Bayesian approach. When no measurements are provided, the probability distribution of the scenarios is assumed to be uniform. The measurement file in this example is shown in Figure \ref{fig:gs_measurements}

\begin{figure}[!ht]
  \unknownInputListing{../../examples/Net3/grabsample/MEAS.dat}{}{1}{3}
  \caption{List of measurements example 2.}
  \label{fig:gs_measurements}
\end{figure}

The example can be executed using the following command:
\begin{unknownListing}
wst grabsample grabsample_ex2.yml
\end{unknownListing}

The results are available in the {\outputprefix}grabsample\_output.yml, which
is shown in Figure \ref{fig:sampling_ex2_re}.

\begin{figure}[H]
  \unknownInputListing{examples/sampling/gs_ex2_output.yml}{}{1}{13}
  \caption{The \code{grabsample} YAML output for example 2.}
  \label{fig:sampling_ex2_re}
\end{figure}


\section{The Basic TSTL Test Tools}

Instead of the fault-free stack, we can test a real-world program with real faults, such as the SymPy library for performing symbolic mathematics in Python \cite{SymPy}.  The SymPy harness can be found in the TSTL github repository {\tt examples/sympy} directory.

{\scriptsize
\begin{code}
 > tstl sympy.tstl
 > tstl\_rt --swarm --noCover --full
...
 UNCAUGHT EXCEPTION
 ERROR: (<type 'exceptions.RuntimeError'>,
 RuntimeError('maximum recursion depth exceeded',)
...
    return func(a, b)
...
 SAVING TEST AS failure.67076.test
...
 STOPPING TESTING DUE TO FAILED TEST
 36.4984600544 TOTAL RUNTIME
 > wc -l failure.67076.test
 72
 > head -n5 failure.67076.test
 self.p\_v[3] = sympy.Symbol('j',positive=True)
 self.p\_expr[0].evalf()
 self.p\_expr[0] = self.p\_expr[0] + self.p\_expr[3]
 self.p\_expr[3] = self.p\_expr[3] + self.p\_expr[1]
 self.p\_expr[1] = self.p\_expr[3] \% self.p\_expr[0]

\end{code}
}

We have instructed the random tester to use swarm testing
\cite{ISSTA12} and not collect code coverage, in order to improve the
chances of quickly finding a fault.  By default {\tt tstl\_rt} uses
delta-debugging to minimize tests before saving them, but we have
also instructed {\tt tstl\_rt} to simply save the original test case {\tt
  --full}.  The unreduced test (which causes Python to enter an
infinite recursion sequence) consists of 72 steps, saved in a
non-executable, technically (but not very) human-readable, textual
format (in an automatically generated file name, based on the process ID).  This is not a very useful test, so we want to reduce
it:

{\scriptsize
\begin{code}
 > tstl\_reduce failure.67076.test reduced.test --noNormalize
 STARTING WITH TEST OF LENGTH 72
 REDUCING...
 REDUCED IN 31.3780119419 SECONDS
 NEW LENGTH 7
 ALPHA CONVERTING...
 c0 = sympy.Integer(4)                            \# STEP 0
 c1 = sympy.Integer(9)                            \# STEP 1
 v0 = sympy.Symbol('k',positive=True)             \# STEP 2
 expr0 = sympy.Rational(c1,c1)                    \# STEP 3
 expr1 = sympy.Product(expr0,(v0,c0,c0))          \# STEP 4
 expr2 = c1                                       \# STEP 5
 expr3 = expr2 \% expr1                            \# STEP 6
\end{code}
}

This test, reduced using standard delta-debugging \cite{DD}, is
short.  Also, note that TSTL automatically alpha-converts the test so
that it uses variables to store intermediate values in a reasonable
way (starting with {\tt v0} rather than arbitrarily beginning with
{\tt v3}, for example).  However, the test is neither as short as possible nor, more
importantly, as simple as possible.  For debugging we may well wonder:
does it matter that {\tt c0} is 4 and {\tt c1} is 9?  Is the use of
the variable {\tt k} relevant?  If we want to know the answers, we can
run the reducer to \emph{normalize} \cite{OneTest} the test, in place
of simply reducing it:

{\scriptsize
\begin{code}
 > tstl\_reduce reduced.test normalized.test --noReduce
 STARTING WITH TEST OF LENGTH 7
 NORMALIZING...
 NORMALIZED IN 383.565114975 SECONDS
 NEW LENGTH 5
 c0 = sympy.Integer(1)                            \# STEP 0
 v0 = sympy.Symbol('a')                           \# STEP 1
 expr0 = c0                                       \# STEP 2
 expr1 = sympy.Sum(expr0,(v0,c0,c0))              \# STEP 3
 expr0 = expr0 \% expr1                            \# STEP 4
\end{code}
}

Notice that normalizing a test is much more expensive than simply
reducing it, but the payoff is an even shorter and simpler
test\footnote{For details on how much shorter and simpler, see the
  conference paper on test case normalization and generalization
  \cite{OneTest}.  Note that normalization times are usually faster in
the current release than reported in that paper, due to the
implementation of a useful heuristic for reducing nearly 1-minimal
tests suggested by David R. MacIver \cite{MacIver}, the author of the Hypothesis tool.}.  By default, the TSTL random test generator
reduces tests before saving them, and the standalone {\tt
  tstl\_reduce} tool is used to normalize interesting tests.  Calling
{\tt tstl\_rt} with the {\tt --normalize} option avoids going through
the standalone tool.  Normalization here pays off by revealing that
the use of a {\tt Rational} and exact numeric/symbol values are not
relevant.

Now that we have an extremely simple test, we can replay it in a
``verbose'' mode to see more exactly what is happening during the test, as shown in
Figure \ref{fig:verbose}.  This shows the values, types, and changes
in values of every pool variable involved in each step of the test
(and would show the state of a reference implementation, if we were
performing automated differential testing).

\begin{figure}
{\scriptsize
\begin{code}
 > tstl\_replay normalized.test --verbose
 STEP \#0: ACTION: c0 = sympy.Integer(1)
 c0 = None : <type 'NoneType'>
 => c0 = 1 : <class 'sympy.core.numbers.One'>
 ==================================================
 STEP \#1: ACTION: v0 = sympy.Symbol('a')
 v0 = None : <type 'NoneType'>
 => v0 = a : <class 'sympy.core.symbol.Symbol'>
 ==================================================
 STEP \#2: ACTION: expr0 = c0
 c0 = 1 : <class 'sympy.core.numbers.One'>
 expr0 = None : <type 'NoneType'>
 => expr0 = 1 : <class 'sympy.core.numbers.One'>
 ==================================================
 STEP \#3: ACTION: expr1 = sympy.Sum(expr0,(v0,c0,c0))
 c0 = 1 : <class 'sympy.core.numbers.One'>
 v0 = a : <class 'sympy.core.symbol.Symbol'>
 expr0 = 1 : <class 'sympy.core.numbers.One'>
 expr1 = None : <type 'NoneType'>
 => expr1 = Sum(1, (a, 1, 1)) : <class 'sympy.concrete.summations.Sum'>
 ==================================================
 STEP \#4: ACTION: expr0 = expr0 \% expr1
 expr0 = 1 : <class 'sympy.core.numbers.One'>
 expr1 = Sum(1, (a, 1, 1)) : <class 'sympy.concrete.summations.Sum'>
 RAISED EXCEPTION: <type 'exceptions.RuntimeError'>
   maximum recursion depth exceeded in cmp
 FAILED STEP
 (<type 'exceptions.RuntimeError'>,
 RuntimeError('maximum recursion depth exceeded in cmp',)
 ...
\end{code}
}
\caption{Verbose replay of a TSTL test.}
\label{fig:verbose}
\end{figure}

In addition to replaying a single test, we can replay a number of
saved tests using the {\tt tstl\_regress} command, which takes as
input a list of all test files to run, and produces a coverage report
in addition to the outcome of each test.  By default it stops on the
first failing test, but can be directed to run all tests with {\tt
  --keepGoing}.  Regression runs can also generate an HTML coverage report using the
facilities of the {\tt coverage.py} library \cite{Coveragepy}.

Finally, we can \emph{generalize} the test, to see what
alternative, similar tests also produce the same failure:

{\scriptsize
\begin{code}
 > tstl\_generalize normalized.test
 GENERALIZING...
 \#[
 c0 = sympy.Integer(1)                               \# STEP 0
 \#  or c0 = sympy.Integer(2)
 \#   - c0 = sympy.Integer(10)
 v0 = sympy.Symbol('a')                              \# STEP 1
 \#  or v0 = sympy.Symbol('b')
 \#   - v0 = sympy.Symbol('d')
 \#  or v0 = sympy.Symbol('x')
 \#   - v0 = sympy.Symbol('z')
 \#  or v0 = sympy.Symbol('e',positive=True)
 \#   - v0 = sympy.Symbol('l',positive=True)
 \#  swaps with step 2
 \#] (steps in [] can be in any order)
 expr0 = c0                                          \# STEP 2
 \#  or expr0 = sympy.Rational(c0,c0)
 \#  or expr0 = sympy.pi
 \#  or expr0 = sympy.E
 \#  or expr0 = sympy.I
 \#  swaps with step 1
 expr1 = sympy.Sum(expr0,(v0,c0,c0))                 \# STEP 3
 \#  or expr1 = sympy.Product(expr0,(v0,c0,c0))
 expr0 = expr0 \% expr1                               \# STEP 4
 \#  or expr2 = expr0 \% expr1
 \#  or expr3 = expr0 \% expr1
 GENERALIZED IN 239.682291985 SECONDS
\end{code}
}

With this information, the basic underlying structure
of the fault is made clear:  using the modulo operator on a {\tt Sum}
or {\tt Product} over an empty range (whether that range is $2 \ldots 2$ or
$\pi \ldots \pi$, with any variable name allowed by our SymPy harness,
causes the failure.  The ordering of operations, other than to the
extent required for data flow, is not important.

Now that we understand the fault, we may want a non-TSTL test to run
in a debugger to try out possible solutions.  Generating a standalone
Python executable
test is easy:

{\scriptsize
\begin{code}
 > tstl\_standalone normalized.test normalized.py
\end{code}
}

In this example, reduction or normalization has always been with
respect to a failure.  However, simply by providing the {\tt
  --coverage} option to {\tt tstl\_reduce} or {\tt tstl\_generalize}
the same approaches can be applied to reduce tests by their code
coverage, a useful method for producing very efficient regression tests
\cite{icst2014,stvrcausereduce}.  Running {\tt tstl\_rt} with the {\tt
  --quickTests} option will also produce a suite of such
coverage-based reduced regression tests.

\section{Avoiding Slippage}

Test slippage \cite{PLDI13,slippage} is when a weak
labeling of failed tests (e.g., simply checking that a failing test
still causes some kind of uncaught exception) results in a test that
originally failed due to one fault being reduced to a test that fails
due to a different fault.

There is a need for flexibility in handling slippage and fault
signatures in general; with some programs, many exceptions may reveal
the same fault, with other programs even the same assertion on the
same line of code can be violated due to different underlying faults.
TSTL therefore provides a few ways to avoid slippage, and also some ways to
intentionally induce ``good'' slippage where a failing test is reduced
to produce multiple tests that fail due to different faults
\cite{slippage}.  First, the random test generator and the reduction,
and generalization tools all take the {\tt --keepLast}
option, which forces reduced tests to have the same final action as
the original test.  This is a heuristic for avoiding slippage
discovered during file system testing at NASA \cite{ICSEDiff}.
Second, the reducer and generalizer take a {\tt --matchException}
argument that forces reductions to fail due to the same type of
exception (but not exact message); this is the default behavior for the random
tester, where the user has more reason to be concerned about losing
the original fault since it is not stored in a file.

While these methods are useful for producing more precise labels for
failure, they are not helpful in instances where precise labeling is
impossible, such as many differential testing settings \cite{PLDI13}.
For these cases, and for using reduction as a mutation-based fuzzing
tool to look for new faults, TSTL provides two more modes.  First,
using the {\tt --multiple} option configures {\tt tstl\_reduce} to use
the {\tt comb-block} algorithm \cite{slippage} to attempt to produce
as many reduced tests as possible, that are all as different as
possible from each other.  The effort extended to consider
combinations of test components can be configured with the {\tt
  --recursive} and {\tt --limit} options.  Second, the {\tt --random}
flag to the reducer causes the order of possible reductions to be
randomized, so that different runs of the reducer will produce
different reduced tests.

\section{API Access to Tool Functionality}

In addition to the command-line tools described here, TSTL also makes
it easy to perform sophisticated test manipulations in code.  When a
TSTL harness is compiled it produces an {\tt sut} module providing an
abstract interface for testing the SUT.  It is this interface that
{\tt tstl\_rt}, {\tt tstl\_reduce}, and the other tools interact with,
making test generation and manipulation independent of the SUT.

The interface includes {\tt reduce}, {\tt normalize} and {\tt
  generalize} methods for reduction and normalization that provide
many more parameters for fine-tuned control of the algorithms than are
provided by the command line tools.  These methods are all
higher-order functions, so the predicate for the algorithm to maintain
as true can be an arbitrary function of a test.  The interface to the
SUT also provides methods to return commonly used predicates, such as
matching the coverage of a test, or failing a property check.  Because
TSTL's reduction implementations do not require their initial input to
satsify the predicate, this can be used for unusual applications.  For
example, if are testing an XML parser, have a long, high-coverage
test, and wish to modify it to produce an input that takes as long as
possible to parse, we can define a function:

{\scriptsize
\begin{code}
def takesLonger(t):
      global WCET, SUT
      start = time.time()
      SUT.replay(t)
      elapsed = time.time() - start
      if elapsed > WCET:
         WCET = elapsed
         return True
      return False
\end{code}
}

and call {\tt SUT.reduce(longTest,takeLonger)} after setting WCET to the
runtime for the initial test.


% !TEX root =main.tex

\section{C-TLP Security Proof}\label{CR-TLP-Proof}

In this section, we present   the security proof of C-TLP scheme. We first prove that without solving $j\text{\small{-th}}$ puzzle, a solver cannot find the parameters  needed to solve the next puzzle, i.e. $(j+1)\text{\small{-th}}$   one.

  \begin{lemma}[Next Group Generator Privacy]\label{lemma::Next-Generator-Privacy}  Let $k$ be a random key for a symmetric key encryption, and  $N$ be a  sufficiently large RSA modulus. Let  the security parameter be $\lambda=|N|=|k|$.  In C-TLP, given puzzle vector: $\vv{\bm{o}}$ and public key: $pk$, an adversary $\mathcal{A}=(\mathcal{A}_{\scriptscriptstyle 1},\mathcal{A}_{\scriptscriptstyle 2})$, defined in Section \ref{Section::Multi-instance-Time-lock Puzzle-Definition},  cannot find the next group generator:
$r_{\scriptscriptstyle j+1}$, where $r_{\scriptscriptstyle j+1} \stackrel{\scriptscriptstyle\$}\leftarrow \mathbb{Z}^{\scriptscriptstyle *}_{\scriptscriptstyle N}$and $j\geq1$, significantly smaller than   $T_{\scriptscriptstyle j}=\delta(j\Delta)$, except with a negligible probability in the security parameter, $\mu(\lambda)$
  \end{lemma}
 \begin{proof}
Since the next generator: $r_{\scriptscriptstyle j+1}$, is: (a) encrypted along with the $j\text{\small{-th}}$ puzzle solution: $s_{\scriptscriptstyle j}$, and (b)  picked uniformly at random from $\mathbb{Z}^{\scriptscriptstyle *}_{\scriptscriptstyle N}$, for the adversary to find $r_{\scriptscriptstyle j+1}$ without performing enough squaring, i.e. $T_{\scriptscriptstyle j}$, it has to either (a) break the symmetric key scheme, decrypt the related ciphertext: $s_{\scriptscriptstyle i}$ and extract the random value from it, or (b) correctly guess $r_{\scriptscriptstyle j+1}$. In both cases, the probability of success is negligible in secure parameter $\mu(\lambda)$,  i.e. $2^{\scriptscriptstyle -|k|}$ in the former case and $2^{\scriptscriptstyle -|N|}$ in the latter one.
 \hfill\(\Box\)
  \end{proof}
%. But its  probability of success is $2^{\scriptscriptstyle -|k|}$ that is negligible in the security parameter,  or  guess $r_{\scriptscriptstyle j+1}$, that has the probability of success  at most $2^{\scriptscriptstyle -|N|}$ which is negligible in $\lambda$ as well.    %\hfill\(\Box\)
 %t \end{proof}

 In the following, we prove that the privacy of a solution in C-TLP scheme is preserved according to Definition \ref{Def::Solution-Privacy}.

 \begin{theorem} [C-TLP Solution Privacy]\label{Solution-Privacy} Let $N$ be a  strong RSA modulus and $\Delta$ be a time parameter. If the sequential squaring assumption holds,  factoring $N$ is a hard problem, $\mathtt{H}(.)$ is a random oracle and the symmetric key encryption is  semantically secure, then  C-TLP encoding $z$ solutions is a privacy-preserving multi-instance time-lock puzzle w.r.t. Definition \ref{Def::Solution-Privacy}.
 \end{theorem}
  \begin{proof} In the following, we argue  for an adversary $\mathcal{A}=(\mathcal{A}_{\scriptscriptstyle 1},\mathcal{A}_{\scriptscriptstyle 2})$, where $\mathcal{A}_{\scriptscriptstyle 1}$ runs in total time $O(poly(j\Delta,\lambda))$,  $\mathcal{A}_{\scriptscriptstyle 2}$ runs in  time $\delta(j\Delta)<j\Delta$ using at most $\pi(\Delta)$ parallel processors, and  $j\in [1,z]$,  (a) when $z=1$: to find $s_{\scriptscriptstyle 1}$ earlier than $\delta(\Delta)$,  it has to  break the TLP scheme, and (b) when $z>1$: to find $s_{\scriptscriptstyle j}$ earlier than $T_{\scriptscriptstyle j}=\delta(j\Delta)$, it has to either find   at least one of the previous solutions earlier than it is supposed to (that ultimately requires breaking TLP scheme again), or find $j\text{\small{-th}}$ generator: $r_{\scriptscriptstyle j}$, earlier. Also, we argue that the commitments: $h_{\scriptscriptstyle j}$, are computationally hiding.   Specifically, when $z=1$, the security of C-TLP is reduced to the security of  the TLP and the scheme is secure as long as TLP is, as the two schemes would be identical. On the other hand, when $z>1$, the adversary has to either find $s_{\scriptscriptstyle j}$ earlier than $T_{\scriptscriptstyle j}$ as soon as the previous solution: $s_{\scriptscriptstyle j-1}$ is found that requires either breaking the TLP scheme, or finding any generator $r_{\scriptscriptstyle j}$  before $s_{\scriptscriptstyle j-1}$ is extracted, when $j\in [2,z]$. Nevertheless, the TLP scheme is secure (under RSA,  sequential squaring, and security of symmetric key encryption assumptions) according to  Theorem \ref{theorem::R-LTP-Sec}, and also the probability of finding the next generator: $r_{\scriptscriptstyle j}$ earlier than $T_{\scriptscriptstyle j-1}$ is negligible, according to Lemma \ref{lemma::Next-Generator-Privacy}. Moreover, for an adversary to find a solution earlier, it may also try to find a (partial information of) pre-image of the commitment: $h_{\scriptscriptstyle j}$ before fully (or without) solving the puzzle. But, this is infeasible for a PPT adversary, given  output of a random oracle: $\mathtt{H}(.)$. Thus, C-TLP is a privacy-preserving multi-instance time-lock puzzle scheme.  \hfill\(\Box\)
  \end{proof}

Next, we prove that the validity of a solution in C-TLP scheme is preserved according to Definition \ref{Def::Solution-Validity}.
  \begin{theorem} [C-TLP Solution Validity]\label{Solution-Validity} Let $\mathtt{H}(.)$ be a hash function modeled as a random oracle. Then, C-TLP preserves a solution validity w.r.t. Definition \ref{Def::Solution-Validity}.
\end{theorem}
\begin{proof}
 The proof  boils down to  the security (i.e. binding property) of the traditional hash-based commitment scheme. In particular, given an  opening pair, $\ddot{p}:(m_{\scriptscriptstyle j},d_{\scriptscriptstyle j})$ and the commitment $h_{\scriptscriptstyle j}=\mathtt{H}(m_{\scriptscriptstyle j},d_{\scriptscriptstyle j})$, for an adversary to break the solution validity, it has to come up $(m'_{\scriptscriptstyle j},d'_{\scriptscriptstyle j})$, such that $\mathtt{H}(m'_{\scriptscriptstyle j},d'_{\scriptscriptstyle j})=h_{\scriptscriptstyle j}$, where $m_{\scriptscriptstyle j}\neq m'_{\scriptscriptstyle j}$, i.e. finds a collision of $\mathtt{H}(.)$. However, this is infeasible for a PPT adversary, as $\mathtt{H}(.)$ is collision resistance, in the random oracle model.
 \hfill\(\Box\)
\end{proof}

 In the following, we restate the main theorem presented in Section \ref{Section::C-TLP-protocol} and then prove it.

\

\noindent\textbf{Theorem \ref{C-TLP-Sec} (C-TLP Security).} \textit{C-TLP  is a secure multi-instance time-lock puzzle. }

 \begin{proof} According to Theorems \ref{Solution-Privacy} and \ref{Solution-Validity}, the privacy and validity of a solution in C-TLP are preserved, respectively.   So, w.r.t. Definition \ref{def::C-TLP-security}, C-TLP is a secure multi-instance  time-lock puzzle.
  \hfill\(\Box\)
\end{proof}


\chapter{Agglomerative Hierarchical Clusters}
\label{app:h-clu}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[DTW].png}
  \caption{ Hierarchical Clusters: Dynamic Time Warping}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[Ed].png}
  \caption{ Hierarchical Clusters: Euclidean Distance}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[EDR;e=.101].png}
  \caption{ Hierarchical Clusters: Edit Distance on Real Sequence, $\epsilon=0.101$}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[EDR;e=.203].png}
  \caption{ Hierarchical Clusters: Edit Distance on Real Sequence, $\epsilon=0.203$}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[ERP;g=0,0].png}
  \caption{ Hierarchical Clusters: Edit Distance with Real Penalty}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[Hd].png}
  \caption{ Hierarchical Clusters: Hausdorff Distance}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[MSM;c=1].png}
  \caption{ Hierarchical Clusters: Move-Split-Merge, cost$=1$}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[MSM;c=.1].png}
  \caption{ Hierarchical Clusters:Move-Split-Merge, cost$=0.1$}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[MSM;c=.01].png}
  \caption{ Hierarchical Clusters:Move-Split-Merge, cost$=0.01$}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[width=\linewidth,height=\textheight,keepaspectratio]{figs/clusters/CLU_H_ALL[SSPD].png}
  \caption{ Hierarchical Clusters: Symmetrized Segment-Path Distance }
\end{figure}


\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[super]{nth}
\title{Interface for Field Access}
\author{Dan Ibanez, SCOREC}
\date{May 15, 2014}
\begin{document}
\maketitle

\section{Goal}

This document aims to establish a consensus on
basic operations that should be made available
by finite element toolkits for accessing finite
element field data attached to a mesh.

\section{Definitions}

A finite element mesh $M$ represents a domain
$\Omega^h \subset {\mathbb R^D}$
composed of entity domains $\Omega_e$:
\[\Omega^h = \bigcup_{e\in M} \Omega_e\]

A finite element field $f : \Omega^h \to T$ is a piece-wise field
from the mesh domain to some tensor space $T$, where
each piece is $f_e : \Omega_e \to T$.
The entity domains have parametric, or parent, coordinate
systems and a map from parametric points $\xi \in {\mathbb R^d}$
to points in the entity domain $X_e(\xi) \in \Omega_e$.

The value of a field at a point $x$ in an entity domain $\Omega_e$
is entirely defined by the corresponding parametric point $\xi$
and a set of tensor multipliers $\bar{W}_e = \{\bar{W}_e^0,...,\bar{W}_e^n\}$
which affect that entity:
\[x\in \Omega_e, x = X_e(\xi), f(x) = f_e(\xi,\bar{W}_e)\]
For example, in a linear tetrahedral mesh the set $\bar{W}_e$ contains
the field values at the vertices of an entity.

The field multipliers are each associated with a unique mesh entity
to allow sharing between entities.
The set of multiplier tensors associated with entity $e$ is denoted
$W_e = \{W_e^0,...,W_e^m\}$.
The set of tensors which affect the field definition over an entity
is composed of tensors associated to nearby entities, usually to
entities in its closure:
\[\bar{W}_e = \bigcup_{a \in \bar{e}} W_a\]
To reuse our example, in linear tetrahedral meshes multipliers are
the field values associated with vertices, and the multipliers
which affect a tetrahedron are those associated to its vertices.

\section{Requirements}

To describe a field, two key pieces of information are needed:
\begin{enumerate}
\item The entity basis functions $f_e(\xi,\bar{W}_e)$ for all $e\in M$.
\item The associated multipliers $W_e$ for all $e \in M$
\end{enumerate}
The description of $f_e$ encompasses several smaller pieces of information:
\begin{enumerate}
\item The parent domain $\Box_e$ such that $X_e(\Box_e)=\Omega_e$.
\item The how many multipliers are associated with each entity: $|W_e|$.
\item How to collect all affecting multipliers: $g(e) = \bar{W}_e$.
\end{enumerate}
Depending on the complexity of the field, much of this information
can be recorded {\it a priori}.
For example, the description of $f_e$ may be just ``\nth{2}-order Lagrange"
or ``Cubic B\'ezier".
In more complex cases such as variable-order fields, information
such as $|W_e|$ and $g$ may have to be specified on a per-entity basis.

\section{Coordinates}

Note that the coordinates are themselves a field $X_e : \Box_e \to \Omega_e$,
and should have equivalent availability of information.
For example, it should be possible to query the basis functions
being used to define coordinates.

\section{Interface}

We will assume an adequate existing interface for topological
mesh descriptions, so that operations such as iterating over
$e \in M$ and getting the entities $a \in \bar{e}$ are available
and efficient.

At a high level, it should also be possible to query the set of fields
defined over a particular mesh.
Fields and entities should have identifying handles that can be efficiently
interpreted by the software.

At a minimum, just to preserve field data, it must be possible to access
tensor multipliers associated with entities.
That is, for a given entity $e$, the count $n=|W_e|$ and values
$W_e^i,1\leq i\leq n$ must be quickly accessible.
Of course, prerequisite to retrieving $W_e^i$ is some agreement on the
storage format for tensor values.
For each $f : \Omega^h \to T$,
the storage format for $t\in T$ should be accessible.

To preserve a complete description of the field, it should also be
possible to query the exact basis functions $f_e$ being used for
each entity, along with the closely associated procedure $g$ for
collecting the ordered set of tensor multipliers $\bar{W}_e$ that
are weighted by $f_e$ based on $\xi$ to produce $f(x)$.

\end{document}


\documentclass[12pt,answers,addpoints]{exam}

%============Macros==================%
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{qcircuit}
\usepackage[margin=1in]{geometry}
%--------------Cosmetic----------------%
\usepackage{mathtools}
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,
    urlcolor=cyan,
}
\usepackage{fullpage}
\usepackage{microtype}
\usepackage{xspace}
\usepackage[svgnames]{xcolor}
\usepackage[sc]{mathpazo}
\usepackage{enumitem}
\setlist[enumerate]{itemsep=1pt,topsep=2pt}
\setlist[itemize]{itemsep=1pt,topsep=2pt}
%-----defs and commands-----%
\def\mG{[\textbf{G}]\xspace}
\def\veps{\varepsilon}
\def\tr{\mathrm{tr}}
\newcommand{\bit}{\{0,1\}}
\newcommand{\bra}[1]{\langle #1 \rvert}
\newcommand{\ket}[1]{\lvert #1 \rangle}
\newcommand{\kera}[1]{\ket{#1}\bra{#1}}
\newcommand{\negl}{\text{negl}}
\newcommand{\complex}{\mathbb{C}}
\newcommand{\integer}{\mathbb{Z}}
\newcommand{\srd}[2]{\textsf{SR}_{#1}^{#2}(X)}
\newcommand{\corr}[1]{{\color{blue}{#1}}}
% \input{../head}
%----------Header--------------------%

\newcommand{\classn}{CSCE 440/640 Quantum Algorithms}
\newcommand{\classnabbr}{CSCE 440/640}
\newcommand{\school}{Texas A\&M U}
\newcommand{\term}{Spring 2019}
\newcommand{\examdate}{March 18, 2019}
\newcommand{\duedate}{March 20, 2019, 11:59pm, AoE}
\newcommand{\examnum}{Mid-term Exam}
\newcommand{\studentname}{\makebox[1.5in]{\hrulefill}} % change it to your name
\pagestyle{head}
\firstpageheader{}{}{}
\runningheader{\classnabbr}{\examnum\ - Page \thepage\ of
  \numpages}{\term}
\vskip 1ex
\setlength{\headsep}{10pt}
\runningheadrule

%\qzheader                       % execute quiz commands

\begin{document}

\noindent
\begin{tabular*}{\textwidth}{l @{\extracolsep{\fill}} r
    @{\extracolsep{6pt}} r}
  {\Large\textbf{\examnum}} & \Large{\textbf{Name:}} & \studentname\\
  {\term}, {\classn} & &  {\examdate}\\
  \school && Prof. Fang Song
\end{tabular*}\\

\rule[2ex]{\textwidth}{1pt}

\subsection*{Instructions (please read carefully before start!)}

\begin{itemize}
\item This take-home exam contains \numpages\ pages (including this
  cover page) and \numquestions\ questions. Total of points is
  \numpoints.
\item You will have till \textbf{\duedate}~(Anywhere on Earth) to
  finish the exam. You must work on your own, and no collaboration or
  help from any resources other than those made available in class
  (lecture notes, recommended texts, homework problems, etc.)  is
  permitted.

\item Email me your solutions in PDF before the deadline, either
  scanned or typeset in \LaTeX. Name your PDF and email subject as:
  \textbf{Lastname\_Firstname\_s19\_mt}. If you choose to hand-write
  and scan, \emph{print out this exam sheet and write your solutions
    on it}. Do your best to fit your answers into the space provided,
  and attach extra papers only if necessary. If you typeset in \LaTeX,
  \emph{use the provided TeX file}. No other formats are accepted.

\item Your work will be graded on correctness and clarity. Make sure
  your hand writing is legible.
\item Don't forget to write your name on top (or update the
  ``{\textbackslash}studentname'' command in the TeX file)!
\end{itemize}

\begin{center}
\textbf{Grade Table} (for instructor use only)\\
\smallskip
\addpoints
\gradetable[v][questions]
\end{center}

\newpage

\begin{questions}
  \question \emph{Short answers}. Answer the following, and briefly
  justify your answer.
  \begin{parts}
    \part[0] (Sample problem) Is
    $\sqrt{i/3} \ket{0} + \sqrt{2/5}\ket{1}$ a valid quantum state?

    \begin{solution}
      Answer: No.\\
      Justification: Because $|\sqrt{i/3}|^2 + |\sqrt{2/5}|^2 \neq 1$.
    \end{solution}

    \part[5] Is $\frac{1}{\sqrt{2}}(\ket{000} + \ket{111})$ an
    entangled state?

    \vskip 3cm
    \part[5] Quantum computers can solve NP-Complete problems in
    polynomial time. Is this statement True/False/Unknown?

   \vskip 3cm % comment this line when typing your answer

   \part[5] Recall in the quantum superdense coding protocol, Alice
   wants to send two classical bits to Bob by sending one
   qubit. Suppose a third party (Eve) intercepts Alice's qubit on the
   way. Can Eve infer anything about which of the four possible bit
   strings 00, 01, 10, 11 Alice was trying to send?

   \vskip 4cm

   \part[5] What is the Quantum Fourier Transform $F_{2^4}$ on a
   four-qubit state
   $ \frac{1}{4}\ket{0000} + \frac{i}{4}\ket{0010} +
   \sqrt{\frac{5}{8}}\ket{1111}$?

 \end{parts}
  \newpage
  \question (Quantum circuits)

  \begin{parts}
    \part[10] Suppose you have an unlimited supply of qubits in the state
    $\ket{\psi} = \alpha\ket{0}+\beta\ket{1}$, and qubits in the state
    $\ket{0}$. Give quantum circuits and specify the inputs for
    producing the following quantum states:

    \begin{enumerate}[label=\roman*)]
    \item
      $\alpha^2\ket{00} - \alpha\beta\ket{01} + \alpha\beta\ket{10} -
      \beta^2\ket{11}$.

      \vskip 3cm
    \item $\alpha\ket{00} - \beta\ket{11}$.  \vskip 3cm
    \end{enumerate}
    \part[20] For each pair of the circuits below, prove or disprove that
    they are equivalent.

    \begin{enumerate}[label=\roman*)]
      \item
        \[ \Qcircuit @C=1em @R=.7em { & \gate{H} & \gate{X} &
            \gate{H}&\qw & \overset{?}{=} & & \gate{Z}
          & \qw } \] \vskip 4cm
      \item
        \[ \Qcircuit @C=1em @R=.7em {
            & \ctrl{2} & \qw  &  & & \gate{-Z}& \qw \\
            &&& \overset{?}{=} & & &\\
            & \gate{Z} & \qw &&&\ctrl{-2}& \qw}
        \]
        \newpage
      \item
        \[ \Qcircuit @C=1em @R=.7em {
            &  \gate{H} & \ctrl{2} & \gate{H}& \qw  &  & & \targ & \qw \\
            &&&&& \overset{?}{=} & & &\\
            &\gate{H} & \targ & \gate{H} & \qw &&&\ctrl{-2}& \qw}
        \]
        \vskip 5cm
      \item Let $U,V$ be unitary, and $V^2 =U$. The left-hand-side is
        $U$ controlled by two qubits $\ket{a}\ket{b}$ such that $U$ is
        applied to the third qubit iff. $a = b = 1$.
        \[ \Qcircuit @C=1em @R=.7em { & \ctrl{2} & \qw & & & \qw &
            \ctrl{1}& \qw & \ctrl{1} &
            \ctrl{2} & \qw \\
            &\ctrl{1}& \qw & \overset{?}{=} & &\ctrl{1}& \targ& \ctrl{1}&\targ &\qw &\qw\\
            &\gate{U} & \qw & & &\gate{V}&\qw &\gate{V^\dagger}& \qw
            &\gate{V} & \qw }
        \]
        \vskip 5cm
      \end{enumerate}
      \part[5] Construct a CNOT gate from one controlled-Z gate and two
      Hadamard gates.
      \newpage
      \part[5] (Phase estimation: alternative) Let $U$ be an $n$-qubit
      unitary operator and $\ket{\psi}$ be an eigenvector with
      $U\ket{\psi} = e^{i \theta } \ket{\psi}$. Analyze the circuit
      below and derive the probability that the measurement outcome is
      $0$.

      \begin{figure}[h!]\label{fig:ape}
        \centerline{\Qcircuit @C=1em @R=.7em {
            \lstick{\ket{0}}&  \gate{H} & \ctrl{1} & \gate{H}& \meter &\cw  \\
            \lstick{\ket{\psi}} & \qw & \gate{U} &\qw & \qw & \qw
          }}
        \caption{Alternative phase estimation algorithm}
      \end{figure}

      \vskip 5cm
      \part (15 Bonus points) Continue from part (d).
      \begin{enumerate}[label=\roman*)]
      \item How many times do we need to repeat the circuit in
        Figure~\ref{fig:ape} to get an estimate $\tilde \theta$ so
        that $|\theta - \tilde \theta | \leq \varepsilon$ with
        probability at least $1 - \delta$?  \vskip 5cm
      \item Suppose you can replace $U$ by $U^k$ for an arbitrary
        integer $k$ of your choice (still controlled by one
        qubit). Show how to approximate $\theta$.
      \end{enumerate}
    \end{parts}

  \newpage
  \question (Quantum algorithms and permutations) A bijection
  $P: \bit^m\to \bit^m $ is called a permutation on $\bit^m$.

  \begin{parts}
    \part[5] How many permutations are there in total on $\bit^m$?
    \vskip 3cm

    \part[6] Let $S$ be the set of all permutations on
    $\bit^m$. Consider a subset $\{P_k\}\subseteq S$ which are indexed
    by $n$-bit keys $k\in \bit^n$ for some $n \leq m$. We are now
    given $(x_1,\ldots, x_t)$ and $(y_1,\ldots, y_t)$ with the promise
    that there is a \emph{unique} $k^*\in \bit^n$ such that
    $P_k(x_i) = y_i$ for all $i =1,\ldots, t$. The goal is to identify
    this key $k^*$.  Let us consider classical algorithms
    first. Suppose we have access to an oracle
    $O: (k,x)\mapsto P_k(x)$. How many queries are sufficient to
    determine $k^*$ in the worst case?  How many are necessary?
    Justify your answer.

      \vfill

    \part[14] Continue from above. Suppose $O$ can be queried in quantum
      superposition, i.e., it is given as a black-box quantum circuit
      implementing the unitary
      \[ U: \ket{k}\ket{x}\ket{y} \mapsto \ket{k}\ket{x}\ket{y\oplus
          P_k(x)}, \forall k\in \bit^n, x,y\in \bit^m \, .\]

      \begin{enumerate}[label=\roman*)]

      \item Show that one can implement another quantum oracle
        \[U': \ket{k} \ket{b} \mapsto \ket{k}\ket{b\oplus f(k)}\, ,\]
        where $f:\bit^n \to \bit$ is such that $f(k) = 1$ iff.
        $P_k(x_i) = y_i$ for all $i = 1,\ldots, t$. How many calls to
        $U$ are needed to answer one query to $U'$?
        \newpage
        \begin{center}
(Problem 3.c continued)
        \end{center}

        \vskip 8cm
      \item Give a quantum algorithm for finding $k^*$. Describe its
        cost in terms of \# of queries to $U$ and the circuit size.
      \end{enumerate}
      \vskip 6cm
      \part (15 Bonus points) Let $k_1,k_2\in \bit^n$ be two secret
      strings and $\pi: \bit^n\to \bit^n$ be a permutation. Define
      another permutation\footnote{This is the Even-Mansour block
        cipher.} $P_{k_1,k_2}: \bit^n \to \bit^n$ as
      \[ P_{k_1,k_2}: x\mapsto \pi(x\oplus k_1)\oplus k_2 \, .\]

      \begin{enumerate}[label=\roman*)]
      \item Define a function $f$ from $\pi$ and $P_{k_1,k_2}$ such
        that for all $x$, $f(x\oplus k_1) = x$.
        \newpage
      \item Suppose $\pi$ is sampled uniformly at random among all
        permutations on $\bit^n$. Given quantum oracles for $\pi$ and
        $P_{k_1,k_2}$, describe a quantum algorithm that recovers
        $k_1,k_2$ efficiently.
      \end{enumerate}
  \end{parts}

\end{questions}
\newpage
\begin{center}
Scrap paper -- no exam questions here.
\end{center}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End: