% !TEX root = hott_intro.tex

\section{Propositions, sets, and the higher truncation levels}
\sectionmark{Truncation levels}\label{chap:hierarchy}

\index{truncated type|(}
\index{truncation level|(}
%Not all types have interesting higher groupoid structure. For example, we will see below that two natural numbers can only be equal in at most one way. Voevodsky articulated a useful notion to detect the homotopical complexity of types, which allows us to distinguish between contractible types (also called \emph{$(-2)$-types}), \emph{propositions} (also called \emph{$(-1)$-types}), \emph{sets} (\emph{$0$-types}), and \emph{$k$-types} for higher $k$.

%We will see [later] that there are types that are not $k$-types for any $k$.

\subsection{Propositions and subtypes}

\index{proposition|(}
\begin{defn}
A type $A$ is said to be a \define{proposition} if there is a term of type\index{is-prop(A)@{$\isprop(A)$}}
\begin{equation*}
\isprop(A)\defeq\prd{x,y:A}\iscontr(x=y).
\end{equation*}
Given a universe $\UU$, we define $\prop_\UU$\index{Prop@{$\prop$}} to be the type of all small propositions, i.e.,
\begin{equation*}
  \prop_\UU\defeq\sm{X:\UU}\isprop(X).
\end{equation*}
\end{defn}

\begin{eg}\label{eg:prop_contr}
  Any contractible type is a proposition by \cref{ex:prop_contr}\index{contractible type!is a proposition}\index{is a proposition!contractible type}. In particular, the unit type is a proposition.

  However, propositions do not need to be inhabited: the empty type is also a proposition, since\index{empty type!is a proposition}\index{is a proposition!empty type}
\begin{equation*}
\prd{x,y:\emptyt}\iscontr(x=y)
\end{equation*}
follows from the induction principle of the empty type.
\end{eg}

In the following lemma we prove that in order to show that a type $A$ is a proposition, it suffices to show that any two terms of $A$ are equal. In other words, propositions are types with \define{proof irrelevance}.

\begin{thm}\label{lem:isprop_eq}
  Let $A$ be a type. Then the following are equivalent:
  \begin{enumerate}
  \item The type $A$ is a proposition.
  \item Any two terms of type $A$ can be identified, i.e., there is a dependent function\index{is-prop'(A)@{$\isprop'(A)$}}\index{is-prop(A)@{$\isprop(A)$}!is-prop(A) iff is-prop'(A)@{$\isprop(A)\leftrightarrow\isprop'(A)$}}
    \begin{equation*}
      \isprop'(A)\defeq\prd{x,y:A}\id{x}{y}.
    \end{equation*}
  \item The type $A$ is contractible as soon as it is inhabited, i.e., there is a function\index{is-prop(A)@{$\isprop(A)$}!is-prop(A) iff A to is-contr(A)@{$\isprop(A)\leftrightarrow(A\to\iscontr(A))$}}
    \begin{equation*}
      A \to \iscontr(A).
    \end{equation*}
  \item The map $\const_\ttt : A\to\unit$ is an embedding.\index{is-prop(A)@{$\isprop(A)$}!is-prop(A) iff is-emb(const star)@{$\isprop(A)\leftrightarrow\isemb(\const_\ttt)$}}
  \end{enumerate}
\end{thm}

\begin{proof}
  To show that (i) implies (ii), let $A$ be a proposition. Then its identity types are contractible, so the center of contraction of $\id{x}{y}$ is identification $\id{x}{y}$, for each $x,y:A$.

  To show that (ii) implies (iii), suppose that $A$ comes equipped with $p:\prd{x,y:A}\id{x}{y}$. Then for any $x:A$ the dependent function $p(x):\prd{y:A}\id{x}{y}$ is a contraction of $A$. Thus we obtain the function
  \begin{equation*}
    \lam{x}(x,p(x)):A\to\iscontr(A).
  \end{equation*}

  To show that (iii) implies (iv), suppose that $A\to\iscontr(A)$. We first make the simple observation that
  \begin{equation*}
    (X\to \isemb(f))\to \isemb(f)
  \end{equation*}
  for any map $f:X\to Y$, so it suffices to show that $A\to\isemb(\const_\ttt)$. However, assuming we have $x:A$, it follows by assumption that $A$ is contractible. Therefore, it follows by \cref{ex:contr_equiv} that the map $\const_\ttt:A\to\unit$ is an equivalence. Since it is an equivalence, it is an embedding by \cref{cor:emb_equiv}.

  To show that (iv) implies (i), note that if $A\to\unit$ is an embedding, then the identity types of $A$ are equivalent to contractible types and therefore they must be contractible.
\end{proof}

In the following lemma we show that propositions are closed under equivalences.

\begin{lem}\label{lem:prop_equiv}
Let $A$ and $B$ be types, and let $e:\eqv{A}{B}$. Then we have\index{proposition!closed under equivalences}
\begin{equation*}
\isprop(A)\leftrightarrow\isprop(B).
\end{equation*}
\end{lem}

\begin{proof}
We will show that $\isprop(B)$ implies $\isprop(A)$. This suffices, because the converse follows from the fact that $e^{-1}:B\to A$ is also an equivalence.

Since $e$ is assumed to be an equivalence, it follows by \cref{cor:emb_equiv} that
\begin{equation*}
\apfunc{e} : (x=y)\to (e(x)=e(y))
\end{equation*}
is an equivalence for any $x,y:A$. If $B$ is a proposition, then in particular the type $e(x)=e(y)$ is contractible for any $x,y:A$, so the claim follows from \cref{thm:contr_equiv}.
\end{proof}

  In set theory, a set $y$ is said to be a subset\index{subset} of a set $x$, if any element of $y$ is an element of $x$, i.e., if the condition
  \begin{equation*}
    \forall_z (z\in y)\to (z\in x)
  \end{equation*}
  holds. We have already noted that type theory is different from set theory in that terms in type theory come equipped with a \emph{unique} type. Moreover, in set theory the proposition $x\in y$ is well-formed for any two sets $x$ and $y$, whereas in type theory the judgment $a:A$ is only well-formed if it is derived using the postulated inference rules. Because of these differences we must find a different way to talk about subtypes.

  Note that in set theory there is a correspondence between the subsets of a set $x$, and the \emph{predicates} on $x$. A predicate on $x$ is just a proposition $P(z)$ that varies over the elements $z\in x$. Indeed, if $y$ is a subset of $x$, then the corresponding predicate is the proposition $z\in y$. Conversely, if $P$ is a predicate on $x$, then we obtain the subset
  \begin{equation*}
    \{z\in x\mid P(z)\}
  \end{equation*}
  of $x$. Now we have the right idea of subtypes in type theory: they are families of propositions.

\begin{defn}
A type family $B$ over $A$ is said to be a \define{subtype}\index{subtype} of $A$ if for each $x:A$ the type $B(x)$ is a proposition. When $B$ is a subtype of $A$, we also say that $B(x)$ is a \define{property}\index{property} of $x:A$.
\end{defn}

We will show in \cref{thm:subtype} that a type family $B$ over $A$ is a subtype of $A$ if and only if the projection map $\proj 1:\big(\sm{x:A}B(x)\big)\to A$ is an embedding.

\index{proposition|)}

\subsection{Sets}

\index{set|(}
\begin{defn}
  A type $A$ is said to be a \define{set} if it comes equipped with a term of type
  \index{is-set(A)@{$\isset(A)$}}\index{is a set}
\begin{equation*}
\isset(A)\defeq \prd{x,y:A}\isprop(\id{x}{y}).
\end{equation*}
\end{defn}

\begin{lem}
A type $A$ is a set if and only if it satisfies \define{axiom K}\index{axiom K}, i.e., if and only if it comes equipped with a term of type\index{is-set(A)@{$\isset(A)$}!is-set(A) iff axiom-K(A)@{$\isset(A)\leftrightarrow\axiomK(A)$}}
\begin{equation*}
\axiomK(A)\defeq\prd{x:A}\prd{p:\id{x}{x}}\id{\refl{x}}{p}.
\end{equation*}
\end{lem}

\begin{proof}
If $A$ is a set, then $\id{x}{x}$ is a proposition, so any two of its elements are equal.
This implies axiom $K$.

For the converse, if $A$ satisfies axiom $K$, then for any $p,q:\id{x}{y}$ we have $\id{\ct{p}{q^{-1}}}{\refl{x}}$, and hence $\id{p}{q}$. This shows that $\id{x}{y}$ is a proposition, and hence that $A$ is a set.
\end{proof}

\begin{thm}\label{lem:prop_to_id}
Let $A$ be a type, and let $R:A\to A\to\UU$ be a binary relation on $A$ satisfying
\begin{enumerate}
\item Each $R(x,y)$ is a proposition,
\item $R$ is reflexive, as witnessed by $\rho:\prd{x:A}R(x,x)$,
\item There is a map
  \begin{equation*}
    R(x,y)\to (x=y)
  \end{equation*}
  for each $x,y:A$.
\end{enumerate}
Then any family of maps
\begin{equation*}
\prd{x,y:A}(\id{x}{y})\to R(x,y)
\end{equation*}
is a family of equivalences. Consequently, the type $A$ is a set.
\end{thm}

\begin{proof}
Let $f:\prd{x,y:A}R(x,y)\to(\id{x}{y})$.
Since $R$ is assumed to be reflexive, we also have a family of maps
\begin{equation*}
\pathind_x(\rho(x)):\prd{y:A}(\id{x}{y})\to R(x,y).
\end{equation*}
Since each $R(x,y)$ is assumed to be a proposition, it therefore follows that each $R(x,y)$ is a retract of $\id{x}{y}$. Therefore it follows that $\sm{y:A}R(x,y)$ is a retract of $\sm{y:A}x=y$, which is contractible. We conclude that $\sm{y:A}R(x,y)$ is contractible, and therefore that any family of maps
\begin{equation*}
  \prd{y:A}(x=y)\to R(x,y)
\end{equation*}
is a family of equivalences.

Now it also follows that $A$ is a set, since its identity types are equivalent to propositions, and therefore they are propositions by \cref{lem:prop_equiv}.
\end{proof}

\begin{defn}
  A map $f:A\to B$ is said to be \define{injective}\index{injective function} if for any $x,y:A$ there is a map
  \begin{equation*}
    (f(x)=f(y))\to (x=y).
  \end{equation*}
\end{defn}

\begin{cor}\label{cor:is-emb-is-injective}
  Any injective map into a set is an embedding.\index{is an embedding!injective map into a set}
\end{cor}

\begin{proof}
  Let $f:A\to B$ be an injective map between sets. Now consider the relation
  \begin{equation*}
    R(x,y)\defeq (f(x)=f(y)).
  \end{equation*}
  Note that $R$ is reflexive, and that $R(x,y)$ is a proposition for each $x,y:A$. Moreover, by the assumption that $f$ is injective, we have
  \begin{equation*}
    R(x,y)\to (x=y)
  \end{equation*}
  for any $x,y:A$. Therefore we are in the situation of \cref{lem:prop_to_id}, so it follows that the map $\apfunc{f} : (x=y)\to (f(x)=f(y))$ is an equivalence.
\end{proof}

\begin{thm}\label{thm:eq_nat}
The type of natural numbers is a set.\index{is a set!natural numbers}\index{natural numbers!is a set}
\end{thm}

\begin{proof}
We will apply \cref{lem:prop_to_id}. Note that the observational equality $\EqN:\N\to(\N\to\UU)$ on $\N$ (\cref{defn:obs_nat}) is a reflexive relation by \cref{ex:obs_nat_eqrel}, and moreover that $\EqN(n,m)$ is a proposition for every $n,m:\N$ (proof by double induction).
Therefore it suffices to show that
\begin{equation*}
\prd{m,n:\N}\EqN(m,n)\to (\id{m}{n}).
\end{equation*}
This follows from the fact that observational equality is the \emph{least} reflexive relation, which was shown in \cref{ex:obs_nat_least}.
\end{proof}

\begin{comment}
\begin{thm}[Hedberg]\label{thm:dec_eq}
Any type with decidable equality is a set.
\end{thm}

\begin{proof}
Let $A$ be a type, and let $d:\prd{x,y:A}(\id{x}{y})+\neg(\id{x}{y})$ be the witness that $A$ has decidable equality.
We first construct a reflexive binary relation $E:A\to A\to\type$ such that each $E(x,y)$ is a proposition.
For every $x,y:A$, we first define a type family $E'(x,y):((\id{x}{y})+\neg(\id{x}{y}))\to\type$ by
\begin{align*}
E'(x,y,\inl(p)) & \defeq \unit \\
E'(x,y,\inr(p)) & \defeq \emptyt.
\end{align*}
Note that $E'(x,y,q)$ is a proposition for each $x,y:A$ and $q:(\id{x}{y})+\neg(\id{x}{y})$.
Now we set $E(x,y)\defeq E'(x,y,d(x,y))$. Then $E$ is clearly reflexive, and a family of propositions.
Therefore it remains to show that $E$ implies identity.

Since $E$ is defined as an instance of $E'$, it suffices to construct a term of type
\begin{equation*}
\prd{x,y:A}\prd{q:(\id{x}{y})+\neg(\id{x}{y})} E'(q)\to (\id{x}{y}).
\end{equation*}
By induction of disjoint sums, it suffices to construct terms of types
\begin{align*}
& \prd{x,y:A}\prd{p:\id{x}{y}} \unit\to (\id{x}{y}) \\
& \prd{x,y:A}\prd{p:\neg(\id{x}{y})} \emptyt\to (\id{x}{y}).
\end{align*}
In the first case, we take $\lam{x}\lam{y}\lam{p}{t}p$, and the second case is by induction on the empty type.
\end{proof}
\end{comment}
\index{set|)}

\subsection{General truncation levels}

