\documentclass[a4paper]{article}

\input{../preambles/preamble}
\setdefaultlanguage{english}
%\setotherlanguages{german,greek}

\input{../preambles/mathematics}
\input{../preambles/physics}

%\newcommand{\RomaN}[1]{%
%  \textup{\uppercase\expandafter{\romannumeral#1}}%
%}

%\addbibresource{main.bib}
\title{Unruh effect}
\author{YiFan Wang}

\begin{document}
\maketitle

%\begin{abstract}
%Your abstract.
%\end{abstract}

\tableofcontents

Defining
\begin{equation}
x_- = t-x,\qquad x_+ = t+x.
\end{equation}

\section{Two-dimensional classical field by Unruh construction}

\begin{equation}
\Ld = -\sqrt{-g}\rbr{g_{\mu\nu}\partial_\mu \partial_\nu \Phi}.
\end{equation}

In flat space-time with Minkowski metric,
\begin{equation}
\rbr{\partial_t^2 - \partial_x^2}\Phi = 0.
\label{eq:eom-Minkowski}
\end{equation}
Solve \cref{eq:eom-Minkowski} simultaneously with
\begin{equation}
\ii\what{\mscrB}_x \Phi = \frac{\kappa}{a}\Psi
\end{equation}
to find a complete set of basis of solution, where
\begin{equation}
\what{\mscrB}_x = x\partial_t + t \partial_x
\end{equation}
is the Lorentz boost generator in the $x$ direction, and is time-like in $L$
and $R$ region.

One finds the basis of solutions in $R$ region to be
\begin{equation}
\sbr{N\rbr{\frac{-x_-}{x_{-0}}}^{+\ii\kappa/a},
N\rbr{\frac{x_+}{x_{+0}}}^{-\ii\kappa/a}},
\end{equation}
Which are named as \emph{boost modes}. Requiring phase at $\rbr{t, x} = \rbr{0,
1/a}$ to be zero yields $x_{-0} = x_{+0}$.

% Let's print the overall heading of the bibliography first:
%\printbibheading
%\printbibliography

\end{document}


% Copyright 2019 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.

\section{Quick Commands}

This section explains the ``quick'' commands of \pgfname. These commands are
executed more quickly than the normal commands of \pgfname, but offer less
functionality. You should use these commands only if you either have a very
large number of commands that need to be processed or if you expect your
commands to be executed very often.

\subsection{Quick Coordinate Commands}

\begin{command}{\pgfqpoint\marg{x}\marg{y}}
    This command does the same as |\pgfpoint|, but \meta{x} and \meta{y} must
    be simple dimensions like |1pt| or |1cm|. Things like |2ex| or |2cm+1pt|
    are not allowed.
\end{command}

\begin{command}{\pgfqpointxy\marg{$s_x$}\marg{$s_y$}}
    This command does the same as |\pgfpointxy|, but \meta{$s_x$} and
    \meta{$s_y$} must be simple numbers without unit, like |1.234| or |5.0|.
    Mathematical expressions or units are not allowed.
\end{command}

\begin{command}{\pgfqpointxyz\marg{$s_x$}\marg{$s_y$}\marg{$s_z$}}
    As |\pgfqpointxy|, but for three-dimensional coordinates. Any argument
    needs to be a number without unit.
\end{command}

\begin{command}{\pgfqpointscale\marg{factor}\marg{coordinate}}
    As |\pgfpointscale|, but \marg{factor} must be a simple number without
    unit, as for the other ``quick'' commands.
\end{command}

\subsection{Quick Path Construction Commands}

The difference between the quick and the normal path commands is that the quick
path commands
%
\begin{itemize}
    \item do not keep track of the bounding boxes,
    \item do not allow you to arc corners,
    \item do not apply coordinate transformations.
\end{itemize}

However, they do use the soft-path subsystem (see
Section~\ref{section-soft-paths} for details), which allows you to mix quick
and normal path commands arbitrarily.

All quick path construction commands start with |\pgfpathq|.

\begin{command}{\pgfpathqmoveto\marg{x dimension}\marg{y dimension}}
    Either starts a path or starts a new part of a path at the coordinate
    $(\meta{x dimension},\meta{y dimension})$. The coordinate is \emph{not}
    transformed by the current coordinate transformation matrix. However, any
    low-level transformations apply.
    %
\begin{codeexample}[]
\begin{tikzpicture}
  \draw[help lines] (0,0) grid (3,2);
  \pgftransformxshift{1cm}
  \pgfpathqmoveto{0pt}{0pt} % not transformed
  \pgfpathqlineto{1cm}{1cm} % not transformed
  \pgfpathlineto{\pgfpoint{2cm}{0cm}}
  \pgfusepath{stroke}
\end{tikzpicture}
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfpathqlineto\marg{x dimension}\marg{y dimension}}
    The quick version of the line-to operation.
\end{command}

\begin{command}{\pgfpathqcurveto\marg{$s^1_x$}\marg{$s^1_y$}\marg{$s^2_x$}\marg{$s^2_y$}\marg{$t_x$}\marg{$t_y$}}
    The quick version of the curve-to operation. The first support point is
    $(s^1_x,s^1_y)$, the second support point is  $(s^2_x,s^2_y)$, and the
    target is $(t_x,t_y)$.
    %
\begin{codeexample}[]
\begin{tikzpicture}
  \draw[help lines] (0,0) grid (3,2);
  \pgfpathqmoveto{0pt}{0pt}
  \pgfpathqcurveto{1cm}{1cm}{2cm}{1cm}{3cm}{0cm}
  \pgfusepath{stroke}
\end{tikzpicture}
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfpathqcircle\marg{radius}}
    Adds a radius around the origin of the given \meta{radius}. This command is
    orders of magnitude faster than |\pgfcircle{\pgfpointorigin}{|\meta{radius}|}|.
    %
\begin{codeexample}[]
\colorlet{examplefill}{yellow!80!black}
\begin{tikzpicture}
  \draw[help lines] (0,0) grid (1,1);
  \pgfpathqcircle{10pt}
  \pgfsetfillcolor{examplefill}
  \pgfusepath{stroke,fill}
\end{tikzpicture}
\end{codeexample}
    %
\end{command}

\subsection{Quick Path Usage Commands}

The quick path usage commands perform similar tasks as |\pgfusepath|, but they
%
\begin{itemize}
    \item do not add arrows,
    \item do not modify the path in any way, in particular,
    \item ends are not shortened,
    \item corners are not replaced by arcs.
