petitRADTRANS.retrieval
=======================

.. py:module:: petitRADTRANS.retrieval


Submodules
----------

.. toctree::
   :maxdepth: 1

   /autoapi/petitRADTRANS/retrieval/data/index
   /autoapi/petitRADTRANS/retrieval/models/index
   /autoapi/petitRADTRANS/retrieval/parameter/index
   /autoapi/petitRADTRANS/retrieval/preparing/index
   /autoapi/petitRADTRANS/retrieval/psis/index
   /autoapi/petitRADTRANS/retrieval/retrieval/index
   /autoapi/petitRADTRANS/retrieval/retrieval_config/index
   /autoapi/petitRADTRANS/retrieval/utils/index


Classes
-------

.. autoapisummary::

   petitRADTRANS.retrieval.Retrieval
   petitRADTRANS.retrieval.RetrievalConfig


Package Contents
----------------

.. py:class:: Retrieval(configuration: petitRADTRANS.retrieval.retrieval_config.RetrievalConfig, output_directory: str = os.getcwd(), use_mpi: bool = False, evaluate_sample_spectra: bool = False, ultranest: bool = False, sampling_efficiency: float = None, constant_efficiency_mode: str = None, n_live_points: int = None, resume: bool = False, corner_plot_names: list[str] = None, use_prt_plot_style: bool = True, test_plotting: bool = False, uncertainties_mode: str = 'default', print_log_likelihood_for_debugging: bool = False, generate_mock_data: bool = False)

   Implement the retrieval method using petitRADTRANS and pymultinest.

   A RetrievalConfig object is passed to this class to describe the retrieval data, parameters
   and priors. The run() method then uses pymultinest to sample the parameter space, producing
   posterior distributions for parameters and bayesian evidence for models.
   Various useful plotting functions have also been included, and can be run once the retrieval is
   complete.

   Args:
       configuration : RetrievalConfig
           A RetrievalConfig object that describes the retrieval to be run. This is the user
           facing class that must be setup for every retrieval.
       output_directory : Str
           The directory in which the output folders should be written
       evaluate_sample_spectra : Bool
           Produce plots and data files for random samples drawn from the outputs of pymultinest.
       ultranest : bool
           If true, use Ultranest sampling rather than pymultinest. Provides a more accurate evidence estimate,
           but is significantly slower.
       corner_plot_names : List(Str)
           List of additional retrieval names that should be included in the corner plotlib.
       use_prt_plot_style : Bool
           Use the petitRADTRANS plotting style as described in style.py. Recommended to
           turn this parameter to false if you want to use interactive plotting, or if the
           test_plotting parameter is True.
       test_plotting : Bool
           Only use when running locally. A boolean flag that will produce plots
           for each sample when pymultinest is run.
       uncertainties_mode : Str
           Uncertainties handling method during the retrieval.
               - "default": the uncertainties are fixed.
               - "optimize": automatically optimize for uncertainties, following Gibson et al. 2020
                 (https://doi.org/10.1093/mnras/staa228).
               - "retrieve": uncertainties are scaled with a coefficient, which is retrieved.
               - "retrieve_add": a fixed scalar is added to the uncertainties, and is retrieved.
       print_log_likelihood_for_debugging : bool
           If True, the current log likelihood of a forward model run will be printed to the console.
       generate_mock_data : bool
           If True, the retrieval will generate a mock data set by sampling the prior distributions and bring
           it into the exact same shape as the input data. This is useful for testing the retrieval setup in input
           = output tests. The mock data will be saved in the mock_data folder in the run directory, with the
           following file names: data.name + '_mock_data.dat'.


   .. py:attribute:: configuration


   .. py:attribute:: ultranest
      :value: False



   .. py:attribute:: use_mpi
      :value: False



   .. py:attribute:: uncertainties_mode
      :value: 'default'



   .. py:attribute:: print_log_likelihood_for_debugging
      :value: False



   .. py:attribute:: generate_mock_data
      :value: False



   .. py:attribute:: output_directory


   .. py:attribute:: corner_files
      :value: None



   .. py:attribute:: best_fit_spectra


   .. py:attribute:: best_fit_parameters


   .. py:attribute:: chi2
      :value: None



   .. py:attribute:: posterior_sample_spectra


   .. py:attribute:: test_plotting
      :value: False



   .. py:attribute:: pt_plot_mode
      :value: False



   .. py:attribute:: evaluate_sample_spectra
      :value: False



   .. py:attribute:: sampling_efficiency
      :value: None



   .. py:attribute:: constant_efficiency_mode
      :value: None



   .. py:attribute:: n_live_points
      :value: None



   .. py:attribute:: resume
      :value: False



   .. py:attribute:: analyzer
      :value: None



   .. py:attribute:: samples


   .. py:attribute:: param_dictionary


   .. py:attribute:: prt_plot_style
      :value: True



   .. py:attribute:: path


   .. py:method:: _check_errors()


   .. py:method:: _data_are_valid(data=None)


   .. py:method:: _error_check_model_function()


   .. py:method:: _rebin_opacities(resolution: float)


   .. py:method:: _run_ultranest(n_live_points, log_z_convergence, step_sampler, warmstart_max_tau, resume, max_iters, frac_remain, l_epsilon)

      Run mode for the class. Uses ultranest to sample parameter space
      and produce standard outputs.

      Args:
          n_live_points : Int
              The minimum number of live points to use for the Ultranest reactive sampler.
          log_z_convergence : float
              The convergence criterion on log z.
          step_sampler : bool
              Use a step sampler to improve the efficiency in ultranest.
          max_iters : int
              Maximum number of sampling iterations. If 0, will continue until convergence criteria are satisfied.
          frac_remain : float
              Ultranest convergence criterion. Halts integration if live point weights are below the specified value.
          l_epsilon : float
              Ultranest convergence criterion. Use with noisy likelihoods. Halts integration if live points are
              within l_epsilon.
          resume : bool
              Continue existing retrieval. If FALSE THIS WILL OVERWRITE YOUR EXISTING RETRIEVAL.



   .. py:method:: build_param_dict(sample: numpy.typing.NDArray[numpy.floating], free_param_names: list[str]) -> dict[str, petitRADTRANS.retrieval.parameter.Parameter]

      This function builds a dictionary of parameters that can be passed to the
      model building functions. It requires a numpy array with the same length
      as the number of free parameters, and a list of all the parameter names
      in the order they appear in the array. The returned dictionary will contain
      all of these parameters, together with the fixed retrieval parameters.

      Args:
          sample : numpy.ndarray
              An array or list of free parameter values
          free_param_names : list(string)
              A list of names for each of the free parameters.
      Returns:
          parameters : dict
              A dictionary of Parameters, with values set to the values
              in sample.



   .. py:method:: calculate_forward_model(parameters=None, data=None, pt_plot_mode: bool = False, amr: bool = False, copy_configuration_parameters: bool = True, **kwargs)

      Calculate the forward model associated with the given data, for the given parameters.

      Args:
          parameters:
              Parameters of the forward models.
              Can be a dictionary with parameter names as keys, or a string, or None.
              Possible string values are:
                  - 'best fit': return the forward model with the retrieved best fit parameters.
                  - 'median': return the forward model with the retrieved median parameters.
                  - 'quantile': return the forward model with retrieved parameters at the given quantile.
              If ``parameter='quantile'``, then a ``quantile`` (float) keyword argument must be added.
              If None, the free parameters of the retrieval are set to their prior mid-range value.
          data:
              Can be a string, or a dictionary with data name as keys and Data objects as values, or None.
              If None, the forward models of all the data in the retrieval configuration are calculated.
          pt_plot_mode:
              If True, the model function should return the pressure and temperature arrays before computing the flux.
          amr:
              If True, use an adaptive high resolution pressure grid around the location of cloud condensation.
              This will increase the size of the pressure grid by a constant factor that can be adjusted in the
              setup_pres function.
          copy_configuration_parameters:
              If True, copy the configuration parameters to prevent unwanted modifications.
      Returns:
          A dictionary with the outputs of the forward models for the requested data, or, if data is a string, the
          output of the forward model corresponding to these data.



   .. py:method:: from_data(data: dict[str, petitRADTRANS.retrieval.data.Data], retrieved_parameters: dict[str, dict], retrieval_name: str = 'retrieval_name', run_mode: str = 'retrieval', amr: bool = False, output_directory: str = '', use_mpi: bool = False, evaluate_sample_spectra: bool = False, ultranest: bool = False, corner_plot_names: list[str] = None, use_prt_plot_style: bool = True, test_plotting: bool = False, uncertainties_mode: str = 'default', scattering_in_emission: bool = False, pressures: numpy.ndarray = None)
      :classmethod:


      Instantiate a Retrieval object with a dictionary of Data objects.
      Intended to be used in couple with the SpectralModel.init_data function.

      The RetrievalConfig object is automatically generated. No fixed parameters will be used, those must be stored
      in their respective Data.model_generating_function. This is automatically done when using the
      SpectralModel.init_data function.

      Args:
          data : Dict
              A dictionary with data names as keys and Data objects as values.
          retrieved_parameters : Dict
              A dictionary with retrieved parameter names as keys and dictionaries as values. Those sub-dictionaries
              must have keys 'prior_parameters' and 'prior_type'. This can also be a list of RetrievalParameter
              objects.
          retrieval_name : Str
              Name of this retrieval. Make it informative so that you can keep track of the outputs!
          run_mode : Str
              Can be either 'retrieval', which runs the retrieval normally using pymultinest,
              or 'evaluate', which produces plots from the best fit parameters stored in the
              output post_equal_weights file.
          amr : Bool
              Use an adaptive high resolution pressure grid around the location of cloud condensation.
              This will increase the size of the pressure grid by a constant factor that can be adjusted
              in the setup_pres function.
          output_directory : Str
              The directory in which the output folders should be written
          use_mpi : bool
              # TODO complete docstring
          evaluate_sample_spectra : Bool
              Produce plots and data files for random samples drawn from the outputs of pymultinest.
          ultranest : bool
              If true, use Ultranest sampling rather than pymultinest. Provides a more accurate evidence estimate,
              but is significantly slower.
          corner_plot_names : List(Str)
              List of additional retrieval names that should be included in the corner plotlib.
          use_prt_plot_style : Bool
              Use the petitRADTRANS plotting style as described in style.py. Recommended to
              turn this parameter to false if you want to use interactive plotting, or if the
              test_plotting parameter is True.
          test_plotting : Bool
              Only use when running locally. A boolean flag that will produce plots
              for each sample when pymultinest is run.
          uncertainties_mode : Str
              Uncertainties handling method during the retrieval.
                  - "default": the uncertainties are fixed.
                  - "optimize": automatically optimize for uncertainties, following Gibson et al. 2020
                    (https://doi.org/10.1093/mnras/staa228).
                  - "retrieve": uncertainties are scaled with a coefficient, which is retrieved.
                  - "retrieve_add": a fixed scalar is added to the uncertainties, and is retrieved.
          scattering_in_emission : Bool
              If using emission spectra, turn scattering on or off.
          pressures : numpy.ndarray
              A log-spaced array of pressures over which to retrieve. 100 points is standard, between
              10^-6 and 10^3.

      Returns:
          An Retrieval object instance.



   .. py:method:: generate_retrieval_summary(stats: dict = None) -> None

      This function produces a human-readable text file describing the retrieval.
      It includes all the fixed and free parameters, the limits of the priors (if uniform),
      a description of the data used, and if the retrieval is complete, a summary of the
      best fit parameters and model evidence.

      Args:
          stats : dict
              A Pymultinest stats dictionary, from Analyzer.get_stats().
              This contains the evidence and best fit parameters.



   .. py:method:: get_analyzer(ret_name: str = '')

      Get the PMN analyzer from a retrieval run

      This function uses gets the PMN analyzer object
      for the current retrieval_name by default,
      though any retrieval_name in the out_PMN folder can
      be passed as an argument - useful for when you're
      comparing multiple similar models.

      Args:
          ret_name : string
              The name of the retrieval that prepends all the PMN
              output files.



   .. py:method:: get_base_figure_name() -> str


   .. py:method:: get_best_fit_chi2(samples: numpy.typing.NDArray[numpy.floating]) -> float

      Get the 𝛘^2 of the best fit model - removing normalization term from log L

      Args:
          samples : numpy.ndarray
              An array of samples and likelihoods taken from a post_equal_weights file.



   .. py:method:: get_best_fit_likelihood(samples: numpy.typing.NDArray[numpy.floating], print_value: bool = True) -> tuple[float, int]
      :staticmethod:


      Get the log likelihood of the best fit model

      Args:
          samples : numpy.ndarray
              An array of samples and likelihoods taken from a post_equal_weights file.
          print_value : bool
              If True, print the best fit likelihood value.



   .. py:method:: get_best_fit_model(best_fit_params: numpy.typing.NDArray[numpy.floating], parameters_read: list[str], ret_name: str = None, contribution: bool = False, prt_reference: str = None, model_generating_function: Callable = None, refresh: bool = True, mode: str = 'bestfit', save: bool = True)

      This function uses the best fit parameters to generate a pRT model that spans the entire wavelength
      range of the retrieval, to be used in plots.

      Args:
          best_fit_params : numpy.ndarray
              A numpy array containing the best fit parameters, to be passed to get_max_likelihood_params
          parameters_read : list
              A list of the free parameters as read from the output files.
          ret_name : str
              If plotting a fit from a different retrieval, input the retrieval name to be included.
          contribution : bool
              If True, calculate the emission or transmission contribution function as well as the spectrum.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          refresh : bool
              If True (default value) the .npy files in the evaluate_[retrieval_name] folder will be replaced
              by recalculating the best fit model. This is useful if plotting intermediate results from a
              retrieval that is still running. If False no new spectrum will be calculated and the plotlib will
              be generated from the .npy files in the evaluate_[retrieval_name] folder.
          mode : str
              If "best_fit", will use the maximum likelihood parameter values to calculate the best fit model
              and contribution. If "median", uses the median parameter values.
          save : bool
              If True, save the best fit spectrum.
      Returns:
          best_fit_wavelengths : numpy.ndarray
              The wavelength array of the best fit model
          best_fit_spectrum : numpy.ndarray
              The emission or transmission spectrum array, with the same shape as best_fit_wavelengths



   .. py:method:: get_best_fit_parameters(return_max_likelihood: bool = False)

      Get the retrieved best fit parameters.

      Args:
          return_max_likelihood:
              if True, also return the max (log) likelihood and the chi2.

      Returns:
          A dict containing the free parameter names as keys and their retrieved best-fit values as values.
          If return_max_likelihood is True, return in addition the max (log) likelihood and the chi2.



   .. py:method:: get_chi2(sample: numpy.typing.NDArray[numpy.floating]) -> float

      Get the 𝛘^2 of the given sample relative to the data - removing normalization term from log L

      Args:
          sample : numpy.ndarray
              A single sample and likelihood taken from a post_equal_weights file



   .. py:method:: get_chi2_normalisation(sample: numpy.typing.NDArray[numpy.floating]) -> float

      Get the 𝛘^2 normalization term from log L

      Args:
          sample : numpy.ndarray
              A single sample and likelihood taken from a post_equal_weights file



   .. py:method:: get_data_model(cube, dd, retrieve_uncertainties=False)


   .. py:method:: get_elpd_per_datapoint(ret_name: str = None)


   .. py:method:: get_evidence(ret_name: str = '') -> tuple[float, float]

      Get the log10 Z and error for the retrieval

      This function uses the pymultinest analyzer to
      get the evidence for the current retrieval_name
      by default, though any retrieval_name in the
      out_PMN folder can be passed as an argument -
      useful for when you're comparing multiple similar
      models. This value is also printed in the summary file.

      Args:
          ret_name : string
              The name of the retrieval that prepends all the PMN
              output files.



   .. py:method:: get_full_range_model(parameters: dict[str, petitRADTRANS.retrieval.parameter.Parameter], model_generating_function: Callable = None, contribution: bool = False, prt_object: petitRADTRANS.radtrans.Radtrans = None, prt_reference: petitRADTRANS.retrieval.data.Data = None) -> tuple

      Retrieve a full wavelength range model based on the given parameters.

      Parameters:
          parameters (dict): A dictionary containing parameters used to generate the model.
          model_generating_function (callable, optional): A function to generate the model.
              Defaults to None.
          contribution (bool, optional): Return the emission or transmission contribution function.
              Defaults to False.
          prt_object (object, optional): RadTrans object for calculating the spectrum.
              Defaults to None.
          prt_reference (object, optional): Reference Data object for calculating the spectrum.
              Defaults to None.

      Returns:
          object: The generated full range model.



   .. py:method:: get_log_likelihood_per_datapoint(samples_use: numpy.typing.NDArray[numpy.floating], ret_name: str = None)


   .. py:method:: get_mass_fractions(sample: numpy.typing.NDArray[numpy.floating], parameters_read: list[str] = None)

      This function returns the mass fraction abundances of each species as a function of pressure

      Args:
          sample : numpy.ndarray
              A sample from the pymultinest output, the abundances returned will be
              computed for this set of parameters.
          parameters_read : list
              A list of the free parameters as read from the output files.
      Returns:
          abundances : dict
              A dictionary of abundances. The keys are the species name,
              the values are the mass fraction abundances at each pressure
          MMW : numpy.ndarray
              The mean molecular weight at each pressure level in the atmosphere.



   .. py:method:: get_max_likelihood_params(best_fit_params: numpy.typing.NDArray[numpy.floating], parameters_read: list[str])

      This function converts the sample from the post_equal_weights file with the maximum
      log likelihood, and converts it into a dictionary of Parameters that can be used in
      a model function.

      Args:
          best_fit_params : numpy.ndarray
              An array of the best fit parameter values (or any other sample)
          parameters_read : list
              A list of the free parameter names as read from the output files.



   .. py:method:: get_median_params(samples: numpy.typing.NDArray[numpy.floating], parameters_read: list[str], return_array=False)

      This function builds a parameter dictionary based on the median value
      of each parameter. This will update the best_fit_parameter dictionary!
      # TODO fix docstring
      Args:
          samples : numpy.ndarray
              An array of samples and likelihoods taken from a post_equal_weights file.
          parameters_read : list
              A list of the free parameter names as read from the output files.
          return_array : bool
              If True, also return the median parameters as an array



   .. py:method:: get_parameters_prior_mid_range_values() -> numpy.typing.NDArray[numpy.floating]

      Return the prior mid-range values of the free parameters.
              



   .. py:method:: get_quantile_parameters(quantile: float) -> dict[str, float]

      Return the given quantile of the retrieved parameters' posteriors.
      For example, if quantile = 0.84, the 84th percentile (~+1 sigma) of the retrieved parameters' posterior is
      returned.

      Args:
          quantile:
              Quantile of the retrieved parameter's posterior.

      Returns:
          A dict with the free parameter names as keys and their value at the requested quantile.



   .. py:method:: get_reduced_chi2(sample, subtract_n_parameters=False, verbose=False, show_chi2=False)

      Get the 𝛘^2/DoF of the given model - divide chi^2 by DoF or number of wavelength channels.

      Args:
          sample : numpy.ndarray
              A single sample and likelihoods taken from a post_equal_weights file
          subtract_n_parameters : bool
              If True, divide the Chi2 by the degrees of freedom (n_data - n_parameters). If False,
              divide only by n_data
          verbose : bool
              If True, display the calculated best fit reduced chi^2, and also the best fit chi^2 if show_chi2 is True
          show_chi2 : bool
              If True, additionally display the calculated best fit chi^2 if verbose is True



   .. py:method:: get_reduced_chi2_from_model(wlen_model, spectrum_model, parameters, subtract_n_parameters=False, verbose=False, show_chi2=False)

      Get the 𝛘^2/DoF of the supplied spectrum - divide chi^2 by DoF

      Args:
          wlen_model : np.ndarray
              The wavelength grid of the model spectrum in micron.
          spectrum_model : np.ndarray
              The model flux in the same units as the data.
          subtract_n_parameters : bool
              If True, divide the Chi2 by the degrees of freedom (n_data - n_parameters). If False,
              divide only by n_data
          verbose : bool
              If True, display the calculated best fit chi^2 and reduced chi^2
          show_chi2 : bool
              If True, additionally display the calculated best fit chi^2 if verbose is True



   .. py:method:: get_samples(ultranest: bool = False, names: list[str] = None, output_directory: str = os.getcwd(), ret_names: list[str] = None) -> tuple[dict[str, numpy.typing.NDArray[numpy.floating]], dict[str, list[str]]]

      Get the samples of the requested retrievals.

      Args:
          ultranest:
              If True, assume that the retrievals are Ultranest retrievals.
          names:
              Names of the retrievals from which to get the samples.
          output_directory :
              Directories in which the retrievals are stored.
          ret_names : list(str)
              Additional list of retrieval names. Used if multiple retrievals are to be included in a corner plot.

      Returns:
          A dict containing the retrieval names as keys and the samples of each requested retrievals as values, and
          a dict containing the retrieval names as keys and the free parameters names as values.



   .. py:method:: get_samples_dict(return_likelihood: bool = False) -> dict[str, numpy.typing.NDArray[numpy.floating]]

      Return the samples of this retrieval as a dict.

      Args:
          return_likelihood:
              If True, the samples dictionary also contains the log likelihood of each sample.
      Returns:
          A dict containing the free parameters names as keys, and their sampled values as values.



   .. py:method:: get_special_parameters() -> set[str]
      :staticmethod:



   .. py:method:: get_volume_mixing_ratios(sample: numpy.typing.NDArray[numpy.floating], parameters_read: list[str] = None)

      This function returns the VMRs of each species as a function of pressure.

      Args:
          sample : numpy.ndarray
              A sample from the pymultinest output, the abundances returned will be
              computed for this set of parameters.
          parameters_read : list
              A list of the free parameters as read from the output files.
      Returns:
          vmr : dict
              A dictionary of abundances. The keys are the species name,
              the values are the mass fraction abundances at each pressure
          MMW : numpy.ndarray
              The mean molecular weight at each pressure level in the atmosphere.



   .. py:method:: log_likelihood(cube: numpy.typing.NDArray[numpy.floating], ndim: int = 0, nparam: int = 0, log_l_per_datapoint_dict: dict = None, return_model: bool = False)

      pyMultiNest required likelihood function.

      This function wraps the model computation and log-likelihood calculations
      for pyMultiNest to sample. If PT_plot_mode is True, it will return
      only the pressure and temperature arrays rather than the wavelength
      and flux. If run_mode is 'evaluate', it will save the provided sample to the
      best-fit spectrum file, and add it to the best_fit_specs dictionary.
      If evaluate_sample_spectra is true, it will store the spectrum in
      posterior_sample_specs.

      Args:
          cube : numpy.ndarray
              The transformed unit hypercube, providing the parameter values
              to be passed to the model_generating_function.
          ndim : int
              The number of dimensions of the problem
          nparam : int
              The number of parameters in the fit.
          log_l_per_datapoint_dict : dict
              Dictionary with instrument-entries. If provided, log likelihood
              per datapoint is appended to existing list.
          return_model : bool
              If True, return the generated model in addition to the log-likelihood.
              This is intended for debugging purposes, and should stay False in a normal retrieval.

      Returns:
          log_likelihood : float
              The (negative) log likelihood of the model given the data.



   .. py:method:: prior(cube: numpy.typing.NDArray[numpy.floating], ndim: int = 0, nparams: int = 0) -> numpy.typing.NDArray[numpy.floating]

      pyMultinest Prior function. Transforms unit hypercube into physical space.



   .. py:method:: prior_ultranest(cube: numpy.typing.NDArray[numpy.floating]) -> numpy.typing.NDArray[numpy.floating]

      pyMultinest Prior function. Transforms unit hypercube into physical space.



   .. py:method:: run(sampling_efficiency: float = 0.8, const_efficiency_mode: bool = False, n_live_points: int = 4000, log_z_convergence: float = 0.5, step_sampler: bool = False, warmstart_max_tau: float = 0.5, n_iter_before_update: int = 50, resume: bool = False, max_iters: int = 0, frac_remain: float = 0.1, l_epsilon: float = 0.3, error_checking: bool = True, force_serial_error_checking: bool = False, seed: int = -1) -> None

      Run mode for the class. Uses pynultinest to sample parameter space
      and produce standard PMN outputs.

      Args:
          sampling_efficiency : Float
              pymultinest sampling efficiency. If const efficiency mode is true, should be set to around
              0.05. Otherwise, it should be around 0.8 for parameter estimation and 0.3 for evidence
              comparison.
          const_efficiency_mode : Bool
              pymultinest constant efficiency mode
          n_live_points : Int
              Number of live points to use in pymultinest, or the minimum number of live points to
              use for the Ultranest reactive sampler.
          log_z_convergence : float
              If ultranest is being used, the convergence criterion on log z.
          step_sampler : bool
              Use a step sampler to improve the efficiency in ultranest.
          warmstart_max_tau : float
              Warm start allows accelerated computation based on a different but similar UltraNest run.
          n_iter_before_update : int
              Number of live point replacements before printing an update to a log file.
          max_iters : int
              Maximum number of sampling iterations. If 0, will continue until convergence criteria are satisfied.
          frac_remain : float
              Ultranest convergence criterion. Halts integration if live point weights are below the specified value.
          l_epsilon : float
              Ultranest convergence criterion. Use with noisy likelihoods. Halts integration if live points are
              within l_epsilon.
          resume : bool
              Continue existing retrieval. If FALSE THIS WILL OVERWRITE YOUR EXISTING RETRIEVAL.
          error_checking : bool
              Test the model generating function for typical errors. ONLY TURN THIS OFF IF YOU KNOW WHAT YOU'RE DOING!
          force_serial_error_checking : bool
              If True, error checking will be performed process-by-process, instead of with all processes at once.
              This can prevent memory overflow.
          seed : int
              Random number generator seed, -ve value for seed from the system clock (for reproducibility)



   .. py:method:: sample_teff(sample_dict, param_dict, ret_names=None, nsample=None, resolution=40)

      This function samples the outputs of a retrieval and computes Teff
      for each sample. For each sample, a model is computed at low resolution,
      and integrated to find the total radiant emittance, which is converted into
      a temperature using the stefan boltzmann law: $j^{\star} = \sigma T^{4}$.
      Teff itself is computed using util.calc_teff.

      Args:
          sample_dict : dict
              A dictionary, where each key is the name of a retrieval, and the values
              are the equal weighted samples.
          param_dict : dict
              A dictionary where each key is the name of a retrieval, and the values
              are the names of the free parameters associated with that retrieval.
          ret_names : Optional(list(string))
              A list of retrieval names, each should be included in the sample_dict.
              If left as none, it defaults to only using the current retrieval name.
          nsample : Optional(int)
              The number of times to compute Teff. If left empty, uses the "take_PTs_from"
              plot_kwarg. Recommended to use ~300 samples, probably more than is set in
              the kwarg!
          resolution : int
              The spectra resolution to compute the models at. Typically, this should be very
              low in order to enable rapid calculation.
      Returns:
          temperature_dict : dict
              A dictionary with retrieval names for keys, and the values are the calculated
              values of Teff for each sample.



   .. py:method:: save_best_fit_outputs(parameters, only_return_best_fit_spectra=False)


   .. py:method:: save_best_fit_outputs_external_variability(parameters, only_return_best_fit_spectra=False)


   .. py:method:: save_mass_fractions(sample_dict, parameter_dict, rets=None)

      Save mass fractions and line absorber species information for specified retrievals.

      Parameters:
      - self: The instance of the class containing the function.
      - sample_dict (dict): A dictionary mapping retrieval names to lists of samples.
      - parameter_dict (dict): A dictionary mapping retrieval names to parameter values.
      - rets (list, optional): List of retrieval names to process. If None, uses the default retrieval name.

      Returns:
      - mass_fractions (numpy.ndarray): Array containing mass fractions for each sample and species.

      The function processes the specified retrievals and saves the corresponding mass fracs and line absorber species
      information to files in the output directory. If 'rets' is not provided, the default retrieval name is used.
      The mass fractinos are saved in a numpy file, and the line absorber species are saved in a JSON file.

      Example usage:
          ```
          sample_dict = {'Retrieval1': [...], 'Retrieval2': [...]}
          parameter_dict = {'Retrieval1': {...}, 'Retrieval2': {...}}
          mass_fractions = save_mass_fractions(sample_dict, parameter_dict)
          ```



   .. py:method:: save_volume_mixing_ratios(sample_dict, parameter_dict, rets=None)

      Save volume mixing ratios (VMRs) and line absorber species information for specified retrievals.

      Parameters:
      - self: The instance of the class containing the function.
      - sample_dict (dict): A dictionary mapping retrieval names to lists of samples.
      - parameter_dict (dict): A dictionary mapping retrieval names to parameter values.
      - rets (list, optional): List of retrieval names to process. If None, uses the default retrieval name.

      Returns:
      - vmrs (numpy.ndarray): Array containing volume mixing ratios for each sample and species.

      The function processes the specified retrievals and saves the corresponding VMRs and line absorber species
      information to files in the output directory. If 'rets' is not provided, the default retrieval name is used.
      The VMRs are saved in a numpy file, and the line absorber species are saved in a JSON file.

      Example usage:
          ```
          sample_dict = {'Retrieval1': [...], 'Retrieval2': [...]}
          parameter_dict = {'Retrieval1': {...}, 'Retrieval2': {...}}
          vmrs = save_volume_mixing_ratios(sample_dict, parameter_dict)
          ```



   .. py:method:: setup_data(scaling=10, width=3)

      Creates a pRT object for each data set that asks for a unique object.
      Checks if there are low resolution c-k models from exo-k, and creates them if necessary.
      The scaling and width parameters adjust the AMR grid as described in RetrievalConfig.setup_pres
      and models.fixed_length_amr. It is recommended to keep the defaults.

      Args:
          scaling : int
              A multiplicative factor that determines the size of the full high resolution pressure grid,
              which will have length self.p_global.shape[0] * scaling.
          width : int
              The number of cells in the low pressure grid to replace with the high resolution grid.



   .. py:method:: plot_abundances(samples_use, parameters_read, species_to_plot=None, contribution=False, refresh=True, model_generating_function=None, prt_reference=None, mode='bestfit', sample_posteriors=False, volume_mixing_ratio=False)

      Plot the abundance profiles in mass fractions or volume mixing ratios as a function of pressure.

      Args:
          samples_use : numpy.ndarray
              An array of the samples from the post_equal_weights file, used to find the best fit sample
          parameters_read : list
              A list of the free parameters as read from the output files.
          species_to_plot : list
              A list of which molecular species to include in the plot.
          contribution : bool
              If true, overplot the emission or transmission contribution function.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          refresh : bool
              If True (default value) the .npy files in the evaluate_[retrieval_name] folder will be replaced
              by recalculating the best fit model. This is useful if plotting intermediate results from a
              retrieval that is still running. If False no new spectrum will be calculated and the plot will
              be generated from the .npy files in the evaluate_[retrieval_name] folder.
          mode : str
              'bestfit' or 'median', indicating which set of values should be used for plotting the abundances.
          sample_posteriors : bool
              If true, sample the posterior distributions to calculate confidence intervals for the retrieved
              abundance profiles.
          volume_mixing_ratio : bool
              If true, plot in units of volume mixing ratio (number fraction) instead of mass fractions.

      Returns:
          fig : matplotlib.figure
              The matplotlib figure, containing the data, best fit spectrum and residuals.
          ax : matplotlib.axes
              The upper pane of the plot, containing the best fit spectrum and data.
          ax_r : matplotlib.axes
              The lower pane of the plot, containing the residuals between the fit and the data.



   .. py:method:: plot_all(output_directory=None, ret_names=None, contribution=False, model_generating_function=None, prt_reference=None, mode='bestfit')

      Produces plots for the best fit spectrum, a sample of 100 output spectra,
      the best fit PT profile and a corner plot for parameters specified in the
      run definition.

      By default, this runs the following functions:
          plot_spectra: Plots the best fit spectrum together with the data, with an extra
                      panel showing the residuals between the model and data.
          plot_PT: plots the pressure-temperature profile contours
          plot_corner : Corner plot based on the posterior sample distributions
          plot_abundances : Abundance profiles for each line species used.

      if contribution = True:
          plot_contribution : The emission or transmission contribution function
          In addition to plotting the contribution function, the contribution
          will also be overlaid on top of the PT profiles and abundance profiles.

      if self.evaluate_sample_spectra = True
          plot_sampled : Randomly draws N samples from the posterior distribution,
          and plots the resulting spectrum overtop the data.

      Args:
          output_directory: string
              Output directory to store the plots. Defaults to selt.output_dir.
          ret_names : list(str)
              List of retrieval names. Used if multiple retrievals are to be included
              in a single corner plot.
          contribution : bool
              If true, plot the emission or transmission contribution function.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          mode : str
              If 'bestfit', consider the maximum likelihood sample for plotting,
              if median, calculate the model based on the median retrieved parameters.



   .. py:method:: plot_contribution(samples_use, parameters_read, model_generating_function=None, prt_reference=None, log_scale_contribution=False, n_contour_levels=30, refresh=True, mode='bestfit')

      Plot the contribution function of the bestfit or median model from a retrieval. This plot indicates the
      relative contribution from each wavelength and each pressure level in the atmosphere to the spectrum.

      Args:
          samples_use : numpy.ndarray
              An array of the samples from the post_equal_weights file, used to find the best fit sample
          parameters_read : list
              A list of the free parameters as read from the output files.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          log_scale_contribution : bool
              If true, take the log10 of the contribution function to visualize faint features.
          n_contour_levels : int
              Number of contour levels to pass to the matplotlib contourf function.
          refresh : bool
              If True (default value) the .npy files in the evaluate_[retrieval_name] folder will be replaced
              by recalculating the best fit model. This is useful if plotting intermediate results from a
              retrieval that is still running. If False no new spectrum will be calculated and the plot will
              be generated from the .npy files in the evaluate_[retrieval_name] folder.
          mode : str
              'bestfit' or 'median', indicating which set of values should be used to calculate the contribution
              function.

      Returns:
          fig : matplotlib.figure
              The matplotlib figure, containing the data, best fit spectrum and residuals.
          ax : matplotlib.axes
              The upper pane of the plot, containing the best fit spectrum and data
          ax_r : matplotlib.axes
              The lower pane of the plot, containing the residuals between the fit and the data



   .. py:method:: plot_corner(sample_dict, parameter_dict, parameters_read, plot_best_fit=True, true_values=None, **kwargs)

      Make the corner plots.

      Args:
          sample_dict : Dict
              Dictionary of samples from PMN outputs, with keys being retrieval names
          parameter_dict : Dict
              Dictionary of parameters for each of the retrievals to be plotted.
          parameters_read : List
              Used to plot correct parameters, as some in self.configuration.parameters are not free, and
              aren't included in the PMN outputs
          plot_best_fit : bool
              If true, plot vertical lines to indicate the maximum likelihood parameter values.
          true-values : np.ndarray
              An array of values for each plotted parameter, where a vertical line will be plotted
              for each value. Can be used to indicate true values if retrieving on synthetic data,
              or to overplot additional measurements.
          kwargs : dict
              Each kwarg can be one of the kwargs used in corner.corner. These can be used to adjust
              the title_kwargs,label_kwargs,hist_kwargs, hist2d_kawargs or the contour kwargs. Each
              kwarg must be a dictionary with the arguments as keys and values as the values.
          true_values :
              # TODO complete docstring



   .. py:method:: plot_data(yscale='linear')

      Plot the data used in the retrieval.



   .. py:method:: plot_pt(sample_dict, parameters_read, contribution=False, refresh=False, model_generating_function=None, prt_reference=None, mode='bestfit')

      Plot the PT profile with error contours

      Args:
          sample_dict : np.ndarray
              posterior samples from pynmultinest outputs (post_equal_weights)
          parameters_read : list
              List of free parameters as read from the output file.
          contribution : bool
              Weight the opacity of the pt profile by the emission contribution function,
              and overplot the contribution curve.
          refresh : bool
              If True (default value) the .npy files in the evaluate_[retrieval_name] folder will be replaced
              by recalculating the best fit model. This is useful if plotting intermediate results from a
              retrieval that is still running. If False no new spectrum will be calculated and the plot will
              be generated from the .npy files in the evaluate_[retrieval_name] folder.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          mode : str
              'bestfit' or 'median', indicating which set of values should be used to calculate the contribution
              function.

      Returns:
          fig : matplotlib.figure
          ax : matplotlib.axes



   .. py:method:: plot_sampled(samples_use, parameters_read, downsample_factor=None, save_outputs=False, nsample=None, model_generating_function=None, prt_reference=None, refresh=True)

      Plot a set of randomly sampled output spectra for each dataset in
      the retrieval.

      This will save nsample files for each dataset included in the retrieval.
      Note that if you change the model_resolution of your Data and rerun this
      function, the files will NOT be updated - if the files exists the function
      defaults to reading from file rather than recomputing. Delete all the
      sample functions and run it again.

      Args:
          samples_use : np.ndarray
              posterior samples from pynmultinest outputs (post_equal_weights)
          parameters_read : list(str)
              list of free parameters as read from the output files.
          downsample_factor : int
              Factor by which to reduce the resolution of the sampled model,
              for smoother plotting. Defaults to None. A value of None will result
              in the full resolution spectrum. Note that this factor can only
              reduce the resolution from the underlying model_resolution of the
              data.
          nsample : int
              Number of samples to draw from the posterior distribution. Defaults to the
              value of self.rd.plot_kwargs["nsample"].
          save_outputs : bool
              If true, saves each calculated spectrum as a .npy file. The name of the file indicates the
              index from the post_equal_weights file that was used to generate the sample.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          refresh : bool
              If True (default value) the .npy files in the evaluate_[retrieval_name] folder will be replaced
              by recalculating the best fit model. This is useful if plotting intermediate results from a
              retrieval that is still running. If False no new spectrum will be calculated and the plot will
              be generated from the .npy files in the evaluate_[retrieval_name] folder.



   .. py:method:: plot_spectra(samples_use, parameters_read, model_generating_function=None, prt_reference=None, refresh=True, mode='bestfit', marker_color_type=None, marker_cmap=None, marker_label='', only_save_best_fit_spectra=False)

      Plot the best fit spectrum, the data from each dataset and the residuals between the two.
      Saves a file to OUTPUT_DIR/evaluate_RETRIEVAL_NAME/RETRIEVAL_NAME_MODE_spec.pdf

      Args:
          samples_use : numpy.ndarray
              An array of the samples from the post_equal_weights file, used to find the best fit sample
          parameters_read : list
              A list of the free parameters as read from the output files.
          model_generating_function : method
              A function that will take in the standard 'model' arguments
              (pRT_object, params, pt_plot_mode, amr, resolution)
              and will return the wavlength and flux arrays as calculated by petitRadTrans.
              If no argument is given, it uses the method of the first dataset included in the retrieval.
          prt_reference : str
              If specified, the pRT object of the data with name pRT_reference will be used for plotting,
              instead of generating a new pRT object at R = 1000.
          model_generating_function : (callable, optional):
              A function that returns the wavelength and spectrum, and takes a Radtrans object and the
              current set of parameters stored in self.configuration.parameters. This should be the same model
              function used in the retrieval.
          refresh : bool
              If True (default value) the .npy files in the evaluate_[retrieval_name] folder will be replaced
              by recalculating the best fit model. This is useful if plotting intermediate results from a
              retrieval that is still running. If False no new spectrum will be calculated and the plot will
              be generated from the .npy files in the evaluate_[retrieval_name] folder.
          mode : str
              Use 'bestfit' (minimum likelihood) parameters, or median parameter values.
          marker_color_type : str
              Data-attribute to plot as marker colors. Use 'delta_elpd', 'elpd', or 'pareto_k'.
          marker_cmap : matplotlib colormap
              Colormap to use for marker colors.
          marker_label : str
              Label to add to colorbar corresponding to marker colors.
          only_save_best_fit_spectra : bool
              If False (default value), the plot_spectra routine will run as per usual, producing a plot
              of the best-fit or median-parameter forward model and the data.
              If True, only the best-fit models will be calculated for every dataset, and saved in the
              "evaluate_"+retrieval_name folder. No figure will be generated.
      Returns:
          fig : matplotlib.figure
              The matplotlib figure, containing the data, best fit spectrum and residuals.
          ax : matplotlib.axes
              The upper pane of the plot, containing the best fit spectrum and data
          ax_r : matplotlib.axes
              The lower pane of the plot, containing the residuals between the fit and the data



   .. py:method:: save_configuration()

      Save the retrieval_config configuration to file. Warning, can take up a significant amount of storage
      space, as the opacities for each Radtrans object will also be saved to file.



.. py:class:: RetrievalConfig(retrieval_name='retrieval_name', run_mode='retrieval', amr=False, scattering_in_emission=False, pressures=None)

   Contain all the data and model level information necessary to run a petitRADTRANS retrieval.

   The name of the class will be used to name outputs.
   This class is passed to the Retrieval, which runs the actual pymultinest retrieval and produces the outputs.

   The general usage of this class is to define it, add the parameters and their priors, add the opacity sources,
   the data together with a model for each dataset, and then configure a few plotting arguments.

   Args:
       retrieval_name : str
           Name of this retrieval. Make it informative so that you can keep track of the outputs!
       run_mode : str
           Can be either 'retrieval', which runs the retrieval normally using pymultinest,
           or 'evaluate', which produces plots from the best fit parameters stored in the
           output post_equal_weights file.
       amr : bool
           Use an adaptive high resolution pressure grid around the location of cloud condensation.
           This will increase the size of the pressure grid by a constant factor that can be adjusted
           in the setup_pres function.
       scattering_in_emission : bool
           If using emission spectra, turn scattering on or off.
       pressures : numpy.array
           A log-spaced array of pressures over which to retrieve. 100 points is standard, between
           10^-6 and 10^3.


   .. py:attribute:: retrieval_name
      :value: 'retrieval_name'



   .. py:attribute:: run_mode
      :value: 'retrieval'



   .. py:attribute:: amr
      :value: False



   .. py:attribute:: scattering_in_emission
      :value: False



   .. py:attribute:: parameters


   .. py:attribute:: data


   .. py:attribute:: instruments
      :value: []



   .. py:attribute:: line_species
      :value: []



   .. py:attribute:: cloud_species
      :value: []



   .. py:attribute:: rayleigh_species
      :value: []



   .. py:attribute:: continuum_opacities
      :value: []



   .. py:attribute:: plot_kwargs


   .. py:method:: _plot_defaults()


   .. py:method:: _setup_pres(scaling=10, width=3)

      This converts the standard pressure grid into the correct length
      for the AMR pressure grid. The scaling adjusts the resolution of the
      high resolution grid, while the width determines the size of the high
      pressure region. This function is automatically called in
      Retrieval.setupData().

      Args:
          scaling : int
              A multiplicative factor that determines the size of the full high resolution pressure grid,
              which will have length self.p_global.shape[0] * scaling.
          width : int
              The number of cells in the low pressure grid to replace with the high resolution grid.



   .. py:method:: add_parameter(name, free, value=None, transform_prior_cube_coordinate=None)

      This function adds a Parameter (see parameter.py) to the dictionary of parameters. A Parameter
      has a name and a boolean parameter to set whether it is a free or fixed parameter during the retrieval.
      In addition, a value can be set, or a prior function can be given that transforms a random variable in
      [0,1] to the physical dimensions of the Parameter.

      Args:
          name : str
              The name of the parameter. Must match the name used in the model function for the retrieval.
          free : bool
              True if the parameter is a free parameter in the retrieval, false if it is fixed.
          value : float
              The value of the parameter in the units used by the model function.
          transform_prior_cube_coordinate : method
              A function that transforms the unit interval to the physical units of the parameter.
              Typically given as a lambda function.



   .. py:method:: list_available_line_species()
      :staticmethod:


      List the currently installed opacity tables that are available for species that contribute to the line opacity.



   .. py:method:: list_available_cloud_species()
      :staticmethod:


      List the currently installed opacity tables that are available for cloud species.



   .. py:method:: list_available_cia_species()
      :staticmethod:


      List the currently installed opacity tables that are available for CIA species.



   .. py:method:: set_line_species(linelist, eq=False, abund_lim=(-6.0, -0.5))

      Set RadTrans.line_species

      This function adds a list of species to the pRT object that will define the line
      opacities of the model. The values in the list are strings, with the names matching
      the pRT opacity names, which vary between the c-k line opacities and the line-by-line opacities.

      NOTE: As of pRT version 2.4.9, the behavior of this function has changed. In previous versions the
      abundance limits were set from abund_lim[0] to (abund_lim[0] + abund_lim[1]). This has been changed
      so that the limits of the prior range are from abund_lim[0] to abund_lim[1] (ie the actual boundaries).

      Args:
          linelist : List(str)
              The list of species to include in the retrieval
          eq : bool
              If false, the retrieval should use free chemistry, and Parameters for the abundance of each
              species in the linelist will be added to the retrieval. Otherwise, equilibrium chemistry will
              be used. If you need fine control species, use the add_line_species and set up each species
              individually.
          abund_lim : Tuple(float,float)
              If free is True, this sets the boundaries of the uniform prior that will be applied for
              each species in linelist. The range of the prior goes from abund_lim[0] to abund_lim[1].
              The abundance limits must be given in log10 units of the mass fraction.



   .. py:method:: set_rayleigh_species(linelist)

      Set the list of species that contribute to the rayleigh scattering in the pRT object.

      Args:
          linelist : List(str)
              A list of species that contribute to the rayleigh opacity.



   .. py:method:: set_continuum_opacities(linelist)

      Set the list of species that contribute to the continuum opacity in the pRT object.

      Args:
          linelist : List(str)
              A list of species that contribute to the continuum opacity.



   .. py:method:: add_line_species(species, eq=False, abund_lim=(-7.0, 0.0), fixed_abund=None)

      This function adds a single species to the pRT object that will define the line opacities of the model.
      The name must match the pRT opacity name, which vary between the c-k line opacities and the line-by-line
      opacities.

      NOTE: As of pRT version 2.4.9, the behavior of this function has changed. In previous versions the
      abundance limits were set from abund_lim[0] to (abund_lim[0] + abund_lim[1]). This has been changed
      so that the limits of the prior range are from abund_lim[0] to abund_lim[1] (ie the actual boundaries).

      Args:
          species : str
              The species to include in the retrieval
          eq : bool
              If False, the retrieval should use free chemistry, and Parameters for the abundance of the
              species will be added to the retrieval. Otherwise, (dis)equilibrium chemistry will be used.
          abund_lim : Tuple(float,float)
              If free is True, this sets the boundaries of the uniform prior that will be applied the species given.
              The range of the prior goes from abund_lim[0] to abund_lim[1]
              The abundance limits must be given in log10 units of the mass fraction.
          fixed_abund : float
              The log-mass fraction abundance of the species. Currently only supports vertically constant
              abundances. If this is set, then the species will not be a free parameter in the retrieval.



   .. py:method:: add_pressure_varying_line_species(species, mode='linear', pressure_spacing='relative', n_nodes=3, abund_lim=(-7.0, 0.0), log_pressure_range_prior=(0, 9), fixed_pressure_node_species=None)

      This function adds a single species to the Radtrans object that will define the line opacities of the model.
      The name must match the pRT opacity name, which vary between the c-k line opacities and the line-by-line
      opacities. This species will have and abundance that varies with pressure, defined by the retrieved
      abundance at each of the provided abundance nodes.

      This function adds a set of parameters to the retrieval to define the abundance profile of the species.
       - {species}_{mode}_abundance_profile defines which profile will be used (fixed parameter)
       - {species}_n_abundance_nodes sets the number of abundance nodes (fixed parameter)
       - {species}_n_pressure_nodes sets the number of pressure nodes (n_nodes - 2) (fixed parameter)
       - {species}_interpolation_mode sets the pressure spacing mode (fixed parameter)
       - {species}_pressure_node_{i} for i in 0 to n_nodes-2, the pressure at each node (free parameter)
       - {species}_abundance_node_{i} for i in 0 to n_nodes, the abundance at each node (free parameter)

      Args:
          species: str
              The species to include in the retrieval
          mode: str
              One of 'linear', 'cubic', or 'stepped' - determines the interpolation method between abundance nodes.
          pressure_spacing: str
              One of 'relative', 'absolute', or 'fixed' - determines whether the pressure nodes are spaced
              relative to the top of the atmosphere pressure, retrieved in absolute log pressue, or fixed
              to the pressure nodes set by fixed_pressure_node_species.
          n_nodes: int
              The number of abundance nodes to use in the retrieval, including top and bottom nodes.
          abund_lim : Tuple(float,float)
              If free is True, this sets the boundaries of the uniform prior that will be applied the species given.
              The range of the prior goes from abund_lim[0] to abund_lim[1]
              The abundance limits must be given in log10 units of the mass fraction.
          log_pressure_range_prior: Tuple(float,float)
              The prior range on the log pressure of the pressure nodes in log bar, only used if pressure_spacing is
              'absolute' or 'relative'.
          fixed_pressure_node_species: str
              If pressure_spacing is 'fixed', this species pressure nodes will be used as the pressure nodes.
              Note that this species must already have been added to the retrieval with
              add_pressure_varying_line_species.



   .. py:method:: remove_species_lines(species, free=False)

      This function removes a species from the pRT line list, and if using a free chemistry retrieval,
      removes the associated Parameter of the species.

      Args:
          species : str
              The species to remove from the retrieval
          free : bool
              If true, the retrieval should use free chemistry, and Parameters for the abundance of the
              species will be removed to the retrieval



   .. py:method:: add_cloud_species(species, eq=True, abund_lim=(-3.5, 1.5), p_base_lim=None, fixed_abund=None, scaling_factor=None, fixed_base=None)

      This function adds a single cloud species to the list of species. Optionally,
      it will add parameters to allow for a retrieval using an ackermann-marley model.
      If an equilibrium condensation model is used in th retrieval model function (eq=True),
      then a parameter is added that scales the equilibrium cloud abundance, as in Molliere (2020).
      If eq is false, two parameters are added, the cloud abundnace and the cloud base pressure.
      The limits set the prior ranges, both on a log scale.

      NOTE: As of pRT version 2.4.9, the behaviour of this function has changed. In previous versions the
      abundance limits were set from abund_lim[0] to (abund_lim[0] + abund_lim[1]). This has been changed
      so that the limits of the prior range are from abund_lim[0] to abund_lim[1] (ie the actual boundaries).
      The same is true for PBase_lim.

      Args:
          species : str
              Name of the pRT cloud species, including the cloud shape tag.
          eq : bool
              Does the retrieval model use an equilibrium cloud model. This restricts the available species!
          abund_lim : tuple(float,float)
              If eq is True, this sets the scaling factor for the equilibrium condensate abundance, typical
              range would be (-3,1). If eq is false, this sets the range on the actual cloud abundance,
              with a typical range being (-5,0).
          p_base_lim : tuple(float,float)
              Only used if not using an equilibrium model. Sets the limits on the log of the cloud base pressure.
              Obsolete.
          fixed_abund : Optional(float)
              A vertically constant log mass fraction abundance for the cloud species. If set, this will not be
              a free parameter in the retrieval. Only compatible with non-equilibrium clouds.
          fixed_base : Optional(float)
              The log cloud base pressure. If set, fixes this parameter to a constant value, and it will not be
              a free parameter in the retrieval. Only compatible with non-equilibrium clouds. Not yet compatible
              with most built in pRT models.
          scaling_factor :
              # TODO complete docstring



   .. py:method:: add_data(name, path_to_observations, model_generating_function, data_resolution=None, model_resolution=None, system_distance=None, scale=False, scale_err=False, offset_bool=False, resample=False, subtract_continuum=False, radvel=False, photometry=False, photometric_transformation_function=None, photometric_bin_edges=None, wavelength_boundaries=None, external_radtrans_reference=None, line_opacity_mode='c-k', wavelength_bin_widths=None, radtrans_grid=False, radtrans_object=None, wavelengths=None, spectrum=None, uncertainties=None, covariance=None, mask=None, concatenate_flux_epochs_variability=False, variability_atmospheric_column_model_flux_return_mode=False, atmospheric_column_flux_mixer=None)

      Create a Data class object.

      Args:
          name : str
              Identifier for this data set.
          path_to_observations : str
              Path to observations file, including filename. This can be a txt or dat file containing the wavelength,
              flux, transit depth and error, or a fits file containing the wavelength, spectrum and covariance matrix.
          model_generating_function : fnc
              A function, typically defined in run_definition.py that returns the model wavelength and
              spectrum (emission or transmission). This is the function that contains the physics
              of the model, and calls pRT in order to compute the spectrum.
          data_resolution : float
              Spectral resolution of the instrument. Optional, allows convolution of model to instrumental line width.
          model_resolution : float
              Spectral resolution of the model, allowing for low resolution correlated k tables from exo-k.
          system_distance : float
              The distance to the object in cgs units. Defaults to a 10pc normalized distance. All data must
              be scaled to the same distance before running the retrieval, which can be done using the
              scale_to_distance method in the Data class.
          scale : bool
              Turn on or off scaling the data by a constant factor.
          wavelength_boundaries : Tuple
              A pair of wavelengths in units of micron that determine the lower and upper boundaries of the
              model computation.
          external_radtrans_reference : str
              The name of an existing Data object. This object's prt_object will be used to calculate the chi squared
              of the new Data object. This is useful when two datasets overlap, as only one model computation is
              required to compute the log likelihood of both datasets.
          line_opacity_mode : str
              Should the retrieval be run using correlated-k opacities (default, 'c-k'),
              or line by line ('lbl') opacities? If 'lbl' is selected, it is HIGHLY
              recommended to set the model_resolution parameter.
          radtrans_grid: bool
              Set to true if data has been binned to a pRT opacity grid, exactly.



   .. py:method:: add_photometry(path: str, model_generating_function: Callable, model_resolution: float = 10.0, distance: float | None = None, scale: bool = False, wlen_range_micron: tuple[float, float] = None, photometric_transformation_function: Callable = None, external_prt_reference: object = None, opacity_mode: str = 'c-k') -> None

      Create a Data class object for each photometric point in a photometry file.
      The photometry file must be a csv file and have the following structure:
      name, lower wavelength bound [um], upper wavelength boundary[um], flux [W/m2/micron], flux error [W/m2/micron]

      Photometric data requires a transformation function to convert a spectrum into synthetic photometry.
      You must provide this function yourself, or have the species package installed.
      If using species, the name in the data file must be of the format instrument/filter.

      Args:
          model_generating_function : str
              Identifier for this data set.
          path : str
              Path to observations file, including filename.
          model_resolution : float
              Spectral resolution of the model, allowing for low resolution correlated k tables from exo-k.
          scale : bool
              Turn on or off scaling the data by a constant factor. Currently only set up to scale all
              photometric data in a given file.
          distance : float
              The distance to the object in cgs units. Defaults to a 10pc normalized distance. All data must
              be scaled to the same distance before running the retrieval, which can be done using the
              scale_to_distance method in the Data class.
          wlen_range_micron : Tuple
              A pair of wavelengths in units of micron that determine the lower and upper boundaries of
              the model computation.
          external_prt_reference : str
              The name of an existing Data object. This object's prt_object will be used to calculate the
              chi squared of the new Data object. This is useful when two datasets overlap, as only
              one model computation is required to compute the log likelihood of both datasets.
          photometric_transformation_function : method
              A function that will transform a spectrum into an average synthetic photometric point,
              typically accounting for filter transmission.
          opacity_mode: str
              Opacity mode.