\begin{defn}
We define $\istrunc{} : \Z_{\geq-2}\to\UU\to\UU$ by induction on $k:\Z_{\geq -2}$, taking\index{is-trunc k(A)@{$\istrunc{k}(A)$}}
\begin{align*}
\istrunc{-2}(A) & \defeq \iscontr(A) \\
\istrunc{k+1}(A) & \defeq \prd{x,y:A}\istrunc{k}(\id{x}{y}).\qedhere
\end{align*}
For any type $A$, we say that $A$ is \define{$k$-truncated}\index{k-truncated type@{$k$-truncated type}|see {truncated type}}, or a \define{$k$-type}\index{k-type@{$k$-type}}, if there is a term of type $\istrunc{k}(A)$. We say that a map $f:A\to B$ is $k$-truncated if its fibers are $k$-truncated.\index{k-truncated map@{$k$-truncated map}|see {truncated map}}\index{truncated map}
\end{defn}

%For the rest of this section, let $k:\Z_{\geq-2}$.

\begin{thm}\label{thm:istrunc_next}
If $A$ is a $k$-type, then $A$ is also a $(k+1)$-type.\index{is-trunc k(A)@{$\istrunc{k}(A)$}!is-trunc k(A) to is-trunc k+1(A)@{$\istrunc{k}(A)\to\istrunc{k+1}(A)$}}
\end{thm}

\begin{proof}
We have seen in \cref{eg:prop_contr} that contractible types are propositions. This proves the base case.
For the inductive step, note that if any $k$-type is also a $(k+1)$-type, then any $(k+1)$-type is a $(k+2)$-type, since its identity types are $k$-types and therefore $(k+1)$-types.
\end{proof}

\begin{thm}\label{thm:ktype_eqv}
If $e:\eqv{A}{B}$ is an equivalence, and $B$ is a $k$-type, then so is $A$.\index{truncated type!closed under equivalences}
\end{thm}

\begin{proof}
We have seen in \cref{ex:contr_equiv} that if $B$ is contractible and $e:\eqv{A}{B}$ is an equivalence, then $A$ is also contractible. This proves the base case.

For the inductive step, assume that the $k$-types are stable under equivalences, and consider $e:\eqv{A}{B}$ where $B$ is a $(k+1)$-type. In \cref{cor:emb_equiv} we have seen that
\begin{equation*}
\apfunc{e}:(\id{x}{y})\to(\id{e(x)}{e(y)})
\end{equation*}
is an equivalence for any $x,y$. Note that $\id{e(x)}{e(y)}$ is a $k$-type, so by the induction hypothesis it follows that $\id{x}{y}$ is a $k$-type. This proves that $A$ is a $(k+1)$-type.
\end{proof}

\begin{cor}\label{cor:emb_into_ktype}
If $f:A\to B$ is an embedding, and $B$ is a $(k+1)$-type, then so is $A$.\index{truncated type!closed under embeddings}
\end{cor}

\begin{proof}
By the assumption that $f$ is an embedding, the action on paths
\begin{equation*}
\apfunc{f}:(\id{x}{y})\to (\id{f(x)}{f(y)})
\end{equation*}
is an equivalence for every $x,y:A$. Since $B$ is assumed to be a $(k+1)$-type, it follows that $f(x)=f(y)$ is a $k$-type for every $x,y:A$. Therefore we conclude by \cref{thm:ktype_eqv} that $\id{x}{y}$ is a $k$-type for every $x,y:A$. In other words, $A$ is a $(k+1)$-type.
\end{proof}

\begin{thm}
Let $B$ be a type family over $A$. Then the following are equivalent:\index{truncated family of types}
\begin{enumerate}
\item For each $x:A$ the type $B(x)$ is $k$-truncated. In this case we say that the family $B$ is \define{$k$-truncated}.
\item The projection map
\begin{equation*}
\proj 1 : \Big(\sm{x:A}B(x)\Big)\to A
\end{equation*}
is $k$-truncated.
\end{enumerate}
\end{thm}

\begin{proof}
By \cref{ex:proj_fiber} we obtain equivalences
\begin{equation*}
\eqv{\fib{\proj 1}{x}}{B(x)}
\end{equation*}
for every $x:A$. Therefore the claim follows from \cref{thm:ktype_eqv}.
\end{proof}

\begin{thm}\label{thm:trunc_ap}
Let $f:A\to B$ be a map. The following are equivalent:
\begin{enumerate}
\item The map $f$ is $(k+1)$-truncated.
\item For each $x,y:A$, the map
\begin{equation*}
\apfunc{f} : (x=y)\to (f(x)=f(y))
\end{equation*}
is $k$-truncated.
\end{enumerate}
\end{thm}

\begin{proof}
First we show that for any $s,t:\fib{f}{b}$ there is an equivalence
\begin{equation*}
\eqv{(s=t)}{\fib{\apfunc{f}}{\ct{\proj 2(s)}{\proj 2(t)^{-1}}}}
\end{equation*}
We do this by $\Sigma$-induction on $s$ and $t$, and then we calculate
\begin{align*}
(\pairr{x,p}=\pairr{y,q}) & \eqvsym \Eqfib_f((x,p),(y,q)) \\
  & \jdeq \sm{\alpha:x=y} p=\ct{\ap{f}{\alpha}}{q} \\
  & \eqvsym \sm{\alpha:x=y} \ct{\ap{f}{\alpha}}{q}=p \\
& \eqvsym \sm{\alpha:x=y} \ap{f}{\alpha}=\ct{p}{q^{-1}} \\
& \jdeq \fib{\apfunc{f}}{\ct{p}{q^{-1}}}.
\end{align*}
By these equivalences, it follows that if $\apfunc{f}$ is $k$-truncated, then for each $s,t:\fib{f}{b}$ the identity type $s=t$ is equivalent to a $k$-truncated type, and therefore we obtain by \cref{thm:ktype_eqv} that $f$ is $(k+1)$-truncated.

For the converse, note that we have equivalences
\begin{align*}
\fib{\apfunc{f}}{p} & \eqvsym ((x,p)=(y,\refl{f(y)})).
\end{align*}
It follows that if $f$ is $(k+1)$-truncated, then the identity type $(x,p)=(y,\refl{f(y)})$ in $\fib{f}{f(y)}$ is $k$-truncated for any $p:f(x)=f(y)$. We conclude by \cref{thm:ktype_eqv} that the fiber $\fib{\apfunc{f}}{p}$ is $k$-truncated.
\end{proof}

\begin{cor}\label{cor:prop_emb}
A map is an embedding if and only if its fibers are propositions.\index{is an embedding!-1-truncated map@{$(-1)$-truncated map}}
\end{cor}

\begin{cor}\label{thm:subtype}
A type family $B$ over $A$ is a subtype if and only if the projection map
\begin{equation*}
\proj 1 : \Big(\sm{x:A}B(x)\Big)\to A
\end{equation*}
is an embedding.
\end{cor}

\begin{thm}
Let $f:\prd{x:A}B(x)\to C(x)$ be a family of maps. Then the following are equivalent:
\begin{enumerate}
\item For each $x:A$ the map $f(x)$ is $k$-truncated.
\item The induced map
\begin{equation*}
\tot{f}:\Big(\sm{x:A}B(x)\Big)\to\Big(\sm{x:A}C(x)\Big)
\end{equation*}
is $k$-truncated.
\end{enumerate}
\end{thm}

\begin{proof}
This follows directly from \cref{lem:fib_total,thm:ktype_eqv}.
\end{proof}

\begin{exercises}
\exercise
  \begin{subexenum}
  \item Show that $\succN:\N\to\N$ is an embedding.\index{succ N@{$\succN$}!is an embedding}\index{is an embedding!succ N@{$\succN$}}
  \item Show that $n\mapsto m+n$ is an embedding, for each $m:\N$.\index{add N@{$\addN$}!add N(m) is an embedding@{$\addN(m)$ is an embedding}}\index{is an embedding!add N(m)@{$\addN(m)$}} Moreover, conclude that there is an equivalence
    \begin{equation*}
      \fib{\addN(m)}{n}\simeq (m\leq n).
    \end{equation*}
  \item Show that $n\mapsto mn$ is an embedding\index{mul N@{$\mulN$}!mul N(m) is an embedding if m>0@{$\mulN(m)$ is an embedding if $m>0$}}\index{is an embedding!mul N(m) for m > 0@{$\mulN(m)$ for $m>0$}}, for each $m>0$ in $\N$. Conclude that the divisibility relation\index{d {"| n}@{$d\mid n$}!is a proposition if d>0@{is a proposition if $d>0$}}\index{is a proposition!d {"| n} for d>0@{$d\mid n$ for $d>0$}}
    \begin{equation*}
      d\mid n
    \end{equation*}
    is a proposition for each $d,n:\N$ such that $d>0$.
  \end{subexenum}
\exercise \label{ex:diagonal}Let $A$ be a type, and let the \define{diagonal} of $A$ be the map $\delta_A:A\to A\times A$ given by $\lam{x}(x,x)$.
\begin{subexenum}
\item Show that
\begin{equation*}
{\isequiv(\delta_A)}\leftrightarrow{\isprop(A)}.
\end{equation*}
\item Construct an equivalence $\eqv{\fib{\delta_A}{(x,y)}}{(x=y)}$ for any $x,y:A$.
\item Show that $A$ is $(k+1)$-truncated if and only if $\delta_A:A\to A\times A$ is $k$-truncated.
\end{subexenum}
\exercise \label{ex:istrunc_sigma}
\begin{subexenum}
\item Let $B$ be a type family over $A$. Show that if $A$ is a $k$-type, and $B(x)$ is a $k$-type for each $x:A$, then so is $\sm{x:A}B(x)$. Conclude that for any two $k$-types $A$ and $B$, the type $A\times B$ is also a $k$-type. Hint: for the base case, use \cref{ex:contr_in_sigma,ex:contr_equiv}.
\item Show that for any $k$-type $A$, the identity types of $A$ are also $k$-types.
\item Show that any maps $f:A\to B$ between $k$-types $A$ and $B$
is a $k$-truncated map.
\item Use \cref{ex:proj_fiber} to show that for any type family $B:A\to \UU$, if $A$ and $\sm{x:A}B(x)$ are $k$-types, then so is $B(x)$ for each $x:A$.
\end{subexenum}
\exercise \label{ex:eq_bool}Show that $\bool$ is a set by applying \cref{lem:prop_to_id} with the observational equality on $\bool$ defined in \cref{ex:obs_bool}.
\exercise \label{ex:set_coprod}Show that for any two $(k+2)$-types $A$ and $B$, the disjoint sum $A+B$ is again a $(k+2)$-type. Conclude that $\mathbb{Z}$ is a set.
\exercise Use \cref{ex:contr_retr,ex:retr_id} to show that if $A$ is a retract of a $k$-type $B$, then $A$ is also a $k$-type.
\exercise Show that a type $A$ is a $(k+1)$-type if and only if the map $\const_x:\unit\to A$ is $k$-truncated for every $x:A$.
\exercise Consider a commuting triangle
\begin{equation*}
\begin{tikzcd}[column sep=tiny]
A \arrow[rr,"h"] \arrow[dr,swap,"f"] & & B \arrow[dl,"g"] \\
& X
\end{tikzcd}
\end{equation*}
with $H: f \htpy g \circ h$, and suppose that $g$ is $k$-truncated. Show that $f$ is $k$-truncated if and only if $h$ is $k$-truncated.
% Suppose that $h$ is $k$-truncated and surjective. Show that $f$ is $(k+1)$-truncated if and only if $g$ is $(k+1)$-truncated.
\end{exercises}
\index{truncated type|)}
\index{truncation level|)}


% !TEX root = index.tex
\maketitle
\tableofcontents
\newpage

\setcounter{section}{-1}
\section{Introduction \& Motivation}
\epigraph{In mathematics you don't understand things. You just get used to them.}{John von Neumann}

Cohomology was introduced by Poincare in a series of papers named \emph{Analysis Situs} and now forms the basis of modern Algebraic Topology.
To a topological space $X$ we can associate a sequence of vector spaces denoted
\begin{align*}
    \check H^i(X)
\end{align*}
for each $i \in \Z_{\ge 0}$ called it's \textbf{Cech Cohomology} (pronounced \emph{check cohomology}). In a very loose sense, the dimension of  $\check H^i(X)$ measures the $i^{th}$ dimensional holes in $X$.\\

Why care about the $i^{th}$ dimensional holes? We can use these to rigorously distinguish between spaces. For example, most proofs of the fact that $\R^m$ is not homeomorphic\footnote{Homeomorphism is the isomorphism for topological spaces.} to $\R^n$ if $m \neq n$ use some cohomology computation. We'll also see that a torus $S^1 \times S^1$ has two \emph{1-dimensional holes} which distinguishes it from a sphere $S^2$ which has none.

\begin{thm}
  Two topological spaces $X$, $Y$ are homeomorphic only if
  \begin{align*}
    \check H^i(X) \cong \check H^i(Y)
  \end{align*} for all non-negative integers $i$.
\end{thm}
\begin{remark}
  The above statement is not an \emph{if and only if} statement. The other direction is easily shown to be false. You'll be able to come up with examples by yourself in a couple of days.
\end{remark}

Computing the cohomology requires multiple steps. The goal of this class is to develop the relevant machinery and actually do some cohomology computations.
\begin{align*}
 \xymatrix@R-2pc{
 X \ar@{~>}[r] & \U \ar@{~>}[r] & \L^\bullet(\U) \ar@{~>}[r] & \check H^*(X)\\
 \mbox{Topological Space} & \mbox{Good cover of } X & \mbox{Cech Complex of } \U & \mbox{Cech Cohomology of } X
 }
\end{align*}

\noindent \textbf{Note:} The number of stars (*) on the problems indicate their difficulty level. The non-starred marked problems are compulsory, the starred problems are optional.

% We'll gradually define Cech cohomology. The strategy is the following.
% \begin{enumerate}
% 	\item For a space $ X$, find a good open cover $ \U$
% 	\item Find the Cech complex (to be defined) $ \L^\bullet(\U)$ associated $ \U$
% 	\item Find the cohomology of the complex $H^*(\L^\bullet(\U))$ which then equals the singular cohomology of the space $H^*(X, \F)$.
% \end{enumerate}
%
% \begin{remark}
% 	When $X$ is a nice enough space (which includes most spaces you can think of) the Cech cohomology $\check H^i(X; \F)$ equals another purely topological invariant of $X$ called the \textbf{singular homology}. And thus Cech cohomology provides a purely algebraic way of computing a topological invariant.
% \end{remark}


\documentclass[reprint,showpacs,prb,nofootinbib,amsmath,amssymb]{revtex4-1}

\usepackage{listings}
\usepackage{graphicx}% Include figure files
\usepackage{dcolumn}% Align table columns on decimal point
\usepackage{bm}% bold math
\usepackage{breqn}
\usepackage{verbatim}   % useful for program listings
\usepackage{appendix}
\usepackage{hyperref}
\usepackage{footnote}
\usepackage{url}

\begin{document}

\title{\textit{LineFit}: a Matlab Toolbox for 1D Line Fitting}
\author{Zhang Jiang}
%    X-ray Science Division\\
%    Advanced Photon Source\\
%    Argonne National Laboratory\\
%    zjiang@aps.anl.gov}
\date{\today}
%\date{October 21, 2016}
\maketitle
\tableofcontents
%\newpage