\end{itemize}

Note that you \emph{have to} use the quick versions in the code of arrow tip
definitions since, inside these definition, you obviously do not want arrows to
be drawn.

\begin{command}{\pgfusepathqstroke}
    Strokes the path without further ado. No arrows are drawn, no corners are
    arced.
    %
\begin{codeexample}[]
\begin{pgfpicture}
  \pgfpathqcircle{5pt}
  \pgfusepathqstroke
\end{pgfpicture}
\end{codeexample}
    %
\end{command}

\begin{command}{\pgfusepathqfill}
    Fills the path without further ado.
\end{command}

\begin{command}{\pgfusepathqfillstroke}
    Fills and then strokes the path without further ado.
\end{command}

\begin{command}{\pgfusepathqclip}
    Clips all subsequent drawings against the current path. The path is not
    processed.
\end{command}

\subsection{Quick Text Box Commands}

\begin{command}{\pgfqbox\marg{box number}}
    This command inserts a \TeX\ box into a |{pgfpicture}| by ``escaping'' to
    \TeX, inserting the box number \meta{box number} at the origin, and then
    returning to the typesetting the picture.
\end{command}

\begin{command}{\pgfqboxsynced\marg{box number}}
    This command works similarly to the |\pgfqbox| command. However, before
    inserting the text in \meta{box number}, the current coordinate
    transformation matrix is applied to the current canvas transformation
    matrix (is it ``synced'' with this matrix, hence the name).

    Thus, this command basically has the same effect as if you first called
    |\pgflowlevelsynccm| followed by |\pgfqbox|. However, this command will use
    |\hskip| and |\raise| commands for the ``translational part'' of the
    coordinate transformation matrix, instead of adding the translational part
    to the current canvas transformation matrix directly. Both methods have the
    same effect (box \meta{box number} is translated to where it should be),
    but the method used by |\pgfqboxsynced| ensures that hyperlinks are placed
    correctly. Note that scaling and rotation will not (cannot, even) apply to
    hyperlinks.
\end{command}

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


\documentclass{article}
\usepackage{listings}
\lstloadlanguages{Haskell}
\lstnewenvironment{code}
    {\lstset{}%
      \csname lst@SetFirstLabel\endcsname}
    {\csname lst@SaveFirstLabel\endcsname}
    \lstset{
      basicstyle=\small\ttfamily,
      flexiblecolumns=false,
      basewidth={0.5em,0.45em},
      literate={+}{{$+$}}1 {/}{{$/$}}1 {*}{{$*$}}1 {=}{{$=$}}1
               {>}{{$>$}}1 {<}{{$<$}}1 {\\}{{$\lambda$}}1
               {\\\\}{{\char`\\\char`\\}}1
               {->}{{$\rightarrow$}}2 {>=}{{$\geq$}}2 {<-}{{$\leftarrow$}}2
               {<=}{{$\leq$}}2 {=>}{{$\Rightarrow$}}2
               {\ .}{{$\circ$}}2 {\ .\ }{{$\circ$}}2
               {>>}{{>>}}2 {>>=}{{>>=}}2
               {|}{{$\mid$}}1
    }
\begin{document}

\section{The specification}

We shall give a specification for fixed point arithmetic in two
steps.  First, we shall specify unbounded exact arithmetic, and
then we shall specify a framework for converting fixed point
numbers to ``fixed point frames''.  The specification is executable
code in the programming language Haskell [ref].

One specification covers both binary and decimal fixed point
arithmetic.  The base is part of the type of a fixed point number.
The LANGUAGE pragmas enable lanuage features added since the
Haskell 2010 report.  The import declarations make the (named)
functions available, these will be used in text$\leftrightarrow$number
conversion.
\begin{code}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Numeric (showSigned)
import Data.Char (isDigit)
\end{code}
Binary and Decimal are ``empty types'' with no values other
than $\bot$ used as compile-time marks.  The type class
Has\_Radix exists to convert these marks to run-time values.
\begin{code}
data Binary
data Decimal

class Has_Radix t
  where radix :: t -> Integer

instance Has_Radix Binary
  where radix _ = 2

instance Has_Radix Decimal
  where radix _ = 10
\end{code}

A fixed point number representation contains two unbounded integers.
To avoid confusing them, we give scales a different type.  The
Scale $t$ type has exactly the same representation as the Integer type;
it has the same integer literals; and it has (some of) the same
operations.  But it is a different type, which helps us avoid errors.
It is a ``phantom type'', so called because it
contains no run-time value of type $t$.  The ScopeTypeVariables
feature means that the type variable $t$ is available in the body
of the `shift' function, so that we can extract the radix without
storing it anywhere.  The `shift' function shifts a number left or
right by some number of digits; it is exactly what a shift instruction
would do on a binary or decimal sign-and-magnitude machine.

\begin{code}
newtype Scale t = Scale Integer
                  deriving (Eq, Ord, Show, Num)

shift :: forall t . Has_Radix t => Integer -> Scale t -> Integer
shift m (Scale p) =
  if p >= 0 then m * radix (undefined :: t) ^ p
  else m `quot` radix (undefined :: t) ^ negate p
\end{code}
% ERROR: shift was not defined for negative p.

A Fixed $t$ contains an integer $m$ and a scale $s$ so that it represents
the value $m\times r^s$ where $r$ is the radix determined by $t$.
These integers are unbounded; we are dealing with exact arithmetic
at this point.
\begin{code}
data Fixed t = FP !Integer !(Scale t)
\end{code}

For testing we want to be able to create an integral Fixed $t$
value with a given scale.

\begin{code}
toFixed :: Has_Radix t => Integer -> Scale t -> Fixed t
toFixed n s = FP (shift n s) s
\end{code}

