\chapter{uguard}

\section{Introduction}

\txs{} checks whether or not there is \emph{input-output-conformance} of an implementation with the \emph{underspecified} traces of its specification (u-ioco, see \cite{volpato2013towards}).
In this context, the specification has only to be u-ioco with itself, and it can therefore potentially be rewritten more aggressively than when a models must preserve a stronger equivalence relation.

Unfortunately, there is no information about the traces of a model that can be extracted directly from that model while it is in LPE form.
The \texttt{uguard} command is an attempt to symbolically detect a specific, relatively simple pattern with actions that do not follow the u-ioco definition.
Upon detection, the command adds guards to the LPE to exclude the underspecified actions from the model (hence its name).

\section{Formal background}

\subsection{Summand implication}

Consider two summands, $s_\alpha$ and $s_\beta$, and reference their elements conform \ref{summandelements}.

Summand $s_\alpha$ is said to \emph{imply} $s_\beta$ if these two conditions hold:

\begin{itemize}
\item $s_\alpha$ and $s_\beta$ must communicate over the exact same channel with exactly as many channel variables; that is, $C_\alpha = C_\beta \land m_\alpha = m_\beta$.

\item Define the mapping
\begin{align*}
X_\beta = [x_\alpha(j) \rightarrow x_\beta(j) \;|\; 1 \leq j \leq \text{min}(m_1, m_2)]
\end{align*}

The following condition must be a tautology:
\begin{align*}
g_\alpha[X_\beta] \rightarrow g_\beta
\end{align*}
\end{itemize}

\subsection{Possible input-successors}

Consider a summand pair $(s_\alpha, s_\beta)$, referencing the elements of $s_\alpha$ and $s_\beta$ conform \ref{summandelements}.
Summand $s_\beta$ is said to be a \emph{possible input-successor} of $s_\alpha$ if $C_\beta$ is an input channel and if the following expression is satisfiable:
\begin{align*}
g_\alpha \land {g_\beta}[v \rightarrow q(v) \;|\; v \in \varsof{g_\beta} \setminus P][p \rightarrow v_\alpha(p) \;|\; p \in P]
\end{align*}

where $q(v)$ is a bijective function that relates variable $v$ to a fresh variable.

\subsection{Definite input-successors}

Consider a summand pair $(s_\alpha, s_\beta)$, referencing the elements of $s_\alpha$ and $s_\beta$ conform \ref{summandelements}.
Summand $s_\beta$ is said to be a \emph{definite input-successor} of $s_\alpha$ if $C_\beta$ is an input channel and if the following expression is a tautology:
\begin{align*}
g_\alpha \rightarrow {g_\beta}[v \mapsto q(v) \;|\; v \in \varsof{g_\beta} \setminus P][p \mapsto v_\alpha(p) \;|\; p \in P]
\end{align*}

where $q(v)$ is a bijective function that relates variable $v$ to a fresh variable.

\section{Algorithm}

Let the input LPE model be $M$ and the underlying LPE be $P$.
The \texttt{uguard} algorithm follows these steps for all summand pairs $(s_\alpha, s_\beta)$ such that $s_\alpha$ implies $s_\beta$:

\begin{enumerate}
\item Compute $\Delta = (D_\beta \setminus P_\alpha) \cup (D_\alpha \setminus P_\beta)$ where
\begin{itemize}
\item $P_\alpha$ is the set of all possible input-successors of $s_\alpha$;
\item $P_\beta$ is the set of all possible input-successors of $s_\beta$;
\item $D_\alpha$ is the set of all definite input-successors of $s_\alpha$; and
\item $D_\beta$ is the set of all definite input-successors of $s_\beta$.
\end{itemize}

If $\Delta = \emptyset{}$, the \texttt{uguard} algorithm does not make any changes and stops.
Otherwise, it continues.

\item Create a new LPE $P'$ with the same parameters as $P$, but without any summands.
Create a new LPE model $M'$ that has the same definition as $M$, except that its references to $P$ have been replaced by references to $P'$.

\item Add a new, fresh parameter $f$ of type \texttt{Bool} to $P'$.
Where $M'$ instantiates $P'$, initialize $f$ with $\textbf{true}$.

\item For each summand $s_i$ of $P$ -- referencing its elements conform \ref{summandelements} -- add to $P'$ a new summand ${s_i}'$ that is defined as
\begin{align*}
{s_i}' = C_i \; \texttt{?} \; x_i(1) \; &\cdots{} \; \texttt{?} \; x_i(m_i) \; [[\Gamma(s_i) \land g_i]] \\
&\texttt{>->} \; P(v_i(p_1), \cdots{}, v_i(p_k), \Upsilon(s_i))
\end{align*}

where
\begin{align*}
\Gamma(s) = \begin{cases}
f \text{ if } s \in \Delta \\
\textbf{true} \text{ if } s \notin \Delta
\end{cases}
\end{align*}

and
\begin{align*}
\Upsilon(s) = \begin{cases}
\textbf{true} \text{ if } s \neq s_\alpha \land s \neq s_\beta \\
\textbf{false} \text{ if } s = s_\alpha \lor s = s_\beta
\end{cases}
\end{align*}
\end{enumerate}

Intuitively, the algorithm first detects that certain summands are underspecified: they are enabled after a certain action if that action is performed by summand $s_\alpha$, but they are not enabled after that action is performed by summand $s_\beta$.
The algorithm therefore makes it so that the underspecified summands are always disabled after $s_\alpha$ or $s_\beta$ (preserving equivalence up to u-ioco).


\chapter{Verification}
\label{sec:verify}

The International Energy Agency has sponsored a number of international
research collaborations to further the state of wind energy technology and
tools.  One of these, Task 30: Offshore Code Comparison Collaboration
(OC3), shared a spar design among many participants to compare
performance as modeled by differed tool sets.  A description of the OC3
spar is provided in \citet{OC3}.  Since it is already a
well-studied geometry, the OC3 spar design was selected as the focus of
verification for \textit{FloatingSE}.  As part of the Task 30 effort,
an ANSYS model of the OC3 spar, using shell elements combined with
stiffeners and bulkheads, was also generated.  This was taken as
the \textit{truth} standard for comparison.

\section{Mass Properties}
The first step in the verification exercise was to ensure that the mass
properties of the spar predicted by \textit{FloatingSE} matched those
calculated by ANSYS.  The comparison is shown in Table \ref{tbl:verify-static},
where \textit{FloatingSE} summary mass estimates are within $1\%$ error
of ANSYS.  To ensure that these mass property calculations remain
consistent over time despite changes in the underlying code, this OC3
mass properties comparison was installed within the \textit{FloatingSE}
test framework.

\begin{table}[htbp] \begin{center}
    \caption{Mass property comparison for OC3 spar between ANSYS and \textit{FloatingSE}.}
    \label{tbl:verify-static}
{\small
  \begin{tabular}{ l c l l l } \hline
    \textbf{Property} & \textbf{Units} & \textbf{ANSYS} & \textbf{WISDEM} & \textbf{Error}\\
    \hline \hline
    Bulkhead mass & $kg$ & 67,682 & 65,951 & -2.6\% \\
    Spar shell mass & $kg$ & 1,443,711 & 1,434,436 & -0.6\%\\
    Stiffener mass  & $kg$ & 77,585 & 78,252 & 0.9\% \\
    Total mass (no ballast) & $kg$ & 1,588,978 & 1,578,639 & -0.7\%\\
    Center of gravity & $m$ & (0,0,-58.93) & (0,0,-58.84) & -0.1\%\\
    Displaced volume & $m^3$ & 1,550 &1,540 & -0.7\% \\
    Ixx moment of inertia (about CG) & $kg\cdot m^2$ & 2,178,400,000 &2,186,163,760 & 0.4\%\\
    Iyy moment of inertia (about CG) & $kg\cdot m^2$ & 2,178,400,000 &2,186,163,760 & 0.4\%\\
    Izz moment of inertia (about CG) & $kg\cdot m^2$ & 32,297,000 & 31,869,072 & -1.3\%\\
  \hline \end{tabular}
}
\end{center} \end{table}

\section{Static Loading Stress}
\subsection{Without wind and waves}
With the mass property comparison showing little difference between
ANSYS and \textit{FloatingSE} calculations, the verification proceeded
to static cases.  The spar was simulated in quiescent air and water
(no wind, waves, or current), which isolated the weight of the turbine
and hydrostatic pressure forces as the only sources on the
substructure.  The effective von Mises stress, as calculated by
\textit{FloatingSE}, was compared to the ANSYS model.  This comparison,
as a function of the z-coordinate along the spar axis ($z=0$ at the
waterline), is shown in Figure \ref{fig:verify}.  The
\textit{FloatingSE} stress calculation matches that of ANSYS nearly
exactly over the top half of the spar, but deviates by approximately
5--10\% towards the bottom half of the spar.  In the bottom half of the
spar, \textit{FloatingSE} actually over-predicts the stress, a more
conservative estimate, which is the preferable approach in a
low-fidelity cost and sizing model.

\begin{figure}[htb]
  \begin{center}
    \includegraphics[width=3in]{figs/oc3-verification_equivalentstress.png}
    \caption{Effective (von Mises) stress comparison between
      \textit{FloatingSE} and WISDEM for a pure static loading case.}
    \label{fig:verify}
  \end{center}
\end{figure}

\subsection{With wind and waves}
At this time, more complicated loading cases, with wind and wave loading
included, have not been performed.

\section{Hydrodynamic Verification}
The rigid body modes predicted by \textit{FloatingSE} were compared
against a FAST model of the OC3 spar.  FAST was used as the truth
solution in this case because it more accurately handles mooring
dynamics than the ANSYS structural model and more accurately captures
hydrodynamic phenomenon.  The results are shown in Table
\ref{tbl:verify-fast}.  The errors in the surge, sway, roll, and pitch
frequencies are 11-12\%.  \textit{FloatingSE} actually estimates the
heave mode frequency quite accurately, to less than 1\% error, but is
significantly off in estimating the yaw mode frequency.  This was deemed
acceptable as there is no focus on the yaw DOF in \textit{FloatingSE}.

