Atomic line radiative transfer with MCFOST I. Code description and benchmarking

Aims. We present MCFOST-art, a new non-local thermodynamic equilibrium radiative transfer solver for multilevel atomic systems. The code is embedded in the 3D radiative transfer code MCFOST and is compatible with most of the MCFOST modules. The code is versatile and designed to model the close environment of stars in 3D. Methods. The code solves for the statistical equilibrium and radiative transfer equations using the Multilevel Accelerated Lambda Iteration (MALI) method. We tested MCFOST-art on spherically symmetric models of stellar photospheres as well as on a standard model of the solar atmosphere. We computed atomic level populations and outgoing fluxes and compared these values with the results of the TURBOspectrum and RH codes. Calculations including expansion and rotation of the atmosphere were also performed. We tested both the pure local thermodynamic equilibrium and the out-of-equilibrium problems. Results. In all cases, the results from all codes agree within a few percent at all wavelengths and reach the sub-percent level between RH and MCFOST-art. We still note a few marginal discrepancies between MCFOST-art and TURBOspectrum as a result of different treatments of background opacities at some critical wavelength ranges.


Introduction
Radiation processes are critical in many aspects of the evolution of astrophysical objects such as stellar atmospheres, magnetospheres and discs. Electromagnetic radiation carries the history of the emitting object to the observer at which point the object is analysed. Through spectroscopy we can deduce fundamental parameters, abundances and unveil the complex atmospheric dynamics of many stellar objects, often via comparison with numerical models.
These numerical models require the solution of the radiative transport equation in complex and different plasma conditions. In many astrophysical applications matter and radiation are coupled : This is the so-called non-local thermodynamic equilibrium (non-LTE) line formation problem. At non-LTE, the atomic level populations are computed from a set of statistical equilibrium equations where radiation plays the central role. In turn, knowledge of emission and absorption processes, which depends on the level populations, is needed to solve for radiation. Therefore, the radiative transport equation must be solved simultaneously with statistical equilibrium equations. This makes the solution of the non-LTE problem challenging. Identifying the best solution to that problem depends mainly on the nature of the simulated plasma and many types of solutions exist (e.g. van Zadelhoff et al. 2002).
In this paper, we present MCFOST-art, a code for the solution of the non-LTE problem for multilevel atomic systems. The code is embedded in the 3D radiative transfer code MCFOST (Pinte et al. 2006(Pinte et al. , 2009 and can be applied to a wide range of astrophysical problems in different geometries. Our main motivation for developing such a code is to address the line forma-tion in the close environment of young stellar objects (YSO). In particular, the evolution of classical T Tauri stars depends on the interaction between the young star and its accretion disc, on distances of a few stellar radii. This complex interaction leads to stellar winds and magnetospheric accretion and ejection processes. These processes have a strong impact on spectral lines and disentangling their typical radiative signatures is a challenging task.
Previous modelling of the environment of T Tauri stars, their magnetosphere (Hartmann et al. 1994;Muzerolle et al. 2001), stellar wind, and disc wind regions (Lima et al. 2010;Kurosawa et al. 2011) show the difficulty to account for all observational signatures of these stars, from their variability to the shape of emission lines. Even a detailed modelling of a specific T Tauri star, with the most updated magneto-hydrodynamics (MHD) models, results in a marginal agreement between synthetic observables and observations (Alencar et al. 2012).
Most of magnetospheric emission lines synthesis used the Sobolev approximation (Sobolev 1957;Rybicki & Hummer 1978) to solve the radiative transfer equation. This approximation is applicable when large velocity gradients (i.e. large compared to the intrinsic width of atomic lines) are encountered in a plasma. It greatly simplifies the solution of the transfer equation. However, in the case of magnetospheres, the required conditions for the Sobolev approximation to hold are not always met, ultimately impacting the level populations. In our code, we use an accelerated Λ-iteration method (Olson et al. 1986) with a preconditioning of the statistical equilibrium equations (Rybicki & Hummer 1991) to solve the coupled radiative transfer and statistical equilibrium equations. Unlike the Sobolev approximation, Article number, page 1 of 13 arXiv:2101.04722v1 [astro-ph.SR] 12 Jan 2021 A&A proofs: manuscript no. bt_spidi1 our approach does not make any assumptions about the local conditions in the plasma.
We tested MCFOST-art on 1D spherically symmetric models including a range of thermodynamic quantities to capture a variety of physical conditions existing in stellar plasma. In §2 we give the details of the physical problem and how it is solved. In §3 we describe the implementation of our code in MCFOST, and in §4 we test the accuracy and precision of our code against benchmark cases. Finally, we give our conclusions in §5.

Non-NLTE radiative transfer problem
In multilevel non-LTE problems, the main difficulty is to find a self-consistent solution of the equations for the atomic level populations with a solution of the transport equation for radiation. In this section we describe the coupling between these equations.

Radiative transfer equation
The unpolarised radiative transfer equation along a ray of length ds in the direction n is written as where, I(ν, n) is the specific intensity at a frequency ν in the direction n, χ is the total (line and continuum) opacity (true absorption and scattering σ), and η is the emissivity. We use the formulation of Rybicki & Hummer (1992) to express the radiative transfer equation, and we define the radiative transfer coefficients U and V as where A and B are the Einstein's coefficients and φ(ν, n) and ψ(ν, n) the absorption and the emission profiles, respectively, for the transition i → j 1 . We further assume complete frequency redistribution, implying an equivalence between the absorption coefficient appearing in V and the emission coefficient appearing in U , that is ψ(ν, n) = φ(ν, n). For a continuum transition the radiative transfer coefficients are given by where α(ν) is the photoionisation cross-section, T the gas temperature, and n * the population (number density) of level , evaluated at local thermodynamic equilibrium (LTE). 1 We adopt the following convention: j and i refer to the upper and lower levels of a transition, respectively. For atomic levels ordered by increasing energies, E , this implies E j > E i . In other cases, when the ordering of levels is unimportant, we use the indexes , , ... Finally, the emissivity η i j and the opacity χ i j for a transition between an upper level j and a lower level i are written as where n i and n j are the lower and upper level populations, respectively. The total opacity and emissivity for all transitions of all atoms and other sources of opacity add up to the total opacity χ(ν, n) and emissivity η(ν, n), where η c and χ c are the sources of continuous emissivity and opacity evaluated at LTE (the background opacity, see §3.4). The solution of Eq. 1 along a ray of length ds is straight forward if χ, η, the populations n, and the properties of the atmosphere (temperature, velocity fields, etc...) are known. Defining the optical depth τ τ(ν, n; s) as dτ(ν, n) = −χ(ν, n; s) ds it reads: where S (ν, n; τ) = η(ν, n; τ) χ(ν, n; τ) is the source function at optical depth τ, at the frequency ν in the direction n.
In general, the emissivity and opacity depend on the level populations which in turn depend on the intensity. Therefore, a self-consistent solution of the radiative transfer equation with a solution of statistical equilibrium equations is required, the socalled non-LTE problem.

Λ−iteration
The solution of Eq. 1 can be recast as where Ψ 2 is a matrix operator whose elements depend on the level populations (for more details see e.g. Hubeny & Mihalas 2014, hereafter, HM14). This equation gives the solution of the intensity if all elements of the Ψ operator, which are functions of the atomic populations, are known. However, in practice, building the full Ψ operator is never affordable and the emissivity appearing in Eq. 7 is substituted by an old value η † evaluated from a known estimate of the level populations (i.e. old values obtained with a previous iteration). The new intensity obtained by the application of the operator on the old emissivity is then used to compute a new value of the level populations and of the emissivity, which are used to compute a new value of the intensity. This iterative process, between old and new values of the populations, is known as Λ−iteration and it is repeated until convergence. Although Λ−iteration is very efficient in an optically thin region, it suffers convergence problems in very optically thick regions. This drawback of classical Λ−iteration can be overcome by a slight modification of Eq. 7 (see Cannon 1973a,b;Scharmer 1981;Olson et al. 1986), that is recasting Eq. 7 in with an approximate operator Ψ * (ν, n) built from a subset of the original operator. Equation 8 improves the convergence of the classical Λ-iteration method in optically thick regions and has been named ALI for accelerated Λ-iteration (after the work of Hamann (1985) and Werner & Husfeld (1985)).
In most applications, the diagonal of the full operator is used, although other studies recommended a tri-diagonal approximate operator (see for instance Hennicker et al. 2018). Higher order approximate operators can improve the convergence of the radiative transfer problem at the price of computational time and memory storage. For 2D radiative transfer problems, Auer et al. (1994) suggested to use the diagonal part of the operator in combination with an algorithm to accelerate the convergence (see §2.7). In our code, we use the diagonal part of the full operator as a compromise between speed and accuracy.

Statistical equilibrium equations
The level populations of an atom in a stellar plasma is a function of the rates of transitions populating or depopulating a given level. These rates in turn are a function of level populations, collisions, and radiation.
The statistical equilibrium equations (SEE) for level is given by 3 where n is the population of level , and C , and R the collisional and radiative rates for a transition between level and , respectively.

Radiative rates
Unlike collisional rates, radiative rates are a product of the radiative transfer code. These rates can be expressed in terms of the radiative transfer coefficients and are written as where the integration is carried out over frequency ν and all solid angles Ω. For line transitions these rates are written as where B i j , B ji , and A ji are the Einstein's coefficients, and J the mean intensity integrated over the line given by where φ(ν, n) is the line absorption profile, also appearing in Eq. 2. For continuum transitions they are as follows: 3 We neglect both the advective and non-stationary terms as they are in general negligible for non-relativistic flows.
where J(ν) is the mean radiation field given by

Matrix form of the SEE
Starting from Eq. 9, passing the right-hand side term on the lefthand side and noticing that n l = n δ with δ non-zero only for = , we can factorise out n and write the SEE as where the rate matrix Γ is

MALI method
Multilevel radiative transfer is a complex problem to solve because of the dependence of the radiation field on the populations, and of the populations on the radiation field. Using Eqs.8 and 10 the rate matrix in Eq. 16 for a multilevel atom reads: where I eff (ν, n) = I † (ν, n) − Ψ * (ν, n)η † (ν, n) is an effective radiation field built with known quantities (old values). In Eq. 17 we assumed that background opacities are constant within subsequent iterations.
The system of equations 15 is nonlinear in the new populations as it involves the product of the form ∝ n × n in Eq. 17. The multilevel accelerated lambda iteration method (hereafter, MALI) proposed by Rybicki & Hummer (1991), latter improved by Uitenbroek (2001), uses the operator splitting method and a full preconditioning to make Eqs. 15 and 17 linear in the new populations. The coupled equations of statistical equilibrium with the radiation field are finally written as follows: The last term in Eq. 18, which disappears in the classic Λiteration (Rybicki & Hummer 1992;Uitenbroek 2001) is called the cross-coupling term. From Eq. 4 the term represents a summation over all opacities of all transitions with a plus sign if l < j or a minus sign if l > j, that is

Coherent electron scattering
In some cases electron scattering is a dominant source of opacity and its effect on both the continuum and spectral lines has to be taken into account (Hillier 1991). However, the evaluation of the scattering emissivity involves the calculation of a scattering integral whose expression in the observer's frame is not trivial (Rybicki & Hummer 1994). We evaluate the electron scattering emissivity by setting it to the mean intensity (coherent approximation), which is in turn determined iteratively through classical Λ-iterations, as suggested by Rybicki & Hummer (1992). This method is accurate enough for the main range of applications of the code, but becomes inaccurate for hot stellar wind where the electron density is very high and the ratio of scattering to true absorption is large.

Level dissolution and occupation probability
To do reliable radiative transfer simulations it is necessary to allow for line overlap and merging close to series limits. The MALI formulation of the non-LTE problem is already capable of dealing with overlapping lines, and we include the formalism of occupation probabilities of Hummer & Mihalas (1988) to allow for lines to merge at the series limits. Because of the presence of perturbers, each bound state i of an atom has a probability w(i), with respect to the same state of a similar isolated atom, to remain bound. Conversely, 1 − w(i) represents the probability of state i to be dissolved, in other words, to belong to the continuum states. Dissolved states contribute to a pseudocontinuum opacity beyond the series limits. Our implementation of the occupation probabilities formalism is similar to that of Hubeny et al. (1994), based on the work of Dappen et al. (1987), and summarised in Hillier & Miller (1998). We further assume, as in Hillier & Miller (1998), that if w(i) is the probability of level i to be undissolved and w( j) this probability for level j, then if j is undissolved, i is necessarily undissolved as it lies in a lower energy state. Therefore, all upward rates in the statistical equilibrium equations have to be multiplied by w( j)/w(i), the probability that the upper level j is undissolved given i is undissolved. In §4.1.1 the impact of level dissolution on stellar continua is shown.

Acceleration of the convergence
To speed up the MALI method we implemented the method of acceleration of Ng (1974) with general orders as defined in Auer et al. (1994) and Uitenbroek (2001). This method uses N sol + 2 previous solutions and accumulated iteration after iteration to extrapolate the new value of the solution by minimising the residual between the previous iterations. The latter step is called Ng's iteration. When using Ng's accelerations, it is important to impose a delay before accumulating solutions, as extrapolating the new solution too early may result in negative or inconsistent values. Following Auer et al. (1994), we recommend doing some MALI iterations between each extrapolation to let the solution settle down. Therefore, after N start MALI iterations (i.e. without acceleration), we start accumulating N sol + 2 solutions up to the Ng's iteration. We repeat this process every N pending MALI iterations. In our tests, we use N sol = 2, N start = 5 and N pending = 5. We note that setting N pending to 0 mainly results in extra overhead due to the matrix inversion required in the minimisation procedure (see for instance Uitenbroek 2001). The main drawback of Ng's acceleration for multidimensional models is the memory required to store N sol + 2 solutions for each atom treated in non-LTE. Following Auer et al. (1994), using a diagonal operator in addition to Ng's iterations is a good compromise between speed (of convergence) and memory requirements in multidimensional models. Whereas in 1D geometry memory storage is usually not a limitation, we discuss the practicability of Ng's acceleration scheme in multidimensional models in a future paper.

Implementation in MCFOST
The formulation of the non-LTE line transfer of Rybicki & Hummer (1992), although developed for 1D grids, can be easily adapted for multidimensional models. Auer et al. (1994) applied the MALI method to a 2D Cartesian grid, while Hauschildt & Baron (2014) applied it to a 3D spherical grid. Recently, De Ceuster et al. (2020) applied the method to an unstructured grid.
MCFOST-art, which stands for MCFOST atomic radiative transitions, is an ensemble of modules implemented in MCFOST (Pinte et al. 2006(Pinte et al. , 2009. A 3D radiative transfer code, MCFOST is written in modern Fortran, dedicated to the modelling of dust emission and molecular lines in the environment of young stars (e.g. protoplanetary discs, circumstellar envelopes). This code has been coupled with SPH codes (e.g. Price et al. 2018) and MHD codes (e.g. Riols et al. 2020). Currently MCFOST handles three types of grids: a cylindrical grid dedicated to the modelling of discs, a spherical grid, and an unstructured grid based on a Voronoi tessellation (see e.g. Camps et al. 2013). The solution of the line transfer equation is done by ray-tracing: several rays are propagated in specific directions along which Eq. 1 is solved for each wavelength simultaneously.
In our new modules, we propagated rays from each cell centre (spatial grid units in 2D and 3D geometries) in directions defined by the angular quadrature scheme (see below). Cells represent the smallest resolution elements of the code and all quantities are constant within them. If the model has a non-zero velocity field, the velocity is projected in the direction of propagation of the ray. When velocity fields are present, it is important to maintain a proper spatial discretisation to prevent nonphysical features due to large velocity gradients (Ibgui et al. 2013). The MCFOST code detects if the projected velocity between two grid points is too large and linearly interpolates the projected velocity accordingly.
To produce images, we solved the intensity out of each pixel by integrating Eq. 1 along rays centred on each pixel.
The solution of Eq. 1 along a ray, specified by a vector direction n, is written as where I 0 (ν, n) is the emerging specific intensity in a given direction; I b (ν, n) is the intensity at the inner boundary of the model, typically this is the stellar radiation if a ray intersects the star; τ tot is the total optical depth from the boundary to the observer; S k the source function for cell k; and τ k the optical depth at the inner (entrance) boundary of a cell. In Eq. 19, the sum represents the contribution of each cell, along the ray path, to the outgoing radiation.
The term dτ k = τ k+1 − τ k = χ k s is the optical depth accumulated by the ray as it travels a distance s inside a cell of opacity χ k . The intensity outgoing in direction n from a specific cell, after travelling a distance s(k + 1) − s(k) in the cell is written as The approximate operator Ψ * appearing in eqs. 8 and 18 is evaluated by solving the transfer equation with a source function, which is 1 at cell k and 0 elsewhere, that is S k = δ(τ − τ k ). According to Eq. 20, this is given by where the numerator is the diagonal of the Λ operator, that is This satisfies the following conditions in the two extreme cases: in optically thin regions it is 0, which corresponds to classical Λ-iterations, and it approaches 1 in optically thick regions. Although this method allows for fast integration of the radiative transfer equation, it depends on the numerical resolution, compared to other methods that use linear or cubic interpolations between grid points.
The part of the code that handles the propagation within the grid is presented in Pinte et al. (2006). In the following, we present in some detail the solution of the non-LTE atomic line formation problem in the code.

Initial solution
In MCFOST-art, there are currently two choices for the initialisation of the level populations of the non-LTE problem: populations are evaluated at LTE and populations are obtained by solving the SEE with the radiation field set to zero. The choice of the initial solution is the critical point of the non-LTE problem. If the initial guess is too far from the solution, the convergence can be slowed down or even fail. In the eventuality that none of these choices lead to convergence, we implemented the collisional-radiative switching method of Hummer & Voels (1988). This method allows for a smooth transition between a collision dominated initial solution (i.e. at LTE) to a non-LTE initial solution. Alternatively, the populations from a previous calculation are given.

Line profiles
The absorption profile for each atomic bound-bound transition can either have a Gaussian or a Voigt shape. The choice of the shape of the absorption profile depends on the line and the problem.
The width of the absorption profile, v D , is given by the sum of the line thermal width and the microturbulence ξ as follows: where k b is the Boltzmann constant, T the temperature, and m the mass of the atomic species.
The damping parameter is the sum of the radiative damping and Van Der Waals and Stark broadenings. The radiative damping of a line transition j → i, Γ j , is computed by summing the Einstein A ji coefficients for all (allowed) transitions for which j is an upper level as follows: In the latter expression, we neglected the effect of stimulated emission. Pressure broadening takes into account van der Waals and Stark (linear and quadratic) broadenings computed in the Lindholm theory. We computed interaction constants using the Unsöld formula (Unsöld & Weidemann 1955) and evaluated the quadratic Stark broadening following Gray (2008, Eq. 11.33). Linear Stark broadening was computed following Sutton (1978). The treatment of the Stark broadening, especially for hydrogen lines is approximate and is only accurate for the first lines of each series. In the future, we plan to add a more accurate treatment of the Stark broadening (see e.g. Stehlé & Hutcheon 1999).

Wavelength grid
The wavelength grid used for non-LTE calculations was built from individual atomic transitions. Firstly, we set up a grid of continuum transitions at a moderate resolution. This continuum grid was used to solve the continuum radiative transfer equation.
Secondly, lines were gathered in groups depending on their bounds (i.e. overlapping regions). Line bounds range from −V to +V, where V is a multiple of the line Doppler width (Eq. 23). The line bounds represent the interaction zone of the line with the radiation field. Since in moving atmosphere a line feels the radiation from different regions, the line bounds include the maximum shift in frequency due to the velocity fields. However, the local (i.e. in the co-moving frame) line profile is not affected by velocity fields.
Each group of lines was sampled with a constant resolution in kilometers per second. Once wavelength grids for each group were determined, they were merged and continuum points from the continuum grid were added outside line groups.

Background opacity
Opacity and emissivity of transitions were computed for each atom using Eqs. 4, 2, and 3. The photoionisation cross-section of hydrogen-like ions was computed using Kramer's formula with correction from quantum mechanics (HM14, Eq. 7.92). For non-hydrogen-like ions, the photoionisation cross-section was directly read from the atomic file and interpolated on the wavelength grid of MCFOST. We took the photoionisation data from TOPbase 4 (Cunto & Mendoza 1992).
We also included continuum transitions from other sources which add up in χ c . These are Thomson scattering on free electrons, hydrogen free-free (HM14, Eq. 7.100), and H − free-free and bound-free transitions from John (1988).

Non-LTE loop
The main module of our code deals with solving Eq. 15 simultaneously with Eq. 1 via the non-LTE loop. Figure 1 shows the main steps leading to the solution of the non-LTE problem with MCFOST-art. We stress that even if Eq. 15 is solved locally (i.e. within each cell) it is coupled with other cells through Eq. 1.
Firstly, the code reads abundances for the atomic species under consideration, the corresponding atomic data (e.g. energy levels E i and the oscillator strength f i j ), and an atmospheric model (temperature, densities, and velocity fields). The electron density is evaluated at LTE if not present in the model (for more detail on electron density loop, see sect. 3.6). Secondly, MCFOST-art initialises the level populations of each atom as described above.
Finally, we evaluate continuous background opacities. In models in which electron scattering is an important source of opacity, the continuum mean intensity and the corresponding Thomson scattering emissivity are computed with the ALI method (for more details, see chapter 13 of HM14). Once background opacities have been evaluated, the non-LTE loop starts. It computes a self-consistent solution for level populations and radiative transfer equations. For each cell, the rate matrix Γ is built for a set of rays, for all wavelengths simultaneously. Once the rate matrix is known, a new value of the level populations is determined. Electron densities can be evaluated with the new values of the non-LTE populations. To avoid convergence issues, the evaluation of the electron density can be done every N iterations of the non-LTE loop.
The new populations are then compared to the previous populations using the following criterion of convergence: where is a user defined convergence threshold. The threshold is usually chosen between 10 −3 -10 −4 . If the maximum relative changes for each cell and each atom is below the convergence threshold the non-LTE loop stops. Otherwise, a new iteration starts with the previously computed populations. Excitation and ionisation temperatures for each transition of each atom are also checked for convergence. In general, transition temperatures converge faster than level populations.

Electron density
Electron densities for a gas mixture of hydrogen and metals cannot be determined analytically. The populations of atomic levels rely on the knowledge of the electron densities (for instance, through the Saha-Boltzmann equation at LTE). In turn, the electron density is a function of the population of atomic levels through their ionisation fraction. Therefore, electron densities have to be determined iteratively. Starting from an initial guess for the electron density, the populations of atomic levels are derived and the new ionisation fractions f is for level i in the ionisation stage s for each electron donors are evaluated. Then, from the new ionisation fractions, electron densities are computed. This iterative procedure is repeated until the relative change in electron densities drops below 10 −6 .
In our code we use a linearisation procedure similar to Eq. 17.88 of HM14. The initial guess for the electron density is given by the ionisation of hydrogen plus one metal (M) n 0 e = n e (H) + n e (M). Hydrogen ionisation yields and the metal ionisation where n H is the total number of hydrogen atoms, φ x the Saha-Boltzmann factor for the ion x, and α M is the abundance of the metal relative to hydrogen.

Collisional rates
The evaluation of the collisional rates appearing in the SEE (Eq. 9) is cumbersome. It generally requires collision calculations with quantum mechanics for which look-up tables of collisional rates are available now (Barklem 2016). However, analytical and semi-analytical recipes exist for faster evaluation of the collision matrix C ji (which is proportional to the collisional rates within a factor). We consider collisional excitation and ionisation by electrons for hydrogen atoms using Johnson (1972). For collisional excitation of metals (and helium) by electrons we use van Regemorter's fomula (van Regemorter 1962) and the impact parameter method (Seaton 1962). For ions, we follow Eq. 34 of Aller et al. (1982) and, for neutrals, we follow Seaton (1962). For collisional ionisation by electrons, we use Eq. 9.60 of HM14 and for collisions with hydrogen atoms, we use Drawin's formula (Eq. 9.62 of HM14).

Quadratures
One of the cornerstones in solving the SEE is the evaluation of the integrals appearing in Eq. 10. In the following, we describe how we performed wavelength and angular integrations. Angular quadrature for molecular lines transfer in MCFOST is done with the Monte Carlo method. For atomic lines, we used a set of fixed directions and weights uniformly distributed on the unit sphere such that integration over the sphere gives 4π. We used the directions and weights of type A quadratures from B. Carlson (whose calculations are described in Bruls et al. (1999)) and the directions and weights from Štěpán et al. (2020) for unpolarised radiation. These two types of quadrature points give similar results. By default we used type A quadrature of Carlson with 80 points sampling 4π steradians (Ibgui et al. 2013).
De Ceuster et al. (2020) used a similar angular quadrature method but with the quadrature points and weights determined by the HEALPix algorithm (Górski et al. 2005). For each cell of a model, starting from the centre of the cell (hereafter one point quadrature), the transfer equation is solved for all directions, while the radiative rates and the mean intensity are accumulated. Integrating the transfer equation from the centre of each cell may underestimate angular means and introduce some inaccuracy in the level populations because it only gives the mean intensity at that position. However, we do not know beforehand whether this inaccuracy is significant or not. Thus, we implemented two options to deal with this issue: first, several starting points for the angular quadrature scheme can be selected for each cell; and, second, Monte Carlo iterations can be done to properly sample each cell, in addition to the one point angular quadrature described above. In §4.3, we discuss these two options.
We replace the double integral appearing in Eq. 12 by a sum over wavelength points and directions as follows: where ω ray is the weight of the angular quadrature for a given direction (or ray) and ω λ the weight of a trapezoidal wavelength quadrature. In the case of a line transition, ω λ includes the normalisation of the line profile.

Benchmarking the code
The MCFOST code is intrinsically 3D, but in this paper we focus on 1D models that test the core of the method and allow us to validate our implementation with well-established 1D codes. While this is not the main application intended for our code, it also illustrates that MCFOST can now be used to generate a variety of stellar spectra. We will devote a forthcoming paper to the applications of our code to 2D and 3D geometries, with a particular emphasis on stellar magnetospheres. We used the codes TURBOspectrum  and RH (Uitenbroek 2001) as references for testing. The code MCFOST does not include a dedicated grid for 1D models, and we used the spherical grid instead. However, the spherical grid of MCFOST is log-scaled in the radial direction and cannot efficiently map the non-uniform grid from the 1D models. Therefore, for our benchmarks, we directly read the grid from the input models as RH and TURBOspectrum do. In that case, a cell is defined as the distance between two consecutive grid points. Because Eq. 1 is solved in MCFOST by summing up the intensity of each cell (i.e. spatial grid unit) weighted by the optical depth (see Eq. 19), the solution is more dependent on the grid resolution (i.e. on the size of cells). On the contrary, RH and TURBOspectrum formal solvers typically interpolate the source function in the initial grid, resulting in a solution that is highly accurate. To mitigate the impact of a lack of resolution on the accuracy of the solution, we decreased the size of the cells by adding more points between each point of the initial models.
The TURBOspectrum code is used to model spectra from cool evolved stars (Alvarez & Plez 1998;de Laverny et al. 2012) in synergy with the model atmosphere code MARCS (Gustafsson et al. 2008). This code works only at LTE but includes a wide library of molecules, the occupation probabilities formalism, and a proper treatment of hydrogen line broadening. To match the capabilities of our code, we slightly modified TURBOspectrum and removed molecular opacities, although, at the coolest temperature, neutral hydrogen density is dependent on the formation of molecules, such as H 2 .
The radiative transfer code RH is mainly used to model line formation in non-LTE conditions using the MALI method. Recent versions of RH have been used to model spectral lines taking into account the Zeeman effect and partial frequency redistribution in 3D cubes of the solar photosphere (de la Cruz Rodríguez et al. 2019). Recently, Criscuoli et al. (2020) benchmarked the RH code and showed its ability to model the solar irradiance with a good agreement with observations. The RH and MCFOST codes use similar treatment of background opacities and both employ the MALI method to solve for level populations. We compared our treatment of background opacities and level dissolution at LTE with TURBOspectrum. We used RH for benchmarking the MALI method on the non-LTE formation of hydrogen lines. We used the (1D) spherically symmetric grid of TURBOspectrum and RH for all tests.

Stellar photospheres
To test our opacity modules and background opacity calculations, we used LTE models of stellar photospheres from the Model ID T eff (K) log g (cm s −2 ) radius (R ) ξ (km s −1 ) LTE  Table 1: Stellar atmosphere models used for the benchmarking of our code. Models are taken from the MARCS database and correspond to the photosphere, except the model C taken from Fontenla et al. (1999). The first column indicates the designation of the model; the second, third, and fourth are the effective temperature, log surface gravity, and radius of the star, respectively. The fifth column gives the constant microturbulence, except for the FAL-C model, which has a depth varying microturbulence. The last column indicates if the model is computed assuming LTE.
MARCS database 5 (Gustafsson et al. 2008). The summary of each model is given in Table 1. The first model, sun, is the standard solar photosphere model from the MARCS code. The last two models, s8000 and s3500, are representative of the photospheres of hot and cool giants, respectively. All models have standard chemical composition and are computed assuming spherical symmetry, except for the solar model, which was computed using the plane-parallel approximation.

Continuum radiation
We compared the stellar continuum computed by the three codes for the stellar photosphere models (see Table 1). Figure 2 shows the continuum flux and the discrepancy function δF/F for each model. The agreement between RH and MCFOST is excellent, being at or below 1% at most wavelengths. For models sun (Fig.  2a) and s3500 (Fig. 2e), the largest discrepancies are due to interpolation errors at the shortest wavelengths. For the model s8000 (Fig. 2c) the agreement between RH and MCFOST is also at the percent level, except at the Balmer jump (about 350 nm), where differences are larger (again owing to the steep slope of the emission), but remain below 30%. Discrepancies between MCFOST and TURBOspectrum are of the same order as those between MCFOST and RH. The largest discrepancy for the model s3500, of the order of 10%, is due to the H − continuum. In TURBOspectrum, the H − density is self-consistently determined by solving chemical equilibrium equations including hydrogen in its atomic and molecular forms, leading to a slightly different value than in RH and MCFOST. For the model s8000, the largest discrepancy occurs at the Balmer jump and is of the order of 40%. As the largest discrepancy with RH occurs at the same location we might not exclude numerical resolution problems. The agreement between RH and TURBOspectrum is of the same order as MCFOST and TURBOspectrum. Furthermore, we note that for this model, continuum scattering becomes non-negligible and is automatically included in TURBOspectrum 6 , but not in MC-FOST, thereby impacting the shape of the continuum.
The agreement between MCFOST and TURBOspectrum remains excellent when level dissolution is taken into account (Fig.  2 right panels). The impact of level dissolution is clearly visible at the Balmer jump where it smoothes the abrupt discontinuity towards redder wavelengths. The shallower spectrum results in an improved agreement between TURBOspectram and MC-FOST for model s8000 around the Balmer jump.

Velocity fields
Although the impact of velocity fields on line formation will be addressed in a forthcoming paper, in this section we show an example of a solar photosphere with a radial velocity V r given by where v 0 is the velocity at the inner point (bottom of the photosphere), V inf a velocity such that max(V r ) = 500 km s −1 , and β the exponent of the velocity law. In our calculations, v 0 = 9 km s −1 and β = 0.5.
We compared the result of our code with RH since TUR-BOspectrum does not deal with macroscopic velocity fields. For comparison, we implemented a solver for the velocity field in RH because the spherically symmetric version does not handle velocity fields. However, unlike MCFOST, the velocity fields between two points are not interpolated. Figure 3 shows the difference between MCFOST and RH for the solar photosphere when a velocity field is included. While the continuum radiation is similar to that of Fig. 2a, lines are impacted significantly by the large velocity gradient, as expected. The differences between the two codes are negligible, although the lack of resolution in RH is noticeable.  Fig. 2: Continuum flux as a function of wavelengths for the photospheric models without (left panels) and with (right panels) level dissolution. In each panel, the upper window shows the flux from RH, TURBOspectrum, and MCFOST in cyan (thin line), orange (dashed), and black (thick line), respectively. The lower window shows the difference between RH and MCFOST (thick dark grey lines), and between TURBOspectrum and MCFOST (dashed light grey lines). As RH does not include level dissolution, it is not shown in the right figures. In figure 2c, the continuum flux computed by RH stops at about 800 nm, leading to incorrect evaluation of the error at this edge point.
We also tested the treatment of the same model with no radial velocity but a constant rotational velocity of 300 km s −1 instead. Figure 4 shows the Hα line flux as a function of inclination. As expected, the impact of rotation on the line shape increases with inclination, from no effect when the star is seen pole-on to maximum broadening when the star is equator-on. ig. 4: Hα flux variation with inclination for a solar photospheric model with rotation. The flux at inclinations of 0 • , 45 • , and 90 • are shown in black, green, and red, respectively. An inclination of 0 • means that the star is seen pole on.

Solar atmosphere model
Although a LTE model of the solar photosphere is adequate to model most solar lines, it fails to reproduce lines formed beyond the photosphere. The upper solar atmosphere is a high temperature and low-density region above the photosphere where non-LTE effects dominate the line formation. In the following we focus on the Lyman α (Lyα) and Hα lines as they form in the upper atmosphere (e.g. Figure 1 of Vernazza et al. 1981) and are thus impacted by non-LTE effects. We used a 6-level hydrogen atom, with five bound levels and one continuum level, which is the ground state of H II. Energy levels and transition frequencies are from Johnson (1972). Bound-free cross-sections are computed using Kramer's formula and collisional rates are evaluated following Johnson (1972). For the Lyman α and Hα lines, the absorption profiles are given by a Voigt function. For the other lines, we used a Gaussian profile. We used model C of Fontenla et al. (1999) as a standard model of the solar atmosphere including the chromosphere and transition region.
Overall, the agreement between RH and MCFOST is excellent. Figure 5 shows the ratio b between non-LTE and LTE populations in model C. In the photosphere (below the temperature minimum), the populations are mostly at LTE with a b ratio of a few. In the deep photosphere, b is close to 1. From the temperature minimum to the transition region (the chromosphere), the populations start to depart from their LTE values. In the lower corona, the populations are very far from LTE, with a b factor greater than 10 6 for the ground state of HI (level 1 in Fig. 5). The formation regions of the two lines are consistent with the earlier work of Vernazza et al. (1981). Contribution functions (i.e. regions of formation) of the Lyα and Hα lines are shown in Figure 6.   Fig. 6: Line contribution function, dI dh (response function to height variation), at disc centre. The contribution function is drawn as a function of the density in the atmosphere and distance from line centre (in nm). Lighter areas show where the contribution function peaks. We indicate the different layers of the solar atmosphere in each panel.  At all wavelengths, the discrepancy is below 1%, except in the core of some lines where it reaches 5%. In the figures, interpolation errors create glitches in the discrepancy functions. However, real differences exist in the core of strong lines, such as the Lyα line, where the mismatch can reach 20%-25%. Figure 8 shows the non-LTE flux of the Lyα line (top panel) and the flux of the Hα line (bottom panel). Although these differences are not critical, using one of the two options discussed in §3.8 to improve the angular quadrature leads to a better agreement between the Lyman α line computed by RH and MCFOST.

Discussion on the angular quadrature
In §3.8, we presented the method we used to perform angular quadratures. These quadratures are important since they are used to evaluate the radiative rates, which in turn determine the level populations. As stated earlier, angular quadratures are performed for a set of fixed rays (i.e. directions) starting from each cell centre. In the following, we test option (i) of §3.8, that is performing the angular quadrature not only from cell centres but also at N random positions in the cells. As in section 4.2, we compute the non-LTE Lyα line flux in model C. Further, we use the original grid of the 1D model, that is without additional points. We randomly chose 99 additional positions in each cell. We then kept these positions fixed during the non-LTE loop to avoid introducing Monte Carlo noise in the solution. For each of these 100 positions, the angular quadrature was performed for 80 rays resulting in a total of 8 000 rays. Thus, for each cell, we obtained 100 values of the mean intensity and radiative rates, each at a different location inside the cell. The mean intensity and the radiative rates in each cell is just the arithmetic mean of these values. Finally, we interpolated the level populations on the same grid used in §4.2 (i.e. with a higher resolution). Because now we have a better estimation of the radiative rates for each cell, the error in the numerical integration of Eq. 1 dominates the discrepancy between RH and MCFOST. In figure 9 we show the Lyα flux computed with this method compared to the profile shown in in Fig. 8a. The agreement between RH and MCFOST is substantially improved, with a maximum discrepancy below 5%, five times better than with only one position for the angular quadrature. Still we note that, even if the core is better reproduced, the wings are not, although the maximum error is small. Similar results are obtained by performing a purely Monte Carlo step after the one point quadrature, that is we randomly selected 1000 positions and directions ( §3.8, option (ii)). The main difference between §3.8 option (i) and §3.8 option (ii) lies in the execution time of the code. The latter approach is eight times faster than the former for an equivalent accuracy. However, the populations computed with §3.8 option (ii) have Monte Carlo noise.

Conclusions
In this paper, we tested our code against spherically symmetric models of stellar atmospheres, representing a range of physical plasma conditions. We tested background opacity calculations with lines merging close to series limits using the occupation probabilities formalism. The agreement between MCFOST-art and both TURBOspectrum and RH is excellent, of the order of 1% or below at most wavelengths. Still, a few discrepancies are present, arising from the different treatment of opacities at a few critical wavelengths (e.g. at the Balmer jump or at the H − minimum). The code has also been successfully tested with vertical and rotational velocities. The proper behaviour of all spectral lines is recovered in models with non-zero velocity fields. We performed non-LTE calculations of the solar Lyman α and Hα lines formation. These calculations were compared with calculations performed with the RH code. Line formation regions and non-LTE effects are reproduced well by our code compared to earlier studies and observations. While the discrepancy in the flux between RH and MCFOST can reach 25% in the core of Lyα, the discrepancy drops below 1% around the Hα line and for most other wavelengths in the spectrum. Furthermore, we showed that improving the accuracy of the angular quadrature scheme decreases this discrepancy by a factor of five.
Although we only tested the code against 1D models, the opacity modules and the non-LTE loop are geometry independent. These modules are therefore applicable to multidimensional models. The MCFOST code is 3D in essence and the solution of the radiative transfer equation is fully performed in 3D. Further applications of this new code to 2D and 3D geometries will be discussed in a forthcoming paper with a particular focus on stellar magnetospheres.