\chapter{Bytevectors}
\label{bytevectorschapter}

Many applications deal with blocks of binary data by accessing
them in various ways---extracting signed or unsigned numbers of
various sizes.  Therefore, the \defrsixlibrary{bytevectors} library
provides a single type for
blocks of binary data with multiple ways to access that data. It deals
with integers and floating-point representations
in various sizes with specified endianness.

Bytevectors\mainindex{bytevector} are objects of a disjoint
type. Conceptually, a bytevector represents a sequence of 8-bit
bytes.  The description of bytevectors uses the term \defining{byte}
for an exact integer object in the interval $\{-128, \ldots, 127\}$ and the
term \defining{octet} for an exact integer object in the interval $\{0,
\ldots, 255\}$.  A byte corresponds to its two's complement
representation as an octet.

The length of a bytevector is the number of bytes it contains. This
number is fixed. A valid index into a bytevector is an exact,
non-negative integer object less than the length of the bytevector.
The first byte of a bytevector has index 0;
the last byte has an index one less than the length of the bytevector.

Generally, the access procedures come in different flavors according
to the size of the represented integer and the endianness of the
representation.  The procedures also distinguish signed and unsigned
representations.
The signed representations all use two's complement.

Like string literals, literals representing bytevectors do not need to
be quoted:
%
\begin{scheme}
\#vu8(12 23 123) \ev \#vu8(12 23 123)%
\end{scheme}

\section{Endianness}

Many operations described in this chapter accept an
\defining{endianness} argument.  Endianness describes the encoding of
exact integer objects as several contiguous bytes in a bytevector~\cite{IEN137}.
For this purpose, the binary representation of the integer object is split into
consecutive bytes.  \mainindex{little-endian}The little-endian
encoding places the least significant byte of an integer first, with
the other bytes following in increasing order of significance.
\mainindex{big-endian}The big-endian encoding places the most
significant byte of an integer first, with the other bytes following
in decreasing order of significance.

This terminology also applies to IEEE-754 numbers: IEEE~754 describes
how to represent a floating-point number as an exact integer object, and
endianness describes how the bytes of such an integer are laid out in
a bytevector.

\begin{note}
  Little- and big-endianness are only the most common kinds of
  endianness.  Some architectures distinguish between the endianness
  at different levels of a binary representation.
\end{note}

\section{General operations}

\begin{entry}{%
\proto{endianness}{ \hyper{endianness symbol}}{\exprtype}}

\domain{The name of \hyper{endianness symbol} must be a symbol describing an
  endianness.  An implementation must support at least the symbols
  {\cf big} and {\cf little}, but may support other endianness
  symbols.}  {\cf (endianness \hyper{endianness symbol})} evaluates to
the symbol named \hyper{endianness symbol}.  Whenever one of the
procedures operating on bytevectors accepts an endianness as an
argument, that argument must be one of these symbols.  It is a syntax
violation for \hyper{endianness symbol} to be anything other than an
endianness symbol supported by the implementation.

\begin{note}
  Implementors should use widely accepted designations
  for endianness symbols other than {\cf big} and {\cf little}.
\end{note}

\begin{note}
  Only the name of \hyper{endianness symbol} is significant.
\end{note}
\end{entry}

\begin{entry}{%
\proto{native-endianness}{}{procedure}}

Returns the endianness symbol associated implementation's preferred
endianness (usually that of the underlying machine architecture).
This may be any \hyper{endianness symbol}, including a symbol other
than {\cf big} and {\cf little}.
\end{entry}

\begin{entry}{%
\proto{bytevector?}{ obj}{procedure}}

Returns \schtrue{} if \var{obj} is a bytevector,
otherwise returns \schfalse{}.
\end{entry}

\begin{entry}{%
\proto{make-bytevector}{ k}{procedure}
\rproto{make-bytevector}{ k fill}{procedure}}

Returns a newly allocated bytevector of \var{k} bytes.

If the \var{fill} argument is missing, the initial contents of the
returned bytevector are unspecified.

If the \var{fill} argument is present, it must be an exact integer
object in
the interval $\{-128, \ldots 255\}$ that specifies the initial value
for the bytes of the bytevector: If \var{fill} is positive, it is
interpreted as an octet; if it is negative, it is interpreted as a byte.
\end{entry}

\begin{entry}{%
\proto{bytevector-length}{ bytevector}{procedure}}

Returns, as an exact integer object, the number of bytes in \var{bytevector}.
\end{entry}

\begin{entry}{%
\proto{bytevector=?}{ \vari{bytevector} \varii{bytevector}}{procedure}}

Returns \schtrue{} if \vari{bytevector} and \varii{bytevector} are equal---that
is, if they have the same length and equal bytes at all valid indices.
It returns \schfalse{} otherwise.
\end{entry}

\begin{entry}{%
\proto{bytevector-fill!}{ bytevector fill}{procedure}}

\domain{The \var{fill} argument is as in the description of the {\cf
    make-bytevector} procedure.}
The {\cf bytevector-fill!} procedure stores \var{fill} in every element of \var{bytevector}
and returns \unspecifiedreturn.  Analogous to {\cf vector-fill!}.
\end{entry}

\begin{entry}{%
\pproto{(bytevector-copy! \var{source} \var{source-start}}{procedure}}
\mainschindex{bytevector-copy!}{\tt\obeyspaces\\
     \var{target} \var{target-start} \var{k})}

\domain{\var{Source} and \var{target} must be bytevectors.
  \var{Source-start}, \var{target-start},
  and \var{k} must be non-negative exact integer objects that satisfy

  \begin{displaymath}
    \begin{array}{rcccccl}
      0 & \leq & \var{source-start} & \leq & \var{source-start} + \var{k} & \leq & l_{\var{source}}
      \\
      0 & \leq & \var{target-start} & \leq & \var{target-start} + \var{k} & \leq & l_{\var{target}}
    \end{array}
  \end{displaymath}
  %
  where $l_{\var{source}}$ is the length of \var{source} and
  $l_{\var{target}}$ is the length of \var{target}.}

  The {\cf bytevector-copy!} procedure copies the bytes from \var{source} at indices
  \begin{displaymath}
     \var{source-start}, \ldots, \var{source-start} + \var{k} - 1
  \end{displaymath}
  to consecutive indices in \var{target} starting at \var{target-index}.

  This must work even if the memory regions for the source and the target
  overlap, i.e., the bytes at the target location after the copy must be
  equal to the bytes at the source location before the copy.

  This returns \unspecifiedreturn.
\begin{scheme}
(let ((b (u8-list->bytevector '(1 2 3 4 5 6 7 8))))
  (bytevector-copy! b 0 b 3 4)
  (bytevector->u8-list b)) \ev (1 2 3 1 2 3 4 8)%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{bytevector-copy}{ bytevector}{procedure}}

Returns a newly allocated copy of \var{bytevector}.
\end{entry}

\section{Operations on bytes and octets}

\begin{entry}{%
\proto{bytevector-u8-ref}{ bytevector k}{procedure}
\proto{bytevector-s8-ref}{ bytevector k}{procedure}}

\domain{\var{K} must be a valid index of \var{bytevector}.}

The {\cf bytevector-u8-ref} procedure returns the byte at index \var{k} of \var{bytevector},
as an octet.

The {\cf bytevector-s8-ref} procedure returns the byte at index \var{k} of \var{bytevector},
as a (signed) byte.

\begin{scheme}
(let ((b1 (make-bytevector 16 -127))
      (b2 (make-bytevector 16 255)))
  (list
    (bytevector-s8-ref b1 0)
    (bytevector-u8-ref b1 0)
    (bytevector-s8-ref b2 0)
    (bytevector-u8-ref b2 0))) \lev (-127 129 -1 255)%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{bytevector-u8-set!}{ bytevector k octet}{procedure}
\proto{bytevector-s8-set!}{ bytevector k byte}{procedure}}

\domain{\var{K} must be a valid index of \var{bytevector}.}

The {\cf bytevector-u8-set!} procedure stores \var{octet} in element \var{k} of
\var{bytevector}.

The {\cf bytevector-s8-set!} procedure stores the two's-complement representation of
\var{byte} in element \var{k} of \var{bytevector}.

Both procedures return \unspecifiedreturn.

\begin{scheme}
(let ((b (make-bytevector 16 -127)))

  (bytevector-s8-set! b 0 -126)
  (bytevector-u8-set! b 1 246)

  (list
    (bytevector-s8-ref b 0)
    (bytevector-u8-ref b 0)
    (bytevector-s8-ref b 1)
    (bytevector-u8-ref b 1))) \lev (-126 130 -10 246)%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{bytevector->u8-list}{ bytevector}{procedure}
\proto{u8-list->bytevector}{ list}{procedure}}

\domain{\var{List} must be a list of octets.}

The {\cf bytevector->u8-list} procedure returns a newly allocated list of the octets of
\var{bytevector} in the same order.

The {\cf u8-list->bytevector} procedure returns a newly allocated bytevector whose
elements are the elements of list \var{list}, in
the same order.  It is analogous to {\cf list->vector}.
\end{entry}

\section{Operations on integers of arbitrary size}

\begin{entry}{%
\proto{bytevector-uint-ref}{ bytevector k endianness size}{procedure}
\proto{bytevector-sint-ref}{ bytevector k endianness size}{procedure}
\proto{bytevector-uint-set!}{ bytevector k n endianness size}{procedure}
\proto{bytevector-sint-set!}{ bytevector k n endianness size}{procedure}}

\domain{\var{Size} must be a positive exact integer object. $\var{K}, \ldots,
  \var{k} + \var{size} - 1$ must be valid indices of \var{bytevector}.}

The {\cf bytevector-uint-ref} procedure retrieves the exact integer object corresponding to the
unsigned representation of size \var{size} and specified by \var{endianness}
at indices $\var{k}, \ldots, \var{k} + \var{size} - 1$.

The {\cf bytevector-sint-ref} procedure retrieves the exact integer object corresponding to the two's-complement representation of size \var{size} and specified by \var{endianness} at
indices $\var{k}, \ldots, \var{k} + \var{size} - 1$.

\domain{For {\cf bytevector-uint-set!}, \var{n} must be an exact
  integer object in the interval $\{0, \ldots, 256^{\mathit{size}}-1\}$.}

The {\cf bytevector-uint-set!} procedure stores the unsigned representation of size \var{size}
and specified by \var{endianness} into \var{bytevector} at indices
$\var{k}, \ldots, \var{k} + \var{size} - 1$.

\domain{For {\cf bytevector-sint-set!}, \var{n} must be an exact
  integer object in
  the interval $\{-256^{\mathit{size}}/2, \ldots,
  256^{\mathit{size}}/2-1\}$.}
{\cf bytevector-sint-set!} stores the two's-complement
representation of size \var{size} and specified by \var{endianness}
into \var{bytevector} at indices $\var{k}, \ldots, \var{k} + \var{size} - 1$.

The \ldots{\cf -set!} procedures return \unspecifiedreturn.

\begin{scheme}
(define b (make-bytevector 16 -127))

(bytevector-uint-set! b 0 (- (expt 2 128) 3)
                     (endianness little) 16)

(bytevector-uint-ref b 0 (endianness little) 16)\lev
    \#xfffffffffffffffffffffffffffffffd

(bytevector-sint-ref b 0 (endianness little) 16)\lev -3

(bytevector->u8-list b)\lev (253 255 255 255 255 255 255 255
               255 255 255 255 255 255 255 255)

(bytevector-uint-set! b 0 (- (expt 2 128) 3)
                 (endianness big) 16)
(bytevector-uint-ref b 0 (endianness big) 16) \lev
    \#xfffffffffffffffffffffffffffffffd

(bytevector-sint-ref b 0 (endianness big) 16) \lev -3

(bytevector->u8-list b) \lev (255 255 255 255 255 255 255 255
               255 255 255 255 255 255 255 253))%
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{bytevector->uint-list}{ bytevector endianness size}{procedure}
\proto{bytevector->sint-list}{ bytevector endianness size}{procedure}
\proto{uint-list->bytevector}{ list endianness size}{procedure}
\proto{sint-list->bytevector}{ list endianness size}{procedure}}

\domain{\var{Size} must be a positive exact integer object.  For {\cf
    uint-list->bytevector}, \var{list} must be a list of exact
  integer objects in the interval $\{0, \ldots, 256^{\mathit{size}}-1\}$.  For
  {\cf sint-list->bytevector}, \var{list} must be a list of exact
  integer objects in the interval $\{-256^{\mathit{size}}/2, \ldots,
  256^{\mathit{size}}/2-1\}$.  The length of \var{bytevector}
  must be divisible by \var{size}.}