\begin{table}[htbp] \begin{center}
    \caption{Rigid body eigen-mode comparison for OC3 spar between FAST and \textit{FloatingSE}.}
    \label{tbl:verify-fast}
{\small
  \begin{tabular}{ l c l l l } \hline
    \textbf{Eigenmode} & \textbf{FAST} & \textbf{WISDEM} & \textbf{Error}\\
    \hline \hline
    Platform surge [$Hz$] & 0.0080479 & 0.0071256 & -11.46\%\\
    Platform sway [$Hz$] & 0.0080475 & 0.0071256 & -11.46\% \\
    Platform heave [$Hz$] & 0.0324294 & 0.032235 & -0.60\% \\
    Platform roll [$Hz$] & 0.0342412 & 0.0385349 & 12.54\% \\
    Platform pitch [$Hz$] & 0.0342602 & 0.0385349 & 12.48\% \\
    Platform yaw [$Hz$] & 0.1210301 & 0.0526347 & -56.51\% \\
  \hline \end{tabular}
}
\end{center} \end{table}


\documentclass{article}
\usepackage{amsmath}

\begin{document}

\title{Properties and Semantics of Cassowary}
\author{Athan Clark\\ Copyright \copyright \enspace The Grid, 2015}

\maketitle

\begin{abstract}
This paper details the entailed logical properties that a linear constraint solver,
annotated with weights and error variables, should have. We hope to use this document
as a paper implementation of the automated test suites accompanied with the
Haskell and PureScript versions of Cassowary.
\end{abstract}

% Equations
\section{Equations}

The generic form for a linear inequality in standard form consists of a unique set
of variables summed together, and a constant value:

\begin{flalign}
  &\mathrm{newtype} \enspace LinVarMap \enspace \alpha \enspace = \enspace
                             LinVarMap \enspace (Map \enspace LinVarName \enspace \alpha) \label{linvarmap-def} \tag{LINVARMAP-DEF}\\
  &\mathrm{data} \enspace IneqExpr \enspace \alpha \enspace = \enspace IneqExpr \nonumber \\
  &\quad \{ \enspace coeffs \enspace :: \enspace (LinVarMap \enspace \alpha) \nonumber \\
  &\quad  , \enspace const \enspace :: \enspace Rational \enspace \} \label{ineqexpr-def} \tag{INEQEXPR-DEF}
\end{flalign}

We segregate the different forms of inequality expressions with newtypes:

\begin{flalign}
  &\mathrm{newtype} \enspace Equ \enspace \alpha \enspace = \enspace Equ \enspace (IneqExpr \enspace \alpha) \label{equ-def} \tag{EQU-DEF}\\
  &\mathrm{newtype} \enspace Lte \enspace \alpha \enspace = \enspace Lte \enspace (IneqExpr \enspace \alpha) \label{lte-def} \tag{LTE-DEF}\\
  &\mathrm{newtype} \enspace Gte \enspace \alpha \enspace = \enspace Gte \enspace (IneqExpr \enspace \alpha) \label{gte-def} \tag{GTE-DEF}
\end{flalign}

Note that the equations are polymorphic in their coefficient type - this will be
important when we introduce weights in section \ref{section-weights}.

For general inequalities, we just combine the different forms with a sum type:

\begin{flalign}
  &\mathrm{data} \enspace IneqStdForm \enspace \alpha \enspace = \nonumber \\
  &\quad \enspace \enspace EquStd \enspace (Equ \enspace \alpha) \nonumber \\
  &\quad |        \enspace LteStd \enspace (Lte \enspace \alpha) \nonumber \\
  &\quad |        \enspace GteStd \enspace (Gte \enspace \alpha) \label{ineqstdform-def} \tag{INEQSTDFORM-DEF}
\end{flalign}

A tableau is then the pair of general constraints, and constraints in basic
feasible form:

\begin{flalign}
  &\mathrm{type} \enspace Tableau \enspace \sigma \enspace = \enspace
                 (Map \enspace LinVarName \enspace \sigma, \enspace IntMap \enspace \sigma) \label{tableau-def} \tag{TABLEAU-DEF}
\end{flalign}

Where a tableau is polymorphic in the constraint type used, and split between
user variables in basic-normal form, and slack variables in basic-normal form.
This is discussed in section \ref{subsection-slack-vars}.

% Simplex
\section{Simplex}
There are several properties for dual and primal simplex method and Bland's ratio.

\subsection{Slack Variables} \label{subsection-slack-vars}

To generate slack variables, we take our list of arbitrary inequalities and turn
them into equations, annotated with the extra slack variable:

\begin{flalign*}
  &\mathrm{makeSlackVars} \enspace :: \enspace [IneqStdForm \enspace \alpha]
                 \enspace \rightarrow \enspace IntMap \enspace (Equ \enspace \alpha)
\end{flalign*}

Pivots for both primal and dual simplex will look similar - they take an objective
function and a constraint set, then refactor the equations depending on the goal:

\begin{flalign*}
  &pivotPrimal \enspace :: \enspace (Equ \enspace \alpha, \enspace Tableau \enspace (Equ \enspace \alpha)) \enspace
               \rightarrow \enspace (Equ \enspace \alpha, \enspace Tableau \enspace (Equ \enspace \alpha))\\
  &pivotDual \enspace :: \enspace (Equ \enspace \alpha, \enspace Tableau \enspace (Equ \enspace \alpha)) \enspace
             \rightarrow \enspace (Equ \enspace \alpha, \enspace Tableau \enspace (Equ \enspace \alpha))
\end{flalign*}

\subsection{Substitution}

This is the operation we take when replacing an equation.

\textbf{Lemma}: When substituting an equation on itself, the empty equation should
                result.

\begin{flalign}
  &\forall f \enspace :: \enspace IneqStdForm \enspace \alpha. \nonumber\\
  &\quad substitute \enspace f \enspace f \enspace \equiv \enspace \emptyset
\end{flalign}

\subsection{Primal}

In the primal simplex method, we first select a non-basic variable to become
basic, and a constraint out of the set that satisfies the minimum Bland ratio for
each pivot.

\subsubsection{Next Variable}

With primal simplex, first we need to select the next variable by selecting the
\textbf{most negative} coefficient in the objective function:

\[
  \mathrm{nextBasicPrimal} \enspace :: \enspace Equ \enspace \alpha \enspace
                           \rightarrow \enspace Maybe \enspace LinVarName
\]

\textbf{Lemma}: If all coefficients are positive, then the result is \(Nothing\).

\begin{flalign}
  &\forall f \enspace :: \enspace Equ \enspace \alpha \enspace | \enspace
                         all \enspace (\geq 0) \enspace \$ \enspace elems \enspace \$ \enspace coeffs \enspace f. \nonumber\\
  &\quad isNothing \enspace \$ \enspace nextBasicPrimal \enspace f \label{nbp-pos-null} \tag{NBP-POS-NULL}
\end{flalign}

\textbf{Lemma}: If there is one or more negative coefficient, then the result is
                \(Just\) the most minimum of the set.

\begin{flalign}
  &\forall f \enspace :: \enspace Equ \enspace \alpha \enspace | \enspace
                         any \enspace (< 0) \enspace \$ \enspace elems \enspace \$
                           \enspace coeffs \enspace f. \nonumber\\
  &\quad \mathrm{let} \enspace x \enspace = \enspace fromJust \enspace ( nextBasicPrimal \enspace f ) \nonumber\\
  &\quad \mathrm{in} \enspace x \enspace \equiv \enspace minimum \enspace
    (elems \enspace \$ \enspace coeffs \enspace f) \label{nbp-neg-min} \tag{NBP-NEG-MIN}
\end{flalign}

\textbf{Notes}:

\begin{enumerate}
  \item{expect \(\alpha\) to be comparable to \(0\)}
  \item{\(\alpha\) should be lexicographically ordered}
\end{enumerate}

\subsubsection{Bland's Rule}

Bland's ratio is used to determine which constraints would have the most effect
on the objective function by simply dividing the constraint's constant value
by its coefficient (for some target variable). When using the ratio, you index
for the minimum positive ratio.

\[
  blandRatioPrimal \enspace :: \enspace LinVarName \enspace \rightarrow
                               \enspace Equ \enspace \alpha \enspace \rightarrow
                               \enspace Maybe \enspace Rational
\]

\textbf{Lemma}: If denominator is \(0\), then result is \(Nothing\).

\begin{flalign}
  &\forall n \enspace :: \enspace LinVarName, \enspace
   \forall f \enspace :: \enspace Equ \enspace \alpha \enspace | \enspace
                         lookup \enspace n \enspace coeff \enspace f \enspace = \enspace 0. \nonumber\\
  &\quad isNothing \enspace (blandRatioPrimal \enspace f) \label{brp-undef-null} \tag{BRP-UNDEF-NULL}
\end{flalign}

\textbf{Lemma}: If the ratio is negative, then the result is \(Nothing\).

\begin{flalign}
  &\forall n \enspace :: \enspace LinVarName, \enspace
   \forall f \enspace :: \enspace Equ \enspace \alpha \enspace \nonumber\\
  &\quad \quad | \enspace
                         const \enspace f \enspace / \enspace lookup \enspace n \enspace (coeff \enspace f). \nonumber\\
  &\quad isNothing \enspace (blandRatioPrimal \enspace f) \label{brp-neg-null} \tag{BRP-NEG-NULL}
\end{flalign}

\textbf{Notes}:

\begin{enumerate}
  \item{expect \(\alpha\) to be comparable to \(0\)}
  \item{expect \(\alpha\) to be a denominator to \(Rational\)}
\end{enumerate}

\subsubsection{Next Constraint / Slack Variable}

The slack variables are initially unique and enumerated in all the constraints
in a tableau, and constitute as basic-normal form. When we pivot with dual or
primal simplex, we corrupt the \textit{basic-ness} of this slack variable, and populate
it in other equations (and likewise move a constraint from the \(IntMap\) to the
\(Map \enspace LinVarName\)).

We chose the next constraint from the \(IntMap\) by finding the least postivie
\textit{Bland ratio} - basically the result of dividing the equations constant by
the target variable's coefficient (note that in primal simplex, the next variable
must be found before the next row).

\[
  nextRowPrimal \enspace :: \enspace LinVarName \enspace \rightarrow
                            \enspace IntMap \enspace (Equ \enspace \alpha) \enspace \rightarrow
                            \enspace Maybe \enspace Int
\]

\textbf{Lemma}: If all coefficients are positive, then the result is \(Nothing\).

\begin{flalign}
  &\forall f \enspace :: \enspace Equ \enspace \alpha \enspace | \enspace
                         all \enspace (\geq 0) \enspace \$ \enspace elems \enspace \$ \enspace coeffs \enspace f. \nonumber\\
  &\quad isNothing \enspace \$ \enspace nextBasicPrimal \enspace f \label{nbp-pos-null} \tag{NBP-POS-NULL}
