\chapter{Sized Dependent Types} \label{ch:sized-dep-types}

\input{figures/sized.tex}
\input{figures/ind.tex}

This chapter can be divided into two halves:
the first gives the formal description of the syntax, judgements, and rules of \lang,
while the second provides a number of examples written in \lang to show how sized types can be used.
They are kept separate so that the examples don't detract from the formal description
and vice versa, but can be read in parallel;
the examples provide intuition for understanding the rules,
while the rules ensure proper understanding of why the examples are correct.

In the sections to follow,
I use ellipses \new{$\seq$} as metanotation for denoting a repeated sequence of some syntactic construct,
overlines \new{$\vec{\phantom{I}}$} for sequences of variables or terms specifically (\eg $\vec{z}$, $\vec{p}$),
and \new{$\mt$} for denoting an empty sequence (particularly in the context of environments).
Irrelevant constructs are omitted using an underscore \new{$\any$}.
Metafunctions are introduced in the prose as needed.

\section{Base \lang}

Although sized types are quite pointless without any inductive types to be sized,
I present in this subsection the sublanguage of \lang without naturals or well-founded trees
to not only get the preliminary details out of the way first,
but also to show that the sublanguage is independent of the chosen inductive types.

\FigSyntax{fig:syntax}
\cref{fig:syntax} gives its syntax, which consists of universes $U$,
sizes $s$, and terms $e$, which includes term functions and size abstractions.
Note that the hierarchy of universes above $\Prop$ start at $\Type{1}$, not $\Type{0}$.
Most judgements use two environments: a term environment $\Gamma$ with assumptions $\annot{x}{\tau}$
and type-annotated definitions $\define{x}{\tau}{e}$,
and a size environment $\Phi$ with unbounded and bounded size variables.
I also use the assumption environment%
\footnote{These are conventionally called \emph{telescopes}\index{telescopes} due to \citet{telescope}.}
$\Delta$ as a shorthand when writing nested expressions with assumptions;
in particular, letting for instance $\Delta_{xy} = \annot{x}{\sigma_1}, \annot{y}{\sigma_2}$,
I use \new{$\arr*{\Delta_{xy}}{\tau}$} to mean $\funtype{x}{\sigma_1}{\funtype{y}{\sigma_2}{\tau}}$.
Similarly, I use \new{$\arr*{\sigma}{\tau}$} to mean the nondependent function type $\funtype{\any}{\sigma}{\tau}$
As a loose convention, I use $\tau, \sigma$ for type-like terms,
$P$ for the \emph{motive} of eliminators,
$z$ for variables representing constructor arguments, and
$f, g$ for variables representing functions.

As mentioned in \cref{ch:introduction}, the judgement forms of \lang include
reduction, its various closures, $\alpha$-cumulativity, subtyping, and typing.
On top of those, there are also judgement forms for subsizing, sizes,
and well-formedness of size and term environments.

\FigRed{fig:reduction}
The reduction rules and their reflexive, transitive closure are described in \cref{fig:reduction}.
\new{$\subst{e}{x}{e'}$} denotes capture-avoiding substitution of $x$ for $e'$ within $e$,
and correspondingly \new{$\subst{e}{x_1, \seq, x_n}{e_1, \seq, e_n}$} denotes simultaneous substitution.
For every syntactic form of a composite term there is a corresponding congruence rule,
which is summarized by the last reduction rule using substitution;
the full set of rules can be found in \cref{app:cong:red}.
By convention, the reduction rules for function applications are also referred to as $\beta$-reduction,
for $\kw{let}$ expressions as $\zeta$-reduction,
and for defined variables as $\delta$-reduction.

These rules can be thought of as a description of nondeterministic evaluation of open terms,
``running'' from the left term to the right.
Separating them into reduction rules that only step once somewhere in the term
and their reflexive, transitive closure,
as opposed to the convention used by \eg \citet{wjb}
where $\rhd^*$ corresponds to the reflexive, transitive, \emph{compatible} closure,
allows for the usual proof techniques to prove confluence.

\FigSubtype{fig:subtyping}
Rather than a single subtyping\index{subtyping} judgement like in
\GCC\index{Calculus of Constructions!Generalized \textasciitilde},
I use the same presentation as MetaCoq\index{MetaCoq}
and split it into a subtyping judgement
and a separate $\alpha$-cumulativity\index{$\alpha$-cumulativity} judgement,
listed in \cref{fig:subtyping}.
This overcomes some technical proof complications specific to the syntactic model
that appear in the single-judgement presentation due to the transitivity rule.
Aside from the expected cumulativity of universes,
the function type and size quantification are covariant in the codomain
(\ie are $\alpha$-cumulative when their codomains are),
while remaining invariant in the domain\punctstack{.}%
\footnote{The domain could be made contravariant instead if function type subtyping
in \CICE were similarly contravariant,
but to my knowledge, there is no such variant of CIC with untyped conversion\index{conversion}
and without $\eta$-conversion that has been proven consistent.}
All other types are invariant, as reflected by \rref{acum-refl}.
A term is then a subtype of another if they are confluent up to $\alpha$-cumulativity.
% Conversion can be defined as the confluence of two terms,
% but conversion isn't needed for any judgements so I exclude the definition.

Notably, \lang does \emph{not} have a notion of $\eta$-conversion\index{$\eta$-conversion}
in either the reduction rules or in the subtyping rules,
which would otherwise allow conversion between $\fun{x}{\tau}{\app{f}{x}}$ and $f$.
Mixing $\eta$-conversion and untyped conversion is notoriously difficult~\citep{eta},
and remains to date an unresolved problem in MetaCoq\index{MetaCoq}, so I exclude it here.

\clearpage % TODO: clearpage
\FigSubsize{fig:subsizing}
\cref{fig:subsizing} describes a preorder on sizes such that
the successor operator is monotonic with respect to the order.
The base size $\circ$ is smaller than all sizes,
and the strict preorder $\bound{\alpha}{s}$ arising from bounded quantification or abstraction
is defined as $\sss{\alpha} \mathrel{\leqslant} s$.
An additional size judgement ensures well-scopedness of sizes.
The size environment must be well formed as well;
its rules are listed in \cref{fig:wf},
along with those for well-formedness of term environments.
\FigWF{fig:wf}

\FigRulesAxioms{fig:rules-axioms}
\FigTyping{fig:typing}
Finally, the typing rules for the base \lang are given in \cref{fig:typing}.
They use the metafunctions $\axioms{\mt}$ for the type of a universe,
$\rules{\mt}{\mt}$ for the type of a function type,
defined in \cref{fig:rules-axioms},
and $\fresh{\seq}$ for fresh variables.

\clearpage % TODO: clearpage
\rref{var, univ, let} are the usual rules for variables, universes, and $\kw{let}$ expressions
in \GCC,\index{Calculus of Constructions!Generalized \textasciitilde}
while \rref{pi, lam, app} are the usual ones for functions.
The $\Prop$ universe is impredicative\index{impredicativity} because
a function type quantifying over any type is itself in $\Prop$
as long as its codomain is as well,
allowing a restricted form of circularity.
For example, a function $\id \mathrel{\coloneqq} \fun{\tau}{\Prop}{\fun{x}{\tau}{x}}$
can be assigned the type $\Id \mathrel{\coloneqq} \funtype{\tau}{\Prop}{\arr*{\tau}{\tau}}$ in $\Prop$
and applied to its own type and itself to yield $\app{\id}{\Id}{\id}$
of type $\Id$.

\rref{conv} uses the subtyping judgement and essentially allows casting a term
from one type to a supertype as needed.
If we were working in a bidirectional presentation,
where the typing judgement is replaced by either
\emph{type checking}, which checks an input term against an input type,
or \emph{type synthesis}, which synthesizes an output type for an input term,
this rule for $\type{\Phi; \Gamma}{e}{\tau}$ would be the sole checking rule,
first synthesizing types $\sigma$ and $U$ for $e$ and $\tau$ respectively,
then checking $\sigma$ against $U$,
and lastly asserting that $\sigma$ is indeed a subtype of $\tau$.
This is why, despite $\type{\Phi; \Gamma}{\sigma}{U}$ being derivable,
I choose to retain it as a premise.

\rref{forall, forall<, slam, slam<, sapp, sapp<} are the new rules relevant to sized types,
describing bound and unbound size quantification, abstraction, and application,
which work similarly to functions.
Of note is the bounded size application rule,
which only allows applications to smaller sizes following the subsizing judgement.

\iffalse
Lastly are \rref{eq, refl, J} for propositional equality.
The constructor $\refl{e}$ is a reflexive proof of $\eq{e}{\tau}{e}$,
that $e$ of type $\tau$ is equal to itself.
Given some equality proof $p$ of $\eq{e_1}{\tau}{e_2}$
and a motive\index{motive} $P$ taking some $y$ of type $\tau$ and a proof that $\eq{e_1}{\tau}{y}$,
the $\J*$ eliminator is a proof of $\app{P}{e_2}{p}$ when provided a proof of $\app{P}{e_1}{\refl{e_1}}$.
Other usual functions on proofs of equality can be derived from it,
such as coercion (when the motive is a constant function on types in its first argument)
or substitution (when the motive ignores the second argument).
$\J*$ is only well typed when fully applied;
it can be manually uncurried for a specific universe $U$ as the function
\marginnote{The type annotation for the equality type and argument to $\refl{}$ may be omitted when evident from context.}
$$\fun{\tau}{U}{\fun{e_1}{\tau}{\fun{e_2}{\tau}{\fun{P}{(\funtype{y}{\tau}{\funtype{z}{\eq{e_1}{}{y}}{U}})}{\fun{d}{\app{P}{e_1}{\refl{}}}{\fun{p}{\eq{e_1}{}{e_2}}{\J{P}{d}{p}}}}}}},$$
and similarly for $\refl{}$.
\fi

\section{Inductive Types: Naturals and Well-Founded Trees}\label{sec:ind-types}

\FigSyntaxInd{fig:syntax-ind}
\cref{fig:syntax-ind} extends the grammar with sized naturals, sized well-founded trees,
$\kw{case}$ expressions, and fixpoint expressions.
Informally, borrowing syntax from the definition of general inductives,
sized naturals and well-founded trees can be thought of as being defined by the following:
%
\begin{align*}
&\data{\N{\alpha}}{\Type{1}} && \data{\App{\app{\W*}{(\annot{A}{\Type{i}})}{(\annot{B}{\arr*{A}{\Type{i}}})}}{\alpha}}{\Type{i+1}} \\
&\quad \annot{\zero*}{\Funtype<{\beta}{\alpha}{\N{\alpha}}} && \quad \annot{\sup*}{\Funtype<{\beta}{\alpha}{\arr{x}{A}{\arr*{(\arr*{\app{B}{x}}{\app{\App{\W*}{\beta}}{A}{B}})}{\App{\app{\W*}{A}{B}}{\alpha}}}}} \\
&\quad \annot{\succ*}{\Funtype<{\beta}{\alpha}{\arr*{\N{\beta}}{\N{\alpha}}}}
\end{align*}

\clearpage % TODO: clearpage
The types of naturals and well-founded trees can then be considered to be (nonuniformly) parametrized by a size,
and constructing an element of that type requires providing a strictly smaller size,
which is the size%
\footnote{The ``size of'' some construction is more precisely the size by which its \emph{inductive type} is parametrized.}
of the constructor's recursive arguments.
Constructors therefore always construct elements whose sizes are larger than their arguments'.
In \lang, the constructors are annotated with their types
since the parameter-like sizes cannot otherwise be synthesized.
Additionally, W types have explicit binders for convenience:
the variable $x$ is bound within $\tau$ in the type $\W{x}{\sigma}{\tau}{s}$.

The expression
$\match{e}{\fun*{x}{P}}{(\app{\App{c}{\alpha}}{z_1}{\seq}{z_m} \Rightarrow e_c) \seq}$
contains three parts:
the \emph{target} $e$ it destructs,
the motive $P$ denoting the return type of the expression abstracted over a target,
and the \emph{branches} $e_c$, one for each constructor of the target's type,
abstracted over the constructor's size and term arguments.
Its reduction rules for each constructor are given in \cref{fig:reduction-ind},
along with the reduction rule for fixpoint expressions.
By convention, the reduction rules for $\kw{case}$ expressions
are also referred to as $\iota$-reduction,
and for fixpoint expressions as $\mu$-reduction.
\FigRedInd{fig:reduction-ind}

Fixpoints reduce when applied to some size $s$ by substitution of itself into its own body.
Fixpoints' bodies are well typed when recursive applications occur only on smaller sizes,
so the substitution wraps itself in a bound size abstraction.
Most importantly, they reduce only when there exists some size strictly smaller than $s$;
intuitively, this restriction prevents fixpoints from reducing indefinitely
because subsizing is well founded, and there cannot be an infinite chain of smaller sizes.

This reduction strategy supersedes the usual restriction that fixpoints only reduce
when applied to a constructor,
since all sized constructors carry a smaller size argument
that will satisfy the subsizing premise.
Furthermore, reduction can also occur when the fixpoint is applied to a successor size
by reflexivity of subsizing, \ie $\App{(\fix{f}{\alpha}{\tau}{e})}{\sss{s}}$ will reduce to
$\subst{e}{\alpha, f}{\sss{s}, \Fun<{\beta}{s}{\App{(\fix{f}{\alpha}{\tau}{e})}{\beta}}}$
since $s < \sss{s}$.

\FigTypingInd{fig:typing-ind}

The typing rules for all new constructs are given in \cref{fig:typing-ind}.
One additional metafunction $\FV{\mt}$ produces the free variables in the given term.
The type of naturals and well-founded trees are well typed
when the sizes they are applied to are well formed, and
their constructors are well typed when applied to smaller sizes.

$\kw{case}$ expressions match on these size arguments in addition to the usual term arguments,
asserting within their branches that they are strictly smaller than the target's size.
The motive is dependent on the target,
and the type of a branch is the motive with its target as the constructor being destructed.
In other words, $\kw{case}$ expressions are inversion principles:
for instance, one proves $P$ for some natural $x$ when one can prove it
for the base case where $x$ is some $\zero*$
and for the step case where $x$ is some $\succ*$.

As discussed, the body of a fixpoint is only well typed
when the fixpoint is recursively applied to a smaller size,
as enforced by its type in the environment when type checking the body.

Sizes aside, the only difference from regular, unsized naturals and well-founded trees
is that their types live in a universe one level higher than they usually are.
$\N{s}$ lives in $\Type{1}$ rather than in $\Type{0}$,
and $\W{x}{\sigma}{\tau}{s}$ lives in $\axioms{U}$ rather than in $U$.
This is a direct consequence of the way that the translation is defined,
and is necessary to maintain its type preservation\index{type preservation} properties.
While not incorrect, inductive types living in the ``wrong'' universe is aesthetically unpleasant
and removes some of the impredicativity\index{impredicativity} of their parameters
by preventing them from quantifying over the inductive types themselves.
I discuss potential methods of circumventing this undesirable trait to varying degrees of success
later in \cref{sec:universe-levels}.

\section{Examples}\label{sec:examples}

Now that the rules of \lang have been established,
this section presents examples of using \lang
for programming and proving.
Although it only has naturals and well-founded trees,
I also use other sized inductive types as examples,
informally defining them similarly to \cref{sec:ind-types}.
Additionally, I omit the type annotation of $\kw{let}$-bound expressions
when the type is evident or deducible from context.

\subsection{Concrete natural numbers}

Concrete numbers can be constructed easily using the base size $\circ$ as a starting point
and its successors as strictly larger sizes.
For convenience, I use the notation \new{$s+n$} for some fixed $n$ to mean the $n$th size successor of $s$.
The same number can be represented as terms of different types by changing the annotation since,
for instance, both $\circ+2$ and $\circ+3$ are strictly larger than $\sss{\circ}$.
Similarly, two different naturals can have the same size
because the size of an inductive type represents \emph{at most}
how many layers of constructors deep an element is.
%
\begin{alignat*}{4}
&\Let{\const{0}&&}{\N{\sss{\circ}}&&}{\zero{\hat{\circ}}{\circ}} \\
&\Let{\const{0'}&&}{\N{\circ+2}&&}{\zero{\circ+2}{\circ}} \\
&\Let{\const{1}&&}{\N{\circ+2}&&}{\succ{\circ+2}{\hat{\circ}}{\const{0}}} \\
&\Let{\const{1'}&&}{\N{\circ+3}&&}{\succ{\circ+3}{\hat{\circ}}{\const{0}}} \\
\end{alignat*}

\clearpage % TODO: clearpage
Two terms representing the same number might not be definitionally equal,
as shown by the terms $\const{0}$ and $\const{0'}$,
or by $\const{1}$ and $\const{1'}$;
this requires \emph{shape irrelevance}\index{shape irrelevance}~\citep{NbE},
which is beyond the scope of this thesis.
However, any natural can be ``lifted'' to a larger size
simply by recursively reconstructing the natural with different sizes.

\begin{align*}
&\Let{\liftN}{\Funtype{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\N{\beta}}{\N{\alpha}}}}}{\\
&\fix{\lift}{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\N{\beta}}{\N{\alpha}}}}{\\
&\quad \Fun<{\beta}{\alpha}{\fun{n}{\N{\beta}}{\\
&\quad \match{n}{\fun*{\any}{\N{\alpha}}}{\\
&\qquad \App{\zero*}{\gamma} \Rightarrow \zero{\alpha}{\beta} \\
&\qquad \app{\App{\succ*}{\gamma}}{z} \Rightarrow \succ{\alpha}{\beta}{(\app{\App{\lift}{\beta}{\gamma}}{z})}}}}}}
\end{align*}

A lifting function can also be defined for well-founded trees
(and for strictly-positive sized inductive types in general).
%
\begin{align*}
&\Let{\liftW}{\funtype{A}{\Type{i}}{\funtype{B}{\arr*{A}{\Type{i}}}{\Funtype{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\W{x}{A}{\app{B}{x}}{\beta}}{\W{x}{A}{\app{B}{x}}{\alpha}}}}}}}{\\
&\fun{A}{\Type{i}}{\fun{B}{\arr*{A}{\Type{i}}}{\\
&\fix{\lift}{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\W{x}{A}{\app{B}{x}}{\beta}}{\W{x}{A}{\app{B}{x}}{\alpha}}}}{\\
&\quad \Fun<{\beta}{\alpha}{\fun{w}{\W{x}{A}{\app{B}{x}}{\beta}}{\\
&\quad \match{w}{\fun*{\any}{\W{x}{A}{\app{B}{x}}{\alpha}}}{\\
&\qquad \app{\App{\sup*}{\gamma}}{a}{f} \Rightarrow \sup{x}{A}{\app{B}{x}}{\alpha}{\beta}{a}{(\fun{x}{A}{\app{\App{\lift}{\beta}{\gamma}}{(\app{f}{x})}})}}}}}}}}
\end{align*}

