\documentclass[a4paper,10pt]{article}
\usepackage{graphicx} % Include figure files
\usepackage{fullpage}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{amssymb,amsmath} 
\usepackage[colorlinks=true,linkcolor=Blue,linktoc=page,citecolor=Red,urlcolor=BrickRed]{hyperref}
%\usepackage{color}
%\usepackage[utf8x]{inputenc}
\usepackage{enumitem}
\usepackage{hyperref}
\usepackage{listings}
%\usepackage{makeidx}
\usepackage{fancyhdr}
\usepackage{titlesec}
\usepackage{epigraph}
\usepackage{titling}
\lstset{
language=C,
basicstyle=\footnotesize,
numbers=left,
numberstyle=\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=false,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
escapeinside={\%*}{*)}
}
\pretitle{\begin{flushleft}\LARGE\bfseries\sffamily}
\posttitle{\par\end{flushleft}\vskip 0.5em\vspace{-7ex}}
\predate{\begin{flushleft}\sffamily\large}
\postdate{\par\end{flushleft}\vskip 0.5em\vspace{-2ex}}
\titleformat{\section}[hang]{\bfseries\sffamily\Large}
{\thesection}
{12pt}{\filright}

\titleformat{\subsection}[hang]{\bfseries\sffamily}
{\thesubsection}
{12pt}{\filright}

\titleformat{\subsubsection}[hang]{\bfseries}
{\thesubsubsection}
{12pt}{\filright}