\end{flalign}

\textbf{Lemma}: If there is one or more positive ratio, then the result is the
                minimum of the set.

\begin{flalign}
  &\forall n \enspace :: \enspace LinVarName,
   \enspace fs \enspace :: \enspace IntMap \enspace (Equ \enspace \alpha),
   \enspace \exists x \enspace :: \enspace Int \nonumber\\
  &\quad \quad | \enspace blandRatioPrimal \enspace (fs \enspace !! \enspace x)
                 \enspace > \enspace 0. \nonumber\\
  &\quad \mathrm{let} \enspace x' \enspace = \enspace fromJust \enspace ( nextRowPrimal \enspace n \enspace fs ) \nonumber\\
  &\quad \mathrm{in} \enspace blandRatioPrimal \enspace (fs \enspace !! \enspace x') \enspace \equiv \nonumber\\
  &\quad \quad \enspace minimum \enspace (blandRatioPrimal \enspace <\$> \enspace fs) \label{nrp-pos-min} \tag{NRP-POS-MIN}
\end{flalign}

\textbf{Notes}:

\begin{enumerate}
  \item{We expect \(\alpha\) to be comparable to \(0\)}
  \item{Inherit from \(blandRatioPrimal\)}
\end{enumerate}

\subsection{Dual}

\subsubsection{Next Constraint / Slack Variable}

For dual simplex, we do something similar to \(nextBasicPrimal\) - we choose the
equation with the least \textit{constant value}, instead of the variable with the least
coefficient in the objective function.

\[
  nextRowDual \enspace :: \enspace IntMap \enspace (Equ \enspace \alpha) \enspace \rightarrow
                          \enspace Maybe \enspace Int
\]

\textbf{Lemma}: If all constants are positive, the result is \(Nothing\).

\begin{flalign}
  &\forall xs \enspace :: \enspace IntMap \enspace (Equ \enspace \alpha) \enspace
             \enspace | \enspace \forall x \in xs. \enspace const \enspace x \enspace > \enspace 0. \nonumber\\
  &\quad isNothing \enspace (nextRowDual \enspace xs) \label{nrd-pos-null} \tag{NRD-POS-NULL}
\end{flalign}

\textbf{Lemma}: If there's one or more negative constant, the result is the minimum.

\begin{flalign}
  &\forall xs \enspace :: \enspace IntMap \enspace (Equ \enspace \alpha) \enspace
             \enspace | \enspace \exists x \in xs. \enspace const \enspace x \enspace \leq \enspace 0. \nonumber\\
  &\quad fromJust \enspace (nextRowDual \enspace xs) \enspace \equiv \enspace
   minimum \enspace (map \enspace const \enspace xs) \label{nrd-neg-min} \tag{NRD-NEG-MIN}
\end{flalign}

\subsubsection{Bland's Rule}

We're going to invert the primal Bland ratio, such that the concepts are exactly
the same, except we swap the roles of slack and user variables, and likewise
with objective coefficients and equation constants.

\[
  blandRatioDual \enspace :: \enspace LinVarName \enspace \rightarrow
                             \enspace Equ \enspace \alpha \enspace \rightarrow
                             \enspace Maybe \enspace Rational
\]

\textbf{Lemma}: If denominator is \(0\), then result is \(Nothing\).

\begin{flalign}
  &\forall n \enspace :: \enspace LinVarName, \enspace
   \forall f \enspace :: \enspace Equ \enspace \alpha \enspace | \enspace
                         const \enspace f \enspace = \enspace 0. \nonumber\\
  &\quad isNothing \enspace (blandRatioPrimal \enspace f) \label{brd-undef-null} \tag{BRD-UNDEF-NULL}
\end{flalign}

\textbf{Lemma}: If the ratio is negative, then the result is \(Nothing\).

\begin{flalign}
  &\forall n \enspace :: \enspace LinVarName, \enspace
   \forall f \enspace :: \enspace Equ \enspace \alpha \enspace \nonumber\\
  &\quad \quad | \enspace lookup \enspace n \enspace (coeff \enspace f) \enspace /
                 \enspace const \enspace f. \nonumber\\
  &\quad isNothing \enspace (blandRatioPrimal \enspace f) \label{brd-neg-null} \tag{BR-NEG-NULL}
\end{flalign}

\textbf{Notes}:

\begin{enumerate}
  \item{expect \(\alpha\) to be comparable to \(0\)}
  \item{expect \(\alpha\) to be a numerator to \(Rational\)}
\end{enumerate}

\subsubsection{Next Variable}

After we have the targeted equation, we choose the next variable to have the
minimum, negative dual Bland ratio.

\[
  nextBasicPrimal \enspace :: \enspace Equ \enspace \alpha \enspace \rightarrow
                              \enspace Maybe \enspace LinVarName
\]

\textbf{Lemma}: If all ratios are positive, the result is nothing.

\begin{flalign}
  &\forall f \enspace :: \enspace Equ \enspace \alpha
             \enspace |  \enspace \forall x \in coeffs \enspace f. \enspace
                         x \enspace / \enspace const \enspace f.
\end{flalign}

% Weights
\section{Weights} \label{section-weights}

Weights are implemented as a (non-empty) list of coefficients:

\begin{flalign}
  &\mathrm{data} \enspace Weight \enspace \alpha \enspace = \enspace WCons \enspace \alpha
                 \enspace (Maybe \enspace (Weight \enspace \alpha)) \label{weight-def} \tag{WEIGHT-DEF}
\end{flalign}

When an equation using \(Rational\) values as coefficents gets augmented with a
weight (usually with a natural number - \(augment \enspace eq1 \enspace 5\)), the coefficients are
pushed to that index in an empty stream of \(0\)s; the example just mentioned
would stream five \(0\)s before containing the original coefficient.

\[
  makeWeight \enspace :: \enspace Nat \enspace \rightarrow
                         \enspace Rational \enspace \rightarrow
                         \enspace Weight \enspace Rational
\]

as an example:

\begin{flalign*}
  &makeWeight \enspace 3 \enspace (1/3) \enspace \equiv \enspace\\
  &WCons \enspace 0 \enspace \$ \enspace Just \enspace (\\
  &\quad WCons \enspace 0 \enspace \$ \enspace Just \enspace (\\
  &\quad \quad WCons \enspace 0 \enspace \$ \enspace Just \enspace (\\
  &\quad \quad \quad WCons \enspace (1/3) \enspace Nothing)))
\end{flalign*}

\textbf{Lemma}: for all non-zero inputs to the second parameter, \(makeWeight\)
                results with only one non-zero element in the stream of \(WCons\).

\begin{flalign}
  &\forall x \enspace :: \enspace Rational, \enspace \forall n \enspace :: \enspace Nat \enspace
   | \enspace x \enspace \not = \enspace 0. \nonumber\\
  &\quad length \enspace (filter \enspace (= \enspace 0) \enspace \$ \enspace makeWeight \enspace n \enspace x)
         \enspace \equiv \enspace 1 \label{makeWeight-singleton} \tag{WEIGHT-SINGLETON}
\end{flalign}

\subsection{Ordering}

Weights are compared with Rationals lexicographically - earlier elements have more prescedence
than later ones.

\begin{flalign*}
  &boolWeight \enspace :: \enspace (\alpha \enspace \rightarrow \enspace Bool) \enspace \rightarrow
                          \enspace Weight \enspace \alpha \enspace \rightarrow \enspace Bool\\
  &boolWeight \enspace p \enspace (WCons \enspace x \enspace mxs) \enspace =\\
  &\quad p \enspace x \enspace \vee \enspace (maybe \enspace False \enspace (boolWeight \enspace p) \enspace mxs)
\end{flalign*}

\textbf{Notes}:

\begin{enumerate}
  \item{Used to see which coefficient is below \(0\) in \(nextBasicPrimal\).}
\end{enumerate}

\begin{flalign*}
  &compareWeight \enspace :: \enspace Weight \enspace \alpha \enspace \rightarrow
                             \enspace Weight \enspace \alpha \enspace \rightarrow
                             \enspace Ordering\\
  &compareWeight \enspace (WCons \enspace x \enspace mxs) \enspace (WCons \enspace y \enspace mys) \enspace =\\
  &\quad \mathrm{case} \enspace compare \enspace x \enspace y \enspace \mathrm{of}\\
  &\quad \quad EQ \enspace \rightarrow \enspace | \enspace isNothing \enspace x \enspace \rightarrow \enspace GT\\
  &\quad \quad \quad \quad \quad \quad          | \enspace isNothing \enspace y \enspace \rightarrow \enspace LT\\
  &\quad \quad \quad \quad \quad \quad          | \enspace otherwise \enspace \rightarrow
                       \enspace compareWeight \enspace (fromJust \enspace mxs)\\
  &\quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad
   \quad \quad \quad \quad \quad \quad \quad \enspace  (fromJust \enspace mys)\\
  &\quad \quad o \enspace \rightarrow \enspace o
\end{flalign*}

\textbf{Notes}:

\begin{enumerate}
  \item{Used to realize the minimum coefficient in \(nextBasicPrimal\).}
\end{enumerate}

\subsection{Arithmetic}

\subsubsection{Addition}

\textbf{Instances}:
\begin{flalign}
  &(.+.) \enspace :: \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \label{add-sym} \tag{ADD-SYM}
\end{flalign}

Addition in \ref{add-sym} is implemented with \(unionWith\) - leaving the larger
of the two lists intact.

\[
  (.+.) \enspace = \enspace \mathrm{unionWith} \enspace (+)
\]

\textbf{Lemma}: The length of the resulting list, when using addition, is the
                maximum length of the two lists added.

\[
  \mathrm{length} \enspace ( xs \enspace .+. \enspace ys ) \equiv
  \mathrm{max} \enspace ( length \enspace xs ) \enspace ( length \enspace ys )
\]

\subsubsection{Subtraction}

\textbf{Instances}:
\begin{flalign}
  &(.-.) \enspace :: \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \label{sub-sym} \tag{SUB-SYM}\\
  &(.-.) \enspace :: \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Rational \label{sub-forget:1} \tag{SUB-FORGET-1}\\
  &(.-.) \enspace :: \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Rational \enspace \rightarrow
                     \enspace Rational \label{sub-forget:2} \tag{SUB-FORGET-2}
\end{flalign}

For the first instance \ref{sub-sym}, we use \(unionWith\) again:

\[
  (.-.) \enspace = \enspace unionWith \enspace (-)
\]

For \ref{sub-forget:1} and \ref{sub-forget:2}, we sum the list (and forget weight data) before subtracting:

\begin{flalign*}
  &x \enspace .-. \enspace ys \enspace = \enspace x \enspace - \enspace sum \enspace ys\\
  &xs \enspace .-. \enspace y \enspace = \enspace sum \enspace xs \enspace - \enspace y
\end{flalign*}

\subsubsection{Multiplication}

\textbf{Instances}:
\begin{flalign}
  &(.*.) \enspace :: \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \label{mul-dist:1} \tag{MUL-DIST-1}\\
  &(.*.) \enspace :: \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \label{mul-dist:2} \tag{MUL-DIST-2}\\
  &(.*.) \enspace :: \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \label{mul-forget} \tag{MUL-FORGET}
\end{flalign}

\ref{mul-dist:1} and \ref{mul-dist:2} naturally distributes the \(Rational\)
multiplied value to every element in the \(Weight\) list. In the \ref{mul-forget}
instance, one of the arguments must be forgotten, and is therefore ambiguous for
it's behaviour. We leave the implementation for this instance ambiguous, only
necessary for implementing substitution.

\begin{flalign*}
  &xs \enspace .*. \enspace y \enspace = \enspace (* \enspace y) \enspace <\$> \enspace xs\\
  &x \enspace .*. \enspace ys \enspace = \enspace (x \enspace *) \enspace <\$> \enspace ys
\end{flalign*}

\subsubsection{Division}

\textbf{Instances}:
\begin{flalign}
  &(./.) \enspace :: \enspace Rational \enspace \rightarrow
                     \enspace Weight \enspace Rational \enspace \rightarrow
                     \enspace Rational \label{div-forget} \tag{DIV-FORGET}
\end{flalign}

We will need to divide a coefficient (\(Rational\)) by a coefficient (possibly
a \(Weight Rational\)) in \(blandRatioPrimal\), where we have a forgetful instance -
divide the constant by the sum of the error coefficients:

\[
  x \enspace ./. \enspace ys \enspace = \enspace x \enspace / \enspace sum \enspace ys
\]

\section{Conclusion}
Write your conclusion here.

\end{document}


\section{Introduction}
\label{gua:sec:intro}

% Motivation: (synthesis is especially valueable in concurrent settings)
Concurrent hardware and software systems are notoriously hard to get right.
Formal methods like model
checking or synthesis can be used to guarantee correctness, but the state explosion
problem prevents us from using such methods for systems with a large number
of components. Furthermore, correctness properties are often expected to hold
for an \emph{arbitrary} number of components. Both problems can be solved by
\emph{parameterized} model checking and synthesis approaches, which give correctness
guarantees for systems with any number of components without considering every
possible system instance explicitly.

While parameterized model checking (PMC) is undecidable in general~\cite{Suzuki88},
there exists a number of methods that decide the problem for specific classes
of systems~\cite{German92,Emerson00,Emerso03}, as well as semi-decision
procedures that are successful in many interesting
cases~\cite{Kurshan95,Clarke08,KaiserKW10}.
In this chapter, we consider the \emph{cutoff} method that can guarantee properties of
systems of arbitrary size by considering only systems of up to a certain
fixed size, thus providing a decision procedure for PMC if components are finite-state.

We consider systems that are composed of an arbitrary number of processes,
each an instance of a process template from a given, finite set.
Process templates can be viewed as synchronization
skeletons~\cite{EmersonC82}, i.e., program abstractions that suppress information not
necessary for synchronization. In our system model, processes communicate by guarded updates,
where guards are statements about other processes that are interpreted either
conjunctively (``every other process satisfies the guard'') or disjunctively
(``there exists a process that satisfies the guard''). Conjunctive guards can
model atomic sections or locks, disjunctive guards can model token-passing or to some extent pairwise rendezvous (cf.~\cite{EmersonK03}).

This class of systems has been studied by Emerson and
Kahlon~\cite{Emerson00}, and cutoffs that depend on the
size of process templates are known for specifications of the form
$\forall{\bar{p}}.\ \spec(\bar{p})$,
where $\spec(\bar{p})$ is an $\LTLmX$ property over the local states of one or more processes
$\bar{p}$. Note that this does not allow us to specify fairness
assumptions, for two reasons: (i) to specify fairness, additional atomic propositions for enabledness and scheduling of processes are needed, and (ii) specifications with global fairness assumptions are of the form
$(\forall{\bar{p}}.\ \fair(\bar{p})) \impl (\forall{\bar{p}}.\ \spec(\bar{p}))$.
Because neither is supported by \cite{Emerson00}, the existing cutoffs are of
limited use for
reasoning about liveness properties.

Emerson and Kahlon~\cite{Emerson00} mentioned this limitation and illustrated it
using the process template on the figure on the right.
Transitions from the initial state $N$
\begin{wrapfigure}{r}{0.28\linewidth}
\vspace{-9pt}
\scalebox{0.84}{
\input{guarded-systems/img/mutex}
}
\label{fig:mutex}
\vspace{-20pt}
\end{wrapfigure}
to the ``trying'' state $T$, and from the critical state $C$ to $N$ are always
possible, while the transition from $T$ to $C$ is only possible if no other
process is in $C$. The existing cutoff results can be
used to prove safety properties like mutual exclusion for systems composed of
arbitrarily many copies of this template. However, they cannot be used to prove
starvation-freedom properties like
$\forall{p}. \pforall \always (T_p \rightarrow \eventually C_p)$,
stating that every process $p$ that enters its local state $T_p$ will
eventually enter state $C_p$, because without fairness
of scheduling the property does not hold.

Also, Emerson and Kahlon~\cite{Emerson00} consider only closed systems.
Therefore, in this example, processes always try to enter $C$.
In contrast, in open systems the transition to $T$ might be a reaction
to a corresponding input from the environment that makes entering $C$ necessary. While it is possible to convert an open system to a closed system that is equivalent under \LTL\ properties, this comes at the cost of a blow-up.

\smallskip
\noindent {\bf Motivation.} Our work is inspired by applications in
parameterized synthesis~\cite{JB14}, where the goal is to automatically
construct process templates such that a given specification is satisfied in
systems with an arbitrary number of components.
In this setting,
one generally considers \emph{open systems} that interact with an uncontrollable environment (user).
Also, most specifications contain liveness properties that cannot be guaranteed without fairness assumptions.
Note that in the parameterized setting liveness properties cannot be reduced to safety properties,
because the size of a system is not bounded a priori.
Finally, we are interested in synthesizing deadlock-free systems.
\emph{Cutoffs} are essential for parameterized synthesis,
because they enable a semi-decision procedure to parameterized synthesis.

\smallskip
\noindent
{\bf Contributions.}
\begin{itemize}
\item We show that existing cutoffs for model checking of $\LTLmX$ properties are in general not sufficient for systems with \emph{fairness assumptions}, and provide new cutoffs for this case.
\item We improve some of the existing cutoff results, and give separate cutoffs for the problem of \emph{deadlock detection}, which is closely related to fairness.
\item We prove \emph{tightness} or asymptotical tightness for all of our cutoffs, showing that smaller cutoffs cannot exist with respect to the parameters we consider.
\end{itemize}
%
Moreover, all of our cutoffs directly support \emph{open systems}, where each process may communicate with an adversarial environment. This makes the blow-up incurred by translation to an equivalent closed system unnecessary.
Finally,
we will show in Sect.~\ref{gua:sec:paramsynt}
how to integrate our size-dependent cutoffs into the parameterized synthesis approach.
%The results presented here are based on a more detailed preliminary version of this paper~\cite{AJK15}.


\subsection{Send message}

\begin{figure}[htb!]
  \centering
    \subfloat[]{\includegraphics[width=0.25\textwidth]{graphics/analysis/mini-scenarios/send-message/1.jpg} \label{fig:filmstrips-send-message-a}}
    \subfloat[]{\includegraphics[width=0.25\textwidth]{graphics/analysis/mini-scenarios/send-message/2.jpg} \label{fig:filmstrips-send-message-b}}
	\subfloat[]{\includegraphics[width=0.25\textwidth]{graphics/analysis/mini-scenarios/send-message/3.jpg} \label{fig:filmstrips-send-message-c}}
	\subfloat[]{\includegraphics[width=0.25\textwidth]{graphics/analysis/mini-scenarios/send-message/4.jpg} \label{fig:filmstrips-send-message-d}}
	\caption{Path of a message}
\label{fig:filmstrips-send-message}
\end{figure}

Sending a message to another peer often means that multiple paths can be taken but only one of the paths is the best. \vref{fig:filmstrips-send-message-a} shows a scenario where \bob can choose between \don and \claire to send a message to \alice. \don has a millisecond latency of $l=50$ and \claire a latency of $l=200$, which \bob has measured by sending continuous ping messages and measuring the time until the pong message has been received.

Thus \bob is selecting \don to deliver the message (\vref{fig:filmstrips-send-message-b} to \alice as he has the best latency.
\don is receiving the message. As the specified receiver address of the message is not his own address, he has to forward the message.

To forward the message he has two options: \claire with a measured latency of $l=75$ and \alice with a measured latency of $l=100$. He is selecting \alice as she is the designated receiver of the message even though the latency is worse (\vref{fig:filmstrips-send-message-c}).

\alice is receiving the message (\vref{fig:filmstrips-send-message-d}) and as her address matches the message receiver address, she is further processing the message.


\chapter{Synthesis of Probabilistic Programs} \label{chap:synthesis_methods}

\section{Automated System Design}

The~dream of automating software development has been present since the~beginning of the~computer age.
As early as 1945,~as part of an~ideal vision for an~automatic computing machine,~Alan Turing argued that the~process of compiling instruction tables would be fascinating,~free of errors and no effort,~as the~machine itself would perform all demanding operations.
What if we could tell the~computer what to do \,--\, or give it a~specification of what we want as users \,--\, and let it work to figure out how to do it?
This is the~promise of program synthesis,~where after entering a~specification,~the~computer automatically generates a~program that satisfies that specification.

\paragraph{Deductive Synthesis.}
The~earliest examples of program synthesis used formal specifications to infer the~correct program automatically.
The~aim is to take a~formal specification and search backwards for a~program that provably satisfies the~specification.
Some of the~synthesisers in this area relied on the~successes of automated theorem provers,~which they used to compile proof of program accuracy.
Others used a~comprehensive set of rewriting rules in an attempt to transform a~specification into an~equivalent program.
This approach is similar to a~regular compiler transforming the~input program into an~output program using rewriting rules from specified grammar.
However,~the~rewriting rules of the~synthesiser should be complete \,--\, the~synthesiser tries to find the~optimal program \,--\, and should be able to transform the~specification into every equivalent program.
The~landmarks in this area are works based on super-optimisation~\cite{superoptimiser} and the~Synthesis kernel~\cite{kernel}.

\paragraph{Syntax-Guided Synthesis.}
The~obstacle of deductive synthesis is that it requires both a~complete formal specification and a~complete axiomatisation of the~program target language.
The~second wave of synthesis research focuses on the~\textit{syntax-driven} synthesis,~trying to relax these requirements.
The~input to the~\textit{syntax-guided} synthesis problem consists of a~semantic correctness specification for the~desired program given by a~logical formula and a~syntactic set of candidate programs.
This set is described by a~sketch~\cite{sketching} (program template) containing undefined locations described as yet unknown system properties or maybe intentionally omitted.
Approaches of this second wave have recently come to the~fore,~and our approach is also based on them.

\section{Related Work}

The~synthesis tasks for parametric probabilistic programs can be divided into the~following two categories.

\paragraph{Topology Synthesis.}
This synthesis task considers a~finite set of parameters that affect the~\textit{topology} of Markov chains.
Finding a~family member that satisfies given specifications is \textit{NP}-complete in the~parameters' number and can be naively solved by analysing all individual family members~\cite{onebyone}.
An~alternative approach models the~family of MCs by an~MDP and uses off-the-shelf algorithms for MDP model-checking~\cite{allinone}.
Tools such as \emph{QFLan}~\cite{qflan} and \emph{ProFeat}~\cite{profeat} implements these approaches to quantitatively analyse alternative designs of software product lines~\cite{sw-product-lines}.
These tools provide the~complete methods to solve synthesis tasks,~but they are limited strictly to small families,~so they do not scale.
Inductive techniques,~motivated from these basic approaches,~form on abstraction-refinement (\emph{AR}) over the~MDP representation~\cite{cegar},~and counterexample guided inductive synthesis (\emph{CEGIS}) for MCs~\cite{cegis} have been proposed to achieve better scalability.
Experiments in previous papers~\cite{cegar,cegis} have shown that the~synthesis methods implemented in \emph{ProFeat} or \emph{QFLan} have evident deficits on the~benchmarks investigated also in this thesis.
This synthesis task is closely connected to controller synthesis for partially observed MDPs (POMPDs),~representing,~for instance,~a~famous Maze~\cite{maze} model for AI planning under uncertainty,~to which we will pay attention later.
Other techniques to solve the~controller synthesis for POMDPs also use neural network oracles to lead search~\cite{pomdp-2} and adaptive learning schemes based on imitation learning~\cite{POMDP3}.

\paragraph{Parameter Synthesis.}
It considers models with a~fixed topology but with uncertain parameters associated with transition probabilities (or rates).
It analyses how the~parameter values affect the~behaviour of Markov chains (or MDPs).
\textit{Parameter} synthesis problems targets finding parameter values for which the~parametric model (optimal) satisfies the~specification.
The~state-of-the-art probability model checkers \storm{}~\cite{STORM} and \prism{}~\cite{KNP11} provide approximate techniques for parameter synthesis that solve the~same parameters in various transitions independently.
We note that these model checkers and others with the~same focus are primarily determined to verify concrete MC and not to the~whole MCs family.
On the~contrary,~exact techniques construct rational functions for symbolic reachability probabilities have been proposed in~\cite{DBLP:conf/ictac/Daws04} and further improved in~\cite{dehnert2015prophesy}.
% The~application of this synthesis task can be found, for instance,~in the~field of model repair problems~\cite{model-repair-1}.
Parametric probabilistic models have several applications in a~wide range of areas.
For instance,~in~\cite{ceska-biochemical} synthesised the~rate parameters in stochastic biochemical networks,~in~\cite{model-repair-usage} tuned the~model parameters exploiting the~parametric Markov chains.
Moreover,~parametric models have applications also when ranking the~patches in the~software repair~\cite{learning-correct-code} and for computing perturbation bounds~\cite{nested-approximation}.

\noindent \\
\emph{Search-based} approaches can handle both synthesis tasks,~but they do not guarantee an~exhaustive exploration of the~parameter space.
Genetic algorithms and evolutionary techniques belong to these approaches group,~and the~tool \rodes{}~\cite{rodes} implements their combination with parameter synthesis.
However,~these approaches are not complete and can only effectively solve a~feasible instance within the~feasibility synthesis task.
In the~case of an~unfeasible instance or optimally synthesis task,~they cannot be applied to them.
Thus,~we omit comparison with the~incomplete methods that cannot treat these types of synthesis tasks.

\section{Synthesis Methods}
Existing methods for a~probabilistic programs synthesis can be separated into two orthogonal classes.
The~first class involves complete methods that prove the~non-existence,~or potentially optimally,~of the~given probabilistic program.
On the~contrary,~incomplete methods handling various evolutionary techniques and intelligent search strategies form the~second one~\cite{spl2}.
However,~these incomplete methods cannot treat unfeasible and optimal synthesis problems compared to the~complete methods.
Therefore,~we focus on the~complete state-of-the-art methods even though the~incomplete methods provide a~valuable flexibility level.
As a~reference and baseline method,~we consider a~\textit{one-by-one} approach that enumerates through each design space member~\cite{onebyone}.
An~explosion of the~design space renders this technique unfeasible for large families,~necessitating using advanced approaches utilising the~arbitrary structure of~the~Markov chain family.

This thesis focuses on the~complete methods considered within the~\textit{oracle-guided} synthesis approach~\cite{oracle1,oracle2}.
The~control unit called \textit{learner} selects a~realisation $r$ from the~designs family and passes it to the~performing unit called \textit{oracle}.
This unit provides an~answer to whether realisation $r$ satisfies a~given specification $\varPhi$.
Whenever it is not this case,~it provides supplementary information representing counterexample (CEGIS) or bounds from MC model checking (AR).
For purposes of this thesis,~two various orthogonal oracles can be considered:
\begin{enumerate}[label=(\roman*)]
    \item \textbf{Inductive Oracle} (CE): It tries to infer the~declarations (counter-examples) about other family members by analysing individual realisation~\cite{cegis}.
    \item \textbf{Deductive Oracle} (AR): Abstraction refinement oracle considers more family members at once and then infers the~consequences of these members' constructed aggregation~\cite{cegar}.
\end{enumerate}

\paragraph{Inductive Oracle.}
\textit{Counter-examples} represents a~concrete system execution violating a~given specification $\phi$.
When considering the~probabilistic model checking of Markov chains,~the~counter-examples represent paths set,~which have the~probabilities added to a~quantity that violates $\bowtie \lambda$.
When an~MC D violates the~given specification $\phi$ ($MC \; D \; \not\models \phi$),~a~ \textit{counter-example} provides diagnostic information related to the~states causing the~violation.
We consider the~counter-examples related to critical sub-systems:

\begin{definition}[Counter-example]
Let $D = \mc$ be an MC with $s_{\bot} \notin S$.
An MC $D \! \downarrow \! C = (S \cup \{ s_{\bot} \}, s_0, \mathbf{P}')$ induced by $C \subseteq S$ is sub-MC of MC $D$, where the~transition probability matrix $\mathbf{P}'$ is defined as follows:
\begin{align*}
    \mathbf{P}'(s) =
    \begin{cases}
        \mathbf{P}(S) \quad & if \; s \in C \\
        [ s_{\bot} \mapsto 1 ] \quad & \l otherwise.
    \end{cases}
\end{align*}
For the~given specification $\reachability{\leq}{\lambda}{T}$,~when holds $D \! \downarrow \! C \not \models \reachability{\leq}{\lambda}{(T \cap (C \cup \{ s_0 \}))}$,~then we call the~sub-system $D \! \downarrow \! C$ as a~\textit{counter-example} (CE).
\end{definition}

Let $D_r$ be an~MC that violates the~given specification $\phi$.
The~inductive oracle constructs the~critical sub-system $D_r \! \downarrow \! C$ to compute other realisations that also violate $\phi$.
Subsequently,~it uses this constructed sub-system to infer a~set called \textit{conflict} for $D_r$ and $\phi$.

\begin{definition}[Conflict] \label{def:conflict_set}
For MCs family $\fml = \family$,~and the~set $C \subseteq S$,~the~conflict set $K_C$ is given by $\bigcup_{s \in C} supp(\mathcal{B}(s))$ and consist of relevant parameters.
\end{definition}

\paragraph{Deductive Oracle.}
As we said above,~a~\textit{quotient} MDP over-approximates the~behaviours of each Markov chain in the~currently analysed family $\fml$.
The~\textit{deductive} oracle performs the~model checking of this MDP,~and it can yields the~following results.
We consider the~following specification against which is performed relevant model checking: $\reachability{\geq}{\lambda}{T}$.
The~model checking of the quotient MDP returns the~corresponding lower ($x_{min}$) and upper ($x_{max}$) bounds,~as well as the~minimising ($\sigma_{min}$) and maximising ($\sigma_{max}$) schedulers on the~considered reachability probability.
When $x_{max} < \lambda$,~the~synthesis task is unfeasible since for each family member $r \in \rlz^\fml$ holds that $\mathcal{D}_r \not\models \phi$.
On the~contrary,~when $x_{min} >= \lambda$,~the~oracle can return an~arbitrary family member as a~solution to the~synthesis task since each satisfies $\phi$.
Last but not least,~when $x_{min} \leq \lambda \leq x_{max}$,~we cannot decide this case,~except when the~scheduler $\sigma_{max}$ is consistent.
Such scheduler represents the~valid member of the~analysed family with $x_{max} \geq \lambda$,~so it is a~solution to the~synthesis task.
Otherwise,~when scheduler $\sigma_{max}$ is not consistent,~the~considered abstraction is too over-approximate,~and the~problem is undecided.

\begin{figure*}[h!]
\centering
\includegraphics[width=0.70\textwidth]{figures/ar_loop.pdf}
\caption{An \textit{Abstraction Refinement} (AR) analysing loop.}%
\label{fig:cegar_loop}%
\end{figure*}

In such a~case,~we split the~undecidable family of Markov chains into two derived subfamilies.
Then each of them represents the~input for deductive oracle,~which analyse them using the~technique introduced above.
When derived subfamilies are still undecidable,~we refine them into smaller and smaller subfamilies until we find a~feasible solution or explore the~whole family.
When the~sub-family represents concrete realisation,~so it induces an~MC and not MDP ($x_{min} = x_{max}$),~such family is necessarily decided and have not split.
Moreover,~since the~family size is finite,~the~presented technique has guaranteed the~termination for these two reasons.
Figure~\ref{fig:cegar_loop} depicts described deductive approach.

\paragraph{Hybrid methods.} The~novel integrated approach,~the~so-called \textit{hybrid} method,~combines both these oracles and can thus take advantage of the~benefits offered by both approaches~\cite{roman-DP,tacas21}.
We illustrate the~cooperation between the~individual units within this method in Figure~\ref{fig:adaptivesynt}.
The~learner unit maintains the~subfamilies queue $\rlz' \subseteq \rlzf$ for subsequent processing and decides which oracle is selected based on their previous efficiency.
The~\textit{CE-Oracle} analyses the~family member $r$ and,~when it satisfies the~given specification $\varPhi$,~then returns it as a~solution.
On the~other hand,~it can generalise the~analysed realisation $r$ into a~subfamily $\rlz'$,~and the~learner unit can discard it from the~whole design space $\rlzf$.
Moreover,~this oracle exploits the~MDP bounds when constructing counterexamples,~thanks to which it can generate more petite generalisations.
The~\textit{Abstr-Oracle} analyses a~given sub-family $\rlz \subseteq \rlzf$,~and according to the~result,~it performs the~subsequent action.
When all realisations $r \in \rlz$ satisfy $\varPhi$,~then it returns the~overall synthesis result as feasible.
In another case,~when all realisations violate $\varPhi$,~the~whole analysed sub-family $\rlz$ will be discarded from the~families queue $\rlzf$ by the~learner.
The~last option returns safe bounds on the~best- and worst-case behaviour of all realisations in $\rlz$ considered $\varPhi$ when the~analysis result is inconclusive.

\begin{figure}[t!]
    \centering
     \begin{tikzpicture}
    \node[rectangle, draw, inner sep=8pt] (learner) {Learner};
    \node[rectangle, draw, inner sep=8pt,right=2.7cm of learner] (oracle) {CE-Oracle};
       \node[rectangle, draw, inner sep=8pt,left=2.7cm of learner] (abst) {Abstr-Oracle};
    \node[above=0.5cm of learner] (rlz) {$\rlzf$};
    \draw[->] (rlz) -- (learner);
    \node[above=0.5cm of oracle] (phi) {$\varPhi$};
    \draw[->] (phi) -- (oracle);
    \node[above=0.5cm of abst] (phiab) {$\varPhi$};
    \draw[->] (phiab) -- (abst);
    \draw[->] (learner) edge[bend left=10] node[above] {\scriptsize{$r \in \rlzf$}+bounds} (oracle);
    \draw[->] (oracle) edge[bend left=10] node[below] {\scriptsize{$\rlz' \subseteq \rlzf$ violate $\varPhi$}} (learner);
      \draw[->] (learner) edge[bend right=10] node[above] {\scriptsize{$\rlz \subseteq \rlzf$}} (abst);
    \draw[->] (abst) edge[bend right=10] node[below,align=center] {\scriptsize{bounds \emph{or} $\rlz$ violates}} (learner);

    \node[below=0.4cm of oracle] (sat) {$r \models \varPhi$};
    \draw[->] (oracle) -- (sat);
    \node[below=0.4cm of abst] (allsat) {each $r \in \rlz$, $r \models \varPhi$};
    \draw[->] (abst) -- (allsat);
    \node[below=0.4cm of learner] (unsat) {no $r \models \varPhi$};
    \draw[->] (learner) -- (unsat);
    \end{tikzpicture}
  \vspace{-0,5em}
    \caption{Oracle-guided synthesis (adapted from~\cite{tacas21}).}
    \label{fig:adaptivesynt}.
    \vspace{-1em}
\end{figure}

\begin{algorithm}[h!]
\hspace*{\algorithmicindent} \textbf{Input:} A~MCs family $\fml$,~a~reachability property $\varphi$. \\
\hspace*{\algorithmicindent} \textbf{Output:} $Realization\; r \in \rlzf \; s.t. \; \mathcal{D}_r \models \varphi$,~otherwise UNSAT. \\
\vspace*{-1.5em}
\begin{algorithmic}[1]
    \STATE $\rlzf \leftarrow \{ \rlz^{\fml} \}$ \hfill \textbf{// each analysed (sub)-family also holds bounds}
    \STATE $\delta_{CEGIS} \leftarrow 1$ \hfill \textbf{// time allocation factor for CEGIS}
    \WHILE{$\rlzf \neq \emptyset$}
        \STATE result, $\rlzf'$, $\sigma_{AR}$, $t_{AR}$ $\leftarrow$ AR($\rlzf$, $\varphi$)
        \IF{\textbf{satisfiable}(result)}
            \RETURN result
        \ELSE
            \STATE result, $\rlzf''$, $\sigma_{CEGIS}$ $\leftarrow$ CEGIS($\rlzf'$, $\varphi$)
            \IF{\textbf{satisfiable}(result)}
                \RETURN result
            \ELSE
                \STATE $\delta_{CEGIS}$ $\leftarrow$ $\sigma_{CEGIS}$ / $\sigma_{AR}$
                \STATE $\rlzf$ $\leftarrow$ $\rlzf''$
            \ENDIF
        \ENDIF
    \ENDWHILE
    \RETURN{UNSAT}
\end{algorithmic}
\caption{Hybrid method: Feasibility synthesis with single property.}
\label{alg:hybrid}
\end{algorithm}

An~extended synthesis approach was introduced in~\cite{roman-DP,tacas21} using the~abstraction refinement to family prune and accelerating the~construction of counter-examples by CE-oracle.
Its main idea is to perform a~limited number of abstraction refinement loops and then invoke CEGIS to one of the~refined sub-families.
It turned out that a~moment of the~switching can be crucial,~and therefore,~the~method has to detect the~rightest moment.
One AR iteration is typically significantly slower than one CEGIS iteration since the~AR iteration involves an~MDP model-checking,~which inspires whole method workflow.
The~advance of the~hybrid methods is also constructing counter-examples within the~CEGIS loop,~where it uses a~fast greedy approach providing smaller generalisations.

As we said above,~this \textit{novel integrated} method combines inductive and deductive oracles,~and we briefly summarise their operation.
CEGIS iterates through all family members (realisations) until it reached the~satisfying realisation,~if such exists,~or when it explores the~whole design space.
Moreover,~it constructs counter-examples whenever the~analysed realisation $r \in \fmlr$ unsatisfying the~given specification $\varPhi$.
Realisations subset $\rlz' \subseteq \rlzf$ represents such counter-examples that CEGIS subsequently prunes from the~analysed design space $\rlzf$.
On the~other hand,~an AR loop builds MDP models from the~sub-families queue $\rlz \subseteq \rlzf$ that model-checkers analyse in follows.
When the~analysis results are inconclusive,~an AR refines the~analysed sub-family and  stores the~obtained satisfiability bounds for further processing within CEGIS loop.
Method allocates the~time per both loop according to their performance,~e.g.,~it can consider the~number of pruned MCs per timed unit and estimates an~efficiency from it.
Namely,~when it notices that AR prunes sub-families twice as slow as CEGIS,~it increases time twice in the~next round for CEGIS.
The~resulting algorithm is summarised in Algorithm~\ref{alg:hybrid},~adapted from~\cite{tacas21}.


% \begin{savequote}[8cm]
% Alles Gescheite ist schon gedacht worden.\\
% Man muss nur versuchen, es noch einmal zu denken.

% All intelligent thoughts have already been thought;\\
% what is necessary is only to try to think them again.
%   \qauthor{--- Johann Wolfgang von Goethe \cite{von_goethe_wilhelm_1829}}
% \end{savequote}

\chapter{\texorpdfstring{A BPGGSZ measurement of $\gamma$ with $\Bpm\to\D h^\pm$ decays}{A BPGGSZ measurement of gamma with B->Dh decays}}
\label{ch:5-GGSZ-measurement}

% \minitoc

This chapter describes a model-independent BPGGSZ measurement of $\gamma$ with \BtoDK and \BtoDpi decays where \DtoKspipi and \DtoKsKK, commonly denoted $\Bpm\to\D(\to\KS h^+h^-)h'^\pm$ decays. The measurement is made with the full \lhcb data set collected during Run~1~and~2 of the LHC, corresponding to an integrated luminosity of about $8.7\invfb$. The analysis has been submitted for publication in the Journal of High Energy Physics.

\input{chapters/ch5-selection-and-backgrounds}
\input{chapters/ch5-the-two-fits}
\input{chapters/ch5-systematics-and-interpretation}


\subsection{DNS Comparison}

A qualitative comparison of the DEM and the CDM model results uses the stress distribution and the surface deflection just before failure. For the DEM solution, since the stress field is discontinuous, the stress fields are smoothed using a cubic spline interpolation and subsequently run through a Gaussian filter with a standard deviation of 2 to reduce the noise in the data set. Figures \ref{fig:S11DNS}, \ref{fig:S22DNS}, and \ref{fig:S12DNS} show the horizontal stress distributions, the vertical stress distributions, and the shear stress distributions, respectively.


\subsection{\Antikt}

The \antikt algorithm with a radius parameter of $R=0.4$ is used to reconstruct jets with a four-momentum recombination scheme, using \topos as inputs. Jet energy is calibrated to the hadronic scale with the effect of \pileup removed

\subsection{\Topos}

Hadronic jets are reconstructed from calibrated three-dimensional \topos.
Clusters are constructed from calorimeter cells that are grouped together using a topological clustering algorithm.
These objects provide a three-dimensional representation of energy depositions in the calorimeter and implement a nearest-neighbour noise suppression algorithm.
The resulting \topos are classified as either electromagnetic or hadronic based on their shape, depth and energy density.
Energy corrections are then applied to the clusters in order to calibrate them to the appropriate energy scale for their classification.
These corrections are collectively referred to as \textit{local cluster weighting}, or LCW, and jets that are calibrated using this procedure are referred to as LCW jets~\cite{PERF-2012-01}.

\subsection{Grooming}

Trimming removes subjets with $\ptsubji/\ptjet < \fcut$, where \ptsubji is the transverse momentum of the $i^{\text{th}}$ subjet, and $\fcut=0.05$.
Filtering proceeds similarly, but utilises the relative masses of the subjets defined and the original jet. For at least one of the configurations tested, trimming and filtering are both able to approximately eliminate the \pileup dependence of the jet mass.


\documentclass[10pt]{article}
%\input{../macro.tex}
%\usepackage{psfrag}
%\usepackage{fancyhdr}
\usepackage{subfigure,amsmath,amssymb,amsfonts,makeidx}
%\renewcommand{\baselinestretch}{1.2}
\textheight 23cm
\textwidth 16cm
\topmargin 0cm
%\evensidemargin 0cm
\oddsidemargin 0cm
\evensidemargin 0cm
\usepackage{layout}
%\usepackage{mathpple}
\makeatletter
%\renewcommand\bibsection{\paragraph{References \@mkboth{\MakeUppercase{\bibname}}{\MakeUppercase{\bibname}}}}
\makeatother
%% style des entetes et des pieds de page
%\fancyhf{} % nettoie le entetes et les pieds
%\fancyhead[L]{Template 1 : Simulation of a two-dimensional bouncing ball -- V. Acary }
%\fancyhead[C]{V. Acary}%
%\fancyhead[R]{\thepage}
%\fancyfoot[L]{\resizebox{!}{0.7cm}{\includegraphics[clip]{logoesm2.eps}}}%
%\fancyfoot[C]{}%
%\fancyfoot[C]{}%
%\fancyfoot[R]{\resizebox{!}{0.7cm}{\includegraphics[clip]{logo_cnrs_amoi.ps}}}%
%\addtolength{\textheight}{2cm}
%\addtolength{\textwidth}{2cm}
%\pagestyle{empty}
%\renewcommand{\baselinestretch}{2.0}

\newcommand{\CC}{\mbox{\rm $~\vrule height6.6pt width0.5pt depth0.25pt\!\!$C}}
\newcommand{\ZZ}{\mbox{\rm \lower0.3pt\hbox{$\angle\!\!\!$}Z}}
\newcommand{\RR}{\mbox{\rm $I\!\!R$}}
\newcommand{\NN}{\mbox{\rm $I\!\!N$}}

\begin{document}
%\layout
\thispagestyle{empty}
\title{WP4 Template 3 - Simulation of an impacting oscillator using an event based timestepping scheme implemented in Matlab}
\author{P.~T.~Piiroinen}

\date{Version 1.0 \\
\today}
\maketitle

%\pagestyle{fancy}

\section{Description of the physical problem: A periodically forced pendulum with impacts}
\label{Sec:description}

\section{Definition of a general abstract class of NSDS: Impacting NSDS}
\label{Sec:descriptionNSDS}

In this section, we provide a short description of a general abstract class of Non Smooth Dynamical system (NSDS): Impacting NSDS. More generally, we will try to present this type of system in a more general framework where the NSDS consists of:
\begin{enumerate}
\item a dynamical system with boundary conditions in terms of state variables,
\item a set of input/output variables and their relations with the state variables,
\item a set of  nonsmooth laws which rely on the input/output variable.
\end{enumerate}

\subsection{Dynamical system and Boundary conditions}

\paragraph{General non-linear case: second order system.} The equation of motion of a mechnical system may be stated as
\begin{eqnarray}
  \label{eq:1}
  M(q)\ddot q + F(\dot q, q , t) = F_{ext}(\dot q, q , t)
\end{eqnarray}
where
\begin{itemize}
\item $q \in \RR^n$ is the generalized coordinates vector. The dimension $n$  of this vector is called  the number of degree of freedom of the system. The first and the second time derivative of $q$, denoted $\dot q$ and $\ddot q$, are usually called the velocity and the acceleration of the system.
\item $M(q): \RR^n \mapsto \mathcal M^{n\times n}$ is the inertia term
\item $F(\dot q, q , t) : \RR^n \times \RR^n \times \RR \mapsto \mathcal \RR^{n}$ is the internal force of the system,
\item $F_{ext}(t):  \RR \mapsto \mathcal \RR^{n}  $  is the given external force,
\end{itemize}

\paragraph{General non-linear case: first order system.} The equations of motion \eqref{eq:1} may be reformulated in terms of the state vector as
\begin{equation}
  \label{eq:2}
M(q)\dot q =f(q,t)
\end{equation}
which is a classical order one formulation of an ordinary differential equation (ODE), and where
\begin{itemize}
\item $q \in \RR^{2n}$ is the generalized coordinates vector.
\item $M(q): \RR^{2n} \mapsto \mathcal M^{2n\times 2n}$ is the inertia term
\item $f(q,t) : \RR^{2n} \times \RR \mapsto \mathcal \RR^{2n}$
\end{itemize}

In a general way, we can denote the state of the system as
\begin{eqnarray}
  x =
  \left[\begin{array}{c}
  x_1 \\
  x_2
  \end{array}\right] =
  \left[\begin{array}{c}
  q \\
  \dot q
  \end{array}\right]
\ \textrm{ or } \
  x =
  \left[\begin{array}{c}
  x_1 \\
  x_2 \\
  x_3
  \end{array}\right] =
  \left[\begin{array}{c}
  q \\
  \dot q \\
  \tau(t)
  \end{array}\right]
\end{eqnarray}
which are vectors of dimension $2\times n$ and $2\times n + 1$, respectively. The second form is used when a non-autonomous systems is transfered to an autonomous.

\subsubsection*{Boundary conditions}
The boundary conditions for an Initial Value Problem (IVP) are given by
\begin{equation}
  \label{eq:3}
  t_0 \in \RR,\quad x(t_0)=x_0 \in \RR^{2n}.
\end{equation}

\subsection{Relation between constrained variables and state variables}
\paragraph{Formal Case.} In a general way, the dynamical system is completed by a set of nonsmooth laws which do not   directly concern the state vector. The set of such variables, denoted $y$, on which we apply the constraints, depends, in a very general way, of the state vector $x$ and the time $t$:
\begin{eqnarray}
  \label{eq:y}
  y=h(x,t).
\end{eqnarray}

\paragraph{Dynamical system}
In the dynamical systems the structure of these relations is very particular and we assume that they can be written as
\begin{eqnarray}
  y&=& h(x),\label{eq:7a} \\
  \dot y &=&  \left\langle\nabla h(x),f(x)\right\rangle,\label{eq:7b} \\
  \ddot y &=&  \left\langle\nabla\left\langle\nabla h(x),f(x)\right\rangle,f(x)\right\rangle. \label{eq:7c}
\end{eqnarray}

\subsection{Definition of the Non Smooth Law between constrained variables}

Several kind of nonsmooth laws may be formulated for dynamical system. For the purpose of this template, we define just the unilateral contact law and the impact law.

The Newton impact law may formulated as follows :
\begin{eqnarray}
  \label{eq:13}
  \text{if } y(t)=0,\quad  x(t^+)=x(t^-) + e(x)\dot{y}(t^-) = x(t^-) + e(x)\left\langle\nabla h(x(t^-)),f(x(t^-))\right\rangle
\end{eqnarray}

\section{The formalization of the forced impacting oscillator into the class of impacting NSDS}
We assume that the system of a forced impacting pendulum belongs to the abstract class of the NSDS.

\subsection{Dynamical system}
From physical data we can find all terms which define a second order NSDS (compare with (\ref{eq:1})). In our special case we get for the free flight
\begin{equation}
  \ddot{\theta} + \kappa\dot{\theta}+\frac{g_e}{L}\sin(\theta) = \frac{A\omega^2}{L}\sin(\omega t),
\end{equation}
where $\theta$ is the angle of the pendulum, $L$ is its effective length, $\kappa$ is the linear damping coefficient, $g_e$ is the effective gravity, $\omega$ is the forcing frequency, $A$ is the forcing amplitude, and $t$ is the time. Following (\ref{eq:1}) we have that
\begin{eqnarray}
  x&=& \theta, \\
  M(x,t)&=& 1, \\
  F(x,x',\tau) &=& \frac{2\beta}{\eta}x' + \frac{1}{4\eta^2}\sin(x),\\
  F_{ext}(x,\tau)& = & \alpha\cos(x)\sin(\tau).
\end{eqnarray}

In what follows we will instead use the ODE formulation (\ref{eq:2}) of the equations of motion instead. By letting $\tau = \omega t$ and $'$ denote $\frac{d}{d\tau}$ the nondimensionalised equations of motion become
\begin{equation}
  \theta'' + \frac{2\beta}{\eta}\theta' + \frac{1}{4\eta^2}\sin(\theta) = \alpha\cos(\theta)\sin(\tau)
\end{equation}
and thus if we let
\begin{equation}
  x=
  \left[\begin{array}{c}
  x_1 \\
  x_2 \\
  x_3
  \end{array}\right] =
  \left[\begin{array}{c}
  q \\
  \dot{q} \\
  \tau
  \end{array}\right]
\end{equation}
we have
\begin{eqnarray}
  M(x,t)\dot{x}= f(x),
\end{eqnarray}
where
\begin{eqnarray}
  M(x,t)&=& \left[\begin{array}{ccc}
  1&0&0 \\
  0&1&0 \\
  0&0&1
  \end{array}\right] \ \textrm { and} \\
f(x)& = & \left[\begin{array}{c}
  x_2 \\
  -\frac{2\beta}{\eta}x' - \frac{1}{4\eta^2}\sin(x) + \alpha\cos(x)\sin(\tau)\\
  1
  \end{array}\right].
\end{eqnarray}
\subsection{relations}

The unilateral constraint requires that
\begin{eqnarray}
  \label{eq:14}
   h = \theta - \hat{\theta} = x_1 - \hat{\theta}  \geq 0,
\end{eqnarray}
so we identify the terms of the equation (\ref{eq:7a})-(\ref{eq:7c}) to be
\begin{eqnarray}
  \label{eq:15}
  y&=& x_1 - \hat{\theta},\\
  y'&=& \left\langle \nabla h(x),f(x,\tau)\right\rangle = x_2\\
  y'' &=&  \left\langle\nabla\left\langle\nabla h(x),f(x,\tau)\right\rangle,f(x,\tau)\right\rangle =   -\frac{2\beta}{\eta}x' - \frac{1}{4\eta^2}\sin(x) + \alpha\cos(x)\sin(\tau).
\end{eqnarray}

\subsection{Nonsmooth laws}

The Newton impact law at impact is given by
\begin{eqnarray}
  \label{eq:18}
  \text{if } y=0,\quad \text{then} \quad  x_2(\tau^+)= x_2(\tau^-) + e(x)\dot y(\tau^-)= -rx_2(\tau^-),
\end{eqnarray}
where
\begin{equation}
  \label{eq:18b}
  e(x) =  \left(\begin{array}{c} 0 \\ -(1+r) \\ 0\end{array}\right).
\end{equation}
\section{Description of the numerical strategy: Simulation using an event-driven sceheme in Matlab}
\label{Sec:Simulation}

\subsection{Numerical implementation of the event driven scheme in Matlab}

In this section we provide an idea how to use an event driven scheme to solve impact type problems (in Matlab).
\subsubsection{Solvers and event detection} \label{sec:solvers}
\subsubsection*{Nonlinear systems}
For nonlinear dynamical systems any of the built-in adaptive integrators, such as \verb|ode45| (4th order Runge-Kutta for nonstiff systems) or \verb|ode15s| (uses backward differential formulas (BDFs) also known as Gear's method for stiff systems) can be used to solve the smooth dynamics. It is of course possible to write your own code for solving ODEs, which should be straight forward.

For nonlinear dynamical systems the built-in event detection routines that is integrated with the numerical integrators can be used to locate $y=0$. For more grazing sensitive simulations, i.e.~to make sure that low-velocity impacts are not lost, one can also look for $\dot{y} = \nabla h(x)f(x)=0$. If a user-provided solver is used then the user also has include an event detection scheme. For this, e.g. standard bisection, secant, or Broyden's method (a variant of the secant method) can be used and with a specified toloreance.

\subsubsection*{Linear system}
For linear dynamical systems any of the built in integrators (as for the nonlinear systems) can be used to solve the smooth dynamics. However, it is also possible to use the \verb|expm| function which is the matrix exponential or in verys simple cases the actual solution can be given to the program for.

The same approach on event detection holds for linear systems as for nonlinear systems (see above).

\subsubsection*{Chatter and sticking/sliding}
In impacting systems chatter and sticking are very common phenomena that often causes a lot of problems in event driven methods. To have sticking there are three condition that has to be fulfilled at impact. They are
\begin{eqnarray}
y & = & 0 \ \ \text{(impact condition)} \label{eq:impcond}\\
\dot{y} & = & 0 \ \ \text{(grazing condition)} \label{eq:grcond}\\
\ddot{y} & \leq & 0 \ \ \text{(acceleration condition)} \label{eq:accond}
\end{eqnarray}

Sticking can be caused by either if the coefficient of restitution is zero or as the result of a chatter sequence. In chatter the system recognises infinite number of impacts in finite time. Obviously it is impossible to numerically solve for an infinite number of events, so the most common way to solve this is to set $\dot{y} = 0$ as the conditions (\ref{eq:impcond}) and (\ref{eq:grcond}) are fulfilled and
\begin{equation}
|\dot{y}| < C, \ \ 0 < C << 1  \label{eq:C}
\end{equation}
where $C$ is a small and positive constant.

When the system is in sticking mode the condition to look for is \textbf{not} $y = 0$, since this is allready fulfilled, but instead we look for $\ddot{y} = 0$ which is exactly when the acceleration is changing sign and eventually the direction of the velocity away from the impacting surface.

\subsubsection{Detection of and action at the impacting surface}
In order to apply Newton's impact law the surface given by
\begin{equation}
y = h(x) = 0
\end{equation}
and possibly also
\begin{equation}
\dot{y} = \nabla h(x)f(x) = 0
\end{equation}
has to be locted with an appropriate method, as describe above in Sec.~\ref{sec:solvers}.

During the ODE integration the event detector will eventually find the exact time and position of an impact, i.e. when $y=0$. At such a point the integrator stops, wherafter the impact law is applied and the integrator is again started, but now with the new inital conditions given by the impact law.

\subsubsection*{Chatter and sticking/sliding}
When the motion fulfills (\ref{eq:impcond}), (\ref{eq:accond}), and (\ref{eq:C}) the solver stops and $\dot{y}$ is set to $0$ and the integration is restarted but now only looking for the event $\ddot{y} = 0$. To avoid drift away from the surface due to numerical errors tt is possible to make the surface attracting by adding the term
\begin{equation}
D\nabla h(x)^Th(x), \ \ D > 0
\end{equation}
to the vector field. The constant should be used to make the time scales for the new term and the sticking vector field equal.

Another and a more recent idea is to use a local mapping att chattering. Such methods have been developed but not yet tested or included in a code.

\subsection{Numerical Strategy}

%The numerical stratgey is given by the pseudo-algorithm \ref{Algo:MTS}.

%\begin{algorithm}
%  \begin{algorithmic}
%{
%    \REQUIRE Classical form of the dynamical equation : $ M, K, C, F_{ext}, q_0, \dot q_0$
%    \REQUIRE  Classical form of the relations : $ H, b$
%    \REQUIRE  Classical form of the non smooth law  : $ e$
%    \REQUIRE Numerical parameter : $ h, \theta, T, t_0$
%    \ENSURE  $(\{ q_n\}, \{ \dot q_n\},\{R_n\}) $
%    \STATE // Construction of time independant operators :
%    \STATE $ W = \left[M+h\theta C + h^2 \theta^2 K\right]^{-1}$ // The iteration matrix
%    \STATE $ w = H^{T} W H $ // The LCP matrix (Delassus operator)
%    \STATE // Time discretization $n_{step} := [ \frac{T-t_0}{h}]$
%    \STATE // Non Smooth Dynamical system integration
%    \FOR{$i=0$ to $n_{step}$ }
%        \STATE // Computation of $\dot q_{free}$
%        \STATE $\dot q_{free} = \dot q_{i}+  W \left[   - h  C \dot q_{i} - h K q_{i} - h^2 \theta  K \dot q_{i}
%+  h\left[\theta  F_{ext}(t_{i+1})+(1-\theta)  F_{ext}(t_{i})  \right]       \right]$
%        \STATE // Prediction of the constrained variables
%        \STATE $q^{p} = q_i + \frac h 2 \dot q_i\,; \qquad y^{p} = H^T q^p +b $
%        \STATE // Contact detection
%        \IF{$y^{p} \leq 0$}
%        \STATE // Formalization of the one-step  LCP
%        \STATE $ bLCP =  H^{T} \dot q_{free}  + e \dot y_{i}$
%        \STATE // Resolution  of the one-step LCP
%        \STATE $ [\dot y^{e}_{i+1}, \lambda_{i+1}]=$\texttt{solveLCP}$(w,bLCP)$
%        \ENDIF
%        \STATE // State Actualisation
%        \STATE $R_{i+1} = H \lambda_{i+1} $
%        \STATE $\dot q_{i+1} = \dot q_{free}  + h W R_{i+1}$
%        \STATE $q_{i+1} = q_{i} +  h\left[\theta  \dot q_{i+1}+(1-\theta)  \dot q_{i}  \right]$
%     \ENDFOR}
%  \end{algorithmic}
%  \caption{Moreau's Time Stepping scheme}
%\label{Algo:MTS}
%\end{algorithm}

%\clearpage

\section{Exploitation of the results}
\label{Sec:Results}

For the case of Lagrangian NSDS, the state variable and the reaction force vs. time are the basic results that we want to export out of the algorithm. Various of energies may be also expected by the user.

\section{First analysis for the architectural point of view}
\label{Sec:Analysis}

To be defined \ldots

\end{document}


\section{Problem definition}
Designing a new product is a very delicate process in which we have to consider all the details of interest. The purpose of this process is to maximise the final result. The greater is the product complexity, the more this process is tricky. In the case of study, a \acs{WPMS} is rated as good if the measures made with it are close enough to the real ones. A question rises: what does ``close enough'' mean? \\

As described in Chapter \ref{ch:technology}, a \acs{SOL} system is made up of many components: cameras, sensors, lenses, laser projectors, laser-camera reciprocal positions, etc. All of these components are sources of noise. Accurately control these sources, allows to significantly increase the accuracy of the output measurement. Unfortunately this is not only a problem of noise. When we design a new system we decide how to put the elements, how to link them and which positions are the best to reach our goal, but when too many elements are taken into account at the same time, it is very difficult to estimate the effect of each single choice on the final result. When there are no models or virtual system that allow to simulate this chain of effects, the only way to evaluate the quality of the system is to build and to try it on real situation or in laboratory, with a waste of time and money in the case the system doesn't reach given requirements. Time and money are two fundamental aspects in a company, specially when products have to be customized on customer needs, or when a new product have to be designed within a deadline. \\

By combining what has just been said with \acs{WPMS}s description in Chapter \ref{ch:sys_cmp}, both from the point of view of hardware and software, we can summarize the sources of noise/error for the acquisition of images and measurement, as follows:
  \begin{itemize}
    \item Environment
      \begin{itemize}
        \item Working tolerances
        \item Temperature range
        \item Installation
        \item Vibration/Shock
        \item External light conditions
        \item Dirty and wet condition on the target (wheel surface)
      \end{itemize}
      %
    \item Not ideal of the model
      \begin{itemize}
        \item Wheel yaw and camber
        \item Laser spot shape (discussed in Subsection \ref{subsec:lenses})
        \item Lenses (discussed in Subsection \ref{subsec:peak-detection})
      \end{itemize}
      %
    \item Images acquisition process
      \begin{itemize}
        \item Laser plane
        \item System calibration and geometrical parameters evaluation
        \item Profile extraction
      \end{itemize}
      %
    \item Data processing
      \begin{itemize}
        \item Point cloud interpolation
        \item Keypoints detection
        \item Measures evaluation and error propagation (Summaries and differences, application of closed formulas, \ldots)
      \end{itemize}
  \end{itemize}

The model proposed in this chapter aims to evaluate the error made determining a 3D point in the world, starting from the detection of its projection in the image. The model tries to consider all the elements described in Chapter \ref{ch:technology}, organizing them accordingly to the \acs{SOL} systems geometry. In particular, we will focus on the problem of sub-pixel point extraction. In the end, we will try to improve the model, considering the calibration problem and including the corrections due to the non-ideality of the image acquisition. \\

In Appendix \ref{ap:model} we summarized the proposed model, with particular attention to the notation and to the simplicity of comprehension. In Appendix \ref{ap:nomen} we added a table with all the definition of interests for this chapter.