
\documentclass[numbers=noenddot]{aux/fcmanual}

\usepackage{lmodern}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}

\usepackage{xcolor}
\usepackage{listings}
\usepackage{hyperref}
\usepackage{units}
\usepackage{xspace}
\usepackage{natbib}
\usepackage{stmaryrd}

\usepackage{chemformula}
\let\ce\ch

\author{Daniel Kitzmann\\
	    Joachim Stock
}

\title{FastChem 2.1}
\subtitle{User and Reference Guide}
\date{}


\newcommand{\fc}{\texttt{FastChem}\xspace}
\newcommand{\pfc}{\texttt{pyFastChem}\xspace}
\newcommand{\cpp}{\ttt{C++}\xspace}
\newcommand{\pb}{\texttt{PyBind11}\xspace}


\newcommand{\ttt}[1]{\texttt {#1}}

\lstloadlanguages{bash, C++, Python}

\lstset{basicstyle=\ttfamily\footnotesize,
  showstringspaces=false,
  breaklines=false,
  commentstyle=\color{red},
  keywordstyle=\color{blue}
}

\lstdefinestyle{customc}{
	belowcaptionskip=1\baselineskip,
	breaklines=false,
	frame=L,
	leftmargin=\parindent,
	language=C++,
	showstringspaces=false,
	basicstyle=\footnotesize\ttfamily,
	keywordstyle=\bfseries\color{green!40!black},
	commentstyle=\itshape\color{purple!40!black},
	identifierstyle=\color{blue},
	stringstyle=\color{orange}
}

\lstset{language=C++}


\setlength\parindent{0pt}



\begin{document}


\maketitle


\tableofcontents

\chapter{Introduction to FastChem}

\section{Overview}

\fc is an open-source computer program that can calculate the gas phase chemical equilibrium composition of general systems for a given temperature pressure and element abundances.


equilibrium chemistry model that can calculate the gas phase chemical composition of general systems. It uses a semi-analytical approach to solve the non-linear system of mass action law equations, which results in a massive increase in computational performance over other approaches like Gibbs minimisation. The general concept and the original version 1.0 is described by \citet{Stock2018MNRAS.479..865S} (Paper I). Version 1.0, however, is restricted to systems that are dominated by hydrogen and helium and required an additional iteration to account for the pressure of the system. The current version 2.0 can now be applied to arbitrary element compositions. This version will be described by \citet{Stock2020inprep}, from here on referred to as Paper II.

\fc has already been applied to numerous different systems, from brown dwarfs \citep{Kitzmann2020ApJ...890..174K}, to mini-Neptunes, hot-Jupiters \citep{Bourrier2020A&A...637A..36B}, to ultra-hot Jupiters \citep{Hoeijmakers2019A&A...627A.165H}. It is directly coupled to the retrieval model \ttt{Helios-r2} \citep{Kitzmann2020ApJ...890..174K}, to the general atmospheric model \ttt{HELIOS} \citep{Malik2019AJ....157..170M}, and the non-equilibrium chemistry \ttt{VULCAN} \citep{Tsai2018ApJ...862...31T}, all of which are available under \url{https://github.com/exoclime}.


%\section{Developers}
%
%The current version of \fc has been developed and written by
%\begin{itemize}
%  \item[] Daniel Kitzmann %(daniel.kitzmann@csh.unibe.ch)
%  \item[] Joachim Stock
%\end{itemize}



\section{Licence}

\fc is released under the GNU Public Licence (GPL) 3.0. That means, it can be freely copied, edited, and re-distributed. If the code is re-distributed it has to be released under at least a GPL 3.0 licence as well. The full licence of \fc can be found in the repository (\ttt{LICENSE} file) or under \url{https://www.gnu.org/licenses/gpl-3.0.html}.

This user guide is released under the Creative Commons Licence (CC BY SA). Licensees may copy and distribute the work and make derivative works based on it only if they give the authors the credits by providing a reference to the original guide and the corresponding GitHub repository. Licensees may also distribute derivative works only under a license identical to ("not more restrictive than") the license that governs the original work.

The \fc repository also links to an additional open source code, the \pb library (\url{https://github.com/pybind/pybind11}) that converts \cpp code into a module callable from Python.
This library is licensed under the BSD licence, see \url{https://github.com/pybind/pybind11/blob/master/LICENSE} for details.

\newpage

\section{About this guide}

This guide provides basic information on the \fc code and how to use it. It is structured into three different parts:

\begin{itemize}
  \item Part \ref{part:install} contains the basic descriptions on how to obtain and compile \fc and its Python module \pfc.

  \item Part \ref{part:running} describes on how to run \fc as a stand-alone application as well as through its Python interface \pfc.

  \item Part \ref{part:code_details} is a more in-depth description of the code itself. It provides information on the interface methods and variables used by \fc and \pfc.
\end{itemize}



\part{Installation of \fc and \pfc}
\label{part:install}

\chapter{Installation}

\fc can be installed in two different ways: either using \ttt{CMake} or by calling a Python setup function \verb|setup.py|. The former will install the \ttt{C++} stand-alone executable and optionally the Python module, while the latter one will only provide the \pfc Python module. The Python module created by \ttt{CMake} will only be available locally in the \ttt{python} directory, while the one produced by \verb|setup.py| will be integrated in your standard Python library and, thus, work as a normal Python package. Additionally, we also support a Python installation via \verb|PyPI|, the Python Package Index.


\section{Obtaining the code}

\fc is hosted on the Exoclime GitHub page: \url{https://github.com/exoclime/fastchem}. If \texttt{git} is available on a computer, the repository can be simply cloned with

\begin{lstlisting}[language=bash]
git clone https://github.com/exoclime/fastchem
\end{lstlisting}

\section{Prerequisites}

\fc is written in \ttt{C++}. It uses features of the \ttt{C++11} standard and, therefore, requires a compiler that implements this standard. We also provide an optional Python interface, allowing \fc to be called directly from within a Python script. The interface is based on the Python package \pb.

\subsection{Prerequisites for installation via \ttt{CMake}}
The complete list of prerequisites for a basic \ttt{CMake} installation is:
\begin{itemize}
	\item a \ttt{C++} compiler (e.g. \ttt{g++} or \ttt{Clang} on MacOS)
	\item \ttt{CMake}, at least version 3.10
\end{itemize}

The \ttt{C++} compiler will be detected by the CMake script when it generates the makefiles. For some of its optional components \fc will need:
\begin{itemize}
	\item an \ttt{OpenMP} library (to run \fc in parallel)
	\item a Python 3.x interpreter (for the Python interface)
\end{itemize}


\subsection{Prerequisites for Python installation via \ttt{setup.py} or \ttt{PyPi} }
An installation of \pfc with the \verb|setup.py| script or\verb|PyPI| requires
\begin{itemize}
	\item a Python 3.x interpreter
	\item a \ttt{C++} compiler (e.g. \ttt{g++} or \ttt{Clang} on MacOS)
	\item an \ttt{OpenMP} library (optional, required to run \fc in parallel)
	\item pip (when using \verb|PyPI|)
\end{itemize}
as well as the following Python modules:
\begin{itemize}
	\item PyBind11 
	\item setuptools
	\item distutils
	\item glob
	\item tempfile
\end{itemize}


\subsection{Supported \ttt{C++} compilers}

The compilation of \fc has been tested on a variety of different compilers and platforms. In particular, it was verified that \fc can be compiled with:
\begin{itemize}
	\item GCC 7.5 or newer
	\item Clang 12.0 (including Apple's Clang 12.0)
\end{itemize}

Since \fc just uses plain \cpp without any external library, any compiler that supports the \ttt{C++11} standard should be able to compile the code successfully.


\subsection{PyBind11 Library}

For its Python interface, \fc requires the \pb library that translates the Python calls into \cpp. While \pb can in theory be installed via \texttt{pip}, \texttt{conda}, or \texttt{brew} (on MacOS), \texttt{CMake} isn't always able to properly locate the installed library. 

For the installation via \texttt{CMake}, we therefore chose to include \pb as a submodule in the \fc repository. \texttt{CMake} will take header files and Python scripts provided by the submodule to create the \texttt{PyFastChem} module. No separate compilation or installation of \pb is required. During the setup stage, \texttt{CMake} will download the \pb library automatically. This code will be placed into a separate \texttt{\_deps} folder.

If you choose to install \pfc via the \verb|setup.py| function, then the \pb library has to already present in your local Python installation.


\section{Configuration and compilation of \fc with CMake}
\label{sec:install_config}

Before \fc can be compiled, \texttt{CMake} is required to configure the compilation files, locate libraries, and write the makefiles that will perform the actual compilations. If required libraries are missing, \texttt{CMake} will report a corresponding error message. In this case, the missing libraries or compilers need to be installed before the configuration can be completed.\\

To run the \ttt{CMake} configuration, first create the \texttt{build} folder inside the \fc source code folder and switch to the folder:
\begin{lstlisting}[language=bash]
  mkdir build
  cd build
\end{lstlisting}
For a basic installation, within the folder run \texttt{CMake}\footnote{Remember the .. after the \texttt{cmake} command}:
\begin{lstlisting}[language=bash]
  cmake ..
\end{lstlisting}

If the Python interface should be installed as well, run
\begin{lstlisting}[language=bash]
  cmake -DUSE_PYTHON=ON ..
\end{lstlisting}

\texttt{CMake} will also try to locate an \texttt{OpenMP} library to allow \fc to be run in parallel. If it cannot detect the library, only the single-core version of \fc will be compiled. If \fc is to be run on MacOS, using \texttt{OpenMP} might be difficult since Apple's \texttt{Clang} compiler does not directly support \texttt{OpenMP}, even if the corresponding library has been installed. It might be possible, though, to install an alternative compiler, for example \texttt{g++}, that supports the use of \texttt{OpenMP}. 

After \texttt{CMake} successfully configured the compilation files, \fc can be compiled by running:
\begin{lstlisting}[language=bash]
  make
\end{lstlisting}
Upon successful compilation, the executable \texttt{fastchem} should be present in the main \fc folder. If the optional Python interface is used, \fc will be automatically compiled twice because the Python version requires different compiler options.


\subsection{Notes on MacOS}

\fc can be compiled and run on MacOS, but requires some libraries and apps that are not installed by default. This especially includes \texttt{CMake}. In order to compile \fc on MacOS, the the prerequisites listed above need to be installed. This can be easily achieved by, for example, using \texttt{brew}. 

In a standard installation of MacOS, no compiler is available. The Apple version of the Clang compiler can be installed through Xcode and the command line tools by running
\begin{lstlisting}[language=bash]
  xcode-select --install
\end{lstlisting}
in the terminal.

Alternatives (e.g. \texttt{g++}) to the default Clang shipped with MacOS can also be installed via \texttt{brew}. However, \texttt{CMake} is not always able to detect these compilers and will still use Clang. This also applies to the optional \ttt{OpenMP} library that allows \fc to be run in parallel. The Clang compiler does not directly support the library, even if it has been installed via \texttt{brew}.

If the Python interface of \fc is used, a corresponding Python 3 installation is also required. By default, MacOS ships only with an outdated Python 2 version that cannot be used for \fc. A more up-to-date version can also be installed by, for example, \texttt{brew}. However, one has to make sure that the \texttt{python3} executable and things like \texttt{pip3} (to install other required Python modules) actually link to that version. An alternative way to install and manage different versions of Python without interference from MacOS' internal Python version is \texttt{pyenv}, which can be found under \url{https://github.com/pyenv/pyenv}. 


\subsection{Notes on Windows}

While in theory \fc could be run on Windows if meeting all the prerequisites, we have never tested the compilation and execution of \fc on such a system. In principle, this should be possible under a virtual Linux environment, such as \texttt{cygwin}, or with the Windows Subsystem for Linux (WSL) shipped with the newer versions of Windows 10. However, due to the lack of a Windows system, we are unable to test this and, therefore, officially at least we cannot support \fc running on Windows.


\section{Installation of \pfc with Python}
\label{sec:install_python}

When setting up \pfc with \verb|PyPI|, it is installed via \verb|pip|:
\begin{lstlisting}[language=bash]
  pip install pyfastchem
\end{lstlisting}
Depending on the Python installation, \verb|pip| might need to be replaced by \verb|pip3| in case \verb|pip| is linked to Python 2.x.

This command will download and compile the \pfc package and resolve potential dependencies. It is important to note, though, that one still has to download the chemistry input data and other Python scripts from the \fc repository in order to use the package properly.\\

As an alternative, \pfc can also be directly installed from source via the \verb|setup.py| script located in the root directory of \fc. The setup is started by
\begin{lstlisting}[language=bash]
  python setup.py install
\end{lstlisting}
assuming that \verb|python| points to your Python 3.x executable. Otherwise, replace \verb|python| with \verb|python3|. As discussed above, using \verb|setup.py| will only create the Python module of \fc, not the stand-alone executable.\\

In both cases, the \pfc module itself will be installed in your local Python package library path and, thus, be available throughout your system like any other normal Python package. The module's location and additional module information can be obtained via
\begin{lstlisting}[language=bash]
  pip show pyfastchem
\end{lstlisting}


The setup script will also try to detect the presence of compiler support for \texttt{OpenMP} to run \fc calculations in parallel. This is currently likely to fail in case of MacOS since Apple's Clang compiler officially does not support this library. We might adapt the \verb|setup.py| script in the future to allow for alternative compilers under MacOS.



\part{Running \fc and \pfc}
\label{part:running}

In this part, we describe how \fc can be run directly via the included \cpp stand-alone version or via Python scripts. In chapter \ref{sec:fastchem_input_files}, we also describe the format of the input files with the thermochemical and element abundance data. A complete overview of all available functions and output from the \fc code can be found in part \ref{part:code_details} for both, the \cpp object class and its Python interface.

\chapter{Standard FastChem input and output files}
\label{sec:fastchem_input_files}

Besides optional other parameter files that are used within the \cpp stand-alone version or the Python version, \fc requires two special input files, one for the element abundances and a second describing the mass action law constant parametrisations. Both are described in the following.

\section{Element abundance file}

This file should contain the element abundances for all chemical elements that are used in \fc. The location of this file is usually supplied either within a separate parameter file or directly in the constructor of the \fc object class.

\paragraph{A note on element abundances}
It is important to note that there are two different ways to define an element abundance. Both variants, denoted by $x_j$ and $\epsilon_j$, are related via:
\begin{equation}
\epsilon_j = 10^{x_j - 12}
\end{equation}
or
\begin{equation}
 x_j = \log\left(\epsilon_j\right) + 12 \ .
\end{equation}
In the $x_i$ version, widely used in the astronomical literature, hydrogen has a value of 12 for solar element abundances, such that its $\epsilon_i$ is unity. 

In its input file, \fc uses the $x_j$ notation, also employed in the usual standard abundance compilations (e.g. \citet{Asplund2009ARA&A..47..481A}). For example, in the $x_j$ notation, the solar element abundance for oxygen is $x_\mathrm{O}$ = 8.69, whereas its value for $\epsilon_\mathrm{O}$ would be $0.00048978$.\\

Internally, \fc converts the $x_j$ from the input file to the computationally more appropriate $\epsilon_j$. This also refers to all methods of the \fc object class that are used to interact with the element abundances: these will \textbf{always} refer to $\epsilon_j$. 

Thus, if one wants to change the oxygen element abundance in the input file (which refers to $x_j$) to ten times its solar value, one would need to use a value of $x_\mathrm{O}$ = 1 + 8.69 = 9.69. If one, on the other hand, uses one of the internal \fc methods to change element abundances on the fly, one would need to set it to a value of $\epsilon_\mathrm{O} = 10 \cdot 0.00048978 =  0.0048978$.

\newpage
\paragraph{File structure}
The element abundance file should have the following structure to be readable by \fc:
\lstinputlisting[basicstyle=\ttfamily\scriptsize, language={}, frame=single]{aux/element_abundances_solar.dat}

The first line is always a header line that provides important information for the user and is ignored by \fc. All subsequent lines contain each the symbol for an element and its element abundance. Molecules that contain elements not present in this file are ignored. The element abundance for  the electron has an arbitrary value. It is only present in the file to inform \fc that the electrons (and thus ions) should be included in the chemistry calculations. Its element abundance $\epsilon_e$ will internally be set to 0 because its number density is determined by charge balance. The elements are not required to be in any particular order. 


\paragraph{Standard files}
Together with \fc, we provide two different element abundance files, located in the \verb|input/| folder. The file \verb|element_abundances_solar.dat| provides the solar element abundances for species that are at least as abundant as germanium. This set of element abundances is used as our standard input file and is based on \citet{Asplund2009ARA&A..47..481A}.\\
As an alternative version, we also also include an additional file \verb|element_abundances_solar_ext.dat| that includes more elements, up to uranium. This file can be used for the extended set of ion species described in the next section. These element abundances are also based on the \citet{Asplund2009ARA&A..47..481A} compilation.


\section{Species file}

Another important input is the thermochemical data for all molecules and ions. This includes in particular their stoichiometric information as well as a parametrisation for their mass action constants. As described in the first \fc publication \citep{Stock2018MNRAS.479..865S}, we use the natural logarithm of the dimensionless mass action constant of species $i$
\begin{equation}
\ln\bar{K}_i(T) = - \frac{\Delta_\mathrm{r} G_i^\minuso(T)}{R\,T} \ ,
\label{eq:lnK}
\end{equation}
where $G_i^\minuso(T)$ is the Gibbs free energy of dissociation. 
For \fc, these mass action constants are fitted with the expression
\begin{equation}
\ln\bar{K}_i(T) = \frac{a_0}{T} + a_1\,\ln T + b_0 + b_1\,T + b_2\,T^2 \ ,
\label{eq:fit}
\end{equation}
where $a_0$, $a_1$, $b_0$, $b_1$, and $b_2$ are the fit coefficients.\\
It is in principle possible to use your own parametrisation. For that, you need to edit the source code that performs the calculation of the mass action constants, located in the source file \verb|mass_action_constant.cpp|.

\paragraph{File structure}
For \fc, the species information file should have the following structure:
\lstinputlisting[basicstyle=\ttfamily\scriptsize, language={}, frame=single]{aux/logK_sample.dat}
The first three lines of the file are treated as header lines and discarded when reading in the file. \\

The data for each species consists of two lines, while different species are separated by a blank line.
The first line starts with the species' sum formula. In the standard \fc files, we use the modified Hill notation for the formulas. Isomeric species would in principle have the same formula in the Hill notation. For example, the two species \ce{HCN} and \ce{HNC} would both be referred to as \texttt{C1H1N1}. To distinguish the two in the standard set of \fc, underscores are used, such that \texttt{C1H1N1\_1} refers to \ce{HCN}, while \texttt{C1H1N1\_2} represents \ce{HNC}.
The use of the Hill notation is not a requirement. In a custom version of the species file, a different chemical notation could be used.\\

The sum formula is followed by an optional name for the species. This name should be contained within a single string. Thus, if the species name is a compound noun, the separating white spaces should be replaced by other characters, for example underscores $\_$ as shown above (e.g. \verb|Aluminum_Chloride| instead of \verb|Aluminum Chloride|). \\

After a seperator \verb|:|, \fc expects the stoichiometric information of the species, i.e. the elements and their stoichiometric coefficients. The elements need to be present in the element abundance file as well, otherwise the species will be discarded. They don't need to be in any specific order.\\
The stoichiometric information is followed by an optional reference for the data. If a reference is used, a separator \verb|#| is required between the stoichiometry and the reference.\\

The second line contains the fit coefficients for the mass action constants. \fc will read in as many coefficients as it can find in that line but for its own parametrisation in Eq. \eqref{eq:fit} it will only use the first five.

\paragraph{Standard files}
Together with \fc, we provide two different species files, located in the \verb|input/| folder. The file \verb|logK.dat| provides the standard set, discussed in \citet{Stock2018MNRAS.479..865S}. This includes species for all elements at least as abundant as germanium.

As an alternative version, we also provide an additional file \verb|logK_ext.dat| that includes more ions for elements up to uranium. The data for this file is discussed in \citet{Hoeijmakers2019A&A...627A.165H}.

\newpage
\section{Basic element data file (optional)}
In addition to the element abundances, \fc also needs to have additional basic data for the elements, such as their atomic weight to calculate the molecular weights of molecules, for example. For most elements up to uranium, this data is hard-coded in a standard set located in the header file \verb|chemical_element_data.h|. If you want to change this standard set by removing or adding elements or add isotopes, you can change it directly in the header file and re-compile \fc.\\
Alternatively, \fc also has the option to read an external file with the required information.

\paragraph{File structure}
The optional file has the following, simple structure, starting with a header line that is ignored when reading in the file:
\lstinputlisting[basicstyle=\ttfamily\scriptsize, language={}, frame=single]{aux/chemical_elements.dat}
It contains three columns, where the first one lists the elements' symbols, the second their names, and the third their atomic weights. An example of this file can be found in the folder \texttt{fastchem\_src/chem\_input/}.


\section{\fc parameter file (optional)}
\label{sec:fc_parameter_file}
\fc is able to load a specific parameter file when one of its instances is created through the object class constructor. This parameter file includes the most important parameters and options used within \fc. All of these quantities can also be changed during runtime by using the appropriate methods listed in Sect. \ref{sec:fastchem_methods} for the \cpp object class and Sect. \ref{sec:pfc_methods} for the Python module. Using the parameter file in principle allows changing these options and parameters outside of the code and, therefore, does not require the code to be recompiled.

\paragraph{File structure}
The optional parameter file has the following structure:
\lstinputlisting[basicstyle=\ttfamily\scriptsize, language={}, frame=single]{aux/parameters.dat}
The first two entries are the locations of the element abundance and species data files. The next parameter determines the convergence criterion of the chemistry iteration. This value is also used for the internal Newton's method. The latter one can be adjusted within in the code by the methods listed in Sects. \ref{sec:fastchem_methods} \& \ref{sec:pfc_methods}.

The next parameter sets the maximum numbers of iterations for the different internal numerical methods employed within \fc. This includes the Newton, Nelder-Mead, and bisection methods. Using the corresponding functions of the \fc object class (Sects. \ref{sec:fastchem_methods} \& \ref{sec:pfc_methods}), this number can be adjusted for each of these numerical methods individually. 
The last parameter is optional and does not need to be present in the file. It contains the path to the file for an alternative basic element data file. If this parameter is not present, \fc will use the standard set that is directly located in the \fc source code (see previous section).


\section{Output files}
\label{sec:fc_cpp_output}

The \cpp stand-alone version will produce two output files: a detailed chemistry output and a monitor file with diagnostic information. The file names of both files can be chosen in the config file discussed in the previous section.

\paragraph{Chemistry output} 
The chemistry output is organised in columns. The first line of the file is a header that describes the content of each column.

The first and second column contain the pressure in bar and the temperature in K, respectively. The third column lists the total number density of all atoms $i$, i.e. $n_\mathrm{tot} = \sum_i \left( n_i + \sum_j n_j \nu_{ij} \right)$, summed over their atomic number densities, as well as the ones contained in all other molecules/ions $j$. This is usually only a diagnostic quantity and rarely used in other applications. 

The fourth column is the number density of the gas in units of cm$^{-3}$, derived from the ideal gas law. This is followed by a column of mean molecular weights of the mixture of species in units of the unified atomic mass unit. For all practical purposes, this can also be converted into units of $\unit{g/mol}$.

All subsequent columns contain the number densities (in cm$^{-3}$) or the mixing ratios of all species, depending on the choice of output made in the config file. By default, elements will be placed in the beginning, followed by molecules and ions. Note that in its species data files, \fc employs the modified Hill notation as used in the JANAF thermochemical tables \citep{Chase1986jtt..book.....C} for the formulas of all non-element species. If, for example, you are looking for the abundance of carbon dioxide, you need to locate the \verb|C1O2| column rather than \verb|CO2|, whereas \verb|NH3| would be listed as \verb|H3N1|.

\paragraph{Monitor file} The monitor output file is a \textbf{very} important diagnostic output that provides crucial details on the outcome of the chemistry calculations. You should further investigate any chemistry calculations that shows problems in this file. It is, therefore, advisable to check this file after each calculation to verify that everything went fine. The first line of the file is a header that describes the content of each column.

The monitor output is organised in columns, where the first column contains a simple integer that refers to index of the input temperature-pressure structure. The second column lists the number of chemistry iterations that were required to solve the system. If the number corresponds to the maximum number of allowed iteration steps, then this points to potential convergence issues. 

The next columns contain information on the convergence of the chemistry and on the status of overall element conservation. If the chemistry did converge properly \verb|ok| will be listed as output, whereas \verb|fail| is used when the chemistry failed to converge in the maximum allowed number of steps. The same keywords are used for the element conservation status: \verb|ok| if all elements were conserved, \verb|fail| if any element was not conserved. 

The next four columns contain basic chemistry output, that is also found in the chemistry output file: the pressure, temperature, total element density, gas number density, and mean molecular weight.

All remaining columns list the status of the element conservation for each element separately. The same keywords as for the overall element conservation status are used again in these columns. For the electrons, this status refers to the charge balance rather than element conservation.




\chapter{The \fc \cpp stand-alone executable}

The \fc object class is designed to be easily coupled to other models. In addition to the object class itself, we also provide a stand-alone executable that can call the module with some simple input scripts. This stand-alone version, however, only provides a very basic functionality, such as reading in a specific temperature-pressure profile that \fc will be run for. The stand-alone version does, for example, not provide more advanced capabilities, such as looping over different metallicity values or C/O ratios. If you intend to use \fc for such purposes, you need to adapt the code that calls \fc.

The source code that is responsible for calling the actual \fc chemistry is located in the folder \verb|model_src/|. It is split across three different files: \verb|model_src/model_main.cpp|, the actual main program, \verb|model_src/read_config.h| for reading in the config file, and \verb|model_src/save_output.h| for managing the output. Thus, if you want to add another parameter to the config file, you would need to edit \verb|model_src/read_config.h|, while changes to the format of the output files can be made in \verb|model_src/save_output.h|. Changing the contents of these files obviously require a re-compilation of the code.


\section{Starting the \fc executable}

Following a successful configuration and compilation via \verb|CMake|, the \fc executable \verb|fastchem| should be present in the root directory. The executable is started via
\begin{lstlisting}[language=bash]
  ./fastchem input/config.input
\end{lstlisting}
where the second argument is the location of the config file that is explained in the next section. \fc will read in a pre-defined pressure-temperature structures, the location of which is also specified in the config file. After a successful calculation, \fc will produce two output files with a detailed chemistry output and one with diagnostic output. The location of these files is also contained in the config file and its contents are discussed in Sect. \ref{sec:fc_cpp_output}.


\section{Config file}

The config file that \fc will read in at the beginning contains all important parameters and file locations necessary to initialise the chemistry and to perform the calculations. The numerical methods that these parameters refer to are described in Paper II.
An example of such an input file is located in the input folder: \verb|input/config.input|. While this config file allows to set the most important \fc parameters, some more advanced ones are not contained in this file and can only be set by invoking special \fc functions during runtime. This, in particular, refers to the use of the optional scaling factors as described in the appendix of Paper II. More information on activating these scaling factors can be found in the description of the object class in Sect. \ref{sec:fastchem_methods}.\\

The config file used for the \cpp stand-alone executable has the following structure:
\lstinputlisting[basicstyle=\ttfamily\scriptsize, language={}, frame=single]{aux/config.input}

It contains the required parameters in the following order:
\begin{itemize}
  \item Location of the file with the pressure-temperature structure the chemistry should be calculated for. The file should contain two columns, where the first one is the pressure in units of bar and the second one the temperature in K. Header lines will be ignored.
  \item Desired location and file name for the chemistry output
  \item Desired location and file name for the diagnostic output
  \item Verbose level, where a level of \verb|1| is almost silent and \verb|4| produces a lot of diagnostic output on the terminal. Increase this level if you encounter issues to identify the source of the problems.
  \item The output format for the species' abundances. By default, \fc will use number densities in units of cm$^{-3}$. If you use the keyword \verb|MR|, mixing ratios will be used instead. Any keyword other than \verb|MR| will result in the default option of using number densities.
  \item Location of the file with the element abundances, see Sect. \ref{sec:fastchem_input_files} for details
  \item Location of the file with the thermochemical and stoichiometric data for all species, see Sect. \ref{sec:fastchem_input_files} for details 
  \item Relative accuracy of the chemistry iterations, used as convergence criterion (also for Newton's method)
  \item Maximum number of chemistry iterations
  \item Maximum number of internal solver method iterations (Newton, Nelder-Mead \& bisection methods)
\end{itemize}

In the input file, the number of iterations for the Newton, Nelder-Mead, and bisection methods are assumed to be the same. This number can be adjusted individually for each of these internal solvers by using the corresponding methods of the \fc object class listed in Sect. \ref{sec:fastchem_methods}. The convergence criterion for Newton's method is also set to the accuracy of the chemistry iteration by default. This convergence criterion can also be changed by the \lstinline!FastChem.setNewtonAccuracy! method (see Sect. \ref{sec:fastchem_methods}).


\section{Benchmark input and output files}

The input folder contains a selected sample of atmospheric structures of various objects, from AGB stars to exoplanets. These files have the same format as the one expected by the \cpp stand-alone version. The pre-computed chemistry output of these benchmark structures can be found in the folder \texttt{output\_benchmarks}. This chemistry output has been generated with the standard \fc options and the standard solar element abundance and equilibrium constants files. These benchmarks can be used to validate if the FastChem installation works correctly.


\chapter{Running \pfc}

In addition to the \cpp executable, we provide several Python scripts that can run the \fc code through its Python interface \pfc. The sample scripts can be found within the \verb|python/| folder. These sample scripts show different use cases and can be used as a basis for your own \fc Python scripts.

\section{Provided Python examples}
\label{sec:pyfc_examples}
Currently, we provide the following examples:\\

\lstinline!fastchem.py!
\begin{addmargin}[25pt]{0pt}
  Runs a simple \fc calculation on a temperature-pressure structure defined within the script, writes output files, and creates a plot with selected species.\\
\end{addmargin}

\lstinline!fastchem_c_o.py!
\begin{addmargin}[25pt]{0pt}
  Runs a \fc calculation on a temperature-pressure structure defined within the script and for a range of different C/O ratios. It will write output files, and create a plot with selected species.\\
\end{addmargin}

\lstinline!fastchem_metallicity.py!
\begin{addmargin}[25pt]{0pt}
  Runs a \fc calculation on a temperature-pressure structure defined within the script and for a range of different metallicity factors. It will write output files, and create a plot with selected species.\\
\end{addmargin}

Note that the scripts should be executed from within the \textsc{Python} folder since all file paths in the scripts are given relative to this directory.
These files can be used as templates to create your own special Python scripts to run \pfc. The following section provides some details on the steps required to run \fc from within Python. A more detailed overview of all the methods and variables available within \pfc can be found in Chapter \ref{sec:pyfc_details}.


\section{Detailed steps for running \fc with \pfc}

As a first step, we need to import the \pfc module:\\

\lstinline[language=Python]!import pyfastchem!\\

This will import the module compiled by \pb. Next, we have to create a \fc object (here named \lstinline[language=Python]!fastchem!) with the constructor \lstinline[language=Python]!pyfastchem.FastChem! provided by \pfc:\\

\lstinline[language=Python]!fastchem = pyfastchem.FastChem('input/element_abundances.dat', 'input/logK.dat', 1)!\\

The constructor requires three different arguments: the location of the element abundance file, the location of the file with the equilibrium constants, and the verbose level. Alternatively, a \fc object can also be created via\\

\lstinline[language=Python]!fastchem = pyfastchem.FastChem('input/parameters.dat', 1)!\\

where the first argument is the location of the parameter file and the second one the initial verbose level. The latter one will later be replaced by the corresponding value read in from the parameter file. The structure of this parameter file is discussed in Section \ref{sec:fc_parameter_file}.\\

Creating a \fc object with the first method will set internal parameters to their default values. The maximum number of chemistry iterations will be 1000, the number of Newton, bisection and Nelder-Mead method iterations is 3000, and the accuracy of the of Newton method and the chemistry iterations is set to $10^{-4}$. All of these values can, however, be adjusted during runtime by using the methods listed in Section \ref{sec:pfc_methods}.\\

Next, we need to create the input and output structures used by \pfc:\\

\lstinline[language=Python]!input_data = pyfastchem.FastChemInput()!\\
\lstinline[language=Python]!output_data = pyfastchem.FastChemOutput()!\\

Details on these structures can be found in Section \ref{sec:pfc_input_ouput_struct}. The input structure basically contains the temperature (in K) and pressure (in bar) arrays that the chemistry should be calculated for. They can be set, for example, by:\\

\lstinline[language=Python]!input_data.temperature = temperature!\\
\lstinline[language=Python]!input_data.pressure = pressure!\\

where \lstinline[language=Python]!temperature! and \lstinline[language=Python]!pressure! are standard Python lists or NumPy arrays. Both arrays need to have the same length.
With the input structure properly set up, we can now run the actual \fc calculation by calling the \lstinline[language=Python]!calcDensities! method:\\

\lstinline[language=Python]!fastchem_flag = fastchem.calcDensities(input_data, output_data)!\\

This method returns an integer flag that describes the overall outcome of the calculation. A description of the different flags can be found in Section \ref{sec:pfc_constants}. After calling the \lstinline[language=Python]!calcDensity! method, the output structure will be filled with the corresponding output data. For example, \\
\lstinline[language=Python]!output_data.number_densities!
will contain the number densities of the chemical species. This is a 2D list, where the first dimension refers to the temperature and pressure input arrays and the second dimension refers to the different chemical species. The list can be easily converted into a NumPy array via:\\

\lstinline[language=Python]!number_densities = np.array(output_data.number_densities)!\\

The Python directory of the \fc repository also contains functions that save the output into files, identical to those from the \cpp version. They can be called by:\\

\lstinline[language=Python, breaklines, breakatwhitespace]!saveChemistryOutput(output_dir + '/chemistry.dat', temperature, pressure, output_data.total_element_density, output_data.mean_molecular_weight,  output_data.number_densities, fastchem)!\\

\lstinline[language=Python, breaklines, breakatwhitespace]!saveMonitorOutput(output_dir + '/monitor.dat', temperature, pressure, output_data.element_conserved, output_data.fastchem_flag, output_data.nb_chemistry_iterations, output_data.total_element_density, output_data.mean_molecular_weight, fastchem)!\\

A more detailed description of the output functions can be found in the next section.


\section{Output functions of \pfc}

The Python directory includes several scripts that can save the \fc chemistry and monitor output in either text or binary data files. All these functions are located within the file \texttt{save\_output.py}. Examples of their usage can be found in the three Python scripts discussed above. \\

\subsection{Chemistry output scripts}

\texttt{save\_output.py} contains two functions for the general chemistry output. The first, \lstinline[language=Python]!saveChemistryOutput!, saves the results in a text file that is identical to the one of the \cpp version. If the chemistry is calculated for a larger number of pressure and temperature points, the output can become quite large. Saving these results into a simple text file can, therefore, take a very long time - in extreme cases even longer than the calculation itself.

Therefore, we provide an alternative function \lstinline[language=Python]!saveChemistryOutputPandas! that saves the output in a pandas \lstinline[language=Python]!DataFrame! format into a pickle file. Since this is a binary format, saving a large output is substantially faster than the corresponding ASCII text version.

The function for saving the output as a normal text file is\\

\lstinline[language=Python, breaklines, breakatwhitespace]!saveChemistryOutput(file_path, temperature, pressure, total_element_density, mean_molecular_weight, number_densities, fastchem, output_species=None, additional_columns=None, additional_columns_desc=None)!

\bigbreak

with the following arguments:

\bigbreak

\lstinline[language=Python]!file_path!
\begin{addmargin}[25pt]{0pt}
	Contains the path to the output file as a \lstinline[language=Python]!str! variable.
\end{addmargin}


\bigbreak

\lstinline[language=Python]!temperature, pressure!
\begin{addmargin}[25pt]{0pt}
	Arrays of \lstinline[language=Python]!float! values with the temperature and pressure structure the chemistry has been calculated for.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!total_element_density!
\begin{addmargin}[25pt]{0pt}
	\lstinline[language=Python]!float! array of the total number density of all atoms $i$, i.e. $n_\mathrm{tot} = \sum_i \left( n_i + \sum_j n_j \nu_{ij} \right)$, summed over their atomic number densities, as well as the ones contained in all other molecules/ions $j$. This quantity is usually only a diagnostic output and not relevant for other calculations. The dimension of the array is equal to that of the temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!mean_molecular_weight!
\begin{addmargin}[25pt]{0pt}
	\lstinline[language=Python]!float! array of the computed mean molecular weight. The dimension of the array is equal to that of the temperature and pressure vectors.
\end{addmargin}


\bigbreak

\lstinline[language=Python]!number_densities!
\begin{addmargin}[25pt]{0pt}
	Two-dimensional \lstinline[language=Python]!float! array of the number densities. The first dimension of the array refers to the temperature and pressure input arrays, while the second dimension describes the different chemical species.
\end{addmargin}


\bigbreak

\lstinline[language=Python]!fastchem!
\begin{addmargin}[25pt]{0pt}
	An object of the \pfc class that has been used to calculate the chemistry. 
\end{addmargin}


\bigbreak

\lstinline[language=Python]!output_species=None!
\begin{addmargin}[25pt]{0pt}
	Optional parameter. Is an array of \lstinline[language=Python]!str! values that contains the chemical symbols of species the chemistry output file should be saved for. Without this optional parameter, the output function will by default save all species. The symbols have to match the ones used in the \fc input file for the equilibrium constants. For the standard files supplied with \fc, the Hill notation, therefore, needs to be used here.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!additional_columns=None, additional_columns_desc=None!
\begin{addmargin}[25pt]{0pt}
	Optional parameters. Sometimes, \fc calculations are not iterated only over temperature or pressure but also other variables, such as the metallicity or C/O ratio. The output function therefore contains these optional parameters that allow to print additional columns in the output file. The first parameter \lstinline[language=Python]!additional_columns! is an $N\times N_\mathrm{tp}$-dimensional array of \lstinline[language=Python]!float! values, where the first dimension refers to the number of additional columns and the second dimension has to be equal to the dimensions of the temperature and pressure arrays. 
	
	The second optional parameter \lstinline[language=Python]!additional_columns_desc! contains an array of \lstinline[language=Python]!str! values with the header descriptions of the additional columns. The dimension has to be equal to number of additional columns. If this is not the case, or if the parameter is missing entirely, the columns will be labelled \texttt{unk} instead.
\end{addmargin}

\bigbreak

All of these function arguments, except for the optional parameters, are contained within the input and output structures of \pfc, discussed in Sect. \ref{sec:pfc_input_ouput_struct}\\

Saving the chemistry output with the panda \lstinline[language=Python]!DataFrame! format in a pickle file is possible via the function:

\bigbreak

\lstinline[language=Python, breaklines, breakatwhitespace]!saveChemistryOutputPandas(file_path, temperature, pressure, total_element_density, mean_molecular_weight, number_densities, fastchem, output_species=None, additional_columns=None, additional_columns_desc=None)!

\bigbreak

All arguments are identical to those of the previous ASCII output function. The saved panda DataFrame contains the same columns and headers as the simple text output.


\subsection{Monitor output scripts}

\texttt{save\_output.py} also contains two functions for the \fc monitor output. The first, \lstinline[language=Python]!savMonitorOutput!, saves the debug output in a text file that is identical to the one of the \cpp version. Just like for the chemistry output, saving the results for a large number of calculations can be quite slow. Therefore, we also provide an alternative function \lstinline[language=Python]!saveMonitorOutputPandas! that saves the output as a pandas \lstinline[language=Python]!DataFrame! format into a pickle file. 

The function for saving the output as a normal text file is\\

\lstinline[language=Python, breaklines, breakatwhitespace]!saveMonitorOutput(file_path, temperature, pressure, element_conserved, fastchem_flags, nb_chemistry_iterations, total_element_density, mean_molecular_weight, fastchem, additional_columns=None, additional_columns_desc=None)!

\bigbreak

with the following arguments:

\bigbreak

\lstinline[language=Python]!file_path!
\begin{addmargin}[25pt]{0pt}
	Contains the path to the output file as a \lstinline[language=Python]!str! variable.
\end{addmargin}


\bigbreak

\lstinline[language=Python]!temperature, pressure!
\begin{addmargin}[25pt]{0pt}
	Arrays of \lstinline[language=Python]!float! values with the temperature and pressure structure the chemistry has been calculated for.
\end{addmargin}

\bigbreak

\lstinline!element_conserved!
\begin{addmargin}[25pt]{0pt}
	The two-dimensional array of \lstinline[language=Python]!int! numbers contains information on the state of element conservation. A value of 0 indicates that element conservation is not fulfilled, whereas a value of 1 means that the element has been conserved. The first dimension refers to the temperature-pressure grid and has the same size as the temperature and pressure vectors of the input structure. The second dimension refers to the number of elements and has a length of \lstinline!getElementNumber()! (see Sect. \ref{sec:pfc_methods}).
\end{addmargin}

\bigbreak

\lstinline!fastchem_flag!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!int! numbers. Contains flags that give information on potential issues of the chemistry calculation for each temperature-pressure point. The set of potential values is stated in Sect. \ref{sec:pfc_constants}. A string message for each corresponding flag can also be obtained from the constant \lstinline!pyfastchem.FASTCHEM_MSG! vector of strings, via \lstinline!pyfastchem.FASTCHEM_MSG[flag]!. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!nb_chemistry_iterations!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!int! numbers. Contains the number of chemistry iterations that were required to solve the system for each temperature-pressure point. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!total_element_density!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!float! numbers that contains the total number density of all atoms $i$, i.e. $n_\mathrm{tot} = \sum_i \left( n_i + \sum_j n_j \nu_{ij} \right)$, summed over their atomic number densities, as well as the ones contained in all other molecules/ions $j$. This quantity is usually only a diagnostic output and not relevant for other calculations. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!mean_molecular_weight!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!float! numbers. Contains the mean molecular weight of the mixture in units of the unified atomic mass unit. For all practical purposes, this can also be converted into units of $\unit{g/mol}$. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!fastchem!
\begin{addmargin}[25pt]{0pt}
	An object of the \pfc class that has been used to calculate the chemistry. 
\end{addmargin}

\bigbreak

\lstinline[language=Python]!additional_columns=None, additional_columns_desc=None!
\begin{addmargin}[25pt]{0pt}
	Optional parameters. Sometimes, \fc calculations are not iterated only over temperature or pressure but also other variables, such as the metallicity or C/O ratio. The output function therefore contains these optional parameters that allow to print additional columns in the output file. The first parameter \lstinline[language=Python]!additional_columns! is an $N\times N_\mathrm{tp}$-dimensional array of \lstinline[language=Python]!float! values, where the first dimension refers to the number of additional columns and the second dimension has to be equal to the dimensions of the temperature and pressure arrays. 
	
	The second optional parameter \lstinline[language=Python]!additional_columns_desc! contains an array of \lstinline[language=Python]!str! values with the header descriptions of the additional columns. The dimension has to be equal to number of additional columns. If this is not the case, or if the parameter is missing entirely, the columns will be labelled \texttt{unk} instead.
\end{addmargin}

\bigbreak

The monitor output file has the same format as the one produced by the \cpp version discussed in Sect. \ref{sec:fc_cpp_output}. Saving the chemistry output with the panda \lstinline[language=Python]!DataFrame! format in a pickle file is possible via the function:

\bigbreak

\lstinline[language=Python, breaklines, breakatwhitespace]!saveMonitorOutputPandas(file_path, temperature, pressure, element_conserved, fastchem_flags, nb_chemistry_iterations, total_element_density, mean_molecular_weight, fastchem, additional_columns=None, additional_columns_desc=None)!

\bigbreak

All arguments are identical to those of the previous ASCII output function. The saved panda \lstinline[language=Python]!DataFrame! contains the same columns and headers as the simple text output. The only difference between the outputs is that for the \lstinline[language=Python]!DataFrame! format, the element conservation and \fc flags are not converted to strings (i.e. to \texttt{fail} or \texttt{ok}) but rather have their original integer values that are returned by \fc. Their values are discussed in Sect. \ref{sec:pfc_input_ouput_struct}  \& \ref{sec:pfc_constants}.




\part{Detailed \texttt{C++} object class and Python module description}
\label{part:code_details}


\chapter{FastChem class}
\label{sec:fc_class}

\fc has been written in an object oriented way, split across several different object classes. The entire source code of \fc is contained in the folder \verb|fastchem_src/|. For including \fc in another \cpp project, only adding the main fastchem header file \verb|fastchem.h| is required. All \fc code is encapsulated in its own namespace called \lstinline!fastchem! to avoid clashing with other libraries.


\section{Some comments on coding conventions}

The entire \fc code has been programmed using specific conventions that make it easy to recognise and differentiate class, method and variable names.

Class and structure names are always capitalised, for example

\bigbreak
\lstinline!  class FastChem{...!
\bigbreak
or
\bigbreak
\lstinline!  struct Molecule{...!
\bigbreak

If the name is a compound noun, each noun is capitalised separately, e.g.
\bigbreak
\lstinline!  struct ChemicalElementData{...!
\bigbreak
No separators like \_ are used for class or structure names.\\

Class methods and functions in general always start with a lowercase letter. If the name is a compound noun, the start of every other noun is capitalised and no separator is used, for example:
\bigbreak
\lstinline!  FastChem.setElementAbundances(...)!
\bigbreak
or
\bigbreak
\lstinline!  Molecule.calcMassActionConstant(...)!
\bigbreak

Variable names are always written in lowercase and compound nouns are separated by a \_. For example:
\bigbreak
\lstinline!  FastChem.element_calculation_order!
\bigbreak
or
\bigbreak
\lstinline!  Element.molecule_list!
\bigbreak
The only exceptions are global constants. They contain only capitalised letters, e.g.:
\bigbreak
\lstinline!  constexpr unsigned int FASTCHEM_UNKNOWN_SPECIES!
\bigbreak
or
\bigbreak
\lstinline!  constexpr double CONST_AMU!
\bigbreak


\section{\fc object class}

The entire \fc model is encapsulated in an object class called \fc that is defined in the header file \verb|fastchem.h|. The object class is programmed as a template that be used in either \verb|double| or \verb|long double| precision. When creating an object of this class by calling a corresponding constructor, one therefore has to specify which of the two versions should be used:
\bigbreak
\lstinline!  FastChem<long double> fastchem("model_parameter_file.dat", 1);!
\bigbreak
\lstinline!  FastChem<double> fastchem("model_parameter_file.dat", 1);!
\bigbreak
The \verb|long double| version has a slightly higher computational overhead and larger memory requirements than the \verb|double| one. On the other hand, it offers a higher numerical precision which is especially important when dealing with chemical systems where the mass action constants and number densities can vary by many orders of magnitudes. We strongly suggest to always use the \verb|long double| version despite the additional computational overhead. In fact, in our experience the increased numerical precision of \verb|long double| can effectively lead to a smaller number of iterations.


\section{FastChem constants}
\label{sec:fastchem_constants}

The \fc namespace \lstinline!fastchem! contains a number of constants that are all defined in the file \verb|fastchem_constants.h|.\\ This includes the constant \lstinline!constexpr unsigned int fastchem::FASTCHEM_UNKNOWN_SPECIES! that is returned by some \fc methods when a chemical species is not found. \\

The chemistry calculation will return several output flags that are also defined in this file. This includes the following constants:

\lstinline!constexpr unsigned int fastchem::FASTCHEM_SUCCESS!
\begin{addmargin}[25pt]{0pt}
  Indicates that the calculation has been successful, i.e. that the chemistry iterations converged.
\end{addmargin}

\bigbreak

\lstinline!constexpr unsigned int fastchem::FASTCHEM_NO_CONVERGENCE!
\begin{addmargin}[25pt]{0pt}
  Indicates that the calculation was not successful, i.e. that the chemistry did not converge within the allowed maximum number of iterations steps given in the config file or set manually via \lstinline!FastChem.setMaxChemistryIter! (see Sect. \ref{sec:fastchem_methods}). One way to solve such a problem is to increase the maximum number of iteration steps.
\end{addmargin}

\bigbreak

\lstinline!constexpr unsigned int fastchem::FASTCHEM_INITIALIZATION_FAILED!
\begin{addmargin}[25pt]{0pt}
  Indicates that something went wrong during reading one of the input files. To find the source of the problem, one can set the verbose level in the config file or manually via \lstinline!FastChem.setVerboseLevel! (see Sect. \ref{sec:fastchem_methods}) to a higher value and look at the terminal output.
\end{addmargin}

\bigbreak

\lstinline!constexpr unsigned int fastchem::FASTCHEM_IS_BUSY!
\begin{addmargin}[25pt]{0pt}
  The chemistry calculations of \fc can only be called once for each object class instance. Attempting to start a new calculation while another is still running, for example via OpenMP, will result in \fc returning this flag.
\end{addmargin}

\bigbreak

\lstinline!constexpr unsigned int fastchem::FASTCHEM_WRONG_INPUT_VALUES!
\begin{addmargin}[25pt]{0pt}
  \fc returns this flag if some input values are wrong. Currently, this refers to the temperature and pressure vectors in the input structure not having the same size (see Sect. \ref{sec:fastchem_input_struct} for details on the input structure). \\
\end{addmargin}

In addition to these flags, \verb|fastchem_constants.h| also includes a constant string vector \lstinline!const std::vector<std::string> fastchem::FASTCHEM_MSG! that contains string expressions for each of these flags. Using this vector with any of the aforementioned flags \lstinline!fastchem::FASTCHEM_MSG[flag]! returns a string with a description of the corresponding flag's meaning. For example, \lstinline!fastchem::FASTCHEM_MSG[fastchem::FASTCHEM_NO_CONVERGENCE]! will return the string \lstinline!"convergence failed"!.


\section{FastChem constructor}
Since \fc is written as an object class, an instance of that class (i.e. an object) needs to be created before \fc can be used. This is done by calling the constructor of the \fc class. There are two primary ways to call the constructor and create an object.\\

\lstinline!FastChem(const std::string& model_parameter_file, const unsigned int verbose_level_init)!
\begin{addmargin}[25pt]{0pt}
  This constructor requires two parameters: the location of the parameter file, described in Sect. \ref{sec:fc_parameter_file}, as well as the initial verbose, i.e. the amount of debug output in the terminal window. All main options and parameters will be read from the parameter file, but can be changed later by using the appropriate methods described in Sect. \ref{sec:fastchem_methods}.
\end{addmargin}

\bigbreak

\lstinline[breaklines=true]!FastChem(const std::string &element_abundances_file, const std::string &species_data_file, const unsigned int verbose_level)!
\begin{addmargin}[25pt]{0pt}
  This constructor requires three parameters: the locations of the element abundance and species data files, as well as the verbose level. All other options and parameters within \fc will be set to their default values but can be later changed by using the appropriate methods described in Sect. \ref{sec:fastchem_methods}. The default maximum number of chemistry iterations is 1000, the number of Newton, bisection and Nelder-Mead method iterations is 3000, and the default accuracy of the of Newton method and the chemistry iterations is set to $10^{-4}$.
\end{addmargin}

\bigbreak

A third way to create a \fc object is to make a copy of an existing one. \fc contains an internal copy constructor that manages the copy of all the object class' data structures. Assuming that \lstinline!fastchem_a! is a valid object instance of the \fc class, a second object, say \lstinline!fastchem_b!, can simply be created by using 
\begin{lstlisting}[language=C++]
  fastchem::FastChem fastchem_b(fastchem_a);
\end{lstlisting}

In this example, \lstinline!fastchem_b! is a direct copy of \lstinline!fastchem_a!, i.e. all parameters, options, and species \& element data structures are identical. After the creation of \lstinline!fastchem_b!, both objects can be used independently from each other and can even be run at the same time. 



\section{Input and output structures}

When the chemistry calculation of FastChem, \lstinline!FastChem.calcDensities(FastChemInput, FastChemOutput)! is called, input and output structures are required. Their definitions can be found in the source file \verb|fastchem_src/input_output_struct.h|

\subsection{Input structure}
\label{sec:fastchem_input_struct}
The input structure is defined as follows:
\begin{lstlisting}[language=C++]
  struct FastChemInput
  {
    std::vector<double> temperature; 
    std::vector<double> pressure;
  };
\end{lstlisting}

It contains vectors for the temperatures (in K) and pressures (in bar) that the chemical composition should be calculated for. Both vectors need to have the same length. Otherwise, \lstinline!FastChem.calcDensities! will return the constant \lstinline!fastchem::FASTCHEM_WRONG_INPUT_VALUES!. Note that even if you want to run the chemistry for only a single temperature and pressure point, you still need to provide the input in vectorial form.


\subsection{Output structure}

The outout structure is defined as
\begin{lstlisting}[language=C++]
  struct FastChemOutput
  {
    std::vector<std::vector<double>> number_densities;
    std::vector<double> total_element_density;
    std::vector<double> mean_molecular_weight;

    std::vector<std::vector<unsigned int>> element_conserved;
    std::vector<unsigned int> nb_chemistry_iterations;
    std::vector<unsigned int> fastchem_flag;
  };
\end{lstlisting}

It has the following variables:

\lstinline!std::vector<std::vector<double>> number_densities!
  \begin{addmargin}[25pt]{0pt}
    The two-dimensional array contains the number densities in \unit{cm$^{-3}$} of all species (elements, molecules, ions). The first dimension refers to the temperature-pressure grid and has the same size as the temperature and pressure vectors of the input structure. The second dimension refers to the number of species and has a length of \lstinline!FastChem.getSpeciesNumber()! (see Sect. \ref{sec:fastchem_methods}).
  \end{addmargin}
  
\bigbreak

\lstinline!std::vector<double> total_element_density!
\begin{addmargin}[25pt]{0pt}
  Contains the total number density of all atoms $i$, i.e. $n_\mathrm{tot} = \sum_i \left( n_i + \sum_j n_j \nu_{ij} \right)$, summed over their atomic number densities, as well as the ones contained in all other molecules/ions $j$. This quantity is usually only a diagnostic output and not relevant for other calculations. The dimension of the vector is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!std::vector<double> mean_molecular_weight!
\begin{addmargin}[25pt]{0pt}
  Contains the mean molecular weight of the mixture in units of the unified atomic mass unit. For all practical purposes, this can also be converted into units of $\unit{g/mol}$. The dimension of the vector is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!std::vector<std::vector<unsigned int>> element_conserved!
\begin{addmargin}[25pt]{0pt}
  The two-dimensional array contains information on the state of element conservation. A value of 0 indicates that element conservation is violated, whereas a value of 1 means that the element has been conserved. The first dimension refers to the temperature-pressure grid and has the same size as the temperature and pressure vectors of the input structure. The second dimension refers to the number of elements and has a length of \lstinline!FastChem.getElementNumber()! (see Sect. \ref{sec:fastchem_methods}).
\end{addmargin}

\bigbreak

\lstinline!std::vector<unsigned int> nb_chemistry_iterations!
\begin{addmargin}[25pt]{0pt}
  Contains the number of chemistry iterations that were required to solve the system for each temperature-pressure point. The dimension of the vector is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!std::vector<unsigned int> fastchem_flag!
\begin{addmargin}[25pt]{0pt}
  Contains flags that give information on potential issues of the chemistry calculation for each temperature-pressure point. The set of potential values is stated in Sect. \ref{sec:fastchem_constants}. A string message for each corresponding flag can also be obtained from the constant \lstinline!fastchem::FASTCHEM_MSG! vector of strings, via \lstinline!fastchem::FASTCHEM_MSG[flag]!. The dimension of the vector is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

The vectors of the output structure don't need to be pre-allocated. This will be done internally within \fc when running the chemistry calculations. If the vectors already contain data, their contents will be overwritten.


\section{Public methods of the fastchem::FastChem object class}
\label{sec:fastchem_methods}

\lstinline!unsigned int FastChem.calcDensities(FastChemInput input, FastChemOutput output)!
\begin{addmargin}[25pt]{0pt}
  Starts a chemistry calculation with the provided \lstinline!FastChemInput! and \lstinline!FastChemOutput! structs. Returns an \lstinline!unsigned int! that represents the highest value from the flag vector within the \lstinline!FastChemOutput! struct.
\end{addmargin}

\bigbreak

\lstinline!unsigned int FastChem.getSpeciesNumber()!
  \begin{addmargin}[25pt]{0pt}
    Returns the total number of chemical species (atoms, ions, molecules) as \lstinline!unsigned int!
  \end{addmargin}
  
\bigbreak

\lstinline!unsigned int FastChem.getElementNumber()!
\begin{addmargin}[25pt]{0pt}
  Returns the total number of elements as \lstinline!unsigned int!
\end{addmargin}

\bigbreak

\lstinline!unsigned int FastChem.getMoleculeNumber()!
\begin{addmargin}[25pt]{0pt}
  Returns the total number of molecules and ions (anything other than elements) as \lstinline!unsigned int!
\end{addmargin}

\bigbreak

\lstinline!std::string FastChem.getSpeciesName(unsigned int species_index)!
\begin{addmargin}[25pt]{0pt}
  Returns the name of a chemical species with index \lstinline!species_index! as \lstinline!std::string!; returns empty string if species does not exist
\end{addmargin}  

\bigbreak

\lstinline!std::string FastChem.getSpeciesSymbol(unsigned int species_index)!
\begin{addmargin}[25pt]{0pt}
  Returns the symbol of an element or the formula of a molecule/ion with index \lstinline!species_index! as \lstinline!std::string!; returns empty string if species does not exist
\end{addmargin}

\bigbreak

\lstinline!unsigned int FastChem.getSpeciesIndex(std::string symbol)!
\begin{addmargin}[25pt]{0pt}
  Returns the index of a species (element/molecule/ion) with symbol/formula \lstinline!symbol! as \lstinline!unsigned int!; returns the constant \lstinline!fastchem::FASTCHEM_UNKOWN_SPECIES! if species does not exist
\end{addmargin}

\bigbreak

\lstinline!double FastChem.getElementAbundance(unsigned int species_index)!
\begin{addmargin}[25pt]{0pt}
  Returns the abundance of an element with index \lstinline!species_index! as \lstinline!double!; returns 0 if element does not exist
\end{addmargin}


\bigbreak

\lstinline!std::vector<double> FastChem.getElementAbundance()!
\begin{addmargin}[25pt]{0pt}
  Returns the abundances of all elements as a vector of \lstinline!double!; vector has a length of \lstinline!FastChem.getElementNumber()!
\end{addmargin}


\bigbreak

\lstinline!double FastChem.getSpeciesMolecularWeight(const unsigned int species_index)!
\begin{addmargin}[25pt]{0pt}
  Returns the molecular weight of a species with index \lstinline!species_index! as \lstinline!double!; returns 0 if species does not exist; for an element this refers to the atomic weight
\end{addmargin}


\bigbreak

\lstinline!void setElementAbundances(std::vector<double> abundances)!
\begin{addmargin}[25pt]{0pt}
  Sets the abundances of all elements; the abundances are supplied as \lstinline!std::vector<double>!, where the vector has to have a size of \lstinline!FastChem.getElementNumber()!; if this is not the case, \fc will print an error message and leave the element abundances unchanged
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setVerboseLevel(unsigned int level)!
\begin{addmargin}[25pt]{0pt}
  Sets the verbose level of \fc, i.e. the amount of text output in the terminal. A value of 0 will result in \fc being almost silent, whereas a value of 4 would provide a lot of debug output. A value larger than 4 will be interpreted as 4. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setMaxChemistryIter(unsigned int nb_steps)!
\begin{addmargin}[25pt]{0pt}
  Sets the maximum number of internal chemistry iterations, provided by \lstinline!unsigned int nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setMaxNewtonIter(unsigned int nb_steps)!
\begin{addmargin}[25pt]{0pt}
  Sets the maximum number of internal Newton iterations, provided by \lstinline!unsigned int nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setMaxBisectionIter(unsigned int nb_steps)!
\begin{addmargin}[25pt]{0pt}
  Sets the maximum number of internal bisection iterations, provided by \lstinline!unsigned int nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setMaxNelderMeadIter(unsigned int nb_steps)!
\begin{addmargin}[25pt]{0pt}
  Sets the maximum number of internal iterations of the Nelder-Mead, provided by \lstinline!unsigned int nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setChemistryAccuracy(double accuracy)!
\begin{addmargin}[25pt]{0pt}
  Sets the desired accuracy of the chemistry convergence criterion, provided by \lstinline!double accuracy!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.setNewtonAccuracy(double accuracy)!
\begin{addmargin}[25pt]{0pt}
  Sets the desired accuracy of the Newton's method convergence criterion, provided by \lstinline!double accuracy!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline!void FastChem.useScalingFactor(bool use)!
\begin{addmargin}[25pt]{0pt}
  Toggles the use of the internal scaling factor. The default value in \fc is \lstinline!false!. The use of the scaling factor is currently not accessible from the config files but can only be activated by this function.
\end{addmargin}


%\part{PyFastChem: The Python version of FastChem}

\chapter{\pfc: The Python module of \fc}
\label{sec:pyfc_details}

By using the library \pb, \fc can be called directly within Python. This requires the compilation of \fc's Python wrapper that is located in the file \verb|python/fastchem_python_wrapper.cpp|. \pfc currently only links to the \lstinline!long double! \cpp version of \fc.\\

As described in Sect. \ref{sec:install_config}, when using the \ttt{CMake} approach, \pfc will be automatically compiled when \ttt{cmake} is configured with the corresponding option. If the configuration and compilation is successful, a module file should be present in the \verb|python/| folder that contains the Python module which acts as a wrapper between Python and the \cpp version of \fc. The file should be named \verb|pyfastchem.cpython-xxxx|, where \verb|xxxx| will be a combination of your Python version and operating system.\\ 

If \pfc has been built using the \verb|setup.py| script or installed via \verb|PyPI|, then the module will be located in your normal Python module library path. It, thus, can be accessed from everywhere on your system like any other standard Python package. The location and additional module information can be obtained via
\begin{lstlisting}[language=bash]
  pip show pyfastchem
\end{lstlisting}
Depending on your Python installation, \verb|pip| might need to be replaced by \verb|pip3|.\\


A description of the module is given in Sect. \ref{sec:pyfc_module}. Besides the \pfc module, we also provide several example Python scripts that show how to call \fc from within Python for several different scenarios. We discuss the examples in Sect. \ref{sec:pyfc_examples}.


\section{The \pfc module}
\label{sec:pyfc_module}

The \pfc module provides access to the \fc object class as well as additional constants used within \fc. They are essentially identical to their \cpp counterparts discussed in Sect. \ref{sec:fc_class}.

To include the \pfc module in your Python project, just import it using

\begin{lstlisting}[language=Python]
  import pyfastchem
\end{lstlisting}

This provides access to the \fc object class as well as the input and output structures and additional pre-defined constants used by \fc.

\section{\pfc constants}
\label{sec:pfc_constants}

The \pfc module contains a number of pre-defined constants. This includes the constant \lstinline!pyfastchem.FASTCHEM_UNKNOWN_SPECIES! of type \lstinline!int! that is returned by some \pfc methods when a chemical species is not found. \\

The chemistry calculation can also return several output flags of type \lstinline!int! defined as constants in the \pfc module:

\lstinline!pyfastchem.FASTCHEM_SUCCESS!
\begin{addmargin}[25pt]{0pt}
  Indicates that the calculation has been successful, i.e. that the chemistry iterations converged.
\end{addmargin}
  
\bigbreak
  
\lstinline!pyfastchem.FASTCHEM_NO_CONVERGENCE!
\begin{addmargin}[25pt]{0pt}
  Indicates that the calculation was not successful, i.e. that the chemistry did not converge within the allowed maximum number of iterations steps given in the config file or set manually via \lstinline!setMaxChemistryIter! (see Sect. \ref{sec:pfc_methods}). One way to solve such a problem is to increase the maximum number of iteration steps.
\end{addmargin}
    
\bigbreak
    
\lstinline!pyfastchem.FASTCHEM_INITIALIZATION_FAILED!
\begin{addmargin}[25pt]{0pt}
  Indicates that something went wrong during reading one of the input files. To find the source of the problem, one can set the verbose level in the config file or manually via \lstinline!setVerboseLevel! (see Sect. \ref{sec:pfc_methods}) to a higher value and look at the terminal output.
\end{addmargin}
      
\bigbreak
      
\lstinline!pyfastchem.FASTCHEM_IS_BUSY!
\begin{addmargin}[25pt]{0pt}
  The chemistry calculations of \fc can only be called once for each object class instance. Attempting to start a new calculation while another is still running will result in \fc returning this flag.
\end{addmargin}
        
\bigbreak
        
\lstinline!pyfastchem.FASTCHEM_WRONG_INPUT_VALUES!
\begin{addmargin}[25pt]{0pt}
  \fc returns this flag if some input values are wrong. Currently, this refers to the temperature and pressure vectors in the input structure not having the same size (see Sect. \ref{sec:fastchem_input_struct} for details on the input structure).
\end{addmargin}

\bigbreak
          
In addition to these flags, the \pfc module also includes a constant string array \lstinline!pyfastchem.FASTCHEM_MSG! that contains string expressions for each of these flags. Using this array with any of the aforementioned flags \lstinline!pyfastchen.FASTCHEM_MSG[flag]! returns a string with a description of the corresponding flag's meaning. For example, \lstinline!pyfastchem.FASTCHEM_MSG[pyfastchem.FASTCHEM_NO_CONVERGENCE]! will return the string \lstinline!"convergence failed"!.


\section{\pfc constructor}

Since \fc is written as an object class, an instance of that class (i.e. an object) needs to be created before \fc can be used. This is done by calling the constructor of the \fc class that is contained within the \pfc module. There are two main ways to call the constructor and create an object.\\


\lstinline[language=Python, breaklines=true]!pyfastchem.FastChem(str element_abundance_file, str equilibrium_constants_file, int verbose_level)!
\begin{addmargin}[25pt]{0pt}
	The constructor requires three different arguments: the location of the element abundance file, the location of the file with the equilibrium constants, and the verbose level, i.e. the amount of debug output in the terminal window. Creating a \fc object with this constructor will set internal parameters to their default values. The maximum number of chemistry iterations will be 1000, the number of Newton, bisection and Nelder-Mead method iterations is 3000, and the accuracy of the of Newton method and the chemistry iterations is set to $10^{-4}$. All of these values can be adjusted during runtime by using the methods listed in Section \ref{sec:pfc_methods}.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!pyfastchem.FastChem(str parameter_file, int intial_verbose_level)!
\begin{addmargin}[25pt]{0pt}
	The constructor requires two different arguments: the location of the parameter file and the initial verbose level. The latter one will be replaced by the corresponding value read in from the parameter file. The structure of this parameter file is discussed in Section \ref{sec:fc_parameter_file}. All of parameter values read in from the file can also be adjusted during runtime by using the methods listed in Section \ref{sec:pfc_methods}.
\end{addmargin}



\section{\pfc input and output structures}
\label{sec:pfc_input_ouput_struct}

Running a FastChem chemistry calculation requires input and output data structures, resembling those of the \cpp version (see Sect. \ref{sec:fastchem_input_struct}). 

\paragraph{Input structure}
An input structure, in the example here called \lstinline!input_data!, can be defined from the \pfc module in the following way:
\begin{lstlisting}[language=Python]
  input_data = pyfastchem.FastChemInput()
\end{lstlisting}

The input structure contains the following variables:

\bigbreak

\lstinline[language=Python]!temperature!
\begin{addmargin}[25pt]{0pt}
	An array of \lstinline[language=Python]!float! numbers that describe the temperature in K.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!pressure!
\begin{addmargin}[25pt]{0pt}
	An array of \lstinline[language=Python]!float! numbers that describe the pressure in bar.
\end{addmargin}

\bigbreak

Both arrays need to have the same length. The \pb library allows normal Python lists or NumPy arrays to be used here. For example, a NumPy array for the pressure could be defined using NumPy's \lstinline!logspace! function:

\begin{lstlisting}[language=Python]
  input_data.pressure = np.logspace(-6, 1, num=1000)
\end{lstlisting}
Both input variables need to be an array-type variable, even if only a single temperature-pressure point is going to be calculated.

\paragraph{Output structure}
The output structure from the \pfc module, in the example here called \lstinline!output_data!, can be defined in the following way:
\begin{lstlisting}[language=Python]
  output_data = pyfastchem.FastChemOutput()
\end{lstlisting}

It has the following variables:

\lstinline!number_densities!
\begin{addmargin}[25pt]{0pt}
	The two-dimensional array contains the number densities in \unit{cm$^{-3}$} of all species (elements, molecules, ions) as \lstinline[language=Python]!float! numbers. The first dimension refers to the temperature-pressure grid and has the same size as the temperature and pressure arrays of the input structure. The second dimension refers to the number of species and has a length of \lstinline!getSpeciesNumber()! (see Sect. \ref{sec:pfc_methods}).
\end{addmargin}

\bigbreak

\lstinline!total_element_density!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!float! numbers that contains the total number density of all atoms $i$, i.e. $n_\mathrm{tot} = \sum_i \left( n_i + \sum_j n_j \nu_{ij} \right)$, summed over their atomic number densities, as well as the ones contained in all other molecules/ions $j$. This quantity is usually only a diagnostic output and not relevant for other calculations. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!mean_molecular_weight!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!float! numbers. Contains the mean molecular weight of the mixture in units of the unified atomic mass unit. For all practical purposes, this can also be converted into units of $\unit{g/mol}$. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!element_conserved!
\begin{addmargin}[25pt]{0pt}
	The two-dimensional array of \lstinline[language=Python]!int! numbers contains information on the state of element conservation. A value of 0 indicates that element conservation is not fulfilled, whereas a value of 1 means that the element has been conserved. The first dimension refers to the temperature-pressure grid and has the same size as the temperature and pressure vectors of the input structure. The second dimension refers to the number of elements and has a length of \lstinline!getElementNumber()! (see Sect. \ref{sec:pfc_methods}).
\end{addmargin}

\bigbreak

\lstinline!nb_chemistry_iterations!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!int! numbers. Contains the number of chemistry iterations that were required to solve the system for each temperature-pressure point. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

\lstinline!fastchem_flag!
\begin{addmargin}[25pt]{0pt}
	One-dimensional array of \lstinline[language=Python]!int! numbers. Contains flags that give information on potential issues of the chemistry calculation for each temperature-pressure point. The set of potential values is stated in Sect. \ref{sec:pfc_constants}. A string message for each corresponding flag can also be obtained from the constant \lstinline!pyfastchem.FASTCHEM_MSG! vector of strings, via \lstinline!pyfastchem.FASTCHEM_MSG[flag]!. The dimension of the array is equal to that of the input temperature and pressure vectors.
\end{addmargin}

\bigbreak

The arrays of the output structure don't need to be pre-allocated. This will be done internally within \fc when running the chemistry calculations. If the arrays already contain data, their contents will be overwritten. The arrays from the output structure can also be easily converted to more practical NumPy arrays by using, for example:
\begin{lstlisting}[language=Python]
  number_densities = np.array(output_data.number_densities)
\end{lstlisting} 


\section{\pfc functions}
\label{sec:pfc_methods}

The \pfc object returned from \lstinline[language=Python]!pyfastchem.FastChem()! has several methods that allow to interact with \fc. These methods are equivalent to those of the \cpp object class discussed in Sect. \ref{sec:fastchem_methods}.\\

\lstinline[language=Python]!int calcDensities(pyfastchem.FastChemInput() input, pyfastchem.FastChemOutput() output)!
\begin{addmargin}[25pt]{0pt}
	Starts a chemistry calculation with the provided \lstinline!pyfastchem.FastChemInput()! and \lstinline!pyfastchem.FastChemOutput()! structures. Returns an \lstinline!int! value that represents the highest value from the flag vector within the \lstinline!pyfastchem.FastChemOutput()! structure.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!int getSpeciesNumber()!
\begin{addmargin}[25pt]{0pt}
	Returns the total number of chemical species (atoms, ions, molecules) as \lstinline!int! value.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!int getElementNumber()!
\begin{addmargin}[25pt]{0pt}
	Returns the total number of elements as \lstinline!int! value.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!int getMoleculeNumber()!
\begin{addmargin}[25pt]{0pt}
	Returns the total number of molecules and ions (anything other than elements) as \lstinline!int! value.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!str getSpeciesName(int species_index)!
\begin{addmargin}[25pt]{0pt}
	Returns the name of a chemical species with \lstinline[language=Python]!int! index\footnote{In the \cpp class, an \lstinline!unsigned int! is required here. Since this data type doesn't exist in Python, \pb will convert the supplied integer value to its unsigned integer version for \cpp. Even though the parameter is defined as an \lstinline!int! value for Python, only positive numbers, including 0, are accepted as valid input. Using a negative value will result in an error message from \pb.} \lstinline!species_index! as \lstinline[language=Python]!str!; returns empty string if species does not exist.
\end{addmargin}  

\bigbreak

\lstinline[language=Python]!str getSpeciesSymbol(int species_index)!
\begin{addmargin}[25pt]{0pt}
	Returns the symbol of an element or the formula of a molecule/ion with \lstinline[language=Python]!int! index\footnotemark[\value{footnote}] \lstinline!species_index! as \lstinline[language=Python]!str!; returns empty string if species does not exist
\end{addmargin}

\bigbreak

\lstinline[language=Python]!int getSpeciesIndex(str symbol)!
\begin{addmargin}[25pt]{0pt}
	Returns the index of a species (element/molecule/ion) with \lstinline[language=Python]!str! symbol/formula \lstinline!symbol! as \lstinline[language=Python]!int!; returns the constant \lstinline!pyfastchem.FASTCHEM_UNKOWN_SPECIES! if species does not exist.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!float getElementAbundance(int species_index)!
\begin{addmargin}[25pt]{0pt}
	Returns the abundance of an element with \lstinline[language=Python]!int! index\footnotemark[\value{footnote}] \lstinline!species_index! as \lstinline!float!; returns 0 if the element does not exist
\end{addmargin}


\bigbreak

\lstinline[language=Python]!float [] getElementAbundance()!
\begin{addmargin}[25pt]{0pt}
	Returns the abundances of all elements as an array of \lstinline[language=Python]!float! values; array has a length of \lstinline!getElementNumber()!.
\end{addmargin}


\bigbreak

\lstinline[language=Python]!float FastChem.getSpeciesMolecularWeight(int species_index)!
\begin{addmargin}[25pt]{0pt}
	Returns the molecular weight of a species with \lstinline[language=Python]!int! index\footnotemark[\value{footnote}] \lstinline!species_index! as \lstinline[language=Python]!float!; returns 0 if species does not exist; for an element this refers to the atomic weight.
\end{addmargin}


\bigbreak

\lstinline[language=Python]!setElementAbundances(float [] abundances)!
\begin{addmargin}[25pt]{0pt}
	Sets the abundances of all elements; the abundances are supplied as an array of \lstinline[language=Python]!float! values, where the array has to have a size of \lstinline[language=Python]!getElementNumber()!; if this is not the case, \fc will print an error message and leave the element abundances unchanged
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setVerboseLevel(int level)!
\begin{addmargin}[25pt]{0pt}
	Sets the verbose level of \fc, i.e. the amount of text output in the terminal. A value of 0 will result in \fc being almost silent, whereas a value of 4 would provide a lot of debug output. A value larger than 4 will be interpreted as 4. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setMaxChemistryIter(int nb_steps)!
\begin{addmargin}[25pt]{0pt}
	Sets the maximum number of internal chemistry iterations, provided by the \lstinline[language=Python]!int!\footnotemark[\value{footnote}] variable \lstinline!nb_steps!. This value will overwrite the one from the \fc parameter file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setMaxNewtonIter(int nb_steps)!
\begin{addmargin}[25pt]{0pt}
	Sets the maximum number of internal Newton iterations, provided by the \lstinline[language=Python]!int!\footnotemark[\value{footnote}] variable \lstinline!nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setMaxBisectionIter(int nb_steps)!
\begin{addmargin}[25pt]{0pt}
	Sets the maximum number of internal bisection iterations, provided by the \lstinline[language=Python]!int!\footnotemark[\value{footnote}] variable \lstinline!nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setMaxNelderMeadIter(int nb_steps)!
\begin{addmargin}[25pt]{0pt}
	Sets the maximum number of internal iterations of the Nelder-Mead, provided by the \lstinline[language=Python]!int!\footnotemark[\value{footnote}] variable \lstinline!nb_steps!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setChemistryAccuracy(float accuracy)!
\begin{addmargin}[25pt]{0pt}
	Sets the desired accuracy of the chemistry convergence criterion, provided by \lstinline[language=Python]!float! variable \lstinline!accuracy!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!setNewtonAccuracy(float accuracy)!
\begin{addmargin}[25pt]{0pt}
	Sets the desired accuracy of the Newton's method convergence criterion, provided by \lstinline[language=Python]!float! variable \lstinline!accuracy!. This value will overwrite the one from the \fc config file.
\end{addmargin}

\bigbreak

\lstinline[language=Python]!useScalingFactor(bool use)!
\begin{addmargin}[25pt]{0pt}
	Toggles the use of the internal scaling factor. The default value in \fc is \lstinline[language=Python]!false!. The use of the scaling factor is currently not accessible from the config files but can only be activated by this function.
\end{addmargin}



\bibliographystyle{aasjournal}
\bibliography{aux/references}
  
\end{document} 