\iffalse
\begin{align*}
\Let{&\liftW}{\funtype{A}{\Type{i}}{\funtype{B}{\arr*{A}{\Type{i}}}{\Funtype{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\W{x}{A}{\app{B}{x}}{\beta}}{\W{x}{A}{\app{B}{x}}{\alpha}}}}}}}{\\
&\liftW \: A \: B \: [\alpha] \: [\beta] \: (\app{\App{\sup*}{\gamma}}{a}{f}) = \sup* \: [\beta] \: a \: (\fun{x}{A}{\liftW \: A \: B \: [\beta] \: [\gamma] \: (\app{f}{x})})}
\end{align*}
\fi

\subsection{Size-preserving functions}

One of the most important uses of sized types is the ability to define
\emph{size-preserving}\index{size preservation} functions,
where the sizes of the input and output are the same.
This guarantees that the output is never larger than the input,
and size-preserving functions can be used in recursive calls of fixpoints.
For instance, the predecessor function $\pred$ which computes
$\maximum{0, n - 1}$ for some number $n$ is size preserving.
%
\begin{align*}
&\Let{\pred}{\Funtype{\alpha}{\arr*{\N{\alpha}}{\N{\alpha}}}}{ \\
&\Fun{\alpha}{\fun{n}{\N{\alpha}}{\match*{n}{ \\
&\quad \App{\zero*}{\beta} \Rightarrow \zero{\alpha}{\beta} \\
&\quad \app{\App{\succ*}{\beta}}{m} \Rightarrow \app{\App{\liftN}{\alpha}{\beta}}{m}}}}}
\end{align*}

The $\monus$ function, which computes $\maximum{0, n - m}$ given numbers $n, m$,
is similarly size preserving in its first argument,
since $n - m$ is never greater than $n$.

\begin{align*}
&\Let{\monus}{\Funtype{\alpha}{\Funtype{\beta}{\arr*{\N{\beta}}{\N{\alpha}}{\N{\beta}}}}}{ \\
&\fix{\monus*}{\alpha}{\Funtype{\beta}{\arr*{\N{\beta}}{\N{\alpha}}{\N{\beta}}}}{ \\
&\quad \Fun{\beta}{\fun{n}{\N{\beta}}{\fun{m}{\N{\alpha}}{\match*{m}{ \\
&\qquad \App{\zero*}{\gamma} \Rightarrow n \\
&\qquad \app{\App{\succ*}{\gamma}}{k} \Rightarrow \app{\App{\monus*}{\gamma}{\beta}}{(\app{\App{\pred}{\beta}}{n})}{k}}}}}}}
\end{align*}

We see the benefit of size preservation with $\divv$,
which computes Euclidean division of $n$ by $m$, or $\left\lceil\frac{n}{m+1}\right\rceil$.
This is computed recursively by subtracting $m$ from the numerator using $\monus$
until $\zero*$ is reached, and counting the number of times the subtraction is performed.
The recursive call is done on the result of $\monus$;
$\divv$ then only type checks because $\monus$ is size preserving.
Because the first argument of the recursive call to $\divv$ isn't \emph{structurally}
a subterm with the call to $\monus$ in the way,
a guardedness check wouldn't accept the corresponding unsized function,
as is the case for CIC.
%
\begin{align*}
&\Let{\divv}{\Funtype{\alpha}{\Funtype{\beta}{\arr*{\N{\alpha}}{\N{\beta}}{\N{\alpha}}}}}{ \\
&\fix{\divv*}{\alpha}{\Funtype{\beta}{\arr*{\N{\alpha}}{\N{\beta}}{\N{\alpha}}}}{ \\
&\quad \Fun{\beta}{\fun{n}{\N{\alpha}}{\fun{m}{\N{\beta}}{\match*{n}{ \\
&\qquad \App{\zero*}{\gamma} \Rightarrow \zero{\alpha}{\gamma} \\
&\qquad \app{\App{\succ*}{\gamma}}{k} \Rightarrow
\succ{\alpha}{\gamma}{
  (\underbrace{\app{\App{\divv*}{\gamma}{\beta}}{
    (\underbrace{\app{\App{\monus}{\beta}{\gamma}}{k}{
      (\underbrace{\app{\App{\pred}{\beta}}{m}}_{\N{\beta}})
    }}_{\N{\gamma}})
  }{m}}_{\N{\gamma}})
}}}}}}}
\end{align*}

\subsection{Large sized functions}

So far, none of these examples have made use of dependent types:
their unsized variants could have all been written in System F.
We therefore now turn to the $n$-ary size-preserving function type,
which does \emph{large elimination}\index{large elimination}
on a natural $n$, \ie returns a type.
This example is due to \citet{MiniAgda}.

\begin{align*}
&\Let{\Nary}{\Funtype{\alpha}{\arr*{\N{\alpha}}{\Funtype{\beta}{\Type{1}}}}}{\\
&\fix{\nary}{\alpha}{\arr*{\N{\alpha}}{\Funtype{\beta}{\Type{1}}}}{\\
&\quad \fun{n}{\N{\alpha}}{\Funtype{\beta}{\match{n}{\fun*{\any}{\Type{1}}}{\\
&\qquad \App{\zero*}{\beta} \Rightarrow \N{\beta} \\
&\qquad \app{\App{\succ*}{\beta}}{m} \Rightarrow \arr*{\N{\beta}}{\App{\app{\nary}{m}}{\beta}}}}}}}
\end{align*}

Intuitively, $\Nary$ constructs the function type

$$\App{\app{\App{\Nary}{\alpha}}{n}}{\beta} = \arr*{\underbrace{\arr*{\N{\beta}}{\seq}{\N{\beta}}}_{\text{$n$ arguments}}}{\N{\beta}}.$$