The :: line for the toFixed function says ``for any type $t$,
provided that $t$ belongs to the Has\_Radix class (that is,
`radix' is defined on it), toFixed a function with an
Integer argument and a Scale t argument that delivers a Fixed t
result.

From an FP value we can extract its scale and base, even though
the base is not stored.  We can also provide the LIA function
{\it ulp} (unit in last place).

\begin{code}
scale :: forall t . Has_Radix t => Fixed t -> Integer
scale (FP _ s) = s

base :: forall t . Has_Radix t => Fixed t -> Integer
base _ = radix (undefined :: t)

ulp :: Has_Radix t => Fixed t -> Fixed t
ulp (FP _ s) = FP 1 s
\end{code}

\subsection{Comparison}

What does it mean for (FP $m_1$ $s_1$) to equal (FP $m_2$ $s_2$)?
Consider (FP 0 0) and (FP 0 1).  They both represent 0.  But they
are behaviourally different.  For example, (FP 0 0) should print
as \verb|"0"| while (FP 0 1) should print as \verb|"0.0"|.  If we
want equality to satisfy Leibniz' law, we have to regard these as
distinct.  On the other hand, it would be difficult to do numeric
calculations if zero wasn't equal to zero.

The standard mathematical way to deal with this is to distinguish
two spaces:  a space $X$ of $(m,s)$ pairs which are equal if and
only if identity and a quotient space $F = X/\equiv$ where
$(m_1,s_1) \equiv (m_2,s_2)$ if and only if $m_1\times r^{s_2} =
m_2 \times r^{s_1}$.  Haskell's \verb|==|, which we are about to
define, should be thought of as $\equiv$ rather than $=$.

In order to compare two numbers, it helps to align them so they
have their radix points in the same place.  This is also useful
for addition and subtraction.

\begin{code}
align :: forall t a . Has_Radix t =>
    Fixed t -> Fixed t -> (Integer -> Integer -> a) -> a

align (FP m1 s1) (FP m2 s2) f
  | s1 > s2 = f m1 (shift m2 (s1-s2))
  | s1 < s2 = f (shift m1 (s2-s1)) m2
  | True    = f m1 m2
\end{code}

This takes two fixed-point numbers in the same base, aligns them,
and passes the aligned values to a function of integers.

By plugging Fixed into Haskell's Eq type class and
defining \verb|==|, we get \verb|/=| for free, correct by
construction (if \verb|==| is).  This provides
the LIA operations {\it eq} and {\it neq}.

\begin{code}
instance (Has_Radix t) => Eq (Fixed t)
  where x1 == x2 = align x1 x2 (==)
\end{code}

By plugging Fixed into Haskell's Ord type-class and
defining three-way comparison, we get $<$, $\le$, $>$, $>=$,
max, and min for free, correct by construction.
This provides the LIA-1 operations {\it lss},
{\it leq}, {\it gtr}, and {\it geq} and the LIA-2 operations
{\it max} and {\it min}, and since `maximum' and `minimum' are
predefined folds derived from `max' and `min', the LIA-2
operations {\it max\_seq} and {\it min\_seq}.

\begin{code}
instance (Has_Radix t) => Ord (Fixed t)
  where compare x1 x2 = align x1 x2 compare
\end{code}

This is all we need to extend LIA-2's divisibility test to
fixed-point numbers:
\begin{code}
lia_divides :: Has_Radix t => Fixed t -> Fixed t -> Bool
lia_divides x y = align x y (\m n -> m /= 0 && n`rem`m == 0)
\end{code}

% We can even define
% lia_gcd :: Has_Radix t => Fixed t -> Fixed t -> Fixed t
% lia_gcd x y = FP (align x y gcd) (scale x`max`scale y)
% lia_lcm :: Has_Radix t => Fixed t -> Fixed t -> Fixed t
% lia_lcm x y = FP (align x y lcm) (scale x `max` scale y)

\subsection{Converting numbers to text}

For general use, we would need a function to convert a
number to a specified number of decimal digits according
to a given rounding mode.  Here we simply specify conversion
to decimal.  Numbers with scale $s \le 0$ have no decimal
point; if $s > 0$ the number of decimal digits required is
$s$ whether the base is Binary or Decimal.  If we supported
bases that were not a multiple of 2, fixed-point numbers in
such a base might not have a finite decimal representation.

Plugging into Haskell's Show type-class takes care of
inserting a negative sign (and if the context demands it,
enclosing parentheses), and avoiding excess concatenation.

\begin{code}
instance (Has_Radix t) => Show (Fixed t)
  where
    showsPrec p x = showSigned showPos p x
      where showPos x@(FP m s) rest =
              if s <= 0 then shows (shift m (negate s)) rest
              else shows i ('.' : show_fract s r)
              where p = shift 1 s
                    (i,r) = quotRem m p
                    show_fract 0 _ = rest
                    show_fract d f = shows h (show_fract (d-1) l)
                      where (h,l) = quotRem (10 * f) p
\end{code}

Converting from text to numbers runs into the problem that
0.1 has no finite representation as a Fixed Binary.
We'll deal with that after considering rounding.

\subsection{Ring arithmetic}

Numbers of the form $m\times r^s$ form a ring under the usual
arithmetic operations, but they are \emph{not} a field, see
subsection Division.
We can convert a fixed-point number to an exact Rational number and
those \emph{are} a field.  None of the ring operations can fail.
This provides the LIA operations {\it add}, {\it sub}, {\it mul},
{\it neg}, {\it abs}, and {\it sign}.  The 2012 revision of LIA-1
defines {\it signum} instead of {\it sign}.  One possible confusion
is that LIA's {\it sign} is Haskell's {\it signum}; testing is
advisible to catch mistakes there.  The LIA-2 {\it dim}
function can also be defined for any ordered numeric type.

\begin{code}
instance (Has_Radix t) => Num (Fixed t)
  where
    x + y = FP (align x y (+)) (scale x `max` scale y)
    x - y = FP (align x y (-)) (scale x `max` scale y)
    negate (FP m s) = FP (negate m) s
    abs    (FP m s) = FP (abs    m) s
    signum (FP m s) = FP (signum m) 0
    fromInteger n   = FP n 0
    (FP m1 s1) * (FP m2 s2)  = FP (m1*m2) (s1+s2)

lia_signum :: (Ord t, Num t) => t -> t
lia_signum x = if x < 0 then -1 else 1

lia_dim :: (Ord t, Num t) => t -> t -> t
lia_dim x y = if x < y then fromInteger 0 else x - y

instance (Has_Radix t) => Real (Fixed t)
  where
    toRational (FP m s) =
      if s >= 0 then m % (shift 1 s)
      else (shift m (negate s)) % 1
\end{code}
% ERROR: the else part was missing here.
The \% operator divides two integers to make a rational number.

Since raising to a non-negative power requires only the unit
(fromInteger 1) and multiplication, we get the power operation
$x$\verb|^|$n$ free.  This operation fails if $n<0$, aligning
it with the LIA-2 {\it power${}_I$} function, but without the
breakage of making $0^0$ an error.  For example,
\begin{verbatim}
> (1234 2 :: Fixed Decimal) ^ 4
23187.85835536
\end{verbatim}

\subsection{Conversion to integer}

The fromInteger function converts integers to fixed-point;
going the other way loses information so we need to say how.

In [section Rounding] we identified 14 rounding modes.
We have three options for naming them:
\begin{itemize}
\item They could be {\it values}, as done in this section.
\item They could be {\it functions}, {\it e.g.},
\begin{code}% don't copy
down :: Real t => Integer
down x = floor (toRational x)
\end{code}
We can construct these functions if we want them:
\begin{code}% don't copy
down = convert Down
\end{code}
\item They could be {\it types} like Binary and Decimal,
which would mean that the Fixed\_Frame type defined in a
later section would have less run-time content.
\end{itemize}

\begin{code}
data Rounding_Mode
   = Down
   | Up
   | In
   | Out
   | Exact
   | Even
   | Nearest Rounding_Mode
\end{code}

This is very nearly an enumeration type, except that it
allows constructions like Nearest Out.  (It also allows
Nearest (Nearest Odd), which is useless but harmless.)

We're going to define a single ``convert'' function that has
a rounding mode and a rational number and returns an integer.
This depends on the standard function `properFraction',
which splits a rational number into an integer part and
a fractional part of the same type as its argument, such
that both parts are non-negative or both parts are non-positive.
RealFrac is the class of numeric types on which it is defined.

\begin{code}
convert :: RealFrac t => Rounding_Mode -> t -> Integer

convert round x =
  case round of
    Down      -> if d < 0 then i-1 else i
    Up        -> if d > 0 then i+1 else i
    In        -> i
    Out       -> i + d
    Exact     -> if d == 0 then i else error "inexact"
    Even      -> if even i then i else
                 if d /= 0 then i + d else
                 if (i + 1 `mod` 4) == 0 then i+1 else i-1
    Nearest h -> if d == 0 then i else
                 case compare (2*abs f) 1 of
                   LT -> i
                   GT -> i + d
                   EQ -> i + convert h f
  where (i,f) = properFraction x
        d     = if f < 0 then -1 else if f > 0 then 1 else 0
\end{code}

We can't plug Fixed into RealFrac that because numeric types
in Haskell can only belong to RealFrac if they also belong to
Fractional, which requires them to have division, reciprocal,
and conversion from arbitrary rationals.

This is an occasion where Haskell proves to be inconvenient,
because the properFraction, truncate, round, ceiling, and floor
functions of the RealFrac class make perfect sense for
fixed-point numbers.  However, we can compose convert with
toRational, making it possible to convert fixed-point numbers
to different scales and different radices in the spirit of LIA,
being like  the LIA functions {\it round} and {\it trunc}.

\begin{code}
rescale :: forall t r . (Has_Radix t, Real r) =>
          Rounding_Mode -> Integer -> r -> Fixed t

rescale round digits x = FP (convert round y) digits
  where y = toRational x * toRational (radix (undefined :: t) ^ digits)
\end{code}

The (convertFixed In) function provides the
LIA (floating-point) operations {\it intpart}, and {\it fractpart}.

\begin{code}
convertFixed :: Has_Radix t =>
    Rounding_Mode -> Fixed t -> (Integer, Fixed t)

convertFixed round x = (q, x - fromInteger q)
  where q = convert round (toRational x)
\end{code}
% ERROR: if the argument is already an (odd, even) integer,
% it's returned unchanged instead of rounding to (even, odd).

Given this operation, we can define division with an
integer quotient and fixed-point remainder, supporting
the LIA-2 {\it quot}, {\it mod}, {\it ratio}, {\it residue},
{\it group}, and {\it pad} functions.

\begin{code}
quotient :: Has_Radix t =>
    Rounding_Mode -> Fixed t -> Fixed t ->
    (Integer, Fixed t)
quotient round x y = (q, x - fromInteger q * y)
  where q = convert round (toRational x / toRational y)
\end{code}
% Error: was convertFixed round x   -- TWO errors!

The Haskell type-class Integral provides integer quotient
and remainder in the type-class Integral.  This is arguably
the wrong place, which explains why we have
\begin{code}%don't copy
quotient Floor -- instead of divMod
quotient In    -- instead of quotRem
\end{code}

\subsection{Frames}

In a language like COBOL or PL/I, the result of a calculation
must fit into the declared type of a variable, while the way
that the exact result is rounded to fit may be separately
specified.  In other languages, like C$\sharp$, the scale is
part of the value, but there is a maximum scale.  We shall
call the combination of radix (carried in the type),
a desired or maximal scale, a rounding
mode, and optional bounds a Fixed\_Frame, and the operation
of taking an exact result and coercing it into a frame ``fitting''.
A programming language standard could for example say that
``BINARY FIXED ($p,s$) corresponds to
Fixed\_Frame Binary (Exact\_Scale $s$) (Nearest Out)
(Just (-($2^p)$, $2^p-1$))''.

\begin{code}
data Result_Scale
   = Exact_Scale   !Integer
   | Maximum_Scale !Integer

data Fixed_Frame t
   = Fixed_Frame !Result_Scale !Rounding_Mode
                 !Maybe (Integer, Integer)

fit :: Has_Radix t =>
       Fixed_Frame t -> Fixed t -> Fixed t

fit (Fixed_Frame rs round bounds) x@(FP m s)
  = check_bounds bounds m' y
  where
    y@(FP m' _) =
      case rs of
        Exact_Scale e   -> if e == s then x else
                           rescale round e x
        Maximum_Scale e -> if e >= s then x else
                           rescale round e x

check_bounds :: Ord t => Maybe (t,t) -> t -> r -> r

check_bounds Nothing      _ y = y
check_bounds (Just (l,u)) x y =
  if l <= x && x <= u then y else error "overflow"

\end{code}

\subsection{Division}

COBOL, PL/I, SQL, Java, C$\sharp$, Swift, and most libraries
inspected for this work provide division.  The COBOL
DIVIDE statement can be given a satisfactory definition because
the destination and the rounding option provide a Fixed\_Frame.
PL/I's DIVIDE function also provides a Fixed\_Frame for the
answer (with only one rounding mode available).

However, no language or library has a satisfactory definition of
``/'' delivering an intermediate result without constraints
provided by a destination.  That is because no satisfactory
definition exists.

The set of fixed-point numbers is not closed under division.
Consider 0.1/0.3.  This has an exact rational result, 1/3,
but there is no $s$ such that $1/3 \times 10^s$ is an integer.
So unlike addition, subtraction, and multiplication, it is not
possible for division to provide an answer that is both fixed
point and exact.

The best that can be one is to specify division given a frame.

\begin{code}
divide :: forall t u v . (Has_Radix t, Real u, Real v) =>
          Fixed_Frame t -> u -> v -> Fixed t
divide (Fixed_Frame rs round bounds) x y
  = check_bounds bounds m (FP m s)
  where
    s = case rs of
          (Exact_Scale   z) -> z
          (Maximum_Scale z) -> z
    p = radix (undefined :: t) ^ s
    q = toRational x / toRational y
    m = convert round (q * fromInteger p)
\end{code}

The same problem arises when trying to define a square root
function on fixed-point numbers, as some libraries do.  The
same solution, of requiring an explicit frame.  LIA-2 extends
{\it sqrt} to integers, but only with the In rounding mode.

\subsection{Converting from text to number}

Specifying conversion for Fixed Decimal numbers
with their natural scale is tedious rather than difficult.
The code that follows is a finite state automaton that
accumulates an integer and counts digits after the decimal point.
This follows the convention of the Haskell Read class that
a string is mapped to a list of (value,residue) pairs with a
pair for each legal way to parse a prefix of the string.  In
this case there is either one way or none.

\begin{code}
readDecimalFixed :: String -> [(Fixed Decimal,String)]
readDecimalFixed ('-':cs) = after_sign negate cs
readDecimalFixed cs       = after_sign id     cs

after_sign f (c:cs)
  | isDigit c = after_digit f (add_digit 0 c) cs
after_sign _ _ = []

after_digit f n (c:cs)
  | isDigit c = after_digit f (add_digit n c) cs
after_digit f n ('.':c:cs)
  | isDigit c = after_dot f 1 (add_digit n c) cs
after_digit f n ('.':_) = []
after_digit f n cs = [(FP (f n) 0, cs)]

after_dot f s n (c:cs)
  | isDigit c = after_dot f (s+1) (add_digit n c) cs
after_dot f s n cs = [(FP (f n) s, cs)]

add_digit :: Integer -> Char -> Integer

add_digit n c =
   n * 10 + fromIntegral (fromEnum c - fromEnum '0')
\end{code}
%ERROR: add_digit had - fromEnum c
%ERROR: after_dot had n and s swapped.

However, \verb|"0.1"| has no exact representation as a
Fixed Binary, nor is the natural scale what a
program necessarily needs.  What is needed is precisely
a Fixed\_Frame.

\begin{code}
readFixed :: Has_Radix t =>
             Fixed\_Frame t -> String ->
             [(Fixed t, String)]

readFixed frame cs =
   [ (fix frame num,rest) | (num,read) <- readDecimalFixed cs ]
\end{code}

\end{document}


\chapter{Evaluation metrics for quantization and rating}
\label{chap:eval}
Evaluating the collected data is one of the key responsibilities of the application. From a set of rated faces, a policy is to be learned that can quantize the user's subjective perception of attractiveness. Depending on the circumstances, different approaches exist to achieve this. Given the \textit{CelebA} dataset, which is already annotated with facial attributes, there is no image processing neccessary. All policies can be learned from the combination of attribute labels and user decision. However, the goal is to make the system applicable to unknown images. Serving as a plug-in for existing applications as it is targeted in chapter \ref{chap:plugin}, images are not labeled. Therefore, the next step of \textit{Quantinder} is to extract relevant attributes from images by its own. This would, however, probably not be executed on the client's phone, as the images are available on servers anyway. Section \ref{sec:celebadesc} explains the structure of the \textit{CelebA} dataset. Section \ref{sec:straightfwd} describes the evaluation approach implemented in \textit{Quantinder} with the labeled images from \textit{CelebA}, whereas section \ref{sec:unlabeled} discusses possibilites to handle unlabeled image datasets by extracting the attributes from the images.
\section{Formal description of the \textit{CelebA} dataset}
\label{sec:celebadesc}
The \textit{CelebA} dataset consists of over 200.000 images from 10.000 celebrities. All images display the face of the identity. Parts of the body are optional. The backgrounds of the images are divergent, there are faces on a magazine's front page as well as well as indoor and outdoor portrais. The main contribution of the \textit{CelebA} dataset are the annotations of each image. They define whether or not a face exhibits a certain attribute. Formally we can describe \textit{CelebA} as a set of images $S_{I}$, where $\lvert S_{I}\rvert=202.599$ and a set of attributes $S_{A}$, where $\lvert S_{A}\rvert=40$. The set $S_{V}$ of all ordered pairs ($i$,$a$), $i\in S_{I}$, $a\in S_{A}$, is obtained by the Cartesian product of the two sets as
\begin{equation}
S_{V}=S_{I}\times S_{A}.
\end{equation}
A mapping fuction
\begin{equation}
\label{eq:f}
f:S_{V}\mapsto Y_V,\quad where\ Y_V = \{1,-1\}
\end{equation}
assigns either $1$ or $-1$ to each element $v=(i,a) \in S_{V}$.  Function $f$ is specified by humans who decided for each image attribute pair $v=(i,a)$ whether the face in the image $i$ exhibits the attribute $a$. If so, $f(v)=1$, otherwise $f(v)=-1$.
\section{Formal description of the data gathered from user input}
\label{sec:userinput}
Through swiping through the images, the user gives either a positive or negative feedback for each image. Thus, the feedback function is defined as
\begin{equation}
\label{eq:g}
g:S_{I}\mapsto Y_S,\quad where\ Y_S\ = \{1,-1\}.
\end{equation}
Function $g(i)$ yields $1$ as its value if the user liked the face in image $i$ and $-1$ if the user disliked the face.
\section{Rating the attributes given the labeled images from \textit{CelebA} and the user's decision}
\label{sec:straightfwd}
Given the labeled dataset according to equation \ref{eq:f} and the user input as defined in equation \ref{eq:g}, a policy should be learned that represents the user's subective perception of attractiveness. To this end, different metrics can be applied to generate an expressive and realistic policy. Both the information sources from equation \ref{eq:f} and \ref{eq:g} are to be combined. For each attribute $a\in S_A$, the user's approval rating $h(a)$ is to be determined by the function
\begin{equation}
h:S_A\mapsto \mathds{R}
\end{equation}
The approval rating value $h(a)$ respresents the subjective attractiveness of the attribute $a$ and is positive if the user likes the attribute and negative if he dislikes $a$. Therefore, the function $h(a)$ is to be specified. Various approaches are envisaged in the following subsections.
\subsection{Increment and decrement scheme}
On account of the simplicity of $f$ and $g$ with binary codomains, the evaluation function $h$ can be defined without complex calculation schemes. Let us consider a case where the user rated one face only. We want to formulate $h$ in a way so that in yields the approval rating for every attribute in $S_A$. The straight-forward solution for the formulation of $h$ for the case of a single image $i$ would be an equality check of the binary attribute value $f(i,a)$ and the binary user decision $g(i)$ as follows:
\begin{equation}
\label{eq:oneface}
h_i(a) = f(i,a)\ XNOR\ g(i).
\end{equation}
Semantically, this means that the approval rating of an attribute is positive either when the user liked the face and the face exhibits this attribute or when the user disliked the face and the face does not exhibit the attribute. Otherwise, the approval rating $h(a)$ is negative. For mathematical convenience and expandability to non-binary values, the codomains $Y_V$ and $Y_S$ of $f$ and $g$ have been defined as $1$ for logic true and $-1$ for logic false. This allows implementing the XNOR operation as an integer multiplication, since
\begin{equation}
\label{eq:verysmall101}
\begin{split}
-1\cdot(-1) = 1\\
-1\cdot1 = -1,\\
1\cdot(-1) = -1,\\
1\cdot1=1.
\end{split}
\end{equation}
When trying to evaluate the results from more than one face, the formulation from equation \ref{eq:oneface} is not sufficient. However, we can iterate over the image set $S_I$ and, apply the logic from equation \ref{eq:oneface} and \ref{eq:verysmall101} and associate the values from the single iterations by summation:
\begin{equation}
\label{eq:morethanoneface}
h(a) = \sum_{i\in S_I} f(i,a) \cdot g(i)
\end{equation}
Function $h(a)$ is calculated for all forty $a\in S_A$. It can be updated incrementally while the user is swiping through the faces. Suppose the user has swiped through a hundred images. Equation \ref{eq:morethanoneface} says, for a further face the user swipes to the right, implying a like and $g(i)=1$, the attribute approval rating $h(a)$ increases by 1 if the face exhibits attribute $a$, implying $f(i,a)=1$. All other attributes, that are not present in the face, are rated down by 1. Through the simple combination of $f$ and $g$, the system is already able to quantize the user's preferences. If the independent application of equation \ref{eq:morethanoneface} for every attribute is merged, then the output can be depicted as the attribute approval rating vector $v_h$, which is obtained by
\begin{equation}
\label{eq:vec}
v_h = [h(a_0), h(a_1) ... h(a_{39})].
\end{equation}
The elements of $v_h$ can be sorted in a way that assigns the highest value the lowest index. Thereafter, a list from the best rated attributes to the worst rated attributes can be printed. This information corresponds to the user's preferences.

Given the attribute approval rating vector $v_h$, it is possible to make a prior guess about the posterior event of the user's decision for the next image. If there are many attributes in the face which have a high value in $v_h$, the user is probably going to like this face as well. This idea is implemented as
\begin{equation}
\label{eq:posteriorguess}
l(i) = \sum_{a\in S_A} v_h[a] \cdot g(i),
\end{equation}
where $l(i)$ is the prior guess value. Increasing positive values of $l(i)$ correspond to an increasing probability that the user is going to like the face. This prior guess value can be converted to a percentage by dividing through the highest possible match.
\subsection{Normalization based on like ratio}
The rating approach based on equations \ref{eq:morethanoneface}, \ref{eq:posteriorguess} is already capable of elaborating preferences and distastes, however, it suffers from being dependent on a balanced like ratio. For instance, when the user swipes all the images to the right, actually it should not be possible to make any assumptions. But a system solely based on the logic from equations \ref{eq:morethanoneface}, \ref{eq:posteriorguess} will still generate an output. The attributes which are exhibited by the most faces will have the highest rating. This violates the validity, which was one of the requirements to the evaluation logic. Therefore, the attribute approval rating $h(a)$ is normalized with respect to the like/dislike ratio.

Given the like ratio, the normalization is achieved by weighting the users's feedback lower for all faces which have been swiped in the direction where the majority of the faces has been swiped to. The influence of liked and disliked faces should thus become equally balanced. Normalization is conducted for each attribute $a$ as
\begin{equation}
\label{eq:basicnormaliz}
h_\eta(a) = h(a) - \eta(a),
\end{equation}
where $\eta(a)$ is the normalization term informally defined as
\begin{equation}
\label{eq:infmleta}
\eta(a) = \frac{diff(\texttt{liked}, \texttt{disliked}) \cdot diff(\texttt{faces with } a, \texttt{faces without } a)}{\texttt{\# rated faces}}.
\end{equation}
Equation \ref{eq:infmleta} expressed more formally, it could be denoted as
\begin{equation}
\label{eq:fmleta}
\eta(a) = \frac{\delta_g\cdot\delta_f(a)}{n},
\end{equation}
where the total number of rated faces $n$ in the denominator can be obtained by
\begin{equation}
n = \lvert \{i\in S_I\ \lvert\ \exists\ g(i)\}\rvert,
\end{equation}
the gap between liked and disliked faces $\delta_g$ by
\begin{equation}
\delta_g = 2\cdot n_{liked} - n,\quad \texttt{where}\ n_{liked}= \{i\in S_{I}\ \lvert\ g(i)=1\},
\end{equation}
and the gap between faces exhibiting $a$ and faces not exhibiting $a$ by
\begin{equation}
\delta_f(a) = 2\cdot n_{exhibits} - n,\quad \texttt{where}\ n_{exhibits}= \{i \in S_{I}\ \lvert\ f(i,a)=1\}.
\end{equation}

Let us consider some cases for $\delta_g$ and $\delta_f$. The normalization term $\eta(a)$ is positive when the like ratio is over 50\% and more than 50\% of the rated faces exhibit $a$. $\eta(a)$ is also positive if both aforementioned conditions do not hold. Semantically, this means the normalized attribute approval rating $h_\eta(a)$ will be less than the original $h(a)$. In general, the normalization term always decreases $h(a)$ with respect to the absolute value. If $\delta_g$ and $\delta_f$ have different signs, $\eta(a)$ is negative, however, in this case $h(a)$ is also negative because of equation \ref{eq:morethanoneface}. If either the number of likes matches the number of dislikes or there is the same number of faces with and without $a$, $\eta(a)$ will be zero. No normalization is applied. To understand the purpose of including $\delta_g$, the example from above is regarded where the user swipes all faces to the right. When the attribute values are equally distributed among $1$ and $-1$, $h(a)$ is already zero. The desired result is also zero because based on the user's input there cannot be made any assumption. So in this case, the normalization should have no effect on $h(a)$. But if the attribute $a$ were present in, for instance, 80 of 100 rated faces, $h(a)$ attains $+60$ according to equation \ref{eq:morethanoneface}. Now, the difference between liked and disliked images $\delta_g$ is $+100$ and the difference $\delta_f$ between faces with $a$ and faces without $a$ is thus $+60$. Following equation \ref{eq:fmleta}, the resulting normalization term is $\eta(a)=+60$. After inserting $\eta(a)$ in equation \ref{eq:basicnormaliz}, it becomes apparent how the consequences of a unbalanced like ratio can be cancelled out by normalization.

\subsection{Normalization based on stochastical dependency among attributes}
The normalization scheme described above is a decisive factor for a evaluation logic that yields relevant results. However, there is still a problem with stochastical dependency among the attributes. This issue originates in the human behaviour to dress and style depending on sex and age as combined with the setup of \textit{CelebA}, where attributes have been chosen in a way they are partially redundant. For instance, experiments have shown that for most of the heterosexual men, the attributes \textit{Heavy Makeup} and \textit{Wearing Lipstick} are among the best rated attributes. Most of the subjects were suprised about the results since they actually do not consider these attributes attractive. However, since the number of women with makeup and lipstick is sharply higher, the attributes have a strong positive rating when the user swipes every women to the right and every men to the left. Therefore, the issue can be defined as follows: Some attributes are continuously rated either positive or negative, although the user is not really interested in this attribute. This is caused by the dependency of this attribute to one or more other attributes which are the real reason for the user to like the face.

Removing this dependency is a further step to obtain valuable results which represent the real subjective perception of attractiveness. Therefore, all attributes are scanned for their dependency on each other. The result is a undirected complete graph, visualized in Figure \ref{pic:complgraph}.

\FG{complgraph.png}{8cm}{Complete undirected graph showing the dependencies among six selected attributes. Dark red edges indicate negative correlation, dark green edges positive correlation and black edges indifferences.}{complgraph}

The dependencies from Figure \ref{pic:complgraph} are to be balanced out in a way so that redundancy is cancelled out in the rating results. Weights are introduced for each rated face and attribute. Faces which do not comply with the general dependency rule are more interesting and thus get a higher weight. For instance, if there is a male(1) person with beard(2), no lipstick(3) but makeup(4), the \textit{Beard} and \textit{Wearing Lipstick} attributes are assigned a lower weight because three out of four edges comply with the general rule based on the dependencies. People wearing beards wear in most cases no lipstick. In the same way, male persons wear almost never lipsticks, but often beards. These general rules based on the dependencies are visualized by the edge colors in Figure \ref{pic:complgraph}. In contrast to the three aforementioned attributes, the makeup attribute occurs more often together with non-male persons with no beard, but lipstick. The makeup attribute is, thus, in the example some kind of the odd one out. Hence the beard attribute is weighted stronger for this face than for faces of women with lipstick and makeup. The beard and lipstick attributes are thus of less interest than the makeup attribute, which is very rare for male people with beard and no lipstick. This rareness makes this particular face a more decisive face with respect to the makeup attribute. Thus, applying this weights in the calculation of the attribute approval rating, the desired effect of removing implicit dependencies can be achieved.

To illustrate the mathematical principle behind the balancing, let us consider a dataset with only two attributes instead of forty. These two attributes are \textit{Male} and \textit{Heavy Makeup}. Table \ref{tab:pairs} shows the attribute values in the example dataset.

\begin{table}
\centering
\begin{tabular}{l | c c}
              & Male & Heavy_Makeup\\
\hline
Face1  & -1 & 1   \\
Face2  & -1 & 1   \\
Face3  & -1 & -1   \\
Face4  & 1 & 1   \\
Face5  & 1 & -1 \\
Face6 & 1 & -1
\end{tabular}
\caption{The example dataset contains images from thre male and three female persons. Two third of the female wear heavy makeup, two third of the male do not.}
\label{tab:pairs}
\end{table}

Starting with the dataset from Table \ref{tab:pairs}, the number of pairs with equal values are counted. There are $n_{tot}=6$ images $i \in S_I$ in the dataset and two attributes $a \in S_A$. Both attributes are equally often present and absent, but they are dependent on each other because more female than male persons wear heavy makeup. The pair for \textit{Face1} is denoted as
\begin{equation}
\label{eq:pair}
p_{i1}=(a_1(i),a_2(i)),
\end{equation}
where $a_1$ corresponds to the male attribute and $a_2$ to the heavy makeup attribute. The number of pairs with equal values is determined by
\begin{equation}
n_{eq}=\lvert (i \in S_I, a \in S_A\ \lvert\ a_1(i) = a_2(i)) \rvert
\end{equation}
Aiming for a balanced ratio between equal and distinct pairs, the weight for all equal pairs is determined as
\begin{equation}
\label{eq:weight}
w_{eq} = \frac{n_{tot}}{2\cdot n_{eq}}.
\end{equation}
Likewise, the weight $n_{dst}$ for the distinct pairs is calculated by replacing $n_{eq}$ in equation \ref{eq:weight} with $n_{tot}-n_{eq}$. In the estimation process of an attribute's approval rating, the weights are multiplied with the binary feedback value obtained from the user. The weight $n_{eq}$ is multiplied to all faces $S_{I,eq}$ for which equation \ref{eq:pair} holds and $n_{dst}$ is multiplied to all faces $S_{I,dst}$ that exhibit dinstinct attribute values, meaning equation \ref{eq:pair} does not hold.
Contemplating the example from Table \ref{tab:pairs}, $w_{eq}$ is calculated as $6/(2 \cdot 2)=1.5$ and $w_{dst}$ is $6/(2\cdot 4)=0.75$. Extending equation \ref{eq:morethanoneface} with the weight term, an $h_n(a)$ can be obtained as
\begin{equation}
\label{eq:weightedsum}
h_n(a) = \sum_{i\in S_I} f(i,a)\cdot g(i) \cdot w(i),
\end{equation}
\begin{equation}
\label{eq:weightseqdst}
where\quad w(i) = \left\{\begin{array}{lr}
        w_{eq} & \text{if }  i \in S_{I,eq}\\
        w_{dist} & \text{otherwise } \\
        \end{array}\right.
\end{equation}
Let the user like all female faces and dislike all male faces. By plugging in the values from Table \ref{tab:pairs} into equation \ref{eq:weightedsum}, the resulting attribute approval ratings are $h_n(\textit{Male}) = +6$ and $h_n(\textit{Heavy Makeup}) = 0$. This is exactly the wanted behaviour. When comparing this to the results without the weighting term by simply plugging into equation \ref{eq:morethanoneface}, we obtain $h(\textit{Male}) = +6$ and $h(\textit{Heavy Makeup}) = +2$. The weighting term has thus successfully removed the dependency of the \textit{Heavy Makeup} attribute from the \textit{Male} attribute.

Unfortunately, this logic becomes more difficult when there are more than two attributes. In the real implementation, there are 780 edges as this is the number of possible pairs out of 40 nodes, given by the n chooses k formula, where n = 40 and k=2:
\begin{equation}
n_{pairs} = \frac{40!}{2! \cdot 38!} = 780.
\end{equation}
However, to achieve a balanced graph, this effort must be taken. For a given attribute, the weights to each of the other 39 attributes are calculated according to equation \ref{eq:weight}. Subsequently, the attribute approval vector $h_n(a)$ can be determined by equation \ref{eq:weightedsum}, where the weight term $w(i)$ is more complicated than in equation \ref{eq:weightseqdst}. For every face, one of the two weights is selected for all pairs containing $a$ and then multiplied together. The selection is executed as per equation \ref{eq:weightseqdst}. After the products of the multiplication has been determined for each face, $h_n(a)$ is finally obtained by summing up the products, where each product has the sign given by $h_i(a)$ from equation \ref{eq:oneface}. Thus the stochastical dependency among the attributes has been removed.

\section{Preparing for unlabeled images by extracting attributes from images}
\label{sec:unlabeled}
In an environment where real images are to be processed, there are no annotations about facial attributes available. Knowledge about the facial attributes are essential for \textit{Quantinder} and the metrics discussed in chapter \ref{chap:eval}. In order to transfer \textit{Quantinder} to the real world, it is neccessary to extract these attributes from the images. Fortunately, this is possible. Either a foreign library or service can be used or an own network is established. The former method is discussed in subsection \ref{subsec:pretrained} and the latter one is contemplated in subsection \ref{subsec:usingdeepl}.

\subsection{Using Deep Learning}
\label{subsec:usingdeepl}
\FG{anetlnetflow.png}{7cm}{Pipeline of the system from Liu \etAl \cite{deeplfaceattr}.}{anetlnetflow}
Given a large annotated dataset like \textit{CelebA}, it is possible to train a network which first learns the attributes from the training images and later on, it is able to infer the presence or absence for each attribute. Liu \etAl use the CelebA data set in their work \cite{deeplfaceattr} to train two \gls{CNN}s. The first \gls{CNN}, called \gls{LNet} addresses the problem of recognizing and localizing a face in images with natural background. \gls{LNet} is repeated once in a coarse to fine scheme, meaning the larger region of face is determined in the first iteration, and the second iteration determines the exact shape of the face. The \gls{ANet}, the second \gls{CNN}, is responsible for extracting discriminative face features from a given face. By installing a linear \gls{SVM}, which is trained with the feature vectors output from \gls{ANet}, attribute prediction can be achieved. Thus the training pipeline for predicting facial attributes from any image is repeated \gls{LNet} followed by \gls{ANet} followed by the \gls{SVM}. For the training of \gls{LNet} the \gls{ILSVR-C} dataset \cite{ilsvrc} is used. It contains 1.2 million annotated images of objects in natural backgrounds, with humans and other objects mixed. The annotation gives information about the object category, such as vehicle, dog, or human face. The annotation is only at image-level, which means \gls{ILSVR-C}'s annotations do not provide information about the object's location in the image. This means \gls{LNet} must learn the location of a face in an image implicitly. On account of the object category labels, \gls{LNet} knows in the training phase which images are a face and which are not, and by learning from the differences, the parts that belong to the face can thus be identified. For fine tuning \gls{LNet}, the CelebA dataset is also considered, but the main purpose of CelebA is to train the \gls{ANet}, which is responsible of extracting distinctive facial features that can subsequently be consulted to determine the binary value of each of the forty attributes.

\subsection{Using foreign pre-trained face attribute extractors}
\label{subsec:pretrained}
The complexity of building an own \gls{CNN} could be avoided by utilizing the knowledge from a trained model which is, however, trained for a different purpose. This is known as transfer learning \cite{transferl}. More specifically, transfer learning means to transfer the learned features from a network to a target network. The target network should learn different features which are related to the features from the reused network. This process will tend to work if the features from the frist network are general with respect to the target network. When trying to learn facial attributes, a network having been trained for general object classification is a good starting point. For object classification, there are many trained \gls{CNN}s available, for instance the \textit{RsNet-50} network, which has been trained on millions of images from the \textit{ImageNet} dataset. Libraries such as \textit{fast.ai} simplify the process of imlementing transfer learning significantly. The first convolutional network, for instance \textit{RsNet-50} can be easily extended by a number of layers which are responsible to fulfill the task of attribute detection. These additional layers still have to be trained, however, effort is less since tasks as face localization are already handled by the \textit{RsNet-50} network.

A further option for extracting facial attributes is to use attribute detection services from foreign providers such as the \textit{Google Cloud Vision} API or the \textit{Haystack.ai} API. Both work by sending images to the provider and receiving a response where the attribute values are listed. In Haystack, the response exhibits information about predicted age, objective attractiveness, race, gender, emotion and nudity. They easily oould be transformed into a set of binary attributes as in \textit{CelebA}. \textit{Google Cloud Vision}'s face recognition software is capable of predicting the likelihood of the presence of certain emotions as well as of attributes such as size and color of facial features. Services like these have in common that all detection algorithms are implemented server-sided. They are based on being trained with large image datasets. Simply using one of these services would simplify the implementation significantly, however, there are a few drawbacks coming along with this method. First, \textit{Google Vision} and \textit{Haystack.ai} are paid services, where a fee is paid for the processing of each image. For a larger scaled application, costs would sour up. Second, no customization of the algorithms is possible. Both response format and the inference method is fixed and cannot be adapted to specific needs. Third, as the services are proprietary, there is no information published about the functionality of the network behind the services. This prevents conducting a suitability analysis.