\documentclass{amsart}[12pt]
\usepackage{amsmath, amsfonts, tikz, natbib, array}
\usetikzlibrary{patterns}
\oddsidemargin=0in \evensidemargin=0in
\textwidth=6.6in \textheight=8.7in

\title{Map projections between spherical and Euclidean triangles}
\author{B R S Recht}
\date{April 2020}

\begin{document}
\maketitle
\tableofcontents

\section{Introduction}
A small but persistent trend in creating world maps has been to map onto a
polyhedron, and then unfold the polyhedron into a flat polyhedral net. An
example is Buckminster Fuller's (second) Dymaxion map, based on an
icosahedron.\cite{gray94} Snyder also presented equal-area maps on the
tetrahedron, octahedron, and icosahedron.\cite{snyder92} The inverse mapping of
each map projection can be used to inscribe a regular grid on a sphere, termed
a geodesic grid (after Fuller's geodesic domes) or discrete global
grid.\cite{williamson}\cite{sahr98}. In Buckminster Fuller's construction of
geodesic domes, a method analogus to Fuller's map projection, but not the same,
appears.\cite{kenner}

Discussion of these maps often neglects the projection used to project onto the
polyhedron. In the literature, there are four such map projections
(or families thereof):
\begin{itemize}
\item Gnomonic - Known in antiquity, this map projection preserves geodesics:
  great circle arcs on the sphere are mapped to lines on the plane.
\item Conformal - These map projections preserve the shape of features.
\item Snyder Equal-Area - These map projections preserve the relative area of
  features.\cite{snyder92}
\item Fuller - The map projections derived by Buckminster Fuller
  for his Dymaxion maps.\cite{gray94}\cite{gray95}\cite{crider08}
\end{itemize}
These will be discussed in more detail later on. There are also map projections
in the literature for particular polygons, e.g. the faces of a particular
regular polyhedron, as in Lee's conformal tetrahedral map.\cite{lee} In general
the published projections all fall into one of the categories above.

This paper is limited to triangular faces: projections to quadrilateral faces
or faces with more sides are uncommon, and often involve dividing the face into
triangles. (An interesting exception is the projection in \cite{crider09}, a
quadrilateral projection similar to Fuller's.) Most published projections only
treat regular triangles, although some can be reasonably extended to irregular
triangles. In this text, map projections between spherical and Euclidean
triangles will be discussed. Some of these are existing map projections, or
extensions of those, while some are new compromise map projections. Some
projections where only the forward or inverse transformation is known in close-
form are included. An attempt is made to generalize projections to irregular
triangles and to be able to project a portion of the exterior of the triangle
as well.

\begin{table}
\begin{tabular}[]{p{3.5cm}|p{1.4cm}p{1.4cm}p{1cm}p{7cm}}
  Name & Forward & Inverse & Cite & Notes \\
  Gnomonic & & & \cite{snyder87} & Preserves geodesics  \\
  Conformal & Eq. \ref{eq:conformal} & Eq. \ref{eq:conformal} & \cite{nehari57}\cite{nehari65}& Slow\\
  Snyder Equal-area & & & \cite{snyder92} & New generalization given here\\
  Symmetrized Snyder & & & New & \\
  Areal & & & New &\\
  Fuller & & & \cite{gray94}\cite{gray95} &\\
  Linear Combination & & N/A & New & Parametrized family\\
  Reverse Fuller & N/A & & \cite{kenner} &\\
  Naive Slerp & N/A & Eq. \ref{eq:nst}  & New & Parametrized family\\
\end{tabular}
\caption{Map projections in this text.}
\label{fig:projs}
\end{table}

\section{Preliminaries}
Let $(u,v)$ be a vector in $\mathbb R^2$, and $\zeta = u + i v$ be the
corresponding complex number in $\mathbb C$ or the Riemann sphere $\mathbb C
\cup \{\infty\}$. Which notation is used will depend on the mapping:
conformal maps are best expressed in terms of complex variables.

\subsection{Spherical geometry with 3-vectors}
Some of the map projections to be discussed are better expressed
in terms of a vector rather than latitude and longitude. This text will only
cover pertinent details: a fuller description can be found in e.g. \cite{strang80}.

Let $\phi \in [-\frac{\pi}{2}, \frac{\pi}{2}]$ be latitude, and
$\lambda \in (-\pi, \pi]$ be longitude. Let $\mathbf v = (x, y, z)$ be a vector
in $\mathbb R^3$ and $\mathbf{\hat{v}} = (x, y, z)$ be a unit vector on the
sphere $S^2$ such that $\| \mathbf{\hat{v}} \| = \sqrt{x^2 + y^2 +z^2} = 1$.
To convert from latitude and longitude to a unit vector:
\begin{equation}
  \mathbf{\hat{v}} = \left(\sin (\phi), \sin (\lambda) \cos (\phi),
  -\cos (\lambda) \cos (\phi) \right)
\end{equation}
To convert from the unit vector $\mathbf{\hat{v}}$ to latitude and longitude:
\begin{equation}\begin{split}
  \phi &= \arcsin (x) = \arctan (x, \sqrt{y^2 + z^2}) \\
  \lambda &= \arctan (y, -z)
\end{split}\end{equation}

Often in this text we'll normalize a vector to make it a unit vector.
For brevity,
we'll notate this pre-normalized vector as $\mathbf{\widetilde{v}}$, such that
\begin{equation}
  \mathbf{\hat{v}} = \frac{\mathbf{\widetilde{v}}}{\|\mathbf{\widetilde{v}}\|}
\end{equation}

\subsubsection{Great circles}
The shortest distance (geodesic) between two points in Euclidean space is a
straight line. On the sphere, the shortest distance is an arc of the great
circle between those points. That distance is the central angle $\theta$
between the two points. There are a few vector forms for it, the most
numerically stable one being the one using $\arctan$.
\begin{equation}\begin{split}
\theta &= \arccos \left(\mathbf{\hat{v}}_1 \cdot \mathbf{\hat{v}}_2\right) \\
&= \arcsin \left(\|\mathbf{\hat{v}}_1 \times \mathbf{\hat{v}}_2\| \right) \\
&= \arctan \left( \frac{\|\mathbf{\hat{v}}_1 \times \mathbf{\hat{v}}_2\|}
  {\mathbf{\hat{v}}_1 \cdot \mathbf{\hat{v}}_2} \right)
\end{split}\end{equation}

The great circle is the intersection of the sphere
and a plane passing through the origin. A plane through the origin can be
specified as $\hat{\mathbf n} \cdot \mathbf v = 0$, where $\hat{\mathbf n}$ is
a unit vector normal to the plane; this vector $\hat{\mathbf n}$ can be used to
specify a great circle. Given two points $\mathbf{\hat{v}_1, \hat{v}_2}$ on the
sphere, the $\hat{\mathbf n}$ of the great circle between those two points is
(up to normalization) their cross product:
\begin{equation}
  \mathbf{\widetilde{n}} = \mathbf{\hat{v}}_1 \times \mathbf{\hat{v}}_2
\end{equation}
Two great circles intersect at two antipodal points on the sphere. The points
of intersection can be found as the cross product of the great circle normals:
\begin{equation}
  \mathbf{\widetilde{v}} = \pm \mathbf{\hat{n}}_1 \times \mathbf{\hat{n}}_2
\end{equation}

\subsubsection{Interpolation}
Interpolation in Euclidean space is standard linear interpolation. On the
sphere, interpolation is given by spherical linear interpolation, or slerp.
\begin{equation}
\mathrm{Lerp}(\mathbf{v_1}, \mathbf{v_2}; t) =
       (1-t) \mathbf{v_1} + t \mathbf{v_2}
\end{equation}
\begin{equation}
\mathrm{Slerp}(\mathbf{\hat{v}_1}, \mathbf{\hat{v}_2}; t) =
        \frac{\sin ((1-t)w)}{\sin (w)} \mathbf{\hat{v}_1} +
       \frac{\sin (tw)}{\sin (w)} \mathbf{\hat{v}_2}
\end{equation}
where $w = \arccos \mathbf{\hat{v}_1} \cdot \mathbf{\hat{v}_2}$. If $\mathbf{\hat{v}_1} = \mathbf{\hat{v}_2}$, then define $\mathrm{Slerp}(\mathbf{\hat{v}_1}, \mathbf{\hat{v}_2}; t) =
\mathbf{\hat{v}_1} = \mathbf{\hat{v}_2}$ for all $t$.

\subsubsection{Face normal}
For the purposes of this text, we define the normal to a (Euclidean) polygon as
so, where $n$ is the number of vertices in the polygon and
$i = 0 \dots n-1$ is an index for each vertex:
\begin{equation}
  \mathbf{\widetilde{n}} =
  \sum^{n-1}_i \mathbf{v}_i \times \mathbf{v}_{i+1}
\end{equation}
$i$ should be treated as if it's mod $n$, so that it loops around.
This definition allows for a somewhat sensible extension to skew polygons:
the normal points in a generally reasonable direction when applied to a skew
polygon. The normal will be outward-facing if the points are ordered
counterclockwise, and inward-facing if the points are ordered clockwise.

\subsection{Euclidean spaces and transformations, including barycentric coordinates}

\subsubsection{Affine transformation}
Affine transformations are combinations of reflection, scaling, rotation,
shearing, and translation. This can be expressed as $\mathbf v = \mathbf A [u,
v]^T + v_0$, where $\mathbf A$ is a matrix. However, it is often more
convenient to express affine transformations using an augmented matrix like so:
\begin{equation}
  \begin{bmatrix}  x \\  y \\  1 \end{bmatrix}
   = \mathbf M
    \begin{bmatrix}  u \\  v \\  1 \end{bmatrix},\,
    \mathbf M = \begin{bmatrix}
       A_{11} & A_{12} & v_{0x} \\
       A_{21} & A_{22} & v_{0y} \\
       0 & 0 & 1
       \end{bmatrix}
\end{equation}
The transformation is invertible if $\mathbf M$ (or $\mathbf A$) is
invertible. This transformation can also transform between spaces of different
dimension, although then $\mathbf M$ is not a square matrix.

Affine transformations are equal-area in the sense defined earlier if
$|\mathbf M| \ne 0$, so if using an equal-area projection it may be desirable
to limit oneself to affine transformations. If $|\mathbf M| = 1$, then it defines a conformal affine transformation, effectively a combination of translation and rotation.

\subsubsection{Barycentric coordinates}
\begin{figure}%[!htbp]
\begin{tikzpicture}
  \draw (0, 0) -- (1.7,3) -- (3.4, 0) -- (0, 0) ;
  \draw[fill] (1.7, 3) circle [radius=0.05] node[anchor=west] {\tiny 1};
  \draw[fill] (0, 0) circle [radius=0.05] node[anchor=south] {\tiny 2};
  \draw[fill] (3.4, 0) circle [radius=0.05] node[anchor=south] {\tiny 3};
  \draw[fill] (2, 1) circle [radius=0.05];
  \draw[dotted] (0,0) -- (2,1) -- (1.7,3);
  \draw[dotted] (3.4, 0) -- (2,1);

  \draw (4, 0) -- (5.7,3) -- (7.4, 0) -- (4, 0) ;
  \draw[fill] (5.7, 3) circle [radius=0.05] node[anchor=west] {\tiny 1};
  \draw[fill] (4, 0) circle [radius=0.05] node[anchor=south] {\tiny 2};
  \draw[fill] (7.4, 0) circle [radius=0.05] node[anchor=south] {\tiny 3};
  \draw[fill] (6, 1) circle [radius=0.05];

  \draw[dotted] (4.6, 1) node[anchor=east] {\tiny 1,2}
  -- (6.85,1) node[anchor=west] {\tiny 1,3};
  \draw[dotted] (5.43, 0) node[anchor=north] {\tiny 3,2}
  -- (6.425, 1.75) node[anchor=west] {\tiny 3,1};
  \draw[dotted] (6.56, 0) node[anchor=north] {\tiny 2,3}
  -- (5.3, 2.2) node[anchor=east] {\tiny 2,1};

\end{tikzpicture}
\caption{Barycentric coordinates. Left: Area opposite of each vertex.
Right: Intersection of lines parallel with triangle edges.}
\label{fig:bary}
\end{figure}
Barycentric coordinates are in fact a special kind of affine coordinates.
Barycentric coordinates are real numbers $\beta_1, \beta_2, \beta_3$ such that
$\sum^3_{i=1} \beta_i = 1$. Given a triangle with vertices $\mathbf v_1,
\mathbf v_2, \mathbf v_3$, the corresponding vertex is given by $\mathbf v =
\sum^3_{i=1} \beta_i \mathbf v_i$. Given $\mathbf v$ and $\mathbf v_i$,
$\beta_i$ can be found by e.g. solving the linear system of
$\beta_1 + \beta_2 + \beta_3 = 1$ and $\mathbf v = \sum^3_{i=1} \beta_i \mathbf
v_i$. $\beta_i$ are all positive on the interior of the triangle. If a point
lies on an edge opposite vertex $i$, then $\beta_i$ is zero.
(If it lies beyond the edge, then $\beta_i < 0$.)

There are two geometric interpretations of barycentric coordinates that will be
useful, as depicted in Figure \ref{fig:bary}. One is that $\beta_i$ is the area
of the smaller triangle opposite $\mathbf v_i$ divided by the area of the large
triangle.
The other is that if a line is placed passing through $\mathbf v$ parallel to
the edge opposite vertex $i$, it will be at $\beta_i$ of the distance between
the edge and its opposite vertex, with $\beta_i = 0$ being on the edge itself.
Let $\mathbf v_{i,j}$ be the point where the line for $i$ meets the line between
vertices $i$ and $j$: then the vertex lies $\frac{\beta_{j}}{1-\beta{i}}$
of the distance from $\mathbf v_{i,j}$ to $\mathbf v_{i,j+1}$. Symbolically,
$\mathbf v_{i,j} = \mathrm{Lerp}(\mathbf v_{j},\mathbf v_i;\beta_{i})$, and
$\mathbf v = \mathrm{Lerp}(\mathrm{Lerp}(\mathbf v_{i-1}, \mathbf v_i;
\beta_{i}), \mathrm{Lerp}(\mathbf v_{i+1}, \mathbf v_i; \beta_{i});
\frac{\beta_{i-1}}{1-\beta_{i}})$ for all $i$.

Generalized barycentric coordinates are defined similarly, but the requirement
that $\sum^3_{i=1} \beta_i = 1$ is dropped. For instance, generalized
barycentric coordinates $\beta'_i$ on the unit sphere replace that requirement
with the condition that $\| \sum^3_{i=1} \beta'_i \mathbf v_i \| = 1$.
$\sum^3_{i=1} \beta'_i$ are $>1$ on the interior of the triangle,
$=1$ on the edges, and $<1$ on the exterior.

\subsection{Dealing with the ellipsoid}
The Earth is reasonably approximated as a sphere, and better approximated as a
slightly flattened oblate ellipsoid. In general this text will only deal with
the spherical approximation, but here we mention two considerations arising
from that approximation.

The vector form described in e.g. \cite{strang12} corresponds to the geodetic latitude.
The mapping between the sphere and the ellipsoid using geodetic latitude is not
area-preserving, conformal, or distance-preserving, although the distortion is
small on the Earth ellipsoid. If applying an area-preserving, conformal, or
distance-preserving map projection, and the required precision is fine enough
that the distortion is a concern, the geodetic latitude can be substituted
with the authalic (equal-area), conformal, or rectifying
(equal-distance along meridians) latitude as described in \cite{snyder87}.
These can be calculated from the geodetic latitude,
and the difference is well-approximated by a Fourier series.

Considering polyhedral maps, in this text we require the edges of the polyhedra
to correspond to geodesics. Geodesics on a sphere are not necessarily geodesics
on an ellipse: as proof, geodesics on an ellipse are not necessarily closed,
while geodesics on a sphere are. (Of course, with the Earth ellipsoid, the
difference between the geodesics is small.) The equator and meridians are
geodesics on both surfaces, so if having exact geodesics is a concern,
place your polyhedron edges along the equator or meridians.

\section{Map projections}

\begin{figure}%[!htbp]
\begin{tikzpicture}
  \draw [gray] (1,1) circle [radius=1];
  \draw[pattern=north east lines, pattern color=gray] (0.5, 0.5) to [out=0, in=-90]
  (1.5, 1.5) to [out=155, in=25]
  (0.5, 1.5) to [out=215, in=125]
  (0.5, 0.5);
  \draw[fill] (0.5,0.5) circle [radius=0.05];
  \draw[fill] (1.5,1.5) circle [radius=0.05];
  \draw[fill] (0.5,1.5) circle [radius=0.05];

  \draw [<->] (2.25,1) -- (2.75,1);
  \draw[pattern=north east lines, pattern color=gray] (2.92, 0.5) -- (4.08, 0.5) -- (3.5, 1.5) -- (2.92, 0.5);
  \draw[fill] (2.92,0.5) circle [radius=0.05];
  \draw[fill] (4.08,0.5) circle [radius=0.05];
  \draw[fill] (3.5,1.5) circle [radius=0.05];

  \draw [<->] (4.25,1) -- (4.75,1);
  \draw[pattern=north east lines, pattern color=gray] (5, 0.5) -- (6, 1.5) -- (5, 1.5) -- (5, 0.5);
  \draw[fill] (5,0.5) circle [radius=0.05];
  \draw[fill] (6,1.5) circle [radius=0.05];
  \draw[fill] (5,1.5) circle [radius=0.05];

\draw (2.5,1) node[anchor=south] {$P$};
\draw (4.5,1) node[anchor=south] {$A$};
\draw (1,0) node[anchor=north] {$R_s \subset S^2$};
\draw (3.5,0) node[anchor=north] {$\mathbf{\beta}$};
\draw (5.5,0) node[anchor=north] {$R_e \subset \mathbb{R}^2$};
\end{tikzpicture}
\caption{Schematic for the application of most projections listed in this text.
$P$ indicates the projection and $A$ is an affine transformation.}
\label{fig:schematic}
\end{figure}

Figure \ref{fig:schematic} illustrates the general form of application of most
projections in this text. (Exceptions are noted in the relevant sections.) The
transformation from barycentric coordinates to the plane, or from $uv$
coordinates to a quadrilateral, takes the same form for each projection, so in
this section we can ignore that part except when there are special
considerations.

The polygon on the sphere $R_s$ and the polygon in the plane $R_e$ can be
basically anything, within the operating parameters of the projection and any
special considerations that may apply. Even with respect to each other, one
can be regular while the other is irregular, if that is desirable. Of course,
this will influence the conformal and length distortion of the projection.

The flip side of this freedom is that given an irregular $R_s$ there is not
necessarily a single recommended way to choose $R_e$. One choice is to choose
$R_e$ such that its edges are proportional in length to those of $R_s$. Another
is to reduce conformal distortion at the vertices. Assuming the maximum angle
distortion $\omega$ is defined at a vertex, $\omega$ is equal to the difference
in the interior angle of that vertex on $R_s$ minus that on $R_e$. Let
$E = \alpha + \beta + \gamma - \pi$ be the spherical excess. To minimize
$\omega$ at each vertex, make the new angles $\alpha' = \alpha - \frac{E}{3}$
and similarly for $\beta'$ and $\gamma'$. This does not define the size of the
triangle, but one can choose $R_e$ to have these angles and the same area of
$R_s$, or that one particular edge has the same length of that in $R_s$, or
another desired quality.

\subsection{Gnomonic}
The gnomonic projection was known to the ancient Greeks, and is the simplest
of the transformations listed here.\cite{snyder87} It has the property that
arcs of great circles are transformed into lines on the plane and vice versa:
that is, geodesics stay geodesics, and (spherical) polygons stay polygons. This
projection is called Method 1 in geodesic dome terminology.\cite{kenner} The
main downside of the gnomonic projection is heavy distortion away from the
center of the projection.

We'll describe this projection in vector form, which is a little unconvential
but will allow us to compare it to other projections later.
Let $\mathbf p$ be a point on a plane given in Hessian normal form by
$\hat{\mathbf n} \cdot \mathbf p = r$. $r$ can be any value except 0.
The gnomonic projection can be described as so:
\begin{equation}
  \widetilde{\mathbf v} = \mathbf p
\end{equation}
\begin{equation}
\mathbf p = \frac{r}
  {\hat{\mathbf n} \cdot \hat{\mathbf v}}\hat{\mathbf v}
\end{equation}
Projection from Euclidean space to the sphere is literally just
normalizing the vector.

For triangles, this projection can be expressed directly in terms
of barycentric coordinates.
\begin{equation}
   \widetilde{\mathbf v} =
   \beta_1 \mathbf v_1 + \beta_2 \mathbf v_2 + \beta_3 \mathbf v_3
\end{equation}
where $\beta_i$ are (planar) barycentric coordinates. If the generalized coordinates are $\beta^\prime_i$, then $\beta^\prime_i = \frac{\beta_1}
{\|\beta_1 \mathbf v_1 + \beta_2 \mathbf v_2 + \beta_3 \mathbf v_3\|}$.

For the inverse, solve this linear system:
\begin{equation}
  \begin{bmatrix}
  \mathbf v_1 & \mathbf v_2 & \mathbf v_3 \end{bmatrix}
   \mathbf{\beta'} = \hat{\mathbf v}
\end{equation}
where $\mathbf{\beta'}$ is a
vector of generalized barycentric coordinates. Then obtain $\mathbf{\beta}$ as
$\mathbf{\beta} = \frac{\mathbf{\beta'}}{\sum{\beta'_i}}$.

\subsection{Conformal triangular}
\begin{figure}%[!htbp]
\begin{tikzpicture}
  \draw [gray] (1,1) circle [radius=1];
  \draw[pattern=north east lines, pattern color=gray] (0.5, 0.5)
    to [out=0, in=-90]
  (1.5, 1.5) to [out=155, in=25]
  (0.5, 1.5) to [out=215, in=125]
  (0.5, 0.5);
  \draw[fill] (0.5,0.5) circle [radius=0.05];
  \draw[fill] (1.5,1.5) circle [radius=0.05];
  \draw[fill] (0.5,1.5) circle [radius=0.05];

  \draw [<->] (2.25,1) -- (2.75,1);
  \draw[pattern=north east lines, pattern color=gray] (3, 0.5) to [out=0, in=-90]
  (4, 1.5) to [out=155, in=25]
  (3, 1.5) to [out=215, in=125]
  (3, 0.5);
  \draw[fill] (3,0.5) circle [radius=0.05];
  \draw[fill] (4,1.5) circle [radius=0.05];
  \draw[fill] (3,1.5) circle [radius=0.05];

  \draw [<->] (4.25,1) -- (4.75,1);
  \draw[pattern=north east lines, pattern color=gray] (5, 0.5) --
  (6, 0.5) to [out=90, in=0]
  (5, 1.5) --  (5, 0.5);
  \draw[fill] (5,0.5) circle [radius=0.05];
  \draw[fill] (6,0.5) circle [radius=0.05];
  \draw[fill] (5,1.5) circle [radius=0.05];

  \draw [<->] (4.25,1) -- (4.75,1);
  \draw[pattern=north east lines, pattern color=gray] (5, 0.5) --
  (6, 0.5) to [out=90, in=0]
  (5, 1.5) --  (5, 0.5);
  \draw[fill] (5,0.5) circle [radius=0.05] node[anchor=north] {0};
  \draw[fill] (6,0.5) circle [radius=0.05] node[anchor=north] {$\varphi_s(1)$};
  \draw[fill] (5,1.5) circle [radius=0.05] node[anchor=south west] {$\varphi_s(\infty)$};

  \draw [<->] (6.25,1) -- (6.75,1);
  \fill[pattern=north east lines, pattern color=gray]
    (7,0.5) rectangle (8,1.5);
  \draw (7, 0.5) -- (8, 0.5);
  \draw[fill] (7.25,0.5) circle [radius=0.05] node[anchor=north] {0};
  \draw[fill] (7.75,0.5) circle [radius=0.05] node[anchor=north] {1};

  \draw [<->] (8.25,1) -- (8.75,1);
  \draw[pattern=north east lines, pattern color=gray] (9, 0.5) --
  (10, 0.5) --  (9, 1.5) --  (9, 0.5);
  \draw[fill] (9,0.5) circle [radius=0.05] node[anchor=north] {0};
  \draw[fill] (10,0.5) circle [radius=0.05] node[anchor=north] {$\varphi_e(1)$};
  \draw[fill] (9,1.5) circle [radius=0.05] node[anchor=south west] {$\varphi_e(\infty)$};

  \draw [<->] (10.25,1) -- (10.75,1);
  \draw[pattern=north east lines, pattern color=gray] (11, 0.5) --
  (12, 1.5) --  (11, 1.5) --  (11, 0.5);
  \draw[fill] (11,0.5) circle [radius=0.05];
  \draw[fill] (12,1.5) circle [radius=0.05];
  \draw[fill] (11,1.5) circle [radius=0.05];

\draw (2.5,1) node[anchor=south] {$S$};
\draw (4.5,1) node[anchor=south] {$M$};
\draw (6.5,1) node[anchor=south] {$\varphi^{-1}_s$};
\draw (8.5,1) node[anchor=south] {$\varphi_e$};
\draw (10.5,1) node[anchor=south] {$L$};

\draw (1,0) node[anchor=north] {$R_s \subset S^2$};
\draw (3.5,0) node[anchor=north] {$\subset \mathbb{C}$};
\draw (5.5,0) node[anchor=north] {$\subset \mathbb{C}$};
\draw (7.5,0) node[anchor=north] {$= \mathbb{C}^+$};
\draw (9.5,0) node[anchor=north] {$\subset \mathbb{C}$};
\draw (11.5,0) node[anchor=north] {$R_e \subset \mathbb{C}$};

\end{tikzpicture}
\caption{Schematic of the conformal triangular projection. $S$ is the stereographic
projection, $M$ is a M\"obius transformation, $\varphi$ is the Schwarz triangle
function, $\mathbb{C}^+$ is the complex upper half-plane,
and $L$ is a complex affine transformation.}
\label{fig:conformal}
\end{figure}

Here we take a turn, as this mapping is very different from the others and
uses its own notation. Conformal map projections have deep connections to the
theory of complex functions. Here we introduce a number of functions which
will later be composed together as illustrated in Figure \ref{fig:conformal}.

The stereographic projection $S$ is the conformal map projection between the
Riemann sphere $\mathbb{C} \cup \{\infty\}$ and the sphere $S^2$. Let
$\mathbf{\hat{v}}_0$ designate the center point of the projection, to be
mapped to 0 in the complex plane. Then $\zeta = S\left(\mathbf{\hat{v}}_0;
\mathbf{\hat{v}}\right)$. As the stereographic projection is one of the most
common projections, its formula will not be repeated here: see \cite{snyder87}
if needed. For numerical reasons, the center point should be chosen to avoid
transforming any points within the spherical triangle to the point at infinity
on the Riemann sphere. That can be the centroid of the triangle, or (for
triangles less than a hemisphere) any vertex of the triangle.

A M\"obius transformation is a function of the form
\begin{equation}\begin{split}
  M(z) = \frac{az+b}{cz+d}
\end{split}\end{equation}
where $a, b, c, d$ are complex numbers such that $ad - bc \ne 0$. Note the
similarity between this function and the homographies mentioned earlier: a
M\"obius transformation is in fact a homography of the Riemann sphere,
although on the Riemann sphere that means that circles and lines are mapped to
circles and lines. (Some lines may be mapped to circles, or vice versa.) The inverse of $M(z)$ is $M^{-1}(z) = \frac{dz-b}{-cz+a}$. A M\"obius transformation may be specified by the transformation of three complex numbers $z_1, z_2, z_3$ to $\zeta_1, \zeta_2, \zeta_3$. Assuming all of these values are finite, the M\"obius transformation has coefficients as so:
\begin{equation}a=\det \begin{pmatrix} z_1\zeta_1 & \zeta_1 & 1 \\
    z_2\zeta_2 & \zeta_2 & 1 \\   z_3\zeta_3 & \zeta_3 & 1 \end{pmatrix},\,
  b=\det \begin{pmatrix} z_1\zeta_1 & z_1 & \zeta_1 \\
    z_2\zeta_2 & z_2 & \zeta_2 \\   z_3\zeta_3 & z_3 & \zeta_3 \end{pmatrix},\,
  c=\det \begin{pmatrix} z_1 & \zeta_1 & 1 \\   z_2 & \zeta_2 & 1 \\
    z_3 & \zeta_3 & 1 \end{pmatrix},\,
  d=\det \begin{pmatrix} z_1\zeta_1 & z_1 & 1 \\
    z_2\zeta_2 & z_2 & 1 \\   z_3\zeta_3 & z_3 & 1 \end{pmatrix}
\end{equation}

The Schwarz triangle function conformally transforms the upper
half-plane to a triangle whose edges are circular arcs. It is given by:
\begin{equation}
   \varphi(\alpha,\beta,\gamma; z) = z^{1-c} \frac{_2 F_1(a',b';c';z)}{_2 F_1(a,b;c;z)}
\end{equation}
where $_2 F_1(a,b;c;z)$ is the hypergeometric function and
\begin{equation}\begin{split}
   a & = \frac{1 - \alpha + \beta - \gamma}{2}\\
   b & = \frac{1 - \alpha - \beta - \gamma}{2}\\
   c & = 1 - \alpha\\
   a' &= \frac{1 + \alpha + \beta - \gamma}{2} = 1 + a - c\\
   b' &= \frac{1 + \alpha - \beta - \gamma}{2} = 1 + b - c\\
   c' &= 1 + \alpha
\end{split}\end{equation}
and the angles at each vertex of the triangle are $\pi \alpha, \pi \beta,
\pi \gamma$. (The angles may be dropped if clear in context.)
If $\alpha + \beta + \gamma < 1$, then the triangle is hyperbolic;
if $=1$ it is Euclidean, and if $>1$ it is spherical.\cite{nehari65}
In this text, the hyperbolic case is not relevant.

The Schwarz triangle map maps the boundary of the half-plane
(i.e. $\mathbb{R} \cup \{\infty\}$, the real projective line)
to the boundary of the triangle. The vertices are the points $z=0$, $1$, and
$\infty$ on that line. The map takes $z=0$ to $0$, $z=1$ to $\varphi(1) =
\frac{\Gamma(c-a) \Gamma(c-b) \Gamma(2-c)}{\Gamma(1-a) \Gamma(1-b) \Gamma(c)}$,
and $z=\infty$ to $\varphi(\infty) = \exp\left(i \pi \alpha \right)
\frac{\Gamma(b) \Gamma(c-a) \Gamma(2-c)}{\Gamma(c) \Gamma(b-c+1) \Gamma(1-a)}$
unless $b=0$ (the Euclidean case),
then $\varphi(\infty) = \exp\left(i \pi \alpha \right)
\frac{\Gamma(a) \Gamma(2-c)}{\Gamma(a-c+1)}$

No closed-form inverse $\varphi^{-1}(z)$ exists in general, even in the
Euclidean case when $b=0$ and the denominator of $\varphi(z)$ is 1.
The function has branch cuts on $(-\infty,0]$ and $[1, \infty)$,
and points are transformed to arbitrarily large values,
so care must be taken performing the numerical inversion. A M\"obius
transformation can be used to estimate initial conditions. The unruliness of this numerical inversion makes it difficult to use in real applications

What remains is to combine all these steps into a conformal map projection
between a Euclidean triangle and a spherical triangle. This is also expressed
with $\varphi(z)$.
\begin{equation}\begin{split}\label{eq:conformal}
  \zeta &= L(\varphi\left(\alpha_e,\beta_e,\gamma_e;
    \varphi^{-1}\left(\alpha_s,\beta_s,\gamma_s;
    M(S(\mathbf{\hat{v}}_0;\mathbf{\hat{v}})) \right)\right)\\
  \hat{v} &= S^{-1}\left(\mathbf{\hat{v}}_0;M^{-1}\left(
    \varphi\left(\alpha_s,\beta_s,\gamma_s;
    \varphi\left(\alpha_e,\beta_e,\gamma_e;L^{-1}(\zeta)\right)\right)
  \right)\right)
\end{split}\end{equation}
where $\alpha_s,\beta_s,\gamma_s$ denotes the angles of the spherical triangle
(over $\pi$), and $\alpha_e, \beta_e, \gamma_e$ denotes the angles of the
Euclidean triangle. $M$ is chosen to map
$S(\hat{v}_1)$ to $0$,
$S(\hat{v}_2)$ to $\varphi\left(\alpha_s,\beta_s,\gamma_s;1\right)$, and
$S(\hat{v}_3)$ to $\varphi\left(\alpha_s,\beta_s,\gamma_s;\infty\right)$.
$L$ is a conformal affine transformation, chosen to map
$0$ to $\zeta_1$,
$\varphi\left(\alpha_e,\beta_e,\gamma_e;1\right)$ to $\zeta_2$, and
$\varphi\left(\alpha_e,\beta_e,\gamma_e;\infty\right)$ to $\zeta_3$.
(Only two of these correspondences are needed to determine $L$.)
In complex terms, $L(z)=az + b$, where a and b are complex constants.

The values on the boundary of the triangle depend on the shape of the entire
triangle. These values are only guaranteed to be equal on the edge between two
triangles if those triangles are reflections of each other across that edge.
That is, those triangles are part of a tiling of the sphere with Schwarz
triangles.%TODO go to the actual source and clarify this

Deriving a general conformal map projection for quadrilaterals and higher
polygons is difficult. While there is only one solution for triangles, for
quadrilaterals there is a one-parameter family of solutions, a two-parameter
for pentagons, and so forth.\cite{nehari57} %TODO cite the right section
Furthermore, except for a few specific cases, the general solution is not a
named function: notable exceptions are the elliptic integral and Jacobi
elliptic functions, which appear in the functions between the square and the
hemisphere.\cite{fong16}
One possible way to handle higher polygons is to divide them into triangles,
but a) if new vertices are introduced, those vertices are singular points,
and b) those triangles must be Schwarz triangles as mentioned above.

\subsection{Snyder equal-area}
The Snyder equal-area projection can be applied to any regular polygon. The
equations in \cite{snyder92} are lengthy, and don't seem to simplify much when
expressed in terms of vectors. The special cases of the hemisphere and the cube
face do have nice simple forms, however.\cite{lambers}\cite{patt} Snyder's
equations won't be repeated here.

The Snyder projection starts by subdividing a regular polygonal face into
isosceles triangles, where two vertices of the new triangles are vertices of
the original polygon, and the third is the center of the polygon. Because of
this interruption, the projection is not differentiable on the lines from the
center to the original vertices. This projection can be applied to faces larger
than a hemisphere, as long as each subdivision triangle is smaller than a
hemisphere.

The Snyder projection does not require the faces of a polyhedron to be the
same, but does require (to maintain the equal-area property between
subdivsions) that the faces be subdividable into identical triangles. In
general, the Snyder equal-area projection cannot be adapted to irregular
polygons while maintaining the equal-area property and not introducing extra
lines of interruption. However, if a polyhedra is made up of identical
isosceles triangles, and those triangles meet at appropriate edges, the map can
be applied directly to those faces without subdivision. (Isosceles triangles of
different dimensions may be allowed if one is willing to abandon either the
equal-area property holding between different faces or the polygons on the
plane fitting together into a net.) An example of an irregular polyhedra that
can be used in this way is an $n$-bipyramid, formed by gluing two $n$-sided
pyramids together at the $n$-gonal base. (This is effectively the same as
applying the subdivision method to a $n$-dihedron.) Other polyhedra would
include the (regular) icosahedron and octahedron and the tetragonal disphenoid
(a stretched form of a tetrahedron with isosceles faces, of which the regular
tetrahedron is a subtype).

\subsection{Spherical areal}
This projection is an analogy with the relationship of barycentric coordinates
to area. Treat $\beta_i$ as the proportion of spherical area in the triangle
that is opposite the vertex $\hat{\mathbf v}_i$. Let $\Omega$ be the spherical
area (solid angle) of the spherical triangle and $\Omega_i = \beta_i\Omega$ be
the area of the smaller triangle opposite vertex $\hat{\mathbf v}_i$.
This area can be found in terms of vectors using this formula:\cite{oosterom}\cite{eriksson}
\begin{equation}
\tan(\Omega/2) = \frac{|\mathbf{\hat{v}_1} \cdot
       \mathbf{\hat{v}}_2 \times \mathbf{\hat{v}}_3|}
       {1+\mathbf{\hat{v}}_1\cdot \mathbf{\hat{v}}_2+\mathbf{\hat{v}}_2
       \cdot \mathbf{\hat{v}}_3+\mathbf{\hat{v}}_3\cdot \mathbf{\hat{v}}_1}
\end{equation}

The formula to find $\hat{\mathbf v}$ given $\beta_i$ more complicated,
although it's also derived from the formula for spherical area.

%https://math.stackexchange.com/questions/1151428/point-within-a-spherical-triangle-given-areas/3189416#3189416

\begin{equation}
\label{eq:sphareal}
  \begin{split}
  \mathbf G & \hat{\mathbf v} = \mathbf h \\
   \mathbf G & = \begin{bmatrix}
   \mathbf g_1 & \mathbf g_2 & \mathbf g_3 \end{bmatrix} \\
   \mathbf h & = \begin{bmatrix} h_1  & h_2 & h_3  \end{bmatrix}^T \\
   \mathbf g_{i} & = \left(1+\cos \Omega_{i}\right) \mathbf v_{i-1} \times
   \mathbf v_{i+1} - \sin\Omega_{i}\left(\mathbf v_{i-1} +
   \mathbf v_{i+1}\right)\\
   h_i &= \sin\Omega_i\left(1+\mathbf v_{i-1}\cdot\mathbf v_{i+1}\right)
\end{split}\end{equation}
The subscripts loop around: 0 should be interpreted as 3, and 4 should be
interpreted as 1. To clarify, $\mathbf G$ is the 3x3 matrix where the $i$th
column is $\mathbf g_i$, and $\mathbf h$ is the column vector where the
$i$th element is $h_i$. The vector $\hat{\mathbf v}$
can be solved for using standard matrix methods.

OR:
\begin{equation}\begin{split}
\tau   &= \tan\left(\frac{\Omega}{2}\right) \\
\tau_i &= \tan\left(\frac{\Omega_i}{2}\right) \\
t_i &= \frac{\tau_i}{\tau} \\
a_i &= \mathbf v_{i-1} \cdot \mathbf v_{i+1} \\
b_i &= \frac{a_{i-1} + a_{i+1}}{1 + a_i} \\
c_i &= \frac{t_i}{(1+b_i) + (1-b_i) t_i} \\
f_i &= \frac{c_i}{1 - c_1 - c_2 - c_3} \\
\mathbf v &= \sum f_i \mathbf v_i = \frac{\sum c_i \mathbf v_i }{ 1 - \sum c_i }
\end{split}\end{equation}

\subsection{Fuller}
this entire section needs to be reworked\cite{crider08}
\begin{figure}%[!htbp]
\begin{tikzpicture}
  \draw (2,2) circle [radius=2];

  \draw (0.6, 1) to [out=-25, in=205]
  (3.4, 1) to [out=90, in=-35]
  (2, 3.5) to [out=215, in=90]
  (0.6, 1);
  \draw[fill] (2, 3.5) circle [radius=0.05] node[anchor=west] {\tiny 1};
  \draw[fill] (0.6, 1) circle [radius=0.05] node[anchor=north] {\tiny 2};
  \draw[fill] (3.4, 1) circle [radius=0.05] node[anchor=north] {\tiny 3};
  \draw[dotted] (0.65, 1.5)  node[anchor=east] {\tiny 1,2}
  to [out=-15, in=195] (3.35, 1.5) node[anchor=west] {\tiny 1,3};

  \draw[dotted] (1.8, 0.65) node[anchor=north] {\tiny 3,2}
  to [out=45, in=265] (2.9, 2.7) node[anchor=west] {\tiny 3,1};
  \draw[dotted] (1.6, 3.1) node[anchor=east] {\tiny 2,1}
  to [out=-45, in=105] (2.9, 0.8) node[anchor=north] {\tiny 2,3};
\end{tikzpicture}
\caption{Intersection of great circle arcs inside a spherical triangle,
and the small spherical triangle formed by the arcs. Exaggerated so that the
small triangle is visible; not to scale.}
\label{fig:intlines}
\end{figure}
note similiarities between chamberlin and fuller, as per \cite{gray94}

This is Method 2 in geodesic dome terminology. Recall in our earlier discussion
of barycentric coordinates that on a plane triangle, we can draw a line
corresponding to each $\beta_i$, and those three lines meet at a point. On the
sphere, if we make the same construction, the lines do not meet at a point
(except on the edges), but instead intersect to form a small spherical
triangle. Take a point within that triangle as $\mathbf v$.
Typically the centroid is used, as it's easy to calculate,
although we'll discuss another variation.

In analytic terms, use Slerp to determine the points on each triangle edge.
Take the cross product of the opposing pairs of points to determine the normal
to the intersecting plane corresponding to each line. Take the cross product of
each pair of normals to find a vector proportional to the point of
intersection. (As the cross product is antisymmetric, be careful about order
here.) Then normalize each vector and take their centroid.

In terms of equations, Method 2 or the Great Circle Intersection
method on a triangle is:
\begin{equation}\begin{split}%??? does this reduce to slerp on the edges?
\widetilde{\mathbf v} & = \sum^3_{i=1} \frac{\mathbf h_i \times \mathbf h_{i+1}}
{\|\mathbf h_i \times \mathbf h_{i+1}\|} \\
\mathbf h_i & =
\mathrm{Slerp}(\mathbf v_{i-1}, \mathbf v_i; \beta_{i})
\times
\mathrm{Slerp}(\mathbf v_{i+1}, \mathbf v_i; \beta_{i})
\end{split}\end{equation}

No explicit inverse, unlike \cite{gray95}\cite{crider08}

The above equation can be tweaked slightly by removing the step of normalizing
the vectors at the points of intersection. This still produces a point within
the triangle. This formula is a little more computationally efficient and
easier to treat algebraically. Where $\mathbf h_i$ is as before:
\begin{equation}\label{eq:gct}%??? does this reduce to slerp on the edges?
\widetilde{\mathbf v} = \sum^3_{i=1} \mathbf h_i \times \mathbf h_{i+1} \\
\end{equation}

This method can be extended to the Quadrilateral. Use Slerp to find points on
opposing sides of the quadrilateral, use the cross product to find their
normal, and then use the cross product to find the point of intersection. Since
we draw two intersecting lines, there is only one point of intersection within
the quadrilateral. The formula is:
\begin{equation}\label{eq:gcq}%??? does this reduce to slerp on the edges?
\widetilde{\mathbf v} =
(\mathrm{Slerp}(\mathbf v_1, \mathbf v_2; \frac{u+1}{2})
\times
\mathrm{Slerp}(\mathbf v_4, \mathbf v_3; \frac{u+1}{2}))
\times
(\mathrm{Slerp}(\mathbf v_1, \mathbf v_4; \frac{v+1}{2})
\times
\mathrm{Slerp}(\mathbf v_2, \mathbf v_3; \frac{v+1}{2}))
\end{equation}

This is similar to the Great Circle method, except instead of using the great
circles to calculate the intersections of the lines, we use another spherical
linear interpolation to get a point near the intersection. We effectively use
the Lerp formulas from the section on coordinates, substituting Slerp for Lerp.
Unlike Lerp, Slerp does not commute, so we take the different permutations of
the arguments and combine the different points that result.

Triangular:
\begin{equation}\label{eq:fullert}
\widetilde{\mathbf v} = \sum^3_{i=3} \mathrm{Slerp}(
\mathrm{Slerp}(\mathbf v_{i-1}, \mathbf v_i; \beta_{i}),
\mathrm{Slerp}(\mathbf v_{i+1}, \mathbf v_i; \beta_{i});
\frac{\beta_{i-1}}{1-\beta{i}})
\end{equation}
Quadrilateral:%??? not symmetric?
\begin{equation}\label{eq:fullerq}
  \begin{split}
\widetilde{\mathbf v} =& \mathrm{Slerp}(
\mathrm{Slerp}(\mathbf v_1, \mathbf v_2; \frac{u+1}{2}),
\mathrm{Slerp}(\mathbf v_4, \mathbf v_3; \frac{u+1}{2}); \frac{v+1}{2})\\
&+ \mathrm{Slerp}(
\mathrm{Slerp}(\mathbf v_1, \mathbf v_4; \frac{v+1}{2}),
\mathrm{Slerp}(\mathbf v_2, \mathbf v_3; \frac{v+1}{2}); \frac{u+1}{2})
\end{split}
\end{equation}

(or is this forward fuller and the other one's reverse fuller?)

Solve for each $\beta'_i$:
\begin{equation}
\begin{vmatrix} \mathbf v &
\mathrm{Slerp}(\mathbf v_{i-1}, \mathbf v_i; \beta'_i) &
\mathrm{Slerp}(\mathbf v_{i+1}, \mathbf v_i; \beta'_i) \end{vmatrix} = 0
\end{equation}
$\beta_i$ does not have a closed-form solution on general triangles,
but each $\beta_i$ can be optimized separately,
so the optimization process is not too unwieldy.

In general, $\sum \beta'_i \ne 1$ for the $\beta'_i$ resulting from this
process. Let $\beta_i = \frac{\beta'_i }{\sum \beta_i}$.

\subsection{Naive Slerp}
The Naive Slerp method is derived by a naive analogy with spherical linear
interpolation (Slerp) extended to barycentric or $uv$ coordinates, thus the
name.
\subsubsection{Triangles}
\begin{equation}\label{eq:nst}
   \widetilde{\mathbf v} = \sum_{i=1}^3\frac{\sin(w\beta_i)}{\sin(w)}  \mathbf v_i
\end{equation}
Here, $w$ is a function of $\beta_i$. Let $w_i$ be the spherical length of the edge opposite vertex $i$. Then,
\begin{equation}
  w = \frac{\beta_0 \beta_1 w_2 + \beta_1 \beta_2 w_0 + \beta_2 \beta_0 w_1}
      {\beta_0 \beta_1 + \beta_1 \beta_2 + \beta_2 \beta_0}.
\end{equation}
This function satisfies the requirement that $w = w_i$ on the edge opposite
vertex $i$, and elsewhere on the triangle smoothly parameterizes between the
values. $w$ is not defined at the vertices, and does not have a limit there
unless the two edges that meet at that vertex have the same length. However,
any positive value for $w$ can be used there without changing the result.
If all the edges are equal length,
$w$ can be replaced with that constant edge length.

\subsubsection{Projection of $\widetilde{\mathbf v}$}
The naive slerp methods produces unit vectors along the edges. Because the
projected edges already lie on the sphere, we have freedom in how to adjust
$\widetilde{\mathbf v}$ to lie on the sphere. The easiest is just to centrally
project the vertices, that is, to normalize $\widetilde{\mathbf v}$ like we
have been. Another option is to perform a parallel projection along the
face normal, as defined earlier. We need the parallel distance $p$ from the
vertex to the sphere surface in the direction of the face normal
$\hat{\mathbf n}$, such that $\hat{\mathbf v} =
\widetilde{\mathbf v} + p\hat{\mathbf n}$. $p$ is given by:
\begin{equation}
   p = -\widetilde{\mathbf v} \cdot \hat{\mathbf n} +
   \sqrt{1+\widetilde{\mathbf v} \cdot \hat{\mathbf n}-\widetilde{\mathbf v} \cdot \widetilde{\mathbf v}}
\end{equation}
$p$ can also be approximated as $\widetilde{p} = 1 - \|\widetilde{\mathbf v}\|
\leq p$, which takes fewer operations and doesn't require
calculation of the face normal. Technically, you can project in almost any
direction, not just that of the face normal, but most other choices don't
produce a symmetric result.

Really, the projection can be performed from any point in space. Central
projection uses rays from a point at the center of the sphere, and parallel can
be thought of as using rays from a point at infinity. Instead of specifying the
point, we define a linear combination of the two projections:
\begin{equation}
  \hat{\mathbf v} = \frac{\widetilde{\mathbf v} + kp\mathbf c}{\|\dots\|}
\end{equation}
When $k=0$, that's the central projection: when $k=1$, it's the parallel
projection. $p$ may be replaced by $\widetilde{p}$. If our goal is to optimize
a measurement of the map projection, like conformal or area distortion, we
can do a 1-variable optimization on $k$.

\subsection{Linear combination}

Let $f_i (\mathbf v)$ be a sequence of map projections from a spherical
polygon $R_s$
to a spherical polygon $R_e$.
Let $\mathbf v_i$ be the
vertices of the spherical polygon. Furthermore, require that $f_i(\mathbf v_j)$
takes the same value for all $i$ and $j$: the projections all maintain the same
orientation of polygon. Then, let $w_i$ be a sequence of weights, possibly
negative, such that $\sum w_i = 1$. It can be easily demonstrated that
$g(\mathbf v) = \sum w_i f_i(\mathbf v)$ is also a map projection from $R_s$ to
$R_e$. (This holds whether we think of $R_e$ in terms of barycentric coordinates
or a planar Euclidean polygon.)

If any individual $f_i(\mathbf v)$ is non-differentiable or has a singularity
at any point or points, $g(\mathbf v)$ will generally be non-differentiable or
have a singularity in the same place.

Unfortunately, $g(\mathbf v)$ may not have a closed-form inverse, even if all
of the contributing $f_i(\mathbf v)$ do.

\section{Analysis}
\subsection{From the sphere to the plane}

\subsection{From the plane to the sphere}

\section{Conclusion}

\bibliographystyle{plain}
\bibliography{references}

\end{document}


\section{CDF and Description Logics}
\label{sec:comp}

\begin{example} \rm \label{ex:classexpr}
Consider the (rather abstract) CDF instance:
\begin{verbatim}
     isa(cid(a),cid(b))                  isa(cid(a),cid(c))
     hasAttr(cid(a),rid(r1),cid(e))      allAttr(cid(a),rid(r2),cid(f)).
\end{verbatim}
%     isa(b,d).
%     isa(f,g).                  hasAttr(f,r3,h)
The axioms for this instance are logically equivalent to
%----------
\begin{tabbing}
fooo\=foo\=foo\=foo\=fooooooooooooooooooooooooooooooo\=ooooooooooooo\=\kill
\> $isClass(a) \wedge isClass(b) \wedge
	(\forall X)[elt(X,a) \Ra elt(X,b)] $ \\
\> $isClass(a) \wedge isClass(c) \wedge
	(\forall X)[elt(X,a) \Ra elt(X,c)] $ \\
\> $isClass(a) \wedge isRel(r1) \wedge isClass(e) \wedge
     (\forall X)[elt(X,a) \Ra \exists Y.(rel(X,r1,Y) \wedge elt(Y,e))]$ \\
\> $isClass(a) \wedge isRel(r2) \wedge isClass(f) \wedge
     (\forall X)[elt(X,a) \Ra \forall Y.(rel(X,r1,Y) \wedge elt(Y,f))]$
\end{tabbing}
%----------
which in turn are logically equivalent to
%----------
\begin{tabbing}
fooo\=foo\=foo\=foo\=fooooooooooooooooooooooooooooooo\=ooooooooooooo\=\kill
$isClass(a) \wedge isClass(b) \wedge isClass(c) \wedge isClass(e)
	\wedge isClass(f) \wedge isRel(r1) \wedge isRel(r2)  \wedge $ \\
$(\forall X)[elt(X,a) \Ra$ \\
\> \> $(elt(X,b) \wedge  elt(X,c) \wedge$ \\
\> \> $(\exists Y)[rel(X,r1,Y) \wedge elt(Y,e)] \wedge
      (\forall Y)[rel(X,r2,Y) \Ra elt(Y,f)]]$
\end{tabbing}
%----------
Semantics for description logics are formulated in various ways.
In~\cite{Swif04}, the semantics for ${\cal ALC}$-style description
logics are given in terms of first order formulas over an ontology
language similar to that used in Definition~\ref{def:ontolang}.  Using
the translation of \cite{Swif04} the class expression
\[ b \sqcap c \sqcap exists(r2,f) \sqcap all(r2,f) \]
translates into the formula.
%----------
\begin{tabbing}
fooo\=foo\=foo\=foo\=fooooooooooooooooooooooooooooooo\=ooooooooooooo\=\kill
\>  $(\exists X)[ $
$ elt(X,b) \wedge elt(X,c)  \wedge $ \\
\> \> $(\exists Y)[rel(X,r1,Y) \wedge elt (Y,e)] \wedge
       (\forall Y)[rel(X,r2,Y) \Ra elt(Y,f)]]$
\end{tabbing}
%----------
\end{example}

Clearly there is a strong similarity between the meaning of certain
class expressions and certain CDF instances.  To formalize this
similarity, we use the definition of an {\em atomic relational CDF
instance}.
\begin{definition}
Let $\cO$ be a CDF intance.  $\cO$ is {\em atomic} if it contains no
product identifiers.  $\cO$ is a {\em relational instance} if it
contains no object identifiers, and no {\tt classHasAttr/3}
predicates.
\end{definition}

%-------------------------
\mycomment{
Next, note that, ignoring sorting predicate, each instance axiom for
an atomic relatoinal class instance $\cO$ has the form: $\forall
X.(elt(X,C) \Ra Template)$.  Thus, $\cO^{\cI}$ is equivalent to the
set of formulas
\begin{tabbing}
fooo\=foo\=foo\=foo\=fooooooooooooooooooooooooooooooo\=ooooooooooooo\=\kill
\> $\forall X.(elt(X,C_1) \Ra Template_1)
       \wedge \ldots \wedge\forall X.(elt(X,C_n) \Ra Template_n) $
\end{tabbing}
Where $\{C_1 \ldots C_n\}$ is the set of class identifiers in the
first argument of each fact in $\cO$.
}
%-------------------------

We also need to formalize the language of class expressions that we
will use.

\begin{definition}
The syntax of an \omsdl{} class expression has the following form, in
which $A$ is an atomic class identifier, $R$ a relation identifer, $N$
a non-negative integer, and $C_1$ and $C_2$ \omsdl{} class expressions.
\[ C \leftarrow A | C_1 \sqcap C_2 | all(R,C_1) | exists(R,C_1)
	| atLeast(N,R,C) | atMost(N,R,C) \]
\end{definition}

If $C$ is an \omsdl{} class expression, it can be translated according
to Definition 1.3 of \cite{Swif04}, into a first order sentence
(denoted as $C^{\cT}$) over what are called first-order description
logic languages.  These languages contain slightly different predicate
symbols from $\cL$, so we make use of a function $f$ from structures
over ontology languages to structures over first-order description
logic languages~\footnote{Given a structure $\cM$ over an ontology
language, $\cL_{CDF}$, we construct a language $f(\cL_{CDF})$ by
setting the set of atomic class names in $f(\cL_{CDF})$ equal to the
class identifiers in $\cL_{CDF}$, and the atomic relation names in
$\cL'_D$ equal to the relation identifiers in $\cL_{CDF}$.  A new
structure $f(\cM)$ is constructed by restricting $\cM$ to $elt/2$
and $rel/3$ predicates.}.

In the following theorem, $TH(\cO)/4$ denotes $TH(\cO)$ minus Core
Axiom~\ref{ax:contained} (Domain Containment).  A model $\cM$ is
$C$-reified for a class expression $C$ if for each sub-expression $C'$
of $C$, there is a constant $c'$ such that $isClass(c')$ and $\cM
\models (\exists X)[elt(X,c')]$ and $C'^{\cT}$ holds for all $d$ such
that $\cM \models elt(d,c)$.   $c'$ is called a witnessing constant for
$C$.

\begin{theorem}
Let $C$ be an \omsdl{} class expression.  Then
\begin{enumerate}
\item There exists a $C$-reified model $f(\cM)$ for $C$.
\item There is an atomic CDF instance $\cO$ such that
\begin{enumerate}
\item For any $C$-reified model $f(\cM)$ of $C$, there is a CDF instance
$\cO$ such that $\cM \models TH(\cO)/4$
\item For any model $\cM$ of $TH(\cO)/4$, $f(\cM) \models C^{\cT}$.
\end{enumerate}
\end{enumerate}
\end{theorem}
\begin{proof}
The proof is contained in the appendix.
\end{proof}

Atomic CDF class instances thus have an expressive power that is
equivalent to a weak description logic.  However general CDF class
instances can also specify axioms about objects and their attributes,
as well as making use of non-inheritable relations and product
identifiers.  From Theorme~\ref{thm:poly}, however, consistency of an
CDF instance can be checked in polynomial time, while consistency
checking for ${\cal ALC}$ is {\em P-space} complete~\cite{ShmS91}.
CDF instances can be considered as ``special-cases'' of class
descriptions that can be extended into more elaborate descriptions if
needed, but otherwise are efficient for consistency checking,
subsumption checking and other operations.

%------------------------------------------------
\mycomment{
However, CDF can be compared to FLORA facts, for which it is somewhat
simpler.  CDF does not provide for a constraint that a given attribute
is functional as is allowed in FLORA, although this extension can be
provided if CDF instances are extended to have unqualified number
restrictions

Also, CDF does not provide for non-monotonic inheritance, but
substitutes the monotonic inheritances described in
Section~\ref{sec:inheritance}.  }


\section{Conclusion and Discussion}

For the resonance method and the comparison method

In the experiment
the speed of sound in the air was measured through two ways:
the resonance method and the phase comparison method.
From the two means, we have
    \begin{equation}
    \begin{split}
        v&=351.05\pm0.4 m/s,\quad u_{r,v}=0.10\%;\\
        v&=348.95\pm10 m/s,\quad u_{r,v}=3\%,
    \end{split}
    \end{equation}
    respectively.

    From the result after analyzing, we can conclude that the results of the resonance method has higher precision but not enough accuracy.
    On the other hand, the results of the phase comparison method has higher accuracy but not enough precision.

The reason account for the lack of  preciseness may be the easiness to
determine the time we get the distance which shares the same length of half wave length for Resonance Method,
or one wave length for Phase comparison Method.

For Resonance Method, it's not very easy to observe whether the wave on oscilloscope became the maximum amplitude.
For Phase-comparison Method, it is easy to observe whether the Lissajous figure becomes a straight line with a positive slope in each period.

Thus we managed to get the data that are close to each other because of the easy observation.
The very uncertainty may due to random error in this experiment.

The reason for the preciseness may be that we manage to obverse the place of first resonance point, though the resonance curve is not flat enough, which may make the observation difficult.
 The little relative error may come from random error in this experiment and the difficulty to obverse.

In conclusion, the result produced in the experiment is relatively precise and accurate.
Through the Resonance Method and the Phase-comparison Method, we can get a very precise result.
Through the Time-difference Method, we can get a very accurate result, though it may only be an accident in this experiment. In order to compare these four methods, we should do the experiment for several times to reduce random error.
Moreover, we are introduced the Successive Difference Method, which is a more effective way to reduce error. We can use this method in other experiments.


% JuliaCon proceedings template
\documentclass{juliacon}
\setcounter{page}{1}

%%%
%% Language Support
%%%
\usepackage[english]{babel}

%%%
%% Images
%%%
\usepackage{graphicx}
\graphicspath{{figures/}}
\usepackage[export]{adjustbox}

%%%
%% Fonts and Typewriting
%%%
\usepackage{mathtools}
\usepackage{amssymb}
\usepackage{bbm}
\usepackage{bm}
\usepackage{microtype}

%%%
%% Enhances Figures and Tables environments
%%%
\usepackage{placeins}
\usepackage[hypcap=true]{caption}
\usepackage{booktabs, multirow, array, tabularx, floatrow, cellspace, threeparttable}
\floatsetup[table]{capposition = top}
\newcolumntype{Z}[1]{>{\centering\arraybackslash}p{#1}}
\newcolumntype{Y}{>{\centering\arraybackslash}X}
\renewcommand{\arraystretch}{1.25}

%%%
%% Enables hyperlinks
%%%
\usepackage{varioref}
\hypersetup{
    pdftitle    = {Econometrics.jl},
    pdfsubject  = {JuliaCon 2019 Proceedings},
    pdfauthor   = {José Bayoán Santiago Calderón},
    pdfkeywords = {Julia, Econometrics, Regression Analysis, Panel Data, Generalized Linear Models, Discrete Choice Models, Instrumental Variables Estimation, Variable Absorption, Software Validation},
    colorlinks  = true,
    linkcolor   = black,
    filecolor   = black,
    urlcolor    = black,
    citecolor   = black
}
\urlstyle{same}

\DeclareMathOperator{\HadamardProduct}{.*}

\begin{document}

\input{header}

\maketitle

\begin{abstract}

Econometrics.jl is a package for econometrics analysis. It provides a series of most common routines for applied econometrics such as models for continuous, nominal, and ordinal outcomes, longitudinal estimators, variable absorption, and support for convenience functionality such as weights, rank deficient, and robust variance covariance estimators. This study complements the package through a discussion of the motivation, placing the contribution within the Julia ecosystem and econometrics software in general, and provides insights on current gaps and ways the Julia ecosystem can evolve.

\end{abstract}

\section{Introduction}

This study has four core sections. The first surveys what are some commonly used functionality for econometrics analysis. The second provides an overview of the current state of these within the Julia \cite{Bezanson_Edelman_Karpinski_Shah_2017} ecosystem including current tools and gaps. The third provides a comprehensive summary of the functionality provided by the new package, Econometrics.jl, and next steps. Lastly, I provide insights on how the Julia ecosystem can evolve from my experience developing the new tool.

Regression analysis is a core tool used to understand the relation among variables. For example, understanding these relationships can provide insights into causal relations or as a basis to develop predictive models. In the realm of statistical inference, one may be interested in common targets such as confidence intervals of the parameters estimates, joint-significance of features, out-of-sample predictive performance, and others. Moreover, most models make certain assumptions which can be tested through statistical tests or model diagnostics which provide confidence in the estimation and results.

Regression analysis is a broad term that encompasses a wide variety of estimators and models. What follows is a brief summary of some of the many components that may fall within the concept. Regression analysis can be used for both observational and experimental settings and it allows great flexibility for a multitude of applications. The main idea is to find estimates for model parameters to optimize some objective such as the likelihood in maximum likelihood estimation (MLE). Other potential objectives include restricted maximum likelihood (REML) or a (Quasi-)Bayesian approach such as maximum a posteriori probability (MAP). One framework is the generalized linear model (GLM) which use a linear predictor that is mapped through a link function to a distribution modeling the response. Continuous responses might use a Normal distribution, count responses a log link with a Negative Binomial distribution, and probability models might use a categorical distribution with links that map to valid probabilities such as the Logit link. In cases such as probability models where the responses are multidimensional, the generalization is known as vector generalized linear models (VGLM). Other generalizations include relaxing the relation between the linear predictor and the outcome to be the sum of smoothing functions through a generalized additive model (GAM) framework or incorporating random effects through a mixed models approach. Some estimators address challenges such as endogeneity, censored responses, and zero-inflated responses through various solutions such as instrumental variables or censored regression model. Others, exploit aspects of the data to overcome challenges or increase efficiency such as random effects in longitudinal data. In relation to the second moment of the estimator, robust variance covariance estimators or boostrapping may be required for inference.

Of the many potential tools practitioners may require, what are some of the most common? Not every estimator is as widely accessible or commonly used. Some educated guesses may be well justified such as ordinary least squares being more widely used than spatially-weighted regressions. In order to avoid speculation, I defer to a reasonable assumption that the most common estimators are those usually taught in academic programs and available in widely used software \cite{Renfro_2009}. Most programs teach tools to address the most common response types: continuous, count / rates, nominal, ordinal, and duration outcomes. This suggests some common models may include linear models, Poisson/negative binomial, multinomial logistic regression, and ordinal logistic regression with proportional odds assumption. Topics in time series and panel data are usually offered in most programs. Perhaps, the most common topic is short panels (i.e., many units of observations and relatively small number of repeated observations). Common estimators include pooling, first-difference, fixed effects / within estimator, and one-way random effects. The between estimator is usually masked as an intermediate model for estimating the error component in the random effects model. Lastly, the two big challenges taught in most programs are endogeneity and heteroscedasticity. These challenges are usually countered through instrumental variables (e.g., 2SLS) or robust variance-covariance estimators (e.g., heteroscedasticity consistent estimators).

Previous work have surveyed the functionality of 24 alternatives for common econometrics routines \cite{Renfro_2009}. Throughout the history of econometrics software, alternatives have risen and fallen in following. Some high contenders by market share include Stata \cite{Stata}, R \cite{R}, MATLAB, Python \cite{Python}, IBM SPSS Statistics, SAS software, and EViews. These include both commercial and open-source alternatives. Functionality may be provided by the base/standard libraries in the statistical software environment, as a product such as a toolkit or user contributed such as a module/package that is distributed. Some examples of user-contributed functionality include the reghdfe Stata module and a series of R packages such as MASS \cite{MASS}, lmtest \cite{lmtest}, sandwich \cite{sandwich}, plm \cite{plm}, and mlogit \cite{mlogit}.

\section{Common Estimators}

\subsection{Weighted Least Squares}

Weighted least squares solves

\begin{equation}
	\beta = \left(X^{\top} W X\right)^{-1} X^{\top} W y
\end{equation}
with information matrix
\begin{equation}
\Psi = \left(X^{\top} W X\right)^{-1}
\end{equation}

where $X$ is the full rank version of a model matrix, $W$ a diagonal matrix with positive values (e.g., frequency), and $y$ the response. The common solution method is to factorize $X$ as either its QR decomposition or Cholesky decomposition. Singular value decomposition may also be used, but it is rare as the computational complexity is significantly higher. In the case of the QR decomposition the solution method comes down to, transforming the model matrix and the response by row-wise multiplying them by the square root of the weights.\footnote{The row-wise Hadamard product is used in equation \ref{QR} as ($\HadamardProduct$).} Afterwards, the factorization is used to solve the system of equations using the appropriate method. In the case of a QR decomposition, $R$ is an upper triangular matrix which enables back substitution to obtain the solution efficiently without matrix inversion. However, a Cholesky decomposition would still be required if the information matrix is desired. The solution method with QR decomposition is delineated in equation \ref{QR}.\footnote{The (\textbackslash)\ is a linear solver operator, such that $x = A \backslash b => Ax = b$.}

The case for the Cholesky decomposition follows closely and without loss of generality other variants could be used such as Bunch-Kaufman decomposition or the upper triangular form ($U^{\top}U$). The QR decomposition is more numerically stable, but more expensive than Cholesky.\footnote{$\mathcal{O}\left(n^{3}\right) > \mathcal{O}\left(2mn^{2}-\frac{2}{3}2n^{3}\right)$ where the matrix has $m$ rows and $n$ columns.} Equation \ref{Cholesky} delineates the solution method with Cholesky decomposition. Since the information matrix is an important component, Bunch-Kaufman decomposition, a Cholesky variant, is the preferred method used in Econometrics.jl.

\begin{equation}
\label{QR}
\begin{split}
	\tilde{X} = X \HadamardProduct \sqrt{w} \\
	\tilde{y} = y \HadamardProduct \sqrt{w} \\
	QR = \tilde{X} \\
	\beta = R \ \backslash \ \left( Q^{\top} \tilde{y} \right)
\end{split}
\end{equation}

\begin{equation}
\label{Cholesky}
\begin{split}
	LL = \left( X^{\top} W X \right) \\
	\beta = L \ \backslash \ \left( X^{\top} W y \right) \\
	\Psi = \left( L^{-1}\right)^{\top} L^{-1}
\end{split}
\end{equation}

The remaining estimators will assume a Cholesky decomposition as part of the estimation technique. The QR decomposition will be used in models estimated through iterative reweighted least squares (IRLS) as the factorization may be computed once and recycled.

\subsection{Within Estimator}

The within estimator is an application of the Frisch-Waugh-Lovell theorem \cite{FWL, FWLProof}. The estimator allows to compute the parameters estimates and information matrix for a subset of predictors without having to include the full set of categorical features. For example, one may include individual fixed effects in a large data set that may increase the dimension of the model matrix to several thousand making the problem unfeasible or inefficient. Moreover, some parameters may not be consistently estimated in certain contexts. For example, individual fixed effects are not consistently estimated when there is a fixed length for the panels (i.e., more observations implies more parameters a type of curse of dimensionality).

Consider the following model,
\begin{equation}
	y = X \beta + D \theta + e
\end{equation}
where $y$ is the response, $\beta$ the parameters of interest, $X$ the features of the parameters of interest, $D$ a high dimensional representation of categorical features as control, $\theta$ the parameters on said covariates, and $e$ the error term. In order to obtain the parameter estimates $\beta$ and the associated information matrix, we can estimate an alternative specification.
\begin{equation}
	\tilde{y} = \tilde{X} \beta + e
\end{equation}
where $\tilde{X}$ and $\tilde{y}$ are obtained by using projections, such as the annihilator matrix (i.e., $I - X \left(X^{\top}W X\right)^{-1} X^{\top})$. There are several methods to obtain a suitable alternative regression and these are not unique. Stata's module reghdfe \cite{reghdfe} presents several approaches to solving these problems including specialized methods in certain applications. Some implementations include Stata module reghdfe and the FixedEffectsModels.jl \cite{FixedEffectModels.jl} package. The two most common approaches are solving for the residuals through a sparse least-squares problems such as with LSMR \cite{LSMR} or using some variant for the method of alternating projections. The residuals approach tends to be more efficient, but degrades certain aspects of the model (e.g., no longer able to obtain the mean response). The method of alternating projections is able to preserve under certain conditions artifacts of the original regression such as obtaining the same estimate for the intercept even though it is not particularly meaningful. Using the original response and the invariant residuals allows to recover the fitted values of the original model.

\subsection{Between Estimator}

The between estimator estimates
\begin{equation}
	\tilde{y} = \tilde{X} \beta + e
\end{equation}

where the transformed model components are collapsed through some dimension through the mean function. For example, one approach to obtaining the error component for a random effects model is to use model statistics of the between estimator collapsing by panel. The weighted version of the model uses the observation weights to compute the weighted mean values and may use the weight fractions by the collapsing dimension as weights for the weighted least squares regression on the transformed model.

\subsection{Random Effects Model}

The random effects model relies in estimating the unobserved error components. Random effects requires a particular schema for the data which has a panel component and a temporal component. There are multiple approaches, but the most common one is the Swamy-Arora approach \cite{SwamyArora}. This estimator uses the mean squared residuals estimates (i.e., deviance divided by residual degrees of freedom) of the between and within models using the panel dimension as the collapsing / dimension to absorb. The error components are estimated as
\begin{equation}
\begin{split}
	\theta_{g} = 1 - \sqrt{\frac{\sigma_{e}^{2}}{T_{g} * \sigma_{u}^{2} + \sigma_{e}^{2}}} \\
	\sigma_{e}^{2} = W \\
	\sigma_{u}^{2} = \max\left\{0, B - \sigma_{e}^{2} * \bar{T}\right\} \\
\end{split}
\end{equation}

where $W$ is the mean squared residuals of the within model, $B$ the mean squared residuals of the between model, and $T_{g}$ is the length of the panel $g$, and $\bar{T}$ is the harmonic mean of the panel lengths.

The model terms are then transformed by partial demeaning
\begin{equation}
\begin{split}
\tilde{y}_{it} = y_{it} - \theta_{g} * \bar{y}_{.t} \\
\tilde{X}_{it} = X_{it} - \theta_{g} * \bar{X}_{.t}
\end{split}
\end{equation}

and these are used in the standard regression setting.

\subsection{First-Difference Estimator}

The first-difference estimator is a special case that use time / panel context for feature designs. The most common transformations include contrasts such as treatment coding (dummy coding), sum coding (effects coding) or Helmert coding which apply to categorical variables. Other common feature engineering techniques include log-transform and polynomial terms. However, certain transformations require a context such as a time dimension. Some examples include shift operations (lag, lead) and differentiating (e.g., first-difference). These operations may optionally require a group context such that the operations are performed group wise. Time-context operations have important concepts such as frequency and gaps. The frequency describes the difference between periods/observations and gaps describe observations that are skipped and should be understood as missing.

\subsection{Instrumental Variables}

Every estimator thus far can be generalized to include endogenous covariates through instrumental variables. The most common method is through two stages least squares (2SLS). The idea is to first apply all the relevant transformations to the model terms and apply the 2SLS standard procedure. In the case of the random effects model, the within and between models are estimated using 2SLS to obtain the error component estimates. After applying the random effects transformation to each model term the 2SLS process is employed in the final regression model \cite{BV_1987}.

The standard 2SLS estimator uses,
\begin{equation}
\begin{split}
\hat{z} = [X Z] \left[ \left( [X Z]^{\top} W [X Z] \right)^{-1} [X Z]^{\top} W z\ \right] \\
\hat{\beta} = \left( [X \hat{z}]^{\top} W [X \hat{z}] \right)^{-1} [X \hat{z}]^{\top} W y \\
\Psi = \left( [X \hat{z}]^{\top} W [X \hat{z}] \right)^{-1} \\
\hat{y} = [X z] \hat{\beta}
\end{split}
\end{equation}

for each model where $z$ is endogenous variables and $Z$ the additional instruments.

\subsection{Nominal Response Model}

Multinomial logistic regression is a probability model for estimating probabilities across multiple categories. It is a vector generalized linear model with softmax link function and the categorical distribution. It is estimated through iterative re-weighted least squares (IRLS) methods such as the QR Newton variant \cite{OLeary_1990}. The data schema for discrete choice models include the response (observed behavior), unit of observation covariates, and outcomes-specific covariates. The initial implementation allows for the base case of no-outcome specific features.

\subsection{Ordinal Response Model}

Ordinal logistic regression is a probability model for estimating probabilities across multiple ordered categories. Similarly to its nominal counterpart, it has a pool of alternatives, and observed outcome, unit of observation covariates, and outcome-specific covariates. A common assumption is the proportional odds assumption which may be relaxed in other models.

The log-likelihood ($\ell$) function has the same form as the general form for computing the cost associated with a categorical distribution and predicted probability for realization. More specific,
\begin{equation}
	\ell = \sum_{i = 1}^{m} \sum_{k}^{K} \mathbbm{1}\left(y_{i} = k\right) \ln\left[F\left(\alpha_{k + 1} - \eta\right) - F\left(\alpha_{k} - \eta\right)\right]
\end{equation}

where $F$ is the cumulative distribution function of the logistic distribution with zero location and unit scale, $\eta$ is the linear projection, and $\alpha_{k}$ is the threshold for lower threshold \cite{ologit}. The log-likelihood function and the gradient are passed to the Optim.jl framework \cite{Optim} using ForwardDiff.jl \cite{ForwardDiff} forward mode automatic differentiation (AD) for the Newtonian solver.

\subsection{Count/Rate Model}

Count/rate models are generalized linear models and follow a similar description as nominal models. The most common distribution choices are Poisson and Negative Binomial with the log link function. Negative Binomial is a generalization of the Poisson model, which adds an extra parameter for modeling the second moment (i.e., relaxes the mean equal variance assumption in the Poisson model). For the Negative Binomial to be a distribution in the exponential family it needs a restriction parameter which may be optimized through maximum likelihood estimation. An offset may be included to handle rates, a generalization of counts, that account for differences in exposures. Other generalizations include additive or multiplicative errors relations.

\subsection{Duration Models}

Duration models deal with responses of the type time until an event. One such model is the Cox proportional hazards model which relies on the proportional hazards assumption. Various models of these kind may be re-specified in a generalized linear model framework relating to the previous descriptions.

\section{Technical Challenges}

One technical challenge that is prevalent through every model is the issue of rank deficient terms. Rank deficient systems of linear equations are not identifiable. One approach is to error out and let the user explore and find a subset of features such that the no multi-collinearity assumption holds. The second approach is to automatically promote the system to a full rank version by excluding linearly dependent features. How much collinearity is too much is not an exact science. Some potential criteria include using the absolute values of the diagonal in the triangular matrix of the factorization (e.g., $L$ in $LL^{\top}$, $R$ in $QR$, $D$ in $LDL^{\top}$, $\Sigma$ in $U\Sigma V^{\top}$). These values are then compared against a chosen tolerance and the column of the term is deemed linearly independent if the values are greater than the tolerance.

Note that Cholesky, QR, and Bunch-Kaufman decomposition allow to identify which columns are independent while singular values only allow to determine the rank. It may be arbitrary to choose among linearly dependent features. An additional level of complexity in probability models is the issue of linearly separability for probability models \cite{Konis_2007}.

\section{Julia Ecosystem}

The usual pipeline for regression analysis involves (1) accessing data (I/O), (2) obtaining a tabular data representation, (3) data wrangling, and (4) employing regression analysis tools. The following sections provides an overview of the pipeline available in Julia provided by the Julia statistics and data ecosystems.

\subsection{Data to Modeling}

StatsBase.jl \cite{StatsBase.jl} builds on top of Statistics.jl (standard library) to provide additional statistical functionality. One which includes the abstraction for Statistical Models (and Regression models which inherits from the former). It provides a simple and powerful API for the whole Julia ecosystem to use. It allows packages to implement the API and easily support a common functionality users can expect and interact with in a familiar manner. For example, \textit{coef} will extract the parameter estimates from any object that implements the API. The full API include model statistics such as: coefficient of determination (or adjusted), information criteria statistics such as AIC/BIC (and corrected), statistics about the model fitness such as deviance, log-likelihood, and usual queries such as point estimates, variance covariance estimates, standard errors, confidence intervals, degrees of freedom (or residual degrees of freedom). Lastly, several accessors are available for fitted values, response, model matrix, information matrix, leverage values, error components, etc. Lastly, it also provides an abstraction for weights including frequency weights and analytical weights.

Tables.jl \cite{Tables.jl} provide an interface for tabular data. This API allows users to choose from various solutions the tabular data implementation of their choosing without having to worry that their choice will limit potential functionality. Many tabular implementations such as DataFrames.jl \cite{DataFrames.jl} provide robust functionality to many routines such as handling categorical features, dates/time, missing values, reshaping data, split/apply operations, and others. Users need not to worry about any I/O issues as a rich array of options exist for importing and exporting across different file formats such as delimiter-separated values, JSON, Feather, HDF5, MATLAB, Stata, SPSS, SAS, and R.

StatsModels.jl \cite{StatsModels.jl} is a package that provides the means to go from data to model terms. It provides the formulae language (e.g., similar to R's formulae syntax). A model is then build using a formula, data, and additional model specific arguments. The process can be summarized as (1) collecting the information in the formula, (2) parsing its meaning by applying a schema based on the data, user-specified contrasts or other arguments, and (3) generating the model terms such as a response, model matrices, etc. Lastly, a package fits said model and implements the API.

\subsection{Regression Analysis}

The regression analysis ecosystem in Julia has GLM.jl \cite{GLM.jl} as its flagship. GLM.jl provides the typical functionality for fitting generalized linear models through Fisher scoring. This includes linear models, Poisson/Negative Binomial, Logit/Probit, and other non-canonical link models. CovarianceMatrices.jl \cite{CovarianceMatrices.jl} provides various variance covariance estimators for GLM.jl models à la R's
sandwich package. MixedModels.jl \cite{MixedModels.jl} extends GLM.jl for mixed-effects models. FixedEffectModels.jl provides fast estimation of linear models with instrumental variables and high dimensional categorical variables à la reghdfe. Survival.jl \cite{Survival.jl} provides a series of estimators for duration models. Two major gaps in the ecosystem include estimating nominal and ordinal response models (i.e., discrete choice) with more than two alternatives and support for longitudinal estimators.

\section{Econometrics.jl}

Econometrics.jl is a package for performing several common econometrics routines in the Julia language. It aims to provide the following functionality for two major gaps in the ecosystem, longitudinal estimators and discrete choice models. Developing the package has resulted in many contributions in the current ecosystem. However, the development of this package serves multiple purposes beyond the immediate effect. As the statistics ecosystem evolves and matures, Econometrics.jl aims to serve as inspiration and an alternative to design decisions, standards, and option for users and developers.

\subsection{Fitting Models}

This section will showcase some examples of using the package for various estimators. For each estimator a brief description of the data, model, syntax, and output will be provided. Results will be provided for Econometrics.jl and some alternatives such as R or Stata.

For linear models, the examples use a crime dataset \cite{Crime}. The data set is a balanced longitudinal data set with 90 counties in North Carolina from 1981 to 1987. The outcome variable is the crime rate and the explanatory variables include the probability of conviction, average sentence, and probability of prison sentence. Estimating the pooling estimator or the between estimator can be accomplished as in figure \vref{estimator_pooling} and \vref{estimator_between}. Table \vref{poberes} shows the estimated 95\% confidence intervals using Econometrics.jl, Stata, and R's plm package.

The syntax to estimate a model follows the StatsBase API which provides a method for building and estimating models (i.e., \textit{fit}). The \textit{fit} approach takes (1) an estimator, (2) a model formula, (3) data, and additional arguments depending on the model. \textit{EconometricModel} is the generic estimator which dispatches to continuous, nominal or ordinal response models automatically based on the type of the response. Other estimators are available and the following figures illustrate some of the use cases.

The fixed effects model or within estimator can be estimated as in figure \vref{withinmodel} which a two-ways fixed effects model (i.e., fixed effects for panel and time dimensions). Table \vref{withinres} shows the estimated 95\% confidence intervals using Econometrics.jl, Stata, and R's plm package.

The random effects model can be estimated as in figure \vref{random} which shows estimating a random effects model with instrumental variables. Table \vref{xtregres} shows the estimated 95\% confidence intervals using Econometrics.jl, Stata's reghdfe module, and R's plm package.

The sysdsn1 Stata example health insurance data set is used to illustrate the multinominal logistic regression when the response is nominal as seen in figure \vref{mlogit}. A comparison with the estimates for the 95\% confidence intervals between Econometrics.jl and Stata is shown in table \vref{mlogitres}.

The fullauto Stata example automobile models data set is used to illustrate the proportional ordinal logistic regression when the response is ordinal as seen in figure \vref{ologit}. A comparison with the estimates for the 95\% confidence intervals between Econometrics.jl, Stata, and R's MASS is shown in table \vref{ologitres}.

\begin{figure}[hbpt]
    \includegraphics[max width=\linewidth,center]{estimator_pooling}
	\caption{Estimation of the pooling estimator}
	\label{estimator_pooling}
\end{figure}

\begin{figure}[hbpt]
    \includegraphics[max width=\linewidth,center]{estimator_between}
	\caption{Estimation of the between panel estimator}
	\label{estimator_between}
\end{figure}

\begin{figure}[hbpt]
	\includegraphics[max width=\linewidth,center]{estimator_fe}
	\caption{Estimation of the within estimator with multiple fixed effects}
	\label{withinmodel}
\end{figure}

\begin{figure}[hbpt]
	\includegraphics[max width=\linewidth,center]{estimator_ivre}
	\caption{Estimation of the random effects model}
	\label{random}
\end{figure}

\begin{figure}[hbpt]
	\includegraphics[max width=\linewidth,center]{estimator_mlogit}
	\caption{Estimation of the multinomial logistic regression}
	\label{mlogit}
\end{figure}

\begin{figure}[hbpt]
	\includegraphics[max width=\linewidth,center]{estimator_ologit}
	\caption{Estimation of the proportional odds logistic regression}
	\label{ologit}
\end{figure}

\subsection{Should Software be Dummy-Proof?}

Statistical software developers play a very powerful role in shaping culture and norms. For example, whether to default to maximum likelihood estimation (MLE) or restricted maximum likelihood estimation (REML), can shape not only choices by practitioners, but by stakeholders, regulatory agencies, and expected components for reports. These changes may be good or bad depending on the case. For example, advances in econometrics are rarely widely adopted without buy-in from software developers. The following discussions will survey some of the decisions relevant to Econometrics.jl.

Should software be dummy-proof? Many times software developers have to choose between exposing users to make mistakes on their own volition or put safeguard against potential misuses by restricting behavior that may be correct under rare scenarios. For example, a basic tool might allow users to mix and match link and distributions in a GLM settings even if the combinations are nonsensical. A safer approach would be to restrict combinations to those ``safe'' combinations such as distributions with canonical links. The trade-off occurs when users may encounter a specification that while uncommon it may be the correct one for that particular model. Currently, Econometrics.jl takes a conservative approach that provides ``dummy-proof'' experience as well as ease of use. For example, rather than requiring users to specify the model, the estimator is inferred based on the type of the response and information provided as long as it is unambiguous. Other examples of this approach include auto-promoting model statistics such as the coefficient of determination to a pseudo-version for non-linear models (a generalization of the linear case), but providing a not a number (NaN) value for instrumental variable models or those that do not include an intercept. Similarly, the software will promote terms to full rank as required. The formula term and coefficient table provide all the information needed to figure which if any feature was suppressed.

The decision to adhere to a common API has various benefits. For example, being able to interact and query models consistently enables packages that enhance the experience providing features such as diagnostics (i.e., statistical tests, plots) or convenience tools for dissemination such as \LaTeX\ code for results. Currently, the ecosystem still demands certain functionality to rely on internals which forces code to be less generalizable (e.g., CovarianceMatrices.jl only supports GLM models and relies on internals rather than a common API).

Econometrics.jl has as a goal to make opinionated decisions after careful consideration. Consider for example whether to report statistics using finite-sample statistics (t-distribution, F-distribution) or asymptotic equivalent counterparts (Normal, Chi squared). These tend to have negligible effects in most applications, but other decisions such as degrees of freedom may have larger consequences. One case is how software computes the degrees of freedom for instrumental variables or absorbed variables depending on the context (e.g., main regression or auxiliary regression for estimating error components). Refinements and robustness checks can also contribute to a better analysis such as verifying gaps for time variant operations such as in first-difference or purging singletons and other degree of freedom adjustments \cite{Singletons}.

\subsection{Best Practices}

Econometrics.jl adopts the best practices standards for open-source statistical software. These include adhering to semantic versioning (semver) for descriptive versioning, continuous integration for development, software validation through a comprehensive code coverage and test suite, and lastly online hosted documentation for the public API.\footnote{\href{https://nosferican.github.io/Econometrics.jl/stable}{https://nosferican.github.io/Econometrics.jl/stable}}

\section{Conclusion}

Econometrics.jl is a new addition to the Julia ecosystem that brings highly demanded functionality concerning longitudinal estimators and discrete choice models. This study serves as a complement to the software documentation providing context to the development, design considerations, and roadmap of the project. A philosophical motivation for the project is to make econometrics accessible to practitioners not only through functionality, but transparency in the code readability, replicability, and correctness. For example, transparent well-written code is easier to maintain, inspect / audit, and can be useful for learning and teaching.

Community contributions and feedback are highly encouraged in order to best continue developing the project. Some features I would like the project to support in the future include more advanced estimators such as: (1) choice-variant categorical response models, (2) count/rate models such as zero-inflated, and (3) censored/truncated response models. Econometrics.jl is ISC licensed and available at the GitHub repository. The package is registered in the official Julia registry (General); as such it can be installed using the Julia package manager.

\section{Acknowledgement}

This research benefited from support from the National Science Foundation and the AEA Mentoring Program: NSF Awards 1357478 \& 1730651.

I would also like to thank Hisam Sabouni for useful feedback during the development of the project and at an earlier draft of the article \cite{JBSC2019} and Jeffrey Wooldridge for guidance in the programming of the estimators.

\input{bib.tex}

\appendix
\onecolumn
\input{figures/pobe.tex}
\input{figures/fem.tex}
\input{figures/xtreg.tex}
\input{figures/mlogit.tex}
\input{figures/polr.tex}

\end{document}

% Inspired by the International Journal of Computer Applications template


%\subsection{Symbolic Numeric Computation}

\bigskip
\noindent
\textbf{2.3. Symbolic-Numeric Computation}
\bigskip

There are important applications in engineering, particularly control theory and linear systems theory, where physical models are represented as polynomials and polynomial matrices (or more generally rational functions and rational matrices). Properties of such models are then represented in terms of arithmetic in polynomial or polynomial matrix domains. However, while the polynomial algebra for such representations assume exact arithmetic, the input data is typically measured (i.e. inexact) values. For these {\em symbolic-numeric} problems \cite{corless2} the arithmetic theory needs to be properly defined, and algorithms need to be both efficient in terms of operation count and, more importantly, numerically correct. Our directions in this area include sparse interpolation and arithmetic with approximate rational functions. The common thread in these two topics is their relation with Prony types of problems.

\bigskip
\noindent
{\bf Previous Work and Proposed Research}
\bigskip

Sparse polynomial interpolation is the problem of recovering a representation of a polynomial over a basis (typically the standard power basis). This problem is closely connected to the shape from moments problem  in the plane \cite{MilanfarGolub} along with the decomposition of a signal built as a linear mixture of complex exponentials \cite{HuaSarkar}. In these cases efficient algorithms need to depend on the number of terms in the sparse representation rather than the possible number of terms found in a dense representation. Sparse representations
are common in applications. For example, the recovery of low rank information from sparse sampling is at the core of the
compressed sensing paradigm \cite{candes}. We have previously shown in [J16] that this problem was closely related to problems solved via Prony's method from 1795. This in turn allowed us to take advantage of modern numerical work by Golub et al \cite{golub1} to solve this problem via the use of generalized Hankel eigenvalues. The issue of the poor numerical conditioning of the generalized Hankel eigenvalue problem (indeed bounded below by an exponential factor) reported in  \cite{begola} was overcome by using randomization in determining sampling points.
%This topic is also the theme of our Dagstuhl meeting in June 2015 and a BIRS workshop in 2016.
%Sparse polynomial interolation and exponential analysis are the themes of our Dagstuhl meeting in June 2015 and a BIRS workshop in 2016.
Sparse interpolation and exponential analysis are the themes of our Dagstuhl meeting in June 2015 and BIRS workshop in 2016.

Sparse interpolation is typically considered for multivariate polynomials defined over the standard polynomial basis. However, there are a number of applications where sparse representations coming from Chebyshev and Pochhammer polynomials \cite{gll2} are more useful - the former being particularly interesting as it allows for sparse modeling of fourier cosine data. We propose to address the computational challenges in finding sparse representations in other orthogonal and/or interpolation bases over approximate floating point environments. In the short term we plan to investigate the use of structured linear algebra formulations represented in terms of Krylov type matrices. However we expect that even analysing the numerical sensitivities of this problem will be extremely challenging.

The standard shape-from-moments problem reconstructs 2-D polygonal shapes from 2-D moment data. Some previous work has been done on higher dimensional shapes \cite{cuyt} but the recent paper by Gravin et al \cite{lasserre}, formulating an $n$-D shape-from-moments problem using Brion's formula to find the $n$ dimensional vertices of a polygonal from higher dimensional moments seems most promising. A longer term challenge is to actually compute the $n$ dimension coordinates in a provable numerically stable way, and whenever not possible, to understand the conditioning issues that arise \cite{cchlc}. We propose to look at this problem by making use of tools from structured linear algebra but with the structures coming from multivariate polynomial arithmetic (for both power and alternate bases).
%Classical structured matrices such as Hankel and Toeplitz linearly describe univariate polynomial arithmetic identities.
%As before, our plan is to do this for both power polynomial or exponential bases along with a number of alternate polynomial bases.

Our second research direction in this area is the symbolic-numeric computation of rational functions.
Symbolic-numeric computation with polynomials, including such operations as finding zeros and greatest common divisors has been a well studied topic over the last two decades in computer algebra. However the same cannot be said for working with rational functions. This is a bit surprising since for applications (for example function approximations or input-output problems from control theory), one typically encounters rational rather than polynomial functions. For rational functions understanding ```close'' properties involves understanding the zeros and poles of nearby rational functions. For example in the case of rational approximation, the nearby zeros and poles have significant impact on convergence and other properties.  This becomes a difficult issue when working over a numerical environment. Interestingly enough one cannot just work with symbolic-numeric arithmetic with numerators and denominators separately. Here the main issue is one of missing or spurious poles, that is, poles with a nearby zero or poles with small residuals.  Recent attempts to address the notion of closeness includes the %introduction of the
concept of
robust rational approximants found in \cite{gonnet} and the notion of well-conditioned rational approximants from the interesting new paper \cite{matos}.

We propose two separate directions for research in this area, both with high impact and long term in nature. The measures for closeness given in \cite{matos} make use of unstructured
condition numbers. We propose to replace these measures by structured condition numbers as was done earlier in case of numerically coprime polynomials \cite{coprime}. We would expect the result that the ``nearby regions''  be enlarged and the computation of the structured measures more efficient. A second problem is to change our representation for rational functions from zero-pole to partial fraction decomposition and then look for measures of closeness. We note that this would require only the poles of a rational function, which can be viewed as a Prony type of problem, and which is better understood in a numerical environment.

%{\bf Arithmetic with Differential Operators : }
%Symbolic/numeric computation with differential operators considers the algebraic operations on operators having polynomial coefficients whose coefficients in turn are approximate numbers. Preliminary work defining basic operations suchas one sided GCDs have recently been presented
%\cite{haraldson}.


\subsection{Runtime}
\label{subsec:experiments-runtime}

Considering runtime, we report CPU time\footnote{\label{foot:runtime}
    Runtimes have been taken on an Intel$^\text{\textregistered}$ Core\texttrademark\xspace i7-3770 @ $3.4GHz$, 64bit with 32GB RAM.
} excluding connected components but including color space conversions if applicable.
We made sure that no multi-threading or GPU computation were used. We begin by considering
runtime in general, with a glimpse on realtime applications, before considering iterative algorithms.

We find that some well performing algorithms can be run at (near) realtime. We
consider Figure \ref{fig:experiments-runtime}
showing runtime in seconds $t$ on the \BSDS (image size $481 \times 321$) and \NYU (image size $608 \times 448$) datasets.
Concretely, considering the watershed-based algorithms \Wr and \CWr, we can report runtimes below $10\text{ms}$
on both datasets, corresponding to roughly~$100\text{fps}$. Similarly, \PFr
runs at below $10\text{ms}$. Furthermore, several algorithms, such as
\SLICr, \ERGCr, \FHr, \PBr, \MSSr and \preSLICr provide runtimes below $80\text{ms}$
and some of them are iterative, \ie reducing the number of iterations may further
reduce runtime. However, using the convention that realtime corresponds to
roughly $30\text{fps}$, this leaves \preSLIC and \MSS on the larger images
of the \NYU dataset. However, even without explicit runtime requirements, we find runtimes
below $1\text{s}$ per image to be beneficial for using superpixel algorithms as
pre-processing tool, ruling out \TPS, \CIS, \SEAW, \RW and \NC.
Overall, several superpixel algorithms provide runtimes appropriate for pre-processing tools;
realtime applications are still limited to a few fast algorithms.

\begin{figure}[t]
    \centering
    \input{plots/runtime-bsds500-nyuv2}
    \caption{Runtime in seconds on the \BSDS and \NYU datasets.
    Watershed-based, some clustering-based algorithms as well as \PF offer
    runtimes below $100ms$. In the light of realtime applications, \CW, \W
    and \PF even provide runtimes below $10ms$. However, independent of the
    application at hand, we find runtimes below $1s$ beneficial for using
    superpixel algorithms as pre-processing tools.
    \textbf{Best viewed in color.}}
    \label{fig:experiments-runtime}
\end{figure}
\begin{figure}[t]
    \centering
    \input{plots/runtime-iterations}
    \caption{\Rec, \UE and runtime in seconds $t$ for iterative algorithms with
    $\K \approx 400$ on the \BSDS dataset.
    Some algorithms allow to gradually trade performance for runtime, reducing runtime
    by several $100ms$ in some cases.
    \textbf{Best viewed in color.}}
    \label{fig:experiments-iterations}
	\vskip 12px
	\input{legends/full+depth+implementations-half}
\end{figure}
\FloatBarrier

Iterative algorithms offer to reduce runtime while gradually lowering performance.
Considering Figure \ref{fig:experiments-iterations},
showing \Rec, \UE and runtime in seconds $t$ for all iterative algorithms on the \BSDS dataset,
we observe that the number of iterations can safely be reduced to decrease
runtime while lowering \Rec and increasing \UE only slightly. In the best case,
for example considering \ETPSr, reducing the number of iterations from $25$ to $1$
reduces the runtime from $680\text{ms}$ to $58\text{ms}$, while keeping \Rec und \UE
nearly constant. For other cases, such as \SEEDSr\footnote{
	We note that we use the original \SEEDS implementation instead of the
	OpenCV \cite{Bradski:2000} implementation which is reported to be more efficient, see
	\url{http://docs.opencv.org/3.0-last-rst/modules/ximgproc/doc/superpixels.html}.
}, \Rec decreases abruptly when
using less than $5$ iterations. Still, runtime can be reduced from $920\text{ms}$
to $220\text{ms}$. For \CRSr and \CISr, runtime reduction is similarly significant,
but both algorithms still exhibit higher runtimes. If post-processing
is necessary, for example for \SLICr and \preSLICr, the number of iterations has
to be fixed in advance. However, for other iterative algorithms, the number of
iterations may be adapted at runtime depending on the available time.
Overall, iterative algorithms are beneficial as they are able to gradually
trade performance for runtime.

We conclude that watershed-based as well as some path-based and clustering-based
algorithms are candidates for realtime applications. Iterative algorithms,
in particular many clustering-based and iterative energy optimization algorithms, may
further be speeded up by reducing the number of iterations and trading performance for
runtime. On a final note, we want to remind the reader that the image sizes of all
used datasets may be relatively small compared to today's applications.
However, the relative runtime comparison is still valuable.