These procedures convert between lists of integer objects and their consecutive
representations according to \var{size} and \var{endianness} in the
\var{bytevector} objects in the same way as {\cf bytevector->u8-list} and {\cf
  u8-list->bytevector} do for one-byte representations.

\begin{scheme}
(let ((b (u8-list->bytevector '(1 2 3 255 1 2 1 2))))
  (bytevector->sint-list b (endianness little) 2)) \lev (513 -253 513 513)

(let ((b (u8-list->bytevector '(1 2 3 255 1 2 1 2))))
  (bytevector->uint-list b (endianness little) 2)) \lev (513 65283 513 513)%
\end{scheme}
\end{entry}

\section{Operations on 16-bit integers}

\begin{entry}{%
\proto{bytevector-u16-ref}{ bytevector k endianness}{procedure}
\proto{bytevector-s16-ref}{ bytevector k endianness}{procedure}
\proto{bytevector-u16-native-ref}{ bytevector k}{procedure}
\proto{bytevector-s16-native-ref}{ bytevector k}{procedure}
\proto{bytevector-u16-set!}{ bytevector k n endianness}{procedure}
\proto{bytevector-s16-set!}{ bytevector k n endianness}{procedure}
\proto{bytevector-u16-native-set!}{ bytevector k n}{procedure}
\proto{bytevector-s16-native-set!}{ bytevector k n}{procedure}}

\domain{\var{K} must be a valid index of \var{bytevector}; so must
  $\var{k} + 1$. For {\cf bytevector-u16-set!} and {\cf
    bytevector-\hp{}u16-native-\hp{}set!}, \var{n} must be an exact integer object in
  the interval $\{0, \ldots, 2^{16}-1\}$.  For {\cf bytevector-s16-set!}
  and {\cf bytevector-s16-native-set!}, \var{n} must be an exact
  integer object in the interval $\{-2^{15}, \ldots, 2^{15}-1\}$.}

These retrieve and set two-byte representations of numbers at indices
\var{k} and $\var{k}+1$, according to the endianness specified by
\var{endianness}. The procedures with {\cf u16} in their names deal with the
unsigned representation; those with {\cf s16} in their names deal
with the two's-complement representation.

The procedures with {\cf native} in their names employ the native
endianness, and work only at aligned indices:
\var{k} must be a multiple of 2.

The \ldots{\cf -set!} procedures return \unspecifiedreturn.

\begin{scheme}
(define b
  (u8-list->bytevector
    '(255 255 255 255 255 255 255 255
      255 255 255 255 255 255 255 253)))

(bytevector-u16-ref b 14 (endianness little)) \lev 65023
(bytevector-s16-ref b 14 (endianness little)) \lev -513
(bytevector-u16-ref b 14 (endianness big)) \lev 65533
(bytevector-s16-ref b 14 (endianness big)) \lev -3

(bytevector-u16-set! b 0 12345 (endianness little))
(bytevector-u16-ref b 0 (endianness little)) \lev 12345

(bytevector-u16-native-set! b 0 12345)
(bytevector-u16-native-ref b 0) \ev 12345

(bytevector-u16-ref b 0 (endianness little)) \lev \unspecified%
\end{scheme}
\end{entry}

\section{Operations on 32-bit integers}

\begin{entry}{%
\proto{bytevector-u32-ref}{ bytevector k endianness}{procedure}
\proto{bytevector-s32-ref}{ bytevector k endianness}{procedure}
\proto{bytevector-u32-native-ref}{ bytevector k}{procedure}
\proto{bytevector-s32-native-ref}{ bytevector k}{procedure}
\proto{bytevector-u32-set!}{ bytevector k n endianness}{procedure}
\proto{bytevector-s32-set!}{ bytevector k n endianness}{procedure}
\proto{bytevector-u32-native-set!}{ bytevector k n}{procedure}
\proto{bytevector-s32-native-set!}{ bytevector k n}{procedure}}

\domain{$\var{K}, \ldots, \var{k}+ 3$ must be valid indices of
  \var{bytevector}.
  For {\cf bytevector-u32-set!} and {\cf
    bytevector-\hp{}u32-\hp{}native-\hp{}set!}, \var{n} must be an exact integer
  object in
  the interval $\{0, \ldots, 2^{32}-1\}$.  For {\cf bytevector-s32-set!}
  and {\cf bytevector-s32-native-set!}, \var{n} must be an exact
  integer object in the interval $\{-2^{31}, \ldots, 2^{31}-1\}$.}

These retrieve and set four-byte representations of numbers at indices $\var{k},
\ldots, \var{k}+ 3$, according to the endianness specified by \var{endianness}. The
procedures with {\cf u32} in their names deal with the unsigned representation;
those with {\cf s32} with the two's-complement representation.

The procedures with {\cf native} in their names employ the native endianness, and
work only at aligned indices: \var{k} must be a multiple of 4.

The \ldots{\cf{}-set!} procedures return \unspecifiedreturn.

\begin{scheme}
(define b
  (u8-list->bytevector
    '(255 255 255 255 255 255 255 255
      255 255 255 255 255 255 255 253)))

(bytevector-u32-ref b 12 (endianness little)) \lev 4261412863
(bytevector-s32-ref b 12 (endianness little)) \lev -33554433
(bytevector-u32-ref b 12 (endianness big)) \lev 4294967293
(bytevector-s32-ref b 12 (endianness big)) \lev -3%
\end{scheme}
\end{entry}

\section{Operations on 64-bit integers}

\begin{entry}{%
\proto{bytevector-u64-ref}{ bytevector k endianness}{procedure}
\proto{bytevector-s64-ref}{ bytevector k endianness}{procedure}
\proto{bytevector-u64-native-ref}{ bytevector k}{procedure}
\proto{bytevector-s64-native-ref}{ bytevector k}{procedure}
\proto{bytevector-u64-set!}{ bytevector k n endianness}{procedure}
\proto{bytevector-s64-set!}{ bytevector k n endianness}{procedure}
\proto{bytevector-u64-native-set!}{ bytevector k n}{procedure}
\proto{bytevector-s64-native-set!}{ bytevector k n}{procedure}}

\domain{$\var{K}, \ldots, \var{k}+ 7$ must be valid indices of
  \var{bytevector}.
  For {\cf bytevector-u64-set!} and {\cf
    bytevector-\hp{}u64-\hp{}native-\hp{}set!}, \var{n} must be an exact integer
  object in
  the interval $\{0, \ldots, 2^{64}-1\}$.  For {\cf bytevector-s64-set!}
  and {\cf bytevector-s64-native-set!}, \var{n} must be an exact
  integer object in the interval $\{-2^{63}, \ldots, 2^{63}-1\}$.}

These retrieve and set eight-byte representations of numbers at
indices $\var{k}, \ldots, \var{k}+ 7$, according to the endianness
specified by \var{endianness}. The procedures with {\cf u64} in their names deal
with the unsigned representation; those with {\cf s64} with the
two's-complement representation.

The procedures with {\cf native} in their names employ the native endianness, and
work only at aligned indices: \var{k} must be a multiple of 8.

The \ldots{\cf{}-set!} procedures return \unspecifiedreturn.

\begin{scheme}
(define b
  (u8-list->bytevector
    '(255 255 255 255 255 255 255 255
      255 255 255 255 255 255 255 253)))

(bytevector-u64-ref b 8 (endianness little)) \lev 18302628885633695743
(bytevector-s64-ref b 8 (endianness little)) \lev -144115188075855873
(bytevector-u64-ref b 8 (endianness big)) \lev 18446744073709551613
(bytevector-s64-ref b 8 (endianness big)) \lev -3%
\end{scheme}
\end{entry}

\section{Operations on IEEE-754 representations}

\begin{entry}{%
\proto{bytevector-ieee-single-native-ref}{ bytevector k}{procedure}
\proto{bytevector-ieee-single-ref}{ bytevector k endianness}{procedure}}

\domain{$\var{K}, \ldots, \var{k}+3$ must be valid indices of
  \var{bytevector}.  For {\cf bytevector-ieee-single-native-ref}, \var{k} must
  be a multiple of $4$.}

These procedures return the inexact real number object that best
represents the IEEE-754 single-precision number represented by the
four bytes beginning at index
\var{k}.
\end{entry}

\begin{entry}{%
\proto{bytevector-ieee-double-native-ref}{ bytevector k}{procedure}
\proto{bytevector-ieee-double-ref}{ bytevector k endianness}{procedure}}

\domain{$\var{K}, \ldots, \var{k}+7$ must be valid indices of
  \var{bytevector}.  For {\cf bytevector-ieee-double-native-ref}, \var{k} must
  be a multiple of $8$.}

These procedures return the inexact real number object that best
represents the IEEE-754 double-precision number represented by the
eight bytes beginning at index \var{k}.
\end{entry}

\begin{entry}{%
\proto{bytevector-ieee-single-native-set!}{ bytevector k x}{procedure}
\pproto{(bytevector-ieee-single-set! \var{bytevector}}{procedure}}
{\tt\obeyspaces\\
     \var{k} \var{x} \var{endianness})}

\domain{$\var{K}, \ldots, \var{k}+3$ must be valid indices of
  \var{bytevector}.  For {\cf bytevector-ieee-single-native-set!}, \var{k} must
  be a multiple of $4$.}

These procedures store an IEEE-754 single-precision representation of \var{x} into
elements \var{k} through $\var{k}+3$ of \var{bytevector}, and return
\unspecifiedreturn.
\end{entry}

\begin{entry}{%
\proto{bytevector-ieee-double-native-set!}{ bytevector k x}{procedure}
\pproto{(bytevector-ieee-double-set! \var{bytevector}}{procedure}}
{\tt\obeyspaces\\
     \var{k} \var{x} \var{endianness})}

\domain{$\var{K}, \ldots, \var{k}+7$ must be valid indices of
  \var{bytevector}.  For {\cf bytevector-ieee-double-native-set!}, \var{k} must
  be a multiple of $8$.}

These procedures store an IEEE-754 double-precision representation of \var{x} into
elements \var{k} through $\var{k}+7$ of \var{bytevector}, and return
\unspecifiedreturn.
\end{entry}

\section{Operations on strings}

This section describes procedures that convert between strings and
bytevectors containing Unicode encodings of those strings.  When
decoding bytevectors, encoding errors are handled as with the {\cf
  replace} semantics of textual I/O (see
section~\ref{transcoderssection}): If an invalid or incomplete
character encoding is encountered, then the replacement character
U+FFFD is appended to the string being generated, an appropriate
number of bytes are ignored, and decoding continues with the following
bytes.

\begin{entry}{%
\proto{string->utf8}{ string}{procedure}}

Returns a newly allocated (unless empty) bytevector that
contains the UTF-8 encoding of the given string.
\end{entry}

\begin{entry}{%
\proto{string->utf16}{ string}{procedure}
\rproto{string->utf16}{ string endianness}{procedure}}

\domain{If \var{endianness} is specified, it must be the symbol {\cf
    big} or the symbol {\cf little}.}  The {\cf string->utf16}
  procedure returns a newly allocated (unless empty) bytevector that
contains the UTF-16BE or UTF-16LE encoding of the given string (with
no byte-order mark).  If endianness is not specified or is {\cf big},
then UTF-16BE is used.  If endianness is {\cf little}, then UTF-16LE
is used.
\end{entry}

\begin{entry}{%
\proto{string->utf32}{ string}{procedure}
\rproto{string->utf32}{ string endianness}{procedure}}

\domain{If \var{endianness} is specified, it must be the symbol {\cf
    big} or the symbol {\cf little}.}  The {\cf string->utf32}
procedure returns
a newly allocated (unless empty) bytevector that contains the UTF-32BE
or UTF-32LE encoding of the given string (with no byte mark).  If
endianness is not specified or is {\cf big}, then UTF-32BE is used.
If endianness is {\cf little}, then UTF-32LE is used.
\end{entry}

\begin{entry}{%
\proto{utf8->string}{ bytevector}{procedure}}

Returns a newly allocated (unless empty) string whose character
sequence is encoded by the given bytevector.
\end{entry}

\begin{entry}{%
\proto{utf16->string}{ bytevector endianness}{procedure}
\pproto{(utf16->string \var{bytevector}}{procedure}}
{\tt\obeyspaces\\
    \var{endianness} \var{endianness-mandatory?})}

\domain{\var{Endianness} must be the symbol {\cf big} or
  the symbol {\cf little}.} The {\cf utf16->string} procedure returns
a newly allocated (unless empty) string whose character sequence is
encoded by the given bytevector.  \var{Bytevector} is decoded according
to UTF-16, UTF-16BE, UTF-16LE, or a fourth encoding scheme that differs from
all three of those as follows: If \var{endianness-mandatory?} is
absent or \schfalse, {\cf utf16->string} determines the endianness
according to a UTF-16 BOM at the beginning of \var{bytevector} if a
BOM is present; in this case, the BOM is not decoded as a character.
Also in this case, if no UTF-16 BOM is present, \var{endianness}
specifies the endianness of the encoding.  If
\var{endianness-mandatory?} is a true value, \var{endianness}
specifies the endianness of the encoding, and any UTF-16 BOM in the
encoding is decoded as a regular character.

\begin{note}
  A UTF-16 BOM is either a sequence of bytes \sharpsign{}xFE,
  \sharpsign{}xFF specifying {\cf big} and UTF-16BE, or \sharpsign{}xFF,
  \sharpsign{}xFE specifying {\cf little} and UTF-16LE.
\end{note}
\end{entry}

\begin{entry}{%
\proto{utf32->string}{ bytevector endianness}{procedure}
\pproto{(utf32->string \var{bytevector}}{procedure}}
{\tt\obeyspaces\\
    \var{endianness} \var{endianness-mandatory?})}

\domain{\var{Endianness} must be the symbol {\cf big} or
  the symbol {\cf little}.} The {\cf utf32->string} procedure returns
a newly allocated (unless empty) string whose character sequence is
encoded by the given bytevector.  \var{Bytevector} is decoded according
to UTF-32, UTF-32BE, UTF-32LE, or a fourth encoding scheme that differs from
all three of those as follows: If \var{endianness-mandatory?} is
absent or \schfalse, {\cf utf32->string} determines the endianness
according to a UTF-32 BOM at the beginning of \var{bytevector} if a
BOM is present; in this case, the BOM is not decoded as a character.
Also in this case, if no UTF-32 BOM is present, \var{endianness}
specifies the endianness of the encoding.  If
\var{endianness-mandatory?} is a true value, \var{endianness}
specifies the endianness of the encoding, and any UTF-32 BOM in the
encoding is decoded as a regular character.

\begin{note}
  A UTF-32 BOM is either a sequence of bytes \sharpsign{}x00,
  \sharpsign{}x00, \sharpsign{}xFE, \sharpsign{}xFF specifying {\cf
    big} and UTF-32BE, or \sharpsign{}xFF, \sharpsign{}xFE,
  \sharpsign{}x00, \sharpsign{}x00, specifying {\cf little} and
  UTF-32LE.
\end{note}
\end{entry}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "r6rs-lib"
%%% End:


%!TEX root = thesis.tex
\chapter{\code{FASMA} and machine learning}
\label{cha:fasmaML}

With the increasing amount of astrophysical data, it is important to perform a rapid and trustworthy
analysis. This is one of the strengths for \code{FASMA} when dealing with high quality spectroscopic
data for determination of stellar atmospheric parameters. Here a classic method to analyse these
large amount of data has been modernised with a new minimisation technique that utilise the physical
knowledge about the system. However smart it may sound like, it can be improved. The time consuming
part in \code{FASMA} are the calls to \code{MOOG}. In the end a couple of minutes are spent on the
minimisation on a modern computer.

This lead to a side-project: explorer the use of machine learning to determine stellar atmospheric
parameters. Machine learning (ML) is not a new topic in computer science, but it is a tool that is
steadily becoming more and more popular in today's science. The effort of using ML here is meant as
a proof of concept, and something that can be improved upon in the future.

The idea was to remove the expensive calls to \code{MOOG} completely. Two things are required in
order to do so in the approach presented here:
\begin{enumerate}
  \item Stellar atmospheric parameters of a large sample of stars with a big span in the parameter
        space
  \item The EW measurements of as many absorption lines as possible (in this case \ion{Fe}{I} and
        \ion{Fe}{II})
\end{enumerate}
Additionally it is here required that the above two points are obtained in a homogeneous way.
Luckily such a sample was already analysed during this thesis as a test of \code{FASMA} (see
\sref{sec:fasma_test}) where a sample of 582 stars were analysed; all of which meet the above
required criteria.

This data set of measurements of EWs and the parameters were organised and prepared in a big table
as follows:
\begin{itemize}
  \item Each row contains both the measurements of the EWs (first N columns) and the parameters
        (last four columns). The parameters are $T_\mathrm{eff}$, $\log g$, $[\ion{Fe}/\ion{H}]$,
        and $\xi_\mathrm{micro}$
  \item The columns excluding the last four are labelled with the wavelength of the absorption line
  \item All wavelength columns which contained at least one missing measurement of the EW for any
        of the 582 stars were removed
\end{itemize}
There are 58 wavelength columns after removing wavelength columns with missing measurements. Before
the removal there were 299 columns with wavelength. In this case the \code{scikit-learn}
package\footnote{\url{http://scikit-learn.org/}} from the Python ecosystem was used to train the
data set. This also package also include a tool to split the data into a training part and testing
part. This is particular useful when trying to evaluate the accuracy of the model used. Here the
training consist of 2/3 of the data, and the rest is for testing. This splitting is done randomly,
giving slight different results each time the script is executed.

The training itself is quite fast (less than \SI{10}{s}). However, the real power comes when the
trained model is saved to the disk, which can later be loaded again. In this way the training will
only be done once. Using the model to obtain the parameters is much less than \SI{1}{s}, which makes
is many orders of magnitudes faster\footnote{Improvements in the order of millions have been
obtained here.} than a more traditional approach as with \code{FASMA}.

When testing the model trained, the 1/3 data set is used to derive parameters. Those derived
parameters are then compared to the actual parameters with a mean absolute error. This gives an idea
of the accuracy. In \fref{fig:ml} the script was run 1000 times (the splitting was done randomly in
each run), and the error for each parameter is shown as a histogram. The mean errors for each
parameters are roughly $T_\mathrm{eff}:\SI{47}{K}$, $\log g:\SI{0.10}{dex}$,
$[\ion{Fe}/\ion{H}]:\SI{0.038}{dex}$, and $\xi_\mathrm{micro}:\SI{0.12}{km/s}$.

\begin{figure}[htpb!]
    \centering
    \includegraphics[width=1.0\linewidth]{figures/ML.pdf}
    \caption{Mean absolute error on each parameter after 1000 runs.}
    \label{fig:ml}
\end{figure}

There exists many different algorithms within \code{scikit-learn} to train the final model. In the
test here a simple \code{LinearRegression} was used. Other algorithms were tested as well, such as
\code{Ridge} and \code{Lasso}, however with very similar results. The main difference between the
different algorithms are found in the details on how the minimisation is done. This is described in
great detail in the online documentation.


% !TEX root = manual.tex

\chapter{Uncertainty Quantification Methods and Tools}
\label{chapter:uq}

\section{Overview}
\label{sec:uqoverview}
The SST/macro UQ workflow generally occurs in two steps:
\begin{itemize}
\item Generating and running parameter sweep
\item Running calibration and sensitivity analysis
\end{itemize}

For uncertainty quantification (UQ) and validation studies the UQ Toolkit (UQTk) library is used.
UQTk (\url{www.sandia.gov/UQToolkit}) is a lightweight C++ library, developed in Sandia National Laboratories, California,
that primarily offers tools for surrogate model construction and uncertainty propagation with
polynomial chaos expansions (PCE), as well as model calibration and validation.

UQTk Version 2.0 is released under the GNU Lesser General Public License (LGPL).
A tar-ball with the source code, tutorials, examples and documentation can be
downloaded from \url{www.sandia.gov/UQToolkit/uqtk\_download.html}
UQTk uses a standard CMake build system.
Fortran (and libgfortran) is required.
The two basic UQ tasks, enabled by UQTk, are \emph{forward UQ} and \emph{inverse UQ} as outlined in the next subsections.

\section{Parameter Sweep and Data Collection}

Performing uncertainty quantification and sensitivity analysis requires sampling across a multi-dimensional parameter space.
Here the multi-dimensional input parameters covers all the latency, bandwidth, and size parameters for a given machine configuration.
In practical usage, a large parameter sweep must be performed to build a surrogate model.
The surrogate model must cover all observables - outputs or statistics of interest from the simulation.
That surrogate model is then used in a Markov Chain Monte-Carlo (MCMC) workflow to derive properties such as:

\begin{itemize}
\item Output sensitvity to input parameters
\item Maximum likelihood values of input parameters
\item Posterior distribution showing for each parameter showing uncertainties
\end{itemize}

\subsection{Surrogate Construction}
\label{subsec:surrogateConstruction}
SST/macro provides helper scripts in the folder \inlineshell{bin/uq} to generate and collect the data for surrogate construction.
The following steps must be performed:

\begin{itemize}
\item Create a template file (see \inlineshell{exampleTemplate.ini} for example). Variables such as \$link\_bw are marked to be replaced.
\item Create a parameter definition file (see \inlineshell{exampleParams} example file). Each variable to explore should match the \$name in the template file. Each parameter must define the range of values to explore. These define the ``prior distribution'' of realistic values for each parameter with min and max for the range given.
\item Run \inlineshell{generate_quad} installed by UQTk. This will create a file \inlineshell{qdpts.dat} defining the parameter sweep to perform.
\item Run \inlineshell{genSweep} using \inlineshell{qdpts.dat} to generate all the input \inlineshell{params_N.ini} files for each point in the sweep.
\item Run \inlineshell{genRunScript} to create a script \inlineshell{runAll} for running all the jobs in parallel on a given machine.
\item Make sure the \inlineshell{runSubSweep} script is in the same folder as \inlineshell{runAll}. Run the \inlineshell{runAll} script. Wait until a \inlineshell{testN.out} file matching all the .ini files is generated.
\item Gather the results. This must be re-written for each study. An example file \inlineshell{gatherResults} shows the basic idea. A final file, e.g. \inlineshell{results.out}, must be
created with one line for each .ini file.  Each line must contain all the output observables corresponding to the run.
\end{itemize}

The files \inlineshell{qdpts.dat} and \inlineshell{results.out} are enough to build the surrogate.

\subsection{Surrogate Validation}
The surrogate is a polynomial fit to the actual observed values.
To test how well the surrogate is able to reproduce the actual simulation, a random set of parameter points should be run through the simulator and compared to the surrogate estimates.
SST/macro provides a helper script \inlineshell{genRandom} to create a \inlineshell{samples.dat} file.
The \inlineshell{samples.dat} file is equivalent to \inlineshell{qdpts.dat} in the surrogate construction phase.
Once \inlineshell{samples.dat} is generated, all the same steps should be followed as in Section \ref{subsec:surrogateConstruction}.

\subsection{Experimental Comparison}
The simulator is trying to reproduce experimental values collected from an actual machine.
These experimental values are the ``nominally correct'' values.
The parameter calibration and sensitivity analysis,
must compare to the nominally correct values.
Usually these will come from a test bed or existing system,
but may come from, e.g. higher-accuracy simulations.
A file \inlineshell{experiments.out} should be generated that matches the format of \inlineshell{results.out} (one line per experimental trial, all output observables on a given line).
While only a single line of data is minimally required,
having multiple trials will improve the UQ workflow by including experimental noise into the uncertainty quantification.

Once you have all three output files (simulation results, random simulation samples, and experimental results),
surrogate construction and analysis can take place using UQTk.

\subsection{Initial Sanity Checks}
To sanity check the match between the simulation parameter sweep and the experimental values,
SST/macro provides a helper script \inlineshell{validatePoints} that creates a PDF plot of all the data.
This is illustrated in Figure \ref{fig:uqSanityCheck} for an MPI ping-pong benchmark.
Here the entire range of the parameter sweep is shown in red lines for the simulator values.
The range of experimental values for each output is also shown.
In this case, the parameter sweep covers all the experimental outputs suggesting that we can reproduce the experiments.

\begin{figure}
\includegraphics{figures/uqSanity.pdf}
\caption{Sanity check plot showing the parameter sweep data (red lines) against the experimental outputs (blue dots) for an MPI ping-pong benchmark}
\label{fig:uqSanityCheck}
\end{figure}

\section{Advanced Usage: Running Surrogate Construction and Sensitivity Analysis By Yourself}
Running the UQ analysis is involved. Help is available by contacting us at \url{sst-macro-help@sandia.gov}.
Documentation pending...

%\section{Applications/Capabilities}
%\label{sec:uqapp}
%
%\subsection{Forward UQ: uncertainty propagation and global sensitivity analysis}
%\label{subsec:fuq}
%
%The main technique we employ for forward UQ is the spectral Polynomial Chaos expansions (PCEs).
%A PCE for a given model allows for a) efficient uncertainty propagation, b) very fast global sensitivity analysis, and
%c) cheap surrogate model construction that can replace the original model in sampling-intensive studies such as calibration,
%optimization, or, generally, inverse UQ.
%
%\subsubsection{Generic workflow:}
%
%A set of scripts that illustrate the essential forward UQ tasks is located in  \texttt{examples\_cpp/uq\_surr}.
%To enable running all scripts one should set an environment variable \texttt{UQTK\_SRC} that points to the location of UQTk.
%
%\begin{ShellCmd}
%setenv UQTK_SRC location/of/uqtk/in/your/computer
%\end{ShellCmd}
%
%
%A generic workflow consists of 4 steps:
%\begin{enumerate}
%\item Generate parameter samples to run the forward model at, for PC construction and validation, \texttt{gen\_sam.x}
%\begin{ShellCmd}
%gen_sam.x <domain_file> <sampling_type(Q/U)> <N_samples> <N_val>
%\end{ShellCmd}
%The list of arguments:
%\subitem \emph{domain\_file}: A file with \bgmth d \endmth rows and 2 columns. \bgmth d \endmth is the total number of parameters being explored.
%           The two columns are the lower and upper bound of the corresponding parameter.
%\subitem \emph{sampling\_type}: Q (Quadrature) or U (uniformly random). Note that currently in this script set, only Q is supported for further PCE generation.
%\subitem \emph{N\_samples}: Number of samples used for training, i.e. for building PCE.
%\subitem \emph{N\_val}:  Number of random samples generated for PCE validation. This can be set to 0 to skip validation.
%
%\item Run the black-box model, \texttt{model.x}
%\begin{ShellCmd}
%model.x
%\end{ShellCmd}
%This is a black-box model that takes no arguments. However, it expects two input files mparam.dat and minput.dat, and returns the function evaluations in the output file moutput.dat.
%\subitem \emph{mparam.dat}: a single column $d\times$1 of the parameters of interest, where d is the number of parameters
%\subitem \emph{minput.dat}: controllable input in a matrix form, $N$$\times$$k$, where $k$ is the number of controllable parameters and $N$ is the number of values or model observables.
%\subitem \emph{moutput.dat}: the model output in a column format $N$$\times$1.
%
%This is the file that needs to be modified/provided by the user according to the model under study. Currently, a simple function $y=Ae^{Bx}+2Bx$ is implemented, where $A$ and $B$ are the parameters (mparam.dat) and $x$ is the single controllable input parameter (minput.dat). A user-created \texttt{model.x} should accept input files minput.dat and mparam.dat as described above, and it should produce an output file moutput.dat with the formats described above,
%
%\item Obtain PCE for the model, \texttt{uq\_surr.x}
%\begin{ShellCmd}
%uq_surr.x <domain_file> <sampling_type(Q/U)> <N_samples> <N_val> \
%		<P_order> <moutput_surr_filename> <moutput_val_filename>
%\end{ShellCmd}
%
%The first four arguments coincide with those from \texttt{gen\_sam.x}, the rest of the arguments are:
%\subitem \emph{P\_order}: the PCE surrogate order. Polynomial series is truncated according to the total order.
%\subitem \emph{moutput\_surr\_filename}: model output file resulting from running \texttt{model.x} on training samples.
%\subitem \emph{moutput\_val\_filename}: model output file resulting from running \texttt{model.x} on validation samples.
%
%\item Postprocess, e.g. global sensitivity analysis, \texttt{pp\_sens.x}
%\begin{ShellCmd}
%pp_sens.x
%\end{ShellCmd}
%
%The current implementation of the post processing script \texttt{pp\_sens.x} takes no arguments. It expects the presence of a PCE information file pccf\_all.dat, which is one of the outcomes of \texttt{uq\_surr.x}. The final global sensitivity results are saved in the \inlineshell{allsens.dat} file of dimensions $N$$\times$$d$, where each row corresponds to a single value for the controllable input (number of controllable inputs = N), and each column corresponds to the sensitivity index of a parameter (number of parameters = d).\\
%
%\medskip
%
%Note that one can run the model \texttt{model.x} in an \emph{online} regime by using the keyword "M" instead of filenames in
%\begin{ShellCmd}
%uq_surr.x <domain_file> <sampling_type(Q/U)> <N_samples> <N_val> <P_order> M M
%\end{ShellCmd}
%that effectively incorporates the steps 1-3 above.
%
%\subsubsection{Simple Example:}
%
%The script \texttt{example.x} incorporates the full workflow above for a test function $y=Ae^{Bx}+2Bx$. Try
%\begin{ShellCmd}
%example.x online
%\end{ShellCmd}
%which produces, in a newly created folder \texttt{test}, the sensitivity file \inlineshell{allsens.dat} with sensitivity indices with respect to $A$ and $B$ for all values of controllable input $x$.
%
%
%
%\end{enumerate}
%
%
%\subsubsection{How Forward UQ applies to \sstmacro}
%
%In the workflow described above, \sstmacro would replace the black-box simple model given by the equation, and \sstmacro parameters of interest would replace $A$ and $B$.   Note that while
%we could explore the entire \sstmacro parameter space using this workflow, the higher the dimensionality of the space the more time process takes, so we would also want to narrow it down to the most important parameters, usually by reasoning, inspection, or simple experimentation.
%Also note that running an \sstmacro simulation can be considerably more expensive than evaluating an
%analytical model, which is why we typically construct a \textit{surrogate}, or an arbitrarily-complex polynomial that can approximate performance given by \sstmacro.
%
%While the above workflow must currently be manually applied to \sstmacro data, we are working on automating this process and coming up with tutorials explaining how it is done.
%
%\subsection{Inverse UQ: parameter calibration and model validation}
%\label{subsec:iuq}
%
%UQTk relies on Bayesian inference methods for model parameter calibration. Model validation is a direct result of calibration
%postprocessing. Indeed, a model is considered validated if the calibrated model parameters and the associated uncertainties can explain/predict available data well.
%The library \texttt{uqtkmcmc} allows implementation of Bayesian calibration using Markov chain Monte Carlo (MCMC) methods. The MCMC technique essentially
%searches the parameter space and compares model results with available data. Note that each parameter sample invokes a model evaluation, and often MCMC requires
%many samples for properly estimating the uncertainties. In such cases, the full model, as a black-box, will be replaced by its surrogate, again as a black-box model, that is constructed by the forward UQ techniques described in Subsection~\ref{subsec:fuq}.


\documentclass[a4paper,11pt]{article}
\usepackage{a4wide}
\usepackage[utf8]{inputenc}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{enumerate}
\usepackage{fancyhdr}
\usepackage{array}
%\usepackage{./include/matrices}
\usepackage{graphicx}
%\usepackage{pictex}
\pagestyle{fancy}
\begin{document}
\renewcommand{\vec}[1]{\ensuremath{\underline{\mathbf{#1}}}}
% Equal sign with hat on top:
\newcommand{\corresponds}{\ensuremath{\widehat{=}}}

\section{fig 1 - handwritten page 2}
\[\substack{	\text{estimate of the density} \\
		\text{at a given point } \vec{x}}
\]
observations

\section{fig 2 - handwritten page 2}
Gaussian kernel \\\\
histogram kernel\\\\
$H$\\\\
$u$

\section{fig 3 - handwritten page 4}
true density \\\\
$P$\\\\
$\widehat{P}$
\[ \substack{ 	\text{estimated density} \\
		\text{(optimal w.r.t } E^T \text{)} }
\]

\section{fig 4 - handwritten page 5}
test data \\\\
model density I \\\\
model density II

\section{fig 5 - handwritten page 8}
Gauss\\\\
$\vec{w}^*$ \\\\
$\widehat{\vec{w}}$\\\\
\[ \substack{ 	\text{width}^2 \text{ (variance) given} \\
		\text{by Fisher information matrix} \\
		\text{(} \leadsto \text{error measure for }
			\widehat{\vec{w}} \text{)}}
\]

\end{document}


\section{}
The chiral central charge tells you the heat current.
If you had a single chiral Majorana mode it's half.

\begin{table}
    \centering
    \begin{tabular}{ccccc}
        (1+1)D & $\mathbb{Z}_2$ invariant &
        $\mathcal{I}=P_0 P_\pi$ &
        $G_f = \mathbb{Z}_2^f$ &
        $\psi\to e^{i\theta}\psi$ Class D\\
        (2+1)D & $\mathbb{Z}$ invariant Chern number &
        C &
        $G=U(1)$ &
        [$G_f=U(1)^f$] Class A\\
        & $\mathbb{Z}$ invariant &
        $\nu=2C_{-}$ (sp. Chern # for free fermions) &
        $G_f=\mathbb{Z}_2^f$
    \end{tabular}
    \caption{Free fermion models}
    \label{tab:freefermions}
\end{table}

\begin{question}
    What is a full Majorana measurement?
\end{question}
Measurement of $\gamma_1 \gamma_j \gamma_k \gamma_l$.
Joint fermion parity.

Consider $U(1)_\uparrow$ with Chern number $C_\uparrow$
and $U(1)_\downarrow$ with Chern number $C_\downarrow$
with
$C_{\uparrow} = -C_{\downarrow} = C$.
There is also time-reversal symmetry.

Chern number breaks time-reversal and reflection symmetry.
It breaks time rerseal because the direction of the current on the edge would
have to switch sign.

But if they have opposite Chern number on both sides with two components then
you can.

A two-component system with $C_\uparrow = -C_\downarrow$ can be time-invariant.

Let's study the edge theory in a particular case here.

\subsection{Edge theory for $C_\uparrow=C_\downarrow=1$}
The Hamiltonian would be like
\begin{align}
    H &=
    \sum_k \left[
    |V_\uparrow| k \psi_{\uparrow,k}^\dagger \psi_{\uparrow,k}
    |V_\downarrow| k \psi_{\downarrow,k}^\dagger \psi_{\downarrow,k}
    \right]
\end{align}
Non-trivial topological phases have something interesitng at the edges.
So consider a backscatttering term or a mass term for htis fermion
\begin{align}
    m \psi_\uparrow^\dagger \psi_\downarrow + h.c.
\end{align}
This breans spin consdervation,
which is the relative $U(1)$.
This breaks the $S_z$ spin conservation.
But that's not so surprising because you have an up fermion and that gets
backscattered by a down fermion,
and it's not so surprising that breaks spin conservation.
More interesting,
this term also breaks time-reversal symmetyr.

Let's deine time reversal to hae the following actiona
\begin{align}
    T: \psi_\uparrow &\to \psi_\downarrow\\
    \psi_\downarrow &\to -\psi_\uparrow
\end{align}
which means on a single fermion $T^2=-1$,
and so
\begin{align}
    T^2 &= {(-1)}^F
\end{align}
So you could say this is a $\mathbb{Z}_4^{T,f}$ symmetry.
But there's also a $U(1)^f$ symmetry.
But if you apply one and apply another,
the order matters,
and there's a complex conjugation when you reverse the order.
And you need to mod out to consider equivalence.
So the symmetry of the system is this
\begin{align}
    G_f &=
    \frac{U(1)^f \rtimes Z_4^{T,f}}{\mathbb{Z}_2}.
\end{align}
This is called the class AII symmetry group in the Cartan classification.

Fermionic symmetry group $G_f$.
Consider whath appens when you act the symmetry only on bosonic operators,
then you can ask what symmetry acts on them,
and that allows you to define a bosoinc symmetry gorup
\begin{align}
    G_b &= G_f/\mathbb{Z}_2^f
\end{align}

If you look at the bosoinc symmetry group,
then
\begin{align}
    G_b &=
    U(1) \rtimes \mathbb{Z}_2^T
\end{align}
Under time-reversal symmetry,
\begin{align}
    T (M \psi_\uparrow^\dagger \psi_\downarrow) T^\dagger &=
    - m^* \psi_\downarrow^\dagger \psi_\uparrow
\end{align}
You'd think there's a single total Chern number.
Surprisingly,
there's still something non-trivial left over.
This suggests there's still some non-trivial topological phase still left over
in the system.
You can then consider two copies.
\begin{align}
    C_\uparrow = - C_\downarro = 2
\end{align}
then you can write the same thing,
but there's an extra flavour $s$.
\begin{align}
    H &=
    \sum_{k,s} \left[
    |V_{\uparrow,s}| k \psi_{\uparrow,k,s}^\dagger \psi_{\uparrow,k,s}
    |V_{\downarrow,s}| k \psi_{\downarrow,k,s}^\dagger \psi_{\downarrow,k,s}
    \right]
\end{align}
Under time-reversal,
\begin{align}
    T: \psi_{\uparrow, s} & \to \psi_{\downarrow,s}\\
    \psi_{\downarrow,s} &\to -\psi_{\uparrow,s}
\end{align}
And now you can consdier what terms you can add,
and it turns out you can add a backscaettering term.
\begin{align}
    \delta H_{\textrm{backscattering}} &=
    m\left(
    \psi_{\uparrow,1}^\dagger \psi_{\downarrow, 2}
    - \psi_{\downarrow,1}^\dagger \psi_{\uparrow, 2}
    + \mathrm{h.c.}
    \right)
\end{align}
and now you can open an energy gap.
This suggests the bulk topological phase should have
$\mathbb{Z}_2$ invariant.

This is the bulk-edge correspondence.
You can deduce the bulk properties by looking at he stability of the boundary
modes under action of the symmetry group.

Now we can consider whath appens when this time-reversal symmetry does not have
this minus sign.
Suppose that instead
\begin{align}
    T: \psi_\uparrow &\to \psi_\downarrow\\
    \psi_\downarrow & \to \psi_\uparrow
\end{align}
and so $T^2=+1$.
Then the symmetry groups are
\begin{align}
    G_f &= U(1)^f \rtimes \mathbb{Z}_2^T\\
    G_b &= U(1) \rtimes \mathbb{Z}_2^T
\end{align}
and then $C_\uparrow = C_\downarrow = -1$
and it does not have protected edge modes.
The fact that $G_f$ is different has consequences on what ind of backscattering
terms you can add.

Fermions can ermge in a variety of situations in solid state systems.
I don't have a good example,
but you can have fermions show up in solid state systems.
Of ten this kind of time reversal can be thoguht of as a effectie time reversal
where you combien it wiht some kind of rotation.
This may be the true time reversal plus some rotation,
but we still call it time reversal because it's anti hermitian.

The $\pi$ rotation in $G_f$ becomes the $1$ operation in $G_b$.
This becomes implicit in
\begin{align}
    G_b &= G_f / \mathbb{Z}_2^f
\end{align}
This becomes a trivial operation as far as a boson is concerned.

\begin{question}
    Why do we ultimately have to define $G_b$?
    The first symmetry gourp is $G_f$.
    Why do we not just work with $G_f$?
\end{question}
I didn't use $G_b$ anywhere,
I just noted $G_b$.
And depending on how sophisticated the theroy is,
it could be useful,
but not in this particular scenario.

Let me remind you of the important Kramers theorem.

If $T^2=-1$,
it measn the minimal representation is 2-dimensional,
whichm eans if you have a state on which $T^2$ acts as $-1$,
it has to be a doublet.
The proof is two lines.
Suppose you act $T$ on a state and you don't change it
\begin{align}
    T\ket{\psi} &= \lambda\ket{\psi}\\
    -\ket{\psi} = T^2 = \lambda^* \lambda \ket{\psi}
\end{align}
So therefore,
$T$ msut bring it to another state
\begin{align}
    T\ket{\uparrow} &= \lambda \ket{\downarrow}\\
    T\ket{\downarrow} &= \lambda^' \ket{\uparrow}
\end{align}
and $\lambda\lambda' = -1$.
which is a contradiction.
So that's Kramers theorem.

consider a cylinder with a momentum around a circle $k_y$ and let $x$ e the axis
of the cylinder.

Consider the spectrum of $E$ vs $k_y$.
there are bulk states in tethe valence conduction bands.
You can see that $T: k \to -k$,
because intiuitively time reversal changes the sign of momentum.
Then the possible time-reversal momenta are
\begin{align}
    \vec{k} &=
    \begin{cases}
        (0, 0)\\
        (0, \pi)\\
        (\pi 0)\\
        (0, 0)
    \end{cases}
\end{align}
There's two topological distrinct scenarios that can happen.
Either these states connect up in a non-trivial way.
This merges into the bulk and then this comes out.

Thisis topological.
No matter where I put my chemical otential,
I'mg going to hit exactly 1.
The trivial situation is when Karmers pairs connect up in a non-trial wahuoWe
have these states and I can have ooThe Kramrs degenerate states in time-reversal
omentua connect up.

You can geta band invariant bby mulitplying hte hern nmber through the Brilluoin
zone.

\section{\mathbb{$Z_2$}c  band invariant}
Define
\begin{align}
    W_{mn}(k) &=
    \bra{U_m(k)} T \ket{U_n(-k)}
\end{align}
where $w$ is unitary.

\begin{align}
    w^T(k) = -w(-k)
\end{align}
$\Lambda_a$ = $ trim,
$a+1,\dpts.a$4$
\begin{align}
    \lambda_n = \mathrm{TRIM}\qquad a=1,\ldots, 4\\
    w^T(\Lambda_a) &= -w(`A_a)
\end{align}
and
\begin{align}
    \delta_a &= \frac{\Pf(w(\Lambda_a))}{\sqrt\det(w(\lambda_a))}}
    = \pm 1
\end{align}
Here
\begin{align}
    \pm 1 &= (-1)^{\nu}
    = \prod_{a=1}^{N}
\end{align}
Need $\sqrt{deg{w(k)}}$ continuous everywhere in BZ.
Can do this if Bloch wave functions we defined continuously everywhere.
Possible boundary condition that total Chern number = 0 by $T$.

\subsection{Time-reversal polarization in 1D}
Fu-Kane arXiv 0606336.
Can split up Bloch states of occupied bands in the two classes.
\begin{align}
    \ket{U_m^I(k)}, \ket{U_m^{II}(k)}\\
    T\ket{U_m^I(k)} &= e^{i\chi_m(k)}\ket{u_m^{II}(-k)}.
\end{align}
Define polarization $P_I$ and $P_{II}$ fore each class.
Total polarization
\begin{align}
    P &= P_I + P_{II}
\end{align}
and time-reversal polarization
\begin{align}
    P_T &= P_I - P_{II}
\end{align}
\begin{align}
    \pm 1 &= (-1)^{P_T} = \delta_1 \delta_2
\end{align}
for $\Lambda_1=0$ $\Lambda_2=\pi$ where
\begin{align}
    \delta_{a} &=
    \frac{\Pf(w(\Lambda_a))}{\sqrt{\det(w(\Lambda_a))}}
\end{align}

The physical meaning is this.
$(-1)^{P_T}=-1$ means boundary has a Kramers degeneracy in each end.

\subsection{Back to 2D}
Can think of 2D system as parameterized 1D
\begin{align}
    H_{2d} &=
    \sum_{k_y} H_{1d}\left( k_y \right)
\end{align}
Consider change in $P_T$ from $k_y=0$ to $\pi$.
\begin{align}
    {(-1)}^{P_T(k_y=\pi) - P_T(k_y=0)} &=
    \delta\left( (0, 0) \right)
    \delta\left( (\pi ,0) \right)
    \delta\left( (0, \pi) \right)
    \delta\left( (\pi, \pi) \right)\\
    &=
    {(-1)}^{\nu}
\end{align}
You can think of this as localized Wannier states.

Just like there is a story for insulators as superconductors,
this story also has an analogue for topological superconductors.
Instead of Chern number $\pm 1$,
we can also consider $p+ip$ or $p-ip$.

Consider a different symmetry group
\begin{align}
    G_f = \mathbb{Z}_4^{T,f}
\end{align}
and there's no $U(1)$.
This is called class DIII.
This would be for topological superconductors.
Consider 2 layers.
There is an invariant $\nu$ for the $p+ip$ layer and
$-\nu$ for the $p-ip$ layer.

All this stuff about topological pumps.
The story on why states are protected.
We get the $\mathbb{Z}_$ classification of topological phases.
From a high level it's very similar.

If you're okay,
we can go to (3+1)D.
Once we've done that,
we'll just leave the world of free fermion topological phases
and go on to describe some other kinds of things.

So we wrote down this band invariant $\nu$.
If you go up one dimension you can consider a similar invariant.

For (3+1)D Classs AII,
\begin{align}
    G_f &= \frac{U(1)^f\rtimes \mathbb{Z}^{T,f}}{\mathbb{Z}_2}
\end{align}
and
\begin{align}
    (-1)^\nu &= \prod_{a=1}^8 \delta_a
\end{align}
8 TRIM:
\begin{align}
    \Lambda_a &= \left( \pi s_1, \pi s_2, \pi s_3 \right)
\end{align}

\section{(3+1)D massive Dirac fermion}
It is useful to start in (4+1)D.
\begin{align}
    H &=
    \sum_{a=0}^{4}
    \sum_{k} \psi_k^\dagger d_a(k)\cdot \Gamma^a \psi_k
\end{align}
where $\Gamma^\mu$ are $4\times 4$ Dirac matrices wiht $\mu=0,\ldots,4$.
Then the anticommutation is
\begin{align}
    \left\{ \Gamma^{\mu}, \Gamma^{\nu} \right\} = 2\delta_{\mu\nu} II
\end{align}
This can be  parameterized family of 3 + 1 dimensional models,
parameetrized by a parameter $k_w$.
\begin{align}
    d_a(k) &=\left(
    m +c \sum_{i=1}^{4}\cos(k),
    \sin k_x,
    \sin k_y,
    \sin k_z,
    \sin k_w
    \right)
\end{align}
so
\begin{align}
    H &= \sum_{k_w} H_{3+1Dj}(k_1,k_2,k_3,k_w).
\end{align}
Then we couple this to a background $U(1)$ gauge field.

View $k_w + A_w = \theta$ as a parameter.
I view this fourth dimension as a parameter.
The 4 + 1 D effective action if we integrate out the fermions is basically a
Chern Simons term.
So it's going to give
\begin{align}
    S_{\mathrm{eff}} &=
    \frac{C_2}{24\pi^2}
    \int d^4x\, dt\,
    \epsilon^{\mu\nu\lambda\sigma}
    A_{\mu} \partial_{\nu} A_{\lambda} \partial_{\rho} A_{\sigma}
\end{align}
where $C_2$ is the second Chern number of Bloch states
\begin{align}
    C_2 &=
    \int \mathcal{F}_{\mu\nu} \mathcal{F}_{\lambda\sigma}
    \epsilon^{\mu\nu\lambda\sigma}
\end{align}
where $\mathcal{F}_{\mu\nu}$ is the Berry curvature of the Bloch wave functions.


\section{Systematic uncertainties}
\label{sec:hmhzz_sys}

This section describes the sources and values of theoretical and experimental systematic uncertainties considered in this analysis.

%% =========================================================================================================================
\subsection{Theoretical systematics}

The theoretical modelling uncertainties include the PDF variations, missing QCD higher-order corrections via the variations of factorisation and renormalization scales,
and the parton showering uncertainties.

\subsubsection{Theoretical uncertainties for signal}
\label{sec:hmhzz_theo_signal}

The PDF, QCD scale and parton showering uncertainties affecting the acceptance difference originating from analysis selection for signal are taken into account in different categories.
The acceptance uncertainties are calculated on the acceptance factor which extrapolates from the fiducial space to the full phase space by a simple ratio:
\begin{equation}
        A = \frac{N_{fiducial}}{N_{total}}
\end{equation}

For PDF uncertainties, the standard derivations of 100 PDF replicas of NNPDF3.0 NNLO, as well as comparison to two external PDF sets: MMHT2014 NNLO, CT14 NNLO are considered.
For missing QCD higher-order corrections, the effects are studied with truth events by comparing weights corresponding to
variations of the renormalization and factorization scale factors, up and down by a factor of two, and the envelop of different variations is used.
The parton showering uncertainties are estimated by comparing events with different setting via \textsc{Pythia8}.

Systematic uncertainties are studied for both cut- and MVA- based event categorizations,
for cut-based analysis in two different categories: the inclusive ggF-CBA-enriched and VBF-CBA-enriched category,
and for MVA-based one in three different categories: inclusive ggF-MVA-high, ggF-MVA-low and VBF-MVA-enriched category.
This section shows the MVA-based results as an example.

Table~\ref{tab:acc-ggF-dnn} and ~\ref{tab:acc-VBF-dnn} show the theoretical uncertainties mentioned above for ggF and VBF signal respectively in MVA-based categorization.

\begin{table}[htbp]
  \centering
  \caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for ggF production. The MVA-based categorization is used.}
  \label{tab:acc-ggF-dnn}
  \begin{spacing}{0.75}
  \begin{tabular}{cccc}
    \toprule
    Categories  & PDF    & QCD Scale  & Parton Shower \\
    \midrule
    ggF-MVA-high  & 0.40\% & 0.06\% & 2.03\% \\
    ggF-MVA-low   & 0.56\% & 0.07\% & 4.86\% \\
    VBF-MVA-enriched  & 0.53\% & 0.09\% & 3.43\% \\
    \bottomrule
  \end{tabular}
  \end{spacing}
\end{table}

\begin{table}[htbp]
  \centering
  \caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for VBF production. The MVA-based categorization is used.}
  \label{tab:acc-VBF-dnn}
  \begin{spacing}{0.75}
  \begin{tabular}{cccc}
    \toprule
    Categories  & PDF    & QCD Scale  & Parton Shower \\
    \midrule
    ggF-MVA-high  & 0.18\% & 1.20\% & 0.41\% \\
    ggF-MVA-low   & 0.43\% & 0.26\% & 0.36\% \\
    VBF-MVA-enriched  & 0.23\% & 3.19\% & 0.85\% \\
    \bottomrule
  \end{tabular}
  \end{spacing}
\end{table}

%\textbf{Cut-based analysis} \\
%
%Table~\ref{tab:acc-ggF-cut} and ~\ref{tab:acc-VBF-cut} show the theoretical uncertainties for ggF and VBF signals respectively in cut-based categorization.
%The uncertainties are computed in two different categories: the inclusive ggF and VBF category.
%\begin{table}[htbp]
%  \centering
%  \caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for ggF production. The cut-based categorization is used.}
%  \label{tab:acc-ggF-cut}
%  \begin{tabular}{cccc}
%    \toprule
%    Categories  & PDF    & QCD Scale  & Parton Shower \\
%    \midrule
%    ggF  & 0.44\% & 0.07\% & 0.22\% \\
%    VBF  & 0.61\% & 0.12\% & 3.33\% \\
%    \bottomrule
%  \end{tabular}
%\end{table}
%
%\begin{table}[htbp]
%  \centering
%  \caption{Summary of acceptance uncertainties of PDF, QCD scale and parton shower variations for VBF production. The cut-based categorization is used.}
%  \label{tab:acc-VBF-cut}
%  \begin{tabular}{cccc}
%    \toprule
%    Categories  & PDF    & QCD Scale  & Parton Shower \\
%    \midrule
%    ggF  & 0.18\% & 2.87\% & 0.52\% \\
%    VBF  & 0.08\% & 4.52\% & 0.72\% \\
%    \bottomrule
%  \end{tabular}
%\end{table}

\subsubsection{Theoretical uncertainties for SM background processes}

The theoretical uncertainties of irreducible $ZZ$ backgrounds are considered in terms of both the variations of shape of \mfl distributions
and the acceptance originating from the event selection.

The PDF and QCD scale uncertainties are considered by using the same method as described for signal.
The parton showering uncertainties for those \textsc{Sherpa} samples are evaluated by varying the resummation scale by a factor of 2,
changing the CKKW setting and using different showering option, following the PMG recommendation in Ref.~\cite{twiki_pmgsyst},
and the quadratic sum between the uncertainties in different kinds of showering option is taken as final result of uncertainties.
Moreover, the shape uncertainty associated with electroweak higher-order correction for \qqZZ process is also taken into account.

Same as for signals, these theoretical uncertainties for irreducible backgrounds are studied for both cut- and MVA- based event categorizations.
The value of shape uncertainties vary from less than 1\% at low mass region to 50\% at high mass tail due to large statistic fluctuation.
As for the acceptance uncertainties, the values vary from about 1\% for PDF variations to 40\% for parton showering variations.
The VBF category has relative larger uncertainties.

Table~\ref{tab:acc-all-qqZZ_MVA} summarizes the acceptance uncertainties of PDF, QCD scale, and parton showering variations for the dominant background: \qqZZ.

\begin{table}[htbp]
  \centering
  \caption{Summary of acceptance uncertainties of PDF, scale, and parton showering variations for QCD \qqZZ background. The MVA-based categorization is used.}
  \label{tab:acc-all-qqZZ_MVA}
  \begin{spacing}{0.75}
  \begin{tabular}{cccc}
    \toprule
    Categories  & PDF    & QCD Scale   & Parton showering \\
    \midrule
    ggF-MVA-high  & 1.15\% & 10.16 \% & 3.71\% \\
    ggF-MVA-low   & 1.04\% & 3.26  \% & 3.80\% \\
    VBF-MVA-enriched  & 2.91\% & 27.90 \% & 23.82\% \\
    \bottomrule
  \end{tabular}
  \end{spacing}
\end{table}

%% =========================================================================================================================
\subsection{Experimental systematics}

The signal and background predictions used in this analysis are also affected by various sources of experimental systematic uncertainties.
Similar as described in section~\ref{sec:vbszz_exp_uncer}, the dominant experimental uncertainties in this analysis also come from the energy/momentum scales
and reconstruction and identification efficiencies of the leptons and jets, as well as the luminosity uncertainty.
The systematic uncertainties are calculated using the recommendations from the Combined Performance (CP) groups of ATLAS experiment.
In addition, as mentioned in previous sections, the uncertainties of irreducible background modelling, reducible background shape smoothing procedure and signal yield difference between simulation and parameterization are all taken into account.
%Table~\ref{tab:np_list} summarizes the experimental systematics considered in this analysis that affect either the normalization of total event yield or the shape of \mfl distribution.
The impact of a few largest systematics and their value from statistical fit are studied in section~\ref{sec:hmhzz_result_4l}.

\iffalse
\begin{table}
  \centering
  \caption{
  A list of the experimental systematics considered in this analysis. The NPs have been separated by whether they only
  affect the normalisation (left column) or if they affect the shape (right column) of the \mfl distribution. They are
  further subdivided into the primary objects that they affect.
  }
  \begin{spacing}{0.65}
  \small
  \begin{tabular}{l|l}
    \toprule
    \multicolumn{1}{c}{Normalisation NPs} & \multicolumn{1}{c}{Shape NPs} \\
    \midrule
    \multicolumn{2}{c}{\textbf{Electrons}} \\
    \midrule
    \texttt{EL\_EFF\_ID\_CorrUncertaintyNP[0-15]}               & \texttt{EG\_RESOLUTION\_ALL} \\
    \texttt{EL\_EFF\_ID\_SIMPLIFIED\_UncorrUncertaintyNP[0-17]} & \texttt{EG\_SCALE\_ALLCORR} \\
    \texttt{EL\_EFF\_Iso\_TOTAL\_1NPCOR\_PLUS\_UNCOR}           & \texttt{EG\_SCALE\_E4SCINTILLATOR} \\
    \texttt{EL\_EFF\_Reco\_TOTAL\_1NPCOR\_PLUS\_UNCOR}          & \texttt{EG\_SCALE\_LARCALIB\_EXTRA2015PRE} \\
    ~                                                           & \texttt{EG\_SCALE\_LARTEMPERATURE\_EXTRA2015PRE} \\
    ~                                                           & \texttt{EG\_SCALE\_LARTEMPERATURE\_EXTRA2016PRE} \\
    \midrule
    \multicolumn{2}{c}{\textbf{Muons}} \\
    \midrule
    \texttt{MUON\_EFF\_ISO\_STAT}         & \texttt{MUON\_ID} \\
    \texttt{MUON\_EFF\_ISO\_SYS}          & \texttt{MUON\_MS} \\
    \texttt{MUON\_EFF\_RECO\_STAT}        & \texttt{MUON\_SAGITTA\_RESBIAS} \\
    \texttt{MUON\_EFF\_RECO\_STAT\_LOWPT} & \texttt{MUON\_SAGITTA\_RHO} \\
    \texttt{MUON\_EFF\_RECO\_SYS}         & \texttt{MUON\_SCALE} \\
    \texttt{MUON\_EFF\_RECO\_SYS\_LOWPT}  & ~ \\
    \texttt{MUON\_EFF\_TTVA\_STAT}        & ~ \\
    \texttt{MUON\_EFF\_TTVA\_SYS}         & ~ \\
    \midrule
    \multicolumn{2}{c}{\textbf{Jets}} \\
    \midrule
    ~                            & \texttt{JET\_BJES\_Response} \\
    ~                            & \texttt{JET\_EffectiveNP\_[1-7]} \\
    ~                            & \texttt{JET\_EffectiveNP\_8restTerm} \\
    ~                            & \texttt{JET\_EtaIntercalibration\_Modelling} \\
    ~                            & \texttt{JET\_EtaIntercalibration\_NonClosure\_highE} \\
    ~                            & \texttt{JET\_EtaIntercalibration\_NonClosure\_negEta} \\
    ~                            & \texttt{JET\_EtaIntercalibration\_NonClosure\_posEta} \\
    ~                            & \texttt{JET\_EtaIntercalibration\_TotalStat} \\
    ~                            & \texttt{JET\_Flavor\_Composition} \\
    ~                            & \texttt{JET\_Flavor\_Response} \\
    ~                            & \texttt{JET\_JER\_DataVsMC} \\
    ~                            & \texttt{JET\_JER\_EffectiveNP\_[1-6]} \\
    ~                            & \texttt{JET\_JER\_EffectiveNP\_7restTerm} \\
    ~                            & \texttt{JET\_Pileup\_OffsetMu} \\
    ~                            & \texttt{JET\_Pileup\_OffsetNPV} \\
    ~                            & \texttt{JET\_Pileup\_PtTerm} \\
    ~                            & \texttt{JET\_Pileup\_RhoTopology} \\
    ~                            & \texttt{JET\_PunchThrough\_MC16} \\
    ~                            & \texttt{JET\_SingleParticle\_HighPt} \\
    \midrule
    \multicolumn{2}{c}{\textbf{Other}} \\
    \midrule
    \texttt{HOEW\_QCD\_syst}    & ~ \\
    \texttt{HOEW\_syst}         & ~ \\
    \texttt{HOQCD\_scale\_syst} & ~ \\
    \texttt{PRW\_DATASF}        & ~ \\
    \bottomrule
  \end{tabular}
  \end{spacing}
  \label{tab:np_list}
\end{table}
\fi


\section{UTxO}
\label{sec:utxo}

\subsection{UTxO Transitions}
\label{sec:utxo-trans}

We have added the following helper functions, which are used in defining the
UTxO transition system, see Figure~\ref{fig:functions:insouts}. These include:

\begin{itemize}
  \item the function $\fun{getOut}$ builds a UTxO-type output out of a
  transaction output
  \item the function $\fun{outs}$ builds the MC UTxO entries from the outputs
  of a transaction
\end{itemize}

\begin{figure}[htb]
  \begin{align*}
    & \fun{getOut} \in \TxOut \to \UTxOOut \\
    & \text{tx outputs transformed to UTxO outputs} \\
    & \fun{getOut} ~{txout}~= (\fun{getAddr}~\var{txout}, \fun{getValue}~\var{txout})
    \nextdef
    & \fun{outs} \in \TxBody \to \UTxO \\
    & \text{tx outputs as UTxO} \\
    & \fun{outs} ~\var{txb} =
        \left\{
          (\fun{txid} ~ \var{txb}, \var{ix}) \mapsto \fun{getOut}~\var{txout} ~
          \middle|~
          \var{ix} \mapsto \var{txout} \in \txouts{txb}
        \right\} \\
  \end{align*}
  \caption{Functions on Tx Inputs and Outputs}
  \label{fig:functions:insouts}
\end{figure}

\textbf{Value Operations and Partial Order.}
Some of the UTxO update and precondition functions now operate on the $\Value$
type instead of $\Coin$ (sometimes on a combination of $\Value$ and $\Coin$).
To make this precise, we must define basic operations on $\Value$, which
include, most notably, addition and $\leq$ comparison.

The type $\Value$ has a partial order defined on it in (see~\cite{plutus_eutxo}).
The idea of this partial order, as well as operations like addition and subtraction
of terms of the $\Value$ type, is that a term $v \in \Value$ can be treated
as a total map that maps to the trivial element $\epsilon \in \Token \to \Quantity$
almost everywhere except for a several currency IDs that appear in $\dom~v$.

This way, when adding two terms of type value, $\{ cid1 \mapsto tkns1\}$ and
$\{ cid2 \mapsto tkns2\}$, the result is
\[ \{ cid1 \mapsto (tkns1 + \epsilon), cid2 \mapsto (\epsilon + tkns2)\} \]

which simplifies to

\[ \{ cid1 \mapsto tkns1, cid2 \mapsto tkns2\} \]

This definition of addition is also defined in Section~\ref{sec:notation-shelley}.
Similarly, if we compare these two tokens, we compare them as follows
(element-wise, with $\epsilon$ as the value associated to any currency ID
not present in on of the values),

\[ (\{ cid1 \mapsto tkns1\}~\leq~\{ cid2 \mapsto tkns2\}) \Leftrightarrow \\
   (tkns1 \leq \epsilon~\wedge~ \epsilon \leq tkns2) \]

\textbf{UTxO Helper Functions.}

Figure~\ref{fig:functions:utxo} defines additional calculations needed for the
UTxO transition system with MC:

\begin{itemize}

  \item $\fun{getCoin}$ adds up all the Ada in a given output and returns it as a
  $\Coin$ value

  \item $\fun{utxoAda}$ returns the set of all the outputs in a UTxO with only Ada
  tokens (the other tokens are ignored). This is used in the stake distribution
  calculation at the epoch boundary

  \item
    The $\fun{ubalance}$ function calculates the (aggregated by currency ID and
    Token) sum total of all the value in a given UTxO.

  \item The $\fun{consumed}$ calculation is still the sum of the reward address
   value consumed, the values of the UTxO entries consumed,
   and the value consumed from the deposit pot due
   to the transaction collecting deposit refunds. There is an additional
   summand in this calculation, the value forged by a transaction.
   This calculation now returns a $\Value$.

  \item The $\fun{produced}$ calculation sums up the same things
  as the corresponding $\fun{produced}$ calculation in Shelley.
  This calculation also returns a $\Value$.
\end{itemize}

\textbf{Produced and Consumed Calculations and Preservation of Value.}
Note that
the $\fun{consumed}$ and $\fun{produced}$ calculations both produce a $\Value$.
The reason for this is that the outputs of a transaction, as well as UTxO outputs,
are of the $\Value$ type. The administrative amounts (of the $\Coin$ type)
are converted into MC values for these summations.

While the preservation of value is a single
equality, it is really a comparison of token quantities aggregated by
$\Token$ and by $\CurrencyID$. In particular, ensuring that the produced
amount equals the consumed amount also implies that the total quantity of
Ada tokens is preserved.

\textbf{Forging and the Preservation of Value.}
What does it mean to preserve the value of non-Ada tokens, since they
are put in and taken out of circulation by the users themselves?
This is expressed by including the $\fun{forge}$ value of the transaction
in the preservation of value equation.

The \textit{produced} side of the equation adds up, among other things, the
values in the
outputs that will be added to the ledger UTxO by the transaction. These outputs are
where the
forged value is "put into of circulation", i.e. how it ends up in the UTxO.
Suppose a transaction $tx$ contains a single output $(a, cid \mapsto tkns)$. Suppose
also that it does not
have any inputs spending any UTxO outputs with currency ID $cid$.

A valid transaction $tx$ satisfies the preservation of value
condition by adding the value $cid \mapsto tkns$ to the \textit{consumed} side as well.
To do this, the $tx$ declares that it is forging the tokens $cid \mapsto tkns$
via the $\fun{forge}$ field, i.e. $tx$ must have

\[cid \mapsto tkns\in\fun{forge}~tx\]

The forge field value is then added to the consumed side. This approach
to balancing the POV equation extends
to cases where the transaction might also be consuming some existing $cid$ tokens,
or taking the out of circulation with negative quantities in the forge field.

The forge field value represents the change in total existing tokens of each given currency
as a result of processing the transaction. It is always added to the
\textit{consumed} side of the POV equation because of this side, the signs of the
quantities in the forge field match the signs of the change. That is,
when tokens are added into the UTxO, their quantities are positive, and when they are
taken out of circulation via the forge field, the signs are negative.

Note also that the UTXO rule only checks that the transaction is forging the
amount it has declared using the forge field (and that no Ada is forged).
The forging scripts themselves are not evaluated in this transition rule.
That step is part of witnessing, i.e. the UTXOW rule, see below.

\begin{figure}[htb]
  \emph{Helper Functions}
  \begin{align*}
    & \fun{getCoin} \in \UTxOOut \to \Coin \\
    & \fun{getCoin}~{\var{out}} ~=~\sum_{\mathsf{adaID} \mapsto tkns \in \fun{getValue}~out}
       (\sum_{q \in \range~{tkns}} \fun{co}~q) \\
    & \text{sum total of amount of Ada in an output}
    \nextdef
    & \fun{utxoAda} \in \UTxO \to \powerset{(\Addr \times \Coin)} \\
    & \fun{utxoAda}~{\var{utxo}} ~=~\{~(\fun{getAddr}~\var{out},~\fun{getCoin}~{out})
    ~\vert~ \var{out} \in \range~\var{utxo} ~\} \\
    & \text{returns the outputs in the UTxO with only the Ada coins} \\
    \nextdef
    & \fun{ubalance} \in \UTxO \to \Value \\
    & \fun{ubalance} ~ utxo = \sum_{\wcard\mapsto\var{u}\in~\var{utxo}}
    \fun{getValue}~\var{u} \\
    & \text{UTxO balance} \\
  \end{align*}
  %
  \emph{Produced and Consumed Calculations}
  \begin{align*}
    & \fun{consumed} \in \PParams \to \UTxO \to \StakeCreds \to \Wdrl \to \TxBody \to \Value \\
    & \consumed{pp}{utxo}{stkCreds}{rewards}~{txb} = \\
    & ~~\ubalance{(\txins{txb} \restrictdom \var{utxo})} + \\
    &~~  \fun{coinToValue}(\fun{wbalance}~(\fun{txwdrls}~{txb})~\\
        &~~+~ \keyRefunds{pp}{stkCreds}{txb}) +
        ~\fun{forge}~\var{txb} \\
    & \text{value consumed} \\
    \nextdef
    & \fun{produced} \to \PParams \to \StakePools \to \TxBody \to \Value \\
    & \fun{produced}~\var{pp}~\var{stpools}~\var{txb} = \\
    &~~\ubalance{(\fun{outs}~{txb})}  + \fun{coinToValue}(\txfee{txb} \\
    &~~+ \deposits{pp}{stpools}~{(\txcerts{txb})})\\
    & \text{value produced} \\
  \end{align*}
  \caption{UTxO Calculations}
  \label{fig:functions:utxo}
\end{figure}

\clearpage

\textbf{The UTXO Transition Rule.}
In Figure \ref{fig:rules:utxo-shelley}, we give the UTXO transition rule,
updated for MC support. There are the following changes to the preconditions
of this rule as compared to the original Shelley UTXO rule:

\begin{itemize}
  \item The transaction is not forging any Ada

  \item All outputs of the transaction contain only non-negative quantities
  (this is the $\Value$-type version to the corresponding rule about non-negative
  $\Coin$ amounts in the Shelley ledger rules)

  \item In the preservation of value calculation (which looks the same as in
  Shelly), the value in the $\fun{forge}$ field is taken into account
\end{itemize}

Note that updating the $\UTxO$ with the inputs and the outputs of the transaction
looks the same as in the Shelley rule, however, there is a type-level difference.
Recall that the outputs of a transaction contain a $\Value$ term, rather than
$\Coin$. Moreover, the $\fun{outs}$ map converts $\TxOut$ terms into $\UTxOOut$.

\begin{figure}[htb]
  \begin{equation}\label{eq:utxo-inductive-shelley}
    \inference[UTxO-inductive]
    { \var{txb}\leteq\txbody{tx}
      & \txttl txb \geq \var{slot}
      \\ \txins{txb} \neq \emptyset
      & \minfee{pp}{tx} \leq \txfee{txb}
      & \txins{txb} \subseteq \dom \var{utxo}
      \\
      \consumed{pp}{utxo}{stkCreds}{rewards}~{txb} = \produced{pp}{stpools}~{txb}
      \\
      ~
      \\
      {
        \begin{array}{r}
          \var{slot} \\
          \var{pp} \\
          \var{genDelegs} \\
        \end{array}
      }
      \vdash \var{ups} \trans{\hyperref[fig:rules:update]{up}}{\fun{txup}~\var{tx}} \var{ups'}
      \\
      ~
      \\
      \mathsf{adaID}~\notin \dom~{\fun{forge}~tx} \\
      \forall txout \in \txouts{txb}, ~ \fun{getValue}~txout  ~\geq ~ \epsilon \\~
      \\
      \fun{txsize}~{tx}\leq\fun{maxTxSize}~\var{pp}
      \\
      ~
      \\
      \var{refunded} \leteq \keyRefunds{pp}{stkCreds}~{txb}
      \\
      \var{decayed} \leteq \decayedTx{pp}{stkCreds}~{txb}
      \\
      \var{depositChange} \leteq
        \fun{totalDeposits}~{pp}{stpools}{(\txcerts{txb})} - (\var{refunded} + \var{decayed})
    }
    {
      \begin{array}{r}
        \var{slot}\\
        \var{pp}\\
        \var{stkCreds}\\
        \var{stpools}\\
        \var{genDelegs}\\
      \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{ups}\\
      \end{array}
      \right)
      \trans{utxo}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{(\txins{txb} \subtractdom \var{utxo}) \cup \fun{outs}{txb}}  \\
        \varUpdate{\var{deposits} + \var{depositChange}} \\
        \varUpdate{\var{fees} + \txfee{txb} + \var{decayed}} \\
        \varUpdate{ups'}\\
      \end{array}
      \right)
    }
  \end{equation}
  \caption{UTxO inference rules}
  \label{fig:rules:utxo-shelley}
\end{figure}

\clearpage

\textbf{Witnessing.}

We have changed the definition of the function
$\fun{scriptsNeeded}$, see Figure~\ref{fig:functions-witnesses}. There is
now an additional category of scripts that are needed for transaction validation,
the forging scripts.

Note that there are no restrictions on the use of forging scripts. Their hashes may
be used as credentials in UTxO entries, certificates, and withdrawals.
Non-MPS type scripts can also be used for forging, e.g. MSig scripts.

Note also that UTxO entries containing MC tokens, just like Shelley UTxO entries,
can be locked by a script. This script will add an additional set of
restrictions to the use of MC tokens (additional to the forging script
requirements, but enforced at spending time). This output-locking script can itself
also be a forging script.

\begin{figure}[htb]
  \begin{align*}
    & \hspace{-1cm}\fun{scriptsNeeded} \in \UTxO \to \Tx \to
      \powerset{\ScriptHash}
    & \text{required script hashes} \\
    &  \hspace{-1cm}\fun{scriptsNeeded}~\var{utxo}~\var{tx} = \\
    & ~~\{ \fun{validatorHash}~a \mid i \mapsto (a, \wcard) \in \var{utxo},\\
    & ~~~~~i\in\fun{txinsScript}~{(\fun{txins~\var{txb}})}~{utxo}\} \\
    \cup & ~~\{ \fun{stakeCred_{r}}~\var{a} \mid a \in \dom (\AddrRWDScr
           \restrictdom \fun{txwdrls}~\var{txb}) \} \\
      \cup & ~~(\AddrScr \cap \fun{certWitsNeeded}~{txb}) \\
      \cup & ~~\dom~(\fun{forge}~{txb}) \\
      & \where \\
      & ~~~~~~~ \var{txb}~=~\txbody{tx} \\
  \end{align*}
  \caption{Scripts Needed}
  \label{fig:functions-witnesses}
\end{figure}

\clearpage


\vssub
\subsection{~Source terms}
\vsssub
\subsubsection{~General concepts}
\vsssub

In deep water, the net source term $S$ is generally considered to consist of
three parts, an atmosphere-wave interaction term $S_{\mathrm{in}}$, which
is usually a positive energy input but can also be negative in the case of swell, a nonlinear wave-wave
interactions term $S_{\mathrm{nl}}$ and a wave-ocean interaction term that is generally dominated by wave breaking
$S_{\mathrm{ds}}$. The input term $S_{\mathrm{in}}$ is dominated by the
exponential wind-wave growth term, and this source term generally describes this
dominant process only. For model initialization, and to provide more realistic
initial wave growth, a linear input term $S_{\mathrm{ln}}$ can also be added in
\ws.

In shallow water additional processes have to be considered, most notably
wave-bottom interactions $S_{\mathrm{bot}}$ \cite[e.g.,][]{pro:Sea78}. In extremely
shallow water, an additional  breaking term ($S_{\mathrm{db}}$) should be considered,
if not well represented in  $S_{\mathrm{ds}}$ \citep[see][]{Filipot&Ardhuin2012}.
Triad wave-wave
interactions ($S_{\mathrm{tr}}$) may also be considered, but present parameterizations have limited accuracy.
Also available in \ws\ are source
terms for scattering of waves by bottom features ($S_{\mathrm{sc}}$), wave-ice
interactions ($S_{\mathrm{ice}}$), reflection off shorelines or floating objects such
as icebergs which can include sources of infragravity wave energy ($S_{\mathrm{ref}}$),  and a general purpose slot for additional, user
defined source terms ($S_{\mathrm{user}}$).

This defines the general source terms used in \ws\ as

%---------------------------------%
% General source term composition %
%---------------------------------%
% eq:general_st

\begin{equation}
S = S_{\mathrm{ln}} + S_{\mathrm{in}} + S_{\mathrm{nl}} + S_{\mathrm{ds}} + S_{\mathrm{bot}} + S_{\mathrm{db}}
    + S_{\mathrm{tr}} +
    S_{\mathrm{sc}} + S_{\mathrm{ice}} + S_{\mathrm{ref}} + S_{\mathrm{user}}\: .
\label{eq:general_st}
\end{equation}

\noindent
Other source terms could be easily added. Those source terms are defined for the
{\em energy} spectra. In the model, however, most source terms are directly
calculated for the action spectrum. The latter source terms are denoted as
$\cS \equiv S/\sigma$.

The explicit treatment of the nonlinear interactions defines third-generation wave
models. Therefore, the options for the calculation of $S_{\mathrm  nl}$ will be
discussed first, starting in section \ref{sec:NL1}. $S_{\mathrm  in}$ and $S_{\mathrm ds}$
represent separate processes, but are often interrelated,
because the balance of these two source terms governs the integral growth
characteristics of the wave energy. Several combinations of these basic source
terms are available, and are described in section~\ref{sec:ST1} and following.
The description of linear input starts in section~\ref{sec:LN1}, and
section~\ref{sec:BT1} and following describe available additional processes, mostly
related to shallow water and sea ice.

%\vspace{\baselineskip} \noindent

A third-generation wave model effectively integrates the spectrum only up to a
cut-off frequency $f_{hf}$ (or wavenumber $k_{hf}$), that is ideally equal to the
highest discretization frequency. In practice the source terms parameterization or the time step used may not allow a proper
balance to be obtained, and thus $f_{hf}$  may be taken within the model frequency range. Above the cut-off frequency a
parametric tail is applied \citep[e.g.,][]{art:WAM88}

%--------------------------------------%
% General tail parameterization E(f,t) %
%--------------------------------------%
% eq:tail_E_f

\begin{equation}
F(f_r,\theta) = F(f_{r,hf},\theta) \left ( \frac{f_r}{f_{r,hf}}
\right ) ^{-m} \label{eq:tail_E_f} ,
\end{equation}

\noindent
which is easily transformed to any other spectrum using the Jacobian
transformations as discussed above. For instance, for the present action
spectrum, the parametric tail can be expressed as (assuming deep water for the
wave components in the tail)

%--------------------------------------%
% General tail parameterization N(k,t) %
%--------------------------------------%
% eq:tail_N_k

\begin{equation}
N(k,\theta) = N(k_{hf},\theta) \left ( \frac{f_r}{f_{r,hf}}
\right ) ^{-m-2} \label{eq:tail_N_k} ,
\end{equation}

\noindent
the actual values of $m$ and the expressions for $f_{r,hf}$ depend on the
source term parameterization used, and will be given below.

%\vspace{\baselineskip} \noindent
Before actual source term parameterizations are described, the definition of
the wind requires some attention. In cases with currents, one can either
consider the wind to be defined in a fixed frame of reference, or in a frame
of reference moving with the current. Both definitions are available in \ws,
and can be selected during compilation. The output of the program, however,
will always be the wind speed which is not in any way corrected for the
current.

%\vspace{\baselineskip} \noindent
The treatment of partial ice coverage (ice concentration) in the source terms
follows the concept of a limited air-sea interface. This means that the momentum
transferred from the atmosphere to the waves is limited. Therefore, input and
dissipation terms are scaled by the fraction of ice concentration. The
nonlinear wave-wave interaction term can be used in areas of open water
and ice \citep{art:PL07}. The scaling is implemented so that it is independent
of the source term selected.


\section{Second-order correlation analysis}

In this section, we analyse the effectiveness of the implemented countermeasures against second-order side-channel analysis based on the linear correlation coefficient (CPA). For this study, we will target the Sbox output value and consider a Hamming weight ($HW$) univariate leakage model.

In the remainder of this section, we will use:
\begin{itemize}

\item the centered product combination function $\mathcal{C}(x,y) = (x-\bar{x})(y-\bar{y})$ to preprocess the traces, where $\bar{x}$ (resp. $\bar{y}$) stands for the mean value of $x$ (resp. $y$), computed on all traces in our campaign;

\item the corresponding function $f_{HW}(z) = \sum_m (HW(z \oplus m) - \overline{HW(z\oplus m)})\\(HW(m)-\overline{HW(m)})$ to compute the predictions, where $\overline{HW(m)}$ (resp $\overline{HW(z \oplus m)}$) stands for the mean value of $HW(m)$ (resp. $HW(z\oplus m)$) computed on all possible values of $m$\footnote{Note that all possible values for $m$ are in $[0,255]$.}.
\end{itemize}

As in our first-order correlation analysis, we will split this study in two parts. The first part will consider priviledged knowledge on the mask values. The second part will not take this knowledge into account.

\subsection{Priviledged knowledge}
We first study the setting where the attacker knows the random masks used to compute the permutation.
In order to characterize the effectiveness of a CPA against this implementation, we use the random masks to recompute the permutation $Sh(i)$ for each byte index $i$.

For each byte index $i$, we use the characterization phase to isolate a window $w_{z\oplus m}$ of $11$ points of interest corresponding to the manipulation of the Sbox output $\rmult \times S[P[Sh(i)\oplus K[Sh(i)]] \oplus \rout$, and a window $w_m$ of $11$ points of interest corresponding to the manipulation of the mask value $\rout$. For each couple $(i,j)$ of points in $w_{z\oplus m} \times w_m$, we apply the combination function $\mathcal{C}(i,j)$.

\noindent We then perform an attack targeting the value $Z_{\hat{k}}[i]=S[P[Sh(i)] \oplus K[Sh(i)] \oplus \hat{k}]$, where $\hat{k}$ is an hypothesis on a value of one byte.

\subsubsection{Multiplicatively masked Sbox output}
We suppose the knowledge of the multiplicative mask $\rmult$. This knowledge allows for the prediction of the value $\rmult \times Z_{\hat{k}}[i]$ for any hypothesis $\hat{k}$.
The attack succeeds with around $8.000$ traces to $20.000$ traces.
Figure~\ref{fig:CPA2O_trickedaZ1} illustrates the results using $20.000$ traces.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.35]{figures/CPA2O_trickedaZ1.png}
	\caption{Correlation coefficients obtained when targeting $\rmult \times S[P[i]\oplus \hat{k}] $, for every value of $\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}
	\label{fig:CPA2O_trickedaZ1}
\end{figure}

\subsubsection{Raw Sbox output}
We target the value $Z_{\hat{k}}[i]$ for any hypothesis $k$.
The attack does not succeed using the $100.000$ traces.
Figure~\ref{fig:CPA2O_trickedZ1} illustrates the results using $100.000$ traces.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.35]{figures/CPA2O_trickedZ1.png}
	\caption{Correlation coefficients obtained when targeting $S[P[i]\oplus \hat{k}] $, for every value of $\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}
	\label{fig:CPA2O_trickedZ1}
\end{figure}

\subsection{Unknown permutation, processed traces}
We now study the setting where the attacker does not know the random masks used to compute the permutation.
We preprocess the traces in order to average the leakage over the different byte indices manipulation:
\begin{itemize}
	\item for each index $i$ in $[0,15]$, we define a small window $w_i$ of $\ell$ points around the SNR peak corresponding to the manipulation of $\rmult \times S[P[Sh(i)] \oplus K[Sh(i)]]\oplus \rout$ in the characterization phase. In our experiments, the size of the window was arbitrarily fixed to $\ell=11$.
	\item for each trace in our acquisition campaign, we compute the average window $m$ such that for each time sample $j$, $m[j]=\frac{1}{16}\sum_{i=0}^{15} w_i[j]$. We then consider $m$ as our reduced averaged trace of size $\ell$.
	\item we concatenate to this trace a small window of $\ell$ points around the SNR peak corresponding to the manipulation of $\rout$.
\end{itemize}

\subsubsection{Multiplicatively masked Sbox output}
We suppose the knowledge of the multiplicative mask $\rmult$. This knowledge allows for the prediction of the value $\rmult \times Z_{\hat{k}}[i]$ for any hypothesis $\hat{k}$.
The attack is unsuccessful using $100.000$ traces.

Figure~\ref{fig:CPA2O_averagedaZ1} illustrates the results using $100.000$ traces.
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.35]{figures/CPA2O_averagedaZ1.png}
	\caption{Correlation coefficients obtained when targeting $\rmult \times S[P[i]\oplus \hat{k}] $, for every value of $\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}
	\label{fig:CPA2O_averagedaZ1}
\end{figure}

However, we observe that, for certain combinations of points (around abscissa 135), the correct hypothesis is indeed the most likely. Furthermore, the rank convergence of the key, plotted on Figure~\ref{fig:convergence}, might indicate that the attack could be successful when using more traces.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.35]{figures/convergence.png}
	\caption{Rank of the ten best-ranked keys, by steps of 10000 measurements, from $10.000$ to $100.000$. Correct key plotted in red.}
	\label{fig:convergence}
\end{figure}

\subsubsection{Raw Sbox output}
We target the value $Z_{\hat{k}}[i]$ for any hypothesis $\hat{k}$.
The attack does not succeed using the $100.000$ traces.
Figure~\ref{fig:CPA2O_averagedZ1} illustrates the results using $100.000$ traces.
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.35]{figures/CPA2O_averagedZ1.png}
	\caption{Correlation coefficients obtained when targeting $S[P[i]\oplus \hat{k}] $, for every value of $\hat{k}$. Correct hypothesis plotted in red. X-axis represents all 121 points combinations.}
	\label{fig:CPA2O_averagedZ1}
\end{figure}

\subsection{Unknown permutation, non-processed traces}
For the sake of completeness, we also perform these experiments on raw unprocessed traces. No success is obtained when targeting $Z_{\hat{k}}[i]$ or $\rmult \times Z_{\hat{k}}[i]$.

No attack is successful using $100.000$ traces.

\subsection{Summary}
This section evidences the effectiveness of the implemented countermeasures.
The shuffling countermeasures increases the number of needed measurements by a factor of at least $\frac{100.000}{8.000} = 12,5$. It is however likely that this countermeasure does not suffice when increasing slightly the number of measurements.
The effectiveness of the affine countermeasure is evidenced by the fact that a 2OCPA is achievable targeting the value $\rmult \times S[P[i] \oplus \hat{k}]$
but no attack is found targeting the value $S[P[i] \oplus \hat{k}]$ using $100.000$ traces.

\begin{figure}[h!]
\centering
\begin{tabular}{|c|c|c|c|c|}
  \hline
   & \multicolumn{2}{c|}{Known permutation}&\multicolumn{2}{c|}{Unknown permutation}\\
  \hline
  Known & $\rmult $ &  None  & $\rmult $  &  None \\
  \hline
  \# Traces& $\approx 8.000$ & $ > 100.000$ & $ > 100.000$ & $> 100.000$\\
  \hline
\end{tabular}
\caption{Number of traces needed for a successful second-order attack, in the different settings.}
\end{figure}