\section{Overview}

\verb|Linefit| is a toolbox for 1D line  fitting. In addition to over 30 built-in curve models, it allows combing those built-in model or customizing new models. As a class object, \verb|linefit|'s properties and methods allow one to customize fitting options, easily switch on/off parameters for fitting, evaluate models, and calculate model properties. It provides both script mode for batch processing and GUI mode for interactive fitting.

\verb|Linefit| works on Matlab 2015b or later. It requires Matlab Optimization Toolbox for \verb|lsqcurvefit| solver.

\section{Installation}

Add the \verb|linefit| directory to Matlab search path either from the \verb|Set Path| in Matlab Home tab or run \verb|>>addpath <your path>/linefit| in the command window. If Voigt distribution function is used, one needs add the Faddeeva~\cite{Faddeeva} sub-directory.

\section{Usage}

We use `curve' to denote the model for fitting and 'bkgd' to denote the model for background. They are stored as fields in private property \verb|linefit.ModelBase|
\begin{align}
	\mbox{CurveModel} 	&: \mbox{[1x1 struct]} \nonumber \\
	\mbox{BkgdModel}	&: \mbox{[1x1 struct]} \nonumber
\end{align}
Each field itself is a structure consisting of model function handle, number of parameters, start values, lower and upper bounds, fit flags, and etc. For example, \verb|CurveModel| has default fields:
\begin{align}
	\mbox{ModelFcnHandle} 	&: \mbox{@linefit.lorentzian} \nonumber \\
	\mbox{NOfParams}	&: \mbox{[3 1]} \nonumber \\
	\mbox{StartParams}	&: \mbox{[3x1 double]} \nonumber \\
	\mbox{LowerBounds}	&: \mbox{[3x1 double]} \nonumber \\
	\mbox{UpperBounds}	&: \mbox{[3x1 double]} \nonumber \\
	\mbox{FitFlags}		&: \mbox{[3x1 double]} \nonumber \\
	\mbox{ModelName}	&: \mbox{`Cauchy/Lorentzian'} \nonumber \\
	\mbox{ModelUsage}	&: \mbox{`lorentzian(x,[amp,x0,gamma])'} \nonumber \\
	\mbox{FitStdErrors}	&: \mbox{[3x1 double]} \nonumber
\end{align}
\verb|FitFlags| is a logical matrix with 1 for fitting and 0 fixed parameters. \verb|FitStdErrors| is a place holder to store the standard deviations after fitting; and its initial value is set to -1 (also an indicator for non-fitting parameters). \verb|ModelBase| is a private property that cannot be directly changed by users. Instead, the curve and background models can be indirectly changed to other built-in models by setting properties \verb|CurveModelIndex| and \verb|BkgdModelIndex| (see Appendix~\ref{app:properties} for details). After a new \verb|linefit| object is created and loaded with 2-column data into property \verb|Data|, \verb|ModelBase| is automatically copied to a public property \verb|Model|, whose field values such as start values, lower and upper bounds, and fit flags can be directly changed. Such way of managing models allows an easy setup for models with multiple curves of the same curve type (e.g. crystallography profiles with multiple peaks). This is achieved simply by adding or reducing number of curves in the \verb|Model.CurveMode| (via method \verb|addcurves| and \verb|reducecurves|) while keeping the base curve model unchanged in \verb|ModelBase|.

There is no better way to demonstrate than going through examples.

\subsection{Script Mode}

\subsubsection{Fitting a double-peak profile}
Create a \verb|linefit| object and load data
\begin{eqnarray*}
&&\verb|foo=load(`demo_doublpeak.dat')| \\
&&\verb|a=linefit(foo)|
\end{eqnarray*}

Instead of default settings of Lorentzian curve mode and no background, we two Gaussian curves and constant background
\begin{eqnarray*}
	&&\verb|a.CuveModelIndex=4 % Gaussian| \\
	&&\verb|a.BkgdModelIndex=1 % constant background| \\
	&&\verb|a=addcurves(a,1)   % add a curve to the end|
\end{eqnarray*}
After method \verb|addcurves| appends another Gaussian curve to the model, a new \verb|linefit| is returned and assigned back to the original object \verb|a|.

To preview the model with start parameter values
\begin{eqnarray*}
&&\verb|plot(a)| \text{  or } \verb|plot(a,`preview')|
\end{eqnarray*}

\verb|Linefit| uses built-in Matlab solver \verb|lsqcurvefit|. The optimization options are identical to those for \verb|lsqcurvefit|, and can be accessed or changed in property \verb|FitOptions|.

To start fitting,
\begin{eqnarray*}
	&&\verb|a=startfit(a)|
\end{eqnarray*}
Fit results, such as fitted parameters and their standard deviations, squared norm of the residual, residuals, exit flag (reason to stop fitting), output (information about fitting process), Jacobian at the solution, and etc., are temporarily saved in \verb|FitOutput| waiting for acceptance or rejection.
\begin{eqnarray*}
	&&\verb|plot(a,`fit')|
\end{eqnarray*}
plots the the fitted curve on the raw data, as well as the residuals.
\begin{eqnarray*}
	&&\verb|a=acceptfit(a)|
\end{eqnarray*}
accepts fit result and updates start values (\verb|StartParams|) and standard deviations (\verb|FitStdErrors|) for both \verb|CurveModel| and \verb|BkgdModel|. Nothing needs to be done to reject.

You can then get the model properties (if defined for the model) such as mean, variance, median, skewness, kurtosis, and etc, either analytically or numerically,
\begin{eqnarray*}
	&&\verb|getmodelprops(a) 	% analytical method| \\
	&&\verb|getmodelprops(a,linspace(-100,100,1000))| \\
	&&\verb|                  % numerical method|
\end{eqnarray*}

You may evaluate the model (calculate the y values) on provided x data or any list of x data by
\begin{eqnarray*}
	&&\verb|y=evalmodel(a) 	% on provided x data| \\
	&&\verb|y=evalmodel(a,-100:0.1:100)|\\
	&&\verb|	               % on other x data|
\end{eqnarray*}
Note that because \verb|getmodelprops| and \verb|evalmodel| use the start values (see Appendix~\ref{app:methods}), you need to accept fit result first if you wish to get the properties and model evaluations on fit result.

\subsubsection{Customized or combined curve models}\label{sec:custommodel}

Now we demonstrate how to create a customized or combined curve model.

Still use the data from the last example. Suppose the customized curve model is
\begin{equation}
f(x)=A\exp\left(-|x-x_0|^3/b\right) \nonumber
\end{equation}
We need to first create the custom model (see Appendixe~\ref{app:methods} for usage details) by
\begin{widetext}
\begin{eqnarray*}
\verb|a.CustomCurveModel=linefit.createmodel(|&&\verb|@(x,p)p(1)*exp(-abs(x-p(2)).^3/p(3)),| \\
&&\verb|3,[1,0,5],[0,-1,0],[100,10,Inf],[1,1,1])|
\end{eqnarray*}
\end{widetext}
where the 1st argument is an anonymous function handle whose expression must be vectorized (e.g. using the `.' for the power, multiplication, division etc), the 2nd argument is the total number of parameters, and the 3rd-6th arguments are start values, lower bounds, upper bounds, and fit flags. The 3rd-6th arguments can be empty [ ] to use the default settings: random values for start values, -Inf's for lower bounds, Inf's for upper bounds, and 1s for fit flags. One can also create a customized model by working out the function in a Matlab .m file. Let's say file \verb|myfun.m| has the function defined by the following lines
\begin{eqnarray*}
	&&\verb|function y=myfun(x,p)| \\
	&&\verb|y=p(1)*exp(-abs(x-p(2)).^3/p(3));|
\end{eqnarray*}
This file has to be in the current working directory or wherever Matlab can see it from its path settings. We then create the model by
\begin{widetext}
	\begin{eqnarray*}
		\verb|a.CustomCurveModel=linefit.creatmodel(|&&\verb|@(x,p)myfun,3,[1,0,5],[0,-1,0],[100,10,Inf],[1,1,1])|
	\end{eqnarray*}
\end{widetext}
The customized model is then loaded to \verb|ModelBase| by setting \verb|CurveModeIndex| to -2.
\begin{eqnarray*}
	&&\verb|a.CurveModelIndex=-2;|
\end{eqnarray*}
We then add one more curve of the same model and start the fitting
\begin{eqnarray*}
&&\verb|a=addcurves(a,1);| \\
&&\verb|a=a.startfit;|
\end{eqnarray*}
Note that analytical model properties are not defined for customized models; instead, use numerical method.

If one Lorentzian and one Gaussian are desired to model the double peak data, we can combine these two built-in models by creating a multi-model
\begin{eqnarray*}
	\verb|a.CustomCurveModel=|&&\verb|a.creatmodel([1,4],[],|\\
	&&\verb|[],[],[],[],[])|
\end{eqnarray*}
where the 1st argument \verb|[1,4]| are the index for Lorentzian and Gaussian. The number of parameters is automatically set to the total number of parameters of these two built-in models; thus the 2nd argument is left empty. The other arguments are also left empty to use the default settings. We then load this multi-model to \verb|ModelBase| by setting the model index to -1
\begin{eqnarray*}
	&&\verb|a.CurveModelIndex=-1;|
\end{eqnarray*}
If you get to this step by continuing the last example where two curves are used, you need to reduce the number of curves to one, because the multi-model itself is a double-peak profile although it is considered as a one curve model.
\begin{eqnarray*}
\verb|a=reducecurves(a,2)|
\end{eqnarray*}
where the 2nd argument is the index(es) of the current curves to be removed in \verb|Model.CurveModel|.

Customized background model can be created in the same way as the customized curve model, but one cannot combine built-in background models. Multiple background models of the same type are not allowed either.

\subsection{GUI Mode}
\begin{figure*}
	\centering
	\includegraphics[width=.8\linewidth]{fig}
	\caption{Top: GUI; Bottom left: manually find peaks; Bottom right: plot after fitting.}
	\label{fig:fig}
\end{figure*}

Although \verb|linefit| toolbox is fully functional in the script model, a GUI interface (\verb|linefitgui|) provides a faster access if there are not too many data sets to be managed. Let's demonstrate with an example. Start GUI and load data
\begin{eqnarray*}
	&&\verb|foo=load(`demo_xtal.data');| \\
	&&\verb|linefitgui(foo)|
\end{eqnarray*}
One also start GUI first by \verb|linefitgui| and load data from there. Complete the fitting by following the steps in Fig.~\ref{fig:fig}.

To use customized model or multi-mode In GUI mode, enter the arguments only separated by commas in the Customization edit boxes, e.g.,
\begin{eqnarray*}
	&&\verb|@(x,p)p(1)*exp(-abs(x-p(2)).^3/p(3)),| \\
	&&\verb|3,[1,0,5],[0,-1,0],[100,10,Inf],[1,1,1]|
\end{eqnarray*}
or
\begin{eqnarray*}
\verb|[1,4],[],[],[],[],[],[]|
\end{eqnarray*}
There is no need to enter the method name \verb|createmodel|. Then use the Select Model popupmenu to change the model index to customized model or multi-model.

\appendix
\appendixpage
\addappheadtotoc
\section{List of \textbf{linefit} properties}\label{app:properties}
In Matlab command window, type \verb"linefit" to view the default properties of a \verb"linefit" object.
\allowdisplaybreaks{
\begin{align}
\mbox{Data} 				&: \mbox{[]} \nonumber \\
\mbox{CurveModelIndex}		&: \mbox{1} \nonumber \\
\mbox{BkgdModelIndex}       &: \mbox{0} \nonumber \\
\mbox{CustomCurveModel}     &: \mbox{[1x1 struct]}  \nonumber \\
\mbox{CustomBkgdModel}      &: \mbox{[1x1 struct]}  \nonumber \\
\mbox{Model}         		&: \mbox{[1x1 struct]}  \nonumber \\
\mbox{FlagNonNegBkgd}       &: \mbox{1}  \nonumber \\
\mbox{FlagLogScale}         &: \mbox{0}  \nonumber \\
\mbox{FitOptions}     		&: \mbox{[1x1 optim.options.Lsqcurvefit]} \nonumber \\
\mbox{FitOutput}            &: \mbox{[1x1 struct]}  \nonumber \\
\mbox{ModelList}            &: \mbox{[1x30 struct]}  \nonumber \\
\mbox{PeaksFound}           &: \mbox{[]}  \nonumber \\
\mbox{ModelBase}            &: \mbox{[1x1 struct]}  \nonumber \\
\mbox{NOfModelCurves}       &: \mbox{1}  \nonumber
\end{align}
}

Public properties that are independent and can be set or accessed by users are
\begin{itemize}
\item \verb"Data": (Public) Input data. Must be a 2-column double or single type data [XData,YData].
\item \verb"CurveModelIndex": (Public) Index of curve models. In Matlab command window, type \verb"linefit.getmodellist" to display all models, usage and initial parameters.
\item \verb"BkgdModelIndex": (Public) Index of background models. -2/-1/[0]/1/2/3/../N: Custom/Power/[No]/Constant/Linear/Quadratic/.../Polynomial of degree N.
\item \verb"CustomCurveModel": (Public) Structure to store custom or multi curve model. Can be created with \verb"createmodel" method.
\item \verb"CustomBkgdModel": (Public) Structure to store custom background model. Can be created with \verb"createmodel" method.
\item \verb"Model": (Public) Complete fit model including both curve and background models (\verb"CurveModel" and \verb"BkgdModel").
\item \verb"FlagNonNegBkgd": (Public) Flag to force a non-negative background. 0/[1]: no/[yes].
\item \verb"FlagLogScale": (Public) Flag to fit in log scale for YData. [0]/1: [no]/yes.
\item \verb"FitOptions": (Public) Optimization options for solver \verb"lsqcurvefit". See Matlab help or documentation for \verb"lsqcurvefit".
\item \verb"FitOutput": (Public) Structure to store fitting result.
\item \verb"ModelList": (Private) Definition of built-in models.
\item \verb"PeaksFound": (Private) Peak value and positions ([Y, X]) for the initialization of peak-shaped models.
\item \verb"ModelBase": (Private) Base curve model and background model for fitting. \verb|ModelBase.CurveModel| is replicated to \verb"Model.CurveModel" if multiple identical curves are used (\verb|NOfModelCurves|). \verb|ModelBase| can be changed only via \verb|CurveModelIndex|.
\item \verb"NOfModelCurves": Number of curves. It can be increased or decreased by methods \verb|addcurves| and \verb|reducecurves|.
\end{itemize}

\section{List of \textbf{linefit} methods}\label{app:methods}

Dynamic methods can be called in two ways: \verb|obj.MethodName(argument1,...)| or \verb|MethodName(obj,argument1,...)|. The 2nd way will be adopted below. Static methods can be called like the 1st way for dynamic methods; they can also be directly called by \verb|linefit.MethodName(argument1,...)| without first creating an object.

\begin{itemize}
\item \verb|linefit| (dynamic): Create a new \verb"linefit" object.

\verb|obj=linefit| creates an empty object.

\verb|obj=linefit(data)| creates an object with \verb|data| and default settings.

\item \verb|addcurves| (dynamic): Add curves of identical \verb|ModelBase.CurveModel| to \verb|Model.CurveModel|.

\verb|obj2=addcurves(obj1)| adds one curve to the end.

\verb|obj2=addcurves(obj1,n)| adds \verb|n| curves to the end.

\verb|obj2=addcurves(obj1,n,pos)| adds \verb|n| curves to position \verb|pos|. \verb|pos| must be a non-zero integer. The value of \verb|pos| (i.e. \verb"|pos|") is the position; the sign of \verb|pos| is the direction (i.e. + means an insertion after \verb"|pos|" and - means an insertion before \verb"|pos|").

This method creates a new object \verb|obj2|. Setting \verb|obj2| to \verb|obj1| as the output argument avoids creating a new object.

\item \verb|reducecurves| (dynamic): Reduce curves from \verb|Model.CurveModel|.

\verb|obj2=reducecurves(obj1)| reduces the last one curve in the list end.

\verb|obj2=reducecurves(obj1,index)| reduces curves of position \verb|index|. \verb|index| must be a scalar or a vector, e.g., [2,5:7] removes curve \#2, \#5, \#6, and \#7.

\item \verb|sortcurves| (dynamic): Sort the order of curves in \verb|Model.CurveModel|.

\verb|obj2=sortcurves(obj1,row)| sorts the curves with default \verb|mode=`ascend'| according to the values in row number \verb|row|, i.e. the index position of the parameters. For example, \verb|row=2| sorts the order of the two curves by the values of the parameters values in \verb|p(2)| in the example in Section~\ref{sec:custommodel}.

\verb|obj2=sortcurves(obj1,row,mode)| sorts with \verb|mode=`ascend'| or \verb|`descent'|.

\item \verb|startfit| (dynamic): Start fitting.

\verb|obj2=startfit(obj1)| starts fitting and stores fit result in \verb|obj2.FitOutput|.

\item \verb|acceptfit| (dynamic): Accept and pass fit result to fields \verb|StartParams| and \verb|FitStdErrors| in \verb|Model.CurveModel| and \verb|Model.BkgdModel|.

\verb|obj2=accetpfit(obj1)| returns to a new object \verb|obj2|.

\item \verb|evalmodel| (dynamic): Evaluate \verb|Model|.

\verb|y=evalmodel(obj)| evaluates using XDATA in \verb|obj.Data| and returns values to \verb|y|.

\verb|y=evalmodel(obj,XV)| evaluates on a vector \verb|XV|.

\verb|[y,iy]=evalmodel(obj,...)| also returns the values for each curve to \verb|iy|.

\verb|[y,iy,bkgd]=evalmodel(obj,...)| also returns the background values to \verb|bkgd|.

\item \verb|plot| (dynamic): Plot model calculations with start parameters or fitted parameters.

\verb|plot(obj)| preview model calculations using parameters in \verb|obj.Model|.

\verb|plot(obj,mode)| plots model calculations when \verb|mode=`preview'|, and fitting result when \verb|mode=`fit'|. Default is \verb|mode=`preview'|. The \verb|`fit'| mode also plots the residual and labels the Pearson's $\chi2$, which are defined by
\begin{eqnarray*}
\mathrm{Residual}(x_i)&=&f(x_i)-y_i \\
\chi^2&=&\sum_{i}^{n}\frac{\left[f(x_i)-y_i\right]^2}{y_i}
\end{eqnarray*}

\verb|hlines=plot(obj,...)| returns the handle of the plotted data line.

\item \verb|findpeakauto| (dynamic): Automatically search for peaks in \verb|Data|.

\verb|obj2=findpeakauto(obj1)| uses function \verb|peakfinder.m| to find peaks~\cite{peakfinder} and stores them to \verb|obj2.peaksfound|.

\verb|obj2=findpeakauto(obj1,arg1,arg2...)| uses arguments defined in \verb|peakfinder|.

\item \verb|findpeakmanual| (dynamic): Manually and interactively search for peaks.

\verb|obj2=findpeakmanual(obj1)| uses interactive tool \verb|getpts| (requires Matlab Image Processing Toolbox) to identify peaks.

\item \verb|getmodelprops| (dynamic): Get curve model properties such as mean, variance, FWHM, skewness, kurtosis, and etc.

\verb|s=getmodelprops(obj)| gets curve model properties using analytical method and returns to a structure \verb|s|.

\verb|s=getmodelprops(obj,XV)| numerically calculates model properties using x values \verb|XV|. \verb|XV| must be a vector. Suppose function $f(x)$ is normalized, i.e., $\int{f(x)dx}=1$. Mean value is then calculated by with Matlab numerical integration function \verb|trapz|,
\begin{equation}
\mu=\int{xf(x)dx}; \nonumber
\end{equation}
the variance (the 2nd central momentum) is calculated by
\begin{equation}
\mu_2=\int{(x-\mu)^2f(x)dx}; \nonumber
\end{equation}
skewness is calculated by
\begin{equation}
\gamma_1=\frac{\mu_3}{\sigma^3},\nonumber
\end{equation}
where $\mu_3=\int{(x-\mu)^3f(x)dx}$ is the 3rd central momentum, and $\sigma=\sqrt{\mu_2}$ is the standard deviation; and excess kurtosis is calculated by
\begin{equation}
\gamma_2=\frac{\mu_4}{\sigma^4}-3,\nonumber
\end{equation}
where $\mu_4=\int{(x-\mu)^4f(x)dx}$ is the 4th central momentum.

\item \verb|applypeaks| (dynamic): Pass peak values and positions in \verb|PeaksFound| to \verb|Model.CurveModel.StartParams|, and set the number of curves to the number of peaks found.

\verb|obj2=applypeaks(obj1)| passes to the 1st and 2nd input parameters (peak amplitudes and positions) for built-in curve models \#1-18 (peak-shaped models).

\verb|obj2=applypeaks(obj1,rows)| passes to \verb|rows| of \verb|Model.CurveModel.StartParams|. \verb|rows| must be a two-element vector with the 1st value for peak amplitude row and 2nd  value for peak location row. For example, \verb|rows|=[3,4] means that, in the model, the 3rd parameter is the peak amplitude and the 4th  parameter is the peak location (x value).

\item \verb|createmodel| (static): Create model structure for \verb|linefit| object

\verb|s=linefit.createmodel(fcn_handle,nofp,| \verb|startparams,lowerbounds,upperbounds,fitflags)|. \verb|fcn_handle| is the function handle for the model. \verb|nofp| is the number of total parameters in the model. \verb|startparams|, \verb|lowerbounds|, and \verb|upperbounds| are initial parameters, lower and upper bounds for the fitting. \verb|fitflags| is logical flags (false/true or 0/1) to indicate whether the parameter is to be fixed or fitted. \verb|startparams|, \verb|lowerbounds|, \verb|upperbounds|, and \verb|fitflags| must be either vector of dimension \verb|nofp|$\times1$, or empty \verb|[]| for default values (random values for \verb|startparams|,
-Inf, Inf and 1 for \verb|lowerbounds|, \verb|upperbounds|, and \verb|fitflags|).

\verb|fcn_handle| must have the format \verb|@(x,p)UserFcn(x,p)| where \verb|x| is the input x value, \verb|p| is a vector of parameters; or it can be an anonymous function, e.g.,
\verb|f=@(x,p)p(1)+p(2)*x+p(3)*sin(x)| (which gives a value  of 3.7296 when
x=4 and p=[2,1,3], i.e. \verb|f(4,[2,1,3])=3.7296|).

For a multi-model (\verb|CurveModelIndex=-1|) where the \verb|Model.CurveModel| is constructed as a sum of built-in models, use \verb|s=createmodel(models,[],startparams,| \verb|lowerbounds,upperbounds,fitflags)|, where \verb|models| is a list of indexes of built-in models, e.g., \verb|models[1,4,13]| constructs a multi-model using the sum of Lorentzian (model \#1), Gaussian (model \#4) and Voigt (model \#13). The default of \verb|nofp| is automatically set to the total number of parameters of these built-in models.

\verb|s=createmodel(...,fitflags,modelname)| takes a name (string) for the model. It is automatically set to empty if not specified, or forced to be built-in model indexes when \verb|CurveModelIndex=-1|.

\verb|s=createmodel(...,modelname, modelusage)| takes usage instructions (string) for the model.

\item \verb|lineprops| (static): Numerically calculate line properties.

\verb|s=obj.lineprops(data)| or \verb|s=linefit.| \verb|lineprops(data)| calculates properties for a 2-column \verb|data|. It outputs a structure \verb|s| with fields: \verb|s.area| for numerically integrated area (using Matlab \verb|trapz| function); \verb|s.peak| for the peak X, Y values, and position index; \verb|s.mean|, \verb|s.variance|, \verb|s.skewness|, \verb|s.kurtosis|, and \verb|s.fwhm| for mean, variance, skewness, kurtosis, and full-width-of-half-maximum (FWHM); and \verb|s.fwhm_x| for the center position of FWHM.

\item \verb|getmodellist| (static): Get the list of built-in models with name, usage, inital parameters, bounds and etc.

\verb|s=obj.getmodellist| or \verb|s=linefit.| \verb|getmodellist| returns to a table \verb|s|.

\end{itemize}

\section{List of \textbf{linefit} built-in curve models}\label{app:builtin}

These functions are defined as static methods, which can be called the same way as other \verb|linefit| static methods. General usage of these functions is \verb|y=linefit.function_name(x,p)| or \verb|[y,props]=| \verb|linefit.function_name(x,p)|, where \verb|p| is the parameter vector defined below, and \verb|props| is a structure for model properties, such as mean, variance and etc.

Note that not all functions have analytical formulas for mean, variance, skewness, kurtosis, or FWHM. Although one may force a calculation of these properties by numerically evaluating the model (see \verb|linefit| method \verb|getmodelprops|), properties such as skewness and kurtosis may not be mathematically defined at all.

Most distribution functions are normalized unless explicitly claimed.

There are 31 built-in models. Models \#1-18 are distribution functions with support $(-\infty,\infty)$; models \#19-28 are distribution functions with half-infinity support; the rest of the models are other profile functions.

\begin{enumerate}
\item \verb|lorentzian(x,[A,x0,gamma])| Lorentzian or Cauchy distribution function

\verb|A|: amplitude, \verb|x0|: location, \verb|gamma| ($\gamma>0$): scale or HWHM (half-width-of-half-maximum).
\begin{equation}
f(x)=A\frac{1}{\pi\gamma}\left[1+\left(\frac{x-x_0}{\gamma}\right)^2\right]^{-1} \nonumber
\end{equation}
\begin{align}
	\mbox{mode}      	&: \mbox{$x_0$}  \nonumber \\
	\mbox{median}       &: \mbox{$x_0$}  \nonumber \\
	\mbox{fwhm} 		&: \mbox{$2\gamma$}  \nonumber
\end{align}

\item \verb|ilorentzian(x,[A,x0,gamma])| Intermediate Lorentzian distribution function~\cite{ilorentzian}

\verb|A|: amplitude, \verb|x0|: location, \verb|gamma| ($\gamma>0$): scale.
\begin{equation}
f(x)=A\frac{\sqrt{2^{\frac{2}{3}}-1}}{2\gamma}\left[1+(2^{\frac{2}{3}}-1)\left(\frac{x-x_0}{\gamma}\right)^2\right]^{-\frac{3}{2}} \nonumber
\end{equation}
\begin{align}
	\mbox{mode}      	&: \mbox{$x_0$}  \nonumber \\
	\mbox{median}       &: \mbox{$x_0$}  \nonumber \\
	\mbox{fwhm} 		&: \mbox{$2\gamma$}  \nonumber
\end{align}

\item \verb|mlorentzian(x,[A,x0,gamma])| Modified Lorentzian distribution function~\cite{mlorentzian}

\verb|A|: amplitude, \verb|x0|: location, \verb|gamma| ($\gamma>0$): scale.
\begin{equation}
f(x)=A\frac{2\sqrt{\sqrt{2}-1}}{\pi\gamma}\left[1+(\sqrt{2}-1)\left(\frac{x-x_0}{\gamma}\right)^2\right]^{-2} \nonumber
\end{equation}
\begin{align}
	\mbox{mode}      	&: \mbox{$x_0$}  \nonumber \\
	\mbox{median}       &: \mbox{$x_0$}  \nonumber \\
	\mbox{fwhm} 		&: \mbox{$2\gamma$}  \nonumber
\end{align}

\item \verb|gaussian(x,[A,x0,sigma])| Gaussian or normal distribution function

\verb|A|: amplitude, \verb|x0|: location, \verb|sigma| ($\sigma>0$): scale or standard deviation.
\begin{equation}
f(x) = A\frac{1}{\sigma\sqrt{2\pi}}\exp\left[-\frac{(x-x_0)^2}{2\sigma^2}\right] \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$x_0$} \nonumber \\
	\mbox{variance}		&: \mbox{$\sigma^2$} \nonumber \\
	\mbox{skewness}     &: \mbox{$0$} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$0$}  \nonumber \\
	\mbox{mode}      	&: \mbox{$x_0$}  \nonumber \\
	\mbox{median}       &: \mbox{$x_0$}  \nonumber \\
	\mbox{fwhm} 		&: \mbox{$2\sqrt{2\log(2)}\sigma$}  \nonumber
\end{align}

\item \verb|generalizednorm1(x,[A,a,b,c])| Generalized normal distribution function version 1~\cite{generalizednorm1}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|$>0$: shape.
\begin{equation}
f(x)=A\frac{c}{2b\Gamma(1/c)}\exp\left[-\left(\frac{\left|x-a\right|}{b}\right)^c\right] \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$a$} \nonumber \\
	\mbox{variance}		&: \mbox{$\frac{b^2\Gamma(3/c)}{\Gamma(1/c)}$} \nonumber \\
	\mbox{skewness}     &: \mbox{$0$} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$\frac{\Gamma(5/c)\Gamma(1/c)}{\Gamma(3/c)^2}-3$}  \nonumber \\
	\mbox{mode}      	&: \mbox{$a$}  \nonumber \\
	\mbox{median}       &: \mbox{$a$}  \nonumber
\end{align}

\item \verb|laplace(x,[A,a,b])| Laplace distribution function~\cite{McLaughlin}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale.
\begin{equation}
f(x)=A\frac{1}{2b}\exp\left(-\frac{\left|x-a\right|}{b}\right) \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$a$} \nonumber \\
	\mbox{variance}		&: \mbox{$2b^2$} \nonumber \\
	\mbox{skewness}     &: \mbox{$0$} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$3$}  \nonumber \\
	\mbox{mode}      	&: \mbox{$a$}  \nonumber \\
	\mbox{median}       &: \mbox{$a$}  \nonumber
\end{align}

\item \verb|logistic(x,[A,a,b])| Logistic distribution function~\cite{McLaughlin}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale.
\begin{equation}
f(x)=A\frac{1}{b}\exp\left(-\frac{x-a}{b}\right)\left[1+\exp\left(-\frac{x-a}{b}\right)\right]^{-2} \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$a$} \nonumber \\
	\mbox{variance}		&: \mbox{$\pi^2b^2/3$} \nonumber \\
	\mbox{skewness}     &: \mbox{$0$} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$7/5$}  \nonumber \\
	\mbox{mode}      	&: \mbox{$a$}  \nonumber \\
	\mbox{median}       &: \mbox{$a$}  \nonumber
\end{align}

\item \verb|pearsonVII(x,[A,a,b,c])| Pearson type VII or student' t distribution function~\cite{McLaughlin,pearsonVII}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|$>0$: shape (degree of freedom).
\begin{equation}
f(x)=A\frac{\Gamma(\frac{c+1}{2})}{b\sqrt{\pi c}\Gamma(\frac{c}{2})}\left[1+\frac{1}{c}\left(\frac{x-a}{b}\right)^2\right]^{-\frac{c+1}{2}} \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$a$ for $c>1$, otherwise undefined} \nonumber \\
	\mbox{variance}		&: \mbox{$\frac{b^2c}{c-2}$ for $c>2$, $\infty$ for $1<c\leq2$,} \nonumber \\
	\mbox{} 			&  \mbox{otherwise undefined} \nonumber \\
	\mbox{skewness}     &: \mbox{$0$ for $c>3$, otherwise undefined} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$\frac{6}{c-4}$ for $c>4$, $\infty$ for $2<c\leq4$,} \nonumber \\
	\mbox{} 			&  \mbox{otherwise undefined} \nonumber \\
	\mbox{mode}      	&: \mbox{$a$}  \nonumber \\
	\mbox{median}       &: \mbox{$a$}  \nonumber
\end{align}

\item \verb|pseudovoigtTCH(x,[A,x0,sigma,gamma])| Pseudo-Voigt type TCH distribution function~\cite{pseudovoigtTCH}

\verb|A|: amplitude, \verb|x0|: location, \verb|sigma| ($\sigma>0$): scale (standard deviation) of the Gaussian for convolution, \verb|gamma| ($\gamma>0$): scale (HWHM) of the Lorentzian for convolution.
\begin{equation}
f(x;\Gamma)=A\left[(1-\eta_L)f_G(x;\gamma_G)+\eta_L f_L(x;\sigma_L)\right], \nonumber
\end{equation}
where $\Gamma$ is the approximated FWHM of Voigt given by
\begin{eqnarray}
\Gamma&=&(\Gamma_{GV}^5+2.69269\Gamma_{GV}^4\Gamma_{LV}+2.42843\Gamma_{GV}^3\Gamma_{LV}^2 \nonumber \\
&+&4.47163\Gamma_{GV}^2\Gamma_{LV}^3+0.07842\Gamma_{GV}\Gamma_{LV}^4+\Gamma_{LV}^5)^{\frac{1}{5}}. \nonumber
\end{eqnarray}
with $\Gamma_{GV}=2\sqrt{2\log(2)}\sigma$ and $\Gamma_{LV}=2\gamma$; $f_L(x)$ is a Lorentzian given by
\begin{equation}
f_L(x;\gamma_L)=\frac{1}{\pi\gamma_L}\left[1+\left(\frac{x-x_0}{\gamma_L}\right)^2\right]^{-1}, \nonumber
\end{equation}
with $\gamma_L=\Gamma/2$; $f_G(x)$ is a Gaussian given by
\begin{equation}
f_G(x) = \frac{1}{\sqrt{2\pi\sigma_G^2}}\exp\left[-\frac{(x-x_0)^2}{2\sigma_G^2}\right], \nonumber
\end{equation}
with $\sigma_G=\Gamma/(2\sqrt{2\log(2)})$;
$\eta_L$ is the contribution from the Lorentzian to the total Voigt
\begin{equation}
\eta_L=1.36603\frac{\Gamma_{LV}}{\Gamma}-0.47719\left(\frac{\Gamma_{LV}}{\Gamma}\right)^2+0.11116\left(\frac{\Gamma_{LV}}{\Gamma}\right)^3. \nonumber
\end{equation}
\begin{align}
	\mbox{fwhm}       &: \mbox{$\Gamma$}  \nonumber
\end{align}

\item \verb|pseudovoigtIAT(x,[A,x0,sigma,gamma])| Pseudo-Voigt type IAT distribution function~\cite{pseudovoigtIAT}

\verb|A|: amplitude, \verb|x0|: location, \verb|sigma| ($\sigma>0$): scale (standard deviation) of the Gaussian for convolution, \verb|gamma| ($\gamma>0$): scale (HWHM) of the Lorentzian for convolution.
\begin{eqnarray}
f(x)&=&A[(1-\eta_L-\eta_I-\eta_P) f_G(x;\sigma_G)  \nonumber \\
&+& \eta_L f_L(x;\gamma_L) + \eta_I f_I(x;\gamma_I) + \eta_P f_P(x;\gamma_P)], \nonumber
\end{eqnarray}
where $f_G(x;\sigma_G)$ is a Gaussian with FWHM $\Gamma_G=2\sqrt{2\log(2)}\sigma_G$; $f_L(x;\gamma_L)$ is a Lorentzian with HWHM $\gamma_L$, FWHM $\Gamma_L=2\gamma_L$, and contribution $\eta_L$; $f_I(x;\gamma_I)$ is an irrational function (equivalent to the intermediate Lorentzian) defined by
\begin{equation}
f_I(x;\gamma_I)=\frac{1}{2\gamma_I}\left[1+\left(\frac{x-x_0}{\gamma_I}\right)^2\right]^{-\frac{3}{2}},\nonumber
\end{equation}
with FWHM $\Gamma_I=2\sqrt{2^{2/3}-1}\gamma_I$ and contribution $\eta_I$; and $f_P(x;\gamma_P)$ is an inverse squared hyperbolic cosine function defined by
\begin{equation}
f_P(x;\gamma_P)=\frac{1}{2\gamma_P}\frac{1}{\cosh^2\left(\frac{x-x_0}{\gamma_P}\right)},\nonumber
\end{equation}
with FWHM $\Gamma_P=2\left[\log(\sqrt{2}+1)\right]\gamma_P$ and contribution $\eta_P$. These FWHMs are calculated via $\Gamma_i=(\Gamma_{GV}+\Gamma_{LV})w_i$, where $\Gamma_{GV}=2\sqrt{2\log(2)}\sigma$,  $\Gamma_{LV}=2\gamma$, and $i\in \{G,L,I,P\}$. With $\rho$ defined as $\rho\equiv\Gamma_{LV}/(\Gamma_{LV}+\Gamma_{GV})$, $w_i$ and $\eta_i$ are calculated via
\begin{eqnarray}
w_G&=&1-\rho\sum_{i=0}^{N}a_i\rho^i,\nonumber\\
w_L&=&1-(1-\rho)\sum_{i=0}^{N}b_i\rho^i,\nonumber\\
w_I&=&\sum_{i=0}^{N}c_i\rho^i,\nonumber\\
w_P&=&\sum_{i=0}^{N}d_i\rho^i,\nonumber\\
\eta_L&=&\rho\left[1+(1-\rho)\sum_{i=0}^{N}f_i\rho^i\right],\nonumber\\
\eta_I&=&\rho(1-\rho)\sum_{i=0}^{N}g_i\rho^i,\nonumber\\
\eta_I&=&\rho(1-\rho)\sum_{i=0}^{N}h_i\rho^i,\nonumber
\end{eqnarray}
where $N=6$, and polynomial coefficients $a_i$, $b_i$, $c_i$, $d_i$, $f_i$, $g_i$ and $h_i$ are
\begin{widetext}
\begin{center}
\begin{tabular}{cccccccc}
	\hline
	$i$ & $a_i$ 	& $b_i$ 	& $c_i$ 	& $d_i$ 	& $f_i$ 	& $g_i$ 	& $h_i$ 	\\
	\hline
	0 	& 0.66 		& -0.42179	& 1.19913   & 1.10186   & -0.30165	& 0.25437   & 1.01579 	\\
    1   & 0.15021   & -1.25693	& 1.43021   & -0.47745	& -1.38927	& -0.14107	& 1.50429 	\\
	2 	& -1.24984	& 10.30003	& -15.36331	& -0.68688	& 9.3155    & 3.23653   & -9.21815 	\\
	3 	& 4.74052   & -23.45651	& 47.06071	& 2.76622   & -24.10743	& -11.09215	& 23.59717 	\\
	4 	& -9.48291	& 29.14158	& -73.61822	& -4.55466	& 34.96491	& 22.10544	& -39.71134 \\
	5 	& 8.48252   & -16.50453	& 57.92559	& 4.05475   & -21.18862	& -24.12407	& 32.83023 	\\
	6 	& -2.95553	& 3.19974   & -17.80614	& -1.26571	& 3.7029    & 9.76947   & -10.02142	\\
	\hline
\end{tabular}
\end{center}
\end{widetext}
\begin{align}
		\mbox{fwhm} &: \mbox{$\Gamma$ (same as \texttt{pseudovoigtTCH})}  \nonumber
\end{align}

\item \verb|pseudovoigtLLHGD(x,[A,x0,sigma,gamma])| Pseudo-Voigt type LLHGD distribution function~\cite{pseudovoigtLLHGD}

\verb|A|: amplitude, \verb|x0|: location, \verb|sigma| ($\sigma>0$): scale (standard deviation) of the Gaussian for convolution, \verb|gamma| ($\gamma>0$): scale (HWHM) of the Lorentzian for convolution.
\begin{equation}
f(x;\Gamma)=c_G f_G(x;\sigma_G)+c_L f_L(x;\gamma_L), \nonumber
\end{equation}
where $\Gamma$ is the approximated FWHM of Voigt~\cite{olivero}
\begin{equation}
\Gamma = 0.5346\Gamma_{LV}+\sqrt{0.2165975\Gamma_{LV}^2+\Gamma_{GV}^2}, \nonumber
\end{equation}
with $\Gamma_{LV}=2\gamma$ and $\Gamma_{GV}=2\sqrt{2\log(2)}\sigma$; $f_G(x;\sigma_G)$ is a Gaussian with $\sigma_G=\Gamma/(2\sqrt{2\log(2)})$; $f_L(x;\gamma_L)$ is a Lorentzian with $\gamma_L=\Gamma/2$; and coefficients $c_G$ and $c_L$ are given by
\begin{eqnarray}
c_G &=& 0.32460 - 0.61825d + 0.17681d^2 + 0.12109d^3, \nonumber \\
c_L &=& 0.68188 + 0.61293d - 0.18384d^2 - 0.11568d^3, \nonumber
\end{eqnarray}
where $d=(\Gamma_{LV}-\Gamma_{GV})/(\Gamma_{LV}+\Gamma_{GV})$.
\begin{align}
	\mbox{fwhm} &: \mbox{$\Gamma$}  \nonumber
\end{align}

\item \verb|uniform(x,[A,a,b])| Uniform distribution function~\cite{uniform}

\verb|A|: amplitude, \verb|a|: location, \verb|b| ($b>a$): scale (upper bound)
\begin{equation}
f(x)=
\begin{cases}
\frac{A}{b-a} &\text{for }x\in[a,b] \\
0 & \text{otherwise} \nonumber
\end{cases}
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$(a+b)/2$} \nonumber \\
	\mbox{variance}		&: \mbox{$(b-a)^2/12$} \nonumber \\
	\mbox{skewness}     &: \mbox{$0$} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$-6/5$} \nonumber \\
	\mbox{median}       &: \mbox{$(a+b)/2$}  \nonumber
\end{align}

\item \verb|voigt(x,[A,x0,sigma,gamma])| Voigt distribution function~\cite{vogit,Faddeeva}

\verb|A|: amplitude, \verb|x0|: location, \verb|sigma| ($\sigma>0$): scale (standard deviation) of the Gaussian for convolution, \verb|gamma| ($\gamma>0$): scale (HWHM) of the Lorentzian for convolution.
\begin{equation}
f(x)=\int_{-\infty}^{\infty}f_G(x';\sigma)f_L(x-x';\gamma)dx'=\frac{\mathrm{Re}[w(z)]}{\sigma\sqrt{2\pi}},\nonumber
\end{equation}
where $f_G$ and $f_L$ are a Gaussian and a Lorentzian, $z=\frac{x-x_0+i\gamma}{\sigma\sqrt{2}}$, and $\mathrm{Re}[w(z)]$ is the real part of the Faddeeva function (a.k.a. Kramp function) which is a scaled complex complementary error function defined as
\begin{eqnarray}
w[z]&=&\exp(-z^2)\mathrm{erfc}(-iz)=\mathrm{erfcx}(-iz) \nonumber \\
&=&\exp(-z^2)\left[1+\frac{2i}{\sqrt{\pi}}\int_{0}^{z}\exp(t^2)dt\right] \nonumber
\end{eqnarray}
\begin{align}
	\mbox{fwhm} &: \mbox{$\Gamma$ (same as \texttt{pseudovoigtTCH})} \nonumber
\end{align}

\item \verb|skewlaplace(x,[A,a,b,c])| Skew-Laplace distribution function~\cite{McLaughlin,skewlaplace}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|$>0$: scale.
\begin{eqnarray}
f(x)=A\frac{1}{b+c}
\begin{cases}
\exp\left(\frac{x-a}{b}\right), &\text{for }x\leq a \\
\exp\left(\frac{a-x}{c}\right), &\text{for }x>a  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$a-b+c$} \nonumber \\
	\mbox{variance}		&: \mbox{$b^2+c^2$} \nonumber \\
	\mbox{skewness}     &: \mbox{$\frac{2(c^3-b^3)}{(c^2+b^2)^{(3/2)}}$} \nonumber \\
	\mbox{kurtosis}     &: \mbox{$\frac{9b^4+6b^2c^2+9c^4}{(c^2+b^2)^2}-3$} \nonumber \\
	\mbox{mode} 	    &: \mbox{$a$} \nonumber \\
	\mbox{median}       &: \mbox{$a+b\log\left(\frac{b+c}{2b}\right)$}  \nonumber
\end{align}

\item \verb|skewlogistic(x,[A,a,b,c])| Skew-logistic or generalized logistic type I distribution function~\cite{McLaughlin,skewlogistic}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|$>0$: shape.
\begin{equation}
f(x)=A\frac{c}{b}\exp\left(-\frac{x-a}{b}\right)\left[1+\exp\left(-\frac{x-a}{b}\right)\right]^{-(c+1)} \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$a+[\gamma+\psi(c)]b$} \nonumber \\
	\mbox{variance}		&: \mbox{$\left[\frac{\pi^2}{6}+\psi^{(1)}(c)\right]b^2$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$\frac{\psi^{(2)}(c)-\psi^{(2)}(1)}{\left[\frac{\pi^2}{6}+\psi^{(1)}(c)\right]^{3/2}}$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$\frac{\psi^{(3)}(c)+\psi^{(1)}(c)\left[\pi^2+3\psi^{(1)}(c)\right]+\frac{3\pi^4}{20}}{\left[\frac{\pi^2}{6}+\psi^{(1)}(c)\right]^2}-3$} \nonumber \\
	\mbox{mode}         &: \mbox{$a+b\log(c)$}  \nonumber \\
	\mbox{median}       &: \mbox{$a-b\log(2^{1/c}-1)$}  \nonumber
\end{align}
where $\gamma$ is the Euler-Mascheroni constant, $\psi(x)$ is the digamma function, and $\psi^{(i)}(x)$ is the polygamma function.

\item \verb|skewnorm(x,[A,a,b,c])| Skew-normal distribution function~\cite{McLaughlin,skewnorm}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|: shape.
\begin{equation}
f(x)=A\frac{1}{b\sqrt{2\pi}}\exp\left[-\frac{(x-a)^2}{2b^2}\right] \left\lbrace 1+\mathrm{erf}\left[\frac{c(x-a)}{b\sqrt{2}}\right]\right\rbrace  \nonumber
\end{equation}
\begin{align}
	\mbox{mean} 		&: \mbox{$a+b\delta\sqrt{\frac{2}{\pi}}$} \nonumber \\
	\mbox{variance}		&: \mbox{$b^2\left(1-\frac{2\delta^2}{\pi}\right)$} \nonumber \\
	\mbox{median}       &: \mbox{$\frac{4-\pi}{2}\frac{(\delta\sqrt{2/\pi})^3}{(1-2\delta^2/\pi)^{3/2}}$}  \nonumber \\
	\mbox{kurtosis}     &: \mbox{$2(\pi-3)\frac{(\delta\sqrt{2/\pi})^4}{(1-2\delta^2/\pi)^2}$}  \nonumber
\end{align}
where $\delta=\frac{c}{\sqrt{1+c^2}}$.

\item \verb|skewpvSB(x,[A,x0,fwhm0,eta,a])| Asymmetric pseudo-Voigt type SB distribution function~\cite{skewpvSB}

\verb|A|: amplitude, \verb|x0|: location, \verb|fwhm0| ($\Gamma_0>0$): FWHM of symmetric Voigt, \verb|eta| ($\eta\geq0$): contribution of Lorentzian, \verb|a|: degree of asymmetry.
\begin{equation}
f(x)=(1-\eta)f_G(x;\sigma_G)+\eta f_L(x;\gamma_L), 	\nonumber
\end{equation}
where $f_G(x;\sigma_G)$ is a Gaussian with $\sigma_G=\Gamma_M/(2\sqrt{2\log(2)})$ and $f_L(x;\gamma_L)$ is a Lorentzian with $\gamma_L=\Gamma_M/2$, where $\Gamma_M$ is the modified FWHM written as
\begin{equation}
\Gamma_M=\frac{2\Gamma_0}{1+\exp\left[-a(x-x_0)\right]}. \nonumber
\end{equation}

Note that $\Gamma_M$ is not FWHM of the distribution function; the FWHM has to be evaluated numerically. Also note that this distribution is not normalized, i.e. the amplitude \verb|A| is not the total area of the distribution.

\item \verb|skewpvSSG(x,[A,x0,fwhm0,eta,a,b])| Asymmetric pseudo-Voigt type SSG distribution function~\cite{skewpvSSG}

\verb|A|: amplitude, \verb|x0|: location, \verb|fwhm0| ($\Gamma_0>0$): FWHM of symmetric Voigt, \verb|eta| ($\eta\geq0$): contribution of Lorentzian, \verb|a|: degree of asymmetry, \verb|b|: location shift of sigmoidal function.

This distribution has identical formula as \verb|skewpvSB|, except that the modified FWHM is
\begin{equation}
\Gamma_M=\frac{2\Gamma_0}{1+\exp\left[-a(x-x_0-b)\right]}. \nonumber
\end{equation}

Note that $\Gamma_M$ is not FWHM of the distribution function; the FWHM has to be evaluated numerically. Also note that this distribution is not normalized, i.e. the amplitude \verb|A| is not the total area of the distribution.

\item \verb|burrXII(x,[A,x0,a,b,c])| Burr type VII distribution function~\cite{McLaughlin}

\verb|A|: amplitude, \verb|x0|: location, \verb|a|$>0$: scale, \verb|b|$>0$: shape, \verb|c|$>0$: shape.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq x_0 \\
\frac{bc}{a}\left(\frac{x-x_0}{a}\right)^{b-1}\left[1+\left(\frac{x-x_0}{a}\right)^b\right]^{-(c+1)}, &\text{for }x>x_0  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$x_0+\mu_1$} \nonumber \\
	\mbox{variance}		&: \mbox{$-\mu_1^2+\mu_2$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$\frac{2\mu_1^3-3\mu_1\mu_2+\mu_3}{(-\mu_1^2+\mu_2)^{3/2}}$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$\frac{-3\mu_1^4+6\mu_1^2\mu_2-4\mu_1\mu_3+\mu_4}{(-\mu_1^2+\mu_2)^2}-3$} \nonumber \\
	\mbox{mode}         &: \mbox{$x_0+a\left(\frac{b-1}{bc+1}\right)^{1/b}$}  \nonumber \\
	\mbox{median}       &: \mbox{$x_0+a(2^{1/c}-1)^{1/b}$}  \nonumber
\end{align}
where $\mu_r=a^rc\mathrm{B}\left(\frac{bc-r}{b},\frac{b+r}{b}\right)$ are moments and $\mathrm{B}(x,y)=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}$ is the beta function (a.k.a. the Euler integral of the first kind).

\item \verb|expdist(x,[A,a,b])| Exponential distribution function~\cite{McLaughlin}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x<a \\
\frac{1}{b}\exp\left(-\frac{x-a}{b}\right), &\text{for }x\geq a  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$a+b$} \nonumber \\
	\mbox{variance}		&: \mbox{$b^2$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$2$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$6$} \nonumber \\
	\mbox{mode}         &: \mbox{$a$}  \nonumber \\
	\mbox{median}       &: \mbox{$a+b\log(2)$}  \nonumber
\end{align}

\item \verb|gammadist(x,[A,a,b,c])| Gamma distribution function~\cite{McLaughlin}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|$>0$: shape
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq a \\
\frac{1}{b\Gamma(c)}\left(\frac{x-a}{b}\right)^{c-1}\exp\left(-\frac{x-a}{b}\right), &\text{for }x>a  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$a+bc$} \nonumber \\
	\mbox{variance}		&: \mbox{$b^2c$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$2/\sqrt{c}$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$6/c$} \nonumber \\
	\mbox{mode}         &: \mbox{$a+b(c-1)$ for $c\geq 1$,}  \nonumber \\
	\mbox{}         	& \mbox{otherwise $a$}  \nonumber
\end{align}

\item \verb|inversegamma(x,[A,x0,a,b])| Inverse gamma distribution function~\cite{McLaughlin,inversegamma}

\verb|A|: amplitude, \verb|x0|: location, \verb|a|$>0$: scale, \verb|b|$>0$: shape.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq x_0 \\
\frac{a^b}{\Gamma(b)}(x-x_0)^{-(b+1)}\exp\left(-\frac{a}{x-x_0}\right), &\text{for }x>x_0  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$x_0+\frac{a}{b-1}$ for $b>1$} \nonumber \\
	\mbox{variance}		&: \mbox{$\frac{a^2}{(b-2)(b-1)^2}$ for $b>2$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$\frac{4\sqrt{b-2}}{b-3}$ for $b>3$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$\frac{30b-66}{(b-4)(b-3)}$ for $b>4$} \nonumber \\
	\mbox{mode}         &: \mbox{$x_0+\frac{a}{b+1}$}  \nonumber
\end{align}

\item \verb|inversenorm(x,[A,x0,a,b])| Inverse normal distribution (a.k.a Wald distribution) function~\cite{McLaughlin,inversenorm}

\verb|A|: amplitude, \verb|x0|: location, \verb|a|$>0$: location and scale, \verb|b|$>0$: scale.
\begin{eqnarray}
&&f(x)=A\times \nonumber \\
&&
\begin{cases}
0, &\text{for }x\leq x_0 \\
\sqrt{\frac{b}{2\pi(x-x_0)^3}}\exp\left[-\frac{b}{2(x-x_0)}\left(\frac{x-x_0-a}{a}\right)^2\right], &\text{for }x>x_0  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$x_0+a$} \nonumber \\
	\mbox{variance}		&: \mbox{$a^3/b$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$3\sqrt{a/b}$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$15a/b$} \nonumber \\
	\mbox{mode}         &: \mbox{$x_0+\frac{a}{2b}\left(\sqrt{9a^2+4b^2}-3a\right)$}  \nonumber
\end{align}

\item \verb|levy(x,[a,b])| L\'{e}vy distribution function~\cite{McLaughlin}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq a \\
\sqrt{\frac{b}{2\pi}}\left(x-a\right)^{-3/2}\exp\left[-\frac{b}{2(x-a)}\right], &\text{for }x>a  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$\infty$} \nonumber \\
	\mbox{variance}		&: \mbox{$\infty$} \nonumber \\
	\mbox{mode}         &: \mbox{$a+b/3$}  \nonumber \\
	\mbox{median}       &: \mbox{$a+(b/2)/\left[\mathrm{erfc}^{-1}(1/2)\right]^2$}  \nonumber
\end{align}
where $\mathrm{erfc}^{-1}(x)$ is the inverse error function.

\item \verb|logcauchy(x,[A,x0,a,b])| Log-Cauchy distribution function~\cite{logcauchy}

\verb|A|: amplitude, \verb|x0|: location, \verb|a|: log-location, \verb|b|$>0$: scale.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq x_0 \\
\frac{1}{\pi(x-x_0)}\{\frac{b}{\left[\log(x-x_0)-a\right]^2+b^2}\}, &\text{for }x>x_0  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{variance}		&: \mbox{$\infty$} \nonumber \\
	\mbox{median}       &: \mbox{$x_0+\exp(a)$}  \nonumber
\end{align}

\item \verb|lognorm(x,[A,x0,a,b])| Log-normal distribution~\cite{McLaughlin,lognorm}

\verb|A|: amplitude, \verb|x0|: location, \verb|a|: log-location, \verb|b|$>0$: scale. Both \verb|a| and \verb|b| are measured in log space.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq x_0 \\
\frac{1}{(x-x_0)b\sqrt{2\pi}}\exp\{-\frac{ \left[\log(x-x_0)-a\right]^2  }{2b^2}\}, &\text{for }x>x_0  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$x_0+\exp(a+b^2/2)$} \nonumber \\
	\mbox{variance}		&: \mbox{$\left[\exp(b^2)-1\right]\exp(2a+b^2)$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$\left[\exp(b^2)+2\right]\sqrt{\exp(b^2)-1}$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$\exp(4b^2)+2\exp(3b^2)+3\exp(2b^2)-6$} \nonumber \\
	\mbox{mode}         &: \mbox{$x_0+\exp(a-b^2)$}  \nonumber \\
	\mbox{median} 		&: \mbox{$x_0+\exp(a)$}  \nonumber
\end{align}

\item \verb|paretoI(x,[A,a,b])| Pareto type I distribution function~\cite{McLaughlin,paretoI}

\verb|A|: amplitude, \verb|a|$>0$: location and scale, \verb|b|$>0$: scale.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x< a \\
\frac{ba^b}{x^{b+1}}, &\text{for }x\geq a  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$\frac{ab}{b-1}$ for $b>1$, otherwise $\infty$} \nonumber \\
	\mbox{variance}		&: \mbox{$\frac{a^2b}{(b-1)^2(b-2)}$ for $b>2$, $\infty$ for $b\in(0,2]$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$\frac{2(1+b)}{b-3}\sqrt{\frac{b-2}{b}}$ for $b>3$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$\frac{6(b^3+b^2-6b-2)}{b(b-3)(b-4)}$ for $b>4$} \nonumber \\
	\mbox{mode}         &: \mbox{$a$}  \nonumber \\
	\mbox{median} 		&: \mbox{$a\sqrt[b]{2}$}  \nonumber
\end{align}

\item \verb|weibull(x,[A,a,b,c])| Weibull distribution function~\cite{weibull,McLaughlin}

\verb|A|: amplitude, \verb|a|: location, \verb|b|$>0$: scale, \verb|c|$>0$: shape.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x< a \\
\frac{c}{b}\left(\frac{x-a}{b}\right)^{c-1}\exp\left[-\left(\frac{x-a}{b}\right)^c\right], &\text{for }x\geq a  \nonumber
\end{cases}
\end{eqnarray}
\begin{align}
	\mbox{mean} 		&: \mbox{$a+bG(1)$} \nonumber \\
	\mbox{variance}		&: \mbox{$\left[-G^2(1)+G(2)\right]b^2$} \nonumber \\
	\mbox{skewness} 	&: \mbox{$\frac{2G^3(1)-3G(1)G(2)+G(3)}{\left[-G^2(1)+G(2)\right]^{3/2}}$} \nonumber \\
	\mbox{kurtosis} 	&: \mbox{$\frac{-3G^4(1)+6G^2(1)G(2)-4G(1)G(3)+G(4)}{\left[-G^2(1)+G(2)\right]^2}$} \nonumber \\
	\mbox{mode}         &: \mbox{$a$ for $c\leq 1$, $a+b\sqrt[c]{\frac{c-1}{c}}$ for $c>1$}  \nonumber \\
	\mbox{median} 		&: \mbox{$a+b\sqrt[c]{2}$}  \nonumber
\end{align}
where $G(n)=\Gamma\left(\frac{c+n}{n}\right)$.

\item \verb|atan(x,[A,a,b])| Inverse tangent function

\verb|A|: amplitude, \verb|a| : location, \verb|b|: scale.
\begin{equation}
f(x)=A\mathrm{atan}\left(\frac{x-a}{b}\right)\nonumber
\end{equation}

\item \verb|erf(x,[A,a,b])| Error function

\verb|A|: amplitude, \verb|a| : location, \verb|b|: scale.
\begin{equation}
f(x)=A\mathrm{erf}\left(\frac{x-a}{b}\right)\nonumber
\end{equation}

\item \verb|powerlaw(x,[A,a,b])| Power-law function

\verb|A|: amplitude or scale, \verb|a| : location, \verb|b|: shape.
\begin{eqnarray}
f(x)=A
\begin{cases}
0, &\text{for }x\leq a \\
(x-a)^{-b}, &\text{for }x> a  \nonumber
\end{cases}
\end{eqnarray}

\end{enumerate}

\bibliography{linefit_manual}

\end{document}


\documentclass{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{geometry}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}
\usepackage{physics}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1em}
\relpenalty=10000
\binoppenalty=10000

\begin{document}
\section*{Geometric inequalities}
	\begin{enumerate}
		\item %vorrat 48
		Prove the inequalities for $x \in \left(\frac{-\pi}{2},\frac{\pi}{2}\right)$
		$$|\tan x| \geq |x| \geq |\sin x| \geq  \frac{2}{\pi}|x|$$
		\item %vorrat 49
		Prove the inequalities for $0 < \alpha < \beta < \frac{\pi}{2}$
		$$\frac{\sin \beta}{\sin \alpha} < \frac{\beta}{\alpha} < \frac{\tan \alpha}{\tan \beta}$$
		\item % vorrat 52
		Prove the inequalities where $a,b,c$ are lengths of triangles sides
		\begin{enumerate}
			\item $a^2 + b^2 + c^2 < 2 (ab + bc + ca)$
			\item $a^4 + b^4 + c^4 < 2 (a^2b^2 + b^2c^2 + c^2a^2)$
		\end{enumerate}
		\item % vorrat 53
		Prove that $R \geq 2r$ given that $R$ is the radius of circumcircle and $r$ is the radius of incircle of a triangle.
		\item \emph{(Ptolemy's inequality).}
		Prove the inequality for any four points $A,B,C,D$ on a plane
		$$AC \cdot BD \leq AB \cdot CD + AD \cdot BC$$
		When does the equality hold?
		\item \emph{(Erdős-Mordell inequality).} % vorrat 62
		Let $P$ be a point in the interior of $\triangle ABC$ and $X$, $Y$,$Z$ projections of $P$ to $BC$,$AC$,$AB$ respectively. Prove that
		$$PA+PB+PC \geq 2(PX+PY+PZ)$$
		When does the equality hold?
		\item %vorrat 63
		Points $A,B,C,X,Y,Z,P$ are defined as before. Prove that
		$$AP \cdot BC + BP \cdot AC + CP \cdot AB \geq 4S_{\triangle ABC} $$
		\item %vorrat 64
		Points $A,B,C,X,Y,Z,P$ are defined as before. Prove that
		$$AP \cdot XP + BP \cdot YP + CP \cdot ZP \geq 2(XP \cdot YP + YP \cdot ZP + ZP \cdot XP) $$
		\item %vorrat 65, imo 96
		Given a convex hexagon $ABCDEF$ such that $AB \parallel DE$, $BC \parallel EF$, $CD \parallel FA$ and with perimeter $P$. Let $R_A, R_C, R_E$ be the radii of circles $FAB,BCD,DEF$ respectively. Prove that
		$$R_A + R_C + R_C \geq \frac{P}{2} $$

	\end{enumerate}
\end{document}


\chapter{Geostrophic balance and coastal flow}
\label{chap:geostrophic}

\includegraphics[width=6.5in]{figs/Geostrophic/HaidaEddy}

\section{Geostrophic balance}

The second balance that involves the Coriolis force is the \Wikiref{Geostrophic balance}, and is when the Coriolis force is in ``balance'' with the pressure gradient:

\begin{equation}
    \frac{du}{dt} = \overunderbraces{\br{2}{geostrophic}}
    {- \frac{1}{\rho_0}\frac{dP}{dx} & +fv & + \frac{1}{\rho}\frac{d\tau_{xz}}{dz}}
    {&\br{2}{Ekman}}
\end{equation}
\begin{equation}
    \frac{dv}{dt} = \overunderbraces{\br{2}{geostrophic}}
    {- \frac{1}{\rho_0}\frac{dP}{dy} & -fu & + \frac{1}{\rho}\frac{d\tau_{yz}}{dz}}
    {&\br{2}{Ekman}}
\end{equation}
\begin{marginfigure}
    \includegraphics{figs/Geostrophic/BalanceSketch}
    \caption{Sketch of geostrophic force-balance for a sea-level high and a sea-level low in the northern hemisphere, looking from above, and from the south for the high.  The flow will be clockwise around a hight and counter-clockwise.}
    \label{fig:BalanceSketch}
\end{marginfigure}
in which case the equations of motion simplify to:
\begin{eqnarray*}
    -\frac{1}{\rho_0}\frac{dP}{dx} & \approx & -fv\\
    -\frac{1}{\rho_0}\frac{dP}{dy} & \approx & +fu\\
\end{eqnarray*}
In the northern hemisphere ($f>0$) this says that water turns to the right as in moves from high pressure to low.  This gives a clockwise circulation around an isolated high, or a counter-clockwise around an isolated low (\fref{fig:BalanceSketch})

Crucially, if we know the pressure gradient, we can directly calculate the geostrophic flow perpendicular to that pressure gradient from the equations above.  So, suppose the high in the cover figure is 16 cm, over 100 km.  The pressure difference due to this flow gives us an estimate of the velocity (assuming $f = 10^{-4}\ \mathrm{rad\,s^{-1}}$)
\begin{equation}
  |u| = \left|\frac{1}{f\rho} \frac{dP}{dx}\right| = \frac{1}{f\rho}\frac{\Delta P}{\Delta x} = \frac{g}{f} \frac{\eta_C - \eta_E}{\Delta x} \approx 0.16 \ \mathrm{m\,s^{-1}}
\end{equation}

The equation applies everywhere in the fluid, and is only made complex by the presence of water with different densities making the flow have a pressure gradient that changes with depth.  An observation of this can be seen in \fref{fig:InteriorEddy}, where there is a sea-surface high in the middle, but the pressure gradient inside the eddy is the other direction.  This causes the pressure gradient force to decrease with depth, and hence the geostrophic flow decays with depth as well.

\begin{figure}
\begin{center}
    \includegraphics[width=2in]{figs/Geostrophic/InteriorEddy}
    \caption{Observations of density inside an Eddy.  Note how the density contours tend to counteract the high sea-surface height.  Blue circles with crosses are into the page, and with dots are out of the page, and the size is sketched to be proportional to the speed of the flow.}
    \label{fig:InteriorEddy}
\end{center}
\end{figure}

As discussed in \fref{chap:EquationofState}, calculating the pressure gradient is simply a matter of calculating the pressure at two locations, and differencing, where the pressure is given by:
\begin{equation}
  P(z) / \rho_0 = \frac{1}{\rho_0}\int_z^\eta \rho g\ \mathrm{d}z \approx g\eta + \frac{1}{\rho_0}\int_z^0 \rho g\ \mathrm{d}z
\end{equation}
So imagine one flank of the eddy, and that the eddy is made of two densities $\rho_1 < \rho_2$ (\fref{fig:CounterPressure}).  In the upper layer
\begin{equation}
  -\frac{1}{\rho_0} \frac{dP}{dx}(z=z_1) = -\frac{1}{\Delta x} g (\eta_B - \eta_A).
\end{equation}
In the lower layer, things are a bit more complicated, so we just do it step by step:
\begin{equation}
  P_A(z=z_2) = \rho_1 g (\eta_A - Z_A) + \rho_2 g (Z_A - z_2)
\end{equation}
\begin{equation}
  P_B(z=z_2) = \rho_1 g (\eta_B - Z_B) + \rho_2 g (Z_B - z_2)
\end{equation}
So the total pressure gradient in the lower layer is approximated as
\begin{equation}
  -\frac{1}{\rho_0}\frac{P_B - P_A}{\Delta x} = \overbrace{-\frac{1}{\Delta x} g (\eta_B - \eta_A)}^{Surface} - \overbrace{\frac{1}{\Delta x} g \frac{\left(\rho_2 - \rho_1\right)}{\rho_0} (Z_B - Z_A)}^{Internal}
  \label{eq:InternalExternal}
\end{equation}

According to the geostrophic balance, then, the flow in the upper layer is into the page, and the one in the bottom layer is either into the page, but more slow, or even out of the page.

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Geostrophic/CounterPressure}
    \caption{Two-layer approximation of pressure gradients in an eddy.}
    \label{fig:CounterPressure}
  \end{center}
\end{figure}

\subsection{Thermal wind}

The example above makes it clear that lateral density differences can drive velocity differences in the vertical if the flow is in geostrophic balance.  This can easily be extended to the continuous case with some  manipulation of the momentum equations.  If we take the vertical derivative of the x- and y-momentum equations we arrive at:
\begin{eqnarray}
    -\frac{1}{\rho_0}\frac{d^2 P}{dx dz} & = & -f \frac{dv}{dz} \\
    -\frac{1}{\rho_0}\frac{d^2 P}{dy dz} & = & f \frac{du}{dz}
\end{eqnarray}
but $P = \int_z^{\eta}\rho g \mathrm{d}z$,  so we get the \Wikiref{thermal wind} relation.
\begin{eqnarray}
    -\frac{1}{\rho_0}\frac{d \rho}{dx} & = & -f \frac{dv}{dz} \\
    -\frac{1}{\rho_0}\frac{d \rho}{dy} & = & f \frac{du}{dz}
\end{eqnarray}
so, if we know the horizontal pressure gradient, we can immediately say how the velocity changes with depth (though we do not know the absolute velocity).

\subsection{Level of no motion and ``dynamic height''}

Back in the pre-satellite days, all oceanographers would have would be measurements of the density under the ocean, like those in \fref{fig:InteriorEddy}.  Estimating the sea-surface height was impossible; imagine detecting 15 cm over 100 km in an ocean that is otherwise also moving due to tides, surface waves, relative to a poorly-constrained geoid.  However, oceanographers noted that most ocean currents, like the eddy, had tilted density surfaces, and that the currents at depth go to approximately zero.

Under these assumptions, oceanographers would assume that the pressure gradient at a ``level of no motion'' was zero, so that the geostrophic flow was zero there as well. In order to get this level of no motion the  pressure  gradients inferred from the interior density measurements were assumed to be balanced by a pressure gradient from the surface at that depth.  So, for instance, in the simple two-layer case the \fref{eq:InternalExternal}, the \emph{Surface} term was equal and opposite in sign to the \emph{Internal} term, if the deep layer was assumed to be not moving.  Note that this allows an estimate of the surface pressure gradient, and using the geostrophic balance, the surface velocities.  This surface pressure gradient is of course supplied by the sealevel interface being tilted, and  calculating these gradients is like calculating a ``dynamic height'' of the ocean.

An example in \fref{fig:DynamicHeight}, calculated in the 1980s looks strikingly similar to the sea surface heights in \fref{chap:winddriven}.  In particular, where there is Ekman convergence in the subtropics there is a high of up to 2 m, and a low in the sub-polar regions where there is Ekman divergence.  The highs and lows are displaced to the west sides of the basins.  The steepest change in dynamic height correspond to the strongest currents, again largely concentrated on the west side of the basins, and associated with the Gulf Stream, Kurishio, East Australian current etc.

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Geostrophic/DynamicHeight1500}
    \includegraphics{figs/Geostrophic/DynamicHeight2500}
    \caption{Dynamic height with a level of no motion at 1500 m (top) and 2500 m (bottom).  Note these are quite similar, strongly indicative that the dynamics are largely above these depths.  }
    \label{fig:DynamicHeight}
  \end{center}
\end{figure}

Just to summarize again how this is done:
\begin{enumerate}
    \item An interior pressure gradient is calculated at two ``stations'' as a function of depth using the density data from CTDs or other measurements.
    \item At a ``depth of no motion'' the pressure gradient is assumed to be zero, so a surface pressure gradient is added to the two points to make that be the case.
    \item If there are multiple stations in a line the surface pressure gradient is integrated to make a dynamic height with an arbitrary zero at some location.
\end{enumerate}

We will come back to \emph{why} the dynamic height looks the way it does in the next chapter.

\section{Coastal upwelling, complete picture}

Using the Ekman and geostrophic balances we are now in a position to explain the coastal upwelling example in detail (i.e. \fref{fig:PerlinFig3a}, one snapshot in detail in \fref{fig:ShelfDetail}).

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Geostrophic/ShelfDetail}
    \caption{Data from \fref{fig:PerlinFig3a}.}
    \label{fig:ShelfDetail}
  \end{center}
\end{figure}

First, the wind starts to blow towards the south; this sets up a southwards windstress $\tau_y^w$ (\fref{fig:CoastalStep1}, red circle).  When this flow is in a steady-state Ekman balance there will be an equal and opposite Coriolis force to the north (\fref{fig:CoastalStep1}, magenta circle).  That implies an offshore Ekman transport to the west given by
\begin{equation}
  u_{Ek}D = \frac{\tau_y^w}{\rho_0 f}
\end{equation}

\begin{figure}[hbt]
  \begin{center}
    \includegraphics[width=2.85in]{figs/Geostrophic/CoastalStep1}
    \caption{On a continental slope, initially at rest, a wind stress blows from north to south (dotted red circle)}
    \label{fig:CoastalStep1}
  \end{center}
\end{figure}

The offshore Ekman transport drops the sealevel at the coast (\fref{fig:CoastalStep2}, surface interface).   This creates a surface pressure gradient force that acts to push water back towards the coast (\fref{fig:CoastalStep2}, red arrow).  Again, in \emph{steady state} geostrophic balance, the pressure gradient force is balanced by a Coriolis force offshore, which must be generated by a geostrophic velocity to the south.  Note that this evolves in time with the deep water \emph{initially} moving onshore, but then being turned south (to the right) by the Coriolis force.

\begin{figure}[hbt]
  \begin{center}
    \includegraphics[width=2.85in]{figs/Geostrophic/CoastalStep2}
    \caption{After the Ekman transport has been active for a while, the sea level drops at the coast (green surface), and an interior geostrophic balanced flow is set up.}
    \label{fig:CoastalStep2}
  \end{center}
\end{figure}

At this point the flow cannot be in steady state because we are transporting water offshore in the surface Ekman layer, but not having any onshore transport to replace it.  Without this return flow, the sea surface will continue to increase its tilt.  The return flow happens in the bottom Ekman layer.  The interior geostrophic flow moves south, so there is a corresponding bottom stress to the north $\tau_y^B$(\fref{fig:CoastalStep3}, red circle at bottom).  In a steady Ekman balance, this implies a Coriolis force to the south, which implies a net Ekman transport onshore (\fref{fig:CoastalStep3}, blue arrows, bottom), given by
\begin{equation}
  u_{Ek}D = \frac{\tau_y^B}{\rho_0 f}
\end{equation}

The offshore Ekman transport drops the sealevel at the coast (\fref{fig:CoastalStep3})
\begin{figure}[hbt]
  \begin{center}
    \includegraphics[width=2.85in]{figs/Geostrophic/CoastalStep3}
    \caption{}
    \label{fig:CoastalStep3}
  \end{center}
\end{figure}

When is the whole flow balanced?  When $\tau^B = \tau^W$ so that the transport in the bottom Ekman layer is the same as the transport in the surface Ekman layer.  So, if we know the wind stress, and have a good estimate of the bottom \Wikiref{drag co-efficient}, $C_D\approx10^{-3}$, then we can guess what the mean geostrophic velocity is, and hence the size of the sea surface tilt.  For the Oregon shelf, $\tau_y^W\approx -0.15\ \mathrm{N\,m^{-2}}$ (minus means to the south).  Than means that the geostrophic velocity $v_g \approx 0.35\ \mathrm{m\,s^{-1}}$ in order for $\rho_0 C_D |v_g|^2$ to be large enough to provide the bottom stress to match.  This is approximately the same as the observations near the bottom.

We can further calculate the sea-surface height drop across the 20-km width of the shelf from $g \frac{d\eta}{dx} = f v_g$ or $\Delta \eta =  0.08\ \mathrm{m}$ across the shelf.

\subsection{Internal dynamics on shelf}

The final thing we notice about the shelf observations is that the  flow is slower towards the sea-floor than at the surface.  This is also largely explained by the geostrophic balance.  Note that the isopycnals tilt up towards the coast, counteracting the surface pressure gradient (also sketched in \fref{fig:CoastalTilt}).  This means that the surface tilt is actually larger than we calculated above if the bottom velocity is to remain $0.38\ \mathrm{m\,s^{-1}}$, leading to faster velocities near the surface.

\begin{figure}[hbt]
  \begin{center}
    \includegraphics[width=2.85in]{figs/Geostrophic/CoastalTilt}
        \caption{Sketch of pressure gradient changes if there are titled isopycnals (cyan line) in the section, as observed in the coastal data.  The tilted isopycnal counteracts the surface tilt, slowing the barotropic flow.  }
    \label{fig:CoastalTilt}
  \end{center}
\end{figure}

\clearpage
\section{Exercises}

\paragraph{Geostrophic balance two stations}

Calculate the geostrophic flow at two stations 50 km apart, assuming $f=10^{-4}\ \mathrm{rad\,s^{-1}}$.
Approximate the density measured at each location as 50-m blocks of homogeneous density:

\begin{tabular}{l|cc}
  $z\ \mathrm{[m]}$ & $\rho_A \mathrm{[kg\,m^{-3}]}$ & $\rho_B \mathrm{[kg\,m^{-3}]}$ \\
  \hline
  0--50 & 1021& 1020 \\
  50--100& 1022& 1021\\
  100--150& 1024& 1023\\
  150--200& 1025& 1024\\
\end{tabular}

\begin{itemize}
  \item If the surface pressure gradient is zero, what is the internal pressure gradient at 50, 100, 150, and 200 m? (do not drop too many decimal places!)
  \item What is the direction and strength of the \emph{geostrophic} velocity at the 4 depths?
  \item If there is a pressure gradient, what must its direction and strength be so that the geostrophic flow is zero at 200 m?
  \item How large must the surface difference be at the two stations?
  \item What is the new flow at the other depths in the presence of this surface gradient?
\end{itemize}

\paragraph{Geostrophic flow Gulf Stream}

Consider the temperature section across the Gulf Stream (\fref{fig:GulfStreamExample}).  Assuming a level of no motion at approximately 1500 m, what does
\begin{itemize}
    \item the sea-surface tilt look like?
    \item the interior velocity look like (just a sketch)?
    \item where would you expect the Gulf Stream to be the fastest?
\end{itemize}

\begin{figure}[hbt]
  \begin{center}
    \includegraphics[width=1.8in]{figs/Geostrophic/GulfStreamLoc}
    \includegraphics[width=2.7in]{figs/Geostrophic/GulfStreamTemp}
    \caption{Location of measurements in the Gulf Stream, and plot of temperature across the section \citep{johnsetal95}.}
    \label{fig:GulfStreamExample}
  \end{center}
\end{figure}


\subsection{Indirect utility functions}

The normal utility function is:

\(U=f(\mathbf x)\)

We have our demand:

\(x_{di}=x_{di}(I, \mathbf p)\)

\subsection{The indirect utility function}

We can plut this in to get:

\(U=g(I, \mathbf p)\)


\section{Glossary}
\smallskip \hrule height 2pt \smallskip

 \begin{itemize}
 	\item \textbf{complementary CDF} (CCDF, or survival function) - can ask how often the random variable is above a particular level.
		Has applications in statistical hypothesis testing, for example, because the one-sided p-value
			is the probability of observing a test statistic at least as extreme as the one observed.
 	\item \textbf{confidence interval} - An interval that represents the expected range of an estimator if
		an experiment is repeated many times.
	\item \textbf{effect size} - any statistic that quantitatively measures the strength of a phenomenon.
	\item \textbf{jitter} - random noise added to data for purposes of visualization.
 	\item \textbf{oversampling} - The technique of increasing the representation of a sub-population in order to avoid errors due to small sample sizes.
	\item \textbf{p-value} - the \underline{\textbf{p}}robability that, using a given statistical model, the statistical summary
		(such as the sample mean difference between two compared groups) would be the same as or more extreme
		than the actual observed results
	\item \textbf{percentile rank} - The percentage of values in a distribution that are less than or equal to a given value.
	\item \textbf{quantizing} - The opposite of smoothing is discretizing, or quantizing.
	\item \textbf{rank} The index where an element appears in a sorted list.
	\item \textbf{raw moment} - A statistic based on the sum of data raised to a power.
		E.g. the correlation between two variables, the regression coefficient in a regression, the mean difference, ...
	\item \textbf{standard error}: - The RMSE of an estimate, which quantifies variability due to sampling error
		(but not other sources of error).
	\item \textbf{standard score} A value that has been standardized so that it is expressed in standard deviations from the mean.

 \end{itemize}


% Created 2020-07-14 mar 10:56
% Intended LaTeX compiler: pdflatex
\documentclass[presentation,aspectratio=169]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{grffile}
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{amssymb}
\usepackage{capt-of}
\usepackage{hyperref}
\usepackage{khpreamble}
\usepackage{amssymb}
\DeclareMathOperator{\shift}{q}
\DeclareMathOperator{\diff}{p}
\usetheme{default}
\author{Kjartan Halvorsen}
\date{\today}
\title{Control computarizado - Asignación de polos}
\hypersetup{
 pdfauthor={Kjartan Halvorsen},
 pdftitle={Control computarizado - Asignación de polos},
 pdfkeywords={},
 pdfsubject={},
 pdfcreator={Emacs 26.3 (Org mode 9.3.6)},
 pdflang={English}}
\begin{document}

\maketitle

\section{Intro}
\label{sec:org70d5d08}

\section{2-dof controller}
\label{sec:org70b8192}

\begin{frame}[label={sec:orga124e5e}]{Two-degree-of-freedom controller}
\begin{center}
\includegraphics[width=0.8\linewidth]{../../figures/2dof-block-explicit-no-delay}
\end{center}
\end{frame}

\section{Problem 5.3}
\label{sec:orga34f588}
\begin{frame}[label={sec:org4d6f90f}]{Åström \& Wittenmark problem 5.3}
Consider the system given by the pulse-transfer function
\[ H(z) = \frac{z+0.7}{z^2 -1.8z + 0.81} \]
Use polynomial design (RST) to determine a controller such that the closed-loop system from command input to output has the characteristic polynomial
\[ A_c(z) = z^2 - 1.5z + 0.7. \]
Let the observer polynomial have as low order as possible, and place all observer poles in the origin (deadbeat observer). Consider three cases
\begin{description}
\item[{(a)}] Positional control with cancellation of the process zero
\item[{(b)}] Positional control with no cancellation of the zero
\item[{(c)}] Incremental controller with  no cancellation of the zero
\end{description}
\end{frame}

\begin{frame}[label={sec:org368a5ad}]{Why cancel the process zero?}
Bode plots of closed-loop systems (from reference signal to output) with and without cancellation of the process zero:

\begin{center}
\includegraphics[width=0.6\linewidth]{../../figures/aw5_3_bode}
\end{center}
\end{frame}

\begin{frame}[label={sec:org91db4f3}]{Preliminary exercise}
Which of the closed-loop responses below  corresponds to (I) Positional control with zero cancellation (II), Positional control without zero cancellation, (III) Incremental control without zero cancellation.
\begin{center}
\includegraphics[width=0.45\linewidth]{../../figures/aw5_3_refstep}
\includegraphics[width=0.45\linewidth]{../../figures/aw5_3_diststep}
\end{center}
\end{frame}
\end{document}