$n$-ary size-preserving functions can then be typed using $\Nary$,
such as a $\MaX$ function that takes the maximum of $n+1$ numbers
all of the same size.
For concision, I define $\maX$ in a pattern-matching style of syntax,
but it can easily be translated to proper \lang as a fixpoint and two $\kw{case}$ expressions.
%
\begin{align*}
\Let{&\maX}{\Funtype{\alpha}{\arr*{\N{\alpha}}{\N{\alpha}}{\N{\alpha}}}}{ \\
&\maX \: \sqbr{\alpha} \: n \: (\App{\zero*}{\beta}) = n \\
&\maX \: \sqbr{\alpha} \: (\App{\zero*}{\beta}) \: m = m \\
&\maX \: \sqbr{\alpha} \: (\app{\App{\succ*}{\beta}}{n'}) \: (\app{\App{\succ*}{\beta}}{m'}) = \succ{\alpha}{\beta}{(\app{\App{\max}{\beta}}{n'}{m'})}}
\end{align*}
\iffalse
\begin{align*}
&\Let{\maX}{\Funtype{\alpha}{\arr*{\N{\alpha}}{\N{\alpha}}{\N{\alpha}}}}{ \\
&\fix{\mathit{max}}{\alpha}{\arr*{\N{\alpha}}{\N{\alpha}}{\N{\alpha}}}{ \\
&\quad \fun{n}{\N{\alpha}}{\fun{m}{\N{\alpha}}{ \\
&\quad \match*{n}{ \\
&\qquad \App{\zero*}{\beta} \Rightarrow m \\
&\qquad \app{\App{\succ*}{\beta}}{n'} \Rightarrow \\
&\qquad \quad \match*{m}{ \\
&\qquad \qquad \App{\zero*}{\beta} \Rightarrow n \\
&\qquad \qquad \app{\App{\succ*}{\beta}}{m'} \Rightarrow \succ{\alpha}{\beta}{(\app{\App{\mathit{max}}{\beta}}{n'}{m'})}}}}}}}
\end{align*}
\fi
%
\begin{align*}
&\Let{\MaX}{\Funtype{\alpha}{\funtype{k}{\N{\alpha}}{\Funtype{\beta}{\arr*{\N{\beta}}{\App{\app{\App{\Nary}{\alpha}}{k}}{\beta}}}}}}{\\
&\fix{\MaX*}{\alpha}{\funtype{k}{\N{\alpha}}{\Funtype{\beta}{\arr*{\N{\beta}}{\App{\app{\App{\Nary}{\alpha}}{k}}{\beta}}}}}{\\
&\quad \fun{k}{\N{\alpha}}{\Fun{\beta}{\fun{n}{\N{\beta}}{\match{k}{\fun*{x}{\App{\app{\App{\Nary}{\alpha}}{x}}{\beta}}}{\\
&\qquad \App{\zero*}{\gamma} \Rightarrow n \\
&\qquad \app{\App{\succ*}{\gamma}}{k'} \Rightarrow \fun{m}{\N{\beta}}{\app{\App{\app{\App{\MaX*}{\gamma}}{k'}}{\beta}}{(\app{\App{\max}{\beta}}{n}{m})}}}}}}}}
\end{align*}

\subsection{Sized lists}

Implementing sized quicksort~\citep{term-check} and mergesort~\citep{Abel-diss} are perhaps the most classic examples,
demonstrating their ease of programming compared to na\"ive unsized implementations that otherwise
impose a significant termination proof burden to the programmer.
Although \lang has no lists for simplicity's sake,
they are no more complicated than naturals.
Using the same informal syntax from \cref{sec:ind-types},
they can be defined by the following:

\begin{align*}
&\data{\List{(\annot{A}{\Type{i}})}{\alpha}}{\Type{i+1}} \\
&\quad \annot{\nil*}{\Funtype<{\beta}{\alpha}{\List{A}{\alpha}}} \\
&\quad \annot{\cons*}{\Funtype<{\beta}{\alpha}{\arr*{A}{\List{A}{\beta}}{\List{A}{\alpha}}}}
\end{align*}

A similar lifting function for lists can be defined, whose type is

$$\annot{\liftL}{\funtype{A}{\Type{i}}{\Funtype{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\List{A}{\beta}}{\List{A}{\alpha}}}}}}.$$

I also use an encoding for \emph{weak dependent pairs}\index{weak dependent pair}
to express pairing a sized type with some particular size
in situations where the size expressions of \lang aren't expressive enough
to specify the exact size.
%
\begin{align*}
\Pairtype{\alpha}{\tau} &= \funtype{\sigma}{\Type{i}}{\arr*{(\Funtype{\alpha}{(\arr*{\tau}{\sigma})})}{\sigma}} \\
\Pair{s}{e}_{\Pairtype{\alpha}{\tau}} &= \fun{\sigma}{\Type{i}}{\fun{f}{\Funtype{\alpha}{(\arr*{\tau}{\sigma})}}{\app{\App{f}{s}}{e}}} \\
\unpair{\alpha}{x}{\alpha}{\tau}{e_1}{\annot{e_2}{\sigma}} &= \app{e_1}{\sigma}{(\Fun{\alpha}{\fun{x}{\tau}{e_2}})}
\end{align*}

This encoding is used in the $\append$ function, written in pattern-matching style,
where the precise size of the resulting list should be the sum of the sizes of the input lists,
but \lang has no addition operator for sizes.
Suppose that $A$ is some type.
%
\begin{align*}
\Let{&\append}{\Funtype{\alpha}{\Funtype{\beta}{\arr*{\List{A}{\alpha}}{\List{A}{\beta}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}}}{ \\
&\append \: \sqbr{\alpha} \: \sqbr{\beta} \: (\nil* \: \sqbr{\alpha'}) \: r = \Pair{\beta}{r} \\
&\append \: \sqbr{\alpha} \: \sqbr{\beta} \: (\cons* \: \sqbr{\alpha'} \: \hd \: \tl) \: r =
  \unpair*{\gamma}{x}{\append \: \sqbr{\alpha'} \: \sqbr{\beta} \: \tl \: r}{
    \cons* \: \sqbr{\gamma} \: hd \: x
  }}
\end{align*}

$\append$ retains the order of the elements of the lists.
On the other hand, if given some ordering function on $A$
$$\annot{\ifleq}{\funtype{C}{\Type{i}}{\arr*{A}{A}{C}{C}{C}}}$$
which selects one of two branches $C$ based on the order of the elements of $A$,
we can define a similar $\mrg$ function that merges two lists such that
the resulting list is sorted with respect to $\ifleq$ if the input lists were.
In pattern-matching style, the recursion appears lexicographical,
but it can be translated to nested fixpoints~\citep{Abel-diss}.

\begin{align*}
\Let{&\mrg}{\Funtype{\alpha}{\Funtype{\beta}{\arr*{\List{A}{\alpha}}{\List{A}{\beta}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}}}{ \\
&\mrg \: \sqbr{\alpha} \: \sqbr{\beta} \: (\nil* \: \sqbr{\alpha'}) \: r = \Pair{\beta}{r} \\
&\mrg \: \sqbr{\alpha} \: \sqbr{\beta} \: l \: (\nil* \: \sqbr{\beta'}) = \Pair{\alpha}{l} \\
&\mrg \: \sqbr{\alpha} \: \sqbr{\beta} \: (\cons* \: \sqbr{\alpha'} \: a \: l) \: (\cons* \: \sqbr{\beta'} \: b \: r) = \\
&\quad \ifleq \: (\List{A}{\gamma}) \: a \: b \\
&\qquad (\unpair*{\gamma}{x}{\mrg \: \sqbr{\alpha'} \: \sqbr{\beta} \: l \: (\cons* \: \sqbr{\beta'} \: b \: r)}{\Pair{\sss{\gamma}}{\cons* \: \sqbr{\gamma} \: a \: x}}) \\
&\qquad (\unpair*{\gamma}{x}{\mrg \: \sqbr{\alpha} \: \sqbr{\beta'} \: (\cons* \: \sqbr{\alpha'} \: a \: l) \: r}{\Pair{\sss{\gamma}}{\cons* \: \sqbr{\gamma} \: b \: x}})}
\end{align*}

Quicksort and mergesort are both divide-and-conquer algorithms,
so we need some way of dividing up a list.
The simplest to implement recursively is to simply $\spt$ it into two lists of alternating elements,
written in continuation-passing style since \lang has no pairs.
%
\begin{align*}
\Let{&\spt}{\Funtype{\alpha}{\funtype{C}{\Type{i}}{\arr*{\List{A}{\alpha}}{(\arr*{\List{A}{\alpha}}{\List{A}{\alpha}}{C})}{C}}}}{ \\
&\spt \: \sqbr{\alpha} \: C \: (\nil* \: \sqbr{\beta}) \: k = \app{k}{(\nil* \: \sqbr{\beta})}{(\nil* \: \sqbr{\beta})} \\
&\spt \: \sqbr{\alpha} \: C \: (\cons* \: \sqbr{\beta} \: \hd \: \tl) \: k = \\
&\quad \spt \: \sqbr{\beta} \: C \: \tl \:
  (\fun{l}{\List{A}{\beta}}{\fun{r}{\List{A}{\beta}}{
    \app{k}{(\cons* \: \sqbr{\beta} \: \hd \: r)}{(\liftL \: A \: \sqbr{\alpha} \: \sqbr{\beta} \: l)}
  }})}
\end{align*}

Alternatively, the list can be $\partition$ed relative to some pivot element
into two according to $\ifleq$,
such that one list contains only elements that are smaller or equal to the pivot
and the other contains elements larger than it.
%
\begin{align*}
\Let{&\partition}{\Funtype{\alpha}{\funtype{C}{\Type{i}}{\arr*{A}{\List{A}{\alpha}}{(\arr*{\List{A}{\alpha}}{\List{A}{\alpha}}{C})}{C}}}}{ \\
&\partition \: \sqbr{\alpha} \: C \: a \: (\nil* \: \sqbr{\beta}) \: k = \app{k}{(\nil* \: \sqbr{\beta})}{(\nil* \: \sqbr{\beta})} \\
&\partition \: \sqbr{\alpha} \: C \: a \: (\cons* \: \sqbr{\beta} \: \hd \: \tl) \: k = \\
&\quad \partition \: \sqbr{\beta} \: C \: a \: \tl \:
  (\fun{l}{\List{A}{\beta}}{\fun{r}{\List{A}{\beta}}{ \\
    &\qquad \ifleq \: C \: \hd \: a \\
    &\qquad \quad (\app{k}{(\cons* \: \sqbr{\beta} \: \hd \: l)}{(\liftL \: A \: \sqbr{\alpha} \: \sqbr{\beta} \: r)}) \\
    &\qquad \quad (\app{k}{(\liftL \: A \: \sqbr{\alpha} \: \sqbr{\beta} \: l)}{(\cons* \: \sqbr{\beta} \: \hd \: r)})
  }})}
\end{align*}

Quicksort sorts a list by picking a pivot element,
$\partition$ing the rest of the list into sublists of elements smaller and greater than the pivot,
recursively sorting them,
then $\append$ing the sorted lists with the pivot in the middle.
Meanwhile, mergesort sorts a list by $\spt$ing the list into sublists,
recursively sorting them,
then $\mrg$ing the sorted lists while maintaining ordering.
Both involve recursive calls on lists that are not structurally smaller,
but do have smaller sizes,
and differ in where $\ifleq$ is applied ($\partition$ or $\mrg$).

\vspace{-\baselineskip}
\begin{multicols}{2}
\begin{align*}
&\Let{\qsort}{\Funtype{\alpha}{\arr*{\List{A}{\alpha}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}}{ \\
&\fix{\qsort*}{\alpha}{\arr*{\List{A}{\alpha}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}{ \\
&\quad \fun{l}{\List{A}{\alpha}}{\match*{l}{ \\
&\qquad \App{\nil*}{\beta} \Rightarrow \Pair{\alpha}{l} \\
&\qquad \app{\App{\cons*}{\beta}}{\hd}{\tl \Rightarrow \\
  &\qquad \quad \app{\App{\partition}{\beta}}{(\Pairtype{\gamma}{\List{A}{\gamma}})}{\hd}{\tl}{ \\
    &\qquad \quad (\fun{l}{\List{A}{\beta}}{\fun{r}{\List{A}{\beta}}{ \\
      &\qquad \qquad \unpair{\delta}{x}{\gamma}{\List{A}{\gamma}}{\app{\App{\qsort*}{\beta}}{l}}{ \\
      &\qquad \qquad \unpair{\varepsilon}{y}{\gamma}{\List{A}{\gamma}}{\app{\App{\qsort*}{\beta}}{r}}{ \\
      &\qquad \qquad \app{\App{\append}{\delta}{\sss{\varepsilon}}}{x}{(\cons{A}{\sss{\varepsilon}}{\varepsilon}{\hd}{y})}}}
    }})}}}}}}
\end{align*}

\begin{align*}
&\Let{\msorted}{\Funtype{\alpha}{\arr*{A}{\List{A}{\alpha}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}}{ \\
&\fix{\msort*}{\alpha}{\arr*{A}{\List{A}{\alpha}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}{ \\
&\quad \fun{a}{A}{\fun{l}{\List{A}{\alpha}}{\match*{l}{ \\
&\qquad \App{\nil*}{\beta} \Rightarrow \Pair{\sss{\alpha}}{\cons{A}{\sss{\alpha}}{\alpha}{a}{l}} \\
&\qquad \app{\App{\cons*}{\beta}}{b}{\tl} \Rightarrow \\
&\qquad \quad \app{\App{\spt}{\beta}}{(\Pairtype{\gamma}{\List{A}{\gamma}})}{\tl}{ \\
&\qquad \quad (\fun{l}{\List{A}{\beta}}{\fun{r}{\List{A}{\beta}}{ \\
&\qquad \qquad \unpair{\delta}{x}{\gamma}{\List{A}{\gamma}}{\app{\App{\msort*}{\beta}}{a}{l}}{ \\
&\qquad \qquad \unpair{\varepsilon}{y}{\gamma}{\List{A}{\gamma}}{\app{\App{\msort*}{\beta}}{b}{r}}{ \\
&\qquad \qquad \app{\App{\mrg}{\delta}{\varepsilon}}{x}{y}}}}})}}}}}} \\\\
&\Let{\msort}{\Funtype{\alpha}{\arr*{\List{A}{\alpha}}{\Pairtype{\gamma}{\List{A}{\gamma}}}}}{ \\
&\Fun{\alpha}{\fun{l}{\List{A}{\alpha}}{\match*{l}{ \\
&\quad \App{\nil*}{\beta} \Rightarrow \Pair{\alpha}{l} \\
&\quad \app{\App{\cons*}{\beta}}{\hd}{\tl \Rightarrow \app{\App{\msorted}{\beta}}{\hd}{\tl}}}}}}
\end{align*}
\end{multicols}

\subsection{Higher-rank sizes}

The final example, demonstrating higher-rank size quantification,
is a traversal of a well-founded tree with a size-preserving function,
adapted from the rose tree traversal example by \citet{NbE}.
Given some size-preserving function on a well-founded tree,
the function is applied to subtrees prior to traversal.
Suppose that $B$ here is some type operator on $A$.
%
\begin{align*}
&\Let{\traverseW}{\arr*{(\Funtype{\gamma}{\arr*{\W{x}{A}{\app{B}{x}}{\gamma}}{\W{x}{A}{\app{B}{x}}{\gamma}}})}{ \\
&\phantom{\kw{let} \: \traverseW \mathrel{:} \phantom{}} \Funtype{\alpha}{\arr*{\W{x}{A}{\app{B}{x}}{\alpha}}{\W{x}{A}{\app{B}{x}}{\alpha}}}}}{ \\
&\quad \fun{f}{\Funtype{\gamma}{\arr*{\W{x}{A}{\app{B}{x}}{\gamma}}{\W{x}{A}{\app{B}{x}}{\gamma}}}}{ \\
&\quad \fix{\traverse}{\alpha}{\arr*{\W{x}{A}{\app{B}{x}}{\alpha}}{\W{x}{A}{\app{B}{x}}{\alpha}}}{ \\
&\qquad \fun{w}{\W{x}{A}{\app{B}{x}}{\alpha}}{\match*{w}{ \\
&\qquad \quad \app{\App{\sup*}{\beta}}{a}{g} \Rightarrow \sup{x}{A}{\app{B}{x}}{\alpha}{\beta}{a}{(\fun{b}{\app{B}{a}}{\app{\App{\traverse}{\beta}}{(\app{\App{f}{\beta}}{(\app{g}{b})})}})}}}}}}
\end{align*}

\subsection{Limitations} \label{sec:examples:limitations}

As expressive as bounded, higher-rank sized types are,
there still exist limitations to what can be expressed in comparison to ordinary inductive types
or to sized type theories which have an infinite size\index{infinite size},
such as the ones listed in \cref{sec:sized-types}.
Limitations typically arise when dealing with inductive definitions where
recursive arguments appear as the return type of a function.
Consider the following inductive definition
representing the Brouwer notation for ordinals (see \eg \citet{ordinals})
with zero, successor, and limit ordinals:
%
\begin{align*}
&\data{\Ord{\alpha}}{\Type{1}} \\
&\quad \annot{\zord*}{\Funtype<{\beta}{\alpha}{\Ord{\alpha}}} \\
&\quad \annot{\sord*}{\Funtype<{\beta}{\alpha}{\arr*{\Ord{\beta}}{\Ord{\alpha}}}} \\
&\quad \annot{\lord*}{\Funtype<{\beta}{\alpha}{\arr*{(\Funtype<{\gamma}{\beta}{\arr*{\N{\gamma}}{\Ord{\beta}}})}{\Ord{\alpha}}}}
\end{align*}

The limit ordinal, taking some function on naturals returning an ordinal,
constructs an ordinal meant to be ``larger'' than any of the returned ordinals.
Such a function should be able to return an ordinal far larger than any natural,
hence the bounded size quantification in its domain.
Conversely, the naturals embed quite naturally within the ordinals.
%
\begin{align*}
&\Let{\natOrd}{\Funtype{\alpha}{\arr*{\N{\alpha}}{\Ord{\alpha}}}}{ \\
&\fix{\natOrd*}{\alpha}{\arr*{\N{\alpha}}{\Ord{\alpha}}}{ \\
&\quad \fun{n}{\N{\alpha}}{\match*{n}{ \\
&\qquad \App{\zero*}{\beta} \Rightarrow \zord{\alpha}{\beta} \\
&\qquad \app{\App{\succ*}{\beta}}{m} \Rightarrow \sord{\alpha}{\beta}{(\app{\App{\natOrd*}{\beta}}{m})}}}}}
\end{align*}

In an unsized type theory, supposing that $\const{natOrd'}$ is an unsized version of $\natOrd$,
the first limit ordinal $\const{\omega'}$ is easily defined as
$\Let{\const{\omega'}}{\const{Ord}}{\app{\lord*}{\const{natOrd'}}}$.
However, in \lang, things are not so easy; the na\"ive attempt yields the following:
%
\begin{align*}
&\Let{\liftO}{\Funtype{\alpha}{\Funtype<{\beta}{\alpha}{\arr*{\Ord{\beta}}{\Ord{\alpha}}}}}{\seq} \\
&\Let{\omegaOrd}{\Ord{\sss{\hole}}}{\lord{\sss{\hole}}{\hole}{(\Fun<{\gamma}{\hole}{\fun{n}{\N{\gamma}}{\app{\App{\liftO}{\hole}{\gamma}}{(\app{\App{\natOrd}{\gamma}}{n})}}})}}
\end{align*}

Aside from the additional bounds and size lifting, there is one crucial problem: what size fills in the hole \new{$\hole$}?
Intuitively, this size must be larger than the size of \emph{any} natural.
Therefore, a corresponding ``limit size'' is needed;
the infinite size in other sized type theories can fill this r\^ole since it's larger than all sizes
and therefore the limit of \emph{all} sizes.
I further discuss the infinite size and its absence from \lang in \cref{sec:infinity}.


\section{Conclusion and Future work}
\label{conclusion}
In this paper, we have introduced the Byzantine Reliable Broadcast problem on partially connected networks and fully connected networks where the topology is known to all processes. We started by introducing the current state of the problem and how the original protocols work. We continued by elaborating on how one can find the required paths through the network for Dolev, and then how this information can be used to build routing tables for processes. We then described \textbf{9} modifications to Dolev, Bracha, and Bracha-Dolev, and evaluated each modification separately. When we combine all modifications, we provide a solution with a lower message complexity and network usage than existing solutions, a reduction of 71.9\% and 79.4\% respectively with a 12B payload when $N=150$ and $f=20$ for Dolev.
We have concluded that we can indeed reduce the number of messages transmitted when processes have topology knowledge.

This work can be extended in the future by deploying our modified protocols on real infrastructure to get accurate measurements as opposed to simulations. Furthermore, the disjoint path solver can likely be further optimized by enhancing the pathfinding and (re)using better-suited data structures. Applying our modifications to dynamic networks should also be researched further. In addition to this, we use several simple heuristics in our paper (\textbf{ORB.2}, \textbf{ORD.5}) which should be replaced by optimal solutions or improved heuristics. Another interesting direction is that of topology discovery~\cite{topology-discovery,explorer,explorer2}. Previously unknown networks can use optimizations specific for known networks when matched with a topology discovered. One challenge to overcome in this scenario is the tolerance for imperfect routing tables.

%It might also be interesting to explore the combination of our modifications and (multi-)signatures to further reduce the number of messages transmitted.


\chapter{Conclusion}
\label{ch:conclusion}
During accomplishing the thesis work I aimed to supply an explicit overview of image medical background including types of medical image modalities together with how usually they are reconstructed after acquisition, narrated about classical and modern segmentation approaches in addition describing mathematical background behind them. Other than that I pointed out pros and cons of each reviewed algorithm, also evaluated them on the baseline CT scan sample to demonstrate the visualisation of their performances.

Following that, I have spotted detailed overview of vertebral segmentation and labelling problem highlighting the historical research way from 2015 to nowadays.

Afterwards I switched the direction on the proposed solution itself. Altogether with dataset description, metrics and losses mathematical overview I conveyed the models architectures. Apprised how they were trained other than that how the data was augmented. To validate the obtained results I introduced the competitor and within comparison against participant I demonstrated the increase of the performance of my approach.

Precis, 2-stage U-net pipeline which initially detect vertebrae then identify specific vertebrae keening with a 2-class cross entropy and $l^{1}$ loss accordingly, outcomes spectacular results for vertebrae segmentation problem on a publicly available pathological spine CT data set.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                 %
%   HBOOK User Guide -- LaTeX Source                              %
%                                                                 %
%   Chapter 6                                                     %
%                                                                 %
%   The following external EPS files are referenced:              %
%                                                                 %
%   Editor: Michel Goossens / CN-AS                               %
%   Last Mod.: 20 Oct 1993  9:20 mg                               %
%                                                                 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\Filename{H1Operations-on-Histograms}
\chapter{Operations on Histograms}
\label{HOPERFIT}

\Filename{H2Arithmetic-Operations}
\section{Arithmetic Operations}
\label{HARITHME}

\index{histogram!operations}
\index{histogram!addition}
\index{add histograms}
\index{histogram!substraction}
\index{subscract histograms}
\index{histogram!multiplication}
\index{multiply histograms}
\index{histogram!division}
\index{divide histograms}
Histograms can be added, subtracted, divided or multiplied, provided
their number of channels are the same.

\Shubr{HOPERA}{(ID1,CHOPER,ID2,ID3,C1,C2)}

\Action
Fills an histogram \Lit{I3} with values such that,
logically (operands are the bin contents)

\begin{verbatim}
ID3 = C1 * ID1 (OPERATION) C2 * ID2
\end{verbatim}

\begin{DLtt}{123456}
\item[{\rm\bf Input parameters:}]
\item[ID1,ID2] Operand histogram identifiers.
\item[CHOPER] Character variable specifying the
     kind of operation to be performed
     (\Lit{+,-,*,/});\\
     \Lit{'B'} compute binomial errors;\\
     \Lit{'E'} compute error bars on the resulting
      histograms correctly, assuming that the
      input histograms \Lit{ID1} and \Lit{ID2} are independent.\\
     For instance \Lit{/BE} will generate binomial errors for the
     division of \Lit{ID1} by \Lit{ID2}.
\item[ID3] Identifier of the histogram containing
the result after the operation.
\item[C1,C2] Multiplicative constants.
\end{DLtt}

\Remark
\begin{UL}
\item \Lit{ID1}, \Lit{ID2} and \Lit{ID3}
      must have the same number of channels.
\item If histogram \Lit{ID3} is not empty, its contents are overwritten
\item The output histogram \Lit{ID3} can be either one of the input
      histograms \Lit{ID1} or \Lit{ID2}.
\item If histogram \Lit{ID3} does not exist, it is created
      by \Rind{HOPERA} with the same specification as for histogram \Lit{ID1}.
\item The mean value, standard deviation, etc. are calculated from the
      contents of the resulting histogram \Lit{ID3},
      unless the \Lit{'STAT'} option\Iind{STAT} is active and the
      operation is an addition or subtraction, in which case
      they are computed exactly.
\item A division by zero gives zero.
\item Negative results for bin contents in a packed histogram are
      meaningless
\item The number of entries in the resulting histogram \Lit{ID3} is set
      to the sum of the entries in histograms \Lit{ID1} and \Lit{ID2}.
\item When an operation is performed on two 1-dimensional histograms with
      the sum of the squares of the weights stored (option \Rind{HBARX}), the
      error on the resulting histogram is calculated
      supposing that the contents of the two input histograms \Lit{ID1} and
      \Lit{ID2} are uncorrelated.
      This is valid also for projections, slices and
      bands of 2-dimensional histograms.
\item If histogram \Lit{ID3} is packed the
      number of bits allocated per channel (cell) has to be sufficient
      to store the results.
\end{UL}

\newpage
\section{Statistical differences between histograms}
\label{HSTATDIF}
\index{difference! between histograms}
\index{test!Kolmogorov}

\Shubr{HDIFF}{(ID1,ID2,PROB*,CHOPT)}

\Action
Statistical test of compatibility in shape between
two histograms using the Kolmogorov test.
The histograms are compared and the probability that they
could come from the same parent distribution is calculated.

The comparison may be done between two 1-dimensional
histograms or between two 2-dimensional histograms.
\index{Kolmogorov test}
For further details on the method, see \ref{HSTATCON}
below.

\begin{DLtt}{123456}
\item[{\rm\bf Input parameters:}]
\item[ID1] Identifier of first histogram to be compared.
\item[ID2] Identifier of second histogram to be compared.
\item[CHOPT] A character string specifying the options desired.
\begin{DLtt}{1234}
\item['D'] Debug printout, produces a blank line and two lines of
information at each call, including the identifier numbers \Lit{ID},
the number
of events in each histogram, the value of \Lit{PROB}, and the maximum
Kolmogorov distance between the two histograms.
For 2-dimensional histograms,
there are two Kolmogorov distances (see below). If option \Lit{'N'} is
specified, there is a third line of output giving the probalility
\Lit{PROB}
for shape and normalization alone separately.
\item['F1'] Histogram \Lit{ID1} has no errors (it is a function).
\item['F2'] Histogram \Lit{ID2} has no errors (it is a function).
\item['N'] Include a comparison of the relative normalization
of the
two histograms, in addition to comparing the shapes.
The output parameter \Lit{PROB} is then
a combined confidence level taking into account absolute contents.
\item['O'] Overflow, requests that overflow bins be taken
into account (also valid for 2-dim).
\item['U'] Underflow, requests that underflow bins be taken
into account (also valid for 2-dim).
\item[{\rm\bf For 2-dimensional histograms only}]
\item['L'] Left, include X-underflows in the calculation.
\item['R'] Right, include X-overflows in the calculation.
\item['B'] Bottom, include Y-underflows in the calculation.
\item['T'] Top, include Y-overflows in the calculation.
\end{DLtt}
\item[{\rm\bf Output Parameter:}]
\item[PROB] The probability of compatibility between the two histograms.
\end{DLtt}
\Remark
\begin{UL}
\item
Options \Lit{'O'} and \Lit{'U'} can also refer to 2-dimensional
histograms, so that, for example the string \Lit{'UT'} means that
underflows in  X and Y and overflows in Y should be
included in the calculation.
\item The histograms \Lit{ID1} and \Lit{ID2} must exist and already
have been filled before the call to \Rind{HDIFF}. They must also have
identical binning (lower and upper limits as well as number of bins).
\item The probability \Lit{PROB} is returned as a number
between zero and one.
A values close to one
indicates very similar histograms, and a value near zero
means that it is very unlikely that the two arose from the same
parent distribution.
\item By default (no options selected with \Lit{CHOPT})
the comparison is done only
on the shape of the two histograms, without consideration of
the difference in number of events, and ignoring all
underflow and overflow bins.
\end{UL}

\subsection{Weights and Saturation}
\label{HWEIGSAT}

\subsubsection*{Weighted 1-dimensional histograms}

It is possible to compare weighted with weighted histograms,
and weighted with unweighted histograms, but only
if \Lit{HBOOK} has been instructed to maintain the necessary
information by appropriate calls (before filling) to
\Rind{HBARX}.
However it is not possible to take into account underflow
or overflow bins if the events are weighted.

\subsubsection*{Saturated 1-dimensional histograms}

If there is saturation
(more than the maximum allowed contents in one or more bins),
the probability \Lit{PROB} is calculated as if the bin contents
were exactly
at their maximum value, ignoring the saturation.
This usually will result in a higher value of \Lit{PROB} than would
be the case if the memory allowed the full contents to be stored,
but not always.
\index{saturation}
It should therefore be realized that the results of \Rind{HDIFF} are
not accurate when there is saturation, and it is the user's
responsability to avoid this condition.

\subsubsection*{2-dimensional histograms}

Routine \Rind{HDIFF} cannot work if the events are weighted,
since, in the current version of \Lit{HBOOK}, the necessary information
is not maintained.
\Rind{HDIFF} will also refuse to compare 2-dimensional histograms if
there is saturation, since it does not have enough information
in this case.

\subsection{Statistical Considerations}
\label{HSTATCON}

\subsubsection*{The Kolmogorov Test}

The calculations in routine \Rind{HDIFF} are based on the Kolmogorov Test
\index{Kolmogorov test}
\index{Chisquare test}
(See, e.g. \cite{bib-EADIE}, pages 269-270).
It is usually superior to the better-known Chisquare Test
for the following reasons:
\begin{UL}
\item
It does not require a minimum number of events per bin,
and in fact it is intended for unbinned data (this is discussed
below).
\item
It takes account not only of the differences between corresponding
bins, but also the sign of the difference, and in particular it is
sensitive to a sequence of consecutive deviations of the same sign.
\end{UL}
\par In discussing the Kolmogorov test, we must distinguish
between the two most important properties of any test: its
{\bf power} and the calculation of its {\bf confidence level.}

\subsubsection*{The Power}

\index{null hypothesis}
The job of a statistical test is to distinguish between a
null hypothesis (in this case: that the two histograms are
compatible) and the alternative hypothesis (in this case:
that the two are not compatible). The power of a test is defined
as the probability of rejecting the null hypothesis when the
alternative is true. In our case, the alternative is not
well-defined (it is simply the ensemble of all hypotheses
except the null) so it is not possible to tell whether one test
is more powerful than another
in general, but only with respect to certain particular
deviations from the null hypothesis.
Based on considerations such as those given above, as well as
considerable computational experience, it is generally believed
that tests like the Kolmogorov or
Smirnov-Cramer-Von-Mises
\index{Smirnov-Cramer-Von-Mises test}
(which is similar but more complicated to calculate)
are probably the most powerful for the kinds of phenomena
generally of interest to high-energy physicists.
This is especially true for two-dimensional data where
the Chisquare Test is of little practical use since it requires
either enormous amounts of data or very big bins.

\subsubsection*{The Confidence Level for 1-dimensional data}

\index{confidence level}
Using the terms introduced above, the confidence level is just
the probability of rejecting the null hypothesis when it
is in fact true. That is, if you accept the two histograms
as compatible whenever the value of \Lit{PROB} is greater than 0.05,
then truly compatible histograms should fail the test
exactly 5\% of the time.
The value of \Lit{PROB} returned by \Rind{HDIFF} is calculated such that
it will be uniformly distributed between {\it zero} and {\it one}
for compatible histograms, provided the
data are not binned (or the number of bins is very large compared
with the number of events).
Users who have access to unbinned data and wish exact confidence
levels should therefore not put their data into histograms,
but should save them in ordinary Fortran arrays and call the
routine \Rind{TKOLMO} which is being introduced into the Program Library.
On the other hand, since \Lit{HBOOK} is a convenient way of collecting
data and saving space, the routine \Rind{HDIFF} has been provided,
and we believe it is the best test for comparison even on binned
data. However, the values of \Lit{PROB} for binned data will be shifted
slightly higher than expected, depending on the effects of the
binning.
For example, when comparing two uniform distributions of 500
events in 100 bins, the values of \Lit{PROB}, instead of being
exactly uniformly distributed between {\it zero} and {\it one},
have a mean value of about 0.56.
Since we are physicists, we can apply a useful rule:
As long as the bin width is small compared with any significant
physical effect (for example the experimental resolution)
then the binning cannot have an important effect.
Therefore,
we believe that for all practical purposes, the probability value
\Lit{PROB} is calculated correctly provided the user is aware that:
\begin{UL}
\item
The value of \Lit{PROB} should not be expected to have
{\bf exactly} the correct distribution for binned data.
\item
The user is responsible for seeing to it that the bin widths are
small compared with any physical phenomena of interest.
\item
The effect of binning (if any) is always to make the value of \Lit{PROB}
slightly too big. That is, setting an acceptance criterion of
(\Lit{PROB>0.05} will assure that {\bf at most}
5\% of truly
compatible histograms are rejected, and usually somewhat less.
\end{UL}

\subsubsection*{The Confidence Level for Two-dimensional Data}

The Kolmogorov Test for 2-dimensional data is not as well
understood as for one dimension.
The basic problem is that it requires the unbinned data to be
ordered, which is easy in one dimension, but is not
well-defined
(i.e. not scale-invariant) in higher dimensions.
Paradoxically, the binning which was a nuisance in one dimension
is now very useful, since it enables us to define
an obvious ordering.
In fact there are two obvious orderings (horizontal and vertical)
which give rise to two (in general different) Kolmogorov
distance measures.
Routine \Rind{HDIFF} takes the average of the two distances
to calculate the probability value \Lit{PROB},
which gives very satisfactory results.
The precautions necessary for 1-dimensional data also apply to this case.

%\finalnewpage%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\Filename{H2Bin-by-bin-histogram-comparisons}
\section{Bin by bin histogram comparisons}

\Shubr{HDIFFB}{(ID1,ID2,TOL,NBINS,CHOPT,NBAD*,DIFFS*)}

\Action Compare two histograms, bin by bin. For each bin, return the
        probability that the contents are from the same distribution.
        For details of the method see below.

        The comparison may be done between two 1-dimensional histograms,
        two 2-dimensional histograms, or between two profile histograms.

\begin{DLtt}{12345}
\item[{\rm\bf Input parameters:}]
\item[ID1]   The first histogram to be compared.
             The ``reference'' histogram in options \Lit{A} and \Lit{C}.
\item[ID2]   The second histogram to be compared.
             The ``data'' histogram in options \Lit{A} and \Lit{C}.\\
             \Lit{ID1}, \Lit{ID2} are a pair of 1-D, 2-D, or profile
             histograms booked with the same number of bins.
\item[TOL]   The tolerance for a passing the test.
             Under options \Lit{S} and \Lit{C}, \Lit{TOL}
             is a number between 0 and 1 which
             represents the smallest probability considered as an acceptable
             match.
             \mbox{\Lit{TOL}=0.05} will cause \Lit{DIFFS} to reject the
             bin as bad if there is less than a 5\% probability the
             two bins came from the same distribution.
             Under option \Lit{A}, \Lit{TOL} is the degree of precision  of
             match required for the test to be considered as passed.
             \mbox{\Lit{TOL}=2.0}
             means that a data bin differing from the reference mean by
             less than 2.0 times the reference error is compatible.
\item[NBINS] The number of bins in the comparison. For a 1-dimensional
             histogram, this is the number of bins plus 0, 1 or 2, depending
             on whether the overflow and underflow channels are included.
             For a 2-dimensional histogram, this will have the total number of
             bins plus room for overflow bins along any of the axes requested.
             For more detail, see the discussion of \Lit{DIFFS} below.
\item[CHOPT] A string allowing specification of the following options:
             \begin{DLtt}{1}
             \item[N]  Use the absolute contents of each histogram, thus
                       including the normalization of the histogram as well as
                       its shape in the comparison.
                       By default, for the \Lit{S} and \Lit{C} options,
                       in 1- and 2-dimensional histograms,
                       the means are adjusted for the
                       relative numbers of entries (including any overflow or
                       underflow bins requested) in \Lit{ID1} and \Lit{ID2}.
                       No adjustment is ever made for profile histograms.
             \item[O]  Overflow, requests that overflow bins be taken into
                       account.
             \item[U]  Underflow, requests that underflow bins be taken into
                       account.
             \item[R]  Right overflow bin. For a 2-dimensional histogram, it
                       includes the X-Axis overflow bin in the comparisons.
                       If the \Lit{O} option is used, this is automatic.
             \item[L]  Left underflow bin.  Same as above, but the X-Axis
                       underflow is used.
                       The \Lit{U} option uses this automatically.
             \item[T]  Top overflow bin.  Same as \Lit{R}, but for the Y-Axis.
             \item[B]  Bottom underflow bin.  Option \Lit{L} for the Y-Axis.
             \item[S]  Statistical comparison. Calculates the probability that
                       both bins were produced from a distribution with the
                       same mean.
                       This probability is referred to in \Lit{TOL} and
                       \Lit{DIFFS}.
             \item[C]  Compatibility test.
                       Considers bins of the reference histogram (\Lit{ID1})
                       as perfectly describing the true distribution.
                       Calculates the probability that the data
                       (from \Lit{ID2}) was produced from that distribution.
                       For 1- or 2-dimensional histograms, the Poisson
                       mean is deduced from \Lit{ID1}.
                       For profile histograms, the test assumes a Gaussian
                       with mean and standard deviation given by the \Lit{ID1}.
                       The \Lit{C} option should be used when comparing data
                       to a function, a well-known reference, or a
                       calibration distribution.
             \item[A]  Absolute test. Like the \Lit{C} test, except that
                       \Lit{TOL} and \Lit{DIFFS} are in terms of the number
                       of standard deviations, rather probability.
                       The test is on the number of standard deviations by
                       which the data from \Lit{ID2} deviates from the mean.
                       Both the mean and the standard deviation are deduced
                       from \Lit{ID1}.
                       Error bars must be on for this option.
                       This forbids overflow bins, underflow bins, and
                       2-dimensional histograms.
                       The \Lit{A} option ignores bins with zero contents
                       in reference histogram.
             \item[Z]  Ignores bins with zero contents in the comparison.
                       For the \Lit{S} option, ignores bins with zero
                       contents in either histogram.
                       For the \Lit{C} and \Lit{A} option, ignores bins
                       with zero contents in the reference histogram.
                       The default action is to consider all
                       bins as significant.
             \item[D]  Debug printout, dumps the critical variables in the
                       comparisons, along with indicators of its weight, etc.
                       The default (no options selected) does the \Lit{S}
                       option (statistical comparison), ignores underflow
                       and overflow bins, and automatically corrects for the
                       difference in entries between \Lit{ID1} and \Lit{ID2}.
             \end{DLtt}
\item[{\rm\bf Output parameters:}]
\item[NBAD*]  The number of bins failing the compatibility test according
              to the criteria defined by \Lit{TOL} and \Lit{CHOPT}.
\item[DIFFS*] An array of length the number of bins being compared, which
              gives the results of the test bin by bin (confidence levels for
              options \Lit{S} and \Lit{C}, deviations for option \Lit{A}).
              Results are passed back in the form:
              \begin{DL}{1-D}
              \item[1-D] \Lit{DIFFS(NX)} for no over or underflow or
                         \Lit{DIFFS(0:NX+1)},
                         for overflow and/or underflow.
              \item[2-D] \Lit{DIFFS(NX,NY)} or \Lit{DIFFS(0:NX+1, 0:NY+1)}.
              \end{DL}
\end{DLtt}

\subsection*{When to use \Rind{HDIFFB} instead of \Rind{HDIFF}:}

\Rind{HDIFFB} treats the histogram bins individually, while \Rind{HDIFF}
treats the histogram as a whole.
In \Rind{HDIFF}, one is comparing the overall shapes of a
probability distribution.
Typically, an event is entered only in one
channel, and the choice of channel depends on a measured value of a continuous
coordinate, so that it makes sense for downward fluctuations in one bin to be
considered as compensated by upward fluctuations in another bin.
In \Rind{HDIFFB},
each bin is considered independently, except, perhaps, for an overall
normalization factor which is the sum over all bins.

Thus \Rind{HDIFFB} is appropriate when:
\begin{UL}
\item It makes sense to identify a single channel as ``bad'',
      for example if the bin contents correspond to hits in a
      given detector element.
\item The data is heterogeneous, for example if the contents
      are counts versus trigger bit.
\item You have already found a discrepancy on a shape with \Rind{HDIFF}
      and wish to focus on where disagreement is worst.
\end{UL}

A plot of hits versus detector element, where the detector elements
cover some angular range, is an example of a histogram which might
be considered with either comparison utility.
The choice depends on the question you wish to answer:

\begin{UL}
\item If you want to know if the angular distribution looks the same,
      use \Rind{HDIFF}.
\item If you want a report on bad detector elements, use \Rind{HDIFFB}.
\end{UL}

\subsection{Choice of \protect\Lit{TOL}:}

If you choose 0.05 for \Lit{TOL}, you should expect 5 or so bad bins per
trial from a histogram with 100 channels.
For monitoring, you must compromise
between the number of false messages you can tolerate (based on the total
number of channels you monitor), and the amount of data you will need to
collect to claim a channel is bad.
In general, a somewhat smaller fraction of
channels than \Lit{TOL} will be flagged as bad,
since for discrete distributions
(Poisson statistics), the probability is quantized.
For example, the probability might be 0.053 for 4 entries, and 0.021 for 3.
If \Lit{TOL}=0.05, only bins with 3 or fewer entries would be flagged as bad.

\subsection*{When to use the \protect\Lit{S} option:}

The \Lit{S} option should be used when both histograms are filled with
statistical data, for example a momentum distribution from two successive
data runs.
Using the \Lit{S} option when comparing data to a function or known
reference yields poor results because it attributes errors to both histograms.
In this case, the \Lit{C} option should be selected.

\subsection*{When to use the \Lit{C} option:}

The \Lit{C} option assumes that the reference histogram contains the
theoretically expected values with no (or negligible) errors.
Examples might be a flat distribution hand-inserted as the expectation
for a phi distribution, or
a long data run to be compared with shorter data runs.

\subsection*{When to use the \Lit{A} option:}

The \Lit{A} option can be used as an equivalent to the \Lit{C}
option by choosing \Lit{TOL}
in terms of standard deviations instead of probability, and returns $z$ values
in \Lit{DIFFS} for each bin.

The \Lit{A} option is intended for setting by hand absolute minima and maxima.
To restrict an efficiency between 80 and 100\%, load the reference histogram
with a mean of 0.9 (via \Rind{HPAK}) and the error bar of 0.1 (via \Rind{HPAKE}),
and use \Rind{HDIFFB} with \mbox{\Lit{TOL}=1.0} and the \Lit{A} option.
The \Lit{N} option should also be selected for this application.

\subsection*{Comparison of Weighted versus Unweighted events:}

This is in general undesirable, as it forces you into the less accurate
Gaussian approximation.
Thus it is preferable, for example, to have unweighted Monte Carlo events
if you need to use \Rind{HDIFFB} to compare with data.
The only useful case is if the weighted histogram is the reference
histogram in the \Lit{C} comparison, which only makes sense if you have much
better accuracy than your data.

\subsection*{Using Profile histograms:}

The \Lit{N} option is irrelevant for profile histograms.
The overflow/underflow options are illegal for profile histograms because
insufficient information is stored to calculate the error bars.
None of the test options (\Lit{S}, \Lit{C}, or \Lit{A}) check on the number
of entries in a profile histogram bin.
(To do that, make a separate 1-dimensional histogram.)
This has an unexpected effect when the number of entries are small.
Bins with no entries always pass the \Lit{S} and \Lit{C} options
(no data is compatible with any distribution), so in such
cases more bins pass than called for by \Lit{TOL}.

\subsection*{Values of \Lit{DIFFS}:}

The value of \Lit{DIFFS} may depend somewhat on the value of \Lit{TOL}
chosen, as the approximation chosen to calculate \Lit{DIFFS} depends
on both the number of entries and on the size of \Lit{TOL}
(how accurately \Lit{DIFFS} must be calcuated).

The \Lit{S} option sometimes returns a confidence level of 1.0 in the small
statistics calculation, i.e. there is no probability that the two numbers
came from different distributions.
This is due to finite precision.
Values slightly higher than 1.0 will be returned when the two content
values are identical, since no statistical test could claim they came from
different distributions.

\subsection*{Other notes:}

The normalization scaling (used unless \Lit{N} option selected) is based on
channel contents for all channels requested (including overflow/underflow),
provided you select one of the overflow/underflow options.

Negative bin contents are flagged as bad bins in \Lit{S}, \Lit{C} options.

\subsection*{Statistical methods and numerical notes:}

(For simplicity, this is written as if the \Lit{N} option were in effect.)

The methods used for the \Lit{S} and \Lit{C} options are correct for
unweighted events and Poisson statistics for 1- or 2- dimensional histograms.
Errors may result in either the \Lit{S} and \Lit{C} options for small
tolerances if bin contents are greater than the largest allowed integer.

For the \Lit{S} option with unweighted events, the test (which is
uniformly most powerful) treats \Lit{N} = \textem{sum of the two bin contents}
as having chosen via a binomial distibution which histogram to enter.
The binomial parameter \Lit{p} is given by the relative normalization of the
histograms (0.5 if the total number of entries in each histogram was the same).
For \Lit{DIFFS} values greater than \Lit{TOL}, the first two digits are correct.
For values less than \Lit{TOL}, the two digits to the right of the first
non-zero \Lit{TOL} digit are significant,
i.e. for \mbox{\Lit{TOL}=0.0001}, 0.000xxx are significant.
One can force higher accuracy by setting \Lit{TOL} smaller (or even 0),
but calculation time will increase, and warning messages will be issued.
A Gaussian approximation is used when there are 25 or more events in each bin,
and \mbox{\Lit{TOL}$>$0.001}.

The \Lit{C} option for unweighted events in the data histogram simply
calculates the Poisson probability of finding $n$, the \Lit{ID2} bin value,
given a mean equal to the bin value of \Lit{ID1}.
A Gaussian approximation is used when the the mean is $10^{6}$ or larger,
and \Lit{TOL} is 0.001 or larger.
Given the expected mean, the choice of \Lit{TOL} implies bounds
($n_{<},n_{>}$) on $n$ (i.e. $n$ within these bounds passes).
An error occurs when the approximations used in calculating
\Lit{DIFFS} give an incorrect value for $n_{<}$ or $n_{>}$.
No such errors occur for mean $<10^{5}$ and \Lit{TOL} $>10^{-15}$.
The errors in $n_{<}$ or $n_{>}$ are less than 2 for mean $<10^{6}$,
\Lit{TOL} $>10^{-6}$, or
    mean $<10^{7}$, \Lit{TOL} $>10^{-5}$.
There is a maximum $n$ beyond which \Lit{DIFFS}
returns zero, so bins with $n > n_{max}$ always fail.  For mean $<10^{7}$,
this is irrelevant for values of \Lit{TOL} $>10^{-9}$ .

For the profile histogram \Lit{S} option, \Rind{HDIFFB} calculates
the $t$ test probability that both bin means were produced from a population
with the same mean.
The \Lit{C} option calculates the probability of finding the
value in \Lit{ID1} given a Gaussian with $\mu$ and $\sigma$ given by the
\Lit{ID2} contents.
Small numbers of entries for either test give \Lit{DIFFS} values which are
too large, and \Rind{HDIFFB} will reject too many events in profile histograms.

For weighted events, the \Lit{S} and \Lit{C} options use a Gaussian
approximation.
This results in \Lit{DIFFS} values which are too low.
\Rind{HDIFFB} rejects too many bins for weighted events,
particularly for small numbers of equivalent events.

\subsection*{Error messages of \Rind{HDIFFB}:}

\newcommand{\erritem}[1]{\item[\underline{\tt#1}]\mbox{}\\}
\begin{DLtt}{xx}
\erritem{Warning: Zero tolerance}
    The passed value \Lit{TOL} is less than or equal to 0.
    \Lit{TOL}=0. can be
    used to force highest accuracy in the \Lit{S} option.
\erritem{Warning: Only one comparison at a time, please.}
    More than one type of comparison was selected.
    Only one of options \Lit{S}, \Lit{C}, and \Lit{A} may be used.
    The default \Lit{S} option will be used.
\erritem{Warning: Different binning.}
    The \Lit{XMIN} values for a 1-dimensional histogram or the
    \Lit{XMIN} and/or \Lit{YMIN}
    values on a 2-dimensional histogram are different.
    This may give inaccurate results.
\erritem{Warning: Weighted or saturated events in 2-dimensions.}
    HBOOK does not compute error bars for two dimensional histograms, thus
    weighted event are not allowed, and \Rind{HDIFFB} can not compute
    the correct statistics.
    An answer is still given, but it is probably not right.
    The only reliable case is a weighted 2-dimenension histogram as the
    reference histogram for the \Lit{C} option.
\erritem{Sum of histogram contents is zero!}
    The sum of the content bins is zero.
\erritem{Histograms must be the same dimension.}
    A 1-dimensional and a 2-dimensional histogram have been specified.  In
    order for the routine to work, both must be the same dimensionality.
\erritem{Both histograms must be the standard or profile type.}
    Two different types of histograms have been specified.
    Both must be profile or non-profile.
    You cannot mix types.
\erritem{Not enough bins in DIFFS to hold result.}
    The parameter \Lit{NBINS} is less that the number of bins in
    the histograms.
\erritem{Number of channels is different.}
    The number of channels in the two histograms to compare are different.
    They must be the same before the routine will process the data.
\erritem{U/O/L/R/T/B Option with weighted events.}
    HBOOK does not compute an error bar for over-/under-flow bins,
    thus it may not be used with weighted events.
\erritem{U/O/L/R/T/B Option with profile histograms.}
    HBOOK  does not compute an error bar for over-/under-flow bins,
    thus it may not be used with profile histograms.
\erritem{Weighted options and no HBARX.}
    The user had not told HBOOK to figure the error bars for the histograms.
    Therefore, the operations will not be valid.
\erritem{A-option with no error bars on reference histogram.}
    The user has not told HBOOK to compute error bars for the reference
    histogram.
    This error is also returned when the user attempts to select
    the \Lit{A} option to compare 2-dimensional histograms.
\end{DLtt}

\subsection*{Statistical comments:}

The methods used for the \Lit{S} and \Lit{C} mode are correct for unweighted events and
Poisson statistics for one or two-dimensional histograms.
For weighted events,
a Gaussian approximation is used, which results in \Lit{DIFFS} values which are
too low when there are fewer than 25 or so ``equivalent events'' (defined
under \Rind{HSTATI}) per bin.
This is caused by either few entries or by wide fluctuation in weights.
The result is that \Rind{HDIFFB} rejects to many bins in this case.

Comparisons for profile histograms assume Gaussian statistics
for the \Lit{S} and \Lit{C} mode comparisons of the channel mean.
Fewer that 25 or so events will result in \Lit{DIFFS} values which are too large.
The result is that \Rind{HDIFFB} rejects too many event in these low statistic cases.

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


\documentclass{article}

\begin{document}

\title{Equations used in Stephen R. Berggren's Apple Nuclear Power Plant Simulation}
\author{Kevin Riggle}

\maketitle

Or, \emph{Nuclear Power Plant: The Board Game}.

Each turn represents a day in the life of a nuclear power plant.

\section{Warning Thresholds}

Notify the player when these thresholds are exceeded:

\begin{itemize}
\item Reactor overheats above 800$^{\circ}$C.
\item Heat Exchanger overheats above 500$^{\circ}$C.
\item Turbine output is low below 1000 kW.
\item Turbine output overloads above 2000 kW.
\item Cooling Tower overheats above 300$^{\circ}$C.
\item Emergency Cooling System coolant volume is low below 200 gal.
\item Primary Cooling System coolant volume is low below 100 gal.
\item Secondary Cooling System coolant volume is low below 100 gal.
\end{itemize}

Notify the player when these levels are met:

\begin{itemize}
\item The Reactor core is damaged when it has 4 or more points of damage.
\item The Reactor core has melted down when it has 6 or more points of damage.  This ends the game in a loss.
\item The Primary Cooling System is leaking when it has 5 or more points of damage.
\item The Secondary Cooling System is leaking when it has 5 or more points of damage.
\item The Emergency Cooling System is leaking when it has 3 or more points of damage.
\end{itemize}

Notify the player of these status conditions:

\begin{itemize}
\item The Primary Cooling System is broken.  Report the coolant pump failure percentage as $10\times$ the number of points of damage the system has, up to a maximum of 100\% (10 or more points).
\item The Secondary Cooling System is broken.  Report the coolant pump failure percentage as $10\times$ the number of points of damage the system has, up to a maximum of 100\% (10 or more points).
\item The Heat Exchanger is broken.
\item The Turbine is broken.
\end{itemize}

\section{Calculating Component Damage}
\subsection{Reactor overheated}

Every turn when the Reactor is overheated (above 800$^{\circ}$C), the reactor gains:
\begin{itemize}
\item 1 point of damage always
\item 1 point if it is above 850$^{\circ}$C
\item 1 point if it is above 900$^{\circ}$C
\item 1 point if it is above 950$^{\circ}$C
\end{itemize}

So the Reactor can gain up to 4 points of damage a turn.

Every turn when the Reactor is overheated the Primary Cooling System gains 1 point of damage.

Every turn when the Reactor is overheated the Emergency Cooling System gains 1 point of damage.  The Emergency Coolant system gains 1 additional point of damage if the Reactor temperature is above 850$^{\circ}$C.

\subsection{Heat Exchanger overheated}

Every turn when the Heat Exchanger is overheated:
\begin{itemize}
\item The Heat Exchanger gains 1 point of damage.  The Heat Exchanger gains 1 additional point of damage if the Heat Exchanger is above 600$^{\circ}$C.
\item The Primary Cooling System gains 1 point of damage.
\item The Secondary Cooling System gains 1 point of damage.
\end{itemize}

\subsection{Turbine overloaded}

Every turn when the Turbine is overloaded (output is above 2000 RPM):
\begin{itemize}
\item The Turbine gains 1 point of damage.  The Turbine gains 1 additional point of damage if its output is above 2500 RPM.
\item The Secondary Cooling System gains 1 point of damage.
\end{itemize}

\subsection{Cooling Tower overheated}

Every turn when the Cooling Tower is overheated (above 300$^{\circ}$C), the Secondary Cooling System gains 1 point of damage.

\subsection{Primary Cooling System coolant volume low}

Every turn when the Primary Cooling System coolant volume is low (below 100 gal.), the Primary Cooling System gains 1 point of damage.

If the Primary Cooling System has 5 or more points of damage, the Primary Cooling System is leaking.  Every turn reduce coolant volume by the number of points of damage the system has.

\subsection{Secondary Cooling System coolant volume low}

Every turn when the Secondary Cooling System coolant volume is low (below 100 gal.), the Secondary Cooling System gains 1 point of damage.

If the Secondary Cooling System has 5 or more points of damage, the Secondary Cooling System is leaking.  Every turn reduce coolant volume by the number of points of damage the system has.

\subsection{Emergency Cooling System damage}

If the Emergency Cooling System has 3 or more points of damage, the Emergency Cooling System is leaking.  Every turn reduce coolant volume by twice (2$\times$) the number of points of damage the system has.

\end{document}


\begin{multicols}{3}
\textbf{Solving Abrupt Silicon PN Junction Question}

\begin{enumerate}
\item Calculate $V_{bi}$.
\item Look up $D_p$ on the diffusion coefficient chart. \ref{fig:pictureonright}
% find that chart in volume one and include? on seperate page?, also reference that picture, figure from Lecture I- Jan 16, p.7
\item Calculate the diffusion length: $L_p = \sqrt{D_p \tau_p}$ (for $p^+n$) - or - $L_n=\sqrt{D_n \tau_n}$ (for $pn^+$)
\item If: $L_p > x_p $ (for $p^+n$) - or - $L_n > x_n$ (for $pn^+)$, the diode is short-base.
\end{enumerate}

\subsection{Bipolar Junction Transistor}

\begin{tabular}{p{5.30cm}p{3.5cm}}
$\beta_F = \frac{\alpha_F}{1-\alpha_F}$; $\beta_{dc}=\frac{\alpha_{dc}}{1-\alpha_{dc}}$ & Gain \\ %\hline
$\alpha_F = \gamma_F \alpha_T$; $\alpha_{dc}=\gamma \alpha_T$ \hfill \break  $\alpha_R=\gamma_R \alpha_T$ & Base Transport \hfill \break  Factor (BTF) \\ %\hline
$\alpha_{T(npn)}=\cfrac{I_{Cn}}{I_{En}}$; $\alpha_{T(pnp)}= \cfrac{I_{Cp}}{I_{EP}}$ & BTF ($\approx 0.999$) \\
$\alpha_T= 1-\frac{x_B^2}{2D_n\tau_n}=1-\frac{x_B^2}{2Ln^2}$ & BTF ($D_n$. Fig 3,5) \\
$I_{pE}= \frac{-qA_En_i^2 D_p}{N_{dE}x_E} \exp\left(\frac{qV_{BE}}{k_BT}-1\right)$ & Short Emitter \hfill \break
$L_{pE}= \sqrt{D_{pE}\tau_n}>x_E$ \\
$I_{pE}= \frac{-qA_E n_i^2 D_p}{N_{dE}L_p} \exp\left(\frac{qV_{BE}}{k_BT}-1\right)$ & Long Emitter \hfill \break
$L_{pE}= \sqrt{D_{pE}\tau_n}<x_E$
\end{tabular}
%
\begin{tabular}{p{3.8cm}p{5cm}}
$\gamma_F= \left[1+\frac{x_B N_{aB} D_{pE}}{x_E N_{dE} D_{nB}}\right]^{-1}$
$\gamma_R = \left[1+\frac{x_B N_{aB} D_{pC}}{x_E N_{dC} D_{nB}}\right]^{-1}$ & Short Emitter Forward and \hfill \break Reverse Emitter Injection (REI) \hfill \break Efficiency ($\gamma_R$ swap roles, E \& C) \\
%
\end{tabular}
%
\begin{tabular}{p{4.2cm}p{4.6cm}}
$\gamma_F= \left[1+\frac{x_B N_{aB} D_{pE}}{L_{PE} N_{dE} D_{nB}}\right]^{-1}$
$\gamma_R = \left[1+\frac{x_B N_{aB} D_{pC}}{L_{PC} N_{dC} D_{nB}}\right]^{-1}$ & Long Emitter Forward and \hfill \break (REI) Efficiency (for $\gamma_R$ swap roles of E \& C) \\
\end{tabular}

\begin{tabular}{p{5cm}p{3.8cm}}
$\gamma_{(npn)}= \cfrac{I_{En}}{I_E}= \cfrac{|I_{En}|}{|I_{En}|+|I_{Ep}|}$  \hfill \break $\gamma_{(pnp)}= \cfrac{I_{Ep}}{I_E}= \cfrac{|I_{Ep}|}{|I_{En}|+|I_{Ep}|}$ & \hfill \break  Emitter injection \hfill \break  Efficiency \\
\end{tabular}

\begin{tabular}{l l}
$I_E=I_{Ep}+I_{En}$ $I_C = I_{Cp}+I_{Cn}$ & $I_B = \cfrac{I_C-I_{CE0}}{\beta_{dc}}$ \\
$I_C = \alpha_{dc}I_E+I_{CB0}$ $I_C=\beta I_B+I_{CE0}$ & $I_{Cn} \approx I_{BC0}$ \\
\end{tabular}

\begin{tabular}{p{5cm}p{3.8cm}}
$I_{Cn} \approx I_{BC0}$ & Collector Reverse  \hfill \break Saturation Current \\
$I_{Cn} \approx I_{BC0}$ & Emitter-Collector \hfill \break Saturation Current \\
\end{tabular}

Electron Current Density (ECD) - constant base doping \hfill \break
$J_n= \frac{qD_n n_i^2}{x_B N_{aB}}\left[\exp\left(\frac{qV_{BC}}{k_BT}\right)-\exp\left(\frac{qV_{BE}}{k_BT}\right)\right]$  (A/$\text{cm}^2$)

ECD - non-constant base doping   (A/$\text{cm}^2$) \hfill \break
$J_n= J_0\left[\exp\left(\frac{qV_{BC}}{k_BT}\right)-\exp\left(\frac{qV_{BE}}{k_BT}\right)\right]$ \hfill \break
$J_0= \frac{q^2n_i^2 \tilde{D}_n}{Q_B}$, $\tilde{D}_n= \text{avg}(D_n)$  \hfill \break
%
%
Collector Current Density (under active bias)  \hfill \break
$J_C \approx J_0 \exp\left(\frac{qV_{BE}}{k_BT}\right)$  \hfill \break
%
%
Recombination of excess minority carriers in the base  \hfill \break
$I_{rB}=\frac{qA_gn_i^2x_B}{2N_{aB}\tau_n}\left[\exp\left(\frac{qV_{BE}}{k_BT}\right)-1\right]$  \hfill \break
%
%
Collector-Emitter Breakdown Voltage  in terms of the Collector-Base
Breakdown. Note that $m \approx 4$ \hfill \break
$BV_{CE0}=\frac{BV_{CB0}}{\beta^{1/m}}$ \hfill
% \vfill\null \columnbreak
  \textbf{Finding}  $\beta$ \textbf{Of a BJT}
  \begin{enumerate}
  \item  Look-up $D_{pE}$ amd $D_{pC}$ on chart
  \item  Find $L_{pE}=\sqrt{D_{pE}\tau_{pE}}$ and $L_{pC}=\sqrt{D_{pC}\tau_{pC}}$
  \item  Check if emitter is long or short $L_{pE}>x_B \rightarrow $ long emitter or $L_{pE}<x_B \rightarrow$ short emitter.
  \end{enumerate}
  % act like an indent
\begin{flushright}
   4. Find $\gamma_F$, (Short Emitter Forward Efficiency) \break
   5.  Find $\alpha_T$ (Base Transport Factor)            \break
   6.  Find $\alpha_F$ (Base Transport Factor)            \break
   7.  Find $\beta_F$  (Current Gain)
\end{flushright}
\vspace*{-0.75cm}
\begin{flushright}
\textbf{Designing an Prototype NPN  \\ Structure for an Amplifier} \break
1. Assume these doping levels: \\ $N_{dC}=10^{16} \text{cm}^{-3}$
and $N_{aB}=5 \times 10^{16} \text{cm}^{-3}$ \\
2. Calculate $V_{bi}=\frac{k_BT}{q} \ln \left[\frac{N_dN_a}{n_i^2}\right]$ \\
3. Use $V_a$, desired punch through voltage. $x_B= \left(\frac{N_{aB}}{N_{dC}}\right)^{-1}\left[\frac{2\epsilon_s}{q}\left(\frac{1}{N_{aB}}+\frac{1}{N_{dC}}\right)(V_A-V_{bi})\right]^{1/2}$ \\
4. Calculate (shown as a design parameter) $x_{p0}=\left(\frac{N_{aB}}{N_{dC}}\right)^{-1}\left[\frac{2\epsilon_s}{q}\left(\frac{1}{N_{aB}}+\frac{1}{N_{dC}}\right)(V_{bi})\right]^{1/2}$ \\
5. Calculate $\alpha_T=1-\frac{x_B^2}{2D_n \tau_n}$ use hole curve ($D_n=23 \text{cm}^2 s^{-1})$ for doping levels above. \\
6. With these doping levels $\alpha_t \cong 1$. Since $\alpha_T \cong 1$, assume $\alpha_F = \gamma_F$. \\
7. Find the ratio = $\frac{N_{dE}}{D_{pE}} = \underbrace{\left(\frac{x_BN_{aB}}{x_ED_{nB}}\right)\left(\frac{1}{\gamma_F}-1\right)}_{ratio}$ \\
8. Using $D_{pE}=\frac{N_{dE}}{ratio}$, find a good value for \\
$N_{dE}$ that allows you to look up $D_{pE}$ on the diffusion chart. Use the curve for holes.
\end{flushright}

\textbf{Ebers-Moll Equations}
\hfill \break
\begin{tabular}{p{4.8cm}p{4cm}}
$I_E=I_F-\alpha_RI_R$ & Emitter Current \\
$I_C=\alpha_FI_F-I_R$ & Collector Current \\
$I_B=I_E-I_C$ \\
$I_B=(1-\alpha_F)I_F+(1-\alpha_R)I_R $& Base Current \\
$I_{F0}=qA \left[\frac{D_En_{E0}}{L_e}+\frac{D_Bp_{B0}}{W}\right]$ & Forward Coefficient \\
$I_F=I_{F0} \left[e^{(eV_{eB}/k_BT)}-1\right]$ & For Curr Component \\
$I_{R0}=qA \left[\frac{D_E N_{c0}}{L_C}+\frac{D_Bp_{B0}}{W}\right]$ & Reverse Coefficient \\
$I_R=I_{R0}\left[e^{(qV_{cB}/k_BT)}-1\right]$& Rev Cur Component \\
$\alpha_FI_{F0}=\alpha_R I_{R0}=I_S$ \\ $\frac{I_{F0}}{I_{R0}}=\frac{\alpha_R}{\alpha_F}$ & reciprocity Relation. \\
$\beta_f = \frac{\alpha_F}{1-\alpha_F}$ & Normal Forward $\beta$
\end{tabular}
$\alpha_R I_R = \frac{qAD_Bp_{B0}}{W} \left[ e^{(qV_{cB}/k_BT)-1}\right]$  Ebers-Moll Eqns \\

$\alpha_R I_R = \frac{qAD_Bp_{B0}}{W} \left[ e^{(qV_{cB}/k_BT)-1}\right]$ Vol III - 47.

\textbf{Transit Time and Frequency Response} \hfill \break
\begin{tabular}{p{1.75cm}p{7.05cm}}
$\tau_1=r_e C_{jE}$ & Emitter-Base Capacitance Charging Time \\
$\tau_2=r_CC_{jC}$ & Collector Capacitance Charging Time \\
$\tau_B=\frac{x_B^2}{2D_{nB}}$ & Base Transit Time \\
$\tau_C = \cfrac{x_{dc}}{v_{sat}}$ & Collector Depletion Region Transit Time \hfill \break ($x_{dc}$:Depletion region width of collector) \hfill \break ($v_{sat}$: Saturation velocity, $\approx 10^7$ m/s)
\end{tabular}
$\tau_{EC}=\tau_1+\tau_2+\tau_B+\tau_C$ $\tau_{EC}=\tau_C+\tau_B+\tau_E$ \hfill \break Emitter to Collector Transit Time.  $f_T = \frac{1}{2 \pi \tau_{EC}}$ Cut-off Frequency.

\textbf{Amplification}: For amplifying BJTs, the thickness and resistivity of the collector are both large.  Th
is results in an increased breakdown voltage and reduces the early effect. \hfill \break

\textbf{Switching}: For switching BJT's, saturation (On-State) resistance must be minimized, which requires a very thin collector layer with a resistivity of a few tenths of an $\Omega$-cm.

The Early Effect results in an increase in $I_C$ due to base-width modulation when $V_{CB}$ is increased.

\textbf{Finding} $V_T$: Using substrate resistivity $\rho \rightarrow N_A \& N_D$ (Vol I - pg 71) 2. Calculate $\phi_p$ 3. Calculate $Q_f$ from given data $Q_f/q$ 4. Calculate $C_{ox} $ 5. Find $\phi_{MS}$ (depends on gate material, use Vol I - pg 96.
6. Calculate $V_{FB}$
7. Calculate $V_T$.

\textbf{MOSFET's} \hfill \break
\begin{tabular}{p{1.8cm}p{7cm}}
$K_s=11.8$ & Dielectric Constant of Si (at 300 K) \\
$K_o=3.9$  & Dielectric Constant of Si$O_2$ (at 300K) \\
\end{tabular}
\begin{tabular}{p{4.6cm}p{4.2cm}}
$\epsilon_s=K_s\epsilon_0=1.1045 \times 10^{-12}\frac{F}{cm}$ & Permittivity of Si (at 300K) \\
\end{tabular}
\begin{tabular}{p{4.8cm}p{4.2cm}}
$\epsilon_{ox}=K_0\epsilon_0=345.15 \times 10^{-15}\frac{F}{cm}$  & Permittivity Si$O_2$ (300K) \\
\end{tabular}
P-type Si MOS Structure $\rightarrow$ N-channel Device \hfill \break
N-type Si MOS Structure $\rightarrow$ P-channel Device \hfill \break
Ref Voltage rel to the semicond doping concent.
$\phi_{F(p-type)}= \phi_p = \frac{kT}{q}\ln\left(\frac{N_A}{n_i}\right)$ \hfill \break
$\phi_{F(n-type)}= \phi_p = - \frac{kT}{q}\ln\left(\frac{N_D}{n_i}\right)$ Semicond Surf Pot at Depletion-Inversion Transition
Point
$\phi_S = 2 \phi_F$ \hfill \break
%
%
Flat-band voltage (voltage that produces flat energy bands in the oxide and silicon) \hfill \break
$V_{FB} = \phi_{MS}-\frac{Q_f}{C_{ox}}$ With a charge on the oxide layer.
$V_{FB}=\phi_M-\phi_S=\phi_{MS}$ oxide layer free of charge.

\begin{tabular}{p{4.4cm}p{4.2cm}}
$W_T=\left[\frac{2K_s\epsilon_0}{qN_A}(2\phi_p)\right]^{1/2}$ & Depletion Width Iv p 43
\\
$\phi(x)=\frac{1}{q}[E_f-E_i(x)]$ & Potential in Silicon \\
%
$\phi_S=\phi(0)=\frac{1}{q}(E_f-E_i(0))$ & Surface Potential \\
%
%
$C_{ox}=\frac{\epsilon_{ox}}{x_{ox}}$ $\dot{A} = 10^{-10} m$ & Oxide Layer Capacitance \\
\end{tabular}
\begin{tabular}{p{4.4cm}p{4.4cm}}
$Q_{d(max)}=\sqrt{4k_s\epsilon_0qN_A|\phi_P|}$ & Space Charge Density (max) \\
\end{tabular}
$V_T =V_{FB}+2|\phi_p| + \frac{|Q_{d(max)}|}{C_{ox}}$, Threshold Voltage(T.V.) \hfill \linebreak
$V_T=2\phi_F-\frac{K_s x_{ox}}{K_{ox}}
\left[\frac{4qN_A}{K_S \epsilon_0}\phi_F\right]$
\hfill \break
$\Delta V_G=V_T^\prime-V_T$ (Threshold Adjustment)
$\Delta V_G= \frac{-Q_l}{C_{ox}}$ $Q_l=\pm qN_l
\rightarrow N_l = \pm \frac{Q_l}{q}$ $V_T^\prime$ Un-adjusted T.V. $V_T$: Adjusted T.V. $N_l$: \# of implanted ions $Q_l$: Implant-related charge/$\text{cm}^2$  Donor\{+\} or Acceptor \{-\}

$I_D = \frac{Z \bar{\mu}_n C_{ox}}{L} \left[(V_G-V_T)V_D - \frac{V_D^2}{2}\right]$ Square-law theory

Z: Width of MOSFET $\bar{\mu}_n$ Effe hole mobil Vol IV. Pg 73

\textbf{Long Channel MOSFET Equation} Bulk Charge Factor ($\alpha$) %\hfill \break
$I_D= \mu C_{ox}\frac{W}{L} \left[\left(V_G-V_T-\frac{1}{2}V_D\right)V_D\right]$ \hfill \break
$I_D= \mu C_{ox}\frac{W}{2\alpha L} \left[\left(V_G-V_T-\frac{1}{2}V_D\right)V_D\right]$

\textbf{Channel Carrier Velocity} (Using Long-Channel Theory)
$V=\cfrac{\mu_n C_{ox}\left[\left(V_G-V_T-\frac{1}{2}V_D\right)V_D\right]}{Q_NL}$

%\hfill \break
Note: The saturation velocity of carriers in Silicon is: $v_{sat} \approx 10^7$ cm/s.
If this equation yields a velocity $v > v_{sat}$, long channel theory does not apply in this situation. $Q_{n(source)}=C_{ox}(V_G-V_T)$, $Q_{n(drain)}=C_{ox}(V_G-V_D-V_T)$.

\textbf{Drain Saturation Voltage}
$V_{D(sat)}=V_G-V_T$ $V_{D(sat)}=\frac{V_G-V_T}{\alpha}$.
\vspace*{-0.4cm}
\begin{flushright}
$g_d$, $g_m$ Small Signal Parameters and Conductance % Vol.IV - pg 83
$f_{max}=\frac{g_m}{2\pi C_{ox}}=\frac{\bar{\mu}_nV_D}{2\pi L^2}$ Cutoff f $V_D \leq V_{D(sat)}$ \break
Using $I_{D(sat)}=\mu_nC_{ox}\frac{W}{2L}(V_G-V_T)^2$ \linebreak
%
Channel Dimensions $\frac{W}{L}=\frac{2I_{D(sat)}}{\mu_nC_{ox}(V_G-V_T)^2}$
\end{flushright}
\textbf{MOSFET Integrated Circuit Applications} \hfill \break
$V_T=V_{FB}+2|\phi_p|+\cfrac{Q_{d(max)}}{\epsilon_{ox}}(d_1+d_2)+\cfrac{Q_{fg}}{\epsilon_{ox}}d_1$
Charge stored on a floating gate memory cell

$|Q_{fg}|=\frac{\epsilon_{ox}}{d_1}\left[V_T-V_{FB}-2\phi_P-\frac{Q_{d(max)}}{\epsilon_{ox}}(d_1+d_2)\right]$, $Q_{fg}=$ Floating Gate Charge Density $V_{FB}=\phi_{MS}$

Step 1: Find $V_{bi}$ (n-well to source/drain junction) using $N_d$ from, the n-well and $N_a$ from the p-channel source/drain.
\vspace*{-0.4cm}
\begin{flushright}
Step 2: Find $x_d$ using the doping levels and $V_{bi}$. \break
Step 3: Find $V_{bi}$ (n-well to p-substrate junction) using $N_d$ from the n-well and $N_a$ from the p-substrate. \break
Step 4: Find $x_n$ using $V_{bi}$ and $V_a=V_{DD}$, and the same doping level as step 3. \break
Step 5: The minimum required n-well depth to prevent punchthrough at this voltage is: $d_{n-well}=d_{p-channel src/drn}+x_{d(step 2)}+ x_{n(step 4)}$
\end{flushright}
$V_{bi}=\frac{k_BT}{q}\ln\left(\frac{N_dN_a}{n_i^2}\right)$ \hfill \break
$x_d=x_n+x_p=\left[\frac{2\epsilon_s}{q} \left(\frac{1}{N_a}+\frac{1}{N_d}\right)(V_a-V_{bi})\right]^{1/2}$, \hfill \break
$x_n= \left\{\frac{2K_s\epsilon_0}{q}(V_{bi}+V_a)\left[\frac{N_a}{N_d(N_a+N_d)}\right]\right\}^{1/2}$
Note: The p-channel source/drain depth $d_{p-channel src/drn}$ should be given in the question.

CMOS Well-Depth Design: Finding minimum well
depth to prevent vertical punch through.

\textbf{CMOS Structures}
P-Well: The substrate is N-Type. The N-Channel device is built into a P-Type well within the parent N-Type substrate.
The P-channel device is built directly on the substrate.

N-Well: The substrate is P-Type. The N-channel device is built directly on the substrate, while the P-channel device is
built into a N-type well within the parent P-Type substrate.

$g_d=\frac{Z\bar{\mu}_n C_o}{L}(V_G-V_T) \ \ (V_D=0)$

\textbf{Practise Test 2}
1) Which of the following can reduce the base transit time? c) Short base width.

2) Design the doping levels and dimensions of a silicon npn bipolar transistor such that the dc current gain is 320 and the Gummel Number is $10^{12} \text{cm}^{-2}$. Assume that $\tau_n=10^{-7} s$ in the base, $\tau_p=10^{-8}s$ in the collector.

$GN = Q_B = \int_0^{x_B}N_{aB} (x) dx$.

$\phi(S) = 4.05 - (4.05+E_g/2+E_f-E_i)$
\end{multicols}
\newpage

% Get figures Vol IV. Pg 73, Iv p 43
\begin{multicols}{2}
%\begin{minipage}{\linewidth}
%\centering
%\raisebox{-.8in}{
%\includegraphics[width=1\linewidth]{DiffusionCoefficientChart.png}}
%\hspace{1em}
%\parbox[c]{4in}{\captionof{figure}{Diffusion Chart from Lecture I},
%\label{fig:pictureonright}}
%\end{minipage}

\begin{minipage}{\linewidth}
\centering
\raisebox{-.8in}{
\includegraphics[width=1\linewidth]{MOSFETTable.png}}
\hspace{1em}
\parbox[c]{4in}{\captionof{figure}{Vol IV Mosfet table},
\label{fig:pictureonright}}
\end{minipage}
\begin{minipage}{\linewidth}
\centering
\raisebox{-.8in}{
\includegraphics[width=1\linewidth]{MOSFETgraphdopants.PNG}}
\hspace{1em}
\parbox[c]{4in}{\captionof{figure}{Doping dependence of the maximum equilibrium depletion width inside silicon devices maintained at 300 K.},
\label{fig:pictureonright}}
\end{minipage}

\begin{minipage}{\linewidth}
	\centering
	\raisebox{-.8in}{
		\includegraphics[width=1\linewidth]{NeamanTable12-1.png}}
	\hspace{1em}
	%\parbox[c]{4in}{\captionof{figure}{Resistivity Plot},
	\label{fig:pictureonrigh8194}
\end{minipage}
\begin{minipage}{\linewidth}
\centering
\raisebox{-.8in}{
\includegraphics[width=0.6\linewidth]{MOSFETgraphVd_0.PNG}}
\hspace{1em}
\parbox[c]{4in}{\captionof{figure}{Vol IV Mosfet Gate voltages},
\label{fig:pictureonright}}
\end{minipage}

\begin{minipage}{\linewidth}
	\centering
	\raisebox{-.8in}{
		\includegraphics[width=1\linewidth]{Fig43VolIV.png}}
	\hspace{1em}
	\parbox[c]{4in}{\captionof{figure}{Workfunction difference as a function of a n- and p-type dopant conecntration in $n^+$ poly-Si-gate and Al-gate $SiO_2-Si$ structures. ($T=300 K$. $\phi_M^\prime-\chi^\prime=-0.18 \ eV$ for the $n^\prime$ poly-Si-gate structure; $\phi_M^\prime-\chi^\prime=0.03 eV$ for the Al-gate structure.)},
		\label{fig:pictureonright78}}
\end{minipage}
\begin{minipage}{\linewidth}
	\centering
	\raisebox{-.8in}{
		\includegraphics[width=0.7\linewidth]{GroupIIIGroupV.png}}
	%\hspace{1em}
%	\parbox[c]{4in}{\captionof{figure}{Boron Diffusion Chart},
		\label{fig:59}
\end{minipage}

\begin{minipage}{\linewidth}
	\centering
	\raisebox{-.8in}{
		\includegraphics[width=0.7\linewidth]{boronChart.png}}
	\hspace{1em}
	\parbox[c]{4in}{\captionof{figure}{Boron Chart},
		\label{fig:4}}
\end{minipage}
\end{multicols}
\begin{minipage}{\linewidth}
	\centering
	\raisebox{-.8in}{
		\includegraphics[height=1\textheight]{V1Figure3-5.png}}
% 	\hspace{1em}
% 	\parbox[c]{4in}{\captionof{figure}{Diffussion Constant},
% 		\label{fig:pictureonright79}}
\end{minipage}

\begin{minipage}{\linewidth}
	\centering
	\raisebox{-.8in}{
		\includegraphics[width=1\textheight]{VIFigure3-7.png}}
	\hspace{1em}
	%\parbox[c]{4in}{\captionof{figure}{Resistivity Plot},
		\label{fig:pictureonrigh819}
\end{minipage}