\documentclass[twocolumn]{article}

\usepackage{fullpage}
\usepackage{nopageno}
\usepackage{hyperref}
\usepackage{agda}
\setlength{\mathindent}{5pt}

\usepackage{todonotes}

\usepackage[T1]{fontenc}
\input{unicode}
\input{commands}

\bibliographystyle{abbrvnat}

\title{Dependent Stringly-Typed Programming}
\author{gallais}

\begin{document}
\maketitle

\section{Introduction}

Static type systems started as a lightweight compile time check enforcing
basic hygiene by preventing users from e.g. adding an integer to a boolean.
Seduced by the promise of ever more guarantees computer scientists have
invented ever more powerful type systems to the point where they could
formalise all of mathematics as types and programs.

In this paper we reclaim this power to the advantage of the honest working
programmer by demonstrating how one can use the ivory tower concepts to
revitalise the age old practice of stringly typed programming. We will use
Agda~\cite{norell2009dependently} as our language of choice
because it provides us with powerful enough
``unsafe'' primitives to conduct our experiment.

This paper is a self-contained literate Agda file so the interested reader
should be able to independently reproduce our results.
You can also find the content on github at
\url{https://github.com/gallais/STRINaGda}.

\section{What even is a type?}

% https://medium.com/@samth/on-typed-untyped-and-uni-typed-languages-8a3b4bedf68c
% https://semantic-domain.blogspot.com/2019/08/on-relationship-between-static-analysis.html
% https://hal.inria.fr/hal-01399694

For our purposes, we will simply say that a type is a function that, given a
linked list of characters, tells us whether we should accept it or not as a
value of that type.
%
Luckily Agda provides us with builtin notions of \AD{List}, \AD{Char},
and \AD{Bool} so this is easily defined.

\begin{code}
open import Agda.Builtin.List  using (List)
open import Agda.Builtin.Char  using (Char)
open import Agda.Builtin.Bool  using (Bool)

Type = List Char → Bool
\end{code}

Next we can define what it means to belong to a type. By definition, a
list of characters belongs to a type if the function returns the boolean
true when run on that list. To make this formal we need to define an Agda
function internalising the predicate ``this boolean is true''.

Agda ships with a notion of trivial truthfulness (the unit type) but
unfortunately it does not provide us with a notion of trivial falsity.
So we have to define the empty type ourselves as a sum type with zero
constructor.

\begin{code}
open import Agda.Builtin.Unit using (⊤)

data ⊥ : Set where
\end{code}

Equipped with trivial truthfulness and trivial falsity, we can internalise
what it means for a boolean to be true by pattern matching on it and
returning the unit type if it is \AIC{true}, or the empty one if it is
\AIC{false}.

\begin{code}
open Agda.Builtin.Bool using (true; false)

IsTrue : Bool → Set
IsTrue true   = ⊤
IsTrue false  = ⊥
\end{code}

This is precisely what we need to express what it means for a list of
characters to belong to a given type: run the type on the
list of characters and check it returned \AIC{true}.

\begin{code}
_∈_ : List Char → Type → Set
cs ∈ A = IsTrue (A cs)
\end{code}

We can define a convenient wrapper for elements of a given type by packing
a list of characters together with the proof that it is accepted at that
type. We use a dependent \AK{record} and
%
make the \ARF{check} field an erased instance argument, that is to say
that we never want to have to write these proofs explicitly, expect
Agda to just automatically pass them around without needing our help,
and to forget about them when compiling the code.

\begin{code}
record Elt (A : Type) : Set where
  constructor [_]
  field     value     : List Char
  field @0  {{check}} : value ∈ A
open Elt
\end{code}

Agda's string literals are tied to its builtin notion of \AF{String} which
is distinct from \AF{List Char}. We can luckily convert from one to the
other by unpacking the string. We define a convenient helper function to,
given a string and a type, return an element of that type by checking that
the unpacked string is accepted at that type. This will help us write
concrete examples and unit tests.

\begin{code}
open import Agda.Builtin.String using (String)
  renaming (primStringToList to unpack)

infix 100 _∋_
_∋_ : (A : Type) (str : String) →
      {{unpack str ∈ A}} → Elt A
A ∋ str = record { value = unpack str }
\end{code}

We now have a formal definition of what a type is, what it means for a string
to be accepted at a given type and what an element of a type looks like.
Let us look at a concrete example of a type.

\section{Our First Type: ℕ}

As is customary in any document talking about dependent types, we will start
by defining the natural numbers. The customary presentation is that a natural
number is either zero or the successor of a natural natural number. In terms
of strings, we will characterise this as being either the ``Z'' string or a
string starting with `S' and whose tail is itself a natural number.

Agda, being a very inpractical programming language, does not ship with
\AF{\_\&\&\_} and \AF{\_||\_} defined on booleans.
The standard library does provide these definitions but has to be installed
separately and we want this document to be self-contained so we will have
to start by defining them ourselves.

\begin{code}
infixr 3 _&&_
_&&_ : Bool → Bool → Bool
true   && b = b
false  && b = false

infixr 2 _||_
_||_ : Bool → Bool → Bool
true   || b = true
false  || b = b
\end{code}

Next we need a way to test that a list of characters is empty.
The builtin type \AD{List} has two constructors: \AIC{[]} for the
empty list, and \AIC{\_∷\_} for putting together a character as the
head of the linked list and a tail of additional characters. A list is
empty precisely when it is \AIC{[]}.

\begin{code}
open Agda.Builtin.List using ([]; _∷_)

isNil : List Char → Bool
isNil []       = true
isNil (_ ∷ _)  = false
\end{code}

The last piece of the puzzle is the ability to test two characters
for equality. This is once again provided as a primitive by Agda and
we import it and simply rename it to make the code more readable.

\begin{code}
open Agda.Builtin.Char
  renaming (primCharEquality to _==_)
\end{code}

We are now ready to define the type of natural numbers. A beautiful
thing about stringly typed programming is that we can assign a very
precise type to each constructor of a datatype. So we not only define
the type \AF{ℕ} but also mutually introduce the types \AF{isZ} and
\AF{isS} of the zero and successor constructors respectively.

\begin{code}
ℕ    : Type
isZ  : Type
isS  : Type
\end{code}

The type of natural numbers is exactly the union of the type of zero
and successors.

\begin{code}
ℕ cs = isZ cs || isS cs
\end{code}

The types of zero and successor are defined by case analysis on the
input list of characters. If the list is empty then it does not belong
to any of these types. If it is non-empty then we check that it is
either `Z'-headed and with an empty tail for the zero type,
or `S'-headed and with a tail that is itself a natural number in the
successor case.

\begin{code}
isZ [] = false
isZ (c ∷ cs) = c == 'Z' && isNil cs

isS [] = false
isS (c ∷ cs) = c == 'S' && ℕ cs
\end{code}

Unsurprisingly we can define the \AF{zero} and \AF{suc} constructors
for \AD{ℕ}. Note that we do not need to write any proofs that the
strings are valid: Agda takes care of the proofs for us by a mix of
computation and implicit proof construction.

\begin{code}
zero : Elt ℕ
zero = ℕ ∋ "Z"

suc : Elt ℕ → Elt ℕ
suc [ n ] = [ 'S' ∷ n ]
\end{code}

We can define constant numbers either by using our \AF{\_∋\_} gadget or by
using \AF{suc} and \AF{zero}, whatever feels most convenient.

\label{sec:natconstant}
\begin{code}
one    = ℕ ∋ "SZ"
two    = suc (suc zero)
three  = ℕ ∋ "SSSZ"
four   = suc three
\end{code}

We will use these constants again when writing unit tests for the programs
over natural numbers we are now going to develop.

Now that we have our notion of types, a working example and even some
inhabitants, it would be nice to be able to do something with them.

\section{Stringly Typed Programming}

Being able to construct values of a given type is all well and good but
we, as programmers, want to be able to take them apart too.

Induction is the dependently typed generalisation of primitive recursion:
for a predicate \AB{P} on values of type \AF{ℕ},
if we can prove that {\AB{P} \AF{zero}} holds
and that for any natural number \AB{n}, if {\AB{P} \AB{n}} holds
then so does {\AB{P} (\AF{suc} \AB{n})}
then we ought to be able to have a function computing from a natural
number \AB{n} a proof of type {\AB{P} \AB{n}}.

\subsection{Small Scale Reflection}

The tricky part in defining induction for the natural numbers is in
connecting the observations made by the builtin boolean-valued equality
test on characters \AF{\_==\_} with propositional equality.

We introduce a \AD{Reflects} inductive family~\cite{dybjer1994inductive}
indexed by two \AD{Char}s and a \AD{Bool}. Inspired by the architecture of
Coq's small scale reflection library~\cite{assia_mahboubi_2021_4457887},
it formalises the fact that whenever the boolean is \AIC{true} then the two
characters are equal.

We name the \AD{Reflects} constructors the same as the boolean constructor
they are respectively indexed by. This means that matching on such a proof
looks like matching on the original boolean.

\begin{code}
data Reflects (c : Char) : Char → Bool → Set where
  true  : Reflects c c true
  false : ∀ {d} → Reflects c d false
\end{code}

We can readily prove that if \AB{a} and \AB{b} are known to be the same
according to Agda's builtin notion of propositional equality then we have
that {\AD{Reflects} \AB{a} \AB{b} \AIC{true}}.

\begin{code}
open import Agda.Builtin.Equality using (_≡_; refl)

mkTrue : ∀ {a b} → a ≡ b → Reflects a b true
mkTrue refl = true
\end{code}

The only thing missing for us is a proof that whenever the boolean test
{\AB{a} \AF{==} \AB{b}} returns \AIC{true} then the values are indeed
propositionally equal i.e. {\AB{a} \AD{≡} \AB{b}}.
Unfortunately Agda does not provide a primitive proof of this fact.
We will have to use an unsafe primitive called \AF{trustMe} to build
such a proof.

\begin{code}
open import Agda.Builtin.TrustMe
  renaming (primTrustMe to trustMe)
\end{code}

By combining \AF{mkTrue} and \AF{trustMe} we can write a function demonstrating
that the {(\AB{a} \AF{==} \AB{b})} test produces a boolean that reflects a test
on propositional equality.

\begin{code}
_≟_ : (a b : Char) → Reflects a b (a == b)
a ≟ b with a == b
... | false = false
... | true = mkTrue trustMe
\end{code}

\subsection{Induction principle for ℕ}

And with that in our backpocket we are well equipped to prove induction.
First we use an anonymous module to parametrise all of the following definitions
over the same predicate \AB{P}, proof of the base case \AB{P0} and proof of the
step case \AB{PS}.

\begin{code}
module _ (P : Elt ℕ → Set)
         (P0 : P zero)
         (PS : ∀ n → P n → P (suc n))
         where
\end{code}

And we then prove the \AF{induction} principle stating that \AB{P} holds for
all of the natural numbers.

\begin{code}
  induction : ∀ n → P n
\end{code}

The details of the proof are not very illuminating but we include them for
completeness' sake. We start by checking
whether the natural number is zero, in which case we can use the base case,
or whether it is a successor in which case we use the step case together
with a recursive call to \AF{induction}.

The stage has been set just right so that things compute where they should,
impossible branches are self-evidently impossible and therefore the proof
goes through. The thing to notice if we want to understand the proof is that
the expression in the \AF{IsTrue} instance argument gets smaller as we make
more and more observations that constrain what the input natural number may
be like.

\begin{code}
  induction [ ccs@(c ∷ cs) ] = checkZ (c ≟ 'Z') cs refl

    where

    checkS : ∀ {b} → Reflects c 'S' b → ∀ cs →
      {{@0 _ : IsTrue (b && ℕ cs)}} →
      ∀ {ccs} → c ∷ cs ≡ ccs .value → P ccs
    checkS true cs refl = PS [ cs ] (induction [ cs ])

    checkZ : ∀ {b} → Reflects c 'Z' b → ∀ cs →
      {{@0 _ : IsTrue (b && isNil cs || isS (c ∷ cs))}} →
      ∀ {ccs} → c ∷ cs ≡ ccs .value → P ccs
    checkZ true  [] refl = P0
    checkZ false cs eq   = checkS (c ≟ 'S') cs eq
\end{code}

An induction operator is of course not just one that has
the right type but one that has the right computational behaviour too.
We can readily check that our \AF{induction} function behaves exactly
like the primitive recursor on natural numbers ought to by writing two
unit tests.

First, when applied to \AF{zero}, the recursor immediately returns
its base case.

\begin{code}
_ : ∀ {P P0 PS} → induction P P0 PS zero ≡ P0
_ = refl
\end{code}

Second, when applied to the successor of a natural number \AB{n}, the
recursor returns its step case applied to \AB{n} and the result of the
recursive call.

\begin{code}
_ : ∀ {P P0 PS n} →
    induction P P0 PS (suc n)
    ≡ PS n (induction P P0 PS n)
_ = refl
\end{code}

The fact that both of these unit tests are provable by \AIC{refl} means
that Agda can tell by computation alone that the expressions are equal.

\subsection{Example: Addition, Multiplication}

As is well known, primitive recursion is enough to implement addition and
multiplication on the natural numbers. So induction will be plenty enough
power for us.

Addition of \AB{m} to \AB{n} can be implemented by induction on \AB{m}.
The base case, corresponding to \AF{zero} \AF{+} \AB{n}, amounts to returning
\AB{n}. The step case amounts to taking the successor of the inductive
hypothesis. This gives us the following definition:

\begin{code}
_+_ : Elt ℕ → Elt ℕ → Elt ℕ
m + n = induction (λ _ → Elt ℕ) n (λ _ → suc) m
\end{code}

We can test the function thus implemented by writing a unit test reusing
the constants defined in Section~\ref{sec:natconstant}, checking for instance
that $3+1$ evaluates to $4$.

\begin{code}
_ : three + one ≡ four
_ = refl
\end{code}

Multiplication is defined in the same way: \AF{zero} \AF{*} \AB{n}
is equal to \AF{zero} and the step case amounts to stating that
(\AF{suc} \AB{m}) \AF{*} \AB{n} should evaluate to
\AB{n} \AF{+} \AB{m} \AF{*} \AB{n}.

\begin{code}
_*_ : Elt ℕ → Elt ℕ → Elt ℕ
m * n = induction (λ _ → Elt ℕ) zero (λ _ → n +_) m
\end{code}

We can check with a unit test that our implementation verifies that
$2*3$ equals $4+2$.

\begin{code}
_ : two * three ≡ four + two
_ = refl
\end{code}

Because our \AF{induction} function has the right computational
behaviour, the definitions we just introduced should be well
behaved too.
They did pass a couple of unit tests but given that we are using a
dependently typed host language we ought to do better than that.

\section{Stringly Typed Proving}

This section is dedicated to proving some of the properties of the
functions we have defined. We hope to convince the reader that they
could pick up any proof from the standard library's
\texttt{Data.Nat.Properties} module and reproduce it on our stringly
typed natural numbers.

\subsection{Equality combinators}

Now that we are entering serious proof territory,
we will need to introduce some basic combinators witnessing the
fundamental properties of propositional equality.

We use a block of variables Agda is authorised to implicitly quantify over
to avoid repeating ourselves in this section.

\begin{code}
variable
  A B : Set
  x y z : A
\end{code}

Propositional equality is a congruence. That is to say that if two values
are equal, applying the same function to both will yield equal results.

\begin{code}
cong : (f : A → B) → x ≡ y → f x ≡ f y
cong f refl = refl
\end{code}

We already know that propositional equality is a reflexive relation as
witnessed by its constructor \AIC{refl} and we can additionally prove that
is is a symmetric and transitive one.

\begin{code}
sym : x ≡ y → y ≡ x
sym refl = refl

trans : x ≡ y → y ≡ z → x ≡ z
trans refl eq = eq
\end{code}

We now have the basic building blocks needed to build equality proofs.

\subsection{Properties of Addition}

Given our earlier observation that \AF{induction} immediately returns its
base case when applied to the natural number \AF{zero}, it should not be
any surprise that \AF{zero} is trivially a left neutral for
our definition of addition.

\begin{code}
zero-+ : ∀ m → zero + m ≡ m
zero-+ m = refl
\end{code}

The proof that it is also a right neutral for addition requires a bit more
work. We can use \AF{induction} itself to build such a proof. The base case
corresponding to {\AF{zero} \AF{+} \AF{zero} \AD{≡} \AF{zero}} is trivially
true. The step case is just a matter of using the induction hypothesis together
with the fact that equality is a congruence to add a \AF{suc} to both sides.

\begin{code}
+-zero : ∀ m → m + zero ≡ m
+-zero =
  induction
    (λ m → m + zero ≡ m)
    refl
    (λ n → cong suc)
\end{code}

Similarly, our previous unit test should lead us to anticipate that the
proof that the addition of \AF{suc} \AB{m} to \AB{n} is equal to the
successor of the addition of \AB{m} to \AB{n} is trival. This indeed holds
true by computation alone.

\begin{code}
suc-+ : ∀ m n → suc m + n ≡ suc (m + n)
suc-+ m n = refl
\end{code}

The statement stating that the addition of \AB{m} to \AF{suc} \AB{n} is
equal to the successor of the addition of \AB{m} to \AB{n} is however a bit
trickier to deal with. It can once again be proven by using induction on \AB{m}.

\begin{code}
+-suc : ∀ m n → m + suc n ≡ suc (m + n)
+-suc m n =
  induction
    (λ m → (m + suc n) ≡ suc (m + n))
    refl
    (λ n → cong suc)
    m
\end{code}

These auxiliary lemmas are the intermediate results we need to be able to
prove that addition is commutative. We, once again, proceed by induction
and this time make crucial use of the fact that equality is symmetric and
transitive.

\begin{code}
+-comm : ∀ m n → m + n ≡ n + m
+-comm m n =
  induction
    (λ m → m + n ≡ n + m)
    (sym (+-zero n))
    (λ m ih → trans (cong suc ih) (sym (+-suc n m)))
    m
\end{code}

Let us conclude with one last example of a property one can prove of addition
on stringly natural numbers: addition is associative.

\begin{code}
+-assoc : ∀ m n p → (m + n) + p ≡ m + (n + p)
+-assoc m n p =
  induction
    (λ m → ((m + n) + p) ≡ (m + (n + p)))
    refl
    (λ m → cong suc)
    m
\end{code}

We have seen how we can define a type together with its induction principle,
and how we can make use of this induction principle to program and prove our
programs' properties. The next step is to use \AF{induction} on a given type
to define new types.

\section{Our First Indexed Type: Fin}

Given that the only type we have defined thus far is \AF{ℕ}, we are going to
use as the index of our type family. The natural candidate is {\AF{Fin} \AB{n}},
the type of finite numbers strictly smaller than \AB{n}.

This definition proceeds by induction on the index and as such is
characterised by a base and a step case.

\begin{code}
Fin : Elt ℕ → Type
Fin = induction (λ _ → Type) base (λ _ → step)

  where
\end{code}

In the base case, corresponding to \AF{Fin} \AF{zero}, the boolean function is
constantly \AIC{false}. The type is empty as there are no finite numbers
strictly smaller than zero.

\begin{code}
  base : Type
  base _ = false
\end{code}

In the step case, corresponding to {\AF{Fin} (\AF{suc} \AB{n})}
we recognise a pattern similar to that used in the definition
of \AF{ℕ}: the string of interest is
either `Z'-headed with an empty tail
or `S'-headed with a tail of type \AF{Fin} \AB{n} (this type is
provided to us by the induction hypothesis called \AB{ih} here).

This time we do not bother introducing separate types for each of the
constructors but we could very well do so.

\begin{code}
  step : Type → Type
  step ih [] = false
  step ih (c ∷ cs) =  c == 'Z' && isNil cs
                  ||  c == 'S' && ih cs
\end{code}

We can once more define the basic constructors for this type. They
have slightly more complex types, statically enforcing that the return
index is \AF{suc}-headed. ``Z'' gives rise to \AF{fzero}.

\begin{code}
fzero : ∀ {n} → Elt (Fin (suc n))
fzero {n} = Fin (suc n) ∋ "Z"
\end{code}

And extending an existing list of characters with `S' is enough to
compute the successor of a \AF{Fin} \AB{n} element as witnessed by
\AF{fsuc}.

\begin{code}
fsuc : ∀ {n} → Elt (Fin n) → Elt (Fin (suc n))
fsuc [ k ] = [ 'S' ∷ k ]
\end{code}

The definition of the induction principle for \AF{Fin} is left as
an exercise to the reader. It is very similar to the definition of
\AF{induction} for \AF{ℕ}. We will focus instead on a more interesting
observation related to \AF{Fin}.

\subsection{Subtyping: Fin n <: ℕ}

The astute reader will have noticed that the definition of \AF{Fin}
is not only similar to that of \AF{ℕ}, it should be the case that
all of the values of type \AF{Fin} \AB{n} are also stringly natural
number.

This can actually be proven. It should be unsurprising by now that
our tool of choice in this endeavour will be the induction principle
for \AF{ℕ}.

The key ingredient is the step case stating that, provided that
we can already prove that elements of \AF{Fin} \AB{n} are elements
of \AF{ℕ} then we should be able to do the same for elements of
\AF{Fin} (\AF{suc} \AB{n}).

\begin{code}
step : ∀ n → (∀ str → str ∈ Fin n → str ∈ ℕ) →
             (∀ str → str ∈ Fin (suc n) → str ∈ ℕ)
step n ih (c ∷ cs) isFin =
  checkZ (c ≟ 'Z') cs {{isFin}} where
\end{code}

We include the proof for completness' sake even though it may not
be illuminating for the Agda novice. It proceeds by case analysis
on the input string, concluding immediately if it is ``Z'' and
utilising the induction hypothesis if it is `S'-headed instead.

\begin{code}
  checkS : ∀ {b} → Reflects c 'S' b → ∀ cs →
           {{IsTrue (b && Fin n cs)}} →
           (c ∷ cs) ∈ ℕ
  checkS true cs {{isFin}} = ih cs isFin

  checkZ : ∀ {b} → Reflects c 'Z' b → ∀ cs →
    {{IsTrue (b && isNil cs || c == 'S' && Fin n cs)}} →
    (c ∷ cs) ∈ ℕ
  checkZ true  [] = _
  checkZ false cs = checkS (c ≟ 'S') cs
\end{code}

This can be put together with a trivial base case (remember that
\AF{Fin} \AF{zero} is the empty type so it cannot have any element
in it) to obtain the proof \AF{sub}.

\begin{code}
sub : ∀ n str → str ∈ Fin n → str ∈ ℕ
sub = induction
        (λ n → ∀ str → str ∈ Fin n → str ∈ ℕ)
        (λ _ ())
        step
\end{code}

This result allows us to write a \AF{cast} function converting an
element of \AF{Fin} \AB{n} into a stringly natural number. Notice
that the \ARF{value} part is the identity. Given that the \ARF{check}
part of the record will be erased at compile time this means we have
defined a \emph{zero cost coercion} from \AF{Fin} \AB{n} to \AF{ℕ}
which is much better than most state of the art dependently typed
programming languages, save for
Cedille~\cite{DBLP:journals/corr/abs-1802-00787}.

\begin{code}
cast : ∀ {n} → Elt (Fin n) → Elt ℕ
cast {n} p .value = p .value
cast {n} p .check = sub n (p .value) (p .check)
\end{code}

\section{Conclusion \& Future Work}

We have seen that we can take advantage of a dependently typed
host language to seriously consider the prospect of safe and
proven correct stringly typed programming.

We were able to define a notion of type of natural numbers carving out a
subset of well structured strings. This type is closed under the usual
constructors for the natural numbers \AF{zero} and \AF{suc}.

We then proved an induction principle for those strings that represent
natural numbers. This empowered us to start programming over these stringly
typed natural numbers in a way that is guaranteed total.

We demonstrated that our induction principle is strong enough to
not only program on the stringly typed natural numbers but also to prove the
fundamental properties of these programs.

We finally showed how we can use induction to define new types,
and how we can take advantage of the fact we are doing dependent
stringly typed programming to obtain zero cost coercions.

The definition of parametrised types such as the type of linked lists
or binary trees with values stored at the leaves is left to future work.

\bibliography{main}

\end{document}


\documentclass[letterpaper]{article}

\usepackage{fullpage}
\usepackage{nopageno}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[utf8]{inputenc}
\allowdisplaybreaks

\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}

\begin{document}
\title{Notes}
\date{November 19, 2014}
\maketitle
\section*{6.1.4}
\section*{6.1.6 the chain rule}
assume that $f:[a,b]\to[c.d]$ is differentiable at $x_0\in[a,b]$ and $g:[c,d]\to\mathbb{R}$ is differentiable at the point $f(x_0)$, then $g\circ f:[a,b]\to \mathbb{R}$ is differentiable at $x_0$ and $(g\circ f)$

\subsubsection*{proof}
from 6.1.4(3) because $f$ is differentiable at $x_0$, we know the there exists a function $\varphi$ such that $\varphi$ is continuous at $x_0, \varphi'(x_0)=f'(x_0)$, and $f(x)=f(x_0)+\varphi(x)(x-x_0)$ similarly $g(y)=g(f(x_0)+\psi(y)(y-f(x_0))$ because $g$ is differentiable at $f(x_0)$ $\psi$ is continuous at $f(x_0)$ and $\psi(f(x_0)=g'(f(x_0)$

we want the same condition for $g\circ f$. $g\circ f(x)=g\circ f(x_0)+\eta  (x)(x-x_0)$ for some $\eta(x)$ continous at $x_0$ and $\eta(x_0)=(g\circ f)'(x_0)$. tat $y=f(x)$. $g(f(x))=g(f(x_0))+\psi(f(x))(f(x)-f(x_0))$ and $g(f(x))=g(f(x_0))+\psi(f(x))\varphi(x)(x-x_0)$

\section*{6.1.7}
\subsection*{example}
let $f(x)=\sin x$ and $f^{-1}(x)=\arcsin x$. on $[-\frac{\pi}{2},\frac{\pi}{2}]$ it is injective. on $[\frac{\pi}{2},\frac{3\pi}{2}]$ $f(x)$ is injective. the inverses are not the same functions. the derivitives though will have the same values.
\subsection*{proof}
by corollary 6.1.4 we know that $f(x)=f(x_0)+\varphi(x)(x-x_0)$ when $\varphi$ is continuous at $x_0$. we want to prove that $f^{-1}(y)=f^{-1}(f(x_0))+\psi(y)(y-f(x_0))$ with $\psi$ continuous at $f(x_0)$ an $\psi(f(x_0))=\frac{1}{f'(x_0)}$. since $f,f^{-1}$ are inverses if $y=f(x)$ then $x=f^{-1}(y)$ and let $y_0=f(x_0)\Leftrightarrow x_0=f^{-1}(y_0)$ and $y-y_0=\varphi(f^{-1}(y)(f^{-1}(y)-f^{-1}(y_0)\to f^{-1}(y)-f^{-1}(y_0)$

is $\frac{1}{\varphi(f^{-1}(y)}$ continous at $f(x_0)$? $\varphi(f^{-1}(f(x_0)))=f'(x_0)\ne 0$.

\section*{from monday}
where is $\sqrt{1-\sin x}$ differentiable?

\begin{align*}
  \lim_{h\to0}\frac{\sqrt{1-\sin(x_0+h)}-\sqrt{1-\sin x_0}}{h}
  &=\lim\frac{1-\sin(x_0+h)-(1-\sin x_0)}{h(\sqrt{1-\sin(x_0+h)}\sqrt{1-\sin x_0})}\\
  &=-\cos x_0\frac{1}{2\sqrt{1-\sin x_0}}
\end{align*}
if $\sin x_0=1$ then $\cos x_0=0$ and $\lim\frac{\sqrt{1-\sin(x_0+h)}}{h}=\lim\frac{ \sqrt{1-\sin^2(x_0+h)}}{h\sqrt{1+\sin(x_0+h)}}=\lim\frac{\sqrt{\cos^2(x_0+h)}}{h\sqrt{1+\sin(x_0+h)}}=\lim\frac{\left\lvert\cos(x_0+h)-\cos x_0\right\rvert}{h\sqrt{1+\sin(x_0+h)}}$
\end{document}


\section{Algebraic Diagrammatic Construction}
With the basic knowledge of second quantization, perturbation theory and Green function, we can then start discussing ADC.
We know that we can calculate ionization potentials, electron affinities and ground state energy from Green function by \ref{spectralrepresentation} and \ref{greenenergy}.
We also know that we can use Wick's theorem and Feynman rules for Abrikosov diagram to calculate each order of Green function.
Thus, as least in principle, we can practically calculate some physical quantities.
However, a finite perturbation expansion, e.g., through third order, e.g.
\begin{equation}
\boldsymbol{G}(\omega)=\boldsymbol{G}^{0}(\omega)+\boldsymbol{G}^{(2)}(\omega)+\boldsymbol{G}^{(3)}(\omega)+O(4)
\end{equation}
does not result in a useful approximation scheme to determine the physical quantities of interest.
The reason is that the components $G_{pq}(ω)$ are analytical functions, and a finite perturbation expansion does not recover the proper analytical structure.
What is needed here is to sum the perturbation expansion, even if only partially, through infinite order.
We will introduce two ways, which are Dyson approach and Non-dyson approach to such infinite summation.

\subsection{Dyson Approach}
The Green function can be written as:

\begin{minipage}{0.08\textwidth}
	\includegraphics[height=3cm]{./figures/free.png}
\end{minipage}
\begin{minipage}{0.05\textwidth}
	+
\end{minipage}
\begin{minipage}{0.08\textwidth}
	\includegraphics[height=3cm]{./figures/diagramA.png}
\end{minipage}
\begin{minipage}{0.05\textwidth}
	+
\end{minipage}
\begin{minipage}{0.12\textwidth}
	\includegraphics[height=3cm]{./figures/diagramC.png}
\end{minipage}
\begin{minipage}{0.05\textwidth}
	+
\end{minipage}
\begin{minipage}{0.1\textwidth}
	\includegraphics[height=3cm]{./figures/order2.png}
\end{minipage}
\begin{minipage}{0.2\textwidth}
	+ \qquad \dots
\end{minipage}

We can see that except the first one, all of the diagrams both start and end with a free Green function line.
Thus, we can define improper self-energy part $\widetilde{\Sigma}_{p q}\left(t_{1}, t_{1}^{\prime}\right)$ as the infinite summation of the parts between two free Green function lines in each diagram:

\hspace{0.4\textwidth}
\begin{minipage}{0.08\textwidth}
	\includegraphics[height=3cm]{./figures/free.png}
\end{minipage}
\begin{minipage}{0.05\textwidth}
	+
\end{minipage}
\begin{minipage}{0.05\textwidth}
	\includegraphics[height=3cm]{./figures/newdyson.png}
\end{minipage}

Algebraically, it reads:
\begin{equation}
	G_{p q}\left(t, t^{\prime}\right)=\delta_{p q} G_{p}^{0}\left(t, t^{\prime}\right)+\int \mathrm{d} t_{1} \int \mathrm{d} t_{1}^{\prime} G_{p}^{0}\left(t, t_{1}\right) \widetilde{\Sigma}_{p q}\left(t_{1}, t_{1}^{\prime}\right) G_{q}^{0}\left(t_{1}^{\prime}, t^{\prime}\right)
\end{equation}
or
\begin{equation}
	G_{p q}(\omega)=\delta_{p q} G_{p}^{0}(\omega)+G_{p}^{0}(\omega) \widetilde{\Sigma}_{p q}(\omega) G_{q}^{0}(\omega)
\end{equation}
in energy representation, or
\begin{equation}
	\boldsymbol{G}(\omega)=\boldsymbol{G}^{0}(\omega)+\boldsymbol{G}^{0}(\omega) \widetilde{\boldsymbol{\Sigma}}(\omega) \boldsymbol{G}^{0}(\omega)
\end{equation}
in matrix representation.

To proceed to the definition of the less trivial proper self-energy part, let us consider the following fourth-order diagram.
\begin{figure}
	\centering
	\includegraphics[height=6cm]{./figures/order4.png}
	\caption{one of fourth-order diagrams}
\end{figure}

It can be separated to two parts by a free Green function.
In a similar way, any diagram can be characterized as being either separable or non-separable with respect to cutting a single free fermion line.
Thus, we can define the proper self-energy $\Sigma$ as summation over all non-separable diagrams.

Obviously, improper self-energy and proper self-energy are related by:

\begin{minipage}{0.12\textwidth}
	\includegraphics[height=2cm]{./figures/improper.png}
\end{minipage}
\begin{minipage}{0.02\textwidth}
	=
\end{minipage}
\begin{minipage}{0.12\textwidth}
	\includegraphics[height=2cm]{./figures/proper1.png}
\end{minipage}
\begin{minipage}{0.02\textwidth}
	+
\end{minipage}
\begin{minipage}{0.12\textwidth}
	\includegraphics[height=4cm]{./figures/proper2.png}
\end{minipage}
\begin{minipage}{0.02\textwidth}
	+
\end{minipage}
\begin{minipage}{0.12\textwidth}
	\includegraphics[height=6cm]{./figures/proper3.png}
\end{minipage}
\begin{minipage}{0.2\textwidth}
	+ \qquad \dots
\end{minipage}

or algebraically by
\begin{equation}
	\tilde{\boldsymbol{\Sigma}}(\omega)=\boldsymbol{\Sigma}(\omega)+\boldsymbol{\Sigma}(\omega) \boldsymbol{G}^0(\omega) \tilde{\boldsymbol{\Sigma}}(\omega)
\end{equation}

Thus we can obtain the Dyson equation:
\begin{equation}
	\boldsymbol{G}(\omega)=\boldsymbol{G}^{0}(\omega)+\boldsymbol{G}^{0}(\omega) \boldsymbol{\Sigma}(\omega) \boldsymbol{G}(\omega)
\end{equation}
and thus
\begin{equation}
	\boldsymbol{\Sigma}(\omega)=\boldsymbol{G}^{0}(\omega)^{-1}-\boldsymbol{G}(\omega)^{-1}
\end{equation}

Since both the improper and proper self-energy are defined by summation of diagrams, it is obvious that they can also be expanded just like Green functions.
For example, the second order of proper self-energy is
\begin{equation} \label{selforder2}
	\Sigma_{p q}^{(2)}(\omega)=\sum_{a, b, k} \frac{V_{p k[a b]} V_{a b[q k]}}{\omega+\epsilon_{k}-\epsilon_{a}-\epsilon_{b}+i \eta}+\sum_{a, k, l} \frac{V_{p a[k l]} V_{k l[q a]}}{\omega+\epsilon_{a}-\epsilon_{k}-\epsilon_{l}-i \eta}
\end{equation}

The self-energy can be written in a general form:
\begin{equation}
	\Sigma_{p q}(\omega)=\Sigma_{p q}(\infty)+M_{p q}(\omega)
\end{equation}
where $\Sigma_{p q}(\infty)$ and $M_{p q}(\omega)$ are refered to as dynamical part and static part, respectively.
It can be proved that $M_{pq}(\omega)$ can also be written in a spectral representation form:
\begin{equation}
	M_{p q}(\omega)=M_{p q}^{+}(\omega)+M_{p q}^{-}(\omega)=\sum_{\nu} \frac{m_{p}^{(\nu)} m_{q}^{(\nu) *}}{\omega-\omega_{\nu}+i \eta}+\sum_{\mu} \frac{m_{p}^{(\mu)} m_{q}^{(\mu) *}}{\omega-\omega_{\mu}-i \eta}
\end{equation}

The proof in given in reference \cite{Mpqproof1,Mpqproof2}.

If the infinite small $\eta$ is ignored, then
\begin{equation}
	M_{p q}(\omega)=\sum_{\nu} \frac{m_{p}^{(\nu)} m_{q}^{(\nu) *}}{\omega-\omega_{\nu}}+\sum_{\mu} \frac{m_{p}^{(\mu)} m_{q}^{(\mu) *}}{\omega-\omega_{\mu}}
\end{equation}
and
\begin{equation}
	G_{p q}(\omega)=\sum_{n} \frac{x_{p}^{n} x_{q}^{n *}}{\omega-e_{n}}
\end{equation}
where $n$ runs over both $N+1$ states and $N-1$ states.

Additionally,
\begin{equation}
	\begin{aligned}
		G_{p q}^{0}(\omega)&=\delta_{p q}\left(\frac{\overline{n}_{p}}{\omega-\varepsilon_{p}+i \eta}+\frac{n_{p}}{\omega-\varepsilon_{p}-i \eta}\right)
		\\
		&=\frac{\delta_{p q}}{\omega-\varepsilon_{p}}
	\end{aligned}
\end{equation}

In matrix representation,
\begin{equation}
	\boldsymbol{M}^{ \pm}(\omega)=\boldsymbol{m}^{ \pm \dagger}\left(\omega \mathbf{1}-\boldsymbol{\Omega}^{ \pm}\right)^{-1} \boldsymbol{m}^{ \pm}
\end{equation}
\begin{equation}
	\boldsymbol{G}(\omega)=\boldsymbol{x}(\omega \mathbf{1}-\boldsymbol{E})^{-1} \boldsymbol{x}^{\dagger}
\end{equation}
\begin{equation}
	\boldsymbol{G}^0(\omega)=(\omega \mathbf{1} - \boldsymbol{\epsilon})^{-1}
\end{equation}
and
\begin{equation}
	\boldsymbol{x} \boldsymbol{x}^{\dagger}=1
\end{equation}

Since
\begin{equation}
	\begin{aligned} \boldsymbol{G}(\omega)^{-1} &=\omega\left[x\left(\mathbf{1}-\frac{\boldsymbol{E}}{\omega}\right)^{-1} \boldsymbol{x}^{\dagger}\right]^{-1} \\ &=\omega\left[\boldsymbol{x}\left(\mathbf{1}+\frac{\boldsymbol{E}}{\omega}+O\left(\omega^{-2}\right)\right) \boldsymbol{x}^{\dagger}\right]^{-1} \\ &=\omega\left[\mathbf{1}+\boldsymbol{x} \frac{\boldsymbol{E}}{\omega} \boldsymbol{x}^{\dagger}+O\left(\omega^{-2}\right)\right]^{-1}=\omega \mathbf{1}-x \boldsymbol{E} \boldsymbol{x}^{\dagger}+O\left(\frac{1}{\omega}\right) \end{aligned}
\end{equation}

We have
\begin{equation}
	\begin{aligned}
		\boldsymbol{\Sigma}(\omega)&=\boldsymbol{G}^{0}(\omega)^{-1}-\boldsymbol{G}(\omega)^{-1}
		\\
		&=-\boldsymbol{\epsilon}+\boldsymbol{x} \boldsymbol{E} \boldsymbol{x}^{\dagger}+O\left(\frac{1}{\omega}\right)
	\end{aligned}
\end{equation}
and thus
\begin{equation}
	\boldsymbol{\Sigma}(\infty)=-\boldsymbol{\epsilon}+\boldsymbol{x} \boldsymbol{E} \boldsymbol{x}^{\dagger}
\end{equation}

As a result, the Dyson equation becomes:
\begin{equation}
	\boldsymbol{G}(\omega)=\left(\omega \mathbf{1}-\boldsymbol{\epsilon}-\boldsymbol{\Sigma}(\infty)-\boldsymbol{m}^{-\dagger}\left(\omega \mathbf{1}-\boldsymbol{\Omega}^{-}\right)^{-1} \boldsymbol{m}^{-}-\boldsymbol{m}^{+^{\dagger}}\left(\omega \mathbf{1}-\boldsymbol{\Omega}^{+}\right)^{-1} \boldsymbol{m}^{+}\right)^{-1}
\end{equation}

It can be proved that if we introduce Dyson secular matrix
\begin{equation} \label{matrixA}
	\boldsymbol{A}=\left( \begin{array}{ccc}{\boldsymbol{\epsilon}+\boldsymbol{\Sigma}(\infty)} & {\boldsymbol{m}^{-\dagger}} & {\boldsymbol{m}^{+\dagger}} \\ {\boldsymbol{m}^{-}} & {\boldsymbol{\Omega}^{-}} & {\mathbf{0}} \\ {\boldsymbol{m}^{+}} & {\mathbf{0}} & {\boldsymbol{\Omega}^{+}}\end{array}\right)
\end{equation}
then
\begin{equation}
	\boldsymbol{G}(\omega)=\left.(\omega \mathbf{1}-\boldsymbol{A})^{-1}\right|_{11}
\end{equation}
where the $11$ subscript means taking the upper left diagonal block.

Thus the energies interested, which are poles of $G$, are also poles of Dyson secular matrix $A$.
Then we can diagonalize the matrix A to determine the values of poles and thus the energies and eigenstates, which are transition amplitudes, i.e.
\begin{equation}
	\boldsymbol{A} \boldsymbol{X}=\boldsymbol{X} \boldsymbol{E}, \quad \boldsymbol{X}^{\dagger} \boldsymbol{X}=1
\end{equation}

from Eq \ref{selforder2}, we can also determine the leading terms of $m$ and $\Omega$.
Since
\begin{equation}
	\begin{aligned}
	M_{p q}^{(2)+}(\omega) &=\sum_{a<b, k} \frac{V_{p k[a b]} V_{a b[q k]}}{\omega+\epsilon_{k}-\epsilon_{a}-\epsilon_{b}+i \eta}
	\\
	M_{p q}^{(2)-}(\omega) &=\sum_{a, k<l} \frac{V_{p a[k l]} V_{k l[q a]}}{\omega+\epsilon_{a}-\epsilon_{k}-\epsilon_{l}-\epsilon_{l}-i \eta}
	\end{aligned}
\end{equation}
we have
\begin{equation}
	\begin{aligned}
	\Omega_{a k l, a k l}^{-} &=-\epsilon_{a}+\epsilon_{k}+\epsilon_{l}
	\\
	\Omega_{a b k, a b k}^{+} &=-\epsilon_{k}+\epsilon_{a}+\epsilon_{b}
	\end{aligned}
\end{equation}
and
\begin{equation}
	m_{a k l, q}^{-} =V_{q a[k l]}, \quad m_{a b k, q}^{+}=V_{a b[q k]}
\end{equation}

They are leading terms since the leading order of $M$ is second order.
This is because
\begin{equation}
	\begin{aligned}
		\boldsymbol{\Sigma}(\omega)&=\boldsymbol{G}^{0}(\omega)^{-1}-\boldsymbol{G}(\omega)^{-1}
		\\
		&=\boldsymbol{G}^{0}(\omega)^{-1}-(\boldsymbol{G}^0(\omega)+O(2))^{-1}
		\\
		&=O(2)
	\end{aligned}
\end{equation}

As is mentioned previously, a finite perturbation expansion of the electron propagator does not reproduce its correct analytical form.
However, we are still using finite perturbation expansion, i.e. determine each order of $m$, $\Omega$ and then calculate the eigenvalues of Dyson secular matrix in Eq \ref{matrixA}.

We will then begin introducing ADC to sum partially to infinity.
We will consider $M^{+}$ in the following since it is analogous for $M^{-}$.

In ADC, equation
\begin{equation}
	M_{p q}(\omega)=\boldsymbol{m}_{p}^{\dagger}(\omega \mathbf{1}-\boldsymbol{\Omega})^{-1} \boldsymbol{m}_{q}
\end{equation}
is replaced by ADC form:
\begin{equation}
	M_{p q}(\omega)=\boldsymbol{U}_{p}^{\dagger}(\omega \mathbf{1}-\boldsymbol{K}-\boldsymbol{C})^{-1} \boldsymbol{U}_{q}
\end{equation}
where
$\boldsymbol{K}+\boldsymbol{C}$ is refered to as ADC secular matrix.

Although $\boldsymbol{K}$, $\boldsymbol{C}$, and $\boldsymbol{U}$ are not specified yet,
we may suppose that the following perturbation expansions apply:
\begin{equation} \label{cuexpansion}
	\begin{aligned}
		\boldsymbol{C} &=\boldsymbol{C}^{(1)}+\boldsymbol{C}^{(2)}+\cdots
		\\
		\boldsymbol{U_{p}} &=\boldsymbol{U_{p}}^{(1)}+\boldsymbol{U_{p}}^{(2)}+\cdots
	\end{aligned}
\end{equation}

Here $\boldsymbol{K}$ is actually the zeroth order of $\boldsymbol{C}$.
Thus
\begin{equation}
	\begin{array}{l}{K_{j a b, j a b}=-\epsilon_{j}+\epsilon_{a}+\epsilon_{b}} \\ {K_{i j a b c, i j a b c}=-\epsilon_{i}-\epsilon_{j}+\epsilon_{a}+\epsilon_{b}+\epsilon_{c}} \\ {\qquad \vdots}\end{array}
\end{equation}
where $i, j, k \dots$ label occupied orbitals while $a, b, c \dots$ label virtual orbitals.

Although we still expand $\boldsymbol{K}$ and $\boldsymbol{C}$ to finite order, the expansion of $M$ is already partially to infinite orders:
\begin{equation} \label{adcexpansion}
	\begin{aligned} M_{p q}(\omega) &=\boldsymbol{U}_{p}^{\dagger}(\omega \mathbf{1}-\boldsymbol{K}-\boldsymbol{C})^{-1} \boldsymbol{U}_{q} \\ &=\boldsymbol{U}_{p}^{\dagger}(\omega \mathbf{1}-\boldsymbol{K})^{-1} \sum_{n=0}^{\infty}\left\{\boldsymbol{C}(\omega \mathbf{1}-\boldsymbol{K})^{-1}\right\}^{n} \boldsymbol{U}_{q} \end{aligned}
\end{equation}

Now, we can formulate the ADC procedure as follows:

Compare the formal perturbation expansion of the ADC form Eq \ref{adcexpansion} to the original diagrammatic perturbation expansion for the self-energy part $M^{+}_{pq}(\omega)$ through a given order $n$ of perturbation theory.
Beginning at second order and proceeding to higher order, this comparison allows one to determine successively the terms in the expansions Eq \ref{cuexpansion} of $\boldsymbol{C}$ and $\boldsymbol{U}_p$ , respectively.

Through second order of $M$, we can determine $\boldsymbol{C}$ and $\boldsymbol{U}_p$ as
\begin{equation}
	U_{j a b, q}^{(1)}=V_{a b[q j]}
\end{equation}
\begin{equation}
	C_{j a b, j^{\prime} a^{\prime} b^{\prime}}=0
\end{equation}

Through third order of $M$, we can determine $\boldsymbol{C}$ and $\boldsymbol{U}_p$ as
\begin{equation}
	\begin{aligned}
		U_{j a b, q}^{(2)}&= \frac{1}{2} \sum_{k l} \frac{V_{a b[k l]} V_{k l[q j]}}{\epsilon_{k}+\epsilon_{l}-\epsilon_{a}-\epsilon_{b}} +\left(\sum_{c k} \frac{V_{a c[k j]} V_{k b[q c]}}{\epsilon_{a}+\epsilon_{c}-\epsilon_{j}-\epsilon_{k}}\right)-(a \leftrightarrow b)
		\\
		C_{j a b, j^{\prime} a^{\prime} b^{\prime}}^{(1)}&=\delta_{j j^{\prime}} V_{a b\left[a^{\prime} b^{\prime}\right]}-\left(\delta_{a a^{\prime}} V_{j^{\prime} b\left[j b^{\prime}\right]}+\delta_{b b^{\prime}} V_{j^{\prime} a\left[j a^{\prime}\right]}\right)+(a^{\prime} \leftrightarrow b^{\prime})
	 \end{aligned}
\end{equation}

Instead of Dyson secular matrix, we have a new Dyson-ADC secular matrix:
\begin{equation}
	\boldsymbol{B}=\left( \begin{array}{ccc}{\epsilon+\mathbf{\Sigma}(\infty)} & {\boldsymbol{U}^{-\dagger}} & {\boldsymbol{U}^{+\dagger}} \\ {\boldsymbol{U}^{-}} & {\boldsymbol{K}^{-}+\boldsymbol{C}^{-}} & {\mathbf{0}} \\ {\boldsymbol{U}^{+}} & {\boldsymbol{0}} & {\boldsymbol{K}^{+}+\boldsymbol{C}^{+}}\end{array}\right)
\end{equation}
and
\begin{equation}
	\boldsymbol{G}(\omega)=\left.(\omega \mathbf{1}-\boldsymbol{B})^{-1}\right|_{11}
\end{equation}
and thus diagonalization as
\begin{equation}
	\boldsymbol{B} \boldsymbol{X}=\boldsymbol{X} \boldsymbol{E}, \quad \boldsymbol{X}^{\dagger} \boldsymbol{X}=1
\end{equation}

The structure of Dyson-ADC(3) matrix is:
\begin{table}
	\centering
	\caption{Structure of Dyson-ADC(3)}
\begin{tabular}{cccc}
                           & 1h/1p                                                                    & 2h-1p                                    & 2p-1h                                      \\ \cline{2-4}
\multicolumn{1}{c|}{1h/1p} & \multicolumn{1}{c|}{$\boldsymbol{\epsilon}+\boldsymbol{\Sigma}(\infty)$} & \multicolumn{1}{c|}{$U^{-(1,2)\dagger}$} & \multicolumn{1}{c|}{$ U^{+(1,2)\dagger} $} \\ \cline{2-4}
\multicolumn{1}{c|}{2h-1p} & \multicolumn{1}{c|}{$U^{-(1,2)}$}                                        & \multicolumn{1}{c|}{$K^{-}+C^{-(1)}$}    & \multicolumn{1}{c|}{0}                     \\ \cline{2-4}
\multicolumn{1}{c|}{2p-1h} & \multicolumn{1}{c|}{$U^{+(1,2)}$}                                        & \multicolumn{1}{c|}{0}                   & \multicolumn{1}{c|}{$K^{+}+C^{+(1)}$}      \\ \cline{2-4}
\end{tabular}
\end{table}

The summation to infinity ensures that Dyson-ADC is a size consistent method, which is an important advantage over CI.
Another advantage is that configuration space of Dyson-ADC is smaller than CI.
For example, The consistent treatment of 1h main states through second (and third order) requires the CI expansions to extend through the 3h-2p configurations.
By contrast, the ADC(2) (and ADC(3)) configuration spaces are restricted to the 2h-1p configurations of $N−1$ particles, but also comprise the 2h-1p configurations of $N+1$ particles.

\subsection{Non-dyson Approach}
The advantage of Dyson approach is the decrease the number of Feynman diagrams one need to calculate by property of Dyson equation.
However, the problem is that $N+1$ part and $N-1$ part are coupled, thus one has to diagonalize the full B matrix.
Moreover, people usually care about the first few ionized or anionized states, which lie in the middle of the energy spectrum.
Algorithmically, it is difficult to determine eigenvalues in the middle part of an energy spectrum.
Thus, we introduce Non-dyson approach, which solve this problem and make sure that all states interested are in the edge of energy spectrum
Since Non-dyson ADC treat $N+1$ part and $N-1$ part separately, we will focus on $N-1$ part, and $N+1$ part is analogous.

Related to $N-1$ part, Green function $G^{-}$ can be written as
\begin{equation}
	\boldsymbol{G}^{-}(\omega)=\boldsymbol{x}(\omega \mathbf{1}-\boldsymbol{\Omega})^{-1} \boldsymbol{x}^{\dagger}
\end{equation}
where $\Omega$ are negative ionization energies that we do care about.

By transposing, we obtain
\begin{equation}
	\tilde{\boldsymbol{G}}(\omega)=\boldsymbol{G}^{-}(\omega)^{t}=\tilde{\boldsymbol{x}}^{\dagger}(\omega \mathbf{1}-\boldsymbol{\Omega})^{-1} \tilde{\boldsymbol{x}}
\end{equation}

Then we introduce ADC representation just like Dyson approach:
\begin{equation}
	\tilde{\boldsymbol{G}}(\omega)=\boldsymbol{f}^{\dagger}(\omega-\boldsymbol{K}-\boldsymbol{C})^{-1} \boldsymbol{f}
\end{equation}
and diagonalization as
\begin{equation} \label{KCeigen}
	(\boldsymbol{K}+\boldsymbol{C}) \boldsymbol{X}=\boldsymbol{X} \boldsymbol{E}, \quad \boldsymbol{X}^{\dagger} \boldsymbol{X}=1
\end{equation}

Just like Dyson approach, we still expand $\boldsymbol{C}$ and $\boldsymbol{g}$ to series:
\begin{equation}
	\begin{aligned} \boldsymbol{K}+\boldsymbol{C} &=\boldsymbol{K}+\boldsymbol{C}^{(1)}+\boldsymbol{C}^{(2)}+\boldsymbol{C}^{(3)}+\ldots \\ \boldsymbol{f} &=\boldsymbol{f}^{(0)}+\boldsymbol{f}^{(1)}+\boldsymbol{f}^{(2)}+\ldots \end{aligned}
\end{equation}
where the expression for $\boldsymbol{K}$ is:
\begin{equation}
	\begin{aligned} K_{k k} &=\epsilon_{k} \\ K_{a k l, a k l} &=\epsilon_{k}+\epsilon_{l}-\epsilon_{a} \\ & \vdots \end{aligned}
\end{equation}

Just like Dyson approach, we can also see that the expansion of $M$ is partially to infinite orders:
\begin{equation}
	\tilde{\boldsymbol{G}}(\omega)=\boldsymbol{f}^{\dagger}(\omega-\boldsymbol{K}-\boldsymbol{C})^{-1} \boldsymbol{f}=\boldsymbol{f}^{\dagger}(\omega-\boldsymbol{K})^{-1} \sum_{\nu=0}^{\infty}\left(\frac{\boldsymbol{C}}{\omega-\boldsymbol{K}}\right)^{\nu} \boldsymbol{f}
\end{equation}

The procedure of Non-dyson ADC is the same with Dyson-ADC.
By this procedure, we obtain the first few orders of $\boldsymbol{C}$ and $\boldsymbol{f}$ for Non-dyson ADC(2):

\begin{equation}
	\begin{aligned}
		f_{p q}^{(0)}&=\delta_{p q} n_{p}
		\\
		f_{\mu}^{(0)}&=0, \text { for } \mu>1
		\\
		f_{1}^{(1)}&=0 \text { for } \mu>2
		\\
		f_{a k l, q}^{(1)}&=\frac{V_{q a[k] ]}}{\epsilon_{q}+\epsilon_{a}-\epsilon_{k}-\epsilon_{l}} \overline{n}_{q}
		\\
		f_{p q}^{(2)}&=\frac{1}{4} \sum_{a, b, j} v_{a b p j} v_{q j a b} n_{q}
		\\
		C_{11}^{(1)}&=0
		\\
		C_{1 \mu}^{(1)}&=0 \text { for } \mu>2
		\\
		C_{p, a k l}^{(1)}&=-V_{k l[p a]} n_{p}
		\\
		C_{p q}^{(2)}&=\frac{1}{2} \sum_{a, b, j} v_{a b p j} v_{q j a b}\left(\epsilon_{a}+\epsilon_{b}-\epsilon_{j}-\frac{1}{2} \epsilon_{p}-\frac{1}{2} \epsilon_{q}\right), n_{p}=n_{q}=1
	\end{aligned}
\end{equation}

The structure of Non-dyson ADC(2) matrix is:
\begin{table}
	\centering
	\caption{Structure of Non-dyson ADC(2)}
	\label{ADC2}
	\begin{tabular}{ccc}
						       &             1p                      &             1h-2p               \\ \cline{2-3}
	\multicolumn{1}{l|}{1p   } & \multicolumn{1}{l|}{$K_1+C^2_{11}$} & \multicolumn{1}{l|}{$C^1_{12}$} \\ \cline{2-3}
	\multicolumn{1}{l|}{1h-2p} & \multicolumn{1}{l|}{$C^1_{21}$}     & \multicolumn{1}{l|}{$K_2$}      \\ \cline{2-3}
	\end{tabular}
\end{table}

The structure of Non-dyson ADC(3) matrix is:
\begin{table}
	\centering
	\caption{Structure of Non-dyson ADC(3)}
	\label{ADC3}
	\begin{tabular}{ccc}
						           &                     1p                       &                     1h-2p                \\ \cline{2-3}
		\multicolumn{1}{l|}{1p   } & \multicolumn{1}{l|}{$K_1+C^2_{11}+C^3_{11}$} & \multicolumn{1}{l|}{$C^1_{12}+C^2_{12}$} \\ \cline{2-3}
		\multicolumn{1}{l|}{1h-2p} & \multicolumn{1}{l|}{$C^1_{21}+C^2_{12}$}     & \multicolumn{1}{l|}{$K_2+C^1_{22}$}      \\ \cline{2-3}
	\end{tabular}
\end{table}

We can also use \ref{greenenergy} to calculate ground state energy by Non-dyson ADC.
\begin{equation}
	\begin{aligned}
		\boldsymbol{\rho}&=\frac{1}{2 \pi i} \oint \boldsymbol{G}^{-}(\omega) \mathrm{d} \omega
		\\
		&=\frac{1}{2 \pi i} \oint \boldsymbol{f}^{\dagger}(\omega-\boldsymbol{K}-\boldsymbol{C})^{-1} \boldsymbol{f} \mathrm{d} \omega=\boldsymbol{f}^{\dagger} \boldsymbol{f}
	\end{aligned}
\end{equation}

Thus
\begin{equation}
	E_{0}=\frac{1}{2} \operatorname{Tr}\left(\boldsymbol{f}^{\dagger}(\boldsymbol{K}+\boldsymbol{C}) \boldsymbol{f}+\boldsymbol{T}^{t} \boldsymbol{f}^{\dagger} \boldsymbol{f}\right)
\end{equation}

The complexity of Non-dyson ADC(2) is $m^4$ while ADC(3) is $m^5$, where $m$ is the number of one particle basis.

It can be proved that Non-dyson ADC is also size consistent.
The reason is that the direct ADC secular matrix can be identified as the representation of the (subtracted) Hamiltonian with respect to a specific set of intermediate states, which will be presented in the next section.


\chapter{Formulas for double-differential energy-angle data}
\label{Sec:double-diff-formula}
This section explains the coding used to treat two representations
by formula for double-differential energy-angle data in the \xendl\ library,
the Kalbach-Mann formula and the phase-space model.  The
Kalbach-Mann model is described first, because it is used so often in \xendl.

\section{The Kalbach-Mann model for double-differential data}
In the Kalbach-Mann representation \cite{Kalbach} the
double differential probability density is of the form
\begin{equation}
  \pi(\Ecm', \mucm \mid E) =
  \pi_E( \Ecm' \mid E) \pi_\mu( \mucm \mid \Ecm', E ),
  \label{Kalbach-prob}
\end{equation}
where $E$ is the energy of the incident particle in laboratory
coordinates and $\Ecm'$ and $\mucm$ are the energy and cosine of
the outgoing particle in center-of-mass coordinates.
The values of the probability density $\pi_E( \Ecm' \mid E)$ for outgoing
energy $\Ecm'$
are given as a table with normalization
$$
  \int_0^\infty d\Ecm' \, \pi_E( \Ecm' \mid E) = 1.
$$
In Eq.~(\ref{Kalbach-prob}) the function
$\pi_\mu( \mucm \mid \Ecm', E )$ is an exponential in
$\mucm$ depending on parameters~$a$ and~$r$~\cite{Kalbach},
\begin{equation}
  \pi_\mu( \mucm \mid \Ecm', E ) =
    \frac{1}{C}
    [ \cosh(a\mucm) + r \sinh(a\mucm)].
  \label{Kalbach-eta}
\end{equation}
The value of $r$ in Eq.~(\ref{Kalbach-eta}) depends on the incident and outgoing energies
$E$ and $\Ecm'$ and is given in a data table.  The formula Eq.~(\ref{Kalbach-eta})
represents a pre-equilibrium model, with $r=0$ representing complete
equilibrium and $r = 1$ no equilibrium at all.  It is therefore always true
that
$$
  0 \le r \le 1.
$$

The value of $C$ in Eq.~(\ref{Kalbach-eta}) is chosen to ensure the normalization
$$
  \int_{-1}^1 d\mucm \, \pi_\mu( \mucm \mid \Ecm', E ) = 1.
$$
That is, take
$$
  C = \frac{ 2 \sinh{a}}{a}.
$$

\subsection{The Kalbach-Mann $a$ parameter}
The values of the parameter~$a$ in Eq.~(\ref{Kalbach-eta}) may be given
as a table depending on the incident
energy $E$ and on $\Ecm'$, the center-of-mass kinetic energy of
the outgoing particle.  It is more common, however, to use the formula
for $a$ as a function of $E$ as found in the references \cite{Kalbach} and~\cite{ENDFB}.
The details are repeated here for the sake of completeness.

{% begin special notation
\newcommand{\Ealab}{E_{a,\text{lab}}}
\newcommand{\Eacm}{E_{a,\text{cm}}}
\newcommand{\EAcm}{E_{A,\text{cm}}}
\newcommand{\EaAcm}{E_{aA,\text{cm}}}
\newcommand{\Ebcm}{E_{b,\text{cm}}}
\newcommand{\EBcm}{E_{B,\text{cm}}}
\newcommand{\EbBcm}{E_{bB,\text{cm}}}
Some special notation is used in this subsection.  The reaction is of the form
\begin{equation}
  A + a \to C \to B + b,
 \label{Kalbach-reaction}
\end{equation}
where
\begin{align*}
  A:\quad &\text{the target with mass $\mtarg$, assumed to be at rest in the laboratory frame,} \\
  a:\quad &\text{the incident particle with mass $\myi$,} \\
  C:\quad &\text{the compound nucleus,} \\
  B:\quad &\text{the residual nucleus with mass $\mres$,} \\
  b:\quad &\text{the emitted particle with mass $\myo$.}
\end{align*}

Several energies are needed, all measured in MeV,
\begin{align*}
  \Ealab:\quad &\text{energy of the incident particle in the laboratory frame,} \\
  \Eacm:\quad &\text{energy of the incident particle in the center-of-mass frame,} \\
  \EAcm:\quad &\text{energy of the target in the center-of-mass frame,} \\
  \EaAcm:\quad &\Eacm + \EAcm = \mtarg \Ealab/( \mtarg + \myi), \\
  \Ebcm:\quad &\text{energy of the outgoing particle in the center-of-mass frame,} \\
  \EbBcm:\quad & (\mres + \myo) \Ebcm / \myo.
\end{align*}
Note that the quantity $\EbBcm$ is the total kinetic energy of $B$ and $b$ if
the breakup of $C$ is a discrete 2-body reaction with the excitation level
of $B$ unspecified.

For a reaction with several outgoing particles, $b$ in Eq.~(\ref{Kalbach-reaction})
is the particle corresponding to the current data, and $B$ is the residual
following the emission of $b$ from the compound nucleus~$C$.
Thus, for the
$$
   {}^{78}\text{Kr} (n, np) {}^{77}\text{Br}
$$
reaction, one uses
$$
   B =  {}^{78}\text{Kr}
$$
in the computation of $a(E, \Ebcm)$ with Kalbach-Mann data for the
outgoing neutron, while
$$
   B =  {}^{78}\text{Br}
$$
with outgoing proton data.  Analogously, use
$$
     B =  {}^{78}\text{Kr}
$$
in the computation of $a(E, \Ebcm)$ with Kalbach-Mann neutron data for the
$$
   {}^{78}\text{Kr} (n, 2n) {}^{77}\text{Kr}
$$
reaction.

For massive incident particles, the value of $a(E, \Ebcm)$ is given
by the expression
\begin{equation}
  a(E, \Ebcm) = C_1 X_1 + C_2 X_1^3 + C_3 M_a m_b X_3^4
 \label{Kalbach-a}
\end{equation}
with terms explained below.

The coefficients in Eq.~(\ref{Kalbach-a}) are
$$
  C_1 = 0.04\,\text{MeV}^{-1}, \quad
  C_2 = 1.8 \times 10^{-6}\,\text{MeV}^{-3}, \quad
  C_3 = 6.7 \times 10^{-7} \,\text{MeV}^{-4}.
$$

The values of $X_1$ and $X_3$ in Eq.~(\ref{Kalbach-a}) depend on
the energies $S_a$ and $S_b$ of the capture and breakup  reactions
in Eq.~(\ref{Kalbach-reaction}).  For the target define
\begin{align*}
  Z_A: \quad & \text{number of protons in the target nucleus,} \\
  N_A: \quad & \text{number of neutrons in the target nucleus,} \\
  A_A: \quad & Z_A + N_A.
\end{align*}
Corresponding $Z_C$, $N_C$, and $A_C$ are defined
for the compound nucleus~$C$ and
$Z_B$, $N_B$, and $A_B$ for the residual nucleus~$B$.
For the capture reaction,
$S_a$ is taken as
\begin{multline}
  S_a = 15.68(A_C - A_A) -
    28.07\left(
      \frac{(N_C - Z_C)^2}{A_C} - \frac{(N_A - Z_A)^2}{A_A }
    \right) - {} \\
    18.56( A_C^{2/3} - A_A^{2/3}) +
      33.22\left(
        \frac{(N_C - Z_C)^2}{A_C^{4/3}} - \frac{(N_A - Z_A)^2}{A_A^{4/3} }
    \right) - {} \\
    0.717\left(
      \frac{Z_C^2}{A_C^{1/3}} - \frac{Z_A^2}{A_A^{1/3}}
    \right) + 1.211\left(
      \frac{Z_C^2}{A_C} - \frac{Z_A^2}{A_A}
    \right) - I_a.
 \label{def-Sa}
\end{multline}
Here, $I_a$ is the breakup energy for the incident particle
as given in Table~10.1.  The energy $S_b$ corresponding to the second
reaction in Eq.~(\ref{Kalbach-reaction}) is obtained from Eq.~(\ref{def-Sa})
with $Z_A$, $N_A$, $A_A$, and $I_a$ replaced, respectively by
$Z_B$, $N_B$, $A_B$, and $I_b$.

\begin{table}
\caption{Breakup energies for incident and outgoing particles in MeV}
$$
 \vbox{ \offinterlineskip \tabskip = 0.0cm
  \halign{
   \mystrut#\hfil  \tabskip = 0.5cm &
   \hfil#\hfil&
   \hfil#\hfil&  \tabskip = 0cm
   \hfil\vrule#\cr
   \noalign{\hrule}
   height 12pt depth 6pt& particle&  $I_a$ or $I_b$& \cr
   \noalign{\hrule}
   height 12pt& $n$& 0& \cr
   &$p$& 0& \cr
   &$d$& 2.22& \cr
   &$t$& 8.48& \cr
   &${}^3\text{He}$& 7.72& \cr
   depth 6pt &$\alpha$& 28.3& \cr
   \noalign{\hrule}
  }
 }
$$
\end{table}

The quantities $X_1$ and $X_3$ in Eq.~(\ref{Kalbach-a}) are
obtained by setting
\begin{alignat*}{2}
   \textbf{E}_a &= \EaAcm + S_a, \qquad
    & \textbf{E}_b &= \EbBcm + S_b, \\
   E_{t1} &= 130 \text{ MeV}, \qquad
    & E_{t3} &= 41 \text{ MeV}, \\
   R_1 &= \min( \textbf{E}_a, E_{t1}), \qquad
    & R_3 &= \min( \textbf{E}_a, E_{t3}), \\
   X_1 &= R_1 \textbf{E}_b / \textbf{E}_a, \qquad
    & X_3 &= R_3 \textbf{E}_b / \textbf{E}_a.
\end{alignat*}

Finally the values $M_a$ for the incident particle and $m_b$ for the
outgoing particle in the last term of Eq.~(\ref{Kalbach-a}) are
given in Table~10.2.  Note that $M_a$ is not defined for incident
tritons or for incident helium-3 nuclei, so that the Kalbach-Mann
model is not applicable when the incident energy of such
particles is so large that $\textbf{E}_a > E_{t3}$.

\begin{table}
\caption{Values of $M_a$ and $m_b$ in Eq.~(\ref{Kalbach-a})}
$$
 \vbox{ \offinterlineskip \tabskip = 0.0cm
  \halign{
   \mystrut#\hfil  \tabskip = 0.5cm &
   \hfil#\hfil&
   \hfil#\hfil&
   \hfil#\hfil&  \tabskip = 0cm
   \hfil\vrule#\cr
   \noalign{\hrule}
   height 12pt depth 6pt& particle&  $M_a$& $m_b$& \cr
   \noalign{\hrule}
   height 12pt& $n$& 1& 1/2 &\cr
   &$p$& 1& 1&\cr
   &$d$& 1& 1& \cr
   &$t$& ---& 1& \cr
   &${}^3\text{He}$& ---& 1&\cr
   depth 6pt &$\alpha$& 0& 2& \cr
   \noalign{\hrule}
  }
 }
$$
\end{table}

\subsection{Photo-nuclear reactions}
When Kalbach-Mann data are given for photo-nuclear reactions,
the parameter $a(E, \Ebcm)$ in Eq.~(\ref{Kalbach-a}) and the
angular probability density $\pi_\mu( \mucm \mid \Ecm', E )$
in Eq.~(\ref{Kalbach-eta}) are modified as in the paper~\cite{photo-nuc}.

One begins by computing $a_n(E, \Ebcm)$ in Eq.~(\ref{Kalbach-a}) using a neutron as
incident particle.  Then, for the incident photon one takes
\begin{equation}
  a(E, \Ebcm) = a_n(E, \Ebcm)
    \sqrt{ \frac{E}{2 m_n} } \,
    \min\left(
      4, \max\left(
        1, \frac{9.3}{\sqrt{\Ebcm}}
      \right)
    \right).
 \label{Kalbach-photo}
\end{equation}
Here, $m_n$ is the mass of the neutron in MeV.

For incident photons the angular probability density takes the form
$$
  \pi_\mu( \mucm \mid \Ecm', E ) =
  \frac{1}{2} \left[
    (1 - r) + \left(
      \frac{ar}{\sinh(a)}
    \right) \expon{a \mucm}
  \right].
$$

\subsection{Interpolation of Kalbach-Mann data}\label{Sec:Kalbach-Mann-interp}

In the \xendl\ library, the Kalbach-Mann data are given
as a table of the probability density $\pi_E( \Ecm' \mid E)$ of outgoing
energy~$\Ecm'$ for an incident particle with energy~$E$,
along with a table of values of the parameter~$r$ in Eq.~(\ref{Kalbach-eta})
as a function of $E$ and~$\Ecm'$.  It is also permitted to include a
table of values $a(E,  \Ebcm)$ to be used in place of the expression
in Eq.~(\ref{Kalbach-a}).
}% end special notation

Because $\pi_E( \Ecm' \mid E)$ is a probability
density, it is to be interpolated with respect to $E$ by one of the methods
of Section~\ref{Sec:2d-interp}.
The interpolated values of $r$, however, must
maintain the physical constraints that $0 \le r \le 1$,
so the Kalbach-Mann $r$ parameter is interpolated by the unscaled methods of
Section~\ref{Sec:Kalbach-r-interp}.  If the values of $a$ are also
given as a table, they are also interpolated as in Section~\ref{Sec:Kalbach-r-interp}.

For unit-base interpolation the method is as follows.
The energy probability density
$\pi_E( \Ecm' \mid E)$ is first mapped to unit base as defined in equations
Eqs.~(\ref{unit-base-map}) and~(\ref{unitbaseMap}), so that
\begin{equation}
  \widehat \pi_E( \widehat \Ecm' \mid E) =
    ( E'_{\text{cm}, \text{max}} - E'_{\text{cm}, \text{min}} )
     \pi_E( \Ecm' \mid E)
 \label{Kalb-pi-unit-base}
\end{equation}
for $0 \le \widehat \Ecm' \le 1$.
The scale factor in Eq.~(\ref{Kalb-pi-unit-base}) is chosen so as to
normalize the function $\widehat \pi_E( \widehat \Ecm' \mid E) $,
$$
  \int_0^1 d\widehat \Ecm' \, \pi_E( \widehat \Ecm' \mid E) = 1.
$$
The values of $\widehat \pi_E( \widehat \Ecm' \mid E)$ are
interpolated linearly with respect to $E$.

For the values of the parameter $r$, the energy
of the outgoing particle to is mapped $0 \le \widehat \Ecm' \le 1$
using Eq.~(\ref{Kalb-unit-base}) in the form of
$$
  \widehat \Ecm' = \frac{
  \Ecm' - E'_{\text{cm}, \text{min}} }
     { E'_{\text{cm}, \text{max}} - E'_{\text{cm}, \text{min}} }.
$$
Because of the
restriction that $0 \le r \le 1$, the parameter $r$ is mapped according to
\begin{equation}
  \widetilde r( \widehat \Ecm', E ) = r( \Ecm', E ).
  \label{map-Kalb-r}
\end{equation}

With these transformations, the number-preserving integral Eq.~(\ref{Inum})
takes the form
\begin{multline}
   \Inum_{gh,\ell} =
         \int_{\calE_g} dE \, \sigma ( E ) M(E) w(E) \widetilde \phi_\ell(E)
       \, \int_{\widehat \Ecm' } d\widehat \Ecm' \,
           \widehat \pi_E( \widehat \Ecm' \mid E) \\
        \int_{\mucm} d\mucm \,  P_\ell( \mulab ) \pi_\mu( \mucm \mid \Ecm', E ),
  \label{Inum-Kalb-corr}
\end{multline}
and the energy-preserving integral Eq.~(\ref{Ien}) becomes
\begin{multline}
  \Ien_{gh,\ell} =
        \int_{\calE_g} dE \, \sigma ( E ) M(E) w(E) \widetilde \phi_\ell(E)
       \, \int_{\widehat \Ecm' } d\widehat \Ecm' \,
           \widehat \pi_E( \widehat \Ecm' \mid E) \\
        \int_{\mucm} d\mucm \,  P_\ell( \mulab ) \pi_\mu( \mucm \mid \Ecm', E ) \Elab' .
  \label{Ien-Kalb-corr}
\end{multline}
The subscripts on $\mu$ serve to emphasize the facts
that the argument $\mulab$ of the Legendre polynomial
$P_\ell( \mulab )$ in Eqs.~(\ref{Inum-Kalb-corr}) and (\ref{Ien-Kalb-corr}) is
the direction cosine of the outgoing particle in laboratory coordinates,
while the integration variable $\mucm$ is the direction cosine in
center-of-mass coordinates.
Specifically, $\Elab' $ depends on $E$ and $\mucm$ according to equation Eq.~(\ref{E_lab}),
and $\mulab$ is given by Eq.~(\ref{get_mu}).

Because the energy probability density $\pi_E( \Ecm' \mid E)$ data are given
in the center-of-mass frame, the identification of the region of integration
over $\widehat \Ecm'$ and~$\mucm$ in Eqs.~(\ref{Inum-Kalb-corr})
and~(\ref{Ien-Kalb-corr}) involves the geometric considerations
presented for tabular center-of-mass data in Section~\ref{Sec:boost-geometry}.
For a given incident energy $E$ in bin $\calE_g$,
the regions of integration over
$\widehat \Ecm'$ and $\mucm$ in Eqs.~(\ref{Inum-Kalb-corr})
and~(\ref{Ien-Kalb-corr}) depend on how the domains for data interpolation
$ \widehat E'_{\text{cm},j-1} \le \widehat \Ecm' \le \widehat E'_{\text{cm},j}$
 intersect
the  $\calE_h'$ outgoing laboratory energy bin.
The situation for a fixed incident
energy~$E$ is illustrated in Figure~\ref{Fig:boost-regions}.
The half annulus
$$
  E'_{\text{cm}, j-1} \le \Ecm' \le  E'_{\text{cm}, j}
$$
is derived from the Kalbach-Mann data.  The region of integration
over $\mucm$ and $\Ecm'$ for fixed incident energy $E$ is the intersection of
these two half annuli, and it is shaded dark gray in Figure~\ref{Fig:boost-regions}.

\subsection{The input file for the Kalbach-Mann model}
The data identifier in Section~\ref{data-model} for the
Kalbach-Mann model is\\
  \Input{Process: Kalbach spectrum}{}\\
and the data are always in the center-of-mass frame\\
  \Input{Product Frame: CenterOfMass}{}\\
Currently, only a Newtonian boost to the laboratory frame is
implemented.

The masses of the particles $a$, $A$, $C$, $b$, and~$B$ in
the reaction Eq.~(\ref{Kalbach-reaction}) are input in Section~\ref{model-info}
of the input file\\
  \Input{Projectile's mass:}{$\myi$} \\
 \Input{Target's mass:}{$\mtarg$} \\
 \Input{Compound's mass:}{$m_C$} \\
 \Input{Product's mass:}{$\myo$} \\
 \Input{Residual's mass:}{$\mres$}\\
The units used for these masses are arbitrary, but they must be the
same for all particles.

The number of protons $Z_A$ and the atomic number $A_A$ of the
target are needed for the computation of $S_a$ in Eq.~(\ref{def-Sa}).
This information is entered into the input file as
$$
  \textsf{ZA}_A = 1000Z_A + A_A,
$$
from which $A_A$, $Z_A$, and the number of neutrons $N_A = A_A - Z_A$
are easily computed.  Corresponding numbers $\textsf{ZA}_a$ for the projectile and
$\textsf{ZA}_b$ for the emitted particle are also given.  The numbers $\textsf{ZA}_C$ for
the compound nucleus and $\textsf{ZA}_B$ for the residual may be calculated
using
\begin{align*}
  \textsf{ZA}_C &= \textsf{ZA}_A + \textsf{ZA}_a,\\
  \textsf{ZA}_B &= \textsf{ZA}_C - \textsf{ZA}_b.
\end{align*}
This section of the input file is therefore\\
  \Input{Projectile's ZA:}{$\textsf{ZA}_a$} \\
 \Input{Target's ZA:}{$\textsf{ZA}_A$} \\
 \Input{Product's ZA:}{$\textsf{ZA}_b$}

 The remainder of the input file consists of tables of $\pi_E( \Ecm' \mid E)$
 and the parameter~$r$ in Eq.~(\ref{Kalbach-eta}) as functions of $E$ and~$\Ecm'$.
 There may also be a table of values of $a$ to be used in place of the expression
 Eq.~(\ref{Kalbach-a}).

 The format for the probability density
 $\pi_E( \Ecm' \mid E)$ is\\
   \Input{Kalbach probabilities:}{$n = K$}\\
  \Input{Incident energy interpolation:}{probability interpolation flag}\\
  \Input{Outgoing energy interpolation:}{list interpolation flag}\\
followed by $K$ blocks of the form\\
 \Input{Ein: $E$:}{$n = J$}\\
with $J$ pairs of values of $\Ecm'$ and~$\pi_E( \Ecm' \mid E)$.
The flag for interpolation with respect to incident energy $E$ is
one of those for probability densities in Section~\ref{interp-flags-probability},
while that for the outgoing energy
is one for simple lists.

The table for the $r$ parameter is of the form\\
   \Input{Kalbach r parameter:}{$n = K$}\\
  \Input{Incident energy interpolation:}{unscaled interpolation flag}\\
  \Input{Outgoing energy interpolation:}{list interpolation flag}\\
followed by $K$ blocks of the form\\
 \Input{Ein: $E$:}{$n = J$}\\
with $J$ pairs of values of $\Ecm'$ and~$r( \Ecm',  E)$.
The flag for interpolation with respect to incident energy $E$ is
one of those for unscaled Kalbach-Mann data in Section~\ref{interp-flags-Kalbach-r},
while that for the outgoing energy
is one for simple lists.

The format for the Kalbach-Mann $a$ parameter is the same as that for $r$,
with ``r'' replaced by ``a''.  \textit{The tables for $\pi_E( \Ecm' \mid E)$, $r$,
and~$a$ must be given at the same incident energies, and at each
incident energy~$E$, the ranges of outgoing energies~$E'$ must also agree.}

An example of the content of Section~\ref{model-info} of the input
file for Kalbach-Mann data is as follows.  All energies are in MeV.\\
 \Input{Product Frame: centerOfMass}{}\\
 \Input{\# masses}{}\\
  \Input{Projectile's mass: 1.008665}{}\\
 \Input{Target's mass: 56.935394}{}\\
 \Input{Compound's mass: 57.933276}{}\\
 \Input{Product's mass: 1.008665}{}\\
 \Input{Residual's mass: 56.935394}{}\\
 \Input{\# ZA numbers}{}\\
  \Input{Projectile's ZA: 1}{}\\
 \Input{Target's ZA: 26057}{}\\
 \Input{Product's ZA: 1}{}\\
 \Input{\# Kalbach-Mann probability data}{}\\
 \Input{Kalbach probabilities:  n = 12}{}\\
 \Input{Incident energy interpolation: lin-lin unitbase}{}\\
 \Input{Outgoing energy interpolation: flat}{}\\
 \Input{ Ein: 7.781480e+00:   n = 2}{}\\
 \Input{ \indent 0.000000e+00   1.000000e+06}{}\\
 \Input{ \indent 1.000000e-06   0.000000e+00}{}\\
 \Input{ Ein: 7.800000e+00:   n = 7}{}\\
 \Input{ \indent 0.000000e+00   7.375605e+00}{}\\
 \Input{ \indent 1.473426e-03   1.472617e+01}{}\\
 \Input{ \indent 3.437994e-03   3.676034e+01}{}\\
 \Input{ \indent 7.367130e-03   5.717426e+01}{}\\
   \Input{ \indent 1.473426e-02  8.186549e+00}{}\\
  \Input{ \indent 3.437994e-02  5.948511e+00}{}\\
  \Input{ \indent 7.367130e-02  1.000000e-30}{}\\
 \Input{ $\cdots$}{}\\
 \Input{ Ein: 2.000000e+01:  n = 53}{}\\
  \Input{ \indent 0.000000e+00  2.063824e-03}{}\\
  \Input{ \indent 1.473426e-03  3.887721e-03}{}\\
  \Input{ \indent 3.437994e-03  9.245874e-03}{}\\
  \Input{ \indent 7.367130e-03  1.805939e-02}{}\\
  \Input{ \indent 1.473426e-02  3.554576e-02}{}\\
  \Input{ \indent 3.437994e-02  8.408804e-02}{}\\
  \Input{ \indent 7.367130e-02  1.261293e-01}{}\\
  \Input{ \indent }{ $\cdots$}\\
  \Input{ \indent 1.154184e+01  1.604784e-03}{}\\
  \Input{ \indent 1.203298e+01  1.000000e-30}{}\\
 \Input{\# Kalbach-Mann r data}{}\\
  \Input{Kalbach r parameter:  n = 12}{}\\
 \Input{Incident energy interpolation: lin-lin unscaledunitbase}{}\\
 \Input{Outgoing energy interpolation: flat}{}\\
 \Input{ Ein: 7.781480e+00:   n = 2}{}\\
 \Input{ \indent 0.000000e+00   0.000000e+00}{}\\
 \Input{ \indent 1.000000e-06  0.000000e+00}{}\\
 \Input{ Ein: 7.800000e+00:   n = 7}{}\\
 \Input{ \indent 0.000000e+00   4.272290e-02}{}\\
 \Input{ \indent 1.473426e-03   2.992310e-02}{}\\
 \Input{ \indent 3.437994e-03   1.833870e-02}{}\\
 \Input{ \indent 7.367130e-03   1.427320e-02}{}\\
   \Input{ \indent 1.473426e-02  1.829320e-02}{}\\
  \Input{ \indent 3.437994e-02  1.611740e-02}{}\\
  \Input{ \indent 7.367130e-02  1.590910e-02}{}\\
 \Input{ $\cdots$}{}\\
 \Input{ Ein: 2.000000e+01:  n = 53}{}\\
  \Input{ \indent 0.000000e+00  7.037570e-02}{}\\
  \Input{ \indent 1.473426e-03  4.957320e-02}{}\\
  \Input{ \indent 3.437994e-03  3.056740e-02}{}\\
  \Input{ \indent 7.367130e-03  2.555550e-02}{}\\
  \Input{ \indent 1.473426e-02  1.908500e-02}{}\\
 \Input{ \indent  $\cdots$}{}\\
 \Input{ \indent 1.154184e+01  9.548000e-01}{}\\
  \Input{ \indent 1.203298e+01  9.656400e-01}{}

\section{The $n$-body phase space model}
The $n$-body phase space model gives the probability density for
the energy of an outgoing particle in center-of-mass coordinates.
The formula is derived from the volume in phase space occupied
by the particles, subject to the constraints of conservation
of energy and momentum.  The model uses Newtonian mechanics.

In the \ENDF\ manual~\cite{ENDFB}
there are two scenarios for this model: (1) a discrete 2-body reaction
followed by break-up of the excited residual, and (2) break-up
induced by the collision.  In the first case, the $n$-body phase space
model treats only the particles emitted in the break-up of the excited
residual, not the one from the initial collision.  The total kinetic energy $\Estar$
of the outgoing particles treated by the model therefore depends on
the scenario.  For both scenarios, the number~$n$ of outgoing particles
ought to be greater than~2, because the breakup into 2 particles may
be treated as a discrete 2-body reaction.

In the case of break-up following a discrete 2-body
reaction, the analysis is in the frame in which the residual from
the initial collision is stationary.  The total kinetic energy of the
outgoing particles involved is then
$$
  \Estar = Q_{\textrm{res}},
$$
where $Q_{\textrm{res}}$ is
the energy of the break-up of the excited residual.  The \gettransfer\
code currently does not implement this scenario, because no data
in the \ENDFdata\ library~\cite{ENDFdata} currently use it.
The \ENDFdata\ library does contain one reaction for which the data are marked
as an $n$-body reaction following a knock-on collision.  But since the subsequent
breakup is into only 2 particles, the \gettransfer\ code treats the reaction
as a sequence of two discrete 2-body reactions as discussed in
Section~\ref{Sec:2-step-2-body}.

For the break-up of a compound nucleus following the collision of a projectile
with a stationary target in the laboratory frame, the total kinetic energy $\Estar$
of the outgoing particles in the center-of-mass frame is the sum of two
components, the $Q$ of the reaction plus the energy of the initial collision in the
center-of-mass frame.  For an incident
particle of mass $m_i$ and energy $E$ in the laboratory frame hitting a
stationary target of mass $\mtarg$, this collision energy in the center-of-mass frame is
$$
  \frac{\mtarg E}{\myi + \mtarg}.
$$
Consequently, in this scenario the total center-of-mass kinetic energy for all
outgoing particles is
\begin{equation}
  \Estar = Q + \frac{\mtarg E}{\myi + \mtarg}.
  \label{def-Estar}
\end{equation}

The details of the $n$-body phase space model are as follows.
Consider a particular outgoing particle, and suppose that its mass is~$\myo$.
Then conservation of energy and
momentum implies that the maximum kinetic energy of this particle
in the center-of-mass frame is given by
\begin{equation}
  \Emax = \frac{(M_t - \myo) \Estar}{M_t},
  \label{def-Emax}
\end{equation}
where $M_t$ is the total mass of the outgoing particles covered by
the $n$-body phase space model.

Suppose that $n$ is the number of particles resulting from the break-up
reaction.  For an outgoing particle with mass $\myo$,
let $\Emax$ be as in Eq.~(\ref{def-Emax}).
Then in the $n$-body phase space model, the energy probability density
that this outgoing particle will have energy $\Ecm'$ with $0 \le \Ecm' \le \Emax$
is given by
\begin{equation}
  \picm(\Ecm' \mid E ) = C_n
     \sqrt{\Ecm'}\,
     (\Emax - \Ecm')^{(3n - 8)/2}.
  \label{n-body-probability}
\end{equation}
Note that this probability density is isotropic in the center-of-mass frame.
Furthermore, the relation Eq.~(\ref{n-body-probability}) was derived using Newtonian
mechanics.

The normalization constant $C_n$ in Eq.~(\ref{n-body-probability}) is best
represented in terms of the beta function
\begin{equation}
  B(\alpha, \beta) =
   \int_0^1 dt \, t^{\alpha - 1} (1 - t)^{\beta - 1} =
   \frac{\Gamma(\alpha) \Gamma(\beta)}{\Gamma( \alpha + \beta)}.
  \label{beta-func}
\end{equation}
With this notation, it is seen that
\begin{equation}
  \frac{1}{C_n} = B\left(\frac{3}{2}, \frac{3n - 6}{2} \right)
    {\Emax}^{(3n - 5)/2}.
  \label{norm}
\end{equation}

\subsection{Geometry of the $n$-body phase space model}
The construction of Figure~\ref{Fig:boost-regions}
made use of the fact that the tabular data required the
consideration of ranges of energy $\Ecm'$ of the outgoing particle
between the tabulated values,
\begin{equation}
  E'_{\text{cm},j-1} \le \Ecm' \le E'_{\text{cm},j}.
  \label{KalbachEcm}
\end{equation}
Here, the limiting values $E'_{\text{cm},j-1}$ and $E'_{\text{cm},j}$
depend on the energy $E$ of the incident particle according to the
principles of unit-base interpolation in Eq.~(\ref{Kalb-unit-base}).

For the $n$-body phase space model, however, the range of
center-of-mass energies of the outgoing particle is
\begin{equation}
  0 \le \Ecm' \le \Emax,
  \label{nBodyEcm}
\end{equation}
where $\Emax$ is as in Eq.~(\ref{def-Emax}).
That is, for the $n$-body phase space
the annular ring Eq.~(\ref{KalbachEcm}) in Figure~8.1 is replaced by the
interior of the semicircle Eq.~(\ref{nBodyEcm}).

\subsection{Quadrature for the $n$-body phase space model}
\label{Sec:n-body-quadrature}
It is clear from Eq.~(\ref{n-body-probability})
that in the integrals in Eqs.~(\ref{Inum}) and~(\ref{Ien}) the
integrands with respect to outgoing energy~$\Ecm'$ have a
$\sqrt{\Ecm'}$ singularity.  The \gettransfer\ code has a parameter~$\delta_s$
such that if integration of Eqs.~(\ref{Inum}) or~(\ref{Ien}) with respect
to~$\Ecm'$ is over an interval $a \le \Ecm' \le b$ with $b \le \delta_s  \Emax$,
then first-order Gaussian integration with weight~$\sqrt{\Ecm' }$ is used.
Furthermore, if $a < \delta_s  \Emax < b \le (1 - \delta_s ) \Emax$ for such an integral, then
$\sqrt{\Ecm' }$ weighted Gaussian integration is used on
the subinterval $a \le \Ecm'  \le \delta_s  \Emax$ and standard
Gaussian integration on $\delta_s  \Emax \le \Ecm'  \le b$.
See Section~\ref{Sec:sqrt-quad} for instructions on setting the
value of~$\delta_s$.  See Section~\ref{Sec:QuadratureMethods}
for control over whether or not adaptive Gaussian quadrature is used.

When this model is used with $n = 3$, the singularity
$\sqrt{\Emax - \Ecm'}$ is handled in a similar fashion.  In this case,
first-order Gaussian quadrature with weight $\sqrt{\Emax - \Ecm'}$
is used for integrals with respect to $\Ecm'$ which overlap with
the interval $(1 - \delta_s ) \Emax < \Ecm' \le \Emax$.

\subsection{Input file for the $n$-body phase space model}
The data identifier in Section~\ref{data-model} for the
$n$-body phase space model is\\
  \Input{Process: phase space spectrum}{}\\
and the data are always in the center-of-mass frame\\
  \Input{Product Frame: CenterOfMass}{}\\
Currently, only a Newtonian boost to the laboratory frame is
implemented.

In the model-dependent Section~\ref{model-info} of the input file,
the computation of $\Estar$ in Eq.~(\ref{def-Estar}) requires the
reaction's $Q$ value, as well as the masses $\myi$ of the projectile
and $\mtarg$ of the target.  The units used for the masses are arbitrary,
but the same units must be used for all particles.  The $Q$ value must be
in the same units as the energy bins.  This information is input using
the commands\\
 \Input{Q value:}{$Q$} \\
  \Input{Projectile's mass:}{$\myi$} \\
 \Input{Target's mass:}{$\mtarg$}

For the calculation of $\Emax$ in Eq.~(\ref{def-Emax}), the mass $\myo$
is needed, along with the total mass $M_t$ of the outgoing particles covered
by the $n$-body phase space model.  This information is input using\\
 \Input{Product's mass:}{$\myo$} \\
 \Input{Total mass:}{$M_t$}\\
The units used for these masses must be the
same as is used for the other particles.

Finally, the probability density in Eq.~(\ref{n-body-probability}) requires the number
of particles $n$ in the model, and this is given by\\
 \Input{Number of particles:}{$n$}

A sample Section~\ref{model-info} of the input file for the
$n$-body phase space model is\\
 \Input{Product Frame: CenterOfMass}{}\\
 \Input{Q value: -2.225002}{}\\
 \Input{Projectile's mass: 1.008665}{}\\
 \Input{Target's mass: 2.014102}{}\\
 \Input{Product's mass: 1.008665}{}\\
 \Input{Total mass: 3.0246030}{}\\
 \Input{Number of particles: 3}{}


\documentclass{article}
\usepackage{amsmath, amssymb}
\usepackage{minipage}
\usepackage{url}
\usepackage[left=2cm, right=2cm, top=2cm, bottom=2cm]{geometry}

\newcommand{\code}[1]{\mathsf{#1}}

\title{TLA PM -- Quick FAQ}
\author{Jael Kriener}

\begin{document}
\maketitle

\section{Introduction}
This is meant to be a quick reference guide to help the reader
develop proofs. The code-patterns below will work in specific
situations. There are other ways of writing the same things in
TLA+ and the keywords used below can be used in other situations.
So please take this as a starting point, and refer to the TLA+ Guide\footnote{
\url{http://research.microsoft.com/en-us/um/people/lamport/tla/tla2-guide.pdf}}
and Chapter 10 of the Hyperbook\footnote{\url{http://research.microsoft.com/en-us/um/people/lamport/tla/hyperbook.html}} to go in further breadth and depth.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%            HOW DO I PROVE ?            %%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{How Do I Prove ... ?}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{A \wedge B}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
To prove $A \wedge B$, we have to prove both $A$ and $B$. \\

\vspace{5pt}

Therefore, we need to write (something like):

\vspace{20pt}
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{300pt}
\begin{verbatim}
<1>1 A
    ...
<1>2 B
    ...
<1>q QED
    BY <1>1, <1>2
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{A \vee B}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
To prove $A \vee B$, it is enough to prove either $A$ or $B$. \\

\vspace{5pt}

Therefore, we need to write (something like):
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 A
    ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}
\hspace{5pt} \vline \hspace{25pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 B
    ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{A \Rightarrow B}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
To prove $A \Rightarrow B$, we have to prove $B$ under the assumption that $A$. \\

\vspace{5pt}

Therefore, we need to write (something like):
\vspace{10pt}
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 ASSUME A
     PROVE  B
       ...
<1>q QED
    BY <1>1
\end{verbatim}
\vspace{1pt}
\end{minipage}
\hspace{5pt} \vline \hspace{15pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 SUFFICES
        ASSUME A
        PROVE  B
   ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{\sim A}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
I think of proving $\sim A$, as proving $A \Rightarrow F$, where `$F$'
is any contradiction; it could be `\verb|FALSE|', but it could also be
something like $2 \leq 1$, or $a \le b \wedge b \le a$ for $a, b \in Int$ \\

\vspace{5pt}

Therefore, we need to write (something like):
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 ASSUME A
     PROVE  F
       ...
<1>q QED
    BY <1>1
\end{verbatim}
\vspace{5pt}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{\forall\ x : P(x)}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
Again, proving an universal quantifier is a lot like proving an
implication. To prove $\forall x : P(x)$ we need to prove
$P(x)$ for \emph{any} $x$, i.e. for an $x$ about which we
make no other assumptions.\\

\vspace{5pt}

The way to write that in TLA+ is (something like):
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 ASSUME NEW x
     PROVE  P(x)
       ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}

\subsubsection{$\code{\forall\ x \in S : P(x)}$}
\vspace{10pt}
\begin{minipage}{230pt}
When a universal quantifier is bounded, i.e. comes with a domain
assumption, that assumption can be used in the prove. So to prove
$\forall x \in S : P(x)$, we need to prove $P(x)$ for
\emph{any} $x \in S$, i.e. for an $x$ about which we make
no assumptions \emph{other than} that it is in $S$. \\

\vspace{5pt}

The way to write that in TLA+ is (something like):
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 ASSUME NEW x \in S
     PROVE  P(x)
       ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{\exists\ x : P(x)}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
To prove an existential quantifier we need to provide a witness,
i.e. to prove $\exists x : P(x)$ we need to prove $P(a)$ for some
$a$ already in the context. \\

\vspace{5pt}
In TLA+ we can do that, either by simply proving $P(a)$
for some $a$, or by first declaring which $a$ we will use, by means of
the \verb|WITNESS|-keyword, and then proving $P(a)$.
The way to write that in TLA+ is (something like):
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 P(a)
    ...
<1>q QED
    BY <1>1
\end{verbatim}
\vspace{0pt}
\end{minipage}
\hspace{25pt} \vline \hspace{20pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1> WITNESS a
<1>1 P(a)
    ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}

\subsubsection{$\code{\exists\ x \in S : P(x)}$}
\vspace{10pt}
\begin{minipage}{230pt}
When an existential quantifier is bounded, i.e. comes with a domain
assumption, that assumption also needs to be proved. So to prove
$\exists x \in S : P(x)$, we need to prove both $a \in S$ and
$P(a)$ for some $a$ already in the context.\\

\vspace{5pt}
There are two things to notice about the \verb|WITNESS|-keyword here:
\begin{itemize}
  \item[a] Its syntax needs to correspond to the syntax of the
    existential quantifier it refers to; i.e. if the existential
    is bounded, the \verb|WITNESS|-statement requires a bound.

  \item[b] A bounded \verb|WITNESS|-step discharges the domain
    assumption, i.e. the obligation $a \in S$. However, the step does
    not take a proof. So at this point, it needs to be obvious, that
    $a \in S$.  When a bounded \verb|WITNESS|-step does not turn
    green, it is a good idea to insert a step ``\verb|<1> a \in S|''
    and prove that step.
\end{itemize}

\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 a \in S
    ...
<1>2 P(a)
    ...
<1>q QED
    BY <1>1, <1>2
\end{verbatim}
%\vspace{35pt}
\end{minipage}
\hspace{25pt} \vline \hspace{15pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1> WITNESS a \in S
<1>1 P(a)
    ...
<1>q QED
    BY <1>1
\end{verbatim}
\vspace{5pt}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\subsection{$\Box A$}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\subsection{$\Diamond A$}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%            HOW DO I USE ?              %%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
\section{How Do I Use ... ?}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{A \wedge B}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
To use $A \wedge B$, we don't have to actually do anything;
$A \wedge B$ in the context is as good as each $A$ and $B$ in
the context independently. \\

\vspace{5pt}

$A \wedge B$ enables us to write both:
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 A
    OBVIOUS
\end{verbatim}
\end{minipage}
\hspace{5pt} \vline \hspace{15pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 B
    OBVIOUS
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{A \vee B}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
To use $A \vee B$, we have to prove the current goal twice,
once assuming $A$, and once assuming $B$. \\

\vspace{5pt}

Probably the simplest way to use $A \vee B$, is by means of the
\verb|CASE|-keyword:

\vspace{15pt}
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 CASE A
    ...
<1>2 CASE B
    ...
<1>q QED
    BY <1>1, <1>2
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{A \Rightarrow B}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
$A \Rightarrow B$ in the context means that, as soon as we have proved
$A$, we can get $B$ straight away.  \\

\vspace{5pt}
$A \Rightarrow B$ in the context enables us to write:

\vspace{15pt}
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 A
    ...
<1>2 B
    BY <1>1
\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{\sim A}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
Again, I think it is useful to think of $\sim A$ as $A \Rightarrow F$,
for any $F$. That means that, if we have $\sim A$ in the context, and
we manage to prove $A$, we are done. \\

\vspace{5pt}

$\sim A$ in the context enables us to write:
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 A
     ...
<1>q QED
    BY <1>1
\end{verbatim}
\vspace{5pt}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{$\code{\forall\ x : P(x)}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
$\forall x : P(x)$ in the context allows us to assert $P(a)$ for
any $a$ in the context.
\vspace{5pt}

That is to say, for all \verb|a| in the context, it enables us to write:
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 P(a)
  OBVIOUS
\end{verbatim}
\vspace{5pt}
\end{minipage}

\subsubsection{$\code{\forall \ x \in S : P(x)}$}
\vspace{10pt}
\begin{minipage}{230pt}
A bounded universal quantifier of the form $\forall x \in S : P(x)$,
in the context allows us to assert $P(a)$ for
any $a$, as long as we can prove that $a \in S$.
\vspace{5pt}

That is to say, for all \verb|a| in the context, it enables us to write:
\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 a \in S
    ...
<1>2 P(a)
  BY <1>1
\end{verbatim}
\vspace{5pt}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
\subsection{$\code{\exists\ x : P(x)}$}
\hrule
\vspace{10pt}
\begin{minipage}{230pt}
An existential quantifier like $\exists x : P(x)$ in the context
allows us to introduce a new $a$ into the context, and assert that
$P(a)$.
\vspace{5pt}

There are different ways of doing that. One is with a simple
\verb|ASSUME/PROVE|; in that case the current goal \verb|G| has to be
repeated.  An alternative is to use the \verb|PICK|-keyword, which in
this situation is short-hand for \verb|SUFFICES-ASSUME/PROVE|.

\end{minipage}
%
\hspace{15pt} \vline \hspace{15pt}
%
%
\begin{minipage}{100pt}
\begin{verbatim}
<1>1 ASSUME NEW a,
            P(a)
     PROVE  G
      ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}
\hspace{0pt} \vline \hspace{10pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 PICK a : P(a)
    OBVIOUS

\end{verbatim}
\end{minipage}

\subsection{$\code{\exists\ x \in S : P(x)}$}
\vspace{10pt}
\begin{minipage}{230pt}
A bounded existential quantifier $\exists x \in S : P(x)$ in the context
allows us to introduce a new $a$ into the context, and assert both
that $a \in S$ and that $P(a)$.

\vspace{5pt}

The additional fact that $a \in S$ is added to the
\verb|ASSUME/PROVE|-step, as you would expect.
The \verb|PICK|-keyword also looks as we would expect.
\end{minipage}
%
\hspace{15pt} \vline \hspace{5pt}
%
%
\begin{minipage}{100pt}
\begin{verbatim}
<1>1 ASSUME NEW a,
            a \in S,
            P(a)
     PROVE  G
      ...
<1>q QED
    BY <1>1
\end{verbatim}
\end{minipage}
\hspace{10pt} \vline \hspace{10pt}
\begin{minipage}{80pt}
\begin{verbatim}
<1>1 PICK a \in S : P(a)
    OBVIOUS

\end{verbatim}
\end{minipage}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\subsection{$\Box A$}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\subsection{$\Diamond A$}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%         FREQUENT SITUATIONS           %%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
\section{Why Doesn't This Turn Green?}

\end{document}


\subsection{Functions}

We can call a function:
\(y=f(x)\)

Here \(x\) are the local variables to be used.

However the global state may also affect the outcome, so we have:

\(y=f(x,z)\)

As a result, calling the same function twice with the same inputs can have different outputs.

Side effects. If a function modifies the state outside of its local variables it has side effects.


% -*-latex-*-

\title{Orbiter Technical Notes: Inertia calculations for composite vessels}
\author{Martin Schweiger}
\date{September 28, 2017}

\documentclass[a4paper]{article}
\usepackage[dvips]{graphicx}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{cite}
\usepackage{setspace}
\usepackage{times}

\newcommand\mat[1]{\mathsf{#1}}

\begin{document}
\maketitle

\section{Introduction}
This document describes the method Orbiter uses to define the inertial behaviour for composite vessels from the parameters of its components.

\section{Definitions}
To describe the dynamics of a rigid body we use Euler's rotation equations that describe the rotation of the body in the rotating system:
\begin{equation}
\mat{I} \dot{\vec{\omega}} + \vec{\omega} \times (\mat{I}\vec{\omega}) = \vec{M}
\end{equation}
where $\vec{\omega}$ are the components of angular velocity around the three main vessel axes, $\vec{M}$ are the applied torques, and $\mat{I}$ is the inertia matrix.

In the principal body frame, the inertia matrix is diagonal, where diagonal elements $I_n\;(n=1,2,3)$ are the principal moments of inertia (PMI). We then get
\begin{equation}
\begin{split}
  I_1 \dot\omega_1 + (I_3 - I_2) \omega_2 \omega_3 &= M_1 \\
  I_2 \dot\omega_2 + (I_1 - I_3) \omega_3 \omega_1 &= M_2 \\
  I_3 \dot\omega_3 + (I_2 - I_1) \omega_1 \omega_2 &= M_3
\end{split}
\end{equation}
Note that Orbiter assumes vessels to be defined in the principal frame but does not enforce it, that is, only the diagonal elements of $\mat{I}$ are considered. For most vessel layouts, an intrinsic symmetry is present, and the vessel frame naturally aligns closely with the principal frame, so that neglecting the off-diagonal elements of $\mat{I}$ incurs a small error. For composite structures this may not be true, so a more general framework may be introduced in the future.

\section{Composite structures}
In spaceflight scenarios, rigid structures may commonly be formed by connecting individual components (launch stack composed from individual stages, spacecraft docked at a space station, Apollo CSM+LM assembly, etc.) These rigid assemblies act as a single body under rotation, governed by its own composite PMI.

While the composite PMI may be pre-calculated for commonly encountered arrangements, not all combinations are predictable. In Orbiter, any vessels with suitable docking ports can be connected to form arbitrary new ``super-vessels'' of two or more components. It is therefore necessary to find a method to compute the composite PMI from the inertia parameters of the individual components and the geometry of the assembly.
Orbiter uses the following method:
\begin{itemize}
\item Represent a vessel by a small number of discrete point masses arranged so that they generate the same PMI as the original vessel.
\item Transform the point masses of all individual vessels into the common barycentric frame of the super-vessel.
\item Compute the PMI of the super-vessel by summing over the point masses of all individual components.
\end{itemize}

\subsection{Point mass representation of a vessel}
In general, the PMI components of an object occupying a volume $V$ with mass density distribution $\rho(\vec{r}),\; \vec{r}\in V$ are given by
\begin{equation}
\begin{split}
  I_1 &= \int_V \rho(\vec{r}) (y^2 + z^2) d\vec{r} \\
  I_2 &= \int_V \rho(\vec{r}) (z^2 + x^2) d\vec{r} \\
  I_3 &= \int_V \rho(\vec{r}) (x^2 + y^2) d\vec{r}
\end{split}
\end{equation}
with $\vec{r} = \lbrace x,y,z \rbrace$.
For an object composed of $n$ individual point masses $m_i$ at locations $\vec{r}_i$ this simplifies to
\begin{equation}
\begin{split}
  I_1 &= \sum_{i=1}^n m_i (y_i^2 + z_i^2) \\
  I_2 &= \sum_{i=1}^n m_i (z_i^2 + x_i^2) \\
  I_3 &= \sum_{i=1}^n m_i (x_i^2 + y_i^2)
\end{split}
\end{equation}

We can now represent a vessel with arbitrary PMI values by 6 point masses that produce the same PMI values:
\begin{equation}
\begin{split}
  \hat{\vec{r}}_{1,2} &= \lbrace \pm \hat x, 0, 0 \rbrace \\
  \hat{\vec{r}}_{3,4} &= \lbrace 0, \pm \hat y, 0 \rbrace \\
  \hat{\vec{r}}_{5,6} &= \lbrace 0, 0, \pm \hat z \rbrace
\end{split}
\end{equation}
and $m_i = \hat m = m/6,\; i=1..6$, given vessel mass $m$.
To compute the axis offsets $\hat x, \hat y, \hat z$ of the point masses we note that
\begin{equation}
\begin{split}
  I_1 &= \hat m (2 \hat y^2 + 2 \hat z^2) \\
  I_2 &= \hat m (2 \hat z^2 + 2 \hat x^2) \\
  I_3 &= \hat m (2 \hat x^2 + 2 \hat y^2)
\end{split}
\end{equation}
and thus
\begin{equation}\label{eq:smp_ofs}
\begin{split}
\hat x &= \frac{1}{2} \sqrt{\left| -\frac{I_1}{\hat m} + \frac{I_2}{\hat m} + \frac{I_3}{\hat m} \right|} \\
\hat y &= \frac{1}{2} \sqrt{\left| \frac{I_1}{\hat m} - \frac{I_2}{\hat m} + \frac{I_3}{\hat m} \right|} \\
\hat z &= \frac{1}{2} \sqrt{\left| \frac{I_1}{\hat m} + \frac{I_2}{\hat m} - \frac{I_3}{\hat m} \right|}.
\end{split}
\end{equation}
It is left to the reader to confirm that this point sample arrangement generates the correct PMI values.

\subsection{Super-vessel definition}
A super-vessel is a composite structure arranged by rigid assembly of individual vessels where the geometry is defined by the position and orientation of the participating docking ports of the component vessels.

The origin of the super-vessel frame is given by the barycentre of the assembly. It should be noted that the origin can shift continuously relative to the vessel assembly if the masses of the component vessels change (e.g. as a result of fuel consumption).

The orientation of the super-vessel frame is currently arbitrarily set to the orientation of the first vessel in the assembly. No attempt is made to rotate to the principal frame. This may need some thought.

With this arrangement, we can define transformations for each component vessel $j$ into the supervessel frame:
\begin{equation}
  \vec{r}_j^S = \mat{R}_j \vec{r}_j + \vec{r}_j^0,
\end{equation}
where $\mat{R}_j$ is a rotation matrix and $\vec{r}_j^0$ is the position of the vessel CoG in the super-vessel frame.
The transformation of the point-mass representations of all participating vessels into the super-vessel frame is given by
\begin{equation}
\hat{\vec{r}}_{ji}^S = \mat{R}_j \hat{\vec{r}}_{ji} + \vec{r}_j^0, \; j=1..N, \; i=1..6,
\end{equation}
where $N$ is the number of participating vessels.
We can now assemble the components $I_n^S$ of the super-vessel PMI by summing over the point samples of all vessels:
\begin{equation}
\begin{split}
I_1^S & = \sum_{j=1}^N \sum_{i=1}^6 \hat m_j ([\hat y_{ji}^S]^2 + [\hat z_{ji}^S]^2)\\
I_2^S & = \sum_{j=1}^N \sum_{i=1}^6 \hat m_j ([\hat z_{ji}^S]^2 + [\hat x_{ji}^S]^2)\\
I_3^S & = \sum_{j=1}^N \sum_{i=1}^6 \hat m_j ([\hat x_{ji}^S]^2 + [\hat y_{ji}^S]^2)
\end{split}
\end{equation}

\section{Mass-normalised PMI}
It should be noted that Orbiter uses \emph{mass-normalised} PMI values $\tilde I_n = I_n/m$, which has the advantage that PMI values can remain unchanged even if the vessel mass changes. All Orbiter API calls by convention return and expect $\tilde I_n$ instead of $I_n$. Applying this convention to the super-vessel definition yields
\begin{equation}
\tilde{I}_n^S = \frac{I_n^S}{\sum_{j=1}^N m_j}
\end{equation}
Likewise, for the computation of the sample offsets in Eq.~\ref{eq:smp_ofs} we can write
\begin{equation}
  \hat x = \frac{1}{2} \sqrt{\left| -\frac{\tilde{I}_1 m}{\hat m} + \frac{\tilde{I}_2 m}{\hat m} + \frac{\tilde{I}_3 m}{\hat m} \right|} =
  \sqrt{\frac{3}{2} \left| -\tilde{I}_1 + \tilde{I}_2 + \tilde{I}_3 \right|}
\end{equation}
with corresponding expressions for $\hat y$ and $\hat z$.

\end{document}