\newcommand{\vari}[2]{\textcolor{OliveGreen}{#1}{#2}}
\newcommand{\macr}[1]{{\tt \textcolor{BrickRed}{#1}}}
\newcommand{\functi}[3]{{\tt\textcolor{OliveGreen}{#1}
    \textcolor{blue}{#2}(#3)}}

\newenvironment{funcdef}[2][void main(void)]
{\vspace{12pt}\par\noindent{\large{\bf #1}}\vspace{5pt}
 \par\noindent\leftskip=20pt{{#2}}\vspace{5pt}
 \par\noindent\leftskip=5pt\rightskip=5pt}
{\par\leftskip=0pt\rightskip=0pt\vspace{12pt}}


\title{NaMaster: C API and code documentation}

\begin{document}

\maketitle
\noindent\makebox[\linewidth]{\rule{\textwidth}{1pt}}
\tableofcontents
\noindent\makebox[\linewidth]{\rule{\textwidth}{1pt}}

\section{Introduction}

NaMaster is a C library, Python module and standalone program to compute full-sky angular cross-power spectra of masked, spin-0 and spin-2 fields with an arbitrary number of known contaminants using a pseudo-$C_\ell$ (aka MASTER) approach.

\subsection{Dependencies}
The following packages need to be installed before NaMaster.
\begin{itemize}
  \item {\bf GSL}: the GNU Scientific Library. This should be available in your usual software repositories (e.g. synaptic for linux), but you can also download and install it from \url{https://www.gnu.org/software/gsl/} (the installation follows the usual {\tt ./configure}, {\tt make}, {\tt make install} procedure.
  \item {\bf HEALPix}: the C HEALPix subroutines are also needed. HEALPix can be downloaded from \url{http://healpix.jpl.nasa.gov/}, and the C library can be compiled following the instructions after typing {\tt ./configure} and then {\tt make c-all}. The header and library files will then be placed in two local folders called {\tt include} and {\tt lib}. The user should then feel free to move these files to a different location.
  \item {\bf CFITSIO}: a FITS file subroutine library. This is used to read/write HEALPix maps in FITS format. {\tt cfitsio} can be downloaded from \url{http://heasarc.gsfc.nasa.gov/fitsio/fitsio.html}.
  \item {\bf Libsharp}: a fast C library for spherical harmonic transforms. Libsharp can be downloaded from its github repository: \url{https://github.com/dagss/libsharp}. After cloning it, you should run {\tt autoreconf -i} to generate the configuration file. Then run {\tt ./configure} and {\tt make}, which will compile the library and place all compilation products in the folder {\tt ./auto}. The corresponding header and library files should then be manually moved to the desired installation directories.
\end{itemize}


\subsection{Compilation and usage}\label{ssec:compile}
\subsubsection*{Installing the C library and binaries}
NaMaster uses {\tt autotools} for installation, which means that you should be able to install it by simply typing
\begin{verbatim}
   ~$ ./configure
   ~$ make
   ~$ make install
\end{verbatim}
If you don't have default admin privileges you may have to precede the last command by {\tt sudo}. If you don't have admin privileges at all (i.e. you can't modify the contents of standard directories such as {\tt /usr/lib}), you can still install NaMaster by substituting the first command by {\tt ./configure --prefix=/path/to/dir}, where {\tt /path/to/dir} should be the full path of the directory where you want to install this package. This will create three sub-directories: {\tt /path/to/dir/include}, {\tt /path/to/dir/lib}, {\tt /path/to/dir/bin}, where the header, library and binary files will be placed respectively.

Note that, if you don't have admin privileges, probably some of the dependencies listed in the previous sections will also be installed in non-standard paths. If that is the case, you should make sure the environment variables {\tt CPPFLAGS} and {\tt LDFLAGS} contain the corresponding {\tt -I/path/to/dir2/include} and {\tt -L/path/to/dir2/lib} tags that point to the directories where these dependencies are installed (see \href{https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html}{this link} for more details on {\tt make} implicit variables).

\subsection*{Installing the python wrapper}
NaMaster comes equipped with a python wrapper. This is installed by running
\begin{verbatim}
   ~$ python setup.py install
\end{verbatim}
Without admin privileges you can still make this work by running
\begin{verbatim}
   ~$ python setup.py install --user
\end{verbatim}
The python wrapper needs to link with NaMaster's library. If the latter was installed in a non-standard path (e.g. {\tt /path/to/install}), you'll need to pass the corresponding directory to {\tt setup.py}. You can do so by running
\begin{verbatim}
   ~$ python setup.py build_ext --library-dirs=/path/to/install/lib/
       --rpath=/path/to/install/lib/
\end{verbatim}
before the install commands above.

\subsection*{Linking with the C library}
If you want to use NaMaster on your own C code you'll need to be able to link with {\tt libnmt} (the NaMaster C library). There are two main things to do:
\begin{enumerate}
 \item Make sure to include the NaMaster header in any C file that makes use of any of the NaMaster subroutines:
       \begin{verbatim}
         #include <namaster.h>
       \end{verbatim}
 \item When compiling your code, make sure you link to {\tt libnmt} and all dependencies. In the simplest case, assuming you have written a C script called {\tt min\_code.c}, the following should work:
       \begin{verbatim}
         gcc -fopenm -I/path/to/nmt/include min_code.c -o min_code
             -L/path/to/nmt/lib -lnmt -lsharp -lfftpack -lc_utils
             -lchealpix -lcfitsio -lgsl -lgslcblas -lm
       \end{verbatim}
       where {\tt /path/to/nmt/include} and {\tt /path/to/nmt/lib} are the directories where {\tt namaster.h} and {\tt libnmt.so} are installed.
\end{enumerate}
Section \ref{sec:sample} below contains a fully working C script that calls the NaMaster library.

\section{NaMaster - the program}
NaMaster comes with its own executable that computes the pseudo-$C_\ell$ power spectrum of two input masked fields with possible contaminants. After installation (and assuming it has been installed in an accessible directory), the program can be invoked by typing {\tt namaster}.

The user interacts with {\tt namaster} by providing parameters as command-line arguments in the form of a pair: {\tt -<param\_name> <param>}. After typing
\begin{verbatim}
  ~$ namaster -h
\end{verbatim}
the user is presented with a list of all available input parameters:
\begin{verbatim}
Usage: namaster -<opt-name> <option>
Options:
  -map      -> path to file containing map(s)
  -map_2    -> path to file containing 2nd map(s) (optional)
  -mask     -> path to file containing mask
  -mask_2   -> path to file containing mask for 2nd map(s) (optional)
  -temp     -> path to file containing contaminant templates (optional)
  -temp_2   -> path to file containing contaminant templates
               for 2nd map(s) (optional)
  -pol      -> spin-0 (0) or spin-2 (1) input map(s)
  -pol_2    -> spin-0 (0) or spin-2 (1) 2nd input map(s)
  -pure_e   -> use pure E-modes for 1st maps? (0-> no or 1-> yes (default->no))
  -pure_b   -> use pure B-modes for 1st maps? (0-> no or 1-> yes (default->no))
  -pure_e_2 -> use pure E-modes for 2nd maps? (0-> no or 1-> yes (default->no))
  -pure_b_2 -> use pure B-modes for 2nd maps? (0-> no or 1-> yes (default->no))
  -cl_noise -> path to file containing noise Cl(s)
  -cl_guess -> path to file containing initial guess for the Cl(s)
  -coupling -> path to file containing coupling matrix (optional)
  -out      -> output filename
  -binning  -> path to file containing binning scheme
  -nlb      -> number of ells per bin (used only if -binning isn't used)
  -h        -> this help
\end{verbatim}

Some clarification is in order regarding some of these parameters:
\begin{itemize}
 \item {\tt map} and {\tt map\_2}: these arguments should point to FITS files containing the maps of the two fields to correlate. These files should contain one map if {\tt pol} (or {\tt pol\_2}) is 0 and two maps ($Q$ and $U$) if {\tt pol} (or {\tt pol\_2}) is 1. If {\tt map\_2} is not passed, the auto-correlation of {\tt map} will be computed (and all other {\tt \_2} options will be ignored).
 \item {\tt mask} and {\tt mask\_2}: these arguments should point to FITS files containing the masks of the two fields to correlate (one map per file).
 \item {\tt temp} and {\tt temp\_2}: these arguments should point to FITS files containing the contaminant templates you suspect are poluting your fields. The number of contaminants will be derived by the code based on the number of maps in the files. Note that an exception will occur if this number is not a multiple of the number of maps corresponding to the field's spin (see above).
 \item {\tt cl\_noise}: this file should contain the expected noise bias (see discussion below Eq. \ref{eq:master_full}) to be subtracted from the estimated power spectrum. The format of this file should be $N+1$ columns, with the first column being the multipole number $\ell$ (starting at $\ell=0$), and the next $N$ being the different component of the power spectrum. $N$ should correspond to the number of power spectra expected given the spins of the two fields being correlated. I.e. $N=1$ if {\tt pol=pol\_2=0} ($(TT)$), $N=2$ if {\tt pol=0}, and {\tt pol\_2=1} (or vice-versa, $(TE,TB)$), and $N=4$ if {\tt pol=pol\_2=1} ($(EE,EB,BE,BB)$). If this option is not passed, it is assumed to be $0$. This file should contain $3{\tt nside}$ rows, where {\tt nside} is the HEALPix resolution parameter of the input maps.
 \item {\tt cl\_guess}: proposal power spectrum (i.e. best guess of true power spectrum) used to compute the deprojection bias (same format as {\tt cl\_noise} above). This is only relevant for contaminated fields. If not passed, the proposal power spectrum is set to $0$.
 \item {\tt out}: path to output ASCII file. First column will correspond to the effective $\ell$ in the bandpower. All subsequent columns correspond to the different components of the power spectrum (as described above depending on the field spins).
 \item {\tt binning}: path to ASCII file describing the binning scheme defining the output bandpowers. This file should contain three columns: the first column should contain the bandpower index of the different multipoles, the second column should contain the multipoles and the third column should contain the weight corresponding to each multipole (the sum of weights in each bandpower is automatically normalized to $1$).
 \item {\tt nlb}: number of multipoles per bandpower. In this case the output power spectrum will be computed by binning multipoles in sets of {\tt nlb} from $\ell=2$ to $\ell=3{\tt nside}-1$.
\end{itemize}






\section{C documentation}
Important note: all HEALPix maps passed to NaMaster routines should be in RING order.

\subsection{Fields}
The definition of the fields to be correlated (including their masks and possible contaminants) is handled through a C structure called {\tt nmt\_field}. The following routines exist to manage this structure:

\begin{funcdef}[nmt\_field\_alloc]
 {\functi{nmt\_field *}{nmt\_field\_alloc}
 {\vari{long}{ nside},\vari{double *}{mask},\vari{int}{ pol},\vari{double **}{maps},\\\vari{int}{ ntemp},\vari{double ***}{temp},\vari{double *}{beam},\vari{int }{pure\_e},\vari{int }{pure\_b}}}
 This is the constructor for {\tt nmt\_field}. The input variables are:
 \begin{itemize}[noitemsep]
   \item {\tt nside}: the HEALPix resolution of all maps involved
   \item {\tt mask}: sky mask (as a single scalar HEALPix map).
   \item {\tt pol}: set to 0 if this is a spin-0 field. Set to 1 if it's a spin-2 field.
   \item {\tt maps}: set of maps corresponding to observed field. This would correspond to one map for a scalar field or two maps for spin-2 quantities (e.g. Q and U for polarization maps or $\gamma_1$, $\gamma_2$ for cosmic shear). The first dimension of this double array would correspond to the number of maps, while the second dimension runs through the different pixels of each map.
   \item {\tt ntemp}: number of contaminant templates for this field.
   \item {\tt temp}: contaminant templates as HEALPix maps. The first dimension should run through the different templates, the second dimension corresponds to the number of maps per template (e.g. 1 for spin-0 and 2 for spin-2) and the third dimension corresponds to the number of pixels.
   \item {\tt beam}: spherical harmonic transform of the instrumental beam (assumed to be rotationally symmetric - i.e. no $m$ dependence). If {\tt NULL}, no beam will be corrected for. Otherwise, this array should have $3\times{\tt nside}$ elements, corresponding to multipoles $\ell\in[0,3\,{\tt nside}-1]$.
   \item {\tt pure\_e}, {\tt pure\_b}: set to a value different from 0 if you want to use pure-$E/B$ modes for this field. Note that, in this case you should make sure the mask and its first derivatives are continuous on its boundary (see {\tt nmt\_apodize\_mask} below).
 \end{itemize}
 \end{funcdef}

\begin{funcdef}[nmt\_field\_read]
 {\functi{nmt\_field *}{nmt\_field\_read}
 {\vari{char *}{fname\_mask},\vari{char *}{fname\_maps},\vari{char *}{fname\_temp},\\\vari{char *}{fname\_beam},\vari{int }{pol},\vari{int }{pure\_e},\vari{int }{pure\_b}}}
 As {\tt nmt\_field\_alloc}, this returns a pointer to a {\tt nmt\_field} structure based on:
 \begin{itemize}[noitemsep]
   \item {\tt pol}: set to 0 if this is a spin-0 field. Set to 1 if it's a spin-2 field.
   \item {\tt fname\_mask}: file name pointing to a FITS file containing the sky mask (as a single scalar HEALPix map).
   \item {\tt fname\_maps}: file name pointing to a FITS file containing the maps of the observed field. This file should contain a single map for {\tt pol}=0 and two maps for {\tt pol}=1.
   \item {\tt fname\_temp}: file name pointing to a FITS file containing the contaminant templates as HEALPix maps. Each template should contain $N$ maps with $N=1$ for {\tt pol}=0 and $N=2$ for {\tt pol}=1. Pass ``none'' if no contaminants are needed (in which case deprojection and debiasing will not take place).
   \item {\tt fname\_beam}: file name pointing to an ASCII file containing the spherical harmonic transform of the instrumental beam (assumed to be rotationally symmetric - i.e. no $m$ dependence). If {\tt ``none''}, no beam will be corrected for. Otherwise, this file should contain two columns ($\ell$ and $b_\ell$) and $3\times{\tt nside}$ columns, corresponding to multipoles $\ell\in[0,3\,{\tt nside}-1]$.
   \item {\tt pure\_e}, {\tt pure\_b}: set to a value different from 0 if you want to use pure-$E/B$ modes for this field. Note that, in this case you should make sure the mask and its first derivatives are continuous on its boundary (see {\tt nmt\_apodize\_mask} below).
 \end{itemize}
\end{funcdef}

\begin{funcdef}[nmt\_field\_free]
 {\functi{void}{nmt\_field\_free}{\vari{nmt\_field *}{fl}}}
 This frees up all memory associated to a previously-allocated {\tt nmt\_field}.
\end{funcdef}


\subsection{Binning scheme}
The definition of bandpowers is managed through C structures called {\tt nmt\_binning\_scheme}. The following routines allow you to interact with this structure:

\begin{funcdef}[nmt\_bins\_constant]
 {\functi{nmt\_binning\_scheme *}{nmt\_bins\_constant}{\vari{int }{nlb},\vari{int }{lmax}}}
 Creates an {\tt nmt\_binning\_scheme} structure (and returns a pointer to it) where the bandpowers are constant intervals of {\tt nlb} multipoles with equal weights between $\ell=2$ and $\ell={\tt lmax}$.
\end{funcdef}

\begin{funcdef}[nmt\_bins\_create]
{\functi{nmt\_binning\_scheme *}{nmt\_bins\_create}{\vari{int }{nell},\vari{int *}{bpws},\vari{int *}{ells},\\\vari{double *}{weights},\vari{int }{lmax}}}
 Creates an {\tt nmt\_binning\_scheme} structure (and returns a pointer to it) with bandpowers defined by the following parameters:
 \begin{itemize}[noitemsep]
  \item {\tt ells}: array of multipole indices
  \item {\tt bpws}: array containing the band power each $\ell$ in {\tt ells} corresponds to.
  \item {\tt weights}: array containing the weight for each $\ell$ in {\tt ells}. These need not be normalized, but they will be normalized such that the sum of weights within each bandpower equals 1.
  \item {\tt nell}: number of elements in the three previous arrays.
  \item {\tt lmax}: all multipoles $\ell>{\tt lmax}$ will be ignored.
 \end{itemize}
\end{funcdef}

\begin{funcdef}[nmt\_bins\_read]
{\functi{nmt\_binning\_scheme *}{nmt\_bins\_read}{\vari{char *}{fname},\vari{int }{lmax}}}
 Creates an {\tt nmt\_binning\_scheme} structure (and returns a pointer to it) with bandpowers defined by the contents of an ASCII file with name {\tt fname}. This file should contain three columns corresponding to the arrays {\tt bpws}, {\tt ells} and {\tt weights} passed to {\tt nmt\_bins\_create}. All multipoles $\ell>{\tt lmax}$ will be ignored.
\end{funcdef}

\begin{funcdef}[nmt\_bins\_free]
{\functi{void}{nmt\_bins\_free}{\vari{nmt\_binning\_scheme *}{bin}}}
 Frees all memory associated with an allocated {\tt nmt\_binning\_scheme} structure.
\end{funcdef}

\begin{funcdef}[nmt\_bin\_cls]
{\functi{void}{nmt\_bin\_cls}{\vari{nmt\_binning\_scheme *}{bin},\vari{double **}{cls\_in},\vari{double **}{cls\_out},\vari{int }{ncls}}}
 Performs a binning operation:
 \begin{equation}
   B_k=\sum_{\ell\in\vec{\ell}_k}w_\ell C_\ell.
 \end{equation}
 Here, $C_\ell\rightarrow{\tt cls\_in}$ is a set of {\tt ncls} angular power spectra, $B_k\rightarrow{\tt cls\_out}$ is a set of bandpowers and $w_\ell$ and $\vec{\ell}_k$ are the weights and multipole ranges defining the binning scheme {\tt bin}. Both {\tt cls\_in} and {\tt cls\_out} should have been previously allocated. The first dimension of both {\tt cls\_in} and {\tt cls\_out} should run from 0 to ${\tt ncls}-1$. Their second dimension should correspond to the number of multipoles and bandpowers used to create {\tt bin} respectively (for instance, the latter can be accessed as {\tt bin->n\_bands}).
\end{funcdef}

\begin{funcdef}[nmt\_unbin\_cls]
{\functi{void}{nmt\_unbin\_cls}{\vari{nmt\_binning\_scheme *}{bin},\vari{double **}{cls\_in},\vari{double **}{cls\_out},\vari{int }{ncls}}}
 Performs a un-binning operation:
 \begin{equation}
   C_\ell=\sum_k\,B_k\Theta(\ell\in\vec{\ell}_k)
 \end{equation}
 Here, $B_k\rightarrow{\tt cls\_in}$ is a set of {\tt ncls} bandpowers, $C_\ell\rightarrow{\tt cls\_out}$ is a set of angular power spectra and $w_\ell$ and $\vec{\ell}_k$ are the weights and multipole ranges defining the binning scheme {\tt bin}. The function $\Theta(\ell\in\ell_k)$ is $1$ for all multipoles contained in the $k$-th bandpower and zero otherwise. Both {\tt cls\_in} and {\tt cls\_out} should have been previously allocated. The first dimension of both {\tt cls\_in} and {\tt cls\_out} should run from 0 to ${\tt ncls}-1$. Their second dimension should correspond to the number of bandpowers and multipoles used to create {\tt bin} respectively (for instance, the former can be accessed as {\tt bin->n\_bands}).
\end{funcdef}

\begin{funcdef}[nmt\_ell\_eff]
 {\functi{void}{nmt\_ell\_eff}{\vari{nmt\_binning\_scheme *}{bin},\vari{double *}{larr}}}
 This function returns, in the output array {\tt larr}, the effective multipole corresponding to each bandpower defined by {\tt bin}. This is computed as:
 \begin{equation}
   \ell^{\rm eff}_k=\sum_{\ell\in\vec{\ell}_k}\ell\,w_\ell,
 \end{equation}
 where $w_\ell$ are the bandpower weights. {\tt larr} should have been previously allocated to the number of bandpowers defined by {\tt bin}.
\end{funcdef}

\subsection{Pseudo-$C_\ell$}
The implementation of the pseudo-$C_\ell$ estimator can be split into the following steps:
\begin{enumerate}
  \item Clean up your best guess of the known contaminants in your data maps. This step can be skipped if you think your maps are clean of contaminants. This step is automatically carried out when initializing an {\tt nmt\_field} structure with template contaminants.
  \item Compute the cross-pseudo-$C_\ell$ of the cleaned maps $\tilde{C}^{\rm clean}_\ell$.
  \item Compute the bias on the pseudo-$C_\ell$ caused by the statistical residual contaminants $\tilde{C}^{\rm cont}_\ell$.
  \item Compute the mode-coupling matrix associated with the field masks ${\sf M}_{\ell\ell'}$.
  \item Compute the de-coupled and de-biased bandpowers:
        \begin{equation}\label{eq:master_full}
          B_k=\sum_{k'}(\mathcal{M})^{-1}_{kk'}\sum_{\ell\in\vec{\ell}_{k'}}w_{\ell'}\left[\tilde{C}^{\rm clean}_{\ell'}-\tilde{C}^{\rm cont}_{\ell'}-\tilde{C}^{\rm noise}_{\ell'}\right],
        \end{equation}
        where $\mathcal{M}$ is the binned coupling matrix:
        \begin{equation}
          \mathcal{M}_{kk'}\equiv\sum_{\ell\in\vec{\ell}_k}\sum_{\ell'\in\vec{\ell}_{k'}}w_\ell{\sf M}_{\ell\ell'}.
        \end{equation}
        When auto-correlating a field with noise, it is in general also desirable to remove the noise bias on the power spectrum. This has been included in Eq. \ref{eq:master_full} above as $\tilde{C}^{\rm noise}_\ell$. This should be the pseudo-$C_\ell$ of the noise component (i.e. the angular power spectrum of masked noise realizations), which can be computed from Monte-Carlo simulations (or analytically for sufficiently simple noise models).
\end{enumerate}
In NaMaster, these computations are carried out through a C structure called {\tt nmt\_workspace}. The relevant functions are described below. Once the pseudo-$C_\ell$ coupling matrix corresponding to two fields has been computed and stored in an {\tt nmt\_workspace}, the same workspace can be re-used to compute the pseudo-$C_\ell$ of any pair of fields as long as they have the same polarizations, masks and choices for $E$ and $B$ purification as the original fields.

Note that the input and output power spectra are given as 2D arrays. The first dimension runs through $N_{\rm spec}$, the number of different cross-spectra:
\begin{enumerate}
 \item For two spin-0 fields $f_1$ and $f_2$, $N_{\rm spec}=1$: $C_\ell=\left(C^{f_1f_2}_\ell\right)$.
 \item For a spin-0 field $f_1$ and a spin-2 field $f_2$, $N_{\rm spec}=2$: $C_\ell=\left(C^{f_1f_2^E}_\ell,C^{f_1f_2^B}_\ell\right)$, where $f_2^{E,B}$ are the $E$ and $B$-modes of $f_2$.
 \item For two spin-2 fields $f_1$ and $f_2$, $N_{\rm spec}=4$: $C_\ell=\left(C^{f_1^Ef_2^E}_\ell,C^{f_1^Ef_2^B}_\ell,C^{f_1^Bf_2^E}_\ell,C^{f_1^Bf_2^B}_\ell\right)$, where $f_x^{E,B}$ are the $E$ and $B$-modes of $f_x$.
\end{enumerate}
The second dimension runs through the different multipole indices or bandpowers. For power spectra, before binning into bandpowers, this index runs from 0 to $\ell_{\rm max}=3\,{\tt nside}-1$, where {\tt nside} is the HEALPix resolution of the fields. For bandpowers, this index runs through the number of different bandpowers defined by the associated {\tt nmt\_binning\_scale} structure.

\begin{funcdef}[nmt\_compute\_coupling\_matrix]
{\functi{nmt\_workspace *}{nmt\_compute\_coupling\_matrix}{\vari{nmt\_field *}{fl1},\vari{nmt\_field *}{fl2},\\\vari{nmt\_binning\_scheme *}{bin}}}
 Computes the coupling matrix and the binned coupling matrix for the two fields {\tt fl1} and {\tt fl2} and the binning scheme {\tt bin}. Note that the only information needed from the two fields is their masks and spins. These matrices are stored internally in the {\tt nmt\_workspace} structure returned by this function.
\end{funcdef}

\begin{funcdef}[nmt\_workspace\_write]
{\functi{void}{nmt\_workspace\_write}{\vari{nmt\_workspace *}{w},\vari{char *}{fname}}}
 Writes an {\tt nmt\_workspace} structure into a file {\tt fname} (using an internal binary format).
\end{funcdef}

\begin{funcdef}[nmt\_workspace\_read]
{\functi{nmt\_workspace *}{nmt\_workspace\_read}{\vari{char *}{fname}}}
 Returns a pointer to a {\tt nmt\_workspace} structured read from file {\tt fname}. This file should have been generated by {\tt nmt\_workspace\_write}. These two functions are useful when computing the power spectrum of several pairs of fields with the same pairs of masks, for which the coupling matrices only need to be computed once.
\end{funcdef}

\begin{funcdef}[nmt\_workspace\_free]
{\functi{void}{nmt\_workspace\_free}{\vari{nmt\_workspace *}{w}}}
 Frees up all memory associated with an {\tt nmt\_workspace} structure.
\end{funcdef}

\begin{funcdef}[nmt\_compute\_deprojection\_bias]
{\functi{void}{nmt\_compute\_deprojection\_bias}{\vari{nmt\_field *}{fl1},\vari{nmt\_field *}{fl2},\\\vari{double **}{cl\_proposal},\vari{double **}{cl\_bias}}}
 Estimates the bias to the cross-power spectrum of two fields {\tt fl1} and {\tt fl2} induced by the contaminant cleaning (i.e. $C^{\rm cont}_\ell$ in Eq. \ref{eq:master_full}). This is returned into the variable {\tt cl\_bias}, which should have been previously allocated (see description in the introduction to this section). The estimate of this bias depends on a guess for the true power spectrum of both fields, given by {\tt cl\_proposal}\footnote{Thus, the pseudo-$C_\ell$ can be thought of as a recursive algorithm, where the estimate of the true power spectrum in a previous iteration is used as a proposal for the computation of the contaminant bias in the next one.}. Note that this operation does not require knowledge of the mode-coupling matrix, and therefore no {\tt nmt\_workspace} structure is needed.
\end{funcdef}

\begin{funcdef}[nmt\_compute\_coupled\_cell]
{\functi{void}{nmt\_compute\_coupled\_cell}{\vari{nmt\_field *}{fl1},\vari{nmt\_field *}{fl2},\vari{double **}{cl\_out},\vari{int }{iter}}}
 This computes the full-sky angular cross-power spectrum of two masked fields {\tt fl1} and {\tt fl2} without aiming to deconvolve the mode-coupling matrix. Effectively, this is equivalent as calling the usual HEALPix {\tt anafast} routine on the masked and contaminant-cleaned maps. The coupled power spectrum is returned in {\tt cl\_out}, which should have been previously allocated (see description in the introduction to this section). The variable {\tt iter} corresponds to the number of iterations used to compute the spherical harmonic transform. A value of 0 will correspond to the fastest but most inaccurate computation. Higher values will yield more accurate results at high-$\ell$ (${\tt niter}=3$ is usually enough in most cases).
 
 Since no attempt is made to deconvolve the mode-coupling matrix, this function does not require a {\tt nmt\_workspace} structure.
\end{funcdef}

\begin{funcdef}[nmt\_decouple\_cl\_l]
{\functi{void}{nmt\_decouple\_cl\_l}{\vari{nmt\_workspace *w},\vari{double **}{cl\_in},\vari{double **}{cl\_noise\_in},\\\vari{double **}{cl\_bias},\vari{double **}{cl\_out}}}
 This function performs the operation in Eq. \ref{eq:master_full}: debiasing and decoupling of a power spectrum computed from {\tt nmt\_compute\_coupled\_cell}. The coupled power spectrum $\tilde{C}_\ell^{\rm clean}$ must be provided in {\tt cl\_in}. The contaminant bias $\tilde{C}_\ell^{\rm cont}$ (e.g. computed through {\tt nmt\_compute\_deprojection\_bias}) and noise bias $\tilde{C}_\ell^{\rm noise}$ must be provided through {\tt cl\_bias} and {\tt cl\_noise\_in} respectively. The mode-coupling matrix ${\sf M}$ (and its binned version $\mathcal{M}$) are stored within {\tt w}, and the de-coupled bandpowers are returned in {\tt cl\_out}.
\end{funcdef}

\begin{funcdef}[nmt\_compute\_power\_spectra]
{\functi{nmt\_workspace *}{nmt\_compute\_power\_spectra}{\vari{nmt\_field *}{fl1},\vari{nmt\_field *}{fl2},\\\vari{nmt\_binning\_scheme *}{bin},\vari{nmt\_workspace *}{w0},\vari{double **}{cl\_noise},\vari{double **}{cl\_proposal},\\\vari{double **}{cl\_out}}}
 Carries out steps 2-5 of the pseudo-$C_\ell$ estimator described in the introduction of this section.
 {\tt fl1} and {\tt fl2} are the two fields to correlate, {\tt bin} defines the output bandpowers, {\tt cl\_noise} is the noise bias, {\tt cl\_proposal} is the best guess for the true power spectrum needed to estimate the contaminant bias $\tilde{C}^{\rm cont}_\ell$ (see {\tt nmt\_compute\_deprojection\_bias}). The output bandpowers are stored in {\tt cl\_out}, which should have been pre-allocated.
 
 This function also accepts an input pointer to a {\tt nmt\_workspace} structure, {\tt w0}. If a {\tt NULL} pointer is passed, the function will compute the mode-coupling matrix and return a newly-allocated {\tt nmt\_workspace} structure containing this information. Otherwise, the function will skip this computation and use the mode-coupling matrix stored in {\tt w0}. In this latter case, the function would return a pointer to {\tt w0}. Note that a call to this function is equivalent to a successive call to {\tt nmt\_compute\_coupling\_matrix}, {\tt nmt\_compute\_deprojection\_bias}, {\tt nmt\_compute\_coupled\_cell} and {\tt nmt\_decouple\_cl\_l}.
\end{funcdef}

\begin{funcdef}[nmt\_couple\_cl\_l]
{\functi{void}{nmt\_couple\_cl\_l}{\vari{nmt\_workspace *}{w},\vari{double **}{cl\_in},\vari{double **}{cl\_out}}}
 Convolves an input power spectrum {\tt cl\_in} with the mode-coupling matrix stored in {\tt w}, and provides the output in {\tt cl\_out}. I.e.:
 \begin{equation}
   C^{\rm out}_\ell=\sum_{\ell'}{\sf M}_{\ell\ell'}C^{\rm in}_{\ell'}
 \end{equation}
 where $C^{\rm out}_\ell\rightarrow{\tt cl\_out}$ and $C^{\rm in}_\ell\rightarrow{\tt cl\_in}$.
\end{funcdef}

\subsection{Utility functions}
\begin{funcdef}[nmt\_apodize\_mask]
{\functi{void}{nmt\_apodize\_mask}{\vari{long }{nside},\vari{double *}{mask\_in},\vari{double *}{mask\_out},\vari{double }{aposize},\\\vari{char *}{apotype}}}
 This function apodizes an input mask, provided in {\tt mask\_in} as a HEALPix map, and stores the result in {\tt mask\_out}. The apodization is defined by an apodization scale {\tt aposize} (in degrees) and an apodization type {\tt apotype}. Three different apodization types are supported (in what follows $\theta_*$ will be the apodization scale {\tt aposize}):
 \begin{itemize}
  \item {\bf {\tt apotype}$=$``C1''}. All pixels are multiplied by a factor $f$ given by:
  \begin{equation}
    f=\left\{\begin{array}{cc}
              x-\sin(2\pi x)/(2\pi) & x<1\\
              1                     & {\rm otherwise}
             \end{array}\right.
  \end{equation}
  where $x\equiv\sqrt{(1-\cos\theta)/(1-\cos\theta_*)}$, and $\theta$ is the angular separation between the pixel and its closest masked pixel (i.e. the closest pixel where the mask is zero.
  \item {\bf {\tt apotype}$=$``C2''}. All pixels are multiplied by a factor $f$ given by:
  \begin{equation}
    f=\left\{\begin{array}{cc}
              \frac{1}{2}\left[1-\cos(\pi\,x)\right] & x<1\\
              1                     & {\rm otherwise}
             \end{array}\right.
  \end{equation}
  where $x\equiv\sqrt{(1-\cos\theta)/(1-\cos\theta_*)}$, and $\theta$ is the angular separation between the pixel and its closest masked pixel (i.e. the closest pixel where the mask is zero.
  \item {\bf {\tt apotype}$=$``Smooth''}. This apodization is carried out in three steps:
    \begin{enumerate}
      \item All pixels within a disc of radius $2.5\theta_*$ of a masked pixel (i.e. where the mask is zero) are masked.
      \item The resulting map is smoothed with a Gaussian window function with standard deviation $\sigma=\theta_*$.
      \item One final pass is made through all pixels to ensure that all pixels that were originally masked remain masked after the smoothing operation.
    \end{enumerate}
 \end{itemize}
\end{funcdef}

\newpage
\section{Sample program}\label{sec:sample}

Here's a simple code using the NaMaster library. This code takes, as command-line options, filenames for two FITS files containing HEALPix maps for a spin-0 field and a mask, and writes the MASTER estimate of its power spectrum into an ASCII file. This file can be found in {\tt test/sample.c}, and can be compiled as described in Section \ref{ssec:compile}.

\lstinputlisting[language=C]{../test/sample.c}

\end{document}
